diff --git a/src/Rosetta/model/blend/Armature.luau b/src/Rosetta/model/blend/Armature.luau new file mode 100644 index 0000000..01e7438 --- /dev/null +++ b/src/Rosetta/model/blend/Armature.luau @@ -0,0 +1,404 @@ +--!strict +-- model/blend/Armature: the rig data of an armature as Blender's Python API names it: bones (head / tail / roll in +-- armature space, deform, connect, wire), bone collections (4.x BoneCollection arrays and lists; before 4.0 the layers +-- and bone groups converted as Blender 4.0's versioning does), bone colours (BoneColor; bone group colours before 4.0), +-- pose bones (custom shapes, locks, rotation mode, IK settings) and constraint stacks (bConstraint and the data structs +-- of IK, copy rotation / location / scale / transforms, damped track, limit rotation / location / scale, child of; the +-- common fields for the rest). Flags from DNA_armature_types.h, DNA_action_types.h, DNA_constraint_types.h. +local Blend = require("@rosetta/containers/Blend") + +local Armature = {} + +export type Target = number | string -- a scene node index, or the object's name when it is not in the scene +export type Resolve = (ob: Blend.View?) -> Target? +export type Color = { palette: string, normal: { number }?, select: { number }?, active: { number }? } + +-- Blender's default theme (userdef_default_theme.c): bone colour sets THEME01..THEME20 as normal, select, active +local THEME = { + { 0x9a0000, 0xbd1111, 0xf70a0a }, { 0xf74018, 0xf66913, 0xfa9900 }, { 0x1e9109, 0x59b70b, 0x83ef1d }, + { 0x0a3694, 0x3667df, 0x5ec1ef }, { 0xa9294e, 0xc1416a, 0xf05d91 }, { 0x430c78, 0x543aa3, 0x8764d5 }, + { 0x24785a, 0x3c9579, 0x6fb6ab }, { 0x4b707c, 0x6a8691, 0x9bc2cd }, { 0xf4c90c, 0xeec236, 0xf3ff00 }, + { 0x1e2024, 0x484c56, 0xffffff }, { 0x6f2f6a, 0x9845be, 0xd330d6 }, { 0x6c8e22, 0x7fb022, 0xbbef5b }, + { 0x8d8d8d, 0xb0b0b0, 0xdedede }, { 0x834326, 0x8b5811, 0xbd6a11 }, { 0x08310e, 0x1c430b, 0x34622b }, + { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, +} + +local function rgb(hex: number): { number } + return { bit32.rshift(hex, 16) / 255, bit32.band(bit32.rshift(hex, 8), 255) / 255, bit32.band(hex, 255) / 255 } +end + +function Armature.colorSets(): { { normal: { number }, select: { number }, active: { number } } } + local out = {} + for i, s in THEME do + out[i] = { normal = rgb(s[1]), select = rgb(s[2]), active = rgb(s[3]) } + end + return out +end + +local ROTMODE: { [number]: string } = { [0] = "QUATERNION", [1] = "XYZ", [2] = "XZY", [3] = "YXZ", [4] = "YZX", [5] = "ZXY", [6] = "ZYX", [-1] = "AXIS_ANGLE" } +local SPACE: { [number]: string } = { [0] = "WORLD", [1] = "LOCAL", [2] = "POSE", [3] = "LOCAL_WITH_PARENT", [5] = "CUSTOM", [6] = "LOCAL_OWNER_ORIENT" } +local EULER_ORDER: { [number]: string } = { [0] = "AUTO", [1] = "XYZ", [2] = "XZY", [3] = "YXZ", [4] = "YZX", [5] = "ZXY", [6] = "ZYX" } +local TRACK: { [number]: string } = { [0] = "TRACK_X", [1] = "TRACK_Y", [2] = "TRACK_Z", [3] = "TRACK_NEGATIVE_X", [4] = "TRACK_NEGATIVE_Y", [5] = "TRACK_NEGATIVE_Z" } +local ROT_MIX: { [number]: string } = { [0] = "REPLACE", [1] = "OFFSET", [2] = "ADD", [3] = "BEFORE", [4] = "AFTER" } +local TRANS_MIX: { [number]: string } = { [0] = "REPLACE", [1] = "BEFORE", [2] = "AFTER", [3] = "BEFORE_FULL", [4] = "BEFORE_SPLIT", [5] = "AFTER_FULL", [6] = "AFTER_SPLIT" } +local TYPE: { [number]: string } = { + [1] = "CHILD_OF", [2] = "TRACK_TO", [3] = "IK", [4] = "FOLLOW_PATH", [5] = "LIMIT_ROTATION", [6] = "LIMIT_LOCATION", + [7] = "LIMIT_SCALE", [8] = "COPY_ROTATION", [9] = "COPY_LOCATION", [10] = "COPY_SCALE", [11] = "PYTHON", [12] = "ACTION", + [13] = "LOCKED_TRACK", [14] = "LIMIT_DISTANCE", [15] = "STRETCH_TO", [16] = "FLOOR", [17] = "RIGID_BODY_JOINT", + [18] = "CLAMP_TO", [19] = "TRANSFORM", [20] = "SHRINKWRAP", [21] = "DAMPED_TRACK", [22] = "SPLINE_IK", + [23] = "COPY_TRANSFORMS", [24] = "MAINTAIN_VOLUME", [25] = "PIVOT", [26] = "FOLLOW_TRACK", [27] = "CAMERA_SOLVER", + [28] = "OBJECT_SOLVER", [29] = "TRANSFORM_CACHE", [30] = "ARMATURE", [31] = "GEOMETRY_ATTRIBUTE", +} +-- constraint types with a head_tail (bConstraint.headtail) in Blender's API +local HEAD_TAIL: { [string]: boolean } = { + COPY_LOCATION = true, COPY_TRANSFORMS = true, DAMPED_TRACK = true, TRACK_TO = true, LOCKED_TRACK = true, + STRETCH_TO = true, LIMIT_DISTANCE = true, +} + +local CONSTRAINT_OFF, CONSTRAINT_BBONE_SHAPE = 0x200, 0x400 +local BONE_CONNECTED, BONE_HIDDEN_P, BONE_NO_DEFORM, BONE_DRAWWIRE = 0x10, 0x40, 0x1000, 0x20000 +local PCHAN_DRAW_NO_CUSTOM_BONE_SIZE = 1 +-- bPoseChannel.protectflag (OB_LOCK_*) and ikflag (BONE_IK_*) +local LOCK_LOC, LOCK_ROT, LOCK_SCALE, LOCK_ROTW, LOCK_ROT4D = { 1, 2, 4 }, { 8, 16, 32 }, { 64, 128, 256 }, 512, 1024 +local IK_NO_DOF, IK_LIMIT = { 1, 2, 4 }, { 8, 16, 32 } +local AXES = { "x", "y", "z" } + +local function bit(v: number?, mask: number): boolean + return bit32.band(v or 0, mask) ~= 0 +end + +local function bits(v: number?, masks: { number }): { boolean } + return { bit(v, masks[1]), bit(v, masks[2]), bit(v, masks[3]) } +end + +local function vec3(v: Blend.View, name: string, fallback: { number }?): { number }? + local x = v:vec(name) + if x and #x >= 3 then + return { x[1], x[2], x[3] } + end + return fallback and table.clone(fallback) +end + +local function text(v: Blend.View, name: string): string? + local s = v:str(name) + return if s and s ~= "" then s else nil +end + +-- ThemeWireColor: char solid[4], select[4], active[4] (sRGB bytes) +local function wire(v: Blend.View?): { [string]: { number } }? + if not v then + return nil + end + local out = {} + for key, field in { normal = "solid", select = "select", active = "active" } do + local fld = v.struct.byName[field] + local o = fld and v.offset + fld.offset + if not o or o + 3 > buffer.len(v.file.buf) then + return nil + end + local b = v.file.buf + out[key] = { buffer.readu8(b, o) / 255, buffer.readu8(b, o + 1) / 255, buffer.readu8(b, o + 2) / 255 } + end + return out +end + +-- palette: 0 default, 1..20 the theme sets, -1 custom (BoneColor.palette_index, bActionGroup.customCol); the colours +-- are the custom ones, or the default theme's set +local function color(index: number?, custom: Blend.View?): Color? + if not index or index == 0 then + return nil + end + local c: Color = { palette = if index < 0 then "CUSTOM" else string.format("THEME%02d", index) } + local w = if index < 0 then wire(custom) else nil + if w then + c.normal, c.select, c.active = w.normal, w.select, w.active + elseif index > 0 and THEME[index] then + local s = THEME[index] + c.normal, c.select, c.active = rgb(s[1]), rgb(s[2]), rgb(s[3]) + end + return c +end + +local function boneColor(v: Blend.View): Color? + local bc = v:sub("color") + if not bc then + return nil + end + return color(bc:num("palette_index"), bc:sub("custom")) +end + +-- ------------------------------------------------------------------------------------------------ bones +export type Collections = { + list: { { name: string, visible: boolean, parent: string? } }, + byBone: { [string]: { string } }, -- bone name -> its collections, in collection order +} + +-- 4.1+: collection_array with child_index / child_count; 4.0: the collections list; before 4.0 the used layers +-- ("Layer N", hidden when the layer is off) and then the bone groups (hidden), as Blender's 4.0 versioning converts them +function Armature.collections(arm: Blend.View, bones: { Blend.View }, pose: Blend.View?): Collections + local out: Collections = { list = {}, byBone = {} } + local byAddr: { [any]: string } = {} + for _, b in bones do + if b.block then + byAddr[b.block.addr] = b:str("name") or "" + end + end + local function add(name: string, members: { string }) + for _, m in members do + local l = out.byBone[m] or {} + out.byBone[m] = l + table.insert(l, name) + end + end + local VISIBLE = 1 + local array = arm:has("collection_array") and arm:pointers("collection_array", arm:num("collection_array_num") or 0) or {} + local cols: { Blend.View } = {} + if #array > 0 then + for _, addr in array do + local blk = addr and Blend.resolve(arm.file, addr, arm.block) + local v = blk and Blend.struct(arm.file, blk, 0, "BoneCollection") + if v then + table.insert(cols, v) + end + end + elseif arm:has("collections") then + cols = arm:list("collections", "BoneCollection") + end + if #cols > 0 then + local parent: { [number]: string } = {} + for i, c in cols do + local first, n = c:num("child_index") or 0, c:num("child_count") or 0 + for k = first + 1, math.min(first + n, #cols) do + parent[k] = c:str("name") + end + local _ = i + end + for i, c in cols do + local name = c:str("name") or "" + table.insert(out.list, { name = name, visible = bit(c:num("flags"), VISIBLE), parent = parent[i] }) + local members = {} + for _, m in c:list("bones", "BoneCollectionMember") do + local n = byAddr[m:ptr("bone")] + if n then + table.insert(members, n) + end + end + add(name, members) + end + return out + end + local used, shown = arm:num("layer_used"), arm:num("layer") + if used then + for layer = 0, 31 do + local mask = bit32.lshift(1, layer) + if bit(used, mask) then + local name = "Layer " .. (layer + 1) + table.insert(out.list, { name = name, visible = bit(shown, mask) }) + local members = {} + for _, b in bones do + if bit(b:num("layer"), mask) then + table.insert(members, b:str("name") or "") + end + end + add(name, members) + end + end + end + if pose then + local groups = pose:list("agroups", "bActionGroup") + local members: { [number]: { string } } = {} + for _, pc in pose:list("chanbase", "bPoseChannel") do + local g = pc:num("agrp_index") or 0 + if g > 0 and groups[g] then + members[g] = members[g] or {} + table.insert(members[g], pc:str("name") or "") + end + end + for g, grp in groups do + local name = grp:str("name") or "" + table.insert(out.list, { name = name, visible = false }) + add(name, members[g] or {}) + end + end + return out +end + +-- a Bone's own fields: head_local / tail_local / roll in armature space (the roll is already in arm_mat, the rest +-- matrix); color from the Bone (4.x) or from the bone group of its pose channel (before 4.0) +function Armature.bone(bone: Blend.View, pc: Blend.View?, pose: Blend.View?): { [string]: any } + local flag = bone:num("flag") or 0 + local e: { [string]: any } = { + deform = not bit(flag, BONE_NO_DEFORM), + use_connect = bit(flag, BONE_CONNECTED), + show_wire = bit(flag, BONE_DRAWWIRE), + hide = bit(flag, BONE_HIDDEN_P), + head_local = vec3(bone, "arm_head"), + tail_local = vec3(bone, "arm_tail"), + roll = bone:num("arm_roll"), + } + if bone:has("color") then + e.color = boneColor(bone) + elseif pc and pose then + local g = pc:num("agrp_index") or 0 + local grp = if g > 0 then pose:list("agroups", "bActionGroup")[g] else nil + if grp then + e.color = color(grp:num("customCol"), grp:sub("cs")) + end + end + return e +end + +-- ------------------------------------------------------------------------------------------------ constraints +local function constraintData(e: { [string]: any }, kind: string, d: Blend.View, resolve: Resolve) + local flag = d:num("flag") or 0 + if kind == "IK" then + -- CONSTRAINT_IK_TIP / ROT / STRETCH / POS, NO_POS_X.. / NO_ROT_X..; type 0 copy pose, 1 distance + e.pole_target = resolve(d:deref("poletar", 0, "Object")) + e.pole_subtarget = text(d, "polesubtarget") + e.pole_angle = d:num("poleangle") + e.chain_count = d:num("rootbone") + e.iterations = d:num("iterations") + e.weight = d:num("weight") + e.orient_weight = d:num("orientweight") + e.use_tail = bit(flag, 1) + e.use_rotation = bit(flag, 2) + e.use_stretch = bit(flag, 16) + e.use_location = bit(flag, 32) + -- lock_* are the inverse of the NO_POS / NO_ROT bits, as Blender's API defines them + e.lock_location_x, e.lock_location_y, e.lock_location_z = not bit(flag, 256), not bit(flag, 512), not bit(flag, 1024) + e.lock_rotation_x, e.lock_rotation_y, e.lock_rotation_z = not bit(flag, 2048), not bit(flag, 4096), not bit(flag, 8192) + e.ik_type = if (d:num("type") or 0) == 1 then "DISTANCE" else "COPY_POSE" + e.distance = d:num("dist") + elseif kind == "COPY_ROTATION" then + -- ROTLIKE_X 1, Y 2, Z 4, X_INVERT 16, Y_INVERT 32, Z_INVERT 64, OFFSET 128 (mix_mode OFFSET before 2.82) + e.use_x, e.use_y, e.use_z = bit(flag, 1), bit(flag, 2), bit(flag, 4) + e.invert_x, e.invert_y, e.invert_z = bit(flag, 16), bit(flag, 32), bit(flag, 64) + e.euler_order = EULER_ORDER[d:num("euler_order") or 0] + local mix = d:num("mix_mode") + e.mix_mode = if mix then ROT_MIX[mix] else (if bit(flag, 128) then "OFFSET" else "REPLACE") + elseif kind == "COPY_LOCATION" then + -- LOCLIKE_X 1, Y 2, Z 4, X_INVERT 16, Y_INVERT 32, Z_INVERT 64, OFFSET 128 + e.use_x, e.use_y, e.use_z = bit(flag, 1), bit(flag, 2), bit(flag, 4) + e.invert_x, e.invert_y, e.invert_z = bit(flag, 16), bit(flag, 32), bit(flag, 64) + e.use_offset = bit(flag, 128) + elseif kind == "COPY_SCALE" then + -- SIZELIKE_X 1, Y 2, Z 4, OFFSET 8 + e.use_x, e.use_y, e.use_z = bit(flag, 1), bit(flag, 2), bit(flag, 4) + e.use_offset = bit(flag, 8) + e.power = d:num("power") or 1 + elseif kind == "COPY_TRANSFORMS" then + e.mix_mode = TRANS_MIX[d:num("mix_mode") or 0] + e.remove_target_shear = bit(flag, 1) + elseif kind == "DAMPED_TRACK" then + e.track_axis = TRACK[d:num("trackflag") or 1] + elseif kind == "LIMIT_ROTATION" then + -- LIMIT_XROT 1, YROT 2, ZROT 4; flag2 LIMIT_TRANSFORM 2 + for i, a in AXES do + e["use_limit_" .. a] = bit(flag, bit32.lshift(1, i - 1)) + e["min_" .. a] = d:num(a .. "min") + e["max_" .. a] = d:num(a .. "max") + end + e.use_transform_limit = bit(d:num("flag2"), 2) + e.euler_order = EULER_ORDER[d:num("euler_order") or 0] + elseif kind == "LIMIT_LOCATION" or kind == "LIMIT_SCALE" then + -- LIMIT_XMIN 1, XMAX 2, YMIN 4, YMAX 8, ZMIN 16, ZMAX 32; flag2 LIMIT_TRANSFORM 2 + for i, a in AXES do + e["use_min_" .. a] = bit(flag, bit32.lshift(1, (i - 1) * 2)) + e["use_max_" .. a] = bit(flag, bit32.lshift(2, (i - 1) * 2)) + e["min_" .. a] = d:num(a .. "min") + e["max_" .. a] = d:num(a .. "max") + end + e.use_transform_limit = bit(d:num("flag2"), 2) + elseif kind == "CHILD_OF" then + -- CHILDOF_LOCX 1 .. SIZEZ 256, SET_INVERSE 512 + for i, a in AXES do + e["use_location_" .. a] = bit(flag, bit32.lshift(1, i - 1)) + e["use_rotation_" .. a] = bit(flag, bit32.lshift(8, i - 1)) + e["use_scale_" .. a] = bit(flag, bit32.lshift(64, i - 1)) + end + e.set_inverse_pending = bit(flag, 512) + local m = d:vec("invmat") + e.inverse_matrix = if m and #m == 16 then m else nil -- column-major + end +end + +-- a constraint stack (ListBase of bConstraint) in evaluation order +function Armature.constraints(owner: Blend.View, resolve: Resolve): { { [string]: any } } + local out = {} + for _, c in owner:list("constraints", "bConstraint") do + local t = c:num("type") or 0 + local kind = TYPE[t] or tostring(t) + local flag = c:num("flag") or 0 + local e: { [string]: any } = { + type = kind, + name = c:str("name") or "", + influence = c:num("enforce") or 1, + mute = bit(flag, CONSTRAINT_OFF), + owner_space = SPACE[c:num("ownspace") or 0], + target_space = SPACE[c:num("tarspace") or 0], + } + if HEAD_TAIL[kind] then + e.head_tail = c:num("headtail") or 0 + e.use_bbone_shape = bit(flag, CONSTRAINT_BBONE_SHAPE) + end + if e.owner_space == "CUSTOM" or e.target_space == "CUSTOM" then + e.space_object = resolve(c:deref("space_object", 0, "Object")) + e.space_subtarget = text(c, "space_subtarget") + end + local d = c:deref("data", 0) + if d then + if d:has("tar") then + e.target = resolve(d:deref("tar", 0, "Object")) + end + e.subtarget = text(d, "subtarget") + if d:has("targets") then + local targets = {} + for _, ct in d:list("targets", "bConstraintTarget") do + table.insert(targets, { target = resolve(ct:deref("tar", 0, "Object")), subtarget = text(ct, "subtarget"), weight = ct:num("weight") }) + end + e.targets = targets + end + constraintData(e, kind, d, resolve) + end + table.insert(out, e) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ pose bones +-- a bPoseChannel's settings into e: constraint targets through resolve, the custom shape object through shape +function Armature.pose(e: { [string]: any }, pc: Blend.View, resolve: Resolve, shape: Resolve) + local protect = pc:num("protectflag") or 0 + local ik = pc:num("ikflag") or 0 + e.rotation_mode = ROTMODE[pc:num("rotmode") or 0] or "QUATERNION" + e.lock_location = bits(protect, LOCK_LOC) + e.lock_rotation = bits(protect, LOCK_ROT) + e.lock_rotation_w = bit(protect, LOCK_ROTW) + e.lock_rotations_4d = bit(protect, LOCK_ROT4D) + e.lock_scale = bits(protect, LOCK_SCALE) + local custom = pc:deref("custom", 0, "Object") + if custom then + e.custom_shape = shape(custom) + end + local tx = pc:deref("custom_tx", 0, "bPoseChannel") + e.custom_shape_transform = if tx then text(tx, "name") else nil + e.custom_shape_translation = vec3(pc, "custom_translation", { 0, 0, 0 }) + e.custom_shape_rotation_euler = vec3(pc, "custom_rotation_euler", { 0, 0, 0 }) + local s = pc:num("custom_scale") or 1 -- before 3.0: one uniform scale + e.custom_shape_scale_xyz = vec3(pc, "custom_scale_xyz", { s, s, s }) + e.use_custom_shape_bone_size = not bit(pc:num("drawflag"), PCHAN_DRAW_NO_CUSTOM_BONE_SIZE) + e.custom_shape_wire_width = pc:num("custom_shape_wire_width") + e.ik_stretch = pc:num("ikstretch") or 0 + local lo, hi, stiff = pc:vec("limitmin"), pc:vec("limitmax"), pc:vec("stiffness") + for i, a in AXES do + e["lock_ik_" .. a] = bit(ik, IK_NO_DOF[i]) + e["use_ik_limit_" .. a] = bit(ik, IK_LIMIT[i]) + e["ik_min_" .. a] = lo and lo[i] or -math.pi + e["ik_max_" .. a] = hi and hi[i] or math.pi + e["ik_stiffness_" .. a] = stiff and stiff[i] or 0 + end + e.pose_color = if pc:has("color") then boneColor(pc) else nil + e.constraints = Armature.constraints(pc, resolve) +end + +return Armature diff --git a/src/Rosetta/model/blend/Mesh.luau b/src/Rosetta/model/blend/Mesh.luau index 25155b5..f890508 100644 --- a/src/Rosetta/model/blend/Mesh.luau +++ b/src/Rosetta/model/blend/Mesh.luau @@ -236,6 +236,75 @@ end export type Limits = { maxVertices: number? } +-- edge count and per-edge readers (vertex 1, vertex 2, sharp): ".edge_verts" / "sharp_edge" attributes or MEdge +local function edgeReaders(f: Blend.File, me: Blend.View, layers: { Layer }): (number, ((number) -> number)?, ((number) -> number)?, ((number) -> boolean)?) + local ne = count(me, "totedge", "edges_num") + local ev = find(layers, "edge", "int2", ".edge_verts") + local se = find(layers, "edge", "bool", "sharp_edge") + local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge") + if ne == 0 then + return 0, nil, nil, nil + end + if ev then + local er = reader(f, ev) + local sr = if se then reader(f, se) else nil + return ne, function(i: number): number + return er(i, 0) + end, function(i: number): number + return er(i, 1) + end, function(i: number): boolean + return sr ~= nil and sr(i, 0) ~= 0 + end + elseif medge then + local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag") + if a and b then + local ser = if se then reader(f, se) else nil + return ne, function(i: number): number + return a(i, 0) + end, function(i: number): number + return b(i, 0) + end, function(i: number): boolean + if ser then + return ser(i, 0) ~= 0 + end + return fl ~= nil and bit32.band(fl(i, 0), ME_SHARP) ~= 0 + end + end + end + return ne, nil, nil, nil +end + +-- edges no face uses, as u32 vertex pairs (rig widgets are usually edges only) +function Mesh.looseEdges(f: Blend.File, me: Blend.View, poly: Poly): buffer + local ne, v1, v2 = edgeReaders(f, me, poly.layers) + if not v1 or not v2 then + return buffer.create(0) + end + local nv = poly.nv + local used: { [number]: boolean } = {} + local cv, fs = poly.cornerVert, poly.faceStart + for fi = 0, poly.nf - 1 do + local s0, s1 = buffer.readu32(fs, fi * 4), buffer.readu32(fs, fi * 4 + 4) + for c = s0, s1 - 1 do + local a, b = buffer.readu32(cv, c * 4), buffer.readu32(cv, (if c + 1 < s1 then c + 1 else s0) * 4) + used[math.min(a, b) * nv + math.max(a, b)] = true + end + end + local out = {} + for i = 0, ne - 1 do + local a, b = v1(i), v2(i) + if a ~= b and a >= 0 and b >= 0 and a < nv and b < nv and not used[math.min(a, b) * nv + math.max(a, b)] then + table.insert(out, a) + table.insert(out, b) + end + end + local buf = buffer.create(#out * 4) + for k, v in out do + buffer.writeu32(buf, (k - 1) * 4, v) + end + return buf +end + function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, string?) local layers = Mesh.layers(f, me) local nv = count(me, "totvert", "verts_num") @@ -515,10 +584,6 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri poly.customNormals = d end -- sharp edges - local ne = count(me, "totedge", "edges_num") - local ev = find(layers, "edge", "int2", ".edge_verts") - local se = find(layers, "edge", "bool", "sharp_edge") - local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge") local flags = me:num("flag") or 0 local smoothresh = me:num("smoothresh") local autoSmooth = f.version < 401 and bit32.band(flags, ME_AUTOSMOOTH) ~= 0 @@ -526,27 +591,8 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri poly.autoSmooth = smoothresh or math.rad(30) end local useSharp = f.version >= 401 or autoSmooth - if useSharp and ne > 0 then - local v1, v2, sharp - if ev and se then - local er, sr = reader(f, ev), reader(f, se) - v1 = function(i: number): number return er(i, 0) end - v2 = function(i: number): number return er(i, 1) end - sharp = function(i: number): boolean return sr(i, 0) ~= 0 end - elseif medge then - local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag") - if a and b and fl then - v1 = function(i: number): number return a(i, 0) end - v2 = function(i: number): number return b(i, 0) end - local ser = if se then reader(f, se) else nil - sharp = function(i: number): boolean - if ser then - return ser(i, 0) ~= 0 - end - return bit32.band(fl(i, 0), ME_SHARP) ~= 0 - end - end - end + if useSharp then + local ne, v1, v2, sharp = edgeReaders(f, me, layers) if v1 and v2 and sharp then for i = 0, ne - 1 do if sharp(i) then @@ -591,7 +637,7 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri end -- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index -export type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean, min: number, max: number } +export type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean, min: number, max: number, vgroup: string? } function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?) local key = me:deref("key", 0, "Key") if not key then @@ -601,6 +647,7 @@ function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, num local refAddr = key:ptr("refkey") local out: { Shape } = {} local ref: number? = nil + local index = 0 for i, kb in blocks do local blk = kb:target("data") local d = buffer.create(nv * 12) @@ -613,15 +660,23 @@ function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, num end end end - if kb.block and kb.block.addr == refAddr then + local isRef = kb.block ~= nil and kb.block.addr == refAddr + if isRef then ref = i + else + index += 1 + end + local name = kb:str("name") + if not name or name == "" then + -- unnamed in old files: named as Blender's 2.45 versioning does (Basis, Key 1, Key 2, ...) + name = if isRef then "Basis" else "Key " .. index end table.insert(out, { - -- unnamed in old files: Key 0 (the basis), Key 1, ... - name = kb:str("name") or ("Key " .. (i - 1)), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, - mute = bit32.band(kb:num("flag") or 0, 2) ~= 0, + name = name, value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, + mute = bit32.band(kb:num("flag") or 0, 1) ~= 0, -- KEYBLOCK_MUTE min = kb:num("slidermin") or 0, max = kb:num("slidermax") or 1, + vgroup = if kb:str("vgroup") ~= "" then kb:str("vgroup") else nil, }) end if ref == nil and #out > 0 then diff --git a/src/Rosetta/model/blend/Prim.luau b/src/Rosetta/model/blend/Prim.luau index 010b907..3b30531 100644 --- a/src/Rosetta/model/blend/Prim.luau +++ b/src/Rosetta/model/blend/Prim.luau @@ -258,8 +258,80 @@ end export type Built = { mesh: Types.Mesh, slots: { number }, vertexSource: { { number } } } --- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints -function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: Skinning?, shapes: { MeshT.Shape }?, ref: number?): Built +-- morph targets of the output vertices (vsrc: their mesh vertices): each key minus its relative key, times the weight +-- of the key's vertex group, as Blender evaluates relative keys +local function targetDeltas(poly: MeshT.Poly, vsrc: { number }, shapes: { MeshT.Shape }, ref: number, groups: { string }?): { { [string]: Types.Accessor } } + local n = #vsrc + local targets: { { [string]: Types.Accessor } } = {} + for k, s in shapes do + if k ~= ref then + local rel = shapes[s.relative + 1] or shapes[ref] + local base = rel.data + local def: number? = nil + if s.vgroup and groups then + for gi, g in groups do + if g == s.vgroup then + def = gi - 1 + end + end + end + local t = table.create(n * 3) :: { number } + for i = 1, n do + local v = vsrc[i] + local w = 1 + if def then + w = 0 + local list = poly.weights and poly.weights[v + 1] or {} + for q = 1, #list - 1, 2 do + if list[q] == def then + w = list[q + 1] + end + end + end + for c = 0, 2 do + t[(i - 1) * 3 + c + 1] = (readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4)) * w + end + end + table.insert(targets, { POSITION = accessor(t, 3) } :: { [string]: Types.Accessor }) + end + end + return targets +end + +-- a "lines" primitive of the given edges (u32 vertex pairs), with the morph targets the face primitives have +function Prim.lines(poly: MeshT.Poly, edges: buffer, shapes: { MeshT.Shape }?, ref: number?, groups: { string }?): Types.Primitive? + local ne = buffer.len(edges) // 8 + if ne == 0 then + return nil + end + local out: { [number]: number } = {} + local vsrc: { number } = {} + local I = buffer.create(ne * 8) + for k = 0, ne * 2 - 1 do + local v = readu32(edges, k * 4) + local o = out[v] + if not o then + o = #vsrc + out[v] = o + table.insert(vsrc, v) + end + writeu32(I, k * 4, o) + end + local n = #vsrc + local P = buffer.create(n * 12) + for i = 1, n do + buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12) + end + local prim: Types.Primitive = { attributes = { POSITION = Scene.accessor(P, "f32", 3, n) }, indices = Scene.accessor(I, "u32", 1, ne * 2), mode = "lines" } + if shapes and ref and #shapes > 1 then + prim.targets = targetDeltas(poly, vsrc, shapes, ref, groups) + end + return prim +end + +-- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints; vgroups names the +-- vertex groups (def_nr + 1) for shape keys limited to one +function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: Skinning?, shapes: { MeshT.Shape }?, ref: number?, vgroups: { string }?): Built local triangulateOn = not (opts and opts.triangulate == false) local flipV = not (opts and opts.flipV == false) local withNormals = not (opts and opts.normals == false) @@ -409,21 +481,7 @@ function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: S prim.material = mat end if shapes and ref and #shapes > 1 then - local base = shapes[ref].data - local targets: { { [string]: Types.Accessor } } = {} - for k, s in shapes do - if k ~= ref then - local t = table.create(n * 3) :: { number } - for i = 1, n do - local v = vsrc[i] - for c = 0, 2 do - t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4) - end - end - table.insert(targets, { POSITION = accessor(t, 3) } :: { [string]: Types.Accessor }) - end - end - prim.targets = targets + prim.targets = targetDeltas(poly, vsrc, shapes, ref, vgroups) end table.insert(mesh.primitives, prim) table.insert(sources, vsrc) @@ -432,7 +490,7 @@ function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: S local w = {} for k, s in shapes do if k ~= ref then - table.insert(w, s.value) + table.insert(w, if s.mute then 0 else s.value) -- Blender skips muted keys end end mesh.weights = w diff --git a/src/Rosetta/model/blend/Read.luau b/src/Rosetta/model/blend/Read.luau index 494c5e0..73dc758 100644 --- a/src/Rosetta/model/blend/Read.luau +++ b/src/Rosetta/model/blend/Read.luau @@ -13,6 +13,7 @@ local Mesh = require("@rosetta/model/blend/Mesh") local Prim = require("@rosetta/model/blend/Prim") local Anim = require("@rosetta/model/blend/Anim") local Material = require("@rosetta/model/blend/Material") +local Armature = require("@rosetta/model/blend/Armature") local Read = {} @@ -22,6 +23,7 @@ type M4 = { number } export type Options = { triangulate: boolean?, flipV: boolean?, + looseEdges: boolean?, -- edges outside faces as "lines" primitives (default false; always for custom shape widgets) collections: boolean?, -- collections as nodes (default true) scene: string?, -- the scene to read (default: the file's current scene) sampleStep: number?, -- frames between animation samples (default 1) @@ -172,6 +174,18 @@ local function mat4(v: Blend.View?, ...: string): M4? end -- ------------------------------------------------------------------------------------------------ scene +type ArmInfo = { + joints: { number }, + names: { [string]: number }, + rest: { M4 }, + restLocal: { M4 }, + bones: { Blend.View }, + deform: { boolean }, + node: number, + poseNames: { [string]: Blend.View }, + arm: Blend.View, + pose: Blend.View?, +} type Ctx = { f: Blend.File, scene: Types.Scene, @@ -183,7 +197,9 @@ type Ctx = { meshes: { [string]: number }, materials: { [any]: number }, textures: { [any]: number }, - armatures: { [any]: { joints: { number }, names: { [string]: number }, rest: { M4 }, restLocal: { M4 }, bones: { Blend.View }, deform: { boolean }, node: number, poseNames: { [string]: Blend.View } } }, + armatures: { [any]: ArmInfo }, + widgets: { [any]: Blend.View }, -- custom shape objects by address + widgetOrder: { any }, prefix: { [number]: M4 }, -- node -> the matrix before its basis (parent inverse, bone tail offset) props: { [number]: Props }, meta: { [string]: any }, @@ -230,7 +246,7 @@ local function armature(ctx: Ctx, ob: Blend.View, node: number) end end end - local info = { joints = {}, names = {}, rest = {}, restLocal = {}, bones = {}, deform = {}, node = node, poseNames = poseNames } + local info: ArmInfo = { joints = {}, names = {}, rest = {}, restLocal = {}, bones = {}, deform = {}, node = node, poseNames = poseNames, arm = arm, pose = pose } local function walk(list: { Blend.View }, parentJoint: number?, parentRest: M4?, depth: number) if depth > 256 then return @@ -400,20 +416,37 @@ local function groupNames(ob: Blend.View, me: Blend.View): { string } return out end -local function mesh(ctx: Ctx, ob: Blend.View, node: number) +local function shapeExtras(shapes: { Mesh.Shape }, ref: number?): ({ string }, { { [string]: any } }) + local names, list = {}, {} + for k, sh in shapes do + if k ~= ref then + table.insert(names, sh.name) + end + local rel = shapes[sh.relative + 1] + table.insert(list, { + name = sh.name, value = sh.value, slider_min = sh.min, slider_max = sh.max, mute = sh.mute, + relative_key = if rel then rel.name else nil, vertex_group = sh.vgroup, + }) + end + return names, list +end + +-- the scene mesh of an object's mesh data (shared between objects with the same data, slots and armature) +local function meshOf(ctx: Ctx, ob: Blend.View, lines: boolean): (number?, ArmInfo?) local f = ctx.f local me = ob:deref("data", 0, "Mesh") if not me then - return + return nil, nil end local slots = slotMaterials(ctx, ob, me) local armOb = deformArmature(ctx, ob) local armInfo = armOb and armOb.block and ctx.armatures[armOb.block.addr] - local key = tostring(me.block and me.block.index) .. ":" .. table.concat(slots, ",") .. ":" .. tostring(armOb and armOb.block and armOb.block.index) + local key = tostring(me.block and me.block.index) .. ":" .. table.concat(slots, ",") .. ":" .. tostring(armOb and armOb.block and armOb.block.index) .. (if lines then ":lines" else "") local skin: Prim.Skinning? = nil + local groups = groupNames(ob, me) if armInfo then local joints = {} - for gi, name in groupNames(ob, me) do + for gi, name in groups do local j = armInfo.names[name] if j and armInfo.deform[j] then joints[gi - 1] = j - 1 @@ -428,9 +461,23 @@ local function mesh(ctx: Ctx, ob: Blend.View, node: number) error(err or "bad mesh", 0) end local shapes, ref = Mesh.shapes(f, me, poly.nv) - local built = Prim.build(poly, slots, { triangulate = ctx.opts.triangulate, flipV = ctx.opts.flipV }, skin, shapes, ref) + local built = Prim.build(poly, slots, { triangulate = ctx.opts.triangulate, flipV = ctx.opts.flipV }, skin, shapes, ref, groups) local m = built.mesh - m.extras = { blend = { vertices = poly.nv, faces = poly.nf, corners = poly.nc, generation = poly.generation, uvs = #poly.uvs, colors = #poly.colors, shapes = #shapes } } + local extras: { [string]: any } = { vertices = poly.nv, faces = poly.nf, corners = poly.nc, generation = poly.generation, uvs = #poly.uvs, colors = #poly.colors, shapes = #shapes } + m.extras = { blend = extras } + if lines then + local lp = Prim.lines(poly, Mesh.looseEdges(f, me, poly), shapes, ref, groups) + if lp then + table.insert(m.primitives, lp) + extras.looseEdges = (lp.indices :: Types.Accessor).count // 2 + end + end + if #shapes > 1 then + local names, list = shapeExtras(shapes, ref) + m.extras.targetNames = names + extras.shape_keys = list + extras.reference_key = if ref then shapes[ref].name else nil + end table.insert(ctx.scene.meshes, m) idx = #ctx.scene.meshes ctx.meshes[key] = idx @@ -440,6 +487,15 @@ local function mesh(ctx: Ctx, ob: Blend.View, node: number) ctx.meta.shapeKeys[idx] = { key = me:deref("key", 0, "Key"), mesh = me, shapes = shapes, ref = ref } end end + return idx, armInfo +end + +local function mesh(ctx: Ctx, ob: Blend.View, node: number) + local addr = ob.block and ob.block.addr + local idx, armInfo = meshOf(ctx, ob, ctx.opts.looseEdges == true or (addr ~= nil and ctx.widgets[addr] ~= nil)) + if not idx then + return + end local n = ctx.scene.nodes[node] n.mesh = idx if ctx.scene.meshes[idx].weights then @@ -523,6 +579,14 @@ local function object(ctx: Ctx, ob: Blend.View, under: number?, depth: number): if lay and ctx.f.version < 280 then extras.layers = lay end + -- Object.visibility_flag (2.8+): OB_HIDE_VIEWPORT 1, OB_HIDE_RENDER 4; restrictflag before: VIEW 1, RENDER 4 + local vis = ob:num("visibility_flag") or ob:num("restrictflag") or 0 + if bit32.band(vis, 1) ~= 0 then + extras.hide_viewport = true + end + if bit32.band(vis, 4) ~= 0 then + extras.hide_render = true + end local mods = {} for _, md in ob:list("modifiers") do table.insert(mods, { name = md:sub("modifier") and (md:sub("modifier") :: Blend.View):str("name") or md:str("name") or "", type = (string.gsub(md.struct.name, "ModifierData$", "")) }) @@ -543,6 +607,77 @@ local function object(ctx: Ctx, ob: Blend.View, under: number?, depth: number): return idx end +-- ------------------------------------------------------------------------------------------------ rigs +-- an object as a constraint target or custom shape: its node, else its name; widgets records custom shapes +local function resolver(ctx: Ctx, widgets: boolean): Armature.Resolve + return function(ob: Blend.View?): Armature.Target? + if not ob then + return nil + end + local addr = ob.block and ob.block.addr + if widgets and addr ~= nil and not ctx.widgets[addr] then + ctx.widgets[addr] = ob + table.insert(ctx.widgetOrder, addr) + end + local node = if addr ~= nil then ctx.objects[addr] else nil + if node then + return node + end + return ob:idName() + end +end + +local function rigs(ctx: Ctx) + local target, shape = resolver(ctx, false), resolver(ctx, true) + for node = 1, #ctx.scene.nodes do + local ob = ctx.objView[node] + local extras = ob and (ctx.scene.nodes[node].extras :: any).blend + if not ob or not extras then + continue + end + local list = Armature.constraints(ob, target) + if #list > 0 then + extras.constraints = list + end + local info = ob.block and ctx.armatures[ob.block.addr] + if info then + local cols = Armature.collections(info.arm, info.bones, info.pose) + extras.bone_collections = cols.list + for j, bone in info.bones do + local name = bone:str("name") or "" + local pc = info.poseNames[name] + local e = (ctx.scene.nodes[info.joints[j]].extras :: any).blend + for k, v in Armature.bone(bone, pc, info.pose) do + e[k] = v + end + e.collections = cols.byBone[name] or {} + if pc then + Armature.pose(e, pc, target, shape) + end + end + end + end +end + +-- every custom shape object: its node (and mesh) when it is in the scene, else its mesh only +local function widgetList(ctx: Ctx): { { [string]: any } } + local list = {} + for _, addr in ctx.widgetOrder do + local ob = ctx.widgets[addr] + local t = ob:num("type") or -1 + local w: { [string]: any } = { name = ob:idName() or "", type = TYPE_NAME[t] or tostring(t) } + local node = ctx.objects[addr] + if node then + w.node = node + w.mesh = ctx.scene.nodes[node].mesh + elseif t == OB_MESH then + w.mesh = (meshOf(ctx, ob, true)) + end + table.insert(list, w) + end + return list +end + -- ------------------------------------------------------------------------------------------------ animation local function apply(props: Props, curves: { Curve }, frame: number, prefix: string?, name: string?): Props local p: Props = {} @@ -734,7 +869,7 @@ local function animations(ctx: Ctx) v = math.clamp(Anim.evaluate(c, fr), math.min(s.min, s.max), math.max(s.min, s.max)) -- the slider range end end - buffer.writef32(out, ((i - 1) * count + k) * 4, v) + buffer.writef32(out, ((i - 1) * count + k) * 4, if s.mute then 0 else v) k += 1 end end @@ -791,7 +926,7 @@ function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) } local ctx: Ctx = { f = f, scene = scene, opts = o, objects = {}, objView = {}, parentOf = {}, world = {}, meshes = {}, materials = {}, - textures = {}, armatures = {}, prefix = {}, props = {}, meta = meta, pending = {}, + textures = {}, armatures = {}, prefix = {}, props = {}, meta = meta, pending = {}, widgets = {}, widgetOrder = {}, } local order: { { ob: Blend.View, under: number? } } = {} if sc then @@ -870,6 +1005,7 @@ function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) local u = a ~= nil and firstUnder[a] or nil object(ctx, e.ob, if u and u > 0 then u else nil, 0) end + rigs(ctx) for node = 1, #scene.nodes do local ob = ctx.objView[node] if ob and (ob:num("type") or -1) == OB_MESH then @@ -877,6 +1013,9 @@ function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) end end skins(ctx) + if next(ctx.armatures) ~= nil then + scene.meta.blend = { widgets = widgetList(ctx), bone_color_sets = Armature.colorSets() } + end if o.animations ~= false then animations(ctx) end diff --git a/tests/model/blend.luau b/tests/model/blend.luau index 31d4fd9..05b73d4 100644 --- a/tests/model/blend.luau +++ b/tests/model/blend.luau @@ -144,7 +144,50 @@ local function corners(mesh: any, facemats: { number }, faceSizes: { number }?): return out end -local checked = { worlds = 0, meshes = 0, normals = 0, weights = 0, shapes = 0, frames = 0, skinned = 0, curves = 0, materials = 0, cameras = 0, lights = 0 } +-- rig values against bpy: numbers within eps, lists element by element, "" in the reference for nil +local function same(got: any, want: any, eps: number): boolean + if want == "" and got == nil then + return true + end + if type(want) == "number" then + return type(got) == "number" and near(got, want, eps) + end + if type(want) == "table" then + if type(got) ~= "table" or #got ~= #want then + return false + end + for i = 1, #want do + if not same(got[i], want[i], eps) then + return false + end + end + return true + end + return got == want +end + +local function angleNear(a: number?, b: number, eps: number): boolean + if not a then + return false + end + local d = (a - b) % (2 * math.pi) + return d < eps or 2 * math.pi - d < eps +end + +local REQUIRED: { [string]: { string } } = { + IK = { "chain_count", "pole_target", "pole_subtarget", "pole_angle", "use_tail", "use_stretch", "iterations", "weight" }, + COPY_ROTATION = { "use_x", "use_y", "use_z", "invert_x", "invert_y", "invert_z", "mix_mode", "euler_order" }, + COPY_LOCATION = { "use_x", "use_y", "use_z", "invert_x", "invert_y", "invert_z", "use_offset", "head_tail" }, + COPY_SCALE = { "use_x", "use_y", "use_z", "use_offset", "power" }, + COPY_TRANSFORMS = { "mix_mode", "head_tail" }, + DAMPED_TRACK = { "track_axis", "head_tail" }, + LIMIT_ROTATION = { "use_limit_x", "use_limit_y", "use_limit_z", "min_x", "max_x", "min_z", "max_z", "use_transform_limit" }, + LIMIT_LOCATION = { "use_min_x", "use_max_x", "use_min_z", "use_max_z", "min_x", "max_x", "min_z", "max_z", "use_transform_limit" }, + CHILD_OF = { "inverse_matrix", "use_location_x", "use_rotation_y", "use_scale_x", "use_scale_z", "set_inverse_pending" }, +} +local COMMON = { "type", "name", "influence", "mute", "target", "subtarget", "owner_space", "target_space" } + +local checked = { rigs = 0, constraints = 0, worlds = 0, meshes = 0, normals = 0, weights = 0, shapes = 0, frames = 0, skinned = 0, curves = 0, materials = 0, cameras = 0, lights = 0 } local samples = {} t:check(#Sets.old >= 4, "the old demo files were fetched (" .. #Sets.old .. ")") @@ -174,6 +217,8 @@ for _, tag in { "old", "279", "293", "35", "41", "cur" } do t:check(i, label .. ": object " .. o.name) if i then t:check(nearList(W[i], o.world, 1e-4), label .. ": " .. o.name .. " world\n got " .. fmt(W[i]) .. "\n want " .. fmt(o.world)) + local e = scene.nodes[i].extras.blend + t:check((e.hide_viewport == true) == o.hide_viewport and (e.hide_render == true) == o.hide_render, label .. ": " .. o.name .. " hide flags") checked.worlds += 1 end end @@ -196,8 +241,12 @@ for _, tag in { "old", "279", "293", "35", "41", "cur" } do t:eq(e.vertices, mi.vertices, label .. ": " .. o.name .. " vertices") local tris = 0 local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local facePrims = 0 for _, p in mesh.primitives do - tris += p.indices.count // 3 + if p.mode ~= "lines" then + tris += p.indices.count // 3 + facePrims += 1 + end local P = read(p.attributes.POSITION) for v = 0, p.attributes.POSITION.count - 1 do for k = 1, 3 do @@ -219,7 +268,7 @@ for _, tag in { "old", "279", "293", "35", "41", "cur" } do end t:eq(e.faces, mi.faces, label .. ": " .. o.name .. " faces") t:eq(e.corners, mi.corners, label .. ": " .. o.name .. " corners") - t:eq(#mesh.primitives, (function() + t:eq(facePrims, (function() local u, n = {}, 0 for _, m in mi.facemats do if not u[m] then @@ -331,20 +380,47 @@ for _, tag in { "old", "279", "293", "35", "41", "cur" } do end end t:eq(#(mesh.weights or {}), #mi.shapes - 1, label .. ": " .. o.name .. " morph weights") + local names = mesh.extras.targetNames or {} + local keys = mesh.extras.blend.shape_keys or {} + t:eq(#keys, #mi.shapes, label .. ": " .. o.name .. " extras.blend.shape_keys") + t:eq(mesh.extras.blend.reference_key, mi.reference, label .. ": " .. o.name .. " reference key") + local groupWeight = {} + for v, list in mi.weights or {} do + for _, g in list do + groupWeight[g[1] .. "/" .. (v - 1)] = g[2] + end + end + for k, s in mi.shapes do + local e = keys[k] or {} + t:check(e.name == s.name and e.relative_key == s.relative and e.mute == s.mute and (e.vertex_group or "") == s.vertex_group + and near(e.slider_min, s.slider_min, 1e-6) and near(e.slider_max, s.slider_max, 1e-6) + and (o.shapeAction or near(e.value, s.value, 1e-6)), label .. ": " .. o.name .. " shape key " .. s.name .. " fields") + end local ti = 0 local worst = 0 for k, s in mi.shapes do if k ~= refIndex then ti += 1 + t:eq(names[ti], s.name, label .. ": " .. o.name .. " targetNames[" .. ti .. "]") if not o.shapeAction then -- animated values are checked per frame below - t:check(near(mesh.weights[ti], s.value, 1e-6), label .. ": " .. o.name .. " " .. s.name .. " weight") + t:check(near(mesh.weights[ti], if s.mute then 0 else s.value, 1e-6), label .. ": " .. o.name .. " " .. s.name .. " weight") + end + -- the delta from the relative key, times the key's vertex group weight + local rel = refIndex + for q, r in mi.shapes do + if r.name == s.relative then + rel = q + end end for ci, cv in if mi.cornerVerts then cs else {} do local tgt = cv[1].targets and cv[1].targets[ti] local get = tgt and read(tgt.POSITION) local v = mi.cornerVerts[ci] for q = 1, 3 do - local want = s.co[v * 3 + q] - mi.shapes[refIndex].co[v * 3 + q] + local want = s.co[v * 3 + q] - mi.shapes[rel].co[v * 3 + q] + if s.vertex_group ~= "" then + want *= groupWeight[s.vertex_group .. "/" .. v] or 0 + end worst = math.max(worst, if get then math.abs(get(cv[2], q - 1) - want) else math.huge) end end @@ -456,7 +532,9 @@ for _, tag in { "old", "279", "293", "35", "41", "cur" } do for _, n in scene.nodes do if n.mesh then for _, p in scene.meshes[n.mesh].primitives do - got += p.indices.count // 3 + if p.mode ~= "lines" then + got += p.indices.count // 3 + end end end end @@ -474,6 +552,107 @@ for _, tag in { "old", "279", "293", "35", "41", "cur" } do t:check(j and nearList(W[j], Scene.mul(aw, b["local"]), 1e-4), label .. ": bone " .. b.name) end end + -- rig data against bpy (Blender 5.x reads the old files through its versioning: layers and bone groups as + -- collections, bone group colours as bone colours) + local function nameOf(v: any): any + return if type(v) == "number" then scene.nodes[v].name else v + end + local function compareTable(got: { [string]: any }, want: { [string]: any }, keys: { string }, what: string) + for _, k in keys do + if want[k] == nil and (k == "target" or k == "subtarget") then + t:check(got[k] == nil, what .. ": no " .. k) + continue + end + t:check(want[k] ~= nil, what .. ": the reference has " .. k) + local g = got[k] + if k == "target" or k == "pole_target" or k == "custom_shape" then + g = nameOf(g) + end + t:check(same(g, want[k], 1e-5), what .. " " .. k .. ": got " .. tostring(g) .. ", want " .. tostring(want[k])) + end + end + local function compareColor(got: any, want: any, what: string) + if want.palette == "DEFAULT" then + t:check(got == nil, what .. ": default colour") + else + -- bpy's custom colours are the stored ones (zero for a theme set in 4.x); the reader gives the theme's + local custom = want.palette == "CUSTOM" + t:check(got and got.palette == want.palette and got.normal and (not custom or nearList(got.normal, want.normal, 1e-5) and nearList(got.select, want.select, 1e-5) and nearList(got.active, want.active, 1e-5)), what .. ": colour " .. want.palette) + end + end + local POSE_KEYS = { "custom_shape", "custom_shape_transform", "custom_shape_translation", "custom_shape_rotation_euler", + "custom_shape_scale_xyz", "use_custom_shape_bone_size", "lock_location", "lock_rotation", "lock_rotation_w", + "lock_rotations_4d", "lock_scale", "rotation_mode", "ik_stretch" } + for _, a in { "x", "y", "z" } do + for _, k in { "lock_ik_", "use_ik_limit_", "ik_min_", "ik_max_", "ik_stiffness_" } do + table.insert(POSE_KEYS, k .. a) + end + end + for armName, rig in ref.rigs or {} do + local ae = scene.nodes[objects[armName]].extras.blend + t:eq(#ae.bone_collections, #rig.collections, label .. ": " .. armName .. " bone collections") + for k, c in rig.collections do + local g = ae.bone_collections[k] or {} + t:check(g.name == c.name and g.visible == c.visible and (g.parent or "") == c.parent, label .. ": collection " .. c.name) + end + for _, b in rig.bones do + local e = scene.nodes[bones[b.name]].extras.blend + local what = label .. ": bone " .. b.name + t:check(e.deform == b.deform and e.use_connect == b.use_connect and e.show_wire == b.show_wire, what .. " flags") + t:check(nearList(e.head_local, b.head_local, 1e-5) and nearList(e.tail_local, b.tail_local, 1e-5), what .. " head / tail") + t:check(angleNear(e.roll, b.roll, 1e-4), what .. " roll " .. tostring(e.roll) .. " / " .. b.roll) + t:check(same(e.collections, b.collections, 0), what .. " collections " .. table.concat(e.collections, ",") .. " / " .. table.concat(b.collections, ",")) + compareColor(e.color, b.color, what) + compareColor(e.pose_color, b.pose.color, what .. " pose") + compareTable(e, b.pose, POSE_KEYS, what) + t:eq(#e.constraints, #b.pose.constraints, what .. " constraints") + for k, rc in b.pose.constraints do + local c = e.constraints[k] or {} + local keys = table.clone(COMMON) + for _, x in REQUIRED[rc.type] or {} do + table.insert(keys, x) + end + compareTable(c, rc, keys, what .. " constraint " .. rc.name) + for key, v in c do -- everything else the reader gives, where bpy has it + if rc[key] ~= nil and type(v) ~= "table" and key ~= "target" and key ~= "pole_target" then + t:check(same(v, rc[key], 1e-5), what .. " constraint " .. rc.name .. " " .. key .. ": got " .. tostring(v) .. ", want " .. tostring(rc[key])) + end + end + checked.constraints += 1 + end + end + checked.rigs += 1 + end + if next(ref.rigs or {}) then + local mb = scene.meta.blend + for k, cs in ref.themeBoneColors do + local g = mb.bone_color_sets[k] + t:check(g and nearList(g.normal, cs.normal, 1e-5) and nearList(g.select, cs.select, 1e-5) and nearList(g.active, cs.active, 1e-5), label .. ": theme bone colours " .. k) + end + -- every custom shape is a widget: a scene node, or a mesh outside the scene; edge-only widgets as lines + local shapes = {} + for _, rig in ref.rigs do + for _, b in rig.bones do + if b.pose.custom_shape ~= "" then + shapes[b.pose.custom_shape] = true + end + end + end + for _, w in mb.widgets do + t:check(shapes[w.name], label .. ": widget " .. w.name .. " is a custom shape") + shapes[w.name] = nil + t:check(w.node == nil or scene.nodes[w.node].name == w.name, label .. ": widget node") + local m = w.mesh and scene.meshes[w.mesh] + local lines = 0 + for _, p in m and m.primitives or {} do + if p.mode == "lines" then + lines += p.indices.count // 2 + end + end + t:check(lines > 0, label .. ": widget " .. w.name .. " edges (" .. lines .. ")") + end + t:check(next(shapes) == nil, label .. ": every custom shape is listed") + end -- f-curves through the evaluator, at every half frame (bezier, linear, constant, extrapolation) local file = assert(Blend.open(buffer.fromstring(c.data))) for _, o in ref.objects do @@ -551,7 +730,16 @@ for _, tag in { "old", "279", "293", "35", "41", "cur" } do for name, values in p.shapes do local i = objects[name] local w = pose[i] and pose[i].weights or scene.nodes[i].weights - local want = table.move(values, 2, #values, 1, {}) + local want = {} + for _, o in ref.objects do + if o.name == name then + for k, s in o.mesh.shapes do + if s.name ~= o.mesh.reference then + table.insert(want, if s.mute then 0 else values[k]) + end + end + end + end -- pre-2.5 IPO bezier keys: Blender recomputes auto handles when converting them; we keep the stored ones local eps = if tag == "old" then 1e-2 else 1e-3 t:check(nearList(w, want, eps), label .. ": frame " .. frame .. " " .. name .. " shape values " .. fmt(w) .. " / " .. fmt(want)) @@ -609,6 +797,7 @@ for _, tag in { "old", "279", "293", "35", "41", "cur" } do end end end +t:note("checked: %d rigs, %d constraints", checked.rigs, checked.constraints) t:note("checked: %d world matrices, %d meshes, %d corner normal sets, %d weight sets, %d shape key sets, %d f-curves, %d posed frames, %d skinned frames, %d materials, %d cameras, %d lights", checked.worlds, checked.meshes, checked.normals, checked.weights, checked.shapes, checked.curves, checked.frames, checked.skinned, checked.materials, checked.cameras, checked.lights) diff --git a/tools/fixtures/_blend_make.py b/tools/fixtures/_blend_make.py index 0d91b24..0de943d 100644 --- a/tools/fixtures/_blend_make.py +++ b/tools/fixtures/_blend_make.py @@ -7,6 +7,11 @@ # keys, actions on bones / objects / shape keys (bezier, linear, constant), a bone parent # scene__z.blend scene_ saved compressed (gzip before 3.0, zstd after) # compat_.blend 2.7x only: the "legacy mesh format" save (MFace tessellated faces) +# ctl_.blend a control rig: deform / control bones, layers + bone groups (before 4.0) or bone +# collections and colours (4.x), custom shapes (a hidden widget in the scene, one outside it), +# pose-bone constraints (IK, copy rotation / location / transforms, damped track, limit +# rotation, child of, stretch to), lock and IK flags; shape keys with slider ranges, mute, +# relative keys, a vertex group, and a shape-key action import bpy, sys, os, math out = sys.argv[sys.argv.index("--") + 1] @@ -394,8 +399,234 @@ def rig_file(): save(os.path.join(out, "rig_%s.blend" % TAG)) +def setp(obj, attr, value): + if hasattr(obj, attr): + try: + setattr(obj, attr, value) + except (TypeError, ValueError, AttributeError): + pass + + +def ctl_file(): + reset() + sc = bpy.context.scene + tgt = link(bpy.data.objects.new("Tgt", None)) + tgt.location = (1, 2, 3) + tgt.rotation_euler = (0.2, 0.4, 0.1) + cv = [(math.cos(a * math.pi / 4), math.sin(a * math.pi / 4), 0) for a in range(8)] + circle = bpy.data.meshes.new("WGT_circle") + circle.from_pydata(cv, [(a, (a + 1) % 8) for a in range(8)], []) + circle.update() + wcircle = bpy.data.objects.new("WGT_circle", circle) + if OLD: + wcircle.use_fake_user = True + else: + wgts = bpy.data.collections.new("Widgets") # not linked to the scene + wgts.objects.link(wcircle) + box = bpy.data.meshes.new("WGT_box") + box.from_pydata([(x, y, z) for z in (0, 1) for y in (-0.5, 0.5) for x in (-0.5, 0.5)], + [(0, 1), (1, 3), (3, 2), (2, 0), (4, 5), (5, 7), (7, 6), (6, 4), (0, 4), (1, 5), (2, 6), (3, 7)], []) + box.update() + wbox = link(bpy.data.objects.new("WGT_box", box)) + wbox.location = (0, 0, -3) + if OLD: + wbox.hide = True + else: + wbox.hide_viewport = True + wbox.hide_render = True + arm_data = bpy.data.armatures.new("CtlData") + rig = link(bpy.data.objects.new("Ctl", arm_data)) + rig.location = (0.5, -1, 0.25) + rig.rotation_euler = (0.1, 0, 0.3) + rig.scale = (1, 1, 1.5) + 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 + spec = ( # name, head, tail, roll, parent, connect, deform + ("root", (0, 0, 0), (0, 1, 0), 0.0, None, False, False), + ("spine", (0, 0, 0.2), (0, 0.1, 1.2), 0.4, "root", False, True), + ("upper", (0, 0.1, 1.2), (0.8, 0.1, 1.3), -0.7, "spine", True, True), + ("lower", (0.8, 0.1, 1.3), (1.6, 0.3, 1.1), 1.1, "upper", True, True), + ("hand_ik", (1.6, 0.3, 1.1), (1.6, 0.8, 1.1), 0.0, "root", False, False), + ("pole", (0.8, -1, 1.3), (0.8, -1.3, 1.3), 0.2, "root", False, False), + ("limit", (-0.5, 0, 0.5), (-0.5, 0, 1.1), 2.5, "root", False, True), + ) + for name, head, tail, roll, parent, connect, deform in spec: + b = eb.new(name) + b.head, b.tail, b.roll = head, tail, roll + if parent: + b.parent = eb[parent] + b.use_connect = connect + b.use_deform = deform + bpy.ops.object.mode_set(mode="OBJECT") + bones = arm_data.bones + bones["root"].show_wire = True + pose = rig.pose.bones + if V >= (4, 0): + ctrl = arm_data.collections.new("Ctrl") + try: + ik = arm_data.collections.new("IK", parent=ctrl) + except TypeError: + ik = arm_data.collections.new("IK") + deform = arm_data.collections.new("Deform") + mch = arm_data.collections.new("MCH") + for c in list(arm_data.collections): + for b in list(c.bones): + c.unassign(b) + for n in ("root", "hand_ik", "pole"): + ctrl.assign(bones[n]) + for n in ("hand_ik", "pole"): + ik.assign(bones[n]) + for n in ("spine", "upper", "lower", "limit"): + deform.assign(bones[n]) + mch.assign(bones["limit"]) + ik.is_visible = False + mch.is_visible = False + bones["root"].color.palette = "THEME04" + bones["pole"].color.palette = "CUSTOM" + bones["pole"].color.custom.normal = (1.0, 0.0, 0.0) + bones["pole"].color.custom.select = (0.0, 1.0, 0.0) + bones["pole"].color.custom.active = (0.0, 0.0, 1.0) + pose["spine"].color.palette = "THEME09" + else: + layers = {"root": (0,), "hand_ik": (0, 1), "pole": (0, 1), "spine": (16,), "upper": (16,), "lower": (16,), "limit": (16, 31)} + for n, ls in layers.items(): + bones[n].layers = [i in ls for i in range(32)] + arm_data.layers = [i in (0, 16) for i in range(32)] + g1 = rig.pose.bone_groups.new(name="Ctrls") + g1.color_set = "THEME04" + g2 = rig.pose.bone_groups.new(name="Custom") + g2.color_set = "CUSTOM" + g2.colors.normal = (1.0, 0.0, 0.0) + g2.colors.select = (0.0, 1.0, 0.0) + g2.colors.active = (0.0, 0.0, 1.0) + pose["root"].bone_group = g1 + pose["hand_ik"].bone_group = g1 + pose["pole"].bone_group = g2 + # custom shapes + pose["root"].custom_shape = wcircle + setp(pose["root"], "custom_shape_scale", 1.5) + setp(pose["root"], "custom_shape_scale_xyz", (1.5, 0.5, 2.0)) + pose["spine"].custom_shape = wbox + pose["spine"].custom_shape_transform = pose["root"] + setp(pose["spine"], "custom_shape_translation", (0, 0.1, 0)) + setp(pose["spine"], "custom_shape_rotation_euler", (0.1, 0.2, 0.3)) + setp(pose["spine"], "use_custom_shape_bone_size", False) + pose["pole"].custom_shape = wcircle + # locks, rotation modes, IK settings + pose["root"].lock_location = (True, True, True) + pose["spine"].rotation_mode = "QUATERNION" + pose["spine"].lock_rotation = (True, False, True) + pose["spine"].lock_rotation_w = True + pose["spine"].lock_rotations_4d = True + pose["limit"].lock_scale = (False, True, False) + pose["upper"].ik_stretch = 0.1 + pose["upper"].lock_ik_y = True + pose["upper"].use_ik_limit_x = True + pose["upper"].ik_min_x = -0.5 + pose["upper"].ik_max_x = 0.7 + pose["upper"].ik_stiffness_z = 0.25 + pose["lower"].rotation_mode = "YZX" + pose["hand_ik"].rotation_mode = "AXIS_ANGLE" + # constraints + c = pose["spine"].constraints.new("COPY_ROTATION") + c.name = "CopyRot" + c.target = tgt + c.use_y = False + c.invert_x = True + setp(c, "mix_mode", "ADD") + c.owner_space, c.target_space = "LOCAL_WITH_PARENT", "LOCAL" + c.influence = 0.75 + c = pose["upper"].constraints.new("COPY_LOCATION") + c.target, c.subtarget = rig, "root" + c.use_offset = True + c.use_z = False + c.invert_z = True + c.head_tail = 0.5 + c.target_space = "POSE" + c = pose["upper"].constraints.new("LIMIT_LOCATION") + c.use_min_x, c.min_x = True, -0.25 + c.use_max_z, c.max_z = True, 0.75 + c.use_transform_limit = True + c = pose["upper"].constraints.new("COPY_SCALE") + c.target = tgt + c.use_y = False + c.use_offset = True + c = pose["lower"].constraints.new("IK") + c.target, c.subtarget = rig, "hand_ik" + c.pole_target, c.pole_subtarget = rig, "pole" + c.pole_angle = -1.2 + c.chain_count = 2 + c.use_tail = True + c.use_stretch = False + c.iterations = 300 + c.weight = 0.6 + c = pose["hand_ik"].constraints.new("COPY_TRANSFORMS") + c.target = tgt + setp(c, "mix_mode", "BEFORE") + c.influence = 0.3 + c.mute = True + c = pose["pole"].constraints.new("DAMPED_TRACK") + c.target, c.subtarget = rig, "lower" + c.track_axis = "TRACK_NEGATIVE_Z" + c.head_tail = 0.25 + c = pose["limit"].constraints.new("LIMIT_ROTATION") + c.use_limit_x, c.min_x, c.max_x = True, -0.3, 0.4 + c.use_limit_z, c.min_z, c.max_z = True, -1.0, 1.0 + c.owner_space = "LOCAL" + c = pose["limit"].constraints.new("CHILD_OF") + c.name = "Parent" + c.target = tgt + c.use_rotation_y = False + c.use_scale_x = False + from mathutils import Matrix + c.inverse_matrix = Matrix(((1, 0, 0, 0.5), (0, 0, -1, 0.25), (0, 1, 0, -1), (0, 0, 0, 1))) + c = pose["limit"].constraints.new("STRETCH_TO") + c.target = tgt + c.influence = 0.5 + # shape keys on a mesh parented to the rig + fv = [(x * 0.5, 0, z * 0.5) for z in range(3) for x in range(3)] + ff = [(0, 1, 4, 3), (1, 2, 5, 4), (3, 4, 7, 6), (4, 5, 8, 7)] + face = link(bpy.data.objects.new("Face", mesh("FaceMesh", fv, ff))) + face.parent = rig + face.location = (0, -0.5, 0) + face.modifiers.new("Armature", "ARMATURE").object = rig + vg = face.vertex_groups.new(name="upper") + vg.add([6, 7, 8], 1.0, "REPLACE") + vg.add([3, 4, 5], 0.4, "REPLACE") + face.vertex_groups.new(name="spine").add(list(range(6)), 1.0, "REPLACE") + face.shape_key_add(name="Basis") + smile = face.shape_key_add(name="Smile") + for i, p in enumerate(smile.data): + p.co = (p.co[0], p.co[1] + 0.1 * i, p.co[2]) + smile.slider_min, smile.slider_max = -0.5, 2.0 + smile.value = 1.5 + blink = face.shape_key_add(name="Blink") + for i, p in enumerate(blink.data): + p.co = (p.co[0] + 0.05 * i, p.co[1] + 0.1 * i, p.co[2] - 0.02 * i) + blink.relative_key = smile + blink.mute = True + blink.vertex_group = "upper" + blink.value = 0.5 + puff = face.shape_key_add(name="Puff") + for i, p in enumerate(puff.data): + p.co = (p.co[0] * 1.2, p.co[1] - 0.05, p.co[2]) + puff.value = 0.3 + for f, v in ((1, 0.0), (10, 2.0), (20, -0.5)): + smile.value = v + smile.keyframe_insert("value", frame=f) + smile.value = 1.5 + sc.frame_set(1) + update() + save(os.path.join(out, "ctl_%s.blend" % TAG)) + + scene_file() rig_file() +ctl_file() if OLD: scene_file() save(os.path.join(out, "compat_%s.blend" % TAG), compat=True) diff --git a/tools/fixtures/_blend_ref.py b/tools/fixtures/_blend_ref.py index fb37763..f8b50be 100644 --- a/tools/fixtures/_blend_ref.py +++ b/tools/fixtures/_blend_ref.py @@ -2,7 +2,9 @@ # -- ): 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), -# and exports a .glb of each file (Z up, no modifiers) whose JSON part is returned as "gltf". +# 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:] @@ -62,6 +64,8 @@ def mesh_info(ob): 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] @@ -122,6 +126,87 @@ def fcurves(act): 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) @@ -140,11 +225,13 @@ def dump(path): 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": {}} + "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]} + "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: @@ -168,6 +255,9 @@ def dump(path): 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: @@ -175,6 +265,13 @@ def dump(path): 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: