model/blend, containers/Blend: read .blend files (2.4x-5.x headers, SDNA structs by name, gzip/zstd), scenes with meshes of every storage generation, materials, images, cameras, lights, armatures, skins, shape keys, actions
This commit is contained in:
1 parent
01c044805f
commit
2e82b7d0af
15 files changed
+4855
-2
No files matched your search
@@ -0,0 +1,390 @@
|
||||
# tools/fixtures/_blend_make: run by tools/fixtures/blend.py inside Blender 2.79 .. 5.x (blender -b --python <this> --
|
||||
# <outdir>): builds the test scenes with whatever API the running version has and saves them as .blend files:
|
||||
# scene_<ver>.blend collections, transforms (euler / quaternion / delta), parenting with a parent inverse,
|
||||
# meshes (quads, an n-gon, smooth / flat), two UV maps, colour attributes, materials (Principled
|
||||
# + packed and external images, a legacy one), cameras, lights, modifiers
|
||||
# rig_<ver>.blend armature with rolls, a skinned mesh (vertex groups, 5 influences on some vertices), shape
|
||||
# keys, actions on bones / objects / shape keys (bezier, linear, constant), a bone parent
|
||||
# scene_<ver>_z.blend scene_<ver> saved compressed (gzip before 3.0, zstd after)
|
||||
# compat_<ver>.blend 2.7x only: the "legacy mesh format" save (MFace tessellated faces)
|
||||
import bpy, sys, os, math
|
||||
|
||||
out = sys.argv[sys.argv.index("--") + 1]
|
||||
V = bpy.app.version
|
||||
TAG = "%d%d" % (V[0], V[1])
|
||||
OLD = V < (2, 80)
|
||||
|
||||
|
||||
def reset():
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True) if not OLD else bpy.ops.wm.read_factory_settings()
|
||||
if OLD:
|
||||
for o in list(bpy.data.objects):
|
||||
bpy.data.objects.remove(o, do_unlink=True)
|
||||
sc = bpy.context.scene
|
||||
sc.render.fps = 24
|
||||
if OLD:
|
||||
sc.render.engine = "CYCLES"
|
||||
sc.frame_start, sc.frame_end = 1, 20
|
||||
|
||||
|
||||
def link(obj, coll=None):
|
||||
sc = bpy.context.scene
|
||||
if OLD:
|
||||
sc.objects.link(obj)
|
||||
else:
|
||||
(coll or sc.collection).objects.link(obj)
|
||||
return obj
|
||||
|
||||
|
||||
def mesh(name, verts, faces, smooth=False):
|
||||
me = bpy.data.meshes.new(name)
|
||||
me.from_pydata(verts, [], faces)
|
||||
me.update()
|
||||
for p in me.polygons:
|
||||
p.use_smooth = smooth
|
||||
return me
|
||||
|
||||
|
||||
def uv(me, name, f):
|
||||
if OLD:
|
||||
me.uv_textures.new(name)
|
||||
layer = me.uv_layers[name]
|
||||
else:
|
||||
layer = me.uv_layers.new(name=name)
|
||||
for i, d in enumerate(layer.data):
|
||||
d.uv = f(i)
|
||||
|
||||
|
||||
def byte_colors(me, name):
|
||||
if V >= (3, 2):
|
||||
a = me.color_attributes.new(name, "BYTE_COLOR", "CORNER")
|
||||
data = a.data
|
||||
else:
|
||||
data = me.vertex_colors.new(name=name).data
|
||||
for i, d in enumerate(data):
|
||||
c = ((i % 3) / 2, (i % 5) / 4, (i % 7) / 6)
|
||||
d.color = c + (1.0,) if len(d.color) == 4 else c
|
||||
|
||||
|
||||
def image(name, w, h, f, pack=True, path=None):
|
||||
img = bpy.data.images.new(name, w, h)
|
||||
px = []
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
px.extend(f(x, y))
|
||||
img.pixels = px
|
||||
if path:
|
||||
img.filepath_raw = path
|
||||
img.file_format = "PNG"
|
||||
img.save()
|
||||
img.filepath = "//" + os.path.basename(path)
|
||||
if pack:
|
||||
if OLD:
|
||||
img.pack(as_png=True)
|
||||
else:
|
||||
img.pack()
|
||||
return img
|
||||
|
||||
|
||||
def socket(node, *names):
|
||||
for n in names:
|
||||
if n in node.inputs:
|
||||
return node.inputs[n]
|
||||
return None
|
||||
|
||||
|
||||
def principled(mat, base, metallic, rough, emission=None, strength=1.0, alpha=1.0):
|
||||
mat.use_nodes = True
|
||||
nt = mat.node_tree
|
||||
bsdf = None
|
||||
for n in nt.nodes:
|
||||
if n.bl_idname == "ShaderNodeBsdfPrincipled":
|
||||
bsdf = n
|
||||
if bsdf is None:
|
||||
for n in list(nt.nodes):
|
||||
if n.bl_idname != "ShaderNodeOutputMaterial":
|
||||
nt.nodes.remove(n)
|
||||
bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled")
|
||||
outs = [n for n in nt.nodes if n.bl_idname == "ShaderNodeOutputMaterial"]
|
||||
outn = outs[0] if outs else nt.nodes.new("ShaderNodeOutputMaterial")
|
||||
nt.links.new(bsdf.outputs[0], outn.inputs["Surface"])
|
||||
socket(bsdf, "Base Color").default_value = base
|
||||
socket(bsdf, "Metallic").default_value = metallic
|
||||
socket(bsdf, "Roughness").default_value = rough
|
||||
e = socket(bsdf, "Emission Color", "Emission")
|
||||
if emission and e:
|
||||
e.default_value = emission + (1.0,)
|
||||
s = socket(bsdf, "Emission Strength")
|
||||
if s:
|
||||
s.default_value = strength
|
||||
a = socket(bsdf, "Alpha")
|
||||
if a:
|
||||
a.default_value = alpha
|
||||
return bsdf
|
||||
|
||||
|
||||
def tex(mat, img, to, normal=False):
|
||||
nt = mat.node_tree
|
||||
t = nt.nodes.new("ShaderNodeTexImage")
|
||||
t.image = img
|
||||
if normal:
|
||||
if not OLD:
|
||||
img.colorspace_settings.name = "Non-Color"
|
||||
nm = nt.nodes.new("ShaderNodeNormalMap")
|
||||
nm.inputs["Strength"].default_value = 0.7
|
||||
nt.links.new(t.outputs["Color"], nm.inputs["Color"])
|
||||
nt.links.new(nm.outputs["Normal"], to)
|
||||
else:
|
||||
nt.links.new(t.outputs["Color"], to)
|
||||
|
||||
|
||||
def camera(name, ortho=False):
|
||||
cam = bpy.data.cameras.new(name)
|
||||
if ortho:
|
||||
cam.type = "ORTHO"
|
||||
cam.ortho_scale = 7.0
|
||||
else:
|
||||
cam.lens = 35.0
|
||||
cam.sensor_width = 36.0
|
||||
cam.clip_start, cam.clip_end = 0.1, 100.0
|
||||
return cam
|
||||
|
||||
|
||||
def light(name, kind):
|
||||
data = (bpy.data.lamps if OLD else bpy.data.lights).new(name, kind)
|
||||
data.color = (1.0, 0.5, 0.25)
|
||||
data.energy = {"POINT": 1000.0, "SUN": 3.0, "SPOT": 500.0, "AREA": 200.0}[kind]
|
||||
if kind == "SPOT":
|
||||
data.spot_size = 0.8
|
||||
data.spot_blend = 0.2
|
||||
return data
|
||||
|
||||
|
||||
def save(path, compress=False, compat=False):
|
||||
kw = {"filepath": path, "compress": compress}
|
||||
if compat:
|
||||
kw["use_mesh_compat"] = True
|
||||
bpy.ops.wm.save_as_mainfile(**kw)
|
||||
|
||||
|
||||
def update():
|
||||
if OLD:
|
||||
bpy.context.scene.update()
|
||||
else:
|
||||
bpy.context.view_layer.update()
|
||||
|
||||
|
||||
def scene_file():
|
||||
reset()
|
||||
sc = bpy.context.scene
|
||||
props = inner = None
|
||||
if not OLD:
|
||||
props = bpy.data.collections.new("Props")
|
||||
sc.collection.children.link(props)
|
||||
inner = bpy.data.collections.new("Inner")
|
||||
props.children.link(inner)
|
||||
cube_v = [(-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)]
|
||||
cube_f = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
|
||||
me = mesh("BoxMesh", cube_v, cube_f)
|
||||
uv(me, "UVMap", lambda i: ((i % 4) / 4 + 0.1, (i // 4) / 6))
|
||||
uv(me, "Second", lambda i: (1 - (i % 3) / 3, (i % 2) * 0.5))
|
||||
byte_colors(me, "Col")
|
||||
if V >= (3, 2):
|
||||
pc = me.color_attributes.new("PCol", "FLOAT_COLOR", "POINT")
|
||||
for i, d in enumerate(pc.data):
|
||||
d.color = (i / 8, 1 - i / 8, 0.5 + i / 16, 1.0)
|
||||
checker = image("checker", 8, 8, lambda x, y: [float((x + y) % 2), 0.5, 0.25, 1.0])
|
||||
bumps = image("bumps", 4, 4, lambda x, y: [0.5 + x / 8, 0.5 + y / 8, 1.0, 1.0])
|
||||
outside = image("outside", 2, 2, lambda x, y: [1.0, 0.0, x * 1.0, 1.0], pack=False,
|
||||
path=os.path.join(out, "outside.png"))
|
||||
red = bpy.data.materials.new("Red")
|
||||
bsdf = principled(red, (0.8, 0.1, 0.1, 1.0), 0.3, 0.4, (0.2, 0.3, 0.4), 2.0, 0.9)
|
||||
tex(red, checker, socket(bsdf, "Base Color"))
|
||||
tex(red, bumps, socket(bsdf, "Normal"), normal=True)
|
||||
blue = bpy.data.materials.new("Blue")
|
||||
blue.diffuse_color = (0.1, 0.2, 0.9) if OLD else (0.1, 0.2, 0.9, 1.0)
|
||||
if not OLD:
|
||||
blue.metallic = 0.25
|
||||
blue.roughness = 0.6
|
||||
if V >= (5, 0):
|
||||
blue.use_nodes = False
|
||||
me.materials.append(red)
|
||||
me.materials.append(blue)
|
||||
for i, p in enumerate(me.polygons):
|
||||
p.material_index = i % 2
|
||||
box = link(bpy.data.objects.new("Box", me), props)
|
||||
box.location = (1, 2, 3)
|
||||
box.rotation_euler = (0.3, 0.2, 0.1)
|
||||
box.scale = (1, 2, 0.5)
|
||||
box.modifiers.new("Subdiv", "SUBSURF")
|
||||
# triangle, quad, convex pentagon, concave hexagon
|
||||
sv = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (2, 0, 0), (3, 0, 0), (3, 1, 0), (2, 1, 0),
|
||||
(4, 0, 0), (5, 0, 0), (5.5, 0.8, 0), (4.5, 1.5, 0), (3.6, 0.8, 0),
|
||||
(6, 0, 0), (8, 0, 0), (8, 2, 0), (7, 0.5, 0), (6, 2, 0), (6.5, 1, 0.2)]
|
||||
sf = [(0, 1, 2), (3, 4, 5, 6), (7, 8, 9, 10, 11), (12, 13, 14, 15, 16, 17)]
|
||||
shape_me = mesh("ShapeMesh", sv, sf, smooth=True)
|
||||
glow = bpy.data.materials.new("Glow")
|
||||
gb = principled(glow, (0.2, 0.9, 0.2, 1.0), 0.0, 0.8, (1.0, 0.8, 0.1), 5.0)
|
||||
tex(glow, outside, socket(gb, "Emission Color", "Emission") or socket(gb, "Subsurface Color"))
|
||||
shape_me.materials.append(glow)
|
||||
shape = link(bpy.data.objects.new("Shape", shape_me), props)
|
||||
shape.location = (-4, 0, 1)
|
||||
shape.modifiers.new("Mirror", "MIRROR")
|
||||
ball_me = mesh("BallMesh", [(math.cos(a * math.pi / 3) * 0.5, math.sin(a * math.pi / 3) * 0.5, z)
|
||||
for z in (-0.4, 0.4) for a in range(6)],
|
||||
[(0, 1, 7, 6), (1, 2, 8, 7), (2, 3, 9, 8), (3, 4, 10, 9), (4, 5, 11, 10), (5, 0, 6, 11),
|
||||
(5, 4, 3, 2, 1, 0), (6, 7, 8, 9, 10, 11)], smooth=True)
|
||||
ball = link(bpy.data.objects.new("Ball", ball_me), inner)
|
||||
ball.location = (-3, 1, 0.5)
|
||||
ball.rotation_euler = (0, 0, 0.7)
|
||||
update()
|
||||
ball.parent = box
|
||||
ball.matrix_parent_inverse = box.matrix_world.inverted()
|
||||
pivot = link(bpy.data.objects.new("Pivot", None), props)
|
||||
pivot.location = (0, -3, 1)
|
||||
pivot.rotation_mode = "QUATERNION"
|
||||
q = (0.9, 0.1, 0.3, 0.2)
|
||||
n = math.sqrt(sum(c * c for c in q))
|
||||
pivot.rotation_quaternion = tuple(c / n for c in q)
|
||||
leaf_me = mesh("LeafMesh", [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [(0, 1, 2, 3)])
|
||||
leaf_me.materials.append(glow)
|
||||
leaf = link(bpy.data.objects.new("Leaf", leaf_me), props)
|
||||
leaf.parent = pivot
|
||||
leaf.location = (0.5, 0.25, 0)
|
||||
leaf.rotation_mode = "ZXY"
|
||||
leaf.rotation_euler = (0.4, -0.3, 1.1)
|
||||
leaf.scale = (1.5, 1, 1)
|
||||
leaf.delta_location = (0, 0, 0.5)
|
||||
leaf.delta_rotation_euler = (0, 0.2, 0)
|
||||
leaf.delta_scale = (1, 1, 2)
|
||||
# smooth grid with custom normals
|
||||
gv = [(x, y, 0.1 * x * y) for y in range(3) for x in range(3)]
|
||||
gf = [(0, 1, 4, 3), (1, 2, 5, 4), (3, 4, 7, 6), (4, 5, 8, 7)]
|
||||
grid_me = mesh("BentMesh", gv, gf, smooth=True)
|
||||
if V < (4, 1):
|
||||
grid_me.use_auto_smooth = True
|
||||
grid_me.normals_split_custom_set_from_vertices([(0.3 * (i % 3 - 1), 0.2 * (i // 3 - 1), 1.0) for i in range(9)])
|
||||
bent = link(bpy.data.objects.new("Bent", grid_me), props)
|
||||
bent.location = (0, 4, 0)
|
||||
cp = link(bpy.data.objects.new("CamP", camera("CamP")))
|
||||
cp.location = (7, -7, 5)
|
||||
cp.rotation_euler = (1.1, 0, 0.8)
|
||||
co = link(bpy.data.objects.new("CamO", camera("CamO", True)))
|
||||
co.location = (0, 0, 10)
|
||||
for kind in ("POINT", "SUN", "SPOT", "AREA"):
|
||||
lo = link(bpy.data.objects.new("L" + kind.lower(), light("L" + kind.lower(), kind)))
|
||||
lo.location = ({"POINT": 4, "SUN": 0, "SPOT": -4, "AREA": 2}[kind], 1, 6)
|
||||
lo.rotation_euler = (0.5, 0.1, 0)
|
||||
sc.frame_set(1)
|
||||
update()
|
||||
save(os.path.join(out, "scene_%s.blend" % TAG))
|
||||
save(os.path.join(out, "scene_%s_z.blend" % TAG), compress=True)
|
||||
|
||||
|
||||
def rig_file():
|
||||
reset()
|
||||
sc = bpy.context.scene
|
||||
arm_data = bpy.data.armatures.new("RigData")
|
||||
rig = link(bpy.data.objects.new("Rig", arm_data))
|
||||
rig.location = (0, 0, 0.5)
|
||||
rig.rotation_euler = (0, 0, 0.2)
|
||||
if OLD:
|
||||
sc.objects.active = rig
|
||||
else:
|
||||
bpy.context.view_layer.objects.active = rig
|
||||
bpy.ops.object.mode_set(mode="EDIT")
|
||||
eb = arm_data.edit_bones
|
||||
root = eb.new("root")
|
||||
root.head, root.tail, root.roll = (0, 0, 0), (0, 0, 1), 0.0
|
||||
mid = eb.new("mid")
|
||||
mid.head, mid.tail, mid.roll, mid.parent, mid.use_connect = (0, 0, 1), (0, 0.5, 2), 0.3, root, True
|
||||
tip = eb.new("tip")
|
||||
tip.head, tip.tail, tip.roll, tip.parent, tip.use_connect = (0, 0.5, 2), (0.3, 0.5, 2.8), -0.5, mid, True
|
||||
aux = eb.new("aux")
|
||||
aux.head, aux.tail, aux.roll, aux.parent = (0.5, 0, 0.5), (1, 0, 0.5), 0.0, root
|
||||
nodef = eb.new("nodef")
|
||||
nodef.head, nodef.tail, nodef.parent, nodef.use_deform = (-0.5, 0, 0.5), (-1, 0, 0.7), root, False
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
ring = [(math.cos(a * math.pi / 4) * 0.3, math.sin(a * math.pi / 4) * 0.3) for a in range(8)]
|
||||
bv = [(x, y + (0.25 if z == 2 else 0), z) for z in (0, 1, 2) for x, y in ring]
|
||||
bf = [(r * 8 + a, r * 8 + (a + 1) % 8, (r + 1) * 8 + (a + 1) % 8, (r + 1) * 8 + a) for r in range(2) for a in range(8)]
|
||||
body_me = mesh("BodyMesh", bv, bf, smooth=True)
|
||||
body = link(bpy.data.objects.new("Body", body_me))
|
||||
body.parent = rig
|
||||
body.location = (0, 0, 0)
|
||||
mod = body.modifiers.new("Armature", "ARMATURE")
|
||||
mod.object = rig
|
||||
groups = {n: body.vertex_groups.new(name=n) for n in ("root", "mid", "tip", "aux", "nodef", "extra")}
|
||||
for i in range(24):
|
||||
z = i // 8
|
||||
groups["root"].add([i], max(0.0, 1.0 - z * 0.6), "REPLACE")
|
||||
groups["mid"].add([i], 0.3 + 0.2 * (z == 1), "REPLACE")
|
||||
if z == 2:
|
||||
groups["tip"].add([i], 0.9, "REPLACE")
|
||||
if i % 3 == 0:
|
||||
groups["aux"].add([i], 0.05 + 0.01 * i, "REPLACE")
|
||||
groups["nodef"].add([i], 0.7, "REPLACE")
|
||||
groups["extra"].add([i], 0.15, "REPLACE")
|
||||
body.shape_key_add(name="Basis")
|
||||
fat = body.shape_key_add(name="Fat")
|
||||
for i, p in enumerate(fat.data):
|
||||
p.co = (p.co[0] * 1.5, p.co[1] * 1.5, p.co[2])
|
||||
thin = body.shape_key_add(name="Thin")
|
||||
for i, p in enumerate(thin.data):
|
||||
p.co = (p.co[0] * 0.5, p.co[1] * 0.5, p.co[2] + 0.1)
|
||||
thin.value = 0.25
|
||||
key = body_me.shape_keys
|
||||
for f, v in ((1, 0.0), (10, 1.0), (20, 0.2)):
|
||||
fat.value = v
|
||||
fat.keyframe_insert("value", frame=f)
|
||||
hat_me = mesh("HatMesh", [(-0.2, -0.2, 0), (0.2, -0.2, 0), (0, 0.2, 0), (0, 0, 0.3)], [(0, 1, 2), (0, 1, 3), (1, 2, 3), (2, 0, 3)])
|
||||
hat = link(bpy.data.objects.new("Hat", hat_me))
|
||||
hat.parent = rig
|
||||
hat.parent_type = "BONE"
|
||||
hat.parent_bone = "tip"
|
||||
hat.location = (0.1, 0.2, 0.0)
|
||||
pose = rig.pose.bones
|
||||
pose["aux"].rotation_mode = "XYZ"
|
||||
keys = ((1, (0, 0, 0), (1, 0, 0, 0), (1, 1, 1), (0, 0, 0)),
|
||||
(10, (0.2, 0.1, 0), (0.92, 0.3, 0.2, 0.1), (1.2, 1, 1), (0.4, 0, 0.3)),
|
||||
(20, (0, 0.3, 0.2), (0.8, -0.2, 0.5, 0.2), (0.8, 1.1, 1), (-0.3, 0.5, 0)))
|
||||
for f, loc, quat, scl, eul in keys:
|
||||
pose["root"].location = loc
|
||||
pose["root"].keyframe_insert("location", frame=f)
|
||||
n = math.sqrt(sum(c * c for c in quat))
|
||||
pose["mid"].rotation_quaternion = tuple(c / n for c in quat)
|
||||
pose["mid"].keyframe_insert("rotation_quaternion", frame=f)
|
||||
pose["tip"].scale = scl
|
||||
pose["tip"].keyframe_insert("scale", frame=f)
|
||||
pose["aux"].rotation_euler = eul
|
||||
pose["aux"].keyframe_insert("rotation_euler", frame=f)
|
||||
mover = link(bpy.data.objects.new("Mover", mesh("MoverMesh", [(0, 0, 0), (1, 0, 0), (0, 1, 0)], [(0, 1, 2)])))
|
||||
for f, loc, rot, scl in ((1, (3, 0, 0), (0, 0, 0), (1, 1, 1)), (8, (3, 2, 1), (0.5, 0, 1), (2, 1, 1)),
|
||||
(20, (5, 2, 0), (0, 1, -1), (1, 1, 3))):
|
||||
mover.location, mover.rotation_euler, mover.scale = loc, rot, scl
|
||||
mover.keyframe_insert("location", frame=f)
|
||||
mover.keyframe_insert("rotation_euler", frame=f)
|
||||
mover.keyframe_insert("scale", frame=f)
|
||||
rig_action = rig.animation_data.action
|
||||
mover_action = mover.animation_data.action
|
||||
for act, rules in ((rig_action, {"location": "LINEAR", "scale": "CONSTANT"}),
|
||||
(mover_action, {"rotation_euler": "LINEAR", "scale": "CONSTANT"})):
|
||||
curves = act.fcurves if hasattr(act, "fcurves") else [c for l in act.layers for s in l.strips for b in s.channelbags for c in b.fcurves]
|
||||
for fc in curves:
|
||||
for k, ipo in rules.items():
|
||||
if fc.data_path.endswith(k):
|
||||
for kp in fc.keyframe_points:
|
||||
kp.interpolation = ipo
|
||||
if fc.data_path == "location" and fc.array_index == 2:
|
||||
fc.extrapolation = "LINEAR"
|
||||
sc.frame_set(1)
|
||||
update()
|
||||
save(os.path.join(out, "rig_%s.blend" % TAG))
|
||||
|
||||
|
||||
scene_file()
|
||||
rig_file()
|
||||
if OLD:
|
||||
scene_file()
|
||||
save(os.path.join(out, "compat_%s.blend" % TAG), compat=True)
|
||||
print("MADE", TAG)
|
||||
@@ -0,0 +1,219 @@
|
||||
# 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),
|
||||
# and 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,
|
||||
"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
|
||||
|
||||
|
||||
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": {}}
|
||||
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]}
|
||||
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]
|
||||
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
|
||||
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)
|
||||
@@ -0,0 +1,92 @@
|
||||
# .blend fixtures (tools/fixtures.py): the same test scenes built by Blender 2.79, 2.93, 3.5, 4.1 (old nixpkgs
|
||||
# releases) and the current nixpkgs Blender (5.x) through tools/fixtures/_blend_make.py, covering every mesh storage
|
||||
# generation (MFace legacy save, MPoly / MLoop, attribute layers, AttributeStorage), gzip and zstd compression, the
|
||||
# 5.0 header, layered actions. Reference values come from the current Blender opening each file
|
||||
# (tools/fixtures/_blend_ref.py: bpy values plus its glTF exporter's output). An old Blender that does not run is
|
||||
# skipped (its cases are missing; the test notes it).
|
||||
# tests/gen/blend_<ver>.luau { { name, data, ref } }
|
||||
# tests/gen/blend_files.luau sibling files the scenes refer to ({ ["outside.png"] = bytes })
|
||||
import json, os, shutil, subprocess, tempfile
|
||||
|
||||
INPUTS = ["tools/fixtures/_blend_make.py", "tools/fixtures/_blend_ref.py"]
|
||||
|
||||
OLD = [
|
||||
("279", ["--impure", "--expr", '(import (builtins.fetchTarball "https://github.com/NixOS/nixpkgs/archive/nixos-19.03.tar.gz") {}).blender']),
|
||||
("293", ["github:NixOS/nixpkgs/nixos-21.11#blender"]),
|
||||
("35", ["github:NixOS/nixpkgs/nixos-23.05#blender"]),
|
||||
("41", ["github:NixOS/nixpkgs/nixos-24.05#blender"]),
|
||||
]
|
||||
|
||||
|
||||
def env():
|
||||
e = dict(os.environ)
|
||||
e.pop("LD_LIBRARY_PATH", None) # the host's alsa / pipewire libraries need a newer glibc than old Blenders have
|
||||
return e
|
||||
|
||||
|
||||
def current():
|
||||
exe = shutil.which("blender")
|
||||
return [exe] if exe else ["nix", "shell", "nixpkgs#blender", "-c", "blender"]
|
||||
|
||||
|
||||
def run(cmd, timeout=1800):
|
||||
try:
|
||||
res = subprocess.run(cmd, capture_output=True, timeout=timeout, env=env())
|
||||
return res.returncode == 0, res.stdout.decode("utf-8", "replace") + res.stderr.decode("utf-8", "replace")
|
||||
except (subprocess.TimeoutExpired, OSError) as e:
|
||||
return False, str(e)
|
||||
|
||||
|
||||
def clean(v):
|
||||
if isinstance(v, dict):
|
||||
return {k: clean(x) for k, x in v.items() if x is not None}
|
||||
if isinstance(v, list):
|
||||
return [False if x is None else clean(x) for x in v]
|
||||
return v
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="blendfx")
|
||||
make = os.path.join(ctx.root, "tools", "fixtures", "_blend_make.py")
|
||||
ref = os.path.join(ctx.root, "tools", "fixtures", "_blend_ref.py")
|
||||
made = {}
|
||||
for tag, inst in OLD + [("cur", None)]:
|
||||
out = os.path.join(tmp, tag)
|
||||
os.makedirs(out)
|
||||
if inst is None:
|
||||
cmd = current()
|
||||
else:
|
||||
cmd = ["nix", "shell"] + inst + ["-c", "blender"]
|
||||
ok, log = run(cmd + ["-b", "--factory-startup", "--python", make, "--", out])
|
||||
files = sorted(f for f in os.listdir(out) if f.endswith(".blend"))
|
||||
if not ok or not files:
|
||||
print("blend: Blender %s did not run (skipped): %s" % (tag, log[-400:]))
|
||||
continue
|
||||
made[tag] = (out, files)
|
||||
paths = [os.path.join(out, f) for out, files in made.values() for f in files]
|
||||
refdir = os.path.join(tmp, "ref")
|
||||
os.makedirs(refdir)
|
||||
ok, log = run(current() + ["-b", "--factory-startup", "--python", ref, "--", json.dumps(paths), refdir], timeout=3600)
|
||||
if not ok:
|
||||
raise RuntimeError("blend: the reference Blender failed: " + log[-2000:])
|
||||
sibling = None
|
||||
for tag, (out, files) in made.items():
|
||||
cases = []
|
||||
for f in files:
|
||||
p = os.path.join(out, f)
|
||||
r = json.load(open(os.path.join(refdir, f + ".json")))
|
||||
g = r.get("gltf")
|
||||
if g:
|
||||
for k in ("bufferViews", "asset", "scene", "scenes", "extensionsUsed", "samplers"):
|
||||
g.pop(k, None)
|
||||
cases.append({"name": f, "data": open(p, "rb").read(), "ref": clean(r)})
|
||||
name = "cur" if tag == "cur" else tag
|
||||
ctx.emit("blend_" + name, cases)
|
||||
if sibling is None and os.path.exists(os.path.join(out, "outside.png")):
|
||||
sibling = open(os.path.join(out, "outside.png"), "rb").read()
|
||||
for tag, _ in OLD + [("cur", None)]:
|
||||
if tag not in made:
|
||||
ctx.emit("blend_" + tag, [])
|
||||
ctx.emit("blend_files", {"outside.png": sibling or b""})
|
||||
ctx.emit("blend_versions", sorted(made.keys()))
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
Reference in new issue
Block a user