--!strict -- ops/MeshOps: editing meshes in the standard Scene type (Types.luau): triangulate (strips, fans, n-gons by fan or ear -- clipping), transform (positions, normals, tangents; winding kept for mirrors), computeNormals (area weighted, or flat), -- computeTangents (per-triangle UV derivatives, Lengyel 2001, Gram-Schmidt + handedness in w), weld (exact or within an -- epsilon), bounds, merge (a whole scene baked into world space, one primitive or one per material), unit and up-axis -- changes, and greedy meshing of voxel grids (VOX: voxelsToPrimitive, meshVoxels). -- Every function takes / returns Primitives and Scenes as decoded by the model formats; inputs may use any accessor type -- (f32, unorm8, snorm16, ...): outputs are f32 attributes and u32 indices. Bad arguments return nil, Err (never throw). -- -- local MeshOps = require("@formats/ops/MeshOps") -- F.ops.mesh in the api (when it lists ops) -- local prim = MeshOps.merge(scene) -- one triangle primitive in world space -- MeshOps.computeNormals(prim) -- MeshOps.meshVoxels(voxScene) -- greedy meshes for every voxel shape local Err = require("@formats/core/Err") local Types = require("@formats/Types") local Greedy = require("@formats/ops/MeshOps/Greedy") local MeshOps = {} type Accessor = Types.Accessor type Primitive = Types.Primitive type Scene = Types.Scene local Scene = Types.Scene local readf32, writef32 = buffer.readf32, buffer.writef32 local readu32, writeu32 = buffer.readu32, buffer.writeu32 -- ------------------------------------------------------------------------------------------------ accessors -- f32(acc) -> the accessor as f32 (the same accessor when it already is), nil for a broken one function MeshOps.f32(acc: Accessor): Accessor? if acc.type == "f32" then return acc end local get = Scene.reader(acc) if not get then return nil end local n, c = acc.count, acc.components local out = buffer.create(n * c * 4) for i = 0, n - 1 do for k = 0, c - 1 do writef32(out, (i * c + k) * 4, get(i, k)) end end local a = Scene.accessor(out, "f32", c, n) a.matrix = acc.matrix return a end -- the index list of a primitive (u32 buffer, count): its indices, or 0 .. n - 1 local function indexBuffer(prim: Primitive): (buffer, number) local ind = prim.indices if ind then if ind.type == "u32" and ind.components == 1 then return ind.data, ind.count end local get = Scene.reader(ind) local out = buffer.create(ind.count * 4) if get then for i = 0, ind.count - 1 do writeu32(out, i * 4, get(i, 0)) end end return out, ind.count end local pos = prim.attributes.POSITION local n = if pos then pos.count else 0 local out = buffer.create(n * 4) for i = 0, n - 1 do writeu32(out, i * 4, i) end return out, n end local function vertexCount(prim: Primitive): number local pos = prim.attributes.POSITION return if pos then pos.count else 0 end local function checkPrim(prim: any): Err.Err? if type(prim) ~= "table" or type(prim.attributes) ~= "table" then return Err.new(Err.ARG, "expected a Primitive") end local pos = prim.attributes.POSITION if not pos or type(pos.data) ~= "buffer" or pos.components < 3 then return Err.new(Err.ARG, "primitive without a POSITION accessor") end local n = pos.count for name, a in prim.attributes do local size = Types.COMPONENT_SIZE[a.type] if not size or type(a.data) ~= "buffer" or buffer.len(a.data) < a.count * a.components * size then return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": bad accessor") end if a.count ~= n then return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": count differs from POSITION") end end if prim.indices then local ind = prim.indices local size = Types.COMPONENT_SIZE[ind.type] if not size or type(ind.data) ~= "buffer" or buffer.len(ind.data) < ind.count * size then return Err.new(Err.ARG, "bad indices accessor") end local get = Scene.reader(ind) if get then for i = 0, ind.count - 1 do if get(i, 0) >= n then return Err.new(Err.ARG, "index out of range") end end end end return nil end MeshOps.check = checkPrim -- ------------------------------------------------------------------------------------------------ triangulate -- ear clipping of one polygon (corner indices into px / py / pz) -> triangles appended to out; fan when it gets stuck local function earclip(poly: { number }, P: (number, number) -> number, out: { number }) local k = #poly if k < 3 then return end if k == 3 then table.insert(out, poly[1]) table.insert(out, poly[2]) table.insert(out, poly[3]) return end -- Newell normal -> the projection plane (drop the dominant axis) local nx, ny, nz = 0, 0, 0 for a = 1, k do local i, j = poly[a], poly[a % k + 1] local xi, yi, zi = P(i, 0), P(i, 1), P(i, 2) local xj, yj, zj = P(j, 0), P(j, 1), P(j, 2) nx += (yi - yj) * (zi + zj) ny += (zi - zj) * (xi + xj) nz += (xi - xj) * (yi + yj) end local ax, ay, az = math.abs(nx), math.abs(ny), math.abs(nz) local cu, cv, sign = 0, 1, nz if ax >= ay and ax >= az then cu, cv, sign = 1, 2, nx elseif ay >= az then cu, cv, sign = 2, 0, ny end local function uv(i: number): (number, number) return P(i, cu), P(i, cv) end local s = if sign < 0 then -1 else 1 local ring = table.clone(poly) local guard = 0 while #ring > 3 and guard < k * k do guard += 1 local n = #ring local clipped = false for a = 1, n do local ia, ib, ic = ring[(a - 2) % n + 1], ring[a], ring[a % n + 1] local ax2, ay2 = uv(ia) local bx, by = uv(ib) local cx, cy = uv(ic) local cross = ((bx - ax2) * (cy - ay2) - (by - ay2) * (cx - ax2)) * s if cross > 0 then local inside = false for q = 1, n do local iq = ring[q] if iq ~= ia and iq ~= ib and iq ~= ic then local qx, qy = uv(iq) local d1 = ((bx - ax2) * (qy - ay2) - (by - ay2) * (qx - ax2)) * s local d2 = ((cx - bx) * (qy - by) - (cy - by) * (qx - bx)) * s local d3 = ((ax2 - cx) * (qy - cy) - (ay2 - cy) * (qx - cx)) * s if d1 >= 0 and d2 >= 0 and d3 >= 0 then inside = true break end end end if not inside then table.insert(out, ia) table.insert(out, ib) table.insert(out, ic) table.remove(ring, a) clipped = true break end end end if not clipped then break end end -- whatever is left (3 corners, or a degenerate / self-intersecting rest): a fan for a = 2, #ring - 1 do table.insert(out, ring[1]) table.insert(out, ring[a]) table.insert(out, ring[a + 1]) end end local function u32(list: { number }): Accessor local n = #list local b = buffer.create(n * 4) for i = 1, n do writeu32(b, (i - 1) * 4, list[i]) end return Scene.accessor(b, "u32", 1, n) end -- triangulate(prim, opts?) -> a new triangle Primitive (the same attributes) | nil, Err. opts.method: "earclip" -- (default; handles concave n-gons) or "fan". Strips and fans are unrolled (strip winding alternates as glTF says). -- Lines and points come back unchanged. function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Primitive?, Err.Err?) local err = checkPrim(prim) if err then return nil, err end local mode = prim.mode or "triangles" if mode == "lines" or mode == "points" or mode == "line_strip" or mode == "line_loop" then return prim, nil end local method = opts and opts.method or "earclip" local ib, n = indexBuffer(prim) local out: { number } = {} if mode == "triangles" then local m = n - n % 3 for i = 0, m - 1 do out[i + 1] = readu32(ib, i * 4) end elseif mode == "triangle_strip" then for i = 0, n - 3 do local a, b, c = readu32(ib, i * 4), readu32(ib, i * 4 + 4), readu32(ib, i * 4 + 8) if i % 2 == 1 then a, b = b, a end if a ~= b and b ~= c and a ~= c then table.insert(out, a) table.insert(out, b) table.insert(out, c) end end elseif mode == "triangle_fan" then for i = 1, n - 2 do table.insert(out, readu32(ib, 0)) table.insert(out, readu32(ib, i * 4)) table.insert(out, readu32(ib, i * 4 + 4)) end elseif mode == "polygons" then local faces = prim.faces if not faces then return nil, Err.new(Err.ARG, "polygons primitive without faces") end local getf = Scene.reader(faces) if not getf then return nil, Err.new(Err.ARG, "bad faces accessor") end local pos = MeshOps.f32(prim.attributes.POSITION) :: Accessor local pd = pos.data local P = function(i: number, c: number): number return readf32(pd, (i * 3 + c) * 4) end local at = 0 for f = 0, faces.count - 1 do local k = getf(f, 0) if at + k > n then return nil, Err.new(Err.ARG, "faces run past the indices") end if k >= 3 then if method == "fan" or k == 3 then for a = 1, k - 2 do table.insert(out, readu32(ib, at * 4)) table.insert(out, readu32(ib, (at + a) * 4)) table.insert(out, readu32(ib, (at + a + 1) * 4)) end else local poly = table.create(k) for a = 0, k - 1 do poly[a + 1] = readu32(ib, (at + a) * 4) end earclip(poly, P, out) end end at += k end else return nil, Err.new(Err.ARG, "unknown mode " .. tostring(mode)) end return { attributes = prim.attributes, indices = u32(out), mode = "triangles", material = prim.material, targets = prim.targets, extras = prim.extras, }, nil end -- ------------------------------------------------------------------------------------------------ transform local function det3(m: { number }): number return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) end -- the inverse transpose of m's 3 x 3 part (column-major 9), for normals local function normalMatrix(m: { number }): { number } local a, b, c = m[1], m[5], m[9] local d, e, f = m[2], m[6], m[10] local g, h, i = m[3], m[7], m[11] local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) if det == 0 then det = 1 end local k = 1 / det -- cofactor matrix / det (= inverse transpose), column-major return { (e * i - f * h) * k, -(b * i - c * h) * k, (b * f - c * e) * k, -(d * i - f * g) * k, (a * i - c * g) * k, -(a * f - c * d) * k, (d * h - e * g) * k, -(a * h - b * g) * k, (a * e - b * d) * k, } end -- transform(prim, matrix) -> prim (changed in place: POSITION, NORMAL, TANGENT become f32; morph target deltas too). -- A mirroring matrix (negative determinant) also reverses the triangle winding so faces stay front-facing. function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err?) local err = checkPrim(prim) if err then return nil, err end if type(m) ~= "table" or #m ~= 16 then return nil, Err.new(Err.ARG, "expected a column-major 4x4 matrix (16 numbers)") end local nm = normalMatrix(m) local function points(acc: Accessor?, w: number): Accessor? if not acc then return nil end local a = MeshOps.f32(acc) :: Accessor if a == acc then a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) end local d, c = a.data, a.components for i = 0, a.count - 1 do local o = i * c * 4 local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) writef32(d, o, m[1] * x + m[5] * y + m[9] * z + m[13] * w) writef32(d, o + 4, m[2] * x + m[6] * y + m[10] * z + m[14] * w) writef32(d, o + 8, m[3] * x + m[7] * y + m[11] * z + m[15] * w) end return a end local function dirs(acc: Accessor?, mat: { number }, normalize: boolean, flipW: boolean): Accessor? if not acc then return nil end local a = MeshOps.f32(acc) :: Accessor if a == acc then a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) end local d, c = a.data, a.components for i = 0, a.count - 1 do local o = i * c * 4 local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) local nx = mat[1] * x + mat[4] * y + mat[7] * z local ny = mat[2] * x + mat[5] * y + mat[8] * z local nz = mat[3] * x + mat[6] * y + mat[9] * z if normalize then local l = math.sqrt(nx * nx + ny * ny + nz * nz) if l > 0 then nx, ny, nz = nx / l, ny / l, nz / l end end writef32(d, o, nx) writef32(d, o + 4, ny) writef32(d, o + 8, nz) if flipW and c >= 4 then writef32(d, o + 12, -readf32(d, o + 12)) end end return a end local mirror = det3(m) < 0 local m3 = { m[1], m[2], m[3], m[5], m[6], m[7], m[9], m[10], m[11] } local attrs = prim.attributes attrs.POSITION = points(attrs.POSITION, 1) :: Accessor attrs.NORMAL = dirs(attrs.NORMAL, nm, true, false) attrs.TANGENT = dirs(attrs.TANGENT, m3, true, mirror) if prim.targets then for _, t in prim.targets do t.POSITION = points(t.POSITION, 0) t.NORMAL = dirs(t.NORMAL, nm, false, false) t.TANGENT = dirs(t.TANGENT, m3, false, false) end end if mirror and (prim.mode == "triangles" or prim.mode == nil) then local ib, n = indexBuffer(prim) local nb = buffer.create(n * 4) buffer.copy(nb, 0, ib, 0, n * 4) for t = 0, n // 3 - 1 do local o = t * 12 local b = readu32(nb, o + 4) writeu32(nb, o + 4, readu32(nb, o + 8)) writeu32(nb, o + 8, b) end prim.indices = Scene.accessor(nb, "u32", 1, n) elseif mirror and prim.mode == "polygons" and prim.faces then local ib, n = indexBuffer(prim) local nb = buffer.create(n * 4) local getf = Scene.reader(prim.faces) local at = 0 if getf then for f = 0, prim.faces.count - 1 do local k = getf(f, 0) for a = 0, k - 1 do if at + a < n then writeu32(nb, (at + a) * 4, readu32(ib, (at + k - 1 - a) * 4)) end end at += k end end prim.indices = Scene.accessor(nb, "u32", 1, n) end return prim, nil end -- ------------------------------------------------------------------------------------------------ normals / tangents -- computeNormals(prim, opts?) -> prim with NORMAL (f32, area-weighted average of the triangle normals of each vertex) | -- nil, Err. opts.flat = true: split every triangle's corners first (unwelded, one face normal per corner). Non-triangle -- modes are triangulated first (the returned primitive is then a new one). function MeshOps.computeNormals(prim: Primitive, opts: { flat: boolean? }?): (Primitive?, Err.Err?) local p = prim if (prim.mode or "triangles") ~= "triangles" then local t, err = MeshOps.triangulate(prim) if not t then return nil, err end p = t else local err = checkPrim(prim) if err then return nil, err end end if p.mode ~= "triangles" then return p, nil -- lines / points: nothing to do end if opts and opts.flat then p = MeshOps.unweld(p) end local pos = MeshOps.f32(p.attributes.POSITION) :: Accessor local pd = pos.data local nv = pos.count local ib, n = indexBuffer(p) local acc = table.create(nv * 3, 0) for t = 0, n // 3 - 1 do local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) local e1x, e1y, e1z = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az local e2x, e2y, e2z = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az -- the cross product is twice the area times the unit normal: area weighting for free local nx, ny, nz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x for _, v in { a, b, c } do acc[v * 3 + 1] += nx acc[v * 3 + 2] += ny acc[v * 3 + 3] += nz end end local out = buffer.create(nv * 12) for v = 0, nv - 1 do local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] local l = math.sqrt(x * x + y * y + z * z) if l > 0 then x, y, z = x / l, y / l, z / l else x, y, z = 0, 0, 1 end writef32(out, v * 12, x) writef32(out, v * 12 + 4, y) writef32(out, v * 12 + 8, z) end p.attributes.NORMAL = Scene.accessor(out, "f32", 3, nv) return p, nil end -- computeTangents(prim, opts?) -> prim with TANGENT (f32 vec4: xyz orthogonal to the normal, w = +-1 handedness) | -- nil, Err. Needs triangles, NORMAL (computed when missing) and TEXCOORD_. function MeshOps.computeTangents(prim: Primitive, opts: { texCoord: number? }?): (Primitive?, Err.Err?) local p = prim if not p.attributes.NORMAL or (p.mode or "triangles") ~= "triangles" then local q, err = MeshOps.computeNormals(prim) if not q then return nil, err end p = q end local err = checkPrim(p) if err then return nil, err end local uvAcc = p.attributes["TEXCOORD_" .. tostring(opts and opts.texCoord or 0)] if not uvAcc then return nil, Err.new(Err.ARG, "computeTangents needs texture coordinates") end local pos = MeshOps.f32(p.attributes.POSITION) :: Accessor local nrm = MeshOps.f32(p.attributes.NORMAL :: Accessor) :: Accessor local uv = MeshOps.f32(uvAcc) :: Accessor local pd, nd, ud = pos.data, nrm.data, uv.data local nv = pos.count local ib, n = indexBuffer(p) local tan = table.create(nv * 3, 0) local bit = table.create(nv * 3, 0) for t = 0, n // 3 - 1 do local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) local x1, y1, z1 = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az local x2, y2, z2 = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az local us, vs = readf32(ud, a * 8), readf32(ud, a * 8 + 4) local s1, t1 = readf32(ud, b * 8) - us, readf32(ud, b * 8 + 4) - vs local s2, t2 = readf32(ud, c * 8) - us, readf32(ud, c * 8 + 4) - vs local den = s1 * t2 - s2 * t1 if den ~= 0 then local r = 1 / den local tx, ty, tz = (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r local bx, by, bz = (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r for _, v in { a, b, c } do tan[v * 3 + 1] += tx tan[v * 3 + 2] += ty tan[v * 3 + 3] += tz bit[v * 3 + 1] += bx bit[v * 3 + 2] += by bit[v * 3 + 3] += bz end end end local out = buffer.create(nv * 16) for v = 0, nv - 1 do local nx, ny, nz = readf32(nd, v * 12), readf32(nd, v * 12 + 4), readf32(nd, v * 12 + 8) local tx, ty, tz = tan[v * 3 + 1], tan[v * 3 + 2], tan[v * 3 + 3] local dot = nx * tx + ny * ty + nz * tz tx, ty, tz = tx - nx * dot, ty - ny * dot, tz - nz * dot local l = math.sqrt(tx * tx + ty * ty + tz * tz) if l > 1e-20 then tx, ty, tz = tx / l, ty / l, tz / l else -- no UV gradient: any unit vector orthogonal to the normal if math.abs(nx) < 0.9 then tx, ty, tz = 0, nz, -ny else tx, ty, tz = -nz, 0, nx end local l2 = math.sqrt(tx * tx + ty * ty + tz * tz) if l2 > 0 then tx, ty, tz = tx / l2, ty / l2, tz / l2 end end -- handedness: (n x t) . b local cx, cy, cz = ny * tz - nz * ty, nz * tx - nx * tz, nx * ty - ny * tx local w = if cx * bit[v * 3 + 1] + cy * bit[v * 3 + 2] + cz * bit[v * 3 + 3] < 0 then -1 else 1 writef32(out, v * 16, tx) writef32(out, v * 16 + 4, ty) writef32(out, v * 16 + 8, tz) writef32(out, v * 16 + 12, w) end p.attributes.TANGENT = Scene.accessor(out, "f32", 4, nv) return p, nil end -- ------------------------------------------------------------------------------------------------ weld / unweld local function gather(acc: Accessor, ib: buffer, n: number): Accessor local size = (Types.COMPONENT_SIZE[acc.type] or 4) * acc.components local out = buffer.create(n * size) for i = 0, n - 1 do buffer.copy(out, i * size, acc.data, readu32(ib, i * 4) * size, size) end local a = Scene.accessor(out, acc.type, acc.components, n) a.matrix = acc.matrix return a end -- unweld(prim) -> a new primitive with one vertex per index (no indices; triangle soups, flat normals) function MeshOps.unweld(prim: Primitive): Primitive local ib, n = indexBuffer(prim) local attrs = {} for name, a in prim.attributes do attrs[name] = gather(a, ib, n) end local targets = nil if prim.targets then targets = {} for k, t in prim.targets do local tt = {} for name, a in t do tt[name] = gather(a, ib, n) end targets[k] = tt end end return { attributes = attrs, indices = nil, mode = prim.mode, faces = prim.faces, material = prim.material, targets = targets, extras = prim.extras } end -- weld(prim, opts?) -> a new indexed primitive where vertices with identical attributes are one | nil, Err. -- opts.epsilon > 0: positions within epsilon (on a grid of that size) merge too, keeping the first vertex's other -- attributes only when they are equal (opts.positionsOnly = true merges by position alone, keeping the first vertex). -- Morph targets are kept per merged vertex (the first one's). function MeshOps.weld(prim: Primitive, opts: { epsilon: number?, positionsOnly: boolean? }?): (Primitive?, Err.Err?) local err = checkPrim(prim) if err then return nil, err end local eps = opts and opts.epsilon or 0 local posOnly = opts and opts.positionsOnly or false local names = {} for name in prim.attributes do if not (posOnly and name ~= "POSITION") and not (eps > 0 and name == "POSITION") then table.insert(names, name) end end table.sort(names) local nv = vertexCount(prim) local pos = MeshOps.f32(prim.attributes.POSITION) :: Accessor local pd = pos.data local inv = if eps > 0 then 1 / eps else 0 local remap = buffer.create(nv * 4) local keep: { number } = {} local seen: { [string]: number } = {} local parts = table.create(#names + 1) for v = 0, nv - 1 do local np = 0 if eps > 0 then np += 1 parts[np] = string.format("%d,%d,%d", math.floor(readf32(pd, v * 12) * inv + 0.5), math.floor(readf32(pd, v * 12 + 4) * inv + 0.5), math.floor(readf32(pd, v * 12 + 8) * inv + 0.5)) end for _, name in names do local a = prim.attributes[name] local size = (Types.COMPONENT_SIZE[a.type] or 4) * a.components np += 1 parts[np] = buffer.readstring(a.data, v * size, size) end local key = table.concat(parts, "\1", 1, np) local k = seen[key] if k == nil then k = #keep seen[key] = k table.insert(keep, v) end writeu32(remap, v * 4, k) end local kb = buffer.create(#keep * 4) for i, v in keep do writeu32(kb, (i - 1) * 4, v) end local attrs = {} for name, a in prim.attributes do attrs[name] = gather(a, kb, #keep) end local targets = nil if prim.targets then targets = {} for k, t in prim.targets do local tt = {} for name, a in t do tt[name] = gather(a, kb, #keep) end targets[k] = tt end end local ib, n = indexBuffer(prim) local out = buffer.create(n * 4) for i = 0, n - 1 do writeu32(out, i * 4, readu32(remap, readu32(ib, i * 4) * 4)) end return { attributes = attrs, indices = Scene.accessor(out, "u32", 1, n), mode = prim.mode, faces = prim.faces, material = prim.material, targets = targets, extras = prim.extras, }, nil end -- ------------------------------------------------------------------------------------------------ bounds -- bounds(primitive | scene) -> min { x, y, z }, max { x, y, z } (a scene: in world space, every mesh primitive and -- voxel shape cell corners excluded) | nil, nil when there are no positions function MeshOps.bounds(x: any): ({ number }?, { number }?) local lo = { math.huge, math.huge, math.huge } local hi = { -math.huge, -math.huge, -math.huge } local function add(prim: Primitive, m: { number }?) local pos = prim.attributes and prim.attributes.POSITION if not pos then return end local get = Scene.reader(pos) if not get then return end for i = 0, pos.count - 1 do local px, py, pz = get(i, 0), get(i, 1), get(i, 2) if m and m ~= Scene.IDENTITY then px, py, pz = m[1] * px + m[5] * py + m[9] * pz + m[13], m[2] * px + m[6] * py + m[10] * pz + m[14], m[3] * px + m[7] * py + m[11] * pz + m[15] end if px < lo[1] then lo[1] = px end if py < lo[2] then lo[2] = py end if pz < lo[3] then lo[3] = pz end if px > hi[1] then hi[1] = px end if py > hi[2] then hi[2] = py end if pz > hi[3] then hi[3] = pz end end end if type(x) ~= "table" then return nil, nil end if x.kind == "scene" then for _, pl in Scene.flatten(x) do add(pl.primitive, pl.matrix) end else add(x, nil) end if lo[1] > hi[1] then return nil, nil end return lo, hi end -- ------------------------------------------------------------------------------------------------ merge -- the value of an attribute nobody had (COLOR_n white, WEIGHTS_0 { 1, 0, 0, 0 }, the rest zero) local function defaultFor(name: string, k: number): number if string.sub(name, 1, 6) == "COLOR_" then return 1 end if string.sub(name, 1, 8) == "WEIGHTS_" then return if k == 0 then 1 else 0 end return 0 end -- merge(scene | { Primitive }, opts?) -> one triangle Primitive with every mesh primitive baked into world space | -- { Primitive } with opts.byMaterial (one per material, in material order) | nil, Err. Attributes present in any input -- appear in the output (f32; missing ones filled with defaults: white colours, zeros); custom "_x" attributes too. -- Lines and points are skipped (opts.keepPoints = true keeps a point-only input as points). Skins and morph targets -- are not applied (the rest pose). function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string? }?): (any, Err.Err?) local placed: { Types.Placed } = {} if type(input) ~= "table" then return nil, Err.new(Err.ARG, "merge: expected a Scene or a list of Primitives") end if input.kind == "scene" then placed = Scene.flatten(input) else for i, p in input do placed[i] = { primitive = p, matrix = Scene.IDENTITY, node = 0, mesh = 0 } end end -- triangulate + bake each local groups: { [number]: { Primitive } } = {} local order: { number } = {} local allPoints = #placed > 0 for _, pl in placed do if pl.primitive.mode ~= "points" then allPoints = false end end for _, pl in placed do local p = pl.primitive local mode = p.mode or "triangles" if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" and (mode ~= "points" or allPoints) then local t, err = if mode == "points" then p else MeshOps.triangulate(p, opts) if not t then return nil, err end -- a private copy of the attributes to bake local copy: Primitive = { attributes = {}, indices = t.indices, mode = t.mode, material = t.material } for name, a in t.attributes do copy.attributes[name] = MeshOps.f32(a) end if pl.matrix ~= Scene.IDENTITY then local ok, terr = MeshOps.transform(copy, pl.matrix) if not ok then return nil, terr end end local key = if opts and opts.byMaterial then (copy.material or 0) else 0 if not groups[key] then groups[key] = {} table.insert(order, key) end table.insert(groups[key], copy) end end table.sort(order) local function concat(list: { Primitive }, material: number?): Primitive local names: { [string]: number } = {} local nv, ni = 0, 0 local points = false for _, p in list do for name, a in p.attributes do names[name] = math.max(names[name] or 0, a.components) end nv += vertexCount(p) local _, n = indexBuffer(p) ni += n points = points or p.mode == "points" end local attrs: { [string]: Accessor } = {} for name, comps in names do local out = buffer.create(nv * comps * 4) local base = 0 for _, p in list do local a = p.attributes[name] local cnt = vertexCount(p) for v = 0, cnt - 1 do for k = 0, comps - 1 do local value = if a and k < a.components then readf32(a.data, (v * a.components + k) * 4) else defaultFor(name, k) writef32(out, ((base + v) * comps + k) * 4, value) end end base += cnt end attrs[name] = Scene.accessor(out, "f32", comps, nv) end local idx = buffer.create(ni * 4) local base, at = 0, 0 for _, p in list do local ib, n = indexBuffer(p) for i = 0, n - 1 do writeu32(idx, (at + i) * 4, readu32(ib, i * 4) + base) end at += n base += vertexCount(p) end return { attributes = attrs, indices = if points then nil else Scene.accessor(idx, "u32", 1, ni), mode = if points then "points" else "triangles", material = material, } end if opts and opts.byMaterial then local out = {} for _, key in order do table.insert(out, concat(groups[key], if key == 0 then nil else key)) end return out, nil end local all = groups[0] or {} local first = all[1] return concat(all, first and first.material), nil end -- ------------------------------------------------------------------------------------------------ units / up axis local function scaleAccessor(acc: Accessor?, f: number): Accessor? if not acc then return nil end local a = MeshOps.f32(acc) :: Accessor if a == acc then a = Scene.accessor(buffer.create(acc.count * acc.components * 4), "f32", acc.components, acc.count) buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) end for i = 0, a.count * a.components - 1 do writef32(a.data, i * 4, readf32(a.data, i * 4) * f) end return a end -- scale(scene, factor) -> scene, scaled in place: mesh positions and morph target deltas, node translations (TRS and -- matrices), translation animations, inverse bind matrices, camera clip planes, light ranges; meta.unit is divided by -- factor (the same physical size in smaller units). function MeshOps.scale(scene: Scene, f: number): (Scene?, Err.Err?) if type(scene) ~= "table" or scene.kind ~= "scene" or type(f) ~= "number" or f ~= f or f == 0 then return nil, Err.new(Err.ARG, "scale: expected a Scene and a non-zero factor") end local done: { [any]: boolean } = {} for _, mesh in scene.meshes do for _, p in mesh.primitives do if not done[p] then done[p] = true p.attributes.POSITION = scaleAccessor(p.attributes.POSITION, f) :: Accessor for _, t in p.targets or {} do t.POSITION = scaleAccessor(t.POSITION, f) end end end end for _, n in scene.nodes do if n.translation then n.translation = { n.translation[1] * f, n.translation[2] * f, n.translation[3] * f } end if n.matrix then local m = table.clone(n.matrix) m[13], m[14], m[15] = m[13] * f, m[14] * f, m[15] * f n.matrix = m end end for _, a in scene.animations do for _, c in a.channels do if c.path == "translation" and not done[c.output] then done[c.output] = true c.output = scaleAccessor(c.output, f) :: Accessor end end end for _, s in scene.skins do local ibm = s.inverseBindMatrices if ibm and not done[ibm] then local a = MeshOps.f32(ibm) :: Accessor if a == ibm then a = Scene.accessor(buffer.create(ibm.count * 64), "f32", 16, ibm.count) buffer.copy(a.data, 0, ibm.data, 0, ibm.count * 64) end for i = 0, a.count - 1 do for k = 12, 14 do writef32(a.data, (i * 16 + k) * 4, readf32(a.data, (i * 16 + k) * 4) * f) end end a.matrix = true s.inverseBindMatrices = a done[a] = true end end for _, c in scene.cameras do if c.type == "perspective" then c.znear *= math.abs(f) if c.zfar then c.zfar *= math.abs(f) end else c.znear *= math.abs(f) if c.zfar then c.zfar *= math.abs(f) end c.xmag = c.xmag and c.xmag * math.abs(f) c.ymag = c.ymag and c.ymag * math.abs(f) end end for _, l in scene.lights do if l.range then l.range *= math.abs(f) end end scene.meta.unit = (scene.meta.unit or 1) / f return scene, nil end -- setUnit(scene, metresPerUnit) -> scene scaled so that one unit is metresPerUnit (from meta.unit, default 1 m) function MeshOps.setUnit(scene: Scene, metresPerUnit: number): (Scene?, Err.Err?) if type(scene) ~= "table" or type(metresPerUnit) ~= "number" or metresPerUnit <= 0 then return nil, Err.new(Err.ARG, "setUnit: expected a Scene and a positive unit") end local from = scene.meta.unit or 1 return MeshOps.scale(scene, from / metresPerUnit) end -- setUp(scene, "y" | "z") -> scene with a new root node rotating the old roots from meta.up (default "y") to up. -- Nothing is baked: the vertex data stays as it is (MeshOps.merge bakes it). function MeshOps.setUp(scene: Scene, up: string): (Scene?, Err.Err?) if type(scene) ~= "table" or scene.kind ~= "scene" or (up ~= "y" and up ~= "z") then return nil, Err.new(Err.ARG, "setUp: expected a Scene and \"y\" or \"z\"") end local from = scene.meta.up or "y" if from == up then return scene, nil end local h = math.sqrt(0.5) -- z-up -> y-up: -90 degrees about x; y-up -> z-up: +90 degrees about x local q = if up == "y" then { -h, 0, 0, h } else { h, 0, 0, h } table.insert(scene.nodes, { name = "up_" .. up, children = scene.roots, rotation = q }) scene.roots = { #scene.nodes } scene.meta.up = up :: any return scene, nil end -- ------------------------------------------------------------------------------------------------ voxels local function linear(c: number): number local s = c / 255 return if s <= 0.04045 then s / 12.92 else ((s + 0.055) / 1.055) ^ 2.4 end -- voxelsToPrimitive(voxels, opts?) -> a triangle Primitive of the grid's visible faces, greedily merged (POSITION, -- NORMAL f32; COLOR_0 from the palette; u32 indices) | nil, Err. -- opts.pivot: "center" (default: MagicaVoxel's placement, cell x spans x - floor(sx / 2) ..) or "corner" (0 .. sx); -- opts.scale: units per voxel (default 1); opts.colors: "linear" (default: f32 linear RGBA, glTF's COLOR_0 meaning) or -- "srgb" (unorm8, the palette bytes as they are); opts.indexAttribute = true adds "_PALETTE_INDEX" (u8 per vertex). function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Primitive?, Err.Err?) if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then return nil, Err.new(Err.ARG, "expected a Voxels grid") end local sx, sy, sz = v.size[1], v.size[2], v.size[3] if type(sx) ~= "number" or type(sy) ~= "number" or type(sz) ~= "number" or sx < 1 or sy < 1 or sz < 1 or buffer.len(v.data) < sx * sy * sz then return nil, Err.new(Err.ARG, "bad voxel grid size") end local pivot = opts and opts.pivot or "center" local scale = opts and opts.scale or 1 local ox, oy, oz = 0, 0, 0 if pivot == "center" then ox, oy, oz = -(sx // 2), -(sy // 2), -(sz // 2) end local g = Greedy.run(v.data, sx, sy, sz, ox, oy, oz, scale) local nv = g.vertices local function trim(b: buffer, size: number): buffer local out = buffer.create(size) buffer.copy(out, 0, b, 0, size) return out end local attrs: { [string]: Accessor } = { POSITION = Scene.accessor(trim(g.positions, nv * 12), "f32", 3, nv), NORMAL = Scene.accessor(trim(g.normals, nv * 12), "f32", 3, nv), } local pal = v.palette or {} local srgb = opts and opts.colors == "srgb" local col = buffer.create(nv * (if srgb then 4 else 16)) local lut: { { number } } = {} for i = 1, 255 do local c = pal[i] or { 255, 255, 255, 255 } if srgb then lut[i] = { c[1] or 0, c[2] or 0, c[3] or 0, c[4] or 255 } else lut[i] = { linear(c[1] or 0), linear(c[2] or 0), linear(c[3] or 0), (c[4] or 255) / 255 } end end for k = 0, nv - 1 do local c = lut[buffer.readu8(g.index, k)] or lut[1] if srgb then for j = 0, 3 do buffer.writeu8(col, k * 4 + j, c[j + 1]) end else for j = 0, 3 do writef32(col, k * 16 + j * 4, c[j + 1]) end end end attrs.COLOR_0 = Scene.accessor(col, if srgb then "unorm8" else "f32", 4, nv) if opts and opts.indexAttribute then attrs._PALETTE_INDEX = Scene.accessor(trim(g.index, nv), "u8", 1, nv) end return { attributes = attrs, indices = Scene.accessor(trim(g.indices, g.quads * 24), "u32", 1, g.quads * 6), mode = "triangles" }, nil end -- meshVoxels(scene, opts?) -> scene with a mesh for every voxel grid (scene.voxels) and node.mesh set on every node -- that shows one (node.voxels); one shared material (white, rough, not metallic: the colours are per vertex). Options as -- voxelsToPrimitive. Grids that already have a mesh made by this function are meshed again. function MeshOps.meshVoxels(scene: Scene, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Scene?, Err.Err?) if type(scene) ~= "table" or scene.kind ~= "scene" then return nil, Err.new(Err.ARG, "expected a Scene") end local grids = scene.voxels or {} local mat = 0 local meshOf: { [number]: number } = {} for i, v in grids do local prim, err = MeshOps.voxelsToPrimitive(v, opts) if not prim then return nil, err end if mat == 0 then local m = Scene.material("voxels") m.metallic = 0 table.insert(scene.materials, m) mat = #scene.materials end prim.material = mat table.insert(scene.meshes, { name = v.name or ("voxels " .. i), primitives = { prim } }) meshOf[i] = #scene.meshes end for _, n in scene.nodes do if n.voxels and meshOf[n.voxels] then n.mesh = meshOf[n.voxels] end end return scene, nil end return MeshOps