diff --git a/src/Rosetta/model/3ds/Build.luau b/src/Rosetta/model/3ds/Build.luau index d01a3ea..e685888 100644 --- a/src/Rosetta/model/3ds/Build.luau +++ b/src/Rosetta/model/3ds/Build.luau @@ -1,11 +1,9 @@ --!strict --- model/3ds/Build: model/3ds/Read's chunk tables -> Types.Scene. The 3DS model: mesh vertices are stored in world --- space and the mesh matrix (0x4160) is the object's world transform; the keyframer places node(t) = parent(t) * --- T(pos) * R(rot) * S(scale) and draws a mesh at node(t) * T(-pivot) * inverse(mesh matrix) (a mirroring mesh matrix --- also flips x, as 3ds Max writes it and assimp reads it). Rotation keys are axis / angle deltas from the previous key --- (the angle measured clockwise). Cameras and spotlights look at their target node's position, with the camera's --- roll about the view axis. Smoothing groups give the normals (corners of faces that share a group and a position --- are averaged; group 0 is flat). Times are frame / fps. +-- model/3ds/Build: Read's chunk tables -> Types.Scene. +-- 3DS transforms: mesh vertices are in world space and the mesh matrix (0x4160) is the object's world transform; a +-- keyframer node is parent * T(pos) * R(rot) * S(scale) and draws its mesh at node * T(-pivot) * inverse(mesh matrix) +-- (a mirroring mesh matrix also flips x, as 3ds Max writes and assimp reads). Rotation keys are clockwise axis / angle +-- deltas from the previous key. Smoothing group 0 is flat. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") local Read = require("@rosetta/model/3ds/Read") @@ -20,7 +18,6 @@ local sqrt, abs = math.sqrt, math.abs export type Options = { normals: boolean?, flipV: boolean?, fps: number? } -- ------------------------------------------------------------------------------------------------ math --- the mesh matrix (X, Y, Z axes, origin) as a column-major 4x4 local function meshMatrix(m: { number }?): { number } if not m then return Mat4.identity() @@ -34,7 +31,6 @@ local function det3(m: { number }): number end Build.det3 = det3 --- q(a) * q(b) local function qmul(a: { number }, b: { number }): { number } local ax, ay, az, aw = a[1], a[2], a[3], a[4] local bx, by, bz, bw = b[1], b[2], b[3], b[4] @@ -47,7 +43,7 @@ local function qmul(a: { number }, b: { number }): { number } end Build.qmul = qmul --- a rotation key (angle in radians, axis) -> its quaternion (3DS angles turn clockwise) +-- 3DS angles turn clockwise local function keyQuat(angle: number, x: number, y: number, z: number): { number } if x == 0 and y == 0 and z == 0 then return { 0, 0, 0, 1 } @@ -63,7 +59,7 @@ local function normalize(x: number, y: number, z: number): (number, number, numb return x / l, y / l, z / l, l end --- lookAt(pos, target, rollDegrees) -> the rotation whose -Z looks from pos to target, +Y up (world up +Z) +-- -Z looks from pos to target, world up +Z function Build.lookAt(p: { number }, t: { number }, roll: number): { number } local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3]) if l == 0 then @@ -73,7 +69,6 @@ function Build.lookAt(p: { number }, t: { number }, roll: number): { number } if abs(fz) > 0.999999 then ux, uy, uz = 0, 1, 0 end - -- right = forward x up, up = right x forward local rx, ry, rz = normalize(fy * uz - fz * uy, fz * ux - fx * uz, fx * uy - fy * ux) ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx local a = math.rad(roll) @@ -163,18 +158,14 @@ local function materials(raw: Read.Raw, scene: Types.Scene): { [string]: number end -- ------------------------------------------------------------------------------------------------ meshes --- mesh(obj, xf, matByName, opts) -> a Types.Mesh of the object's faces (one primitive per material), vertices moved --- by xf (world -> the node's local space) local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [string]: number }, opts: Options): Types.Mesh local nv, nf = m.nv, m.nf local pos, faces = m.positions, m.faces - -- local positions local lp = table.create(nv * 3, 0) for v = 0, nv - 1 do local x, y, z = Mat4.point(xf, readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)) lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] = x, y, z end - -- faces with valid corners, their materials local fa, fb, fc = table.create(nf, 0), table.create(nf, 0), table.create(nf, 0) local valid = table.create(nf, false) for f = 0, nf - 1 do @@ -193,7 +184,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st end local smooth = m.smoothing local doNormals = opts.normals ~= false - -- face normals (area weighted) and the faces around each distinct position local fn = table.create(nf * 3, 0) local around: { [number]: { number } } = {} local group = table.create(nv, 0) @@ -248,7 +238,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st local nx, ny, nz = normalize(x, y, z) return nx, ny, nz end - -- primitives in the order their material first appears local order: { number } = {} local byMat: { [number]: { number } } = {} for f = 1, nf do @@ -321,7 +310,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st end -- ------------------------------------------------------------------------------------------------ tracks --- the value of a track at a frame (linear between keys, clamped at the ends) local function evalTrack(t: Read.Track?, frame: number, default: { number }): { number } if not t or #t.frames == 0 then return default @@ -359,7 +347,6 @@ local function scaleKey(v: { number }): { number } return { if v[1] == 0 then 1 else v[1], if v[2] == 0 then 1 else v[2], if v[3] == 0 then 1 else v[3] } end --- absolute rotations from a rotation track: times (frames), quaternions; deltas over ~180 degrees get extra keys local function rotations(t: Read.Track): ({ number }, { { number } }) local frames, quats = {}, {} local acc: { number }? = nil @@ -396,7 +383,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene local fps = o.fps or 30 local scene = S.new() local matByName = materials(raw, scene) - -- objects by name local objByName: { [string]: Read.Object } = {} for _, obj in raw.objects do if objByName[obj.name] == nil then @@ -478,7 +464,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene local kf = raw.keyframer local kfNodes = if kf then kf.nodes else {} - -- targets of cameras / spotlights by name local targets: { [string]: Read.Node } = {} for _, n in kfNodes do if n.kind == "target" or n.kind == "lightTarget" then @@ -486,7 +471,7 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene end end local placedObj: { [Read.Object]: boolean } = {} - local sceneOf: { [number]: number } = {} -- kf id -> scene node + local sceneOf: { [number]: number } = {} local channels: { Types.Channel } = {} local function channel(node: number, path: any, times: { number }, values: { number }, comps: number) for i = 1, #times do @@ -551,7 +536,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene channel(ni, "scale", table.clone(tr.scl.frames), vals, 3) end else - -- cameras and lights: position, target, roll local isCam = kind == "camera" local cam = if obj and isCam then obj.camera else nil local lit = if obj and not isCam then obj.light else nil @@ -581,7 +565,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene end local ni = addNode(node, parent) sceneOf[id] = ni - -- every key time of the position, roll and target tracks local set: { [number]: boolean } = {} local times: { number } = {} for _, t in { tr.pos, tr.roll, if aims and tgt then tgt.tracks.pos else nil } do @@ -612,7 +595,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene end end end - -- objects the keyframer does not place (or files without one): at their own matrix / position for _, obj in raw.objects do if placedObj[obj] then continue diff --git a/src/Rosetta/model/3ds/Read.luau b/src/Rosetta/model/3ds/Read.luau index 648b4c5..31e53ea 100644 --- a/src/Rosetta/model/3ds/Read.luau +++ b/src/Rosetta/model/3ds/Read.luau @@ -1,10 +1,6 @@ --!strict --- model/3ds/Read: the 3DS chunk tree (a u16 id and a u32 size that counts the 6-byte header, little endian) read --- into plain tables: materials, named objects (triangle meshes, cameras, lights) and the keyframer (nodes with their --- tracks). Chunk ids and layouts from the 3D Studio file format as documented by Autodesk's 3DS File Toolkit notes --- and read by assimp's 3DS importer (BSD-3, used as the reference) and lib3ds (read for the layout only, no code). --- Unknown chunks are skipped. A chunk running past the end of the data is an error; one running past its parent is --- clipped to the parent. Never throws on bad data: returns nil, message, offset. +-- model/3ds/Read: the 3DS chunk tree (u16 id, u32 size including the 6-byte header, little endian) -> plain tables. +-- Unknown chunks are skipped; a chunk past the end of the data is an error, one past its parent is clipped to it. local Read = {} local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32 @@ -28,17 +24,14 @@ local C = { } Read.C = C --- material map chunks -> their name in Raw materials Read.MAPS = { [0xA200] = "diffuse", [0xA33A] = "diffuse2", [0xA210] = "opacity", [0xA230] = "bump", [0xA204] = "specular", [0xA33C] = "shininess", [0xA33D] = "selfIllum", [0xA220] = "reflection", } --- keyframer node chunks -> kind local NODE_KINDS = { [0xB001] = "ambient", [0xB002] = "object", [0xB003] = "camera", [0xB004] = "target", [0xB005] = "light", [0xB006] = "lightTarget", [0xB007] = "spot", } --- track chunks -> (field, values per key) local TRACKS: { [number]: { any } } = { [0xB020] = { "pos", 3 }, [0xB021] = { "rot", 4 }, [0xB022] = { "scl", 3 }, [0xB023] = { "fov", 1 }, [0xB024] = { "roll", 1 }, [0xB025] = { "color", 3 }, [0xB027] = { "hotspot", 1 }, [0xB028] = { "falloff", 1 }, @@ -59,7 +52,7 @@ export type Mesh = { nf: number, faces: buffer?, -- nf * 4 u16 (a, b, c, flags) faceMats: { { name: string, faces: { number } } }, -- 0-based face numbers smoothing: buffer?, -- nf u32 - matrix: { number }?, -- 12 floats: the X, Y, Z axes and the origin (world space) + matrix: { number }?, -- 12 floats: X, Y, Z axes, origin (world space) } export type Camera = { pos: { number }, target: { number }, roll: number, lens: number, near: number?, far: number? } export type Light = { @@ -82,13 +75,12 @@ export type Raw = { -- ------------------------------------------------------------------------------------------------ helpers type Ctx = { b: buffer, limit: number, maxVertices: number, raw: Raw } --- each(ctx, p, stop, fn): calls fn(id, body, chunkEnd) for the chunks of [p, stop); returns fn's error or a size error local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, number) -> (string?, number?)): (string?, number?) local b = ctx.b while p + 6 <= stop do local id, size = readu16(b, p), readu32(b, p + 2) if size < 6 then - return nil, nil -- padding or garbage after the last chunk + return nil, nil end local e = p + size if e > ctx.limit then @@ -103,7 +95,6 @@ local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, numb return nil, nil end --- cstring(b, p, stop) -> the NUL-terminated string at p, the offset after it | nil local function cstring(b: buffer, p: number, stop: number): (string?, number) for q = p, stop - 1 do if readu8(b, q) == 0 then @@ -117,7 +108,7 @@ local function vec3(b: buffer, p: number): { number } return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } end --- a colour chunk list: the first float or byte colour (gamma-corrected "linear" variants only when nothing else) +-- colour chunks: the first float or byte colour (the gamma-corrected variants only when nothing else) local function color(ctx: Ctx, p: number, stop: number): { number }? local b = ctx.b local main: { number }?, lin: { number }? = nil, nil @@ -142,7 +133,6 @@ local function color(ctx: Ctx, p: number, stop: number): { number }? return main or lin end --- a percentage chunk list -> a fraction 0..1 local function percent(ctx: Ctx, p: number, stop: number): number? local b = ctx.b local v: number? = nil @@ -472,7 +462,6 @@ local function editor(ctx: Ctx, p: number, stop: number): (string?, number?) end) end --- parse(b, base, limit, opts) -> Raw | nil, message, offset function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, string?, number?) if limit - base < 6 or readu16(b, base) ~= C.MAIN then return nil, "not a 3DS file (no 0x4D4D main chunk)", base @@ -483,7 +472,6 @@ function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, if size < 6 then return nil, "bad main chunk size", base end - -- a main chunk declared longer than the data: truncated if base + size > limit then return nil, "truncated: the main chunk runs past the end of the data", base end diff --git a/src/Rosetta/model/3ds/Write.luau b/src/Rosetta/model/3ds/Write.luau index 18ba0c7..38b9ee0 100644 --- a/src/Rosetta/model/3ds/Write.luau +++ b/src/Rosetta/model/3ds/Write.luau @@ -1,13 +1,6 @@ --!strict --- model/3ds/Write: Types.Scene -> 3DS. One named object per mesh (split at 65535 vertices / faces), vertices in world --- space at the first node that shows the mesh, its world matrix as the mesh matrix, uvs (v flipped back to 3DS's --- bottom-left origin), smoothing groups (extras["3ds"].smoothing from model/3ds, else 0 for flat-shaded faces and 1 --- for the others), per-face materials; Phong materials (extras["3ds"] when present, else from the PBR fields) with --- texture maps (file names: texture.uri, or a name for texture.data put into opts.files); cameras (lens from yfov and --- aspect, target along -Z) and lights (omni / spot; directional lights become spots); the keyframer: every node in --- tree order (object nodes, $$$DUMMY nodes for empty ones, camera / light nodes with their targets), pivot 0, one key --- per track or the keys of the first animation (frames = round(time * fps)), rotation keys as axis / angle deltas. --- Mirroring nodes are written the way 3ds Max does (positive keyframer transform, mirror in the mesh matrix). +-- model/3ds/Write: Types.Scene -> 3DS. Objects split at 65535 vertices / faces; mirroring nodes written as 3ds Max does +-- (positive keyframer transform, mirror in the mesh matrix). local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Sampler = require("@rosetta/codecs/model/Sampler") @@ -108,7 +101,6 @@ local function unit(x: number, y: number, z: number): (number, number, number) return x / l, y / l, z / l end --- a quaternion -> the 3DS (clockwise angle, axis) local function axisAngle(q: { number }): (number, number, number, number) local x, y, z, w = q[1], q[2], q[3], q[4] local n = sqrt(x * x + y * y + z * z + w * w) @@ -128,7 +120,6 @@ local function conj(q: { number }): { number } return { -q[1], -q[2], -q[3], q[4] } end --- a channel's value at a time (codecs/model/Sampler: STEP, LINEAR with slerp, CUBICSPLINE) local function sample(ch: Types.Channel, t: number): { number } local f = Sampler.channel(ch) if not f then @@ -191,7 +182,6 @@ local function writeMaterial(w: W, m: Types.Material, mname: string, files: { [n if x.wire then leaf(w, C.MAT_WIRE, function() end) end - -- maps: the PBR texture refs first, then the other kinds model/3ds read local maps: { [string]: any } = {} local function fromRef(ref: Types.TextureRef?, saved: any): any if not ref or not files[ref.texture] then @@ -246,7 +236,6 @@ end -- ------------------------------------------------------------------------------------------------ meshes type Part = { name: string, positions: { number }, uvs: { number }?, faces: { number }, smooth: { number }, mats: { [number]: { number } } } --- the mesh as 3DS parts (local space), or nil, message local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, string?) local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { mesh } }, function(n: string): boolean return n == "TEXCOORD_0" or n == "NORMAL" @@ -260,7 +249,6 @@ local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, local tv, tc = if T then T.values else nil, if T then T.components else 0 local flipV = opts.flipV ~= false local corners = merged.corners - -- per face: material, smoothing group local nf = #corners // 3 local fmat, fsg = table.create(nf, 0), table.create(nf, 1) for _, part in merged.parts do @@ -272,7 +260,6 @@ local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, if savedOk then fsg[f] = saved[f - part.firstFace] elseif N then - -- flat when every corner normal is the face normal local a, b, c = corners[f * 3 - 2], corners[f * 3 - 1], corners[f * 3] local e1 = { P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3] } local e2 = { P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3] } @@ -398,7 +385,6 @@ local function writeMesh(w: W, part: Part, M: { number }, matNames: { [number]: end -- ------------------------------------------------------------------------------------------------ cameras / lights --- the eye, target and roll of a node's world matrix (looking down -Z, Y up) local function aim(m: { number }, dist: number): ({ number }, { number }, number) local p = { m[13], m[14], m[15] } local fx, fy, fz = unit(-m[9], -m[10], -m[11]) @@ -406,7 +392,6 @@ local function aim(m: { number }, dist: number): ({ number }, { number }, number fx, fy, fz = 0, 0, -1 end local t = { p[1] + fx * dist, p[2] + fy * dist, p[3] + fz * dist } - -- the roll: the angle from the unrolled up vector (Build.lookAt) to the node's Y axis local q0 = Build.lookAt(p, t, 0) local m0 = Mat4.fromQuat(q0) local ux, uy, uz = unit(m[5], m[6], m[7]) @@ -490,11 +475,10 @@ local function writeTrack(w: W, id: number, frames: { number }, values: { number end type KfNode = { - chunk: number, name: string, instance: string?, parent: number, -- parent: kf index or -1 + chunk: number, name: string, instance: string?, parent: number, -- kf index or -1 frames: { [string]: { number } }, values: { [string]: { number } }, } --- frames (rounded, strictly increasing) and the indices of the channel keys they keep local function frameKeys(ch: Types.Channel, fps: number): ({ number }, { number }) local IN = S.reader(ch.input) :: any local frames, keep = {}, {} @@ -558,7 +542,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) leaf(w, C.MESH_VERSION, function() w:u32le(3) end) - -- materials (unique names) local files = textureFiles(scene, o) local matNames: { [number]: string } = {} local used: { [string]: boolean } = {} @@ -578,7 +561,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) leaf(w, C.MASTER_SCALE, function() w:f32le(1) end) - -- meshes: at the first node showing them; their kf world (mirrors moved out of the keyframer) used = {} local firstNode: { [number]: number } = {} for _, i in order do @@ -608,7 +590,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) writeMesh(w, part, M, matNames) end end - -- the keyframer world of each node: W, or W * flip-x where the node's mesh matrix mirrors local KW: { [number]: { number } } = {} for _, i in order do local n = scene.nodes[i] @@ -645,7 +626,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) local kn: KfNode = { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } } table.insert(kfs, kn) local idx = #kfs - -- animated root cameras / lights: position, target and roll at the key times local chs: any = if p == 0 then byNode[i] else nil local targetFrames, targetVals = { 0 }, tgt if chs and (chs.translation or chs.rotation) then @@ -707,7 +687,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) end if onlyThis and idx then kfOf[i] = idx - -- the node's frame in the keyframer: the camera / light pose local kn = kfs[idx] local pos = kn.values.pos local m: { number } = W[i] @@ -724,7 +703,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) camLight(true) continue end - -- an object node (or a dummy) with the node's transform relative to its keyframer parent local pkw = if p ~= 0 and kfOf[p] then KW[p] else S.IDENTITY local inv = Mat4.inverse(pkw) or Mat4.identity() local L = S.mul(inv, KW[i]) @@ -733,7 +711,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) local objName = if plist then plist[1].name else "$$$DUMMY" local instance = if plist and n.name and n.name ~= objName then name(n.name, objName) elseif not plist then name(n.name, "Dummy" .. i) else nil local kn: KfNode = { chunk = 0xB002, name = objName, instance = instance, parent = if pk then pk - 1 else -1, frames = { pos = { 0 }, rot = { 0 }, scl = { 0 } }, values = { pos = single(t), rot = rotTrack({ r }), scl = single(s) } } - -- animation keys, when the keyframer transform is the node's own (no mirror fix-up up the tree) local chs = byNode[i] if chs then local own = S.nodeMatrix(n) @@ -774,7 +751,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) camLight(false) end close(w, ed) - -- the keyframer local kf = open(w, C.KEYFRAMER) leaf(w, C.KF_HDR, function() w:u16le(5) diff --git a/src/Rosetta/model/3ds/init.luau b/src/Rosetta/model/3ds/init.luau index 8b4b9ed..115c896 100644 --- a/src/Rosetta/model/3ds/init.luau +++ b/src/Rosetta/model/3ds/init.luau @@ -1,25 +1,7 @@ --!strict --- model/3ds: Autodesk 3D Studio (.3ds, the chunked binary of 3D Studio R4 / 3ds Max's exporter). New code, from the --- chunk layout as documented by the 3DS File Toolkit notes and read by assimp's 3DS importer (BSD-3: the reference --- for transforms and conventions; no code ported) and lib3ds (layouts only). --- Reads: triangle meshes (vertices, faces, uvs (TEXCOORD_0, flipped to glTF's top-left origin), the mesh matrix, --- per-face materials -> one primitive per material, smoothing groups -> NORMAL: corners of faces sharing a group and --- a position are averaged, group 0 is flat; extras["3ds"].smoothing keeps the groups per triangle), materials --- (ambient / diffuse / specular colours, shininess, shininess strength, transparency, self-illumination, two-sided, --- shading, wire; texture maps -> Textures with `uri` (never loaded: F.model.loadTextures resolves them), diffuse as --- baseColorTexture, self-illumination as emissiveTexture, the others in extras["3ds"].maps; uv scale / offset / --- angle as a texture transform), cameras (lens -> yfov at a 4:3 aspect, near / far ranges; -Z looking at the --- target, rolled), lights (omni -> point, spot -> spot with hotspot / falloff cones, colour, multiplier, outer range), --- the keyframer (node hierarchy by node id, $$$DUMMY nodes with their instance names, instances of one object, --- pivots, the first key of every track as the node's TRS, tracks with several keys -> one animation: position / --- scale keys linear, rotation keys accumulated from their axis / angle deltas, cameras / spotlights sampled from --- their position, target and roll tracks; TCB spline parameters are ignored, times are frame / opts.fps). Objects --- without a keyframer node stand at their mesh matrix. meta.up = "z"; meta.source has version, masterScale (not --- applied), the keyframer frame range. --- Writes: see model/3ds/Write (meshes, materials, texture names, cameras, lights, the keyframer and the first --- animation). Not supported: 3DS project / material library files (.prj, .mli), morph / hide tracks, procedural --- and shadow parameters, background / atmosphere settings, mesh limits beyond 65535 vertices per object (split on --- write), vertex colours / normals (3DS has neither; normals come from smoothing groups). +-- model/3ds: Autodesk 3D Studio chunked binary; layouts from the 3DS File Toolkit notes, assimp's importer (BSD-3, +-- reference only) and lib3ds. Supports: meshes, smoothing groups, Phong materials and maps, cameras, lights, keyframer. +-- Not supported: .prj / .mli, morph / hide tracks, TCB spline parameters, vertex colours / normals (3DS has none). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -41,16 +23,16 @@ local ThreeDs = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - normals: boolean?, -- compute NORMAL from the smoothing groups (default true; false keeps the file's vertices) - flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) - fps: number?, -- keyframer frames per second (default 30, 3ds Max's default) - maxVertices: number?, -- refuse more vertices in total (default 2^24) + normals: boolean?, -- default true + flipV: boolean?, -- default true + fps: number?, -- default 30 (3ds Max's default) + maxVertices: number?, -- default 2^24 } export type EncodeOptions = { - flipV: boolean?, -- default true (the inverse of decode) - fps: number?, -- seconds -> keyframer frames (default 30) - name: string?, -- the destination's file name (names textures that have no uri) - files: { [string]: any }?, -- receives the bytes of textures that have data but no uri + flipV: boolean?, -- default true + fps: number?, -- default 30 + name: string?, + files: { [string]: any }?, -- receives the bytes of textures with data but no uri } -- ------------------------------------------------------------------------------------------------ sniff @@ -74,7 +56,6 @@ function ThreeDs.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, E if not raw then return nil, Err.from(msg, at) end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene = pcall(Build.scene, raw, opts :: any) if not ok then return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) diff --git a/src/Rosetta/model/3mf/Read.luau b/src/Rosetta/model/3mf/Read.luau index f9fc5b7..d8408a3 100644 --- a/src/Rosetta/model/3mf/Read.luau +++ b/src/Rosetta/model/3mf/Read.luau @@ -1,11 +1,6 @@ --!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. +-- model/3mf/Read: a 3MF package -> Scene. The root model part comes from _rels/.rels (fallback: the first *.model under +-- 3D/); vertices are split where corners of one vertex carry different colours / texture coordinates. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Xml = require("@rosetta/codecs/text/Xml") @@ -21,7 +16,6 @@ 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] @@ -44,7 +38,7 @@ local function int(s: string?): number? return nil end --- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1 +-- "#RRGGBB" / "#RRGGBBAA", sRGB local function hexColor(s: string?): { number }? if type(s) ~= "string" then return nil @@ -68,7 +62,7 @@ function Read.toLinear(c: number): number end local toLinear = Read.toLinear --- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid +-- "m00 m01 m02 m10 ... m32": 3MF's row-vector convention local function transform(s: string?): ({ number }?, boolean) if not s then return nil, true @@ -99,7 +93,6 @@ local function normPath(p: string): string 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?) @@ -253,7 +246,6 @@ local function parseModel(text: string, path: string, opts: any): (Model?, Err.E 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 @@ -313,7 +305,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) 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 @@ -359,7 +350,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) 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 @@ -429,7 +419,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) 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 @@ -532,7 +521,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) 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?) diff --git a/src/Rosetta/model/3mf/Write.luau b/src/Rosetta/model/3mf/Write.luau index 4f3af58..515cad1 100644 --- a/src/Rosetta/model/3mf/Write.luau +++ b/src/Rosetta/model/3mf/Write.luau @@ -1,10 +1,5 @@ --!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. +-- model/3mf/Write: Scene -> a 3MF package; the node hierarchy is flattened into build items at world matrices. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Xml = require("@rosetta/codecs/text/Xml") @@ -48,7 +43,6 @@ local function hex(r: number, g: number, b: number, a: number): string 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 @@ -128,10 +122,9 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) nextId += 1 return nextId end - local res: { string } = {} -- resource XML chunks, in definition order + local res: { string } = {} 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 @@ -152,16 +145,14 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) 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 defaultBase = nmat 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 @@ -186,7 +177,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) return rid end - -- objects local objectOf: { [number]: number } = {} local objChunks: { string } = {} for mi, mesh in scene.meshes do @@ -195,7 +185,7 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) local base = 0 local objPid: number?, objP: number? = nil, nil local anyNone = false - local triList: { { number } } = {} -- { v1, v2, v3, pid | -1, p1, p2, p3 } + local triList: { { number } } = {} for _, prim in mesh.primitives do local corners = triangles(prim) if not corners or #corners == 0 then @@ -210,7 +200,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) for v = 0, n - 1 do table.insert(verts, fmt('\t\t\t\t\t\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 @@ -296,7 +285,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) 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\n', baseId) } for _, m in scene.materials do @@ -310,7 +298,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) 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 @@ -342,7 +329,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) end end - -- metadata local meta: { string } = {} local md = scene.meta and scene.meta.metadata if type(md) == "table" then diff --git a/src/Rosetta/model/3mf/init.luau b/src/Rosetta/model/3mf/init.luau index 888670e..18cdfe2 100644 --- a/src/Rosetta/model/3mf/init.luau +++ b/src/Rosetta/model/3mf/init.luau @@ -1,21 +1,7 @@ --!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/text/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). +-- model/3mf: 3D Manufacturing Format (core 1.3, materials extension 1.2, production extension 1.1 p:path). +-- Supports: meshes, components, build items, base materials, colour / texture / composite / multi groups. +-- Not supported: beam lattice, slices, displacement, volumetric and secure content, thumbnails, normals. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -37,13 +23,13 @@ local ThreeMf = { -- ------------------------------------------------------------------------------------------------ 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) + maxVertices: number?, -- default 2^25 + maxNodes: number?, -- 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) + -- millimeter) + level: number?, -- default 6; 0 stores } -- ------------------------------------------------------------------------------------------------ sniff @@ -51,7 +37,6 @@ 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 diff --git a/src/Rosetta/model/b3d/Read.luau b/src/Rosetta/model/b3d/Read.luau index 80b0534..2db075a 100644 --- a/src/Rosetta/model/b3d/Read.luau +++ b/src/Rosetta/model/b3d/Read.luau @@ -1,8 +1,5 @@ --!strict --- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are --- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes --- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end. --- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +-- model/b3d/Read: the BB3D chunk tree (4-byte id, u32 little-endian size, no padding) -> Types.Scene. local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Chunks = require("@rosetta/containers/Chunks") @@ -26,8 +23,8 @@ type MeshRec = { mesh: number, node: number, count: number, joints: { { number } type Bone = { node: number, target: MeshRec?, list: { number } } type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } } --- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated --- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored +-- Blitz3D is left-handed Y up: z mirrored; quaternions are w x y z, conjugated (Blitz3D stores the inverse +-- rotation, as assimp reads them) then mirrored local function vec(r: Bytes.Reader): { number } local x, y, z = r:f32le(), r:f32le(), r:f32le() return { x, y, -z } @@ -54,7 +51,6 @@ local function fetcher(opts: Options?): (string) -> buffer? end end --- scene(r, opts) -> Scene | nil, message, kind function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?) local buf = src.buf local maxVertices = opts and opts.maxVertices or 2 ^ 24 @@ -77,7 +73,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, local scene = Types.Scene.new() local texs: { TexInfo } = {} local brushes: { Brush } = {} - local materialOf: { [number]: number } = {} -- brush index (0-based) -> material + local materialOf: { [number]: number } = {} local meshes: { MeshRec } = {} local bones: { Bone } = {} local nodeKeys: { [number]: Keys } = {} @@ -141,7 +137,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, end end - -- the material of brush id (0-based) | nil for -1 / out of range local function material(id: number): number? if id < 0 or id >= #brushes then return nil @@ -290,7 +285,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, fail(string.format("triangle %d: vertex index out of range", i)) return nil end - -- mirrored z: reverse the winding to keep the faces front-facing writeu32(idx, i * 12, a) writeu32(idx, i * 12 + 4, cc) writeu32(idx, i * 12 + 8, b) @@ -302,7 +296,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, end end if not attrs then - return nil -- a mesh without vertices: the node stays a pivot + return nil end if #mesh.primitives == 0 then table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" }) @@ -472,7 +466,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, end end end - local self: number? = nil -- the mesh node as a joint, for vertices no bone moves + local self: number? = nil local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) for v = 0, nv - 1 do local e = inf[v + 1] @@ -484,7 +478,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, buffer.writeu16(jb, v * 8, self :: number) buffer.writef32(wb, v * 16, 1) else - -- the 4 strongest, normalised local order = {} for k = 1, #e, 2 do table.insert(order, k) @@ -568,7 +561,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, brushes = #brushes, frames = if anim then anim.frames else nil, fps = if anim then anim.fps else nil, - handedness = "left", -- converted: z mirrored, winding reversed + handedness = "left", } return scene, nil, nil end diff --git a/src/Rosetta/model/b3d/init.luau b/src/Rosetta/model/b3d/init.luau index e208d12..308453d 100644 --- a/src/Rosetta/model/b3d/init.luau +++ b/src/Rosetta/model/b3d/init.luau @@ -1,21 +1,7 @@ --!strict --- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description --- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer. --- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler, --- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes -> --- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is --- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree --- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) / --- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the --- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights --- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the --- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps, --- default 60) -> one animation of LINEAR channels at frame / fps seconds. --- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding --- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their --- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }. --- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the --- extras; texture coordinate sets of 3 / 4 components keep their first two. +-- model/b3d: Blitz3D .b3d (BB3D chunks, version 1; blitzbasic.com "b3dfile_specs.txt", checked against assimp). +-- Supports: TEXS, BRUS, NODE / MESH / VRTS / TRIS, BONE skins, KEYS + ANIM; left-handed, so z is mirrored. +-- Not supported: writing; several VRTS chunks in one MESH (the first is used); 3 / 4 component texture coordinates. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -35,10 +21,10 @@ local B3d = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- texture files (the api sets it for paths) - files: { [string]: any }?, -- or: the files by name + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, maxVertices: number?, -- default 2^24 - maxDepth: number?, -- node nesting (default 256) + maxDepth: number?, -- default 256 } -- ------------------------------------------------------------------------------------------------ sniff @@ -54,7 +40,6 @@ function B3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if r:peek(4) ~= "BB3D" then return nil, Err.new(Err.CORRUPT, "no BB3D chunk") end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, msg, kind = pcall(Read.scene, r, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene)) diff --git a/src/Rosetta/model/bsp/Brush.luau b/src/Rosetta/model/bsp/Brush.luau index 83fa807..f745199 100644 --- a/src/Rosetta/model/bsp/Brush.luau +++ b/src/Rosetta/model/bsp/Brush.luau @@ -1,13 +1,7 @@ --!strict --- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex --- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture --- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the --- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake / --- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the --- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from --- opts.resolve("textures/.wal") when available, else texture coordinates stay in texels: extras.bsp.texels). --- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken. --- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls. +-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the +-- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture +-- size. local Types = require("@rosetta/Types") local Pixels = require("@rosetta/codecs/image/Pixels") @@ -20,7 +14,7 @@ local writef32, writeu32 = buffer.writef32, buffer.writeu32 export type Lump = { at: number, size: number } export type Options = { palette: buffer?, - wal: ((name: string) -> buffer?)?, -- Quake II: the .wal file of a texture (for its size) + wal: ((name: string) -> buffer?)?, -- Quake II: a texture's .wal file (for its size) maxPixels: number?, maxVertices: number?, } @@ -32,7 +26,6 @@ local function cstr(b: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string end --- miptex lump (Quake / Half-Life) -> textures local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer?, maxPixels: number): ({ Tex }?, string?) local out: { Tex } = {} if l.size < 4 then @@ -80,9 +73,6 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer return out, nil end --- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message --- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes, --- models, miptex (q1 / hl) function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?) local q2 = variant == "q2" local maxPixels = opts and opts.maxPixels or 2 ^ 24 @@ -95,9 +85,8 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian if nF > (opts and opts.maxVertices or 2 ^ 24) then return nil, "limit: too many faces" end - -- textures local texs: { Tex } = {} - local texOf: { number } = {} -- texinfo -> texture index (1-based) + local texOf: { number } = {} if q2 then local byName: { [string]: number } = {} for i = 0, nTI - 1 do @@ -126,7 +115,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian texOf[i + 1] = if mt >= 0 and mt < #texs then mt + 1 else 0 end end - -- faces of each model local scene = Scene.new() scene.meta.up = "z" local faceModel: { number } = {} @@ -160,7 +148,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian skipped += 1 continue end - -- the polygon local poly: { number } = {} local ok = true for k = 0, numEdges - 1 do @@ -189,7 +176,7 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian if side ~= 0 then nx, ny, nz = -nx, -ny, -nz end - -- orient counter-clockwise about the normal (Newell's normal of the polygon as stored) + -- Newell's normal of the polygon as stored local n = #poly // 3 local ax, ay, az = 0, 0, 0 for k = 0, n - 1 do @@ -239,7 +226,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian end end end - -- textures, materials for i, t in texs do local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) } table.insert(scene.textures, tex) @@ -250,7 +236,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any table.insert(scene.materials, mat) end - -- meshes and nodes local root: Types.Node = { name = "bsp", children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 diff --git a/src/Rosetta/model/bsp/Quake3.luau b/src/Rosetta/model/bsp/Quake3.luau index 3284055..de8c1a4 100644 --- a/src/Rosetta/model/bsp/Quake3.luau +++ b/src/Rosetta/model/bsp/Quake3.luau @@ -1,11 +1,6 @@ --!strict --- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a --- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches --- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap --- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1 --- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as --- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped. --- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken. +-- model/bsp/Quake3: Quake III Arena maps (IBSP 46; RTCW 47 has the same layout) -> Scene, from the Unofficial Quake 3 +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped. local Types = require("@rosetta/Types") local Quake3 = {} @@ -17,19 +12,18 @@ local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.wri export type Lump = { at: number, size: number } export type Options = { patchLevel: number?, maxVertices: number? } -type Batch = { shader: number, lightmap: number, verts: { number } } -- vertex records (indices into the vertex lump, or -1 - k for patch vertices) +type Batch = { shader: number, lightmap: number, verts: { number } } -- indices into the vertex lump, or -1 - k for patch vertices local function cstr(b: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string end --- decode(b, base, lumps, opts) -> Scene | nil, message function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: Options?): (Types.Scene?, string?) local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps local nT, nM, nV, nMV, nF, nLM = T.size // 72, M.size // 40, VX.size // 44, MV.size // 4, F.size // 104, LM.size // 49152 local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16) local maxV = opts and opts.maxVertices or 2 ^ 24 - -- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids + -- patch vertices: 12 floats + 4 colour bytes each local extra: { number } = {} local function vertex(i: number): { number } local o = base + VX.at + i * 44 @@ -92,7 +86,6 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: local L = level for py = 0, (h - 1) // 2 - 1 do for px = 0, (w - 1) // 2 - 1 do - -- the 3x3 control points of this sub-patch local ctrl: { { number } } = {} for j = 0, 2 do for i = 0, 2 do @@ -127,7 +120,7 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: for gx = 0, L - 1 do local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] - -- counter-clockwise for Quake's clockwise-front control grids + -- Quake's control grids are clockwise-front for _, v in { a, d, c2, c2, d, e } do table.insert(tris, v) end @@ -166,7 +159,6 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: end local scene = Scene.new() scene.meta.up = "z" - -- shaders, lightmaps for i = 0, nT - 1 do local name = cstr(b, base + T.at + i * 72, 64) table.insert(scene.textures, { name = name, uri = name }) diff --git a/src/Rosetta/model/bsp/init.luau b/src/Rosetta/model/bsp/init.luau index ff2dcda..02ae8d9 100644 --- a/src/Rosetta/model/bsp/init.luau +++ b/src/Rosetta/model/bsp/init.luau @@ -1,11 +1,6 @@ --!strict --- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38) --- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a --- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III --- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as --- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not --- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey. --- Quake II .wal sizes come from opts.resolve("textures/.wal") / opts.files. Units are map units, z up. +-- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW +-- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. -- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. -- ------------------------------------------------------------------------------------------------ requires @@ -28,10 +23,10 @@ local Bsp = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - palette: (buffer | string)?, -- Quake 1: the 768-byte palette + palette: (buffer | string)?, -- Quake 1: 768 bytes resolve: ((uri: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, - patchLevel: number?, -- Quake III patch subdivisions (default 4) + patchLevel: number?, -- default 4 maxPixels: number?, -- default 2^24 maxVertices: number?, -- default 2^24 } @@ -55,7 +50,6 @@ function Bsp.sniff(r: Bytes.Reader): number return if v == 38 or v == 46 or v == 47 then 1 else 0.3 end if v == 29 or v == 30 then - -- no magic: check that the lump directory fits the file local size = r:remaining() for i = 0, 14 do local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8) @@ -69,7 +63,6 @@ function Bsp.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the entities text -> { { key = value } } local function entities(text: string): { { [string]: string } } local out: { { [string]: string } } = {} for block in string.gmatch(text, "%b{}") do diff --git a/src/Rosetta/model/dae/Math.luau b/src/Rosetta/model/dae/Math.luau index cabfc97..4da24c2 100644 --- a/src/Rosetta/model/dae/Math.luau +++ b/src/Rosetta/model/dae/Math.luau @@ -1,6 +1,5 @@ --!strict --- model/dae/Math: the Collada-specific transform elements (, ); everything else (matrices, --- quaternions, decomposition) is codecs/model/Mat4. Matrices are flat arrays of 16 in column-major order. +-- model/dae/Math: the Collada transform elements and ; matrices are flat column-major arrays of 16. local Mat4 = require("@rosetta/codecs/model/Mat4") local DaeMath = {} @@ -18,7 +17,7 @@ local function norm(a: { number }): { number } 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 +-- : 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) }) @@ -27,14 +26,14 @@ function DaeMath.lookat(v: { number }): { number } 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) +-- (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 = Mat4.identity() - -- M = I + s * t * r^T (column-major: m[col*4 + row]) + -- M = I + s * t * r^T for row = 0, 2 do for col = 0, 2 do m[col * 4 + row + 1] += s * t[row + 1] * r[col + 1] diff --git a/src/Rosetta/model/dae/Read.luau b/src/Rosetta/model/dae/Read.luau index 8cf63f9..b7e5eae 100644 --- a/src/Rosetta/model/dae/Read.luau +++ b/src/Rosetta/model/dae/Read.luau @@ -1,13 +1,5 @@ --!strict --- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / --- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile --- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains, --- images (kept encoded through the fetch callback, or embedded hex ), the visual scene's node tree (matrix / --- translate / rotate / scale / lookat / skew, instance_node, several instances per node as child nodes), skin --- controllers (bind shape applied, inverse bind matrices, the 4 strongest weights), morph controllers (targets as --- deltas), cameras, lights (ambient lights as node extras) and animations (every channel on a node's transform --- elements, resampled at the union of the key times (plus subdivisions of large rotations) into glTF-style TRS --- channels; one animation per animation clip, else one for the file). +-- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Xml = require("@rosetta/codecs/text/Xml") @@ -100,8 +92,8 @@ type Ctx = { meshes: { [string]: number }, skins: { [string]: number }, posIndex: { [any]: { number } }, - nodeOf: { [string]: { number } }, -- collada node id -> scene nodes - info: { [number]: any }, -- scene node -> { el, xf, sid, cid } + nodeOf: { [string]: { number } }, + info: { [number]: any }, pendingSkins: { any }, skipped: { [string]: number }, err: string?, @@ -113,7 +105,6 @@ local function skip(C: Ctx, what: string) end -- ------------------------------------------------------------------------------------------------ sources --- source(el) -> { data = flat numbers or strings, comps, count } (only the accessor's named params) local function readSource(C: Ctx, el: any): any local cached = C.sources[el] if cached ~= nil then @@ -279,7 +270,6 @@ local function image(C: Ctx, id: string): any return img end --- the effect's newparams by sid (this level and the profile's) local function newparams(effect: any, profile: any, technique: any): { [string]: any } local out = {} for _, scope in { effect, profile, technique } do @@ -295,7 +285,6 @@ local function newparams(effect: any, profile: any, technique: any): { [string]: return out end --- texture(effect params, sampler sid) -> scene texture index local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): number? local np = params[samplerSid] local imageId: string? = nil @@ -364,7 +353,6 @@ local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): n return idx end --- one colour-or-texture parameter of a common technique local function param(C: Ctx, params: { [string]: any }, el: any, uvsets: { [string]: number }): (any, any) if not el then return nil, nil @@ -474,7 +462,7 @@ local function material(C: Ctx, id: string, uvsets: { [string]: number }): numbe if type(shininess) == "number" then mat.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) end - -- opacity (Collada 1.4.1 spec section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance) + -- Collada 1.4.1 section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance if transparentEl and (type(transparent) == "table" or type(transparency) == "number") then local mode = attr(transparentEl, "opaque") or "A_ONE" local tv = if type(transparency) == "number" then transparency else 1 @@ -531,7 +519,6 @@ end -- ------------------------------------------------------------------------------------------------ geometry type Input = { semantic: string, source: any, offset: number, set: number } --- the inputs of a primitive element (VERTEX expanded into the inputs) local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number) local out: { Input } = {} local stride = 0 @@ -563,7 +550,6 @@ local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number) return out, math.max(stride, 1) end --- faces(primEl, kind, stride) -> corner list (tuple starts into the concatenated p), face sizes, mode local function corners(C: Ctx, prim: any, kind: string, stride: number): ({ number }?, { number }?, { number }?, string) local p: { number } = {} local faces: { number } = {} @@ -670,7 +656,6 @@ local PRIMS = { triangles = true, polylist = true, polygons = true, lines = true type Built = { prim: Types.Primitive, symbol: string?, texSets: { number }, posIndex: { number } } --- one primitive element -> Primitive (+ the source position index of each output vertex, for skins / morphs) local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Built? local ins, stride = inputs(C, prim, verticesEl) local p, faces, starts, mode = corners(C, prim, kind, stride) @@ -688,7 +673,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil skip(C, "primitives without positions") return nil end - -- attribute names local named: { { input: Input, name: string, comps: number } } = {} local texSets: { number } = {} local texInputs: { Input } = {} @@ -725,10 +709,9 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil table.insert(named, { input = i, name = "_" .. s .. (if i.set ~= 0 then tostring(i.set) else ""), comps = math.max(comps, 1) }) end end - -- de-index local np = #p local keyOf: { [any]: number } = {} - local tuples: { number } = {} -- the first p index of each output vertex's tuple + local tuples: { number } = {} local corner = table.create(#starts) :: { number } local count = 0 for ci, s in starts do @@ -803,7 +786,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil if allTri then mode = "triangles" elseif C.triangulate then - -- fan triangulation local tri: { number } = {} local at = 0 for _, f in faces do @@ -832,7 +814,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil return { prim = out, symbol = attr(prim, "material"), texSets = texSets, posIndex = posIndex } end --- geometry(el) -> the built primitives (cached per geometry element) local function geometry(C: Ctx, el: any): { Built }? local cached = C.posIndex[el] if cached then @@ -863,7 +844,6 @@ local function geometry(C: Ctx, el: any): { Built }? return out end --- the material bindings of an instance: symbol -> material id, and semantic -> texcoord set local function bindings(node: any): ({ [string]: string }, { [string]: { [string]: number } }) local syms: { [string]: string } = {} local sets: { [string]: { [string]: number } } = {} @@ -894,7 +874,6 @@ local function copyAccessor(a: Types.Accessor): Types.Accessor return Scene.accessor(b, a.type, a.components, a.count) end --- mesh(geometry element, instance element, skin?) -> scene mesh index local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { number }?): (number?, { Built }?) local syms, sets = bindings(inst) local parts = { key } @@ -915,7 +894,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { for _, b in built do local prim = b.prim if bindShape then - -- skinned: the bind shape matrix applied to positions and normals (a copy: the geometry may be shared) local attrs = table.clone(prim.attributes) local pos = copyAccessor(attrs.POSITION) for v = 0, pos.count - 1 do @@ -961,7 +939,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { end end if target then - -- texcoord semantic -> TEXCOORD_n index among this primitive's sets local uv: { [string]: number } = {} for sem, set in (sym and sets[sym]) or {} do uv[sem] = (table.find(b.texSets, set) or 1) - 1 @@ -976,7 +953,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { return idx, built end --- morph controller -> mesh with targets (deltas) local function morphMesh(C: Ctx, ctrl: any, morph: any, inst: any): number? local base = C.ids[urlId(attr(morph, "source")) or ""] if not base or lname(base) ~= "geometry" then @@ -1082,7 +1058,6 @@ local function camera(C: Ctx, el: any): number? return #C.scene.cameras end --- light(el) -> light index, or nil and the ambient colour local function light(C: Ctx, el: any): (number?, { number }?) local tc = child(el, "technique_common") if not tc then @@ -1124,7 +1099,6 @@ end -- ------------------------------------------------------------------------------------------------ nodes local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, skew = 7 } --- the matrix of one transform element's values local function xfMatrix(kind: string, v: { number }): { number } if kind == "matrix" then return Mat4.fromRows(v) @@ -1182,7 +1156,7 @@ local function addChild(C: Ctx, parent: Types.Node, node: Types.Node): number return idx end --- the instances of a node: the first of each kind on the node itself, the rest on child nodes +-- extra instances of a node go on child nodes local function instances(C: Ctx, el: any, node: Types.Node, idx: number) local function slot(kind: string, name: string?): (Types.Node, number) local n: any = node @@ -1322,7 +1296,7 @@ visitNode = function(C: Ctx, el: any): number? end -- ------------------------------------------------------------------------------------------------ skins --- the scene node for a joint name: by sid below the skeleton roots, else by sid / id / name anywhere +-- joints: by sid below the skeleton roots, else by sid / id / name anywhere local function findJoint(C: Ctx, name: string, roots: { number }, byId: boolean): number? local nodes = C.scene.nodes local function search(i: number, depth: number): number? @@ -1410,7 +1384,7 @@ local function resolveSkins(C: Ctx) local skin: Types.Skin = { name = attr(ps.ctrl, "name") or attr(ps.ctrl, "id"), joints = jointNodes } if ps.bind then local sk: any = skin - sk.extras = { dae = { bindShapeMatrix = ps.bind } } -- already applied to the mesh's positions / normals + sk.extras = { dae = { bindShapeMatrix = ps.bind } } end if ibm and ibm.comps == 16 and ibm.count >= #names then local b = buffer.create(#names * 64) @@ -1432,7 +1406,6 @@ local function resolveSkins(C: Ctx) cache[key] = si end C.scene.nodes[ps.node].skin = si - -- vertex weights -> JOINTS_0 / WEIGHTS_0 (once per mesh) local mesh = C.scene.meshes[ps.mesh] if mesh.primitives[1] and mesh.primitives[1].attributes.JOINTS_0 then continue @@ -1457,7 +1430,7 @@ local function resolveSkins(C: Ctx) local vcount = numbers(text(child(vw, "vcount") or ""), C.limit) or {} local v = numbers(text(child(vw, "v") or ""), C.limit * 8) or {} local wdata = wSrc and wSrc.data or {} - local per: { { number } } = {} -- position index -> { j1, w1, j2, w2, ... } strongest 4 + local per: { { number } } = {} local at = 0 for pi, c in vcount do local list = {} @@ -1555,9 +1528,9 @@ local function sample(c: Curve, t: number): { number } return a end --- resolve "id/sid/sid.member" or "id/sid(i)(j)" to a node's transform element +-- "id/sid/sid.member" or "id/sid(i)(j)" local function target(C: Ctx, s: string): ({ number }?, any, number?) - -- the id may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" + -- ids may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" local id, sids = match(s, "^([^/]*)/(.*)$") if not id then return nil, nil, nil @@ -1607,7 +1580,6 @@ local function target(C: Ctx, s: string): ({ number }?, any, number?) return nodes, xf, member end --- the channels of one (recursively) -> curves grouped by node local function collect(C: Ctx, anim: any, byNode: { [number]: { Curve } }, order: { number }, depth: number) if depth > 64 then return @@ -1697,7 +1669,6 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde local tb, rb, sb = buffer.create(n * 12), buffer.create(n * 16), buffer.create(n * 12) local prev: { number }? = nil for i, t in times do - -- this time's values of each animated element local xf = {} for k, x in info.xf do xf[k] = { kind = x.kind, values = table.clone(x.values) } @@ -1738,7 +1709,6 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel) table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" } :: Types.Channel) table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel) - -- the node is now TRS-driven local node = C.scene.nodes[ni] if node.matrix then setTransform(node, node.matrix) @@ -1821,12 +1791,11 @@ function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err? } for _, el in Xml.descendants(root) do local id = el.attrs.id - -- duplicate ids: the first one, unless it is empty (some exporters write before the real one) + -- duplicate ids: the first, unless empty (some exporters write before the real one) if type(id) == "string" and (C.ids[id] == nil or #C.ids[id].children == 0) then C.ids[id] = el end end - -- asset: up axis, unit local asset = child(root, "asset") local up = asset and child(asset, "up_axis") local upAxis = if up then upper(match(text(up), "[%w_]+") or "Y_UP") else "Y_UP" @@ -1834,7 +1803,6 @@ function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err? local unit = asset and child(asset, "unit") local meter = unit and attr(unit, "meter") scene.meta.unit = if meter then tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 else 1 - -- the instanced visual scene (else the first one) local vsId: string? = nil local sceneEl = child(root, "scene") local ivs = sceneEl and child(sceneEl, "instance_visual_scene") diff --git a/src/Rosetta/model/dae/Write.luau b/src/Rosetta/model/dae/Write.luau index c317f42..b777d96 100644 --- a/src/Rosetta/model/dae/Write.luau +++ b/src/Rosetta/model/dae/Write.luau @@ -1,9 +1,6 @@ --!strict --- model/dae/Write: Scene -> Collada 1.4.1 text. One 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 ; cameras; --- lights. Not written: skins, morph targets, animations. +-- model/dae/Write: Scene -> Collada 1.4.1 text; strips and fans unrolled, points skipped, nodes as row-major . +-- Not written: skins, morph targets, animations. local Types = require("@rosetta/Types") local Xml = require("@rosetta/codecs/text/Xml") local Base64 = require("@rosetta/core/Base64") @@ -38,7 +35,6 @@ 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 } = {} @@ -160,7 +156,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? local meta: { [string]: any } = scene.meta or {} local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP" w(format('rosetta1970-01-01T00:00:00Z1970-01-01T00:00:00Z%s\n', f(meta.unit or 1), up)) - -- images local imageId: { [number]: string } = {} if #scene.textures > 0 then w("\n") @@ -184,12 +179,11 @@ function Write.build(scene: Types.Scene, opts: any?): string? end w("\n") end - -- effects + materials if #scene.materials > 0 then w("\n") for i, mat in scene.materials do local ph: any = mat.extras and mat.extras.phong or {} - local params: { [any]: any } = {} -- the newparam strings, and their sids as seen-keys + local params: { [any]: any } = {} local function texParam(ref: Types.TextureRef?): (string?, number?) if not ref or not imageId[ref.texture] then return nil, nil @@ -236,7 +230,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? end w("\n") end - -- geometries: one per primitive local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {} w("\n") for mi, mesh in scene.meshes do @@ -289,7 +282,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? end end w("\n") - -- cameras / lights if #scene.cameras > 0 then w("\n") for i, cam in scene.cameras do @@ -316,7 +308,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? end w("\n") end - -- the node tree w('\n') local seen: { [number]: boolean } = {} local function node(i: number, depth: number) diff --git a/src/Rosetta/model/dae/init.luau b/src/Rosetta/model/dae/init.luau index a3fb3de..289bfa8 100644 --- a/src/Rosetta/model/dae/init.luau +++ b/src/Rosetta/model/dae/init.luau @@ -1,26 +1,8 @@ --!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 ( 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: 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 --- 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: / geometry, polygon holes (: 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. +-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry, +-- common-profile materials, images, the visual scene, skin / morph controllers, cameras, lights, transform animations. +-- Not supported: / , polygon holes (), Bezier / Hermite curves (sampled linearly), non-transform +-- animation targets, physics / kinematics / non-COMMON FX profiles; writing skins, morphs and animations. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -43,17 +25,17 @@ local Dae = { -- ------------------------------------------------------------------------------------------------ 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) + resolve: ((uri: string) -> any)?, -- image files (buffer or string) + files: { [string]: any }?, + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + maxVertices: number?, -- 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 + files: { [string]: any }?, -- receives the texture images (else data: URIs or their uri) + name: string?, + flipV: boolean?, -- default true + format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images) } -- ------------------------------------------------------------------------------------------------ sniff @@ -107,7 +89,7 @@ local function fetcher(opts: DecodeOptions?, zip: any): Read.Fetch end end --- the main .dae of a .zae: manifest.xml's , else the first .dae entry +-- a .zae's main .dae: manifest.xml's , 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 @@ -174,7 +156,6 @@ function Dae.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err 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 diff --git a/src/Rosetta/model/fbx/Ascii.luau b/src/Rosetta/model/fbx/Ascii.luau index 9975cc8..7f6f62f 100644 --- a/src/Rosetta/model/fbx/Ascii.luau +++ b/src/Rosetta/model/fbx/Ascii.luau @@ -1,7 +1,6 @@ --!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. +-- model/fbx/Ascii: the ASCII FBX 7.x node tree ("Name: value, ... { children }", ';' comments, "*N { a: ... }" arrays, +-- " in strings); integers longer than 15 digits stay strings so ids are exact. local Base64 = require("@rosetta/core/Base64") local Ascii = {} @@ -15,7 +14,6 @@ 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 @@ -36,7 +34,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n 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 @@ -61,7 +58,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n return nil, i end - -- the values of one node (after the ':'), up to a new name, '{' or '}' local function values(): ({ any }?, string?) local props: { any } = {} while true do @@ -163,7 +159,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n 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] @@ -213,7 +208,6 @@ local function fmt(v: number): string 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 rosetta\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) } local function node(nd: any, indent: string) @@ -236,7 +230,7 @@ function Ascii.write(root: any, version: number?): string 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 + -- 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 diff --git a/src/Rosetta/model/fbx/Binary.luau b/src/Rosetta/model/fbx/Binary.luau index 34bb2c5..90a2cb4 100644 --- a/src/Rosetta/model/fbx/Binary.luau +++ b/src/Rosetta/model/fbx/Binary.luau @@ -1,10 +1,7 @@ --!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/compress/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" so ids stay exact. Never throws: errors are returned (nil, message, offset). +-- model/fbx/Binary: the binary FBX 7.x node tree (32-bit node records before 7500, 64-bit from 7500), as documented by +-- Blender's io_scene_fbx and assimp's FBXBinaryTokenizer. Scalar L values past 2^53 become "L" so ids stay exact. local Deflate = require("@rosetta/codecs/compress/Deflate") local Binary = {} @@ -21,7 +18,7 @@ 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>" +-- signed 64-bit: a number when |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 @@ -40,7 +37,6 @@ Binary.i64 = i64 local ELEM: { [string]: number } = { 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 @@ -66,7 +62,6 @@ local function toF64(t: string, src: buffer, p: number, n: number): buffer 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 @@ -158,7 +153,6 @@ function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: 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 @@ -230,10 +224,8 @@ function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: 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). +-- default version 7400 (32-bit records; 7500+ writes 64-bit); node.types = "ILDS..." gives one type character per +-- property; arrays over 32 elements are zlib-compressed export type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } local function sizeHint(n: WNode): number diff --git a/src/Rosetta/model/fbx/Read.luau b/src/Rosetta/model/fbx/Read.luau index b18510d..110b110 100644 --- a/src/Rosetta/model/fbx/Read.luau +++ b/src/Rosetta/model/fbx/Read.luau @@ -1,15 +1,6 @@ --!strict --- model/fbx/Read: an FBX 7.x node tree (model/fbx/Binary or model/fbx/Ascii) -> Scene. Objects + Connections -> --- nodes (Model, with the full FBX transform: pre / post rotation, pivots, offsets, rotation order, geometric --- transform baked into the mesh data), meshes (polygons, layer elements for normals / uvs / colours / materials in --- every mapping (ByPolygonVertex, ByVertice, ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode, one --- primitive per material, vertices unwelded per polygon corner as assimp does), materials (Phong / Lambert and the --- 3ds Max Physical / PBR compound -> PBR fields + extras.fbx), textures (embedded Video content kept encoded, or file --- references through the fetch callback), skins (Skin + Cluster deformers -> JOINTS_0 / WEIGHTS_0, inverse bind --- matrices), blend shapes (BlendShape / BlendShapeChannel / Shape -> morph targets), animation stacks (every layer's --- curve nodes on Lcl Translation / Rotation / Scaling and DeformPercent, sampled at the union of key times (or --- opts.sampleRate) and turned into glTF channels through the node transform), cameras and lights (on a child node --- turning glTF's -Z forward into FBX's +X camera / -Y light axis). Property templates from Definitions supply defaults. +-- model/fbx/Read: an FBX 7.x node tree -> Scene. Layer elements in every mapping (ByPolygonVertex, ByVertice, +-- ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode; vertices unwelded per polygon corner as assimp does. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Base64 = require("@rosetta/core/Base64") @@ -50,7 +41,7 @@ local function isArray(v: any): boolean return type(v) == "table" and v.array == true end --- the array under n. (or inline numbers: old ASCII files) +-- old ASCII files have inline numbers local function array(n: Node?, name: string): Array? local c = child(n, name) if not c then @@ -87,7 +78,7 @@ local function at(a: Array, i: number): number return buffer.readf64(a.data, i * 8) end --- "Name\0\1Class" (binary) / "Class::Name" (ASCII) -> name +-- "Name\0\1Class" (binary) / "Class::Name" (ASCII) local function objectName(s: any): string if type(s) ~= "string" then return "" @@ -104,7 +95,7 @@ local function objectName(s: any): string end Read.objectName = objectName --- Properties70 (P: name, type, label, flags, values...) -> { [name] = { type, v1, v2, ... } } +-- Properties70: P: name, type, label, flags, values... local function properties(n: Node?, into: { [string]: { any } }?): { [string]: { any } } local out = into or {} local p70 = child(n, "Properties70") @@ -155,7 +146,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local maxVertices = opts and opts.maxVertices or 2 ^ 25 local scene = Types.Scene.new() - -- property templates (Definitions/ObjectType/PropertyTemplate) by object class + -- Definitions/ObjectType/PropertyTemplate local templates: { [string]: { [string]: { any } } } = {} local defs = child(root, "Definitions") if defs then @@ -169,7 +160,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end - -- objects local objects: { [any]: Obj } = {} local order: { Obj } = {} local objs = child(root, "Objects") @@ -187,7 +177,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end - -- connections: children (sources) of each parent, parents of each child, in file order local kids: { [any]: { Conn } } = {} local parents: { [any]: { Conn } } = {} local conns = child(root, "Connections") @@ -236,7 +225,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ return out end - -- global settings local gs = properties(child(root, "GlobalSettings")) local upAxis = pnum(gs, "UpAxis", 1) local unitScale = pnum(gs, "UnitScaleFactor", 1) @@ -280,7 +268,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ return p end end - -- ASCII: base64 strings (possibly split into several) + -- ASCII: base64, possibly split into several strings local parts = {} for _, p in c.props do if type(p) == "string" then @@ -384,7 +372,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ if opacity < 1 then m.alphaMode = "blend" end - -- 3ds Max Physical / PBR materials local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"] if pbr then local prefix = if p["3dsMax|main|basecolor"] then "3dsMax|main|" else "3dsMax|Parameters|" @@ -504,7 +491,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ nd.scale = s end nd.extras = { fbx = { type = o.sub, id = o.id } } - -- parent local parentModel: Obj? = nil for _, t2 in targets(o.id, "Model") do parentModel = t2.obj @@ -517,7 +503,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ table.insert(scene.roots, ni) end end - -- break parent cycles (a node reachable from itself is not a valid tree): cut children already placed + -- break parent cycles: cut children already placed do local placed: { [number]: boolean } = {} local function visit(i: number) @@ -537,13 +523,11 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end for i in scene.nodes do if not placed[i] then - -- part of a parent cycle: make it a root table.insert(scene.roots, i) visit(i) end end end - -- world matrices (rest pose) local worldM: { [number]: Mat4.M4 } = {} local function world(i: number, parent: Mat4.M4) worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity()) @@ -559,7 +543,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ -- ------------------------------------------------------------------------------------------ meshes local corners = 0 - -- per geometry: skin (control point -> { joint node, weight }) and blend shape channels local function skinOf(geo: Obj): ({ { { number } } }?, Types.Skin?) local skin = sources(geo.id, "Deformer", "Skin")[1] if not skin then @@ -645,7 +628,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end local meshCache: { [string]: number } = {} - local shapeChannels: { [number]: { Obj } } = {} -- mesh index -> blend shape channel objects (for weights curves) + local shapeChannels: { [number]: { Obj } } = {} local nodeSkin: { [number]: number } = {} local skinCache: { [any]: number } = {} @@ -662,7 +645,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ if corners > maxVertices or ncp > maxVertices then return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices") end - -- polygons: corner -> control point, polygon of each corner, polygon starts local cp = table.create(nc, 0) local polyOf = table.create(nc, 0) local starts: { number } = { 0 } @@ -688,7 +670,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ np += 1 starts[np + 1] = nc end - -- layer elements type Elem = { data: Array, index: Array?, mapping: string, comps: number, name: string?, order: number } local function elems(kind: string, dataName: string, indexName: string, comps: number): { Elem } local out: { Elem } = {} @@ -711,7 +692,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end) return out end - -- the data element of a corner (c 0-based), or -1 local function lookup(e: Elem, c: number): number local m = e.mapping local i @@ -742,7 +722,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4) local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3) local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1] - -- the normals index name varies ("NormalsIndex" / "NormalIndex") + -- "NormalsIndex" / "NormalIndex" for _, e in normals do if not e.index then local c = nil @@ -758,7 +738,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end end - -- polygons by material slot local groups: { [number]: { number } } = {} local slots: { number } = {} for p = 0, np - 1 do @@ -785,7 +764,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ table.sort(slots) local perCp, skin = skinOf(geo) local shapes = shapesOf(geo) - local N3: Mat4.M4? = nil -- normal matrix (inverse transpose of G) + local N3: Mat4.M4? = nil -- inverse transpose of G if G then local inv = Mat4.inverse(G) if inv then @@ -1004,12 +983,11 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ for _, o in models do local ni = nodeOf[o.id] local nd = scene.nodes[ni] - -- materials of the model, in connection order local mats: { number } = {} for _, m in sources(o.id, "Material") do table.insert(mats, material(m)) end - -- geometric transform (not inherited: baked into the mesh) + -- geometric transform: not inherited, baked into the mesh local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 }) local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 }) local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 }) @@ -1047,7 +1025,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end end - -- cameras and lights: on a child node rotated from glTF's -Z forward to FBX's axis + -- cameras / lights: a child node rotated from glTF's -Z forward to FBX's +X camera / -Y light axis for _, a in sources(o.id, "NodeAttribute") do local p = a.props if a.sub == "Camera" then @@ -1120,7 +1098,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ times[k + 1] = at(kt, k) / TICKS values[k + 1] = at(kv, k) end - -- per-key attribute flags (expanded through KeyAttrRefCount) + -- expanded through KeyAttrRefCount local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat") local flags = table.create(n, 4) local slopes: { { number } } = {} @@ -1223,11 +1201,10 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ for _, stack in order do if stack.class == "AnimationStack" then local anim: Types.Animation = { name = stack.name, channels = {} } - -- model id -> { T/R/S -> { axis -> curve } , defaults } type Track = { curves: { [string]: { [number]: Curve } }, defaults: { [string]: { number } } } local tracks: { [any]: Track } = {} local trackOrder: { any } = {} - local morph: { [any]: Curve } = {} -- blend shape channel id -> DeformPercent curve + local morph: { [any]: Curve } = {} local layers = sources(stack.id, "AnimationLayer") for _, layer in layers do for _, cn in sources(layer.id, "AnimationCurveNode") do @@ -1328,7 +1305,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end end - -- morph target weights: every node whose mesh has an animated blend shape channel if next(morph) then for ni, nd in scene.nodes do local chans = nd.mesh and shapeChannels[nd.mesh] diff --git a/src/Rosetta/model/fbx/Write.luau b/src/Rosetta/model/fbx/Write.luau index e48613a..7311530 100644 --- a/src/Rosetta/model/fbx/Write.luau +++ b/src/Rosetta/model/fbx/Write.luau @@ -1,11 +1,6 @@ --!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. +-- model/fbx/Write: Scene -> an FBX 7.4 node tree. 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); rotations as Euler XYZ degrees. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") @@ -28,7 +23,7 @@ local function arr(t: string, list: { number }): any end return { array = true, type = t, count = n, data = d } end --- P: name, type, label, flags, values (vt: one type character per value) +-- P: name, type, label, flags, values 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 @@ -64,7 +59,6 @@ local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) -> 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 @@ -235,7 +229,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) 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, @@ -260,7 +253,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) -- ------------------------------------------------------------------------------------------ models local modelIds: { [number]: number } = {} local skip: { [number]: boolean } = {} - local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there) + local attrHost: { [number]: number } = {} local parentOf: { [number]: number } = {} for i, nd in nodes do for _, c in nd.children or {} do @@ -283,7 +276,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) attrHost[i] = p end end - -- world matrices (rest pose) for clusters and the bind pose local worldM: { [number]: Mat4.M4 } = {} local visiting: { [number]: boolean } = {} local function world(i: number): Mat4.M4 @@ -390,7 +382,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local euler = Mat4.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 @@ -430,9 +421,9 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) -- ------------------------------------------------------------------------------------------ geometry local geoIds: { [number]: number } = {} - local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot + local geoSlots: { [number]: { number } } = {} local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {} - local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation) + local geoChannels: any = {} local geoCount: { [number]: number } = {} local function geometry(mi: number): number? if geoIds[mi] then @@ -625,7 +616,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) 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 @@ -717,7 +707,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) 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 @@ -728,7 +717,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) 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 = {} } @@ -878,7 +866,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) 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] diff --git a/src/Rosetta/model/fbx/Xform.luau b/src/Rosetta/model/fbx/Xform.luau index abe251b..b7376ff 100644 --- a/src/Rosetta/model/fbx/Xform.luau +++ b/src/Rosetta/model/fbx/Xform.luau @@ -1,7 +1,6 @@ --!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, with FBX's numbered Euler orders. The --- matrix / quaternion arithmetic is codecs/model/Mat4. +-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): +-- local = T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1 local Mat4 = require("@rosetta/codecs/model/Mat4") local Xform = {} @@ -12,7 +11,6 @@ function Xform.euler(x: number, y: number, z: number, order: number?): Mat4.M4 return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz") 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 }, @@ -28,7 +26,6 @@ function Xform.localMatrix(p: Props): Mat4.M4 end m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) if not isZero(p.Rpost) then - -- the inverse of a rotation is its transpose m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0))) end m = Mat4.mul(m, Mat4.translation(-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])) diff --git a/src/Rosetta/model/fbx/init.luau b/src/Rosetta/model/fbx/init.luau index db1f96d..b266afd 100644 --- a/src/Rosetta/model/fbx/init.luau +++ b/src/Rosetta/model/fbx/init.luau @@ -1,24 +1,7 @@ --!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/compress/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). +-- model/fbx: Autodesk FBX 7.x binary and ASCII, from Blender's io_scene_fbx, assimp and the FBX SDK transform docs. +-- Supports: Model transforms, meshes, Phong / Physical materials, textures, skins, blend shapes, animation, cameras. +-- Not supported: FBX 6.x and older, NURBS / patches / lines, constraints, animation layer blending. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -41,21 +24,21 @@ local Fbx = { -- ------------------------------------------------------------------------------------------------ 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) + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + sampleRate: number?, -- samples per second (default: the keys only) + resolve: ((uri: string) -> any)?, -- external texture files + files: { [string]: any }?, + maxBytes: number?, -- default 2^30 bytes of arrays + maxVertices: number?, -- default 2^25 polygon corners } export type EncodeOptions = { - ascii: boolean?, -- write ASCII FBX (default binary) + ascii: boolean?, -- 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) + flipV: boolean?, -- default true + embedTextures: boolean?, -- default true + compress: boolean?, -- arrays over 32 elements (default true) + name: string?, creator: string?, } @@ -100,8 +83,6 @@ end local toErr = Err.from --- 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) @@ -129,7 +110,6 @@ function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E 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)) diff --git a/src/Rosetta/model/gltf/Pack.luau b/src/Rosetta/model/gltf/Pack.luau index 470d384..998eb9b 100644 --- a/src/Rosetta/model/gltf/Pack.luau +++ b/src/Rosetta/model/gltf/Pack.luau @@ -1,15 +1,11 @@ --!strict --!native --- model/gltf/Pack: the byte loops of glTF accessors: strided / column-padded elements into tightly packed Scene --- accessor data (gather), the reverse for writing (scatter), and sparse substitution. Callers check every range --- first (offsets, strides and counts against the buffer lengths); nothing here throws. +-- model/gltf/Pack: the byte loops of glTF accessors (gather strided elements, scatter, sparse substitution); callers +-- check every range first. glTF pads matrix columns to 4 bytes. local Pack = {} local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32 --- gather(dst, src, off, count, elem, stride, cols, colBytes, colStride): element i starts at off + i * stride; an element is --- cols columns of colBytes bytes, colStride apart (glTF pads matrix columns to 4 bytes); dst gets them packed (elem = --- cols * colBytes bytes each) function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) if cols == 1 or colBytes == colStride then if stride == elem then @@ -30,7 +26,6 @@ function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: end end --- scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride): the reverse of gather (dst zero-filled) function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) if cols == 1 or colBytes == colStride then if stride == elem then @@ -51,8 +46,6 @@ function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: end end --- sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) -> false when an index is out of range: element --- idx[k] of dst becomes value k (values packed, elem bytes each) function Pack.sparse(dst: buffer, count: number, elem: number, idx: buffer, idxOff: number, idxSize: number, values: buffer, valOff: number, n: number): boolean for k = 0, n - 1 do local i diff --git a/src/Rosetta/model/gltf/Read.luau b/src/Rosetta/model/gltf/Read.luau index 7159685..f3d1176 100644 --- a/src/Rosetta/model/gltf/Read.luau +++ b/src/Rosetta/model/gltf/Read.luau @@ -1,10 +1,6 @@ --!strict --- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. Accessors of every component type --- (normalized ones as unorm / snorm, matrices with their column padding removed, byte strides, sparse substitution, --- accessors without a bufferView as zeros), images kept encoded (bufferView / data: URI / external file through the --- fetch callback), samplers, PBR materials with every material extension (textureInfo objects -> TextureRefs), the --- KHR_texture_transform of every texture reference, cameras, KHR_lights_punctual, skins, animations, morph targets, --- scenes. glTF extras and unhandled extensions are kept in .extras.gltf = { extras, extensions }. +-- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. glTF extras and unhandled extensions are +-- kept in .extras.gltf = { extras, extensions }. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Base64 = require("@rosetta/core/Base64") @@ -27,7 +23,7 @@ local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 } local MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" } local WRAP: { [number]: "clamp" | "mirror" | "repeat" } = { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" } local MIN_FILTER = { [9728] = "nearest", [9729] = "linear", [9984] = "nearest_mipmap_nearest", [9985] = "linear_mipmap_nearest", [9986] = "nearest_mipmap_linear", [9987] = "linear_mipmap_linear" } --- the extensions this reader understands (everything else that is required -> UNSUPPORTED) +-- the extensions this reader understands (any other required one -> UNSUPPORTED) local KNOWN = { KHR_lights_punctual = true, KHR_mesh_quantization = true, @@ -83,7 +79,6 @@ local function numbers(v: any, n: number): { number }? return table.move(v, 1, n, 1, {} :: { number }) end --- extras.gltf: the JSON extras and the extensions not turned into Scene fields local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any }? local extras = obj.extras local ext: { [string]: any }? = nil @@ -102,8 +97,7 @@ local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any return { gltf = { extras = extras, extensions = ext } } end --- a Draco attribute as the type its glTF accessor declares (the bytes as they are when the layouts agree, else value --- by value: normalized integers <-> floats, ints widened or narrowed) +-- a Draco attribute as its glTF accessor's type: bytes as they are when the layouts agree, else value by value local DRACO_HANDLED = { KHR_draco_mesh_compression = true } local DRACO_SIZE = { i8 = 1, u8 = 1, i16 = 2, u16 = 2, i32 = 4, u32 = 4, f32 = 4 } local DRACO_SAME: { [string]: string } = { i8 = "i8", u8 = "u8", i16 = "i16", u16 = "u16", u32 = "u32", f32 = "f32", snorm8 = "i8", unorm8 = "u8", snorm16 = "i16", unorm16 = "u16", i32 = "i32" } @@ -171,7 +165,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end end local scene = Types.Scene.new() - -- buffers local buffers: { buffer } = {} local total = 0 for i, b in arr(doc.buffers) do @@ -228,7 +221,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end views[i] = { buf = b, offset = off, length = len, stride = stride } end - -- accessors local accessors: { Types.Accessor } = {} for i, a in arr(doc.accessors) do local label = "accessor " .. (i - 1) @@ -295,7 +287,7 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc if io + n * isz > iv.length or vo + n * elem > vv.length then return nil, Err.new(Err.CORRUPT, label .. ": sparse data runs past its bufferView") end - -- sparse values are tightly packed (matrices: padded columns, rare enough to repack first) + -- sparse values are tightly packed (matrices: padded columns) local vals, valOff = vv.buf, vv.offset + vo if cols > 1 and colBytes ~= colStride then vals = buffer.create(n * elem) @@ -317,7 +309,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc local k = int(v) return if k then accessors[k + 1] else nil end - -- images (kept encoded), samplers, textures local images: { Img } = {} for i, im in arr(doc.images) do if type(im) ~= "table" then @@ -403,7 +394,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.textures, tex) end - -- materials local function texRef(info: any): Types.TextureRef? if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures then return nil @@ -415,7 +405,7 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end return r end - -- an extension object with every textureInfo (a table with an index, under a key ending in Texture) -> TextureRef + -- a textureInfo: a table with an index, under a key ending in Texture local function convertExt(v: any): any if type(v) ~= "table" then return v @@ -465,7 +455,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc mat.extras = kept table.insert(scene.materials, mat) end - -- meshes for i, m in arr(doc.meshes) do if type(m) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad mesh " .. (i - 1)) @@ -534,7 +523,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc if not ind or ind.components ~= 1 or (ind.type ~= "u8" and ind.type ~= "u16" and ind.type ~= "u32") then return nil, Err.new(Err.CORRUPT, "bad indices accessor") end - -- indices must reference existing vertices local get = Types.Scene.reader(ind :: Types.Accessor) :: any for q = 0, ind.count - 1 do if get(q, 0) >= count then @@ -563,7 +551,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.meshes, mesh) end - -- cameras, lights for _, c in arr(doc.cameras) do if type(c) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad camera") @@ -591,7 +578,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc }) end end - -- nodes local nodes = arr(doc.nodes) for i, n in nodes do if type(n) ~= "table" then @@ -647,7 +633,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc p = parent[p] end end - -- skins for _, s in arr(doc.skins) do if type(s) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad skin") @@ -661,7 +646,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.skins, { name = str(s.name), joints = joints, inverseBindMatrices = accessor(s.inverseBindMatrices), skeleton = if int(s.skeleton) and s.skeleton < #scene.nodes then s.skeleton + 1 else nil }) end - -- animations for _, a in arr(doc.animations) do if type(a) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad animation") @@ -698,7 +682,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.animations, anim) end - -- scenes local scenes = arr(doc.scenes) local list = {} for _, s in scenes do @@ -720,7 +703,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end end end - -- root extensions other than the lights, asset info local rootExt = nil if type(doc.extensions) == "table" then for k, v in doc.extensions do diff --git a/src/Rosetta/model/gltf/Write.luau b/src/Rosetta/model/gltf/Write.luau index dc91e3d..9ff38ff 100644 --- a/src/Rosetta/model/gltf/Write.luau +++ b/src/Rosetta/model/gltf/Write.luau @@ -1,11 +1,6 @@ --!strict --- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. One bufferView per accessor (vertex --- attributes 4-byte aligned per element with a byteStride when needed, matrix columns padded as glTF requires), --- accessors shared between primitives / animations written once, f64 / i32 data converted (glTF has neither), --- POSITION and animation input min / max, KHR_mesh_quantization declared when attributes are not floats, --- KHR_texture_transform / KHR_lights_punctual / material extensions declared when used, images deduplicated by their --- bytes (or uri), samplers by their settings. "polygons" primitives are fan-triangulated (MeshOps.triangulate first --- for concave faces). +-- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. Vertex attributes 4-byte aligned per +-- element, matrix columns padded, f64 / i32 data converted (glTF has neither), POSITION and animation input min / max. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -89,7 +84,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) return #views - 1 end - -- accessor(acc, usage, attribute?) -> the glTF index (0-based) local function accessor(acc: Types.Accessor, usage: string, attribute: string?): number local known = accIndex[acc] if known then @@ -148,7 +142,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) return 0 end if attribute == "POSITION" or usage == "input" then - -- min / max of the raw component values local raw = Types.Scene.accessor(a.data, if a.type == "unorm8" then "u8" elseif a.type == "unorm16" then "u16" elseif a.type == "snorm8" then "i8" elseif a.type == "snorm16" then "i16" else a.type, comps, a.count) local get = Types.Scene.reader(raw) :: (number, number) -> number local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge) @@ -173,7 +166,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) return index end - -- extras.gltf -> extras / extensions fields of a glTF object local function restore(g: any, extras: any) local saved = type(extras) == "table" and extras.gltf if type(saved) ~= "table" then @@ -193,7 +185,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end end - -- images, samplers, textures local images: { any } = {} local imageOut: { { data: buffer, mime: string?, name: string } } = {} local imageIndex: { [any]: number } = {} @@ -212,7 +203,7 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) im.bufferView = view(data, buffer.len(data), nil, nil) im.mimeType = mime or "image/png" elseif embedImages then - im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI by the caller (init) / a file name + im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI / a file name by the caller im.mimeType = mime table.insert(imageOut, { data = data, mime = mime, name = im.uri }) else @@ -316,7 +307,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end return out end - -- materials local materials: { any } = {} for i, m in scene.materials or {} do if type(m) ~= "table" then @@ -370,7 +360,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, m.extras) table.insert(materials, g) end - -- meshes local meshes: { any } = {} for i, mesh in scene.meshes or {} do if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then @@ -396,7 +385,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) local mode = p.mode or "triangles" local indices = p.indices if mode == "polygons" then - -- fan-triangulate local faces = p.faces local getf = faces and Types.Scene.reader(faces) local n = if indices then indices.count else p.attributes.POSITION.count @@ -459,7 +447,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, mesh.extras) table.insert(meshes, g) end - -- cameras, lights local cameras: { any } = {} for _, c in scene.cameras or {} do local g = object() @@ -498,7 +485,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end table.insert(lights, g) end - -- nodes local nodes: { any } = {} local nodeCount = #(scene.nodes or {}) for i, n in scene.nodes or {} do @@ -549,7 +535,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, n.extras) table.insert(nodes, g) end - -- skins local skins: { any } = {} for _, s in scene.skins or {} do local g = object() @@ -570,7 +555,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end table.insert(skins, g) end - -- animations local animations: { any } = {} for _, a in scene.animations or {} do local g = object() @@ -602,7 +586,7 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) if failure then return nil, failure end - -- scenes: the original list (meta.gltf.scenes) when it is there, else the roots + -- scenes: the original list (meta.gltf.scenes), else the roots local meta: { [string]: any } = if type(scene.meta) == "table" then scene.meta else {} local mg = type(meta.gltf) == "table" and meta.gltf or {} local scenes = {} @@ -619,7 +603,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, s.extras) table.insert(scenes, g) end - -- the current roots replace the default scene's list local which = mg.scene or 1 if scenes[which] then scenes[which].nodes = {} @@ -646,7 +629,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) asset.extras = mg.asset.extras end doc.asset = asset - -- root extensions kept from the source (variants, ...), the lights if type(mg.extensions) == "table" then doc.extensions = object() for k, v in mg.extensions do diff --git a/src/Rosetta/model/gltf/init.luau b/src/Rosetta/model/gltf/init.luau index 9d094ed..3a592da 100644 --- a/src/Rosetta/model/gltf/init.luau +++ b/src/Rosetta/model/gltf/init.luau @@ -1,22 +1,7 @@ --!strict --- model/gltf: glTF 2.0 (Khronos specification 2.0.1), JSON (.gltf with embedded data: URIs or external files) and --- binary (.glb). New code. --- Reads: scenes, the node tree (TRS / matrix), meshes (every primitive mode, morph targets), accessors of every --- component type (normalized -> unorm / snorm, sparse, byte strides, padded matrix columns, no bufferView), PBR --- materials + the KHR_materials_* extensions (emissive_strength, unlit, clearcoat, transmission, volume, ior, --- specular, sheen, iridescence, anisotropy, dispersion, diffuse_transmission, pbrSpecularGlossiness: their fields kept, --- textureInfo objects as TextureRefs), KHR_texture_transform, textures + samplers + images (kept encoded: bytes + mime, --- or the uri; KHR_texture_basisu / EXT_texture_webp / EXT_texture_avif sources), cameras, KHR_lights_punctual, skins, --- animations, KHR_mesh_quantization, extras and unknown extensions (written back). Images are never decoded here (a --- format does not require another format): F.model.loadTextures(scene) decodes them at the api layer. --- External .bin / image files come from opts.resolve(uri) or opts.files[uri] (the api sets resolve for paths). --- Writes .gltf (buffers and images embedded as data: URIs by default; opts.external = true writes .bin and the --- images into opts.files) or .glb (opts.binary, or opts.format == "glb": the api passes the destination's extension). --- Draco compressed primitives (KHR_draco_mesh_compression) decode through codecs/model/Draco: the attributes the --- extension lists and the indices come from the Draco data, as the types their accessors declare. Written back --- uncompressed (the extension is dropped). --- Not supported: meshopt (EXT_meshopt_compression) compressed primitives (UNSUPPORTED), KHR_animation_pointer channels --- (skipped and counted in the animation's extras). +-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), .gltf JSON and .glb. Supports: the core spec, KHR_materials_*, +-- KHR_texture_transform, KHR_lights_punctual, KHR_mesh_quantization, KHR_draco_mesh_compression (written uncompressed). +-- Not supported: EXT_meshopt_compression (UNSUPPORTED), KHR_animation_pointer channels (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -40,16 +25,16 @@ local Gltf = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string); the api sets it for paths - files: { [string]: any }?, -- or: the files by uri - maxBytes: number?, -- refuse buffers / accessors over this many bytes in total (default 2^30) + resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string) + files: { [string]: any }?, + maxBytes: number?, -- default 2^30 bytes of buffers / accessors } export type EncodeOptions = { - binary: boolean?, -- write GLB (default: when opts.format is "glb") - format: string?, -- "glb" -> binary (set by the api from the destination's extension) - external: boolean?, -- .gltf: write the buffer and images as files into opts.files (default false: data: URIs) + binary: boolean?, -- default: when opts.format is "glb" + format: string?, + external: boolean?, -- default false: data: URIs files: { [string]: any }?, -- receives .bin and images with external = true - name: string?, -- the destination's file name (names the external files) + name: string?, embedImages: boolean?, -- default true (false with external = true) } @@ -98,7 +83,6 @@ local function fetcher(opts: DecodeOptions?): Read.Fetch end end --- the JSON text and BIN chunk of a GLB local function glb(r: Bytes.Reader): (string?, buffer?, Err.Err?) local magic, version, length = r:u32le(), r:u32le(), r:u32le() if r.err then @@ -178,7 +162,6 @@ function Gltf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Er local doc = out.doc local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" local files = opts and opts.files - -- images: data: URIs, or files if doc.images then local n = 0 for _, im in doc.images do diff --git a/src/Rosetta/model/iqm/Read.luau b/src/Rosetta/model/iqm/Read.luau index df004ac..0ce4fe9 100644 --- a/src/Rosetta/model/iqm/Read.luau +++ b/src/Rosetta/model/iqm/Read.luau @@ -1,7 +1,5 @@ --!strict --- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and --- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken). --- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall). +-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. Every header range is checked before it is read. local Types = require("@rosetta/Types") local Rig = require("@rosetta/codecs/model/Rig") @@ -32,7 +30,7 @@ local function half(h: number): number return s * (1 + m / 1024) * 2 ^ (e - 15) end --- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1) +-- normalized: integer formats scaled to 0..1 / -1..1 local function values(b: buffer, at: number, format: number, n: number, normalized: boolean): { number } local out = table.create(n) :: { number } local size = Read.SIZES[format] @@ -77,7 +75,6 @@ end local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } --- scene(b, base, limit, opts) -> Scene | nil, message function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: number? }?): (Types.Scene?, string?) local size = limit - base local H: { [string]: number } = {} @@ -128,7 +125,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: if H.num_comment > 0 then source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") end - -- vertex arrays (the whole model's vertices; meshes are ranges of them) local nv = H.num_vertexes type Array = { kind: string, name: string, format: number, comps: number, offset: number } local arrays: { Array } = {} @@ -147,7 +143,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: local name = if kind then kind else "_" .. (if typ >= 0x10 then str(typ - 0x10) else tostring(typ)) table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) end - -- joints -> nodes + a skin local jointNodes: { number } = {} local skin: number? = nil if H.num_joints > 0 then @@ -166,7 +161,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: end jointNodes, skin = Rig.skeleton(scene, joints, "local") end - -- materials: one per distinct material string (IQM names its texture there) + -- materials: one per distinct material string (IQM tools name the texture there) local matOf: { [string]: number } = {} local function material(name: string): number? if name == "" then @@ -185,7 +180,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: matOf[name] = #scene.materials return #scene.materials end - -- meshes for m = 0, H.num_meshes - 1 do local p = base + H.ofs_meshes + m * 24 local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) @@ -242,7 +236,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: if not attributes.POSITION then return nil, "no position array" end - -- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise + -- IQM's front faces are clockwise: corners 2 and 3 swap local ib = buffer.create(ct * 12) for k = 0, ct - 1 do local q = base + H.ofs_triangles + (ft + k) * 12 @@ -263,7 +257,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: table.insert(scene.nodes, node) table.insert(scene.roots, #scene.nodes) end - -- animations: frames hold the masked pose channels (offset + value * scale), in pose order + -- frames hold the masked pose channels (offset + value * scale), in pose order if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then local np = H.num_poses local poses: { { mask: number, offset: { number }, scale: { number } } } = {} diff --git a/src/Rosetta/model/iqm/Write.luau b/src/Rosetta/model/iqm/Write.luau index a1dbe7a..63e03c8 100644 --- a/src/Rosetta/model/iqm/Write.luau +++ b/src/Rosetta/model/iqm/Write.luau @@ -1,14 +1,6 @@ --!strict --- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). One IQM mesh per triangle-able primitive (lines --- and points are skipped), vertex arrays position / texcoord / normal / tangent (f32), blend indexes / weights --- (u8, the four strongest weights, summing to 255) and colour (u8). The skeleton is the union of the scene's skins --- (parents before children; a joint's parent is its nearest ancestor that is a joint): bind poses from the inverse --- bind matrices, so IQM's implied inverse bind matrices are the scene's. Unskinned primitives are baked into world --- space and, in a skinned model, bound to their nearest joint ancestor (else the first joint). Animations are --- sampled (codecs/model/Sampler) at their own key spacing when it is uniform, else at opts.framerate (default 30), --- quantized per pose channel to 16 bits, with per-frame bounds from the skinned vertices. --- Coordinates are written as they are (IQM is z-up: a y-up scene can be turned with F.ops.mesh.setUp first). --- Plain code (the caller wraps it in pcall). +-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). Blend weights are u8 summing to 255; the skeleton +-- is the union of the scene's skins, parents first; animations quantized per pose channel to 16 bits. local Types = require("@rosetta/Types") local Bytes = require("@rosetta/core/Bytes") local Mat4 = require("@rosetta/codecs/model/Mat4") @@ -21,7 +13,6 @@ local Scene = Types.Scene type M4 = { number } -- ------------------------------------------------------------------------------------------------ scene walk --- world matrices (rest pose, or with a pose's overrides) and the parent of every node local function parents(scene: Types.Scene): { [number]: number } local parent: { [number]: number } = {} for i, n in scene.nodes do @@ -70,7 +61,6 @@ local function worlds(scene: Types.Scene, parent: { [number]: number }, pose: Sa end -- ------------------------------------------------------------------------------------------------ geometry --- the triangle corners of a primitive (0-based vertex numbers), or nil for lines / points local function triangles(prim: Types.Primitive): { number }? local mode = prim.mode or "triangles" local nv = prim.attributes.POSITION.count @@ -143,7 +133,7 @@ local function readAll(acc: Types.Accessor?, comps: number, nv: number, default: return out end --- the influences of vertex v: global joint numbers, the 4 strongest, u8 weights summing to 255, as a flat list +-- the 4 strongest, u8 weights summing to 255 local function influences(skin: Types.Skin, jointIndex: { [number]: number }, joints: { number }, weights: { number }, v: number): { number } local pairs_: { { number } } = {} for c = 1, 4 do @@ -179,7 +169,6 @@ local function influences(skin: Types.Skin, jointIndex: { [number]: number }, jo return list end --- appends a flat influence list to the blend index / weight arrays (4 slots) local function push4(bi: { number }, bw: { number }, list: { number }) local n = #bi for c = 1, 4 do @@ -194,7 +183,6 @@ type MeshOut = { name: string, material: string, first: number, count: number, t function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: string? }?): (buffer?, string?) local parent = parents(scene) local rest = worlds(scene, parent, nil) - -- the skeleton: every skin joint, parents first local isJoint: { [number]: boolean } = {} local ibmOf: { [number]: M4 } = {} for _, skin in scene.skins do @@ -212,9 +200,9 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end end end - -- the skins' joints in order, each after its joint ancestors (IQM wants parents first) + -- IQM wants parents first local jointList: { number } = {} - local jointIndex: { [number]: number } = {} -- node -> 0-based joint + local jointIndex: { [number]: number } = {} local function add(n: number, depth: number) if jointIndex[n] or depth > #scene.nodes then return @@ -271,7 +259,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end return Mat4.decompose(m) end - -- the meshes local nodeOfMesh: { [number]: number } = {} local placed: { { node: number, mesh: number } } = {} local seen: { [number]: boolean } = {} @@ -311,7 +298,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri local hasTC, hasN, hasTG, hasC = false, false, false, false local tris: { number } = {} local meshes: { MeshOut } = {} - -- every primitive's per-vertex skinning as lists (joint, weight), for the bounds local skinOf: { { number } } = {} local nvTotal = 0 for _, pl in placed do @@ -392,7 +378,7 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri else table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C) end - -- influences: global joint numbers, the 4 strongest, u8 weights summing to 255 + -- the 4 strongest, u8 weights summing to 255 local list: { number } if joints and weights and skinned then list = influences(skinned, jointIndex, joints, weights, v) @@ -404,7 +390,7 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri push4(BI, BW, list) skinOf[#skinOf + 1] = list end - -- triangles back to IQM's clockwise order + -- IQM's clockwise order local tfirst = #tris // 3 for k = 1, #tri, 3 do table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris) @@ -428,7 +414,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri if #meshes == 0 then return nil, "nothing to write: no triangle primitives" end - -- animation frames local frames: { { { number } } } = {} -- frames[f][joint] = 10 values local anims: { { name: string, first: number, count: number, rate: number } } = {} local frameWorld: { { [number]: M4 } } = {} @@ -438,7 +423,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri if #keys > 0 then local rate = opts and opts.framerate if not rate then - -- the key spacing when uniform (decoded IQM / MD5 animations), else 30 per second local dt = if #keys > 1 then keys[2] - keys[1] else 0 local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4 for k = 2, #keys do @@ -475,7 +459,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end end end - -- quantization per pose channel local masks, offsets, scales = {}, {}, {} local numChannels = 0 for j = 1, #jointList do @@ -500,7 +483,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end masks[j], offsets[j], scales[j] = mask, off, sc end - -- text local text = { "\0" } local textLen = 1 local textAt: { [string]: number } = { [""] = 0 } @@ -527,7 +509,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri str(a.name) end local comment = opts and opts.comment - -- layout local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4) local H: { [string]: number } = {} local function at(): number @@ -549,7 +530,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri w:u32le(v) end end - -- vertex arrays: headers, then data type Arr = { typ: number, format: number, comps: number, data: { number } } local arrs: { Arr } = { { typ = 0, format = 7, comps = 3, data = P } } if hasTC then @@ -648,7 +628,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri while at() % 4 ~= 0 do w:u8(0) end - -- bounds of the skinned vertices per frame H.ofs_bounds = at() local skinM = table.create(#jointList) :: { M4 } for f, world in frameWorld do diff --git a/src/Rosetta/model/iqm/init.luau b/src/Rosetta/model/iqm/init.luau index 016b70e..53f5e17 100644 --- a/src/Rosetta/model/iqm/init.luau +++ b/src/Rosetta/model/iqm/init.luau @@ -1,15 +1,7 @@ --!strict --- model/iqm: Inter-Quake Model (IQM version 2), read and write. New code from the IQM format description (iqm.txt / --- iqm.h of Lee Salzman's IQM SDK, public domain); checked against assimp (which reads IQM geometry). --- Reads meshes (one node + mesh each; material strings -> materials whose baseColorTexture uri is that string, as --- IQM tools name the texture there), vertex arrays in every IQM format (position, texcoord (top-left origin, as --- glTF), normal, tangent, blend indexes / weights -> JOINTS_0 / WEIGHTS_0, colour, custom arrays as _), joints --- (a node each, bind pose TRS, one skin with the inverse bind matrices), poses + frames + anims (16-bit channels --- dequantized into translation / rotation / scale channels at the anim's frame rate; loop flags and frame ranges in --- meta.source.animations) and per-frame bounds (meta.source.bounds). IQM's clockwise triangles become glTF's --- counter-clockwise ones; IQM is z-up (meta.up = "z", nothing is rotated). --- Writes the same (see model/iqm/Write): any Scene's triangle primitives, skins merged into one skeleton, sampled and --- quantized animations, bounds. Not supported: IQM version 1, adjacency and extensions (skipped on read, not written). +-- model/iqm: Inter-Quake Model (IQM version 2; iqm.txt / iqm.h of Lee Salzman's IQM SDK, public domain; checked against +-- assimp). Supports: meshes, every vertex array format, joints / skin, poses + anims, bounds. IQM is z-up, clockwise. +-- Not supported: IQM version 1, adjacency and extensions. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,11 +22,11 @@ local Iqm = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxVertices: number?, -- refuse more vertices or triangles (default 2^25) + maxVertices: number?, -- default 2^25 } export type EncodeOptions = { - framerate: number?, -- animation sampling rate (default: the key spacing when uniform, else 30 per second) - comment: string?, -- stored in the comment block + framerate: number?, -- default: the key spacing when uniform, else 30 per second + comment: string?, } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Rosetta/model/ldraw/Colors.luau b/src/Rosetta/model/ldraw/Colors.luau index d114066..7d3d36f 100644 --- a/src/Rosetta/model/ldraw/Colors.luau +++ b/src/Rosetta/model/ldraw/Colors.luau @@ -1,7 +1,6 @@ --!strict --- model/ldraw/Colors: the LDraw colour table: code -> { name, rgb, edge, alpha, luminance, finish }, parsed from --- !COLOUR lines. The built-in table is the colour list of LDraw.org's LDConfig.ldr (UPDATE 2025-05-20; CC BY 2.0, see --- licenses/LDRAW_COLOURS.txt), one line per colour without the "0 !COLOUR " prefix and with the MATERIAL parameters cut +-- model/ldraw/Colors: the LDraw colour table, parsed from !COLOUR lines. The built-in table is LDraw.org's LDConfig.ldr +-- (UPDATE 2025-05-20; CC BY 2.0, see licenses/LDRAW_COLOURS.txt), without the "0 !COLOUR " prefix and with MATERIAL cut -- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB. local Colors = {} @@ -10,7 +9,7 @@ export type Table = { [number]: Colour } local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true } --- entry(rest) -> code, Colour | nil: one "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." +-- "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." function Colors.entry(rest: string): (number?, Colour?) local words: { string } = {} for w in string.gmatch(rest, "%S+") do @@ -51,7 +50,6 @@ function Colors.entry(rest: string): (number?, Colour?) return code, { name = name, rgb = rgb :: number, edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish } end --- parse(text, into?) -> into (a new table by default) with every "0 !COLOUR" line of text added function Colors.parse(text: string, into: Table?): Table local t: Table = into or {} for line in string.gmatch(text, "[^\n]+") do @@ -297,7 +295,6 @@ Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16 ]] local cache: Table? = nil --- builtin() -> a fresh copy of the LDConfig.ldr table (callers may add to it) function Colors.builtin(): Table if not cache then local t: Table = {} diff --git a/src/Rosetta/model/ldraw/Read.luau b/src/Rosetta/model/ldraw/Read.luau index 8b5b060..bcc201a 100644 --- a/src/Rosetta/model/ldraw/Read.luau +++ b/src/Rosetta/model/ldraw/Read.luau @@ -1,8 +1,7 @@ --!strict --- model/ldraw/Read: LDraw text -> Types.Scene (see model/ldraw for the mapping). Files are parsed once into command --- lists (MPD sections, then sub-files through opts.files / opts.resolve with the library paths); parts are baked into --- one mesh per (part, colour, inversion), with the BFC rules applied inside the part; model files become nodes. --- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +-- model/ldraw/Read: LDraw text -> Types.Scene. Sub-files are tried as written (backslashes as slashes), then lower +-- case, under "", "parts/", "p/", "parts/s/" and "models/"; faces are written counter-clockwise after the matrices' +-- mirroring. local Types = require("@rosetta/Types") local Colors = require("@rosetta/model/ldraw/Colors") @@ -22,7 +21,7 @@ export type Options = { maxNodes: number?, } --- a parsed line: k = 0 (a BFC state change: cw / clip), 1 (a reference: v = x y z a b c d e f g h i), 2..5 +-- k = 0 (a BFC state change), 1 (a reference: v = x y z a b c d e f g h i), 2..5 type Cmd = { k: number, c: number, v: { number }, name: string?, inv: boolean?, step: number?, cw: boolean?, clip: boolean? } type File = { name: string, @@ -52,7 +51,6 @@ local function srgbToLinear(v: number): number return if v <= 0.04045 then v / 12.92 else ((v + 0.055) / 1.055) ^ 2.4 end --- parse(text, name) -> File (colour definitions go into colours as they are met) local function parse(text: string, name: string, colours: Colors.Table, stats: { bad: number, lines: number }): File local f: File = { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false } local cmds = f.cmds @@ -96,7 +94,6 @@ local function parse(text: string, name: string, colours: Colors.Table, stats: { elseif w1 == "Author:" then f.author = rest elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then - -- (headers) elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then f.title = (string.match(line, "^%s*0%s+(.-)%s*$")) end @@ -152,7 +149,6 @@ local function parse(text: string, name: string, colours: Colors.Table, stats: { return f end --- scene(text, opts) -> Scene | nil, message, kind function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, string?) local o: Options = opts or {} local colours = Colors.builtin() @@ -329,7 +325,7 @@ function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, strin end end - -- bake(file, m (3x4 row-major), colour, inv, certified, depth, stack, groups, order, direct) + -- m is a 3x4 row-major matrix local function bake(f: File, m: { number }, colour: number, inv: boolean, certified: boolean, depth: number, stack: { [File]: boolean }, groups: { [string]: Group }, order: { Group }, direct: boolean) if failure then return @@ -439,7 +435,6 @@ function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, strin return Types.Scene.accessor(b, "f32", 3, count) end - -- the mesh of a file baked at the identity (nil when it has no geometry) local meshOf: { [string]: number | false } = {} local function meshFor(f: File, colour: number, inv: boolean, direct: boolean): number? local key = f.key .. "|" .. colour .. "|" .. (if inv then "i" else "") .. (if direct then "d" else "") diff --git a/src/Rosetta/model/ldraw/init.luau b/src/Rosetta/model/ldraw/init.luau index 01aab94..245a395 100644 --- a/src/Rosetta/model/ldraw/init.luau +++ b/src/Rosetta/model/ldraw/init.luau @@ -1,33 +1,7 @@ --!strict --- model/ldraw: LDraw (.ldr / .dat / .mpd), read. Written from the LDraw File Format specification 1.0.2, the MPD and --- BFC (back face culling) language extensions and the colour definition (!COLOUR) extension (ldraw.org); checked --- against an independent expansion in the fixture generator and LeoCAD's OBJ export of library parts and models. --- Reads: line types 0 (meta: Name / Author / !LDRAW_ORG / STEP / !COLOUR / BFC), 1 (sub-file references: colour + --- 3x4 matrix), 2 (lines), 3 (triangles), 4 (quads, split in two), 5 (optional lines: skipped, or opts.optionalLines --- -> "lines" primitives with _CONTROL_0 / _CONTROL_1 attributes and prim.extras.ldraw.optional). MPD files split at --- `0 FILE` / `0 NOFILE` (the first file is the model); other sub-files come through opts.files / opts.resolve, tried --- as written (backslashes as slashes), then lower case, under "", "parts/", "p/", "parts/s/" and "models/". Missing --- sub-files are skipped and listed (meta.source.missing); a file that places itself is skipped (meta.source.cycles). --- Scene: parts (files whose !LDRAW_ORG type is not a model, library files, .dat sub-files, a main file without --- references) are baked into one mesh per (part, colour, INVERTNEXT), shared by every placement; models (the main --- file, .ldr / .mpd sub-models) become nodes: one node per reference with the reference's matrix (node.extras.ldraw = --- { file, color, step, invert? }), a model's own geometry on an extra node. opts.flatten bakes the whole model into one --- mesh. Primitives: one "triangles" primitive per colour (and per one- / double-sided), "lines" for type 2 (opts.lines --- = false drops them); no normals, no indices (each triangle has its own three vertices). --- BFC, inside a part: CERTIFY / NOCERTIFY, CW / CCW, CLIP / NOCLIP and INVERTNEXT; faces are written counter-clockwise --- (glTF's front faces) after the reference matrices' mirroring; faces of uncertified files (and their sub-files) or --- under NOCLIP get double-sided materials. Model files do not limit the certification of the parts they place. --- Colours: 16 (the parent's colour; opts.color at the top, default 16 "Main_Colour"), 24 (the parent colour's edge --- colour), codes from the built-in LDConfig.ldr table (model/ldraw/Colors; !COLOUR lines in the files and opts.ldconfig --- text add or replace entries), direct colours 0x2RRGGBB (opaque) / 0x3RRGGBB (transparent) and the old dithered --- 0x4-0x7 codes. One material per colour (baseColor linear, ALPHA -> blend, CHROME / METAL / PEARLESCENT / RUBBER -> --- metallic / roughness; extras.ldraw = { code, name, edge, finish?, luminance? }). --- Axes: LDraw is right-handed with -Y up, 1 LDU = 0.4 mm. The vertices and matrices keep LDraw's values; a root node --- "LDraw" turns the model 180 degrees about X so the scene is Y up (meta.up = "y", meta.unit = 0.0004); opts.upright = --- false leaves it out (meta.up = nil, meta.source.up = "-y"). --- meta.source = { format, mpd, name?, title?, author?, files, missing, cycles, badLines, up? }. --- Not supported: writing; !TEXMAP and !DATA (texture mapping, embedded images: ignored); the LDCad / MLCad / LPub meta --- commands (ignored); BFC in model files' references (models place parts as certified). +-- model/ldraw: LDraw (.ldr / .dat / .mpd), read; File Format spec 1.0.2 with the MPD, BFC and !COLOUR extensions +-- (ldraw.org). Supports: line types 0-5, sub-files, BFC, LDConfig colours. -Y up, 1 LDU = 0.4 mm (a root node turns +-- it). Not supported: writing; !TEXMAP and !DATA; LDCad / MLCad / LPub meta commands; BFC in model files' references. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -49,15 +23,15 @@ local Ldraw = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- sub-files (parts, primitives) by library path (the api sets it for paths) - files: { [string]: any }?, -- or: the files by library path ("parts/3001.dat", "p/stud.dat", ...) + resolve: ((uri: string) -> any)?, -- sub-files by library path + files: { [string]: any }?, -- or by library path ("parts/3001.dat", "p/stud.dat", ...) ldconfig: string?, -- LDConfig.ldr text: its !COLOUR lines add to / replace the built-in colours - color: number?, -- the colour of code 16 at the top (default 16, "Main_Colour") - upright: boolean?, -- add the root node turning -Y up into Y up (default true) - flatten: boolean?, -- one mesh for the whole model instead of a node per reference (default false) - lines: boolean?, -- type 2 edge lines as "lines" primitives (default true) - optionalLines: boolean?, -- type 5 optional lines too (default false) - maxDepth: number?, -- sub-file nesting (default 64) + color: number?, -- default 16 ("Main_Colour") + upright: boolean?, -- default true + flatten: boolean?, -- default false + lines: boolean?, -- default true + optionalLines: boolean?, -- default false + maxDepth: number?, -- default 64 maxTriangles: number?, -- default 2^24 maxNodes: number?, -- default 2^20 } @@ -80,7 +54,6 @@ end -- ------------------------------------------------------------------------------------------------ decode function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, msg, kind = pcall(Read.scene, text, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene)) @@ -92,8 +65,6 @@ function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err end -- ------------------------------------------------------------------------------------------------ extras --- colors(ldconfig?) -> { [code] = { name, rgb (0xRRGGBB sRGB), edge (a code or 0x2RRGGBB), alpha (0..255), luminance, --- finish? } }: the built-in LDConfig.ldr table, with the !COLOUR lines of ldconfig added function Ldraw.colors(ldconfig: string?): { [number]: any } local t = Colors.builtin() if ldconfig then diff --git a/src/Rosetta/model/lwo/Build.luau b/src/Rosetta/model/lwo/Build.luau index c8cfc02..4bbd6d2 100644 --- a/src/Rosetta/model/lwo/Build.luau +++ b/src/Rosetta/model/lwo/Build.luau @@ -1,11 +1,6 @@ --!strict --- model/lwo/Build: a parsed LightWave object (model/lwo/Parse) -> Types.Scene. LightWave is left-handed (y up, z --- away from the viewer, clockwise front faces): z is negated and the winding reversed, so the scene is glTF's --- right-handed y-up with counter-clockwise front faces (assimp does the same). One node per layer (translation = its --- pivot relative to the parent layer's pivot, geometry relative to the pivot, so world positions are the file's), --- one mesh per layer, one primitive per surface (and per kind: polygons, lines, points; subdivision patches apart, --- flagged extras.lwo.subdivision). Vertices are shared per point, split where a VMAD gives a corner its own value. --- Plain code (the caller wraps it in pcall). +-- model/lwo/Build: a parsed LightWave object -> Types.Scene. LightWave is left-handed (y up, clockwise front faces): z +-- is negated and the winding reversed, as assimp does. Vertices are split where a VMAD gives a corner its own value. local Types = require("@rosetta/Types") local Parse = require("@rosetta/model/lwo/Parse") @@ -14,7 +9,7 @@ local Build = {} local Scene = Types.Scene local writef32, writeu32 = buffer.writef32, buffer.writeu32 -type Group = { material: number, class: string, polys: { number } } -- class: "poly" / "patch" / "line" / "point" +type Group = { material: number, class: string, polys: { number } } -- "poly" / "patch" / "line" / "point" local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", iff = "image/x-iff" } @@ -118,7 +113,6 @@ local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { return groups end --- the corners of a face in output order (winding reversed for the handedness change, first corner kept) local function ordered(corners: { number }): { number } local n = #corners local out = table.create(n) :: { number } @@ -134,8 +128,8 @@ type Attr = { map: Parse.Map, name: string, comps: number } local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: { Parse.Map }, triangulate: boolean): Types.Primitive local pts, pivot = layer.pts, layer.pivot local vertOf: { [number]: number } = {} - local srcPoint: { number } = {} -- vertex (1-based) -> point - local srcPoly: { number } = {} -- vertex -> the polygon whose VMAD values it carries (-1: none) + local srcPoint: { number } = {} + local srcPoly: { number } = {} -- -1: none local indices: { number } = {} local faces: { number } = {} local madMaps: { Parse.Map } = {} @@ -204,7 +198,6 @@ local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: writef32(pos, o + 8, -(pts[p + 3] - pivot[3])) end local attributes: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pos, "f32", 3, nv) } - -- the value of map m for vertex v (1-based), or nil local function value(m: Parse.Map, v: number): ({ number }?, number?) local f = srcPoly[v] if f >= 0 then @@ -306,7 +299,7 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S local scene = Scene.new() scene.meta.up = "y" scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped } - -- texture coordinate sets: every TXUV map name, in order of first appearance, gets one TEXCOORD_n index + -- every TXUV map name, in order of first appearance, gets one TEXCOORD_n index local uvSets: { [string]: number } = {} local nuv = 0 for _, layer in m.layers do @@ -317,7 +310,6 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S end end end - -- materials: one per surface, then one per tag without a surface, then a default one local texCache: { [string]: number } = {} local bySurfName: { [string]: number } = {} for i, surf in m.surfaces do @@ -359,7 +351,6 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S end return default :: number end - -- nodes and meshes local nodeOf: { [number]: number } = {} local layerOfNode: { Parse.Layer } = {} for _, layer in m.layers do @@ -434,7 +425,7 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S end end end - -- the layer hierarchy (parents by layer index; a link that would close a cycle is dropped) + -- a parent link that would close a cycle is dropped local parentOf: { [number]: number } = {} for ni, layer in layerOfNode do local pi = if layer.parent ~= nil then nodeOf[layer.parent] else nil diff --git a/src/Rosetta/model/lwo/Parse.luau b/src/Rosetta/model/lwo/Parse.luau index d977762..110f66e 100644 --- a/src/Rosetta/model/lwo/Parse.luau +++ b/src/Rosetta/model/lwo/Parse.luau @@ -1,15 +1,7 @@ --!strict --- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build --- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave --- 5.x), checked against what assimp's LWO importer reads (no code taken). --- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are --- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS --- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo --- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural --- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF). --- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN, --- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. --- Plain code (the caller wraps it in pcall); bad data returns nil, message. +-- model/lwo/Parse: LightWave object chunks -> plain tables. From the LWO2 specification (LightWave 6 "Object Files", +-- Ernie Wright) and the LWOB one (LightWave 5.x), checked against assimp (no code taken). Several PNTS per layer: later +-- POLS / VMAP indices are relative to the latest. Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. local Bytes = require("@rosetta/core/Bytes") local Chunks = require("@rosetta/containers/Chunks") @@ -19,17 +11,17 @@ export type Map = { kind: string, -- "uv" | "color" | "normal" | "weight" | "morph" | "spot" name: string, dims: number, - vals: { number }, -- per point: vals[point * dims + c + 1] + vals: { number }, -- vals[point * dims + c + 1] has: { [number]: boolean }, mad: { [number]: { [number]: { number } } }, -- VMAD: mad[poly][point] = values } -export type Poly = { kind: string, surf: number?, corners: { number } } -- corners: 0-based point indices +export type Poly = { kind: string, surf: number?, corners: { number } } -- 0-based point indices export type Layer = { index: number, name: string?, parent: number?, pivot: { number }, - pts: { number }, -- x, y, z flat + pts: { number }, polys: { Poly }, maps: { Map }, implicit: boolean?, -- the layer before any LAYR @@ -50,7 +42,7 @@ export type Block = { } export type Surface = { name: string, - values: { [string]: number }, -- COLR is separate; DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SMAN, RIND + values: { [string]: number }, color: { number }, side: number, vcol: { name: string, kind: string, intensity: number }?, @@ -62,7 +54,7 @@ export type Model = { tags: { string }, layers: { Layer }, surfaces: { Surface }, - clips: { [number]: string }, -- clip index -> path + clips: { [number]: string }, skipped: { [string]: number }, corners: number, } @@ -79,7 +71,7 @@ local MAP_KINDS: { [string]: string } = { } -- ------------------------------------------------------------------------------------------------ primitives --- S0: a NUL-terminated string padded to an even length +-- S0: NUL-terminated, padded to an even length local function s0(r: Bytes.Reader): string local start = r.pos local s = r:cstring() @@ -89,7 +81,7 @@ local function s0(r: Bytes.Reader): string return s end --- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte) +-- VX: 2 bytes, or 4 bytes after an 0xFF byte local function vx(r: Bytes.Reader): number if r:peekU8() == 0xFF then return r:u32be() - 0xFF000000 @@ -102,7 +94,7 @@ local function id4(r: Bytes.Reader): string return (string.gsub(s, " +$", "")) end --- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body) +-- LWO2 sub-chunks: 4-byte id, 2-byte size, padded to even local function subchunks(buf: buffer, p: number, e: number, f: (string, Bytes.Reader) -> ()) while p + 6 <= e do local id = buffer.readstring(buf, p, 4) @@ -133,7 +125,6 @@ local function readPoints(r: Bytes.Reader, layer: Layer, limit: number): string? return nil end --- POLS (LWO2): returns nil or an error local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: number, budget: { number }): string? local polys = layer.polys local npts = #layer.pts // 3 @@ -281,7 +272,7 @@ end local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true } local function readBlock(r: Bytes.Reader, surf: Surface) - -- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks + -- IMAP / PROC / GRAD / SHDR header: ordinal string, header sub-chunks if r:remaining() < 6 then return end @@ -464,7 +455,6 @@ local function readClip(r: Bytes.Reader, clips: { [number]: string }, refs: { [n end -- ------------------------------------------------------------------------------------------------ the file --- parse(buf, from, limit, opts) -> Model | nil, message function Parse.model(buf: buffer, from: number, limit: number, maxCorners: number): (Model?, string?) local version = buffer.readstring(buf, from + 8, 4) local declared = bit32.byteswap(buffer.readu32(buf, from + 4)) @@ -516,7 +506,7 @@ function Parse.model(buf: buffer, from: number, limit: number, maxCorners: numbe if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then err = readPolys(r, layer, kind, ptBase, budget) else - -- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry + -- PTAG / VMAD refer to the polygon numbering: keep it, skip the geometry local before = #layer.polys err = readPolys(r, layer, kind, ptBase, budget) model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before diff --git a/src/Rosetta/model/lwo/init.luau b/src/Rosetta/model/lwo/init.luau index 810ba5b..d6a2e29 100644 --- a/src/Rosetta/model/lwo/init.luau +++ b/src/Rosetta/model/lwo/init.luau @@ -1,19 +1,7 @@ --!strict --- model/lwo: LightWave objects: LWO2 (LightWave 6+), LWOB (LightWave 5.x) and Modo's LXOB, read only. New code from --- the LWO2 / LWOB specifications, checked against assimp's LWO importer and test models. --- Reads layers (one node each: the pivot as translation, parents by layer index), points and polygons (FACE; PTCH / --- SUBD subdivision cages kept as polygons and flagged extras.lwo.subdivision; CURV, BONE and metaballs skipped and --- counted in meta.source.skipped; 1- and 2-point polygons as points / lines primitives), vertex maps (VMAP / VMAD: --- TXUV -> TEXCOORD_n (one set per map name, flipped to glTF's top-left origin), RGB / RGBA -> COLOR_0 for the map the --- surface's VCOL names and _COLOR_n for the others, Modo NORM -> NORMAL, WGHT / MNVW weight maps -> _WEIGHT_n (LWO has --- no skeleton to bind them to), MORF / SPOT -> morph targets; the map names are in prim.extras.lwo.maps), surfaces --- (one material each: COLR -> baseColor, TRAN -> alpha, GLOS / SPEC -> roughness, LUMI -> emissive, SIDE -> --- doubleSided, every value and texture block in extras.lwo; the first enabled COLR image block -> baseColorTexture, --- with its UV map as texCoord) and clips (textures keep the file name as uri and the full path in extras.lwo.path: --- F.model.loadTextures reads them). LightWave's left-handed space becomes glTF's right-handed y up (z negated, winding --- reversed), as assimp does. Polygons are fan-triangulated unless opts.triangulate = false. --- Not supported: LWO3, envelopes, procedural / gradient textures (kept as entries in extras.lwo.maps), planar / --- cylindrical / spherical projections (no UVs are generated), smoothing (no normals are computed). +-- model/lwo: LightWave objects LWO2 (6+), LWOB (5.x) and Modo's LXOB, read; from the LWO2 / LWOB specs, checked against +-- assimp. Supports: layers, polygons, VMAP / VMAD, surfaces, clips. Left-handed: z negated, winding reversed. Not +-- supported: LWO3, envelopes, procedural / gradient textures, planar / cylindrical / spherical projections, smoothing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,8 +22,8 @@ local Lwo = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - maxVertices: number?, -- refuse more points / polygon corners (default 2^25) + triangulate: boolean?, -- default true + maxVertices: number?, -- default 2^25 } -- ------------------------------------------------------------------------------------------------ constants