Files
rosetta/tools/fixtures/_blend_ref.py
T

317 lines
14 KiB
Python

# tools/fixtures/_blend_ref: run by tools/fixtures/blend.py inside Blender (blender -b --factory-startup --python
# <this> -- <json list of .blend paths> <out dir>): opens each file (old ones through Blender's versioning) and writes
# <out dir>/<file>.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
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)}
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):
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"}
def constraint_info(c):
out = {}
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))
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],
"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()}
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}
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
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" 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("<I", data, 12)[0]
ref["gltf"] = json.loads(data[20:20 + n].decode("utf-8"))
ref["gltf"].pop("buffers", None)
except Exception as e: # noqa: BLE001
ref["gltfError"] = str(e)
return ref
for p in paths:
try:
r = dump(p)
except Exception as e: # noqa: BLE001
r = {"error": str(e)}
with open(os.path.join(outdir, os.path.basename(p) + ".json"), "w") as fh:
json.dump(r, fh)