# tools/fixtures/_blend_ref: run by tools/fixtures/blend.py inside Blender (blender -b --factory-startup --python # -- ): opens each file (old ones through Blender's versioning) and writes # /.json with the reference values (object world matrices, mesh counts / bounds / attribute sums / corner normals, # vertex groups, shape keys, materials, images, cameras, lights, bones, f-curve values, posed world matrices per frame), # the rig data of each armature (bone head / tail / roll, collections, colours, custom shapes, locks, IK settings, # constraints with every RNA property of their type) and the default theme's bone colour sets; posed matrices are # taken with every constraint muted (the reader does not evaluate constraints). It exports a .glb of each file (Z up, no modifiers) whose JSON part is returned as "gltf". import bpy, sys, os, json, struct, math args = sys.argv[sys.argv.index("--") + 1:] paths, outdir = json.loads(args[0]), args[1] V = bpy.app.version def mat(m): return [m[r][c] for c in range(4) for r in range(4)] # column-major def r6(x): return round(float(x), 6) def color_attrs(me): out = [] attrs = me.color_attributes if hasattr(me, "color_attributes") else [] for a in attrs: s = [0.0, 0.0, 0.0, 0.0] for l in me.loops: d = a.data[l.index if a.domain == "CORNER" else l.vertex_index] for k in range(4): s[k] += d.color[k] out.append({"name": a.name, "domain": a.domain, "type": a.data_type, "count": len(a.data), "cornerSum": [r6(x) for x in s]}) return out def mesh_info(ob): me = ob.data me.calc_loop_triangles() vs = [v.co for v in me.vertices] lo = [min(v[k] for v in vs) for k in range(3)] if vs else [0, 0, 0] hi = [max(v[k] for v in vs) for k in range(3)] if vs else [0, 0, 0] info = { "name": me.name, "vertices": len(me.vertices), "corners": len(me.loops), "faces": len(me.polygons), "triangles": len(me.loop_triangles), "min": [r6(x) for x in lo], "max": [r6(x) for x in hi], "possum": [r6(sum(v[k] for v in vs)) for k in range(3)], "uvs": [], "colors": color_attrs(me), "slots": [s.material.name if s.material else "" for s in ob.material_slots], "facemats": [p.material_index for p in me.polygons], "smooth": [1 if p.use_smooth else 0 for p in me.polygons], } for layer in me.uv_layers: su = sv = 0.0 for d in layer.data: su += d.uv[0] sv += d.uv[1] info["uvs"].append({"name": layer.name, "sum": [r6(su), r6(sv)], "active_render": bool(layer.active_render)}) if len(me.loops) <= 400: if hasattr(me, "corner_normals"): info["normals"] = [[r6(c) for c in n.vector] for n in me.corner_normals] info["cornerVerts"] = [l.vertex_index for l in me.loops] info["custom"] = bool(me.has_custom_normals) groups = {g.index: g.name for g in ob.vertex_groups} if groups: info["weights"] = [[[groups.get(g.group, "?"), r6(g.weight)] for g in v.groups] for v in me.vertices] if me.shape_keys: k = me.shape_keys info["shapes"] = [{"name": b.name, "value": r6(b.value), "relative": b.relative_key.name, "slider_min": r6(b.slider_min), "slider_max": r6(b.slider_max), "mute": bool(b.mute), "vertex_group": b.vertex_group, "co": [r6(p.co[c]) for p in b.data for c in range(3)]} for b in k.key_blocks] info["reference"] = k.reference_key.name info["modifiers"] = [m.type for m in ob.modifiers] return info def socket_val(s): if s is None: return None v = s.default_value try: return [r6(x) for x in v] except TypeError: return r6(v) def linked_image(s): if s is None or not s.is_linked: return None n = s.links[0].from_node if n.bl_idname == "ShaderNodeNormalMap": return linked_image(n.inputs["Color"]) if n.bl_idname == "ShaderNodeTexImage" and n.image: return n.image.name return "?" + n.bl_idname PASS = {"NodeReroute": ["Input"], "ShaderNodeMix": ["A_Color", "B_Color"], "ShaderNodeMixRGB": ["Color1", "Color2"], "ShaderNodeHueSaturation": ["Color"], "ShaderNodeBrightContrast": ["Color"], "ShaderNodeGamma": ["Color"], "ShaderNodeInvert": ["Color"], "ShaderNodeRGBCurve": ["Color"], "ShaderNodeValToRGB": ["Fac"]} def by_identifier(sockets, ident): for s in sockets: if s.identifier == ident: return s return None def trace(sock, via, stack, depth=0): """bpy's view of the reader's rules: (end node, from-socket name, group stack) of the first image, else the last node""" if depth > 64 or not sock.is_linked: return None, None link = sock.links[0] n, out = link.from_node, link.from_socket if n.bl_idname == "ShaderNodeTexImage": return n, out.name if n.bl_idname == "ShaderNodeGroup" and n.node_tree: outs = [x for x in n.node_tree.nodes if x.bl_idname == "NodeGroupOutput"] if outs: inner = by_identifier(outs[0].inputs, out.identifier) if inner is not None: via.append(n.bl_idname) r, nm = trace(inner, via, stack + [n], depth + 1) if r is not None and r.bl_idname == "ShaderNodeTexImage": return r, nm via.pop() return n, out.name if n.bl_idname == "NodeGroupInput" and stack: g = stack[-1] outer = by_identifier(g.inputs, out.identifier) if outer is not None: return trace(outer, via, stack[:-1], depth + 1) return n, out.name if n.bl_idname in PASS: last = n for ident in PASS[n.bl_idname]: s = by_identifier(n.inputs, ident) or (n.inputs.get(ident) if hasattr(n.inputs, "get") else None) if s is None and n.bl_idname == "NodeReroute": s = n.inputs[0] if s is None: continue sub = [] r, nm = trace(s, sub, stack, depth + 1) if r is not None and r.bl_idname == "ShaderNodeTexImage": via.append(n.bl_idname) via.extend(sub) return r, nm if n.bl_idname == "NodeReroute": return (r, nm) if r is not None else (n, out.name) return last, out.name return n, out.name def image_info(img): info = {"name": img.name, "source": img.source, "filepath": img.filepath} if img.source == "TILED": info["tiles"] = [{"number": t.number, "label": t.label} for t in img.tiles] return info def graph_info(m): out = {} if not m.node_tree: return out bsdf = None # the reader's choice: the Principled BSDF linked to an output's Surface, else the first for n in m.node_tree.nodes: if n.bl_idname == "ShaderNodeOutputMaterial" and n.inputs["Surface"].is_linked: f = n.inputs["Surface"].links[0].from_node if f.bl_idname == "ShaderNodeBsdfPrincipled": bsdf = f if bsdf is None: bsdf = next((n for n in m.node_tree.nodes if n.bl_idname == "ShaderNodeBsdfPrincipled"), None) if bsdf is None: return out for name in ("Base Color", "Metallic", "Roughness", "Normal", "Alpha", "Emission Color", "Emission"): s = bsdf.inputs.get(name) if s is None or not s.is_linked: continue sock = s e = {"linked": s.links[0].from_node.bl_idname} if name == "Normal" and e["linked"] in ("ShaderNodeNormalMap", "ShaderNodeBump"): nn = s.links[0].from_node sock = nn.inputs["Color"] if e["linked"] == "ShaderNodeNormalMap" else nn.inputs["Height"] if e["linked"] == "ShaderNodeBump": e["strength"] = r6(nn.inputs["Strength"].default_value) e["distance"] = r6(nn.inputs["Distance"].default_value) via = [] n, outname = trace(sock, via, []) if n is not None and n.bl_idname == "ShaderNodeTexImage" and n.image: e["image"] = image_info(n.image) e["via"] = via e["output"] = outname elif n is not None: e["end"] = n.bl_idname if n.bl_idname == "ShaderNodeVertexColor": e["vertexColor"] = n.layer_name elif n.bl_idname == "ShaderNodeAttribute": e["vertexColor"] = n.attribute_name out[name] = e return out def material_info(m): info = {"name": m.name, "diffuse": [r6(x) for x in m.diffuse_color], "metallic": r6(m.metallic), "roughness": r6(m.roughness), "use_nodes": bool(m.use_nodes), "cull": bool(m.use_backface_culling), "graph": graph_info(m)} if m.node_tree: for n in m.node_tree.nodes: if n.bl_idname == "ShaderNodeBsdfPrincipled": ins = n.inputs g = lambda *names: next((ins[x] for x in names if x in ins), None) info["principled"] = { "base": socket_val(g("Base Color")), "metallic": socket_val(g("Metallic")), "roughness": socket_val(g("Roughness")), "emission": socket_val(g("Emission Color", "Emission")), "strength": socket_val(g("Emission Strength")), "alpha": socket_val(g("Alpha")), "baseTex": linked_image(g("Base Color")), "normalTex": linked_image(g("Normal")), "emissionTex": linked_image(g("Emission Color", "Emission")), } if n.bl_idname == "ShaderNodeNormalMap": info["normalStrength"] = r6(n.inputs["Strength"].default_value) return info def fcurves(act): if act is None: return [] if hasattr(act, "fcurves") and V < (5, 0): return list(act.fcurves) out = [] for layer in act.layers: for strip in layer.strips: for bag in strip.channelbags: out.extend(bag.fcurves) return out def rna_value(v): if v is None: return "" if isinstance(v, bpy.types.ID): return v.name if isinstance(v, (bpy.types.PoseBone, bpy.types.Bone)): return v.name if isinstance(v, bool): return v if isinstance(v, (int, float)): return r6(v) if isinstance(v, str): return v if hasattr(v, "col"): # a Matrix return [r6(x) for x in mat(v)] try: return [rna_value(x) for x in v] except TypeError: return None SKIP = {"rna_type", "show_expanded", "active", "is_valid", "is_override_data_editable", "error_location", "error_rotation", "targets", "space_object", "space_subtarget"} BONE_KEYS = ("inherit_scale", "use_inherit_rotation", "use_local_location", "use_relative_parent", "bbone_segments", "bbone_x", "bbone_z", "bbone_easein", "bbone_easeout", "bbone_rollin", "bbone_rollout", "bbone_curveinx", "bbone_curveinz", "bbone_curveoutx", "bbone_curveoutz", "bbone_scalein", "bbone_scaleout", "bbone_handle_type_start", "bbone_handle_type_end", "bbone_custom_handle_start", "bbone_custom_handle_end", "use_endroll_as_inroll", "bbone_mapping_mode") def action_fcurves(act): if V >= (4, 4) and hasattr(act, "layers") and len(act.layers) > 0: for strip in act.layers[0].strips: for bag in strip.channelbags: return list(bag.fcurves) return [] return list(act.fcurves) def action_info(act): curves = [] for fc in action_fcurves(act): keys = [{"co": [r6(k.co[0]), r6(k.co[1])], "interpolation": k.interpolation, "easing": k.easing, "handle_left": [r6(k.handle_left[0]), r6(k.handle_left[1])], "handle_right": [r6(k.handle_right[0]), r6(k.handle_right[1])]} for k in fc.keyframe_points] curves.append({"data_path": fc.data_path, "array_index": fc.array_index, "extrapolation": fc.extrapolation, "keys": keys}) return {"frame_range": [r6(act.frame_range[0]), r6(act.frame_range[1])], "curves": curves} def modifier_info(m): e = {"type": m.type, "name": m.name, "show_viewport": m.show_viewport, "show_render": m.show_render} if m.type == "ARMATURE": e.update({"object": m.object.name if m.object else "", "use_vertex_groups": m.use_vertex_groups, "use_bone_envelopes": m.use_bone_envelopes, "use_deform_preserve_volume": m.use_deform_preserve_volume, "use_multi_modifier": m.use_multi_modifier, "vertex_group": m.vertex_group, "invert_vertex_group": m.invert_vertex_group}) return e def props_info(owner): out = {} for k in owner.keys(): if k == "_RNA_UI": continue v = owner[k] if hasattr(v, "to_dict"): v = v.to_dict() elif hasattr(v, "to_list"): v = v.to_list() out[k] = v return out MOD_KEYS = ("type", "mode", "use_additive", "coefficients", "poly_order", "mute", "influence", "use_influence", "use_restricted_range", "frame_start", "frame_end", "blend_in", "blend_out") def driver_info(fc): d = fc.driver variables = [] for v in d.variables: targets = [] for t in v.targets: targets.append({"id": t.id.name if t.id else "", "id_type": t.id_type, "data_path": t.data_path, "bone_target": t.bone_target, "transform_type": t.transform_type, "transform_space": t.transform_space, "rotation_mode": t.rotation_mode, "context_property": t.context_property}) variables.append({"name": v.name, "type": v.type, "targets": targets}) mods = [] for m in fc.modifiers: e = {} for k in MOD_KEYS: if hasattr(m, k): e[k] = rna_value(getattr(m, k)) mods.append(e) return {"data_path": fc.data_path, "array_index": fc.array_index, "extrapolation": fc.extrapolation, "keys": [{"co": [r6(k.co[0]), r6(k.co[1])], "interpolation": k.interpolation} for k in fc.keyframe_points], "driver": {"type": d.type, "expression": d.expression, "use_self": d.use_self, "variables": variables}, "modifiers": mods} def drivers_of(idb): ad = getattr(idb, "animation_data", None) return [driver_info(fc) for fc in ad.drivers] if ad else [] def constraint_info(c): out = {} if c.type == "ARMATURE": out["targets"] = [{"target": t.target.name if t.target else "", "subtarget": t.subtarget, "weight": r6(t.weight)} for t in c.targets] for prop in c.bl_rna.properties: k = prop.identifier if k in SKIP or prop.type == "COLLECTION": continue try: v = rna_value(getattr(c, k)) except Exception: # noqa: BLE001 continue if v is not None: out[k] = v return out def color_info(c): return {"palette": c.palette, "normal": [r6(x) for x in c.custom.normal], "select": [r6(x) for x in c.custom.select], "active": [r6(x) for x in c.custom.active]} def rig_info(ob): arm = ob.data bones = [] for b in arm.bones: _, roll = bpy.types.Bone.AxisRollFromMatrix(b.matrix_local.to_3x3()) pb = ob.pose.bones[b.name] pose = { "custom_shape": pb.custom_shape.name if pb.custom_shape else "", "custom_shape_transform": pb.custom_shape_transform.name if pb.custom_shape_transform else "", "custom_shape_translation": [r6(x) for x in pb.custom_shape_translation], "custom_shape_rotation_euler": [r6(x) for x in pb.custom_shape_rotation_euler], "custom_shape_scale_xyz": [r6(x) for x in pb.custom_shape_scale_xyz], "use_custom_shape_bone_size": pb.use_custom_shape_bone_size, "lock_location": list(pb.lock_location), "lock_rotation": list(pb.lock_rotation), "lock_rotation_w": pb.lock_rotation_w, "lock_rotations_4d": pb.lock_rotations_4d, "lock_scale": list(pb.lock_scale), "rotation_mode": pb.rotation_mode, "ik_stretch": r6(pb.ik_stretch), "color": color_info(pb.color), "constraints": [constraint_info(c) for c in pb.constraints], } for a in "xyz": for k in ("lock_ik_", "use_ik_limit_", "ik_min_", "ik_max_", "ik_stiffness_"): pose[k + a] = rna_value(getattr(pb, k + a)) for k in ("location", "rotation_quaternion", "rotation_euler", "rotation_axis_angle", "scale"): pose[k] = rna_value(getattr(pb, k)) pose["props"] = props_info(pb) pose["bone_props"] = props_info(b) info = {} for k in BONE_KEYS: if hasattr(b, k): info[k] = rna_value(getattr(b, k)) bones.append({"name": b.name, "head_local": [r6(x) for x in b.head_local], "tail_local": [r6(x) for x in b.tail_local], "bone": info, "roll": r6(roll), "deform": b.use_deform, "use_connect": b.use_connect, "show_wire": b.show_wire, "collections": [c.name for c in b.collections], "color": color_info(b.color), "pose": pose}) cols = [{"name": c.name, "visible": c.is_visible, "parent": c.parent.name if c.parent else ""} for c in arm.collections_all] return {"bones": bones, "collections": cols} def theme_colors(): out = [] for cs in bpy.context.preferences.themes[0].bone_color_sets: out.append({"normal": [r6(x) for x in cs.normal], "select": [r6(x) for x in cs.select], "active": [r6(x) for x in cs.active]}) return out FRAMES = [1 + 0.5 * i for i in range(43)] # 1 .. 22 (past the last key: extrapolation) def curve_info(act): out = [] for fc in fcurves(act): out.append({"path": fc.data_path, "index": fc.array_index, "extrapolation": fc.extrapolation, "keys": len(fc.keyframe_points), "values": [r6(fc.evaluate(f)) for f in FRAMES]}) return out def dump(path): bpy.ops.wm.open_mainfile(filepath=path) sc = bpy.context.scene sc.frame_set(sc.frame_current) obs = list(sc.objects) ref = {"version": list(bpy.data.version), "fps": sc.render.fps / sc.render.fps_base, "frameStart": sc.frame_start, "frameCurrent": sc.frame_current, "resolution": [sc.render.resolution_x, sc.render.resolution_y], "objects": [], "materials": [], "images": [], "cameras": {}, "lights": {}, "armatures": {}, "actions": {}, "rigs": {}, "themeBoneColors": theme_colors(), "allActions": {a.name: action_info(a) for a in bpy.data.actions}} for ob in obs: o = {"name": ob.name, "type": ob.type, "parent": ob.parent.name if ob.parent else "", "parent_type": ob.parent_type, "parent_bone": ob.parent_bone, "world": [r6(x) for x in mat(ob.matrix_world)], "collections": [c.name for c in ob.users_collection], "hide_viewport": ob.hide_viewport, "hide_render": ob.hide_render, "props": props_info(ob), "drivers": drivers_of(ob), "parent_info": {"matrix_parent_inverse": [r6(x) for x in mat(ob.matrix_parent_inverse)], "parent_vertices": list(ob.parent_vertices)} if ob.parent else {}, "modifier_info": [modifier_info(m) for m in ob.modifiers], "data_drivers": drivers_of(ob.data) if ob.data is not None and ob.type in ("ARMATURE", "MESH") else [], "shape_key_drivers": drivers_of(ob.data.shape_keys) if ob.type == "MESH" and ob.data.shape_keys else []} if ob.type == "MESH": o["mesh"] = mesh_info(ob) if ob.animation_data and ob.animation_data.action: a = ob.animation_data.action ref["actions"][a.name] = curve_info(a) o["action"] = a.name if ob.type == "MESH" and ob.data.shape_keys and ob.data.shape_keys.animation_data and ob.data.shape_keys.animation_data.action: a = ob.data.shape_keys.animation_data.action ref["actions"][a.name] = curve_info(a) o["shapeAction"] = a.name ref["objects"].append(o) if ob.type == "CAMERA": c = ob.data ref["cameras"][ob.name] = {"type": c.type, "lens": r6(c.lens), "sensor": [r6(c.sensor_width), r6(c.sensor_height)], "fit": c.sensor_fit, "ortho": r6(c.ortho_scale), "clip": [r6(c.clip_start), r6(c.clip_end)], "angle": [r6(c.angle_x), r6(c.angle_y)]} if ob.type == "LIGHT": l = ob.data ref["lights"][ob.name] = {"type": l.type, "color": [r6(x) for x in l.color], "energy": r6(l.energy), "spot": [r6(l.spot_size), r6(l.spot_blend)] if l.type == "SPOT" else [0, 0]} if ob.type == "ARMATURE": ref["armatures"][ob.name] = [{"name": b.name, "parent": b.parent.name if b.parent else "", "deform": b.use_deform, "local": [r6(x) for x in mat(b.matrix_local)], "length": r6(b.length)} for b in ob.data.bones] ref["rigs"][ob.name] = rig_info(ob) if ob.constraints: o["constraints"] = [constraint_info(c) for c in ob.constraints] for m in bpy.data.materials: ref["materials"].append(material_info(m)) for im in bpy.data.images: if im.source in ("FILE", "GENERATED") and im.type == "IMAGE": ref["images"].append({"name": im.name, "filepath": im.filepath, "packed": im.packed_file.size if im.packed_file else 0, "source": im.source}) # posed world matrices: objects, pose bones (world), shape key values for ob in obs: for c in ob.constraints: c.mute = True if ob.type == "ARMATURE": for pb in ob.pose.bones: for c in pb.constraints: c.mute = True sc.frame_set(sc.frame_current) for o in ref["objects"]: o["worldMuted"] = [r6(x) for x in mat(bpy.data.objects[o["name"]].matrix_world)] ref["posedBones"] = {ob.name + "/" + pb.name: [r6(x) for x in mat(ob.matrix_world @ pb.matrix)] for ob in obs if ob.type == "ARMATURE" for pb in ob.pose.bones} poses = [] if ref["actions"]: for f in FRAMES: sc.frame_set(int(math.floor(f)), subframe=f - math.floor(f)) p = {"frame": f, "objects": {}, "bones": {}, "shapes": {}} for ob in obs: p["objects"][ob.name] = [r6(x) for x in mat(ob.matrix_world)] if ob.type == "ARMATURE": for pb in ob.pose.bones: p["bones"][ob.name + "/" + pb.name] = [r6(x) for x in mat(ob.matrix_world @ pb.matrix)] if ob.type == "MESH" and ob.data.shape_keys: p["shapes"][ob.name] = [r6(b.value) for b in ob.data.shape_keys.key_blocks] if ob.type == "MESH" and any(m.type == "ARMATURE" and m.object and m.show_viewport for m in ob.modifiers) and f == math.floor(f): ev = ob.evaluated_get(bpy.context.evaluated_depsgraph_get()) em = ev.to_mesh() w = ob.matrix_world p.setdefault("skinned", {})[ob.name] = [r6(c) for v in em.vertices for c in (w @ v.co)] ev.to_mesh_clear() poses.append(p) ref["poses"] = poses # Blender's glTF exporter on the same file (Z up, modifiers not applied) glb = os.path.join(outdir, os.path.basename(path) + ".glb") try: bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", export_yup=False, export_apply=False, export_cameras=True, export_lights=True) with open(glb, "rb") as fh: data = fh.read() n = struct.unpack_from("