merge ws/3d2
This commit is contained in:
commit
7c59c12348
45 files changed
+16368
-2
No files matched your search
@@ -27,12 +27,17 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` |
|
||||
| audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` |
|
||||
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
|
||||
| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` |
|
||||
| model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` |
|
||||
| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` |
|
||||
| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` |
|
||||
| model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` |
|
||||
| model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` |
|
||||
| model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` |
|
||||
| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` |
|
||||
| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` |
|
||||
| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
|
||||
| cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` |
|
||||
| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` |
|
||||
| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
|
||||
| font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` |
|
||||
|
||||
@@ -278,6 +278,42 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/wav")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "3mf",
|
||||
category = "model",
|
||||
path = "model/3mf",
|
||||
extensions = { "3mf" },
|
||||
mime = { "model/3mf" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" },
|
||||
caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true },
|
||||
load = function()
|
||||
return require("@formats/model/3mf")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "dae",
|
||||
category = "model",
|
||||
path = "model/dae",
|
||||
extensions = { "dae", "zae" },
|
||||
mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Base64", "containers/Zip" },
|
||||
caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true },
|
||||
load = function()
|
||||
return require("@formats/model/dae")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "fbx",
|
||||
category = "model",
|
||||
path = "model/fbx",
|
||||
extensions = { "fbx" },
|
||||
mime = { "application/vnd.autodesk.fbx", "model/fbx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" },
|
||||
caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true },
|
||||
load = function()
|
||||
return require("@formats/model/fbx")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "gltf",
|
||||
category = "model",
|
||||
@@ -338,6 +374,18 @@ local list: { Entry } = {
|
||||
return require("@formats/model/stl")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "usda",
|
||||
category = "model",
|
||||
path = "model/usda",
|
||||
extensions = { "usda", "usd", "usdz" },
|
||||
mime = { "model/vnd.usda", "model/vnd.usdz+zip" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" },
|
||||
caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false },
|
||||
load = function()
|
||||
return require("@formats/model/usda")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "vox",
|
||||
category = "model",
|
||||
@@ -350,6 +398,18 @@ local list: { Entry } = {
|
||||
return require("@formats/model/vox")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "step",
|
||||
category = "cad",
|
||||
path = "cad/step",
|
||||
extensions = { "step", "stp", "p21" },
|
||||
mime = { "model/step", "application/step", "application/p21" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" },
|
||||
load = function()
|
||||
return require("@formats/cad/step")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "bmfont",
|
||||
category = "font",
|
||||
|
||||
@@ -562,7 +562,9 @@ end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Cad
|
||||
-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep)
|
||||
export type StepEntity = { id: number, type: string, args: { any } }
|
||||
-- complex (external mapping) instances: type = "COMPLEX", args = {}, parts = { { type, args } } in file order;
|
||||
-- section = the DATA section index when a file has more than one (edition 3)
|
||||
export type StepEntity = { id: number, type: string, args: { any }, parts: { { type: string, args: { any } } }?, section: number? }
|
||||
export type Cad = {
|
||||
kind: "cad",
|
||||
schema: string, -- "AP203", "AP214", "AP242", ...
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
--!strict
|
||||
-- cad/step/Brep: the injected B-rep plug-in (Formats.plugins.brep; formats-luau never requires a kernel). Normalises
|
||||
-- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a
|
||||
-- Scene. Interpreted on purpose: the plug-in's errors unwind through here.
|
||||
--
|
||||
-- The interface (every function may throw; results are checked):
|
||||
-- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?,
|
||||
-- body.color? = Color3 | { r, g, b } | { 1, 2, 3 })
|
||||
-- write(bodies: { Body }, opts) -> string bodies -> STEP text
|
||||
-- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based
|
||||
-- triples }, faceOf = { [triangle] = Face (face.color?) }? }
|
||||
-- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read =
|
||||
-- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Brep = {}
|
||||
|
||||
export type Plugin = {
|
||||
read: (text: string, opts: any) -> any,
|
||||
write: ((bodies: { any }, opts: any) -> string)?,
|
||||
tessellate: ((body: any, opts: any) -> any)?,
|
||||
}
|
||||
|
||||
local function rgbOf(c: any): (number?, number?, number?)
|
||||
if c == nil then
|
||||
return nil, nil, nil
|
||||
end
|
||||
local ok, r, g, b = pcall(function(): (any, any, any)
|
||||
if type(c) == "table" then
|
||||
return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3]
|
||||
end
|
||||
return (c :: any).R, (c :: any).G, (c :: any).B -- Color3
|
||||
end)
|
||||
if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then
|
||||
return r, g, b
|
||||
end
|
||||
return nil, nil, nil
|
||||
end
|
||||
|
||||
-- plugin(p) -> the normalised interface, or nil + the reason
|
||||
function Brep.plugin(p: any): (Plugin?, string?)
|
||||
if type(p) ~= "table" then
|
||||
return nil, "needs the B-rep plug-in (Formats.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })"
|
||||
end
|
||||
if type(p.read) == "function" then
|
||||
return {
|
||||
read = p.read,
|
||||
write = if type(p.write) == "function" then p.write else nil,
|
||||
tessellate = if type(p.tessellate) == "function" then p.tessellate else nil,
|
||||
}, nil
|
||||
end
|
||||
local S, SB, SW, Tess = p.Step, p.StepBrep, p.StepWrite, p.Tess
|
||||
if type(S) == "table" and type(SB) == "table" and type(S.parse) == "function" and type(SB.read) == "function" then
|
||||
return {
|
||||
read = function(text: string, opts: any): any
|
||||
return SB.read(S.parse(text), opts)
|
||||
end,
|
||||
write = if type(SW) == "table" and type(SW.write) == "function"
|
||||
then function(bodies: { any }, opts: any): string
|
||||
local o = if type(opts) == "table" then table.clone(opts) else {}
|
||||
if o.colors == nil then
|
||||
local colors = {}
|
||||
for i, b in bodies do
|
||||
local r, g, bl = rgbOf(type(b) == "table" and b.color or nil)
|
||||
if r then
|
||||
colors[i] = { r, g, bl }
|
||||
end
|
||||
end
|
||||
o.colors = colors
|
||||
end
|
||||
return SW.write(bodies, o)
|
||||
end
|
||||
else nil,
|
||||
tessellate = if type(Tess) == "table" and type(Tess.body) == "function"
|
||||
then function(body: any, opts: any): any
|
||||
return Tess.body(body, opts)
|
||||
end
|
||||
else nil,
|
||||
}, nil
|
||||
end
|
||||
return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules"
|
||||
end
|
||||
|
||||
-- find(opts) -> the plug-in from opts.brep or opts.plugins.brep
|
||||
function Brep.find(opts: any): (Plugin?, Err.Err?)
|
||||
local p = nil
|
||||
if type(opts) == "table" then
|
||||
p = opts.brep
|
||||
if p == nil and type(opts.plugins) == "table" then
|
||||
p = opts.plugins.brep
|
||||
end
|
||||
end
|
||||
local plug, why = Brep.plugin(p)
|
||||
if not plug then
|
||||
return nil, Err.new(Err.UNSUPPORTED, why :: string)
|
||||
end
|
||||
return plug, nil
|
||||
end
|
||||
|
||||
-- read(plug, text, opts) -> bodies, result | nil, Err
|
||||
function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?)
|
||||
local ok, res = pcall(plug.read, text, opts)
|
||||
if not ok then
|
||||
return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to read: " .. tostring(res))
|
||||
end
|
||||
if type(res) ~= "table" or type(res.bodies) ~= "table" then
|
||||
return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in's read returned no bodies")
|
||||
end
|
||||
return res.bodies, res, nil
|
||||
end
|
||||
|
||||
-- write(plug, bodies, opts) -> text | nil, Err
|
||||
function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?)
|
||||
local w = plug.write
|
||||
if not w then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no write()")
|
||||
end
|
||||
local ok, res = pcall(w, bodies, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "the B-rep plug-in failed to write: " .. tostring(res))
|
||||
end
|
||||
if type(res) ~= "string" then
|
||||
return nil, Err.new(Err.ARG, "the B-rep plug-in's write returned no text")
|
||||
end
|
||||
return res, nil
|
||||
end
|
||||
|
||||
local function xyz(p: any): (number, number, number)
|
||||
if type(p) == "table" then
|
||||
return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0
|
||||
end
|
||||
return (p :: any).X, (p :: any).Y, (p :: any).Z -- vector / Vector3
|
||||
end
|
||||
|
||||
local function linear(c: number): number
|
||||
c = math.clamp(c, 0, 1)
|
||||
return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4
|
||||
end
|
||||
|
||||
-- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by
|
||||
-- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written)
|
||||
function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?)
|
||||
local tess = plug.tessellate
|
||||
if not tess then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no tessellate()")
|
||||
end
|
||||
local scene = Types.Scene.new()
|
||||
scene.meta.up = "z"
|
||||
scene.meta.unit = 0.001
|
||||
local tessOpts = if type(opts) == "table" and type(opts.tess) == "table"
|
||||
then opts.tess
|
||||
else { chord = if type(opts) == "table" and type(opts.chord) == "number" then opts.chord else 0.05 }
|
||||
local matByKey: { [string]: number } = {}
|
||||
local function material(r: number?, g: number?, b: number?): number
|
||||
local key = if r then string.format("%.6f,%.6f,%.6f", r, g :: number, b :: number) else "default"
|
||||
local m = matByKey[key]
|
||||
if m then
|
||||
return m
|
||||
end
|
||||
local mat = Types.Scene.material(if r then "step_" .. #scene.materials + 1 else "default")
|
||||
if r then
|
||||
mat.baseColor = { linear(r), linear(g :: number), linear(b :: number), 1 }
|
||||
mat.extras = { color = { r, g, b } }
|
||||
else
|
||||
mat.baseColor = { 0.6, 0.6, 0.6, 1 }
|
||||
end
|
||||
mat.metallic, mat.roughness = 0, 0.5
|
||||
table.insert(scene.materials, mat)
|
||||
matByKey[key] = #scene.materials
|
||||
return #scene.materials
|
||||
end
|
||||
for bi, body in bodies do
|
||||
local ok, mesh = pcall(tess, body, tessOpts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to tessellate body " .. bi .. ": " .. tostring(mesh))
|
||||
end
|
||||
if type(mesh) ~= "table" or type(mesh.positions) ~= "table" or type(mesh.indices) ~= "table" then
|
||||
return nil, Err.new(Err.CORRUPT, "the B-rep plug-in's tessellate returned no mesh")
|
||||
end
|
||||
local cok, prims = pcall(function(): { Types.Primitive }
|
||||
local P, N, I = mesh.positions, mesh.normals, mesh.indices
|
||||
local nv = #P
|
||||
local pos = Types.Scene.accessor(nil, "f32", 3, nv)
|
||||
local nrm = if type(N) == "table" and #N == nv then Types.Scene.accessor(nil, "f32", 3, nv) else nil
|
||||
for i = 1, nv do
|
||||
local x, y, z = xyz(P[i])
|
||||
buffer.writef32(pos.data, (i - 1) * 12, x)
|
||||
buffer.writef32(pos.data, (i - 1) * 12 + 4, y)
|
||||
buffer.writef32(pos.data, (i - 1) * 12 + 8, z)
|
||||
if nrm then
|
||||
local a, b, c = xyz(N[i])
|
||||
buffer.writef32(nrm.data, (i - 1) * 12, a)
|
||||
buffer.writef32(nrm.data, (i - 1) * 12 + 4, b)
|
||||
buffer.writef32(nrm.data, (i - 1) * 12 + 8, c)
|
||||
end
|
||||
end
|
||||
local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil)
|
||||
-- triangles grouped by colour, in first-seen order
|
||||
local groups: { { mat: number, tris: { number } } } = {}
|
||||
local byMat: { [number]: { mat: number, tris: { number } } } = {}
|
||||
local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {}
|
||||
local nt = #I // 3
|
||||
for t = 1, nt do
|
||||
local f = faceOf[t]
|
||||
local r, g, b = rgbOf(type(f) == "table" and f.color or nil)
|
||||
if not r then
|
||||
r, g, b = br, bg, bb
|
||||
end
|
||||
local m = material(r, g, b)
|
||||
local grp = byMat[m]
|
||||
if not grp then
|
||||
grp = { mat = m, tris = {} }
|
||||
byMat[m] = grp
|
||||
table.insert(groups, grp)
|
||||
end
|
||||
table.insert(grp.tris, t)
|
||||
end
|
||||
local out: { Types.Primitive } = {}
|
||||
for _, grp in groups do
|
||||
local idx = Types.Scene.accessor(nil, "u32", 1, #grp.tris * 3)
|
||||
for k, t in grp.tris do
|
||||
for c = 0, 2 do
|
||||
local v = (tonumber(I[(t - 1) * 3 + c + 1]) or 1) - 1
|
||||
buffer.writeu32(idx.data, ((k - 1) * 3 + c) * 4, math.clamp(v, 0, math.max(nv - 1, 0)))
|
||||
end
|
||||
end
|
||||
local attrs: { [string]: Types.Accessor } = { POSITION = pos }
|
||||
if nrm then
|
||||
attrs.NORMAL = nrm
|
||||
end
|
||||
table.insert(out, { attributes = attrs, indices = idx, mode = "triangles" :: any, material = grp.mat })
|
||||
end
|
||||
return out
|
||||
end)
|
||||
if not cok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad tessellation of body " .. bi .. ": " .. tostring(prims))
|
||||
end
|
||||
local name = if type(body) == "table" and type(body.name) == "string" then body.name else "body_" .. bi
|
||||
table.insert(scene.meshes, { name = name, primitives = prims })
|
||||
table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes })
|
||||
table.insert(scene.roots, #scene.nodes)
|
||||
end
|
||||
scene.meta.source = { format = "step", tessellated = true, bodies = #bodies }
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Brep
|
||||
@@ -0,0 +1,573 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass
|
||||
-- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`),
|
||||
-- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every
|
||||
-- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary,
|
||||
-- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset.
|
||||
--
|
||||
-- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v };
|
||||
-- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`)
|
||||
-- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so
|
||||
-- the writer prints it back as a real; integral numbers without that mark are written as integers.
|
||||
local Parse = {}
|
||||
|
||||
local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor
|
||||
|
||||
local MAX_DEPTH = 100
|
||||
|
||||
export type Ctx = {
|
||||
s: string,
|
||||
n: number,
|
||||
err: string?,
|
||||
errAt: number?,
|
||||
null: any,
|
||||
derived: any,
|
||||
}
|
||||
|
||||
local function fail(ctx: Ctx, msg: string, at: number): nil
|
||||
if not ctx.err then
|
||||
ctx.err, ctx.errAt = msg, at
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error)
|
||||
local function skip(ctx: Ctx, i: number): number
|
||||
local s, n = ctx.s, ctx.n
|
||||
while i <= n do
|
||||
local c = sbyte(s, i)
|
||||
if c == 32 or c == 10 or c == 13 or c == 9 or c == 12 then
|
||||
i += 1
|
||||
elseif c == 47 and sbyte(s, i + 1) == 42 then
|
||||
local _, e = sfind(s, "*/", i + 2, true)
|
||||
if not e then
|
||||
fail(ctx, "unterminated comment", i)
|
||||
return n + 1
|
||||
end
|
||||
i = e + 1
|
||||
else
|
||||
return i
|
||||
end
|
||||
end
|
||||
return i
|
||||
end
|
||||
|
||||
local function isAlpha(c: number): boolean
|
||||
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
|
||||
end
|
||||
local function isWord(c: number): boolean
|
||||
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57)
|
||||
end
|
||||
|
||||
-- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none
|
||||
local function keyword(ctx: Ctx, i: number): (string?, number)
|
||||
local s, n = ctx.s, ctx.n
|
||||
local j = i
|
||||
if j <= n and sbyte(s, j) == 33 then -- '!' user-defined
|
||||
j += 1
|
||||
end
|
||||
if j > n or not isAlpha(sbyte(s, j) :: number) then
|
||||
return nil, i
|
||||
end
|
||||
j += 1
|
||||
while j <= n and isWord(sbyte(s, j) :: number) do
|
||||
j += 1
|
||||
end
|
||||
return string.upper(ssub(s, i, j - 1)), j
|
||||
end
|
||||
|
||||
-- UTF-8 of a code point
|
||||
local function utf8char(cp: number): string
|
||||
if cp < 0x80 then
|
||||
return schar(cp)
|
||||
elseif cp < 0x800 then
|
||||
return schar(0xC0 + floor(cp / 64), 0x80 + cp % 64)
|
||||
elseif cp < 0x10000 then
|
||||
return schar(0xE0 + floor(cp / 4096), 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64)
|
||||
elseif cp < 0x110000 then
|
||||
return schar(0xF0 + floor(cp / 262144), 0x80 + floor(cp / 4096) % 64, 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64)
|
||||
end
|
||||
return "\239\191\189"
|
||||
end
|
||||
Parse.utf8char = utf8char
|
||||
|
||||
local function hexAt(s: string, i: number, k: number): number?
|
||||
local h = ssub(s, i, i + k - 1)
|
||||
if #h ~= k or sfind(h, "[^%x]") then
|
||||
return nil
|
||||
end
|
||||
return tonumber(h, 16)
|
||||
end
|
||||
|
||||
-- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\,
|
||||
-- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed)
|
||||
-- pass through.
|
||||
function Parse.unescape(raw: string): string
|
||||
if not sfind(raw, "[\\']") then
|
||||
return raw
|
||||
end
|
||||
local out = {}
|
||||
local i, n = 1, #raw
|
||||
local plain = 1
|
||||
while i <= n do
|
||||
local c = sbyte(raw, i)
|
||||
if c == 39 then -- '' -> '
|
||||
table.insert(out, ssub(raw, plain, i))
|
||||
i += 2
|
||||
plain = i
|
||||
elseif c == 92 then
|
||||
table.insert(out, ssub(raw, plain, i - 1))
|
||||
local d = sbyte(raw, i + 1)
|
||||
if d == 92 then
|
||||
table.insert(out, "\\")
|
||||
i += 2
|
||||
elseif d == 83 and sbyte(raw, i + 2) == 92 and i + 3 <= n then -- \S\c
|
||||
table.insert(out, utf8char(((sbyte(raw, i + 3) :: number) + 128) % 256))
|
||||
i += 4
|
||||
elseif d == 80 and sbyte(raw, i + 3) == 92 then -- \P?\ code page
|
||||
i += 4
|
||||
elseif d == 88 and sbyte(raw, i + 2) == 92 then -- \X\hh
|
||||
local h = hexAt(raw, i + 3, 2)
|
||||
if h then
|
||||
table.insert(out, utf8char(h))
|
||||
i += 5
|
||||
else
|
||||
table.insert(out, "\\")
|
||||
i += 1
|
||||
end
|
||||
elseif d == 88 and (sbyte(raw, i + 2) == 50 or sbyte(raw, i + 2) == 52) and sbyte(raw, i + 3) == 92 then
|
||||
local k = if sbyte(raw, i + 2) == 50 then 4 else 8
|
||||
local j = i + 4
|
||||
local hi: number? = nil
|
||||
while j <= n do
|
||||
if sbyte(raw, j) == 92 then
|
||||
break
|
||||
end
|
||||
local cp = hexAt(raw, j, k)
|
||||
if not cp then
|
||||
break
|
||||
end
|
||||
if k == 4 and cp >= 0xD800 and cp < 0xDC00 then
|
||||
hi = cp
|
||||
elseif k == 4 and hi and cp >= 0xDC00 and cp < 0xE000 then
|
||||
table.insert(out, utf8char(0x10000 + (hi - 0xD800) * 1024 + (cp - 0xDC00)))
|
||||
hi = nil
|
||||
else
|
||||
table.insert(out, utf8char(cp))
|
||||
hi = nil
|
||||
end
|
||||
j += k
|
||||
end
|
||||
if ssub(raw, j, j + 3) == "\\X0\\" then
|
||||
j += 4
|
||||
end
|
||||
i = j
|
||||
else
|
||||
table.insert(out, "\\")
|
||||
i += 1
|
||||
end
|
||||
plain = i
|
||||
else
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
table.insert(out, ssub(raw, plain, n))
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local function markReal(t: { [any]: any }, key: any)
|
||||
local mt: any = getmetatable(t)
|
||||
if not mt then
|
||||
mt = { __reals = {} }
|
||||
setmetatable(t, mt)
|
||||
end
|
||||
mt.__reals[key] = true
|
||||
end
|
||||
|
||||
-- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure)
|
||||
local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean)
|
||||
|
||||
local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number)
|
||||
-- i is just past "("
|
||||
local s = ctx.s
|
||||
local out = {}
|
||||
i = skip(ctx, i)
|
||||
if sbyte(s, i) == 41 then
|
||||
return out, i + 1
|
||||
end
|
||||
local k = 0
|
||||
while true do
|
||||
local v, j, intReal = value(ctx, i, depth + 1)
|
||||
if v == nil then
|
||||
return nil, j
|
||||
end
|
||||
k += 1
|
||||
out[k] = v
|
||||
if intReal then
|
||||
markReal(out, k)
|
||||
end
|
||||
j = skip(ctx, j)
|
||||
local c = sbyte(s, j)
|
||||
if c == 44 then
|
||||
i = skip(ctx, j + 1)
|
||||
elseif c == 41 then
|
||||
return out, j + 1
|
||||
elseif c == nil then
|
||||
return fail(ctx, "truncated list", j), j
|
||||
else
|
||||
return fail(ctx, "expected , or ) in a list", j), j
|
||||
end
|
||||
end
|
||||
end
|
||||
Parse.list = list
|
||||
|
||||
value = function(ctx: Ctx, i: number, depth: number): (any, number, boolean)
|
||||
if depth > MAX_DEPTH then
|
||||
return fail(ctx, "lists nested too deeply", i), i, false
|
||||
end
|
||||
local s = ctx.s
|
||||
i = skip(ctx, i)
|
||||
local c = sbyte(s, i)
|
||||
if c == nil then
|
||||
return fail(ctx, "truncated parameter", i), i, false
|
||||
elseif c == 35 then -- #ref
|
||||
local _, e = sfind(s, "^%d+", i + 1)
|
||||
if not e then
|
||||
return fail(ctx, "bad entity reference", i), i, false
|
||||
end
|
||||
return { ref = tonumber(ssub(s, i + 1, e)) }, e + 1, false
|
||||
elseif c == 39 then -- 'string'
|
||||
local j = i + 1
|
||||
while true do
|
||||
local q = sfind(s, "'", j, true)
|
||||
if not q then
|
||||
return fail(ctx, "unterminated string", i), i, false
|
||||
end
|
||||
if sbyte(s, q + 1) == 39 then
|
||||
j = q + 2
|
||||
else
|
||||
return Parse.unescape(ssub(s, i + 1, q - 1)), q + 1, false
|
||||
end
|
||||
end
|
||||
elseif c == 36 then
|
||||
return ctx.null, i + 1, false
|
||||
elseif c == 42 then
|
||||
return ctx.derived, i + 1, false
|
||||
elseif c == 40 then
|
||||
local l, j = list(ctx, i + 1, depth)
|
||||
return l, j, false
|
||||
elseif c == 46 then -- .ENUM.
|
||||
local _, e = sfind(s, "^[%a_][%w_]*%.", i + 1)
|
||||
if not e then
|
||||
return fail(ctx, "bad enumeration", i), i, false
|
||||
end
|
||||
return { enum = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false
|
||||
elseif c == 34 then -- "binary"
|
||||
local _, e = sfind(s, "^[0-3]%x*\"", i + 1)
|
||||
if not e then
|
||||
return fail(ctx, "bad binary literal", i), i, false
|
||||
end
|
||||
return { binary = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false
|
||||
elseif (c >= 48 and c <= 57) or c == 45 or c == 43 then
|
||||
local _, e = sfind(s, "^[+-]?%d*%.?%d*[eE]?[+-]?%d*", i)
|
||||
local tok = ssub(s, i, e :: number)
|
||||
local num = tonumber(if c == 43 then ssub(tok, 2) else tok)
|
||||
if num == nil then
|
||||
-- "1.E" without digits and the like
|
||||
local core = string.match(tok, "^[+-]?%d*%.?%d*")
|
||||
num = core and tonumber(if c == 43 then ssub(core, 2) else core)
|
||||
if num == nil then
|
||||
return fail(ctx, "bad number", i), i, false
|
||||
end
|
||||
e = i + #(core :: string) - 1
|
||||
end
|
||||
local real = sfind(tok, "[.eE]") ~= nil
|
||||
local nv = num :: number
|
||||
return nv, (e :: number) + 1, real and nv == floor(nv) and nv == nv
|
||||
elseif isAlpha(c) or c == 33 then -- typed parameter NAME(value)
|
||||
local word, j = keyword(ctx, i)
|
||||
j = skip(ctx, j)
|
||||
if word == nil or sbyte(s, j) ~= 40 then
|
||||
return fail(ctx, "expected a parameter", i), i, false
|
||||
end
|
||||
local v, k, intReal = value(ctx, j + 1, depth + 1)
|
||||
if v == nil then
|
||||
return nil, k, false
|
||||
end
|
||||
k = skip(ctx, k)
|
||||
if sbyte(s, k) ~= 41 then
|
||||
return fail(ctx, "expected ) after a typed parameter", k), k, false
|
||||
end
|
||||
local t = { typed = word, value = v }
|
||||
if intReal then
|
||||
markReal(t, "value")
|
||||
end
|
||||
return t, k + 1, false
|
||||
end
|
||||
return fail(ctx, "unexpected character " .. string.format("%q", schar(c)), i), i, false
|
||||
end
|
||||
Parse.value = value
|
||||
|
||||
-- the simple record at i: NAME(params) -> type, args, next
|
||||
local function record(ctx: Ctx, i: number): (string?, { any }?, number)
|
||||
local word, j = keyword(ctx, i)
|
||||
if not word then
|
||||
return fail(ctx, "expected an entity name", i), nil, i
|
||||
end
|
||||
j = skip(ctx, j)
|
||||
if sbyte(ctx.s, j) ~= 40 then
|
||||
return fail(ctx, "expected ( after " .. word, j), nil, j
|
||||
end
|
||||
local args, k = list(ctx, j + 1, 0)
|
||||
if not args then
|
||||
return nil, nil, k
|
||||
end
|
||||
return word, args, k
|
||||
end
|
||||
|
||||
-- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil
|
||||
local function expect(ctx: Ctx, i: number, ch: number, what: string): number?
|
||||
i = skip(ctx, i)
|
||||
if sbyte(ctx.s, i) ~= ch then
|
||||
if i > ctx.n then
|
||||
return fail(ctx, "truncated: expected " .. what, i)
|
||||
end
|
||||
return fail(ctx, "expected " .. what, i)
|
||||
end
|
||||
return i + 1
|
||||
end
|
||||
|
||||
local function at(s: string, i: number, word: string): boolean
|
||||
return ssub(s, i, i + #word - 1) == word
|
||||
end
|
||||
|
||||
export type Result = {
|
||||
header: { [string]: { any } },
|
||||
headerOrder: { string },
|
||||
entities: { [number]: any },
|
||||
count: number,
|
||||
sections: { { name: any?, schema: any? } },
|
||||
extra: { { name: string, text: string } },
|
||||
duplicates: number,
|
||||
terminated: boolean,
|
||||
}
|
||||
|
||||
-- parse(s, opts) -> Result | nil, message, offset (1-based position in s)
|
||||
function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?)
|
||||
local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived }
|
||||
local res: Result = {
|
||||
header = {},
|
||||
headerOrder = {},
|
||||
entities = {},
|
||||
count = 0,
|
||||
sections = {},
|
||||
extra = {},
|
||||
duplicates = 0,
|
||||
terminated = false,
|
||||
}
|
||||
local i = skip(ctx, 1)
|
||||
if not at(s, i, "ISO-10303-21") then
|
||||
return nil, "no ISO-10303-21 magic", i
|
||||
end
|
||||
local ni = expect(ctx, i + 12, 59, ";")
|
||||
if not ni then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
i = ni
|
||||
local sawData = false
|
||||
while true do
|
||||
i = skip(ctx, i)
|
||||
if ctx.err then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
if i > ctx.n then
|
||||
if not sawData then
|
||||
return nil, "truncated: no DATA section", i
|
||||
end
|
||||
break
|
||||
end
|
||||
if at(s, i, "END-ISO-10303-21") then
|
||||
res.terminated = true
|
||||
local e = expect(ctx, i + 16, 59, ";")
|
||||
if not e then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
break
|
||||
end
|
||||
local word, j = keyword(ctx, i)
|
||||
if word == "HEADER" then
|
||||
local e = expect(ctx, j, 59, ";")
|
||||
if not e then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
i = e
|
||||
while true do
|
||||
i = skip(ctx, i)
|
||||
if at(s, i, "ENDSEC") then
|
||||
local e2 = expect(ctx, i + 6, 59, ";")
|
||||
if not e2 then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
i = e2
|
||||
break
|
||||
end
|
||||
if i > ctx.n then
|
||||
return nil, "truncated header", i
|
||||
end
|
||||
local t, args, k = record(ctx, i)
|
||||
if not t then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
local e2 = expect(ctx, k, 59, ";")
|
||||
if not e2 then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
if res.header[t] == nil then
|
||||
table.insert(res.headerOrder, t)
|
||||
end
|
||||
res.header[t] = args :: { any }
|
||||
i = e2
|
||||
end
|
||||
elseif word == "DATA" then
|
||||
sawData = true
|
||||
local sec: { name: any?, schema: any? } = {}
|
||||
j = skip(ctx, j)
|
||||
if sbyte(s, j) == 40 then
|
||||
local params, k = list(ctx, j + 1, 0)
|
||||
if not params then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
sec.name, sec.schema = params[1], params[2]
|
||||
j = k
|
||||
end
|
||||
table.insert(res.sections, sec)
|
||||
local secIndex = #res.sections
|
||||
local e = expect(ctx, j, 59, ";")
|
||||
if not e then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
i = e
|
||||
while true do
|
||||
i = skip(ctx, i)
|
||||
if ctx.err then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
local c = sbyte(s, i)
|
||||
if c == nil then
|
||||
return nil, "truncated: the DATA section has no ENDSEC", i
|
||||
end
|
||||
if c ~= 35 then
|
||||
if at(s, i, "ENDSEC") then
|
||||
local e2 = expect(ctx, i + 6, 59, ";")
|
||||
if not e2 then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
i = e2
|
||||
break
|
||||
end
|
||||
return nil, "expected an entity instance (#id = ...)", i
|
||||
end
|
||||
local _, idEnd = sfind(s, "^%d+", i + 1)
|
||||
if not idEnd then
|
||||
return nil, "bad entity instance name", i
|
||||
end
|
||||
local id = tonumber(ssub(s, i + 1, idEnd)) :: number
|
||||
local k = expect(ctx, idEnd + 1, 61, "=")
|
||||
if not k then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
k = skip(ctx, k)
|
||||
local ent: any
|
||||
if sbyte(s, k) == 40 then -- complex instance (A(..) B(..))
|
||||
local parts = {}
|
||||
k = skip(ctx, k + 1)
|
||||
while sbyte(s, k) ~= 41 do
|
||||
if k > ctx.n then
|
||||
return nil, "truncated complex instance", k
|
||||
end
|
||||
local t, args, k2 = record(ctx, k)
|
||||
if not t then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
table.insert(parts, { type = t, args = args })
|
||||
k = skip(ctx, k2)
|
||||
end
|
||||
if #parts == 0 then
|
||||
return nil, "empty complex instance", k
|
||||
end
|
||||
ent = { id = id, type = "COMPLEX", args = {}, parts = parts }
|
||||
k += 1
|
||||
else
|
||||
local t, args, k2 = record(ctx, k)
|
||||
if not t then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
ent = { id = id, type = t, args = args }
|
||||
k = k2
|
||||
end
|
||||
local e2 = expect(ctx, k, 59, ";")
|
||||
if not e2 then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
if secIndex > 1 then
|
||||
ent.section = secIndex
|
||||
end
|
||||
if res.entities[id] then
|
||||
res.duplicates += 1
|
||||
else
|
||||
res.count += 1
|
||||
if res.count > maxEntities then
|
||||
return nil, "LIMIT", i
|
||||
end
|
||||
end
|
||||
res.entities[id] = ent
|
||||
i = e2
|
||||
end
|
||||
elseif word == "ANCHOR" or word == "REFERENCE" or word == "SIGNATURE" then
|
||||
-- kept as raw text (to the ENDSEC outside strings)
|
||||
local k = j
|
||||
local stop: number? = nil
|
||||
while k <= ctx.n do
|
||||
local c = sbyte(s, k)
|
||||
if c == 39 then
|
||||
local q = k + 1
|
||||
while true do
|
||||
local p = sfind(s, "'", q, true)
|
||||
if not p then
|
||||
return nil, "unterminated string", k
|
||||
end
|
||||
if sbyte(s, p + 1) == 39 then
|
||||
q = p + 2
|
||||
else
|
||||
k = p + 1
|
||||
break
|
||||
end
|
||||
end
|
||||
elseif c == 69 and at(s, k, "ENDSEC") then
|
||||
stop = k
|
||||
break
|
||||
else
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
if not stop then
|
||||
return nil, "truncated " .. word .. " section", i
|
||||
end
|
||||
table.insert(res.extra, { name = word, text = ssub(s, j, stop - 1) })
|
||||
local e2 = expect(ctx, stop + 6, 59, ";")
|
||||
if not e2 then
|
||||
return nil, ctx.err, ctx.errAt
|
||||
end
|
||||
i = e2
|
||||
else
|
||||
return nil, "unknown section " .. tostring(word), i
|
||||
end
|
||||
end
|
||||
if not sawData then
|
||||
return nil, "no DATA section", i
|
||||
end
|
||||
return res, nil, nil
|
||||
end
|
||||
|
||||
return Parse
|
||||
@@ -0,0 +1,252 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings
|
||||
-- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid
|
||||
-- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws:
|
||||
-- failures return nil, message.
|
||||
local Write = {}
|
||||
|
||||
local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge
|
||||
|
||||
local MAX_DEPTH = 100
|
||||
|
||||
-- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E)
|
||||
function Write.real(v: number): string?
|
||||
if v ~= v or v == huge or v == -huge then
|
||||
return nil
|
||||
end
|
||||
local s = sformat("%.15g", v)
|
||||
if tonumber(s) ~= v then
|
||||
s = sformat("%.16g", v)
|
||||
if tonumber(s) ~= v then
|
||||
s = sformat("%.17g", v)
|
||||
end
|
||||
end
|
||||
s = string.upper(s)
|
||||
local e = sfind(s, "E", 1, true)
|
||||
if not sfind(s, ".", 1, true) then
|
||||
if e then
|
||||
s = ssub(s, 1, e - 1) .. "." .. ssub(s, e)
|
||||
else
|
||||
s ..= "."
|
||||
end
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
local HEX = "0123456789ABCDEF"
|
||||
local function hex(v: number, k: number): string
|
||||
local out = table.create(k)
|
||||
for i = k, 1, -1 do
|
||||
local d = v % 16
|
||||
out[i] = ssub(HEX, d + 1, d + 1)
|
||||
v = floor(v / 16)
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
-- a string's Part 21 literal (with the quotes)
|
||||
function Write.str(s: string): string
|
||||
if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \
|
||||
return "'" .. s .. "'"
|
||||
end
|
||||
local out = { "'" }
|
||||
local i, n = 1, #s
|
||||
local wide: number? = nil -- 4 (\X2\) or 8 (\X4\) while in an extended run
|
||||
local function close()
|
||||
if wide then
|
||||
table.insert(out, "\\X0\\")
|
||||
wide = nil
|
||||
end
|
||||
end
|
||||
while i <= n do
|
||||
local c = sbyte(s, i) :: number
|
||||
if c >= 32 and c < 127 then
|
||||
close()
|
||||
if c == 39 then
|
||||
table.insert(out, "''")
|
||||
elseif c == 92 then
|
||||
table.insert(out, "\\\\")
|
||||
else
|
||||
table.insert(out, string.char(c))
|
||||
end
|
||||
i += 1
|
||||
else
|
||||
-- a UTF-8 sequence -> code point
|
||||
local cp: number? = nil
|
||||
local len = 1
|
||||
if c >= 0xC2 and c < 0xE0 then
|
||||
local c2 = sbyte(s, i + 1)
|
||||
if c2 and c2 >= 0x80 and c2 < 0xC0 then
|
||||
cp, len = (c - 0xC0) * 64 + (c2 - 0x80), 2
|
||||
end
|
||||
elseif c >= 0xE0 and c < 0xF0 then
|
||||
local c2, c3 = sbyte(s, i + 1, i + 2)
|
||||
if c2 and c3 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 then
|
||||
local v = (c - 0xE0) * 4096 + (c2 - 0x80) * 64 + (c3 - 0x80)
|
||||
if v >= 0x800 and (v < 0xD800 or v >= 0xE000) then
|
||||
cp, len = v, 3
|
||||
end
|
||||
end
|
||||
elseif c >= 0xF0 and c < 0xF5 then
|
||||
local c2, c3, c4 = sbyte(s, i + 1, i + 3)
|
||||
if c2 and c3 and c4 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 and c4 >= 0x80 and c4 < 0xC0 then
|
||||
local v = (c - 0xF0) * 262144 + (c2 - 0x80) * 4096 + (c3 - 0x80) * 64 + (c4 - 0x80)
|
||||
if v >= 0x10000 and v < 0x110000 then
|
||||
cp, len = v, 4
|
||||
end
|
||||
end
|
||||
end
|
||||
if cp == nil then
|
||||
close()
|
||||
table.insert(out, "\\X\\" .. hex(c, 2))
|
||||
i += 1
|
||||
else
|
||||
local k = if cp >= 0x10000 then 8 else 4
|
||||
if wide ~= k then
|
||||
close()
|
||||
table.insert(out, if k == 4 then "\\X2\\" else "\\X4\\")
|
||||
wide = k
|
||||
end
|
||||
table.insert(out, hex(cp, k))
|
||||
i += len
|
||||
end
|
||||
end
|
||||
end
|
||||
close()
|
||||
table.insert(out, "'")
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local function isName(s: any): boolean
|
||||
return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil
|
||||
end
|
||||
Write.isName = isName
|
||||
|
||||
export type Ctx = { out: { string }, null: any, derived: any, err: string? }
|
||||
|
||||
local value: (ctx: Ctx, v: any, real: boolean, depth: number) -> boolean
|
||||
|
||||
local function reals(t: any): { [any]: boolean }?
|
||||
local mt = getmetatable(t)
|
||||
return if type(mt) == "table" and type(mt.__reals) == "table" then mt.__reals else nil
|
||||
end
|
||||
|
||||
local function list(ctx: Ctx, t: { any }, depth: number): boolean
|
||||
local out = ctx.out
|
||||
table.insert(out, "(")
|
||||
local marks = reals(t)
|
||||
local n = #t
|
||||
for i = 1, n do
|
||||
if i > 1 then
|
||||
table.insert(out, ",")
|
||||
end
|
||||
if not value(ctx, t[i], marks ~= nil and marks[i] == true, depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
table.insert(out, ")")
|
||||
return true
|
||||
end
|
||||
Write.list = list
|
||||
|
||||
value = function(ctx: Ctx, v: any, real: boolean, depth: number): boolean
|
||||
local out = ctx.out
|
||||
if depth > MAX_DEPTH then
|
||||
ctx.err = "values nested too deeply (or a cycle)"
|
||||
return false
|
||||
end
|
||||
local tv = type(v)
|
||||
if tv == "number" then
|
||||
if not real and v == floor(v) and v > -2 ^ 53 and v < 2 ^ 53 then
|
||||
table.insert(out, sformat("%.0f", v))
|
||||
return true
|
||||
end
|
||||
local r = Write.real(v)
|
||||
if not r then
|
||||
ctx.err = "a number that STEP cannot hold (nan / inf)"
|
||||
return false
|
||||
end
|
||||
table.insert(out, r)
|
||||
return true
|
||||
elseif tv == "string" then
|
||||
table.insert(out, Write.str(v))
|
||||
return true
|
||||
elseif tv == "boolean" then
|
||||
table.insert(out, if v then ".T." else ".F.")
|
||||
return true
|
||||
elseif tv == "table" then
|
||||
if v == ctx.null then
|
||||
table.insert(out, "$")
|
||||
return true
|
||||
elseif v == ctx.derived then
|
||||
table.insert(out, "*")
|
||||
return true
|
||||
end
|
||||
local ref = v.ref
|
||||
if ref ~= nil then
|
||||
if type(ref) ~= "number" or ref ~= floor(ref) or ref < 0 then
|
||||
ctx.err = "bad entity reference " .. tostring(ref)
|
||||
return false
|
||||
end
|
||||
table.insert(out, sformat("#%.0f", ref))
|
||||
return true
|
||||
end
|
||||
local enum = v.enum
|
||||
if enum ~= nil then
|
||||
if type(enum) ~= "string" or not sfind(enum, "^[%a_][%w_]*$") then
|
||||
ctx.err = "bad enumeration " .. tostring(enum)
|
||||
return false
|
||||
end
|
||||
table.insert(out, "." .. string.upper(enum) .. ".")
|
||||
return true
|
||||
end
|
||||
local bin = v.binary
|
||||
if bin ~= nil then
|
||||
if type(bin) ~= "string" or not sfind(bin, "^[0-3]%x*$") then
|
||||
ctx.err = "bad binary literal"
|
||||
return false
|
||||
end
|
||||
table.insert(out, "\"" .. string.upper(bin) .. "\"")
|
||||
return true
|
||||
end
|
||||
local typed = v.typed
|
||||
if typed ~= nil then
|
||||
if not isName(typed) then
|
||||
ctx.err = "bad typed parameter name " .. tostring(typed)
|
||||
return false
|
||||
end
|
||||
if v.value == nil then
|
||||
ctx.err = "typed parameter " .. typed .. " without a value"
|
||||
return false
|
||||
end
|
||||
local marks = reals(v)
|
||||
table.insert(out, string.upper(typed) .. "(")
|
||||
if not value(ctx, v.value, marks ~= nil and marks.value == true, depth + 1) then
|
||||
return false
|
||||
end
|
||||
table.insert(out, ")")
|
||||
return true
|
||||
end
|
||||
return list(ctx, v, depth)
|
||||
end
|
||||
ctx.err = "cannot write a " .. tv .. " value"
|
||||
return false
|
||||
end
|
||||
Write.value = value
|
||||
|
||||
-- record(ctx, type, args) -> appends TYPE(args)
|
||||
function Write.record(ctx: Ctx, t: any, args: any): boolean
|
||||
if not isName(t) then
|
||||
ctx.err = "bad entity type " .. tostring(t)
|
||||
return false
|
||||
end
|
||||
if type(args) ~= "table" then
|
||||
ctx.err = "entity " .. t .. " without an args list"
|
||||
return false
|
||||
end
|
||||
table.insert(ctx.out, string.upper(t))
|
||||
return list(ctx, args, 0)
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,412 @@
|
||||
--!strict
|
||||
-- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema).
|
||||
-- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME /
|
||||
-- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and
|
||||
-- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers;
|
||||
-- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to
|
||||
-- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" },
|
||||
-- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE /
|
||||
-- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same
|
||||
-- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII).
|
||||
--
|
||||
-- B-rep bodies and tessellation come from an injected kernel, never required by formats-luau:
|
||||
-- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text,
|
||||
-- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } }
|
||||
-- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = }
|
||||
-- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) /
|
||||
-- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies /
|
||||
-- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up,
|
||||
-- millimetres (meta.unit = 0.001).
|
||||
-- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT),
|
||||
-- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Parse = require("@formats/cad/step/Parse")
|
||||
local Write = require("@formats/cad/step/Write")
|
||||
local Brep = require("@formats/cad/step/Brep")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Step = {
|
||||
name = "step",
|
||||
category = "cad",
|
||||
extensions = { "step", "stp", "p21" },
|
||||
mime = { "model/step", "application/step", "application/p21" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse larger files (default 2^30)
|
||||
maxEntities: number?, -- refuse more instances (default 2^24)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
schema: string?, -- "AP203" | "AP214" | "AP242" | a schema name: overrides the header's FILE_SCHEMA
|
||||
name: string?, -- FILE_NAME name (default: the header's, else "model")
|
||||
timestamp: string?, -- FILE_NAME time_stamp when the header has none (default "1970-01-01T00:00:00")
|
||||
crlf: boolean?, -- CRLF line ends (default LF)
|
||||
}
|
||||
export type BrepOptions = {
|
||||
brep: any?, -- the plug-in (else opts.plugins.brep)
|
||||
plugins: { [string]: any }?,
|
||||
chord: number?, -- tessellation sag in millimetres (default 0.05); opts.tess = the kernel's own options instead
|
||||
tess: { [string]: any }?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
Step.NULL = table.freeze({ null = true }) -- $
|
||||
Step.DERIVED = table.freeze({ derived = true }) -- *
|
||||
|
||||
local SCHEMAS = {
|
||||
AP203 = "CONFIG_CONTROL_DESIGN",
|
||||
AP214 = "AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }",
|
||||
AP242 = "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }",
|
||||
}
|
||||
Step.SCHEMAS = SCHEMAS
|
||||
|
||||
-- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself
|
||||
local function schemaOf(name: string): string
|
||||
local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name)
|
||||
if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then
|
||||
return "AP203"
|
||||
elseif n == "AUTOMOTIVE_DESIGN" or n == "AUTOMOTIVE_DESIGN_CC2" or string.find(n, "^AP214") then
|
||||
return "AP214"
|
||||
elseif string.find(n, "^AP242") then
|
||||
return "AP242"
|
||||
end
|
||||
return n
|
||||
end
|
||||
Step.schemaOf = schemaOf
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Step.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(256)
|
||||
if string.sub(head, 1, 3) == "\239\187\191" then
|
||||
head = string.sub(head, 4)
|
||||
end
|
||||
head = string.gsub(head, "^%s*/%*.-%*/", "")
|
||||
if string.find(head, "^%s*ISO%-10303%-21%s*;") then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Step.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Cad?, Err.Err?)
|
||||
local size = r.limit - r.base
|
||||
if size > (opts and opts.maxBytes or 2 ^ 30) then
|
||||
return nil, Err.new(Err.LIMIT, "file over maxBytes")
|
||||
end
|
||||
local s = buffer.readstring(r.buf, r.base, size)
|
||||
local bom = 0
|
||||
if string.sub(s, 1, 3) == "\239\187\191" then
|
||||
s = string.sub(s, 4)
|
||||
bom = 3
|
||||
end
|
||||
local res, msg, at = Parse.parse(s, Step.NULL, Step.DERIVED, opts and opts.maxEntities or 2 ^ 24)
|
||||
if not res then
|
||||
local off = if at then r.base + bom + at - 1 else nil
|
||||
if msg == "LIMIT" then
|
||||
return nil, Err.new(Err.LIMIT, "more entity instances than maxEntities", off)
|
||||
end
|
||||
local m = msg or "parse error"
|
||||
if string.find(m, "^truncated") or string.find(m, "^unterminated") or (at and at > #s) then
|
||||
return nil, Err.new(Err.TRUNCATED, m, off)
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, m, off)
|
||||
end
|
||||
local fs = res.header.FILE_SCHEMA
|
||||
local schemaName = if fs and type(fs[1]) == "table" and type(fs[1][1]) == "string" then fs[1][1] else ""
|
||||
local cad: Types.Cad = {
|
||||
kind = "cad",
|
||||
schema = if schemaName ~= "" then schemaOf(schemaName) else "unknown",
|
||||
header = res.header,
|
||||
entities = res.entities,
|
||||
meta = {
|
||||
count = res.count,
|
||||
headerOrder = res.headerOrder,
|
||||
source = {
|
||||
format = "step",
|
||||
schemaName = schemaName,
|
||||
sections = res.sections,
|
||||
extra = if #res.extra > 0 then res.extra else nil,
|
||||
duplicates = if res.duplicates > 0 then res.duplicates else nil,
|
||||
terminated = res.terminated,
|
||||
},
|
||||
},
|
||||
}
|
||||
return cad, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function headerArgs(cad: Types.Cad, o: EncodeOptions): { [string]: { any } }
|
||||
local h = if type(cad.header) == "table" then cad.header else {}
|
||||
local out: { [string]: { any } } = {}
|
||||
for k, v in h do
|
||||
out[k] = v
|
||||
end
|
||||
if type(out.FILE_DESCRIPTION) ~= "table" then
|
||||
out.FILE_DESCRIPTION = { { "formats-luau" }, "2;1" }
|
||||
end
|
||||
if type(out.FILE_NAME) ~= "table" then
|
||||
out.FILE_NAME = { o.name or "model", o.timestamp or "1970-01-01T00:00:00", { "" }, { "" }, "formats-luau", "formats-luau", "" }
|
||||
end
|
||||
local schema = o.schema or (if type(out.FILE_SCHEMA) ~= "table" then cad.schema else nil)
|
||||
if schema then
|
||||
out.FILE_SCHEMA = { { SCHEMAS[schema] or schema } }
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a Cad (kind = \"cad\", entities)")
|
||||
end
|
||||
local o: EncodeOptions = opts or {}
|
||||
local nl = if o.crlf then "\r\n" else "\n"
|
||||
local ctx: Write.Ctx = { out = {}, null = Step.NULL, derived = Step.DERIVED, err = nil }
|
||||
local out = ctx.out
|
||||
table.insert(out, "ISO-10303-21;" .. nl .. "HEADER;" .. nl)
|
||||
local header = headerArgs(cad, o)
|
||||
local order = { "FILE_DESCRIPTION", "FILE_NAME", "FILE_SCHEMA" }
|
||||
local seen = { FILE_DESCRIPTION = true, FILE_NAME = true, FILE_SCHEMA = true }
|
||||
local meta: any = if type(cad.meta) == "table" then cad.meta else {}
|
||||
local rest = {}
|
||||
for _, k in (if type(meta.headerOrder) == "table" then meta.headerOrder else {}) do
|
||||
if type(k) == "string" and header[k] and not seen[k] then
|
||||
seen[k] = true
|
||||
table.insert(order, k)
|
||||
end
|
||||
end
|
||||
for k in header do
|
||||
if type(k) == "string" and not seen[k] then
|
||||
table.insert(rest, k)
|
||||
end
|
||||
end
|
||||
table.sort(rest)
|
||||
for _, k in rest do
|
||||
table.insert(order, k)
|
||||
end
|
||||
for _, k in order do
|
||||
if not Write.record(ctx, k, header[k]) then
|
||||
return nil, Err.new(Err.ARG, "header " .. tostring(k) .. ": " .. tostring(ctx.err))
|
||||
end
|
||||
table.insert(out, ";" .. nl)
|
||||
end
|
||||
table.insert(out, "ENDSEC;" .. nl)
|
||||
local source = if type(meta.source) == "table" then meta.source else {}
|
||||
if type(source.extra) == "table" then
|
||||
for _, x in source.extra do
|
||||
if type(x) == "table" and type(x.name) == "string" and type(x.text) == "string" then
|
||||
table.insert(out, x.name .. x.text .. "ENDSEC;" .. nl)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- entities by section, in id order
|
||||
local ids = {}
|
||||
for id, e in cad.entities do
|
||||
if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "entity ids must be non-negative integers (" .. tostring(id) .. ")")
|
||||
end
|
||||
table.insert(ids, id)
|
||||
end
|
||||
table.sort(ids)
|
||||
local sections = if type(source.sections) == "table" and #source.sections > 1 then source.sections else { {} }
|
||||
for si, sec in sections do
|
||||
if #sections > 1 then
|
||||
table.insert(out, "DATA")
|
||||
local params = {}
|
||||
if sec.name ~= nil then
|
||||
params[1] = sec.name
|
||||
params[2] = if sec.schema ~= nil then sec.schema else {}
|
||||
if not Write.list(ctx, params, 0) then
|
||||
return nil, Err.new(Err.ARG, "section " .. si .. ": " .. tostring(ctx.err))
|
||||
end
|
||||
end
|
||||
table.insert(out, ";" .. nl)
|
||||
else
|
||||
table.insert(out, "DATA;" .. nl)
|
||||
end
|
||||
for _, id in ids do
|
||||
local e: any = cad.entities[id]
|
||||
local esec = if type(e.section) == "number" then e.section else 1
|
||||
if #sections == 1 or esec == si or (si == 1 and (esec < 1 or esec > #sections)) then
|
||||
table.insert(out, string.format("#%.0f=", id))
|
||||
if e.type == "COMPLEX" or type(e.parts) == "table" then
|
||||
if type(e.parts) ~= "table" or #e.parts == 0 then
|
||||
return nil, Err.new(Err.ARG, "#" .. id .. ": a complex instance without parts")
|
||||
end
|
||||
table.insert(out, "(")
|
||||
for _, p in e.parts do
|
||||
if type(p) ~= "table" or not Write.record(ctx, p.type, p.args) then
|
||||
return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err or "bad part"))
|
||||
end
|
||||
end
|
||||
table.insert(out, ")")
|
||||
elseif not Write.record(ctx, e.type, e.args) then
|
||||
return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err))
|
||||
end
|
||||
table.insert(out, ";" .. nl)
|
||||
end
|
||||
end
|
||||
table.insert(out, "ENDSEC;" .. nl)
|
||||
end
|
||||
table.insert(out, "END-ISO-10303-21;" .. nl)
|
||||
return buffer.fromstring(table.concat(out)), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- get(cad, id | { ref = id }) -> the entity
|
||||
function Step.get(cad: Types.Cad, id: any): Types.StepEntity?
|
||||
if type(id) == "table" then
|
||||
id = id.ref
|
||||
end
|
||||
return cad.entities[id]
|
||||
end
|
||||
|
||||
-- ids(cad) -> the instance ids in ascending order
|
||||
function Step.ids(cad: Types.Cad): { number }
|
||||
local out = {}
|
||||
for id in cad.entities do
|
||||
table.insert(out, id)
|
||||
end
|
||||
table.sort(out)
|
||||
return out
|
||||
end
|
||||
|
||||
-- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending
|
||||
function Step.byType(cad: Types.Cad, name: string): { number }
|
||||
local n = string.upper(name)
|
||||
local out = {}
|
||||
for id, e in cad.entities do
|
||||
if e.type == n then
|
||||
table.insert(out, id)
|
||||
elseif e.parts then
|
||||
for _, p in e.parts do
|
||||
if p.type == n then
|
||||
table.insert(out, id)
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(out)
|
||||
return out
|
||||
end
|
||||
|
||||
-- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance)
|
||||
function Step.part(e: Types.StepEntity?, name: string): { any }?
|
||||
if not e then
|
||||
return nil
|
||||
end
|
||||
if e.type == name then
|
||||
return e.args
|
||||
end
|
||||
if e.parts then
|
||||
for _, p in e.parts do
|
||||
if p.type == name then
|
||||
return p.args
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- add(cad, type, args) -> id: a new instance after the highest id
|
||||
function Step.add(cad: Types.Cad, type: string, args: { any }): number
|
||||
local top = 0
|
||||
for id in cad.entities do
|
||||
if id > top then
|
||||
top = id
|
||||
end
|
||||
end
|
||||
local id = top + 1
|
||||
cad.entities[id] = { id = id, type = string.upper(type), args = args }
|
||||
cad.meta.count = (cad.meta.count or 0) + 1
|
||||
return id
|
||||
end
|
||||
|
||||
-- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`)
|
||||
function Step.real(t: { [any]: any }, key: any): { [any]: any }
|
||||
local mt: any = getmetatable(t)
|
||||
if not mt then
|
||||
mt = { __reals = {} }
|
||||
setmetatable(t, mt)
|
||||
end
|
||||
mt.__reals[key] = true
|
||||
return t
|
||||
end
|
||||
|
||||
-- new(schema?) -> an empty Cad ("AP214" by default)
|
||||
function Step.new(schema: string?): Types.Cad
|
||||
return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } }
|
||||
end
|
||||
|
||||
-- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason
|
||||
Step.plugin = Brep.plugin
|
||||
|
||||
local function textOf(cad: Types.Cad): (string?, Err.Err?)
|
||||
local buf, err = Step.encode(cad)
|
||||
if not buf then
|
||||
return nil, err
|
||||
end
|
||||
return buffer.tostring(buf), nil
|
||||
end
|
||||
|
||||
-- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err
|
||||
function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any)
|
||||
local plug, perr = Brep.find(opts)
|
||||
if not plug then
|
||||
return nil, perr
|
||||
end
|
||||
local text, err = textOf(cad)
|
||||
if not text then
|
||||
return nil, err
|
||||
end
|
||||
local bodies, res, rerr = Brep.read(plug, text, opts)
|
||||
if not bodies then
|
||||
return nil, rerr
|
||||
end
|
||||
return bodies, res
|
||||
end
|
||||
|
||||
-- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err
|
||||
function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?)
|
||||
if type(bodies) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a list of bodies")
|
||||
end
|
||||
local plug, perr = Brep.find(opts)
|
||||
if not plug then
|
||||
return nil, perr
|
||||
end
|
||||
local text, err = Brep.write(plug, bodies, opts)
|
||||
if not text then
|
||||
return nil, err
|
||||
end
|
||||
return Step.decode(Bytes.reader(buffer.fromstring(text)))
|
||||
end
|
||||
|
||||
-- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err
|
||||
function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?)
|
||||
local plug, perr = Brep.find(opts)
|
||||
if not plug then
|
||||
return nil, perr
|
||||
end
|
||||
local bodies = value
|
||||
if type(value) == "table" and value.kind == "cad" then
|
||||
local b, err = Step.toBodies(value, opts)
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
bodies = b
|
||||
end
|
||||
if type(bodies) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a Cad or a list of bodies")
|
||||
end
|
||||
return Brep.scene(plug, bodies, opts)
|
||||
end
|
||||
|
||||
return Step
|
||||
+30
-1
@@ -255,11 +255,15 @@ end
|
||||
-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) ->
|
||||
-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for
|
||||
-- the embedded parts) when called directly.
|
||||
-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own.
|
||||
local function withHooks(o: Options): Options
|
||||
if o.decodeImage ~= nil and o.encodeImage ~= nil then
|
||||
if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil then
|
||||
return o
|
||||
end
|
||||
local c = table.clone(o)
|
||||
if c.plugins == nil then
|
||||
c.plugins = F.plugins
|
||||
end
|
||||
if c.decodeImage == nil then
|
||||
c.decodeImage = function(b: buffer): (any, Err.Err?)
|
||||
return F.load(b, { category = "image" })
|
||||
@@ -539,6 +543,31 @@ for category in Types.CATEGORIES do
|
||||
end
|
||||
F.data.null = Types.null
|
||||
|
||||
-- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err;
|
||||
-- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel
|
||||
-- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED.
|
||||
for _, fn in { "toBodies", "fromBodies", "tessellate" } do
|
||||
local name: string = fn
|
||||
F.cad[name] = function(value: any, opts: Options?): (any, any)
|
||||
local o = if opts then table.clone(opts) else {}
|
||||
if o.plugins == nil then
|
||||
o.plugins = F.plugins
|
||||
end
|
||||
local m, err = F.format("step")
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
local ok, a, b = pcall(m[name], value, o)
|
||||
if not ok then
|
||||
return nil, Err.wrap(Err.new(Err.CORRUPT, name .. " threw: " .. tostring(a)), "step")
|
||||
end
|
||||
if a == nil and type(b) == "table" and b.code then
|
||||
return nil, Err.wrap(b, "step")
|
||||
end
|
||||
return a, b
|
||||
end
|
||||
end
|
||||
|
||||
-- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or
|
||||
-- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images
|
||||
-- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose
|
||||
|
||||
@@ -0,0 +1,598 @@
|
||||
--!strict
|
||||
-- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first
|
||||
-- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items),
|
||||
-- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension
|
||||
-- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry,
|
||||
-- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit.
|
||||
-- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and
|
||||
-- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Xml = require("@formats/codecs/Xml")
|
||||
local Zip = require("@formats/containers/Zip")
|
||||
|
||||
local Read = {}
|
||||
|
||||
local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
|
||||
local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
|
||||
Read.UNITS = UNITS
|
||||
local WRAP = { wrap = "repeat", mirror = "mirror", clamp = "clamp", none = "clamp" }
|
||||
local MAX_DEPTH = 64
|
||||
|
||||
local localName = Xml.localName
|
||||
|
||||
-- an attribute by local name (namespaced attributes such as p:path)
|
||||
local function attr(node: any, name: string): string?
|
||||
local a = node.attrs
|
||||
local v = a[name]
|
||||
if v ~= nil then
|
||||
return v
|
||||
end
|
||||
for k, x in next, a do
|
||||
if type(k) == "string" and localName(k) == name then
|
||||
return x
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function int(s: string?): number?
|
||||
local n = if s then tonumber(s) else nil
|
||||
if n and n == math.floor(n) and n >= 0 then
|
||||
return n
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1
|
||||
local function hexColor(s: string?): { number }?
|
||||
if type(s) ~= "string" then
|
||||
return nil
|
||||
end
|
||||
local h = string.match(s, "^%s*#(%x+)%s*$")
|
||||
if not h or (#h ~= 6 and #h ~= 8) then
|
||||
return nil
|
||||
end
|
||||
local function c(i: number): number
|
||||
return (tonumber(string.sub(h :: string, i, i + 1), 16) :: number) / 255
|
||||
end
|
||||
return { c(1), c(3), c(5), if #h == 8 then c(7) else 1 }
|
||||
end
|
||||
Read.hexColor = hexColor
|
||||
|
||||
function Read.toLinear(c: number): number
|
||||
if c <= 0.04045 then
|
||||
return c / 12.92
|
||||
end
|
||||
return ((c + 0.055) / 1.055) ^ 2.4
|
||||
end
|
||||
local toLinear = Read.toLinear
|
||||
|
||||
-- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid
|
||||
local function transform(s: string?): ({ number }?, boolean)
|
||||
if not s then
|
||||
return nil, true
|
||||
end
|
||||
local v = {}
|
||||
for w in string.gmatch(s, "%S+") do
|
||||
local n = tonumber(w)
|
||||
if not n or n ~= n or n == math.huge or n == -math.huge then
|
||||
return nil, false
|
||||
end
|
||||
table.insert(v, n)
|
||||
end
|
||||
if #v ~= 12 then
|
||||
return nil, false
|
||||
end
|
||||
local m = { v[1], v[2], v[3], 0, v[4], v[5], v[6], 0, v[7], v[8], v[9], 0, v[10], v[11], v[12], 1 }
|
||||
for i = 1, 16 do
|
||||
if m[i] ~= Types.Scene.IDENTITY[i] then
|
||||
return m, true
|
||||
end
|
||||
end
|
||||
return nil, true
|
||||
end
|
||||
|
||||
local function normPath(p: string): string
|
||||
p = string.gsub(p, "\\", "/")
|
||||
p = string.gsub(p, "^/+", "")
|
||||
return p
|
||||
end
|
||||
|
||||
-- one model part parsed into its resources and build
|
||||
type Model = { path: string, unit: string?, metadata: { [string]: string }, res: { [number]: any }, items: { any }, required: string? }
|
||||
|
||||
local function parseModel(text: string, path: string, opts: any): (Model?, Err.Err?)
|
||||
local doc, err = Xml.decode(text, { parents = false })
|
||||
if not doc then
|
||||
return nil, err
|
||||
end
|
||||
local root = (doc :: any).root
|
||||
if not root or localName(root.name) ~= "model" then
|
||||
return nil, Err.new(Err.CORRUPT, path .. ": the root element is not <model>")
|
||||
end
|
||||
local maxV = opts.maxVertices or 2 ^ 25
|
||||
local model: Model = { path = path, unit = attr(root, "unit"), metadata = {}, res = {}, items = {}, required = attr(root, "requiredextensions") }
|
||||
local resources: any = nil
|
||||
local build: any = nil
|
||||
for _, ch in Xml.children(root) do
|
||||
local ln = localName(ch.name)
|
||||
if ln == "metadata" then
|
||||
local n = attr(ch, "name")
|
||||
if n then
|
||||
model.metadata[n] = Xml.text(ch)
|
||||
end
|
||||
elseif ln == "resources" then
|
||||
resources = ch
|
||||
elseif ln == "build" then
|
||||
build = ch
|
||||
end
|
||||
end
|
||||
local total = 0
|
||||
if resources then
|
||||
for _, r in Xml.children(resources) do
|
||||
local ln = localName(r.name)
|
||||
local id = int(attr(r, "id"))
|
||||
if id == nil then
|
||||
continue
|
||||
end
|
||||
if ln == "object" then
|
||||
local o: any = { kind = "object", id = id, name = attr(r, "name"), type = attr(r, "type") or "model", pid = int(attr(r, "pid")), pindex = int(attr(r, "pindex")), partnumber = attr(r, "partnumber") }
|
||||
local mesh = Xml.child(r, "mesh")
|
||||
local comps = Xml.child(r, "components")
|
||||
if mesh then
|
||||
local verts = Xml.child(mesh, "vertices")
|
||||
local tris = Xml.child(mesh, "triangles")
|
||||
local vl = if verts then Xml.children(verts, "vertex") else {}
|
||||
local tl = if tris then Xml.children(tris, "triangle") else {}
|
||||
total += #vl + #tl * 3
|
||||
if total > maxV then
|
||||
return nil, Err.new(Err.LIMIT, "more than " .. maxV .. " vertices / corners")
|
||||
end
|
||||
local nv = #vl
|
||||
local pos = table.create(nv * 3, 0)
|
||||
for i, v in vl do
|
||||
local a = v.attrs
|
||||
local x, y, z = tonumber(a.x), tonumber(a.y), tonumber(a.z)
|
||||
if not x or not y or not z then
|
||||
return nil, Err.new(Err.CORRUPT, "object " .. id .. ": bad vertex " .. i)
|
||||
end
|
||||
pos[i * 3 - 2], pos[i * 3 - 1], pos[i * 3] = x, y, z
|
||||
end
|
||||
local nt = #tl
|
||||
local tv = table.create(nt * 3, 0)
|
||||
local tp = table.create(nt * 4, -1) -- pid, p1, p2, p3 (-1 = none)
|
||||
for i, tri in tl do
|
||||
local a = tri.attrs
|
||||
local v1, v2, v3 = int(a.v1), int(a.v2), int(a.v3)
|
||||
if not v1 or not v2 or not v3 or v1 >= nv or v2 >= nv or v3 >= nv then
|
||||
return nil, Err.new(Err.CORRUPT, "object " .. id .. ": triangle " .. i .. " has a bad vertex index")
|
||||
end
|
||||
tv[i * 3 - 2], tv[i * 3 - 1], tv[i * 3] = v1, v2, v3
|
||||
local b = i * 4 - 4
|
||||
local pid, p1, p2, p3 = int(a.pid), int(a.p1), int(a.p2), int(a.p3)
|
||||
tp[b + 1] = pid or -1
|
||||
tp[b + 2] = p1 or -1
|
||||
tp[b + 3] = p2 or p1 or -1
|
||||
tp[b + 4] = p3 or p1 or -1
|
||||
end
|
||||
o.positions, o.tv, o.tp, o.nt = pos, tv, tp, nt
|
||||
end
|
||||
if comps then
|
||||
o.components = {}
|
||||
for _, c in Xml.children(comps, "component") do
|
||||
local oid = int(attr(c, "objectid"))
|
||||
local m, ok = transform(attr(c, "transform"))
|
||||
if oid and ok then
|
||||
table.insert(o.components, { objectid = oid, matrix = m, path = attr(c, "path") })
|
||||
end
|
||||
end
|
||||
end
|
||||
model.res[id] = o
|
||||
elseif ln == "basematerials" then
|
||||
local items = {}
|
||||
for _, b in Xml.children(r, "base") do
|
||||
table.insert(items, { name = attr(b, "name"), color = hexColor(attr(b, "displaycolor")) or { 1, 1, 1, 1 }, hex = attr(b, "displaycolor") })
|
||||
end
|
||||
model.res[id] = { kind = "base", id = id, items = items }
|
||||
elseif ln == "colorgroup" then
|
||||
local items = {}
|
||||
for _, c in Xml.children(r, "color") do
|
||||
table.insert(items, hexColor(attr(c, "color")) or { 1, 1, 1, 1 })
|
||||
end
|
||||
model.res[id] = { kind = "color", id = id, items = items }
|
||||
elseif ln == "texture2d" then
|
||||
model.res[id] = { kind = "texture", id = id, path = attr(r, "path"), contenttype = attr(r, "contenttype"), tileu = attr(r, "tilestyleu"), tilev = attr(r, "tilestylev"), filter = attr(r, "filter") }
|
||||
elseif ln == "texture2dgroup" then
|
||||
local uvs = {}
|
||||
for _, c in Xml.children(r, "tex2coord") do
|
||||
table.insert(uvs, tonumber(attr(c, "u")) or 0)
|
||||
table.insert(uvs, tonumber(attr(c, "v")) or 0)
|
||||
end
|
||||
model.res[id] = { kind = "texgroup", id = id, texid = int(attr(r, "texid")), uvs = uvs, count = #uvs // 2 }
|
||||
elseif ln == "compositematerials" then
|
||||
local mats = {}
|
||||
for w in string.gmatch(attr(r, "matindices") or "", "%S+") do
|
||||
table.insert(mats, tonumber(w) or 0)
|
||||
end
|
||||
local items = {}
|
||||
for _, c in Xml.children(r, "composite") do
|
||||
local vals = {}
|
||||
for w in string.gmatch(attr(c, "values") or "", "%S+") do
|
||||
table.insert(vals, tonumber(w) or 0)
|
||||
end
|
||||
table.insert(items, vals)
|
||||
end
|
||||
model.res[id] = { kind = "composite", id = id, matid = int(attr(r, "matid")), matindices = mats, items = items }
|
||||
elseif ln == "multiproperties" then
|
||||
local pids = {}
|
||||
for w in string.gmatch(attr(r, "pids") or "", "%S+") do
|
||||
table.insert(pids, tonumber(w) or -1)
|
||||
end
|
||||
local items = {}
|
||||
for _, c in Xml.children(r, "multi") do
|
||||
local ix = {}
|
||||
for w in string.gmatch(attr(c, "pindices") or "", "%S+") do
|
||||
table.insert(ix, tonumber(w) or 0)
|
||||
end
|
||||
table.insert(items, ix)
|
||||
end
|
||||
model.res[id] = { kind = "multi", id = id, pids = pids, items = items }
|
||||
end
|
||||
end
|
||||
end
|
||||
if build then
|
||||
for _, it in Xml.children(build, "item") do
|
||||
local oid = int(attr(it, "objectid"))
|
||||
local m, ok = transform(attr(it, "transform"))
|
||||
if oid and ok then
|
||||
table.insert(model.items, { objectid = oid, matrix = m, path = attr(it, "path"), partnumber = attr(it, "partnumber") })
|
||||
end
|
||||
end
|
||||
end
|
||||
return model, nil
|
||||
end
|
||||
|
||||
-- the root model part's path
|
||||
local function rootPath(zip: any): string?
|
||||
local rels = zip:readString("_rels/.rels")
|
||||
if rels then
|
||||
local doc = Xml.decode(rels, { parents = false })
|
||||
if doc then
|
||||
for _, rel in Xml.descendants((doc :: any).root or doc, "Relationship") do
|
||||
local t, target = attr(rel, "Type"), attr(rel, "Target")
|
||||
if t and target and (t == REL_MODEL or string.find(t, "/3dmodel$")) then
|
||||
return normPath(target)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, e in zip:list() do
|
||||
if not e.isDir and string.find(string.lower(e.name), "%.model$") then
|
||||
return e.name
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?)
|
||||
local rootP = rootPath(zip)
|
||||
if not rootP then
|
||||
return nil, Err.new(Err.CORRUPT, "no 3D model part in the package")
|
||||
end
|
||||
local models: { [string]: Model } = {}
|
||||
local function getModel(path: string): (Model?, Err.Err?)
|
||||
local p = normPath(path)
|
||||
local m = models[p]
|
||||
if m then
|
||||
return m, nil
|
||||
end
|
||||
local text, err = zip:readString(p)
|
||||
if not text then
|
||||
return nil, err or Err.new(Err.CORRUPT, "missing model part " .. p)
|
||||
end
|
||||
if string.sub(text, 1, 5) == "%3McF" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "secure content extension: " .. p .. " is encrypted / wrapped")
|
||||
end
|
||||
local mm, perr = parseModel(text, p, opts)
|
||||
if not mm then
|
||||
return nil, perr
|
||||
end
|
||||
models[p] = mm
|
||||
return mm, nil
|
||||
end
|
||||
local root, rerr = getModel(rootP)
|
||||
if not root then
|
||||
return nil, rerr
|
||||
end
|
||||
|
||||
local scene = Types.Scene.new()
|
||||
local unitName = root.unit or "millimeter"
|
||||
scene.meta.up = "z"
|
||||
scene.meta.unit = UNITS[unitName] or 1e-3
|
||||
scene.meta.metadata = root.metadata
|
||||
scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required }
|
||||
|
||||
-- textures and materials (shared across model parts by part path + resource id)
|
||||
local texCache: { [string]: number } = {}
|
||||
local function texture(model: Model, id: number): number?
|
||||
local key = model.path .. "#" .. id
|
||||
if texCache[key] then
|
||||
return texCache[key]
|
||||
end
|
||||
local r = model.res[id]
|
||||
if not r or r.kind ~= "texture" or type(r.path) ~= "string" then
|
||||
return nil
|
||||
end
|
||||
local data = zip:read(normPath(r.path))
|
||||
local tex: Types.Texture = {
|
||||
name = r.path,
|
||||
data = data,
|
||||
mime = r.contenttype,
|
||||
uri = r.path,
|
||||
sampler = { wrapS = WRAP[r.tileu or "wrap"] or "repeat", wrapT = WRAP[r.tilev or "wrap"] or "repeat", filter = if r.filter == "nearest" or r.filter == "linear" then r.filter else nil },
|
||||
extras = { ["3mf"] = { id = id, tilestyleu = r.tileu, tilestylev = r.tilev, filter = r.filter } },
|
||||
}
|
||||
table.insert(scene.textures, tex)
|
||||
texCache[key] = #scene.textures
|
||||
return #scene.textures
|
||||
end
|
||||
local matCache: { [string]: number } = {}
|
||||
local function addMaterial(key: string, make: () -> Types.Material): number
|
||||
local i = matCache[key]
|
||||
if i then
|
||||
return i
|
||||
end
|
||||
table.insert(scene.materials, make())
|
||||
matCache[key] = #scene.materials
|
||||
return #scene.materials
|
||||
end
|
||||
local function colorMaterial(name: string?, c: { number }, extras: any): Types.Material
|
||||
local m = Types.Scene.material(name)
|
||||
m.baseColor = { toLinear(c[1]), toLinear(c[2]), toLinear(c[3]), c[4] }
|
||||
m.metallic = 0
|
||||
m.roughness = 1
|
||||
if c[4] < 1 then
|
||||
m.alphaMode = "blend"
|
||||
end
|
||||
m.extras = { ["3mf"] = extras }
|
||||
return m
|
||||
end
|
||||
|
||||
-- property of one corner -> (group key, material index?, kind, resource, index)
|
||||
local function resolve(model: Model, pid: number, p: number, depth: number?): (string, number?, string, any, number)
|
||||
local r = model.res[pid]
|
||||
if not r or p < 0 then
|
||||
return "none", nil, "none", nil, 0
|
||||
end
|
||||
local k = r.kind
|
||||
if k == "base" then
|
||||
local item = r.items[p + 1]
|
||||
if not item then
|
||||
return "none", nil, "none", nil, 0
|
||||
end
|
||||
local key = "b" .. model.path .. "#" .. pid .. ":" .. p
|
||||
return key, addMaterial(key, function()
|
||||
return colorMaterial(item.name, item.color, { group = pid, index = p, displaycolor = item.hex })
|
||||
end), "base", r, p
|
||||
elseif k == "color" then
|
||||
return "c" .. model.path .. "#" .. pid, nil, "color", r, p
|
||||
elseif k == "texgroup" then
|
||||
local ti = r.texid and texture(model, r.texid)
|
||||
local mat: number? = nil
|
||||
if ti then
|
||||
local mk = "t" .. model.path .. "#" .. (r.texid :: number)
|
||||
mat = addMaterial(mk, function()
|
||||
local m = Types.Scene.material("texture " .. tostring(r.texid))
|
||||
m.metallic = 0
|
||||
m.roughness = 1
|
||||
m.baseColorTexture = { texture = ti :: number }
|
||||
m.extras = { ["3mf"] = { texture = r.texid } }
|
||||
return m
|
||||
end)
|
||||
end
|
||||
return "t" .. model.path .. "#" .. pid, mat, "tex", r, p
|
||||
elseif k == "composite" then
|
||||
local item = r.items[p + 1]
|
||||
local base = r.matid and model.res[r.matid]
|
||||
if not item or not base or base.kind ~= "base" then
|
||||
return "none", nil, "none", nil, 0
|
||||
end
|
||||
local key = "x" .. model.path .. "#" .. pid .. ":" .. p
|
||||
return key, addMaterial(key, function()
|
||||
local c, sum = { 0, 0, 0, 0 }, 0
|
||||
for j, w in item do
|
||||
local b = base.items[(r.matindices[j] or 0) + 1]
|
||||
if b then
|
||||
for q = 1, 4 do
|
||||
c[q] += b.color[q] * w
|
||||
end
|
||||
sum += w
|
||||
end
|
||||
end
|
||||
if sum > 0 then
|
||||
for q = 1, 4 do
|
||||
c[q] /= sum
|
||||
end
|
||||
else
|
||||
c = { 1, 1, 1, 1 }
|
||||
end
|
||||
return colorMaterial("composite " .. pid .. ":" .. p, c, { composite = pid, index = p })
|
||||
end), "base", r, p
|
||||
elseif k == "multi" and (depth or 0) < 1 then
|
||||
local item = r.items[p + 1]
|
||||
local first = r.pids[1]
|
||||
if item and first then
|
||||
return resolve(model, first, item[1] or 0, 1)
|
||||
end
|
||||
end
|
||||
return "none", nil, "none", nil, 0
|
||||
end
|
||||
|
||||
-- one Scene mesh per (part, object) with a mesh
|
||||
local meshCache: { [string]: number } = {}
|
||||
local function buildMesh(model: Model, o: any): number?
|
||||
local key = model.path .. "#" .. o.id
|
||||
local cached = meshCache[key]
|
||||
if cached ~= nil then
|
||||
return if cached > 0 then cached else nil
|
||||
end
|
||||
local groups: { [string]: any } = {}
|
||||
local order: { any } = {}
|
||||
local pos, tv, tp = o.positions, o.tv, o.tp
|
||||
for t = 0, o.nt - 1 do
|
||||
local pid = tp[t * 4 + 1]
|
||||
local ps = { tp[t * 4 + 2], tp[t * 4 + 3], tp[t * 4 + 4] }
|
||||
if pid < 0 then
|
||||
pid = o.pid or -1
|
||||
if ps[1] < 0 then
|
||||
local d = o.pindex or (if pid >= 0 then 0 else -1)
|
||||
ps = { d, d, d }
|
||||
end
|
||||
end
|
||||
local gkey, mat, kind, res, _ = resolve(model, pid, ps[1])
|
||||
local g = groups[gkey]
|
||||
if not g then
|
||||
g = { kind = kind, res = res, material = mat, vmap = {}, pos = {}, attr = {}, idx = {}, n = 0 }
|
||||
groups[gkey] = g
|
||||
table.insert(order, g)
|
||||
end
|
||||
for c = 1, 3 do
|
||||
local v = tv[t * 3 + c]
|
||||
local vk = v
|
||||
local pc = 0
|
||||
if kind == "color" or kind == "tex" then
|
||||
pc = ps[c]
|
||||
local cnt = if kind == "color" then #res.items else res.count
|
||||
if pc < 0 or pc >= cnt then
|
||||
pc = ps[1]
|
||||
end
|
||||
if pc < 0 or pc >= cnt then
|
||||
pc = 0
|
||||
end
|
||||
vk = v * (cnt + 1) + pc
|
||||
end
|
||||
local ni = g.vmap[vk]
|
||||
if not ni then
|
||||
ni = g.n
|
||||
g.n += 1
|
||||
g.vmap[vk] = ni
|
||||
table.insert(g.pos, pos[v * 3 + 1])
|
||||
table.insert(g.pos, pos[v * 3 + 2])
|
||||
table.insert(g.pos, pos[v * 3 + 3])
|
||||
if kind == "color" then
|
||||
local col = res.items[pc + 1] or { 1, 1, 1, 1 }
|
||||
table.insert(g.attr, toLinear(col[1]))
|
||||
table.insert(g.attr, toLinear(col[2]))
|
||||
table.insert(g.attr, toLinear(col[3]))
|
||||
table.insert(g.attr, col[4])
|
||||
elseif kind == "tex" then
|
||||
table.insert(g.attr, res.uvs[pc * 2 + 1] or 0)
|
||||
table.insert(g.attr, 1 - (res.uvs[pc * 2 + 2] or 0))
|
||||
end
|
||||
end
|
||||
table.insert(g.idx, ni)
|
||||
end
|
||||
end
|
||||
local mesh: Types.Mesh = { name = o.name, primitives = {}, extras = { ["3mf"] = { id = o.id, part = model.path, type = o.type, partnumber = o.partnumber } } }
|
||||
for _, g in order do
|
||||
local n = g.n
|
||||
local pa = Types.Scene.accessor(nil, "f32", 3, n)
|
||||
for i, x in g.pos do
|
||||
buffer.writef32(pa.data, (i - 1) * 4, x)
|
||||
end
|
||||
local ia = Types.Scene.accessor(nil, "u32", 1, #g.idx)
|
||||
for i, x in g.idx do
|
||||
buffer.writeu32(ia.data, (i - 1) * 4, x)
|
||||
end
|
||||
local prim: Types.Primitive = { attributes = { POSITION = pa }, indices = ia, mode = "triangles", material = g.material }
|
||||
if g.kind == "color" then
|
||||
local ca = Types.Scene.accessor(nil, "f32", 4, n)
|
||||
for i, x in g.attr do
|
||||
buffer.writef32(ca.data, (i - 1) * 4, x)
|
||||
end
|
||||
prim.attributes.COLOR_0 = ca
|
||||
prim.extras = { ["3mf"] = { colorgroup = g.res.id } }
|
||||
elseif g.kind == "tex" then
|
||||
local ua = Types.Scene.accessor(nil, "f32", 2, n)
|
||||
for i, x in g.attr do
|
||||
buffer.writef32(ua.data, (i - 1) * 4, x)
|
||||
end
|
||||
prim.attributes.TEXCOORD_0 = ua
|
||||
prim.extras = { ["3mf"] = { texture2dgroup = g.res.id } }
|
||||
end
|
||||
table.insert(mesh.primitives, prim)
|
||||
end
|
||||
if #mesh.primitives == 0 then
|
||||
meshCache[key] = 0
|
||||
return nil
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
meshCache[key] = #scene.meshes
|
||||
return #scene.meshes
|
||||
end
|
||||
|
||||
-- nodes: one per object instance (build items and components)
|
||||
local nodeCount = 0
|
||||
local maxNodes = opts.maxNodes or 2 ^ 20
|
||||
local instantiate: (model: Model, oid: number, matrix: { number }?, depth: number, extra: any) -> (number?, Err.Err?)
|
||||
function instantiate(model: Model, oid: number, matrix: { number }?, depth: number, extra: any): (number?, Err.Err?)
|
||||
if depth > MAX_DEPTH then
|
||||
return nil, Err.new(Err.CORRUPT, "components nested deeper than " .. MAX_DEPTH .. " (a cycle?)")
|
||||
end
|
||||
nodeCount += 1
|
||||
if nodeCount > maxNodes then
|
||||
return nil, Err.new(Err.LIMIT, "more than " .. maxNodes .. " object instances")
|
||||
end
|
||||
local o = model.res[oid]
|
||||
if not o or o.kind ~= "object" then
|
||||
return nil, Err.new(Err.CORRUPT, "no object " .. oid .. " in " .. model.path)
|
||||
end
|
||||
local node: Types.Node = { name = o.name, children = {}, matrix = matrix, extras = { ["3mf"] = extra or { objectid = oid } } }
|
||||
table.insert(scene.nodes, node)
|
||||
local index = #scene.nodes
|
||||
if o.positions then
|
||||
node.mesh = buildMesh(model, o)
|
||||
end
|
||||
if o.components then
|
||||
for _, c in o.components do
|
||||
local m: Model? = model
|
||||
if c.path then
|
||||
local mm, err = getModel(c.path)
|
||||
if not mm then
|
||||
return nil, err
|
||||
end
|
||||
m = mm
|
||||
end
|
||||
local child, err = instantiate(m :: Model, c.objectid, c.matrix, depth + 1, { objectid = c.objectid, path = c.path })
|
||||
if not child then
|
||||
return nil, err
|
||||
end
|
||||
table.insert(node.children, child)
|
||||
end
|
||||
end
|
||||
return index, nil
|
||||
end
|
||||
for _, it in root.items do
|
||||
local m: Model? = root
|
||||
if it.path then
|
||||
local mm, err = getModel(it.path)
|
||||
if not mm then
|
||||
return nil, err
|
||||
end
|
||||
m = mm
|
||||
end
|
||||
local idx, err = instantiate(m :: Model, it.objectid, it.matrix, 0, { objectid = it.objectid, path = it.path, partnumber = it.partnumber, item = true })
|
||||
if not idx then
|
||||
return nil, err
|
||||
end
|
||||
table.insert(scene.roots, idx)
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
function Read.open(r: any): (any, Err.Err?)
|
||||
return Zip.open(r)
|
||||
end
|
||||
|
||||
return Read
|
||||
@@ -0,0 +1,417 @@
|
||||
--!strict
|
||||
-- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles,
|
||||
-- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the
|
||||
-- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours),
|
||||
-- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has
|
||||
-- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/).
|
||||
-- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Xml = require("@formats/codecs/Xml")
|
||||
local Zip = require("@formats/containers/Zip")
|
||||
|
||||
local Write = {}
|
||||
|
||||
local NS_CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
|
||||
local NS_MAT = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02"
|
||||
local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
|
||||
local REL_TEXTURE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture"
|
||||
local UNIT_ORDER = { "micron", "millimeter", "centimeter", "inch", "foot", "meter" }
|
||||
local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
|
||||
local TEX_EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg" }
|
||||
|
||||
local fmt = string.format
|
||||
local esc = Xml.escapeAttr
|
||||
|
||||
local function num(x: number): string
|
||||
if x ~= x or x == math.huge or x == -math.huge then
|
||||
return "0"
|
||||
end
|
||||
if x == math.floor(x) and math.abs(x) < 1e15 then
|
||||
return fmt("%d", x)
|
||||
end
|
||||
return fmt("%.9g", x)
|
||||
end
|
||||
|
||||
local function toSrgb(c: number): number
|
||||
c = math.clamp(c, 0, 1)
|
||||
if c <= 0.0031308 then
|
||||
return c * 12.92
|
||||
end
|
||||
return 1.055 * c ^ (1 / 2.4) - 0.055
|
||||
end
|
||||
|
||||
local function hex(r: number, g: number, b: number, a: number): string
|
||||
local function q(x: number): number
|
||||
return math.clamp(math.floor(x * 255 + 0.5), 0, 255)
|
||||
end
|
||||
return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1)))
|
||||
end
|
||||
|
||||
-- the triangle corner list of a primitive (0-based vertex indices) or nil
|
||||
local function triangles(prim: any): { number }?
|
||||
local pos = prim.attributes and prim.attributes.POSITION
|
||||
if type(pos) ~= "table" then
|
||||
return nil
|
||||
end
|
||||
local n = pos.count
|
||||
local ix: { number } = {}
|
||||
if prim.indices then
|
||||
local get = Types.Scene.reader(prim.indices)
|
||||
if not get then
|
||||
return nil
|
||||
end
|
||||
for i = 0, prim.indices.count - 1 do
|
||||
ix[i + 1] = get(i, 0)
|
||||
end
|
||||
else
|
||||
for i = 1, n do
|
||||
ix[i] = i - 1
|
||||
end
|
||||
end
|
||||
for _, v in ix do
|
||||
if v ~= v or v < 0 or v >= n then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
local mode = prim.mode or "triangles"
|
||||
local out: { number } = {}
|
||||
local function tri(a: number, b: number, c: number)
|
||||
if a ~= b and b ~= c and a ~= c then
|
||||
table.insert(out, a)
|
||||
table.insert(out, b)
|
||||
table.insert(out, c)
|
||||
end
|
||||
end
|
||||
if mode == "triangles" then
|
||||
for i = 1, #ix - 2, 3 do
|
||||
tri(ix[i], ix[i + 1], ix[i + 2])
|
||||
end
|
||||
elseif mode == "triangle_strip" then
|
||||
for i = 1, #ix - 2 do
|
||||
if i % 2 == 1 then
|
||||
tri(ix[i], ix[i + 1], ix[i + 2])
|
||||
else
|
||||
tri(ix[i + 1], ix[i], ix[i + 2])
|
||||
end
|
||||
end
|
||||
elseif mode == "triangle_fan" then
|
||||
for i = 2, #ix - 1 do
|
||||
tri(ix[1], ix[i], ix[i + 1])
|
||||
end
|
||||
elseif mode == "polygons" and prim.faces then
|
||||
local get = Types.Scene.reader(prim.faces)
|
||||
if not get then
|
||||
return nil
|
||||
end
|
||||
local at = 1
|
||||
for f = 0, prim.faces.count - 1 do
|
||||
local k = get(f, 0)
|
||||
if at + k - 1 > #ix then
|
||||
break
|
||||
end
|
||||
for j = 1, k - 2 do
|
||||
tri(ix[at], ix[at + j], ix[at + j + 1])
|
||||
end
|
||||
at += k
|
||||
end
|
||||
else
|
||||
return nil
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
|
||||
local o = opts or {}
|
||||
local nextId = 0
|
||||
local function id(): number
|
||||
nextId += 1
|
||||
return nextId
|
||||
end
|
||||
local res: { string } = {} -- resource XML chunks, in definition order
|
||||
local files: { { name: string, data: buffer, mime: string } } = {}
|
||||
|
||||
-- unit
|
||||
local unitName: string, scale: number = "millimeter", 1
|
||||
local mu: any = scene.meta and scene.meta.unit
|
||||
if type(o.unit) == "string" and UNITS[o.unit] then
|
||||
unitName = o.unit
|
||||
if type(mu) == "number" and mu > 0 then
|
||||
scale = mu / UNITS[o.unit]
|
||||
end
|
||||
elseif type(mu) == "number" and mu > 0 then
|
||||
local found = false
|
||||
for _, u in UNIT_ORDER do
|
||||
if math.abs(UNITS[u] - mu) <= 1e-9 * mu then
|
||||
unitName, found = u, true
|
||||
break
|
||||
end
|
||||
end
|
||||
if not found then
|
||||
scale = mu / 1e-3
|
||||
end
|
||||
end
|
||||
|
||||
-- base materials: one group with every Scene material
|
||||
local baseId: number? = nil
|
||||
local nmat = #scene.materials
|
||||
local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed
|
||||
local needDefault = false
|
||||
if nmat > 0 then
|
||||
baseId = id()
|
||||
end
|
||||
|
||||
-- textures used as base colour textures
|
||||
local texRes: { [number]: number } = {}
|
||||
local function textureId(ti: number): number?
|
||||
if texRes[ti] ~= nil then
|
||||
return if texRes[ti] > 0 then texRes[ti] else nil
|
||||
end
|
||||
local tex = scene.textures[ti]
|
||||
local ext = tex and TEX_EXT[tex.mime or ""]
|
||||
if not tex or type(tex.data) ~= "buffer" or not ext then
|
||||
texRes[ti] = 0
|
||||
return nil
|
||||
end
|
||||
local rid = id()
|
||||
local name = fmt("3D/Textures/texture_%d.%s", ti, ext :: string)
|
||||
table.insert(files, { name = name, data = tex.data :: buffer, mime = tex.mime :: string })
|
||||
local s = tex.sampler
|
||||
local function tile(w: string?): string
|
||||
return if w == "clamp" then "clamp" elseif w == "mirror" then "mirror" else "wrap"
|
||||
end
|
||||
local filter = if s and (s.filter == "nearest" or s.filter == "linear") then s.filter else "auto"
|
||||
table.insert(res, fmt('\t\t<m:texture2d id="%d" path="/%s" contenttype="%s" tilestyleu="%s" tilestylev="%s" filter="%s" />\n', rid, esc(name), tex.mime :: string, tile(s and s.wrapS), tile(s and s.wrapT), filter))
|
||||
texRes[ti] = rid
|
||||
return rid
|
||||
end
|
||||
|
||||
-- objects
|
||||
local objectOf: { [number]: number } = {}
|
||||
local objChunks: { string } = {}
|
||||
for mi, mesh in scene.meshes do
|
||||
local verts: { string } = {}
|
||||
local tris: { string } = {}
|
||||
local base = 0
|
||||
local objPid: number?, objP: number? = nil, nil
|
||||
local anyNone = false
|
||||
local triList: { { number } } = {} -- { v1, v2, v3, pid | -1, p1, p2, p3 }
|
||||
for _, prim in mesh.primitives do
|
||||
local corners = triangles(prim)
|
||||
if not corners or #corners == 0 then
|
||||
continue
|
||||
end
|
||||
local pos = prim.attributes.POSITION
|
||||
local getP = Types.Scene.reader(pos)
|
||||
if not getP then
|
||||
continue
|
||||
end
|
||||
local n = pos.count
|
||||
for v = 0, n - 1 do
|
||||
table.insert(verts, fmt('\t\t\t\t\t<vertex x="%s" y="%s" z="%s" />\n', num(getP(v, 0)), num(if pos.components >= 2 then getP(v, 1) else 0), num(if pos.components >= 3 then getP(v, 2) else 0)))
|
||||
end
|
||||
-- properties: texture group, colour group, base material, none
|
||||
local pid, kind = -1, "none"
|
||||
local mat = prim.material and scene.materials[prim.material]
|
||||
local uv = prim.attributes.TEXCOORD_0
|
||||
local col = prim.attributes.COLOR_0
|
||||
local tref = mat and mat.baseColorTexture
|
||||
local tid = if tref and uv and (tref.texCoord or 0) == 0 then textureId(tref.texture) else nil
|
||||
if tid and uv then
|
||||
local get = Types.Scene.reader(uv)
|
||||
if get then
|
||||
pid, kind = id(), "tex"
|
||||
local parts = { fmt('\t\t<m:texture2dgroup id="%d" texid="%d">\n', pid, tid) }
|
||||
for v = 0, n - 1 do
|
||||
table.insert(parts, fmt('\t\t\t<m:tex2coord u="%s" v="%s" />\n', num(get(v, 0)), num(1 - get(v, 1))))
|
||||
end
|
||||
table.insert(parts, "\t\t</m:texture2dgroup>\n")
|
||||
table.insert(res, table.concat(parts))
|
||||
end
|
||||
end
|
||||
if kind == "none" and col then
|
||||
local get = Types.Scene.reader(col)
|
||||
if get then
|
||||
pid, kind = id(), "color"
|
||||
local parts = { fmt('\t\t<m:colorgroup id="%d">\n', pid) }
|
||||
local four = col.components >= 4
|
||||
for v = 0, n - 1 do
|
||||
table.insert(parts, fmt('\t\t\t<m:color color="%s" />\n', hex(get(v, 0), get(v, 1), get(v, 2), if four then get(v, 3) else 1)))
|
||||
end
|
||||
table.insert(parts, "\t\t</m:colorgroup>\n")
|
||||
table.insert(res, table.concat(parts))
|
||||
end
|
||||
end
|
||||
local pindex = -1
|
||||
if kind == "none" and baseId and prim.material and scene.materials[prim.material] then
|
||||
pid, kind, pindex = baseId :: number, "base", prim.material - 1
|
||||
end
|
||||
for i = 1, #corners, 3 do
|
||||
local a, b, c = corners[i] + base, corners[i + 1] + base, corners[i + 2] + base
|
||||
if kind == "tex" or kind == "color" then
|
||||
table.insert(triList, { a, b, c, pid, corners[i], corners[i + 1], corners[i + 2] })
|
||||
elseif kind == "base" then
|
||||
table.insert(triList, { a, b, c, pid, pindex, pindex, pindex })
|
||||
else
|
||||
table.insert(triList, { a, b, c, -1, -1, -1, -1 })
|
||||
anyNone = true
|
||||
end
|
||||
if objPid == nil and kind ~= "none" then
|
||||
objPid, objP = pid, if kind == "base" then pindex else corners[i]
|
||||
end
|
||||
end
|
||||
base += n
|
||||
end
|
||||
if #triList == 0 then
|
||||
continue
|
||||
end
|
||||
if objPid and anyNone then
|
||||
needDefault = true
|
||||
if not baseId then
|
||||
baseId = id()
|
||||
end
|
||||
end
|
||||
for _, t in triList do
|
||||
if t[4] < 0 and objPid then
|
||||
t[4], t[5], t[6], t[7] = baseId :: number, defaultBase, defaultBase, defaultBase
|
||||
end
|
||||
if t[4] < 0 then
|
||||
table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" />\n', t[1], t[2], t[3]))
|
||||
elseif t[5] == t[6] and t[6] == t[7] then
|
||||
table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" />\n', t[1], t[2], t[3], t[4], t[5]))
|
||||
else
|
||||
table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" p2="%d" p3="%d" />\n', t[1], t[2], t[3], t[4], t[5], t[6], t[7]))
|
||||
end
|
||||
end
|
||||
local oid = id()
|
||||
objectOf[mi] = oid
|
||||
local head = fmt('\t\t<object id="%d" type="model"', oid)
|
||||
if mesh.name then
|
||||
head ..= fmt(' name="%s"', esc(mesh.name))
|
||||
end
|
||||
if objPid then
|
||||
head ..= fmt(' pid="%d" pindex="%d"', objPid, objP :: number)
|
||||
end
|
||||
table.insert(objChunks, table.concat({ head, ">\n\t\t\t<mesh>\n\t\t\t\t<vertices>\n", table.concat(verts), "\t\t\t\t</vertices>\n\t\t\t\t<triangles>\n", table.concat(tris), "\t\t\t\t</triangles>\n\t\t\t</mesh>\n\t\t</object>\n" }))
|
||||
table.insert(res, objChunks[#objChunks])
|
||||
end
|
||||
|
||||
-- the base material group goes first (its id was taken first)
|
||||
if baseId then
|
||||
local parts = { fmt('\t\t<basematerials id="%d">\n', baseId) }
|
||||
for _, m in scene.materials do
|
||||
local c = m.baseColor or { 1, 1, 1, 1 }
|
||||
table.insert(parts, fmt('\t\t\t<base name="%s" displaycolor="%s" />\n', esc(m.name or "material"), hex(c[1] or 1, c[2] or 1, c[3] or 1, c[4] or 1)))
|
||||
end
|
||||
if needDefault then
|
||||
table.insert(parts, '\t\t\t<base name="default" displaycolor="#FFFFFFFF" />\n')
|
||||
end
|
||||
table.insert(parts, "\t\t</basematerials>\n")
|
||||
table.insert(res, 1, table.concat(parts))
|
||||
end
|
||||
|
||||
-- build items: every node with a mesh, at its world matrix
|
||||
local items: { string } = {}
|
||||
local seen: { [number]: boolean } = {}
|
||||
for _, pl in Types.Scene.flatten(scene) do
|
||||
if seen[pl.node] then
|
||||
continue
|
||||
end
|
||||
seen[pl.node] = true
|
||||
local oid = objectOf[pl.mesh]
|
||||
if not oid then
|
||||
continue
|
||||
end
|
||||
local m = pl.matrix
|
||||
local s = scale
|
||||
local tr = { m[1] * s, m[2] * s, m[3] * s, m[5] * s, m[6] * s, m[7] * s, m[9] * s, m[10] * s, m[11] * s, m[13] * s, m[14] * s, m[15] * s }
|
||||
local ident = s == 1
|
||||
for i, v in { 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 } do
|
||||
if tr[i] ~= v then
|
||||
ident = false
|
||||
end
|
||||
end
|
||||
if ident then
|
||||
table.insert(items, fmt('\t\t<item objectid="%d" />\n', oid))
|
||||
else
|
||||
local ns = table.create(12, "")
|
||||
for i = 1, 12 do
|
||||
ns[i] = num(tr[i])
|
||||
end
|
||||
table.insert(items, fmt('\t\t<item objectid="%d" transform="%s" />\n', oid, table.concat(ns, " ")))
|
||||
end
|
||||
end
|
||||
|
||||
-- metadata
|
||||
local meta: { string } = {}
|
||||
local md = scene.meta and scene.meta.metadata
|
||||
if type(md) == "table" then
|
||||
local keys: { string } = {}
|
||||
for k: any, v: any in md do
|
||||
if type(k) == "string" and (type(v) == "string" or type(v) == "number") then
|
||||
table.insert(keys, k)
|
||||
end
|
||||
end
|
||||
table.sort(keys)
|
||||
for _, k in keys do
|
||||
table.insert(meta, fmt('\t<metadata name="%s">%s</metadata>\n', esc(k), Xml.escape(tostring(md[k]))))
|
||||
end
|
||||
end
|
||||
|
||||
local model = table.concat({
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n',
|
||||
'<model unit="' .. unitName .. '" xml:lang="en-US" xmlns="' .. NS_CORE .. '" xmlns:m="' .. NS_MAT .. '">\n',
|
||||
table.concat(meta),
|
||||
"\t<resources>\n",
|
||||
table.concat(res),
|
||||
"\t</resources>\n\t<build>\n",
|
||||
table.concat(items),
|
||||
"\t</build>\n</model>\n",
|
||||
})
|
||||
|
||||
local types = { '<?xml version="1.0" encoding="UTF-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n',
|
||||
'\t<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />\n',
|
||||
'\t<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml" />\n' }
|
||||
local exts: { [string]: boolean } = {}
|
||||
for _, f in files do
|
||||
local e = string.match(f.name, "%.(%w+)$") :: string
|
||||
if not exts[e] then
|
||||
exts[e] = true
|
||||
table.insert(types, fmt('\t<Default Extension="%s" ContentType="%s" />\n', e, f.mime))
|
||||
end
|
||||
end
|
||||
table.insert(types, "</Types>\n")
|
||||
local rels = '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n'
|
||||
.. fmt('\t<Relationship Target="/3D/3dmodel.model" Id="rel0" Type="%s" />\n', REL_MODEL)
|
||||
.. "</Relationships>\n"
|
||||
|
||||
local w = Zip.writer()
|
||||
local level = o.level or 6
|
||||
local method = if level == 0 then "store" else "deflate"
|
||||
local ok, err = w:add("[Content_Types].xml", table.concat(types), { level = level, method = method })
|
||||
if ok then
|
||||
ok, err = w:add("_rels/.rels", rels, { level = level, method = method })
|
||||
end
|
||||
if ok then
|
||||
ok, err = w:add("3D/3dmodel.model", model, { level = level, method = method })
|
||||
end
|
||||
if ok and #files > 0 then
|
||||
local mr = { '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n' }
|
||||
for i, f in files do
|
||||
table.insert(mr, fmt('\t<Relationship Target="/%s" Id="rel%d" Type="%s" />\n', esc(f.name), i, REL_TEXTURE))
|
||||
end
|
||||
table.insert(mr, "</Relationships>\n")
|
||||
ok, err = w:add("3D/_rels/3dmodel.model.rels", table.concat(mr), { level = level, method = method })
|
||||
for _, f in files do
|
||||
if ok then
|
||||
ok, err = w:add(f.name, f.data, { method = "store" })
|
||||
end
|
||||
end
|
||||
end
|
||||
if not ok then
|
||||
return nil, err or Err.new(Err.ARG, "zip writer failed")
|
||||
end
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,95 @@
|
||||
--!strict
|
||||
-- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2,
|
||||
-- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts
|
||||
-- (codecs/Xml).
|
||||
-- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from
|
||||
-- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices
|
||||
-- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata
|
||||
-- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours
|
||||
-- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to
|
||||
-- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it
|
||||
-- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first
|
||||
-- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices
|
||||
-- are split where a vertex's corners carry different colours / texture coordinates.
|
||||
-- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a
|
||||
-- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups,
|
||||
-- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit).
|
||||
-- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are
|
||||
-- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Zip = require("@formats/containers/Zip")
|
||||
local Read = require("@formats/model/3mf/Read")
|
||||
local Write = require("@formats/model/3mf/Write")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local ThreeMf = {
|
||||
name = "3mf",
|
||||
category = "model",
|
||||
extensions = { "3mf" },
|
||||
mime = { "model/3mf" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" },
|
||||
caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxVertices: number?, -- refuse more vertices + triangle corners in total (default 2^25)
|
||||
maxNodes: number?, -- refuse more object instances (default 2^20)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
unit: string?, -- "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter" (default: from meta.unit, else
|
||||
-- millimeter); positions are scaled through the build transforms when meta.unit differs
|
||||
level: number?, -- deflate level for the XML parts (default 6; 0 stores them)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function ThreeMf.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) ~= "PK\3\4" then
|
||||
return 0
|
||||
end
|
||||
-- the central directory sits at the end: look for the model part's name there, then at the start
|
||||
local n = r:size()
|
||||
local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536))
|
||||
if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then
|
||||
return 0.95
|
||||
end
|
||||
local head = r:peek(256)
|
||||
if string.find(head, "3D/", 1, true) then
|
||||
return 0.7
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function ThreeMf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local zip, zerr = Zip.open(r)
|
||||
if not zip then
|
||||
return nil, zerr
|
||||
end
|
||||
local ok, scene, err = pcall(Read.scene, zip, opts or {})
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad package (" .. tostring(scene) .. ")")
|
||||
end
|
||||
return scene, err
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function ThreeMf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.materials) ~= "table" or type(scene.textures) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a Scene")
|
||||
end
|
||||
if opts and opts.unit ~= nil and not Read.UNITS[opts.unit] then
|
||||
return nil, Err.new(Err.ARG, "unknown unit " .. tostring(opts.unit))
|
||||
end
|
||||
local ok, out, err = pcall(Write.build, scene, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "bad scene (" .. tostring(out) .. ")")
|
||||
end
|
||||
return out, err
|
||||
end
|
||||
|
||||
return ThreeMf
|
||||
@@ -0,0 +1,188 @@
|
||||
--!strict
|
||||
-- model/dae/Math: the matrix helpers the Collada reader and writer share. Matrices are flat arrays of 16 in glTF's
|
||||
-- column-major order (Collada writes row-major: fromRows / toRows convert). Quaternions are { x, y, z, w }.
|
||||
local DaeMath = {}
|
||||
|
||||
local sqrt, abs, rad, sin, cos = math.sqrt, math.abs, math.rad, math.sin, math.cos
|
||||
|
||||
function DaeMath.identity(): { number }
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
-- fromRows(v, at?) -> column-major from 16 row-major values starting at v[at] (default 1)
|
||||
function DaeMath.fromRows(v: { number }, at: number?): { number }
|
||||
local o = (at or 1) - 1
|
||||
local m = table.create(16, 0)
|
||||
for r = 0, 3 do
|
||||
for c = 0, 3 do
|
||||
m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
function DaeMath.toRows(m: { number }): { number }
|
||||
local v = table.create(16, 0)
|
||||
for r = 0, 3 do
|
||||
for c = 0, 3 do
|
||||
v[r * 4 + c + 1] = m[c * 4 + r + 1]
|
||||
end
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
function DaeMath.mul(a: { number }, b: { number }): { number }
|
||||
local m = table.create(16, 0)
|
||||
for col = 0, 3 do
|
||||
for row = 0, 3 do
|
||||
local s = 0
|
||||
for k = 0, 3 do
|
||||
s += a[k * 4 + row + 1] * b[col * 4 + k + 1]
|
||||
end
|
||||
m[col * 4 + row + 1] = s
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
function DaeMath.translation(x: number, y: number, z: number): { number }
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 }
|
||||
end
|
||||
|
||||
function DaeMath.scaling(x: number, y: number, z: number): { number }
|
||||
return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
-- axisAngle(x, y, z, degrees) -> quaternion
|
||||
function DaeMath.axisAngle(x: number, y: number, z: number, degrees: number): { number }
|
||||
local l = sqrt(x * x + y * y + z * z)
|
||||
if l < 1e-12 then
|
||||
return { 0, 0, 0, 1 }
|
||||
end
|
||||
local h = rad(degrees) / 2
|
||||
local s = sin(h) / l
|
||||
return { x * s, y * s, z * s, cos(h) }
|
||||
end
|
||||
|
||||
function DaeMath.quatMatrix(q: { number }): { number }
|
||||
local x, y, z, w = q[1], q[2], q[3], q[4]
|
||||
local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
|
||||
return {
|
||||
1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0,
|
||||
2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0,
|
||||
2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0,
|
||||
0, 0, 0, 1,
|
||||
}
|
||||
end
|
||||
|
||||
local function cross(a: { number }, b: { number }): { number }
|
||||
return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] }
|
||||
end
|
||||
local function norm(a: { number }): { number }
|
||||
local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3])
|
||||
if l < 1e-20 then
|
||||
return { 0, 0, 0 }
|
||||
end
|
||||
return { a[1] / l, a[2] / l, a[3] / l }
|
||||
end
|
||||
|
||||
-- lookat(eye, interest, up) -> the placement of an object at eye whose -Z looks at interest
|
||||
function DaeMath.lookat(v: { number }): { number }
|
||||
local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0
|
||||
local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) })
|
||||
local x = norm(cross({ v[7] or 0, v[8] or 1, v[9] or 0 }, z))
|
||||
local y = cross(z, x)
|
||||
return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 }
|
||||
end
|
||||
|
||||
-- skew(angle, rotation axis, translation axis) (RenderMan's skew)
|
||||
function DaeMath.skew(v: { number }): { number }
|
||||
local a = rad(v[1] or 0)
|
||||
local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 })
|
||||
local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 })
|
||||
local s = math.tan(a)
|
||||
local m = DaeMath.identity()
|
||||
-- M = I + s * t * r^T (column-major: m[col*4 + row])
|
||||
for row = 0, 2 do
|
||||
for col = 0, 2 do
|
||||
m[col * 4 + row + 1] += s * t[row + 1] * r[col + 1]
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
-- decompose(m) -> translation, rotation, scale | nil (shear, a projective row, or a singular matrix)
|
||||
function DaeMath.decompose(m: { number }): ({ number }?, { number }?, { number }?)
|
||||
if abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6 then
|
||||
return nil, nil, nil
|
||||
end
|
||||
local c1 = { m[1], m[2], m[3] }
|
||||
local c2 = { m[5], m[6], m[7] }
|
||||
local c3 = { m[9], m[10], m[11] }
|
||||
local sx = sqrt(c1[1] * c1[1] + c1[2] * c1[2] + c1[3] * c1[3])
|
||||
local sy = sqrt(c2[1] * c2[1] + c2[2] * c2[2] + c2[3] * c2[3])
|
||||
local sz = sqrt(c3[1] * c3[1] + c3[2] * c3[2] + c3[3] * c3[3])
|
||||
if sx < 1e-12 or sy < 1e-12 or sz < 1e-12 then
|
||||
return nil, nil, nil
|
||||
end
|
||||
local x, y, z = { c1[1] / sx, c1[2] / sx, c1[3] / sx }, { c2[1] / sy, c2[2] / sy, c2[3] / sy }, { c3[1] / sz, c3[2] / sz, c3[3] / sz }
|
||||
local dxy = x[1] * y[1] + x[2] * y[2] + x[3] * y[3]
|
||||
local dxz = x[1] * z[1] + x[2] * z[2] + x[3] * z[3]
|
||||
local dyz = y[1] * z[1] + y[2] * z[2] + y[3] * z[3]
|
||||
if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then
|
||||
return nil, nil, nil
|
||||
end
|
||||
local cr = cross(x, y)
|
||||
if cr[1] * z[1] + cr[2] * z[2] + cr[3] * z[3] < 0 then
|
||||
sx = -sx
|
||||
x = { -x[1], -x[2], -x[3] }
|
||||
end
|
||||
-- rotation matrix (columns x, y, z) -> quaternion
|
||||
local m00, m01, m02 = x[1], y[1], z[1]
|
||||
local m10, m11, m12 = x[2], y[2], z[2]
|
||||
local m20, m21, m22 = x[3], y[3], z[3]
|
||||
local tr = m00 + m11 + m22
|
||||
local qx, qy, qz, qw
|
||||
if tr > 0 then
|
||||
local s = sqrt(tr + 1) * 2
|
||||
qw, qx, qy, qz = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s
|
||||
elseif m00 > m11 and m00 > m22 then
|
||||
local s = sqrt(1 + m00 - m11 - m22) * 2
|
||||
qw, qx, qy, qz = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s
|
||||
elseif m11 > m22 then
|
||||
local s = sqrt(1 + m11 - m00 - m22) * 2
|
||||
qw, qx, qy, qz = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s
|
||||
else
|
||||
local s = sqrt(1 + m22 - m00 - m11) * 2
|
||||
qw, qx, qy, qz = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4
|
||||
end
|
||||
local l = sqrt(qx * qx + qy * qy + qz * qz + qw * qw)
|
||||
return { m[13], m[14], m[15] }, { qx / l, qy / l, qz / l, qw / l }, { sx, sy, sz }
|
||||
end
|
||||
|
||||
-- transformPoint / transformDir (column-major m)
|
||||
function DaeMath.point(m: { number }, x: number, y: number, z: number): (number, number, number)
|
||||
return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15]
|
||||
end
|
||||
|
||||
-- the inverse transpose of the upper 3x3 (for normals), as a column-major 4x4
|
||||
function DaeMath.normalMatrix(m: { number }): { number }
|
||||
local a, b, c = m[1], m[5], m[9]
|
||||
local d, e, f = m[2], m[6], m[10]
|
||||
local g, h, i = m[3], m[7], m[11]
|
||||
local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g
|
||||
local det = a * A + b * B + c * C
|
||||
if abs(det) < 1e-30 then
|
||||
return DaeMath.identity()
|
||||
end
|
||||
local k = 1 / det
|
||||
-- inverse = adj / det; its transpose has rows = cofactors
|
||||
return {
|
||||
A * k, B * k, C * k, 0,
|
||||
-(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0,
|
||||
(b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0,
|
||||
0, 0, 0, 1,
|
||||
}
|
||||
end
|
||||
|
||||
return DaeMath
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,376 @@
|
||||
--!strict
|
||||
-- model/dae/Write: Scene -> Collada 1.4.1 text. One <geometry> per mesh primitive (triangles, lines or polylist; strips
|
||||
-- and fans unrolled into triangles, points skipped) with POSITION / NORMAL / TEXCOORD_n (V flipped back) / COLOR_n
|
||||
-- sources sharing one index; common-profile phong (or lambert / constant) effects from the PBR material and its
|
||||
-- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major <matrix>; cameras;
|
||||
-- lights. Not written: skins, morph targets, animations.
|
||||
local Types = require("@formats/Types")
|
||||
local Xml = require("@formats/codecs/Xml")
|
||||
local Base64 = require("@formats/codecs/Base64")
|
||||
local M = require("@formats/model/dae/Math")
|
||||
|
||||
local Write = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local format, concat = string.format, table.concat
|
||||
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/tga"] = "tga", ["image/bmp"] = "bmp", ["image/gif"] = "gif" }
|
||||
|
||||
local function f(v: number): string
|
||||
if v ~= v or v == math.huge or v == -math.huge then
|
||||
return "0"
|
||||
end
|
||||
if v == math.floor(v) and math.abs(v) < 1e15 then
|
||||
return format("%d", v)
|
||||
end
|
||||
return format("%.9g", v)
|
||||
end
|
||||
local function list(v: { number }): string
|
||||
local out = table.create(#v)
|
||||
for i, x in v do
|
||||
out[i] = f(x)
|
||||
end
|
||||
return concat(out, " ")
|
||||
end
|
||||
local function esc(s: string): string
|
||||
return Xml.escapeAttr(s)
|
||||
end
|
||||
local function nameAttr(s: string?): string
|
||||
return if s then ' name="' .. esc(s) .. '"' else ""
|
||||
end
|
||||
|
||||
-- triangle / line corner lists of a primitive (0-based vertex indices) and the element kind
|
||||
local function corners(prim: Types.Primitive): ({ number }?, string?, { number }?)
|
||||
local n = prim.attributes.POSITION.count
|
||||
local idx: { number } = {}
|
||||
if prim.indices then
|
||||
local get = Scene.reader(prim.indices)
|
||||
if not get then
|
||||
return nil, nil, nil
|
||||
end
|
||||
for i = 0, prim.indices.count - 1 do
|
||||
idx[i + 1] = get(i, 0)
|
||||
end
|
||||
else
|
||||
for i = 0, n - 1 do
|
||||
idx[i + 1] = i
|
||||
end
|
||||
end
|
||||
for _, i in idx do
|
||||
if i < 0 or i >= n then
|
||||
return nil, nil, nil
|
||||
end
|
||||
end
|
||||
local mode = prim.mode or "triangles"
|
||||
if mode == "triangles" then
|
||||
local m = #idx - #idx % 3
|
||||
return table.move(idx, 1, m, 1, {}), "triangles", nil
|
||||
elseif mode == "triangle_strip" or mode == "triangle_fan" then
|
||||
local out = {}
|
||||
for k = 1, #idx - 2 do
|
||||
if mode == "triangle_fan" then
|
||||
table.insert(out, idx[1])
|
||||
table.insert(out, idx[k + 1])
|
||||
table.insert(out, idx[k + 2])
|
||||
elseif k % 2 == 1 then
|
||||
table.insert(out, idx[k])
|
||||
table.insert(out, idx[k + 1])
|
||||
table.insert(out, idx[k + 2])
|
||||
else
|
||||
table.insert(out, idx[k + 1])
|
||||
table.insert(out, idx[k])
|
||||
table.insert(out, idx[k + 2])
|
||||
end
|
||||
end
|
||||
return out, "triangles", nil
|
||||
elseif mode == "lines" then
|
||||
local m = #idx - #idx % 2
|
||||
return table.move(idx, 1, m, 1, {}), "lines", nil
|
||||
elseif mode == "line_strip" or mode == "line_loop" then
|
||||
local out = {}
|
||||
for k = 1, #idx - 1 do
|
||||
table.insert(out, idx[k])
|
||||
table.insert(out, idx[k + 1])
|
||||
end
|
||||
if mode == "line_loop" and #idx > 2 then
|
||||
table.insert(out, idx[#idx])
|
||||
table.insert(out, idx[1])
|
||||
end
|
||||
return out, "lines", nil
|
||||
elseif mode == "polygons" and prim.faces then
|
||||
local get = Scene.reader(prim.faces)
|
||||
if not get then
|
||||
return nil, nil, nil
|
||||
end
|
||||
local sizes = {}
|
||||
local total = 0
|
||||
for i = 0, prim.faces.count - 1 do
|
||||
sizes[i + 1] = get(i, 0)
|
||||
total += sizes[i + 1]
|
||||
end
|
||||
if total ~= #idx then
|
||||
return nil, nil, nil
|
||||
end
|
||||
return idx, "polylist", sizes
|
||||
end
|
||||
return nil, nil, nil
|
||||
end
|
||||
|
||||
local function source(out: { string }, id: string, acc: Types.Accessor, comps: number, params: { string }, flipV: boolean)
|
||||
local get = Scene.reader(acc)
|
||||
if not get then
|
||||
return
|
||||
end
|
||||
local vals = table.create(acc.count * comps)
|
||||
local n = 0
|
||||
for i = 0, acc.count - 1 do
|
||||
for c = 0, comps - 1 do
|
||||
n += 1
|
||||
local v = if c < acc.components then get(i, c) else (if c == 3 then 1 else 0)
|
||||
if flipV and c == 1 then
|
||||
v = 1 - v
|
||||
end
|
||||
vals[n] = f(v)
|
||||
end
|
||||
end
|
||||
table.insert(out, format('<source id="%s"><float_array id="%s-array" count="%d">%s</float_array>', id, id, n, concat(vals, " ")))
|
||||
local ps = {}
|
||||
for c = 1, comps do
|
||||
ps[c] = format('<param name="%s" type="float"/>', params[c] or "V")
|
||||
end
|
||||
table.insert(out, format('<technique_common><accessor source="#%s-array" count="%d" stride="%d">%s</accessor></technique_common></source>\n', id, acc.count, comps, concat(ps)))
|
||||
end
|
||||
|
||||
local function colorEl(tag: string, c: { number }?, tex: string?, uv: number?): string
|
||||
if tex then
|
||||
return format('<%s><texture texture="%s" texcoord="UVSET%d"/></%s>', tag, tex, uv or 0, tag)
|
||||
end
|
||||
local v = c or { 0, 0, 0, 1 }
|
||||
return format("<%s><color>%s %s %s %s</color></%s>", tag, f(v[1] or 0), f(v[2] or 0), f(v[3] or 0), f(v[4] or 1), tag)
|
||||
end
|
||||
|
||||
function Write.build(scene: Types.Scene, opts: any?): string?
|
||||
local files = opts and type(opts.files) == "table" and opts.files or nil
|
||||
local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
|
||||
local flipV = not (opts and opts.flipV == false)
|
||||
local out: { string } = {}
|
||||
local function w(s: string)
|
||||
table.insert(out, s)
|
||||
end
|
||||
w('<?xml version="1.0" encoding="utf-8"?>\n<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">\n')
|
||||
local meta = scene.meta or {}
|
||||
local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP"
|
||||
w(format('<asset><contributor><authoring_tool>formats-luau</authoring_tool></contributor><created>1970-01-01T00:00:00Z</created><modified>1970-01-01T00:00:00Z</modified><unit meter="%s" name="unit"/><up_axis>%s</up_axis></asset>\n', f(meta.unit or 1), up))
|
||||
-- images
|
||||
local imageId: { [number]: string } = {}
|
||||
if #scene.textures > 0 then
|
||||
w("<library_images>\n")
|
||||
for i, tex in scene.textures do
|
||||
local uri: string? = nil
|
||||
if tex.data then
|
||||
if files then
|
||||
uri = format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png")
|
||||
files[uri :: string] = tex.data
|
||||
else
|
||||
uri = Base64.dataUri(tex.data, tex.mime or "image/png")
|
||||
end
|
||||
elseif tex.uri then
|
||||
uri = tex.uri
|
||||
end
|
||||
if uri then
|
||||
local id = "image" .. i
|
||||
imageId[i] = id
|
||||
w(format('<image id="%s"%s><init_from>%s</init_from></image>\n', id, nameAttr(tex.name), Xml.escape(uri :: string)))
|
||||
end
|
||||
end
|
||||
w("</library_images>\n")
|
||||
end
|
||||
-- effects + materials
|
||||
if #scene.materials > 0 then
|
||||
w("<library_effects>\n")
|
||||
for i, mat in scene.materials do
|
||||
local ph: any = mat.extras and mat.extras.phong or {}
|
||||
local params = {}
|
||||
local function texParam(ref: Types.TextureRef?): (string?, number?)
|
||||
if not ref or not imageId[ref.texture] then
|
||||
return nil, nil
|
||||
end
|
||||
local sid = "tex" .. ref.texture
|
||||
if not params[sid] then
|
||||
params[sid] = true
|
||||
table.insert(params, format('<newparam sid="%s-surface"><surface type="2D"><init_from>%s</init_from></surface></newparam><newparam sid="%s"><sampler2D><source>%s-surface</source></sampler2D></newparam>', sid, imageId[ref.texture], sid, sid))
|
||||
end
|
||||
return sid, ref.texCoord
|
||||
end
|
||||
local dtex, duv = texParam(mat.baseColorTexture)
|
||||
local etex, euv = texParam(mat.emissiveTexture)
|
||||
local ntex, nuv = texParam(mat.normalTexture)
|
||||
local unlit = mat.extensions and mat.extensions.KHR_materials_unlit ~= nil
|
||||
local model = if unlit then "constant" elseif ph.model == "lambert" then "lambert" else "phong"
|
||||
local body = {}
|
||||
local bc = mat.baseColor
|
||||
if unlit then
|
||||
table.insert(body, colorEl("emission", { bc[1], bc[2], bc[3], 1 }, nil, nil))
|
||||
else
|
||||
table.insert(body, colorEl("emission", if type(ph.emission) == "table" then ph.emission else { mat.emissive[1], mat.emissive[2], mat.emissive[3], 1 }, etex, euv))
|
||||
table.insert(body, colorEl("ambient", if type(ph.ambient) == "table" then ph.ambient else { 0, 0, 0, 1 }, nil, nil))
|
||||
table.insert(body, colorEl("diffuse", { bc[1], bc[2], bc[3], 1 }, dtex, duv))
|
||||
if model == "phong" then
|
||||
table.insert(body, colorEl("specular", if type(ph.specular) == "table" then ph.specular else { 0, 0, 0, 1 }, nil, nil))
|
||||
local sh = if type(ph.shininess) == "number" then ph.shininess else math.max(2 / math.max((mat.roughness or 1) ^ 2, 1e-4) - 2, 0)
|
||||
table.insert(body, format("<shininess><float>%s</float></shininess>", f(sh)))
|
||||
end
|
||||
end
|
||||
if (bc[4] or 1) < 1 then
|
||||
table.insert(body, '<transparent opaque="A_ONE"><color>1 1 1 1</color></transparent>')
|
||||
table.insert(body, format("<transparency><float>%s</float></transparency>", f(bc[4])))
|
||||
end
|
||||
local extra = ""
|
||||
if ntex or mat.doubleSided then
|
||||
extra = "<extra><technique profile=\"FCOLLADA\">" .. (if ntex then format('<bump><texture texture="%s" texcoord="UVSET%d"/></bump>', ntex, nuv or 0) else "") .. (if mat.doubleSided then "<double_sided>1</double_sided>" else "") .. "</technique></extra>"
|
||||
end
|
||||
w(format('<effect id="effect%d"><profile_COMMON>%s<technique sid="common"><%s>%s</%s>%s</technique></profile_COMMON></effect>\n', i, concat(params), model, concat(body), model, extra))
|
||||
end
|
||||
w("</library_effects>\n<library_materials>\n")
|
||||
for i, mat in scene.materials do
|
||||
w(format('<material id="material%d"%s><instance_effect url="#effect%d"/></material>\n', i, nameAttr(mat.name), i))
|
||||
end
|
||||
w("</library_materials>\n")
|
||||
end
|
||||
-- geometries: one per primitive
|
||||
local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {}
|
||||
w("<library_geometries>\n")
|
||||
for mi, mesh in scene.meshes do
|
||||
geoms[mi] = {}
|
||||
for pi, prim in mesh.primitives do
|
||||
local pos = prim.attributes and prim.attributes.POSITION
|
||||
if not pos then
|
||||
continue
|
||||
end
|
||||
local idx, kind, sizes = corners(prim)
|
||||
if not idx or not kind or #idx == 0 then
|
||||
continue
|
||||
end
|
||||
local id = format("mesh%d-%d", mi, pi)
|
||||
w(format('<geometry id="%s"%s><mesh>\n', id, nameAttr(mesh.name)))
|
||||
source(out, id .. "-positions", pos, 3, { "X", "Y", "Z" }, false)
|
||||
local ins = { format('<input semantic="VERTEX" source="#%s-vertices" offset="0"/>', id) }
|
||||
if prim.attributes.NORMAL then
|
||||
source(out, id .. "-normals", prim.attributes.NORMAL, 3, { "X", "Y", "Z" }, false)
|
||||
table.insert(ins, format('<input semantic="NORMAL" source="#%s-normals" offset="0"/>', id))
|
||||
end
|
||||
local sets = 0
|
||||
for k = 0, 7 do
|
||||
local a = prim.attributes["TEXCOORD_" .. k]
|
||||
if not a then
|
||||
break
|
||||
end
|
||||
source(out, format("%s-uv%d", id, k), a, 2, { "S", "T" }, flipV)
|
||||
table.insert(ins, format('<input semantic="TEXCOORD" source="#%s-uv%d" offset="0" set="%d"/>', id, k, k))
|
||||
sets += 1
|
||||
end
|
||||
for k = 0, 7 do
|
||||
local a = prim.attributes["COLOR_" .. k]
|
||||
if not a then
|
||||
break
|
||||
end
|
||||
local c = if a.components >= 4 then 4 else 3
|
||||
source(out, format("%s-color%d", id, k), a, c, { "R", "G", "B", "A" }, false)
|
||||
table.insert(ins, format('<input semantic="COLOR" source="#%s-color%d" offset="0" set="%d"/>', id, k, k))
|
||||
end
|
||||
w(format('<vertices id="%s-vertices"><input semantic="POSITION" source="#%s-positions"/></vertices>\n', id, id))
|
||||
local matAttr = if prim.material and scene.materials[prim.material] then format(' material="m%d"', prim.material) else ""
|
||||
local count = if kind == "triangles" then #idx // 3 elseif kind == "lines" then #idx // 2 else #(sizes :: { number })
|
||||
w(format('<%s count="%d"%s>%s', kind, count, matAttr, concat(ins)))
|
||||
if sizes then
|
||||
w("<vcount>" .. list(sizes) .. "</vcount>")
|
||||
end
|
||||
w("<p>" .. list(idx) .. "</p></" .. kind .. ">\n</mesh></geometry>\n")
|
||||
table.insert(geoms[mi], { id = id, material = if matAttr ~= "" then prim.material else nil, sets = sets })
|
||||
end
|
||||
end
|
||||
w("</library_geometries>\n")
|
||||
-- cameras / lights
|
||||
if #scene.cameras > 0 then
|
||||
w("<library_cameras>\n")
|
||||
for i, cam in scene.cameras do
|
||||
local body: string
|
||||
if cam.type == "orthographic" then
|
||||
body = format("<orthographic><xmag>%s</xmag><ymag>%s</ymag><znear>%s</znear><zfar>%s</zfar></orthographic>", f(cam.xmag or 1), f(cam.ymag or 1), f(cam.znear or 0.1), f(cam.zfar or 1000))
|
||||
else
|
||||
body = format("<perspective><yfov>%s</yfov>%s<znear>%s</znear><zfar>%s</zfar></perspective>", f(math.deg(cam.yfov or 0.8)), if cam.aspect then format("<aspect_ratio>%s</aspect_ratio>", f(cam.aspect)) else "", f(cam.znear or 0.1), f(cam.zfar or 1000))
|
||||
end
|
||||
w(format('<camera id="camera%d"%s><optics><technique_common>%s</technique_common></optics></camera>\n', i, nameAttr(cam.name), body))
|
||||
end
|
||||
w("</library_cameras>\n")
|
||||
end
|
||||
if #scene.lights > 0 then
|
||||
w("<library_lights>\n")
|
||||
for i, l in scene.lights do
|
||||
local c = l.color or { 1, 1, 1 }
|
||||
local k = l.intensity or 1
|
||||
local col = format("<color>%s %s %s</color>", f(c[1] * k), f(c[2] * k), f(c[3] * k))
|
||||
local body = if l.type == "spot" then format("<spot>%s<constant_attenuation>1</constant_attenuation><linear_attenuation>0</linear_attenuation><quadratic_attenuation>0</quadratic_attenuation><falloff_angle>%s</falloff_angle><falloff_exponent>0</falloff_exponent></spot>", col, f(math.deg(l.outerCone or math.pi / 4) * 2))
|
||||
elseif l.type == "point" then format("<point>%s<constant_attenuation>1</constant_attenuation><linear_attenuation>0</linear_attenuation><quadratic_attenuation>0</quadratic_attenuation></point>", col)
|
||||
else format("<directional>%s</directional>", col)
|
||||
w(format('<light id="light%d"%s><technique_common>%s</technique_common></light>\n', i, nameAttr(l.name), body))
|
||||
end
|
||||
w("</library_lights>\n")
|
||||
end
|
||||
-- the node tree
|
||||
w('<library_visual_scenes><visual_scene id="scene" name="scene">\n')
|
||||
local seen: { [number]: boolean } = {}
|
||||
local function node(i: number, depth: number)
|
||||
local n = scene.nodes[i]
|
||||
if not n or seen[i] or depth > 512 then
|
||||
return
|
||||
end
|
||||
seen[i] = true
|
||||
w(format('<node id="node%d"%s type="NODE"><matrix sid="transform">%s</matrix>', i, nameAttr(n.name), list(M.toRows(Scene.nodeMatrix(n)))))
|
||||
if n.mesh and geoms[n.mesh] then
|
||||
for _, g in geoms[n.mesh] do
|
||||
if g.material then
|
||||
local binds = {}
|
||||
for k = 0, g.sets - 1 do
|
||||
table.insert(binds, format('<bind_vertex_input semantic="UVSET%d" input_semantic="TEXCOORD" input_set="%d"/>', k, k))
|
||||
end
|
||||
w(format('<instance_geometry url="#%s"><bind_material><technique_common><instance_material symbol="m%d" target="#material%d">%s</instance_material></technique_common></bind_material></instance_geometry>', g.id, g.material, g.material, concat(binds)))
|
||||
else
|
||||
w(format('<instance_geometry url="#%s"/>', g.id))
|
||||
end
|
||||
end
|
||||
end
|
||||
if n.camera and scene.cameras[n.camera] then
|
||||
w(format('<instance_camera url="#camera%d"/>', n.camera))
|
||||
end
|
||||
if n.light and scene.lights[n.light] then
|
||||
w(format('<instance_light url="#light%d"/>', n.light))
|
||||
end
|
||||
w("\n")
|
||||
for _, c in n.children or {} do
|
||||
node(c, depth + 1)
|
||||
end
|
||||
w("</node>\n")
|
||||
end
|
||||
local roots = scene.roots
|
||||
if not roots or #roots == 0 then
|
||||
local isChild = {}
|
||||
for _, n in scene.nodes do
|
||||
for _, c in n.children or {} do
|
||||
isChild[c] = true
|
||||
end
|
||||
end
|
||||
roots = {}
|
||||
for i in scene.nodes do
|
||||
if not isChild[i] then
|
||||
table.insert(roots, i)
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, r in roots do
|
||||
node(r, 0)
|
||||
end
|
||||
w('</visual_scene></library_visual_scenes>\n<scene><instance_visual_scene url="#scene"/></scene>\n</COLLADA>\n')
|
||||
return concat(out)
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,206 @@
|
||||
--!strict
|
||||
-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos COLLADA specifications; .dae XML, and .zae: a zip holding the .dae, its
|
||||
-- manifest.xml and the images). New code.
|
||||
-- Reads: geometry (<mesh> triangles / polylist / polygons / lines / linestrips / tristrips / trifans with shared input
|
||||
-- offsets, de-indexed per index tuple; n-gons fan-triangulated unless opts.triangulate = false keeps "polygons"),
|
||||
-- common-profile materials (phong / blinn / lambert / constant -> PBR baseColor / emissive / roughness from shininess /
|
||||
-- alpha from transparent + transparency; every Phong term kept in material.extras.phong; FCOLLADA / MAX3D bump ->
|
||||
-- normalTexture, double_sided), images through newparam sampler2D -> surface -> image (1.4) or instance_image (1.5),
|
||||
-- kept encoded (opts.resolve / opts.files, embedded hex <data>, data: URIs), the instanced visual scene (matrix /
|
||||
-- translate / rotate / scale / lookat / skew; instance_geometry / controller / camera / light / node; extra instances
|
||||
-- of a node become child nodes), skin controllers (bind_shape_matrix applied to the mesh, joints by sid under
|
||||
-- <skeleton> or by id / name, INV_BIND_MATRIX, JOINTS_0 / WEIGHTS_0 from the 4 strongest weights, normalized), morph
|
||||
-- controllers (targets as POSITION / NORMAL deltas, weights), cameras (perspective: yfov from xfov / aspect;
|
||||
-- orthographic), lights (directional / point / spot; attenuation in light.extras.dae; ambient lights as
|
||||
-- node.extras.dae.ambientLight), animations (channels on node transform elements: whole elements, .X / .ANGLE
|
||||
-- members, matrix (i)(j) elements; resampled at the union of their key times, rotations over 90 degrees subdivided,
|
||||
-- into glTF TRS channels; one animation per animation_clip, else one for the file). meta.up = the up_axis ("y" / "z"
|
||||
-- / "x"), meta.unit = unit meter; the data is never rotated or scaled. TEXCOORD_n V is flipped to glTF's top-left
|
||||
-- origin (opts.flipV = false keeps Collada's).
|
||||
-- Writes: Collada 1.4.1 (see model/dae/Write: meshes, materials, images, nodes, cameras, lights), or a .zae.
|
||||
-- Not supported: <spline> / <brep> geometry, polygon holes (<ph>: the outer loop only), Bezier / Hermite curves
|
||||
-- (sampled linearly at their keys), animations of non-transform targets, physics / kinematics / FX profiles other than
|
||||
-- COMMON (counted in meta.source.skipped). Writing skins, morphs and animations.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Xml = require("@formats/codecs/Xml")
|
||||
local Zip = require("@formats/containers/Zip")
|
||||
local Read = require("@formats/model/dae/Read")
|
||||
local Write = require("@formats/model/dae/Write")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Dae = {
|
||||
name = "dae",
|
||||
category = "model",
|
||||
extensions = { "dae", "zae" },
|
||||
mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Base64", "containers/Zip" },
|
||||
caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
resolve: ((uri: string) -> any)?, -- image files (buffer or string); the api sets it for paths
|
||||
files: { [string]: any }?, -- or: the files by uri / base name
|
||||
triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives
|
||||
flipV: boolean?, -- TEXCOORD_n v = 1 - v (default true: glTF's convention)
|
||||
maxVertices: number?, -- refuse more output vertices / array values (default 2^25)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
files: { [string]: any }?, -- receives the texture images (else they are written as data: URIs or their uri)
|
||||
name: string?, -- the destination's file name (names the image files)
|
||||
flipV: boolean?, -- default true (the inverse of decode)
|
||||
format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images); the api passes the extension
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Dae.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(2048)
|
||||
if string.sub(head, 1, 4) == "PK\3\4" then
|
||||
local nlen = string.byte(head, 27) or 0
|
||||
local name = string.lower(string.sub(head, 31, 30 + nlen))
|
||||
if string.find(name, "%.dae$") or name == "manifest.xml" then
|
||||
return 0.95
|
||||
end
|
||||
return 0
|
||||
end
|
||||
-- UTF-16 files: drop the zero bytes
|
||||
if string.find(string.sub(head, 1, 4), "\0", 1, true) then
|
||||
head = string.gsub(head, "%z", "")
|
||||
end
|
||||
if string.find(head, "<COLLADA", 1, true) then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function fetcher(opts: DecodeOptions?, zip: any): Read.Fetch
|
||||
return function(uri: string): buffer?
|
||||
local v: any = nil
|
||||
if zip then
|
||||
local d = zip:read(uri)
|
||||
if d then
|
||||
return d
|
||||
end
|
||||
end
|
||||
if not opts then
|
||||
return nil
|
||||
end
|
||||
if type(opts.files) == "table" then
|
||||
v = opts.files[uri]
|
||||
if v == nil then
|
||||
v = opts.files[string.match(uri, "([^/\\]+)$") or uri]
|
||||
end
|
||||
end
|
||||
if v == nil and type(opts.resolve) == "function" then
|
||||
local ok, res = pcall(opts.resolve, uri)
|
||||
v = if ok then res else nil
|
||||
end
|
||||
if type(v) == "string" then
|
||||
return buffer.fromstring(v)
|
||||
end
|
||||
return if type(v) == "buffer" then v else nil
|
||||
end
|
||||
end
|
||||
|
||||
-- the main .dae of a .zae: manifest.xml's <dae_root>, else the first .dae entry
|
||||
local function zae(r: Bytes.Reader): (any, string?, Err.Err?)
|
||||
local zip, err = Zip.open(r)
|
||||
if not zip then
|
||||
return nil, nil, err
|
||||
end
|
||||
local main: string? = nil
|
||||
local manifest = zip:readString("manifest.xml")
|
||||
if manifest then
|
||||
local d = Xml.decode(manifest)
|
||||
local rootEl = d and d.root and Xml.child(d.root, "dae_root")
|
||||
if rootEl then
|
||||
main = string.match(Xml.text(rootEl), "^%s*(.-)%s*$")
|
||||
main = main and string.gsub(main, "^%./", "")
|
||||
end
|
||||
end
|
||||
if not main or not zip:find(main) then
|
||||
main = nil
|
||||
for _, e in zip:list() do
|
||||
if string.find(string.lower(e.name), "%.dae$") then
|
||||
main = e.name
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
if not main then
|
||||
return nil, nil, Err.new(Err.CORRUPT, "zae without a .dae")
|
||||
end
|
||||
local text, rerr = zip:readString(main)
|
||||
if not text then
|
||||
return nil, nil, rerr
|
||||
end
|
||||
return zip, text, nil
|
||||
end
|
||||
|
||||
function Dae.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local text: string
|
||||
local zip: any = nil
|
||||
if r:peek(4) == "PK\3\4" then
|
||||
local z, t, err = zae(r)
|
||||
if not z then
|
||||
return nil, err
|
||||
end
|
||||
zip, text = z, t :: string
|
||||
else
|
||||
text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
end
|
||||
local doc, xerr = Xml.decode(text)
|
||||
if not doc then
|
||||
return nil, xerr
|
||||
end
|
||||
local scene, err = Read.scene(doc, fetcher(opts, zip), opts)
|
||||
if not scene then
|
||||
return nil, err
|
||||
end
|
||||
if zip and scene.meta.source then
|
||||
scene.meta.source.zae = true
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Dae.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.nodes) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a Scene")
|
||||
end
|
||||
if opts and opts.format == "zae" then
|
||||
-- a zip: manifest.xml, the .dae and its images
|
||||
local files = {}
|
||||
local o = table.clone(opts)
|
||||
o.files = files
|
||||
o.name = "model.dae"
|
||||
local text = Write.build(scene, o)
|
||||
if not text then
|
||||
return nil, Err.new(Err.ARG, "the scene could not be written")
|
||||
end
|
||||
local w = Zip.writer()
|
||||
w:add("manifest.xml", '<?xml version="1.0" encoding="utf-8"?>\n<dae_root>./model.dae</dae_root>\n')
|
||||
w:add("model.dae", text)
|
||||
local names = {}
|
||||
for name in files do
|
||||
table.insert(names, name)
|
||||
end
|
||||
table.sort(names)
|
||||
for _, name in names do
|
||||
w:add(name, files[name], { method = "store" })
|
||||
end
|
||||
return w:finish()
|
||||
end
|
||||
local text = Write.build(scene, opts)
|
||||
if not text then
|
||||
return nil, Err.new(Err.ARG, "the scene could not be written")
|
||||
end
|
||||
return buffer.fromstring(text), nil
|
||||
end
|
||||
|
||||
return Dae
|
||||
@@ -0,0 +1,274 @@
|
||||
--!strict
|
||||
-- model/fbx/Ascii: the ASCII FBX node tree reader and writer (7.x: "Name: value, value, ... { children }", ';'
|
||||
-- comments, "*N { a: ... }" arrays, " in strings). Produces the same Node / Array values as model/fbx/Binary
|
||||
-- (arrays as f64 buffers; integers longer than 15 digits stay strings so ids are exact). Never throws.
|
||||
local Base64 = require("@formats/core/Base64")
|
||||
|
||||
local Ascii = {}
|
||||
|
||||
type Node = { name: string, props: { any }, children: { Node } }
|
||||
|
||||
local sbyte, sfind, ssub = string.byte, string.find, string.sub
|
||||
local MAX_DEPTH = 128
|
||||
|
||||
local function isNameStart(c: number): boolean
|
||||
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
|
||||
end
|
||||
|
||||
-- parse(text) -> root node (children = the top-level nodes), version | nil, message, offset
|
||||
function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, number?)
|
||||
local maxBytes = opts and opts.maxBytes or 2 ^ 30
|
||||
local n = #text
|
||||
local i = 1
|
||||
local total = 0
|
||||
|
||||
local function skip()
|
||||
while i <= n do
|
||||
local c = sbyte(text, i)
|
||||
if c == 59 then -- ; comment
|
||||
local e = sfind(text, "\n", i, true)
|
||||
i = if e then e + 1 else n + 1
|
||||
elseif c == 32 or c == 9 or c == 10 or c == 13 then
|
||||
i += 1
|
||||
else
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- at i: a name followed by ':'? -> name, the index after ':'
|
||||
local function nameAt(): (string?, number)
|
||||
local c = sbyte(text, i)
|
||||
if not c or not isNameStart(c) then
|
||||
return nil, i
|
||||
end
|
||||
local s, e = sfind(text, "^[%w_|%-]+", i)
|
||||
if not s then
|
||||
return nil, i
|
||||
end
|
||||
local j = (e :: number) + 1
|
||||
while j <= n do
|
||||
local d = sbyte(text, j)
|
||||
if d == 32 or d == 9 then
|
||||
j += 1
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
if sbyte(text, j) == 58 then
|
||||
return ssub(text, i, e :: number), j + 1
|
||||
end
|
||||
return nil, i
|
||||
end
|
||||
|
||||
-- the values of one node (after the ':'), up to a new name, '{' or '}'
|
||||
local function values(): ({ any }?, string?)
|
||||
local props = {}
|
||||
while true do
|
||||
skip()
|
||||
if i > n then
|
||||
return props
|
||||
end
|
||||
local c = sbyte(text, i)
|
||||
if c == 44 then -- ,
|
||||
i += 1
|
||||
elseif c == 123 or c == 125 then
|
||||
return props
|
||||
elseif c == 34 then -- "
|
||||
local e = sfind(text, "\"", i + 1, true)
|
||||
if not e then
|
||||
return nil, "unterminated string"
|
||||
end
|
||||
local s = ssub(text, i + 1, e - 1)
|
||||
if sfind(s, "&", 1, true) then
|
||||
s = string.gsub(s, """, "\"")
|
||||
end
|
||||
table.insert(props, s)
|
||||
i = e + 1
|
||||
elseif c == 42 then -- *N
|
||||
local s, e = sfind(text, "^%*%d+", i)
|
||||
if not s then
|
||||
return nil, "bad array length"
|
||||
end
|
||||
table.insert(props, { star = tonumber(ssub(text, i + 1, e :: number)) })
|
||||
i = (e :: number) + 1
|
||||
elseif (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then
|
||||
local s, e = sfind(text, "^[-+%deE.]+", i)
|
||||
local tok = ssub(text, i, e :: number)
|
||||
local v = tonumber(tok)
|
||||
if v == nil then
|
||||
-- "1.#INF", "-1.#IND", "nan": special floats
|
||||
local s2, e2 = sfind(text, "^[-+%w.#]+", i)
|
||||
tok = ssub(text, i, e2 :: number)
|
||||
local low = string.lower(tok)
|
||||
if sfind(low, "inf", 1, true) then
|
||||
v = if sbyte(tok, 1) == 45 then -math.huge else math.huge
|
||||
else
|
||||
v = 0 / 0
|
||||
end
|
||||
e = e2
|
||||
local _ = s2
|
||||
elseif #tok > 15 and not sfind(tok, "[.eE]") then
|
||||
v = (if sbyte(tok, 1) == 45 then "L-" else "L") .. string.gsub(tok, "^[-+]", "") :: any
|
||||
end
|
||||
local _ = s
|
||||
table.insert(props, v)
|
||||
i = (e :: number) + 1
|
||||
else
|
||||
local nm = nameAt()
|
||||
if nm then
|
||||
return props
|
||||
end
|
||||
local s, e = sfind(text, "^[%w_]+", i)
|
||||
if not s then
|
||||
return nil, string.format("unexpected character %q", ssub(text, i, i))
|
||||
end
|
||||
table.insert(props, ssub(text, i, e :: number))
|
||||
i = (e :: number) + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function nodes(depth: number, into: { Node }): string?
|
||||
while true do
|
||||
skip()
|
||||
if i > n then
|
||||
return if depth > 0 then "unterminated {" else nil
|
||||
end
|
||||
if sbyte(text, i) == 125 then
|
||||
if depth == 0 then
|
||||
return "unbalanced }"
|
||||
end
|
||||
i += 1
|
||||
return nil
|
||||
end
|
||||
local name, j = nameAt()
|
||||
if not name then
|
||||
return string.format("expected a node name at %q", ssub(text, i, i + 10))
|
||||
end
|
||||
i = j
|
||||
local props, err = values()
|
||||
if not props then
|
||||
return err
|
||||
end
|
||||
local node: Node = { name = name, props = props, children = {} }
|
||||
skip()
|
||||
if sbyte(text, i) == 123 then
|
||||
if depth >= MAX_DEPTH then
|
||||
return "nodes nested too deep"
|
||||
end
|
||||
i += 1
|
||||
local e = nodes(depth + 1, node.children)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
end
|
||||
-- "*N { a: v, v, ... }" -> an Array
|
||||
local p1 = props[1]
|
||||
if #props == 1 and type(p1) == "table" and p1.star then
|
||||
local a = node.children[1]
|
||||
local count = if a and a.name == "a" then #a.props else 0
|
||||
total += count * 8
|
||||
if total > maxBytes then
|
||||
return "limit:arrays over " .. maxBytes .. " bytes"
|
||||
end
|
||||
local data = buffer.create(count * 8)
|
||||
for k = 1, count do
|
||||
local v = (a :: Node).props[k]
|
||||
buffer.writef64(data, (k - 1) * 8, if type(v) == "number" then v else (tonumber(v) or 0))
|
||||
end
|
||||
node.props = { { array = true, type = "d", count = count, data = data } }
|
||||
node.children = {}
|
||||
end
|
||||
table.insert(into, node)
|
||||
end
|
||||
end
|
||||
|
||||
local root: Node = { name = "", props = {}, children = {} }
|
||||
local err = nodes(0, root.children)
|
||||
if err then
|
||||
return nil, err, i - 1
|
||||
end
|
||||
local version = nil
|
||||
for _, c in root.children do
|
||||
if c.name == "FBXHeaderExtension" then
|
||||
for _, d in c.children do
|
||||
if d.name == "FBXVersion" then
|
||||
version = d.props[1]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return root, version, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writer
|
||||
local function fmt(v: number): string
|
||||
if v == math.floor(v) and math.abs(v) < 1e15 then
|
||||
return string.format("%d", v)
|
||||
end
|
||||
if v ~= v then
|
||||
return "0"
|
||||
end
|
||||
return string.format("%.17g", v)
|
||||
end
|
||||
|
||||
-- write(root) -> string: the ASCII form of a tree (the same node shapes Binary.write takes)
|
||||
function Ascii.write(root: any, version: number?): string
|
||||
local out = { string.format("; FBX %d.%d.0 project file\n; Created by formats-luau\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) }
|
||||
local function node(nd: any, indent: string)
|
||||
local parts = {}
|
||||
local arr = nil
|
||||
for _, v in nd.props do
|
||||
local tv = type(v)
|
||||
if tv == "number" then
|
||||
table.insert(parts, fmt(v))
|
||||
elseif tv == "boolean" then
|
||||
table.insert(parts, if v then "T" else "F")
|
||||
elseif tv == "string" then
|
||||
if string.sub(v, 1, 1) == "L" and string.find(v, "^L%-?%d+$") then
|
||||
table.insert(parts, string.sub(v, 2))
|
||||
else
|
||||
local nm, cls = string.match(v, "^(.-)%z\1(.*)$")
|
||||
local sv = if nm then cls .. "::" .. nm else v
|
||||
table.insert(parts, "\"" .. string.gsub(sv, "\"", """) .. "\"")
|
||||
end
|
||||
elseif tv == "table" and v.array then
|
||||
arr = v
|
||||
elseif tv == "buffer" then
|
||||
-- raw bytes (Video Content): base64, split into lines as the FBX SDK writes them
|
||||
local b64 = Base64.encode(v)
|
||||
local chunks = {}
|
||||
for k = 1, #b64, 2048 do
|
||||
table.insert(chunks, "\"" .. string.sub(b64, k, k + 2047) .. "\"")
|
||||
end
|
||||
table.insert(parts, if #chunks > 0 then table.concat(chunks, ",\n") else "\"\"")
|
||||
end
|
||||
end
|
||||
if arr then
|
||||
local vals = table.create(arr.count)
|
||||
for k = 0, arr.count - 1 do
|
||||
vals[k + 1] = fmt(buffer.readf64(arr.data, k * 8))
|
||||
end
|
||||
table.insert(out, string.format("%s%s: *%d {\n%s\ta: %s\n%s}\n", indent, nd.name, arr.count, indent, table.concat(vals, ","), indent))
|
||||
return
|
||||
end
|
||||
table.insert(out, indent .. nd.name .. ": " .. table.concat(parts, ", "))
|
||||
local ch = nd.children
|
||||
if ch and #ch > 0 then
|
||||
table.insert(out, " {\n")
|
||||
for _, c in ch do
|
||||
node(c, indent .. "\t")
|
||||
end
|
||||
table.insert(out, indent .. "}\n")
|
||||
else
|
||||
table.insert(out, "\n")
|
||||
end
|
||||
end
|
||||
for _, c in root.children do
|
||||
node(c, "")
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
return Ascii
|
||||
@@ -0,0 +1,461 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit
|
||||
-- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's
|
||||
-- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/Deflate when compressed and kept as Tree.Array
|
||||
-- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become
|
||||
-- the string "L<hex>" so ids stay exact. Never throws: errors are returned (nil, message, offset).
|
||||
local Deflate = require("@formats/codecs/Deflate")
|
||||
|
||||
local Binary = {}
|
||||
|
||||
export type Node = { name: string, props: { any }, children: { Node } }
|
||||
export type Array = { array: true, type: string, count: number, data: buffer }
|
||||
|
||||
local MAGIC = "Kaydara FBX Binary \0"
|
||||
Binary.MAGIC = MAGIC
|
||||
local FOOT_ID = "\250\188\171\9\208\200\212\102\177\118\251\131\28\247\38\126"
|
||||
local FOOT_MAGIC = "\248\90\140\106\222\245\217\126\236\233\12\227\117\143\41\11"
|
||||
local MAX_DEPTH = 128
|
||||
|
||||
local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16
|
||||
local writef64 = buffer.writef64
|
||||
|
||||
-- a signed 64-bit integer at p: a number when exact (|v| < 2^53), else "L<16 hex digits>"
|
||||
local function i64(b: buffer, p: number, asString: boolean): any
|
||||
local lo, hi = readu32(b, p), readu32(b, p + 4)
|
||||
if hi >= 0x80000000 then
|
||||
local v = (hi - 4294967296) * 4294967296 + lo
|
||||
if v >= -9007199254740991 or not asString then
|
||||
return v
|
||||
end
|
||||
else
|
||||
if hi < 0x200000 or not asString then
|
||||
return hi * 4294967296 + lo
|
||||
end
|
||||
end
|
||||
return string.format("L%08x%08x", hi, lo)
|
||||
end
|
||||
Binary.i64 = i64
|
||||
|
||||
local ELEM = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 }
|
||||
|
||||
-- the elements of a raw array (n elements of type t at p) as f64s
|
||||
local function toF64(t: string, src: buffer, p: number, n: number): buffer
|
||||
local out = buffer.create(n * 8)
|
||||
if t == "d" then
|
||||
buffer.copy(out, 0, src, p, n * 8)
|
||||
elseif t == "f" then
|
||||
for k = 0, n - 1 do
|
||||
writef64(out, k * 8, readf32(src, p + k * 4))
|
||||
end
|
||||
elseif t == "i" then
|
||||
for k = 0, n - 1 do
|
||||
writef64(out, k * 8, readi32(src, p + k * 4))
|
||||
end
|
||||
elseif t == "l" then
|
||||
for k = 0, n - 1 do
|
||||
local lo, hi = readu32(src, p + k * 8), readu32(src, p + k * 8 + 4)
|
||||
writef64(out, k * 8, if hi >= 0x80000000 then (hi - 4294967296) * 4294967296 + lo else hi * 4294967296 + lo)
|
||||
end
|
||||
else
|
||||
for k = 0, n - 1 do
|
||||
writef64(out, k * 8, readu8(src, p + k))
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- parse(buf, base, limit, opts?) -> root node (name "", children = the top-level nodes), version | nil, message, offset
|
||||
function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?)
|
||||
local maxBytes = opts and opts.maxBytes or 2 ^ 30
|
||||
if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then
|
||||
return nil, "not a binary FBX", base
|
||||
end
|
||||
local version = readu32(b, base + 23)
|
||||
if version < 7000 or version >= 10000 then
|
||||
return nil, "unsupported:FBX version " .. version, base + 23
|
||||
end
|
||||
local wide = version >= 7500
|
||||
local head = if wide then 25 else 13
|
||||
local total = 0
|
||||
|
||||
local function props(p: number, n: number, stop: number): ({ any }?, any)
|
||||
local out = table.create(math.min(n, 64))
|
||||
for k = 1, n do
|
||||
if p >= stop then
|
||||
return nil, "property list runs past its record"
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
local v: any
|
||||
if c == 89 then -- Y
|
||||
if p + 2 > stop then return nil, "truncated property" end
|
||||
v = readi16(b, p)
|
||||
p += 2
|
||||
elseif c == 67 then -- C
|
||||
if p + 1 > stop then return nil, "truncated property" end
|
||||
v = readu8(b, p) ~= 0
|
||||
p += 1
|
||||
elseif c == 73 then -- I
|
||||
if p + 4 > stop then return nil, "truncated property" end
|
||||
v = readi32(b, p)
|
||||
p += 4
|
||||
elseif c == 70 then -- F
|
||||
if p + 4 > stop then return nil, "truncated property" end
|
||||
v = readf32(b, p)
|
||||
p += 4
|
||||
elseif c == 68 then -- D
|
||||
if p + 8 > stop then return nil, "truncated property" end
|
||||
v = readf64(b, p)
|
||||
p += 8
|
||||
elseif c == 76 then -- L
|
||||
if p + 8 > stop then return nil, "truncated property" end
|
||||
v = i64(b, p, true)
|
||||
p += 8
|
||||
elseif c == 83 or c == 82 then -- S, R
|
||||
if p + 4 > stop then return nil, "truncated property" end
|
||||
local len = readu32(b, p)
|
||||
p += 4
|
||||
if len > stop - p then return nil, "string runs past its record" end
|
||||
if c == 83 then
|
||||
v = buffer.readstring(b, p, len)
|
||||
else
|
||||
local raw = buffer.create(len)
|
||||
buffer.copy(raw, 0, b, p, len)
|
||||
v = raw
|
||||
end
|
||||
p += len
|
||||
elseif c == 102 or c == 100 or c == 108 or c == 105 or c == 98 or c == 99 then -- f d l i b c
|
||||
if p + 12 > stop then return nil, "truncated array header" end
|
||||
local count, enc, clen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8)
|
||||
p += 12
|
||||
local t = string.char(c)
|
||||
local es = ELEM[t]
|
||||
if clen > stop - p then return nil, "array runs past its record" end
|
||||
total += count * 8
|
||||
if total > maxBytes then return nil, "limit:arrays over " .. maxBytes .. " bytes" end
|
||||
local data: buffer
|
||||
if enc == 0 then
|
||||
if clen < count * es then return nil, "raw array shorter than its count" end
|
||||
data = toF64(t, b, p, count)
|
||||
elseif enc == 1 then
|
||||
local raw, err = Deflate.zlib(b, p, clen, count * es)
|
||||
if not raw then
|
||||
return nil, "array: " .. tostring(if type(err) == "table" then err.message else err)
|
||||
end
|
||||
data = toF64(t, raw, 0, count)
|
||||
else
|
||||
return nil, "unknown array encoding " .. enc
|
||||
end
|
||||
p += clen
|
||||
v = { array = true, type = t, count = count, data = data }
|
||||
else
|
||||
return nil, string.format("unknown property type 0x%02x", c)
|
||||
end
|
||||
out[k] = v
|
||||
end
|
||||
return out, p
|
||||
end
|
||||
|
||||
-- one node record at p: node | false (the null record), next offset | nil, message, offset
|
||||
local function node(p: number, stop: number, depth: number): (any, any, number?)
|
||||
if p + head > stop then
|
||||
return nil, "truncated node record", p
|
||||
end
|
||||
local endOff, nprops, plen, nlen
|
||||
if wide then
|
||||
endOff = readu32(b, p) + readu32(b, p + 4) * 4294967296
|
||||
nprops = readu32(b, p + 8) + readu32(b, p + 12) * 4294967296
|
||||
plen = readu32(b, p + 16) + readu32(b, p + 20) * 4294967296
|
||||
nlen = readu8(b, p + 24)
|
||||
else
|
||||
endOff, nprops, plen, nlen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8), readu8(b, p + 12)
|
||||
end
|
||||
if endOff == 0 then
|
||||
return false, p + head
|
||||
end
|
||||
local e = base + endOff
|
||||
if e > stop or e < p + head + nlen + plen then
|
||||
return nil, "node end offset out of range", p
|
||||
end
|
||||
if nprops > plen then
|
||||
return nil, "more properties than bytes", p
|
||||
end
|
||||
local q = p + head
|
||||
local name = buffer.readstring(b, q, nlen)
|
||||
q += nlen
|
||||
local pl, nq = props(q, nprops, q + plen)
|
||||
if not pl then
|
||||
return nil, nq, q
|
||||
end
|
||||
q += plen
|
||||
local children: { Node } = {}
|
||||
if q < e then
|
||||
if depth >= MAX_DEPTH then
|
||||
return nil, "nodes nested too deep", p
|
||||
end
|
||||
while q < e do
|
||||
local child, nx, off = node(q, e, depth + 1)
|
||||
if child == nil then
|
||||
return nil, nx, off
|
||||
end
|
||||
q = nx
|
||||
if child == false then
|
||||
break
|
||||
end
|
||||
table.insert(children, child)
|
||||
end
|
||||
end
|
||||
return { name = name, props = pl, children = children }, e
|
||||
end
|
||||
|
||||
local root: Node = { name = "", props = {}, children = {} }
|
||||
local p = base + 27
|
||||
while p < limit do
|
||||
local n, nx, off = node(p, limit, 0)
|
||||
if n == nil then
|
||||
if #root.children > 0 and p + head > limit then
|
||||
break -- a file cut right after its last node: keep what was read
|
||||
end
|
||||
return nil, nx, off
|
||||
end
|
||||
if n == false then
|
||||
break
|
||||
end
|
||||
table.insert(root.children, n)
|
||||
p = nx
|
||||
end
|
||||
return root, version, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writer
|
||||
-- write(root, version?) -> buffer: the children of root as a binary FBX file (default version 7400, the 32-bit
|
||||
-- record layout; 7500+ writes 64-bit records). Values: numbers are written as D unless the node gives a type hint
|
||||
-- (node.types = "ILDS..." one character per property), booleans as C, strings as S, buffers as R, Arrays by their
|
||||
-- type (compressed with zlib when longer than 32 elements, unless compress = false).
|
||||
export type WNode = { name: string, props: { any }, children: { WNode }?, types: string? }
|
||||
|
||||
local function sizeHint(n: WNode): number
|
||||
local s = 32 + #n.name
|
||||
for _, v in n.props do
|
||||
if type(v) == "string" then
|
||||
s += 5 + #v
|
||||
elseif type(v) == "buffer" then
|
||||
s += 5 + buffer.len(v)
|
||||
elseif type(v) == "table" then
|
||||
s += 13 + (v.count or 0) * 8
|
||||
else
|
||||
s += 9
|
||||
end
|
||||
end
|
||||
for _, c in n.children or {} do
|
||||
s += sizeHint(c)
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
function Binary.write(root: WNode, version: number?, compress: boolean?): buffer
|
||||
local zip = compress ~= false
|
||||
local ver = version or 7400
|
||||
local wide = ver >= 7500
|
||||
local head = if wide then 25 else 13
|
||||
local cap = sizeHint(root) + 256
|
||||
local out = buffer.create(cap)
|
||||
local pos = 0
|
||||
local function ensure(n: number)
|
||||
if pos + n > cap then
|
||||
while pos + n > cap do
|
||||
cap *= 2
|
||||
end
|
||||
local nb = buffer.create(cap)
|
||||
buffer.copy(nb, 0, out, 0, pos)
|
||||
out = nb
|
||||
end
|
||||
end
|
||||
local function u8(v: number)
|
||||
ensure(1)
|
||||
buffer.writeu8(out, pos, v)
|
||||
pos += 1
|
||||
end
|
||||
local function u32(v: number)
|
||||
ensure(4)
|
||||
buffer.writeu32(out, pos, v)
|
||||
pos += 4
|
||||
end
|
||||
local function i64w(v: number)
|
||||
ensure(8)
|
||||
local hi = math.floor(v / 4294967296)
|
||||
local lo = v - hi * 4294967296
|
||||
buffer.writeu32(out, pos, lo)
|
||||
buffer.writeu32(out, pos + 4, hi % 4294967296)
|
||||
pos += 8
|
||||
end
|
||||
local function str(s: string)
|
||||
ensure(#s)
|
||||
buffer.writestring(out, pos, s)
|
||||
pos += #s
|
||||
end
|
||||
local function bytes(src: buffer)
|
||||
local n = buffer.len(src)
|
||||
ensure(n)
|
||||
buffer.copy(out, pos, src, 0, n)
|
||||
pos += n
|
||||
end
|
||||
local function array(a: any)
|
||||
local t, n, d = a.type, a.count, a.data
|
||||
local es = ELEM[t] or 8
|
||||
local raw = buffer.create(n * es)
|
||||
if a.raw then
|
||||
buffer.copy(raw, 0, a.raw, 0, math.min(buffer.len(a.raw), n * es))
|
||||
else
|
||||
for k = 0, n - 1 do
|
||||
local v = readf64(d, k * 8)
|
||||
if t == "d" then
|
||||
writef64(raw, k * 8, v)
|
||||
elseif t == "f" then
|
||||
buffer.writef32(raw, k * 4, v)
|
||||
elseif t == "i" then
|
||||
buffer.writei32(raw, k * 4, v)
|
||||
elseif t == "b" then
|
||||
buffer.writeu8(raw, k, if v ~= 0 then 1 else 0)
|
||||
else
|
||||
local hi = math.floor(v / 4294967296)
|
||||
buffer.writeu32(raw, k * 8, v - hi * 4294967296)
|
||||
buffer.writeu32(raw, k * 8 + 4, hi % 4294967296)
|
||||
end
|
||||
end
|
||||
end
|
||||
u8(string.byte(t))
|
||||
u32(n)
|
||||
if zip and n > 32 then
|
||||
local z = Deflate.zlibCompress(raw, { level = 6 })
|
||||
if z then
|
||||
u32(1)
|
||||
u32(buffer.len(z))
|
||||
bytes(z)
|
||||
return
|
||||
end
|
||||
end
|
||||
u32(0)
|
||||
u32(n * es)
|
||||
bytes(raw)
|
||||
end
|
||||
local function setOff(at: number, v: number)
|
||||
if wide then
|
||||
buffer.writeu32(out, at, v % 4294967296)
|
||||
buffer.writeu32(out, at + 4, math.floor(v / 4294967296))
|
||||
else
|
||||
buffer.writeu32(out, at, v)
|
||||
end
|
||||
end
|
||||
local function nullRecord()
|
||||
ensure(head)
|
||||
buffer.fill(out, pos, 0, head)
|
||||
pos += head
|
||||
end
|
||||
local function node(n: WNode)
|
||||
local start = pos
|
||||
ensure(head)
|
||||
buffer.fill(out, pos, 0, head)
|
||||
pos += head
|
||||
buffer.writeu8(out, start + head - 1, #n.name)
|
||||
str(n.name)
|
||||
local pstart = pos
|
||||
local hints = n.types or ""
|
||||
for k, v in n.props do
|
||||
local h = string.sub(hints, k, k)
|
||||
local tv = type(v)
|
||||
if tv == "number" then
|
||||
if h == "I" then
|
||||
u8(73)
|
||||
ensure(4)
|
||||
buffer.writei32(out, pos, v)
|
||||
pos += 4
|
||||
elseif h == "L" then
|
||||
u8(76)
|
||||
i64w(v)
|
||||
elseif h == "F" then
|
||||
u8(70)
|
||||
ensure(4)
|
||||
buffer.writef32(out, pos, v)
|
||||
pos += 4
|
||||
elseif h == "Y" then
|
||||
u8(89)
|
||||
ensure(2)
|
||||
buffer.writei16(out, pos, v)
|
||||
pos += 2
|
||||
else
|
||||
u8(68)
|
||||
ensure(8)
|
||||
writef64(out, pos, v)
|
||||
pos += 8
|
||||
end
|
||||
elseif tv == "boolean" then
|
||||
u8(67)
|
||||
u8(if v then 1 else 0)
|
||||
elseif tv == "string" then
|
||||
if string.sub(v, 1, 1) == "L" and h == "L" and #v == 17 then
|
||||
u8(76)
|
||||
local hi, lo = tonumber(string.sub(v, 2, 9), 16) or 0, tonumber(string.sub(v, 10, 17), 16) or 0
|
||||
u32(lo)
|
||||
u32(hi)
|
||||
else
|
||||
u8(83)
|
||||
u32(#v)
|
||||
str(v)
|
||||
end
|
||||
elseif tv == "buffer" then
|
||||
u8(82)
|
||||
u32(buffer.len(v))
|
||||
bytes(v)
|
||||
elseif tv == "table" and v.array then
|
||||
array(v)
|
||||
else
|
||||
u8(83)
|
||||
u32(0)
|
||||
end
|
||||
end
|
||||
local plen = pos - pstart
|
||||
local children = n.children
|
||||
if children and #children > 0 then
|
||||
for _, c in children do
|
||||
node(c)
|
||||
end
|
||||
nullRecord()
|
||||
elseif #n.props == 0 then
|
||||
nullRecord()
|
||||
end
|
||||
setOff(start, pos)
|
||||
if wide then
|
||||
setOff(start + 8, #n.props)
|
||||
setOff(start + 16, plen)
|
||||
else
|
||||
buffer.writeu32(out, start + 4, #n.props)
|
||||
buffer.writeu32(out, start + 8, plen)
|
||||
end
|
||||
end
|
||||
str(MAGIC)
|
||||
u8(0x1A)
|
||||
u8(0)
|
||||
u32(ver)
|
||||
for _, c in root.children or {} do
|
||||
node(c)
|
||||
end
|
||||
nullRecord()
|
||||
str(FOOT_ID)
|
||||
str("\0\0\0\0")
|
||||
local pad = ((pos + 15) // 16) * 16 - pos
|
||||
if pad == 0 then
|
||||
pad = 16
|
||||
end
|
||||
str(string.rep("\0", pad))
|
||||
u32(ver)
|
||||
str(string.rep("\0", 120))
|
||||
str(FOOT_MAGIC)
|
||||
local res = buffer.create(pos)
|
||||
buffer.copy(res, 0, out, 0, pos)
|
||||
return res
|
||||
end
|
||||
|
||||
return Binary
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,996 @@
|
||||
--!strict
|
||||
-- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types
|
||||
-- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f).
|
||||
-- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one
|
||||
-- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals
|
||||
-- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material;
|
||||
-- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets ->
|
||||
-- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Xform = require("@formats/model/fbx/Xform")
|
||||
|
||||
local Write = {}
|
||||
|
||||
type WNode = { name: string, props: { any }, children: { WNode }?, types: string? }
|
||||
|
||||
local TICKS = 46186158000
|
||||
local ORIENT_INV = { camera = { 0, 90, 0 }, light = { 90, 0, 0 } }
|
||||
|
||||
local function N(name: string, types: string, props: { any }, children: { WNode }?): WNode
|
||||
return { name = name, types = types, props = props, children = children }
|
||||
end
|
||||
local function arr(t: string, list: { number }): any
|
||||
local n = #list
|
||||
local d = buffer.create(n * 8)
|
||||
for k = 1, n do
|
||||
buffer.writef64(d, (k - 1) * 8, list[k])
|
||||
end
|
||||
return { array = true, type = t, count = n, data = d }
|
||||
end
|
||||
-- P: name, type, label, flags, values (vt: one type character per value)
|
||||
local function P(name: string, ptype: string, label: string, flags: string, vt: string, ...: any): WNode
|
||||
return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } }
|
||||
end
|
||||
local function Pvec(name: string, ptype: string, label: string, v: { number }): WNode
|
||||
return P(name, ptype, label, "A", "DDD", v[1], v[2], v[3])
|
||||
end
|
||||
local function Pcolor(name: string, v: { number }): WNode
|
||||
return P(name, "Color", "", "A", "DDD", v[1] or 0, v[2] or 0, v[3] or 0)
|
||||
end
|
||||
local function Pnum(name: string, v: number): WNode
|
||||
return P(name, "Number", "", "A", "D", v)
|
||||
end
|
||||
local function Pint(name: string, v: number): WNode
|
||||
return P(name, "int", "Integer", "", "I", v)
|
||||
end
|
||||
local function Penum(name: string, v: number): WNode
|
||||
return P(name, "enum", "", "", "I", v)
|
||||
end
|
||||
local function Pdouble(name: string, v: number): WNode
|
||||
return P(name, "double", "Number", "", "D", v)
|
||||
end
|
||||
local function Ptime(name: string, v: number): WNode
|
||||
return P(name, "KTime", "Time", "", "L", v)
|
||||
end
|
||||
local function cls(name: string?, class: string): string
|
||||
return (name or "") .. "\0\1" .. class
|
||||
end
|
||||
|
||||
local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) -> number)?
|
||||
if not acc then
|
||||
return nil
|
||||
end
|
||||
return Types.Scene.reader(acc)
|
||||
end
|
||||
|
||||
-- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based)
|
||||
local function faces(prim: Types.Primitive): { { number } }?
|
||||
local pos = prim.attributes.POSITION
|
||||
if not pos then
|
||||
return nil
|
||||
end
|
||||
local n = pos.count
|
||||
local idx = accessorReader(prim.indices)
|
||||
local count = if prim.indices then prim.indices.count else n
|
||||
local function I(k: number): number
|
||||
return if idx then idx(k, 0) else k
|
||||
end
|
||||
local out: { { number } } = {}
|
||||
local mode = prim.mode or "triangles"
|
||||
if mode == "triangles" then
|
||||
for k = 0, count // 3 - 1 do
|
||||
table.insert(out, { I(k * 3), I(k * 3 + 1), I(k * 3 + 2) })
|
||||
end
|
||||
elseif mode == "polygons" and prim.faces then
|
||||
local f = accessorReader(prim.faces)
|
||||
local p = 0
|
||||
if f then
|
||||
for k = 0, prim.faces.count - 1 do
|
||||
local sz = f(k, 0)
|
||||
if p + sz > count then
|
||||
break
|
||||
end
|
||||
local poly = table.create(sz)
|
||||
for q = 0, sz - 1 do
|
||||
poly[q + 1] = I(p + q)
|
||||
end
|
||||
p += sz
|
||||
table.insert(out, poly)
|
||||
end
|
||||
end
|
||||
elseif mode == "triangle_strip" then
|
||||
for k = 0, count - 3 do
|
||||
local a, b, c = I(k), I(k + 1), I(k + 2)
|
||||
if k % 2 == 1 then
|
||||
a, b = b, a
|
||||
end
|
||||
table.insert(out, { a, b, c })
|
||||
end
|
||||
elseif mode == "triangle_fan" then
|
||||
for k = 1, count - 2 do
|
||||
table.insert(out, { I(0), I(k), I(k + 1) })
|
||||
end
|
||||
else
|
||||
return nil -- points / lines: not written
|
||||
end
|
||||
for _, f in out do
|
||||
for q, v in f do
|
||||
if v < 0 or v >= n then
|
||||
f[q] = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
|
||||
local flipV = not (opts and opts.flipV == false)
|
||||
local embed = not (opts and opts.embedTextures == false)
|
||||
local nextId = 1000000
|
||||
local function id(): number
|
||||
nextId += 1
|
||||
return nextId
|
||||
end
|
||||
local objects: { WNode } = {}
|
||||
local conns: { WNode } = {}
|
||||
local counts: { [string]: number } = {}
|
||||
local function add(class: string, node: WNode)
|
||||
table.insert(objects, node)
|
||||
counts[class] = (counts[class] or 0) + 1
|
||||
end
|
||||
local function OO(child: number, parent: number)
|
||||
table.insert(conns, N("C", "SLL", { "OO", child, parent }))
|
||||
end
|
||||
local function OP(child: number, parent: number, prop: string)
|
||||
table.insert(conns, N("C", "SLLS", { "OP", child, parent, prop }))
|
||||
end
|
||||
local nodes = scene.nodes or {}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ textures
|
||||
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" }
|
||||
local texIds: { [number]: number } = {}
|
||||
local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
|
||||
for ti, tex in scene.textures or {} do
|
||||
local file = tex.uri or (base .. "_" .. (tex.name or tostring(ti)) .. "." .. (EXT[tex.mime or ""] or "png"))
|
||||
local tname = tex.name or ("Texture" .. ti)
|
||||
local vid, tid = id(), id()
|
||||
local vchildren = {
|
||||
N("Type", "S", { "Clip" }),
|
||||
N("Properties70", "", {}, { P("Path", "KString", "XRefUrl", "", "S", file) }),
|
||||
N("UseMipMap", "I", { 0 }),
|
||||
N("Filename", "S", { file }),
|
||||
N("RelativeFilename", "S", { file }),
|
||||
}
|
||||
if embed and tex.data then
|
||||
table.insert(vchildren, N("Content", "R", { tex.data }))
|
||||
end
|
||||
add("Video", N("Video", "LSS", { vid, cls(tname, "Video"), "Clip" }, vchildren))
|
||||
local tp = { P("UseMaterial", "bool", "", "", "I", 1) }
|
||||
local smp = tex.sampler
|
||||
if smp and smp.wrapS == "clamp" then
|
||||
table.insert(tp, Penum("WrapModeU", 1))
|
||||
end
|
||||
if smp and smp.wrapT == "clamp" then
|
||||
table.insert(tp, Penum("WrapModeV", 1))
|
||||
end
|
||||
add("Texture", N("Texture", "LSS", { tid, cls(tname, "Texture"), "" }, {
|
||||
N("Type", "S", { "TextureVideoClip" }),
|
||||
N("Version", "I", { 202 }),
|
||||
N("TextureName", "S", { cls(tname, "Texture") }),
|
||||
N("Properties70", "", {}, tp),
|
||||
N("Media", "S", { cls(tname, "Video") }),
|
||||
N("FileName", "S", { file }),
|
||||
N("RelativeFilename", "S", { file }),
|
||||
N("ModelUVTranslation", "DD", { 0, 0 }),
|
||||
N("ModelUVScaling", "DD", { 1, 1 }),
|
||||
N("Texture_Alpha_Source", "S", { "None" }),
|
||||
N("Cropping", "IIII", { 0, 0, 0, 0 }),
|
||||
}))
|
||||
OO(vid, tid)
|
||||
texIds[ti] = tid
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ materials
|
||||
local matIds: { [number]: number } = {}
|
||||
for mi, m in scene.materials or {} do
|
||||
local x = m.extras and (m.extras :: any).fbx or {}
|
||||
local bc = m.baseColor or { 1, 1, 1, 1 }
|
||||
local alpha = bc[4] or 1
|
||||
local rough = math.clamp(m.roughness or 1, 0.02, 1)
|
||||
local shin = if type(x.shininess) == "number" then x.shininess else 2 / (rough * rough) - 2
|
||||
local em = m.emissive or { 0, 0, 0 }
|
||||
local spec = if type(x.specular) == "table" then x.specular else { 0.2, 0.2, 0.2 }
|
||||
local pid = id()
|
||||
local props = {
|
||||
Pcolor("AmbientColor", if type(x.ambient) == "table" then x.ambient else { 0, 0, 0 }),
|
||||
Pnum("AmbientFactor", if type(x.ambientFactor) == "number" then x.ambientFactor else 1),
|
||||
Pcolor("DiffuseColor", { bc[1], bc[2], bc[3] }),
|
||||
Pnum("DiffuseFactor", 1),
|
||||
Pcolor("EmissiveColor", em),
|
||||
Pnum("EmissiveFactor", 1),
|
||||
Pcolor("SpecularColor", spec),
|
||||
Pnum("SpecularFactor", if type(x.specularFactor) == "number" then x.specularFactor else 1),
|
||||
Pnum("Shininess", shin),
|
||||
Pnum("ShininessExponent", shin),
|
||||
Pcolor("TransparentColor", { 1, 1, 1 }),
|
||||
Pnum("TransparencyFactor", 1 - alpha),
|
||||
Pnum("Opacity", alpha),
|
||||
Pcolor("ReflectionColor", if type(x.reflection) == "table" then x.reflection else { 0, 0, 0 }),
|
||||
Pnum("ReflectionFactor", if type(x.reflectionFactor) == "number" then x.reflectionFactor else 0),
|
||||
}
|
||||
add("Material", N("Material", "LSS", { pid, cls(m.name or ("Material" .. mi), "Material"), "" }, {
|
||||
N("Version", "I", { 102 }),
|
||||
N("ShadingModel", "S", { if type(x.shadingModel) == "string" and x.shadingModel ~= "unknown" then x.shadingModel else "phong" }),
|
||||
N("MultiLayer", "I", { 0 }),
|
||||
N("Properties70", "", {}, props),
|
||||
}))
|
||||
matIds[mi] = pid
|
||||
local function link(ref: Types.TextureRef?, prop: string)
|
||||
local t = ref and texIds[ref.texture]
|
||||
if t then
|
||||
OP(t, pid, prop)
|
||||
end
|
||||
end
|
||||
link(m.baseColorTexture, "DiffuseColor")
|
||||
link(m.normalTexture, "NormalMap")
|
||||
link(m.emissiveTexture, "EmissiveColor")
|
||||
-- the other textures the FBX material had (specular, metalness, ... maps), under their property names
|
||||
local linked = {
|
||||
[m.baseColorTexture and m.baseColorTexture.texture or -1] = true,
|
||||
[m.normalTexture and m.normalTexture.texture or -1] = true,
|
||||
[m.emissiveTexture and m.emissiveTexture.texture or -1] = true,
|
||||
}
|
||||
if type(x.textures) == "table" then
|
||||
local props = {}
|
||||
for prop in x.textures do
|
||||
table.insert(props, prop)
|
||||
end
|
||||
table.sort(props)
|
||||
for _, prop in props do
|
||||
local ti = x.textures[prop]
|
||||
if type(ti) == "number" and not linked[ti] and texIds[ti] then
|
||||
linked[ti] = true
|
||||
OP(texIds[ti], pid, prop)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ models
|
||||
local modelIds: { [number]: number } = {}
|
||||
local skip: { [number]: boolean } = {}
|
||||
local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there)
|
||||
local parentOf: { [number]: number } = {}
|
||||
for i, nd in nodes do
|
||||
for _, c in nd.children or {} do
|
||||
if parentOf[c] == nil and c ~= i then
|
||||
parentOf[c] = i
|
||||
end
|
||||
end
|
||||
end
|
||||
local jointSet: { [number]: boolean } = {}
|
||||
for _, s in scene.skins or {} do
|
||||
for _, j in s.joints do
|
||||
jointSet[j] = true
|
||||
end
|
||||
end
|
||||
for i, nd in nodes do
|
||||
local o = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.orientation
|
||||
local p = parentOf[i]
|
||||
if o and p and (nd.camera or nd.light) and #(nd.children or {}) == 0 and not nd.mesh and not nodes[p].camera and not nodes[p].light then
|
||||
skip[i] = true
|
||||
attrHost[i] = p
|
||||
end
|
||||
end
|
||||
-- world matrices (rest pose) for clusters and the bind pose
|
||||
local worldM: { [number]: Xform.M4 } = {}
|
||||
local visiting: { [number]: boolean } = {}
|
||||
local function world(i: number): Xform.M4
|
||||
if worldM[i] then
|
||||
return worldM[i]
|
||||
end
|
||||
if visiting[i] then
|
||||
return Xform.identity()
|
||||
end
|
||||
visiting[i] = true
|
||||
local nd = nodes[i]
|
||||
local l = if nd.matrix and #nd.matrix == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale)
|
||||
local p = parentOf[i]
|
||||
local w = if p then Xform.mul(world(p), l) else l
|
||||
worldM[i] = w
|
||||
return w
|
||||
end
|
||||
local function trs(nd: Types.Node): ({ number }, { number }, { number })
|
||||
if nd.matrix and #nd.matrix == 16 then
|
||||
return Xform.decompose(nd.matrix)
|
||||
end
|
||||
return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 }
|
||||
end
|
||||
local function model(name: string, sub: string, t: { number }, r: { number }, s: { number }): number
|
||||
local mid = id()
|
||||
add("Model", N("Model", "LSS", { mid, cls(name, "Model"), sub }, {
|
||||
N("Version", "I", { 232 }),
|
||||
N("Properties70", "", {}, {
|
||||
Penum("RotationOrder", 0),
|
||||
Penum("InheritType", 1),
|
||||
Pint("DefaultAttributeIndex", 0),
|
||||
Pvec("Lcl Translation", "Lcl Translation", "", t),
|
||||
Pvec("Lcl Rotation", "Lcl Rotation", "", r),
|
||||
Pvec("Lcl Scaling", "Lcl Scaling", "", s),
|
||||
}),
|
||||
N("Shading", "C", { true }),
|
||||
N("Culling", "S", { "CullingOff" }),
|
||||
}))
|
||||
return mid
|
||||
end
|
||||
local function attribute(nd: Types.Node, mid: number, nodeName: string)
|
||||
if nd.camera and scene.cameras[nd.camera] then
|
||||
local c = scene.cameras[nd.camera]
|
||||
local aid = id()
|
||||
local aspect = c.aspect or 4 / 3
|
||||
local fh = 0.612
|
||||
local fw = fh * aspect
|
||||
local props
|
||||
if c.type == "orthographic" then
|
||||
props = { Penum("CameraProjectionType", 1), Pdouble("OrthoZoom", c.ymag or 1), Pdouble("AspectWidth", aspect * 100), Pdouble("AspectHeight", 100), Pdouble("NearPlane", c.znear or 0.1), Pdouble("FarPlane", c.zfar or 1000), Pdouble("FilmWidth", fw), Pdouble("FilmHeight", fh) }
|
||||
else
|
||||
local yfov = c.yfov or 0.8
|
||||
local hfov = 2 * math.atan(math.tan(yfov / 2) * aspect)
|
||||
local focal = fw * 25.4 / (2 * math.tan(hfov / 2))
|
||||
props = {
|
||||
Penum("CameraProjectionType", 0),
|
||||
Penum("ApertureMode", 1),
|
||||
P("FieldOfView", "FieldOfView", "", "A", "D", hfov * 180 / math.pi),
|
||||
P("FocalLength", "Number", "", "A", "D", focal),
|
||||
Pdouble("FilmWidth", fw),
|
||||
Pdouble("FilmHeight", fh),
|
||||
Penum("AspectRatioMode", 0),
|
||||
Pdouble("AspectWidth", aspect * 100),
|
||||
Pdouble("AspectHeight", 100),
|
||||
Pdouble("NearPlane", c.znear or 0.1),
|
||||
Pdouble("FarPlane", c.zfar or 1000),
|
||||
}
|
||||
end
|
||||
add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(c.name or nodeName, "NodeAttribute"), "Camera" }, {
|
||||
N("Properties70", "", {}, props),
|
||||
N("TypeFlags", "S", { "Camera" }),
|
||||
N("GeometryVersion", "I", { 124 }),
|
||||
}))
|
||||
OO(aid, mid)
|
||||
elseif nd.light and scene.lights[nd.light] then
|
||||
local l = scene.lights[nd.light]
|
||||
local aid = id()
|
||||
local lt = if l.type == "directional" then 1 elseif l.type == "spot" then 2 else 0
|
||||
local props = {
|
||||
Penum("LightType", lt),
|
||||
Pcolor("Color", l.color or { 1, 1, 1 }),
|
||||
Pnum("Intensity", (l.intensity or 1) * 100),
|
||||
P("CastLight", "bool", "", "", "I", 1),
|
||||
}
|
||||
if lt == 2 then
|
||||
table.insert(props, Pnum("InnerAngle", (l.innerCone or 0) * 360 / math.pi))
|
||||
table.insert(props, Pnum("OuterAngle", (l.outerCone or math.pi / 4) * 360 / math.pi))
|
||||
end
|
||||
if l.range then
|
||||
table.insert(props, P("EnableFarAttenuation", "bool", "", "", "I", 1))
|
||||
table.insert(props, Pnum("FarAttenuationEnd", l.range))
|
||||
end
|
||||
add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(l.name or nodeName, "NodeAttribute"), "Light" }, {
|
||||
N("Properties70", "", {}, props),
|
||||
N("TypeFlags", "S", { "Light" }),
|
||||
N("GeometryVersion", "I", { 124 }),
|
||||
}))
|
||||
OO(aid, mid)
|
||||
end
|
||||
end
|
||||
for i, nd in nodes do
|
||||
if not skip[i] then
|
||||
local t, r, s = trs(nd)
|
||||
local euler = Xform.eulerXYZ(r)
|
||||
local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type
|
||||
local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null"
|
||||
-- an orientation child folded into this node gives it its attribute
|
||||
local folded: number? = nil
|
||||
for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array)
|
||||
if host == i then
|
||||
folded = c
|
||||
end
|
||||
end
|
||||
if not nd.mesh and folded then
|
||||
sub = if nodes[folded].camera then "Camera" else "Light"
|
||||
end
|
||||
local mid = model(nd.name or ("Node" .. i), sub, t, euler, s)
|
||||
modelIds[i] = mid
|
||||
if sub == "LimbNode" then
|
||||
local aid = id()
|
||||
add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(nd.name, "NodeAttribute"), "LimbNode" }, { N("TypeFlags", "S", { "Skeleton" }) }))
|
||||
OO(aid, mid)
|
||||
end
|
||||
if folded then
|
||||
attribute(nodes[folded], mid, nd.name or "")
|
||||
end
|
||||
if nd.camera or nd.light then
|
||||
-- a glTF-oriented camera / light: an FBX-oriented child model carries it
|
||||
local kind = if nd.camera then "camera" else "light"
|
||||
local cmid = model((nd.name or "") .. "_" .. kind, if nd.camera then "Camera" else "Light", { 0, 0, 0 }, ORIENT_INV[kind], { 1, 1, 1 })
|
||||
OO(cmid, mid)
|
||||
attribute(nd, cmid, nd.name or "")
|
||||
end
|
||||
end
|
||||
end
|
||||
for i in nodes do
|
||||
local mid = modelIds[i]
|
||||
if mid then
|
||||
local p = parentOf[i]
|
||||
local pm = p and modelIds[p]
|
||||
OO(mid, pm or 0)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ geometry
|
||||
local geoIds: { [number]: number } = {}
|
||||
local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot
|
||||
local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {}
|
||||
local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation)
|
||||
local geoCount: { [number]: number } = {}
|
||||
local function geometry(mi: number): number?
|
||||
if geoIds[mi] then
|
||||
return geoIds[mi]
|
||||
end
|
||||
local mesh = scene.meshes[mi]
|
||||
if not mesh then
|
||||
return nil
|
||||
end
|
||||
local V, PVI, NRM, MATS = {}, {}, {}, {}
|
||||
local UV: { [number]: { number } } = {}
|
||||
local UVI: { [number]: { number } } = {}
|
||||
local COL: { [number]: { number } } = {}
|
||||
local COLI: { [number]: { number } } = {}
|
||||
local slots: { number } = {}
|
||||
local slotOf: { [number]: number } = {}
|
||||
local hasN = false
|
||||
local nuv, ncol = 0, 0
|
||||
for _, prim in mesh.primitives do
|
||||
for k = 0, 7 do
|
||||
if prim.attributes["TEXCOORD_" .. k] then
|
||||
nuv = math.max(nuv, k + 1)
|
||||
end
|
||||
if prim.attributes["COLOR_" .. k] then
|
||||
ncol = math.max(ncol, k + 1)
|
||||
end
|
||||
end
|
||||
if prim.attributes.NORMAL then
|
||||
hasN = true
|
||||
end
|
||||
end
|
||||
for k = 1, nuv do
|
||||
UV[k], UVI[k] = {}, {}
|
||||
end
|
||||
for k = 1, ncol do
|
||||
COL[k], COLI[k] = {}, {}
|
||||
end
|
||||
local layout = {}
|
||||
local offset = 0
|
||||
for _, prim in mesh.primitives do
|
||||
local fs = faces(prim)
|
||||
local pos = prim.attributes.POSITION
|
||||
local R = accessorReader(pos)
|
||||
if fs and R and pos then
|
||||
table.insert(layout, { prim = prim, offset = offset })
|
||||
local n = pos.count
|
||||
for v = 0, n - 1 do
|
||||
table.insert(V, R(v, 0))
|
||||
table.insert(V, R(v, 1))
|
||||
table.insert(V, R(v, 2))
|
||||
end
|
||||
local NR = accessorReader(prim.attributes.NORMAL)
|
||||
if hasN then
|
||||
for v = 0, n - 1 do
|
||||
if NR then
|
||||
table.insert(NRM, NR(v, 0))
|
||||
table.insert(NRM, NR(v, 1))
|
||||
table.insert(NRM, NR(v, 2))
|
||||
else
|
||||
table.insert(NRM, 0)
|
||||
table.insert(NRM, 0)
|
||||
table.insert(NRM, 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
local uvBase: { number } = {}
|
||||
for k = 1, nuv do
|
||||
uvBase[k] = #UV[k] // 2
|
||||
local T = accessorReader(prim.attributes["TEXCOORD_" .. (k - 1)])
|
||||
for v = 0, n - 1 do
|
||||
local u, w = 0, 0
|
||||
if T then
|
||||
u, w = T(v, 0), T(v, 1)
|
||||
end
|
||||
table.insert(UV[k], u)
|
||||
table.insert(UV[k], if flipV then 1 - w else w)
|
||||
end
|
||||
end
|
||||
local colBase: { number } = {}
|
||||
for k = 1, ncol do
|
||||
colBase[k] = #COL[k] // 4
|
||||
local acc = prim.attributes["COLOR_" .. (k - 1)]
|
||||
local C = accessorReader(acc)
|
||||
local comps = acc and acc.components or 4
|
||||
for v = 0, n - 1 do
|
||||
table.insert(COL[k], if C then C(v, 0) else 1)
|
||||
table.insert(COL[k], if C then C(v, 1) else 1)
|
||||
table.insert(COL[k], if C then C(v, 2) else 1)
|
||||
table.insert(COL[k], if C and comps >= 4 then C(v, 3) else 1)
|
||||
end
|
||||
end
|
||||
local mat = prim.material or 0
|
||||
local slot = slotOf[mat]
|
||||
if slot == nil then
|
||||
table.insert(slots, mat)
|
||||
slot = #slots - 1
|
||||
slotOf[mat] = slot
|
||||
end
|
||||
for _, f in fs do
|
||||
for q, v in f do
|
||||
local cp = v + offset
|
||||
table.insert(PVI, if q == #f then -cp - 1 else cp)
|
||||
for k = 1, nuv do
|
||||
table.insert(UVI[k], uvBase[k] + v)
|
||||
end
|
||||
for k = 1, ncol do
|
||||
table.insert(COLI[k], colBase[k] + v)
|
||||
end
|
||||
end
|
||||
table.insert(MATS, slot)
|
||||
end
|
||||
offset += n
|
||||
end
|
||||
end
|
||||
if #PVI == 0 then
|
||||
return nil
|
||||
end
|
||||
local gid = id()
|
||||
local ch: { WNode } = {
|
||||
N("Properties70", "", {}, {}),
|
||||
N("GeometryVersion", "I", { 124 }),
|
||||
N("Vertices", "", { arr("d", V) }),
|
||||
N("PolygonVertexIndex", "", { arr("i", PVI) }),
|
||||
}
|
||||
local layer0: { WNode } = { N("Version", "I", { 100 }) }
|
||||
if hasN then
|
||||
table.insert(ch, N("LayerElementNormal", "I", { 0 }, {
|
||||
N("Version", "I", { 101 }),
|
||||
N("Name", "S", { "" }),
|
||||
N("MappingInformationType", "S", { "ByVertice" }),
|
||||
N("ReferenceInformationType", "S", { "Direct" }),
|
||||
N("Normals", "", { arr("d", NRM) }),
|
||||
}))
|
||||
table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementNormal" }), N("TypedIndex", "I", { 0 }) }))
|
||||
end
|
||||
local extraLayers: { WNode } = {}
|
||||
local uvNames = mesh.extras and (mesh.extras :: any).fbx and (mesh.extras :: any).fbx.uvSets or {}
|
||||
for k = 1, nuv do
|
||||
table.insert(ch, N("LayerElementUV", "I", { k - 1 }, {
|
||||
N("Version", "I", { 101 }),
|
||||
N("Name", "S", { if type(uvNames[k]) == "string" then uvNames[k] else (if k == 1 then "UVMap" else "UVMap" .. k) }),
|
||||
N("MappingInformationType", "S", { "ByPolygonVertex" }),
|
||||
N("ReferenceInformationType", "S", { "IndexToDirect" }),
|
||||
N("UV", "", { arr("d", UV[k]) }),
|
||||
N("UVIndex", "", { arr("i", UVI[k]) }),
|
||||
}))
|
||||
local le = N("LayerElement", "", {}, { N("Type", "S", { "LayerElementUV" }), N("TypedIndex", "I", { k - 1 }) })
|
||||
if k == 1 then
|
||||
table.insert(layer0, le)
|
||||
else
|
||||
table.insert(extraLayers, N("Layer", "I", { k - 1 }, { N("Version", "I", { 100 }), le }))
|
||||
end
|
||||
end
|
||||
for k = 1, ncol do
|
||||
table.insert(ch, N("LayerElementColor", "I", { k - 1 }, {
|
||||
N("Version", "I", { 101 }),
|
||||
N("Name", "S", { "Col" .. (if k > 1 then tostring(k) else "") }),
|
||||
N("MappingInformationType", "S", { "ByPolygonVertex" }),
|
||||
N("ReferenceInformationType", "S", { "IndexToDirect" }),
|
||||
N("Colors", "", { arr("d", COL[k]) }),
|
||||
N("ColorIndex", "", { arr("i", COLI[k]) }),
|
||||
}))
|
||||
if k == 1 then
|
||||
table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementColor" }), N("TypedIndex", "I", { 0 }) }))
|
||||
end
|
||||
end
|
||||
local anyMat = false
|
||||
for _, m in slots do
|
||||
if m ~= 0 and matIds[m] then
|
||||
anyMat = true
|
||||
end
|
||||
end
|
||||
if anyMat then
|
||||
local allSame = #slots == 1
|
||||
table.insert(ch, N("LayerElementMaterial", "I", { 0 }, {
|
||||
N("Version", "I", { 101 }),
|
||||
N("Name", "S", { "" }),
|
||||
N("MappingInformationType", "S", { if allSame then "AllSame" else "ByPolygon" }),
|
||||
N("ReferenceInformationType", "S", { "IndexToDirect" }),
|
||||
N("Materials", "", { arr("i", if allSame then { 0 } else MATS) }),
|
||||
}))
|
||||
table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementMaterial" }), N("TypedIndex", "I", { 0 }) }))
|
||||
end
|
||||
table.insert(ch, N("Layer", "I", { 0 }, layer0))
|
||||
for _, l in extraLayers do
|
||||
table.insert(ch, l)
|
||||
end
|
||||
add("Geometry", N("Geometry", "LSS", { gid, cls(mesh.name or ("Mesh" .. mi), "Geometry"), "Mesh" }, ch))
|
||||
geoIds[mi] = gid
|
||||
geoSlots[mi] = if anyMat then slots else {}
|
||||
geoVerts[mi] = layout
|
||||
geoCount[mi] = offset
|
||||
-- morph targets
|
||||
local prims = mesh.primitives
|
||||
local ntargets = 0
|
||||
for _, l in layout do
|
||||
ntargets = math.max(ntargets, if l.prim.targets then #(l.prim.targets :: any) else 0)
|
||||
end
|
||||
if ntargets > 0 then
|
||||
local bsid = id()
|
||||
add("Deformer", N("Deformer", "LSS", { bsid, cls(mesh.name, "Deformer"), "BlendShape" }, { N("Version", "I", { 100 }) }))
|
||||
OO(bsid, gid)
|
||||
local names = mesh.extras and (mesh.extras :: any).targetNames or {}
|
||||
for t = 1, ntargets do
|
||||
local IDX, DV, DN = {}, {}, {}
|
||||
local anyN = false
|
||||
for _, l in layout do
|
||||
local tg = l.prim.targets and (l.prim.targets :: any)[t]
|
||||
if tg and tg.NORMAL then
|
||||
anyN = true
|
||||
end
|
||||
end
|
||||
for _, l in layout do
|
||||
local tg = l.prim.targets and (l.prim.targets :: any)[t]
|
||||
local TP = tg and accessorReader(tg.POSITION)
|
||||
local TN = tg and accessorReader(tg.NORMAL)
|
||||
if TP then
|
||||
for v = 0, l.prim.attributes.POSITION.count - 1 do
|
||||
local x, y, z = TP(v, 0), TP(v, 1), TP(v, 2)
|
||||
local nx, ny, nz = 0, 0, 0
|
||||
if TN then
|
||||
nx, ny, nz = TN(v, 0), TN(v, 1), TN(v, 2)
|
||||
end
|
||||
if x ~= 0 or y ~= 0 or z ~= 0 or nx ~= 0 or ny ~= 0 or nz ~= 0 then
|
||||
table.insert(IDX, l.offset + v)
|
||||
table.insert(DV, x)
|
||||
table.insert(DV, y)
|
||||
table.insert(DV, z)
|
||||
if anyN then
|
||||
table.insert(DN, nx)
|
||||
table.insert(DN, ny)
|
||||
table.insert(DN, nz)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local tname = if type(names[t]) == "string" then names[t] else ("Target" .. t)
|
||||
local chid, shid = id(), id()
|
||||
local w = mesh.weights and mesh.weights[t] or 0
|
||||
add("Deformer", N("Deformer", "LSS", { chid, cls(tname, "SubDeformer"), "BlendShapeChannel" }, {
|
||||
N("Version", "I", { 100 }),
|
||||
N("DeformPercent", "D", { w * 100 }),
|
||||
N("FullWeights", "", { arr("d", { 100 }) }),
|
||||
N("Properties70", "", {}, { Pnum("DeformPercent", w * 100) }),
|
||||
}))
|
||||
local shch = { N("Version", "I", { 100 }), N("Indexes", "", { arr("i", IDX) }), N("Vertices", "", { arr("d", DV) }) }
|
||||
if anyN then
|
||||
table.insert(shch, N("Normals", "", { arr("d", DN) }))
|
||||
end
|
||||
add("Geometry", N("Geometry", "LSS", { shid, cls(tname, "Geometry"), "Shape" }, shch))
|
||||
OO(chid, bsid)
|
||||
OO(shid, chid)
|
||||
local gc: any = geoChannels
|
||||
gc[mi] = gc[mi] or {}
|
||||
gc[mi][t] = chid
|
||||
end
|
||||
end
|
||||
local _ = prims
|
||||
return gid
|
||||
end
|
||||
|
||||
local poseNodes: { WNode } = {}
|
||||
local posed: { [number]: boolean } = {}
|
||||
local function pose(mid: number, m: Xform.M4)
|
||||
if posed[mid] then
|
||||
return
|
||||
end
|
||||
posed[mid] = true
|
||||
table.insert(poseNodes, N("PoseNode", "", {}, { N("Node", "L", { mid }), N("Matrix", "", { arr("d", m) }) }))
|
||||
end
|
||||
local skinned: { [string]: boolean } = {}
|
||||
for i, nd in nodes do
|
||||
local mid = modelIds[i]
|
||||
if nd.mesh and mid then
|
||||
local gid = geometry(nd.mesh)
|
||||
if gid then
|
||||
OO(gid, mid)
|
||||
for _, m in geoSlots[nd.mesh] do
|
||||
local pm = matIds[m]
|
||||
if pm then
|
||||
OO(pm, mid)
|
||||
end
|
||||
end
|
||||
-- skin: one Skin per (geometry, skin)
|
||||
local skin = nd.skin and scene.skins[nd.skin]
|
||||
local key = tostring(gid) .. ":" .. tostring(nd.skin)
|
||||
if skin and not skinned[key] then
|
||||
skinned[key] = true
|
||||
local sid = id()
|
||||
add("Deformer", N("Deformer", "LSS", { sid, cls(nd.name, "Deformer"), "Skin" }, { N("Version", "I", { 101 }), N("Link_DeformAcuracy", "D", { 50 }) }))
|
||||
OO(sid, gid)
|
||||
local meshWorld = world(i)
|
||||
pose(mid, meshWorld)
|
||||
local ibm = accessorReader(skin.inverseBindMatrices)
|
||||
-- per joint: control points and weights
|
||||
local perJoint: { { idx: { number }, w: { number } } } = {}
|
||||
for j in skin.joints do
|
||||
perJoint[j] = { idx = {}, w = {} }
|
||||
end
|
||||
for _, l in geoVerts[nd.mesh] do
|
||||
local J = accessorReader(l.prim.attributes.JOINTS_0)
|
||||
local W = accessorReader(l.prim.attributes.WEIGHTS_0)
|
||||
if J and W then
|
||||
for v = 0, l.prim.attributes.POSITION.count - 1 do
|
||||
for q = 0, 3 do
|
||||
local j, w = J(v, q), W(v, q)
|
||||
local pj = perJoint[j + 1]
|
||||
if w > 0 and pj then
|
||||
table.insert(pj.idx, l.offset + v)
|
||||
table.insert(pj.w, w)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for j, ji in skin.joints do
|
||||
local jm = modelIds[ji]
|
||||
if jm then
|
||||
local IB = Xform.identity()
|
||||
if ibm and skin.inverseBindMatrices and j <= skin.inverseBindMatrices.count then
|
||||
for k = 1, 16 do
|
||||
IB[k] = ibm(j - 1, k - 1)
|
||||
end
|
||||
end
|
||||
local inv = Xform.inverse(IB) or Xform.identity()
|
||||
local link = Xform.mul(meshWorld, inv)
|
||||
local cid = id()
|
||||
add("Deformer", N("Deformer", "LSS", { cid, cls(nodes[ji].name, "SubDeformer"), "Cluster" }, {
|
||||
N("Version", "I", { 100 }),
|
||||
N("UserData", "SS", { "", "" }),
|
||||
N("Indexes", "", { arr("i", perJoint[j].idx) }),
|
||||
N("Weights", "", { arr("d", perJoint[j].w) }),
|
||||
N("Transform", "", { arr("d", meshWorld) }),
|
||||
N("TransformLink", "", { arr("d", link) }),
|
||||
}))
|
||||
OO(cid, sid)
|
||||
OO(jm, cid)
|
||||
pose(jm, link)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #poseNodes > 0 then
|
||||
local pch = { N("Type", "S", { "BindPose" }), N("Version", "I", { 100 }), N("NbPoseNodes", "I", { #poseNodes }) }
|
||||
for _, pn in poseNodes do
|
||||
table.insert(pch, pn)
|
||||
end
|
||||
add("Pose", N("Pose", "LSS", { id(), cls("BindPose", "Pose"), "BindPose" }, pch))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ animations
|
||||
local tmin, tmax = math.huge, -math.huge
|
||||
local function curveNode(name: string, layer: number, target: number, prop: string, comps: { { number } }, times: { number }, labels: { string }, step: boolean)
|
||||
local cnid = id()
|
||||
local p = {}
|
||||
for k, lab in labels do
|
||||
table.insert(p, Pnum("d|" .. lab, comps[k][1] or 0))
|
||||
end
|
||||
add("AnimationCurveNode", N("AnimationCurveNode", "LSS", { cnid, cls(name, "AnimCurveNode"), "" }, { N("Properties70", "", {}, p) }))
|
||||
OO(cnid, layer)
|
||||
OP(cnid, target, prop)
|
||||
local ticks = table.create(#times, 0)
|
||||
for k, t in times do
|
||||
ticks[k] = math.floor(t * TICKS + 0.5)
|
||||
end
|
||||
for k, lab in labels do
|
||||
local cid = id()
|
||||
local df = buffer.create(32)
|
||||
buffer.writeu32(df, 8, 218434821)
|
||||
local dfa = { array = true, type = "f", count = 4, data = buffer.create(32) }
|
||||
buffer.writef64(dfa.data, 16, buffer.readf32(df, 8))
|
||||
add("AnimationCurve", N("AnimationCurve", "LSS", { cid, cls("", "AnimCurve"), "" }, {
|
||||
N("Default", "D", { comps[k][1] or 0 }),
|
||||
N("KeyVer", "I", { 4009 }),
|
||||
N("KeyTime", "", { arr("l", ticks) }),
|
||||
N("KeyValueFloat", "", { arr("f", comps[k]) }),
|
||||
N("KeyAttrFlags", "", { arr("i", { if step then 0x00000002 else 0x00000104 }) }),
|
||||
N("KeyAttrDataFloat", "", { dfa }),
|
||||
N("KeyAttrRefCount", "", { arr("i", { #times }) }),
|
||||
}))
|
||||
OP(cid, cnid, "d|" .. lab)
|
||||
end
|
||||
end
|
||||
local PATH = { translation = { "T", "Lcl Translation", 3 }, rotation = { "R", "Lcl Rotation", 4 }, scale = { "S", "Lcl Scaling", 3 } }
|
||||
for ai, anim in scene.animations or {} do
|
||||
local stid, lid = id(), id()
|
||||
local astart, astop = math.huge, -math.huge
|
||||
local layerNodes = {}
|
||||
for _, ch in anim.channels do
|
||||
local mid = modelIds[ch.node]
|
||||
local IN = accessorReader(ch.input)
|
||||
local OUT = accessorReader(ch.output)
|
||||
local spec = PATH[ch.path]
|
||||
if IN and OUT and ch.input.count > 0 and mid and (spec or ch.path == "weights") then
|
||||
local n = ch.input.count
|
||||
local times = table.create(n, 0)
|
||||
for k = 0, n - 1 do
|
||||
times[k + 1] = IN(k, 0)
|
||||
astart, astop = math.min(astart, times[k + 1]), math.max(astop, times[k + 1])
|
||||
end
|
||||
local cubic = ch.interpolation == "CUBICSPLINE"
|
||||
local step = ch.interpolation == "STEP"
|
||||
if spec then
|
||||
local comps = spec[3]
|
||||
local function val(k: number, c: number): number
|
||||
local e = if cubic then k * 3 + 1 else k
|
||||
if e >= ch.output.count then
|
||||
return 0
|
||||
end
|
||||
return OUT(e, c)
|
||||
end
|
||||
local X, Y, Z = table.create(n, 0), table.create(n, 0), table.create(n, 0)
|
||||
local prev: { number }? = nil
|
||||
for k = 0, n - 1 do
|
||||
local v
|
||||
if comps == 4 then
|
||||
local q = { val(k, 0), val(k, 1), val(k, 2), val(k, 3) }
|
||||
local ql = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4])
|
||||
if ql > 0 then
|
||||
q = { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql }
|
||||
else
|
||||
q = { 0, 0, 0, 1 }
|
||||
end
|
||||
v = Xform.eulerXYZ(q)
|
||||
if prev then
|
||||
for a = 1, 3 do
|
||||
while v[a] - prev[a] > 180 do
|
||||
v[a] -= 360
|
||||
end
|
||||
while v[a] - prev[a] < -180 do
|
||||
v[a] += 360
|
||||
end
|
||||
end
|
||||
end
|
||||
prev = v
|
||||
else
|
||||
v = { val(k, 0), val(k, 1), val(k, 2) }
|
||||
end
|
||||
X[k + 1], Y[k + 1], Z[k + 1] = v[1], v[2], v[3]
|
||||
end
|
||||
table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step })
|
||||
else
|
||||
-- weights: one DeformPercent curve per blend shape channel of the node's mesh
|
||||
local nd = nodes[ch.node]
|
||||
local gc: any = geoChannels
|
||||
local chans = nd.mesh and gc[nd.mesh]
|
||||
if chans then
|
||||
local nt = #chans
|
||||
for t = 1, nt do
|
||||
local vals = table.create(n, 0)
|
||||
for k = 0, n - 1 do
|
||||
local e = if cubic then (k * 3 + 1) * nt + (t - 1) else k * nt + (t - 1)
|
||||
vals[k + 1] = if e < ch.output.count then OUT(e, 0) * 100 else 0
|
||||
end
|
||||
table.insert(layerNodes, { "DeformPercent", lid, chans[t], "DeformPercent", { vals }, times, { "DeformPercent" }, step })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if astart > astop then
|
||||
astart, astop = 0, 0
|
||||
end
|
||||
tmin, tmax = math.min(tmin, astart), math.max(tmax, astop)
|
||||
add("AnimationStack", N("AnimationStack", "LSS", { stid, cls(if anim.name and anim.name ~= "" then anim.name else ("Animation" .. ai), "AnimStack"), "" }, {
|
||||
N("Properties70", "", {}, {
|
||||
Ptime("LocalStart", math.floor(astart * TICKS + 0.5)),
|
||||
Ptime("LocalStop", math.floor(astop * TICKS + 0.5)),
|
||||
Ptime("ReferenceStart", math.floor(astart * TICKS + 0.5)),
|
||||
Ptime("ReferenceStop", math.floor(astop * TICKS + 0.5)),
|
||||
}),
|
||||
}))
|
||||
add("AnimationLayer", N("AnimationLayer", "LSS", { lid, cls("BaseLayer", "AnimLayer"), "" }, { N("Properties70", "", {}, {}) }))
|
||||
OO(lid, stid)
|
||||
for _, ln in layerNodes do
|
||||
curveNode(ln[1], ln[2], ln[3], ln[4], ln[5], ln[6], ln[7], ln[8])
|
||||
end
|
||||
end
|
||||
if tmin > tmax then
|
||||
tmin, tmax = 0, 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------ document
|
||||
local meta = scene.meta or {}
|
||||
local src = type(meta.source) == "table" and meta.source or {}
|
||||
local up = if meta.up == "z" then 2 else 1
|
||||
local upSign, front, frontSign, coord, coordSign = 1, 2, 1, 0, 1
|
||||
if up == 2 then
|
||||
front, frontSign = 1, -1
|
||||
end
|
||||
if src.format == "fbx" and src.upAxis == up then
|
||||
upSign = src.upAxisSign or upSign
|
||||
front, frontSign = src.frontAxis or front, src.frontAxisSign or frontSign
|
||||
coord, coordSign = src.coordAxis or coord, src.coordAxisSign or coordSign
|
||||
end
|
||||
local unitScale = if type(meta.unit) == "number" and meta.unit > 0 then meta.unit * 100 else 1
|
||||
local creator = opts and opts.creator or "formats-luau"
|
||||
local defs: { WNode } = { N("Version", "I", { 100 }) }
|
||||
local total = 1
|
||||
local CLASSES = { "Model", "Geometry", "Material", "Texture", "Video", "Deformer", "Pose", "NodeAttribute", "AnimationStack", "AnimationLayer", "AnimationCurveNode", "AnimationCurve" }
|
||||
for _, c in CLASSES do
|
||||
total += counts[c] or 0
|
||||
end
|
||||
table.insert(defs, N("Count", "I", { total }))
|
||||
table.insert(defs, N("ObjectType", "S", { "GlobalSettings" }, { N("Count", "I", { 1 }) }))
|
||||
for _, c in CLASSES do
|
||||
if counts[c] then
|
||||
table.insert(defs, N("ObjectType", "S", { c }, { N("Count", "I", { counts[c] }) }))
|
||||
end
|
||||
end
|
||||
local docId = id()
|
||||
local root: WNode = { name = "", props = {}, children = {
|
||||
N("FBXHeaderExtension", "", {}, {
|
||||
N("FBXHeaderVersion", "I", { 1003 }),
|
||||
N("FBXVersion", "I", { opts and opts.version or 7400 }),
|
||||
N("CreationTimeStamp", "", {}, {
|
||||
N("Version", "I", { 1000 }), N("Year", "I", { 1970 }), N("Month", "I", { 1 }), N("Day", "I", { 1 }),
|
||||
N("Hour", "I", { 0 }), N("Minute", "I", { 0 }), N("Second", "I", { 0 }), N("Millisecond", "I", { 0 }),
|
||||
}),
|
||||
N("Creator", "S", { creator }),
|
||||
}),
|
||||
N("FileId", "R", { buffer.fromstring("(\179*\235\182$\204\194\191\200\176*\169+\252\241") }),
|
||||
N("CreationTime", "S", { "1970-01-01 10:00:00:000" }),
|
||||
N("Creator", "S", { creator }),
|
||||
N("GlobalSettings", "", {}, {
|
||||
N("Version", "I", { 1000 }),
|
||||
N("Properties70", "", {}, {
|
||||
Pint("UpAxis", up), Pint("UpAxisSign", upSign), Pint("FrontAxis", front), Pint("FrontAxisSign", frontSign),
|
||||
Pint("CoordAxis", coord), Pint("CoordAxisSign", coordSign), Pint("OriginalUpAxis", up), Pint("OriginalUpAxisSign", upSign),
|
||||
Pdouble("UnitScaleFactor", unitScale), Pdouble("OriginalUnitScaleFactor", unitScale),
|
||||
P("AmbientColor", "ColorRGB", "Color", "", "DDD", 0, 0, 0),
|
||||
P("DefaultCamera", "KString", "", "", "S", "Producer Perspective"),
|
||||
Penum("TimeMode", 6),
|
||||
Penum("TimeProtocol", 2),
|
||||
Penum("SnapOnFrameMode", 0),
|
||||
Ptime("TimeSpanStart", math.floor(tmin * TICKS + 0.5)),
|
||||
Ptime("TimeSpanStop", math.floor(tmax * TICKS + 0.5)),
|
||||
Pdouble("CustomFrameRate", -1),
|
||||
}),
|
||||
}),
|
||||
N("Documents", "", {}, {
|
||||
N("Count", "I", { 1 }),
|
||||
N("Document", "LSS", { docId, "Scene", "Scene" }, {
|
||||
N("Properties70", "", {}, { P("SourceObject", "object", "", "", ""), P("ActiveAnimStackName", "KString", "", "", "S", "") }),
|
||||
N("RootNode", "L", { 0 }),
|
||||
}),
|
||||
}),
|
||||
N("References", "", {}, {}),
|
||||
N("Definitions", "", {}, defs),
|
||||
N("Objects", "", {}, objects),
|
||||
N("Connections", "", {}, conns),
|
||||
N("Takes", "", {}, { N("Current", "S", { "" }) }),
|
||||
} }
|
||||
local _ = Err
|
||||
return root, nil
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,200 @@
|
||||
--!strict
|
||||
-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model
|
||||
-- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, Euler rotations in degrees in the six
|
||||
-- orders, column-major 4x4 matrices (flat arrays of 16, translation at 13..15 as glTF and FBX store them), inverse,
|
||||
-- TRS decomposition (quaternion x, y, z, w) and Euler XYZ from a quaternion (the writer).
|
||||
local Xform = {}
|
||||
|
||||
export type M4 = { number }
|
||||
|
||||
local rad = math.pi / 180
|
||||
|
||||
function Xform.identity(): M4
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
function Xform.mul(a: M4, b: M4): M4
|
||||
local m = table.create(16, 0)
|
||||
for col = 0, 3 do
|
||||
for row = 0, 3 do
|
||||
m[col * 4 + row + 1] = a[row + 1] * b[col * 4 + 1] + a[4 + row + 1] * b[col * 4 + 2] + a[8 + row + 1] * b[col * 4 + 3] + a[12 + row + 1] * b[col * 4 + 4]
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
function Xform.translate(x: number, y: number, z: number): M4
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 }
|
||||
end
|
||||
|
||||
function Xform.scale(x: number, y: number, z: number): M4
|
||||
return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
local function rx(a: number): M4
|
||||
local c, s = math.cos(a), math.sin(a)
|
||||
return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
local function ry(a: number): M4
|
||||
local c, s = math.cos(a), math.sin(a)
|
||||
return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
local function rz(a: number): M4
|
||||
local c, s = math.cos(a), math.sin(a)
|
||||
return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
-- FBX RotationOrder: 0 XYZ (R = Rz * Ry * Rx: X applied first), 1 XZY, 2 YZX, 3 YXZ, 4 ZXY, 5 ZYX, 6 spheric (= XYZ)
|
||||
local ORDERS = { [0] = "xyz", "xzy", "yzx", "yxz", "zxy", "zyx", "xyz" }
|
||||
function Xform.euler(x: number, y: number, z: number, order: number?): M4
|
||||
local o = ORDERS[order or 0] or "xyz"
|
||||
local R = { x = rx(x * rad), y = ry(y * rad), z = rz(z * rad) }
|
||||
local a, b, c = string.sub(o, 1, 1), string.sub(o, 2, 2), string.sub(o, 3, 3)
|
||||
return Xform.mul(R[c], Xform.mul(R[b], R[a]))
|
||||
end
|
||||
|
||||
-- inverse of an affine matrix (general 3x3 part) | nil when singular
|
||||
function Xform.inverse(m: M4): M4?
|
||||
local a, b, c = m[1], m[5], m[9]
|
||||
local d, e, f = m[2], m[6], m[10]
|
||||
local g, h, i = m[3], m[7], m[11]
|
||||
local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g
|
||||
local det = a * A + b * B + c * C
|
||||
if det == 0 or det ~= det then
|
||||
return nil
|
||||
end
|
||||
local k = 1 / det
|
||||
local r = {
|
||||
A * k, B * k, C * k, 0,
|
||||
-(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0,
|
||||
(b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0,
|
||||
0, 0, 0, 1,
|
||||
}
|
||||
local tx, ty, tz = m[13], m[14], m[15]
|
||||
r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz)
|
||||
r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz)
|
||||
r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz)
|
||||
return r
|
||||
end
|
||||
|
||||
-- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers
|
||||
export type Props = {
|
||||
T: { number }, R: { number }, S: { number },
|
||||
Rpre: { number }, Rpost: { number }, Roff: { number }, Rp: { number }, Soff: { number }, Sp: { number },
|
||||
order: number,
|
||||
}
|
||||
local function isZero(v: { number }): boolean
|
||||
return v[1] == 0 and v[2] == 0 and v[3] == 0
|
||||
end
|
||||
function Xform.localMatrix(p: Props): M4
|
||||
local m = Xform.translate(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p.Rp[2], p.T[3] + p.Roff[3] + p.Rp[3])
|
||||
if not isZero(p.Rpre) then
|
||||
m = Xform.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0))
|
||||
end
|
||||
m = Xform.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order))
|
||||
if not isZero(p.Rpost) then
|
||||
local post = Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0)
|
||||
-- the inverse of a rotation is its transpose
|
||||
local tr = { post[1], post[5], post[9], 0, post[2], post[6], post[10], 0, post[3], post[7], post[11], 0, 0, 0, 0, 1 }
|
||||
m = Xform.mul(m, tr)
|
||||
end
|
||||
m = Xform.mul(m, Xform.translate(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3]))
|
||||
m = Xform.mul(m, Xform.scale(p.S[1], p.S[2], p.S[3]))
|
||||
if not isZero(p.Sp) then
|
||||
m = Xform.mul(m, Xform.translate(-p.Sp[1], -p.Sp[2], -p.Sp[3]))
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
-- quaternion (x, y, z, w) of a pure rotation matrix
|
||||
local function quat(m: M4): { number }
|
||||
local m00, m01, m02 = m[1], m[5], m[9]
|
||||
local m10, m11, m12 = m[2], m[6], m[10]
|
||||
local m20, m21, m22 = m[3], m[7], m[11]
|
||||
local tr = m00 + m11 + m22
|
||||
local x, y, z, w
|
||||
if tr > 0 then
|
||||
local s = math.sqrt(tr + 1) * 2
|
||||
w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s
|
||||
elseif m00 > m11 and m00 > m22 then
|
||||
local s = math.sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2
|
||||
w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s
|
||||
elseif m11 > m22 then
|
||||
local s = math.sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2
|
||||
w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s
|
||||
else
|
||||
local s = math.sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2
|
||||
w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4
|
||||
end
|
||||
local n = math.sqrt(x * x + y * y + z * z + w * w)
|
||||
if n == 0 or n ~= n then
|
||||
return { 0, 0, 0, 1 }
|
||||
end
|
||||
return { x / n, y / n, z / n, w / n }
|
||||
end
|
||||
Xform.quat = quat
|
||||
|
||||
-- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale)
|
||||
function Xform.decompose(m: M4): ({ number }, { number }, { number })
|
||||
local t = { m[13], m[14], m[15] }
|
||||
local sx = math.sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3])
|
||||
local sy = math.sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7])
|
||||
local sz = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11])
|
||||
local det = m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])
|
||||
if det < 0 then
|
||||
sx = -sx
|
||||
end
|
||||
local ix = if sx ~= 0 then 1 / sx else 0
|
||||
local iy = if sy ~= 0 then 1 / sy else 0
|
||||
local iz = if sz ~= 0 then 1 / sz else 0
|
||||
local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 }
|
||||
return t, quat(r), { sx, sy, sz }
|
||||
end
|
||||
|
||||
-- the rotation matrix of a quaternion
|
||||
function Xform.fromQuat(q: { number }): M4
|
||||
local x, y, z, w = q[1], q[2], q[3], q[4]
|
||||
local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
|
||||
return {
|
||||
1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0,
|
||||
2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0,
|
||||
2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0,
|
||||
0, 0, 0, 1,
|
||||
}
|
||||
end
|
||||
|
||||
-- Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion
|
||||
function Xform.eulerXYZ(q: { number }): { number }
|
||||
local m = Xform.fromQuat(q)
|
||||
-- m[3] = r20 = -sin(y)
|
||||
local sy = -m[3]
|
||||
sy = math.clamp(sy, -1, 1)
|
||||
local y = math.asin(sy)
|
||||
local x, z
|
||||
if math.abs(sy) < 0.9999999 then
|
||||
x = math.atan2(m[7], m[11])
|
||||
z = math.atan2(m[2], m[1])
|
||||
else
|
||||
x = math.atan2(-m[10], m[6])
|
||||
z = 0
|
||||
end
|
||||
return { x / rad, y / rad, z / rad }
|
||||
end
|
||||
|
||||
-- TRS -> matrix (glTF semantics)
|
||||
function Xform.compose(t: { number }?, r: { number }?, s: { number }?): M4
|
||||
local m = if r then Xform.fromQuat(r) else Xform.identity()
|
||||
if s then
|
||||
for k = 0, 2 do
|
||||
m[k * 4 + 1] *= s[k + 1]
|
||||
m[k * 4 + 2] *= s[k + 1]
|
||||
m[k * 4 + 3] *= s[k + 1]
|
||||
end
|
||||
end
|
||||
if t then
|
||||
m[13], m[14], m[15] = t[1], t[2], t[3]
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
return Xform
|
||||
@@ -0,0 +1,177 @@
|
||||
--!strict
|
||||
-- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays
|
||||
-- through codecs/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and
|
||||
-- assimp's FBX importer, and the FBX SDK's documentation of the transform model.
|
||||
-- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl
|
||||
-- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms
|
||||
-- baked into the mesh), meshes (polygons fan-triangulated by default or kept as "polygons"; layer elements for normals,
|
||||
-- tangents, uvs (TEXCOORD_n, flipped to glTF's top-left origin), colours and materials in every mapping and reference
|
||||
-- mode), Phong / Lambert materials (-> PBR approximations + the Phong values in extras.fbx) and 3ds Max Physical PBR
|
||||
-- materials, textures (embedded Video content kept encoded, or the file through opts.resolve / opts.files), skins
|
||||
-- (clusters -> JOINTS_0 / WEIGHTS_0, the 4 strongest influences, inverse bind matrices), blend shapes (morph targets
|
||||
-- + weights), animation stacks (curves on T / R / S and DeformPercent sampled at their keys, or opts.sampleRate, and
|
||||
-- turned into glTF translation / rotation / scale / weights channels), cameras and lights (on child nodes oriented for
|
||||
-- glTF's -Z forward axis), the axis system and unit (meta.up, meta.unit = UnitScaleFactor / 100; nothing is rotated).
|
||||
-- Writes binary FBX 7.4 (or ASCII with opts.ascii): the node hierarchy, meshes (one Geometry per mesh, its primitives
|
||||
-- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields),
|
||||
-- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster +
|
||||
-- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler
|
||||
-- XYZ curves; arrays zlib-compressed unless opts.compress = false). Checked with assimp and Blender (not the FBX SDK).
|
||||
-- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered
|
||||
-- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Binary = require("@formats/model/fbx/Binary")
|
||||
local Ascii = require("@formats/model/fbx/Ascii")
|
||||
local Read = require("@formats/model/fbx/Read")
|
||||
local Write = require("@formats/model/fbx/Write")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Fbx = {
|
||||
name = "fbx",
|
||||
category = "model",
|
||||
extensions = { "fbx" },
|
||||
mime = { "application/vnd.autodesk.fbx", "model/fbx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" },
|
||||
caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
|
||||
flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's convention)
|
||||
sampleRate: number?, -- also sample animation curves at this many samples per second (default: their keys only)
|
||||
resolve: ((uri: string) -> any)?, -- external texture files (the api sets it for paths)
|
||||
files: { [string]: any }?, -- or: the files by name
|
||||
maxBytes: number?, -- refuse arrays over this many bytes in total (default 2^30)
|
||||
maxVertices: number?, -- refuse more polygon corners (default 2^25)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
ascii: boolean?, -- write ASCII FBX (default binary)
|
||||
version: number?, -- 7400 (default) or 7500 (64-bit records)
|
||||
flipV: boolean?, -- default true (the inverse of decode)
|
||||
embedTextures: boolean?, -- embed texture.data as Video content (default true)
|
||||
compress: boolean?, -- zlib-compress arrays over 32 elements (default true; false writes ~3x faster, ~2x bigger)
|
||||
name: string?, -- the destination's file name (names textures without a uri)
|
||||
creator: string?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = Binary.MAGIC
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Fbx.sniff(r: Bytes.Reader): number
|
||||
if r:peek(21) == MAGIC then
|
||||
return 1
|
||||
end
|
||||
local head = r:peek(2048)
|
||||
if string.find(head, "FBXHeaderExtension:", 1, true) then
|
||||
return 0.95
|
||||
end
|
||||
if string.find(head, "^; FBX %d") then
|
||||
return 0.8
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function fetcher(opts: DecodeOptions?): Read.Fetch
|
||||
return function(uri: string): buffer?
|
||||
if not opts then
|
||||
return nil
|
||||
end
|
||||
local v: any = nil
|
||||
if type(opts.files) == "table" then
|
||||
v = opts.files[uri]
|
||||
end
|
||||
if v == nil and type(opts.resolve) == "function" then
|
||||
local ok, res = pcall(opts.resolve, uri)
|
||||
v = if ok then res else nil
|
||||
end
|
||||
if type(v) == "string" then
|
||||
return buffer.fromstring(v)
|
||||
end
|
||||
return if type(v) == "buffer" then v else nil
|
||||
end
|
||||
end
|
||||
|
||||
local function toErr(msg: any, offset: number?): Err.Err
|
||||
local s = tostring(msg)
|
||||
local code = Err.CORRUPT
|
||||
if string.sub(s, 1, 12) == "unsupported:" then
|
||||
code, s = Err.UNSUPPORTED, string.sub(s, 13)
|
||||
elseif string.sub(s, 1, 6) == "limit:" then
|
||||
code, s = Err.LIMIT, string.sub(s, 7)
|
||||
elseif string.find(s, "truncated", 1, true) or string.find(s, "runs past", 1, true) then
|
||||
code = Err.TRUNCATED
|
||||
end
|
||||
return Err.new(code, s, offset)
|
||||
end
|
||||
|
||||
-- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err.
|
||||
-- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }.
|
||||
function Fbx.tree(r: Bytes.Reader, opts: DecodeOptions?): (any, any, boolean?)
|
||||
if r:peek(21) == MAGIC then
|
||||
local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts)
|
||||
if not root then
|
||||
return nil, toErr(version, off)
|
||||
end
|
||||
return root, version, true
|
||||
end
|
||||
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
local root, version, off = Ascii.parse(text, opts)
|
||||
if not root then
|
||||
return nil, toErr(version, off and r.base + off)
|
||||
end
|
||||
if type(version) ~= "number" then
|
||||
return nil, Err.new(Err.CORRUPT, "no FBXHeaderExtension / FBXVersion")
|
||||
end
|
||||
if version < 7000 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "FBX version " .. version .. " (only 7.x)")
|
||||
end
|
||||
return root, version, false
|
||||
end
|
||||
|
||||
function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local root, version, binary = Fbx.tree(r, opts)
|
||||
if not root then
|
||||
return nil, version
|
||||
end
|
||||
-- the scene builder is plain (not native) code: a bug there must not escape as an error
|
||||
local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene))
|
||||
end
|
||||
if not scene then
|
||||
return nil, err
|
||||
end
|
||||
scene.meta.source.binary = binary
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Fbx.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(scene) ~= "table" or scene.kind ~= "scene" then
|
||||
return nil, Err.new(Err.ARG, "needs a Scene")
|
||||
end
|
||||
local version = opts and opts.version or 7400
|
||||
if version ~= 7400 and version ~= 7500 then
|
||||
return nil, Err.new(Err.ARG, "version must be 7400 or 7500")
|
||||
end
|
||||
local ok, root, err = pcall(Write.tree, scene, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "bad scene: " .. tostring(root))
|
||||
end
|
||||
if not root then
|
||||
return nil, err
|
||||
end
|
||||
if opts and opts.ascii then
|
||||
return buffer.fromstring(Ascii.write(root, version)), nil
|
||||
end
|
||||
return Binary.write(root, version, not (opts and opts.compress == false)), nil
|
||||
end
|
||||
|
||||
return Fbx
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,820 @@
|
||||
--!strict
|
||||
-- model/usda/Parse: USD ASCII (Sdf text format, "#usda 1.0") -> a layer of prim specs. New code, from the Sdf text
|
||||
-- grammar as Pixar's USD writes and reads it: layer metadata, def / over / class prims with metadata, attributes
|
||||
-- (custom / uniform / varying / config, scalar and array types, defaults, .timeSamples, .connect, metadata), relationships,
|
||||
-- list ops (prepend / append / add / delete / reorder), variant sets, dictionaries, strings ("", '', triple quoted),
|
||||
-- asset paths (@...@, @@@...@@@), paths (<...>), comments (#, //, /* */). Numeric arrays (points, indices) take a fast
|
||||
-- path into flat number arrays. .spline blocks and unknown constructs are skipped by bracket matching.
|
||||
-- Errors raise a table { usda = message, at = byte offset } inside this module; Parse.layer catches them (pcall) and
|
||||
-- returns nil, message, offset - nothing escapes.
|
||||
local Parse = {}
|
||||
|
||||
-- values: numbers, booleans, strings, and these tagged tables
|
||||
export type Arr = { t: "arr", w: number, v: { number } } -- numeric array, w numbers per element (tuples flattened)
|
||||
export type Value = any
|
||||
|
||||
export type Prop = {
|
||||
name: string,
|
||||
rel: boolean, -- a relationship
|
||||
typeName: string?, -- "point3f", "token", ... (attributes)
|
||||
array: boolean?,
|
||||
uniform: boolean?,
|
||||
custom: boolean?,
|
||||
value: Value?, -- the default value (attributes) or the targets (relationships: { path strings })
|
||||
hasValue: boolean?,
|
||||
samples: { times: { number }, values: { Value } }?,
|
||||
connect: { string }?, -- connection target paths (attributes)
|
||||
meta: { [string]: Value }?,
|
||||
}
|
||||
export type Prim = {
|
||||
specifier: string, -- "def" | "over" | "class"
|
||||
typeName: string?,
|
||||
name: string,
|
||||
meta: { [string]: Value },
|
||||
props: { [string]: Prop },
|
||||
order: { string }, -- property names in file order
|
||||
children: { Prim },
|
||||
variantSets: { [string]: { [string]: Prim } }?, -- set -> variant -> a prim body (props / children)
|
||||
}
|
||||
export type Layer = { meta: { [string]: Value }, prims: { Prim } }
|
||||
|
||||
local NONE = table.freeze({ t = "none" })
|
||||
Parse.NONE = NONE
|
||||
|
||||
local sfind, ssub, sbyte, smatch, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch
|
||||
|
||||
local LISTOPS = { prepend = true, append = true, add = true, delete = true, reorder = true }
|
||||
local VARIABILITY = { uniform = true, varying = true, config = true }
|
||||
local MAX_DEPTH = 200
|
||||
|
||||
local function fail(msg: string, at: number): never
|
||||
error({ usda = msg, at = at }, 0)
|
||||
end
|
||||
|
||||
-- the parser over one text; positions are 1-based string indices
|
||||
local function parser(s: string, maxBytes: number)
|
||||
local n = #s
|
||||
local depth = 0
|
||||
|
||||
-- whitespace and comments (newlines included)
|
||||
local function ws(i: number): number
|
||||
while true do
|
||||
local _, e = sfind(s, "^[ \t\r\n]+", i)
|
||||
if e then
|
||||
i = e + 1
|
||||
end
|
||||
local c = sbyte(s, i)
|
||||
if c == 35 then -- #
|
||||
local nl = sfind(s, "\n", i, true)
|
||||
i = if nl then nl + 1 else n + 1
|
||||
elseif c == 47 and sbyte(s, i + 1) == 47 then -- //
|
||||
local nl = sfind(s, "\n", i, true)
|
||||
i = if nl then nl + 1 else n + 1
|
||||
elseif c == 47 and sbyte(s, i + 1) == 42 then -- /* */
|
||||
local _, ce = sfind(s, "*/", i + 2, true)
|
||||
if not ce then
|
||||
fail("unterminated comment", i)
|
||||
end
|
||||
i = (ce :: number) + 1
|
||||
else
|
||||
return i
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function expect(i: number, ch: string): number
|
||||
i = ws(i)
|
||||
if ssub(s, i, i) ~= ch then
|
||||
fail("expected '" .. ch .. "'", i)
|
||||
end
|
||||
return i + 1
|
||||
end
|
||||
|
||||
local function ident(i: number): (string?, number)
|
||||
local a, e = sfind(s, "^[%a_][%w_:]*", i)
|
||||
if not a then
|
||||
return nil, i
|
||||
end
|
||||
return ssub(s, a, e), (e :: number) + 1
|
||||
end
|
||||
|
||||
local ESC = { n = "\n", t = "\t", r = "\r", ["\\"] = "\\", ['"'] = '"', ["'"] = "'", ["0"] = "\0", a = "\a", b = "\b", f = "\f", v = "\v" }
|
||||
local function unescape(str: string): string
|
||||
if not sfind(str, "\\", 1, true) then
|
||||
return str
|
||||
end
|
||||
return (string.gsub(str, "\\(x?)(.)", function(x: string, c: string): string
|
||||
if x == "x" then
|
||||
return "\\x" .. c -- left alone (rare)
|
||||
end
|
||||
return ESC[c] or c
|
||||
end))
|
||||
end
|
||||
|
||||
local function str(i: number): (string, number)
|
||||
local q = ssub(s, i, i)
|
||||
if ssub(s, i, i + 2) == q .. q .. q then
|
||||
local e = sfind(s, q .. q .. q, i + 3, true)
|
||||
if not e then
|
||||
fail("unterminated string", i)
|
||||
end
|
||||
return unescape(ssub(s, i + 3, (e :: number) - 1)), (e :: number) + 3
|
||||
end
|
||||
local j = i + 1
|
||||
while true do
|
||||
local a = sfind(s, "[\\\n" .. q .. "]", j)
|
||||
if not a then
|
||||
fail("unterminated string", i)
|
||||
end
|
||||
local c = sbyte(s, a :: number)
|
||||
if c == 92 then
|
||||
j = (a :: number) + 2
|
||||
elseif c == 10 then
|
||||
fail("newline in string", a :: number)
|
||||
else
|
||||
return unescape(ssub(s, i + 1, (a :: number) - 1)), (a :: number) + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function number(i: number): (number?, number)
|
||||
local a, e = sfind(s, "^[-+]?%d*%.?%d*[eE][-+]?%d+", i)
|
||||
if not a then
|
||||
a, e = sfind(s, "^[-+]?%d*%.?%d*", i)
|
||||
end
|
||||
if a and (e :: number) >= (a :: number) then
|
||||
local v = tonumber(ssub(s, a, e))
|
||||
if v then
|
||||
return v, (e :: number) + 1
|
||||
end
|
||||
end
|
||||
-- inf / -inf / nan
|
||||
local w, e2 = sfind(s, "^[-+]?%a+", i)
|
||||
if w then
|
||||
local word = string.lower(ssub(s, w, e2))
|
||||
if word == "inf" or word == "+inf" then
|
||||
return math.huge, (e2 :: number) + 1
|
||||
elseif word == "-inf" then
|
||||
return -math.huge, (e2 :: number) + 1
|
||||
elseif word == "nan" or word == "-nan" or word == "+nan" then
|
||||
return 0 / 0, (e2 :: number) + 1
|
||||
end
|
||||
end
|
||||
return nil, i
|
||||
end
|
||||
|
||||
-- skip a balanced (), [], {} block starting at i (strings and comments respected)
|
||||
local function skipBalanced(i: number): number
|
||||
local open = sbyte(s, i)
|
||||
local level = 0
|
||||
while i <= n do
|
||||
i = ws(i)
|
||||
local c = sbyte(s, i)
|
||||
if c == nil then
|
||||
break
|
||||
end
|
||||
if c == 40 or c == 91 or c == 123 then
|
||||
level += 1
|
||||
i += 1
|
||||
elseif c == 41 or c == 93 or c == 125 then
|
||||
level -= 1
|
||||
i += 1
|
||||
if level == 0 then
|
||||
return i
|
||||
end
|
||||
elseif c == 34 or c == 39 then
|
||||
local _, j = str(i)
|
||||
i = j
|
||||
elseif c == 64 then
|
||||
local e = sfind(s, "@", i + 1, true)
|
||||
i = if e then e + 1 else n + 1
|
||||
elseif c == 60 then
|
||||
local e = sfind(s, ">", i + 1, true)
|
||||
i = if e then e + 1 else n + 1
|
||||
else
|
||||
local _, e = sfind(s, "^[^%(%)%[%]{}\"'@<#/ \t\r\n]+", i)
|
||||
i = if e then e + 1 else i + 1
|
||||
end
|
||||
end
|
||||
fail("unbalanced " .. string.char(open or 63), i)
|
||||
end
|
||||
|
||||
local value: (i: number) -> (Value, number)
|
||||
local metadata: (i: number) -> ({ [string]: Value }, number)
|
||||
|
||||
-- [ ... ]: the fast path for numeric arrays (flat numbers + tuple width), else a generic list
|
||||
local function list(i: number): (Value, number)
|
||||
local close = sfind(s, "]", i + 1, true)
|
||||
if close then
|
||||
local body = ssub(s, i + 1, close - 1)
|
||||
if not sfind(body, "[^%d%s%.,eE%-%+%(%)]") then
|
||||
local first = smatch(body, "^%s*%(([^%)]*)%)")
|
||||
local w = 1
|
||||
if first then
|
||||
w = 0
|
||||
for _ in gmatch(first, "[^%s,]+") do
|
||||
w += 1
|
||||
end
|
||||
elseif sfind(body, "[%(%)]") then
|
||||
w = -1 -- nested tuples: the generic path
|
||||
end
|
||||
if w > 0 then
|
||||
local out: { number } = {}
|
||||
local k = 0
|
||||
local ok = true
|
||||
for tok in gmatch(body, "[^%s,%(%)]+") do
|
||||
local v = tonumber(tok)
|
||||
if not v then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
k += 1
|
||||
out[k] = v
|
||||
end
|
||||
if ok and k % w == 0 then
|
||||
if k * 8 > maxBytes then
|
||||
fail("array over the size limit", i)
|
||||
end
|
||||
return { t = "arr", w = w, v = out } :: Arr, close + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- generic
|
||||
local items = {}
|
||||
i += 1
|
||||
while true do
|
||||
i = ws(i)
|
||||
local c = ssub(s, i, i)
|
||||
if c == "]" then
|
||||
i += 1
|
||||
break
|
||||
elseif c == "" then
|
||||
fail("unterminated list", i)
|
||||
end
|
||||
local v
|
||||
v, i = value(i)
|
||||
table.insert(items, v)
|
||||
i = ws(i)
|
||||
if ssub(s, i, i) == "(" then -- per-item metadata (subLayers offsets, ...)
|
||||
local _
|
||||
_, i = metadata(i)
|
||||
i = ws(i)
|
||||
end
|
||||
c = ssub(s, i, i)
|
||||
if c == "," then
|
||||
i += 1
|
||||
elseif c ~= "]" then
|
||||
fail("expected ',' or ']' in a list", i)
|
||||
end
|
||||
end
|
||||
-- all numbers, or all equal-width numeric tuples -> arr
|
||||
local w: number? = nil
|
||||
local flat: { number } = {}
|
||||
for _, it in items do
|
||||
if type(it) == "number" then
|
||||
if w and w ~= 1 then
|
||||
return { t = "list", v = items }, i
|
||||
end
|
||||
w = 1
|
||||
table.insert(flat, it)
|
||||
elseif type(it) == "table" and it.t == "tuple" then
|
||||
local tw = #it.v
|
||||
if (w and w ~= tw) or tw == 0 then
|
||||
return { t = "list", v = items }, i
|
||||
end
|
||||
w = tw
|
||||
for _, x in it.v do
|
||||
if type(x) ~= "number" then
|
||||
return { t = "list", v = items }, i
|
||||
end
|
||||
table.insert(flat, x)
|
||||
end
|
||||
else
|
||||
return { t = "list", v = items }, i
|
||||
end
|
||||
end
|
||||
if w == nil then
|
||||
return { t = "list", v = items }, i
|
||||
end
|
||||
return { t = "arr", w = w, v = flat } :: Arr, i
|
||||
end
|
||||
|
||||
local function tuple(i: number): (Value, number)
|
||||
local items = {}
|
||||
i += 1
|
||||
while true do
|
||||
i = ws(i)
|
||||
local c = ssub(s, i, i)
|
||||
if c == ")" then
|
||||
i += 1
|
||||
break
|
||||
elseif c == "" then
|
||||
fail("unterminated tuple", i)
|
||||
end
|
||||
local v
|
||||
v, i = value(i)
|
||||
table.insert(items, v)
|
||||
i = ws(i)
|
||||
c = ssub(s, i, i)
|
||||
if c == "," then
|
||||
i += 1
|
||||
elseif c ~= ")" then
|
||||
fail("expected ',' or ')' in a tuple", i)
|
||||
end
|
||||
end
|
||||
return { t = "tuple", v = items }, i
|
||||
end
|
||||
|
||||
-- { type key = value ... } (metadata dictionaries)
|
||||
local function dict(i: number): (Value, number)
|
||||
local out: { [string]: Value } = {}
|
||||
i += 1
|
||||
while true do
|
||||
i = ws(i)
|
||||
local c = ssub(s, i, i)
|
||||
if c == "}" then
|
||||
i += 1
|
||||
break
|
||||
elseif c == "" then
|
||||
fail("unterminated dictionary", i)
|
||||
elseif c == ";" or c == "," then
|
||||
i += 1
|
||||
continue
|
||||
end
|
||||
local ty
|
||||
ty, i = ident(i)
|
||||
if not ty then
|
||||
fail("expected a type in a dictionary", i)
|
||||
end
|
||||
i = ws(i)
|
||||
if ssub(s, i, i + 1) == "[]" then
|
||||
i += 2
|
||||
end
|
||||
i = ws(i)
|
||||
local key: string?
|
||||
c = ssub(s, i, i)
|
||||
if c == '"' or c == "'" then
|
||||
key, i = str(i)
|
||||
else
|
||||
key, i = ident(i)
|
||||
end
|
||||
if not key then
|
||||
fail("expected a key in a dictionary", i)
|
||||
end
|
||||
i = expect(i, "=")
|
||||
local v
|
||||
v, i = value(i)
|
||||
out[key :: string] = v
|
||||
end
|
||||
return { t = "dict", v = out }, i
|
||||
end
|
||||
|
||||
function value(i: number): (Value, number)
|
||||
depth += 1
|
||||
if depth > MAX_DEPTH then
|
||||
fail("nesting too deep", i)
|
||||
end
|
||||
i = ws(i)
|
||||
local c = ssub(s, i, i)
|
||||
local v: Value
|
||||
if c == "[" then
|
||||
v, i = list(i)
|
||||
elseif c == "(" then
|
||||
v, i = tuple(i)
|
||||
elseif c == "{" then
|
||||
v, i = dict(i)
|
||||
elseif c == '"' or c == "'" then
|
||||
v, i = str(i)
|
||||
elseif c == "@" then
|
||||
local path
|
||||
if ssub(s, i, i + 2) == "@@@" then
|
||||
local e = sfind(s, "@@@", i + 3, true)
|
||||
if not e then
|
||||
fail("unterminated asset path", i)
|
||||
end
|
||||
path, i = ssub(s, i + 3, (e :: number) - 1), (e :: number) + 3
|
||||
else
|
||||
local e = sfind(s, "@", i + 1, true)
|
||||
if not e then
|
||||
fail("unterminated asset path", i)
|
||||
end
|
||||
path, i = ssub(s, i + 1, (e :: number) - 1), (e :: number) + 1
|
||||
end
|
||||
local a: { [string]: any } = { t = "asset", v = path }
|
||||
local j = ws(i)
|
||||
if ssub(s, j, j) == "<" then -- references = @file@</prim>
|
||||
local e = sfind(s, ">", j + 1, true)
|
||||
if not e then
|
||||
fail("unterminated path", j)
|
||||
end
|
||||
a.path = ssub(s, j + 1, (e :: number) - 1)
|
||||
i = (e :: number) + 1
|
||||
end
|
||||
v = a
|
||||
elseif c == "<" then
|
||||
local e = sfind(s, ">", i + 1, true)
|
||||
if not e then
|
||||
fail("unterminated path", i)
|
||||
end
|
||||
v, i = { t = "path", v = ssub(s, i + 1, (e :: number) - 1) }, (e :: number) + 1
|
||||
else
|
||||
local num, j = number(i)
|
||||
if num ~= nil then
|
||||
v, i = num, j
|
||||
else
|
||||
local id
|
||||
id, j = ident(i)
|
||||
if not id then
|
||||
fail("expected a value", i)
|
||||
end
|
||||
i = j
|
||||
if id == "None" then
|
||||
v = NONE
|
||||
elseif id == "true" then
|
||||
v = true
|
||||
elseif id == "false" then
|
||||
v = false
|
||||
else
|
||||
v = { t = "id", v = id }
|
||||
end
|
||||
end
|
||||
end
|
||||
depth -= 1
|
||||
return v, i
|
||||
end
|
||||
|
||||
-- ( key = value ; "doc" ; prepend key = value ... )
|
||||
function metadata(i: number): ({ [string]: Value }, number)
|
||||
local out: { [string]: Value } = {}
|
||||
i = expect(i, "(")
|
||||
while true do
|
||||
i = ws(i)
|
||||
local c = ssub(s, i, i)
|
||||
if c == ")" then
|
||||
return out, i + 1
|
||||
elseif c == "" then
|
||||
fail("unterminated metadata", i)
|
||||
elseif c == ";" or c == "," then
|
||||
i += 1
|
||||
continue
|
||||
elseif c == '"' or c == "'" then
|
||||
out.doc, i = str(i)
|
||||
continue
|
||||
end
|
||||
local key
|
||||
key, i = ident(i)
|
||||
if not key then
|
||||
fail("expected a metadata key", i)
|
||||
end
|
||||
local op: string? = nil
|
||||
if LISTOPS[key] then
|
||||
op = key
|
||||
i = ws(i)
|
||||
key, i = ident(i)
|
||||
if not key then
|
||||
fail("expected a metadata key", i)
|
||||
end
|
||||
end
|
||||
i = ws(i)
|
||||
if ssub(s, i, i) == "=" then
|
||||
local v
|
||||
v, i = value(i + 1)
|
||||
if op == "delete" then
|
||||
-- deletions only matter for composition
|
||||
elseif op and op ~= "reorder" then
|
||||
-- prepend / append / add: merge into one list
|
||||
local prev = out[key :: string]
|
||||
if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then
|
||||
for _, x in v.v do
|
||||
table.insert(prev.v, x)
|
||||
end
|
||||
else
|
||||
out[key :: string] = v
|
||||
end
|
||||
else
|
||||
out[key :: string] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- time samples: { time: value, ... }
|
||||
local function samples(i: number): ({ times: { number }, values: { Value } }, number)
|
||||
local times, values = {}, {}
|
||||
i = expect(i, "{")
|
||||
while true do
|
||||
i = ws(i)
|
||||
local c = ssub(s, i, i)
|
||||
if c == "}" then
|
||||
i += 1
|
||||
break
|
||||
elseif c == "" then
|
||||
fail("unterminated time samples", i)
|
||||
elseif c == "," then
|
||||
i += 1
|
||||
continue
|
||||
end
|
||||
local t
|
||||
t, i = number(i)
|
||||
if t == nil then
|
||||
fail("expected a time code", i)
|
||||
end
|
||||
i = expect(i, ":")
|
||||
local v
|
||||
v, i = value(i)
|
||||
table.insert(times, t)
|
||||
table.insert(values, v)
|
||||
end
|
||||
return { times = times, values = values }, i
|
||||
end
|
||||
|
||||
local function targets(v: Value): { string }
|
||||
local out = {}
|
||||
if type(v) == "table" then
|
||||
if v.t == "path" then
|
||||
table.insert(out, v.v)
|
||||
elseif v.t == "list" then
|
||||
for _, x in v.v do
|
||||
if type(x) == "table" and x.t == "path" then
|
||||
table.insert(out, x.v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local primBody: (i: number, prim: Prim) -> number
|
||||
|
||||
local function newPrim(specifier: string, typeName: string?, name: string): Prim
|
||||
return { specifier = specifier, typeName = typeName, name = name, meta = {}, props = {}, order = {}, children = {} }
|
||||
end
|
||||
|
||||
-- def Type "name" ( meta ) { body }
|
||||
local function prim(i: number, specifier: string): (Prim, number)
|
||||
i = ws(i)
|
||||
local typeName: string? = nil
|
||||
local c = ssub(s, i, i)
|
||||
if c ~= '"' and c ~= "'" then
|
||||
typeName, i = ident(i)
|
||||
if not typeName then
|
||||
fail("expected a prim type or name", i)
|
||||
end
|
||||
i = ws(i)
|
||||
-- dotted schema names (rare)
|
||||
while ssub(s, i, i) == "." do
|
||||
local more
|
||||
more, i = ident(i + 1)
|
||||
typeName = (typeName :: string) .. "." .. (more or "")
|
||||
end
|
||||
i = ws(i)
|
||||
end
|
||||
c = ssub(s, i, i)
|
||||
if c ~= '"' and c ~= "'" then
|
||||
fail("expected a prim name", i)
|
||||
end
|
||||
local name
|
||||
name, i = str(i)
|
||||
local p = newPrim(specifier, typeName, name)
|
||||
i = ws(i)
|
||||
if ssub(s, i, i) == "(" then
|
||||
p.meta, i = metadata(i)
|
||||
end
|
||||
i = expect(i, "{")
|
||||
i = primBody(i, p)
|
||||
return p, i
|
||||
end
|
||||
|
||||
-- variantSet "name" = { "variant" ( meta ) { body } ... }
|
||||
local function variantSet(i: number, p: Prim): number
|
||||
i = ws(i)
|
||||
local setName
|
||||
setName, i = str(i)
|
||||
i = expect(i, "=")
|
||||
i = expect(i, "{")
|
||||
local sets = p.variantSets or {}
|
||||
p.variantSets = sets
|
||||
local set = sets[setName] or {}
|
||||
sets[setName] = set
|
||||
while true do
|
||||
i = ws(i)
|
||||
local c = ssub(s, i, i)
|
||||
if c == "}" then
|
||||
return i + 1
|
||||
elseif c ~= '"' and c ~= "'" then
|
||||
fail("expected a variant name", i)
|
||||
end
|
||||
local vname
|
||||
vname, i = str(i)
|
||||
local body = newPrim("def", nil, vname)
|
||||
i = ws(i)
|
||||
if ssub(s, i, i) == "(" then
|
||||
body.meta, i = metadata(i)
|
||||
end
|
||||
i = expect(i, "{")
|
||||
i = primBody(i, body)
|
||||
set[vname] = body
|
||||
end
|
||||
end
|
||||
|
||||
-- one property: [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...]
|
||||
local function property(i: number, first: string, p: Prim): number
|
||||
local word: string? = first
|
||||
local op: string? = nil
|
||||
if LISTOPS[word :: string] then
|
||||
op = word
|
||||
i = ws(i)
|
||||
word, i = ident(i)
|
||||
end
|
||||
local custom, uniform = false, false
|
||||
if word == "custom" then
|
||||
custom = true
|
||||
i = ws(i)
|
||||
word, i = ident(i)
|
||||
end
|
||||
if word and VARIABILITY[word] then
|
||||
uniform = word == "uniform"
|
||||
i = ws(i)
|
||||
word, i = ident(i)
|
||||
end
|
||||
if not word then
|
||||
fail("expected a property", i)
|
||||
end
|
||||
local isRel = word == "rel"
|
||||
local typeName: string? = nil
|
||||
local array = false
|
||||
if not isRel then
|
||||
typeName = word
|
||||
i = ws(i)
|
||||
if ssub(s, i, i + 1) == "[]" then
|
||||
array = true
|
||||
i += 2
|
||||
end
|
||||
end
|
||||
i = ws(i)
|
||||
local name
|
||||
name, i = ident(i)
|
||||
if not name then
|
||||
fail("expected a property name", i)
|
||||
end
|
||||
local suffix: string? = nil
|
||||
if ssub(s, i, i) == "." then
|
||||
suffix, i = ident(i + 1)
|
||||
end
|
||||
local prop = p.props[name :: string]
|
||||
if not prop then
|
||||
prop = { name = name :: string, rel = isRel }
|
||||
p.props[name :: string] = prop
|
||||
table.insert(p.order, name :: string)
|
||||
end
|
||||
local pr = prop :: Prop
|
||||
if typeName then
|
||||
pr.typeName, pr.array = typeName, array
|
||||
end
|
||||
pr.uniform = pr.uniform or uniform or nil
|
||||
pr.custom = pr.custom or custom or nil
|
||||
i = ws(i)
|
||||
if ssub(s, i, i) == "=" then
|
||||
i = ws(i + 1)
|
||||
if suffix == "timeSamples" then
|
||||
pr.samples, i = samples(i)
|
||||
elseif suffix == "spline" or (suffix ~= nil and suffix ~= "connect" and suffix ~= "default" and ssub(s, i, i) == "{") then
|
||||
i = skipBalanced(i)
|
||||
else
|
||||
local v
|
||||
v, i = value(i)
|
||||
if op == "delete" then
|
||||
-- composition only
|
||||
elseif suffix == "connect" then
|
||||
pr.connect = targets(v)
|
||||
elseif isRel then
|
||||
pr.value = targets(v)
|
||||
pr.hasValue = true
|
||||
else
|
||||
pr.value = v
|
||||
pr.hasValue = true
|
||||
end
|
||||
end
|
||||
end
|
||||
i = ws(i)
|
||||
if ssub(s, i, i) == "(" then
|
||||
local m
|
||||
m, i = metadata(i)
|
||||
if pr.meta then
|
||||
for k, v in m do
|
||||
(pr.meta :: any)[k] = v
|
||||
end
|
||||
else
|
||||
pr.meta = m
|
||||
end
|
||||
end
|
||||
return i
|
||||
end
|
||||
|
||||
function primBody(i: number, p: Prim): number
|
||||
depth += 1
|
||||
if depth > MAX_DEPTH then
|
||||
fail("nesting too deep", i)
|
||||
end
|
||||
while true do
|
||||
i = ws(i)
|
||||
local c = ssub(s, i, i)
|
||||
if c == "}" then
|
||||
depth -= 1
|
||||
return i + 1
|
||||
elseif c == "" then
|
||||
fail("unterminated prim", i)
|
||||
elseif c == ";" then
|
||||
i += 1
|
||||
continue
|
||||
end
|
||||
local word, j = ident(i)
|
||||
if not word then
|
||||
fail("unexpected character in a prim", i)
|
||||
end
|
||||
if word == "def" or word == "over" or word == "class" then
|
||||
local child
|
||||
child, i = prim(j, word)
|
||||
table.insert(p.children, child)
|
||||
elseif word == "variantSet" then
|
||||
i = variantSet(j, p)
|
||||
elseif word == "reorder" then
|
||||
local k = ws(j)
|
||||
local w2, k2 = ident(k)
|
||||
if w2 == "nameChildren" or w2 == "properties" or w2 == "rootPrims" then
|
||||
k2 = expect(k2, "=")
|
||||
local _
|
||||
_, i = value(k2)
|
||||
else
|
||||
i = property(j, word, p)
|
||||
end
|
||||
else
|
||||
i = property(j, word, p)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- the whole layer
|
||||
local function layer(): Layer
|
||||
local i = 1
|
||||
if ssub(s, 1, 3) == "\239\187\191" then
|
||||
i = 4
|
||||
end
|
||||
if ssub(s, i, i + 4) ~= "#usda" then
|
||||
fail("not a USDA file (no #usda header)", i)
|
||||
end
|
||||
local nl = sfind(s, "\n", i, true)
|
||||
i = if nl then nl + 1 else n + 1
|
||||
local out: Layer = { meta = {}, prims = {} }
|
||||
i = ws(i)
|
||||
if ssub(s, i, i) == "(" then
|
||||
out.meta, i = metadata(i)
|
||||
end
|
||||
while true do
|
||||
i = ws(i)
|
||||
if i > n then
|
||||
break
|
||||
end
|
||||
local word, j = ident(i)
|
||||
if word == "def" or word == "over" or word == "class" then
|
||||
local p
|
||||
p, i = prim(j, word)
|
||||
table.insert(out.prims, p)
|
||||
elseif word == "reorder" then
|
||||
j = ws(j)
|
||||
local _
|
||||
_, j = ident(j)
|
||||
j = expect(j, "=")
|
||||
_, i = value(j)
|
||||
elseif ssub(s, i, i) == ";" then
|
||||
i += 1
|
||||
else
|
||||
fail("expected def / over / class", i)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return layer
|
||||
end
|
||||
|
||||
-- layer(text, opts?) -> Layer | nil, message, offset (0-based)
|
||||
function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?)
|
||||
local run = parser(text, maxBytes or 2 ^ 30)
|
||||
local ok, res = pcall(run)
|
||||
if ok then
|
||||
return res, nil, nil
|
||||
end
|
||||
if type(res) == "table" and res.usda then
|
||||
return nil, res.usda, math.max((res.at or 1) - 1, 0)
|
||||
end
|
||||
return nil, "parse error: " .. tostring(res), nil
|
||||
end
|
||||
|
||||
-- version(text) -> the "#usda <version>" string
|
||||
function Parse.version(text: string): string?
|
||||
return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)")
|
||||
end
|
||||
|
||||
return Parse
|
||||
@@ -0,0 +1,840 @@
|
||||
--!strict
|
||||
-- model/usda/Write: Scene -> USD ASCII text (UsdGeom / UsdShade / UsdLux). New code.
|
||||
-- Layout: one root prim (the scene's single root node, else an Xform "root" holding every root) as the defaultPrim,
|
||||
-- a "Looks" scope under it with the materials (UsdPreviewSurface + UsdUVTexture + UsdPrimvarReader_float2, texture
|
||||
-- transforms as UsdTransform2d), and one prim per node: a node with a mesh is a Mesh prim (its primitives merged, a
|
||||
-- GeomSubset per primitive when there are several), a node with only a camera / light is that Camera / light prim,
|
||||
-- other nodes are Xforms (meshes / cameras / lights that cannot share the node's prim become children). Transforms are
|
||||
-- translate / orient / scale ops (or a transform op for matrices); animation channels (translation / rotation / scale)
|
||||
-- become time samples on those ops (timeCodesPerSecond 24). TEXCOORD_n -> primvars:st, st1, ... (v flipped back),
|
||||
-- COLOR_0 -> displayColor (+ displayOpacity), NORMAL -> normals, all "vertex" interpolated. Textures: their uri, or the
|
||||
-- embedded bytes written into opts.files as <name>_<n>.<ext>. Not written: skins, morph targets, weights animation,
|
||||
-- lines / points primitives (counted in the returned notes).
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Write = {}
|
||||
|
||||
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif", ["image/bmp"] = "bmp", ["image/x-tga"] = "tga", ["image/gif"] = "gif", ["image/tiff"] = "tiff" }
|
||||
local RAD = 180 / math.pi
|
||||
|
||||
export type Options = { files: { [string]: any }?, name: string?, upAxis: string?, metersPerUnit: number? }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ text helpers
|
||||
local function fmt(x: number): string
|
||||
if x ~= x then
|
||||
return "nan"
|
||||
elseif x == math.huge then
|
||||
return "inf"
|
||||
elseif x == -math.huge then
|
||||
return "-inf"
|
||||
elseif x == math.floor(x) and math.abs(x) < 1e15 then
|
||||
return string.format("%d", x)
|
||||
end
|
||||
return string.format("%.9g", x)
|
||||
end
|
||||
local function tuple(t: { number }): string
|
||||
local parts = table.create(#t)
|
||||
for k, v in t do
|
||||
parts[k] = fmt(v)
|
||||
end
|
||||
return "(" .. table.concat(parts, ", ") .. ")"
|
||||
end
|
||||
local function quote(s: string): string
|
||||
return '"' .. string.gsub(s, '[\\"\n]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n" }) .. '"'
|
||||
end
|
||||
local function asset(s: string): string
|
||||
if string.find(s, "@", 1, true) then
|
||||
return "@@@" .. s .. "@@@"
|
||||
end
|
||||
return "@" .. s .. "@"
|
||||
end
|
||||
-- a valid, sibling-unique prim name
|
||||
local function namer(): (string?, string) -> string
|
||||
local used: { [string]: boolean } = {}
|
||||
return function(name: string?, fallback: string): string
|
||||
local n = string.gsub(name or "", "[^%w_]", "_")
|
||||
if n == "" then
|
||||
n = fallback
|
||||
end
|
||||
if string.find(n, "^%d") then
|
||||
n = "_" .. n
|
||||
end
|
||||
local base, k = n, 1
|
||||
while used[n] do
|
||||
k += 1
|
||||
n = base .. "_" .. k
|
||||
end
|
||||
used[n] = true
|
||||
return n
|
||||
end
|
||||
end
|
||||
|
||||
-- an accessor's elements as numbers (normalized types to floats)
|
||||
local function values(acc: Types.Accessor?): ({ number }?, number)
|
||||
if not acc then
|
||||
return nil, 0
|
||||
end
|
||||
local get = Types.Scene.reader(acc)
|
||||
if not get then
|
||||
return nil, 0
|
||||
end
|
||||
local n, c = acc.count, acc.components
|
||||
local out = table.create(n * c)
|
||||
for i = 0, n - 1 do
|
||||
for k = 0, c - 1 do
|
||||
out[i * c + k + 1] = get(i, k)
|
||||
end
|
||||
end
|
||||
return out, c
|
||||
end
|
||||
|
||||
-- array literal of tuples ("[(x, y, z), ...]") or scalars
|
||||
local function arrayText(vals: { number }, width: number, stride: number?, count: number?, map: ((i: number, k: number, v: number) -> number)?): string
|
||||
local st = stride or width
|
||||
local n = count or (#vals // st)
|
||||
local parts = table.create(n)
|
||||
local buf = table.create(width)
|
||||
for i = 0, n - 1 do
|
||||
for k = 1, width do
|
||||
local v = vals[i * st + k] or 0
|
||||
if map then
|
||||
v = map(i, k, v)
|
||||
end
|
||||
buf[k] = fmt(v)
|
||||
end
|
||||
parts[i + 1] = if width == 1 then buf[1] else "(" .. table.concat(buf, ", ", 1, width) .. ")"
|
||||
end
|
||||
return "[" .. table.concat(parts, ", ") .. "]"
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ primitives
|
||||
type Merged = {
|
||||
points: { number },
|
||||
counts: { number },
|
||||
indices: { number },
|
||||
normals: { number }?,
|
||||
uvs: { [number]: { number } },
|
||||
colors: { number }?, -- rgba
|
||||
hasAlpha: boolean,
|
||||
subsets: { { faces: { number }, material: number? } },
|
||||
}
|
||||
|
||||
-- the triangles / polygons of a primitive as (counts, corner indices into its vertices); nil for lines / points
|
||||
local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?)
|
||||
local idx: { number }
|
||||
if p.indices then
|
||||
idx = (values(p.indices)) or {}
|
||||
else
|
||||
idx = table.create(nverts)
|
||||
for i = 1, nverts do
|
||||
idx[i] = i - 1
|
||||
end
|
||||
end
|
||||
local counts, out = {}, {}
|
||||
local mode = p.mode
|
||||
if mode == "triangles" or mode == nil then
|
||||
for k = 1, #idx - 2, 3 do
|
||||
table.insert(counts, 3)
|
||||
table.insert(out, idx[k])
|
||||
table.insert(out, idx[k + 1])
|
||||
table.insert(out, idx[k + 2])
|
||||
end
|
||||
elseif mode == "polygons" then
|
||||
local fs = (values(p.faces)) or {}
|
||||
local at = 1
|
||||
for _, n in fs do
|
||||
if at + n - 1 > #idx then
|
||||
break
|
||||
end
|
||||
table.insert(counts, n)
|
||||
for k = at, at + n - 1 do
|
||||
table.insert(out, idx[k])
|
||||
end
|
||||
at += n
|
||||
end
|
||||
elseif mode == "triangle_strip" then
|
||||
for k = 1, #idx - 2 do
|
||||
local a, b, c = idx[k], idx[k + 1], idx[k + 2]
|
||||
if k % 2 == 0 then
|
||||
a, b = b, a
|
||||
end
|
||||
table.insert(counts, 3)
|
||||
table.insert(out, a)
|
||||
table.insert(out, b)
|
||||
table.insert(out, c)
|
||||
end
|
||||
elseif mode == "triangle_fan" then
|
||||
for k = 2, #idx - 1 do
|
||||
table.insert(counts, 3)
|
||||
table.insert(out, idx[1])
|
||||
table.insert(out, idx[k])
|
||||
table.insert(out, idx[k + 1])
|
||||
end
|
||||
else
|
||||
return nil, nil
|
||||
end
|
||||
return counts, out
|
||||
end
|
||||
|
||||
-- the primitives of a mesh merged into one USD mesh (GeomSubsets per primitive); nil when nothing is writable
|
||||
local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged?
|
||||
local prims: { Types.Primitive } = {}
|
||||
for _, p in mesh.primitives do
|
||||
if p.attributes and p.attributes.POSITION and p.attributes.POSITION.components == 3 and p.mode ~= "lines" and p.mode ~= "line_strip" and p.mode ~= "line_loop" and p.mode ~= "points" then
|
||||
table.insert(prims, p)
|
||||
else
|
||||
notes["lines / points primitives"] = (notes["lines / points primitives"] or 0) + 1
|
||||
end
|
||||
if p.targets and #p.targets > 0 then
|
||||
notes["morph targets"] = (notes["morph targets"] or 0) + 1
|
||||
end
|
||||
end
|
||||
if #prims == 0 then
|
||||
return nil
|
||||
end
|
||||
-- attributes every primitive has
|
||||
local all = { NORMAL = true }
|
||||
local uvSets: { number } = {}
|
||||
for k = 0, 7 do
|
||||
local every = true
|
||||
for _, p in prims do
|
||||
if not p.attributes["TEXCOORD_" .. k] then
|
||||
every = false
|
||||
end
|
||||
end
|
||||
if every then
|
||||
table.insert(uvSets, k)
|
||||
end
|
||||
end
|
||||
local anyColor = false
|
||||
for _, p in prims do
|
||||
if not p.attributes.NORMAL or p.attributes.NORMAL.components ~= 3 then
|
||||
all.NORMAL = false
|
||||
end
|
||||
if p.attributes.COLOR_0 then
|
||||
anyColor = true
|
||||
end
|
||||
end
|
||||
local m: Merged = { points = {}, counts = {}, indices = {}, normals = if all.NORMAL then {} else nil, uvs = {}, colors = if anyColor then {} else nil, hasAlpha = false, subsets = {} }
|
||||
for _, k in uvSets do
|
||||
m.uvs[k] = {}
|
||||
end
|
||||
local face = 0
|
||||
for _, p in prims do
|
||||
local base = #m.points // 3
|
||||
local pos = (values(p.attributes.POSITION)) or {}
|
||||
local nv = p.attributes.POSITION.count
|
||||
table.move(pos, 1, nv * 3, #m.points + 1, m.points)
|
||||
if m.normals then
|
||||
local nrm = (values(p.attributes.NORMAL)) or {}
|
||||
table.move(nrm, 1, nv * 3, #m.normals + 1, m.normals)
|
||||
end
|
||||
for _, k in uvSets do
|
||||
local uv, c = values(p.attributes["TEXCOORD_" .. k])
|
||||
local dst = m.uvs[k]
|
||||
for i = 0, nv - 1 do
|
||||
table.insert(dst, (uv :: { number })[i * c + 1] or 0)
|
||||
table.insert(dst, (uv :: { number })[i * c + 2] or 0)
|
||||
end
|
||||
end
|
||||
if m.colors then
|
||||
local col, c = values(p.attributes.COLOR_0)
|
||||
local dst = m.colors :: { number }
|
||||
for i = 0, nv - 1 do
|
||||
if col then
|
||||
table.insert(dst, col[i * c + 1] or 1)
|
||||
table.insert(dst, col[i * c + 2] or 1)
|
||||
table.insert(dst, col[i * c + 3] or 1)
|
||||
local a = if c >= 4 then col[i * c + 4] or 1 else 1
|
||||
if a ~= 1 then
|
||||
m.hasAlpha = true
|
||||
end
|
||||
table.insert(dst, a)
|
||||
else
|
||||
table.insert(dst, 1)
|
||||
table.insert(dst, 1)
|
||||
table.insert(dst, 1)
|
||||
table.insert(dst, 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
local counts, idx = faces(p, nv)
|
||||
local sub = { faces = {}, material = p.material }
|
||||
if counts and idx then
|
||||
local ok = true
|
||||
for _, v in idx do
|
||||
if v < 0 or v >= nv then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if ok then
|
||||
for _, c in counts do
|
||||
table.insert(m.counts, c)
|
||||
table.insert(sub.faces, face)
|
||||
face += 1
|
||||
end
|
||||
for _, v in idx do
|
||||
table.insert(m.indices, v + base)
|
||||
end
|
||||
else
|
||||
notes["out-of-range indices"] = (notes["out-of-range indices"] or 0) + 1
|
||||
end
|
||||
end
|
||||
table.insert(m.subsets, sub)
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ write
|
||||
function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: number })
|
||||
local o: Options = opts or {}
|
||||
local notes: { [string]: number } = {}
|
||||
local out: { string } = {}
|
||||
local function line(depth: number, s: string)
|
||||
table.insert(out, string.rep(" ", depth) .. s)
|
||||
end
|
||||
local nodes = scene.nodes or {}
|
||||
local roots = scene.roots
|
||||
if not roots or #roots == 0 then
|
||||
local child = {}
|
||||
for _, n in nodes do
|
||||
for _, c in n.children or {} do
|
||||
child[c] = true
|
||||
end
|
||||
end
|
||||
roots = {}
|
||||
for i in nodes do
|
||||
if not child[i] then
|
||||
table.insert(roots, i)
|
||||
end
|
||||
end
|
||||
end
|
||||
if #(scene.skins or {}) > 0 then
|
||||
notes.skins = #scene.skins
|
||||
end
|
||||
local wrap = #roots ~= 1 or (nodes[roots[1]] == nil)
|
||||
local rootNames = namer()
|
||||
local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root")
|
||||
|
||||
-- texture files
|
||||
local base = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model"
|
||||
local texFile: { [number]: string } = {}
|
||||
for i, tex in scene.textures or {} do
|
||||
local uri: string? = if tex.uri then (string.gsub(tex.uri, "\\", "/")) else nil
|
||||
if tex.data and type(o.files) == "table" then
|
||||
uri = uri or (base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png"))
|
||||
if string.find(uri :: string, "^data:") or string.find(uri :: string, "^%a+://") then
|
||||
uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")
|
||||
end
|
||||
local files: any = o.files
|
||||
if files[uri] == nil then
|
||||
files[uri] = tex.data
|
||||
end
|
||||
elseif not uri then
|
||||
uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")
|
||||
notes["textures without a file (not written)"] = (notes["textures without a file (not written)"] or 0) + 1
|
||||
end
|
||||
texFile[i] = uri :: string
|
||||
end
|
||||
|
||||
-- animation: per node, per path -> { times, values (components) }
|
||||
type Track = { times: { number }, vals: { number }, comps: number }
|
||||
local tracks: { [number]: { [string]: Track } } = {}
|
||||
local tcps = 24
|
||||
local tMin, tMax = math.huge, -math.huge
|
||||
for _, anim in scene.animations or {} do
|
||||
for _, ch in anim.channels or {} do
|
||||
if ch.path == "weights" then
|
||||
notes["weights animation"] = (notes["weights animation"] or 0) + 1
|
||||
elseif nodes[ch.node] and ch.input and ch.output then
|
||||
local times = (values(ch.input)) or {}
|
||||
local vals, comps = values(ch.output)
|
||||
if vals and #times > 0 then
|
||||
local stride = comps
|
||||
local per = #vals // (comps * #times)
|
||||
-- CUBICSPLINE: in-tangent, value, out-tangent per key: keep the value
|
||||
local off = if ch.interpolation == "CUBICSPLINE" and per == 3 then comps else 0
|
||||
local mult = if ch.interpolation == "CUBICSPLINE" and per == 3 then 3 else 1
|
||||
local tv = {}
|
||||
for k = 0, #times - 1 do
|
||||
for c = 1, stride do
|
||||
table.insert(tv, vals[k * comps * mult + off + c] or 0)
|
||||
end
|
||||
end
|
||||
tracks[ch.node] = tracks[ch.node] or {}
|
||||
tracks[ch.node][ch.path] = { times = times, vals = tv, comps = comps }
|
||||
for _, t in times do
|
||||
tMin = math.min(tMin, t * tcps)
|
||||
tMax = math.max(tMax, t * tcps)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- header
|
||||
table.insert(out, "#usda 1.0")
|
||||
table.insert(out, "(")
|
||||
line(1, "defaultPrim = " .. quote(rootName))
|
||||
line(1, 'doc = "formats-luau"')
|
||||
if tMin <= tMax then
|
||||
line(1, "endTimeCode = " .. fmt(tMax))
|
||||
end
|
||||
line(1, "metersPerUnit = " .. fmt(o.metersPerUnit or scene.meta.unit or 1))
|
||||
if tMin <= tMax then
|
||||
line(1, "startTimeCode = " .. fmt(tMin))
|
||||
line(1, "timeCodesPerSecond = " .. fmt(tcps))
|
||||
end
|
||||
line(1, "upAxis = " .. quote(o.upAxis or (if scene.meta.up == "z" then "Z" else "Y")))
|
||||
table.insert(out, ")")
|
||||
table.insert(out, "")
|
||||
|
||||
local looksPath = "/" .. rootName .. "/Looks"
|
||||
local matNames = namer()
|
||||
local matPath: { [number]: string } = {}
|
||||
for i, mat in scene.materials or {} do
|
||||
matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i)
|
||||
end
|
||||
|
||||
-- xform ops of a node (+ its animation)
|
||||
local function xform(depth: number, ni: number, n: Types.Node)
|
||||
local tr = tracks[ni]
|
||||
local order: { string } = {}
|
||||
local function samples(track: Track, f: (vals: { number }, at: number) -> string): string
|
||||
local parts = {}
|
||||
for k, t in track.times do
|
||||
table.insert(parts, fmt(t * tcps) .. ": " .. f(track.vals, (k - 1) * track.comps))
|
||||
end
|
||||
return "{ " .. table.concat(parts, ", ") .. " }"
|
||||
end
|
||||
local function quat(v: { number }, at: number): string
|
||||
-- USD writes (real, i, j, k)
|
||||
return tuple({ v[at + 4] or 1, v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 })
|
||||
end
|
||||
local function vec3(v: { number }, at: number): string
|
||||
return tuple({ v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 })
|
||||
end
|
||||
local t, r, s = n.translation, n.rotation, n.scale
|
||||
if n.matrix and #n.matrix == 16 then
|
||||
if tr then
|
||||
-- animated: start from the matrix's TRS
|
||||
local m = n.matrix
|
||||
local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2)
|
||||
local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2)
|
||||
local sz = math.sqrt(m[9] ^ 2 + m[10] ^ 2 + m[11] ^ 2)
|
||||
t, s = { m[13], m[14], m[15] }, { sx, sy, sz }
|
||||
r = nil
|
||||
notes["matrix nodes with animation (rotation reset)"] = (notes["matrix nodes with animation (rotation reset)"] or 0) + 1
|
||||
else
|
||||
local m = n.matrix
|
||||
line(depth, string.format("matrix4d xformOp:transform = ( %s, %s, %s, %s )", tuple({ m[1], m[2], m[3], m[4] }), tuple({ m[5], m[6], m[7], m[8] }), tuple({ m[9], m[10], m[11], m[12] }), tuple({ m[13], m[14], m[15], m[16] })))
|
||||
line(depth, 'uniform token[] xformOpOrder = ["xformOp:transform"]')
|
||||
return
|
||||
end
|
||||
end
|
||||
if t or (tr and tr.translation) then
|
||||
if t then
|
||||
line(depth, "double3 xformOp:translate = " .. tuple({ t[1] or 0, t[2] or 0, t[3] or 0 }))
|
||||
end
|
||||
if tr and tr.translation then
|
||||
line(depth, "double3 xformOp:translate.timeSamples = " .. samples(tr.translation, vec3))
|
||||
end
|
||||
table.insert(order, '"xformOp:translate"')
|
||||
end
|
||||
if r or (tr and tr.rotation) then
|
||||
if r then
|
||||
line(depth, "quatf xformOp:orient = " .. quat(r, 0))
|
||||
end
|
||||
if tr and tr.rotation then
|
||||
line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation, quat))
|
||||
end
|
||||
table.insert(order, '"xformOp:orient"')
|
||||
end
|
||||
if s or (tr and tr.scale) then
|
||||
if s then
|
||||
line(depth, "float3 xformOp:scale = " .. tuple({ s[1] or 1, s[2] or 1, s[3] or 1 }))
|
||||
end
|
||||
if tr and tr.scale then
|
||||
line(depth, "float3 xformOp:scale.timeSamples = " .. samples(tr.scale, vec3))
|
||||
end
|
||||
table.insert(order, '"xformOp:scale"')
|
||||
end
|
||||
if #order > 0 then
|
||||
line(depth, "uniform token[] xformOpOrder = [" .. table.concat(order, ", ") .. "]")
|
||||
end
|
||||
end
|
||||
|
||||
local function meshBody(depth: number, m: Merged, path: string)
|
||||
local doubleSided = false
|
||||
for _, sub in m.subsets do
|
||||
local mat = sub.material and scene.materials[sub.material]
|
||||
if mat and mat.doubleSided then
|
||||
doubleSided = true
|
||||
end
|
||||
end
|
||||
if doubleSided then
|
||||
line(depth, "uniform bool doubleSided = 1")
|
||||
end
|
||||
-- extent
|
||||
local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for i = 0, #m.points // 3 - 1 do
|
||||
for c = 1, 3 do
|
||||
local v = m.points[i * 3 + c]
|
||||
if v < mn[c] then
|
||||
mn[c] = v
|
||||
end
|
||||
if v > mx[c] then
|
||||
mx[c] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
if #m.points > 0 then
|
||||
line(depth, "float3[] extent = [" .. tuple(mn) .. ", " .. tuple(mx) .. "]")
|
||||
end
|
||||
line(depth, "int[] faceVertexCounts = " .. arrayText(m.counts, 1))
|
||||
line(depth, "int[] faceVertexIndices = " .. arrayText(m.indices, 1))
|
||||
local single = #m.subsets == 1
|
||||
if single and m.subsets[1].material and matPath[m.subsets[1].material :: number] then
|
||||
line(depth, "rel material:binding = <" .. matPath[m.subsets[1].material :: number] .. ">")
|
||||
end
|
||||
if m.normals then
|
||||
line(depth, "normal3f[] normals = " .. arrayText(m.normals, 3) .. " (")
|
||||
line(depth + 1, 'interpolation = "vertex"')
|
||||
line(depth, ")")
|
||||
end
|
||||
line(depth, "point3f[] points = " .. arrayText(m.points, 3))
|
||||
if m.colors then
|
||||
line(depth, "color3f[] primvars:displayColor = " .. arrayText(m.colors, 3, 4) .. " (")
|
||||
line(depth + 1, 'interpolation = "vertex"')
|
||||
line(depth, ")")
|
||||
if m.hasAlpha then
|
||||
local alpha = {}
|
||||
for i = 0, #m.colors // 4 - 1 do
|
||||
alpha[i + 1] = m.colors[i * 4 + 4]
|
||||
end
|
||||
line(depth, "float[] primvars:displayOpacity = " .. arrayText(alpha, 1) .. " (")
|
||||
line(depth + 1, 'interpolation = "vertex"')
|
||||
line(depth, ")")
|
||||
end
|
||||
end
|
||||
local uvKeys = {}
|
||||
for k in m.uvs do
|
||||
table.insert(uvKeys, k)
|
||||
end
|
||||
table.sort(uvKeys)
|
||||
for _, k in uvKeys do
|
||||
local name = if k == 0 then "st" else "st" .. k
|
||||
line(depth, "texCoord2f[] primvars:" .. name .. " = " .. arrayText(m.uvs[k], 2, nil, nil, function(_i: number, c: number, v: number): number
|
||||
return if c == 2 then 1 - v else v
|
||||
end) .. " (")
|
||||
line(depth + 1, 'interpolation = "vertex"')
|
||||
line(depth, ")")
|
||||
end
|
||||
line(depth, 'uniform token subdivisionScheme = "none"')
|
||||
if not single then
|
||||
local names = namer()
|
||||
for k, sub in m.subsets do
|
||||
if #sub.faces > 0 then
|
||||
local mp = sub.material and matPath[sub.material :: number]
|
||||
table.insert(out, "")
|
||||
line(depth, 'def GeomSubset "' .. names("subset_" .. k, "subset") .. '"' .. (if mp then ' (\n' .. string.rep(" ", depth + 1) .. 'prepend apiSchemas = ["MaterialBindingAPI"]\n' .. string.rep(" ", depth) .. ")" else ""))
|
||||
line(depth, "{")
|
||||
line(depth + 1, 'uniform token elementType = "face"')
|
||||
line(depth + 1, 'uniform token familyName = "materialBind"')
|
||||
line(depth + 1, "int[] indices = " .. arrayText(sub.faces, 1))
|
||||
if mp then
|
||||
line(depth + 1, "rel material:binding = <" .. mp .. ">")
|
||||
end
|
||||
line(depth, "}")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function cameraBody(depth: number, c: Types.Camera)
|
||||
if c.type == "orthographic" then
|
||||
line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 }))
|
||||
line(depth, "float horizontalAperture = " .. fmt((c.xmag or 1) * 20))
|
||||
line(depth, 'token projection = "orthographic"')
|
||||
line(depth, "float verticalAperture = " .. fmt((c.ymag or 1) * 20))
|
||||
return
|
||||
end
|
||||
local vap = 24
|
||||
local yfov = c.yfov or 0.8
|
||||
local focal = vap / (2 * math.tan(yfov / 2))
|
||||
line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 }))
|
||||
line(depth, "float focalLength = " .. fmt(focal))
|
||||
line(depth, "float horizontalAperture = " .. fmt(vap * (c.aspect or 1)))
|
||||
line(depth, 'token projection = "perspective"')
|
||||
line(depth, "float verticalAperture = " .. fmt(vap))
|
||||
end
|
||||
|
||||
local LIGHT_TYPE = { directional = "DistantLight", point = "SphereLight", spot = "SphereLight" }
|
||||
local function lightBody(depth: number, l: Types.Light)
|
||||
local c = l.color or { 1, 1, 1 }
|
||||
line(depth, "color3f inputs:color = " .. tuple({ c[1] or 1, c[2] or 1, c[3] or 1 }))
|
||||
line(depth, "float inputs:intensity = " .. fmt(l.intensity or 1))
|
||||
if l.type ~= "directional" then
|
||||
line(depth, "float inputs:radius = 0")
|
||||
end
|
||||
if l.type == "spot" then
|
||||
local outer = l.outerCone or math.pi / 4
|
||||
line(depth, "float inputs:shaping:cone:angle = " .. fmt(outer * RAD))
|
||||
line(depth, "float inputs:shaping:cone:softness = " .. fmt(if outer > 0 then 1 - (l.innerCone or 0) / outer else 0))
|
||||
end
|
||||
if l.type ~= "directional" then
|
||||
line(depth, "bool treatAsPoint = 1")
|
||||
end
|
||||
end
|
||||
local function lightHead(l: Types.Light): string
|
||||
return if l.type == "spot" then ' (\n%s prepend apiSchemas = ["ShapingAPI"]\n%s)' else ""
|
||||
end
|
||||
|
||||
local visited: { [number]: boolean } = {}
|
||||
local function writeNode(depth: number, ni: number, path: string, names: (string?, string) -> string, isRoot: boolean)
|
||||
local n = nodes[ni]
|
||||
if not n or visited[ni] then
|
||||
return
|
||||
end
|
||||
visited[ni] = true
|
||||
local name = if isRoot and not wrap then rootName else names(n.name, "node_" .. ni)
|
||||
local myPath = path .. "/" .. name
|
||||
local mesh = n.mesh and scene.meshes[n.mesh]
|
||||
local merged = mesh and merge(mesh, notes)
|
||||
local cam = n.camera and scene.cameras[n.camera]
|
||||
local lig = n.light and scene.lights[n.light]
|
||||
local kind = "Xform"
|
||||
local head = ""
|
||||
local pad = string.rep(" ", depth)
|
||||
if merged then
|
||||
kind = "Mesh"
|
||||
if #merged.subsets == 1 and merged.subsets[1].material and matPath[merged.subsets[1].material :: number] then
|
||||
head = ' (\n' .. pad .. ' prepend apiSchemas = ["MaterialBindingAPI"]\n' .. pad .. ")"
|
||||
end
|
||||
elseif cam and not lig then
|
||||
kind = "Camera"
|
||||
elseif lig and not cam then
|
||||
kind = LIGHT_TYPE[lig.type] or "SphereLight"
|
||||
local h = lightHead(lig)
|
||||
head = if h ~= "" then string.format(h, pad, pad) else ""
|
||||
end
|
||||
if n.skin then
|
||||
notes.skins = (notes.skins or 0) + 0
|
||||
end
|
||||
table.insert(out, "")
|
||||
line(depth, "def " .. kind .. " " .. quote(name) .. head)
|
||||
line(depth, "{")
|
||||
xform(depth + 1, ni, n)
|
||||
if kind == "Mesh" then
|
||||
meshBody(depth + 1, merged :: Merged, myPath)
|
||||
elseif kind == "Camera" then
|
||||
cameraBody(depth + 1, cam :: Types.Camera)
|
||||
elseif kind ~= "Xform" then
|
||||
lightBody(depth + 1, lig :: Types.Light)
|
||||
end
|
||||
local childNames = namer()
|
||||
-- a camera / light that did not take the node's prim
|
||||
if cam and kind ~= "Camera" then
|
||||
table.insert(out, "")
|
||||
line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera")))
|
||||
line(depth + 1, "{")
|
||||
cameraBody(depth + 2, cam)
|
||||
line(depth + 1, "}")
|
||||
end
|
||||
if lig and kind == "Xform" or (lig and kind == "Mesh") or (lig and kind == "Camera") then
|
||||
local l = lig :: Types.Light
|
||||
local h = lightHead(l)
|
||||
local pad2 = string.rep(" ", depth + 1)
|
||||
table.insert(out, "")
|
||||
line(depth + 1, "def " .. (LIGHT_TYPE[l.type] or "SphereLight") .. " " .. quote(childNames(l.name, "light")) .. (if h ~= "" then string.format(h, pad2, pad2) else ""))
|
||||
line(depth + 1, "{")
|
||||
lightBody(depth + 2, l)
|
||||
line(depth + 1, "}")
|
||||
end
|
||||
if isRoot and not wrap then
|
||||
Write._looks(out, depth + 1, scene, matPath, texFile, line)
|
||||
end
|
||||
for _, c in n.children or {} do
|
||||
writeNode(depth + 1, c, myPath, childNames, false)
|
||||
end
|
||||
line(depth, "}")
|
||||
end
|
||||
|
||||
if wrap then
|
||||
line(0, "def Xform " .. quote(rootName))
|
||||
line(0, "{")
|
||||
Write._looks(out, 1, scene, matPath, texFile, line)
|
||||
local names = namer()
|
||||
names("Looks", "Looks")
|
||||
for _, r in roots do
|
||||
writeNode(1, r, "/" .. rootName, names, false)
|
||||
end
|
||||
line(0, "}")
|
||||
else
|
||||
writeNode(0, roots[1], "", rootNames, true)
|
||||
end
|
||||
table.insert(out, "")
|
||||
return table.concat(out, "\n"), notes
|
||||
end
|
||||
|
||||
-- the Looks scope: materials as UsdPreviewSurface networks
|
||||
function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPath: { [number]: string }, texFile: { [number]: string }, line: (number, string) -> ())
|
||||
local mats = scene.materials or {}
|
||||
if #mats == 0 then
|
||||
return
|
||||
end
|
||||
table.insert(out, "")
|
||||
line(depth, 'def Scope "Looks"')
|
||||
line(depth, "{")
|
||||
for i, mat in mats do
|
||||
local path = matPath[i]
|
||||
local mname = string.match(path, "([^/]+)$") :: string
|
||||
table.insert(out, "")
|
||||
line(depth + 1, "def Material " .. quote(mname))
|
||||
line(depth + 1, "{")
|
||||
local d = depth + 2
|
||||
line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>")
|
||||
-- texture nodes (one per distinct ref)
|
||||
type TexNode = { name: string, ref: Types.TextureRef, color: boolean }
|
||||
local texNodes: { TexNode } = {}
|
||||
local function texNode(ref: Types.TextureRef?, color: boolean): string?
|
||||
if not ref or not texFile[ref.texture] then
|
||||
return nil
|
||||
end
|
||||
for _, tn in texNodes do
|
||||
if tn.ref == ref or (tn.ref.texture == ref.texture and (tn.ref.texCoord or 0) == (ref.texCoord or 0) and tn.ref.transform == nil and ref.transform == nil and tn.color == color) then
|
||||
return tn.name
|
||||
end
|
||||
end
|
||||
local name = "Texture_" .. (#texNodes + 1)
|
||||
table.insert(texNodes, { name = name, ref = ref, color = color })
|
||||
return name
|
||||
end
|
||||
local bc = mat.baseColor or { 1, 1, 1, 1 }
|
||||
local blend = mat.alphaMode == "blend" or mat.alphaMode == "mask"
|
||||
local diffuseTex = texNode(mat.baseColorTexture, true)
|
||||
local mrTex = texNode(mat.metallicRoughnessTexture, false)
|
||||
local emTex = texNode(mat.emissiveTexture, true)
|
||||
local nTex = texNode(mat.normalTexture, false)
|
||||
local oTex = texNode(mat.occlusionTexture, false)
|
||||
table.insert(out, "")
|
||||
line(d, 'def Shader "PreviewSurface"')
|
||||
line(d, "{")
|
||||
local e = d + 1
|
||||
line(e, 'uniform token info:id = "UsdPreviewSurface"')
|
||||
if diffuseTex then
|
||||
line(e, "color3f inputs:diffuseColor.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:rgb>")
|
||||
else
|
||||
line(e, "color3f inputs:diffuseColor = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1 }))
|
||||
end
|
||||
local em = mat.emissive or { 0, 0, 0 }
|
||||
if emTex then
|
||||
line(e, "color3f inputs:emissiveColor.connect = <" .. path .. "/" .. emTex .. ".outputs:rgb>")
|
||||
elseif (em[1] or 0) ~= 0 or (em[2] or 0) ~= 0 or (em[3] or 0) ~= 0 then
|
||||
line(e, "color3f inputs:emissiveColor = " .. tuple({ em[1] or 0, em[2] or 0, em[3] or 0 }))
|
||||
end
|
||||
local ext = mat.extensions or {}
|
||||
if ext.KHR_materials_clearcoat and type(ext.KHR_materials_clearcoat.clearcoatFactor) == "number" then
|
||||
line(e, "float inputs:clearcoat = " .. fmt(ext.KHR_materials_clearcoat.clearcoatFactor))
|
||||
line(e, "float inputs:clearcoatRoughness = " .. fmt(tonumber(ext.KHR_materials_clearcoat.clearcoatRoughnessFactor) or 0))
|
||||
end
|
||||
if ext.KHR_materials_ior and type(ext.KHR_materials_ior.ior) == "number" then
|
||||
line(e, "float inputs:ior = " .. fmt(ext.KHR_materials_ior.ior))
|
||||
end
|
||||
if mrTex then
|
||||
line(e, "float inputs:metallic.connect = <" .. path .. "/" .. mrTex .. ".outputs:b>")
|
||||
else
|
||||
line(e, "float inputs:metallic = " .. fmt(mat.metallic or 0))
|
||||
end
|
||||
if nTex then
|
||||
line(e, "normal3f inputs:normal.connect = <" .. path .. "/" .. nTex .. ".outputs:rgb>")
|
||||
end
|
||||
if oTex then
|
||||
line(e, "float inputs:occlusion.connect = <" .. path .. "/" .. oTex .. ".outputs:r>")
|
||||
end
|
||||
if blend and diffuseTex then
|
||||
line(e, "float inputs:opacity.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:a>")
|
||||
elseif blend then
|
||||
line(e, "float inputs:opacity = " .. fmt(bc[4] or 1))
|
||||
end
|
||||
if mat.alphaMode == "mask" then
|
||||
line(e, "float inputs:opacityThreshold = " .. fmt(mat.alphaCutoff or 0.5))
|
||||
end
|
||||
if mrTex then
|
||||
line(e, "float inputs:roughness.connect = <" .. path .. "/" .. mrTex .. ".outputs:g>")
|
||||
else
|
||||
line(e, "float inputs:roughness = " .. fmt(mat.roughness or 1))
|
||||
end
|
||||
line(e, "token outputs:surface")
|
||||
line(d, "}")
|
||||
-- primvar readers per texCoord set, transforms, textures
|
||||
local readers: { [number]: boolean } = {}
|
||||
for _, tn in texNodes do
|
||||
local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0
|
||||
if not readers[tc] then
|
||||
readers[tc] = true
|
||||
table.insert(out, "")
|
||||
line(d, 'def Shader "PrimvarReader_' .. tc .. '"')
|
||||
line(d, "{")
|
||||
line(d + 1, 'uniform token info:id = "UsdPrimvarReader_float2"')
|
||||
line(d + 1, "string inputs:varname = " .. quote(if tc == 0 then "st" else "st" .. tc))
|
||||
line(d + 1, "float2 outputs:result")
|
||||
line(d, "}")
|
||||
end
|
||||
end
|
||||
for _, tn in texNodes do
|
||||
local ref = tn.ref
|
||||
local tc = (ref.transform and ref.transform.texCoord) or ref.texCoord or 0
|
||||
local stSource = path .. "/PrimvarReader_" .. tc .. ".outputs:result"
|
||||
if ref.transform then
|
||||
local tr = ref.transform :: any
|
||||
table.insert(out, "")
|
||||
line(d, 'def Shader "' .. tn.name .. '_Transform"')
|
||||
line(d, "{")
|
||||
line(d + 1, 'uniform token info:id = "UsdTransform2d"')
|
||||
line(d + 1, "float2 inputs:in.connect = <" .. stSource .. ">")
|
||||
if tr.rotation then
|
||||
line(d + 1, "float inputs:rotation = " .. fmt(tr.rotation * RAD))
|
||||
end
|
||||
if tr.scale then
|
||||
line(d + 1, "float2 inputs:scale = " .. tuple({ tr.scale[1] or 1, tr.scale[2] or 1 }))
|
||||
end
|
||||
if tr.offset then
|
||||
line(d + 1, "float2 inputs:translation = " .. tuple({ tr.offset[1] or 0, tr.offset[2] or 0 }))
|
||||
end
|
||||
line(d + 1, "float2 outputs:result")
|
||||
line(d, "}")
|
||||
stSource = path .. "/" .. tn.name .. "_Transform.outputs:result"
|
||||
end
|
||||
local tex = scene.textures[ref.texture]
|
||||
local sampler = tex and tex.sampler or {}
|
||||
table.insert(out, "")
|
||||
line(d, 'def Shader "' .. tn.name .. '"')
|
||||
line(d, "{")
|
||||
line(d + 1, 'uniform token info:id = "UsdUVTexture"')
|
||||
line(d + 1, "asset inputs:file = " .. asset(texFile[ref.texture]))
|
||||
if tn.ref == mat.baseColorTexture and ((bc[1] or 1) ~= 1 or (bc[2] or 1) ~= 1 or (bc[3] or 1) ~= 1 or (bc[4] or 1) ~= 1) then
|
||||
line(d + 1, "float4 inputs:scale = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1, bc[4] or 1 }))
|
||||
end
|
||||
if tn.ref == mat.normalTexture then
|
||||
line(d + 1, "float4 inputs:bias = (-1, -1, -1, 0)")
|
||||
line(d + 1, "float4 inputs:scale = (2, 2, 2, 1)")
|
||||
end
|
||||
line(d + 1, 'token inputs:sourceColorSpace = "' .. (if tn.color then "sRGB" else "raw") .. '"')
|
||||
line(d + 1, "float2 inputs:st.connect = <" .. stSource .. ">")
|
||||
line(d + 1, 'token inputs:wrapS = "' .. (sampler.wrapS or "repeat") .. '"')
|
||||
line(d + 1, 'token inputs:wrapT = "' .. (sampler.wrapT or "repeat") .. '"')
|
||||
line(d + 1, "float outputs:a")
|
||||
line(d + 1, "float outputs:b")
|
||||
line(d + 1, "float outputs:g")
|
||||
line(d + 1, "float outputs:r")
|
||||
line(d + 1, "float3 outputs:rgb")
|
||||
line(d, "}")
|
||||
end
|
||||
line(depth + 1, "}")
|
||||
end
|
||||
line(depth, "}")
|
||||
end
|
||||
|
||||
return Write
|
||||
@@ -0,0 +1,221 @@
|
||||
--!strict
|
||||
-- model/usda: USD ASCII layers (.usda, .usd in text form) and USDZ packages holding them. New code, from the Sdf text
|
||||
-- format and the UsdGeom / UsdShade / UsdLux schema documentation (OpenUSD 26.x); checked against OpenUSD's own
|
||||
-- reader / writer (pxr) and Blender's USD exporter.
|
||||
-- Reads: stage metadata (upAxis -> meta.up, metersPerUnit -> meta.unit, defaultPrim, timeCodesPerSecond, start /
|
||||
-- endTimeCode), the prim tree (def / over; class skipped; selected variants merged), xform op stacks (translate, scale,
|
||||
-- rotateX/Y/Z, rotateXYZ ... rotateZYX, orient, transform, !invert!, !resetXformStack!) with time samples -> one
|
||||
-- animation of TRS channels, Mesh (faceVertexCounts / Indices, holes, leftHanded orientation, normals, every
|
||||
-- texCoord2f primvar -> TEXCOORD_n with st first, displayColor / displayOpacity, all interpolations, :indices,
|
||||
-- GeomSubsets -> one primitive each), UsdPreviewSurface materials with UsdUVTexture / UsdPrimvarReader_float2 /
|
||||
-- UsdTransform2d, material:binding (inherited, per subset), Camera, DistantLight / SphereLight (+ ShapingAPI cone ->
|
||||
-- spot) / RectLight / DiskLight (-> spot lights over a hemisphere). Textures stay encoded: bytes from opts.files /
|
||||
-- opts.resolve (or the USDZ package) + mime, else just the uri (F.model.loadTextures decodes them).
|
||||
-- Writes .usda (see model/usda/Write): Xform / Mesh / GeomSubset / Material / Shader / Camera / lights, time samples.
|
||||
-- Not supported: USDC binary crate files (.usdc, and .usd / USDZ holding one: UNSUPPORTED), composition arcs
|
||||
-- (references, payloads, inherits, specializes, subLayers: ignored and listed in meta.source.unsupported), UsdSkel
|
||||
-- skinning, blend shapes, curves / points / NURBS prims, point instancers, MaterialX shading networks, writing USDZ.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Zip = require("@formats/containers/Zip")
|
||||
local Parse = require("@formats/model/usda/Parse")
|
||||
local Build = require("@formats/model/usda/Build")
|
||||
local Write = require("@formats/model/usda/Write")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Usda = {
|
||||
name = "usda",
|
||||
category = "model",
|
||||
extensions = { "usda", "usd", "usdz" },
|
||||
mime = { "model/vnd.usda", "model/vnd.usdz+zip" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" },
|
||||
caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
triangulate: boolean?, -- fan-triangulate faces (default true); false keeps "polygons" primitives
|
||||
flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's top-left origin)
|
||||
resolve: ((uri: string) -> any)?, -- texture files next to the layer (the api sets it for paths)
|
||||
files: { [string]: any }?, -- or: the files by asset path
|
||||
maxVertices: number?, -- refuse meshes with more points / face corners (default 2^25)
|
||||
maxBytes: number?, -- refuse numeric arrays over this many bytes (default 2^30)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
files: { [string]: any }?, -- receives embedded texture bytes as <name>_<n>.<ext>
|
||||
name: string?, -- the destination's file name (names the texture files)
|
||||
format: string?, -- "usdz" -> UNSUPPORTED (set by the api from the destination's extension)
|
||||
upAxis: string?, -- "Y" / "Z" (default: from scene.meta.up)
|
||||
metersPerUnit: number?, -- default scene.meta.unit or 1
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local function isUsdz(r: Bytes.Reader): boolean
|
||||
if r:peek(4) ~= "PK\3\4" then
|
||||
return false
|
||||
end
|
||||
-- the first entry is the root layer
|
||||
local lo, hi = r:peekU8(26), r:peekU8(27)
|
||||
if lo < 0 or hi < 0 then
|
||||
return false
|
||||
end
|
||||
local nameLen = lo + hi * 256
|
||||
local name = string.lower(r:peek(30 + nameLen))
|
||||
name = string.sub(name, 31)
|
||||
return string.find(name, "%.usd[ac]?$") ~= nil
|
||||
end
|
||||
|
||||
function Usda.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(8)
|
||||
if string.sub(head, 1, 5) == "#usda" or string.sub(head, 1, 8) == "\239\187\191#usda" then
|
||||
return 1
|
||||
end
|
||||
if head == "PXR-USDC" then
|
||||
return 0.9 -- recognised so the error says USDC is not supported
|
||||
end
|
||||
if isUsdz(r) then
|
||||
return 0.95
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function fetcher(opts: DecodeOptions?, package: any): (uri: string) -> buffer?
|
||||
return function(uri: string): buffer?
|
||||
local candidates = { uri }
|
||||
local slashed = string.gsub(uri, "\\", "/")
|
||||
local stripped = string.gsub(slashed, "^%./", "")
|
||||
if slashed ~= uri then
|
||||
table.insert(candidates, slashed)
|
||||
end
|
||||
if stripped ~= slashed then
|
||||
table.insert(candidates, stripped)
|
||||
end
|
||||
-- packaged assets: "model.usdz[textures/a.png]"
|
||||
local inner = string.match(uri, "%[(.+)%]$")
|
||||
if inner then
|
||||
table.insert(candidates, inner)
|
||||
end
|
||||
for _, u in candidates do
|
||||
if package then
|
||||
local data = package:read(u)
|
||||
if data then
|
||||
return data
|
||||
end
|
||||
end
|
||||
local v: any = nil
|
||||
if opts and type(opts.files) == "table" then
|
||||
v = opts.files[u]
|
||||
end
|
||||
if v == nil and opts and type(opts.resolve) == "function" then
|
||||
local ok, res = pcall(opts.resolve, u)
|
||||
v = if ok then res else nil
|
||||
end
|
||||
if type(v) == "string" then
|
||||
return buffer.fromstring(v)
|
||||
elseif type(v) == "buffer" then
|
||||
return v
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
end
|
||||
|
||||
function Usda.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local head = r:peek(8)
|
||||
if head == "PXR-USDC" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "USDC binary crate files (convert with usdcat to .usda)")
|
||||
end
|
||||
local text: string
|
||||
local package: any = nil
|
||||
local usdz = false
|
||||
if string.sub(head, 1, 4) == "PK\3\4" then
|
||||
local archive, zerr = Zip.open(r)
|
||||
if not archive then
|
||||
return nil, zerr or Err.new(Err.CORRUPT, "bad USDZ package")
|
||||
end
|
||||
local entries = archive:list()
|
||||
local root = nil
|
||||
for _, e in entries do
|
||||
if not e.dir and string.find(string.lower(e.name), "%.usd[ac]?$") then
|
||||
root = e
|
||||
break
|
||||
end
|
||||
end
|
||||
if not root then
|
||||
return nil, Err.new(Err.CORRUPT, "the USDZ package holds no USD layer")
|
||||
end
|
||||
local data, rerr = archive:read(root)
|
||||
if not data then
|
||||
return nil, rerr
|
||||
end
|
||||
if buffer.len(data) >= 8 and buffer.readstring(data, 0, 8) == "PXR-USDC" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "USDZ holding a USDC binary crate layer")
|
||||
end
|
||||
text = buffer.tostring(data)
|
||||
package = archive
|
||||
usdz = true
|
||||
else
|
||||
text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
end
|
||||
if not Parse.version(text) then
|
||||
return nil, Err.new(Err.CORRUPT, "no #usda header")
|
||||
end
|
||||
local layer, msg, at = Parse.layer(text, opts and opts.maxBytes)
|
||||
if not layer then
|
||||
if msg == "array over the size limit" then
|
||||
return nil, Err.new(Err.LIMIT, msg :: string, at)
|
||||
end
|
||||
local code = if at and at >= #text - 1 then Err.TRUNCATED else Err.CORRUPT
|
||||
if msg and string.find(msg, "^unterminated") then
|
||||
code = Err.TRUNCATED
|
||||
end
|
||||
return nil, Err.new(code, msg or "parse error", if usdz then nil else at)
|
||||
end
|
||||
local scene, err = Build.scene(layer, {
|
||||
triangulate = opts and opts.triangulate,
|
||||
flipV = opts and opts.flipV,
|
||||
maxVertices = opts and opts.maxVertices,
|
||||
fetch = fetcher(opts, package),
|
||||
})
|
||||
if not scene then
|
||||
if err == "LIMIT" then
|
||||
return nil, Err.new(Err.LIMIT, "a mesh over maxVertices")
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, err or "bad scene")
|
||||
end
|
||||
local src: any = scene.meta.source
|
||||
src.version = Parse.version(text)
|
||||
src.usdz = usdz or nil
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Usda.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(scene) ~= "table" or scene.kind ~= "scene" then
|
||||
return nil, Err.new(Err.ARG, "needs a Scene")
|
||||
end
|
||||
if opts and opts.format == "usdz" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "writing USDZ; write .usda")
|
||||
end
|
||||
local ok, text = pcall(Write.text, scene, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.ARG, "bad scene: " .. tostring(text))
|
||||
end
|
||||
return buffer.fromstring(text :: any), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- parse(text) -> the raw layer (prim specs, properties, metadata) | nil, Err: for prims the Scene does not cover
|
||||
function Usda.parse(text: string): (Parse.Layer?, Err.Err?)
|
||||
local layer, msg, at = Parse.layer(text)
|
||||
if not layer then
|
||||
return nil, Err.new(Err.CORRUPT, msg or "parse error", at)
|
||||
end
|
||||
return layer, nil
|
||||
end
|
||||
|
||||
return Usda
|
||||
@@ -0,0 +1,392 @@
|
||||
-- cad/step tests: STEP files written by OCCT (solids modelled in gmsh's OpenCASCADE kernel) and public sample files,
|
||||
-- against an independent Python Part 21 census (instances, count per type); our writer's output read back by OCCT
|
||||
-- (solids, volume, faces, area, bounding box equal to the originals); parse -> write -> parse equality; every
|
||||
-- parameter kind and string escape, complex instances, edition 3 sections, comments; the api (F.load / F.save /
|
||||
-- F.cad.*); the B-rep plug-in path through brep-luau (luau CLI only: the alias in tests/gen/.luaurc) against OCCT's
|
||||
-- volumes and bounds, and a custom plug-in table; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/step.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Step = require("@formats/cad/step")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Cases = require("@tests/gen/step_cases")
|
||||
|
||||
local t = T.suite("step")
|
||||
|
||||
local function decode(s: string, opts: any?): (any, any)
|
||||
return Step.decode(Bytes.reader(buffer.fromstring(s)), opts)
|
||||
end
|
||||
local function encode(cad: any, opts: any?): string
|
||||
local b, err = Step.encode(cad, opts)
|
||||
t:check(b, "encode: " .. tostring(err))
|
||||
return if b then buffer.tostring(b) else ""
|
||||
end
|
||||
local function near(a: number, b: number, rel: number): boolean
|
||||
return math.abs(a - b) <= rel * math.max(1, math.abs(a), math.abs(b))
|
||||
end
|
||||
|
||||
-- 1. contract
|
||||
t:eq(Step.name, "step", "name")
|
||||
t:eq(Step.category, "cad", "category")
|
||||
t:check(Step.caps.decode and Step.caps.encode and table.find(Step.extensions, "stp"), "contract")
|
||||
|
||||
-- deep equality of two decoded values (buffers, the real marks of lists included)
|
||||
local function same(a: any, b: any, path: string, depth: number?): (boolean, string)
|
||||
local d = depth or 0
|
||||
if type(a) ~= "table" or type(b) ~= "table" then
|
||||
return a == b, path
|
||||
end
|
||||
if a == b then
|
||||
return true, path
|
||||
end
|
||||
if d > 60 then
|
||||
return false, path .. " (too deep)"
|
||||
end
|
||||
for k, v in a do
|
||||
local ok, where = same(v, b[k], path .. "." .. tostring(k), d + 1)
|
||||
if not ok then
|
||||
return false, where
|
||||
end
|
||||
end
|
||||
for k in b do
|
||||
if a[k] == nil then
|
||||
return false, path .. "." .. tostring(k) .. " (extra)"
|
||||
end
|
||||
end
|
||||
local ma, mb = getmetatable(a), getmetatable(b)
|
||||
local ra = ma and ma.__reals or {}
|
||||
local rb = mb and mb.__reals or {}
|
||||
for k in ra do
|
||||
if not rb[k] then
|
||||
return false, path .. "[" .. tostring(k) .. "] real mark"
|
||||
end
|
||||
end
|
||||
for k in rb do
|
||||
if not ra[k] then
|
||||
return false, path .. "[" .. tostring(k) .. "] real mark (extra)"
|
||||
end
|
||||
end
|
||||
return true, path
|
||||
end
|
||||
|
||||
-- 2. fixtures: census, round trips; OCCT read our output like the original
|
||||
local decoded = {}
|
||||
local samples = {}
|
||||
local t0 = T.clock()
|
||||
local bytes = 0
|
||||
for i, c in Cases do
|
||||
local cad, err = decode(c.data)
|
||||
t:check(cad, c.name .. ": decode: " .. tostring(err))
|
||||
decoded[i] = cad
|
||||
bytes += #c.data
|
||||
t:eq(cad.meta.count, c.census.count, c.name .. ": instances (census)")
|
||||
local types = {}
|
||||
for _, e in cad.entities do
|
||||
types[e.type] = (types[e.type] or 0) + 1
|
||||
end
|
||||
for ty, n in c.census.types do
|
||||
t:eq(types[ty], n, c.name .. ": " .. ty .. " count")
|
||||
end
|
||||
for ty in types do
|
||||
t:check(c.census.types[ty], c.name .. ": no extra type " .. ty)
|
||||
end
|
||||
local text = encode(cad)
|
||||
local again = decode(text)
|
||||
t:check(again, c.name .. ": our output decodes")
|
||||
local ok, where = same(cad.entities, again.entities, "entities")
|
||||
t:check(ok, c.name .. ": round trip differs at " .. where)
|
||||
t:eq(encode(again), text, c.name .. ": write is stable")
|
||||
t:check(same(cad.header, again.header, "header"), c.name .. ": header round trip")
|
||||
if c.occt and not c.occt.failed then
|
||||
t:check(c.ours and not c.ours.failed, c.name .. ": OCCT reads our output")
|
||||
t:eq(c.ours.solids, c.occt.solids, c.name .. ": OCCT solids of our output")
|
||||
t:eq(c.ours.faces, c.occt.faces, c.name .. ": OCCT faces of our output")
|
||||
t:check(near(c.ours.volume, c.occt.volume, 1e-9), c.name .. ": OCCT volume of our output")
|
||||
t:check(near(c.ours.area, c.occt.area, 1e-9), c.name .. ": OCCT area of our output")
|
||||
end
|
||||
if #samples < 4 and #c.data < 40000 then
|
||||
table.insert(samples, buffer.fromstring(c.data))
|
||||
end
|
||||
end
|
||||
local dt = T.clock() - t0
|
||||
t:note("%d files (%.1f MB): census, OCCT read-back, round trips (%.2f s)", #Cases, bytes / 1e6, dt)
|
||||
|
||||
-- 3. every parameter kind, escapes, complex instances, sections, comments
|
||||
local CRAFT = [[
|
||||
ISO-10303-21; /* a comment */
|
||||
HEADER;
|
||||
FILE_DESCRIPTION(('test'),'2;1');
|
||||
FILE_NAME('craft.stp','2024-01-01T00:00:00',('A \X2\00C9\X0\crivain'),(''),'','','');
|
||||
FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));
|
||||
ENDSEC;
|
||||
DATA;
|
||||
#1=CARTESIAN_POINT('',(0.,1.5,-2.E-3));
|
||||
#2 = DIRECTION ( 'd' , ( 1. , 0. , 0. ) ) ;
|
||||
#3=FOO('It''s','back\\slash','\S\i','\X\E9t\X\E9','\X2\03B103B2\X0\ ok','\X4\0001F600\X0\',.T.,.UNSPECIFIED.,$,*,#1,
|
||||
"0FF",LENGTH_MEASURE(2.),POSITIVE_LENGTH_MEASURE(3.5),(1,2,(3,4.)),(),-7,+8,1.E2);
|
||||
#10=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT((#11))REPRESENTATION_CONTEXT('c','3D'));
|
||||
#11=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));
|
||||
/* comment between instances */
|
||||
#12=!USER_DEFINED(1);
|
||||
ENDSEC;
|
||||
END-ISO-10303-21;
|
||||
]]
|
||||
local cad, err = decode(CRAFT)
|
||||
t:check(cad, "craft: " .. tostring(err))
|
||||
t:eq(cad.schema, "AP214", "craft: schema")
|
||||
t:eq(cad.meta.count, 6, "craft: count")
|
||||
t:eq(cad.header.FILE_NAME[3][1], "A Écrivain", "craft: header \\X2\\")
|
||||
local p = cad.entities[1]
|
||||
t:eq(p.type, "CARTESIAN_POINT", "craft: type")
|
||||
t:eq(p.args[2][3], -2e-3, "craft: real")
|
||||
t:check(getmetatable(p.args[2]).__reals[1] and getmetatable(p.args[2]).__reals[2] == nil, "craft: integral real marked")
|
||||
t:eq(cad.entities[2].args[1], "d", "craft: spaced instance")
|
||||
local a = cad.entities[3].args
|
||||
t:eq(a[1], "It's", "craft: ''")
|
||||
t:eq(a[2], "back\\slash", "craft: \\\\")
|
||||
t:eq(a[3], "é", "craft: \\S\\")
|
||||
t:eq(a[4], "été", "craft: \\X\\")
|
||||
t:eq(a[5], "αβ ok", "craft: \\X2\\")
|
||||
t:eq(a[6], "😀", "craft: \\X4\\")
|
||||
t:eq(a[7].enum, "T", "craft: boolean")
|
||||
t:eq(a[8].enum, "UNSPECIFIED", "craft: enum")
|
||||
t:eq(a[9], Step.NULL, "craft: $")
|
||||
t:eq(a[10], Step.DERIVED, "craft: *")
|
||||
t:eq(a[11].ref, 1, "craft: ref")
|
||||
t:eq(Step.get(cad, a[11]), p, "craft: get(ref)")
|
||||
t:eq(a[12].binary, "0FF", "craft: binary")
|
||||
t:eq(a[13].typed, "LENGTH_MEASURE", "craft: typed")
|
||||
t:eq(a[13].value, 2, "craft: typed value")
|
||||
t:eq(a[14].value, 3.5, "craft: typed real")
|
||||
t:eq(a[15][3][2], 4, "craft: nested list")
|
||||
t:eq(#a[16], 0, "craft: empty list")
|
||||
t:eq(a[17], -7, "craft: negative integer")
|
||||
t:eq(a[18], 8, "craft: +integer")
|
||||
t:eq(a[19], 100, "craft: 1.E2")
|
||||
local cx = cad.entities[10]
|
||||
t:eq(cx.type, "COMPLEX", "craft: complex")
|
||||
t:eq(#cx.parts, 3, "craft: complex parts")
|
||||
t:eq(Step.part(cx, "GEOMETRIC_REPRESENTATION_CONTEXT")[1], 3, "craft: part()")
|
||||
t:eq(Step.part(cad.entities[11], "SI_UNIT")[2].enum, "METRE", "craft: SI_UNIT part")
|
||||
t:eq(cad.entities[12].type, "!USER_DEFINED", "craft: user-defined entity")
|
||||
t:eq(#Step.byType(cad, "SI_UNIT"), 1, "craft: byType through complex parts")
|
||||
local text = encode(cad)
|
||||
t:check(string.find(text, "#3=FOO('It''s','back\\\\slash','\\X2\\00E9\\X0\\'", 1, true), "craft: strings re-escaped")
|
||||
t:check(string.find(text, "'\\X4\\0001F600\\X0\\'", 1, true), "craft: \\X4\\ written")
|
||||
t:check(string.find(text, "CARTESIAN_POINT('',(0.,1.5,-0.002))", 1, true), "craft: reals written")
|
||||
t:check(string.find(text, "LENGTH_MEASURE(2.)", 1, true), "craft: typed integral real")
|
||||
t:check(string.find(text, "(1,2,(3,4.)),(),-7,8,100.);", 1, true), "craft: integers and lists")
|
||||
t:check(string.find(text, "#10=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT((#11))", 1, true), "craft: complex written")
|
||||
local back = decode(text)
|
||||
t:check(back and same(cad.entities, back.entities, "entities"), "craft: round trip")
|
||||
t:eq(back.header.FILE_NAME[3][1], "A Écrivain", "craft: header round trip")
|
||||
|
||||
-- edition 3: named DATA sections, ANCHOR section kept raw
|
||||
local ED3 = [[ISO-10303-21;
|
||||
HEADER;
|
||||
FILE_DESCRIPTION((''),'3;1');
|
||||
FILE_NAME('','',(''),(''),'','','');
|
||||
FILE_SCHEMA(('CONFIG_CONTROL_DESIGN','OTHER_SCHEMA'));
|
||||
ENDSEC;
|
||||
ANCHOR;
|
||||
<http://example.org/a> = #1;
|
||||
ENDSEC;
|
||||
DATA('first',('CONFIG_CONTROL_DESIGN'));
|
||||
#1=A(1);
|
||||
ENDSEC;
|
||||
DATA('second',('OTHER_SCHEMA'));
|
||||
#2=B('x;y',#1);
|
||||
ENDSEC;
|
||||
END-ISO-10303-21;
|
||||
]]
|
||||
local e3, e3err = decode(ED3)
|
||||
t:check(e3, "ed3: " .. tostring(e3err))
|
||||
t:eq(e3.schema, "AP203", "ed3: schema")
|
||||
t:eq(#e3.meta.source.sections, 2, "ed3: sections")
|
||||
t:eq(e3.entities[2].section, 2, "ed3: entity section")
|
||||
t:eq(e3.entities[2].args[1], "x;y", "ed3: ; inside a string")
|
||||
t:eq(e3.meta.source.extra[1].name, "ANCHOR", "ed3: anchor kept")
|
||||
local e3text = encode(e3)
|
||||
t:check(string.find(e3text, "DATA('second',('OTHER_SCHEMA'));\n#2=B('x;y',#1);", 1, true), "ed3: sections written")
|
||||
t:check(string.find(e3text, "ANCHOR;\n<http://example.org/a> = #1;\nENDSEC;", 1, true), "ed3: anchor written")
|
||||
local e3b = decode(e3text)
|
||||
t:check(e3b and same(e3.entities, e3b.entities, "e"), "ed3: round trip")
|
||||
|
||||
-- 4. building a file
|
||||
local new = Step.new("AP242")
|
||||
local pt = Step.add(new, "cartesian_point", { "origin", Step.real({ 0, 0, 1.25 }, 1) })
|
||||
Step.add(new, "VERTEX_POINT", { "", { ref = pt } })
|
||||
local ntext = encode(new, { name = "built.stp" })
|
||||
t:check(string.find(ntext, "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));", 1, true), "new: schema")
|
||||
t:check(string.find(ntext, "#1=CARTESIAN_POINT('origin',(0.,0,1.25));\n#2=VERTEX_POINT('',#1);", 1, true), "new: instances")
|
||||
t:eq(decode(ntext).schema, "AP242", "new: decodes")
|
||||
local _, bad = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "X", args = { 0 / 0 } } }, header = {}, meta = {} })
|
||||
t:eq(bad and bad.code, Err.ARG, "encode: nan -> ARG")
|
||||
local _, bad2 = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "bad type", args = {} } }, header = {}, meta = {} })
|
||||
t:eq(bad2 and bad2.code, Err.ARG, "encode: bad type -> ARG")
|
||||
local cyc = {}
|
||||
cyc[1] = cyc
|
||||
local _, bad3 = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "X", args = cyc } }, header = {}, meta = {} })
|
||||
t:eq(bad3 and bad3.code, Err.ARG, "encode: cycle -> ARG")
|
||||
local _, bad4 = Step.encode({ kind = "image" } :: any)
|
||||
t:eq(bad4 and bad4.code, Err.ARG, "encode: not a Cad")
|
||||
|
||||
-- 5. errors and sniff
|
||||
local function code(s: string, opts: any?): string?
|
||||
local v, e = decode(s, opts)
|
||||
return if v then nil else e.code
|
||||
end
|
||||
t:eq(code("hello"), Err.CORRUPT, "no magic")
|
||||
t:eq(code(string.sub(CRAFT, 1, 400)), Err.TRUNCATED, "truncated")
|
||||
t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A(1,;\nENDSEC;\nEND-ISO-10303-21;"), Err.CORRUPT, "bad list")
|
||||
t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A('x);\nENDSEC;\n"), Err.TRUNCATED, "open string")
|
||||
t:eq(code(CRAFT, { maxEntities = 3 }), Err.LIMIT, "maxEntities")
|
||||
t:eq(code(CRAFT, { maxBytes = 100 }), Err.LIMIT, "maxBytes")
|
||||
t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\n"), Err.TRUNCATED, "no DATA")
|
||||
local deep = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A(" .. string.rep("(", 500) .. string.rep(")", 500) .. ");\nENDSEC;\n"
|
||||
t:eq(code(deep), Err.CORRUPT, "nesting limit")
|
||||
t:eq(Step.sniff(Bytes.reader(buffer.fromstring(CRAFT))), 1, "sniff")
|
||||
t:eq(Step.sniff(Bytes.reader(buffer.fromstring("\239\187\191/* x */ ISO-10303-21;"))), 1, "sniff: BOM + comment")
|
||||
t:eq(Step.sniff(Bytes.reader(buffer.fromstring("ISO-10303-28"))), 0, "sniff: other")
|
||||
|
||||
-- 6. the api
|
||||
local loaded, lerr = F.load(CRAFT)
|
||||
t:check(loaded and loaded.kind == "cad", "F.load: " .. tostring(lerr))
|
||||
t:eq(F.detect(CRAFT), "step", "F.detect")
|
||||
local saved = F.save(loaded)
|
||||
t:check(type(saved) == "buffer" and decode(buffer.tostring(saved)).meta.count == 6, "F.save (source format)")
|
||||
local _, nop = Step.toBodies(loaded)
|
||||
t:eq(nop and nop.code, Err.UNSUPPORTED, "toBodies without a plug-in")
|
||||
local _, nop2 = F.cad.tessellate(loaded)
|
||||
t:eq(nop2 and nop2.code, Err.UNSUPPORTED, "F.cad.tessellate without a plug-in")
|
||||
|
||||
-- 7. the plug-in: a custom interface table
|
||||
local calls = {}
|
||||
local fake = {
|
||||
read = function(text: string, _opts: any): any
|
||||
calls.read = #text
|
||||
return { bodies = { { name = "tri", color = { 1, 0, 0 } } }, stats = { solids = 1 } }
|
||||
end,
|
||||
write = function(bodies: { any }, _opts: any): string
|
||||
calls.write = #bodies
|
||||
return CRAFT
|
||||
end,
|
||||
tessellate = function(_body: any, _opts: any): any
|
||||
return { positions = { { 0, 0, 0 }, { x = 1, y = 0, z = 0 }, { 0, 1, 0 }, { 0, 0, 1 } }, indices = { 1, 3, 2, 1, 2, 4, 1, 4, 3, 2, 3, 4 } }
|
||||
end,
|
||||
}
|
||||
local fb, finfo = Step.toBodies(loaded, { brep = fake })
|
||||
t:check(fb and #fb == 1 and finfo.stats.solids == 1 and calls.read > 0, "custom plug-in: toBodies")
|
||||
local fc = Step.fromBodies({ {} }, { plugins = { brep = fake } })
|
||||
t:check(fc and fc.kind == "cad" and calls.write == 1, "custom plug-in: fromBodies")
|
||||
local fs, fserr = Step.tessellate(loaded, { brep = fake })
|
||||
t:check(fs and fs.kind == "scene", "custom plug-in: tessellate: " .. tostring(fserr))
|
||||
t:eq(fs.meta.up, "z", "scene: z up")
|
||||
t:eq(fs.meta.unit, 0.001, "scene: millimetres")
|
||||
t:eq(fs.meshes[1].name, "tri", "scene: body name")
|
||||
t:eq(fs.materials[fs.meshes[1].primitives[1].material].extras.color[1], 1, "scene: body colour")
|
||||
t:eq(fs.meshes[1].primitives[1].indices.count, 12, "scene: indices")
|
||||
local throwing = { read = function(): any
|
||||
error("kernel failure")
|
||||
end }
|
||||
local _, terr = Step.toBodies(loaded, { brep = throwing })
|
||||
t:eq(terr and terr.code, Err.CORRUPT, "plug-in that throws -> Err")
|
||||
F.plugins.brep = fake
|
||||
local fapi = F.cad.tessellate(loaded)
|
||||
t:check(fapi and fapi.kind == "scene", "F.cad.tessellate through F.plugins")
|
||||
F.plugins.brep = nil
|
||||
|
||||
-- 8. brep-luau (luau CLI: tests/gen/.luaurc aliases it; LuaJIT has no `vector` type: skipped)
|
||||
local function volume(scene: any): (number, { number })
|
||||
local v = 0
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for _, m in scene.meshes do
|
||||
for _, pr in m.primitives do
|
||||
local pos, ind = pr.attributes.POSITION.data, pr.indices.data
|
||||
local function P(i: number, k: number): number
|
||||
return buffer.readf32(pos, (i * 3 + k) * 4)
|
||||
end
|
||||
for tri = 0, pr.indices.count // 3 - 1 do
|
||||
local ia, ib, ic = buffer.readu32(ind, tri * 12), buffer.readu32(ind, tri * 12 + 4), buffer.readu32(ind, tri * 12 + 8)
|
||||
local ax, ay, az = P(ia, 0), P(ia, 1), P(ia, 2)
|
||||
local bx, by, bz = P(ib, 0), P(ib, 1), P(ib, 2)
|
||||
local cx2, cy, cz = P(ic, 0), P(ic, 1), P(ic, 2)
|
||||
v += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx2) + az * (bx * cy - by * cx2)) / 6
|
||||
for _, q in { { ax, ay, az }, { bx, by, bz }, { cx2, cy, cz } } do
|
||||
for k = 1, 3 do
|
||||
lo[k] = math.min(lo[k], q[k])
|
||||
hi[k] = math.max(hi[k], q[k])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return v, { lo[1], lo[2], lo[3], hi[1], hi[2], hi[3] }
|
||||
end
|
||||
|
||||
local brepOk, brep = false, nil
|
||||
if T.runtime == "luau" then
|
||||
local ok, mods = pcall(require, "@tests/gen/step_brep")
|
||||
brepOk, brep = ok and type(mods) == "table", mods
|
||||
end
|
||||
if brepOk then
|
||||
local plug = { Step = brep.Step, StepBrep = brep.StepBrep, StepWrite = brep.StepWrite, Tess = brep.Tess }
|
||||
local n = 0
|
||||
for i, c in Cases do
|
||||
-- the gmsh solids and the small public part (the 2 MB sample takes too long to tessellate here)
|
||||
if decoded[i] and c.occt and not c.occt.failed and #c.data < 400000 then
|
||||
local scene, serr = Step.tessellate(decoded[i], { brep = plug, tess = { chord = 0.01, angle = 0.05 } })
|
||||
t:check(scene, c.name .. ": tessellate: " .. tostring(serr))
|
||||
if scene then
|
||||
local bodies = Step.toBodies(decoded[i], { brep = plug })
|
||||
t:eq(#bodies, c.occt.solids, c.name .. ": solids (OCCT)")
|
||||
local v, bb = volume(scene)
|
||||
-- brep-luau reading the original text directly: our parse + write must not change what the kernel sees
|
||||
local direct = brep.StepBrep.read(brep.Step.parse(c.data)).bodies
|
||||
local dv, leaks = 0, 0
|
||||
for _, b in direct do
|
||||
local m = brep.Tess.body(b, { chord = 0.01, angle = 0.05 })
|
||||
dv += brep.Tess.volume(m)
|
||||
leaks += brep.Tess.leaks(m)
|
||||
end
|
||||
t:check(near(v, dv, 1e-6), string.format("%s: volume %.4f, brep-luau on the original %.4f", c.name, v, dv))
|
||||
if leaks == 0 then
|
||||
t:check(near(v, c.occt.volume, 2e-3), string.format("%s: volume %.3f, OCCT %.3f", c.name, v, c.occt.volume))
|
||||
else
|
||||
t:note("%s: brep-luau's tessellation leaks (%d open edges): volume %.1f vs OCCT %.1f not compared", c.name, leaks, v, c.occt.volume)
|
||||
end
|
||||
for k = 1, 6 do
|
||||
-- (OCCT's box is not tight around curved faces: ours must lie inside it)
|
||||
local inside = if k <= 3 then bb[k] >= c.occt.bbox[k] - 0.05 else bb[k] <= c.occt.bbox[k] + 0.05
|
||||
t:check(inside, string.format("%s: bounds[%d] %.4f, OCCT %.4f", c.name, k, bb[k], c.occt.bbox[k]))
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- kernel bodies -> our Cad -> our text -> bodies again
|
||||
local M = brep.M
|
||||
local part = brep.Boolean.subtract(brep.Build.box(M.v(0, 0, 0), M.v(40, 30, 5)), brep.Build.cylinder(M.v(20, 15, -1), 6, 7))[1]
|
||||
part.color = { r = 0.2, g = 0.5, b = 0.9 }
|
||||
local built, berr = F.cad.fromBodies({ part }, { brep = plug })
|
||||
t:check(built and built.kind == "cad" and #Step.byType(built, "ADVANCED_FACE") >= 7, "fromBodies: " .. tostring(berr))
|
||||
local again2 = decode(encode(built))
|
||||
local scene2 = Step.tessellate(again2, { brep = plug, chord = 0.01 })
|
||||
local v2 = volume(scene2)
|
||||
local want = brep.Tess.volume(brep.Tess.body(part, { chord = 0.01 }))
|
||||
t:check(near(v2, want, 1e-3), string.format("fromBodies round trip: volume %.3f, kernel %.3f", v2, want))
|
||||
t:check(near(v2, 40 * 30 * 5 - math.pi * 36 * 5, 2e-3), "fromBodies round trip: analytic volume")
|
||||
local col = scene2.materials[scene2.meshes[1].primitives[1].material].extras.color
|
||||
t:check(col and near(col[1], 0.2, 1e-6) and near(col[3], 0.9, 1e-6), "fromBodies round trip: colour")
|
||||
t:note("brep-luau plug-in: %d files tessellated against OCCT, bodies -> STEP -> bodies", n)
|
||||
else
|
||||
t:note("brep-luau plug-in part skipped (%s)", if T.runtime ~= "luau" then "LuaJIT: no vector type" else "no ~/dev/luau/brep-luau")
|
||||
end
|
||||
|
||||
-- 9. fuzz
|
||||
table.insert(samples, buffer.fromstring(CRAFT))
|
||||
table.insert(samples, buffer.fromstring(ED3))
|
||||
t:fuzz("decode", function(b: buffer): any
|
||||
return Step.decode(Bytes.reader(b))
|
||||
end, samples, { keepHeader = 13 })
|
||||
t:done()
|
||||
@@ -0,0 +1,420 @@
|
||||
-- model/3mf tests: the lib3mf test suite and SDK files, assimp's box.3mf and files from assimp's / trimesh's 3MF
|
||||
-- exporters against lib3mf (world triangles, area, bounds through build items and components; unit), assimp and
|
||||
-- trimesh; our writer's output read back by lib3mf / assimp / trimesh (3mf_xcheck); round trips through our own reader
|
||||
-- (materials, vertex colours, textures, hierarchy, units); hand-written packages for per-corner colour / texture
|
||||
-- groups, composite and multiproperties, components across model parts (p:path), units; error codes; the fuzz
|
||||
-- no-throw pass. Fixtures: tools/fixtures/3mf.py.
|
||||
local T = require("@tests/T")
|
||||
local ThreeMf = require("@formats/model/3mf")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Zip = require("@formats/containers/Zip")
|
||||
local Cases = require("@tests/gen/3mf_cases")
|
||||
local Xcheck = require("@tests/gen/3mf_xcheck")
|
||||
|
||||
local t = T.suite("3mf")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return ThreeMf.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(ThreeMf.name, "3mf", "name")
|
||||
t:eq(ThreeMf.category, "model", "category")
|
||||
t:check(ThreeMf.caps.decode and ThreeMf.caps.encode and ThreeMf.extensions[1] == "3mf", "contract")
|
||||
|
||||
local function near(a: number, b: number, eps: number): boolean
|
||||
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
|
||||
end
|
||||
|
||||
-- world-space triangles, area and bounds of every placed primitive
|
||||
local function metrics(scene: any): (number, number, { number }, { number })
|
||||
local tris, area = 0, 0
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for _, pl in Types.Scene.flatten(scene) do
|
||||
local p = pl.primitive
|
||||
local m = pl.matrix
|
||||
local pos = p.attributes.POSITION
|
||||
local W = {}
|
||||
for i = 0, pos.count - 1 do
|
||||
local x, y, z = buffer.readf32(pos.data, i * 12), buffer.readf32(pos.data, i * 12 + 4), buffer.readf32(pos.data, i * 12 + 8)
|
||||
local w = { m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] }
|
||||
W[i] = w
|
||||
end
|
||||
local ind = p.indices
|
||||
for k = 0, ind.count // 3 - 1 do
|
||||
local a, b, c = W[buffer.readu32(ind.data, k * 12)], W[buffer.readu32(ind.data, k * 12 + 4)], W[buffer.readu32(ind.data, k * 12 + 8)]
|
||||
for _, v in { a, b, c } do
|
||||
for q = 1, 3 do
|
||||
lo[q] = math.min(lo[q], v[q])
|
||||
hi[q] = math.max(hi[q], v[q])
|
||||
end
|
||||
end
|
||||
local e1 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] }
|
||||
local e2 = { c[1] - a[1], c[2] - a[2], c[3] - a[3] }
|
||||
local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]
|
||||
area += math.sqrt(x * x + y * y + z * z) / 2
|
||||
tris += 1
|
||||
end
|
||||
end
|
||||
return tris, area, lo, hi
|
||||
end
|
||||
|
||||
local function boundsNear(lo: { number }, hi: { number }, rmin: { number }, rmax: { number }): boolean
|
||||
local ext = 0
|
||||
for q = 1, 3 do
|
||||
ext = math.max(ext, rmax[q] - rmin[q])
|
||||
end
|
||||
local eps = 1e-5 * math.max(ext, 1e-6)
|
||||
for q = 1, 3 do
|
||||
if math.abs(lo[q] - rmin[q]) > eps or math.abs(hi[q] - rmax[q]) > eps then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ reference files
|
||||
local UNIT_NAMES = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
|
||||
local refCount, rejectedOk, unsupported = 0, 0, 0
|
||||
local byIndex = {}
|
||||
for i, c in Cases do
|
||||
local scene, err = decode(c.data)
|
||||
byIndex[i] = scene
|
||||
local ref = c.lib3mf
|
||||
if ref.failed then
|
||||
-- lib3mf rejects these (strict checks we do not make); it is enough not to throw
|
||||
rejectedOk += 1
|
||||
continue
|
||||
end
|
||||
if not scene and err and err.code == Err.UNSUPPORTED and string.find(c.name, "SecureContent", 1, true) then
|
||||
unsupported += 1 -- encrypted / wrapped model parts (the secure content extension)
|
||||
continue
|
||||
end
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
if not scene then
|
||||
continue
|
||||
end
|
||||
t:eq(scene.meta.source.unit, ref.unit, c.name .. ": unit")
|
||||
t:eq(scene.meta.unit, UNIT_NAMES[ref.unit], c.name .. ": meta.unit")
|
||||
t:eq(scene.meta.up, "z", c.name .. ": up")
|
||||
local tris, area, lo, hi = metrics(scene)
|
||||
t:eq(tris, ref.triangles, c.name .. ": world triangles (lib3mf)")
|
||||
t:check(near(area, ref.area, 1e-5), string.format("%s: area %.7g, lib3mf %.7g", c.name, area, ref.area))
|
||||
if ref.min then
|
||||
t:check(boundsNear(lo, hi, ref.min, ref.max), c.name .. ": bounds (lib3mf)")
|
||||
end
|
||||
t:check(#scene.textures <= ref.textures, c.name .. ": textures <= lib3mf's texture2d count")
|
||||
refCount += 1
|
||||
-- trimesh reads build items and components the same way (it skips degenerate input)
|
||||
local tm = c.trimesh
|
||||
if tm and not tm.failed and tm.faces == tris and tm.faces > 0 then
|
||||
t:check(near(area, tm.area, 1e-5), c.name .. ": area (trimesh)")
|
||||
end
|
||||
end
|
||||
t:note("%d files: %d against lib3mf, %d rejected by lib3mf (decoded without throwing), %d secure content (UNSUPPORTED)", #Cases, refCount, rejectedOk, unsupported)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ our output read back
|
||||
local xchecked, withTextures = 0, 0
|
||||
for _, x in Xcheck do
|
||||
local c = Cases[x.case]
|
||||
local ref = c.lib3mf
|
||||
if not byIndex[x.case] then
|
||||
continue
|
||||
end
|
||||
t:check(not x.lib3mf.failed, x.name .. " (" .. c.name .. "): lib3mf reads our file: " .. tostring(x.lib3mf.failed))
|
||||
if not x.lib3mf.failed then
|
||||
t:eq(x.lib3mf.triangles, ref.triangles, c.name .. ": our file's triangles (lib3mf)")
|
||||
t:check(near(x.lib3mf.area, ref.area, 1e-5), string.format("%s: our file's area %.7g vs %.7g (lib3mf)", c.name, x.lib3mf.area, ref.area))
|
||||
if ref.min then
|
||||
t:check(boundsNear(x.lib3mf.min, x.lib3mf.max, ref.min, ref.max), c.name .. ": our file's bounds (lib3mf)")
|
||||
end
|
||||
t:eq(x.lib3mf.unit, ref.unit, c.name .. ": our file's unit (lib3mf)")
|
||||
-- the material groups made it: textures, colour groups, base materials
|
||||
local scene = byIndex[x.case]
|
||||
local tex, col = 0, 0
|
||||
for _, m in scene.meshes do
|
||||
for _, p in m.primitives do
|
||||
if p.attributes.TEXCOORD_0 and p.material and scene.materials[p.material].baseColorTexture then
|
||||
tex += 1
|
||||
elseif p.attributes.COLOR_0 then
|
||||
col += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check((tex == 0) == (x.lib3mf.texGroups == 0), c.name .. ": our texture groups (lib3mf)")
|
||||
t:check(tex == 0 or x.lib3mf.textures > 0, c.name .. ": our textures (lib3mf)")
|
||||
t:eq(x.lib3mf.colorGroups, col, c.name .. ": our colour groups (lib3mf)")
|
||||
t:eq(x.lib3mf.baseGroups, if #scene.materials > 0 then 1 else 0, c.name .. ": our base material group (lib3mf)")
|
||||
if tex > 0 then
|
||||
withTextures += 1
|
||||
end
|
||||
end
|
||||
t:check(not x.assimp.failed or c.assimp.failed, c.name .. ": assimp reads our file")
|
||||
if not x.trimesh.failed and x.trimesh.faces > 0 and not c.trimesh.failed and c.trimesh.faces == x.trimesh.faces then
|
||||
t:check(near(x.trimesh.area, c.trimesh.area, 1e-5), c.name .. ": our file's area (trimesh)")
|
||||
end
|
||||
xchecked += 1
|
||||
end
|
||||
t:note("%d of our files read back by lib3mf / assimp / trimesh like the originals (%d with textures)", xchecked, withTextures)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ round trips (ours)
|
||||
local rts = 0
|
||||
for i, c in Cases do
|
||||
local scene = byIndex[i]
|
||||
if scene and not c.lib3mf.failed then
|
||||
local out, err = ThreeMf.encode(scene)
|
||||
t:check(out, c.name .. ": encode: " .. tostring(err))
|
||||
local back, berr = decode(out)
|
||||
t:check(back, c.name .. ": decode ours: " .. tostring(berr))
|
||||
local a1, b1 = metrics(scene)
|
||||
local a2, b2 = metrics(back)
|
||||
t:eq(a2, a1, c.name .. ": round trip triangles")
|
||||
t:check(near(b2, b1, 1e-6), c.name .. ": round trip area")
|
||||
t:eq(back.meta.unit, scene.meta.unit, c.name .. ": round trip unit")
|
||||
-- textures: the same bytes
|
||||
local used = 0
|
||||
for _, m in back.materials do
|
||||
if m.baseColorTexture then
|
||||
used += 1
|
||||
t:check(back.textures[m.baseColorTexture.texture].data ~= nil, c.name .. ": texture bytes")
|
||||
end
|
||||
end
|
||||
rts += 1
|
||||
end
|
||||
end
|
||||
t:note("%d round trips through our writer", rts)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ hand-written packages
|
||||
local function package(model: string, extra: { [string]: string }?): buffer
|
||||
local w = Zip.writer()
|
||||
w:add("[Content_Types].xml", '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/></Types>', { method = "store" })
|
||||
w:add("_rels/.rels", '<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Target="/3D/3dmodel.model" Id="r0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/></Relationships>', { method = "store" })
|
||||
w:add("3D/3dmodel.model", model, { method = "store" })
|
||||
for k, v in extra or {} do
|
||||
w:add(k, v, { method = "store" })
|
||||
end
|
||||
return (w:finish())
|
||||
end
|
||||
local HEAD = '<?xml version="1.0" encoding="UTF-8"?><model unit="%s" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:m="http://schemas.microsoft.com/3dmanufacturing/material/2015/02" xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06">'
|
||||
local QUAD = '<mesh><vertices><vertex x="0" y="0" z="0"/><vertex x="1" y="0" z="0"/><vertex x="1" y="1" z="0"/><vertex x="0" y="1" z="0"/></vertices><triangles>%s</triangles></mesh>'
|
||||
local samples = {}
|
||||
|
||||
local function f32s(acc: any): { number }
|
||||
local out = {}
|
||||
for i = 0, acc.count * acc.components - 1 do
|
||||
out[i + 1] = buffer.readf32(acc.data, i * 4)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
do -- per-corner colours: vertex 0 has two different colours -> split
|
||||
local xml = string.format(HEAD, "inch")
|
||||
.. '<metadata name="Title">quad & co</metadata><resources>'
|
||||
.. '<m:colorgroup id="1"><m:color color="#FF0000"/><m:color color="#00FF0080"/><m:color color="#0000FF"/></m:colorgroup>'
|
||||
.. '<object id="2" type="model" name="q">' .. string.format(QUAD, '<triangle v1="0" v2="1" v3="2" pid="1" p1="0" p2="1" p3="2"/><triangle v1="0" v2="2" v3="3" pid="1" p1="2"/>') .. '</object>'
|
||||
.. '</resources><build><item objectid="2" transform="1 0 0 0 1 0 0 0 1 10 20 30"/></build></model>'
|
||||
local pkg = package(xml)
|
||||
table.insert(samples, pkg)
|
||||
local s, err = decode(pkg)
|
||||
t:check(s, "colours: " .. tostring(err))
|
||||
t:eq(s.meta.unit, 0.0254, "colours: inch")
|
||||
t:eq(s.meta.metadata.Title, "quad & co", "colours: metadata")
|
||||
t:eq(#s.meshes, 1, "colours: one mesh")
|
||||
local prim = s.meshes[1].primitives[1]
|
||||
t:eq(#s.meshes[1].primitives, 1, "colours: one primitive")
|
||||
-- corners: (0,red) (1,green) (2,blue) | (0,blue) (2,blue) (3,blue) -> 5 vertices
|
||||
t:eq(prim.attributes.POSITION.count, 5, "colours: vertex 0 split by colour")
|
||||
local col = f32s(prim.attributes.COLOR_0)
|
||||
t:eq(col[1], 1, "colours: red r (linear)")
|
||||
t:eq(col[2], 0, "colours: red g")
|
||||
t:check(math.abs(col[8] - 128 / 255) < 1e-6, "colours: alpha kept linear")
|
||||
t:eq(s.nodes[1].matrix[13], 10, "colours: transform tx")
|
||||
t:eq(s.nodes[1].matrix[15], 30, "colours: transform tz")
|
||||
-- through our writer and back: the same colours
|
||||
local back = decode((ThreeMf.encode(s)))
|
||||
local col2 = f32s(back.meshes[1].primitives[1].attributes.COLOR_0)
|
||||
local same = #col2 == #col
|
||||
for i = 1, #col do
|
||||
same = same and math.abs(col[i] - col2[i]) < 1e-6
|
||||
end
|
||||
t:check(same, "colours: round trip exact (8-bit sRGB)")
|
||||
t:eq(back.meta.metadata.Title, "quad & co", "colours: metadata round trip")
|
||||
t:eq(back.meta.source.unit, "inch", "colours: unit round trip")
|
||||
end
|
||||
|
||||
do -- base materials, object defaults, composite, multiproperties, textures
|
||||
local png = "\137PNG\r\n\26\nfake"
|
||||
local xml = string.format(HEAD, "millimeter") .. "<resources>"
|
||||
.. '<basematerials id="1"><base name="red" displaycolor="#FF0000"/><base name="half" displaycolor="#808080FF"/></basematerials>'
|
||||
.. '<m:texture2d id="3" path="/3D/Texture/a.png" contenttype="image/png" tilestyleu="clamp" tilestylev="mirror" filter="nearest"/>'
|
||||
.. '<m:texture2dgroup id="4" texid="3"><m:tex2coord u="0" v="0"/><m:tex2coord u="1" v="0.25"/><m:tex2coord u="1" v="1"/></m:texture2dgroup>'
|
||||
.. '<m:compositematerials id="5" matid="1" matindices="0 1"><m:composite values="0.5 0.5"/></m:compositematerials>'
|
||||
.. '<m:multiproperties id="6" pids="1 4"><m:multi pindices="1 0"/></m:multiproperties>'
|
||||
.. '<object id="7" type="model" pid="1" pindex="0">' .. string.format(QUAD,
|
||||
'<triangle v1="0" v2="1" v3="2"/>' -- object default: red
|
||||
.. '<triangle v1="0" v2="2" v3="3" pid="4" p1="0" p2="1" p3="2"/>' -- texture
|
||||
.. '<triangle v1="1" v2="2" v3="3" pid="5" p1="0"/>' -- composite
|
||||
.. '<triangle v1="0" v2="1" v3="3" pid="6" p1="0"/>' -- multi -> its first layer (base 1 = "half")
|
||||
.. '<triangle v1="0" v2="3" v3="2" pid="1" p1="1"/>') -- half
|
||||
.. "</object></resources><build><item objectid=\"7\"/></build></model>"
|
||||
local pkg = package(xml, { ["3D/Texture/a.png"] = png })
|
||||
table.insert(samples, pkg)
|
||||
local s, err = decode(pkg)
|
||||
t:check(s, "materials: " .. tostring(err))
|
||||
local prims = s.meshes[1].primitives
|
||||
t:eq(#prims, 4, "materials: red, texture, composite, half (multi shares half)")
|
||||
local red = s.materials[prims[1].material]
|
||||
t:eq(red.name, "red", "materials: object default pid / pindex")
|
||||
t:eq(red.baseColor[1], 1, "materials: red")
|
||||
t:eq(red.extras["3mf"].displaycolor, "#FF0000", "materials: display colour kept")
|
||||
local tex = s.materials[prims[2].material]
|
||||
t:check(tex.baseColorTexture and s.textures[tex.baseColorTexture.texture], "materials: texture material")
|
||||
local tx = s.textures[tex.baseColorTexture.texture]
|
||||
t:eq(buffer.tostring(tx.data), png, "materials: texture bytes from the package")
|
||||
t:eq(tx.mime, "image/png", "materials: texture mime")
|
||||
t:eq(tx.sampler.wrapS, "clamp", "materials: tilestyleu")
|
||||
t:eq(tx.sampler.wrapT, "mirror", "materials: tilestylev")
|
||||
t:eq(tx.sampler.filter, "nearest", "materials: filter")
|
||||
local uv = f32s(prims[2].attributes.TEXCOORD_0)
|
||||
t:eq(uv[4], 0.75, "materials: v flipped to the top-left origin")
|
||||
local comp = s.materials[prims[3].material]
|
||||
local half = (128 / 255 + 0.055) / 1.055
|
||||
t:check(math.abs(comp.baseColor[1] - (((1 + 128 / 255) / 2 + 0.055) / 1.055) ^ 2.4) < 1e-6, "materials: composite blends in sRGB")
|
||||
t:eq(s.materials[prims[4].material].name, "half", "materials: multiproperties -> first layer")
|
||||
t:eq(prims[4].indices.count, 6, "materials: multi and base 'half' share a primitive")
|
||||
t:check(math.abs(s.materials[prims[4].material].baseColor[1] - half ^ 2.4) < 1e-6, "materials: sRGB -> linear")
|
||||
-- round trip: texture + materials survive
|
||||
local out = assert(ThreeMf.encode(s))
|
||||
local back = assert(decode(out))
|
||||
local tm = nil
|
||||
for _, m in back.materials do
|
||||
if m.baseColorTexture then
|
||||
tm = m
|
||||
end
|
||||
end
|
||||
t:check(tm and buffer.tostring(back.textures[tm.baseColorTexture.texture].data) == png, "materials: texture round trip")
|
||||
t:eq(back.textures[1].sampler.wrapS, "clamp", "materials: sampler round trip")
|
||||
local _, a1 = metrics(s)
|
||||
local _, a2 = metrics(back)
|
||||
t:check(near(a1, a2, 1e-6), "materials: area round trip")
|
||||
local names = {}
|
||||
for _, m in back.materials do
|
||||
if m.name then
|
||||
names[m.name] = true
|
||||
end
|
||||
end
|
||||
t:check(names.red and names.half, "materials: base names round trip")
|
||||
end
|
||||
|
||||
do -- components, another model part through p:path, nested transforms
|
||||
local part = string.format(HEAD, "millimeter") .. "<resources><object id=\"1\" type=\"model\" name=\"leaf\">"
|
||||
.. string.format(QUAD, '<triangle v1="0" v2="1" v3="2"/><triangle v1="0" v2="2" v3="3"/>') .. "</object></resources><build/></model>"
|
||||
local xml = string.format(HEAD, "centimeter") .. "<resources>"
|
||||
.. '<object id="1" type="model" name="local">' .. string.format(QUAD, '<triangle v1="0" v2="1" v3="2"/>') .. "</object>"
|
||||
.. '<object id="2" type="model" name="group"><components><component objectid="1" transform="2 0 0 0 2 0 0 0 2 0 0 0"/>'
|
||||
.. '<component objectid="1" p:path="/3D/other.model" transform="1 0 0 0 1 0 0 0 1 5 0 0"/></components></object>'
|
||||
.. '</resources><build><item objectid="2" transform="1 0 0 0 1 0 0 0 1 0 0 1"/><item objectid="2"/></build></model>'
|
||||
local pkg = package(xml, { ["3D/other.model"] = part })
|
||||
table.insert(samples, pkg)
|
||||
local s, err = decode(pkg)
|
||||
t:check(s, "components: " .. tostring(err))
|
||||
t:eq(#s.roots, 2, "components: two build items")
|
||||
t:eq(#s.meshes, 2, "components: meshes shared between instances")
|
||||
t:eq(s.nodes[s.roots[1]].name, "group", "components: node names")
|
||||
t:eq(#s.nodes[s.roots[1]].children, 2, "components: children")
|
||||
local tris, area, lo, hi = metrics(s)
|
||||
t:eq(tris, 6, "components: world triangles")
|
||||
t:check(near(area, 2 * (2 + 1), 1e-9), "components: world area")
|
||||
t:check(lo[1] == 0 and hi[1] == 6 and hi[3] == 1, "components: nested transforms")
|
||||
t:eq(s.meta.unit, 0.01, "components: centimetre")
|
||||
-- the writer flattens the hierarchy into build items
|
||||
local back = assert(decode((ThreeMf.encode(s))))
|
||||
local tris2, area2, lo2, hi2 = metrics(back)
|
||||
t:eq(tris2, 6, "components: flattened round trip triangles")
|
||||
t:check(near(area2, area, 1e-9) and lo2[1] == 0 and hi2[1] == 6 and hi2[3] == 1, "components: flattened round trip bounds")
|
||||
t:eq(back.meta.source.unit, "centimeter", "components: unit round trip")
|
||||
-- a unit 3MF lacks: scaled into millimetres
|
||||
s.meta.unit = 0.5
|
||||
local scaled = assert(decode((ThreeMf.encode(s))))
|
||||
local _, _, _, hi3 = metrics(scaled)
|
||||
t:eq(scaled.meta.source.unit, "millimeter", "units: millimetres when the scene's unit is not a 3MF unit")
|
||||
t:check(math.abs(hi3[1] - 3000) < 1e-3, "units: positions scaled through the build transforms")
|
||||
t:check(select(2, ThreeMf.encode(s, { unit = "parsec" :: any })).code == Err.ARG, "units: bad opts.unit")
|
||||
end
|
||||
|
||||
do -- a Scene built by hand: strips, fans, polygons, vertex colours + texture coordinates, an unplaced mesh
|
||||
local s = Types.Scene.new()
|
||||
local pos = Types.Scene.accessor(nil, "f32", 3, 4)
|
||||
for i, v in { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 } do
|
||||
buffer.writef32(pos.data, (i - 1) * 4, v)
|
||||
end
|
||||
local faces = Types.Scene.accessor(nil, "u32", 1, 1)
|
||||
buffer.writeu32(faces.data, 0, 4)
|
||||
local col = Types.Scene.accessor(nil, "unorm8", 3, 4)
|
||||
buffer.fill(col.data, 0, 255)
|
||||
s.meshes = {
|
||||
{ primitives = { { attributes = { POSITION = pos }, mode = "triangle_strip" }, { attributes = { POSITION = pos }, mode = "triangle_fan", material = 1 } } },
|
||||
{ primitives = { { attributes = { POSITION = pos, COLOR_0 = col }, mode = "polygons", faces = faces }, { attributes = { POSITION = pos }, mode = "points" } } },
|
||||
}
|
||||
s.materials = { Types.Scene.material("m") }
|
||||
s.nodes = { { children = { 2 }, mesh = 1, translation = { 0, 0, 5 } }, { children = {}, mesh = 2, scale = { 2, 2, 2 } } }
|
||||
s.roots = { 1 }
|
||||
local out, err = ThreeMf.encode(s, { level = 0 })
|
||||
t:check(out, "scene: encode " .. tostring(err))
|
||||
table.insert(samples, out)
|
||||
local back = assert(decode(out))
|
||||
local tris, area, _, hi = metrics(back)
|
||||
t:eq(tris, 6, "scene: strip + fan + polygon triangles (points skipped)")
|
||||
t:check(near(area, 2 + 4, 1e-9), "scene: area with node transforms")
|
||||
t:eq(hi[3], 5, "scene: parent translation applied to the child")
|
||||
t:eq(#back.roots, 2, "scene: one build item per placed mesh")
|
||||
local m2 = back.meshes[back.nodes[back.roots[2]].mesh]
|
||||
t:check(m2.primitives[1].attributes.COLOR_0 ~= nil, "scene: vertex colours as a colour group")
|
||||
t:check(select(2, ThreeMf.encode({} :: any)).code == Err.ARG, "encode: not a scene")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ errors
|
||||
do
|
||||
local _, e1 = decode("not a zip at all")
|
||||
t:check(e1 and e1.code ~= nil, "errors: not a zip")
|
||||
local w = Zip.writer()
|
||||
w:add("hello.txt", "hi")
|
||||
local _, e2 = decode((w:finish()))
|
||||
t:eq(e2 and e2.code, Err.CORRUPT, "errors: no model part")
|
||||
local bad = string.format(HEAD, "millimeter") .. '<resources><object id="1">' .. string.format(QUAD, '<triangle v1="0" v2="1" v3="9"/>') .. "</object></resources><build><item objectid=\"1\"/></build></model>"
|
||||
local _, e3 = decode(package(bad))
|
||||
t:eq(e3 and e3.code, Err.CORRUPT, "errors: vertex index out of range")
|
||||
local cyc = string.format(HEAD, "millimeter") .. '<resources><object id="1"><components><component objectid="2"/></components></object><object id="2"><components><component objectid="1"/></components></object></resources><build><item objectid="1"/></build></model>'
|
||||
local _, e4 = decode(package(cyc))
|
||||
t:eq(e4 and e4.code, Err.CORRUPT, "errors: component cycle")
|
||||
local _, e5 = decode(package(string.format(HEAD, "millimeter") .. "<resources/><build><item objectid=\"3\"/></build></model>"))
|
||||
t:eq(e5 and e5.code, Err.CORRUPT, "errors: build item without an object")
|
||||
local _, e6 = decode(package(string.format(HEAD, "millimeter") .. '<resources><object id="1">' .. string.format(QUAD, "") .. "</object></resources><build/></model>"), { maxVertices = 2 })
|
||||
t:eq(e6 and e6.code, Err.LIMIT, "errors: maxVertices")
|
||||
table.insert(samples, package(bad))
|
||||
table.insert(samples, package(cyc))
|
||||
-- sniff
|
||||
t:eq(ThreeMf.sniff(Bytes.reader(package(bad))), 0.95, "sniff: a 3MF package")
|
||||
t:eq(ThreeMf.sniff(Bytes.reader((w:finish()))), 0, "sniff: another zip")
|
||||
t:eq(ThreeMf.sniff(Bytes.reader(buffer.fromstring("solid x"))), 0, "sniff: not a zip")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
do
|
||||
for _, c in Cases do
|
||||
if #c.data < 20000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local s = ThreeMf.decode(Bytes.reader(b))
|
||||
if s then
|
||||
ThreeMf.encode(s)
|
||||
end
|
||||
return s
|
||||
end, samples, { mutations = 12 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,581 @@
|
||||
-- model/dae tests: assimp's Collada test models (triangles / polylist / polygons / tristrips, UTF-16 and BOM files,
|
||||
-- decimal commas, 2 UV sets, vertex colours, instance_node, cameras, lights, nested / clipped / full-rotation
|
||||
-- animations, skins, .zae) and glTF samples exported by assimp's Collada exporter, against `assimp info -r` (meshes,
|
||||
-- faces, bounds in assimp's space, materials, animations, cameras, lights), and against the glTF originals read by
|
||||
-- model/gltf (skinned rest-pose bounds, joints, every LINEAR animation key); our writer's output read back by assimp
|
||||
-- (dae_xcheck) and by us (round trips, .dae and .zae); polygons kept with triangulate = false; textures decoded lazily
|
||||
-- at the api layer; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/dae.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Dae = require("@formats/model/dae")
|
||||
local Gltf = require("@formats/model/gltf")
|
||||
local MeshOps = require("@formats/ops/MeshOps")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/dae_cases")
|
||||
local Xcheck = require("@tests/gen/dae_xcheck")
|
||||
|
||||
local Scene = Types.Scene
|
||||
local t = T.suite("dae")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Dae.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(Dae.name, "dae", "name")
|
||||
t:eq(Dae.category, "model", "category")
|
||||
t:check(Dae.caps.decode and Dae.caps.encode and table.find(Dae.extensions, "zae"), "contract")
|
||||
|
||||
local function near(a: number, b: number, eps: number): boolean
|
||||
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
|
||||
end
|
||||
local function nearV(a: { number }, b: { number }, eps: number): boolean
|
||||
for i = 1, #b do
|
||||
if not near(a[i], b[i], eps) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return #a == #b
|
||||
end
|
||||
local function fmt(v: { number }?): string
|
||||
if not v then
|
||||
return "-"
|
||||
end
|
||||
return string.format("(%.4g %.4g %.4g)", v[1], v[2], v[3])
|
||||
end
|
||||
|
||||
-- assimp's counts: one mesh per primitive reached (instances of one primitive once), faces as stored
|
||||
local function counts(scene: any): (number, number)
|
||||
local prims, faces = 0, 0
|
||||
local seen = {}
|
||||
for _, pl in Scene.flatten(scene) do
|
||||
if not seen[pl.primitive] then
|
||||
seen[pl.primitive] = true
|
||||
local p = pl.primitive
|
||||
prims += 1
|
||||
if p.mode == "polygons" then
|
||||
faces += p.faces.count
|
||||
elseif p.mode == "triangles" then
|
||||
faces += p.indices.count // 3
|
||||
elseif p.mode == "lines" then
|
||||
faces += p.indices.count // 2
|
||||
end
|
||||
end
|
||||
end
|
||||
return prims, faces
|
||||
end
|
||||
|
||||
local function inverse(m: { number }): { number }
|
||||
-- general 4x4 inverse (column-major; cofactors)
|
||||
local inv = table.create(16, 0)
|
||||
local a = m
|
||||
inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11]
|
||||
inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11]
|
||||
inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10]
|
||||
inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10]
|
||||
inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11]
|
||||
inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11]
|
||||
inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10]
|
||||
inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10]
|
||||
inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7]
|
||||
inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7]
|
||||
inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6]
|
||||
inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6]
|
||||
inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7]
|
||||
inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7]
|
||||
inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6]
|
||||
inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6]
|
||||
local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13]
|
||||
for i = 1, 16 do
|
||||
inv[i] /= det
|
||||
end
|
||||
return inv
|
||||
end
|
||||
|
||||
local function grow(lo: { number }, hi: { number }, x: number, y: number, z: number)
|
||||
lo[1], lo[2], lo[3] = math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z)
|
||||
hi[1], hi[2], hi[3] = math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z)
|
||||
end
|
||||
local function apply(m: { number }, x: number, y: number, z: number): (number, number, number)
|
||||
return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15]
|
||||
end
|
||||
|
||||
-- the bounds `assimp info` prints: its Collada importer puts the up-axis rotation and unit scale on the root node,
|
||||
-- and Info.cpp accumulates node transforms as local * parent (sic); skinned meshes without their bind shape matrix
|
||||
local function assimpBounds(scene: any, written: boolean?): ({ number }?, { number }?)
|
||||
local u = scene.meta.unit or 1
|
||||
local root = if scene.meta.up == "z" then { u, 0, 0, 0, 0, 0, -u, 0, 0, u, 0, 0, 0, 0, 0, 1 }
|
||||
elseif scene.meta.up == "x" then { 0, u, 0, 0, -u, 0, 0, 0, 0, 0, u, 0, 0, 0, 0, 1 }
|
||||
else { u, 0, 0, 0, 0, u, 0, 0, 0, 0, u, 0, 0, 0, 0, 1 }
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
local seen = {}
|
||||
local function visit(i: number, parent: { number })
|
||||
local n = scene.nodes[i]
|
||||
if seen[i] then
|
||||
return
|
||||
end
|
||||
seen[i] = true
|
||||
local m = Scene.mul(Scene.nodeMatrix(n), parent)
|
||||
local mesh = n.mesh and scene.meshes[n.mesh]
|
||||
if mesh then
|
||||
local mm = m
|
||||
local skin = n.skin and scene.skins[n.skin]
|
||||
if skin and not written and skin.extras and skin.extras.dae and skin.extras.dae.bindShapeMatrix then
|
||||
mm = Scene.mul(m, inverse(skin.extras.dae.bindShapeMatrix))
|
||||
end
|
||||
for _, p in mesh.primitives do
|
||||
local pos = p.attributes.POSITION
|
||||
for v = 0, pos.count - 1 do
|
||||
grow(lo, hi, apply(mm, buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8)))
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, c in n.children do
|
||||
visit(c, m)
|
||||
end
|
||||
end
|
||||
for _, r in scene.roots do
|
||||
visit(r, root)
|
||||
end
|
||||
if lo[1] > hi[1] then
|
||||
return nil, nil
|
||||
end
|
||||
return lo, hi
|
||||
end
|
||||
|
||||
-- world matrices (correct order) of every node
|
||||
local function worlds(scene: any): { [number]: { number } }
|
||||
local w = {}
|
||||
local function visit(i: number, parent: { number })
|
||||
if w[i] then
|
||||
return
|
||||
end
|
||||
w[i] = Scene.mul(parent, Scene.nodeMatrix(scene.nodes[i]))
|
||||
for _, c in scene.nodes[i].children do
|
||||
visit(c, w[i])
|
||||
end
|
||||
end
|
||||
for _, r in scene.roots do
|
||||
visit(r, Scene.IDENTITY)
|
||||
end
|
||||
return w
|
||||
end
|
||||
|
||||
-- bounds of the rest pose with skins applied (glTF semantics: skinned vertices = sum w * world(joint) * ibm * v)
|
||||
local function posedBounds(scene: any): ({ number }?, { number }?)
|
||||
local w = worlds(scene)
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for ni, m in w do
|
||||
local n = scene.nodes[ni]
|
||||
local mesh = n.mesh and scene.meshes[n.mesh]
|
||||
if mesh then
|
||||
local skin = n.skin and scene.skins[n.skin]
|
||||
local jm = {}
|
||||
if skin then
|
||||
local ibm = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices)
|
||||
for j, jn in skin.joints do
|
||||
local inv = table.create(16, 0)
|
||||
for k = 1, 16 do
|
||||
inv[k] = if ibm then ibm(j - 1, k - 1) else (if k % 5 == 1 then 1 else 0)
|
||||
end
|
||||
jm[j - 1] = Scene.mul(w[jn] or Scene.IDENTITY, inv)
|
||||
end
|
||||
end
|
||||
for _, p in mesh.primitives do
|
||||
local pos = p.attributes.POSITION
|
||||
local J = skin and p.attributes.JOINTS_0 and Scene.reader(p.attributes.JOINTS_0)
|
||||
local W = skin and p.attributes.WEIGHTS_0 and Scene.reader(p.attributes.WEIGHTS_0)
|
||||
for v = 0, pos.count - 1 do
|
||||
local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8)
|
||||
if J and W then
|
||||
local sx, sy, sz = 0, 0, 0
|
||||
for k = 0, 3 do
|
||||
local wt = W(v, k)
|
||||
if wt > 0 then
|
||||
local px, py, pz = apply(jm[J(v, k)] or Scene.IDENTITY, x, y, z)
|
||||
sx, sy, sz = sx + wt * px, sy + wt * py, sz + wt * pz
|
||||
end
|
||||
end
|
||||
grow(lo, hi, sx, sy, sz)
|
||||
else
|
||||
grow(lo, hi, apply(m, x, y, z))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if lo[1] > hi[1] then
|
||||
return nil, nil
|
||||
end
|
||||
return lo, hi
|
||||
end
|
||||
|
||||
local function lightCount(scene: any): number
|
||||
local n = #scene.lights
|
||||
for _, node in scene.nodes do
|
||||
if node.extras and node.extras.dae and node.extras.dae.ambientLight then
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
-- a channel's value at time tm (LINEAR; rotations nlerped)
|
||||
local function channelAt(ch: any, tm: number): { number }
|
||||
local inp, out = Scene.reader(ch.input) :: any, Scene.reader(ch.output) :: any
|
||||
local n, c = ch.input.count, ch.output.components
|
||||
local function at(i: number): { number }
|
||||
local r = {}
|
||||
for k = 0, c - 1 do
|
||||
r[k + 1] = out(i, k)
|
||||
end
|
||||
return r
|
||||
end
|
||||
if tm <= inp(0, 0) then
|
||||
return at(0)
|
||||
end
|
||||
for i = 1, n - 1 do
|
||||
local t1 = inp(i, 0)
|
||||
if tm <= t1 + 1e-6 then
|
||||
local t0 = inp(i - 1, 0)
|
||||
local f = if t1 > t0 then math.clamp((tm - t0) / (t1 - t0), 0, 1) else 1
|
||||
local a, b = at(i - 1), at(i)
|
||||
for k = 1, c do
|
||||
a[k] += (b[k] - a[k]) * f
|
||||
end
|
||||
return a
|
||||
end
|
||||
end
|
||||
return at(n - 1)
|
||||
end
|
||||
|
||||
local checked = { assimp = 0, bounds = 0, gltf = 0, keys = 0, roundTrips = 0, xcheck = 0 }
|
||||
local decoded: { [number]: any } = {}
|
||||
local samples: { string } = {}
|
||||
for i, c in Cases do
|
||||
local scene, err = decode(c.data, { files = c.files, triangulate = false })
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
if not scene then
|
||||
continue
|
||||
end
|
||||
t:eq(scene.meta.source.format, "dae", c.name .. ": source")
|
||||
local ref = c.assimp
|
||||
local prims, faces = counts(scene)
|
||||
if ref and not ref.failed then
|
||||
-- assimp builds a placeholder skeleton mesh for scenes without meshes
|
||||
if prims > 0 then
|
||||
t:eq(prims, ref.meshes, c.name .. ": meshes (assimp)")
|
||||
t:eq(faces, ref.faces, c.name .. ": faces (assimp)")
|
||||
local lo, hi = assimpBounds(scene)
|
||||
local ok = lo ~= nil and hi ~= nil and nearV(lo :: any, ref.min, 2e-4) and nearV(hi :: any, ref.max, 2e-4)
|
||||
t:check(ok, string.format("%s: bounds %s %s, assimp %s %s", c.name, fmt(lo), fmt(hi), fmt(ref.min), fmt(ref.max)))
|
||||
checked.bounds += 1
|
||||
-- assimp adds a default material when a mesh has none
|
||||
t:check(ref.materials - #scene.materials == 0 or ref.materials - #scene.materials == 1, c.name .. ": materials (assimp)")
|
||||
end
|
||||
t:eq(#scene.cameras, ref.cameras, c.name .. ": cameras (assimp)")
|
||||
t:eq(lightCount(scene), ref.lights, c.name .. ": lights (assimp)")
|
||||
t:eq(#scene.animations, ref.animations, c.name .. ": animations (assimp)")
|
||||
checked.assimp += 1
|
||||
end
|
||||
-- against the glTF original of an assimp export
|
||||
if c.gltf then
|
||||
local g, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(c.gltf)), { files = c.gltfFiles })
|
||||
t:check(g, c.name .. ": gltf original: " .. tostring(gerr))
|
||||
if g then
|
||||
local glo, ghi = posedBounds(g)
|
||||
local lo, hi = posedBounds(scene)
|
||||
-- assimp's exporter folds a root Z-up rotation node of the source into <up_axis>Z_UP</up_axis>
|
||||
if lo and hi and scene.meta.up == "z" then
|
||||
lo, hi = { lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] }
|
||||
end
|
||||
t:check(lo and glo and nearV(lo, glo, 1e-4) and nearV(hi :: any, ghi :: any, 1e-4), string.format("%s: posed bounds %s %s, glTF %s %s", c.name, fmt(lo), fmt(hi), fmt(glo), fmt(ghi)))
|
||||
t:eq(#scene.skins, #g.skins, c.name .. ": skins")
|
||||
if #g.skins > 0 and #scene.skins > 0 then
|
||||
t:eq(#scene.skins[1].joints, #g.skins[1].joints, c.name .. ": joints")
|
||||
end
|
||||
-- every LINEAR key of the original, evaluated on our resampled channels (nodes matched by name)
|
||||
local byName = {}
|
||||
for ni, n in scene.nodes do
|
||||
if n.name then
|
||||
byName[n.name] = byName[n.name] or ni
|
||||
end
|
||||
end
|
||||
-- assimp's Collada exporter writes key times in milliseconds (its glTF importer's ticks per second)
|
||||
local function maxTime(sc: any): number
|
||||
local m = 0
|
||||
for _, a in sc.animations do
|
||||
for _, ch in a.channels do
|
||||
m = math.max(m, buffer.readf32(ch.input.data, (ch.input.count - 1) * 4))
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
local gmax, omax = maxTime(g), maxTime(scene)
|
||||
local tscale = if gmax > 0 and near(omax / gmax, 1000, 1e-3) then 1000 else 1
|
||||
-- (files assimp cannot read back: its exporter left out animation sources; their channels are dropped)
|
||||
for _, ga in if ref and not ref.failed then g.animations else {} do
|
||||
for _, gc in ga.channels do
|
||||
local gname = g.nodes[gc.node].name
|
||||
local ni = gname and byName[gname]
|
||||
if gc.interpolation == "LINEAR" and gc.path ~= "weights" and ni then
|
||||
local ours = nil
|
||||
for _, a in scene.animations do
|
||||
for _, ch in a.channels do
|
||||
if ch.node == ni and ch.path == gc.path then
|
||||
ours = ch
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(ours, c.name .. ": animated " .. gname .. " " .. gc.path)
|
||||
if ours then
|
||||
local gin, gout = Scene.reader(gc.input) :: any, Scene.reader(gc.output) :: any
|
||||
for k = 0, gc.input.count - 1 do
|
||||
local want = {}
|
||||
for q = 0, gc.output.components - 1 do
|
||||
want[q + 1] = gout(k, q)
|
||||
end
|
||||
local got = channelAt(ours, gin(k, 0) * tscale)
|
||||
local ok
|
||||
if gc.path == "rotation" then
|
||||
local d = math.abs(got[1] * want[1] + got[2] * want[2] + got[3] * want[3] + got[4] * want[4])
|
||||
ok = d > 1 - 1e-4
|
||||
else
|
||||
ok = nearV(got, want, 1e-4)
|
||||
end
|
||||
t:check(ok, string.format("%s: %s %s at %g", c.name, gname, gc.path, gin(k, 0)))
|
||||
checked.keys += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
checked.gltf += 1
|
||||
end
|
||||
end
|
||||
-- the full rotations file: no resampled step over 90 degrees
|
||||
if string.find(c.name, "full_rotations", 1, true) then
|
||||
local worst = 1
|
||||
for _, a in scene.animations do
|
||||
for _, ch in a.channels do
|
||||
if ch.path == "rotation" then
|
||||
local r = Scene.reader(ch.output) :: any
|
||||
for k = 1, ch.output.count - 1 do
|
||||
local d = 0
|
||||
for q = 0, 3 do
|
||||
d += r(k, q) * r(k - 1, q)
|
||||
end
|
||||
worst = math.min(worst, d)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(worst >= math.cos(math.rad(45)) - 1e-6, "full rotations: subdivided (worst dot " .. worst .. ")")
|
||||
end
|
||||
-- round trip through our writer (.dae, and .zae for a few)
|
||||
local tri = decode(c.data, { files = c.files })
|
||||
decoded[i] = tri
|
||||
local files = {}
|
||||
local out, eerr = Dae.encode(tri, { files = files, name = "rt.dae" })
|
||||
t:check(out, c.name .. ": encode: " .. tostring(eerr))
|
||||
if out then
|
||||
local back, berr = decode(out, { files = files })
|
||||
t:check(back, c.name .. ": re-decode: " .. tostring(berr))
|
||||
if back then
|
||||
local p1, f1 = counts(tri)
|
||||
local p2, f2 = counts(back)
|
||||
t:eq(p2, p1, c.name .. ": round trip meshes")
|
||||
t:eq(f2, f1, c.name .. ": round trip faces")
|
||||
local lo1, hi1 = MeshOps.bounds(tri)
|
||||
local lo2, hi2 = MeshOps.bounds(back)
|
||||
t:check((lo1 == nil and lo2 == nil) or (lo1 and lo2 and nearV(lo2, lo1, 1e-5) and nearV(hi2 :: any, hi1 :: any, 1e-5)), c.name .. ": round trip bounds")
|
||||
t:eq(#back.materials, #tri.materials, c.name .. ": round trip materials")
|
||||
t:eq(#back.cameras, #tri.cameras, c.name .. ": round trip cameras")
|
||||
t:eq(#back.lights, #tri.lights, c.name .. ": round trip lights")
|
||||
t:eq(#back.textures, #tri.textures, c.name .. ": round trip textures")
|
||||
for ti, tex in tri.textures do
|
||||
local bt = back.textures[ti]
|
||||
if tex.data and bt then
|
||||
t:check(bt.data and buffer.tostring(bt.data) == buffer.tostring(tex.data), c.name .. ": round trip texture " .. ti)
|
||||
end
|
||||
end
|
||||
for mi, m in tri.materials do
|
||||
local bm = back.materials[mi]
|
||||
t:check(bm and nearV(bm.baseColor, m.baseColor, 1e-6), c.name .. ": round trip baseColor " .. mi)
|
||||
end
|
||||
checked.roundTrips += 1
|
||||
end
|
||||
end
|
||||
if #c.data < 20000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
|
||||
-- assimp reads what we wrote like the source
|
||||
for _, x in Xcheck do
|
||||
local src = decoded[x.case]
|
||||
local ref = x.assimp
|
||||
t:check(ref and not ref.failed, x.name .. ": assimp reads our file")
|
||||
if src and ref and not ref.failed then
|
||||
local prims, faces = counts(src)
|
||||
if prims > 0 then
|
||||
t:eq(ref.meshes, prims, x.name .. ": meshes (assimp, ours)")
|
||||
t:eq(ref.faces, faces, x.name .. ": faces (assimp, ours)")
|
||||
local lo, hi = assimpBounds(src, true) -- our writer bakes the bind shape (it writes no skins)
|
||||
t:check(lo and nearV(lo, ref.min, 2e-4) and nearV(hi :: any, ref.max, 2e-4), string.format("%s: bounds %s %s, assimp %s %s", x.name, fmt(lo), fmt(hi), fmt(ref.min), fmt(ref.max)))
|
||||
end
|
||||
t:eq(ref.cameras, #src.cameras, x.name .. ": cameras (assimp, ours)")
|
||||
t:eq(ref.lights, #src.lights, x.name .. ": lights (assimp, ours)")
|
||||
checked.xcheck += 1
|
||||
end
|
||||
end
|
||||
|
||||
-- polygons: kept or fan-triangulated
|
||||
local function case(name: string): any
|
||||
for i, c in Cases do
|
||||
if string.find(c.name, name, 1, true) then
|
||||
return c, i
|
||||
end
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
do
|
||||
local c = case("ConcavePolygon")
|
||||
if c then
|
||||
local s = decode(c.data, { triangulate = false })
|
||||
local p = s.meshes[1].primitives[1]
|
||||
t:eq(p.mode, "polygons", "polygons kept")
|
||||
local corners = 0
|
||||
local get = Scene.reader(p.faces) :: any
|
||||
for k = 0, p.faces.count - 1 do
|
||||
corners += get(k, 0) - 2
|
||||
end
|
||||
local s2 = decode(c.data)
|
||||
t:eq(s2.meshes[1].primitives[1].mode, "triangles", "polygons triangulated")
|
||||
t:eq(s2.meshes[1].primitives[1].indices.count // 3, corners, "fan triangle count")
|
||||
local tri = MeshOps.triangulate(p)
|
||||
t:check(tri and tri.indices.count // 3 == corners, "MeshOps ear-clips the kept polygon")
|
||||
end
|
||||
end
|
||||
|
||||
-- materials and textures (duck: blinn, a TGA diffuse texture; decoded at the api layer)
|
||||
do
|
||||
local c = case("assimp/duck.dae")
|
||||
if c then
|
||||
local s = decode(c.data, { files = c.files })
|
||||
local m = s.materials[1]
|
||||
local ti = m.baseColorTexture and m.baseColorTexture.texture
|
||||
local tex = ti and s.textures[ti]
|
||||
t:check(tex and tex.data, "duck: diffuse texture bytes")
|
||||
t:eq(tex and tex.mime, "image/tga", "duck: texture mime")
|
||||
t:check(m.extras.phong.model == "blinn" and type(m.extras.phong.shininess) == "number", "duck: phong extras")
|
||||
local _, errs = F.model.loadTextures(s)
|
||||
t:check(tex and tex.image and tex.image.width > 0 and errs[ti :: number] == nil, "duck: texture decoded lazily")
|
||||
-- without the image files: the uri stays, no data
|
||||
local s2 = decode(c.data)
|
||||
t:check(ti and s2.textures[ti].data == nil and s2.textures[ti].uri == "./duckCM.tga", "duck: uri without files")
|
||||
local cam = s.cameras[1]
|
||||
t:check(cam.type == "perspective" and cam.yfov > 0 and cam.yfov < math.pi, "duck: camera")
|
||||
t:eq(s.meta.up, "y", "duck: up axis")
|
||||
end
|
||||
local z = case("assimp/duck.zae")
|
||||
if z then
|
||||
local s = decode(z.data)
|
||||
t:check(s.textures[1] and s.textures[1].data, "zae: texture read from the zip")
|
||||
t:check(Dae.sniff(Bytes.reader(buffer.fromstring(z.data))) > 0.9, "zae sniff")
|
||||
local zb = Dae.encode(s, { format = "zae" })
|
||||
local back = zb and decode(zb)
|
||||
t:check(back and back.textures[1] and back.textures[1].data and buffer.len(back.textures[1].data) == buffer.len(s.textures[1].data), "zae round trip with the texture")
|
||||
end
|
||||
local l = case("assimp/lights.dae")
|
||||
if l then
|
||||
local s = decode(l.data)
|
||||
local kinds = {}
|
||||
for _, li in s.lights do
|
||||
kinds[li.type] = (kinds[li.type] or 0) + 1
|
||||
end
|
||||
t:check(kinds.point == 2 and kinds.directional == 1 and kinds.spot == 1, "lights: kinds")
|
||||
t:eq(lightCount(s) - #s.lights, 1, "lights: one ambient")
|
||||
end
|
||||
local u = case("cube_UTF16LE")
|
||||
if u then
|
||||
t:eq(Dae.sniff(Bytes.reader(buffer.fromstring(u.data))), 1, "UTF-16 sniff")
|
||||
end
|
||||
local k = case("kwxport")
|
||||
if k then
|
||||
local s = decode(k.data)
|
||||
t:check(s.meta.up == "z" and near(s.meta.unit, 0.0254, 1e-9), "kwxport: Z_UP, inches")
|
||||
t:check(s.meshes[1].primitives[1].attributes.COLOR_0 ~= nil, "kwxport: vertex colours")
|
||||
end
|
||||
local uv2 = case("cube_with_2UVs")
|
||||
if uv2 then
|
||||
local s = decode(uv2.data)
|
||||
local a = s.meshes[1].primitives[1].attributes
|
||||
t:check(a.TEXCOORD_0 and a.TEXCOORD_1, "2 UV sets")
|
||||
end
|
||||
local clips = case("library_animation_clips")
|
||||
if clips then
|
||||
local s = decode(clips.data)
|
||||
t:check(#s.animations == 2 and s.animations[1].name ~= nil, "animation clips named")
|
||||
t:check(#s.skins >= 1 and s.skins[1].inverseBindMatrices ~= nil, "clips: skin with inverse bind matrices")
|
||||
local p = s.meshes[s.nodes[(function()
|
||||
for i, n in s.nodes do
|
||||
if n.skin then
|
||||
return i
|
||||
end
|
||||
end
|
||||
return 1
|
||||
end)()].mesh].primitives[1]
|
||||
local w = Scene.reader(p.attributes.WEIGHTS_0) :: any
|
||||
local okSum = true
|
||||
for v = 0, p.attributes.WEIGHTS_0.count - 1 do
|
||||
local sum = w(v, 0) + w(v, 1) + w(v, 2) + w(v, 3)
|
||||
if sum > 0 and math.abs(sum - 1) > 1e-5 then
|
||||
okSum = false
|
||||
end
|
||||
end
|
||||
t:check(okSum, "clips: weights normalized")
|
||||
end
|
||||
end
|
||||
|
||||
-- api: F.load by content / extension
|
||||
do
|
||||
local c = case("cube_tristrips")
|
||||
if c then
|
||||
local s, err = F.load(c.data)
|
||||
t:check(s and s.meta.source.format == "dae", "F.load: " .. tostring(err))
|
||||
local out = F.save(s, nil, { format = "dae" })
|
||||
t:check(out and string.find(buffer.tostring(out), "<COLLADA", 1, true), "F.save dae")
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e1 = decode('<?xml version="1.0"?><root/>')
|
||||
t:check(e1 and e1.code == Err.CORRUPT, "not COLLADA: CORRUPT")
|
||||
local _, e2 = decode('<COLLADA version="1.4.1"><library_geometries>')
|
||||
t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "unclosed XML")
|
||||
local bad = [[<COLLADA version="1.4.1"><library_geometries><geometry id="g"><mesh>
|
||||
<source id="p"><float_array id="pa" count="3">0 0 0</float_array><technique_common><accessor source="#pa" count="1" stride="3"><param name="X" type="float"/><param name="Y" type="float"/><param name="Z" type="float"/></accessor></technique_common></source>
|
||||
<vertices id="v"><input semantic="POSITION" source="#p"/></vertices><triangles count="1"><input semantic="VERTEX" source="#v" offset="0"/><p>0 0 7</p></triangles></mesh></geometry></library_geometries>
|
||||
<library_visual_scenes><visual_scene id="s"><node id="n"><instance_geometry url="#g"/></node></visual_scene></library_visual_scenes><scene><instance_visual_scene url="#s"/></scene></COLLADA>]]
|
||||
local _, e3 = decode(bad)
|
||||
t:check(e3 and e3.code == Err.CORRUPT, "index out of range: CORRUPT")
|
||||
local _, e4 = decode(string.gsub(bad, "0 0 7", "0 0 0"), { maxVertices = 0 })
|
||||
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: LIMIT")
|
||||
local ok = decode((string.gsub(bad, "0 0 7", "0 0 0")))
|
||||
t:check(ok and #ok.meshes == 1 and ok.meshes[1].primitives[1].attributes.POSITION.count == 1, "minimal file")
|
||||
local _, e5 = Dae.encode({} :: any)
|
||||
t:check(e5 and e5.code == Err.ARG, "encode: ARG")
|
||||
t:eq(Dae.sniff(Bytes.reader(buffer.fromstring("<svg/>"))), 0, "sniff: other XML")
|
||||
table.insert(samples, (string.gsub(bad, "0 0 7", "0 0 0")))
|
||||
end
|
||||
|
||||
t:note("%d cases: %d against assimp (%d bounds), %d against their glTF originals (%d animation keys), %d round trips", #Cases, checked.assimp, checked.bounds, checked.gltf, checked.keys, checked.roundTrips)
|
||||
t:note("%d of our files read back by assimp like the sources", checked.xcheck)
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Dae.decode(Bytes.reader(b))
|
||||
end, samples)
|
||||
t:done()
|
||||
@@ -0,0 +1,542 @@
|
||||
-- model/fbx tests: assimp's FBX test models (binary 7.4 / 7.5, ASCII 7.4 - 7.7, embedded textures, skeletons,
|
||||
-- animation), Blender's exporter (materials, textures, colours, skin, shape keys, animation, camera, lights) and
|
||||
-- assimp's exporters (binary and ASCII), against assimp (meshes, polygons, vertices, world bounds, materials,
|
||||
-- animations, cameras, lights) and Blender's importer (meshes, polygons, materials, bones, shape keys, cameras,
|
||||
-- lights, images); round trips through our writer (binary and ASCII) and glTF sample models through FBX (world
|
||||
-- triangles, materials, textures, skins, morph targets, sampled animation, cameras, lights); assimp and Blender
|
||||
-- reading our files like the originals (fbx_xcheck); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/fbx.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Fbx = require("@formats/model/fbx")
|
||||
local Gltf = require("@formats/model/gltf")
|
||||
local MeshOps = require("@formats/ops/MeshOps")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/fbx_cases")
|
||||
local Xcheck = require("@tests/gen/fbx_xcheck")
|
||||
local GltfCases = require("@tests/gen/fbx_gltf")
|
||||
|
||||
local t = T.suite("fbx")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Fbx.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(Fbx.name, "fbx", "name")
|
||||
t:eq(Fbx.category, "model", "category")
|
||||
t:check(Fbx.caps.decode and Fbx.caps.encode, "contract")
|
||||
|
||||
local function near(a: number, b: number, eps: number): boolean
|
||||
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
|
||||
end
|
||||
|
||||
local function triArea(prim: any): number
|
||||
local pos, ind = prim.attributes.POSITION, prim.indices
|
||||
if not ind then
|
||||
return 0
|
||||
end
|
||||
local area = 0
|
||||
local function P(i: number, k: number): number
|
||||
return buffer.readf32(pos.data, (i * 3 + k) * 4)
|
||||
end
|
||||
for tri = 0, ind.count // 3 - 1 do
|
||||
local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8)
|
||||
local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) }
|
||||
local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) }
|
||||
local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]
|
||||
area += math.sqrt(x * x + y * y + z * z) / 2
|
||||
end
|
||||
return area
|
||||
end
|
||||
|
||||
-- assimp-like counts: placed primitives, polygons, corners
|
||||
local function counts(scene: any): (number, number, number)
|
||||
local prims, faces, verts = 0, 0, 0
|
||||
local seen = {}
|
||||
for _, pl in Types.Scene.flatten(scene) do
|
||||
if not seen[pl.primitive] then
|
||||
seen[pl.primitive] = true
|
||||
prims += 1
|
||||
faces += if pl.primitive.faces then pl.primitive.faces.count else pl.primitive.indices.count // 3
|
||||
verts += pl.primitive.attributes.POSITION.count
|
||||
end
|
||||
end
|
||||
return prims, faces, verts
|
||||
end
|
||||
|
||||
local function noMaterial(scene: any): boolean
|
||||
for _, m in scene.meshes do
|
||||
for _, p in m.primitives do
|
||||
if p.material == nil then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function stats(scene: any): { [string]: number }
|
||||
local s = { meshNodes = 0, limbs = 0, shapes = 0, textures = #scene.textures, cameras = #scene.cameras, lights = #scene.lights }
|
||||
for _, n in scene.nodes do
|
||||
if n.mesh then
|
||||
s.meshNodes += 1
|
||||
end
|
||||
if n.extras and n.extras.fbx and n.extras.fbx.type == "LimbNode" then
|
||||
s.limbs += 1
|
||||
end
|
||||
end
|
||||
for _, m in scene.meshes do
|
||||
s.shapes += if m.weights then #m.weights else 0
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
-- world bounds, also under assimp's Z-up -> Y-up root conversion (x, z, -y)
|
||||
local function boundsMatch(lo: { number }, hi: { number }, want: any, eps: number): boolean
|
||||
local function eq(a: { number }, b: { number }, c: { number }, d: { number }): boolean
|
||||
for k = 1, 3 do
|
||||
if not near(a[k], c[k], eps) or not near(b[k], d[k], eps) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
if eq(lo, hi, want.min, want.max) then
|
||||
return true
|
||||
end
|
||||
return eq({ lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] }, want.min, want.max)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ reference files
|
||||
local checked = { assimp = 0, blender = 0, roundTrips = 0, failed = 0 }
|
||||
local scenes = {}
|
||||
for i, c in Cases do
|
||||
local scene, err = decode(c.data, { files = c.files, triangulate = false })
|
||||
local a = c.assimp
|
||||
if a.failed then
|
||||
t:check(scene == nil and err ~= nil, c.name .. ": assimp rejects it, so do we")
|
||||
checked.failed += 1
|
||||
else
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
scenes[i] = scene
|
||||
local prims, faces, verts = counts(scene)
|
||||
t:eq(prims, a.meshes, c.name .. ": meshes (assimp)")
|
||||
t:eq(faces, a.faces, c.name .. ": polygons (assimp)")
|
||||
t:eq(verts, a.vertices, c.name .. ": vertices (assimp)")
|
||||
t:eq(#scene.cameras, a.cameras, c.name .. ": cameras (assimp)")
|
||||
t:eq(#scene.lights, a.lights, c.name .. ": lights (assimp)")
|
||||
t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)")
|
||||
t:eq(#scene.materials + (if noMaterial(scene) then 1 else 0), a.materials, c.name .. ": materials (assimp, + its default)")
|
||||
if a.min then
|
||||
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
|
||||
t:check(lo and boundsMatch(lo, hi, a, 1e-3), string.format("%s: world bounds (assimp) %s %s", c.name, if lo then table.concat(lo, " ") else "-", if hi then table.concat(hi, " ") else "-"))
|
||||
end
|
||||
checked.assimp += 1
|
||||
local b = c.blender
|
||||
if b and not b.failed then
|
||||
local s = stats(scene)
|
||||
t:eq(s.meshNodes, b.meshes, c.name .. ": mesh objects (Blender)")
|
||||
t:eq(faces, b.polygons, c.name .. ": polygons (Blender)")
|
||||
t:eq(#scene.materials, b.materials, c.name .. ": materials (Blender)")
|
||||
t:eq(s.limbs, b.bones, c.name .. ": bones (Blender)")
|
||||
t:eq(s.shapes, b.shapeKeys, c.name .. ": shape keys (Blender)")
|
||||
t:eq(s.cameras, b.cameras, c.name .. ": cameras (Blender)")
|
||||
t:eq(s.lights, b.lights, c.name .. ": lights (Blender)")
|
||||
t:eq(s.textures, b.images, c.name .. ": textures (Blender)")
|
||||
t:check((#scene.animations > 0) == (b.actions > 0), c.name .. ": animated (Blender)")
|
||||
checked.blender += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d files: %d against assimp, %d against Blender, %d rejected by both", #Cases, checked.assimp, checked.blender, checked.failed)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ round trips
|
||||
-- world triangles (area, count, bounds), materials, textures, skins, morph targets, animation samples, cameras, lights
|
||||
local function compare(a: any, b: any, label: string, eps: number)
|
||||
local ma, mb = MeshOps.merge(a), MeshOps.merge(b)
|
||||
local na = if ma and ma.indices then ma.indices.count // 3 else 0
|
||||
local nb = if mb and mb.indices then mb.indices.count // 3 else 0
|
||||
t:eq(nb, na, label .. ": triangles")
|
||||
if na > 0 and nb > 0 then
|
||||
t:check(near(triArea(ma), triArea(mb), eps), string.format("%s: area %.7g / %.7g", label, triArea(ma), triArea(mb)))
|
||||
local la, ha = MeshOps.bounds(ma)
|
||||
local lb, hb = MeshOps.bounds(mb)
|
||||
local ok = true
|
||||
for k = 1, 3 do
|
||||
ok = ok and near(la[k], lb[k], eps) and near(ha[k], hb[k], eps)
|
||||
end
|
||||
t:check(ok, label .. ": bounds")
|
||||
end
|
||||
t:eq(#b.materials, #a.materials, label .. ": materials")
|
||||
for k, m in a.materials do
|
||||
local m2 = b.materials[k]
|
||||
if m2 then
|
||||
local ok = true
|
||||
for q = 1, 4 do
|
||||
ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6)
|
||||
end
|
||||
t:check(ok, label .. ": material " .. k .. " colour")
|
||||
t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture")
|
||||
end
|
||||
end
|
||||
t:eq(#b.textures, #a.textures, label .. ": textures")
|
||||
for k, tex in a.textures do
|
||||
local t2 = b.textures[k]
|
||||
if tex.data and t2 then
|
||||
t:check(t2.data and buffer.tostring(t2.data) == buffer.tostring(tex.data), label .. ": texture " .. k .. " bytes")
|
||||
end
|
||||
end
|
||||
t:eq(#b.skins, #a.skins, label .. ": skins")
|
||||
for k, s in a.skins do
|
||||
local s2 = b.skins[k]
|
||||
if s2 then
|
||||
t:eq(#s2.joints, #s.joints, label .. ": skin joints")
|
||||
end
|
||||
end
|
||||
local function targets(s: any): number
|
||||
local n = 0
|
||||
for _, m in s.meshes do
|
||||
n += if m.weights then #m.weights else 0
|
||||
end
|
||||
return n
|
||||
end
|
||||
t:eq(targets(b), targets(a), label .. ": morph targets")
|
||||
t:eq(#b.cameras, #a.cameras, label .. ": cameras")
|
||||
t:eq(#b.lights, #a.lights, label .. ": lights")
|
||||
-- cameras / lights: the same world placement (forward axis included)
|
||||
local function placed(s: any, field: string): { { number } }
|
||||
local out = {}
|
||||
local function visit(i: number, parent: { number }, seen: { [number]: boolean })
|
||||
if seen[i] then
|
||||
return
|
||||
end
|
||||
seen[i] = true
|
||||
local n = s.nodes[i]
|
||||
local w = Types.Scene.mul(parent, Types.Scene.nodeMatrix(n))
|
||||
if n[field] then
|
||||
out[n[field]] = w
|
||||
end
|
||||
for _, c in n.children do
|
||||
visit(c, w, seen)
|
||||
end
|
||||
end
|
||||
local seen = {}
|
||||
for _, r in s.roots do
|
||||
visit(r, Types.Scene.IDENTITY, seen)
|
||||
end
|
||||
return out
|
||||
end
|
||||
for _, field in { "camera", "light" } do
|
||||
local pa, pb = placed(a, field), placed(b, field)
|
||||
for k, w in pa do
|
||||
local w2 = pb[k]
|
||||
local ok = w2 ~= nil
|
||||
if w2 then
|
||||
for q = 1, 16 do
|
||||
ok = ok and math.abs(w[q] - w2[q]) <= eps * math.max(1, math.abs(w[q]))
|
||||
end
|
||||
end
|
||||
t:check(ok, label .. ": " .. field .. " " .. k .. " world matrix")
|
||||
end
|
||||
end
|
||||
-- animations: every channel of b sampled against a (LINEAR / STEP / CUBICSPLINE values at the keys of b)
|
||||
t:eq(#b.animations, #a.animations, label .. ": animations")
|
||||
local function evalCh(ch: any, time: number, comps: number): { number }
|
||||
local IN, OUT = Types.Scene.reader(ch.input) :: any, Types.Scene.reader(ch.output) :: any
|
||||
local n = ch.input.count
|
||||
local cubic = ch.interpolation == "CUBICSPLINE"
|
||||
local function v(k: number): { number }
|
||||
local e = if cubic then k * 3 + 1 else k
|
||||
local r = {}
|
||||
for q = 0, comps - 1 do
|
||||
r[q + 1] = OUT(e, q)
|
||||
end
|
||||
return r
|
||||
end
|
||||
if time <= IN(0, 0) then
|
||||
return v(0)
|
||||
end
|
||||
for k = 0, n - 2 do
|
||||
local t0, t1 = IN(k, 0), IN(k + 1, 0)
|
||||
if time <= t1 then
|
||||
if ch.interpolation == "STEP" or t1 <= t0 then
|
||||
return if time >= t1 then v(k + 1) else v(k)
|
||||
end
|
||||
local u = (time - t0) / (t1 - t0)
|
||||
local a0, a1 = v(k), v(k + 1)
|
||||
if comps == 4 and ch.path == "rotation" and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then
|
||||
a1 = { -a1[1], -a1[2], -a1[3], -a1[4] }
|
||||
end
|
||||
local r = {}
|
||||
for q = 1, comps do
|
||||
r[q] = a0[q] + (a1[q] - a0[q]) * u
|
||||
end
|
||||
return r
|
||||
end
|
||||
end
|
||||
return v(n - 1)
|
||||
end
|
||||
for ai, an in a.animations do
|
||||
local bn = b.animations[ai]
|
||||
if bn then
|
||||
-- channels by node name + path
|
||||
local byKey = {}
|
||||
for _, ch in an.channels do
|
||||
byKey[(a.nodes[ch.node].name or "") .. "/" .. ch.path] = ch
|
||||
end
|
||||
local bad, n = 0, 0
|
||||
for _, ch in bn.channels do
|
||||
local key = (b.nodes[ch.node].name or "") .. "/" .. ch.path
|
||||
local orig = byKey[key]
|
||||
local comps = if ch.path == "rotation" then 4 elseif ch.path == "weights" then ch.output.count // ch.input.count else 3
|
||||
if orig then
|
||||
local IN = Types.Scene.reader(ch.input) :: any
|
||||
for k = 0, ch.input.count - 1 do
|
||||
local time = IN(k, 0)
|
||||
local want = evalCh(orig, time, comps)
|
||||
local got = evalCh(ch, time, comps)
|
||||
local dot = 0
|
||||
for q = 1, comps do
|
||||
dot += want[q] * got[q]
|
||||
end
|
||||
local sign = if ch.path == "rotation" and dot < 0 then -1 else 1
|
||||
for q = 1, comps do
|
||||
if math.abs(got[q] * sign - want[q]) > 1e-3 * math.max(1, math.abs(want[q])) then
|
||||
bad += 1
|
||||
end
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(bad == 0, string.format("%s: animation %d: %d of %d samples differ", label, ai, bad, n))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local scene = scenes[i]
|
||||
if scene then
|
||||
for _, ascii in { false, true } do
|
||||
local out, err = Fbx.encode(scene, { ascii = ascii })
|
||||
t:check(out, c.name .. ": encode: " .. tostring(err))
|
||||
local back, berr = decode(out :: buffer, { triangulate = false })
|
||||
t:check(back, c.name .. ": decode ours: " .. tostring(berr))
|
||||
if back then
|
||||
compare(scene, back, c.name .. (if ascii then " (ascii)" else ""), 1e-5)
|
||||
t:eq(#back.nodes, #scene.nodes, c.name .. ": nodes")
|
||||
local p1, f1, v1 = counts(scene)
|
||||
local p2, f2, v2 = counts(back)
|
||||
t:check(p1 == p2 and f1 == f2 and v1 == v2, c.name .. ": polygons kept")
|
||||
end
|
||||
end
|
||||
checked.roundTrips += 1
|
||||
end
|
||||
end
|
||||
|
||||
-- glTF sample models through FBX
|
||||
local ng = 0
|
||||
for _, g in GltfCases do
|
||||
local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files })
|
||||
t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr))
|
||||
if scene then
|
||||
local out, err = Fbx.encode(scene)
|
||||
t:check(out, g.name .. ": encode: " .. tostring(err))
|
||||
local back, berr = decode(out :: buffer)
|
||||
t:check(back, g.name .. ": decode ours: " .. tostring(berr))
|
||||
if back then
|
||||
-- glTF points / lines are not written
|
||||
local lines = false
|
||||
for _, m in scene.meshes do
|
||||
for _, p in m.primitives do
|
||||
if p.mode == "points" or p.mode == "lines" or p.mode == "line_strip" or p.mode == "line_loop" then
|
||||
lines = true
|
||||
end
|
||||
end
|
||||
end
|
||||
if not lines then
|
||||
compare(scene, back, "glTF " .. g.name, 2e-5)
|
||||
end
|
||||
ng += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d round trips of the reference files (binary + ASCII), %d glTF models through FBX", checked.roundTrips, ng)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ cross-check
|
||||
-- assimp and Blender read our files like the originals
|
||||
local nx = 0
|
||||
for _, x in Xcheck do
|
||||
local c = Cases[x.case]
|
||||
local a, ca = x.assimp, c.assimp
|
||||
local scene = scenes[x.case]
|
||||
if not ca.failed and scene then
|
||||
local _, faces = counts(scene)
|
||||
t:check(not a.failed, x.name .. ": assimp reads our file")
|
||||
t:eq(a.meshes, ca.meshes, x.name .. ": assimp meshes of our file (" .. c.name .. ")")
|
||||
t:eq(a.faces, faces, x.name .. ": assimp polygons of our file (" .. c.name .. ")")
|
||||
t:eq(a.cameras, ca.cameras, x.name .. ": assimp cameras of our file")
|
||||
t:eq(a.lights, ca.lights, x.name .. ": assimp lights of our file")
|
||||
t:eq(a.animations, ca.animations, x.name .. ": assimp animations of our file")
|
||||
t:eq(a.bones, ca.bones, x.name .. ": assimp bones of our file")
|
||||
if a.min and ca.min then
|
||||
local ok = true
|
||||
for k = 1, 3 do
|
||||
ok = ok and near(a.min[k], ca.min[k], 1e-4) and near(a.max[k], ca.max[k], 1e-4)
|
||||
end
|
||||
t:check(ok, x.name .. ": assimp world bounds of our file (" .. c.name .. ")")
|
||||
end
|
||||
local b, cb = x.blender, c.blender
|
||||
if b and cb and not cb.failed then
|
||||
t:check(not b.failed, x.name .. ": Blender reads our file: " .. tostring(b.failed))
|
||||
if not b.failed then
|
||||
for _, k in { "meshes", "polygons", "materials", "bones", "shapeKeys", "cameras", "lights", "images" } do
|
||||
t:eq(b[k], cb[k], x.name .. ": Blender " .. k .. " of our file (" .. c.name .. ")")
|
||||
end
|
||||
t:check((b.actions > 0) == (cb.actions > 0), x.name .. ": Blender actions of our file")
|
||||
end
|
||||
end
|
||||
nx += 1
|
||||
end
|
||||
end
|
||||
t:note("%d of our files read back by assimp / Blender like the originals", nx)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ details
|
||||
do
|
||||
local byName = {}
|
||||
for i, c in Cases do
|
||||
byName[c.name] = scenes[i]
|
||||
end
|
||||
local cube = byName["blender/blender_cube.fbx"]
|
||||
if cube then
|
||||
local tex = cube.textures[1]
|
||||
t:check(tex and tex.data and tex.mime == "image/png", "Blender cube: embedded PNG kept encoded")
|
||||
local _, errs = F.model.loadTextures(cube)
|
||||
t:check(tex.image and tex.image.width == 8 and next(errs) == nil, "F.model.loadTextures decodes the embedded PNG")
|
||||
local red = cube.materials[1]
|
||||
t:check(red.name == "Red" and red.baseColorTexture and red.extras.fbx.shadingModel ~= nil, "material with a texture + Phong extras")
|
||||
local prim = cube.meshes[1].primitives[1]
|
||||
t:check(prim.attributes.COLOR_0 and prim.attributes.TEXCOORD_0 and prim.attributes.NORMAL, "colours, uvs, normals")
|
||||
t:eq(cube.meta.up, "y", "Blender writes Y up")
|
||||
t:check(near(cube.meta.unit, 0.01, 1e-9), "unit: centimetres")
|
||||
end
|
||||
local skin = byName["blender/blender_skin.fbx"]
|
||||
if skin then
|
||||
local m = skin.meshes[1]
|
||||
local p = m.primitives[1]
|
||||
t:check(#skin.skins == 1 and #skin.skins[1].joints == 2 and p.attributes.JOINTS_0 and p.attributes.WEIGHTS_0, "skin: joints and weights")
|
||||
t:check(m.weights and #m.weights == 1 and m.weights[1] >= 0 and m.weights[1] <= 1 and p.targets and p.targets[1].POSITION, "shape key: a morph target and its weight")
|
||||
local paths = {}
|
||||
for _, ch in skin.animations[1].channels do
|
||||
paths[ch.path] = true
|
||||
end
|
||||
t:check(paths.rotation and paths.weights, "animation: rotation and morph weights channels")
|
||||
-- weights sum to 1
|
||||
local W = Types.Scene.reader(p.attributes.WEIGHTS_0) :: any
|
||||
local ok = true
|
||||
for v = 0, p.attributes.WEIGHTS_0.count - 1 do
|
||||
local s = W(v, 0) + W(v, 1) + W(v, 2) + W(v, 3)
|
||||
ok = ok and (math.abs(s - 1) < 1e-5 or s == 0)
|
||||
end
|
||||
t:check(ok, "skin weights normalized")
|
||||
end
|
||||
local cl = byName["blender/blender_camlight.fbx"]
|
||||
if cl then
|
||||
local types = {}
|
||||
for _, l in cl.lights do
|
||||
types[l.type] = true
|
||||
end
|
||||
t:check(types.point and types.directional and types.spot, "point, directional, spot lights")
|
||||
local cam = cl.cameras[1]
|
||||
-- Blender's 35 mm lens on a 36 mm sensor, 16:9 render
|
||||
t:check(cam.type == "perspective" and cam.yfov > 0.3 and cam.yfov < 1.2, "camera fov " .. cam.yfov)
|
||||
end
|
||||
local pbr = byName["assimp/maxPbrMaterial_metalRough.fbx"]
|
||||
if pbr then
|
||||
local m = pbr.materials[1]
|
||||
t:check(near(m.metallic, 0.25, 1e-6) and near(m.roughness, 0.5, 1e-6), "3ds Max PBR material: metalness / roughness")
|
||||
end
|
||||
local emb = byName["assimp/embedded_ascii/box.FBX"]
|
||||
if emb then
|
||||
t:check(emb.textures[1] and emb.textures[1].data and emb.meta.source.binary == false, "ASCII: base64 embedded texture")
|
||||
t:eq(emb.meta.up, "z", "3ds Max: Z up")
|
||||
end
|
||||
-- polygons kept / triangulated
|
||||
local box = decode(Cases[2].data)
|
||||
t:check(box.meshes[1].primitives[1].mode == "triangles", "triangulated by default")
|
||||
-- through the api
|
||||
local s = F.load(Cases[2].data)
|
||||
t:check(s and s.kind == "scene" and s.meta.source.format == "fbx", "F.load detects binary FBX")
|
||||
local viaApi = F.save(s, nil, { format = "fbx" })
|
||||
t:check(viaApi and buffer.readstring(viaApi, 0, 18) == "Kaydara FBX Binary", "F.save format fbx")
|
||||
-- a 7.5 (64-bit records) file
|
||||
local v75 = Fbx.encode(s, { version = 7500 }) :: buffer
|
||||
local b75 = decode(v75)
|
||||
t:check(b75 and b75.meta.source.version == 7500 and #b75.meshes == #s.meshes, "7.5 records")
|
||||
-- a scene made by hand: a quad as polygons, written and read back as one polygon
|
||||
local p = Types.Scene.accessor(nil, "f32", 3, 4)
|
||||
for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } } do
|
||||
for k = 1, 3 do
|
||||
buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k])
|
||||
end
|
||||
end
|
||||
local faces = Types.Scene.accessor(nil, "u32", 1, 1)
|
||||
buffer.writeu32(faces.data, 0, 4)
|
||||
local ind = Types.Scene.accessor(nil, "u32", 1, 4)
|
||||
for k = 0, 3 do
|
||||
buffer.writeu32(ind.data, k * 4, k)
|
||||
end
|
||||
local quad = Types.Scene.fromPrimitive({ attributes = { POSITION = p }, indices = ind, faces = faces, mode = "polygons" }, "quad")
|
||||
local qb = decode(Fbx.encode(quad) :: buffer, { triangulate = false })
|
||||
t:check(qb and qb.meshes[1].primitives[1].faces.count == 1 and qb.meshes[1].primitives[1].indices.count == 4, "a quad stays one polygon")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ errors
|
||||
do
|
||||
local _, e1 = decode("; FBX 6.1.0 project file\nFBXHeaderExtension: {\n\tFBXVersion: 6100\n}\n")
|
||||
t:check(e1 and e1.code == Err.UNSUPPORTED, "FBX 6: " .. tostring(e1))
|
||||
local bin = Cases[2].data
|
||||
local _, e2 = decode(string.sub(bin, 1, 200))
|
||||
t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "truncated: " .. tostring(e2))
|
||||
local _, e3 = decode(string.sub(bin, 1, 23) .. "\100\25\0\0" .. string.sub(bin, 28))
|
||||
t:check(e3 and e3.code == Err.UNSUPPORTED, "binary version 6500: " .. tostring(e3))
|
||||
local _, e4 = decode("FBXHeaderExtension: { FBXVersion: 7400 }\nObjects: {")
|
||||
t:check(e4 and e4.code == Err.CORRUPT, "unterminated ASCII: " .. tostring(e4))
|
||||
local _, e5 = decode("FBXHeaderExtension: { FBXVersion: 7400 }\n")
|
||||
t:check(e5 and e5.code == Err.CORRUPT, "no Objects: " .. tostring(e5))
|
||||
local _, e6 = decode(bin, { maxBytes = 100 })
|
||||
t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6))
|
||||
local _, e7 = Fbx.encode({} :: any)
|
||||
t:check(e7 and e7.code == Err.ARG, "encode junk")
|
||||
local _, e8 = Fbx.encode(Types.Scene.new(), { version = 6100 })
|
||||
t:check(e8 and e8.code == Err.ARG, "encode version 6100")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for i, c in Cases do
|
||||
if #c.data < 60000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
local s = scenes[i]
|
||||
if s and #samples < 24 then
|
||||
local a = Fbx.encode(s, { ascii = true })
|
||||
if a and buffer.len(a) < 60000 then
|
||||
table.insert(samples, buffer.tostring(a))
|
||||
end
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local s = Fbx.decode(Bytes.reader(b))
|
||||
if s then
|
||||
Fbx.encode(s)
|
||||
MeshOps.merge(s)
|
||||
end
|
||||
return s
|
||||
end, samples, { mutations = 12, keepHeader = 27 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,547 @@
|
||||
-- model/usda tests: stages authored with OpenUSD's API (every xform op kind / order, pivots, resetXformStack,
|
||||
-- primvar interpolations, holes, leftHanded, n-gons, UsdPreviewSurface networks, GeomSubsets, inherited bindings,
|
||||
-- cameras, lights, time samples, a USDZ package, a USDC file), a hand-written grammar test, assimp's USD models
|
||||
-- (usda + usdc converted by Sdf), Blender 5 exports of glTF samples - all against OpenUSD (pxr: world transforms,
|
||||
-- triangles, area and bounds per mesh, bound materials, PreviewSurface inputs and textures, cameras, lights, xform time
|
||||
-- samples); OpenUSD's schema layers parse-only (prim spec counts); round trips through our writer (stable text) and
|
||||
-- pxr reading our output (usda_xcheck); the api; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/usda.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Usda = require("@formats/model/usda")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/usda_cases")
|
||||
local Specs = require("@tests/gen/usda_specs")
|
||||
local Xcheck = require("@tests/gen/usda_xcheck")
|
||||
|
||||
local t = T.suite("usda")
|
||||
local Scene = Types.Scene
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Usda.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(Usda.name, "usda", "name")
|
||||
t:eq(Usda.category, "model", "category")
|
||||
t:check(Usda.caps.decode and Usda.caps.encode and table.find(Usda.extensions, "usdz"), "contract")
|
||||
|
||||
local function near(a: number, b: number, eps: number): boolean
|
||||
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
|
||||
end
|
||||
local function nearAll(a: { number }, b: { number }, eps: number): boolean
|
||||
if #a ~= #b then
|
||||
return false
|
||||
end
|
||||
for k = 1, #a do
|
||||
if not near(a[k], b[k], eps) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ scene helpers
|
||||
-- a node's channels evaluated at time s (seconds): translation / rotation / scale overrides
|
||||
local function animated(scene: any, s: number?): { [number]: any }
|
||||
local out: { [number]: any } = {}
|
||||
if not s then
|
||||
return out
|
||||
end
|
||||
for _, anim in scene.animations do
|
||||
for _, ch in anim.channels do
|
||||
local n = ch.input.count
|
||||
local get = Scene.reader(ch.output) :: any
|
||||
local comps = ch.output.components
|
||||
local k = 0
|
||||
for i = 0, n - 1 do
|
||||
if buffer.readf32(ch.input.data, i * 4) <= s + 1e-6 then
|
||||
k = i
|
||||
end
|
||||
end
|
||||
local t0 = buffer.readf32(ch.input.data, k * 4)
|
||||
local f = 0
|
||||
if k < n - 1 then
|
||||
local t1 = buffer.readf32(ch.input.data, (k + 1) * 4)
|
||||
f = math.clamp((s - t0) / (t1 - t0), 0, 1)
|
||||
end
|
||||
local v = {}
|
||||
for c = 0, comps - 1 do
|
||||
local a = get(k, c)
|
||||
local b = if k < n - 1 then get(k + 1, c) else a
|
||||
v[c + 1] = a + (b - a) * f
|
||||
end
|
||||
out[ch.node] = out[ch.node] or {}
|
||||
out[ch.node][ch.path] = v
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- world matrices of every node (at animation time s when given)
|
||||
local function worlds(scene: any, s: number?): { [number]: { number } }
|
||||
local over = animated(scene, s)
|
||||
local out: { [number]: { number } } = {}
|
||||
local function visit(i: number, parent: { number })
|
||||
local n = scene.nodes[i]
|
||||
if not n or out[i] then
|
||||
return
|
||||
end
|
||||
local o = over[i]
|
||||
local m
|
||||
if o then
|
||||
m = Scene.nodeMatrix({ children = {}, translation = o.translation or n.translation, rotation = o.rotation or n.rotation, scale = o.scale or n.scale })
|
||||
else
|
||||
m = Scene.nodeMatrix(n)
|
||||
end
|
||||
local w = Scene.mul(parent, m)
|
||||
out[i] = w
|
||||
for _, c in n.children do
|
||||
visit(c, w)
|
||||
end
|
||||
end
|
||||
for _, r in scene.roots do
|
||||
visit(r, Scene.IDENTITY :: any)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function byPath(scene: any): { [string]: number }
|
||||
local out = {}
|
||||
for i, n in scene.nodes do
|
||||
local u = n.extras and n.extras.usd
|
||||
if u and u.path then
|
||||
out[u.path] = i
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- triangles, world area and bounds of a node's mesh (or of everything: node = nil)
|
||||
local function geometry(scene: any, ws: { [number]: { number } }, only: number?): (number, number, { number }, { number })
|
||||
local tris, area = 0, 0
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for i, n in scene.nodes do
|
||||
if n.mesh and (only == nil or only == i) and ws[i] then
|
||||
local m = ws[i]
|
||||
for _, p in scene.meshes[n.mesh].primitives do
|
||||
local pos = p.attributes.POSITION
|
||||
local function P(v: number): { number }
|
||||
local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8)
|
||||
return { m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] }
|
||||
end
|
||||
local ind = p.indices
|
||||
for k = 0, ind.count // 3 - 1 do
|
||||
local a, b, c = P(buffer.readu32(ind.data, k * 12)), P(buffer.readu32(ind.data, k * 12 + 4)), P(buffer.readu32(ind.data, k * 12 + 8))
|
||||
local e1 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] }
|
||||
local e2 = { c[1] - a[1], c[2] - a[2], c[3] - a[3] }
|
||||
local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]
|
||||
area += math.sqrt(x * x + y * y + z * z) / 2
|
||||
tris += 1
|
||||
for _, q in { a, b, c } do
|
||||
for j = 1, 3 do
|
||||
lo[j] = math.min(lo[j], q[j])
|
||||
hi[j] = math.max(hi[j], q[j])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return tris, area, lo, hi
|
||||
end
|
||||
|
||||
-- pxr's totals over every mesh
|
||||
local function refTotals(ref: any): (number, number, { number }, { number })
|
||||
local tris, area = 0, 0
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for _, m in ref.meshes do
|
||||
tris += m.triangles
|
||||
area += m.area
|
||||
if #m.min == 3 then
|
||||
for j = 1, 3 do
|
||||
lo[j] = math.min(lo[j], m.min[j])
|
||||
hi[j] = math.max(hi[j], m.max[j])
|
||||
end
|
||||
end
|
||||
end
|
||||
return tris, area, lo, hi
|
||||
end
|
||||
|
||||
local LIGHT_TYPES = { DistantLight = "directional", SphereLight = "point", RectLight = "spot", DiskLight = "spot" }
|
||||
local SKIP_TYPES = { Skeleton = true, SkelRoot = true }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ against pxr
|
||||
local decoded: { [number]: any } = {}
|
||||
local counts = { xforms = 0, meshes = 0, materials = 0, cameras = 0, lights = 0, samples = 0, textures = 0 }
|
||||
for ci, c in Cases do
|
||||
local scene, err = decode(c.data, { files = c.files })
|
||||
if c.expect then
|
||||
t:check(scene == nil and err and err.code == Err[c.expect], c.name .. ": " .. c.expect .. " (" .. tostring(err) .. ")")
|
||||
continue
|
||||
end
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
if not scene then
|
||||
continue
|
||||
end
|
||||
decoded[ci] = scene
|
||||
local ref = c.ref
|
||||
t:eq(scene.meta.up, string.lower(ref.upAxis), c.name .. ": up axis")
|
||||
if ref.metersPerUnit > 0 then
|
||||
t:check(scene.meta.unit and near(scene.meta.unit, ref.metersPerUnit, 1e-9), c.name .. ": metersPerUnit")
|
||||
else
|
||||
t:eq(scene.meta.unit, nil, c.name .. ": no metersPerUnit")
|
||||
end
|
||||
local paths = byPath(scene)
|
||||
local ws = worlds(scene)
|
||||
-- transforms: every xformable pxr sees is a node with the same world matrix
|
||||
for _, x in ref.xforms do
|
||||
if not SKIP_TYPES[x.type] then
|
||||
local ni = paths[x.path]
|
||||
t:check(ni, c.name .. ": node " .. x.path)
|
||||
if ni then
|
||||
t:check(nearAll(ws[ni], x.world, 1e-4), c.name .. ": world matrix of " .. x.path)
|
||||
counts.xforms += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- meshes
|
||||
for _, m in ref.meshes do
|
||||
local ni = paths[m.path]
|
||||
local node = ni and scene.nodes[ni]
|
||||
if node and m.triangles > 0 then
|
||||
t:check(node.mesh, c.name .. ": mesh at " .. m.path)
|
||||
local tris, area, lo, hi = geometry(scene, ws, ni)
|
||||
t:eq(tris, m.triangles, c.name .. ": triangles of " .. m.path)
|
||||
t:check(near(area, m.area, 1e-4), string.format("%s: area of %s %.6g, pxr %.6g", c.name, m.path, area, m.area))
|
||||
t:check(nearAll(lo, m.min, 1e-4) and nearAll(hi, m.max, 1e-4), c.name .. ": bounds of " .. m.path)
|
||||
-- bound materials (whole mesh, then subsets)
|
||||
local mesh = scene.meshes[node.mesh]
|
||||
local whole, subs = nil, {}
|
||||
for _, p in mesh.primitives do
|
||||
local mat = p.material and scene.materials[p.material]
|
||||
local mp = mat and mat.extras and mat.extras.usd and mat.extras.usd.path or ""
|
||||
if p.extras and p.extras.usd and p.extras.usd.subset then
|
||||
table.insert(subs, mp)
|
||||
else
|
||||
whole = mp
|
||||
end
|
||||
end
|
||||
if m.material ~= "" and whole then
|
||||
t:eq(whole, m.material, c.name .. ": material of " .. m.path)
|
||||
end
|
||||
table.sort(subs)
|
||||
t:eq(table.concat(subs, ","), table.concat(m.subsetMaterials, ","), c.name .. ": subset materials of " .. m.path)
|
||||
counts.meshes += 1
|
||||
end
|
||||
end
|
||||
-- cameras
|
||||
for _, cam in ref.cameras do
|
||||
local ni = paths[cam.path]
|
||||
local camera = ni and scene.nodes[ni].camera and scene.cameras[scene.nodes[ni].camera]
|
||||
t:check(camera, c.name .. ": camera " .. cam.path)
|
||||
if camera then
|
||||
if cam.projection == "orthographic" then
|
||||
t:check(camera.type == "orthographic" and near(camera.xmag, cam.hap / 20, 1e-6) and near(camera.ymag, cam.vap / 20, 1e-6), c.name .. ": ortho camera")
|
||||
else
|
||||
t:check(near(camera.yfov, 2 * math.atan(cam.vap / (2 * cam.focal)), 1e-5), c.name .. ": yfov of " .. cam.path)
|
||||
t:check(near(camera.aspect, cam.hap / cam.vap, 1e-5), c.name .. ": aspect of " .. cam.path)
|
||||
end
|
||||
t:check(near(camera.znear, cam.near, 1e-5) and near(camera.zfar, cam.far, 1e-5), c.name .. ": clipping of " .. cam.path)
|
||||
counts.cameras += 1
|
||||
end
|
||||
end
|
||||
-- lights
|
||||
for _, l in ref.lights do
|
||||
local ni = paths[l.path]
|
||||
local light = ni and scene.nodes[ni].light and scene.lights[scene.nodes[ni].light]
|
||||
t:check(light, c.name .. ": light " .. l.path)
|
||||
if light then
|
||||
local want = if l.cone > 0 and l.cone < 90 then "spot" else LIGHT_TYPES[l.type]
|
||||
t:eq(light.type, want, c.name .. ": light type of " .. l.path)
|
||||
t:check(near(light.intensity, l.intensity, 1e-5) and nearAll(light.color, l.color, 1e-5), c.name .. ": light values of " .. l.path)
|
||||
if want == "spot" and l.cone > 0 then
|
||||
t:check(near(light.outerCone, math.rad(l.cone), 1e-5), c.name .. ": cone of " .. l.path)
|
||||
end
|
||||
counts.lights += 1
|
||||
end
|
||||
end
|
||||
-- materials
|
||||
local mats = {}
|
||||
for _, m in scene.materials do
|
||||
if m.extras and m.extras.usd and m.extras.usd.path then
|
||||
mats[m.extras.usd.path] = m
|
||||
end
|
||||
end
|
||||
for _, rm in ref.materials do
|
||||
local m = mats[rm.path]
|
||||
if m then -- only bound materials become Scene materials
|
||||
local tx = rm.textures
|
||||
if rm.diffuseColor and not tx.diffuseColor then
|
||||
t:check(nearAll({ m.baseColor[1], m.baseColor[2], m.baseColor[3] }, rm.diffuseColor, 1e-6), c.name .. ": diffuse of " .. rm.path)
|
||||
end
|
||||
if rm.metallic and not tx.metallic then
|
||||
t:check(near(m.metallic, rm.metallic, 1e-6), c.name .. ": metallic of " .. rm.path)
|
||||
end
|
||||
if rm.roughness and not tx.roughness then
|
||||
t:check(near(m.roughness, rm.roughness, 1e-6), c.name .. ": roughness of " .. rm.path)
|
||||
end
|
||||
if rm.emissiveColor and not tx.emissiveColor then
|
||||
t:check(nearAll(m.emissive, rm.emissiveColor, 1e-6), c.name .. ": emissive of " .. rm.path)
|
||||
end
|
||||
if rm.opacity and not tx.opacity then
|
||||
t:check(near(m.baseColor[4], rm.opacity, 1e-6), c.name .. ": opacity of " .. rm.path)
|
||||
if rm.opacityThreshold and rm.opacityThreshold > 0 then
|
||||
t:check(m.alphaMode == "mask" and near(m.alphaCutoff, rm.opacityThreshold, 1e-6), c.name .. ": alpha mask of " .. rm.path)
|
||||
elseif rm.opacity < 1 then
|
||||
t:eq(m.alphaMode, "blend", c.name .. ": alpha blend of " .. rm.path)
|
||||
end
|
||||
end
|
||||
local function texFile(ref: any): string?
|
||||
local tex = ref and scene.textures[ref.texture]
|
||||
return tex and tex.uri
|
||||
end
|
||||
for input, field in { diffuseColor = "baseColorTexture", normal = "normalTexture", emissiveColor = "emissiveTexture", occlusion = "occlusionTexture", roughness = "metallicRoughnessTexture", metallic = "metallicRoughnessTexture" } do
|
||||
if tx[input] then
|
||||
t:eq(texFile(m[field]), tx[input].file, c.name .. ": " .. input .. " texture of " .. rm.path)
|
||||
counts.textures += 1
|
||||
end
|
||||
end
|
||||
counts.materials += 1
|
||||
end
|
||||
end
|
||||
-- xform time samples
|
||||
for _, a in ref.anim do
|
||||
local ni = paths[a.path]
|
||||
for _, smp in a.samples do
|
||||
local w = worlds(scene, smp.time / ref.tcps)
|
||||
t:check(ni and nearAll(w[ni], smp.world, 1e-4), string.format("%s: %s at time %g", c.name, a.path, smp.time))
|
||||
counts.samples += 1
|
||||
end
|
||||
end
|
||||
-- textures with their file at hand carry its bytes
|
||||
for _, tex in scene.textures do
|
||||
local want = c.files[tex.uri] or c.files[(string.gsub(string.gsub(tex.uri, "\\", "/"), "^%./", ""))] or (c.like ~= nil)
|
||||
if want then
|
||||
t:check(tex.data and buffer.len(tex.data) > 0, c.name .. ": texture bytes for " .. tex.uri)
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d files against pxr: %d transforms, %d meshes, %d materials (%d textures), %d cameras, %d lights, %d time samples", #Cases, counts.xforms, counts.meshes, counts.materials, counts.textures, counts.cameras, counts.lights, counts.samples)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ specific facts
|
||||
do
|
||||
local hand
|
||||
for ci, c in Cases do
|
||||
if c.name == "hand.usda" then
|
||||
hand = decoded[ci]
|
||||
end
|
||||
end
|
||||
local p = byPath(hand)
|
||||
t:check(p["/Hand/Big"] and not p["/Hand/Small"] and not p["/_Template"] and not p["/Elsewhere/Undefined"], "hand: selected variant, no class / undefined over")
|
||||
t:check(p["/Hand/Untyped/Inner/Quad"] and not p["/Hand/Looks"], "hand: untyped prims are nodes, material scopes are not")
|
||||
t:check(table.find(hand.meta.source.unsupported, "references"), "hand: references reported unsupported")
|
||||
t:eq(hand.meta.source.defaultPrim, "Hand", "hand: defaultPrim")
|
||||
local tri = hand.nodes[p["/Hand/Tri"]]
|
||||
local mat = hand.materials[hand.meshes[tri.mesh].primitives[1].material]
|
||||
t:check(nearAll(mat.baseColor, { 0.1, 0.2, 0.9, 1 }, 1e-6), "hand: diffuse through a Material interface input + relative paths")
|
||||
local big = hand.meshes[hand.nodes[p["/Hand/Big"]].mesh].primitives[1]
|
||||
t:check(big.attributes.COLOR_0 and big.attributes.COLOR_0.count == 4, "hand: vertex displayColor -> COLOR_0")
|
||||
local layer = Usda.parse(Cases[1].data)
|
||||
t:check(layer and #layer.prims == 1 and layer.meta.defaultPrim == "World", "parse: the raw layer")
|
||||
end
|
||||
do
|
||||
local prim
|
||||
for ci, c in Cases do
|
||||
if c.name == "pxr/primvars.usda" then
|
||||
prim = decoded[ci]
|
||||
end
|
||||
end
|
||||
local p = byPath(prim)
|
||||
local grid = prim.meshes[prim.nodes[p["/Grid"]].mesh].primitives[1]
|
||||
t:check(grid.attributes.TEXCOORD_0 and grid.attributes.TEXCOORD_1 and grid.attributes.NORMAL and grid.attributes.COLOR_0.components == 4, "primvars: st, uv2, normals, colour + opacity")
|
||||
local cc = prim.meshes[prim.nodes[p["/Grid/ConstColor"]].mesh].primitives[1]
|
||||
t:check(cc.attributes.COLOR_0 == nil and nearAll(prim.materials[cc.material].baseColor, { 0.2, 0.4, 0.8, 1 }, 1e-6), "primvars: constant displayColor -> material")
|
||||
local poly = decode(Cases[2].data, { triangulate = false })
|
||||
local pg = poly.meshes[1].primitives[1]
|
||||
t:check(pg.mode == "polygons" and pg.faces.count == 17, "primvars: polygons kept (16 quads + pentagon + triangle - 1 hole)")
|
||||
-- the texture transform on the materials stage
|
||||
local mats
|
||||
for ci, c in Cases do
|
||||
if c.name == "pxr/materials.usda" then
|
||||
mats = decoded[ci]
|
||||
end
|
||||
end
|
||||
for _, m in mats.materials do
|
||||
if m.name == "Textured" then
|
||||
local mr = m.metallicRoughnessTexture
|
||||
t:check(mr and mr.texCoord == 1 and mr.transform and near(mr.transform.rotation, math.rad(30), 1e-6), "materials: uv2 + UsdTransform2d -> texCoord 1 + KHR_texture_transform")
|
||||
t:eq(mats.textures[mr.texture].sampler.wrapS, "mirror", "materials: wrapS")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ parse-only
|
||||
for _, s in Specs do
|
||||
local layer, err = Usda.parse(s.data)
|
||||
t:check(layer, s.name .. ": parse: " .. tostring(err))
|
||||
if layer then
|
||||
local n = 0
|
||||
local function count(list: { any })
|
||||
for _, p in list do
|
||||
n += 1
|
||||
count(p.children)
|
||||
end
|
||||
end
|
||||
count(layer.prims)
|
||||
t:eq(n, s.prims, s.name .. ": prim specs (Sdf)")
|
||||
end
|
||||
end
|
||||
t:note("%d OpenUSD schema layers parsed", #Specs)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ round trips
|
||||
local rt = 0
|
||||
local texts: { [number]: string } = {}
|
||||
for ci = 1, #Cases do
|
||||
local scene = decoded[ci]
|
||||
if not scene then
|
||||
continue
|
||||
end
|
||||
local name = Cases[ci].name
|
||||
local files = {}
|
||||
local out, err = Usda.encode(scene, { files = files, name = "rt.usda" })
|
||||
t:check(out, name .. ": encode: " .. tostring(err))
|
||||
if out then
|
||||
texts[ci] = buffer.tostring(out)
|
||||
local back, berr = decode(out, { files = files })
|
||||
t:check(back, name .. ": decode our output: " .. tostring(berr))
|
||||
if back then
|
||||
local a1, a2, a3, a4 = geometry(scene, worlds(scene))
|
||||
local b1, b2, b3, b4 = geometry(back, worlds(back))
|
||||
t:eq(b1, a1, name .. ": round trip triangles")
|
||||
t:check(near(b2, a2, 1e-5) and (a1 == 0 or (nearAll(b3, a3, 1e-5) and nearAll(b4, a4, 1e-5))), name .. ": round trip area / bounds")
|
||||
t:eq(#back.materials, #scene.materials, name .. ": round trip materials")
|
||||
t:eq(#back.cameras, #scene.cameras, name .. ": round trip cameras")
|
||||
t:eq(#back.lights, #scene.lights, name .. ": round trip lights")
|
||||
t:eq(#back.animations, #scene.animations, name .. ": round trip animations")
|
||||
t:eq(back.meta.up, scene.meta.up, name .. ": round trip up axis")
|
||||
for k, m in scene.materials do
|
||||
local b = back.materials[k]
|
||||
t:check(b and nearAll(b.baseColor, m.baseColor, 1e-6) and near(b.metallic, m.metallic, 1e-6) and near(b.roughness, m.roughness, 1e-6) and b.alphaMode == m.alphaMode and (b.baseColorTexture ~= nil) == (m.baseColorTexture ~= nil), name .. ": round trip material " .. k)
|
||||
end
|
||||
-- animated geometry at every key time
|
||||
if #scene.animations > 0 then
|
||||
local ch = scene.animations[1].channels[1]
|
||||
for i = 0, ch.input.count - 1 do
|
||||
local s = buffer.readf32(ch.input.data, i * 4)
|
||||
local _, x2, x3 = geometry(scene, worlds(scene, s))
|
||||
local _, y2, y3 = geometry(back, worlds(back, s))
|
||||
t:check(near(x2, y2, 1e-4) and nearAll(x3, y3, 1e-4), string.format("%s: round trip animation at %g s", name, s))
|
||||
end
|
||||
end
|
||||
-- our text is stable: after one cycle (a scene with several roots gains a "root" prim), writing what we
|
||||
-- read from our own output gives the same text
|
||||
local again = Usda.encode(back, { files = {}, name = "rt.usda" }) :: buffer
|
||||
local third = Usda.encode((decode(again)), { files = {}, name = "rt.usda" }) :: buffer
|
||||
t:eq(buffer.tostring(third), buffer.tostring(again), name .. ": stable text")
|
||||
rt += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d round trips", rt)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ pxr reads our output
|
||||
local xc = 0
|
||||
for _, x in Xcheck do
|
||||
local scene = decoded[x.case]
|
||||
local ref = x.ref
|
||||
local name = Cases[x.case].name .. " -> ours"
|
||||
t:check(scene and not ref.failed, name .. ": pxr opens our file")
|
||||
if scene and not ref.failed then
|
||||
local a1, a2, a3, a4 = geometry(scene, worlds(scene))
|
||||
local r1, r2, r3, r4 = refTotals(ref)
|
||||
t:eq(r1, a1, name .. ": triangles (pxr)")
|
||||
t:check(near(r2, a2, 1e-4), string.format("%s: area %.6g, pxr %.6g", name, a2, r2))
|
||||
if a1 > 0 then
|
||||
t:check(nearAll(r3, a3, 1e-4) and nearAll(r4, a4, 1e-4), name .. ": bounds (pxr)")
|
||||
end
|
||||
t:eq(#ref.materials, #scene.materials, name .. ": materials (pxr)")
|
||||
t:eq(#ref.cameras, #scene.cameras, name .. ": cameras (pxr)")
|
||||
t:eq(#ref.lights, #scene.lights, name .. ": lights (pxr)")
|
||||
t:eq(string.lower(ref.upAxis), scene.meta.up, name .. ": up axis (pxr)")
|
||||
-- every material's values as pxr reads them
|
||||
local want, got = {}, {}
|
||||
for _, m in scene.materials do
|
||||
table.insert(want, string.format("%.4f %.4f %.4f", if m.metallicRoughnessTexture then -1 else m.metallic, if m.metallicRoughnessTexture then -1 else m.roughness, if m.baseColorTexture then -1 else m.baseColor[1]))
|
||||
end
|
||||
for _, m in ref.materials do
|
||||
table.insert(got, string.format("%.4f %.4f %.4f", if m.textures.metallic then -1 else m.metallic or 0, if m.textures.roughness then -1 else m.roughness or 0.5, if m.textures.diffuseColor then -1 else (m.diffuseColor or { 0.18 })[1]))
|
||||
end
|
||||
table.sort(want)
|
||||
table.sort(got)
|
||||
t:eq(table.concat(got, ";"), table.concat(want, ";"), name .. ": material values (pxr)")
|
||||
-- animated nodes: each pxr sample matches one of our nodes at that time
|
||||
for _, a in ref.anim do
|
||||
for _, smp in a.samples do
|
||||
local w = worlds(scene, smp.time / ref.tcps)
|
||||
local found = false
|
||||
for _, m in w do
|
||||
if nearAll(m, smp.world, 1e-4) then
|
||||
found = true
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(found, string.format("%s: %s at %g (pxr)", name, a.path, smp.time))
|
||||
end
|
||||
end
|
||||
xc += 1
|
||||
end
|
||||
end
|
||||
t:note("%d of our files read back by pxr like the originals", xc)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ api
|
||||
do
|
||||
local scene, err = F.model.load(Cases[1].data)
|
||||
t:check(scene and scene.meta.source.format == "usda", "api: F.model.load sniffs usda: " .. tostring(err))
|
||||
local s = F.saveString(scene, { format = "usda" })
|
||||
t:check(s and string.sub(s, 1, 9) == "#usda 1.0", "api: F.saveString usda")
|
||||
local _, zerr = F.save(scene, nil, { format = "usdz" })
|
||||
t:check(zerr and zerr.code == Err.UNSUPPORTED, "api: usdz writing unsupported")
|
||||
t:eq(F.detect(Cases[1].data), "usda", "api: detect")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ errors
|
||||
do
|
||||
local _, e1 = decode("#usda 1.0\ndef Xform \"a\" {\n")
|
||||
t:check(e1 and e1.code == Err.TRUNCATED, "truncated prim: " .. tostring(e1))
|
||||
local _, e2 = decode("#usda 1.0\ndef Xform \"a\" { float x = ] }\n")
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "bad value: " .. tostring(e2))
|
||||
local _, e3 = decode("hello")
|
||||
t:check(e3 and e3.code == Err.CORRUPT, "no header")
|
||||
local _, e4 = decode("#usda 1.0\ndef Mesh \"m\" { point3f[] points = [(0,0,0)] int[] faceVertexCounts = [3] int[] faceVertexIndices = [0, 1, 2] }")
|
||||
t:check(e4 and e4.code == Err.CORRUPT, "index out of range: " .. tostring(e4))
|
||||
local _, e5 = decode(Cases[1].data, { maxVertices = 4 })
|
||||
t:check(e5 and e5.code == Err.LIMIT, "maxVertices")
|
||||
local _, e6 = Usda.encode({ kind = "image" } :: any)
|
||||
t:check(e6 and e6.code == Err.ARG, "encode a non-scene")
|
||||
local deep = "#usda 1.0\ndef \"a\" { custom float x = " .. string.rep("(", 500) .. "1" .. string.rep(")", 500) .. " }"
|
||||
local _, e7 = decode(deep)
|
||||
t:check(e7 and e7.code == Err.CORRUPT, "nesting limit")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
if #c.data < 40000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local s = decode(b)
|
||||
if s then
|
||||
Usda.encode(s)
|
||||
end
|
||||
return s
|
||||
end, samples, { mutations = 24, keepHeader = 10 })
|
||||
t:done()
|
||||
@@ -774,3 +774,127 @@ do
|
||||
realtime("tracker 32 ch (mod)", song("mod", false), 32)
|
||||
realtime("tracker 32 ch + NNA, filters", song("it", true), 64)
|
||||
end
|
||||
do
|
||||
-- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a
|
||||
-- 128^3 noise voxel grid through VOX and greedy meshing
|
||||
local Types = require("@formats/Types")
|
||||
local MeshOps = require("@formats/ops/MeshOps")
|
||||
local Gltf = require("@formats/model/gltf")
|
||||
local Obj = require("@formats/model/obj")
|
||||
local Stl = require("@formats/model/stl")
|
||||
local Ply = require("@formats/model/ply")
|
||||
local Vox = require("@formats/model/vox")
|
||||
local N = 400
|
||||
local pos = Types.Scene.accessor(nil, "f32", 3, N * N)
|
||||
local uv = Types.Scene.accessor(nil, "f32", 2, N * N)
|
||||
for y = 0, N - 1 do
|
||||
for x = 0, N - 1 do
|
||||
local i = y * N + x
|
||||
buffer.writef32(pos.data, i * 12, x / N)
|
||||
buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05)
|
||||
buffer.writef32(pos.data, i * 12 + 8, y / N)
|
||||
buffer.writef32(uv.data, i * 8, x / N)
|
||||
buffer.writef32(uv.data, i * 8 + 4, y / N)
|
||||
end
|
||||
end
|
||||
local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6)
|
||||
local k = 0
|
||||
for y = 0, N - 2 do
|
||||
for x = 0, N - 2 do
|
||||
local a = y * N + x
|
||||
for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do
|
||||
buffer.writeu32(ind.data, k * 4, v)
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any
|
||||
MeshOps.computeNormals(prim)
|
||||
local scene = Types.Scene.fromPrimitive(prim, "grid")
|
||||
bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function()
|
||||
MeshOps.computeNormals(prim)
|
||||
end)
|
||||
local glb = assert(Gltf.encode(scene, { binary = true }))
|
||||
bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function()
|
||||
Gltf.decode(Bytes.reader(glb))
|
||||
end)
|
||||
bench("gltf glb encode", 3, buffer.len(glb), function()
|
||||
Gltf.encode(scene, { binary = true })
|
||||
end)
|
||||
local obj = assert(Obj.encode(scene))
|
||||
bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function()
|
||||
Obj.decode(Bytes.reader(obj))
|
||||
end)
|
||||
bench("obj encode", 2, buffer.len(obj), function()
|
||||
Obj.encode(scene)
|
||||
end)
|
||||
local stl = assert(Stl.encode(scene))
|
||||
bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function()
|
||||
Stl.decode(Bytes.reader(stl))
|
||||
end)
|
||||
local ply = assert(Ply.encode(scene))
|
||||
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
|
||||
Ply.decode(Bytes.reader(ply))
|
||||
end)
|
||||
local Fbx = require("@formats/model/fbx")
|
||||
local fbx = assert(Fbx.encode(scene))
|
||||
bench("fbx binary decode (" .. buffer.len(fbx) // 1000 .. " KB)", 3, buffer.len(fbx), function()
|
||||
Fbx.decode(Bytes.reader(fbx))
|
||||
end)
|
||||
bench("fbx binary encode (zlib arrays)", 2, buffer.len(fbx), function()
|
||||
Fbx.encode(scene)
|
||||
end)
|
||||
bench("fbx binary encode (raw arrays)", 3, buffer.len(fbx), function()
|
||||
Fbx.encode(scene, { compress = false })
|
||||
end)
|
||||
local fbxa = assert(Fbx.encode(scene, { ascii = true }))
|
||||
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
|
||||
Fbx.decode(Bytes.reader(fbxa))
|
||||
end)
|
||||
local ThreeMf = require("@formats/model/3mf")
|
||||
local tmf = assert(ThreeMf.encode(scene))
|
||||
bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
|
||||
ThreeMf.decode(Bytes.reader(tmf))
|
||||
end)
|
||||
bench("3mf encode", 2, buffer.len(tmf), function()
|
||||
ThreeMf.encode(scene)
|
||||
end)
|
||||
local V = 128
|
||||
local grid = Types.Voxels.new(V, V, V)
|
||||
for z = 0, V - 1 do
|
||||
for y = 0, V - 1 do
|
||||
for x = 0, V - 1 do
|
||||
local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0
|
||||
if z < h then
|
||||
Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local vox = assert(Vox.encode(grid))
|
||||
bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function()
|
||||
Vox.decode(Bytes.reader(vox))
|
||||
end)
|
||||
bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function()
|
||||
MeshOps.voxelsToPrimitive(grid)
|
||||
end)
|
||||
end
|
||||
do
|
||||
-- STEP (tools/fixtures/step.py): the largest case, parse and write
|
||||
local Step = require("@formats/cad/step")
|
||||
local SC = require("@tests/gen/step_cases")
|
||||
local big = SC[1]
|
||||
for _, c in SC do
|
||||
if #c.data > #big.data then
|
||||
big = c
|
||||
end
|
||||
end
|
||||
local data = buffer.fromstring(big.data)
|
||||
local cad = assert(Step.decode(Bytes.reader(data)))
|
||||
bench(string.format("step parse (%.1f MB)", #big.data / 1e6), 3, #big.data, function()
|
||||
Step.decode(Bytes.reader(data))
|
||||
end)
|
||||
bench("step write", 3, #big.data, function()
|
||||
Step.encode(cad)
|
||||
end)
|
||||
end
|
||||
@@ -0,0 +1,111 @@
|
||||
# 3MF fixtures (tools/fixtures.py): the lib3mf test suite and SDK example files (nixpkgs#lib3mf.src, read only, never
|
||||
# committed: core, materials (base / colour / texture / composite / multiproperties), production parts, metadata,
|
||||
# units, thumbnails, files lib3mf rejects), assimp's box.3mf (nixpkgs#assimp.src), and files written by assimp's and
|
||||
# trimesh's 3MF exporters, with reference values from lib3mf 2.5 (tools/fixtures/_3mf_reference.py: world-space
|
||||
# triangles / area / bounds through build items and components, mesh object sizes, material group counts, unit),
|
||||
# assimp (`assimp info -r`) and trimesh (area, faces).
|
||||
# tests/gen/3mf_cases.luau { name, data, lib3mf = {...} | { failed }, assimp, trimesh }
|
||||
# tests/gen/3mf_xcheck.luau our encoder's output for every case (tools/fixtures/_3mf_encode.luau) read back by
|
||||
# lib3mf / assimp / trimesh: { name, case, lib3mf, assimp, trimesh }
|
||||
import importlib.util, json, os, subprocess, sys
|
||||
|
||||
INPUTS = ["src/Formats/model/3mf", "src/Formats/codecs/Xml", "src/Formats/containers/Zip",
|
||||
"tools/fixtures/_3mf_reference.py", "tools/fixtures/_3mf_encode.luau", "tools/fixtures/_model_ref.py"]
|
||||
MAX_SIZE = 500_000
|
||||
|
||||
|
||||
def ref_module(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def store(attr):
|
||||
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + attr], check=True, capture_output=True)
|
||||
return out.stdout.decode().strip().split("\n")[-1]
|
||||
|
||||
|
||||
def lib3mf(ctx, paths):
|
||||
src, lib = store("lib3mf.src"), store("lib3mf")
|
||||
res = subprocess.run([sys.executable, "-I", os.path.join(ctx.root, "tools", "fixtures", "_3mf_reference.py"),
|
||||
os.path.join(src, "Autogenerated", "Bindings", "Python"), os.path.join(lib, "lib", "lib3mf")],
|
||||
input=json.dumps(paths).encode(), capture_output=True, check=True)
|
||||
return json.loads(res.stdout)
|
||||
|
||||
|
||||
TRIMESH_EXPORT = r"""
|
||||
import sys, trimesh
|
||||
m = trimesh.creation.icosphere(subdivisions=2, radius=10.0)
|
||||
b = trimesh.creation.box(extents=(4, 6, 8))
|
||||
b.apply_translation((20, 0, 0))
|
||||
s = trimesh.Scene([m, b])
|
||||
open(sys.argv[1] if len(sys.argv) > 1 else "/dev/stdout", "wb").write(s.export(file_type="3mf"))
|
||||
"""
|
||||
|
||||
|
||||
def ply_torus(R=20.0, r=5.0, a=24, b=12):
|
||||
import math
|
||||
vs, fs = [], []
|
||||
for i in range(a):
|
||||
for j in range(b):
|
||||
u, v = 2 * math.pi * i / a, 2 * math.pi * j / b
|
||||
vs.append(((R + r * math.cos(v)) * math.cos(u), (R + r * math.cos(v)) * math.sin(u), r * math.sin(v)))
|
||||
for i in range(a):
|
||||
for j in range(b):
|
||||
p, q = i * b + j, ((i + 1) % a) * b + j
|
||||
p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b
|
||||
fs.append((p, q2, p2))
|
||||
fs.append((p, q, q2))
|
||||
head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs))
|
||||
return (head + "".join("%r %r %r\n" % v for v in vs) + "".join("3 %d %d %d\n" % f for f in fs)).encode()
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = ref_module(ctx)
|
||||
src = store("lib3mf.src")
|
||||
files = []
|
||||
for base in ("Tests/TestFiles", "SDK/Examples/Files"):
|
||||
for d, _, fs in sorted(os.walk(os.path.join(src, base))):
|
||||
for f in sorted(fs):
|
||||
p = os.path.join(d, f)
|
||||
if f.endswith(".3mf") and os.path.getsize(p) <= MAX_SIZE:
|
||||
files.append(("lib3mf/" + os.path.relpath(p, os.path.join(src, base)), p))
|
||||
files.append(("assimp/box.3mf", os.path.join(store("assimp.src"), "test", "models", "3MF", "box.3mf")))
|
||||
tmp = M.tempdir()
|
||||
ply = os.path.join(tmp, "torus.ply")
|
||||
with open(ply, "wb") as f:
|
||||
f.write(ply_torus())
|
||||
out = os.path.join(tmp, "torus_assimp.3mf")
|
||||
ctx.nix(["assimp"], ["assimp", "export", ply, out, "-f3mf"])
|
||||
files.append(("assimp/torus_export.3mf", out))
|
||||
tm = ctx.python(["trimesh", "numpy", "networkx", "lxml"], TRIMESH_EXPORT)
|
||||
out = os.path.join(tmp, "trimesh_export.3mf")
|
||||
with open(out, "wb") as f:
|
||||
f.write(tm)
|
||||
files.append(("trimesh/export.3mf", out))
|
||||
|
||||
paths = [p for _, p in files]
|
||||
refs = lib3mf(ctx, paths)
|
||||
infos = M.assimp_info(ctx, paths, raw=True)
|
||||
tms = M.trimesh_metrics(ctx, paths)
|
||||
cases = []
|
||||
for (name, p), r, a, t in zip(files, refs, infos, tms):
|
||||
cases.append({"name": name, "data": open(p, "rb").read(), "lib3mf": r, "assimp": a, "trimesh": t})
|
||||
ctx.emit("3mf_cases", cases)
|
||||
|
||||
# the reference tools read our output
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_3mf_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
names = sorted(ours, key=lambda n: int(n.split("_")[1].split(".")[0]))
|
||||
xp = []
|
||||
for n in names:
|
||||
p = os.path.join(xtmp, n)
|
||||
with open(p, "wb") as f:
|
||||
f.write(ours[n])
|
||||
xp.append(p)
|
||||
xr = lib3mf(ctx, xp)
|
||||
xi = M.assimp_info(ctx, xp, raw=True)
|
||||
xt = M.trimesh_metrics(ctx, xp)
|
||||
ctx.emit("3mf_xcheck", [{"name": n, "case": int(n.split("_")[1].split(".")[0]), "lib3mf": r, "assimp": a, "trimesh": t}
|
||||
for n, r, a, t in zip(names, xr, xi, xt)])
|
||||
@@ -0,0 +1,28 @@
|
||||
-- tools/fixtures/_3mf_encode: run by tools/fixtures/3mf.py (luau CLI, repo root): decodes every 3MF case that lib3mf
|
||||
-- reads with our reader and encodes it with our writer, printing "rt_<case>.3mf\t<hex>" lines for the reference tools
|
||||
-- (lib3mf, assimp, trimesh) to read back.
|
||||
local ThreeMf = require("@formats/model/3mf")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/3mf_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = HEX[string.byte(s, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
if not c.lib3mf.failed then
|
||||
local scene = ThreeMf.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if scene then
|
||||
local out = assert(ThreeMf.encode(scene))
|
||||
print(string.format("rt_%d.3mf\t%s", i, hex(buffer.tostring(out))))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,115 @@
|
||||
# 3MF reference values through lib3mf's Python binding (ctypes over lib3mf.so; both from nixpkgs), run by 3mf.py as
|
||||
# `python3 -I _3mf_reference.py <bindings dir> <lib3mf.so without .so> < paths.json` -> JSON list, one entry per file:
|
||||
# { unit, items, meshObjects = [ [vertices, triangles] ... sorted ], triangles, area, min, max (world space, every
|
||||
# build item through its components), baseGroups, colorGroups, textures, texGroups } or { failed = message }
|
||||
import json, math, sys
|
||||
|
||||
sys.path.insert(0, sys.argv[1])
|
||||
import Lib3MF # noqa: E402
|
||||
|
||||
W = Lib3MF.Wrapper(sys.argv[2])
|
||||
UNITS = {0: "micron", 1: "millimeter", 2: "centimeter", 3: "inch", 4: "foot", 5: "meter"}
|
||||
|
||||
|
||||
def mat(t):
|
||||
f = t.Fields
|
||||
return [[f[r][c] for c in range(3)] for r in range(4)]
|
||||
|
||||
|
||||
def mul(a, b): # row-vector 4x3 affine: p * a * b
|
||||
out = []
|
||||
for r in range(4):
|
||||
row = []
|
||||
for c in range(3):
|
||||
s = sum(a[r][k] * b[k][c] for k in range(3))
|
||||
if r == 3:
|
||||
s += b[3][c]
|
||||
row.append(s)
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
IDENT = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]]
|
||||
|
||||
|
||||
def count(it):
|
||||
n = 0
|
||||
while it.MoveNext():
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def info(path):
|
||||
model = W.CreateModel()
|
||||
reader = model.QueryReader("3mf")
|
||||
reader.SetStrictModeActive(False)
|
||||
reader.ReadFromFile(path)
|
||||
res = {"unit": UNITS.get(model.GetUnit().value if hasattr(model.GetUnit(), "value") else model.GetUnit(), "?")}
|
||||
meshes = []
|
||||
it = model.GetMeshObjects()
|
||||
while it.MoveNext():
|
||||
m = it.GetCurrentMeshObject()
|
||||
meshes.append([m.GetVertexCount(), m.GetTriangleCount()])
|
||||
res["meshObjects"] = sorted(meshes)
|
||||
tot = {"tri": 0, "area": 0.0, "min": [math.inf] * 3, "max": [-math.inf] * 3}
|
||||
|
||||
def place(rid, M, depth):
|
||||
if depth > 32:
|
||||
return
|
||||
try:
|
||||
mo = model.GetMeshObjectByID(rid)
|
||||
except Exception:
|
||||
mo = None
|
||||
if mo is not None:
|
||||
verts = mo.GetVertices()
|
||||
tris = mo.GetTriangleIndices()
|
||||
P = []
|
||||
for v in verts:
|
||||
x, y, z = v.Coordinates[0], v.Coordinates[1], v.Coordinates[2]
|
||||
P.append([x * M[0][c] + y * M[1][c] + z * M[2][c] + M[3][c] for c in range(3)])
|
||||
for p in P:
|
||||
for c in range(3):
|
||||
tot["min"][c] = min(tot["min"][c], p[c])
|
||||
tot["max"][c] = max(tot["max"][c], p[c])
|
||||
for t in tris:
|
||||
a, b, c = (P[i] for i in t.Indices)
|
||||
e1 = [b[k] - a[k] for k in range(3)]
|
||||
e2 = [c[k] - a[k] for k in range(3)]
|
||||
cx = e1[1] * e2[2] - e1[2] * e2[1]
|
||||
cy = e1[2] * e2[0] - e1[0] * e2[2]
|
||||
cz = e1[0] * e2[1] - e1[1] * e2[0]
|
||||
tot["area"] += math.sqrt(cx * cx + cy * cy + cz * cz) / 2
|
||||
tot["tri"] += 1
|
||||
return
|
||||
co = model.GetComponentsObjectByID(rid)
|
||||
for i in range(co.GetComponentCount()):
|
||||
comp = co.GetComponent(i)
|
||||
T = mat(comp.GetTransform()) if comp.HasTransform() else IDENT
|
||||
place(comp.GetObjectResourceID(), mul(T, M), depth + 1)
|
||||
|
||||
items = model.GetBuildItems()
|
||||
n = 0
|
||||
while items.MoveNext():
|
||||
bi = items.GetCurrent()
|
||||
n += 1
|
||||
T = mat(bi.GetObjectTransform()) if bi.HasObjectTransform() else IDENT
|
||||
place(bi.GetObjectResourceID(), T, 0)
|
||||
res["items"] = n
|
||||
res["triangles"] = tot["tri"]
|
||||
res["area"] = tot["area"]
|
||||
if tot["tri"]:
|
||||
res["min"], res["max"] = tot["min"], tot["max"]
|
||||
res["baseGroups"] = count(model.GetBaseMaterialGroups())
|
||||
res["colorGroups"] = count(model.GetColorGroups())
|
||||
res["textures"] = count(model.GetTexture2Ds())
|
||||
res["texGroups"] = count(model.GetTexture2DGroups())
|
||||
return res
|
||||
|
||||
|
||||
out = []
|
||||
for p in json.loads(sys.stdin.read()):
|
||||
try:
|
||||
out.append(info(p))
|
||||
except Exception as e: # noqa: BLE001
|
||||
out.append({"failed": str(e)[:200]})
|
||||
print(json.dumps(out))
|
||||
@@ -0,0 +1,36 @@
|
||||
-- tools/fixtures/_dae_encode: run by tools/fixtures/dae.py (luau CLI, repo root): decodes every Collada case with our
|
||||
-- reader and encodes it with our writer (rt_<case>.dae + its image files, and rt_<case>.zae for the first cases),
|
||||
-- printing "<file>\t<hex>" lines for assimp to read back.
|
||||
local Dae = require("@formats/model/dae")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/dae_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = HEX[string.byte(s, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local scene, err = Dae.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
|
||||
if scene then
|
||||
local files = {}
|
||||
local dae = assert(Dae.encode(scene, { files = files, name = "rt_" .. i .. ".dae" }))
|
||||
print(string.format("rt_%d.dae\t%s", i, hex(buffer.tostring(dae))))
|
||||
for name, data in files do
|
||||
print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
|
||||
end
|
||||
if i <= 3 then
|
||||
local zae = assert(Dae.encode(scene, { format = "zae" }))
|
||||
print(string.format("rt_%d.zae\t%s", i, hex(buffer.tostring(zae))))
|
||||
end
|
||||
else
|
||||
print("skipped " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,94 @@
|
||||
# tools/fixtures/_fbx_blender: run by tools/fixtures/fbx.py inside Blender (blender -b --python <this> -- <outdir>): builds
|
||||
# test scenes (textured cube with two materials, vertex colours and a child; a skinned, animated cylinder with a
|
||||
# shape key; a camera and three lights) and exports each to binary FBX 7.4.
|
||||
import bpy, sys, os, math
|
||||
out = sys.argv[sys.argv.index("--") + 1]
|
||||
def reset():
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
def export(name, **kw):
|
||||
bpy.ops.export_scene.fbx(filepath=os.path.join(out, name), **kw)
|
||||
|
||||
# 1. textured cube: material, uv, vertex colours, packed image
|
||||
reset()
|
||||
bpy.ops.mesh.primitive_cube_add(size=2, location=(1, 2, 3), rotation=(0.3, 0.2, 0.1))
|
||||
cube = bpy.context.object
|
||||
cube.name = "Cube"
|
||||
mesh = cube.data
|
||||
mesh.color_attributes.new("Col", "BYTE_COLOR", "CORNER")
|
||||
for i, d in enumerate(mesh.color_attributes["Col"].data):
|
||||
d.color = ((i % 3) / 2, (i % 5) / 4, (i % 7) / 6, 1)
|
||||
img = bpy.data.images.new("checker", 8, 8)
|
||||
img.pixels = [((x + y) % 2) * 1.0 if c < 3 else 1.0 for y in range(8) for x in range(8) for c in range(4)]
|
||||
img.filepath_raw = os.path.join(out, "checker.png")
|
||||
img.file_format = "PNG"
|
||||
img.save()
|
||||
img.pack()
|
||||
mat = bpy.data.materials.new("Red")
|
||||
mat.use_nodes = True
|
||||
bsdf = mat.node_tree.nodes["Principled BSDF"]
|
||||
bsdf.inputs["Base Color"].default_value = (0.8, 0.1, 0.1, 1)
|
||||
bsdf.inputs["Roughness"].default_value = 0.4
|
||||
tex = mat.node_tree.nodes.new("ShaderNodeTexImage")
|
||||
tex.image = img
|
||||
mat.node_tree.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
|
||||
mesh.materials.append(mat)
|
||||
mat2 = bpy.data.materials.new("Blue")
|
||||
mat2.diffuse_color = (0.1, 0.1, 0.9, 1)
|
||||
mesh.materials.append(mat2)
|
||||
for i, p in enumerate(mesh.polygons):
|
||||
p.material_index = i % 2
|
||||
bpy.ops.mesh.primitive_uv_sphere_add(segments=12, ring_count=6, location=(-3, 0, 0))
|
||||
bpy.context.object.name = "Sphere"
|
||||
bpy.context.object.parent = cube
|
||||
export("blender_cube.fbx", path_mode="COPY", embed_textures=True)
|
||||
|
||||
# 2. skinned, animated mesh with shape keys
|
||||
reset()
|
||||
bpy.ops.object.armature_add(location=(0, 0, 0))
|
||||
arm = bpy.context.object
|
||||
arm.name = "Rig"
|
||||
bpy.ops.object.mode_set(mode="EDIT")
|
||||
b0 = arm.data.edit_bones[0]
|
||||
b0.name = "root"
|
||||
b0.head, b0.tail = (0, 0, 0), (0, 0, 1)
|
||||
b1 = arm.data.edit_bones.new("tip")
|
||||
b1.head, b1.tail, b1.parent = (0, 0, 1), (0, 0, 2), b0
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
bpy.ops.mesh.primitive_cylinder_add(vertices=8, depth=2, radius=0.3, location=(0, 0, 1))
|
||||
cyl = bpy.context.object
|
||||
cyl.name = "Body"
|
||||
bpy.ops.object.mode_set(mode="EDIT")
|
||||
bpy.ops.mesh.subdivide(number_cuts=3)
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
cyl.shape_key_add(name="Basis")
|
||||
sk = cyl.shape_key_add(name="Fat")
|
||||
for v in sk.data:
|
||||
v.co.x *= 1.5
|
||||
v.co.y *= 1.5
|
||||
sk.value = 0.25
|
||||
cyl.select_set(True)
|
||||
arm.select_set(True)
|
||||
bpy.context.view_layer.objects.active = arm
|
||||
bpy.ops.object.parent_set(type="ARMATURE_AUTO")
|
||||
bpy.context.scene.frame_start, bpy.context.scene.frame_end = 1, 20
|
||||
bpy.ops.object.mode_set(mode="POSE")
|
||||
pb = arm.pose.bones["tip"]
|
||||
pb.rotation_mode = "XYZ"
|
||||
for f, a in ((1, 0), (10, 0.8), (20, 0)):
|
||||
pb.rotation_euler = (a, 0, 0)
|
||||
pb.keyframe_insert("rotation_euler", frame=f)
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
for f, v in ((1, 0), (20, 1)):
|
||||
sk.value = v
|
||||
sk.keyframe_insert("value", frame=f)
|
||||
export("blender_skin.fbx", add_leaf_bones=False, bake_anim=True)
|
||||
|
||||
# 3. camera and lights
|
||||
reset()
|
||||
bpy.ops.object.camera_add(location=(0, -5, 1), rotation=(math.pi / 2, 0, 0))
|
||||
bpy.context.object.data.lens = 35
|
||||
for kind, loc in (("POINT", (1, 0, 3)), ("SUN", (0, 0, 5)), ("SPOT", (2, 2, 2))):
|
||||
bpy.ops.object.light_add(type=kind, location=loc)
|
||||
bpy.context.object.data.energy = 10
|
||||
bpy.ops.mesh.primitive_plane_add(size=4)
|
||||
export("blender_camlight.fbx")
|
||||
@@ -0,0 +1,31 @@
|
||||
# tools/fixtures/_fbx_blender_stats: run by tools/fixtures/fbx.py inside Blender (blender -b --python <this> -- <json
|
||||
# list of paths>): imports each FBX with Blender's importer and prints one JSON line "STATS <list>" with per file
|
||||
# counts: mesh objects, polygons, vertices, materials, bones, actions, shape keys, cameras, lights, images; or
|
||||
# {"failed": message}.
|
||||
import bpy, sys, json
|
||||
paths = json.loads(sys.argv[sys.argv.index("--") + 1])
|
||||
res = []
|
||||
for p in paths:
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
try:
|
||||
r = bpy.ops.import_scene.fbx(filepath=p)
|
||||
if "FINISHED" not in r:
|
||||
raise RuntimeError(str(r))
|
||||
except Exception as e:
|
||||
res.append({"failed": str(e)[:200]})
|
||||
continue
|
||||
obs = bpy.context.scene.objects
|
||||
meshes = [o for o in obs if o.type == "MESH"]
|
||||
res.append({
|
||||
"meshes": len(meshes),
|
||||
"polygons": sum(len(o.data.polygons) for o in meshes),
|
||||
"vertices": sum(len(o.data.vertices) for o in meshes),
|
||||
"materials": len([m for m in bpy.data.materials if m.users > 0]),
|
||||
"bones": sum(len(o.data.bones) for o in obs if o.type == "ARMATURE"),
|
||||
"actions": len(bpy.data.actions),
|
||||
"shapeKeys": sum(len(o.data.shape_keys.key_blocks) - 1 for o in meshes if o.data.shape_keys),
|
||||
"cameras": len([o for o in obs if o.type == "CAMERA"]),
|
||||
"lights": len([o for o in obs if o.type == "LIGHT"]),
|
||||
"images": len([i for i in bpy.data.images if i.users > 0]),
|
||||
})
|
||||
print("STATS " + json.dumps(res))
|
||||
@@ -0,0 +1,38 @@
|
||||
-- tools/fixtures/_fbx_encode: run by tools/fixtures/fbx.py (luau CLI, repo root): decodes every FBX case with our
|
||||
-- reader and writes it back with our writer (binary 7.4, and ASCII for every third case), printing "<file>\t<hex>"
|
||||
-- lines for assimp and Blender to read back. Files: rt_<case>.fbx (binary), rt_<case>.a.fbx (ASCII).
|
||||
local Fbx = require("@formats/model/fbx")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/fbx_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = HEX[buffer.readu8(b, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local scene, err = Fbx.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
|
||||
if scene then
|
||||
local bin, e2 = Fbx.encode(scene)
|
||||
if bin then
|
||||
print(string.format("rt_%d.fbx\t%s", i, hex(bin)))
|
||||
else
|
||||
print("encode failed " .. c.name .. ": " .. tostring(e2))
|
||||
end
|
||||
if i % 3 == 0 then
|
||||
local a = Fbx.encode(scene, { ascii = true })
|
||||
if a then
|
||||
print(string.format("rt_%d.a.fbx\t%s", i, hex(a)))
|
||||
end
|
||||
end
|
||||
else
|
||||
print("skipped " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,27 @@
|
||||
-- tools/fixtures/_step_encode: run by tools/fixtures/step.py (luau CLI, repo root): decodes every STEP case with our
|
||||
-- reader and writes it back with our writer, printing "case_<i>.step\t<hex>" lines for OCCT (through gmsh) to read.
|
||||
local Step = require("@formats/cad/step")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/step_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = HEX[string.byte(s, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local cad, err = Step.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if cad then
|
||||
local out = assert(Step.encode(cad))
|
||||
print(string.format("case_%d.step\t%s", i, hex(buffer.tostring(out))))
|
||||
else
|
||||
print("skipped " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
-- tools/fixtures/_usda_encode: run by tools/fixtures/usda.py (luau CLI, repo root): decodes every USDA case with our
|
||||
-- reader and writes it back with our writer, printing "<file>\t<hex>" lines (case_<n>.usda + the texture files it
|
||||
-- references) for OpenUSD (pxr) to read back.
|
||||
local Usda = require("@formats/model/usda")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/usda_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = HEX[string.byte(s, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
if not c.expect then
|
||||
local scene = Usda.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
|
||||
if scene then
|
||||
local files = {}
|
||||
local out = assert(Usda.encode(scene, { files = files, name = "case_" .. i .. ".usda" }))
|
||||
print(string.format("case_%d.usda\t%s", i, hex(buffer.tostring(out))))
|
||||
for name, data in files do
|
||||
if not string.find(name, "%.%.") and string.sub(name, 1, 1) ~= "/" then
|
||||
print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,404 @@
|
||||
# OpenUSD (pxr) side of tools/fixtures/usda.py, run by ctx.python(["openusd"], <this file's text>) with a JSON
|
||||
# request on stdin:
|
||||
# {"mode": "author", "dir": d} -> writes the authored test stages into d (usda, plus a usdc and a usdz) and prints
|
||||
# the file names
|
||||
# {"mode": "metrics", "paths": [...]} -> prints [ metrics per file ] (see metrics() below)
|
||||
# {"mode": "convert", "src": a, "dst": b} -> usdc -> usda through Sdf (as usdcat does)
|
||||
# {"mode": "specs", "paths": [...]} -> the number of prim specs in each layer (parse-only checks)
|
||||
import json, math, os, struct, sys, zlib
|
||||
from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade, UsdUtils, Vt
|
||||
|
||||
req = json.loads(sys.stdin.read())
|
||||
|
||||
|
||||
def png(w, h, rgba):
|
||||
raw = b"".join(b"\0" + bytes(rgba[(y * w) * 4:(y * w + w) * 4]) for y in range(h))
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def cube(stage, path, size=1.0, quads=True):
|
||||
m = UsdGeom.Mesh.Define(stage, path)
|
||||
s = size / 2
|
||||
pts = [(-s, -s, -s), (s, -s, -s), (s, s, -s), (-s, s, -s), (-s, -s, s), (s, -s, s), (s, s, s), (-s, s, s)]
|
||||
faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
|
||||
m.CreatePointsAttr([Gf.Vec3f(*p) for p in pts])
|
||||
if quads:
|
||||
m.CreateFaceVertexCountsAttr([4] * 6)
|
||||
m.CreateFaceVertexIndicesAttr([i for f in faces for i in f])
|
||||
else:
|
||||
m.CreateFaceVertexCountsAttr([3] * 12)
|
||||
m.CreateFaceVertexIndicesAttr([i for f in faces for i in (f[0], f[1], f[2], f[0], f[2], f[3])])
|
||||
m.CreateExtentAttr([Gf.Vec3f(-s, -s, -s), Gf.Vec3f(s, s, s)])
|
||||
return m
|
||||
|
||||
|
||||
def author(d):
|
||||
names = []
|
||||
# 1. transforms: every op kind and order
|
||||
st = Usd.Stage.CreateInMemory()
|
||||
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y)
|
||||
UsdGeom.SetStageMetersPerUnit(st, 1.0)
|
||||
root = UsdGeom.Xform.Define(st, "/World")
|
||||
st.SetDefaultPrim(root.GetPrim())
|
||||
x = UsdGeom.Xform.Define(st, "/World/TRS")
|
||||
x.AddTranslateOp().Set(Gf.Vec3d(1, 2, 3))
|
||||
x.AddRotateXYZOp().Set(Gf.Vec3f(30, 45, 60))
|
||||
x.AddScaleOp().Set(Gf.Vec3f(1, 2, 0.5))
|
||||
cube(st, "/World/TRS/Cube")
|
||||
for k, order in enumerate(["XZY", "YXZ", "YZX", "ZXY", "ZYX"]):
|
||||
x = UsdGeom.Xform.Define(st, "/World/R%s" % order)
|
||||
x.AddTranslateOp().Set(Gf.Vec3d(k * 3, 0, 0))
|
||||
op = x.AddXformOp(getattr(UsdGeom.XformOp, "TypeRotate" + order))
|
||||
op.Set(Gf.Vec3f(10 + k, 70, -25))
|
||||
cube(st, "/World/R%s/Cube" % order, 0.5)
|
||||
x = UsdGeom.Xform.Define(st, "/World/Single")
|
||||
x.AddRotateYOp().Set(33.0)
|
||||
x.AddRotateXOp().Set(-12.0)
|
||||
x.AddScaleOp().Set(Gf.Vec3f(2, 2, 2))
|
||||
cube(st, "/World/Single/Cube")
|
||||
x = UsdGeom.Xform.Define(st, "/World/Orient")
|
||||
x.AddOrientOp().Set(Gf.Quatf(0.9238795, 0, 0.3826834, 0))
|
||||
x.AddTranslateOp().Set(Gf.Vec3d(0, 1, 0))
|
||||
cube(st, "/World/Orient/Cube")
|
||||
x = UsdGeom.Xform.Define(st, "/World/Pivot")
|
||||
x.AddTranslateOp().Set(Gf.Vec3d(5, 0, 0))
|
||||
piv = x.AddTranslateOp(opSuffix="pivot")
|
||||
piv.Set(Gf.Vec3d(1, 1, 0))
|
||||
x.AddRotateZOp().Set(90.0)
|
||||
x.AddTranslateOp(opSuffix="pivot", isInverseOp=True)
|
||||
cube(st, "/World/Pivot/Cube")
|
||||
x = UsdGeom.Xform.Define(st, "/World/Matrix")
|
||||
x.AddTransformOp().Set(Gf.Matrix4d(Gf.Rotation(Gf.Vec3d(1, 1, 0), 40), Gf.Vec3d(-2, 0, 4)) * Gf.Matrix4d().SetScale(Gf.Vec3d(1.5, 1.5, 1.5)))
|
||||
cube(st, "/World/Matrix/Cube")
|
||||
r = UsdGeom.Xform.Define(st, "/World/Matrix/Reset")
|
||||
r.SetResetXformStack(True)
|
||||
r.AddTranslateOp().Set(Gf.Vec3d(0, -3, 0))
|
||||
cube(st, "/World/Matrix/Reset/Cube", 0.25)
|
||||
neg = UsdGeom.Xform.Define(st, "/World/Negative")
|
||||
neg.AddScaleOp().Set(Gf.Vec3f(-1, 1, 1))
|
||||
cube(st, "/World/Negative/Cube")
|
||||
names.append(("xforms.usda", st))
|
||||
|
||||
# 2. primvars, interpolations, holes, orientation, n-gons
|
||||
st = Usd.Stage.CreateInMemory()
|
||||
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.z)
|
||||
UsdGeom.SetStageMetersPerUnit(st, 0.01)
|
||||
m = UsdGeom.Mesh.Define(st, "/Grid")
|
||||
st.SetDefaultPrim(m.GetPrim())
|
||||
n = 4
|
||||
pts = [Gf.Vec3f(i, j, 0.1 * i * j) for j in range(n + 1) for i in range(n + 1)]
|
||||
counts, idx = [], []
|
||||
for j in range(n):
|
||||
for i in range(n):
|
||||
a = j * (n + 1) + i
|
||||
counts.append(4)
|
||||
idx += [a, a + 1, a + n + 2, a + n + 1]
|
||||
# a pentagon and a triangle
|
||||
pts += [Gf.Vec3f(10, 0, 0), Gf.Vec3f(11, 0, 0), Gf.Vec3f(11.5, 1, 0), Gf.Vec3f(10.5, 2, 0), Gf.Vec3f(9.5, 1, 0)]
|
||||
b = (n + 1) * (n + 1)
|
||||
counts += [5, 3]
|
||||
idx += [b, b + 1, b + 2, b + 3, b + 4, b, b + 2, b + 3]
|
||||
m.CreatePointsAttr(pts)
|
||||
m.CreateFaceVertexCountsAttr(counts)
|
||||
m.CreateFaceVertexIndicesAttr(idx)
|
||||
m.CreateHoleIndicesAttr([5])
|
||||
pv = UsdGeom.PrimvarsAPI(m)
|
||||
stp = pv.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
|
||||
stp.Set([Gf.Vec2f(0, 0), Gf.Vec2f(1, 0), Gf.Vec2f(1, 1), Gf.Vec2f(0, 1)])
|
||||
stp.SetIndices(Vt.IntArray([k % 4 for k in range(len(idx))]))
|
||||
col = pv.CreatePrimvar("displayColor", Sdf.ValueTypeNames.Color3fArray, UsdGeom.Tokens.uniform)
|
||||
col.Set([Gf.Vec3f((k % 3) / 2, (k % 5) / 4, 1 - (k % 2)) for k in range(len(counts))])
|
||||
op = pv.CreatePrimvar("displayOpacity", Sdf.ValueTypeNames.FloatArray, UsdGeom.Tokens.vertex)
|
||||
op.Set([0.5 + 0.5 * (k % 2) for k in range(len(pts))])
|
||||
uv2 = pv.CreatePrimvar("uv2", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex)
|
||||
uv2.Set([Gf.Vec2f(p[0] / 12, p[1] / 4) for p in pts])
|
||||
m.CreateNormalsAttr([Gf.Vec3f(0, 0, 1)] * len(pts))
|
||||
m.SetNormalsInterpolation(UsdGeom.Tokens.vertex)
|
||||
m2 = cube(st, "/Grid/Left")
|
||||
m2.CreateOrientationAttr(UsdGeom.Tokens.leftHanded)
|
||||
UsdGeom.Xformable(m2).AddTranslateOp().Set(Gf.Vec3d(0, 0, 5))
|
||||
m3 = cube(st, "/Grid/ConstColor", 2)
|
||||
UsdGeom.Xformable(m3).AddTranslateOp().Set(Gf.Vec3d(0, 6, 0))
|
||||
m3.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant).Set([Gf.Vec3f(0.2, 0.4, 0.8)])
|
||||
names.append(("primvars.usda", st))
|
||||
|
||||
# 3. materials: textures, transforms, subsets, inherited bindings, interface inputs
|
||||
st = Usd.Stage.CreateInMemory()
|
||||
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y)
|
||||
root = UsdGeom.Xform.Define(st, "/Root")
|
||||
st.SetDefaultPrim(root.GetPrim())
|
||||
UsdGeom.Scope.Define(st, "/Root/Looks")
|
||||
|
||||
def surface(path, **inputs):
|
||||
mat = UsdShade.Material.Define(st, path)
|
||||
sh = UsdShade.Shader.Define(st, path + "/Surface")
|
||||
sh.CreateIdAttr("UsdPreviewSurface")
|
||||
for k, v in inputs.items():
|
||||
if isinstance(v, tuple):
|
||||
sh.CreateInput(k, Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*v))
|
||||
else:
|
||||
sh.CreateInput(k, Sdf.ValueTypeNames.Float).Set(v)
|
||||
mat.CreateSurfaceOutput().ConnectToSource(sh.ConnectableAPI(), "surface")
|
||||
return mat, sh
|
||||
|
||||
def texture(mat, sh, name, file, varname="st", wrap="repeat", transform=None, iface=False):
|
||||
path = mat.GetPath().pathString
|
||||
reader = UsdShade.Shader.Define(st, path + "/" + name + "_Reader")
|
||||
reader.CreateIdAttr("UsdPrimvarReader_float2")
|
||||
if iface:
|
||||
mi = mat.CreateInput("frame:stPrimvarName", Sdf.ValueTypeNames.Token)
|
||||
mi.Set(varname)
|
||||
reader.CreateInput("varname", Sdf.ValueTypeNames.Token).ConnectToSource(mi)
|
||||
else:
|
||||
reader.CreateInput("varname", Sdf.ValueTypeNames.Token).Set(varname)
|
||||
src = reader.ConnectableAPI()
|
||||
if transform:
|
||||
tr = UsdShade.Shader.Define(st, path + "/" + name + "_Transform")
|
||||
tr.CreateIdAttr("UsdTransform2d")
|
||||
tr.CreateInput("in", Sdf.ValueTypeNames.Float2).ConnectToSource(src, "result")
|
||||
tr.CreateInput("rotation", Sdf.ValueTypeNames.Float).Set(transform[0])
|
||||
tr.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(*transform[1]))
|
||||
tr.CreateInput("translation", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(*transform[2]))
|
||||
src = tr.ConnectableAPI()
|
||||
t = UsdShade.Shader.Define(st, path + "/" + name)
|
||||
t.CreateIdAttr("UsdUVTexture")
|
||||
t.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(file)
|
||||
t.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(src, "result")
|
||||
t.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set(wrap)
|
||||
t.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("clamp")
|
||||
return t.ConnectableAPI()
|
||||
|
||||
red, _ = surface("/Root/Looks/Red", diffuseColor=(0.8, 0.1, 0.1), metallic=0.25, roughness=0.75)
|
||||
glass, _ = surface("/Root/Looks/Glass", diffuseColor=(0.9, 0.9, 1.0), opacity=0.3, roughness=0.05, ior=1.33)
|
||||
glow, _ = surface("/Root/Looks/Glow", emissiveColor=(1.0, 0.5, 0.0), opacityThreshold=0.4, opacity=0.9)
|
||||
tex, tsh = surface("/Root/Looks/Textured", roughness=0.5)
|
||||
c = texture(tex, tsh, "Diffuse", "./textures/checker.png", iface=True)
|
||||
tsh.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(c, "rgb")
|
||||
mr = texture(tex, tsh, "MetalRough", "textures/mr.png", varname="uv2", wrap="mirror", transform=(30.0, (2, 2), (0.25, 0.5)))
|
||||
tsh.CreateInput("metallic", Sdf.ValueTypeNames.Float).ConnectToSource(mr, "b")
|
||||
tsh.CreateInput("roughness", Sdf.ValueTypeNames.Float).ConnectToSource(mr, "g")
|
||||
nrm = texture(tex, tsh, "Normal", "textures/normal.png")
|
||||
tsh.CreateInput("normal", Sdf.ValueTypeNames.Normal3f).ConnectToSource(nrm, "rgb")
|
||||
grp = UsdGeom.Xform.Define(st, "/Root/Group")
|
||||
UsdShade.MaterialBindingAPI.Apply(grp.GetPrim()).Bind(red)
|
||||
a = cube(st, "/Root/Group/Inherits")
|
||||
b = cube(st, "/Root/Group/Own")
|
||||
UsdGeom.Xformable(b).AddTranslateOp().Set(Gf.Vec3d(2, 0, 0))
|
||||
UsdShade.MaterialBindingAPI.Apply(b.GetPrim()).Bind(glass)
|
||||
s = cube(st, "/Root/Subsets", 1.0, quads=False)
|
||||
UsdGeom.Xformable(s).AddTranslateOp().Set(Gf.Vec3d(0, 3, 0))
|
||||
pv = UsdGeom.PrimvarsAPI(s)
|
||||
pv.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set([Gf.Vec2f((k % 2), (k // 2) % 2) for k in range(8)])
|
||||
pv.CreatePrimvar("uv2", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set([Gf.Vec2f((k % 4) / 4, k / 8) for k in range(8)])
|
||||
mb = UsdShade.MaterialBindingAPI.Apply(s.GetPrim())
|
||||
mb.Bind(glow)
|
||||
s1 = mb.CreateMaterialBindSubset("top", Vt.IntArray([0, 1, 2, 3]))
|
||||
UsdShade.MaterialBindingAPI.Apply(s1.GetPrim()).Bind(tex)
|
||||
s2 = mb.CreateMaterialBindSubset("side", Vt.IntArray([4, 5, 6]))
|
||||
UsdShade.MaterialBindingAPI.Apply(s2.GetPrim()).Bind(red)
|
||||
names.append(("materials.usda", st))
|
||||
|
||||
# 4. cameras and lights
|
||||
st = Usd.Stage.CreateInMemory()
|
||||
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y)
|
||||
root = UsdGeom.Xform.Define(st, "/Scene")
|
||||
st.SetDefaultPrim(root.GetPrim())
|
||||
cam = UsdGeom.Camera.Define(st, "/Scene/Persp")
|
||||
cam.CreateFocalLengthAttr(35)
|
||||
cam.CreateHorizontalApertureAttr(36)
|
||||
cam.CreateVerticalApertureAttr(24)
|
||||
cam.CreateClippingRangeAttr(Gf.Vec2f(0.1, 500))
|
||||
UsdGeom.Xformable(cam).AddTranslateOp().Set(Gf.Vec3d(0, 1, 10))
|
||||
o = UsdGeom.Camera.Define(st, "/Scene/Ortho")
|
||||
o.CreateProjectionAttr(UsdGeom.Tokens.orthographic)
|
||||
o.CreateHorizontalApertureAttr(40)
|
||||
o.CreateVerticalApertureAttr(30)
|
||||
UsdLux.DistantLight.Define(st, "/Scene/Sun").CreateIntensityAttr(3)
|
||||
sp = UsdLux.SphereLight.Define(st, "/Scene/Bulb")
|
||||
sp.CreateIntensityAttr(50)
|
||||
sp.CreateColorAttr(Gf.Vec3f(1, 0.8, 0.6))
|
||||
sp.CreateExposureAttr(2)
|
||||
UsdGeom.Xformable(sp).AddTranslateOp().Set(Gf.Vec3d(0, 4, 0))
|
||||
spot = UsdLux.SphereLight.Define(st, "/Scene/Spot")
|
||||
sh = UsdLux.ShapingAPI.Apply(spot.GetPrim())
|
||||
sh.CreateShapingConeAngleAttr(30)
|
||||
sh.CreateShapingConeSoftnessAttr(0.5)
|
||||
UsdLux.RectLight.Define(st, "/Scene/Panel").CreateIntensityAttr(7)
|
||||
UsdLux.DiskLight.Define(st, "/Scene/Disk")
|
||||
cube(st, "/Scene/Floor", 10)
|
||||
names.append(("camlights.usda", st))
|
||||
|
||||
# 5. time samples
|
||||
st = Usd.Stage.CreateInMemory()
|
||||
st.SetTimeCodesPerSecond(30)
|
||||
st.SetStartTimeCode(0)
|
||||
st.SetEndTimeCode(60)
|
||||
root = UsdGeom.Xform.Define(st, "/Anim")
|
||||
st.SetDefaultPrim(root.GetPrim())
|
||||
x = UsdGeom.Xform.Define(st, "/Anim/Mover")
|
||||
t = x.AddTranslateOp()
|
||||
for k, v in ((0, (0, 0, 0)), (30, (4, 1, 0)), (60, (4, 1, -6))):
|
||||
t.Set(Gf.Vec3d(*v), k)
|
||||
r = x.AddRotateXYZOp()
|
||||
for k, v in ((0, (0, 0, 0)), (20, (0, 90, 0)), (45, (30, 180, 10))):
|
||||
r.Set(Gf.Vec3f(*v), k)
|
||||
s = x.AddScaleOp()
|
||||
s.Set(Gf.Vec3f(1, 1, 1))
|
||||
cube(st, "/Anim/Mover/Box")
|
||||
y = UsdGeom.Xform.Define(st, "/Anim/Mover/Child")
|
||||
q = y.AddOrientOp()
|
||||
q.Set(Gf.Quatf(1, 0, 0, 0), 0)
|
||||
q.Set(Gf.Quatf(0.7071068, 0.7071068, 0, 0), 60)
|
||||
y.AddTranslateOp().Set(Gf.Vec3d(0, 2, 0))
|
||||
cube(st, "/Anim/Mover/Child/Box", 0.5)
|
||||
names.append(("anim.usda", st))
|
||||
|
||||
out = []
|
||||
for name, st in names:
|
||||
st.GetRootLayer().Export(os.path.join(d, name))
|
||||
out.append(name)
|
||||
os.makedirs(os.path.join(d, "textures"), exist_ok=True)
|
||||
checker = []
|
||||
for yy in range(8):
|
||||
for xx in range(8):
|
||||
v = 255 if (xx + yy) % 2 else 40
|
||||
checker += [v, v, v, 255]
|
||||
for f, data in (("checker.png", png(8, 8, checker)), ("mr.png", png(2, 2, [0, 128, 255, 255] * 4)), ("normal.png", png(2, 2, [128, 128, 255, 255] * 4))):
|
||||
with open(os.path.join(d, "textures", f), "wb") as fh:
|
||||
fh.write(data)
|
||||
# a usdc (UNSUPPORTED) and a usdz package of the materials stage
|
||||
Sdf.Layer.FindOrOpen(os.path.join(d, "xforms.usda")).Export(os.path.join(d, "xforms.usdc"))
|
||||
out.append("xforms.usdc")
|
||||
cwd = os.getcwd()
|
||||
os.chdir(d)
|
||||
UsdUtils.CreateNewUsdzPackage(Sdf.AssetPath("materials.usda"), "materials.usdz")
|
||||
os.chdir(cwd)
|
||||
out.append("materials.usdz")
|
||||
return out
|
||||
|
||||
|
||||
def mat16(m):
|
||||
return [float(m[i][j]) for i in range(4) for j in range(4)]
|
||||
|
||||
|
||||
def metrics(path):
|
||||
stage = Usd.Stage.Open(path)
|
||||
if stage is None:
|
||||
return {"failed": True}
|
||||
res = {
|
||||
"upAxis": str(UsdGeom.GetStageUpAxis(stage)),
|
||||
"metersPerUnit": float(UsdGeom.GetStageMetersPerUnit(stage)) if UsdGeom.StageHasAuthoredMetersPerUnit(stage) else -1.0,
|
||||
"tcps": float(stage.GetTimeCodesPerSecond()),
|
||||
"meshes": [], "xforms": [], "materials": [], "cameras": [], "lights": [], "anim": [],
|
||||
}
|
||||
t0 = Usd.TimeCode.EarliestTime()
|
||||
cache = UsdGeom.XformCache(t0)
|
||||
for prim in stage.Traverse():
|
||||
if not prim.IsA(UsdGeom.Xformable):
|
||||
continue
|
||||
path_s = prim.GetPath().pathString
|
||||
world = cache.GetLocalToWorldTransform(prim)
|
||||
res["xforms"].append({"path": path_s, "type": str(prim.GetTypeName()), "world": mat16(world)})
|
||||
x = UsdGeom.Xformable(prim)
|
||||
times = x.GetTimeSamples()
|
||||
if len(times) > 1:
|
||||
samples = []
|
||||
for t in times:
|
||||
samples.append({"time": float(t), "world": mat16(x.ComputeLocalToWorldTransform(t))})
|
||||
res["anim"].append({"path": path_s, "samples": samples})
|
||||
if prim.IsA(UsdGeom.Mesh):
|
||||
m = UsdGeom.Mesh(prim)
|
||||
pts = m.GetPointsAttr().Get(t0) or []
|
||||
counts = m.GetFaceVertexCountsAttr().Get(t0) or []
|
||||
idx = m.GetFaceVertexIndicesAttr().Get(t0) or []
|
||||
holes = set(m.GetHoleIndicesAttr().Get(t0) or [])
|
||||
wp = [world.Transform(Gf.Vec3d(*p)) for p in pts]
|
||||
tris, area, at = 0, 0.0, 0
|
||||
lo, hi = [math.inf] * 3, [-math.inf] * 3
|
||||
for f, c in enumerate(counts):
|
||||
corners = list(idx[at:at + c])
|
||||
at += c
|
||||
if c < 3 or f in holes:
|
||||
continue
|
||||
for k in range(1, c - 1):
|
||||
a, b, cc = wp[corners[0]], wp[corners[k]], wp[corners[k + 1]]
|
||||
area += 0.5 * Gf.Cross(b - a, cc - a).GetLength()
|
||||
tris += 1
|
||||
for v in corners:
|
||||
for j in range(3):
|
||||
lo[j] = min(lo[j], wp[v][j])
|
||||
hi[j] = max(hi[j], wp[v][j])
|
||||
mat, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
|
||||
subsets = UsdShade.MaterialBindingAPI(prim).GetMaterialBindSubsets()
|
||||
res["meshes"].append({
|
||||
"path": path_s, "triangles": tris, "area": area, "min": lo if tris else [], "max": hi if tris else [],
|
||||
"material": mat.GetPath().pathString if mat else "", "subsets": len(subsets),
|
||||
"subsetMaterials": sorted(
|
||||
(UsdShade.MaterialBindingAPI(sub.GetPrim()).ComputeBoundMaterial()[0].GetPath().pathString if UsdShade.MaterialBindingAPI(sub.GetPrim()).ComputeBoundMaterial()[0] else "") for sub in subsets),
|
||||
})
|
||||
if prim.IsA(UsdGeom.Camera):
|
||||
c = UsdGeom.Camera(prim)
|
||||
cr = c.GetClippingRangeAttr().Get(t0)
|
||||
res["cameras"].append({
|
||||
"path": path_s, "projection": str(c.GetProjectionAttr().Get(t0)), "focal": float(c.GetFocalLengthAttr().Get(t0)),
|
||||
"hap": float(c.GetHorizontalApertureAttr().Get(t0)), "vap": float(c.GetVerticalApertureAttr().Get(t0)),
|
||||
"near": float(cr[0]), "far": float(cr[1]),
|
||||
})
|
||||
for lt in ("DistantLight", "SphereLight", "RectLight", "DiskLight"):
|
||||
cls = getattr(UsdLux, lt)
|
||||
if prim.IsA(cls):
|
||||
l = cls(prim)
|
||||
col = l.GetColorAttr().Get(t0)
|
||||
cone = prim.GetAttribute("inputs:shaping:cone:angle")
|
||||
res["lights"].append({
|
||||
"path": path_s, "type": lt, "intensity": float(l.GetIntensityAttr().Get(t0)) * 2 ** float(l.GetExposureAttr().Get(t0)),
|
||||
"color": [float(v) for v in col], "cone": float(cone.Get(t0)) if cone and cone.HasAuthoredValue() else -1.0,
|
||||
})
|
||||
for prim in stage.Traverse():
|
||||
if not prim.IsA(UsdShade.Material):
|
||||
continue
|
||||
mat = UsdShade.Material(prim)
|
||||
surf = mat.ComputeSurfaceSource()
|
||||
sh = surf[0] if surf else None
|
||||
if not sh or sh.GetIdAttr().Get() != "UsdPreviewSurface":
|
||||
continue
|
||||
d = {"path": prim.GetPath().pathString, "textures": {}}
|
||||
for name in ("diffuseColor", "emissiveColor", "metallic", "roughness", "opacity", "opacityThreshold", "ior", "normal", "occlusion"):
|
||||
inp = sh.GetInput(name)
|
||||
if not inp:
|
||||
continue
|
||||
srcs = inp.GetConnectedSources()[0] if inp.HasConnectedSource() else []
|
||||
if srcs:
|
||||
src = UsdShade.Shader(srcs[0].source.GetPrim())
|
||||
f = src.GetInput("file")
|
||||
if f:
|
||||
d["textures"][name] = {"file": f.Get().path, "output": str(srcs[0].sourceName)}
|
||||
else:
|
||||
v = inp.Get()
|
||||
if v is not None:
|
||||
d[name] = [float(x) for x in v] if hasattr(v, "__len__") else float(v)
|
||||
res["materials"].append(d)
|
||||
return res
|
||||
|
||||
|
||||
mode = req["mode"]
|
||||
if mode == "author":
|
||||
print(json.dumps(author(req["dir"])))
|
||||
elif mode == "metrics":
|
||||
print(json.dumps([metrics(p) for p in req["paths"]]))
|
||||
elif mode == "convert":
|
||||
Sdf.Layer.FindOrOpen(req["src"]).Export(req["dst"])
|
||||
print("[]")
|
||||
elif mode == "specs":
|
||||
out = []
|
||||
for p in req["paths"]:
|
||||
layer = Sdf.Layer.FindOrOpen(p)
|
||||
n = [0]
|
||||
def visit(path):
|
||||
if path.IsPrimPath():
|
||||
n[0] += 1
|
||||
layer.Traverse(Sdf.Path.absoluteRootPath, visit)
|
||||
out.append(n[0])
|
||||
print(json.dumps(out))
|
||||
@@ -0,0 +1,106 @@
|
||||
# Collada fixtures (tools/fixtures.py): assimp's Collada test models (read from the nixpkgs assimp source at fixture
|
||||
# time, never committed: test/models/Collada, licences in that folder's licence.md), glTF sample models converted to
|
||||
# .dae by assimp's Collada exporter (skins, animations, cameras, textures), with reference values from `assimp info -r`
|
||||
# (meshes, faces, vertices, bounds, materials, animations, cameras, lights, bones). Blender 5 has no Collada support.
|
||||
# tests/gen/dae_cases.luau { name, main, data, files = { name -> bytes }, assimp, gltf? + gltfFiles? (the original
|
||||
# of an assimp export: the test compares skins and animations with it) }
|
||||
# tests/gen/dae_xcheck.luau our encoder's .dae of every case (tools/fixtures/_dae_encode.luau) read back by assimp:
|
||||
# { name, case, assimp }
|
||||
import importlib.util, os, re, subprocess
|
||||
|
||||
INPUTS = ["src/Formats/model/dae", "src/Formats/codecs/Xml", "tools/fixtures/_model_ref.py", "tools/fixtures/_dae_encode.luau",
|
||||
"tests/fixtures/gltf"]
|
||||
|
||||
|
||||
def ref_module(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def assimp_src():
|
||||
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
|
||||
return out.stdout.decode().strip().split("\n")[-1]
|
||||
|
||||
|
||||
def info(ctx, M, path):
|
||||
a = M.assimp_info(ctx, [path], raw=True)[0]
|
||||
try:
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
|
||||
except subprocess.CalledProcessError:
|
||||
return {"failed": True}
|
||||
for label in ("Animations", "Cameras", "Lights", "Bones", "Materials"):
|
||||
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
|
||||
if m:
|
||||
a[label.lower()] = int(m.group(1))
|
||||
# assimp's root node transform (its Collada importer bakes up axis / unit conversion into it): not reported by
|
||||
# `assimp info`; the test applies the conversion itself
|
||||
return a
|
||||
|
||||
|
||||
IMAGE_EXT = (".jpg", ".jpeg", ".png", ".tga", ".bmp")
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = ref_module(ctx)
|
||||
src = os.path.join(assimp_src(), "test", "models", "Collada")
|
||||
cases = []
|
||||
images = {f: os.path.join(src, f) for f in sorted(os.listdir(src)) if f.lower().endswith(IMAGE_EXT)}
|
||||
for f in sorted(os.listdir(src)):
|
||||
if not (f.lower().endswith(".dae") or f.lower().endswith(".zae")) or "_triangulate" in f:
|
||||
continue # the *_triangulate files are the same models again (fixture size)
|
||||
path = os.path.join(src, f)
|
||||
data = open(path, "rb").read()
|
||||
files = {}
|
||||
text = data.decode("latin-1")
|
||||
for im, ip in images.items():
|
||||
if im in text:
|
||||
files[im] = open(ip, "rb").read()
|
||||
cases.append({"name": "assimp/" + f, "main": f, "path": path, "files": files})
|
||||
# glTF samples -> assimp's Collada exporter
|
||||
tmp = M.tempdir()
|
||||
groot = os.path.join(ctx.root, "tests", "fixtures", "gltf")
|
||||
for model, variant, main in (("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("RiggedSimple", "glTF-Binary", "RiggedSimple.glb"),
|
||||
("BoxTextured", "glTF", "BoxTextured.gltf"), ("AnimatedTriangle", "glTF", "AnimatedTriangle.gltf"),
|
||||
("Cameras", "glTF", "Cameras.gltf"), ("BoxVertexColors", "glTF-Binary", "BoxVertexColors.glb"),
|
||||
("SimpleMeshes", "glTF", "SimpleMeshes.gltf"), ("InterpolationTest", "glTF-Binary", "InterpolationTest.glb"),
|
||||
("MultiUVTest", "glTF-Binary", "MultiUVTest.glb")):
|
||||
d = os.path.join(groot, model, variant)
|
||||
if not os.path.exists(os.path.join(d, main)):
|
||||
continue
|
||||
out = os.path.join(tmp, model + ".dae")
|
||||
try:
|
||||
ctx.nix("assimp", ["assimp", "export", os.path.join(d, main), out, "-fcollada"])
|
||||
except subprocess.CalledProcessError:
|
||||
continue
|
||||
files = {}
|
||||
text = open(out, "rb").read().decode("latin-1")
|
||||
for f in os.listdir(tmp):
|
||||
if f.lower().endswith(IMAGE_EXT) and f in text:
|
||||
files[f] = open(os.path.join(tmp, f), "rb").read()
|
||||
for f in os.listdir(d):
|
||||
if f.lower().endswith(IMAGE_EXT) and f in text:
|
||||
files[f] = open(os.path.join(d, f), "rb").read()
|
||||
orig = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != main}
|
||||
cases.append({"name": "assimp-export/" + model, "main": model + ".dae", "path": out, "files": files,
|
||||
"gltf": open(os.path.join(d, main), "rb").read(), "gltfFiles": orig})
|
||||
for c in cases:
|
||||
c["assimp"] = info(ctx, M, c["path"])
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
del c["path"]
|
||||
ctx.emit("dae_cases", cases)
|
||||
|
||||
# assimp reads our output
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_dae_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
names = []
|
||||
for name, data in sorted(ours.items()):
|
||||
with open(os.path.join(xtmp, name), "wb") as f:
|
||||
f.write(data)
|
||||
if name.endswith(".dae") or name.endswith(".zae"):
|
||||
names.append(name)
|
||||
out = []
|
||||
for n in names:
|
||||
out.append({"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": info(ctx, M, os.path.join(xtmp, n))})
|
||||
ctx.emit("dae_xcheck", out)
|
||||
@@ -0,0 +1,179 @@
|
||||
# FBX fixtures (tools/fixtures.py): assimp's FBX test models (binary 7.4 / 7.5, ASCII 7.4 / 7.5 / 7.7, embedded
|
||||
# textures, skeletons, animation; read from the nixpkgs assimp source, never committed), scenes exported by Blender
|
||||
# (tools/fixtures/_fbx_blender.py: materials, textures, vertex colours, skin, shape keys, animation, camera, lights)
|
||||
# and by assimp's FBX exporters (binary and ASCII), with reference values from assimp (`assimp info -r`: meshes,
|
||||
# faces, vertices, bounds, materials, animations, cameras, lights, bones) and Blender's importer
|
||||
# (tools/fixtures/_fbx_blender_stats.py). Then our encoder's output (tools/fixtures/_fbx_encode.luau) read back by
|
||||
# assimp and Blender.
|
||||
# tests/gen/fbx_cases.luau { name, data, files = { name -> bytes }, assimp, blender? }
|
||||
# tests/gen/fbx_xcheck.luau { name, case, assimp, blender? }
|
||||
# tests/gen/fbx_gltf.luau glTF sample models (tests/fixtures/gltf) for the writer round trips: { name, data, files }
|
||||
import importlib.util, json, os, shutil, subprocess
|
||||
|
||||
INPUTS = ["src/Formats/model/fbx", "tests/fixtures/gltf", "src/Formats/codecs/Deflate", "tools/fixtures/_model_ref.py",
|
||||
"tools/fixtures/_fbx_blender.py", "tools/fixtures/_fbx_blender_stats.py", "tools/fixtures/_fbx_encode.luau"]
|
||||
|
||||
|
||||
def ref_module(ctx):
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def assimp_extra(ctx, path):
|
||||
import re
|
||||
try:
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
|
||||
except subprocess.CalledProcessError:
|
||||
return {}
|
||||
out = {}
|
||||
for label in ("Animations", "Cameras", "Lights", "Bones", "Animation Channels"):
|
||||
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
|
||||
if m:
|
||||
out[label.lower().replace(" ", "_")] = int(m.group(1))
|
||||
return out
|
||||
|
||||
|
||||
def ptv_bounds(ctx, path, tmp):
|
||||
# world-space bounds: assimp's PreTransformVertices output (`assimp info` multiplies node matrices in the wrong
|
||||
# order for nested nodes, so its own bounds are not used)
|
||||
out = os.path.join(tmp, "ptv.obj")
|
||||
try:
|
||||
ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"])
|
||||
lo, hi = [1e30] * 3, [-1e30] * 3
|
||||
with open(out) as f:
|
||||
for line in f:
|
||||
if line.startswith("v "):
|
||||
v = [float(x) for x in line.split()[1:4]]
|
||||
lo = [min(a, b) for a, b in zip(lo, v)]
|
||||
hi = [max(a, b) for a, b in zip(hi, v)]
|
||||
os.remove(out)
|
||||
return {"min": lo, "max": hi} if lo[0] <= hi[0] else {}
|
||||
except (subprocess.CalledProcessError, OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def blender():
|
||||
return shutil.which("blender")
|
||||
|
||||
|
||||
def blender_stats(ctx, paths):
|
||||
exe = blender()
|
||||
if not exe or not paths:
|
||||
return [None] * len(paths)
|
||||
script = os.path.join(ctx.root, "tools", "fixtures", "_fbx_blender_stats.py")
|
||||
try:
|
||||
res = subprocess.run([exe, "-b", "--factory-startup", "--python", script, "--", json.dumps(paths)],
|
||||
capture_output=True, timeout=900)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
return [None] * len(paths)
|
||||
for line in res.stdout.decode("utf-8", "replace").split("\n"):
|
||||
if line.startswith("STATS "):
|
||||
return json.loads(line[6:])
|
||||
return [None] * len(paths)
|
||||
|
||||
|
||||
def assimp_src(ctx):
|
||||
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
|
||||
return out.stdout.decode().strip().split("\n")[-1]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = ref_module(ctx)
|
||||
tmp = M.tempdir()
|
||||
cases = []
|
||||
# assimp's test models (read only)
|
||||
src = os.path.join(assimp_src(ctx), "test", "models", "FBX")
|
||||
for root, _, files in sorted(os.walk(src)):
|
||||
for f in sorted(files):
|
||||
if f.lower().endswith(".fbx"):
|
||||
p = os.path.join(root, f)
|
||||
cases.append({"name": "assimp/" + os.path.relpath(p, src), "path": p, "files": {}})
|
||||
# Blender's exporter
|
||||
exe = blender()
|
||||
if exe:
|
||||
bdir = os.path.join(tmp, "blender")
|
||||
os.makedirs(bdir)
|
||||
subprocess.run([exe, "-b", "--factory-startup", "--python", os.path.join(ctx.root, "tools", "fixtures", "_fbx_blender.py"), "--", bdir],
|
||||
capture_output=True, check=True, timeout=600)
|
||||
for f in sorted(os.listdir(bdir)):
|
||||
if f.endswith(".fbx"):
|
||||
cases.append({"name": "blender/" + f, "path": os.path.join(bdir, f), "files": {}})
|
||||
# assimp's exporters: binary and ASCII, from a few glTF sample models (skin, morph, textures) and a PLY torus
|
||||
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
|
||||
for model, variant, main in (("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("BoxTextured", "glTF", "BoxTextured.gltf"),
|
||||
("RiggedSimple", "glTF-Binary", "RiggedSimple.glb"), ("Cameras", "glTF", "Cameras.gltf"),
|
||||
("BoxVertexColors", "glTF-Binary", "BoxVertexColors.glb")):
|
||||
inp = os.path.join(gl, model, variant, main)
|
||||
if not os.path.exists(inp):
|
||||
continue
|
||||
for fmt in ("fbx", "fbxa"):
|
||||
out = os.path.join(tmp, "%s_%s.fbx" % (model, fmt))
|
||||
try:
|
||||
ctx.nix("assimp", ["assimp", "export", inp, out, "-f" + fmt])
|
||||
except subprocess.CalledProcessError:
|
||||
continue
|
||||
cases.append({"name": "assimp-export/%s.%s" % (model, fmt), "path": out, "files": {}})
|
||||
paths = [c["path"] for c in cases]
|
||||
infos = M.assimp_info(ctx, paths, raw=True)
|
||||
bl = blender_stats(ctx, paths)
|
||||
for c, a, b in zip(cases, infos, bl):
|
||||
a.update(assimp_extra(ctx, c["path"]))
|
||||
a.pop("min", None)
|
||||
a.pop("max", None)
|
||||
a.update(ptv_bounds(ctx, c["path"], tmp))
|
||||
c["assimp"] = a
|
||||
if b:
|
||||
c["blender"] = b
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
# sibling files a model refers to (textures next to it)
|
||||
d = os.path.dirname(c["path"])
|
||||
for f in sorted(os.listdir(d)):
|
||||
if f.lower().endswith((".png", ".jpg", ".jpeg", ".tga")) and os.path.getsize(os.path.join(d, f)) < 300000:
|
||||
c["files"][f] = open(os.path.join(d, f), "rb").read()
|
||||
del c["path"]
|
||||
ctx.emit("fbx_cases", cases)
|
||||
|
||||
# glTF sample models for the writer round trips (glTF -> FBX -> Scene, compared with the glTF scene)
|
||||
picks = []
|
||||
for model in ("Box", "BoxTextured", "BoxVertexColors", "SimpleSkin", "RiggedSimple", "SimpleMorph", "AnimatedMorphCube",
|
||||
"Cameras", "MultiUVTest", "InterpolationTest", "NegativeScaleTest", "PointLightIntensityTest",
|
||||
"AnimatedTriangle", "TextureCoordinateTest", "MeshPrimitiveModes", "SimpleMeshes"):
|
||||
d0 = os.path.join(gl, model)
|
||||
if not os.path.isdir(d0):
|
||||
continue
|
||||
for variant in sorted(os.listdir(d0)):
|
||||
d = os.path.join(d0, variant)
|
||||
if not os.path.isdir(d):
|
||||
continue
|
||||
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
|
||||
if mains:
|
||||
picks.append({"name": model + "/" + variant, "data": open(os.path.join(d, mains[0]), "rb").read(),
|
||||
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
|
||||
break
|
||||
ctx.emit("fbx_gltf", picks)
|
||||
|
||||
# the reference tools read our output
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_fbx_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
names = sorted(n for n in ours if n.endswith(".fbx"))
|
||||
for name, data in ours.items():
|
||||
with open(os.path.join(xtmp, name), "wb") as f:
|
||||
f.write(data)
|
||||
xpaths = [os.path.join(xtmp, n) for n in names]
|
||||
xi = M.assimp_info(ctx, xpaths, raw=True)
|
||||
bin_paths = [p for p in xpaths if not p.endswith(".a.fbx")] # Blender reads binary FBX only
|
||||
xb_bin = dict(zip(bin_paths, blender_stats(ctx, bin_paths)))
|
||||
xb = [xb_bin.get(p) for p in xpaths]
|
||||
out = []
|
||||
for n, p, a, b in zip(names, xpaths, xi, xb):
|
||||
a.update(assimp_extra(ctx, p))
|
||||
a.pop("min", None)
|
||||
a.pop("max", None)
|
||||
a.update(ptv_bounds(ctx, p, xtmp))
|
||||
e = {"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": a}
|
||||
if b:
|
||||
e["blender"] = b
|
||||
out.append(e)
|
||||
ctx.emit("fbx_xcheck", out)
|
||||
@@ -0,0 +1,185 @@
|
||||
# STEP fixtures (tools/fixtures.py): solids modelled in gmsh's OpenCASCADE kernel and written as STEP by OCCT
|
||||
# (gmsh -0 x.geo -o x.step), plus public STEP files fetched at fixture time into a fresh temporary directory
|
||||
# (untrusted input, only read; skipped when offline). Reference values:
|
||||
# - a Part 21 instance census by an independent Python tokenizer (instance count, count per entity type),
|
||||
# - OCCT through gmsh's Python API: number of solids, total volume, number of faces, total area, bounding box.
|
||||
# Our writer's output (tools/fixtures/_step_encode.luau re-encodes every case) is read back by OCCT through gmsh too.
|
||||
# tests/gen/step_cases.luau { name, data, census = { count, types = { TYPE = n } }, occt = { solids, volume,
|
||||
# faces, area, bbox }, ours = occt values of our re-encoded file }
|
||||
# tests/gen/step_brep.luau brep-luau's modules ({ Step, StepBrep, StepWrite, Tess, Build, Boolean, M }) through the
|
||||
# tests/gen/.luaurc alias "brep" (only when ~/dev/luau/brep-luau, or $BREP_LUAU, exists; luau CLI only)
|
||||
import json, os, re, shutil, subprocess, tempfile, urllib.request
|
||||
|
||||
INPUTS = ["src/Formats/cad/step", "tools/fixtures/_step_encode.luau"]
|
||||
|
||||
GEO = {
|
||||
"plate": """Box(1) = {0,0,0, 40,30,5};
|
||||
Cylinder(2) = {20,15,-1, 0,0,7, 6};
|
||||
BooleanDifference{ Volume{1}; Delete; }{ Volume{2}; Delete; }""",
|
||||
"sphere": "Sphere(1) = {0,0,0, 10};",
|
||||
"torus": "Torus(1) = {0,0,0, 20, 5};",
|
||||
"cone": "Cone(1) = {0,0,0, 0,0,12, 6, 2};",
|
||||
"two_boxes": """Box(1) = {0,0,0, 10,10,10};
|
||||
Box(2) = {20,0,0, 5,5,30};""",
|
||||
"bracket": """Box(1) = {0,0,0, 60,40,8};
|
||||
Box(2) = {0,0,0, 8,40,50};
|
||||
BooleanUnion{ Volume{1}; Delete; }{ Volume{2}; Delete; }
|
||||
Cylinder(3) = {30,20,-1, 0,0,10, 7};
|
||||
Sphere(4) = {4,20,35, 9};
|
||||
BooleanDifference{ Volume{1}; Delete; }{ Volume{3,4}; Delete; }""",
|
||||
}
|
||||
|
||||
URLS = {
|
||||
# build123d documentation example (Apache-2.0)
|
||||
"nema17_bracket": "https://raw.githubusercontent.com/gumyr/build123d/dev/docs/topology_selection/examples/nema-17-bracket.step",
|
||||
# pythonocc-demos sample model (parse + OCCT reference only; not committed)
|
||||
"ventilator": "https://raw.githubusercontent.com/tpaviot/pythonocc-demos/master/assets/models/Ventilator.stp",
|
||||
}
|
||||
MAX_FETCH = 4 << 20
|
||||
|
||||
OCCT = r"""
|
||||
import json, sys, gmsh
|
||||
gmsh.initialize()
|
||||
gmsh.option.setNumber("General.Terminal", 0)
|
||||
res = []
|
||||
for p in json.loads(sys.stdin.read()):
|
||||
try:
|
||||
gmsh.clear()
|
||||
gmsh.model.occ.importShapes(p)
|
||||
gmsh.model.occ.synchronize()
|
||||
vols = gmsh.model.getEntities(3)
|
||||
faces = gmsh.model.getEntities(2)
|
||||
bb = gmsh.model.getBoundingBox(-1, -1)
|
||||
res.append({"solids": len(vols), "volume": sum(gmsh.model.occ.getMass(3, t) for _, t in vols),
|
||||
"faces": len(faces), "area": sum(gmsh.model.occ.getMass(2, t) for _, t in faces), "bbox": list(bb)})
|
||||
except Exception as e:
|
||||
res.append({"failed": True})
|
||||
print(json.dumps(res))
|
||||
"""
|
||||
|
||||
|
||||
def census(text):
|
||||
# an independent Part 21 tokenizer: comments and strings removed, statements split at ';'
|
||||
out = []
|
||||
i, n = 0, len(text)
|
||||
while i < n:
|
||||
c = text[i]
|
||||
if c == "'":
|
||||
j = i + 1
|
||||
while True:
|
||||
j = text.index("'", j)
|
||||
if j + 1 < n and text[j + 1] == "'":
|
||||
j += 2
|
||||
else:
|
||||
break
|
||||
out.append("''")
|
||||
i = j + 1
|
||||
elif c == "/" and text.startswith("/*", i):
|
||||
i = text.index("*/", i + 2) + 2
|
||||
else:
|
||||
out.append(c)
|
||||
i += 1
|
||||
clean = "".join(out)
|
||||
data = clean[clean.index("DATA"):]
|
||||
types = {}
|
||||
count = 0
|
||||
for st in data.split(";"):
|
||||
m = re.match(r"\s*#(\d+)\s*=\s*(\(|[A-Za-z_][A-Za-z0-9_]*)", st)
|
||||
if m:
|
||||
count += 1
|
||||
t = "COMPLEX" if m.group(2) == "(" else m.group(2).upper()
|
||||
types[t] = types.get(t, 0) + 1
|
||||
return {"count": count, "types": types}
|
||||
|
||||
|
||||
def occt(ctx, paths):
|
||||
expr = "with import <nixpkgs> {}; python3.withPackages (p: [p.gmsh])"
|
||||
cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", OCCT]
|
||||
res = subprocess.run(cmd, input=json.dumps(paths).encode(), capture_output=True, check=True)
|
||||
return json.loads(res.stdout)
|
||||
|
||||
|
||||
def luau(ctx, script):
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe, script] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script]
|
||||
res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True)
|
||||
files = {}
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if "\t" in line:
|
||||
name, hexdata = line.split("\t", 1)
|
||||
files[name] = bytes.fromhex(hexdata.strip())
|
||||
return files
|
||||
|
||||
|
||||
def brep(ctx):
|
||||
root = os.environ.get("BREP_LUAU") or os.path.expanduser("~/dev/luau/brep-luau")
|
||||
rc = os.path.join(ctx.gen, ".luaurc")
|
||||
mod = os.path.join(ctx.gen, "step_brep.luau")
|
||||
if not os.path.exists(os.path.join(root, "src", "step", "StepBrep.luau")):
|
||||
for p in (rc, mod):
|
||||
if os.path.exists(p):
|
||||
os.remove(p)
|
||||
ctx.emit("step_brep", False)
|
||||
return
|
||||
with open(rc, "w") as f:
|
||||
json.dump({"aliases": {"brep": os.path.join(os.path.abspath(root), "src")}}, f)
|
||||
path = os.path.join(ctx.gen, "step_brep.luau")
|
||||
with open(path, "w") as f:
|
||||
f.write("-- generated by tools/fixtures.py (tools/fixtures/step.py) - do not edit\n"
|
||||
"-- brep-luau through the tests/gen/.luaurc alias \"brep\" (luau CLI only)\n"
|
||||
"return {\n"
|
||||
"\tStep = require(\"@brep/step/Step\"),\n"
|
||||
"\tStepBrep = require(\"@brep/step/StepBrep\"),\n"
|
||||
"\tStepWrite = require(\"@brep/kernel/StepWrite\"),\n"
|
||||
"\tTess = require(\"@brep/kernel/Tess\"),\n"
|
||||
"\tBuild = require(\"@brep/kernel/Build\"),\n"
|
||||
"\tBoolean = require(\"@brep/kernel/Boolean\"),\n"
|
||||
"\tM = require(\"@brep/kernel/Math\"),\n"
|
||||
"}\n")
|
||||
ctx.outputs.append(path)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="formats-step-")
|
||||
cases = []
|
||||
for name, geo in GEO.items():
|
||||
g = os.path.join(tmp, name + ".geo")
|
||||
with open(g, "w") as f:
|
||||
f.write('SetFactory("OpenCASCADE");\n' + geo + "\n")
|
||||
out = os.path.join(tmp, name + ".step")
|
||||
ctx.nix("gmsh", ["gmsh", "-0", g, "-o", out])
|
||||
cases.append({"name": "gmsh/" + name, "path": out})
|
||||
fetched = tempfile.mkdtemp(prefix="formats-step-fetch-")
|
||||
for name, url in URLS.items():
|
||||
dst = os.path.join(fetched, name + ".step")
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=30) as r:
|
||||
data = r.read(MAX_FETCH + 1)
|
||||
if len(data) > MAX_FETCH:
|
||||
continue
|
||||
with open(dst, "wb") as f:
|
||||
f.write(data)
|
||||
cases.append({"name": "public/" + name, "path": dst, "public": True})
|
||||
except Exception:
|
||||
pass
|
||||
refs = occt(ctx, [c["path"] for c in cases])
|
||||
for c, r in zip(cases, refs):
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
c["census"] = census(c["data"].decode("latin-1"))
|
||||
c["occt"] = r
|
||||
# our writer's output of every case, read back by OCCT
|
||||
ctx.emit("step_cases", [{k: v for k, v in c.items() if k != "path"} for c in cases])
|
||||
ours = luau(ctx, "tools/fixtures/_step_encode.luau")
|
||||
xtmp = tempfile.mkdtemp(prefix="formats-step-ours-")
|
||||
paths = []
|
||||
for i in range(len(cases)):
|
||||
data = ours.get("case_%d.step" % (i + 1))
|
||||
p = os.path.join(xtmp, "case_%d.step" % (i + 1))
|
||||
with open(p, "wb") as f:
|
||||
f.write(data or b"")
|
||||
paths.append(p)
|
||||
back = occt(ctx, paths)
|
||||
for c, r in zip(cases, back):
|
||||
c["ours"] = r
|
||||
ctx.emit("step_cases", [{k: v for k, v in c.items() if k != "path"} for c in cases])
|
||||
brep(ctx)
|
||||
@@ -0,0 +1,264 @@
|
||||
# USDA fixtures (tools/fixtures.py): stages authored through OpenUSD's own API (pxr, nixpkgs python3Packages.openusd:
|
||||
# every xform op kind / order, pivots, !resetXformStack!, primvar interpolations + indices, holes, leftHanded, n-gons,
|
||||
# UsdPreviewSurface + UsdUVTexture / UsdTransform2d / interface inputs, GeomSubsets, inherited bindings, cameras,
|
||||
# UsdLux lights, time samples; plus a .usdc and a .usdz), assimp's USD test models (models-nonbsd/USD: the .usda files
|
||||
# and the .usdc ones converted to .usda by Sdf, read from the nixpkgs assimp source, not committed), Blender 5 USD
|
||||
# exports of glTF sample models (when blender is on PATH), a hand-written file exercising the text grammar, and the
|
||||
# OpenUSD schema layers (parse-only). Reference values come from pxr (Usd.Stage: world transforms, triangles / area /
|
||||
# bounds per mesh, bound materials, cameras, lights, xform time samples).
|
||||
# tests/gen/usda_cases.luau { name, data, files = { uri -> bytes }, ref = pxr metrics | nil, expect = "UNSUPPORTED"? }
|
||||
# tests/gen/usda_specs.luau { name, data, prims = number of prim specs (Sdf) }
|
||||
# tests/gen/usda_xcheck.luau our writer's .usda for every case (tools/fixtures/_usda_encode.luau) read back by pxr:
|
||||
# { name, case, ref }
|
||||
import json, os, shutil, subprocess, tempfile
|
||||
|
||||
INPUTS = ["src/Formats/model/usda", "tools/fixtures/_usda_reference.py", "tools/fixtures/_usda_encode.luau",
|
||||
"tools/fixtures/_model_ref.py", "tests/fixtures/gltf"]
|
||||
|
||||
# the text grammar: comments, metadata of every kind, list ops, variants, class / over, dictionaries, strings,
|
||||
# relative paths, typed values that the Scene ignores
|
||||
HANDWRITTEN = r'''#usda 1.0
|
||||
(
|
||||
"""A layer written by hand: every construct of the text format the reader has to get through."""
|
||||
customLayerData = {
|
||||
string creator = "formats-luau tests"
|
||||
dictionary nested = {
|
||||
int[] numbers = [1, 2, 3]
|
||||
double "quoted key" = 1.5
|
||||
}
|
||||
}
|
||||
defaultPrim = "Hand"
|
||||
metersPerUnit = 0.0254
|
||||
upAxis = "Z"
|
||||
timeCodesPerSecond = 24
|
||||
)
|
||||
|
||||
# a class (abstract: not a node) and an over of nothing
|
||||
class "_Template"
|
||||
{
|
||||
float3 xformOp:translate = (100, 100, 100)
|
||||
}
|
||||
|
||||
def Xform "Hand" (
|
||||
kind = "assembly"
|
||||
doc = 'single quoted doc'
|
||||
variants = {
|
||||
string look = "big"
|
||||
}
|
||||
prepend variantSets = "look"
|
||||
customData = { bool flag = true }
|
||||
)
|
||||
{
|
||||
custom string notes = """multi
|
||||
line""" // trailing comment
|
||||
custom asset path = @@@weird@name.png@@@
|
||||
custom double[] empty = []
|
||||
custom float big = inf
|
||||
custom float small = -inf
|
||||
custom token[] tokens = ["a", "b"]
|
||||
custom rel others = [</Hand/Big>, <../Hand>]
|
||||
reorder nameChildren = ["Big", "Tri"]
|
||||
|
||||
def Mesh "Tri" ( active = true )
|
||||
{
|
||||
point3f[] points = [(0,0,0),(1,0,0),(0,1,0)] ; int[] faceVertexCounts = [3]
|
||||
int[] faceVertexIndices = [0, 1, 2]
|
||||
double3 xformOp:translate = (1, 0, 0)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate"]
|
||||
rel material:binding = <../Looks/Blue>
|
||||
}
|
||||
|
||||
variantSet "look" = {
|
||||
"big" (doc = "selected") {
|
||||
def Mesh "Big"
|
||||
{
|
||||
float3 xformOp:scale = (3, 3, 3)
|
||||
uniform token[] xformOpOrder = ["xformOp:scale"]
|
||||
point3f[] points = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
|
||||
int[] faceVertexCounts = [4]
|
||||
int[] faceVertexIndices = [0, 1, 2, 3]
|
||||
color3f[] primvars:displayColor = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 1)] (
|
||||
interpolation = "vertex"
|
||||
)
|
||||
}
|
||||
}
|
||||
"small" {
|
||||
def Mesh "Small"
|
||||
{
|
||||
point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
|
||||
int[] faceVertexCounts = [3]
|
||||
int[] faceVertexIndices = [0, 1, 2]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def Scope "Looks"
|
||||
{
|
||||
def Material "Blue"
|
||||
{
|
||||
color3f inputs:tint = (0.1, 0.2, 0.9)
|
||||
token outputs:surface.connect = <Surface.outputs:surface>
|
||||
|
||||
def Shader "Surface"
|
||||
{
|
||||
uniform token info:id = "UsdPreviewSurface"
|
||||
color3f inputs:diffuseColor.connect = </Hand/Looks/Blue.inputs:tint>
|
||||
float inputs:roughness = 0.25
|
||||
token outputs:surface
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def "Untyped"
|
||||
{
|
||||
def Xform "Inner" (
|
||||
prepend references = @missing.usda@</Thing>
|
||||
)
|
||||
{
|
||||
matrix4d xformOp:transform.timeSamples = {
|
||||
0: ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ),
|
||||
10: ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 5, 1) ),
|
||||
}
|
||||
uniform token[] xformOpOrder = ["xformOp:transform"]
|
||||
|
||||
def Mesh "Quad"
|
||||
{
|
||||
point3f[] points = [(0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0)]
|
||||
int[] faceVertexCounts = [4]
|
||||
int[] faceVertexIndices = [0, 1, 2, 3]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
over "Elsewhere"
|
||||
{
|
||||
def Xform "Undefined"
|
||||
{
|
||||
double3 xformOp:translate = (0, 0, -1)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate"]
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
GLTF_MODELS = [("Box", "glTF", "Box.gltf"), ("BoxTextured", "glTF", "BoxTextured.gltf"), ("AnimatedTriangle", "glTF", "AnimatedTriangle.gltf"),
|
||||
("Cameras", "glTF", "Cameras.gltf"), ("MultiUVTest", "glTF-Binary", None), ("BoxVertexColors", "glTF-Binary", None)]
|
||||
|
||||
BLENDER = r'''
|
||||
import bpy, sys
|
||||
args = sys.argv[sys.argv.index("--") + 1:]
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
bpy.ops.import_scene.gltf(filepath=args[0])
|
||||
bpy.ops.wm.usd_export(filepath=args[1], export_materials=True, export_animation=True, relative_paths=True)
|
||||
'''
|
||||
|
||||
|
||||
def pxr(ctx, req):
|
||||
code = ctx.read("tools/fixtures/_usda_reference.py").decode()
|
||||
try:
|
||||
return json.loads(ctx.python(["openusd"], code, input=json.dumps(req).encode()))
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("pxr (%s) failed:\n%s" % (req["mode"], e.stderr.decode(errors="replace")[-3000:])) from None
|
||||
|
||||
|
||||
def files_under(d, skip):
|
||||
out = {}
|
||||
for root, _, fs in os.walk(d):
|
||||
for f in fs:
|
||||
p = os.path.join(root, f)
|
||||
rel = os.path.relpath(p, d).replace(os.sep, "/")
|
||||
if rel != skip and not rel.endswith((".usda", ".usdc", ".usdz", ".usd", ".py")):
|
||||
out[rel] = open(p, "rb").read()
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="formats-usda-")
|
||||
cases = [] # name, path, files, expect?
|
||||
# 1. stages authored through pxr
|
||||
adir = os.path.join(tmp, "authored")
|
||||
os.makedirs(adir)
|
||||
for name in pxr(ctx, {"mode": "author", "dir": adir}):
|
||||
p = os.path.join(adir, name)
|
||||
c = {"name": "pxr/" + name, "path": p, "files": files_under(adir, name)}
|
||||
if name.endswith(".usdc"):
|
||||
c["expect"] = "UNSUPPORTED"
|
||||
if name.endswith(".usdz"):
|
||||
c["files"] = {}
|
||||
c["like"] = "pxr/materials.usda"
|
||||
cases.append(c)
|
||||
# 2. hand-written grammar test
|
||||
hand = os.path.join(tmp, "hand.usda")
|
||||
with open(hand, "w") as f:
|
||||
f.write(HANDWRITTEN)
|
||||
cases.append({"name": "hand.usda", "path": hand, "files": {}})
|
||||
# 3. assimp's USD test models (untrusted data: read only, from the nix store)
|
||||
src = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().strip()
|
||||
usd = os.path.join(src, "test", "models-nonbsd", "USD")
|
||||
conv = os.path.join(tmp, "assimp")
|
||||
os.makedirs(conv)
|
||||
for f in sorted(os.listdir(os.path.join(usd, "usda"))):
|
||||
if f.endswith(".usda"):
|
||||
cases.append({"name": "assimp/" + f, "path": os.path.join(usd, "usda", f), "files": files_under(os.path.join(usd, "usda"), f)})
|
||||
for d, f in [(os.path.join(usd, "usdc"), x) for x in sorted(os.listdir(os.path.join(usd, "usdc"))) if x.endswith(".usdc")] + [(os.path.join(src, "test", "models", "USD"), "MotionCaptureROM.usdc")]:
|
||||
dst = os.path.join(conv, f[:-5] + ".usda")
|
||||
pxr(ctx, {"mode": "convert", "src": os.path.join(d, f), "dst": dst})
|
||||
cases.append({"name": "assimp/" + f + " (usdcat)", "path": dst, "files": files_under(d, f)})
|
||||
# 4. Blender USD exports of glTF samples
|
||||
if shutil.which("blender"):
|
||||
bdir = os.path.join(tmp, "blender")
|
||||
os.makedirs(bdir)
|
||||
script = os.path.join(tmp, "blender_export.py")
|
||||
with open(script, "w") as f:
|
||||
f.write(BLENDER)
|
||||
groot = os.path.join(ctx.root, "tests", "fixtures", "gltf")
|
||||
for model, variant, main in GLTF_MODELS:
|
||||
d = os.path.join(groot, model, variant)
|
||||
if not os.path.isdir(d):
|
||||
continue
|
||||
main = main or [x for x in sorted(os.listdir(d)) if x.endswith((".gltf", ".glb"))][0]
|
||||
out = os.path.join(bdir, model, model + ".usda")
|
||||
os.makedirs(os.path.dirname(out), exist_ok=True)
|
||||
r = subprocess.run(["blender", "-b", "--factory-startup", "--python", script, "--", os.path.join(d, main), out], capture_output=True)
|
||||
if r.returncode == 0 and os.path.exists(out):
|
||||
cases.append({"name": "blender/" + model, "path": out, "files": files_under(os.path.dirname(out), model + ".usda")})
|
||||
refs = pxr(ctx, {"mode": "metrics", "paths": [c["path"] for c in cases if "expect" not in c]})
|
||||
k = 0
|
||||
for c in cases:
|
||||
if "expect" not in c:
|
||||
c["ref"] = refs[k]
|
||||
k += 1
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
del c["path"]
|
||||
ctx.emit("usda_cases", cases)
|
||||
|
||||
# 5. parse-only: OpenUSD's schema layers
|
||||
usdpkg = ctx.python(["openusd"], "import pxr, os; print(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(pxr.__file__)))))))").decode().strip()
|
||||
specs = []
|
||||
for root, _, fs in os.walk(usdpkg):
|
||||
for f in fs:
|
||||
if f.endswith(".usda") and ("usdGeom" in root or "usdShade" in root or "usdLux" in root or "usdSkel" in root):
|
||||
specs.append(os.path.join(root, f))
|
||||
specs = sorted(specs)[:8]
|
||||
counts = pxr(ctx, {"mode": "specs", "paths": specs})
|
||||
ctx.emit("usda_specs", [{"name": os.path.relpath(p, usdpkg), "data": open(p, "rb").read(), "prims": n} for p, n in zip(specs, counts)])
|
||||
|
||||
# 6. pxr reads our writer's output
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe, "tools/fixtures/_usda_encode.luau"] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_usda_encode.luau"]
|
||||
res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True)
|
||||
xdir = os.path.join(tmp, "ours")
|
||||
os.makedirs(xdir)
|
||||
mains = []
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if "\t" in line:
|
||||
name, hexdata = line.split("\t", 1)
|
||||
p = os.path.join(xdir, name)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
with open(p, "wb") as f:
|
||||
f.write(bytes.fromhex(hexdata.strip()))
|
||||
if name.endswith(".usda") and "/" not in name:
|
||||
mains.append(name)
|
||||
xrefs = pxr(ctx, {"mode": "metrics", "paths": [os.path.join(xdir, n) for n in mains]})
|
||||
ctx.emit("usda_xcheck", [{"name": n, "case": int(n[5:].split(".")[0]), "ref": r} for n, r in zip(mains, xrefs)])
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
Reference in new issue
Block a user