model/blend: Blender 1.6x-2.0x files (big-endian, 32-bit, TFace / MCol, IPO curves, additive dsize), easing curves, owner-scoped address lookup; containers/Blend tests; docs section; bench line

This commit is contained in:
4DBug committed 2026-11-01 19:23:28 -06:00
1 parent 2e82b7d0af
commit 3c8d5e99d7
14 files changed
+766 -110

No files matched your search

+50 -1
View File
@@ -2,7 +2,7 @@
Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D, B3D, LDraw, LightWave Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D, B3D, LDraw, LightWave
LWO, DirectX .x, IQM, PMX / PMD, VRML, X3D, the [game models](#game-models) MD2 / MD3 / MDL / MD5 / BSP / SMD, LWO, DirectX .x, IQM, PMX / PMD, VRML, X3D, the [game models](#game-models) MD2 / MD3 / MDL / MD5 / BSP / SMD,
[Roblox meshes](roblox.md) and the [Minecraft and Qubicle voxel files](voxel.md)) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes [Blender .blend](#blender-blend), [Roblox meshes](roblox.md) and the [Minecraft and Qubicle voxel files](voxel.md)) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes
made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations.
Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`).
Editing goes through `F.ops.mesh`. Editing goes through `F.ops.mesh`.
@@ -716,6 +716,54 @@ assert(back.meta.source.format == "iqm" and back.meshes[1].name == "tri")
assert(back.meshes[1].primitives[1].indices.count == 3) assert(back.meshes[1].primitives[1].indices.count == 3)
``` ```
## Blender (.blend)
`.blend` files load read only, from every Blender version since 2.4x: plain, gzip (before 3.0) or zstd (3.0+)
compressed, 32 or 64-bit pointers, either byte order, and the 5.0+ header. Each file is read through its own SDNA (the
struct catalogue Blender writes into every file), so fields are found by name whatever version wrote them. The
current scene loads: objects (transforms with euler orders, quaternions, axis angles, delta transforms, the parent
inverse, bone parents), collections as nodes (`collections = false` flattens them), meshes, materials, images,
cameras, lights, armatures, skins, shape keys and actions. Blender is z-up (`meta.up = "z"`).
| Part | What loads |
|---|---|
| Meshes | every storage generation: MFace (before 2.63 and the 2.7x "legacy mesh format"), MPoly / MLoop (2.63 - 3.x), attribute layers (`position`, `.corner_vert`, ... 3.x - 4.x), AttributeStorage (5.x); a primitive per used material slot, `triangulate = false` keeps the faces (`"polygons"`) |
| Mesh data | UV maps (`TEXCOORD_n`, v flipped to glTF's origin), colour attributes (byte and float, point and corner) as linear `COLOR_n`, corner normals from Blender's smooth fans (sharp edges / faces, auto smooth before 4.1) or the stored custom normals, weights (`JOINTS_0` / `WEIGHTS_0`: the 4 largest deform-bone groups, normalized) |
| Materials | the Principled BSDF (base colour, metallic, roughness, alpha, emission and its strength, image textures on Base Color / Emission, Normal through a Normal Map node, Roughness / Metallic through Separate RGB), else the legacy `r, g, b` colour |
| Images | packed images as encoded bytes (`texture.data`), external ones as `uri` (relative to the `.blend`, bytes through `files` / `resolve`) |
| Cameras, lights | perspective (`yfov` from the lens, sensor fit and render aspect) / orthographic; point, sun, spot (watts to candela / lux as Blender's glTF exporter does); area lights are skipped (`meta.source.skippedLights`) |
| Armatures | a joint node per bone (rest pose times the saved pose), one skin per deformed mesh |
| Animation | the active action of each object, armature (pose bones) and shape key set, f-curves evaluated (constant, linear, bezier, easing; extrapolation) and sampled once per frame (`sampleStep`) into channels; time 0 is `meta.source.frameZero` at `meta.source.fps` |
| Not loaded | modifiers (listed per object in `meta.source.modifiers`, never applied), curves, text, metaballs, grease pencil, volumes, NLA strips, drivers, constraints, linked libraries |
```luau
local scene = assert(F.model.load(riggedBlendBytes))
local src = scene.meta.source
assert(src.format == "blend" and src.version >= 500 and src.compression == "zstd")
assert(scene.meta.up == "z" and #scene.skins == 1 and #scene.animations == 1)
local tube = scene.meshes[1].primitives[1]
assert(tube.attributes.JOINTS_0 and tube.attributes.WEIGHTS_0 and #tube.targets == 1)
assert(scene.materials[1].name == "Skin" and scene.materials[1].roughness > 0.69)
print(src.modifiers.Tube[1].type) -- Armature (not applied)
```
Anything else in the file is reachable through the container: `F.format("blend").open` parses the blocks and the
SDNA, and every struct reads by field name (`get`, `num`, `str`, `vec`, `sub`, `deref`, `list` for ListBase, `array`
and `pointers` behind pointers).
```luau
local blend = F.format("blend")
local file = assert(blend.open(F.Bytes.reader(riggedBlendBytes)))
local Blend = blend.container
for _, block in Blend.blocks(file, "OB") do
local ob = assert(Blend.struct(file, block))
print(ob:idName(), ob:num("type"), ob:vec("loc")[3]) -- Rig 25 0 / Tube 1 0
end
local arm = assert(Blend.struct(file, Blend.blocks(file, "AR")[1]))
local bones = arm:list("bonebase")
assert(bones[1]:str("name") == "lower" and bones[1]:list("childbase")[1]:str("name") == "upper")
```
## Formats ## Formats
| Format | Read | Write | Notes | | Format | Read | Write | Notes |
@@ -746,6 +794,7 @@ assert(back.meshes[1].primitives[1].indices.count == 3)
| STEP | via the CAD plug-in | | see [cad.md](cad.md) | | STEP | via the CAD plug-in | | see [cad.md](cad.md) |
| MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | | MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above |
| SMD | yes | yes | Valve studiomdl data | | SMD | yes | yes | Valve studiomdl data |
| Blender `.blend` | yes | | 2.4x - 5.x, compressed; meshes of every generation, materials, skins, shape keys, actions; see "Blender" above |
| Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) | | Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) |
| Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) | | Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) |
+31 -24
View File
@@ -184,7 +184,7 @@ local function parseDna(f: File, at: number, size: number): string?
if n < 0 or n > e - p then if n < 0 or n > e - p then
return nil, p return nil, p
end end
local out = table.create(n) local out = table.create(n) :: { string }
for k = 1, n do for k = 1, n do
local q = p local q = p
while q < e and readu8(b, q) ~= 0 do while q < e and readu8(b, q) ~= 0 do
@@ -215,7 +215,7 @@ local function parseDna(f: File, at: number, size: number): string?
if p + 4 + nt * 2 > e or readstring(b, p, 4) ~= "TLEN" then if p + 4 + nt * 2 > e or readstring(b, p, 4) ~= "TLEN" then
return "bad SDNA TLEN" return "bad SDNA TLEN"
end end
local lengths = table.create(nt) local lengths = table.create(nt) :: { number }
for k = 1, nt do for k = 1, nt do
lengths[k] = f.u16(b, p + 4 + (k - 1) * 2) lengths[k] = f.u16(b, p + 4 + (k - 1) * 2)
end end
@@ -230,7 +230,7 @@ local function parseDna(f: File, at: number, size: number): string?
end end
local i16 = f.i16 local i16 = f.i16
local ps = f.pointerSize local ps = f.pointerSize
local structs, byName = table.create(ns), {} local structs, byName = table.create(ns) :: { Struct }, {} :: { [string]: Struct }
for k = 1, ns do for k = 1, ns do
if p + 4 > e then if p + 4 > e then
return "truncated SDNA structs" return "truncated SDNA structs"
@@ -240,7 +240,8 @@ local function parseDna(f: File, at: number, size: number): string?
if t < 0 or t >= nt or nf < 0 or p + nf * 4 > e then if t < 0 or t >= nt or nf < 0 or p + nf * 4 > e then
return "bad SDNA struct " .. k return "bad SDNA struct " .. k
end end
local s: Struct = { name = types[t + 1], index = k - 1, size = lengths[t + 1], fields = table.create(nf), byName = {} } local tnames = types :: { string }
local s: Struct = { name = tnames[t + 1], index = k - 1, size = lengths[t + 1], fields = table.create(nf) :: { Field }, byName = {} }
local off = 0 local off = 0
for j = 1, nf do for j = 1, nf do
local ft, fn = i16(b, p), i16(b, p + 2) local ft, fn = i16(b, p), i16(b, p + 2)
@@ -248,9 +249,9 @@ local function parseDna(f: File, at: number, size: number): string?
if ft < 0 or ft >= nt or fn < 0 or fn >= #names then if ft < 0 or ft >= nt or fn < 0 or fn >= #names then
return "bad SDNA field in " .. s.name return "bad SDNA field in " .. s.name
end end
local decl = names[fn + 1] local decl: string = (names :: { string })[fn + 1]
local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*" local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*"
local dims, count = {}, 1 local dims: { number }, count = {}, 1
for d in string.gmatch(decl, "%[(%d+)%]") do for d in string.gmatch(decl, "%[(%d+)%]") do
local v = tonumber(d) or 1 local v = tonumber(d) or 1
table.insert(dims, v) table.insert(dims, v)
@@ -258,9 +259,9 @@ local function parseDna(f: File, at: number, size: number): string?
end end
local base = string.gsub(decl, "%[.*$", "") local base = string.gsub(decl, "%[.*$", "")
base = string.gsub(base, "[%*%(%)]", "") base = string.gsub(base, "[%*%(%)]", "")
local elem = if pointer then ps else lengths[ft + 1] local elem: number = if pointer then ps else lengths[ft + 1]
local fld: Field = { local fld: Field = {
name = base, decl = decl, type = types[ft + 1], offset = off, size = elem * count, name = base, decl = decl, type = tnames[ft + 1], offset = off, size = elem * count,
pointer = pointer, dims = dims, count = count, elem = elem, pointer = pointer, dims = dims, count = count, elem = elem,
} }
s.fields[j] = fld s.fields[j] = fld
@@ -272,7 +273,7 @@ local function parseDna(f: File, at: number, size: number): string?
structs[k] = s structs[k] = s
byName[s.name] = s byName[s.name] = s
end end
f.dna = { names = names, types = types, lengths = lengths, structs = structs, byName = byName } f.dna = { names = names :: { string }, types = types :: { string }, lengths = lengths, structs = structs, byName = byName }
return nil return nil
end end
@@ -298,7 +299,8 @@ function Blend.open(data: buffer, offset: number?, length: number?, opts: Option
end end
local hs, ps, little, version, fmt, herr = header(b, n) local hs, ps, little, version, fmt, herr = header(b, n)
if not hs then if not hs then
return nil, Err.new(if n < 12 then Err.TRUNCATED else Err.CORRUPT, herr or "bad header", 0) local code = if n < 12 then Err.TRUNCATED elseif herr and string.sub(herr, 1, 12) == "unsupported:" then Err.UNSUPPORTED else Err.CORRUPT
return nil, Err.new(code, herr or "bad header", 0)
end end
local f: File = { local f: File = {
buf = b, version = version, subversion = nil, pointerSize = ps, little = little, format = fmt, buf = b, version = version, subversion = nil, pointerSize = ps, little = little, format = fmt,
@@ -341,7 +343,8 @@ function Blend.open(data: buffer, offset: number?, length: number?, opts: Option
count = i32(b, p + 12 + ps) count = i32(b, p + 12 + ps)
end end
p += bh p += bh
code = string.gsub(code, "%z+$", "") -- two-letter ID codes are a 16-bit value in a 32-bit field: "\0\0SC" in big-endian files
code = string.gsub(string.gsub(code, "%z+$", ""), "^%z+", "")
if code == "ENDB" then if code == "ENDB" then
break break
end end
@@ -389,29 +392,33 @@ function Blend.open(data: buffer, offset: number?, length: number?, opts: Option
f.byAddr[if ps == 8 then string.rep("\0", 8) else 0] = nil f.byAddr[if ps == 8 then string.rep("\0", 8) else 0] = nil
local glob = f.byCode.GLOB local glob = f.byCode.GLOB
local fg = f.dna.byName.FileGlobal local fg = f.dna.byName.FileGlobal
if glob and fg and fg.byName.subversion then local g1: Block? = if glob then glob[1] else nil
local fld = fg.byName.subversion local fld = fg and fg.byName.subversion
if fld.offset + 2 <= glob[1].size then if g1 and fld then
f.subversion = f.i16(b, glob[1].offset + fld.offset) if fld.offset + 2 <= g1.size then
f.subversion = f.i16(b, g1.offset + fld.offset)
end end
end end
return f, nil return f, nil
end end
-- ------------------------------------------------------------------------------------------------ structs -- ------------------------------------------------------------------------------------------------ structs
export type View = {
file: File,
struct: Struct,
offset: number, -- the struct's first byte in file.buf
block: Block?,
}
local View = {} local View = {}
View.__index = View View.__index = View
Blend.View = View Blend.View = View
export type View = typeof(setmetatable(
{} :: {
file: File,
struct: Struct,
offset: number, -- the struct's first byte in file.buf
block: Block?,
},
View
))
local function view(f: File, s: Struct, offset: number, blk: Block?): View local function view(f: File, s: Struct, offset: number, blk: Block?): View
return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View) :: any return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View)
end end
function Blend.structOf(f: File, blk: Block): Struct? function Blend.structOf(f: File, blk: Block): Struct?
@@ -641,7 +648,7 @@ function View.array(self: View, name: string | { string }, as: string?): { View
local blk = first.block :: Block local blk = first.block :: Block
local s = first.struct local s = first.struct
local n = if s.size > 0 then blk.size // s.size else 0 local n = if s.size > 0 then blk.size // s.size else 0
local out = table.create(n) local out = table.create(n) :: { View }
for k = 0, n - 1 do for k = 0, n - 1 do
out[k + 1] = view(self.file, s, blk.offset + k * s.size, blk) out[k + 1] = view(self.file, s, blk.offset + k * s.size, blk)
end end
+59 -2
View File
@@ -1,7 +1,8 @@
--!strict --!strict
-- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips -> -- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips ->
-- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear, -- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear,
-- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes; -- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes
-- (elastic uses Penner's amplitude / period, which Blender scales differently);
-- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated. -- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated.
local Blend = require("@rosetta/containers/Blend") local Blend = require("@rosetta/containers/Blend")
@@ -112,6 +113,62 @@ function Anim.curves(f: Blend.File, adt: Blend.View?): ({ Curve }?, string?)
return out, act:idName() return out, act:idName()
end end
-- pre-2.5 IPO curves (Object.ipo / Key.ipo): the curve's adrcode picks the channel; object rotations are in units of
-- 10 degrees; the interpolation and extrapolation (0 constant, 1 linear; cyclic ones as constant) are per curve
local OB_ADR: { [number]: { any } } = {
[1] = { "location", 0 }, [2] = { "location", 1 }, [3] = { "location", 2 },
[4] = { "delta_location", 0 }, [5] = { "delta_location", 1 }, [6] = { "delta_location", 2 },
[7] = { "rotation_euler", 0, math.pi / 18 }, [8] = { "rotation_euler", 1, math.pi / 18 }, [9] = { "rotation_euler", 2, math.pi / 18 },
[10] = { "delta_rotation_euler", 0, math.pi / 18 }, [11] = { "delta_rotation_euler", 1, math.pi / 18 }, [12] = { "delta_rotation_euler", 2, math.pi / 18 },
[13] = { "scale", 0 }, [14] = { "scale", 1 }, [15] = { "scale", 2 },
}
function Anim.ipo(f: Blend.File, ipo: Blend.View?, keyNames: { string }?): ({ Curve }?, string?)
if not ipo then
return nil, nil
end
local out: { Curve } = {}
for _, icu in ipo:list("curve", "IpoCurve") do
local adr = icu:num("adrcode") or -1
local path, index, scale
if keyNames then
if adr >= 1 and keyNames[adr + 1] then
path, index, scale = 'key_blocks["' .. keyNames[adr + 1] .. '"].value', 0, 1
end
else
local m = OB_ADR[adr]
if m then
path, index, scale = m[1], m[2], m[3] or 1
end
end
if path then
local ipoMode = icu:num("ipo") or BEZ
local keys: { Key } = {}
for _, b in icu:array("bezt", "BezTriple") do
local v = b:vec("vec")
if v and #v >= 9 then
table.insert(keys, {
lx = v[1], ly = v[2] * scale, x = v[4], y = v[5] * scale, rx = v[7], ry = v[8] * scale,
ipo = if ipoMode == CONST or ipoMode == LIN then ipoMode else BEZ, easing = 0, back = 1.70158, amplitude = 0.8, period = 4.1,
})
end
end
local n = math.min(#keys, icu:num("totvert") or #keys)
while #keys > n do
table.remove(keys)
end
if #keys > 0 then
table.sort(keys, function(a: Key, b: Key): boolean
return a.x < b.x
end)
table.insert(out, { path = path, index = index, keys = keys, extend = if (icu:num("extrap") or 0) == 1 then 1 else 0, modifiers = 0 })
end
end
end
local _ = f
return out, ipo:idName()
end
-- ------------------------------------------------------------------------------------------------ evaluation -- ------------------------------------------------------------------------------------------------ evaluation
local function bezierAt(p0: number, p1: number, p2: number, p3: number, t: number): number local function bezierAt(p0: number, p1: number, p2: number, p3: number, t: number): number
local u = 1 - t local u = 1 - t
@@ -191,7 +248,7 @@ local function easeIn(ipo: number, t: number, a: Key): number -- 0..1 -> 0..1
t -= 1 t -= 1
return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p)) return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p))
elseif ipo == EXPO then elseif ipo == EXPO then
return if t <= 0 then 0 else 2 ^ (10 * (t - 1)) return (2 ^ (10 * (t - 1)) - 2 ^ -10) / (1 - 2 ^ -10) -- normalized to run from 0 to 1, as Blender's does
elseif ipo == QUAD then elseif ipo == QUAD then
return t * t return t * t
elseif ipo == QUART then elseif ipo == QUART then
+3 -1
View File
@@ -190,9 +190,11 @@ local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, throug
return nil, n return nil, n
end end
local sampler: Types.Sampler = {} local sampler: Types.Sampler = {}
local custom = false
local st = n.view:deref("storage", 0, "NodeTexImage") local st = n.view:deref("storage", 0, "NodeTexImage")
if st then if st then
local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0 local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0
custom = interp == 1 or (ext >= 1 and ext <= 3)
if interp == 1 then if interp == 1 then
sampler.filter = "nearest" sampler.filter = "nearest"
sampler.minFilter = "nearest" sampler.minFilter = "nearest"
@@ -203,7 +205,7 @@ local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, throug
sampler.wrapS, sampler.wrapT = "mirror", "mirror" sampler.wrapS, sampler.wrapT = "mirror", "mirror"
end end
end end
local t = texture(ctx, img, if next(sampler) then sampler else nil) local t = texture(ctx, img, if custom then sampler else nil)
if not t then if not t then
return nil, n return nil, n
end end
+58 -19
View File
@@ -198,6 +198,29 @@ local function fieldReader(f: Blend.File, L: Layer, field: string): ((number, nu
end end
end end
-- tessellated face colours: corner k of face i at offset + i * faceStride + first + k * cornerStride, bytes in MCol's
-- memory order (alpha, blue, green, red; reversed when an int held them in a big-endian file), sRGB -> linear;
-- TFace colours load opaque, as Blender's versioning makes them
local function tessColors(f: Blend.File, tess: buffer, nc: number, offset: number, bytes: number, faceStride: number, first: number, cornerStride: number, swap: boolean, opaque: boolean?): buffer
local d = buffer.create(nc * 16)
for i = 0, nc - 1 do
local tc = buffer.readu32(tess, i * 4)
local at = (tc // 4) * faceStride + first + (tc % 4) * cornerStride
if at + 4 <= bytes then
local o = offset + at
local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3)
if swap then
aa, bb, gg, rr = rr, gg, bb, aa
end
buffer.writef32(d, i * 16, SRGB[rr + 1])
buffer.writef32(d, i * 16 + 4, SRGB[gg + 1])
buffer.writef32(d, i * 16 + 8, SRGB[bb + 1])
buffer.writef32(d, i * 16 + 12, if opaque then 1 else aa / 255)
end
end
return d
end
function Mesh.layers(f: Blend.File, me: Blend.View): { Layer } function Mesh.layers(f: Blend.File, me: Blend.View): { Layer }
local layers: { Layer } = {} local layers: { Layer } = {}
customData(f, me, { "vdata", "vert_data" }, "point", layers) customData(f, me, { "vdata", "vert_data" }, "point", layers)
@@ -396,10 +419,11 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri
end end
elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then
local r = fieldReader(f, L, "uv") local r = fieldReader(f, L, "uv")
local tess = corner.tess :: buffer
if r then if r then
local d = buffer.create(nc * 8) local d = buffer.create(nc * 8)
for i = 0, nc - 1 do for i = 0, nc - 1 do
local tc = buffer.readu32(corner.tess, i * 4) local tc = buffer.readu32(tess, i * 4)
local face, k = tc // 4, tc % 4 local face, k = tc // 4, tc % 4
buffer.writef32(d, i * 8, r(face, k * 2)) buffer.writef32(d, i * 8, r(face, k * 2))
buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1)) buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1))
@@ -408,6 +432,21 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri
end end
end end
end end
-- before 2.42 (no CustomData): Mesh.tface (TFace, uv[4][2] per face) and Mesh.mcol (MCol x 4 per face)
if #poly.uvs == 0 and corner.tess then
local tf = legacy(f, me, "tface", "TFace", "tess")
local r = tf and fieldReader(f, tf, "uv")
if r then
local tess = corner.tess :: buffer
local d = buffer.create(nc * 8)
for i = 0, nc - 1 do
local tc = buffer.readu32(tess, i * 4)
buffer.writef32(d, i * 8, r(tc // 4, (tc % 4) * 2))
buffer.writef32(d, i * 8 + 4, r(tc // 4, (tc % 4) * 2 + 1))
end
table.insert(poly.uvs, { name = "UVMap", data = d })
end
end
local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute") local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute")
if active then if active then
for k, u in poly.uvs do for k, u in poly.uvs do
@@ -434,23 +473,20 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri
end end
table.insert(poly.colors, { name = L.name, domain = L.domain, data = d }) table.insert(poly.colors, { name = L.name, domain = L.domain, data = d })
elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then
-- MCol keeps alpha, blue, green, red in its a, r, g, b fields
local st = f.dna.byName.MCol local st = f.dna.byName.MCol
local d = buffer.create(nc * 16)
local stride = if st then st.size else 4 local stride = if st then st.size else 4
for i = 0, nc - 1 do table.insert(poly.colors, { name = L.name, domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, L.offset, L.bytes, stride * 4, 0, stride, false) })
local tc = buffer.readu32(corner.tess, i * 4) end
local at = (tc // 4) * 4 * stride + (tc % 4) * stride end
if at + 4 <= L.bytes then -- before 2.42 (no CustomData): Mesh.mcol, or TFace.col (unsigned int col[4], MCol's byte layout in memory)
local o = L.offset + at if #poly.colors == 0 and corner.tess then
local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) local mc = legacy(f, me, "mcol", "MCol", "tess")
buffer.writef32(d, i * 16, SRGB[rr + 1]) local tf = legacy(f, me, "tface", "TFace", "tess")
buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) local col = f.dna.byName.TFace and f.dna.byName.TFace.byName.col
buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) if mc then
buffer.writef32(d, i * 16 + 12, aa / 255) table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, mc.offset, mc.bytes, mc.elem * 4, 0, mc.elem, false) })
end elseif tf and col then
end table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, tf.offset, tf.bytes, tf.elem, col.offset, 4, not f.little, true) })
table.insert(poly.colors, { name = L.name, domain = "corner", data = d })
end end
end end
-- MLoopCol layers carry the CD_PROP_BYTE_COLOR type (17) and are read above as bytecolor (r, g, b, a bytes) -- MLoopCol layers carry the CD_PROP_BYTE_COLOR type (17) and are read above as bytecolor (r, g, b, a bytes)
@@ -539,7 +575,7 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri
local mw = f.dna.byName.MDeformWeight local mw = f.dna.byName.MDeformWeight
local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight
if dwf and twf and mw and nrf and wf then if dwf and twf and mw and nrf and wf then
local weights = table.create(nv) local weights = table.create(nv) :: { { number } }
for i = 0, nv - 1 do for i = 0, nv - 1 do
local list = {} local list = {}
local at = i * dv.elem local at = i * dv.elem
@@ -565,7 +601,7 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri
end end
-- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index -- 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 } export type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean, min: number, max: number }
function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?) function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?)
local key = me:deref("key", 0, "Key") local key = me:deref("key", 0, "Key")
if not key then if not key then
@@ -591,8 +627,11 @@ function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, num
ref = i ref = i
end end
table.insert(out, { table.insert(out, {
name = kb:str("name") or ("Key " .. i), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, -- 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, mute = bit32.band(kb:num("flag") or 0, 2) ~= 0,
min = kb:num("slidermin") or 0,
max = kb:num("slidermax") or 1,
}) })
end end
if ref == nil and #out > 0 then if ref == nil and #out > 0 then
+10 -15
View File
@@ -185,15 +185,10 @@ function Prim.cornerNormals(poly: MeshT.Poly, fn: buffer, ang: buffer, fans: Fan
local r = readu32(fanId, c * 4) local r = readu32(fanId, c * 4)
local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8) local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8)
local l = sqrt(x * x + y * y + z * z) local l = sqrt(x * x + y * y + z * z)
if l > 1e-20 then local fi = readu32(fans.face, c * 4)
x, y, z = x / l, y / l, z / l writef32(out, c * 12, if l > 1e-20 then x / l else readf32(fn, fi * 12))
else writef32(out, c * 12 + 4, if l > 1e-20 then y / l else readf32(fn, fi * 12 + 4))
local fi = readu32(fans.face, c * 4) writef32(out, c * 12 + 8, if l > 1e-20 then z / l else readf32(fn, fi * 12 + 8))
x, y, z = readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8)
end
writef32(out, c * 12, x)
writef32(out, c * 12 + 4, y)
writef32(out, c * 12 + 8, z)
end end
return out, fanId return out, fanId
end end
@@ -231,7 +226,7 @@ local function triangulate(poly: MeshT.Poly, fi: number, fnx: number, fny: numbe
elseif ay >= az then elseif ay >= az then
cu, cv, sign = 2, 0, fny cu, cv, sign = 2, 0, fny
end end
local ring = table.create(n * 2) local ring = table.create(n * 2) :: { number }
for c = s0, s1 - 1 do for c = s0, s1 - 1 do
local v = readu32(poly.cornerVert, c * 4) local v = readu32(poly.cornerVert, c * 4)
local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4) local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4)
@@ -284,7 +279,7 @@ function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: S
table.insert(g, fi) table.insert(g, fi)
end end
table.sort(order) table.sort(order)
local cornerColors, pointColors = {}, {} local cornerColors: { MeshT.Color }, pointColors: { MeshT.Color } = {}, {}
for _, c in poly.colors do for _, c in poly.colors do
table.insert(if c.domain == "corner" then cornerColors else pointColors, c) table.insert(if c.domain == "corner" then cornerColors else pointColors, c)
end end
@@ -367,7 +362,7 @@ function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: S
ci += 1 ci += 1
end end
if skin and poly.weights then if skin and poly.weights then
local lists = table.create(n) local lists = table.create(n) :: { { number } }
for i = 1, n do for i = 1, n do
local src = poly.weights[vsrc[i] + 1] or {} local src = poly.weights[vsrc[i] + 1] or {}
local l = {} local l = {}
@@ -415,17 +410,17 @@ function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: S
end end
if shapes and ref and #shapes > 1 then if shapes and ref and #shapes > 1 then
local base = shapes[ref].data local base = shapes[ref].data
local targets = {} local targets: { { [string]: Types.Accessor } } = {}
for k, s in shapes do for k, s in shapes do
if k ~= ref then if k ~= ref then
local t = table.create(n * 3) local t = table.create(n * 3) :: { number }
for i = 1, n do for i = 1, n do
local v = vsrc[i] local v = vsrc[i]
for c = 0, 2 do for c = 0, 2 do
t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4) t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4)
end end
end end
table.insert(targets, { POSITION = accessor(t, 3) }) table.insert(targets, { POSITION = accessor(t, 3) } :: { [string]: Types.Accessor })
end end
end end
prim.targets = targets prim.targets = targets
+65 -28
View File
@@ -86,26 +86,33 @@ export type Props = { [string]: { number } } -- location / rotation_euler / ...
-- an object's or pose bone's transform properties, keyed by their RNA names -- an object's or pose bone's transform properties, keyed by their RNA names
local function objectProps(ob: Blend.View): Props local function objectProps(ob: Blend.View): Props
local function v(n: number, ...: string): { number } -- fields missing from old files take their neutral value
local function v(fallback: { number }, ...: string): { number }
local x = ob:vec(...) local x = ob:vec(...)
if x and #x >= n then if x and #x >= #fallback then
return table.clone(x) return table.clone(x)
end end
return table.create(n, 0) return fallback
end end
return { local p: Props = {
location = v(3, "loc"), location = v({ 0, 0, 0 }, "loc"),
rotation_euler = v(3, "rot"), rotation_euler = v({ 0, 0, 0 }, "rot"),
rotation_quaternion = v(4, "quat"), rotation_quaternion = v({ 1, 0, 0, 0 }, "quat"),
rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) }, rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "rotAxis")) },
scale = v(3, "scale", "size"), scale = v({ 1, 1, 1 }, "scale", "size"),
delta_location = v(3, "dloc"), delta_location = v({ 0, 0, 0 }, "dloc"),
delta_rotation_euler = v(3, "drot"), delta_rotation_euler = v({ 0, 0, 0 }, "drot"),
delta_rotation_quaternion = v(4, "dquat"), delta_rotation_quaternion = v({ 1, 0, 0, 0 }, "dquat"),
delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v(3, "drotAxis")) }, delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "drotAxis")) },
delta_scale = v(3, "dscale", "dsize"), delta_scale = v({ 1, 1, 1 }, "dscale"),
rotmode = { ob:num("rotmode") or 1 }, rotmode = { ob:num("rotmode") or 1 },
} }
if not ob:has("dscale") then
-- before 2.5x the delta scale ("dsize") was added to the scale
local d = v({ 0, 0, 0 }, "dsize")
p.scale = { p.scale[1] + d[1], p.scale[2] + d[2], p.scale[3] + d[3] }
end
return p
end end
local function poseProps(pc: Blend.View?): Props local function poseProps(pc: Blend.View?): Props
@@ -267,12 +274,13 @@ local function camera(ctx: Ctx, ob: Blend.View, node: number)
local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100 local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100
local c: Types.Camera local c: Types.Camera
if (cam:num("type") or 0) == 1 then if (cam:num("type") or 0) == 1 then
local half = (cam:num("ortho_scale") or 6) / 2 -- files without ortho_scale (before 2.3x) scaled orthographic views by 256 / lens, as Blender's versioning sets it
local half = (cam:num("ortho_scale") or 256 / math.max(cam:num("lens") or 35, 1e-3)) / 2
local xmag, ymag = half, half / aspect local xmag, ymag = half, half / aspect
if aspect < 1 then if aspect < 1 then
xmag, ymag = half * aspect, half xmag, ymag = half * aspect, half
end end
c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } :: Types.Camera
else else
local lens = cam:num("lens") or 50 local lens = cam:num("lens") or 50
local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24 local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24
@@ -285,7 +293,7 @@ local function camera(ctx: Ctx, ob: Blend.View, node: number)
else else
yfov = 2 * math.atan(sx / 2 / lens) yfov = 2 * math.atan(sx / 2 / lens)
end end
c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } :: Types.Camera
end end
table.insert(ctx.scene.cameras, c) table.insert(ctx.scene.cameras, c)
ctx.scene.nodes[node].camera = #ctx.scene.cameras ctx.scene.nodes[node].camera = #ctx.scene.cameras
@@ -299,9 +307,13 @@ local function light(ctx: Ctx, ob: Blend.View, node: number)
local t = la:num("type") or 0 local t = la:num("type") or 0
local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 } local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 }
local energy = la:num("energy") or 1 local energy = la:num("energy") or 1
if ctx.f.version < 280 then if ctx.f.version < 280 and ctx.meta.engine ~= "CYCLES" then
-- before 2.8 Cycles took the strength from the lamp's Emission node, else 100 (sun: 1); Blender's 2.8 -- Blender's 2.8 versioning: Blender Internal energies times 100 (suns unchanged)
-- versioning moves that to energy if t ~= LA_SUN and t ~= LA_HEMI then
energy *= 100
end
elseif ctx.f.version < 280 then
-- Cycles took the strength from the lamp's Emission node, else 100 (sun: 1)
energy = if t == LA_SUN or t == LA_HEMI then 1 else 100 energy = if t == LA_SUN or t == LA_HEMI then 1 else 100
local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil
for _, n in if tree then tree:list("nodes", "bNode") else {} do for _, n in if tree then tree:list("nodes", "bNode") else {} do
@@ -318,13 +330,17 @@ local function light(ctx: Ctx, ob: Blend.View, node: number)
local name = ob:idName() local name = ob:idName()
local l: Types.Light local l: Types.Light
if t == LA_SUN or t == LA_HEMI then if t == LA_SUN or t == LA_HEMI then
l = { name = name, type = "directional", color = color, intensity = energy * W2LM } l = { name = name, type = "directional", color = color, intensity = energy * W2LM } :: Types.Light
elseif t == LA_SPOT then elseif t == LA_SPOT then
local outer = (la:num("spotsize") or math.rad(45)) / 2 local size = la:num("spotsize") or math.rad(45)
if ctx.f.version < 263 then
size = math.rad(size) -- degrees before 2.63
end
local outer = size / 2
local blend = la:num("spotblend") or 0 local blend = la:num("spotblend") or 0
l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } :: Types.Light
elseif t == LA_LOCAL then elseif t == LA_LOCAL then
l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } :: Types.Light
else else
local skipped = ctx.meta.skippedLights or {} local skipped = ctx.meta.skippedLights or {}
ctx.meta.skippedLights = skipped ctx.meta.skippedLights = skipped
@@ -568,11 +584,23 @@ type Job = { kind: string, node: number?, nodes: { number }?, info: any?, curves
local function animations(ctx: Ctx) local function animations(ctx: Ctx)
local f = ctx.f local f = ctx.f
local jobs: { Job } = {} local jobs: { Job } = {}
-- an IPO shared by several objects animates the first by name only, as Blender's 2.5 conversion leaves it
local ipoOwner: { [any]: string } = {}
for _, ob in ctx.objView do
local a, nm = ob:ptr("ipo"), ob:idName() or ""
if a ~= nil and (ipoOwner[a] == nil or nm < ipoOwner[a]) then
ipoOwner[a] = nm
end
end
for node = 1, #ctx.scene.nodes do for node = 1, #ctx.scene.nodes do
local ob = ctx.objView[node] local ob = ctx.objView[node]
local curves, name local curves, name
if ob then if ob then
curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData")) curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData"))
local ipoAddr = ob:ptr("ipo")
if not curves and not ob:has("adt") and ipoAddr ~= nil and ipoOwner[ipoAddr] == ob:idName() then
curves, name = Anim.ipo(f, ob:deref("ipo", 0, "Ipo"))
end
end end
if curves and #curves > 0 and name then if curves and #curves > 0 and name then
table.insert(jobs, { kind = "object", node = node, curves = curves, action = name }) table.insert(jobs, { kind = "object", node = node, curves = curves, action = name })
@@ -584,6 +612,13 @@ local function animations(ctx: Ctx)
end end
for meshIdx, sk in ctx.meta.shapeKeys do for meshIdx, sk in ctx.meta.shapeKeys do
local curves, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) local curves, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData"))
if not curves and sk.key and not sk.key:has("adt") then
local names = {}
for i, s in sk.shapes do
names[i] = s.name
end
curves, name = Anim.ipo(f, sk.key:deref("ipo", 0, "Ipo"), names)
end
-- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value") -- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value")
local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData")) local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData"))
for _, c in mc or {} do for _, c in mc or {} do
@@ -601,7 +636,7 @@ local function animations(ctx: Ctx)
table.insert(nodes, i) table.insert(nodes, i)
end end
end end
table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves, action = name, meshIdx = meshIdx }) table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves :: { Curve }, action = name, meshIdx = meshIdx })
end end
end end
if #jobs == 0 then if #jobs == 0 then
@@ -622,12 +657,12 @@ local function animations(ctx: Ctx)
for _, j in jobs do for _, j in jobs do
local anim = byAction[j.action] local anim = byAction[j.action]
if not anim then if not anim then
anim = { name = j.action, channels = {} } anim = { name = j.action, channels = {} } :: Types.Animation
byAction[j.action] = anim byAction[j.action] = anim
table.insert(ctx.scene.animations, anim) table.insert(ctx.scene.animations, anim)
end end
local lo, hi = Anim.range(j.curves) local lo, hi = Anim.range(j.curves)
local fs = frames(lo, hi, step) local fs = frames(math.floor(lo), math.ceil(hi), step) -- whole frames, as Blender plays them
local times = {} local times = {}
for i, fr in fs do for i, fr in fs do
times[i] = (fr - zero) / fps times[i] = (fr - zero) / fps
@@ -695,7 +730,7 @@ local function animations(ctx: Ctx)
for _, c in j.curves do for _, c in j.curves do
local kind, who, rest = Anim.split(c.path) local kind, who, rest = Anim.split(c.path)
if kind == "key_blocks" and who == s.name and rest == "value" then if kind == "key_blocks" and who == s.name and rest == "value" then
v = Anim.evaluate(c, fr) v = math.clamp(Anim.evaluate(c, fr), math.min(s.min, s.max), math.max(s.min, s.max)) -- the slider range
end end
end end
buffer.writef32(out, ((i - 1) * count + k) * 4, v) buffer.writef32(out, ((i - 1) * count + k) * 4, v)
@@ -764,6 +799,7 @@ function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?)
local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6) local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6)
meta.fps = if fps > 0 then fps else 24 meta.fps = if fps > 0 then fps else 24
meta.frameStart = r:num("sfra") or 1 meta.frameStart = r:num("sfra") or 1
meta.engine = r:str("engine")
local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080 local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080
local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1 local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1
if xs > 0 and ys > 0 and xa > 0 and ya > 0 then if xs > 0 and ys > 0 and xa > 0 and ya > 0 then
@@ -846,6 +882,7 @@ function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?)
animations(ctx) animations(ctx)
end end
meta.shapeKeys = nil meta.shapeKeys = nil
meta.engine = nil
local render = meta.render local render = meta.render
meta.render = nil meta.render = nil
scene.meta.up = "z" scene.meta.up = "z"
+2
View File
@@ -69,7 +69,9 @@ function BlendFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene
end end
-- ------------------------------------------------------------------------------------------------ extras -- ------------------------------------------------------------------------------------------------ extras
BlendFormat.container = Blend
BlendFormat.evaluate = Anim.evaluate BlendFormat.evaluate = Anim.evaluate
BlendFormat.curves = Anim.curves BlendFormat.curves = Anim.curves
BlendFormat.ipo = Anim.ipo
return BlendFormat return BlendFormat
+294
View File
@@ -0,0 +1,294 @@
-- containers/Blend tests: synthetic files in every header / pointer size / byte order (12-byte header with 4 and 8
-- byte pointers, little and big endian; the 5.0+ 17-byte header with large block heads), structs by name, arrays,
-- pointers, ListBase walks, addresses reused between IDs, gzip; the real files of tools/fixtures/blend.py (headers,
-- versions, zstd); errors; the fuzz pass.
local T = require("@tests/T")
local Blend = require("@rosetta/containers/Blend")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Err = require("@rosetta/core/Err")
local Cur = require("@tests/gen/blend_cur")
local Old = require("@tests/gen/blend_293")
local t = T.suite("containers/Blend")
-- a writer of either byte order
local function writer(little: boolean)
local parts: { string } = {}
local w = {}
local function bytes(v: number, n: number): string
local s = {}
for k = 0, n - 1 do
s[k + 1] = string.char(math.floor(v / 256 ^ k) % 256)
end
local str = table.concat(s)
return if little then str else string.reverse(str)
end
function w.u8(v: number)
table.insert(parts, string.char(v))
end
function w.i16(v: number)
table.insert(parts, bytes(v % 65536, 2))
end
function w.i32(v: number)
table.insert(parts, bytes(v % 4294967296, 4))
end
function w.u64(v: number)
table.insert(parts, bytes(v, 8))
end
function w.f32(v: number)
local b = buffer.create(4)
buffer.writef32(b, 0, v)
local s = buffer.tostring(b)
table.insert(parts, if little then s else string.reverse(s))
end
function w.f64(v: number)
local b = buffer.create(8)
buffer.writef64(b, 0, v)
local s = buffer.tostring(b)
table.insert(parts, if little then s else string.reverse(s))
end
function w.str(s: string)
table.insert(parts, s)
end
function w.ptr(v: number, ps: number)
if ps == 8 then
w.u64(v)
else
w.i32(v)
end
end
function w.done(): string
return table.concat(parts)
end
return w
end
-- SDNA: ListBase { void *first, *last }; Thing { Thing *next, *prev; int a; float b[2]; char name[8]; short s;
-- char pad[2]; void *data }; Holder { ListBase things; Thing *one; double d; ID-less }
local NAMES = { "*first", "*last", "*next", "*prev", "a", "b[2]", "name[8]", "s", "pad[2]", "*data", "things", "*one", "d" }
local TYPES = { "char", "short", "int", "float", "double", "void", "ListBase", "Thing", "Holder" }
local function sdna(little: boolean, ps: number): string
local w = writer(little)
local function pad()
local s = w.done()
return (4 - #s % 4) % 4
end
w.str("SDNA")
w.str("NAME")
w.i32(#NAMES)
for _, n in NAMES do
w.str(n .. "\0")
end
for _ = 1, pad() do
w.u8(0)
end
w.str("TYPE")
w.i32(#TYPES)
for _, n in TYPES do
w.str(n .. "\0")
end
for _ = 1, pad() do
w.u8(0)
end
w.str("TLEN")
local thing = ps * 2 + 4 + 8 + 8 + 2 + 2 + ps
for _, l in { 1, 2, 4, 4, 8, 0, ps * 2, thing, ps * 2 + ps + 8 } do
w.i16(l)
end
for _ = 1, pad() do
w.u8(0)
end
w.str("STRC")
w.i32(3)
local function struct(ty: number, fields: { { number } })
w.i16(ty)
w.i16(#fields)
for _, f in fields do
w.i16(f[1])
w.i16(f[2])
end
end
-- type / name indices are 0-based
struct(6, { { 5, 0 }, { 5, 1 } })
struct(7, { { 7, 2 }, { 7, 3 }, { 2, 4 }, { 3, 5 }, { 0, 6 }, { 1, 7 }, { 0, 8 }, { 5, 9 } })
struct(8, { { 6, 10 }, { 7, 11 }, { 4, 12 } })
return w.done()
end
local function file(little: boolean, ps: number, large: boolean, dupe: boolean?): string
local w = writer(little)
if large then
w.str("BLENDER17-01v0502")
else
w.str("BLENDER" .. (if ps == 8 then "-" else "_") .. (if little then "v" else "V") .. "279")
end
local function head(code: string, size: number, addr: number, sdnaIndex: number, count: number)
w.str(code .. string.rep("\0", 4 - #code))
if large then
w.i32(sdnaIndex)
w.u64(addr)
w.u64(size)
w.u64(count)
else
w.i32(size)
w.ptr(addr, ps)
w.i32(sdnaIndex)
w.i32(count)
end
end
local thingSize = ps * 2 + 24 + ps
head("HO", ps * 3 + 8, 0x1000, 2, 1)
w.ptr(0x2000, ps) -- things.first
w.ptr(0x3000, ps) -- things.last
w.ptr(0x3000, ps) -- one
w.f64(2.5)
local function thing(next: number, prev: number, a: number, b1: number, b2: number, name: string, s: number, data: number)
w.ptr(next, ps)
w.ptr(prev, ps)
w.i32(a)
w.f32(b1)
w.f32(b2)
w.str(name .. string.rep("\0", 8 - #name))
w.i16(s)
w.str("\0\0")
w.ptr(data, ps)
end
head("DATA", thingSize, 0x2000, 1, 1)
thing(0x3000, 0, -7, 1.5, -2.25, "first", -300, 0x4000)
head("DATA", thingSize, 0x3000, 1, 1)
thing(0, 0x2000, 123456, 0.5, 4, "second!", 1234, 0)
head("DATA", 6, 0x4000, 0, 1)
w.str("hello\0")
if dupe then
-- a second ID whose own data reuses the address 0x4000
head("H2", ps * 3 + 8, 0x5000, 2, 1)
w.ptr(0, ps)
w.ptr(0, ps)
w.ptr(0x4000, ps)
w.f64(-1)
head("DATA", thingSize, 0x4000, 1, 1)
thing(0, 0, 99, 0, 0, "dup", 0, 0)
end
local dna = sdna(little, ps)
head("DNA1", #dna, 0x9000, 0, 1)
w.str(dna)
head("ENDB", 0, 0, 0, 0)
return w.done()
end
for _, v in { { true, 8, false }, { true, 4, false }, { false, 8, false }, { false, 4, false }, { true, 8, true } } do
local little, ps, large = v[1], v[2], v[3]
local label = string.format("%s-endian, %d-byte pointers%s", if little then "little" else "big", ps, if large then ", 5.0 header" else "")
local f, err = Blend.open(buffer.fromstring(file(little, ps, large)))
t:check(f, label .. ": open: " .. tostring(err))
if not f then
continue
end
t:eq(f.pointerSize, ps, label .. ": pointer size")
t:eq(f.little, little, label .. ": byte order")
t:eq(f.version, if large then 502 else 279, label .. ": version")
t:eq(f.format, if large then 1 else 0, label .. ": format")
t:eq(#f.blocks, 5, label .. ": blocks (ENDB not listed)")
t:eq(f.dna.byName.Thing.size, ps * 3 + 24, label .. ": struct size from TLEN")
t:eq(f.dna.byName.Thing.byName.data.offset, ps * 2 + 24, label .. ": field offsets")
local ho = assert(Blend.struct(f, Blend.blocks(f, "HO")[1]))
t:eq(ho:num("d"), 2.5, label .. ": double")
local list = ho:list("things")
t:eq(#list, 2, label .. ": ListBase walk")
t:eq(list[1]:num("a"), -7, label .. ": int")
t:eq(list[2]:num("a"), 123456, label .. ": int 2")
t:eq(list[1]:num("s"), -300, label .. ": short")
t:eq(list[1]:str("name"), "first", label .. ": char array")
t:eq(list[2]:str("name"), "second!", label .. ": char array 2")
local b = list[1]:vec("b")
t:check(b and b[1] == 1.5 and b[2] == -2.25, label .. ": float array")
t:eq(list[1]:cstring("data"), "hello", label .. ": pointer to raw data")
local one = ho:deref("one")
t:check(one and one:num("a") == 123456, label .. ": deref by field type")
t:check(ho:ptr("one") ~= nil and list[2]:ptr("next") == nil, label .. ": null pointers are nil")
t:check(ho:get("missing") == nil and ho:has("d") and not ho:has("missing"), label .. ": unknown fields")
t:eq(ho:num("missing", "d"), 2.5, label .. ": the first existing of several names")
local fld = Blend.field(f, "Thing", "nope", "b")
t:check(fld and fld.count == 2 and fld.type == "float" and #fld.dims == 1, label .. ": Blend.field")
end
-- an address reused by another ID's data resolves inside the ID that points at it
do
local f = assert(Blend.open(buffer.fromstring(file(true, 8, false, true))))
local h1 = assert(Blend.struct(f, Blend.blocks(f, "HO")[1]))
local h2 = assert(Blend.struct(f, Blend.blocks(f, "H2")[1]))
t:eq(h1:list("things")[1]:cstring("data"), "hello", "reused address: the first ID's raw data")
local d = h2:deref("one")
t:check(d and d:num("a") == 99 and d:str("name") == "dup", "reused address: the second ID's own block")
end
-- gzip (Blender before 3.0)
do
local raw = file(true, 8, false)
local gz = assert(Deflate.gzip(raw))
local f, err = Blend.open(gz)
t:check(f and f.compression == "gzip" and #f.blocks == 5, "gzip: " .. tostring(err))
t:eq(Blend.sniff(gz), 0.05, "gzip sniffs weakly")
t:eq(Blend.sniff(buffer.fromstring(raw)), 1, "magic")
end
-- the real files: headers and compression
for _, set in { Cur, Old } do
for _, c in set do
local f, err = Blend.open(buffer.fromstring(c.data))
t:check(f, c.name .. ": " .. tostring(err))
if f then
local want = c.ref.version[1] * 100 + c.ref.version[2]
t:eq(f.version, want, c.name .. ": version")
t:eq(f.format, if want >= 500 then 1 else 0, c.name .. ": header format")
if string.find(c.name, "_z%.blend$") then
t:eq(f.compression, if want >= 300 then "zstd" else "gzip", c.name .. ": compression")
end
t:check(f.dna.byName.Object and f.dna.byName.Mesh and #Blend.blocks(f, "OB") > 0, c.name .. ": SDNA and objects")
end
end
end
-- errors
local function code(s: string): string?
local f, e = Blend.open(buffer.fromstring(s))
return if f then nil else e.code
end
local good = file(true, 8, false)
t:eq(code("BLEND"), Err.TRUNCATED, "short file")
t:eq(code("NOTBLEND-v279" .. string.rep("\0", 40)), Err.CORRUPT, "bad magic")
t:eq(code(string.sub(good, 1, #good - 30)), Err.TRUNCATED, "no ENDB")
t:eq(code("BLENDER17-02v0502" .. string.rep("\0", 40)), Err.UNSUPPORTED, "unknown header format version")
local noDna = string.gsub(good, "DNA1", "DNA2")
t:eq(code(noDna), Err.CORRUPT, "no DNA1")
local badDna = string.gsub(good, "STRC", "STRX")
t:eq(code(badDna), Err.CORRUPT, "bad SDNA")
local _, e = Blend.open(buffer.fromstring(good), 0, 999999)
t:eq(e and e.code, Err.ARG, "bad range")
local samples = { good, file(false, 4, false), file(true, 8, true, true) }
t:fuzz("open", function(b: buffer)
local f = Blend.open(b)
if f then
for _, blk in f.blocks do
local v = Blend.struct(f, blk)
if v then
for _, fld in v.struct.fields do
local x = v:get(fld.name)
if fld.pointer then
v:deref(fld.name)
v:array(fld.name)
v:pointers(fld.name)
v:cstring(fld.name)
elseif fld.type == "ListBase" then
v:list(fld.name)
end
local _ = x
end
end
end
end
return f
end, samples, { mutations = 64 })
t:done()
+49 -18
View File
@@ -19,6 +19,7 @@ local Sets = {
["35"] = require("@tests/gen/blend_35"), ["35"] = require("@tests/gen/blend_35"),
["41"] = require("@tests/gen/blend_41"), ["41"] = require("@tests/gen/blend_41"),
cur = require("@tests/gen/blend_cur"), cur = require("@tests/gen/blend_cur"),
old = require("@tests/gen/blend_old"), -- Blender 1.66 - 2.04 demo files (big-endian among them)
} }
local t = T.suite("blend") local t = T.suite("blend")
@@ -146,7 +147,8 @@ 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 } local checked = { worlds = 0, meshes = 0, normals = 0, weights = 0, shapes = 0, frames = 0, skinned = 0, curves = 0, materials = 0, cameras = 0, lights = 0 }
local samples = {} local samples = {}
for _, tag in { "279", "293", "35", "41", "cur" } do t:check(#Sets.old >= 4, "the old demo files were fetched (" .. #Sets.old .. ")")
for _, tag in { "old", "279", "293", "35", "41", "cur" } do
for _, c in Sets[tag] do for _, c in Sets[tag] do
local ref = c.ref local ref = c.ref
local label = c.name local label = c.name
@@ -334,8 +336,10 @@ for _, tag in { "279", "293", "35", "41", "cur" } do
for k, s in mi.shapes do for k, s in mi.shapes do
if k ~= refIndex then if k ~= refIndex then
ti += 1 ti += 1
t:check(near(mesh.weights[ti], s.value, 1e-6), label .. ": " .. o.name .. " " .. s.name .. " weight") if not o.shapeAction then -- animated values are checked per frame below
for ci, cv in cs do t:check(near(mesh.weights[ti], s.value, 1e-6), label .. ": " .. o.name .. " " .. s.name .. " weight")
end
for ci, cv in if mi.cornerVerts then cs else {} do
local tgt = cv[1].targets and cv[1].targets[ti] local tgt = cv[1].targets and cv[1].targets[ti]
local get = tgt and read(tgt.POSITION) local get = tgt and read(tgt.POSITION)
local v = mi.cornerVerts[ci] local v = mi.cornerVerts[ci]
@@ -391,9 +395,11 @@ for _, tag in { "279", "293", "35", "41", "cur" } do
tex = x tex = x
end end
end end
if im.packed > 0 then if not tex then
t:check(tex and tex.data and buffer.len(tex.data) == im.packed and tex.mime == "image/png", label .. ": packed image " .. im.name) continue -- not used by a node material (legacy texture slots, face images)
elseif tex then elseif im.packed > 0 then
t:check(tex.data and buffer.len(tex.data) == im.packed and (tag == "old" or tex.mime == "image/png"), label .. ": packed image " .. im.name)
else
t:eq(tex.uri, "outside.png", label .. ": external image uri") t:eq(tex.uri, "outside.png", label .. ": external image uri")
t:check(tex.data and buffer.len(tex.data) == #Files["outside.png"], label .. ": external image bytes through opts.files") t:check(tex.data and buffer.len(tex.data) == #Files["outside.png"], label .. ": external image bytes through opts.files")
end end
@@ -432,17 +438,26 @@ for _, tag in { "279", "293", "35", "41", "cur" } do
checked.lights += 1 checked.lights += 1
end end
-- triangles: the glTF exporter's meshes -- triangles: the glTF exporter's meshes
if gl.meshes then local curves = false -- the exporter turns curves / text / surfaces / metaballs into meshes; we do not
for _, o in ref.objects do
curves = curves or o.type == "CURVE" or o.type == "FONT" or o.type == "SURFACE" or o.type == "META"
end
if gl.meshes and not curves then
-- per instance (both sides share meshes differently)
local want = 0 local want = 0
for _, m in gl.meshes do for _, n in gl.nodes or {} do
for _, p in m.primitives do if n.mesh then
want += gl.accessors[p.indices + 1].count // 3 for _, p in gl.meshes[n.mesh + 1].primitives do
want += gl.accessors[p.indices + 1].count // 3
end
end end
end end
local got = 0 local got = 0
for _, m in scene.meshes do for _, n in scene.nodes do
for _, p in m.primitives do if n.mesh then
got += p.indices.count // 3 for _, p in scene.meshes[n.mesh].primitives do
got += p.indices.count // 3
end
end end
end end
t:eq(got, want, label .. ": triangles (glTF exporter)") t:eq(got, want, label .. ": triangles (glTF exporter)")
@@ -471,9 +486,16 @@ for _, tag in { "279", "293", "35", "41", "cur" } do
ob = v ob = v
end end
end end
local curves = B.curves(file, ob and ob:deref("adt", 0, "AnimData")) or {} local curves = B.curves(file, ob and ob:deref("adt", 0, "AnimData"))
t:eq(#curves, #refCurves, label .. ": " .. o.name .. " f-curves") if not curves and ob and not ob:has("adt") then
curves = B.ipo(file, ob:deref("ipo", 0, "Ipo")) -- before 2.5
end
curves = curves or {}
for _, rc in refCurves do for _, rc in refCurves do
local p = rc.path
if not (p == "location" or p == "scale" or string.find(p, "rotation") or string.find(p, "^delta_")) then
continue -- only the transform curves are read
end
local cur = nil local cur = nil
for _, x in curves do for _, x in curves do
if x.path == rc.path and x.index == rc.index then if x.path == rc.path and x.index == rc.index then
@@ -492,14 +514,21 @@ for _, tag in { "279", "293", "35", "41", "cur" } do
end end
-- the animations sampled at whole frames: posed world matrices, bones, shape key values, skinned positions -- the animations sampled at whole frames: posed world matrices, bones, shape key values, skinned positions
if #ref.poses > 0 then if #ref.poses > 0 then
t:check(#scene.animations > 0, label .. ": animations") local animated = false -- transform or shape key curves (others, such as an object colour, are not read)
for _, list in ref.actions do
for _, rc in list do
local p = rc.path
animated = animated or p == "location" or p == "scale" or string.find(p, "rotation") ~= nil or string.find(p, "key_blocks") ~= nil
end
end
t:check(#scene.animations > 0 or not animated, label .. ": animations")
local caches = {} local caches = {}
for _, p in ref.poses do for _, p in ref.poses do
local frame = p.frame local frame = p.frame
if frame ~= math.floor(frame) or frame > 20 then if frame ~= math.floor(frame) or frame > 20 then
continue continue
end end
local time = (frame - src.frameZero) / src.fps local time = (frame - (src.frameZero or src.frameStart)) / src.fps
local pose = {} local pose = {}
for ai, a in scene.animations do for ai, a in scene.animations do
caches[ai] = caches[ai] or {} caches[ai] = caches[ai] or {}
@@ -523,7 +552,9 @@ for _, tag in { "279", "293", "35", "41", "cur" } do
local i = objects[name] local i = objects[name]
local w = pose[i] and pose[i].weights or scene.nodes[i].weights local w = pose[i] and pose[i].weights or scene.nodes[i].weights
local want = table.move(values, 2, #values, 1, {}) local want = table.move(values, 2, #values, 1, {})
t:check(nearList(w, want, 1e-3), label .. ": frame " .. frame .. " " .. name .. " shape values " .. fmt(w) .. " / " .. fmt(want)) -- 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))
end end
for name, want in p.skinned or {} do for name, want in p.skinned or {} do
-- morph, then skin: sum of w * jointWorld * inverseBind * position -- morph, then skin: sum of w * jointWorld * inverseBind * position
+9
View File
@@ -941,6 +941,15 @@ do
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function() bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
Fbx.decode(Bytes.reader(fbxa)) Fbx.decode(Bytes.reader(fbxa))
end) end)
local BlendFmt = require("@rosetta/model/blend")
for _, c in require("@tests/gen/blend_cur") do
if c.name == "rig_52.blend" or c.name == "scene_52_z.blend" then
local bb = buffer.fromstring(c.data)
bench("blend decode " .. c.name .. " (" .. buffer.len(bb) // 1000 .. " KB)", 5, buffer.len(bb), function()
BlendFmt.decode(Bytes.reader(bb))
end)
end
end
local ThreeMf = require("@rosetta/model/3mf") local ThreeMf = require("@rosetta/model/3mf")
local tmf = assert(ThreeMf.encode(scene)) local tmf = assert(ThreeMf.encode(scene))
bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function() bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
+12
View File
@@ -365,6 +365,18 @@ def rig_file():
mover.keyframe_insert("location", frame=f) mover.keyframe_insert("location", frame=f)
mover.keyframe_insert("rotation_euler", frame=f) mover.keyframe_insert("rotation_euler", frame=f)
mover.keyframe_insert("scale", frame=f) mover.keyframe_insert("scale", frame=f)
# easing interpolations (Penner) with explicit and automatic easing
easer = link(bpy.data.objects.new("Easer", None))
eases = (("SINE", "EASE_IN_OUT"), ("BOUNCE", "AUTO"), ("SINE", "EASE_OUT"), ("BACK", "EASE_IN"),
("EXPO", "AUTO"), ("CIRC", "EASE_OUT"), ("QUART", "EASE_IN_OUT"), ("EXPO", "EASE_OUT"), ("EXPO", "EASE_IN_OUT"), ("CUBIC", "EASE_IN"))
for k in range(len(eases) + 1):
easer.location = (k % 2 * 2.0, k * 0.5, 0)
easer.keyframe_insert("location", frame=1 + k * 2.5)
for fc in (easer.animation_data.action.fcurves if hasattr(easer.animation_data.action, "fcurves") else
[c for l in easer.animation_data.action.layers for s in l.strips for b in s.channelbags for c in b.fcurves]):
for kp, (ipo, easing) in zip(fc.keyframe_points, eases):
kp.interpolation = ipo
kp.easing = easing
rig_action = rig.animation_data.action rig_action = rig.animation_data.action
mover_action = mover.animation_data.action mover_action = mover.animation_data.action
for act, rules in ((rig_action, {"location": "LINEAR", "scale": "CONSTANT"}), for act, rules in ((rig_action, {"location": "LINEAR", "scale": "CONSTANT"}),
+51 -2
View File
@@ -3,8 +3,10 @@
# generation (MFace legacy save, MPoly / MLoop, attribute layers, AttributeStorage), gzip and zstd compression, the # 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 # 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 # (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). # skipped (its cases are missing; the test notes it). Plus a few Blender 1.6x / 2.0x files from download.blender.org's
# tests/gen/blend_<ver>.luau { { name, data, ref } } # old demos (fetched, never committed; 32-bit pointers, big-endian SGI / PowerPC files among them), with references
# from Blender 4.1 (5.0 dropped big-endian files).
# tests/gen/blend_<ver>.luau { { name, data, ref } } (<ver>: 279, 293, 35, 41, cur, old)
# tests/gen/blend_files.luau sibling files the scenes refer to ({ ["outside.png"] = bytes }) # tests/gen/blend_files.luau sibling files the scenes refer to ({ ["outside.png"] = bytes })
import json, os, shutil, subprocess, tempfile import json, os, shutil, subprocess, tempfile
@@ -18,6 +20,52 @@ OLD = [
] ]
OLD_DEMOS = "https://download.blender.org/demo/old_demos/"
OLD_FILES = ["escher.blend", "hairball.blend", "nmesh.blend", "relative.blend", "demo2.04.blend.gz"]
def old_samples(ctx, tmp):
import gzip, urllib.request
out = os.path.join(tmp, "olddemos")
os.makedirs(out)
files = []
for f in OLD_FILES:
try:
with urllib.request.urlopen(OLD_DEMOS + f, timeout=60) as r:
data = r.read()
except OSError as e:
print("blend: could not fetch %s: %s" % (f, e))
continue
if f.endswith(".gz"):
data = gzip.decompress(data)
f = f[:-3].replace("2.04", "204")
with open(os.path.join(out, f), "wb") as fh:
fh.write(data)
files.append(os.path.join(out, f))
if not files:
return []
refdir = os.path.join(tmp, "oldref")
os.makedirs(refdir)
ref = os.path.join(ctx.root, "tools", "fixtures", "_blend_ref.py")
ok, log = run(["nix", "shell"] + OLD[3][1] + ["-c", "blender", "-b", "--factory-startup", "--python", ref, "--", json.dumps(files), refdir])
cases = []
for p in files:
rp = os.path.join(refdir, os.path.basename(p) + ".json")
if not os.path.exists(rp):
continue
r = json.load(open(rp))
if r.get("error"):
continue
g = r.get("gltf")
if g:
for k in ("bufferViews", "asset", "scene", "scenes", "extensionsUsed", "samplers"):
g.pop(k, None)
cases.append({"name": "old/" + os.path.basename(p), "data": open(p, "rb").read(), "ref": clean(r)})
if not cases:
print("blend: Blender 4.1 gave no reference for the old demos: " + log[-400:])
return cases
def env(): def env():
e = dict(os.environ) e = dict(os.environ)
e.pop("LD_LIBRARY_PATH", None) # the host's alsa / pipewire libraries need a newer glibc than old Blenders have e.pop("LD_LIBRARY_PATH", None) # the host's alsa / pipewire libraries need a newer glibc than old Blenders have
@@ -87,6 +135,7 @@ def generate(ctx):
for tag, _ in OLD + [("cur", None)]: for tag, _ in OLD + [("cur", None)]:
if tag not in made: if tag not in made:
ctx.emit("blend_" + tag, []) ctx.emit("blend_" + tag, [])
ctx.emit("blend_old", old_samples(ctx, tmp))
ctx.emit("blend_files", {"outside.png": sibling or b""}) ctx.emit("blend_files", {"outside.png": sibling or b""})
ctx.emit("blend_versions", sorted(made.keys())) ctx.emit("blend_versions", sorted(made.keys()))
shutil.rmtree(tmp, ignore_errors=True) shutil.rmtree(tmp, ignore_errors=True)
+73
View File
@@ -0,0 +1,73 @@
# Docs inputs for the .blend section of docs/guide/scene.md (tools/fixtures.py; tools/docs_check.py explains the
# inputs): a small rig saved zstd-compressed by the nixpkgs Blender (a two-bone armature, a skinned cylinder with a
# shape key, a bone action and a Principled material).
# tests/gen/docs_blend.luau { files = { ["rig.blend"] = bytes }, vars = { riggedBlendBytes = "rig.blend" } }
import importlib.util, os, shutil, subprocess, tempfile
INPUTS = ["tools/docs_check.py"]
SCRIPT = r'''
import bpy, sys, math
out = sys.argv[sys.argv.index("--") + 1]
bpy.ops.wm.read_factory_settings(use_empty=True)
arm = bpy.data.armatures.new("RigData")
rig = bpy.data.objects.new("Rig", arm)
bpy.context.scene.collection.objects.link(rig)
bpy.context.view_layer.objects.active = rig
bpy.ops.object.mode_set(mode="EDIT")
a = arm.edit_bones.new("lower")
a.head, a.tail = (0, 0, 0), (0, 0, 1)
b = arm.edit_bones.new("upper")
b.head, b.tail, b.parent, b.use_connect = (0, 0, 1), (0, 0, 2), a, True
bpy.ops.object.mode_set(mode="OBJECT")
ring = [(math.cos(k * math.pi / 3) * 0.3, math.sin(k * math.pi / 3) * 0.3) for k in range(6)]
verts = [(x, y, z) for z in (0, 1, 2) for x, y in ring]
faces = [(r * 6 + k, r * 6 + (k + 1) % 6, (r + 1) * 6 + (k + 1) % 6, (r + 1) * 6 + k) for r in range(2) for k in range(6)]
me = bpy.data.meshes.new("Tube")
me.from_pydata(verts, [], faces)
mat = bpy.data.materials.new("Skin")
mat.use_nodes = True
bsdf = mat.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = (0.9, 0.6, 0.5, 1)
bsdf.inputs["Roughness"].default_value = 0.7
me.materials.append(mat)
tube = bpy.data.objects.new("Tube", me)
bpy.context.scene.collection.objects.link(tube)
tube.parent = rig
tube.modifiers.new("Armature", "ARMATURE").object = rig
lo, up = tube.vertex_groups.new(name="lower"), tube.vertex_groups.new(name="upper")
for i in range(18):
lo.add([i], 1.0 - (i // 6) * 0.5, "REPLACE")
up.add([i], (i // 6) * 0.5, "REPLACE")
tube.shape_key_add(name="Basis")
bulge = tube.shape_key_add(name="Bulge")
for p in bulge.data:
p.co = (p.co[0] * 1.4, p.co[1] * 1.4, p.co[2])
pb = rig.pose.bones["upper"]
for f, angle in ((1, 0.0), (12, 0.8), (24, 0.0)):
pb.rotation_quaternion = (math.cos(angle / 2), math.sin(angle / 2), 0, 0)
pb.keyframe_insert("rotation_quaternion", frame=f)
bpy.context.scene.frame_set(1)
bpy.ops.wm.save_as_mainfile(filepath=out, compress=True)
'''
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
check = importlib.util.module_from_spec(spec)
spec.loader.exec_module(check)
tmp = tempfile.mkdtemp(prefix="formats-docs-blend-")
try:
script = os.path.join(tmp, "make.py")
with open(script, "w") as f:
f.write(SCRIPT)
out = os.path.join(tmp, "rig.blend")
exe = shutil.which("blender")
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#blender", "-c", "blender"]
env = dict(os.environ)
env.pop("LD_LIBRARY_PATH", None)
subprocess.run(cmd + ["-b", "--factory-startup", "--python", script, "--", out], capture_output=True, check=True, timeout=900, env=env)
files = {"rig.blend": open(out, "rb").read()}
finally:
shutil.rmtree(tmp, ignore_errors=True)
check.emit_inputs(ctx, files, {"riggedBlendBytes": "rig.blend"})