diff --git a/compat/luajit.lua b/compat/luajit.lua index e56268a..c5b1813 100644 --- a/compat/luajit.lua +++ b/compat/luajit.lua @@ -410,7 +410,7 @@ function M.__iter(t, s, c) local mt = getmetatable(t) if rawtype(mt) == "table" and mt.__iter then return mt.__iter(t) end local n = #t - if n > 0 and next(t, n) == nil then return ipairs(t) end + if n > 0 and t[0] == nil and next(t, n) == nil then return ipairs(t) end -- LuaJIT keeps t[0] in the array part return next, t, nil end diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 245d234..9209cab 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -19,6 +19,12 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | +| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | +| model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | +| model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | +| model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | +| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | +| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | | font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` | @@ -46,6 +52,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build Codecs (layer 1, shared by formats; not loadable on their own): +- codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs - codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written - codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec - codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts @@ -54,6 +61,7 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and +- codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks - codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette - codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine - codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 96d6c3b..198c4de 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -20,6 +20,9 @@ | `src/Formats/image/jpeg/` (Decode, Scan, Color), `src/Formats/codecs/Dct/` (inverse DCTs) | jpeg-luau 1.0 (same author); the IDCTs, upsampling, colour conversion and IDCT-size choice are Luau translations of libjpeg / libjpeg-turbo (jidctint.c, jidctred.c, jdsample.c, jdcolor.c, jdmaster.c) | IJG licence + libjpeg-turbo BSD: [libjpeg-turbo-LICENSE.md](libjpeg-turbo-LICENSE.md), [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. | | `src/Formats/image/jpeg/Arith.luau`, `src/Formats/image/jpeg/Encode.luau`, `src/Formats/codecs/Dct/` (forward DCT) | new; Luau translations of libjpeg-turbo 3.2 jdarith.c / jaricom.c (Guido Vollbeding), jccolor.c, jcsample.c, jccoefct.c, jfdctint.c, jcdctmgr.c, jchuff.c, jcphuff.c, jcparam.c | as above | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | +| `tests/fixtures/vox/{chr_knight,chr_sword,deer,maze}.vox`, `tests/fixtures/vox/MagicaVoxel-file-format-vox*.txt` (the format spec) | ephtracy/voxel-model (MagicaVoxel sample models) | MIT: [voxel-model-LICENSE.txt](voxel-model-LICENSE.txt) | +| `tests/fixtures/vox/ogt_*.vox` | jpaver/opengametools `demo/vox/` (files saved by MagicaVoxel 0.99.x) | MIT: [opengametools-LICENSE.txt](opengametools-LICENSE.txt) | +| `tests/fixtures/gltf/` | KhronosGroup/glTF-Sample-Assets `Models/` (one LICENSE.md per model folder; `UnicodeTest` is `Unicode❤♻Test` renamed) | CC-BY-4.0 or CC0-1.0 per model, see each folder's LICENSE.md | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/opengametools-LICENSE.txt b/licenses/opengametools-LICENSE.txt new file mode 100644 index 0000000..eadf720 --- /dev/null +++ b/licenses/opengametools-LICENSE.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2019 Justin Paver + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/licenses/voxel-model-LICENSE.txt b/licenses/voxel-model-LICENSE.txt new file mode 100644 index 0000000..d6af977 --- /dev/null +++ b/licenses/voxel-model-LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ephtracy + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index bde3cf6..7a15352 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -182,6 +182,78 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "gltf", + category = "model", + path = "model/gltf", + extensions = { "gltf", "glb" }, + mime = { "model/gltf+json", "model/gltf-binary" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Base64" }, + caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, + load = function() + return require("@formats/model/gltf") + end, + }, + { + name = "obj", + category = "model", + path = "model/obj", + extensions = { "obj" }, + mime = { "model/obj" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true }, + load = function() + return require("@formats/model/obj") + end, + }, + { + name = "off", + category = "model", + path = "model/off", + extensions = { "off" }, + mime = { "model/off", "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false }, + load = function() + return require("@formats/model/off") + end, + }, + { + name = "ply", + category = "model", + path = "model/ply", + extensions = { "ply" }, + mime = { "model/ply", "application/ply" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true }, + load = function() + return require("@formats/model/ply") + end, + }, + { + name = "stl", + category = "model", + path = "model/stl", + extensions = { "stl" }, + mime = { "model/stl", "application/sla" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false }, + load = function() + return require("@formats/model/stl") + end, + }, + { + name = "vox", + category = "model", + path = "model/vox", + extensions = { "vox" }, + mime = { "model/x-vox" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true }, + load = function() + return require("@formats/model/vox") + end, + }, { name = "bmfont", category = "font", diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 1d8db5c..0678bfd 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -197,21 +197,66 @@ export type VideoDecoder = { } -- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped) +-- Indices are 1-based everywhere (node, mesh, material, texture, ...). Accessor data is tightly packed (no stride, no +-- padding, sparse accessors already applied). unorm / snorm types are glTF's normalized integers (value / 255, +-- max(value / 127, -1), ...). Positions are in scene units (meta.unit = metres per unit when known), meta.up is the +-- source's up axis ("y" for glTF / OBJ, "z" for STL / VOX / most CAD) - no format rotates the data on load. +-- +-- Textures keep the encoded image (texture.data + texture.mime, PNG / JPEG / ... bytes) or an external reference +-- (texture.uri): a model format never decodes images (a format does not require another format). Decode them at the +-- api layer, lazily: `F.model.loadTextures(scene)` sets texture.image = F.image.load(texture.data) for each texture +-- whose image format is available (or do it yourself when needed). Writers embed texture.data when set, else write +-- texture.uri; a texture with only a decoded image must be encoded first (texture.data = F.save(texture.image, nil, +-- { format = "png" }), texture.mime = "image/png"), which `F.model.save` does for you. +-- +-- Other files (OBJ's .mtl, glTF's .bin / images): decoders ask `opts.resolve(uri) -> buffer | string | nil`, or look +-- up `opts.files[uri]` (a table of buffers / strings); the api sets opts.resolve to read files next to a path it +-- loaded. Encoders that write more than one file return the main file and put the others into `opts.files` (when the +-- caller passes a table there; the api does, and writes them next to the destination), named after `opts.name`. export type Accessor = { - data: buffer, -- tightly packed - type: "f32" | "u8" | "u16" | "u32" | "i8" | "i16" | "unorm8" | "unorm16" | "snorm8" | "snorm16", - components: number, -- 1 (SCALAR) .. 4 (VEC4), 16 (MAT4) + data: buffer, -- tightly packed, little endian + type: "f32" | "f64" | "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "unorm8" | "unorm16" | "snorm8" | "snorm16", + components: number, -- 1 (SCALAR) .. 4 (VEC4), 4 (MAT2), 9 (MAT3), 16 (MAT4) count: number, + matrix: boolean?, -- components 4 / 9 / 16 are MAT2 / MAT3 / MAT4 (glTF), not VEC4 + name: string?, } export type Primitive = { - attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_0, COLOR_0, JOINTS_0, WEIGHTS_0 + attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_n, COLOR_n, JOINTS_n, WEIGHTS_n; custom + -- attributes start with "_" (glTF convention: PLY extra vertex properties, ...) indices: Accessor?, - mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip", + -- "polygons": faces (u32, one size per face) splits indices into n-gons (OBJ / PLY / OFF with triangulate = false; + -- MeshOps.triangulate turns them into triangles) + mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip" | "line_loop" | "polygons", + faces: Accessor?, material: number?, -- index into scene.materials (1-based) + targets: { { [string]: Accessor } }?, -- morph targets (POSITION / NORMAL / TANGENT deltas) + extras: { [string]: any }?, +} +export type Mesh = { name: string?, primitives: { Primitive }, weights: { number }?, extras: { [string]: any }? } +export type Sampler = { + wrapS: ("repeat" | "clamp" | "mirror")?, -- default "repeat" + wrapT: ("repeat" | "clamp" | "mirror")?, + filter: ("linear" | "nearest")?, -- magnification + minFilter: string?, -- "nearest" | "linear" | "nearest_mipmap_nearest" | ... (glTF names, lower case) +} +export type Texture = { + name: string?, + image: Image?, -- decoded (F.model.loadTextures or the caller), never by a model format + data: buffer?, -- the encoded image bytes (embedded / GLB / data: URI / resolved external file) + mime: string?, -- "image/png", "image/jpeg", "image/webp", "image/ktx2", ... + uri: string?, -- the external file name (relative to the model) when the data was not available or not embedded + sampler: Sampler?, + extras: { [string]: any }?, +} +export type TextureRef = { + texture: number, -- index into scene.textures (1-based) + texCoord: number?, -- TEXCOORD_n set (default 0) + scale: number?, -- normalTexture scale + strength: number?, -- occlusionTexture strength + -- KHR_texture_transform (texCoord overrides the ref's texCoord) + transform: { offset: { number }?, scale: { number }?, rotation: number?, texCoord: number? }?, } -export type Mesh = { name: string?, primitives: { Primitive } } -export type Texture = { image: Image?, uri: string?, sampler: { wrapS: string?, wrapT: string?, filter: string? }? } -export type TextureRef = { texture: number, texCoord: number?, transform: { offset: { number }?, scale: { number }?, rotation: number? }? } export type Material = { name: string?, baseColor: { number }, -- r, g, b, a linear 0..1 @@ -226,6 +271,9 @@ export type Material = { alphaMode: "opaque" | "mask" | "blend", alphaCutoff: number, doubleSided: boolean, + -- glTF material extensions by name (KHR_materials_emissive_strength = { emissiveStrength = 5 }, KHR_materials_unlit + -- = {}, ...), their fields as in glTF except textureInfo objects, which are TextureRefs + extensions: { [string]: any }?, extras: { [string]: any }?, -- classic Phong (OBJ / FBX): ambient, diffuse, specular, shininess, ... } export type Node = { @@ -235,17 +283,52 @@ export type Node = { camera: number?, light: number?, skin: number?, + voxels: number?, -- index into scene.voxels (MagicaVoxel shapes; MeshOps.meshVoxels gives them meshes) translation: { number }?, -- TRS, or matrix (column-major 4x4), not both rotation: { number }?, -- quaternion x, y, z, w scale: { number }?, matrix: { number }?, + weights: { number }?, -- morph target weights extras: { [string]: any }?, } -export type Camera = { type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? } -export type Light = { type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? } -export type Skin = { joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? } +export type Camera = { name: string?, type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? } +export type Light = { name: string?, type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? } +export type Skin = { name: string?, joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? } export type Channel = { node: number, path: "translation" | "rotation" | "scale" | "weights", input: Accessor, output: Accessor, interpolation: "LINEAR" | "STEP" | "CUBICSPLINE" } export type Animation = { name: string?, channels: { Channel } } + +-- a voxel grid (MagicaVoxel): one byte per cell, 0 = empty, 1..255 = palette index +export type VoxelMaterial = { type: string, [string]: any } -- "diffuse" | "metal" | "glass" | "emit" | "blend" | "media" | ..., MATL properties (numbers when numeric) +export type Voxels = { + kind: "voxels", + name: string?, + size: { number }, -- x, y, z cells + data: buffer, -- size x * y * z bytes, cell (x, y, z) at x + sx * (y + sy * z) + palette: { { number } }, -- palette[i] = { r, g, b, a } 0..255 (sRGB) for i = 1 .. 255 (shared between a file's models) + materials: { [number]: VoxelMaterial }?, -- by palette index +} +local Voxels = {} +-- new(sx, sy, sz, palette?) -> an empty grid (the palette defaults to grey ramps: callers set their own) +function Voxels.new(sx: number, sy: number, sz: number, palette: { { number } }?): Voxels + local pal = palette + if not pal then + local p = table.create(255) + for i = 1, 255 do + p[i] = { i, i, i, 255 } + end + pal = p + end + return { kind = "voxels", size = { sx, sy, sz }, data = buffer.create(sx * sy * sz), palette = pal :: { { number } }, materials = nil } +end +-- get / set(v, x, y, z [, index]): 0-based cell coordinates, no bounds check +function Voxels.get(v: Voxels, x: number, y: number, z: number): number + return buffer.readu8(v.data, x + v.size[1] * (y + v.size[2] * z)) +end +function Voxels.set(v: Voxels, x: number, y: number, z: number, index: number) + buffer.writeu8(v.data, x + v.size[1] * (y + v.size[2] * z), index) +end +Types.Voxels = Voxels + export type Scene = { kind: "scene", nodes: { Node }, @@ -257,6 +340,7 @@ export type Scene = { lights: { Light }, skins: { Skin }, animations: { Animation }, + voxels: { Voxels }?, -- voxel grids (VOX), referenced by node.voxels meta: { up: "y" | "z"?, unit: number?, source: { format: string, [string]: any }?, [string]: any }, } @@ -273,11 +357,30 @@ function Scene.new(): Scene lights = {}, skins = {}, animations = {}, + voxels = nil, meta = {}, } end -function Scene.accessor(data: buffer, type: any, components: number, count: number): Accessor - return { data = data, type = type, components = components, count = count } +-- the byte size of one component of an accessor type +local COMPONENT_SIZE: { [string]: number } = { + f32 = 4, + f64 = 8, + u8 = 1, + u16 = 2, + u32 = 4, + i8 = 1, + i16 = 2, + i32 = 4, + unorm8 = 1, + unorm16 = 2, + snorm8 = 1, + snorm16 = 2, +} +Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE) +-- accessor(data, type, components, count) -> Accessor (data = nil allocates a zero-filled buffer) +function Scene.accessor(data: buffer?, type: any, components: number, count: number): Accessor + local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4)) + return { data = d, type = type, components = components, count = count } end function Scene.material(name: string?): Material return { @@ -301,6 +404,161 @@ function Scene.fromPrimitive(prim: Primitive, name: string?): Scene end Types.Scene = Scene +-- reader(acc) -> get(i, c): element i (0-based), component c (0-based) as a number; normalized types are converted +-- to floats (unorm8 255 -> 1, snorm16 -32767 -> -1, glTF rules). Nil for an unknown type. +function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)? + local d, n, t = acc.data, acc.components, acc.type + local size = COMPONENT_SIZE[t] + if not size or type(d) ~= "buffer" then + return nil + end + local stride = n * size + local rb = buffer + if t == "f32" then + local f = rb.readf32 + return function(i: number, c: number): number + return f(d, i * stride + c * 4) + end + elseif t == "f64" then + local f = rb.readf64 + return function(i: number, c: number): number + return f(d, i * stride + c * 8) + end + elseif t == "u8" or t == "unorm8" then + local f, k = rb.readu8, if t == "unorm8" then 1 / 255 else 1 + return function(i: number, c: number): number + return f(d, i * stride + c) * k + end + elseif t == "u16" or t == "unorm16" then + local f, k = rb.readu16, if t == "unorm16" then 1 / 65535 else 1 + return function(i: number, c: number): number + return f(d, i * stride + c * 2) * k + end + elseif t == "u32" then + local f = rb.readu32 + return function(i: number, c: number): number + return f(d, i * stride + c * 4) + end + elseif t == "i8" then + local f = rb.readi8 + return function(i: number, c: number): number + return f(d, i * stride + c) + end + elseif t == "snorm8" then + local f = rb.readi8 + return function(i: number, c: number): number + return math.max(f(d, i * stride + c) / 127, -1) + end + elseif t == "i16" then + local f = rb.readi16 + return function(i: number, c: number): number + return f(d, i * stride + c * 2) + end + elseif t == "snorm16" then + local f = rb.readi16 + return function(i: number, c: number): number + return math.max(f(d, i * stride + c * 2) / 32767, -1) + end + elseif t == "i32" then + local f = rb.readi32 + return function(i: number, c: number): number + return f(d, i * stride + c * 4) + end + end + return nil +end + +-- the identity and products of column-major 4x4 matrices (flat arrays of 16) +local IDENTITY = table.freeze({ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }) +Scene.IDENTITY = IDENTITY +function Scene.mul(a: { number }, b: { number }): { number } + local m = table.create(16, 0) + for col = 0, 3 do + for row = 0, 3 do + local s = 0 + for k = 0, 3 do + s += a[k * 4 + row + 1] * b[col * 4 + k + 1] + end + m[col * 4 + row + 1] = s + end + end + return m +end +-- nodeMatrix(node) -> the node's local matrix (node.matrix, or T * R * S) +function Scene.nodeMatrix(node: Node): { number } + if node.matrix and #node.matrix == 16 then + return node.matrix + end + local t, r, sc = node.translation, node.rotation, node.scale + if not t and not r and not sc then + return IDENTITY + end + local tx, ty, tz = 0, 0, 0 + if t then + tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 + end + local x, y, z, w = 0, 0, 0, 1 + if r then + x, y, z, w = r[1] or 0, r[2] or 0, r[3] or 0, r[4] or 1 + end + local sx, sy, sz = 1, 1, 1 + if sc then + sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1 + end + local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z + return { + (1 - 2 * (yy + zz)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0, + (2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0, + (2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0, + tx, ty, tz, 1, + } +end +export type Placed = { primitive: Primitive, matrix: { number }, node: number, mesh: number } +-- flatten(scene) -> { { primitive, matrix (world), node, mesh } } for every mesh primitive reachable from the roots +-- (depth first, in order; cycles and repeated visits are cut). Scenes without roots use every node without a parent. +function Scene.flatten(scene: Scene): { Placed } + local out: { Placed } = {} + local nodes = scene.nodes or {} + local roots = scene.roots + if not roots or #roots == 0 then + local child = {} + for _, n in nodes do + for _, c in n.children or {} do + child[c] = true + end + end + roots = {} + for i in nodes do + if not child[i] then + table.insert(roots, i) + end + end + end + local seen: { [number]: boolean } = {} + local function visit(i: number, parent: { number }) + local node = nodes[i] + if not node or seen[i] then + return + end + seen[i] = true + local m = Scene.nodeMatrix(node) + local world = if parent == IDENTITY then m elseif m == IDENTITY then parent else Scene.mul(parent, m) + local mesh = node.mesh and scene.meshes[node.mesh] + if mesh then + for _, p in mesh.primitives do + table.insert(out, { primitive = p, matrix = world, node = i, mesh = node.mesh :: number }) + end + end + for _, c in node.children or {} do + visit(c, world) + end + end + for _, r in roots do + visit(r, IDENTITY) + end + return out +end + -- ------------------------------------------------------------------------------------------------ Cad -- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep) export type StepEntity = { id: number, type: string, args: { any } } diff --git a/src/Formats/codecs/Base64/init.luau b/src/Formats/codecs/Base64/init.luau new file mode 100644 index 0000000..3d3030f --- /dev/null +++ b/src/Formats/codecs/Base64/init.luau @@ -0,0 +1,140 @@ +--!strict +--!native +-- codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs +-- (glTF, SVG, CSS), PEM-like text, YAML !!binary, ... New code. decode skips whitespace, accepts missing padding and +-- both alphabets; any other character is an error. Never throws. +-- +-- local Base64 = require("@formats/codecs/Base64") +-- local s = Base64.encode(buf) -- string ("" for an empty buffer) +-- local b, err = Base64.decode(s) -- buffer | nil, "message" +-- local b2 = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, message +local Base64 = {} + +local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +local ALPHA_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" +local ENC = buffer.fromstring(ALPHA) +local ENC_URL = buffer.fromstring(ALPHA_URL) +-- the decode table: 0..63, 64 = skip (whitespace), 65 = padding, 255 = bad +local DEC = buffer.create(256) +buffer.fill(DEC, 0, 255) +for i = 1, 64 do + buffer.writeu8(DEC, string.byte(ALPHA, i), i - 1) +end +buffer.writeu8(DEC, string.byte("-"), 62) +buffer.writeu8(DEC, string.byte("_"), 63) +for _, c in { 9, 10, 13, 32 } do + buffer.writeu8(DEC, c, 64) +end +buffer.writeu8(DEC, string.byte("="), 65) + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- encode(buf, opts?, offset?, length?) -> string. opts.url: the URL-safe alphabet; opts.pad = false: no "=" padding. +function Base64.encode(buf: buffer, opts: { url: boolean?, pad: boolean? }?, offset: number?, length: number?): string + local o = math.clamp(offset or 0, 0, buffer.len(buf)) + local n = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) + local enc = if opts and opts.url then ENC_URL else ENC + local pad = not (opts and opts.pad == false) + local full = n // 3 + local rest = n - full * 3 + local outLen = full * 4 + (if rest == 0 then 0 elseif pad then 4 else rest + 1) + local out = buffer.create(outLen) + local p = 0 + for i = 0, full - 1 do + local q = o + i * 3 + local v = readu8(buf, q) * 65536 + readu8(buf, q + 1) * 256 + readu8(buf, q + 2) + writeu8(out, p, readu8(enc, v // 262144)) + writeu8(out, p + 1, readu8(enc, (v // 4096) % 64)) + writeu8(out, p + 2, readu8(enc, (v // 64) % 64)) + writeu8(out, p + 3, readu8(enc, v % 64)) + p += 4 + end + if rest > 0 then + local q = o + full * 3 + local v = readu8(buf, q) * 65536 + (if rest == 2 then readu8(buf, q + 1) * 256 else 0) + writeu8(out, p, readu8(enc, v // 262144)) + writeu8(out, p + 1, readu8(enc, (v // 4096) % 64)) + if rest == 2 then + writeu8(out, p + 2, readu8(enc, (v // 64) % 64)) + elseif pad then + writeu8(out, p + 2, 61) + end + if pad then + writeu8(out, p + 3, 61) + end + end + return buffer.tostring(out) +end + +-- decode(s) -> buffer | nil, message +function Base64.decode(s: string | buffer): (buffer?, string?) + local src = if type(s) == "string" then buffer.fromstring(s) else s + local n = buffer.len(src) + local out = buffer.create((n // 4 + 1) * 3) + local acc, bits, p = 0, 0, 0 + local padded = false + for i = 0, n - 1 do + local d = readu8(DEC, readu8(src, i)) + if d < 64 then + if padded then + return nil, "data after padding" + end + acc = acc * 64 + d + bits += 6 + if bits >= 8 then + bits -= 8 + local byte = acc // (2 ^ bits) + writeu8(out, p, byte % 256) + p += 1 + acc = acc % (2 ^ bits) + end + elseif d == 65 then + padded = true + elseif d ~= 64 then + return nil, string.format("bad base64 character 0x%02x at %d", readu8(src, i), i) + end + end + if bits >= 6 then + return nil, "truncated base64 (a single character in the last group)" + end + local res = buffer.create(p) + buffer.copy(res, 0, out, 0, p) + return res, nil +end + +-- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[][;params][;base64]," (percent-encoded data +-- when not base64) +function Base64.decodeDataUri(uri: string): (buffer?, string?) + if string.sub(uri, 1, 5) ~= "data:" then + return nil, "not a data: URI" + end + local comma = string.find(uri, ",", 6, true) + if not comma then + return nil, "data: URI without a comma" + end + local head = string.sub(uri, 6, comma - 1) + local isB64 = string.sub(head, -7) == ";base64" + local mime = string.match(head, "^([^;]*)") or "" + if mime == "" then + mime = "text/plain" + end + local body = string.sub(uri, comma + 1) + if isB64 then + local b, err = Base64.decode(body) + if not b then + return nil, err + end + return b, mime + end + local decoded = string.gsub(body, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + return buffer.fromstring(decoded), mime +end + +-- dataUri(buf, mime) -> "data:;base64,..." +function Base64.dataUri(buf: buffer, mime: string?): string + return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf) +end + +return Base64 diff --git a/src/Formats/codecs/MeshFlatten.luau b/src/Formats/codecs/MeshFlatten.luau new file mode 100644 index 0000000..298a577 --- /dev/null +++ b/src/Formats/codecs/MeshFlatten.luau @@ -0,0 +1,556 @@ +--!strict +-- codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks +-- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are), +-- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring +-- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices, +-- polygons, strips, fans, points; lines are skipped). Shared here because a format cannot require another one +-- (ops/MeshOps.merge is the editing-side equivalent). +-- Never throws: bad input returns nil, message. +local Types = require("@formats/Types") + +local Flatten = {} + +local readf32, readf64 = buffer.readf32, buffer.readf64 +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local readi8, readi16, readi32 = buffer.readi8, buffer.readi16, buffer.readi32 + +local SIZE = Types.COMPONENT_SIZE +-- normalized integer types: their scale (raw / scale = the normalized value) +local NORM: { [string]: number } = { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 } + +export type Attr = { + type: string, -- the accessor type shared by every part ("f32" when the parts disagree) + components: number, + raw: boolean, -- values are raw integers of a normalized type (unorm8: 0..255), else plain numbers + values: { number }, -- count * components +} +export type PartInfo = { + prim: Types.Primitive, + mesh: Types.Mesh?, + node: Types.Node?, + firstVertex: number, -- 0-based offset of the part's vertices in the merged mesh + vertexCount: number, + firstFace: number, -- 0-based offset of the part's faces + faceCount: number, + identity: boolean, -- no transform was applied +} +export type Merged = { + count: number, -- vertices + attrs: { [string]: Attr }, -- POSITION and NORMAL in world space (f32 values), the others as read + sizes: { number }?, -- vertices per face (nil: no part has faces, a point cloud) + corners: { number }, -- 0-based vertex indices, face after face + parts: { PartInfo }, +} + +-- ------------------------------------------------------------------------------------------------ accessors +-- numbers(acc, raw) -> the accessor's count * components values (normalized types divided out unless raw), or nil, msg +function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?) + if type(acc) ~= "table" or type(acc.data) ~= "buffer" then + return nil, "accessor without a data buffer" + end + local t, comps, count = acc.type, acc.components, acc.count + local size = SIZE[t] + if size == nil then + return nil, "unknown accessor type " .. tostring(t) + end + if type(comps) ~= "number" or type(count) ~= "number" or comps < 1 or comps > 16 or count < 0 or comps % 1 ~= 0 or count % 1 ~= 0 then + return nil, "bad accessor components / count" + end + local n = count * comps + local d: buffer = acc.data + if buffer.len(d) < n * size then + return nil, "accessor data shorter than count * components" + end + local out = table.create(n) + if t == "f32" then + for i = 0, n - 1 do + out[i + 1] = readf32(d, i * 4) + end + elseif t == "f64" then + for i = 0, n - 1 do + out[i + 1] = readf64(d, i * 8) + end + elseif t == "u8" or t == "unorm8" then + for i = 0, n - 1 do + out[i + 1] = readu8(d, i) + end + elseif t == "u16" or t == "unorm16" then + for i = 0, n - 1 do + out[i + 1] = readu16(d, i * 2) + end + elseif t == "u32" then + for i = 0, n - 1 do + out[i + 1] = readu32(d, i * 4) + end + elseif t == "i8" or t == "snorm8" then + for i = 0, n - 1 do + out[i + 1] = readi8(d, i) + end + elseif t == "i16" or t == "snorm16" then + for i = 0, n - 1 do + out[i + 1] = readi16(d, i * 2) + end + else -- i32 + for i = 0, n - 1 do + out[i + 1] = readi32(d, i * 4) + end + end + local scale = NORM[t] + if scale and not raw then + local signed = t == "snorm8" or t == "snorm16" + for i = 1, n do + local v = out[i] / scale + out[i] = if signed and v < -1 then -1 else v + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ transforms +local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } + +-- column-major 4x4 product a * b +local function mul(a: { number }, b: { number }): { number } + local m = table.create(16, 0) + for c = 0, 3 do + for r = 0, 3 do + local s = 0 + for k = 0, 3 do + s += a[k * 4 + r + 1] * b[c * 4 + k + 1] + end + m[c * 4 + r + 1] = s + end + end + return m +end + +local function numList(v: any, n: number): boolean + if type(v) ~= "table" then + return false + end + for i = 1, n do + if type(v[i]) ~= "number" then + return false + end + end + return true +end + +-- a node's local matrix (nil: none), or nil, message +local function localMatrix(node: any): ({ number }?, string?) + if node.matrix ~= nil then + if not numList(node.matrix, 16) then + return nil, "node matrix is not 16 numbers" + end + local m = table.create(16) + for i = 1, 16 do + m[i] = node.matrix[i] + end + return m, nil + end + local t, q, s = node.translation, node.rotation, node.scale + if t == nil and q == nil and s == nil then + return nil, nil + end + if (t ~= nil and not numList(t, 3)) or (q ~= nil and not numList(q, 4)) or (s ~= nil and not numList(s, 3)) then + return nil, "bad node translation / rotation / scale" + end + local x, y, z, w = 0, 0, 0, 1 + if q then + x, y, z, w = q[1], q[2], q[3], q[4] + end + local sx, sy, sz = 1, 1, 1 + if s then + sx, sy, sz = s[1], s[2], s[3] + end + local tx, ty, tz = 0, 0, 0 + if t then + tx, ty, tz = t[1], t[2], t[3] + end + return { + (1 - 2 * (y * y + z * z)) * sx, + (2 * (x * y + z * w)) * sx, + (2 * (x * z - y * w)) * sx, + 0, + (2 * (x * y - z * w)) * sy, + (1 - 2 * (x * x + z * z)) * sy, + (2 * (y * z + x * w)) * sy, + 0, + (2 * (x * z + y * w)) * sz, + (2 * (y * z - x * w)) * sz, + (1 - 2 * (x * x + y * y)) * sz, + 0, + tx, + ty, + tz, + 1, + }, + nil +end + +local function isIdentity(m: { number }): boolean + for i = 1, 16 do + if m[i] ~= IDENTITY[i] then + return false + end + end + return true +end + +type Instance = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, matrix: { number }? } + +-- the primitive instances of a scene in traversal order, or nil, message +local function instances(scene: any): ({ Instance }?, string?) + local out: { Instance } = {} + local nodes, meshes = scene.nodes, scene.meshes + if type(nodes) ~= "table" or type(meshes) ~= "table" then + return nil, "scene without nodes / meshes tables" + end + local function addMesh(mi: any, node: Types.Node?, m: { number }?): string? + local mesh = meshes[mi] + if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then + return "node refers to a missing mesh " .. tostring(mi) + end + for _, prim in mesh.primitives do + if type(prim) ~= "table" or type(prim.attributes) ~= "table" then + return "bad primitive" + end + table.insert(out, { prim = prim, mesh = mesh, node = node, matrix = m }) + end + return nil + end + local visiting: { [number]: boolean } = {} + local function visit(ni: any, parent: { number }?, depth: number): string? + local node = nodes[ni] + if type(node) ~= "table" then + return "missing node " .. tostring(ni) + end + if depth > 256 or visiting[ni] then + return "node hierarchy is cyclic or too deep" + end + visiting[ni] = true + local m, merr = localMatrix(node) + if merr then + return merr + end + local world = if m and parent then mul(parent, m) elseif m then m else parent + if node.mesh ~= nil then + local e = addMesh(node.mesh, node, world) + if e then + return e + end + end + if type(node.children) == "table" then + for _, c in node.children do + local e = visit(c, world, depth + 1) + if e then + return e + end + end + end + visiting[ni] = nil + return nil + end + local roots = scene.roots + if type(roots) == "table" and #roots > 0 then + for _, ri in roots do + local e = visit(ri, nil, 0) + if e then + return nil, e + end + end + elseif #nodes > 0 then + local isChild: { [number]: boolean } = {} + for _, n in nodes do + if type(n) == "table" and type(n.children) == "table" then + for _, c in n.children do + isChild[c] = true + end + end + end + for i = 1, #nodes do + if not isChild[i] then + local e = visit(i, nil, 0) + if e then + return nil, e + end + end + end + else + for i = 1, #meshes do + local e = addMesh(i, nil, nil) + if e then + return nil, e + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ faces +-- the faces of a primitive: sizes (nil = all triangles), corners (0-based), or "points" / "skip", or nil, message +local function faces(prim: any, nv: number): (any, any, string?) + local mode = prim.mode or "triangles" + if mode == "points" then + return "points", nil, nil + elseif mode == "lines" or mode == "line_strip" or mode == "line_loop" then + return "skip", nil, nil + end + local idx: { number } + if prim.indices ~= nil then + local v, err = Flatten.numbers(prim.indices, true) + if not v then + return nil, nil, "indices: " .. tostring(err) + end + idx = v + else + idx = table.create(nv) + for i = 1, nv do + idx[i] = i - 1 + end + end + for i = 1, #idx do + local v = idx[i] + if v < 0 or v >= nv or v % 1 ~= 0 then + return nil, nil, string.format("index %s out of range (%d vertices)", tostring(v), nv) + end + end + if mode == "triangles" then + local n = #idx - #idx % 3 + if n ~= #idx then + local c = table.create(n) + table.move(idx, 1, n, 1, c) + idx = c + end + return false, idx, nil + elseif mode == "polygons" then + if prim.faces == nil then + return nil, nil, "polygons primitive without faces" + end + local sizes, err = Flatten.numbers(prim.faces, true) + if not sizes then + return nil, nil, "faces: " .. tostring(err) + end + local total = 0 + for i = 1, #sizes do + local s = sizes[i] + if s < 0 or s % 1 ~= 0 then + return nil, nil, "bad face size" + end + total += s + end + if total ~= #idx then + return nil, nil, "face sizes do not add up to the index count" + end + return sizes, idx, nil + elseif mode == "triangle_strip" or mode == "triangle_fan" then + local c = {} + for i = 3, #idx do + if mode == "triangle_fan" then + table.insert(c, idx[1]) + table.insert(c, idx[i - 1]) + table.insert(c, idx[i]) + elseif i % 2 == 1 then + table.insert(c, idx[i - 2]) + table.insert(c, idx[i - 1]) + table.insert(c, idx[i]) + else + table.insert(c, idx[i - 1]) + table.insert(c, idx[i - 2]) + table.insert(c, idx[i]) + end + end + return false, c, nil + end + return nil, nil, "unknown primitive mode " .. tostring(mode) +end + +-- ------------------------------------------------------------------------------------------------ merge +-- the fill value of a missing attribute component: colours default to opaque white, everything else to 0 +local function fill(name: string, t: string, raw: boolean): number + if string.sub(name, 1, 6) ~= "COLOR_" then + return 0 + end + return if raw and NORM[t] then NORM[t] else 1 +end + +local function f32(v: number): number + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return buffer.readf32(b, 0) +end + +-- merge(scene, keep, opts) -> Merged | nil, message. keep(name) says which attributes to carry (POSITION always). +-- opts.triangulate fan-triangulates polygons (faces of fewer than 3 vertices are dropped then). +function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulate: boolean? }?): (Merged?, string?) + if type(scene) ~= "table" then + return nil, "not a scene" + end + local list, lerr = instances(scene) + if not list then + return nil, lerr + end + local triangulate = opts and opts.triangulate or false + -- the attribute set: union over parts, a type every part agrees on (else f32), the widest component count + local types: { [string]: string } = {} + local comps: { [string]: number } = {} + local used: { Instance } = {} + for _, inst in list do + local mode = inst.prim.mode or "triangles" + if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" then + local pos = inst.prim.attributes.POSITION + if type(pos) ~= "table" then + return nil, "primitive without POSITION" + end + table.insert(used, inst) + for name, acc in inst.prim.attributes do + if type(name) == "string" and (name == "POSITION" or keep(name)) and type(acc) == "table" then + local t = acc.type + if types[name] == nil then + types[name] = t + elseif types[name] ~= t then + types[name] = "f32" + end + comps[name] = math.max(comps[name] or 0, tonumber(acc.components) or 0) + end + end + end + end + if (comps.POSITION or 3) < 3 then + return nil, "POSITION needs 3 components" + end + local attrs: { [string]: Attr } = {} + for name, t in types do + local raw = NORM[t] ~= nil + if name == "POSITION" or name == "NORMAL" then + raw = false + end + attrs[name] = { type = if name == "POSITION" or name == "NORMAL" then "f32" else t, components = if name == "POSITION" or name == "NORMAL" then 3 else comps[name], raw = raw, values = {} } + end + local merged: Merged = { count = 0, attrs = attrs, sizes = nil, corners = {}, parts = {} } + local sizes: { number } = {} + local anyFaces = false + local corners = merged.corners + for _, inst in used do + local prim: any = inst.prim + local posAcc = prim.attributes.POSITION + local nv = tonumber(posAcc.count) or 0 + local m = inst.matrix + local identity = m == nil or isIdentity(m :: { number }) + local info: PartInfo = { prim = prim, mesh = inst.mesh, node = inst.node, firstVertex = merged.count, vertexCount = nv, firstFace = #sizes, faceCount = 0, identity = identity } + for name, a in attrs do + local acc = prim.attributes[name] + local dst = a.values + local n0 = #dst + local ac = a.components + if acc == nil then + local f = fill(name, a.type, a.raw) + for i = 1, nv * ac do + dst[n0 + i] = f + end + else + if acc.count ~= nv then + return nil, name .. " count differs from POSITION" + end + local vals, err = Flatten.numbers(acc, a.raw and acc.type == a.type) + if not vals then + return nil, name .. ": " .. tostring(err) + end + local sc = acc.components + if a.raw and acc.type ~= a.type then + return nil, name .. ": mixed accessor types" + end + local f = fill(name, a.type, a.raw) + if name == "POSITION" and not identity then + local mm = m :: { number } + for i = 0, nv - 1 do + local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3] + dst[n0 + i * 3 + 1] = f32(mm[1] * x + mm[5] * y + mm[9] * z + mm[13]) + dst[n0 + i * 3 + 2] = f32(mm[2] * x + mm[6] * y + mm[10] * z + mm[14]) + dst[n0 + i * 3 + 3] = f32(mm[3] * x + mm[7] * y + mm[11] * z + mm[15]) + end + elseif name == "NORMAL" and not identity and sc >= 3 then + local mm = m :: { number } + -- the cofactor matrix of the upper 3x3 = det * inverse transpose; the sign of det keeps the direction + local a1, a2, a3, b1, b2, b3, c1, c2, c3 = mm[1], mm[2], mm[3], mm[5], mm[6], mm[7], mm[9], mm[10], mm[11] + local n11, n12, n13 = b2 * c3 - b3 * c2, b3 * c1 - b1 * c3, b1 * c2 - b2 * c1 + local n21, n22, n23 = c2 * a3 - c3 * a2, c3 * a1 - c1 * a3, c1 * a2 - c2 * a1 + local n31, n32, n33 = a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 + local sgn = if a1 * n11 + a2 * n12 + a3 * n13 < 0 then -1 else 1 + for i = 0, nv - 1 do + local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3] + -- column j of the cofactor matrix multiplies component j: (inverse transpose) * n + local nx = n11 * x + n21 * y + n31 * z + local ny = n12 * x + n22 * y + n32 * z + local nz = n13 * x + n23 * y + n33 * z + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = sgn * nx / l, sgn * ny / l, sgn * nz / l + end + dst[n0 + i * 3 + 1] = f32(nx) + dst[n0 + i * 3 + 2] = f32(ny) + dst[n0 + i * 3 + 3] = f32(nz) + end + else + for i = 0, nv - 1 do + for c = 1, ac do + dst[n0 + i * ac + c] = if c <= sc then vals[i * sc + c] else f + end + end + end + end + end + local fs, cs, ferr = faces(prim, nv) + if ferr then + return nil, ferr + end + local flip = false + if not identity then + local mm = m :: { number } + local det = mm[1] * (mm[6] * mm[11] - mm[7] * mm[10]) - mm[5] * (mm[2] * mm[11] - mm[3] * mm[10]) + mm[9] * (mm[2] * mm[7] - mm[3] * mm[6]) + flip = det < 0 + end + if fs ~= "points" and fs ~= "skip" then + anyFaces = true + local base = merged.count + local cl: { number } = cs + local p = 0 + local nf = if fs then #fs else #cl // 3 + for f = 1, nf do + local s = if fs then fs[f] else 3 + if triangulate then + for k = 2, s - 1 do + table.insert(sizes, 3) + local a, b, c = cl[p + 1], cl[p + k], cl[p + k + 1] + if flip then + b, c = c, b + end + table.insert(corners, base + a) + table.insert(corners, base + b) + table.insert(corners, base + c) + end + else + table.insert(sizes, s) + if flip then + table.insert(corners, base + cl[p + 1]) + for k = s, 2, -1 do + table.insert(corners, base + cl[p + k]) + end + else + for k = 1, s do + table.insert(corners, base + cl[p + k]) + end + end + end + p += s + end + end + info.faceCount = #sizes - info.firstFace + merged.count += nv + table.insert(merged.parts, info) + end + merged.sizes = if anyFaces then sizes else nil + return merged, nil +end + +return Flatten diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 7601210..19fd6c7 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -161,6 +161,26 @@ local function drain(dec: any): any return a end +-- siblings(path) -> resolve(uri): reads files relative to path's directory (no absolute paths, no "..", no URLs) +local function siblings(path: string): (uri: string) -> buffer? + local dir = string.match(path, "^(.*[/\\])") or "" + return function(uri: string): buffer? + if type(uri) ~= "string" or uri == "" or string.find(uri, "^%a[%w+.-]*:") or string.sub(uri, 1, 1) == "/" then + return nil + end + local u = string.gsub(uri, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + for part in string.gmatch(u, "[^/\\]+") do + if part == ".." then + return nil + end + end + local b = host.readFile(dir .. u) + return b + end +end + -- ------------------------------------------------------------------------------------------------ API export type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options @@ -272,6 +292,11 @@ function F.load(src: any, opts: Options?): (any, Err.Err?) if not m then return nil, merr end + if o.resolve == nil and name and name == (type(src) == "string" and src or nil) and host.hasFiles then + -- files next to the one loaded (OBJ .mtl, glTF .bin / images): opts.resolve(uri) for the decoder + o = table.clone(o) + o.resolve = siblings(name) + end local value, err if m.decode then local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o)) @@ -328,8 +353,10 @@ function F.open(src: any, opts: Options?): (any, Err.Err?) return dec end +local encodeTextures: (scene: any) -> Err.Err? + -- the writable format for a value: opts.format, the destination's extension, or the source format -local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?) +local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?, string?) local category = o.category if category == nil and type(value) == "table" and type(value.kind) == "string" then category = KIND_CATEGORY[value.kind] @@ -359,16 +386,49 @@ local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entr end return nil, nil, Err.wrap(Err.new(Err.UNSUPPORTED, "read-only format" .. (if alt then "; try " .. alt else "")), entry.name) end - return entry, m, nil + return entry, m, nil, key +end + +-- scene textures with only a decoded image get PNG bytes before a model writer sees them (writers never encode images) +function encodeTextures(scene: any): Err.Err? + if type(scene.textures) ~= "table" then + return nil + end + for _, tex in scene.textures do + if type(tex) == "table" and tex.data == nil and type(tex.image) == "table" and tex.uri == nil then + local png, err = F.save(tex.image, nil, { format = "png" }) + if not png then + return err + end + tex.data, tex.mime = png, "image/png" + end + end + return nil end -- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) local o = opts or {} - local entry, m, err = encoderFor(value, dest, o) + local entry, m, err, key = encoderFor(value, dest, o) if not entry then return nil, err end + -- the encoder sees the format key it was picked by ("glb" vs "gltf"), the destination's name, and (writing a file) + -- an opts.files table for the extra files it writes (OBJ .mtl, glTF .bin) + o = table.clone(o) + o.format = o.format or key + if dest then + o.name = o.name or string.match(dest, "([^/\\]+)$") + if o.files == nil then + o.files = {} + end + end + if type(value) == "table" and value.kind == "scene" then + local terr = encodeTextures(value) + if terr then + return nil, terr + end + end local ok, buf, e = pcall(m.encode, value, withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name) @@ -381,6 +441,15 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) if not wok then return nil, werr end + if type(o.files) == "table" and o.files ~= (opts and opts.files) then + local dir = string.match(dest, "^(.*[/\\])") or "" + for fname, data in o.files do + local fok, ferr = host.writeFile(dir .. fname, if type(data) == "string" then buffer.fromstring(data) else data) + if not fok then + return nil, ferr + end + end + end return true end return buf @@ -470,4 +539,33 @@ for category in Types.CATEGORIES do end F.data.null = Types.null +-- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or +-- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images +-- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose +-- image format is missing or broken keep image = nil and report an Err. +F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: Err.Err }) + local errs: { [number]: Err.Err } = {} + if type(scene) ~= "table" or type(scene.textures) ~= "table" then + return scene, errs + end + local resolve = opts and opts.resolve + for i, tex in scene.textures do + if type(tex) == "table" and tex.image == nil then + local data = tex.data + if data == nil and tex.uri and resolve then + data = resolve(tex.uri) + end + if data ~= nil then + local img, err = F.load(data, { category = "image", name = tex.uri, data = true }) + if img then + tex.image = img + elseif err then + errs[i] = err + end + end + end + end + return scene, errs +end + return F diff --git a/src/Formats/model/gltf/Pack.luau b/src/Formats/model/gltf/Pack.luau new file mode 100644 index 0000000..470d384 --- /dev/null +++ b/src/Formats/model/gltf/Pack.luau @@ -0,0 +1,74 @@ +--!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. +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 + bcopy(dst, 0, src, off, count * elem) + return + end + for i = 0, count - 1 do + bcopy(dst, i * elem, src, off + i * stride, elem) + end + return + end + for i = 0, count - 1 do + local s = off + i * stride + local d = i * elem + for c = 0, cols - 1 do + bcopy(dst, d + c * colBytes, src, s + c * colStride, colBytes) + end + 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 + bcopy(dst, at, src, 0, count * elem) + return + end + for i = 0, count - 1 do + bcopy(dst, at + i * stride, src, i * elem, elem) + end + return + end + for i = 0, count - 1 do + local d = at + i * stride + local s = i * elem + for c = 0, cols - 1 do + bcopy(dst, d + c * colStride, src, s + c * colBytes, colBytes) + end + 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 + if idxSize == 1 then + i = readu8(idx, idxOff + k) + elseif idxSize == 2 then + i = readu16(idx, idxOff + k * 2) + else + i = readu32(idx, idxOff + k * 4) + end + if i >= count then + return false + end + bcopy(dst, i * elem, values, valOff + k * elem, elem) + end + return true +end + +return Pack diff --git a/src/Formats/model/gltf/Read.luau b/src/Formats/model/gltf/Read.luau new file mode 100644 index 0000000..ab59fe6 --- /dev/null +++ b/src/Formats/model/gltf/Read.luau @@ -0,0 +1,661 @@ +--!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 }. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Base64 = require("@formats/codecs/Base64") +local Pack = require("@formats/model/gltf/Pack") + +local Read = {} + +local COMPONENT: { [number]: { string } } = { + [5120] = { "i8", "snorm8" }, + [5121] = { "u8", "unorm8" }, + [5122] = { "i16", "snorm16" }, + [5123] = { "u16", "unorm16" }, + [5125] = { "u32", "" }, + [5126] = { "f32", "" }, +} +local SIZE = { [5120] = 1, [5121] = 1, [5122] = 2, [5123] = 2, [5125] = 4, [5126] = 4 } +local TYPE_COMPONENTS = { SCALAR = 1, VEC2 = 2, VEC3 = 3, VEC4 = 4, MAT2 = 4, MAT3 = 9, MAT4 = 16 } +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 = { [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) +local KNOWN = { + KHR_lights_punctual = true, + KHR_mesh_quantization = true, + KHR_texture_transform = true, + KHR_materials_emissive_strength = true, + KHR_materials_unlit = true, + KHR_materials_clearcoat = true, + KHR_materials_transmission = true, + KHR_materials_volume = true, + KHR_materials_ior = true, + KHR_materials_specular = true, + KHR_materials_sheen = true, + KHR_materials_iridescence = true, + KHR_materials_anisotropy = true, + KHR_materials_dispersion = true, + KHR_materials_diffuse_transmission = true, + KHR_materials_variants = true, + KHR_materials_pbrSpecularGlossiness = true, + KHR_texture_basisu = true, -- the image stays encoded (image/ktx2) + EXT_texture_webp = true, + EXT_texture_avif = true, + KHR_node_visibility = true, + KHR_xmp_json_ld = true, +} +Read.KNOWN = KNOWN + +export type Fetch = (uri: string) -> buffer? +type View = { buf: buffer, offset: number, length: number, stride: number? } +type Img = { data: buffer?, mime: string?, uri: string?, name: string? } + +local function num(v: any, default: number): number + return if type(v) == "number" then v else default +end +local function int(v: any): number? + return if type(v) == "number" and v == math.floor(v) and v >= 0 then v else nil +end +local function arr(v: any): { any } + return if type(v) == "table" then v else {} +end +local function str(v: any): string? + return if type(v) == "string" then v else nil +end +local function numbers(v: any, n: number): { number }? + if type(v) ~= "table" or #v ~= n then + return nil + end + for i = 1, n do + if type(v[i]) ~= "number" then + return nil + end + end + return table.move(v, 1, n, 1, {}) +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 + if type(obj.extensions) == "table" then + for k, v in obj.extensions do + if not (handled and handled[k]) then + ext = ext or {} + local e: any = ext + e[k] = v + end + end + end + if extras == nil and ext == nil then + return nil + end + return { gltf = { extras = extras, extensions = ext } } +end + +function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + if type(doc) ~= "table" then + return nil, Err.new(Err.CORRUPT, "the JSON is not an object") + end + local asset = doc.asset + if type(asset) ~= "table" or type(asset.version) ~= "string" then + return nil, Err.new(Err.CORRUPT, "no asset.version") + end + if string.sub(asset.version, 1, 1) ~= "2" then + return nil, Err.new(Err.UNSUPPORTED, "glTF version " .. asset.version .. " (only 2.x)") + end + for _, e in arr(doc.extensionsRequired) do + if type(e) == "string" and not KNOWN[e] then + return nil, Err.new(Err.UNSUPPORTED, "required extension " .. e) + end + end + local scene = Types.Scene.new() + -- buffers + local buffers: { buffer } = {} + local total = 0 + for i, b in arr(doc.buffers) do + if type(b) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad buffer " .. (i - 1)) + end + local len = int(b.byteLength) + if not len then + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " without byteLength") + end + total += len + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "buffers over " .. maxBytes .. " bytes") + end + local data: buffer? = nil + local uri = str(b.uri) + if uri == nil then + if i == 1 and bin then + data = bin + else + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " has no uri and no GLB BIN chunk") + end + elseif string.sub(uri, 1, 5) == "data:" then + local d, derr = Base64.decodeDataUri(uri) + if not d then + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. ": " .. tostring(derr)) + end + data = d + else + data = fetch(uri) + if not data then + return nil, Err.new(Err.IO, "buffer file " .. uri .. " not found (pass opts.resolve or opts.files)") + end + end + if buffer.len(data :: buffer) < len then + return nil, Err.new(Err.TRUNCATED, "buffer " .. (i - 1) .. " is shorter than its byteLength") + end + buffers[i] = data :: buffer + end + -- buffer views -> { buf, offset, length, stride } + local views: { View } = {} + for i, v in arr(doc.bufferViews) do + if type(v) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad bufferView " .. (i - 1)) + end + local bi, off, len = int(v.buffer), int(v.byteOffset or 0), int(v.byteLength) + local b = bi and buffers[bi + 1] + if not b or not off or not len or off + len > buffer.len(b) then + return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. " out of range") + end + local stride = v.byteStride + if stride ~= nil and (not int(stride) or stride < 4 or stride > 252) then + return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. ": bad byteStride") + 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) + if type(a) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad " .. label) + end + local ct, count, typ = a.componentType, int(a.count), a.type + local names = COMPONENT[ct] + local comps = TYPE_COMPONENTS[typ] + if not names or not count or not comps then + return nil, Err.new(Err.CORRUPT, label .. ": bad componentType, count or type") + end + local normalized = a.normalized == true + local tname = if normalized then names[2] else names[1] + if tname == "" then + return nil, Err.new(Err.CORRUPT, label .. ": normalized " .. names[1]) + end + local size = SIZE[ct] + local cols = TYPE_COLUMNS[typ] or 1 + local rows = comps // cols + local colBytes = rows * size + local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes + local elem = comps * size + local padded = cols * colStride + if count * elem > maxBytes then + return nil, Err.new(Err.LIMIT, label .. " is over " .. maxBytes .. " bytes") + end + local data = buffer.create(count * elem) + local vi = a.bufferView + if vi ~= nil then + local view = int(vi) and views[vi + 1] + if not view then + return nil, Err.new(Err.CORRUPT, label .. ": bad bufferView") + end + local off = int(a.byteOffset or 0) + if not off then + return nil, Err.new(Err.CORRUPT, label .. ": bad byteOffset") + end + local stride = view.stride or padded + if stride < padded and count > 1 then + return nil, Err.new(Err.CORRUPT, label .. ": byteStride smaller than an element") + end + if count > 0 and off + (count - 1) * stride + padded > view.length then + return nil, Err.new(Err.CORRUPT, label .. " runs past its bufferView") + end + if count > 0 then + Pack.gather(data, view.buf, view.offset + off, count, elem, stride, cols, colBytes, colStride) + end + end + local sp = a.sparse + if type(sp) == "table" then + local n = int(sp.count) + local si, sv = sp.indices, sp.values + if not n or type(si) ~= "table" or type(sv) ~= "table" then + return nil, Err.new(Err.CORRUPT, label .. ": bad sparse") + end + local isz = SIZE[si.componentType] + local iv, vv = int(si.bufferView) and views[si.bufferView + 1], int(sv.bufferView) and views[sv.bufferView + 1] + local io, vo = int(si.byteOffset or 0), int(sv.byteOffset or 0) + local okType = si.componentType == 5121 or si.componentType == 5123 or si.componentType == 5125 + if not okType or not isz or not iv or not vv or not io or not vo then + return nil, Err.new(Err.CORRUPT, label .. ": bad sparse indices / values") + end + 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) + local vals, valOff = vv.buf, vv.offset + vo + if cols > 1 and colBytes ~= colStride then + vals = buffer.create(n * elem) + Pack.gather(vals, vv.buf, vv.offset + vo, n, elem, padded, cols, colBytes, colStride) + valOff = 0 + end + if not Pack.sparse(data, count, elem, iv.buf, iv.offset + io, isz, vals, valOff, n) then + return nil, Err.new(Err.CORRUPT, label .. ": sparse index out of range") + end + end + local acc = Types.Scene.accessor(data, tname, comps, count) + if cols > 1 then + acc.matrix = true + end + acc.name = str(a.name) + accessors[i] = acc + end + local function accessor(v: any): Types.Accessor? + 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 + return nil, Err.new(Err.CORRUPT, "bad image " .. (i - 1)) + end + local img: Img = { mime = str(im.mimeType), name = str(im.name) } + if im.bufferView ~= nil then + local view = int(im.bufferView) and views[im.bufferView + 1] + if not view then + return nil, Err.new(Err.CORRUPT, "image " .. (i - 1) .. ": bad bufferView") + end + local d = buffer.create(view.length) + buffer.copy(d, 0, view.buf, view.offset, view.length) + img.data = d + elseif type(im.uri) == "string" then + if string.sub(im.uri, 1, 5) == "data:" then + local d, mime = Base64.decodeDataUri(im.uri) + if d then + img.data = d + img.mime = img.mime or mime + end + else + img.uri = im.uri + img.data = fetch(im.uri) + if not img.mime then + local ext = string.lower(string.match(im.uri, "%.(%w+)$") or "") + img.mime = if ext == "png" then "image/png" elseif ext == "jpg" or ext == "jpeg" then "image/jpeg" elseif ext == "webp" then "image/webp" elseif ext == "ktx2" then "image/ktx2" else nil + end + end + end + images[i] = img + end + local samplers: { Types.Sampler } = {} + for i, s in arr(doc.samplers) do + if type(s) == "table" then + samplers[i] = { + wrapS = WRAP[s.wrapS] or (if s.wrapS == nil then nil else "repeat") :: any, + wrapT = WRAP[s.wrapT] or (if s.wrapT == nil then nil else "repeat") :: any, + filter = if s.magFilter == 9728 then "nearest" elseif s.magFilter == 9729 then "linear" else nil, + minFilter = MIN_FILTER[s.minFilter], + } + else + samplers[i] = {} + end + end + local TEX_SOURCE_EXT = { "KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif" } + for i, t in arr(doc.textures) do + if type(t) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad texture " .. (i - 1)) + end + local src = t.source + local handled = {} + if type(t.extensions) == "table" then + for _, e in TEX_SOURCE_EXT do + local x = t.extensions[e] + if type(x) == "table" and int(x.source) then + src = x.source + handled[e] = true + break + end + end + end + local img = int(src) and images[src + 1] + local tex: Types.Texture = { name = str(t.name) } + if img then + tex.data, tex.mime, tex.uri = img.data, img.mime, img.uri + tex.name = tex.name or img.name + end + local si = int(t.sampler) + if si and samplers[si + 1] then + tex.sampler = table.clone(samplers[si + 1]) + end + tex.extras = keep(t, handled) + if next(handled) then + -- the fallback image (t.source) and the extension name, for writing the texture back the same way + tex.extras = tex.extras or { gltf = {} } + local g = (tex.extras :: any).gltf + g.sourceExtension = next(handled) + local fb = int(t.source) and images[t.source + 1] + if fb then + g.fallback = { data = fb.data, mime = fb.mime, uri = fb.uri } + end + 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 + end + local r: Types.TextureRef = { texture = info.index + 1, texCoord = int(info.texCoord), scale = if type(info.scale) == "number" then info.scale else nil, strength = if type(info.strength) == "number" then info.strength else nil } + local tt = type(info.extensions) == "table" and info.extensions.KHR_texture_transform + if type(tt) == "table" then + r.transform = { offset = numbers(tt.offset, 2), scale = numbers(tt.scale, 2), rotation = if type(tt.rotation) == "number" then tt.rotation else nil, texCoord = int(tt.texCoord) } + end + return r + end + -- an extension object with every textureInfo (a table with an index, under a key ending in Texture) -> TextureRef + local function convertExt(v: any): any + if type(v) ~= "table" then + return v + end + local out = if Types.isObject(v) or next(v) == nil then Types.object() else {} + for k, x in v do + if type(k) == "string" and string.sub(k, -7) == "Texture" and type(x) == "table" and int(x.index) then + out[k] = texRef(x) + else + out[k] = convertExt(x) + end + end + return out + end + for i, m in arr(doc.materials) do + if type(m) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad material " .. (i - 1)) + end + local mat = Types.Scene.material(str(m.name)) + local pbr = if type(m.pbrMetallicRoughness) == "table" then m.pbrMetallicRoughness else {} + mat.baseColor = numbers(pbr.baseColorFactor, 4) or { 1, 1, 1, 1 } + mat.baseColorTexture = texRef(pbr.baseColorTexture) + mat.metallic = num(pbr.metallicFactor, 1) + mat.roughness = num(pbr.roughnessFactor, 1) + mat.metallicRoughnessTexture = texRef(pbr.metallicRoughnessTexture) + mat.normalTexture = texRef(m.normalTexture) + mat.occlusionTexture = texRef(m.occlusionTexture) + mat.emissive = numbers(m.emissiveFactor, 3) or { 0, 0, 0 } + mat.emissiveTexture = texRef(m.emissiveTexture) + mat.alphaMode = if m.alphaMode == "MASK" then "mask" elseif m.alphaMode == "BLEND" then "blend" else "opaque" + mat.alphaCutoff = num(m.alphaCutoff, 0.5) + mat.doubleSided = m.doubleSided == true + if type(m.extensions) == "table" then + local ext = {} + for k, v in m.extensions do + ext[k] = convertExt(v) + end + mat.extensions = ext + end + local kept = keep(m, mat.extensions and (mat.extensions :: any) or {}) + local pk = keep(pbr, nil) + if pk then + kept = kept or { gltf = {} } + local kk: any = kept + kk.gltf.pbr = pk.gltf + end + 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)) + end + local mesh: Types.Mesh = { name = str(m.name), primitives = {}, weights = if type(m.weights) == "table" then table.clone(m.weights) else nil, extras = keep(m, nil) } + for k, p in arr(m.primitives) do + if type(p) ~= "table" or type(p.attributes) ~= "table" then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: no attributes", i - 1, k - 1)) + end + if type(p.extensions) == "table" and (p.extensions.KHR_draco_mesh_compression or p.extensions.EXT_meshopt_compression) then + return nil, Err.new(Err.UNSUPPORTED, "compressed primitives (Draco / meshopt)") + end + local attrs: { [string]: Types.Accessor } = {} + local count = -1 + for name, ai in p.attributes do + local a = accessor(ai) + if not a then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attribute %s: bad accessor", i - 1, tostring(name))) + end + if count >= 0 and a.count ~= count then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attributes with different counts", i - 1)) + end + count = a.count + attrs[name] = a + end + local mode = MODES[if p.mode == nil then 4 else p.mode] + if not mode then + return nil, Err.new(Err.CORRUPT, "bad primitive mode") + end + local prim: Types.Primitive = { attributes = attrs, mode = mode :: any, material = if int(p.material) and p.material < #scene.materials then p.material + 1 else nil } + if p.indices ~= nil then + local ind = accessor(p.indices) + 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) :: any + for q = 0, ind.count - 1 do + if get(q, 0) >= count then + return nil, Err.new(Err.CORRUPT, "index out of range") + end + end + prim.indices = ind + end + if type(p.targets) == "table" then + local targets = {} + for ti, t in p.targets do + local tt = {} + for name, ai in (if type(t) == "table" then t else {}) do + local a = accessor(ai) + if not a or a.count ~= count then + return nil, Err.new(Err.CORRUPT, "bad morph target accessor") + end + tt[name] = a + end + targets[ti] = tt + end + prim.targets = targets + end + prim.extras = keep(p, nil) + table.insert(mesh.primitives, prim) + 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") + end + if c.type == "orthographic" and type(c.orthographic) == "table" then + local o = c.orthographic + table.insert(scene.cameras, { name = str(c.name), type = "orthographic", xmag = num(o.xmag, 1), ymag = num(o.ymag, 1), znear = num(o.znear, 0), zfar = num(o.zfar, 100) }) + else + local p = if type(c.perspective) == "table" then c.perspective else {} + table.insert(scene.cameras, { name = str(c.name), type = "perspective", yfov = num(p.yfov, 0.8), aspect = if type(p.aspectRatio) == "number" then p.aspectRatio else nil, znear = num(p.znear, 0.01), zfar = if type(p.zfar) == "number" then p.zfar else nil }) + end + end + local lp = type(doc.extensions) == "table" and doc.extensions.KHR_lights_punctual + for _, l in arr(lp and lp.lights) do + if type(l) == "table" then + local spot = if type(l.spot) == "table" then l.spot else {} + table.insert(scene.lights, { + name = str(l.name), + type = if l.type == "spot" or l.type == "point" then l.type else "directional", + color = numbers(l.color, 3) or { 1, 1, 1 }, + intensity = num(l.intensity, 1), + range = if type(l.range) == "number" then l.range else nil, + innerCone = if l.type == "spot" then num(spot.innerConeAngle, 0) else nil, + outerCone = if l.type == "spot" then num(spot.outerConeAngle, math.pi / 4) else nil, + }) + end + end + -- nodes + local nodes = arr(doc.nodes) + for i, n in nodes do + if type(n) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad node " .. (i - 1)) + end + local node: Types.Node = { name = str(n.name), children = {} } + for _, c in arr(n.children) do + if not int(c) or c >= #nodes then + return nil, Err.new(Err.CORRUPT, "node " .. (i - 1) .. ": bad child") + end + table.insert(node.children, c + 1) + end + if int(n.mesh) and n.mesh < #scene.meshes then + node.mesh = n.mesh + 1 + end + if int(n.camera) and n.camera < #scene.cameras then + node.camera = n.camera + 1 + end + if int(n.skin) and n.skin < #arr(doc.skins) then + node.skin = n.skin + 1 + end + node.matrix = numbers(n.matrix, 16) + node.translation = numbers(n.translation, 3) + node.rotation = numbers(n.rotation, 4) + node.scale = numbers(n.scale, 3) + node.weights = if type(n.weights) == "table" then table.clone(n.weights) else nil + local handled = {} + local le = type(n.extensions) == "table" and n.extensions.KHR_lights_punctual + if type(le) == "table" and int(le.light) and le.light < #scene.lights then + node.light = le.light + 1 + handled.KHR_lights_punctual = true + end + node.extras = keep(n, handled) + scene.nodes[i] = node + end + -- a node may have one parent only, and no cycles + local parent: { [number]: number } = {} + for i, node in scene.nodes do + for _, c in node.children do + if parent[c] or c == i then + return nil, Err.new(Err.CORRUPT, "node " .. (c - 1) .. " has two parents or is its own child") + end + parent[c] = i + end + end + for i in scene.nodes do + local seen, p = 0, parent[i] + while p do + seen += 1 + if seen > #scene.nodes then + return nil, Err.new(Err.CORRUPT, "the node hierarchy has a cycle") + end + 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") + end + local joints = {} + for _, j in arr(s.joints) do + if not int(j) or j >= #scene.nodes then + return nil, Err.new(Err.CORRUPT, "skin: bad joint") + end + table.insert(joints, j + 1) + 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") + end + local anim: Types.Animation = { name = str(a.name), channels = {} } + local samplersA = arr(a.samplers) + local skipped = {} + for _, c in arr(a.channels) do + local s = type(c) == "table" and int(c.sampler) and samplersA[c.sampler + 1] + local target = type(c) == "table" and c.target + if not s or type(target) ~= "table" then + return nil, Err.new(Err.CORRUPT, "animation: bad channel") + end + local input, output = accessor(s.input), accessor(s.output) + if not input or not output then + return nil, Err.new(Err.CORRUPT, "animation: bad sampler accessors") + end + local path = target.path + if int(target.node) and target.node < #scene.nodes and (path == "translation" or path == "rotation" or path == "scale" or path == "weights") then + table.insert(anim.channels, { + node = target.node + 1, + path = path, + input = input, + output = output, + interpolation = if s.interpolation == "STEP" or s.interpolation == "CUBICSPLINE" then s.interpolation else "LINEAR", + }) + else + table.insert(skipped, c) -- KHR_animation_pointer and friends + end + end + if #skipped > 0 then + local aa: any = anim + aa.extras = { gltf = { skippedChannels = #skipped } } + end + table.insert(scene.animations, anim) + end + -- scenes + local scenes = arr(doc.scenes) + local list = {} + for _, s in scenes do + local roots = {} + for _, n in arr(type(s) == "table" and s.nodes) do + if int(n) and n < #scene.nodes and not parent[n + 1] then + table.insert(roots, n + 1) + end + end + table.insert(list, { name = type(s) == "table" and str(s.name) or nil, nodes = roots, extras = if type(s) == "table" then keep(s, nil) else nil }) + end + local which = int(doc.scene) or 0 + if list[which + 1] then + scene.roots = list[which + 1].nodes + elseif #list == 0 then + for i in scene.nodes do + if not parent[i] then + table.insert(scene.roots, i) + 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 + if k ~= "KHR_lights_punctual" then + rootExt = rootExt or {} + rootExt[k] = v + end + end + end + scene.meta.up = "y" + scene.meta.unit = 1 + scene.meta.gltf = { + asset = asset, + scenes = list, + scene = if doc.scene ~= nil then which + 1 else nil, + extensionsUsed = doc.extensionsUsed, + extensionsRequired = doc.extensionsRequired, + extensions = rootExt, + extras = doc.extras, + } + return scene, nil +end + +return Read diff --git a/src/Formats/model/gltf/Write.luau b/src/Formats/model/gltf/Write.luau new file mode 100644 index 0000000..473f293 --- /dev/null +++ b/src/Formats/model/gltf/Write.luau @@ -0,0 +1,696 @@ +--!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). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pack = require("@formats/model/gltf/Pack") + +local Write = {} + +local object = Types.object +local CT = { i8 = 5120, u8 = 5121, i16 = 5122, u16 = 5123, u32 = 5125, f32 = 5126, unorm8 = 5121, unorm16 = 5123, snorm8 = 5120, snorm16 = 5122 } +local SIZE = Types.COMPONENT_SIZE +local NORMALIZED = { unorm8 = true, unorm16 = true, snorm8 = true, snorm16 = true } +local MODES = { points = 0, lines = 1, line_loop = 2, line_strip = 3, triangles = 4, triangle_strip = 5, triangle_fan = 6 } +local WRAP = { clamp = 33071, mirror = 33648, ["repeat"] = 10497 } +local MIN_FILTER = { nearest = 9728, linear = 9729, nearest_mipmap_nearest = 9984, linear_mipmap_nearest = 9985, nearest_mipmap_linear = 9986, linear_mipmap_linear = 9987 } +-- attribute types the core spec allows (others need KHR_mesh_quantization) +local CORE = { + POSITION = { f32 = true }, + NORMAL = { f32 = true }, + TANGENT = { f32 = true }, + TEXCOORD = { f32 = true, unorm8 = true, unorm16 = true }, + COLOR = { f32 = true, unorm8 = true, unorm16 = true }, + JOINTS = { u8 = true, u16 = true }, + WEIGHTS = { f32 = true, unorm8 = true, unorm16 = true }, +} + +export type Options = { embedImages: boolean?, binary: boolean? } +export type Out = { doc: any, bin: buffer, images: { { data: buffer, mime: string?, name: string } } } + +local function convert(acc: Types.Accessor, to: string): Types.Accessor + local get = Types.Scene.reader(acc) :: (number, number) -> number + local out = Types.Scene.accessor(nil, to, acc.components, acc.count) + local w = if to == "f32" then buffer.writef32 else buffer.writeu32 + local size = SIZE[to] + for i = 0, acc.count - 1 do + for c = 0, acc.components - 1 do + local v = get(i, c) + if to == "u32" then + v = math.clamp(math.floor(v), 0, 4294967295) + end + w(out.data, (i * acc.components + c) * size, v) + end + end + out.matrix = acc.matrix + out.name = acc.name + return out +end + +local function checkAcc(acc: any, label: string): Err.Err? + if type(acc) ~= "table" or type(acc.data) ~= "buffer" or not SIZE[acc.type] or type(acc.count) ~= "number" or type(acc.components) ~= "number" then + return Err.new(Err.ARG, label .. ": not an accessor") + end + if acc.components < 1 or acc.components > 16 or buffer.len(acc.data) < acc.count * acc.components * SIZE[acc.type] then + return Err.new(Err.ARG, label .. ": data is smaller than count x components") + end + return nil +end + +function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) + local binary = opts and opts.binary or false + local embedImages = not (opts and opts.embedImages == false) + local doc: { [string]: any } = object() + local used: { [string]: boolean } = {} + local required: { [string]: boolean } = {} + local bin = Bytes.writer(65536) + local views: { any } = {} + local accessors: { any } = {} + local accIndex: { [any]: number } = {} + local failure: Err.Err? = nil + + local function view(data: buffer, length: number, target: number?, stride: number?): number + local pad = (4 - bin:tell() % 4) % 4 + bin:fill(0, pad) + local v = object() + v.buffer = 0 + v.byteOffset = bin:tell() + v.byteLength = length + v.target = target + v.byteStride = stride + bin:bytes(data, 0, length) + table.insert(views, v) + 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 + return known + end + local err = checkAcc(acc, attribute or usage) + if err then + failure = failure or err + return 0 + end + local a = acc + if usage == "index" then + if a.type ~= "u8" and a.type ~= "u16" and a.type ~= "u32" then + a = convert(a, "u32") + end + elseif a.type == "f64" or a.type == "i32" or a.type == "u32" and usage ~= "index" and attribute ~= nil then + a = convert(a, "f32") + end + if attribute then + local kind = string.match(attribute, "^([A-Z]+)_%d+$") or attribute + local core = CORE[kind] + if core and not core[a.type] then + used.KHR_mesh_quantization = true + required.KHR_mesh_quantization = true + end + end + local size = SIZE[a.type] + local comps = a.components + local isMat = a.matrix == true and (comps == 4 or comps == 9 or comps == 16) + local cols = if isMat then math.sqrt(comps) else 1 + local colBytes = (comps // cols) * size + local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes + local elem = comps * size + local padded = cols * colStride + local stride = padded + local byteStride: number? = nil + if usage == "vertex" and padded % 4 ~= 0 then + stride = (padded + 3) // 4 * 4 + byteStride = stride + end + local data = a.data + local length = a.count * stride + if stride ~= elem then + data = buffer.create(length) + Pack.scatter(data, 0, a.data, a.count, elem, stride, cols, colBytes, colStride) + end + local g = object() + g.bufferView = view(data, length, if usage == "vertex" then 34962 elseif usage == "index" then 34963 else nil, byteStride) + g.componentType = CT[a.type] + g.normalized = if NORMALIZED[a.type] then true else nil + g.count = a.count + g.type = if isMat then ({ [4] = "MAT2", [9] = "MAT3", [16] = "MAT4" })[comps] else ({ "SCALAR", "VEC2", "VEC3", "VEC4" })[comps] + g.name = acc.name + if not g.type then + failure = failure or Err.new(Err.ARG, (attribute or usage) .. ": " .. comps .. " components is not a glTF type") + 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) + for i = 0, a.count - 1 do + for c = 1, comps do + local v = get(i, c - 1) + if v < lo[c] then + lo[c] = v + end + if v > hi[c] then + hi[c] = v + end + end + end + if a.count > 0 then + g.min, g.max = lo, hi + end + end + table.insert(accessors, g) + local index = #accessors - 1 + accIndex[acc] = index + 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 + return + end + if saved.extras ~= nil then + g.extras = saved.extras + end + if type(saved.extensions) == "table" then + g.extensions = g.extensions or object() + for k, v in saved.extensions do + if g.extensions[k] == nil then + g.extensions[k] = v + used[k] = true + end + end + end + end + + -- images, samplers, textures + local images: { any } = {} + local imageOut: { { data: buffer, mime: string?, name: string } } = {} + local imageIndex: { [any]: number } = {} + local function image(data: buffer?, mime: string?, uri: string?, name: string?): number? + local key: any = data or uri + if key == nil then + return nil + end + if imageIndex[key] then + return imageIndex[key] + end + local im = object() + im.name = name + if data then + if binary then + 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.mimeType = mime + table.insert(imageOut, { data = data, mime = mime, name = im.uri }) + else + im.uri = uri or ("\0file" .. (#images + 1)) + im.mimeType = mime + table.insert(imageOut, { data = data, mime = mime, name = im.uri }) + end + else + im.uri = uri + im.mimeType = mime + end + table.insert(images, im) + imageIndex[key] = #images - 1 + return #images - 1 + end + local samplers: { any } = {} + local samplerIndex: { [string]: number } = {} + local function sampler(s: Types.Sampler?): number? + if type(s) ~= "table" then + return nil + end + local g = object() + g.wrapS = if s.wrapS then WRAP[s.wrapS] else nil + g.wrapT = if s.wrapT then WRAP[s.wrapT] else nil + g.magFilter = if s.filter == "nearest" then 9728 elseif s.filter == "linear" then 9729 else nil + g.minFilter = if s.minFilter then MIN_FILTER[s.minFilter] else nil + local key = string.format("%s/%s/%s/%s", tostring(g.wrapS), tostring(g.wrapT), tostring(g.magFilter), tostring(g.minFilter)) + if samplerIndex[key] == nil then + table.insert(samplers, g) + samplerIndex[key] = #samplers - 1 + end + return samplerIndex[key] + end + local textures: { any } = {} + for i, t in scene.textures or {} do + if type(t) ~= "table" then + return nil, Err.new(Err.ARG, "texture " .. i .. ": not a table") + end + local g = object() + g.name = t.name + g.sampler = sampler(t.sampler) + local saved = type(t.extras) == "table" and type(t.extras.gltf) == "table" and t.extras.gltf or nil + local srcExt = saved and saved.sourceExtension + local img = image(t.data, t.mime, t.uri, t.name) + if srcExt and img then + g.extensions = object() + local e = object() + e.source = img + g.extensions[srcExt] = e + used[srcExt] = true + local fb = saved.fallback + if type(fb) == "table" then + g.source = image(fb.data, fb.mime, fb.uri, nil) + end + if g.source == nil then + required[srcExt] = true + end + else + g.source = img + end + restore(g, t.extras) + table.insert(textures, g) + end + local function texInfo(r: any, kind: string?): any + if type(r) ~= "table" or type(r.texture) ~= "number" or not textures[r.texture] then + return nil + end + local g = object() + g.index = r.texture - 1 + if r.texCoord and r.texCoord ~= 0 then + g.texCoord = r.texCoord + end + if kind == "normal" and r.scale ~= nil and r.scale ~= 1 then + g.scale = r.scale + end + if kind == "occlusion" and r.strength ~= nil and r.strength ~= 1 then + g.strength = r.strength + end + if type(r.transform) == "table" then + local tt = object() + tt.offset = r.transform.offset + tt.scale = r.transform.scale + tt.rotation = r.transform.rotation + tt.texCoord = r.transform.texCoord + g.extensions = object() + g.extensions.KHR_texture_transform = tt + used.KHR_texture_transform = true + end + return g + end + local function extValue(v: any, key: string?): any + if type(v) ~= "table" then + return v + end + if key and string.sub(key, -7) == "Texture" and type(v.texture) == "number" then + return texInfo(v, if key == "normalTexture" or key == "clearcoatNormalTexture" then "normal" else nil) + end + local out = if Types.isObject(v) or next(v) == nil then object() else {} + for k, x in v do + out[k] = extValue(x, if type(k) == "string" then k else nil) + end + return out + end + -- materials + local materials: { any } = {} + for i, m in scene.materials or {} do + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "material " .. i .. ": not a table") + end + local g = object() + g.name = m.name + local pbr = object() + local bc = m.baseColor or { 1, 1, 1, 1 } + if bc[1] ~= 1 or bc[2] ~= 1 or bc[3] ~= 1 or (bc[4] or 1) ~= 1 then + pbr.baseColorFactor = { bc[1], bc[2], bc[3], bc[4] or 1 } + end + pbr.baseColorTexture = texInfo(m.baseColorTexture) + if m.metallic ~= nil and m.metallic ~= 1 then + pbr.metallicFactor = m.metallic + end + if m.roughness ~= nil and m.roughness ~= 1 then + pbr.roughnessFactor = m.roughness + end + pbr.metallicRoughnessTexture = texInfo(m.metallicRoughnessTexture) + local saved = type(m.extras) == "table" and type(m.extras.gltf) == "table" and m.extras.gltf or nil + if saved and saved.pbr then + restore(pbr, { gltf = saved.pbr }) + end + g.pbrMetallicRoughness = pbr + g.normalTexture = texInfo(m.normalTexture, "normal") + g.occlusionTexture = texInfo(m.occlusionTexture, "occlusion") + g.emissiveTexture = texInfo(m.emissiveTexture) + local em = m.emissive or { 0, 0, 0 } + if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 then + g.emissiveFactor = { em[1], em[2], em[3] } + end + if m.alphaMode == "mask" then + g.alphaMode = "MASK" + if m.alphaCutoff ~= nil and m.alphaCutoff ~= 0.5 then + g.alphaCutoff = m.alphaCutoff + end + elseif m.alphaMode == "blend" then + g.alphaMode = "BLEND" + end + if m.doubleSided then + g.doubleSided = true + end + if type(m.extensions) == "table" then + g.extensions = object() + for k, v in m.extensions do + g.extensions[k] = extValue(v, nil) + used[k] = true + end + end + 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 + return nil, Err.new(Err.ARG, "mesh " .. i .. ": no primitives") + end + local g = object() + g.name = mesh.name + g.primitives = {} + for k, p in mesh.primitives do + if type(p) ~= "table" or type(p.attributes) ~= "table" or not p.attributes.POSITION then + return nil, Err.new(Err.ARG, string.format("mesh %d primitive %d: no POSITION", i, k)) + end + local gp = object() + gp.attributes = object() + local names = {} + for name in p.attributes do + table.insert(names, name) + end + table.sort(names) + for _, name in names do + gp.attributes[name] = accessor(p.attributes[name], "vertex", name) + end + 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 + local geti = if indices then Types.Scene.reader(indices) else nil + if not faces or not getf or (indices and not geti) then + return nil, Err.new(Err.ARG, "polygons without faces") + end + local list = {} + local at = 0 + for f = 0, faces.count - 1 do + local c = getf(f, 0) + if at + c > n then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + for a = 1, c - 2 do + for _, j in { at, at + a, at + a + 1 } do + table.insert(list, if geti then geti(j, 0) else j) + end + end + at += c + end + local ib = buffer.create(#list * 4) + for q, v in list do + buffer.writeu32(ib, (q - 1) * 4, v) + end + indices = Types.Scene.accessor(ib, "u32", 1, #list) + mode = "triangles" + end + if MODES[mode] == nil then + return nil, Err.new(Err.ARG, "unknown primitive mode " .. tostring(mode)) + end + if indices then + gp.indices = accessor(indices, "index", nil) + end + if mode ~= "triangles" then + gp.mode = MODES[mode] + end + if type(p.material) == "number" and materials[p.material] then + gp.material = p.material - 1 + end + if type(p.targets) == "table" and #p.targets > 0 then + gp.targets = {} + for _, t in p.targets do + local gt = object() + local tn = {} + for name in t do + table.insert(tn, name) + end + table.sort(tn) + for _, name in tn do + gt[name] = accessor(t[name], "vertex", nil) + end + table.insert(gp.targets, gt) + end + end + restore(gp, p.extras) + table.insert(g.primitives, gp) + end + g.weights = mesh.weights + restore(g, mesh.extras) + table.insert(meshes, g) + end + -- cameras, lights + local cameras: { any } = {} + for _, c in scene.cameras or {} do + local g = object() + g.name = c.name + g.type = c.type + local p = object() + if c.type == "orthographic" then + p.xmag, p.ymag, p.znear, p.zfar = c.xmag or 1, c.ymag or 1, c.znear or 0, c.zfar or 100 + g.orthographic = p + else + g.type = "perspective" + p.yfov, p.aspectRatio, p.znear, p.zfar = c.yfov or 0.8, c.aspect, c.znear or 0.01, c.zfar + g.perspective = p + end + table.insert(cameras, g) + end + local lights: { any } = {} + for _, l in scene.lights or {} do + local g = object() + g.name = l.name + g.type = l.type + if l.color and (l.color[1] ~= 1 or l.color[2] ~= 1 or l.color[3] ~= 1) then + g.color = { l.color[1], l.color[2], l.color[3] } + end + if l.intensity ~= nil and l.intensity ~= 1 then + g.intensity = l.intensity + end + if l.type ~= "directional" then + g.range = l.range + end + if l.type == "spot" then + local s = object() + s.innerConeAngle = if l.innerCone and l.innerCone ~= 0 then l.innerCone else nil + s.outerConeAngle = if l.outerCone and math.abs(l.outerCone - math.pi / 4) > 1e-12 then l.outerCone else nil + g.spot = s + end + table.insert(lights, g) + end + -- nodes + local nodes: { any } = {} + local nodeCount = #(scene.nodes or {}) + for i, n in scene.nodes or {} do + if type(n) ~= "table" then + return nil, Err.new(Err.ARG, "node " .. i .. ": not a table") + end + local g = object() + g.name = n.name + if n.children and #n.children > 0 then + g.children = {} + for _, c in n.children do + if type(c) ~= "number" or c < 1 or c > nodeCount then + return nil, Err.new(Err.ARG, "node " .. i .. ": bad child") + end + table.insert(g.children, c - 1) + end + end + if n.mesh and meshes[n.mesh] then + g.mesh = n.mesh - 1 + end + if n.camera and cameras[n.camera] then + g.camera = n.camera - 1 + end + if n.skin and scene.skins[n.skin] then + g.skin = n.skin - 1 + end + if n.matrix then + local ident = true + for k = 1, 16 do + if n.matrix[k] ~= Types.Scene.IDENTITY[k] then + ident = false + end + end + if not ident then + g.matrix = n.matrix + end + else + g.translation, g.rotation, g.scale = n.translation, n.rotation, n.scale + end + g.weights = n.weights + if n.light and lights[n.light] then + g.extensions = object() + local le = object() + le.light = n.light - 1 + g.extensions.KHR_lights_punctual = le + used.KHR_lights_punctual = true + end + restore(g, n.extras) + table.insert(nodes, g) + end + -- skins + local skins: { any } = {} + for _, s in scene.skins or {} do + local g = object() + g.name = s.name + g.joints = {} + for _, j in s.joints or {} do + table.insert(g.joints, j - 1) + end + if s.inverseBindMatrices then + local ibm = s.inverseBindMatrices + if ibm.matrix == nil and ibm.components == 16 then + ibm.matrix = true + end + g.inverseBindMatrices = accessor(ibm, "other", nil) + end + if s.skeleton then + g.skeleton = s.skeleton - 1 + end + table.insert(skins, g) + end + -- animations + local animations: { any } = {} + for _, a in scene.animations or {} do + local g = object() + g.name = a.name + g.channels, g.samplers = {}, {} + local samplerOf: { [string]: number } = {} + for _, c in a.channels or {} do + local input = accessor(c.input, "input", nil) + local output = accessor(c.output, "other", nil) + local key = input .. "/" .. output .. "/" .. tostring(c.interpolation) + if samplerOf[key] == nil then + local s = object() + s.input, s.output = input, output + if c.interpolation and c.interpolation ~= "LINEAR" then + s.interpolation = c.interpolation + end + table.insert(g.samplers, s) + samplerOf[key] = #g.samplers - 1 + end + local ch = object() + ch.sampler = samplerOf[key] + ch.target = object() + ch.target.node = c.node - 1 + ch.target.path = c.path + table.insert(g.channels, ch) + end + table.insert(animations, g) + end + if failure then + return nil, failure + end + -- scenes: the original list (meta.gltf.scenes) when it is there, else the roots + local meta = if type(scene.meta) == "table" then scene.meta else {} + local mg = type(meta.gltf) == "table" and meta.gltf or {} + local scenes = {} + if type(mg.scenes) == "table" and #mg.scenes > 0 then + for _, s in mg.scenes do + local g = object() + g.name = s.name + g.nodes = {} + for _, n in s.nodes or {} do + if nodes[n] then + table.insert(g.nodes, n - 1) + end + end + 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 = {} + for _, r in scene.roots or {} do + table.insert(scenes[which].nodes, r - 1) + end + end + doc.scene = (mg.scene or 1) - 1 + else + local g = object() + g.nodes = {} + for _, r in scene.roots or {} do + table.insert(g.nodes, r - 1) + end + table.insert(scenes, g) + doc.scene = 0 + end + local asset = object() + asset.version = "2.0" + asset.generator = "formats-luau" + if type(mg.asset) == "table" then + asset.copyright = mg.asset.copyright + asset.minVersion = mg.asset.minVersion + 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 + doc.extensions[k] = v + used[k] = true + end + end + if #lights > 0 then + doc.extensions = doc.extensions or object() + local lp = object() + lp.lights = lights + doc.extensions.KHR_lights_punctual = lp + used.KHR_lights_punctual = true + end + doc.extras = mg.extras + local function list(t: { [string]: boolean }): { string }? + local out = {} + for k in t do + table.insert(out, k) + end + table.sort(out) + return if #out > 0 then out else nil + end + -- the source's required extensions that are still used stay required + for _, e in (if type(mg.extensionsRequired) == "table" then mg.extensionsRequired else {}) do + if used[e] then + required[e] = true + end + end + doc.extensionsUsed = list(used) + doc.extensionsRequired = list(required) + doc.scenes = scenes + doc.nodes = if #nodes > 0 then nodes else nil + doc.meshes = if #meshes > 0 then meshes else nil + doc.materials = if #materials > 0 then materials else nil + doc.textures = if #textures > 0 then textures else nil + doc.images = if #images > 0 then images else nil + doc.samplers = if #samplers > 0 then samplers else nil + doc.cameras = if #cameras > 0 then cameras else nil + doc.skins = if #skins > 0 then skins else nil + doc.animations = if #animations > 0 then animations else nil + doc.accessors = if #accessors > 0 then accessors else nil + doc.bufferViews = if #views > 0 then views else nil + return { doc = doc, bin = bin:finish(), images = imageOut }, nil +end + +return Write diff --git a/src/Formats/model/gltf/init.luau b/src/Formats/model/gltf/init.luau new file mode 100644 index 0000000..3f533a0 --- /dev/null +++ b/src/Formats/model/gltf/init.luau @@ -0,0 +1,248 @@ +--!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). +-- Not supported: Draco (KHR_draco_mesh_compression) and meshopt (EXT_meshopt_compression) compressed primitives +-- (UNSUPPORTED), KHR_animation_pointer channels (skipped and counted in the animation's extras). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Json = require("@formats/codecs/Json") +local Base64 = require("@formats/codecs/Base64") +local Read = require("@formats/model/gltf/Read") +local Write = require("@formats/model/gltf/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Gltf = { + name = "gltf", + category = "model", + extensions = { "gltf", "glb" }, + mime = { "model/gltf+json", "model/gltf-binary" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Base64" }, + caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, +} + +-- ------------------------------------------------------------------------------------------------ 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) +} +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) + files: { [string]: any }?, -- receives .bin and images with external = true + name: string?, -- the destination's file name (names the external files) + embedImages: boolean?, -- default true (false with external = true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local GLB_MAGIC = 0x46546C67 -- "glTF" +local CHUNK_JSON = 0x4E4F534A +local CHUNK_BIN = 0x004E4942 + +-- ------------------------------------------------------------------------------------------------ sniff +function Gltf.sniff(r: Bytes.Reader): number + if r:peek(4) == "glTF" then + return 1 + end + local head = r:peek(1024) + local s = string.gsub(head, "^\239\187\191", "") + if string.find(s, "^%s*{") and string.find(s, "\"asset\"", 1, true) then + return 0.9 + end + if string.find(s, "^%s*{") and (string.find(s, "\"accessors\"", 1, true) or string.find(s, "\"bufferViews\"", 1, true)) then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?): Read.Fetch + return function(uri: string): buffer? + if not opts then + return nil + end + local decoded = string.gsub(uri, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[decoded] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil + end +end + +-- the 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 + return nil, nil, r.err + end + if magic ~= GLB_MAGIC then + return nil, nil, Err.new(Err.CORRUPT, "bad GLB magic") + end + if version ~= 2 then + return nil, nil, Err.new(Err.UNSUPPORTED, "GLB version " .. version) + end + if length > r:size() then + return nil, nil, Err.new(Err.TRUNCATED, "the GLB is shorter than its header says", r.base + 8) + end + local json: string? = nil + local bin: buffer? = nil + while r:tell() + 8 <= length do + local clen, ctype = r:u32le(), r:u32le() + if clen > length - r:tell() then + return nil, nil, Err.new(Err.TRUNCATED, "a GLB chunk runs past the end", r.base + r:tell() - 8) + end + if ctype == CHUNK_JSON and json == nil then + json = r:string(clen) + elseif ctype == CHUNK_BIN and bin == nil and json ~= nil then + bin = r:bytes(clen) + else + r:skip(clen) + end + if r.err then + return nil, nil, r.err + end + end + if not json then + return nil, nil, Err.new(Err.CORRUPT, "GLB without a JSON chunk") + end + return json, bin, nil +end + +function Gltf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local binary = r:peek(4) == "glTF" + local text: string?, bin: buffer? + if binary then + local t, b, err = glb(r) + if not t then + return nil, err + end + text, bin = t, b + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + local doc, jerr = Json.decode(text :: string) + if doc == nil then + return nil, jerr + end + local scene, err = Read.scene(doc, bin, fetcher(opts), opts) + if not scene then + return nil, err + end + scene.meta.source = { format = "gltf", binary = binary, generator = type(doc.asset) == "table" and doc.asset.generator or nil } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif" } + +function Gltf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local binary = opts and (opts.binary or opts.format == "glb") or false + local external = opts and opts.external == true and type(opts.files) == "table" and not binary + local embedImages = if opts and opts.embedImages ~= nil then opts.embedImages else not external + local out, err = Write.build(scene, { binary = binary, embedImages = embedImages }) + if not out then + return nil, err + end + 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 + if type(im.uri) == "string" and string.sub(im.uri, 1, 1) == "\0" then + for _, o in out.images do + if o.name == im.uri then + if string.sub(im.uri, 1, 6) == "\0image" or type(files) ~= "table" then + im.uri = Base64.dataUri(o.data, o.mime or "image/png") + else + n += 1 + local fname = base .. "_" .. n .. "." .. (EXT[o.mime or ""] or "png") + files[fname] = o.data + im.uri = fname + end + break + end + end + elseif type(im.uri) == "string" and type(files) == "table" and not embedImages then + for _, o in out.images do + if o.name == im.uri then + files[im.uri] = o.data + end + end + end + end + end + local binLen = buffer.len(out.bin) + if binLen > 0 then + local b = Types.object() + b.byteLength = binLen + if not binary then + if external then + local fname = base .. ".bin" + b.uri = fname + local ff: any = files + ff[fname] = out.bin + else + b.uri = Base64.dataUri(out.bin, "application/octet-stream") + end + end + doc.buffers = { b } + end + local text, jerr = Json.encode(doc, if binary then nil else { indent = 2 }) + if not text then + return nil, Err.new(Err.ARG, "JSON: " .. tostring(jerr and jerr.message or jerr)) + end + if not binary then + return buffer.fromstring(text :: string), nil + end + local jpad = (4 - #(text :: string) % 4) % 4 + local bpad = (4 - binLen % 4) % 4 + local w = Bytes.writer(12 + 8 + #(text :: string) + jpad + 8 + binLen + bpad) + w:u32le(GLB_MAGIC) + w:u32le(2) + local lenAt = w:tell() + w:u32le(0) + w:u32le(#(text :: string) + jpad) + w:u32le(CHUNK_JSON) + w:string(text :: string) + w:string(string.rep(" ", jpad)) + if binLen > 0 then + w:u32le(binLen + bpad) + w:u32le(CHUNK_BIN) + w:bytes(out.bin) + w:fill(0, bpad) + end + w:setU32le(lenAt, w:tell()) + return w:finish(), nil +end + +return Gltf diff --git a/src/Formats/model/obj/Mtl.luau b/src/Formats/model/obj/Mtl.luau new file mode 100644 index 0000000..64f18de --- /dev/null +++ b/src/Formats/model/obj/Mtl.luau @@ -0,0 +1,294 @@ +--!strict +-- model/obj/Mtl: Wavefront .mtl material libraries (Paul Bourke's MTL spec + the common PBR extension: Pr, Pm, Ps, Pc, +-- Pcr, aniso, anisor, Ke, map_Pr, map_Pm, map_Ke, norm). parse(text) -> { name -> { statement -> values } } keeping +-- every statement; toMaterial maps one onto the Scene Material (glTF PBR, Phong values in extras.obj); write is the +-- reverse (from extras.obj when present, else from the PBR fields). +local Types = require("@formats/Types") + +local Mtl = {} + +export type Map = { file: string, options: { [string]: { string } } } -- -o / -s / -bm / -clamp / ... with their values +export type Entry = { name: string, values: { [string]: { number } }, maps: { [string]: Map }, order: { string } } + +-- the number of arguments of each texture map option (Bourke): -o / -s / -t take 1..3 numbers +local OPT_ARGS = { blendu = 1, blendv = 1, cc = 1, clamp = 1, mm = 2, bm = 1, boost = 1, texres = 1, imfchan = 1, type = 1 } +local MAPS = { + map_Ka = true, map_Kd = true, map_Ks = true, map_Ke = true, map_Ns = true, map_d = true, map_Tr = true, + map_bump = true, bump = true, map_Bump = true, disp = true, decal = true, refl = true, norm = true, map_Pr = true, + map_Pm = true, map_Ps = true, map_Pc = true, map_Pcr = true, map_RMA = true, map_ORM = true, map_aniso = true, +} +Mtl.MAPS = MAPS + +local function parseMap(args: { string }): Map + local opts: { [string]: { string } } = {} + local i = 1 + while i <= #args and string.sub(args[i], 1, 1) == "-" and tonumber(args[i]) == nil do + local key = string.sub(args[i], 2) + local vals = {} + i += 1 + local n = OPT_ARGS[key] + if n then + for _ = 1, n do + if i <= #args then + table.insert(vals, args[i]) + i += 1 + end + end + else + -- -o / -s / -t: up to three numbers + while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do + table.insert(vals, args[i]) + i += 1 + end + end + opts[key] = vals + end + -- the file name is the rest (it may contain spaces) + local file = table.concat(args, " ", i) + return { file = file, options = opts } +end + +-- parse(text) -> { Entry } in file order +function Mtl.parse(text: string): { Entry } + local out: { Entry } = {} + local cur: Entry? = nil + for line in string.gmatch(text, "[^\r\n]+") do + local l = string.gsub(line, "#.*$", "") + local words = {} + for w in string.gmatch(l, "%S+") do + table.insert(words, w) + end + local key = words[1] + if key == "newmtl" then + cur = { name = table.concat(words, " ", 2), values = {}, maps = {}, order = {} } + table.insert(out, cur :: Entry) + elseif key and cur then + local e = cur :: Entry + local args = table.move(words, 2, #words, 1, {}) + if MAPS[key] then + e.maps[key] = parseMap(args) + table.insert(e.order, key) + else + local nums = {} + for _, a in args do + local v = tonumber(a) + if v == nil then + nums = nil :: any + break + end + table.insert(nums, v) + end + if nums then + if e.values[key] == nil then + table.insert(e.order, key) + end + e.values[key] = nums + end + end + end + end + return out +end + +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", gif = "image/gif", bmp = "image/bmp", tga = "image/x-tga", tif = "image/tiff", tiff = "image/tiff", dds = "image/vnd-ms.dds", ktx2 = "image/ktx2", exr = "image/x-exr", hdr = "image/vnd.radiance" } +function Mtl.mime(file: string): string? + local ext = string.match(file, "%.([%w]+)$") + return if ext then MIME[string.lower(ext)] else nil +end + +-- toMaterial(entry, texture) -> Material: texture(map) returns the scene texture index for a map +function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material + local m = Types.Scene.material(e.name) + local v = e.values + local kd = v.Kd + if kd and #kd >= 3 then + m.baseColor = { kd[1], kd[2], kd[3], 1 } + end + local d = if v.d then v.d[1] elseif v.Tr then 1 - v.Tr[1] else 1 + m.baseColor[4] = d + if d < 1 then + m.alphaMode = "blend" + end + local ke = v.Ke + if ke and #ke >= 3 then + m.emissive = { ke[1], ke[2], ke[3] } + end + m.metallic = if v.Pm then v.Pm[1] else 0 + if v.Pr then + m.roughness = v.Pr[1] + elseif v.Ns then + m.roughness = math.clamp(math.sqrt(2 / (math.max(v.Ns[1], 0) + 2)), 0, 1) + end + local function ref(key: string): Types.TextureRef? + local map = e.maps[key] + if not map or map.file == "" then + return nil + end + local r: Types.TextureRef = { texture = texture(map) } + local o, s = map.options.o, map.options.s + if o or s then + r.transform = { + offset = if o then { tonumber(o[1]) or 0, tonumber(o[2]) or 0 } else nil, + scale = if s then { tonumber(s[1]) or 1, tonumber(s[2]) or 1 } else nil, + } + end + if map.options.bm then + r.scale = tonumber(map.options.bm[1]) + end + return r + end + m.baseColorTexture = ref("map_Kd") + m.emissiveTexture = ref("map_Ke") + m.normalTexture = ref("norm") or ref("map_bump") or ref("bump") or ref("map_Bump") + m.metallicRoughnessTexture = ref("map_ORM") or ref("map_RMA") + if m.emissiveTexture and not ke then + m.emissive = { 1, 1, 1 } + end + -- everything else as it was, for the writer and for Phong renderers + local extra: { [string]: any } = {} + for k, vals in v do + extra[k] = vals + end + local maps: { [string]: any } = {} + for k, map in e.maps do + maps[k] = { file = map.file, options = map.options, texture = texture(map) } + end + m.extras = { obj = { values = extra, maps = maps, order = e.order } } + return m +end + +local function num(v: number): string + if v == math.floor(v) and math.abs(v) < 1e15 then + return string.format("%d", v) + end + for _, f in { "%.6g", "%.9g", "%.17g" } do + local s = string.format(f, v) + if tonumber(s) == v then + return s + end + end + return string.format("%.17g", v) +end +Mtl.num = num + +-- write(materials, name, textureFile) -> MTL text. textureFile(index) -> the file name a map refers to. +function Mtl.write(materials: { Types.Material }, names: { string }, textureFile: (number) -> string?): string + local out = { "# written by formats-luau" } + for i, m in materials do + table.insert(out, "") + table.insert(out, "newmtl " .. names[i]) + local saved = m.extras and m.extras.obj + local values: { [string]: { number } } = {} + local maps: { [string]: any } = {} + local order: { string } = {} + if type(saved) == "table" and type(saved.values) == "table" then + for k, vals in saved.values do + values[k] = vals + end + for k, mp in saved.maps or {} do + maps[k] = mp + end + order = table.clone(saved.order or {}) + end + -- the PBR fields win over the saved Phong values they map to + local bc = m.baseColor or { 1, 1, 1, 1 } + values.Kd = { bc[1], bc[2], bc[3] } + if (bc[4] or 1) < 1 or values.d then + values.d = { bc[4] or 1 } + values.Tr = nil + end + local em = m.emissive or { 0, 0, 0 } + if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 or values.Ke then + values.Ke = { em[1], em[2], em[3] } + end + if not (saved and saved.values and saved.values.Ns and not saved.values.Pr) then + values.Pr = { m.roughness } + end + if m.metallic ~= 0 or values.Pm then + values.Pm = { m.metallic } + end + local function setMap(key: string, ref: Types.TextureRef?) + if ref then + local file = textureFile(ref.texture) + if file then + local prev = maps[key] + local options = if prev and prev.texture == ref.texture then prev.options else {} + options = table.clone(options or {}) + if ref.transform then + if ref.transform.offset then + options.o = { num(ref.transform.offset[1]), num(ref.transform.offset[2]) } + end + if ref.transform.scale then + options.s = { num(ref.transform.scale[1]), num(ref.transform.scale[2]) } + end + end + if ref.scale and key ~= "map_Kd" then + options.bm = { num(ref.scale) } + end + maps[key] = { file = file, options = options, texture = ref.texture } + end + end + end + setMap("map_Kd", m.baseColorTexture) + setMap("map_Ke", m.emissiveTexture) + if m.normalTexture and not maps.map_bump and not maps.bump and not maps.map_Bump then + setMap("norm", m.normalTexture) + end + setMap("map_ORM", m.metallicRoughnessTexture) + -- the saved order first, then the rest sorted + local keys = {} + local seen = {} + for _, k in order do + if (values[k] or maps[k]) and not seen[k] then + table.insert(keys, k) + seen[k] = true + end + end + local rest = {} + for k in values do + if not seen[k] then + table.insert(rest, k) + end + end + for k in maps do + if not seen[k] and not values[k] then + table.insert(rest, k) + end + end + table.sort(rest) + for _, k in rest do + seen[k] = true + table.insert(keys, k) + end + for _, k in keys do + local mp = maps[k] + if mp and type(mp.file) == "string" then + local file = if type(mp.texture) == "number" then (textureFile(mp.texture) or mp.file) else mp.file + local parts = { k } + local okeys = {} + for ok in mp.options or {} do + table.insert(okeys, ok) + end + table.sort(okeys) + for _, ok in okeys do + table.insert(parts, "-" .. ok) + for _, ov in mp.options[ok] do + table.insert(parts, tostring(ov)) + end + end + table.insert(parts, file) + table.insert(out, table.concat(parts, " ")) + elseif values[k] then + local parts = { k } + for _, x in values[k] do + table.insert(parts, num(x)) + end + table.insert(out, table.concat(parts, " ")) + end + end + end + table.insert(out, "") + return table.concat(out, "\n") +end + +return Mtl diff --git a/src/Formats/model/obj/init.luau b/src/Formats/model/obj/init.luau new file mode 100644 index 0000000..f39a894 --- /dev/null +++ b/src/Formats/model/obj/init.luau @@ -0,0 +1,762 @@ +--!strict +-- model/obj: Wavefront OBJ (+ MTL), from Paul Bourke's OBJ / MTL specifications and what Blender / Maya / assimp +-- write. Supports: v (with the common "v x y z r g b" vertex colour extension), vt, vn, f with every index form +-- (v, v/vt, v//vn, v/vt/vn, negative = relative), l, p, o / g (nodes), usemtl / mtllib (materials: Phong + the PBR +-- extension, texture maps with -o / -s / -bm options; texture images stay encoded bytes or file names, see Types), line +-- continuations, comments. n-gons are fan-triangulated by default (opts.triangulate = false keeps them as "polygons", +-- MeshOps.triangulate ear-clips concave ones). TEXCOORD_0 is flipped to glTF's top-left origin (opts.flipV = false +-- keeps OBJ's). +-- Nodes: one per object (o); groups (g) inside an object become child nodes; files without o: one root node per group. +-- Each node has a mesh with one primitive per material. Vertices are unwelded per (v, vt, vn) combination. +-- Not supported: free-form geometry (curv, surf, ...: skipped and counted in meta.source.skipped), smoothing groups +-- (s: kept per node in extras.obj.smoothing, not used to compute normals). +-- encode: every mesh primitive of the scene baked into world space, one o per node; materials into a .mtl (written to +-- opts.files[.mtl] when opts.files is a table, see Types), embedded texture bytes into opts.files too. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Mtl = require("@formats/model/obj/Mtl") + +-- ------------------------------------------------------------------------------------------------ contract +local Obj = { + name = "obj", + category = "model", + extensions = { "obj" }, + mime = { "model/obj" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) + mtl: (string | buffer)?, -- the material library text, when not found through resolve / files + resolve: ((uri: string) -> any)?, -- reads mtllib / texture files (the api sets it for paths) + files: { [string]: any }?, -- or: the other files by name + maxVertices: number?, -- refuse more v / vt / vn / corners (default 2^25) +} +export type EncodeOptions = { + name: string?, -- the destination file name: the .mtl is named after it (default "model.mtl") + mtlName: string?, -- the .mtl file name (overrides name) + files: { [string]: any }?, -- receives the .mtl and embedded textures + flipV: boolean?, -- default true (the inverse of decode) + normals: boolean?, -- write vn (default true when the primitives have NORMAL) + texcoords: boolean?, -- write vt (default true when the primitives have TEXCOORD_0) + colors: boolean?, -- write vertex colours after v (default true when COLOR_0 exists) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Obj.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.find(head, "\0", 1, true) then + return 0 + end + if string.find(head, "^%s*v%s+[%-%d%.]") or string.find(head, "\n%s*v%s+[%-%d%.]") then + return 0.6 + end + if string.find(head, "^#") and (string.find(head, "\nmtllib ") or string.find(head, "\no ") or string.find(head, "\ng ")) then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetch(opts: DecodeOptions?, uri: string): string? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "buffer" then + return buffer.tostring(v) + elseif type(v) == "string" then + return v + end + return nil +end + +type Prim = { + material: string?, + mode: string, + cv: { number }, -- per corner: position index (0-based), texcoord index (-1 none), normal index (-1 none) + ct: { number }, + cn: { number }, + faces: { number }, -- corners per face (polygons / lines) + hasT: boolean, + hasN: boolean, +} +type Section = { object: string?, group: string?, prims: { Prim }, byKey: { [string]: Prim }, smoothing: string? } + +function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local maxV = opts and opts.maxVertices or 2 ^ 25 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local P, C, UV, N = {}, {}, {}, {} + local np, nt, nn = 0, 0, 0 + local hasColor = false + local sections: { Section } = {} + local byName: { [string]: Section } = {} + local cur: Section? = nil + local object: string? = nil + local group: string? = nil + local material: string? = nil + local smoothing: string? = nil + local mtllibs: { string } = {} + local skipped = 0 + local corners = 0 + local hasObjects = false + local lineNo = 0 + local pos = 1 + local len = #text + local function section(): Section + if cur then + return cur + end + local key = (object or "") .. "\0" .. (group or "") + local s = byName[key] + if not s then + s = { object = object, group = group, prims = {}, byKey = {}, smoothing = smoothing } + byName[key] = s + table.insert(sections, s) + end + cur = s + return s + end + local function prim(mode: string): Prim + local s = section() + local key = mode .. "\0" .. (material or "") + local p = s.byKey[key] + if not p then + p = { material = material, mode = mode, cv = {}, ct = {}, cn = {}, faces = {}, hasT = false, hasN = false } + s.byKey[key] = p + table.insert(s.prims, p) + end + return p + end + -- one corner "v/vt/vn" -> indices (0-based, -1 for none) | nil + local function corner(tok: string): (number?, number, number) + local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$") + local vi = tonumber(a) + if not vi then + return nil, -1, -1 + end + vi = if vi < 0 then np + vi else vi - 1 + local ti, ni = -1, -1 + local t = tonumber(b) + if t then + ti = if t < 0 then nt + t else t - 1 + if ti < 0 or ti >= nt then + return nil, -1, -1 + end + end + local n = tonumber(c) + if n then + ni = if n < 0 then nn + n else n - 1 + if ni < 0 or ni >= nn then + return nil, -1, -1 + end + end + if vi < 0 or vi >= np then + return nil, -1, -1 + end + return vi, ti, ni + end + local fs: { string } = {} + while pos <= len do + local e = string.find(text, "\n", pos, true) or (len + 1) + local line = string.sub(text, pos, e - 1) + pos = e + 1 + lineNo += 1 + -- continuation lines + while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do + line = string.gsub(line, "\\\r?$", " ") + local e2 = string.find(text, "\n", pos, true) or (len + 1) + line ..= string.sub(text, pos, e2 - 1) + pos = e2 + 1 + lineNo += 1 + end + local key, rest = string.match(line, "^%s*(%S+)%s*(.-)%s*$") + if key == nil or string.sub(key, 1, 1) == "#" then + continue + end + local hash = string.find(rest, "#", 1, true) + if hash then + rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "") + end + if key == "v" then + local x, y, z, a, b, c = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)%s*(%S*)%s*(%S*)%s*(%S*)") + local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z) + if not fx or not fy or not fz then + return nil, Err.new(Err.CORRUPT, "bad vertex on line " .. lineNo) + end + if np >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " vertices") + end + P[np * 3 + 1], P[np * 3 + 2], P[np * 3 + 3] = fx, fy, fz + local cr, cg, cb = tonumber(a), tonumber(b), tonumber(c) + if cr and cg and cb then + hasColor = true + C[np * 3 + 1], C[np * 3 + 2], C[np * 3 + 3] = cr, cg, cb + end + np += 1 + elseif key == "vt" then + local u, v = string.match(rest, "^(%S+)%s*(%S*)") + local fu = tonumber(u) + if not fu then + return nil, Err.new(Err.CORRUPT, "bad texture coordinate on line " .. lineNo) + end + if nt >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " texture coordinates") + end + local fv = tonumber(v) or 0 + UV[nt * 2 + 1], UV[nt * 2 + 2] = fu, if flipV then 1 - fv else fv + nt += 1 + elseif key == "vn" then + local x, y, z = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)") + local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z) + if not fx or not fy or not fz then + return nil, Err.new(Err.CORRUPT, "bad normal on line " .. lineNo) + end + if nn >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " normals") + end + N[nn * 3 + 1], N[nn * 3 + 2], N[nn * 3 + 3] = fx, fy, fz + nn += 1 + elseif key == "f" or key == "l" or key == "p" then + table.clear(fs) + for tok in string.gmatch(rest, "%S+") do + table.insert(fs, tok) + end + local k = #fs + local mode = if key == "f" then (if triangulate then "triangles" else "polygons") elseif key == "l" then "lines" else "points" + if (key == "f" and k < 3) or (key == "l" and k < 2) or k < 1 then + return nil, Err.new(Err.CORRUPT, "an element with too few corners on line " .. lineNo) + end + corners += k + if corners > maxV * 4 then + return nil, Err.new(Err.LIMIT, "too many face corners") + end + local p = prim(mode) + local base = #p.cv + for i, tok in fs do + local vi, ti, ni = corner(tok) + if not vi then + return nil, Err.new(Err.CORRUPT, "bad index '" .. tok .. "' on line " .. lineNo) + end + p.cv[base + i], p.ct[base + i], p.cn[base + i] = vi, ti, ni + if ti >= 0 then + p.hasT = true + end + if ni >= 0 then + p.hasN = true + end + end + if mode == "triangles" and k > 3 then + -- fan: rewrite the k corners as (k - 2) triangles + local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) + local o = base + for a = 2, k - 1 do + for _, j in { 1, a, a + 1 } do + o += 1 + p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j] + end + end + elseif mode == "lines" then + -- a polyline -> segments + local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) + local o = base + for a = 1, k - 1 do + for _, j in { a, a + 1 } do + o += 1 + p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j] + end + end + elseif mode == "polygons" then + table.insert(p.faces, k) + end + elseif key == "o" then + object = rest + group = nil + hasObjects = true + cur = nil + elseif key == "g" then + group = if rest == "" then nil else rest + cur = nil + elseif key == "usemtl" then + material = rest + elseif key == "mtllib" then + table.insert(mtllibs, rest) + elseif key == "s" then + smoothing = rest + if cur then + cur.smoothing = cur.smoothing or rest + end + else + skipped += 1 + end + end + -- materials + local scene = Types.Scene.new() + local matIndex: { [string]: number } = {} + local texIndex: { [string]: number } = {} + local function texture(map: Mtl.Map): number + local file = string.gsub(map.file, "\\", "/") + local i = texIndex[file] + if i then + return i + end + local tex: Types.Texture = { uri = file, mime = Mtl.mime(file) } + local data = fetch(opts, file) + if data then + tex.data = buffer.fromstring(data) + end + if map.options.clamp and map.options.clamp[1] == "on" then + tex.sampler = { wrapS = "clamp", wrapT = "clamp" } + end + table.insert(scene.textures, tex) + i = #scene.textures + texIndex[file] = i + return i + end + local mtlText = if opts and opts.mtl then (if type(opts.mtl) == "buffer" then buffer.tostring(opts.mtl) else opts.mtl) else nil + local missing: { string } = {} + local libs: { string } = {} + if mtlText then + table.insert(libs, mtlText :: string) + end + for _, lib in mtllibs do + local t = fetch(opts, lib) + if t then + table.insert(libs, t) + elseif not mtlText then + table.insert(missing, lib) + end + end + for _, lt in libs do + for _, e in Mtl.parse(lt) do + if not matIndex[e.name] then + table.insert(scene.materials, Mtl.toMaterial(e, texture)) + matIndex[e.name] = #scene.materials + end + end + end + -- materials named by usemtl but not defined anywhere: a default one with the name + for _, s in sections do + for _, p in s.prims do + if p.material and not matIndex[p.material] then + table.insert(scene.materials, Types.Scene.material(p.material)) + scene.materials[#scene.materials].metallic = 0 + matIndex[p.material] = #scene.materials + end + end + end + -- vertices: one per distinct (v, vt, vn) in each primitive + local f32 = buffer.writef32 + local KT, KN = nt + 1, nn + 1 + local numericKeys = np * KT * KN < 2 ^ 52 + local function build(p: Prim): Types.Primitive + local n = #p.cv + local map: { [any]: number } = {} + local verts: { number } = {} + local idx = buffer.create(n * 4) + local count = 0 + for i = 1, n do + local v, t, nr = p.cv[i], p.ct[i], p.cn[i] + local key: any = if numericKeys then (v * KT + (t + 1)) * KN + (nr + 1) else string.format("%d/%d/%d", v, t, nr) + local k = map[key] + if k == nil then + k = count + map[key] = k + count += 1 + verts[count * 3 - 2], verts[count * 3 - 1], verts[count * 3] = v, t, nr + end + buffer.writeu32(idx, (i - 1) * 4, k) + end + local pb = buffer.create(count * 12) + local tb = if p.hasT then buffer.create(count * 8) else nil + local nb = if p.hasN then buffer.create(count * 12) else nil + local cb = if hasColor then buffer.create(count * 12) else nil + for k = 0, count - 1 do + local v, t, nr = verts[k * 3 + 1], verts[k * 3 + 2], verts[k * 3 + 3] + f32(pb, k * 12, P[v * 3 + 1]) + f32(pb, k * 12 + 4, P[v * 3 + 2]) + f32(pb, k * 12 + 8, P[v * 3 + 3]) + if tb and t >= 0 then + f32(tb, k * 8, UV[t * 2 + 1]) + f32(tb, k * 8 + 4, UV[t * 2 + 2]) + end + if nb and nr >= 0 then + f32(nb, k * 12, N[nr * 3 + 1]) + f32(nb, k * 12 + 4, N[nr * 3 + 2]) + f32(nb, k * 12 + 8, N[nr * 3 + 3]) + end + if cb then + f32(cb, k * 12, C[v * 3 + 1] or 1) + f32(cb, k * 12 + 4, C[v * 3 + 2] or 1) + f32(cb, k * 12 + 8, C[v * 3 + 3] or 1) + end + end + local A = Types.Scene.accessor + local attrs: { [string]: Types.Accessor } = { POSITION = A(pb, "f32", 3, count) } + if tb then + attrs.TEXCOORD_0 = A(tb, "f32", 2, count) + end + if nb then + attrs.NORMAL = A(nb, "f32", 3, count) + end + if cb then + attrs.COLOR_0 = A(cb, "f32", 3, count) + end + local out: Types.Primitive = { attributes = attrs, indices = A(idx, "u32", 1, n), mode = p.mode :: any, material = if p.material then matIndex[p.material] else nil } + if p.mode == "points" then + out.indices = if count == n then nil else out.indices + end + if p.mode == "polygons" then + local fb = buffer.create(#p.faces * 4) + for i, k in p.faces do + buffer.writeu32(fb, (i - 1) * 4, k) + end + out.faces = A(fb, "u32", 1, #p.faces) + end + return out + end + -- nodes: objects at the root, their groups as children; without objects every group is a root + local objectNode: { [string]: number } = {} + for _, s in sections do + if #s.prims > 0 then + local mesh: Types.Mesh = { name = s.group or s.object, primitives = {} } + for _, p in s.prims do + table.insert(mesh.primitives, build(p)) + end + table.insert(scene.meshes, mesh) + local node: Types.Node = { name = s.group or s.object, children = {}, mesh = #scene.meshes } + if s.smoothing then + node.extras = { obj = { smoothing = s.smoothing } } + end + if hasObjects and s.object and s.group then + local oi = objectNode[s.object] + if not oi then + table.insert(scene.nodes, { name = s.object, children = {} }) + oi = #scene.nodes + objectNode[s.object] = oi + table.insert(scene.roots, oi) + end + table.insert(scene.nodes, node) + table.insert(scene.nodes[oi].children, #scene.nodes) + else + if hasObjects and s.object and not s.group and objectNode[s.object] == nil then + table.insert(scene.nodes, node) + objectNode[s.object] = #scene.nodes + table.insert(scene.roots, #scene.nodes) + elseif hasObjects and s.object and objectNode[s.object] then + -- the object's own faces after its groups: a child too + table.insert(scene.nodes, node) + table.insert(scene.nodes[objectNode[s.object]].children, #scene.nodes) + else + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + end + end + end + scene.meta.up = "y" + scene.meta.source = { + format = "obj", + positions = np, + texcoords = nt, + normals = nn, + vertexColors = hasColor, + mtllib = if #mtllibs > 0 then mtllibs else nil, + missingMtl = if #missing > 0 then missing else nil, + skipped = skipped, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the shortest decimal that reads back as the same f32 +local probe = buffer.create(4) +local function f32str(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + if v == math.floor(v) and math.abs(v) < 1e7 then + return string.format("%d", v) + end + buffer.writef32(probe, 0, v) + local want = buffer.readf32(probe, 0) + for _, f in { "%.6g", "%.7g", "%.8g" } do + local s = string.format(f, v) + buffer.writef32(probe, 0, tonumber(s) :: number) + if buffer.readf32(probe, 0) == want then + return s + end + end + return string.format("%.9g", v) +end + +local function nameOk(s: string): string + local t = string.gsub(s, "[\r\n]", " ") + return t +end + +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/ktx2"] = "ktx2" } + +function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local flipV = not (opts and opts.flipV == false) + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local mtlName = opts and opts.mtlName or (base .. ".mtl") + local files = opts and opts.files + local placed = Types.Scene.flatten(scene) + local out = { "# written by formats-luau" } + local mats = scene.materials or {} + -- material names (unique), texture file names + local names: { string } = {} + local used: { [string]: boolean } = {} + for i, m in mats do + local n = string.gsub(m.name or ("material_" .. i), "%s", "_") + while used[n] do + n ..= "_" .. i + end + used[n] = true + names[i] = n + end + local texFiles: { [number]: string } = {} + local function textureFile(i: number): string? + if texFiles[i] then + return texFiles[i] + end + local tex = scene.textures and scene.textures[i] + if not tex then + return nil + end + local file = tex.uri + if (file == nil or string.find(file, "^data:")) and tex.data then + file = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + end + if file and tex.data and type(files) == "table" then + files[file] = tex.data + end + texFiles[i] = file + return file + end + if #mats > 0 then + table.insert(out, "mtllib " .. mtlName) + if type(files) == "table" then + files[mtlName] = Mtl.write(mats, names, textureFile) + end + end + local nv, nt, nn = 0, 0, 0 + local lastNode = -1 + for _, pl in placed do + local prim = pl.primitive + local attrs = prim.attributes + local pos = attrs and attrs.POSITION + if not pos then + continue + end + local P = Types.Scene.reader(pos) + if not P then + return nil, Err.new(Err.ARG, "bad POSITION accessor") + end + if buffer.len(pos.data) < pos.count * pos.components * (Types.COMPONENT_SIZE[pos.type] or 4) then + return nil, Err.new(Err.ARG, "POSITION data is smaller than its count") + end + local m = pl.matrix + local ident = m == Types.Scene.IDENTITY + local node = scene.nodes[pl.node] + if pl.node ~= lastNode then + lastNode = pl.node + table.insert(out, "o " .. nameOk(node.name or ("node_" .. pl.node))) + end + local n = pos.count + local Cc = if attrs.COLOR_0 and not (opts and opts.colors == false) then Types.Scene.reader(attrs.COLOR_0) else nil + local T = if attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) then Types.Scene.reader(attrs.TEXCOORD_0) else nil + local Nr = if attrs.NORMAL and not (opts and opts.normals == false) then Types.Scene.reader(attrs.NORMAL) else nil + for _, a in { attrs.COLOR_0, attrs.TEXCOORD_0, attrs.NORMAL } do + if a and (a.count < n or buffer.len(a.data) < a.count * a.components * (Types.COMPONENT_SIZE[a.type] or 4)) then + return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION") + end + end + -- the normal matrix (inverse transpose) for baked normals + local nm: { number }? = nil + if Nr and not ident then + local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11] + local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) + local k = if det ~= 0 then 1 / det else 1 + nm = { (e * i - f * h) * k, -(d * i - f * g) * k, (d * h - e * g) * k, -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k } + end + for v = 0, n - 1 do + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + if not ident then + x, y, z = m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] + end + if Cc then + table.insert(out, string.format("v %s %s %s %s %s %s", f32str(x), f32str(y), f32str(z), f32str(Cc(v, 0)), f32str(Cc(v, 1)), f32str(Cc(v, 2)))) + else + table.insert(out, string.format("v %s %s %s", f32str(x), f32str(y), f32str(z))) + end + end + if T then + for v = 0, n - 1 do + local tv = T(v, 1) + table.insert(out, string.format("vt %s %s", Mtl.num(T(v, 0)), Mtl.num(if flipV then 1 - tv else tv))) + end + end + if Nr then + for v = 0, n - 1 do + local x, y, z = Nr(v, 0), Nr(v, 1), Nr(v, 2) + if nm then + x, y, z = nm[1] * x + nm[4] * y + nm[7] * z, nm[2] * x + nm[5] * y + nm[8] * z, nm[3] * x + nm[6] * y + nm[9] * z + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + end + table.insert(out, string.format("vn %s %s %s", f32str(x), f32str(y), f32str(z))) + end + end + if prim.material and names[prim.material] then + table.insert(out, "usemtl " .. names[prim.material]) + end + local function ref(i: number): string + local s = tostring(nv + i + 1) + if T and Nr then + return string.format("%s/%d/%d", s, nt + i + 1, nn + i + 1) + elseif T then + return string.format("%s/%d", s, nt + i + 1) + elseif Nr then + return string.format("%s//%d", s, nn + i + 1) + end + return s + end + -- the corner list + local ind = prim.indices + local I: ((number, number) -> number)? = if ind then Types.Scene.reader(ind) else nil + local count = if ind then ind.count else n + if ind and buffer.len(ind.data) < ind.count * (Types.COMPONENT_SIZE[ind.type] or 4) then + return nil, Err.new(Err.ARG, "indices data is smaller than its count") + end + local function at(i: number): number + return if I then I(i, 0) else i + end + for i = 0, count - 1 do + if at(i) >= n then + return nil, Err.new(Err.ARG, "index out of range") + end + end + local mirror = not ident and (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])) < 0 + local function face(list: { number }) + local parts = table.create(#list + 1) + parts[1] = "f" + if mirror then + for k = #list, 1, -1 do + table.insert(parts, ref(list[k])) + end + else + for k = 1, #list do + table.insert(parts, ref(list[k])) + end + end + table.insert(out, table.concat(parts, " ")) + end + local mode = prim.mode or "triangles" + if mode == "triangles" then + for t = 0, count // 3 - 1 do + face({ at(t * 3), at(t * 3 + 1), at(t * 3 + 2) }) + end + elseif mode == "polygons" then + local F = if prim.faces then Types.Scene.reader(prim.faces) else nil + if not F or not prim.faces then + return nil, Err.new(Err.ARG, "polygons without faces") + end + local o = 0 + for f = 0, prim.faces.count - 1 do + local k = F(f, 0) + if o + k > count then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + local list = table.create(k) + for j = 0, k - 1 do + list[j + 1] = at(o + j) + end + if k >= 3 then + face(list) + end + o += k + end + elseif mode == "triangle_strip" or mode == "triangle_fan" then + for t = 0, count - 3 do + local a, b, c = at(t), at(t + 1), at(t + 2) + if mode == "triangle_fan" then + a = at(0) + elseif t % 2 == 1 then + a, b = b, a + end + face({ a, b, c }) + end + elseif mode == "lines" then + for s = 0, count // 2 - 1 do + table.insert(out, "l " .. ref(at(s * 2)) .. " " .. ref(at(s * 2 + 1))) + end + elseif mode == "line_strip" or mode == "line_loop" then + local parts = { "l" } + for i = 0, count - 1 do + table.insert(parts, ref(at(i))) + end + if mode == "line_loop" and count > 0 then + table.insert(parts, ref(at(0))) + end + table.insert(out, table.concat(parts, " ")) + elseif mode == "points" then + for i = 0, count - 1 do + table.insert(out, "p " .. ref(at(i))) + end + end + nv += n + if T then + nt += n + end + if Nr then + nn += n + end + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- encodeMtl(scene, opts?) -> the .mtl text for the scene's materials (what encode puts in opts.files) +function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or type(scene.materials) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local files = {} + local o: any = table.clone(opts or {}) + o.files = files + o.mtlName = "x.mtl" + local _, err = Obj.encode(scene, o) + if err then + return nil, err + end + local text = files["x.mtl"] + return buffer.fromstring(text or ""), nil +end + +return Obj diff --git a/src/Formats/model/off/init.luau b/src/Formats/model/off/init.luau new file mode 100644 index 0000000..92b4107 --- /dev/null +++ b/src/Formats/model/off/init.luau @@ -0,0 +1,480 @@ +--!strict +-- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description +-- (geomview.org/docs/html/OFF.html). +-- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the +-- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`; +-- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8 +-- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given). +-- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces; +-- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are +-- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or +-- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single +-- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points". +-- meta.source = { format, keyword, vertices, faces, edges }. +-- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes +-- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons +-- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are +-- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF +-- (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Flatten = require("@formats/codecs/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Off = { + name = "off", + category = "model", + extensions = { "off" }, + mime = { "model/off", "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- default 2^25 +} +export type EncodeOptions = { + colors: boolean?, -- write COLOR_0 (COFF) and prim.extras.faceColors when present (default true) + normals: boolean?, -- write NORMAL (NOFF) when present (default true) + texcoords: boolean?, -- write TEXCOORD_0 (STOFF) when present (default true) + comment: string?, -- a "# ..." line after the header keyword +} + +-- ------------------------------------------------------------------------------------------------ constants +local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Off.sniff(r: Bytes.Reader): number + local head = r:peek(512) + for _ = 1, 16 do -- leading comment lines + local rest = string.match(head, "^%s*#[^\n]*\n(.*)$") + if not rest then + break + end + head = rest + end + local kw = string.match(head, "^%s*(%w+)") + if kw and string.match(kw, "^S?T?C?N?4?n?OFF$") then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32 +type ColorSet = { values: { number }, float: boolean, max: number } + +local function colorType(c: ColorSet): string + return if not c.float and c.max > 1 then "unorm8" else "f32" +end + +-- the colour accessor for count entries of 4 values (nan = absent: opaque white) +local function colorAccessor(c: ColorSet, count: number): (Types.Accessor?, string?) + local t = colorType(c) + local buf = buffer.create(count * (if t == "unorm8" then 4 else 16)) + local vals = c.values + for i = 0, count * 4 - 1 do + local v = vals[i + 1] + if t == "unorm8" then + if v ~= v then + v = 255 + elseif v < 0 or v > 255 or v % 1 ~= 0 then + return nil, "colour value out of range" + end + writeu8(buf, i, v) + else + writef32(buf, i * 4, if v ~= v then 1 else v) + end + end + return Types.Scene.accessor(buf, t, 4, count), nil +end + +local function addColor(c: ColorSet, toks: { string }, from: number, n: number) + local vals = c.values + for k = 0, 3 do + if k < n then + local s = toks[from + k] + local v = tonumber(s) :: number + table.insert(vals, v) + if not c.float and string.find(s, "[%.eEnN]") then + c.float = true + end + if v > c.max then + c.max = v + end + else + table.insert(vals, 0 / 0) -- absent: full (opaque white) + end + end +end + +function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = true + if opts and opts.triangulate == false then + triangulate = false + end + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + -- the next non-empty line's tokens (comments stripped) + local at = 1 + local lineNo = 0 + local function line(): { string }? + while at <= #text do + local e = string.find(text, "\n", at, true) or (#text + 1) + local s = string.sub(text, at, e - 1) + at = e + 1 + lineNo += 1 + local hash = string.find(s, "#", 1, true) + if hash then + s = string.sub(s, 1, hash - 1) + end + local toks = {} + for w in string.gmatch(s, "%S+") do + table.insert(toks, w) + end + if #toks > 0 then + return toks + end + end + return nil + end + local head = line() + if not head then + return nil, Err.new(Err.TRUNCATED, "empty file") + end + local kw = head[1] + local rest = kw + local st, hasC, hasN = false, false, false + if string.sub(rest, 1, 2) == "ST" then + st, rest = true, string.sub(rest, 3) + end + if string.sub(rest, 1, 1) == "C" then + hasC, rest = true, string.sub(rest, 2) + end + if string.sub(rest, 1, 1) == "N" then + hasN, rest = true, string.sub(rest, 2) + end + if rest == "4OFF" or rest == "nOFF" or rest == "4nOFF" then + return nil, Err.new(Err.UNSUPPORTED, kw .. " (homogeneous / n-dimensional vertices)") + elseif rest ~= "OFF" then + return nil, Err.new(Err.CORRUPT, "bad header keyword " .. string.sub(kw, 1, 20)) + end + local counts: { string } + if head[2] == "BINARY" then + return nil, Err.new(Err.UNSUPPORTED, "binary OFF") + elseif #head >= 3 then + counts = { head[2], head[3], head[4] } + else + local c = line() + if not c then + return nil, Err.new(Err.TRUNCATED, "no counts line") + end + counts = c + end + local nv, nf, ne = tonumber(counts[1]), tonumber(counts[2]), tonumber(counts[3] or "0") + if not nv or not nf or nv < 0 or nf < 0 or nv % 1 ~= 0 or nf % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad counts line") + end + if nv > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", nv, maxVertices)) + end + if nf > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces)) + end + -- every vertex / face line takes at least 6 / 2 bytes + if nv * 6 + nf * 2 > #text - at + 2 then + return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need") + end + local fixed = 3 + (if hasN then 3 else 0) + (if st then 2 else 0) + local pos = buffer.create(nv * 12) + local nrm = if hasN then buffer.create(nv * 12) else nil + local tex = if st then buffer.create(nv * 8) else nil + local vcol: ColorSet = { values = {}, float = false, max = 0 } + for i = 0, nv - 1 do + local t = line() + if not t then + return nil, Err.new(Err.TRUNCATED, string.format("vertex %d missing", i)) + end + local n = #t + local nc = 0 + if hasC then + nc = n - fixed + if nc ~= 3 and nc ~= 4 then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values and an RGB / RGBA colour", i, fixed)) + end + elseif n < fixed then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values", i, fixed)) + end + for k = 1, fixed + nc do + if tonumber(t[k]) == nil then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: bad number", i)) + end + end + writef32(pos, i * 12, tonumber(t[1]) :: number) + writef32(pos, i * 12 + 4, tonumber(t[2]) :: number) + writef32(pos, i * 12 + 8, tonumber(t[3]) :: number) + local k = 4 + if nrm then + writef32(nrm, i * 12, tonumber(t[4]) :: number) + writef32(nrm, i * 12 + 4, tonumber(t[5]) :: number) + writef32(nrm, i * 12 + 8, tonumber(t[6]) :: number) + k = 7 + end + if hasC then + addColor(vcol, t, k, nc) + k += nc + end + if tex then + writef32(tex, i * 8, tonumber(t[k]) :: number) + writef32(tex, i * 8 + 4, tonumber(t[k + 1]) :: number) + end + end + local sizes = buffer.create(nf * 4) + local corners: { number } = {} + local fcol: ColorSet = { values = {}, float = false, max = 0 } + local anyFaceColor, colormap = false, false + for f = 0, nf - 1 do + local t = line() + if not t then + return nil, Err.new(Err.TRUNCATED, string.format("face %d missing", f)) + end + local n = tonumber(t[1]) + if n == nil or n < 0 or n % 1 ~= 0 or #t < n + 1 then + return nil, Err.new(Err.CORRUPT, string.format("face %d: bad vertex count", f)) + end + writeu32(sizes, f * 4, n) + for k = 2, n + 1 do + local v = tonumber(t[k]) + if v == nil or v < 0 or v >= nv or v % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, string.format("face %d: vertex index out of range", f)) + end + table.insert(corners, v) + end + local nc = #t - n - 1 + if nc == 3 or nc == 4 then + for k = n + 2, #t do + if tonumber(t[k]) == nil then + return nil, Err.new(Err.CORRUPT, string.format("face %d: bad colour", f)) + end + end + addColor(fcol, t, n + 2, nc) + anyFaceColor = true + else + if nc == 1 then + colormap = true + end + addColor(fcol, t, 1, 0) + end + end + -- the primitive + local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } + if nrm then + attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) + end + if hasC then + local acc, cerr = colorAccessor(vcol, nv) + if not acc then + return nil, Err.new(Err.CORRUPT, "vertex " .. tostring(cerr)) + end + attrs.COLOR_0 = acc + end + if tex then + attrs.TEXCOORD_0 = Types.Scene.accessor(tex, "f32", 2, nv) + end + local prim: Types.Primitive = { attributes = attrs, mode = "points" } + local extras: { [string]: any } = {} + if anyFaceColor then + local acc, cerr = colorAccessor(fcol, nf) + if not acc then + return nil, Err.new(Err.CORRUPT, "face " .. tostring(cerr)) + end + extras.faceColors = acc + end + if nf > 0 then + local total = #corners + local cbuf = buffer.create(total * 4) + for i = 1, total do + writeu32(cbuf, (i - 1) * 4, corners[i]) + end + local allTri = total == nf * 3 + if allTri then + for f = 0, nf - 1 do + if buffer.readu32(sizes, f * 4) ~= 3 then + allTri = false + break + end + end + end + if allTri then + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total) + elseif triangulate then + local tris: { number } = {} + local fot: { number } = {} + local p = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + for k = 1, s - 2 do + table.insert(tris, corners[p + 1]) + table.insert(tris, corners[p + k + 1]) + table.insert(tris, corners[p + k + 2]) + table.insert(fot, f) + end + p += s + end + local ib = buffer.create(#tris * 4) + for i, v in tris do + writeu32(ib, (i - 1) * 4, v) + end + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(ib, "u32", 1, #tris) + if anyFaceColor then + local fb = buffer.create(#fot * 4) + for i, v in fot do + writeu32(fb, (i - 1) * 4, v) + end + extras.faceOfTriangle = Types.Scene.accessor(fb, "u32", 1, #fot) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + if next(extras) then + prim.extras = extras + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "off", keyword = kw, vertices = nv, faces = nf, edges = ne or 0, colormap = colormap or nil } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local scratch = buffer.create(4) +local function fnum(v: number): string? + writef32(scratch, 0, v) + v = buffer.readf32(scratch, 0) + if v ~= v or v == math.huge or v == -math.huge then + return nil + end + return string.format("%.9g", v) +end + +-- a colour attribute's 4 components of entry i (0-based) as text +local function colorText(a: Flatten.Attr, vals: { number }, comps: number, i: number): string + local out = table.create(4) + for c = 1, 4 do + local v = if c <= comps then vals[i * comps + c] else nil + if a.raw and a.type == "unorm8" then + out[c] = string.format("%d", if v == nil then 255 else math.clamp(v, 0, 255)) + else + if v == nil then + v = 1 + elseif a.raw then + v = if a.type == "unorm16" then v / 65535 elseif a.type == "snorm8" then math.max(v / 127, -1) else math.max(v / 32767, -1) + end + out[c] = fnum(v :: number) or "0" + end + end + return table.concat(out, " ") +end + +function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local wantC, wantN, wantT = o.colors ~= false, o.normals ~= false, o.texcoords ~= false + local m, merr = Flatten.merge(scene, function(name: string): boolean + return (name == "NORMAL" and wantN) or (name == "COLOR_0" and wantC) or (name == "TEXCOORD_0" and wantT) + end, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local A = m.attrs + local P, N, C, T = A.POSITION, A.NORMAL, A.COLOR_0, A.TEXCOORD_0 + if T and T.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + local nv = m.count + local sizes = m.sizes or {} + local nf = #sizes + local out = table.create(nv + nf + 3) + table.insert(out, (if T then "ST" else "") .. (if C then "C" else "") .. (if N then "N" else "") .. "OFF") + if o.comment then + table.insert(out, "# " .. string.gsub(o.comment, "[\r\n]", " ")) + end + table.insert(out, string.format("%d %d 0", nv, nf)) + local pv = P.values + for i = 0, nv - 1 do + local x, y, z = fnum(pv[i * 3 + 1]), fnum(pv[i * 3 + 2]), fnum(pv[i * 3 + 3]) + if not (x and y and z) then + return nil, Err.new(Err.ARG, "OFF cannot hold a non-finite coordinate") + end + local s = x .. " " .. y .. " " .. z + if N then + local nvv = N.values + s ..= " " .. (fnum(nvv[i * 3 + 1]) or "0") .. " " .. (fnum(nvv[i * 3 + 2]) or "0") .. " " .. (fnum(nvv[i * 3 + 3]) or "0") + end + if C then + s ..= " " .. colorText(C, C.values, C.components, i) + end + if T then + local tv, tc = T.values, T.components + s ..= " " .. (fnum(tv[i * tc + 1]) or "0") .. " " .. (fnum(if tc >= 2 then tv[i * tc + 2] else 0) or "0") + end + table.insert(out, s) + end + -- face colours of a single primitive (per file face, or through faceOfTriangle) + local fc: Flatten.Attr? = nil + local fcMap: { number }? = nil + if wantC and #m.parts == 1 and nf > 0 then + local ex = m.parts[1].prim.extras + local acc = type(ex) == "table" and ex.faceColors + if acc then + local raw = acc.type == "unorm8" or acc.type == "unorm16" or acc.type == "snorm8" or acc.type == "snorm16" + local vals = Flatten.numbers(acc, raw) + if vals then + local a: Flatten.Attr = { type = acc.type, components = acc.components, raw = raw, values = vals } + if acc.count == nf then + fc = a + elseif ex.faceOfTriangle then + local fot = Flatten.numbers(ex.faceOfTriangle, true) + if fot and #fot == nf then + fc, fcMap = a, fot + for _, f in fot do + if f < 0 or f >= acc.count then + fc = nil + break + end + end + end + end + end + end + end + local corners = m.corners + local p = 0 + for f = 1, nf do + local s = sizes[f] + local line = table.create(s + 2) + line[1] = string.format("%d", s) + for k = 1, s do + line[k + 1] = string.format("%d", corners[p + k]) + end + p += s + if fc then + local src = if fcMap then fcMap[f] else f - 1 + table.insert(line, colorText(fc, fc.values, fc.components, src)) + end + table.insert(out, table.concat(line, " ")) + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +return Off diff --git a/src/Formats/model/ply/Binary.luau b/src/Formats/model/ply/Binary.luau new file mode 100644 index 0000000..5bfdf92 --- /dev/null +++ b/src/Formats/model/ply/Binary.luau @@ -0,0 +1,212 @@ +--!strict +--!native +--!optimize 2 +-- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, +-- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of +-- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the +-- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list +-- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws. +local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64 = buffer.readf32, buffer.readf64 +local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32 +local writef32, writef64 = buffer.writef32, buffer.writef64 +local byteswap, band, rshift = bit32.byteswap, bit32.band, bit32.rshift + +local Binary = {} + +Binary.SIZE = { 1, 1, 2, 2, 4, 4, 4, 8 } +local SIZE = Binary.SIZE +local scratch = buffer.create(8) + +local function swap16(v: number): number + return rshift(v, 8) + band(v, 255) * 256 +end + +-- rd(b, q, code, be) -> the value at q +local function rd(b: buffer, q: number, code: number, be: boolean): number + if not be then + if code == 7 then + return readf32(b, q) + elseif code == 2 then + return readu8(b, q) + elseif code == 5 then + return readi32(b, q) + elseif code == 6 then + return readu32(b, q) + elseif code == 8 then + return readf64(b, q) + elseif code == 1 then + return readi8(b, q) + elseif code == 3 then + return readi16(b, q) + end + return readu16(b, q) + end + if code <= 2 then + return if code == 1 then readi8(b, q) else readu8(b, q) + elseif code <= 4 then + local v = swap16(readu16(b, q)) + return if code == 3 and v >= 32768 then v - 65536 else v + elseif code <= 7 then + local v = byteswap(readu32(b, q)) + if code == 6 then + return v + elseif code == 5 then + return if v >= 2147483648 then v - 4294967296 else v + end + writeu32(scratch, 0, v) + return readf32(scratch, 0) + end + writeu32(scratch, 0, byteswap(readu32(b, q + 4))) + writeu32(scratch, 4, byteswap(readu32(b, q))) + return readf64(scratch, 0) +end +Binary.rd = rd + +-- wr(d, o, code, v): v as code, little endian +local function wr(d: buffer, o: number, code: number, v: number) + if code == 7 then + writef32(d, o, v) + elseif code == 6 then + writeu32(d, o, v) + elseif code == 5 then + writei32(d, o, v) + elseif code == 2 then + writeu8(d, o, v) + elseif code == 8 then + writef64(d, o, v) + elseif code == 1 then + writei8(d, o, v) + elseif code == 3 then + writei16(d, o, v) + else + writeu16(d, o, v) + end +end +Binary.wr = wr + +-- put(d, o, code, v, be): v as code in either byte order (the writer) +function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean) + if not be or code <= 2 then + wr(d, o, code, v) + return + end + wr(scratch, 0, code, v) + if code <= 4 then + writeu16(d, o, swap16(readu16(scratch, 0))) + elseif code <= 7 then + writeu32(d, o, byteswap(readu32(scratch, 0))) + else + writeu32(d, o, byteswap(readu32(scratch, 4))) + writeu32(d, o + 4, byteswap(readu32(scratch, 0))) + end +end + +-- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p +function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }) + for k = 1, np do + local sc, dc, d = code[k], dCode[k], dst[k] + local q0, o0, st = p + srcOff[k], dOff[k], dStride[k] + if sc == dc and not be then + local sz = SIZE[sc] + if sz == 4 then + for i = 0, n - 1 do + writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize)) + end + elseif sz == 1 then + for i = 0, n - 1 do + writeu8(d, o0 + i * st, readu8(b, q0 + i * rowSize)) + end + elseif sz == 2 then + for i = 0, n - 1 do + writeu16(d, o0 + i * st, readu16(b, q0 + i * rowSize)) + end + else + for i = 0, n - 1 do + writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize)) + writeu32(d, o0 + i * st + 4, readu32(b, q0 + i * rowSize + 4)) + end + end + else + for i = 0, n - 1 do + wr(d, o0 + i * st, dc, rd(b, q0 + i * rowSize, sc, be)) + end + end + end +end + +-- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property, +-- or -1, message (truncated rows, a negative / fractional count) +function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any) + local totals = table.create(np, 0) + local q = p + for _ = 1, n do + for k = 1, np do + if isList[k] then + local cc = countCode[k] + local csz = SIZE[cc] + if q + csz > limit then + return -1, "list runs past the end" + end + local c = rd(b, q, cc, be) + if c < 0 or c ~= c // 1 then + return -1, "bad list count" + end + q += csz + c * SIZE[code[k]] + if q > limit then + return -1, "list runs past the end" + end + totals[k] += c + else + q += SIZE[code[k]] + if q > limit then + return -1, "row runs past the end" + end + end + end + end + return q, totals +end + +-- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message. +-- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their +-- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows +-- must have passed scan() with the same arguments. +function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?) + local at = table.create(np, 0) + local q = p + for i = 0, n - 1 do + for k = 1, np do + local sc, dc, d = code[k], dCode[k], dst[k] + if isList[k] then + local cc = countCode[k] + local c = rd(b, q, cc, be) + q += SIZE[cc] + writeu32(sizes[k], i * 4, c) + local ia, ssz, dsz, bd = at[k], SIZE[sc], SIZE[dc], bound[k] + if bd >= 0 then + for j = 0, c - 1 do + local v = rd(b, q, sc, be) + q += ssz + if v < 0 or v >= bd or v ~= v // 1 then + return false, "vertex index out of range" + end + wr(d, (ia + j) * dsz, dc, v) + end + else + for j = 0, c - 1 do + wr(d, (ia + j) * dsz, dc, rd(b, q, sc, be)) + q += ssz + end + end + at[k] = ia + c + else + wr(d, dOff[k] + i * dStride[k], dc, rd(b, q, sc, be)) + q += SIZE[sc] + end + end + end + return true, nil +end + +return Binary diff --git a/src/Formats/model/ply/init.luau b/src/Formats/model/ply/init.luau new file mode 100644 index 0000000..8b9350e --- /dev/null +++ b/src/Formats/model/ply/init.luau @@ -0,0 +1,1148 @@ +--!strict +-- model/ply: PLY (Stanford polygon file format, Greg Turk 1994), ascii / binary_little_endian / binary_big_endian, +-- read + write. Written from the format description (paulbourke.net/dataformats/ply, the rply / plyfile behaviour). +-- Decode: the vertex element maps x y z -> POSITION f32 x3, nx ny nz -> NORMAL f32 x3, red green blue [alpha] -> +-- COLOR_0 (uchar: unorm8 x4, ushort: unorm16 x4, float / double: f32 x4; alpha full when absent), u v / s t / texture_u +-- texture_v / texture_s texture_t -> TEXCOORD_0 f32 x2, every other property -> "_" .. name in its own type (char -> +-- i8, uchar -> u8, ..., double -> f64). Doubles in x / y / z / normals / texcoords become f32. The face element's +-- vertex_indices / vertex_index list gives the faces: triangles stay triangles (u32 indices), n-gons are +-- fan-triangulated (opts.triangulate, default true: right for convex faces; faces of fewer than 3 vertices are +-- dropped) or kept as mode "polygons" (prim.faces = vertex count per face). No faces: a point cloud (mode "points", +-- no indices). Other face properties: prim.extras.faceAttributes[name] (one value per file face, its own type), face +-- lists: prim.extras.faceLists[name] = { countType, itemType, sizes (u32 accessor), items (accessor) }; after +-- triangulating n-gons prim.extras.faceOfTriangle (u32, 0-based) maps triangles to file faces. Other elements (edge, +-- material, ...) are kept raw in scene.meta.ply.elements (in their types) and written back, as are comments +-- (meta.ply.comments), obj_info lines (meta.ply.objInfo), the element order and the vertex / face property order and +-- types. meta.source = { format, encoding, vertices, faces }. +-- Encode: every primitive in world space (node transforms applied) into one vertex list: POSITION, NORMAL, COLOR_0, +-- TEXCOORD_0 and "_" attributes (under their name, in their type; several components: name_0, name_1, ...), faces +-- (triangles and polygons natively as `property list uchar int vertex_indices`, a wider count / uint index type when +-- needed), point clouds without a face element; lines are skipped. Floats print as %.9g (f32-exact), doubles %.17g. +-- Not supported: list properties in the vertex element (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Binary = require("@formats/model/ply/Binary") +local Flatten = require("@formats/codecs/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Ply = { + name = "ply", + category = "model", + extensions = { "ply" }, + mime = { "model/ply", "application/ply" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- faces, and rows of any other element (default 2^25) +} +export type EncodeOptions = { + format: ("binary_little_endian" | "binary_big_endian" | "ascii")?, -- default "binary_little_endian" + comments: { string }?, -- extra comment lines (after those in scene.meta.ply.comments) +} + +type Prop = { name: string, ply: string, code: number, list: boolean, countPly: string?, countCode: number? } +type Elem = { name: string, count: number, props: { Prop } } + +-- ------------------------------------------------------------------------------------------------ constants +local CODES: { [string]: number } = { + char = 1, + int8 = 1, + uchar = 2, + uint8 = 2, + short = 3, + int16 = 3, + ushort = 4, + uint16 = 4, + int = 5, + int32 = 5, + uint = 6, + uint32 = 6, + float = 7, + float32 = 7, + double = 8, + float64 = 8, +} +local ACC_TYPE = { "i8", "u8", "i16", "u16", "i32", "u32", "f32", "f64" } +local PLY_NAME = { "char", "uchar", "short", "ushort", "int", "uint", "float", "double" } +local CODE_OF_ACC: { [string]: number } = { i8 = 1, u8 = 2, i16 = 3, u16 = 4, i32 = 5, u32 = 6, f32 = 7, f64 = 8, unorm8 = 2, unorm16 = 4, snorm8 = 1, snorm16 = 3 } +local RANGE = { { -128, 127 }, { 0, 255 }, { -32768, 32767 }, { 0, 65535 }, { -2147483648, 2147483647 }, { 0, 4294967295 } } +local SIZE = Binary.SIZE +local ENCODINGS = { ascii = true, binary_little_endian = true, binary_big_endian = true } +local MAX_HEADER = 1048576 +local TEXCOORD_PAIRS = { { "u", "v" }, { "s", "t" }, { "texture_u", "texture_v" }, { "texture_s", "texture_t" } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ply.sniff(r: Bytes.Reader): number + local h = r:peek(4) + return if h == "ply\n" or h == "ply\r" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Header = { encoding: string, elems: { Elem }, comments: { string }, objInfo: { string }, dataStart: number } + +local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) + local b, base, size = r.buf, r.base, r.limit - r.base + local text = buffer.readstring(b, base, math.min(size, MAX_HEADER)) + if string.sub(text, 1, 3) ~= "ply" or not string.match(string.sub(text, 4, 5), "^\r?\n") then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local h: Header = { encoding = "", elems = {}, comments = {}, objInfo = {}, dataStart = -1 } + local at = 1 + local first = true + while true do + local e = string.find(text, "\n", at, true) + if not e then + if size > MAX_HEADER then + return nil, Err.new(Err.LIMIT, "header longer than 1 MB") + end + return nil, Err.new(Err.TRUNCATED, "no end_header", base + at - 1) + end + local line = string.sub(text, at, e - 1) + if string.sub(line, -1) == "\r" then + line = string.sub(line, 1, -2) + end + local lineAt = base + at - 1 + at = e + 1 + local kw = string.match(line, "^%s*(%S+)") + if first then + first = false -- "ply" + elseif kw == nil then + -- blank line + elseif kw == "end_header" then + h.dataStart = base + at - 1 + break + elseif kw == "comment" or kw == "obj_info" then + local rest = string.match(line, "^%s*%S+ ?(.*)$") or "" + table.insert(if kw == "comment" then h.comments else h.objInfo, rest) + elseif kw == "format" then + local enc, ver = string.match(line, "^%s*format%s+(%S+)%s+(%S+)") + if not enc or not ENCODINGS[enc] then + return nil, Err.new(Err.UNSUPPORTED, "unknown format " .. tostring(enc), lineAt) + end + if string.sub(ver, 1, 1) ~= "1" then + return nil, Err.new(Err.UNSUPPORTED, "version " .. ver, lineAt) + end + h.encoding = enc + elseif kw == "element" then + local name, count = string.match(line, "^%s*element%s+(%S+)%s+(%d+)%s*$") + local n = tonumber(count) + if not name or not n then + return nil, Err.new(Err.CORRUPT, "bad element line", lineAt) + end + table.insert(h.elems, { name = name, count = n, props = {} }) + elseif kw == "property" then + local el = h.elems[#h.elems] + if not el then + return nil, Err.new(Err.CORRUPT, "property before any element", lineAt) + end + local words = {} + for w in string.gmatch(line, "%S+") do + table.insert(words, w) + end + local p: Prop + if words[2] == "list" and #words == 5 then + local cc, ic = CODES[words[3]], CODES[words[4]] + if not cc or not ic then + return nil, Err.new(Err.CORRUPT, "unknown property type in " .. line, lineAt) + end + p = { name = words[5], ply = words[4], code = ic, list = true, countPly = words[3], countCode = cc } + elseif #words == 3 and CODES[words[2]] then + p = { name = words[3], ply = words[2], code = CODES[words[2]], list = false } + else + return nil, Err.new(Err.CORRUPT, "bad property line: " .. string.sub(line, 1, 60), lineAt) + end + for _, q in el.props do + if q.name == p.name then + return nil, Err.new(Err.CORRUPT, "duplicate property " .. p.name, lineAt) + end + end + table.insert(el.props, p) + else + return nil, Err.new(Err.CORRUPT, "unknown header line: " .. string.sub(line, 1, 60), lineAt) + end + end + if h.encoding == "" then + return nil, Err.new(Err.CORRUPT, "no format line", base) + end + return h, nil +end + +-- the reading plan of one element: per property, where its values go +type Plan = { + code: { number }, + isList: { boolean }, + countCode: { number }, + dst: { buffer }, + dOff: { number }, + dStride: { number }, + dCode: { number }, + sizes: { buffer }, + bound: { number }, + totals: { number }, +} + +local function newPlan(e: Elem): Plan + local np = #e.props + local pl: Plan = { + code = table.create(np, 0), + isList = table.create(np, false), + countCode = table.create(np, 2), + dst = table.create(np), + dOff = table.create(np, 0), + dStride = table.create(np, 0), + dCode = table.create(np, 0), + sizes = table.create(np), + bound = table.create(np, -1), + totals = table.create(np, 0), + } + for k, p in e.props do + pl.code[k] = p.code + pl.isList[k] = p.list + pl.countCode[k] = p.countCode or 2 + pl.dCode[k] = p.code + pl.dStride[k] = SIZE[p.code] + end + return pl +end + +-- unset scalar destinations get their own native buffer +local function ownBuffers(e: Elem, pl: Plan) + for k, p in e.props do + if not p.list and pl.dst[k] == nil then + pl.dst[k] = buffer.create(e.count * SIZE[p.code]) + end + end +end + +-- read one element's rows (binary) into the plan; returns the next offset or nil, Err +local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boolean): (number?, Err.Err?) + local b, limit, n, np = r.buf, r.limit, e.count, #e.props + local hasList, rowSize = false, 0 + for k, pr in e.props do + if pr.list then + hasList = true + rowSize += SIZE[pr.countCode :: number] + else + rowSize += SIZE[pr.code] + end + end + if n * rowSize > limit - p then + return nil, Err.new(Err.TRUNCATED, string.format("element %s: %d rows need at least %d bytes", e.name, n, n * rowSize), p) + end + if not hasList then + ownBuffers(e, pl) + local srcOff = table.create(np, 0) + local o = 0 + for k, pr in e.props do + srcOff[k] = o + o += SIZE[pr.code] + end + Binary.fixed(b, p, n, rowSize, np, srcOff, pl.code, be, pl.dst, pl.dOff, pl.dStride, pl.dCode) + return p + n * rowSize, nil + end + local q, totals = Binary.scan(b, p, limit, n, np, pl.code, pl.isList, pl.countCode, be) + if q < 0 then + return nil, Err.new(if totals == "bad list count" then Err.CORRUPT else Err.TRUNCATED, "element " .. e.name .. ": " .. tostring(totals), p) + end + ownBuffers(e, pl) + for k, pr in e.props do + if pr.list then + pl.totals[k] = totals[k] + pl.sizes[k] = buffer.create(n * 4) + pl.dst[k] = buffer.create(totals[k] * SIZE[pl.dCode[k]]) + end + end + local ok, msg = Binary.rows(b, p, n, np, pl.code, pl.isList, pl.countCode, be, pl.dst, pl.dOff, pl.dStride, pl.dCode, pl.sizes, pl.bound) + if not ok then + return nil, Err.new(Err.CORRUPT, "element " .. e.name .. ": " .. tostring(msg), p) + end + return q, nil +end + +-- a token as a value of type code, or nil +local function value(tok: string?, code: number): number? + if tok == nil then + return nil + end + local v = tonumber(tok) + if v == nil then + return nil + end + local rg = RANGE[code] + if rg and (v ~= v // 1 or v < rg[1] or v > rg[2]) then + return nil + end + return v +end + +-- read one element's rows (ascii) from the token stream +local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err? + ownBuffers(e, pl) + local n = e.count + local listSizes: { [number]: { number } } = {} + local listItems: { [number]: { number } } = {} + for k, p in e.props do + if p.list then + listSizes[k] = table.create(n) + listItems[k] = {} + end + end + local wr = Binary.wr + for i = 0, n - 1 do + for k, p in e.props do + if p.list then + local t = nextTok() + local c = value(t, p.countCode :: number) + if c == nil or c < 0 or c % 1 ~= 0 then + return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad list count", e.name, i)) + end + listSizes[k][i + 1] = c + local items, bd, code = listItems[k], pl.bound[k], p.code + for _ = 1, c do + local t2 = nextTok() + local v = value(t2, code) + if v == nil then + return Err.new(if t2 == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad value", e.name, i)) + end + if bd >= 0 and (v < 0 or v >= bd or v ~= v // 1) then + return Err.new(Err.CORRUPT, string.format("element %s row %d: vertex index out of range", e.name, i)) + end + table.insert(items, v) + end + else + local t = nextTok() + local v = value(t, p.code) + if v == nil then + return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad %s value", e.name, i, p.name)) + end + wr(pl.dst[k], pl.dOff[k] + i * pl.dStride[k], pl.dCode[k], v) + end + end + end + for k in listSizes do + local sz, items = listSizes[k], listItems[k] + local s = buffer.create(n * 4) + for i = 1, n do + buffer.writeu32(s, (i - 1) * 4, sz[i]) + end + local dc = pl.dCode[k] + local d = buffer.create(#items * SIZE[dc]) + for j = 1, #items do + wr(d, (j - 1) * SIZE[dc], dc, items[j]) + end + pl.sizes[k], pl.dst[k], pl.totals[k] = s, d, #items + end + return nil +end + +local function propIndex(e: Elem, name: string): number? + for k, p in e.props do + if p.name == name then + return k + end + end + return nil +end + +-- vertex element -> attributes: sets the plan's destinations, returns the attribute table +local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Err.Err?) + local nv = e.count + local attrs: { [string]: Types.Accessor } = {} + local taken: { [number]: boolean } = {} + for _, p in e.props do + if p.list then + return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element") + end + end + -- group(attr, names, required, ok, comps, fill): the first `required` names must exist, the others are optional + local function group(attr: string, names: { string }, required: number, ok: (codes: { number }) -> number?, comps: number, fillValue: number?) + local ks: { [number]: number } = {} + local codes = {} + for i, nm in names do + local k = propIndex(e, nm) + if k == nil then + if i <= required then + return + end + else + ks[i] = k + table.insert(codes, e.props[k].code) + end + end + local dc = ok(codes) + if dc == nil then + return + end + local sz = SIZE[dc] + local buf = buffer.create(nv * comps * sz) + if fillValue then + for i = 0, nv - 1 do + Binary.wr(buf, (i * comps + comps - 1) * sz, dc, fillValue) + end + end + for i, k in ks do + pl.dst[k], pl.dOff[k], pl.dStride[k], pl.dCode[k] = buf, (i - 1) * sz, comps * sz, dc + taken[k] = true + end + local accType = if attr == "COLOR_0" and dc == 2 then "unorm8" elseif attr == "COLOR_0" and dc == 4 then "unorm16" else ACC_TYPE[dc] + attrs[attr] = Types.Scene.accessor(buf, accType, comps, nv) + end + local function floats(codes: { number }): number? + for _, c in codes do + if c ~= 7 and c ~= 8 then + return nil + end + end + return 7 + end + local function anyNumber(_codes: { number }): number? + return 7 + end + group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil) + group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil) + -- colours: one type class for all channels + do + local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha") + if rk and gk and bk then + local codes = { e.props[rk].code, e.props[gk].code, e.props[bk].code } + if ak then + table.insert(codes, e.props[ak].code) + end + local cls: number? = codes[1] + for _, c in codes do + local a = if c == 8 then 7 else c + local b0 = if cls == 8 then 7 else cls + if a ~= b0 then + cls = nil + end + end + local dc = if cls == 2 then 2 elseif cls == 4 then 4 elseif cls == 7 or cls == 8 then 7 else nil + if dc then + group("COLOR_0", { "red", "green", "blue", "alpha" }, 3, function() + return dc + end, 4, if dc == 2 then 255 elseif dc == 4 then 65535 else 1) + end + end + end + for _, pair in TEXCOORD_PAIRS do + if attrs.TEXCOORD_0 == nil then + group("TEXCOORD_0", pair, 2, floats, 2, nil) + end + end + for k, p in e.props do + if not taken[k] then + local buf = buffer.create(nv * SIZE[p.code]) + pl.dst[k] = buf + attrs["_" .. p.name] = Types.Scene.accessor(buf, ACC_TYPE[p.code], 1, nv) + end + end + return attrs, nil +end + +-- the fan triangulation of faces with sizes / corners; returns indices (u32), triangle count, faceOfTriangle +local function fan(sizes: buffer, corners: buffer, nf: number): (buffer, number, buffer) + local nt = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + if s >= 3 then + nt += s - 2 + end + end + local idx, fot = buffer.create(nt * 12), buffer.create(nt * 4) + local p, t = 0, 0 + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + for f = 0, nf - 1 do + local s = readu32(sizes, f * 4) + local a = readu32(corners, p * 4) + for k = 1, s - 2 do + writeu32(idx, t * 12, a) + writeu32(idx, t * 12 + 4, readu32(corners, (p + k) * 4)) + writeu32(idx, t * 12 + 8, readu32(corners, (p + k + 1) * 4)) + writeu32(fot, t * 4, f) + t += 1 + end + p += s + end + return idx, nt, fot +end + +function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = true + if opts and opts.triangulate == false then + triangulate = false + end + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local h, herr = parseHeader(r) + if not h then + return nil, herr + end + local vi, fi, idxK + for i, e in h.elems do + if e.name == "vertex" and vi == nil then + vi = i + if e.count > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", e.count, maxVertices)) + end + elseif e.name == "face" and fi == nil then + local k = propIndex(e, "vertex_indices") or propIndex(e, "vertex_index") + if k and e.props[k].list then + fi, idxK = i, k + end + end + if e.count > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("element %s: %d rows is over the %d limit", e.name, e.count, maxFaces)) + end + end + if vi == nil then + return nil, Err.new(Err.CORRUPT, "no vertex element") + end + local nv = h.elems[vi].count + local be = h.encoding == "binary_big_endian" + local ascii = h.encoding == "ascii" + local nextTok: () -> string? = function() + return nil + end + if ascii then + local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart) + -- each value takes at least 2 bytes (a digit and a separator): bound the counts before allocating + local need = 0 + for _, e in h.elems do + need += e.count * #e.props + end + if need > (#body + 1) // 2 then + return nil, Err.new(Err.TRUNCATED, "fewer values than the element counts need", h.dataStart) + end + nextTok = string.gmatch(body, "%S+") :: any + end + local plans: { Plan } = {} + local attrs: { [string]: Types.Accessor } = {} + local p = h.dataStart + if not ascii then + -- every row takes at least its scalar sizes and list counts: bound the counts before allocating + local need = 0 + for _, e in h.elems do + local row = 0 + for _, pr in e.props do + row += SIZE[if pr.list then pr.countCode :: number else pr.code] + end + need += e.count * row + end + if need > r.limit - h.dataStart then + return nil, Err.new(Err.TRUNCATED, string.format("the elements need at least %d bytes, %d left", need, r.limit - h.dataStart), h.dataStart) + end + end + for i, e in h.elems do + local pl = newPlan(e) + plans[i] = pl + if i == vi then + local a, aerr = planVertex(e, pl) + if not a then + return nil, aerr + end + attrs = a + elseif i == fi then + pl.dCode[idxK] = 6 + pl.bound[idxK] = nv + end + if ascii then + local err = readAscii(nextTok, e, pl) + if err then + return nil, err + end + else + local q, err = readBinary(r, p, e, pl, be) + if not q then + return nil, err + end + p = q + end + end + -- the primitive + local prim: Types.Primitive = { attributes = attrs, mode = "points" } + local nf = 0 + local extras: { [string]: any } = {} + local faceProps: { any } = {} + if fi then + local e, pl = h.elems[fi], plans[fi] + nf = e.count + local sizes, corners, total = pl.sizes[idxK], pl.dst[idxK], pl.totals[idxK] + local faceAttributes: { [string]: Types.Accessor } = {} + local faceLists: { [string]: any } = {} + local anyExtra = false + for k, pr in e.props do + table.insert(faceProps, { name = pr.name, type = pr.ply, countType = pr.countPly }) + if k ~= idxK then + anyExtra = true + if pr.list then + faceLists[pr.name] = { + countType = pr.countPly, + itemType = pr.ply, + sizes = Types.Scene.accessor(pl.sizes[k], "u32", 1, nf), + items = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, pl.totals[k]), + } + else + faceAttributes[pr.name] = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, nf) + end + end + end + if next(faceAttributes) then + extras.faceAttributes = faceAttributes + end + if next(faceLists) then + extras.faceLists = faceLists + end + if nf > 0 then + local allTri = total == nf * 3 + if allTri then + for f = 0, nf - 1 do + if buffer.readu32(sizes, f * 4) ~= 3 then + allTri = false + break + end + end + end + if allTri then + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + elseif triangulate then + local idx, nt, fot = fan(sizes, corners, nf) + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(idx, "u32", 1, nt * 3) + if anyExtra then + extras.faceOfTriangle = Types.Scene.accessor(fot, "u32", 1, nt) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + end + if next(extras) then + prim.extras = extras + end + -- raw elements, element order, property order + local elements: { any } = {} + local order: { string } = {} + for i, e in h.elems do + table.insert(order, e.name) + if i ~= vi and i ~= fi then + local pl = plans[i] + local props = {} + for k, pr in e.props do + props[k] = { name = pr.name, type = pr.ply, countType = pr.countPly, values = pl.dst[k], sizes = pl.sizes[k], total = if pr.list then pl.totals[k] else nil } + end + table.insert(elements, { name = e.name, count = e.count, properties = props }) + end + end + local vprops = {} + for _, pr in h.elems[vi].props do + table.insert(vprops, { name = pr.name, type = pr.ply }) + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "ply", encoding = h.encoding, vertices = nv, faces = nf } + scene.meta.ply = { + comments = h.comments, + objInfo = h.objInfo, + elements = elements, + order = order, + vertexProperties = vprops, + faceProperties = if fi then faceProps else nil, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- a column to write: ply type code + spelling, the values (one per row, or per row * stride at offset) +type Column = { name: string, ply: string, code: number, values: { number }, stride: number, offset: number } +type ListColumn = { name: string, ply: string, code: number, countPly: string, countCode: number, sizes: { number }, items: { number } } + +local function keep(name: string): boolean + return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_" +end + +-- the spelling `want` from the source file when it means the same type as code, else the classic name +local function spell(want: string?, code: number): string + if want and CODES[want] == code then + return want + end + return PLY_NAME[code] +end + +local function toInt(v: number, code: number): number + local rg = RANGE[code] + if rg then + if v ~= v then + return 0 + end + return math.clamp(math.floor(v + 0.5), rg[1], rg[2]) + end + return v +end + +-- write rows of columns (+ list columns, in `order`) for n rows: ascii lines into out, binary into the writer +type Row = { kind: "s", col: Column } | { kind: "l", col: ListColumn } + +local function rowsAscii(out: { string }, n: number, cols: { Row }) + local fmt = string.format + local function num(code: number, v: number): string + if code == 7 then + return fmt("%.9g", v) + elseif code == 8 then + return fmt("%.17g", v) + end + return fmt("%d", toInt(v, code)) + end + local at: { [number]: number } = {} + for i = 0, n - 1 do + local parts = {} + for k, c in cols do + if c.kind == "s" then + local col = c.col :: Column + table.insert(parts, num(col.code, col.values[i * col.stride + col.offset + 1])) + else + local col = c.col :: ListColumn + local s = col.sizes[i + 1] + table.insert(parts, fmt("%d", s)) + local a = at[k] or 0 + for j = 1, s do + table.insert(parts, num(col.code, col.items[a + j])) + end + at[k] = a + s + end + end + table.insert(out, table.concat(parts, " ")) + end +end + +local function rowsBinary(w: Bytes.Writer, n: number, cols: { Row }, be: boolean) + local size = 0 + for _, c in cols do + if c.kind == "s" then + size += n * SIZE[(c.col :: Column).code] + else + local col = c.col :: ListColumn + size += n * SIZE[col.countCode] + #col.items * SIZE[col.code] + end + end + local o = w:reserve(size) + local d = w.buf + local put = Binary.put + local at: { [number]: number } = {} + for i = 0, n - 1 do + for k, c in cols do + if c.kind == "s" then + local col = c.col :: Column + local code = col.code + put(d, o, code, toInt(col.values[i * col.stride + col.offset + 1], code), be) + o += SIZE[code] + else + local col = c.col :: ListColumn + local s = col.sizes[i + 1] + put(d, o, col.countCode, s, be) + o += SIZE[col.countCode] + local a, code = at[k] or 0, col.code + for j = 1, s do + put(d, o, code, toInt(col.items[a + j], code), be) + o += SIZE[code] + end + at[k] = a + s + end + end + end + w.pos = o +end + +-- numbers of a raw element column (buffer of a ply type) +local function bufNumbers(b: any, code: number, count: number): { number }? + if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then + return nil + end + local out = table.create(count) + for i = 0, count - 1 do + out[i + 1] = Binary.rd(b, i * SIZE[code], code, false) + end + return out +end + +-- the list count type for a maximum count +local function countCodeFor(maxCount: number): number + return if maxCount <= 255 then 2 elseif maxCount <= 65535 then 4 else 6 +end + +function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local enc = o.format or "binary_little_endian" + if not ENCODINGS[enc] then + return nil, Err.new(Err.ARG, "format must be ascii, binary_little_endian or binary_big_endian") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local meta: any = if type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" then scene.meta.ply else {} + local nv = m.count + -- source property spellings / order + local srcType: { [string]: string } = {} + local srcOrder: { [string]: number } = {} + if type(meta.vertexProperties) == "table" then + for i, vp in meta.vertexProperties do + if type(vp) == "table" and type(vp.name) == "string" then + srcType[vp.name] = vp.type + srcOrder[vp.name] = i + end + end + end + local cols: { Column } = {} + local function add(name: string, code: number, a: Flatten.Attr, comp: number) + table.insert(cols, { name = name, ply = spell(srcType[name], code), code = code, values = a.values, stride = a.components, offset = comp }) + end + local function floatCode(name: string): number + return if CODES[srcType[name] or ""] == 8 then 8 else 7 + end + local A = m.attrs + for i, nm in { "x", "y", "z" } do + add(nm, floatCode(nm), A.POSITION, i - 1) + end + if A.NORMAL then + for i, nm in { "nx", "ny", "nz" } do + add(nm, floatCode(nm), A.NORMAL, i - 1) + end + end + local C = A.COLOR_0 + if C then + local code = if C.raw and C.type == "unorm8" then 2 elseif C.raw and C.type == "unorm16" then 4 else 7 + if C.raw and code == 7 then + -- another normalized type: as floats + local vals = table.create(#C.values) + local scale = if C.type == "snorm8" then 127 else 32767 + for i, v in C.values do + vals[i] = math.max(v / scale, -1) + end + C = { type = "f32", components = C.components, raw = false, values = vals } + end + local cc = C :: Flatten.Attr + for i, nm in { "red", "green", "blue" } do + if i <= cc.components then + add(nm, code, cc, i - 1) + end + end + if cc.components >= 4 then + local full = if code == 2 then 255 elseif code == 4 then 65535 else 1 + local need = srcOrder.alpha ~= nil + if not need then + for i = 0, nv - 1 do + if cc.values[i * cc.components + 4] ~= full then + need = true + break + end + end + end + if need then + add("alpha", code, cc, 3) + end + end + end + if A.TEXCOORD_0 then + local names = { "s", "t" } + for _, pair in TEXCOORD_PAIRS do + if srcOrder[pair[1]] and srcOrder[pair[2]] then + names = pair + break + end + end + local tc = A.TEXCOORD_0 + if tc.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + add(names[1], floatCode(names[1]), tc, 0) + if tc.components >= 2 then + add(names[2], floatCode(names[2]), tc, 1) + end + end + local customs = {} + for name in A do + if string.sub(name, 1, 1) == "_" then + table.insert(customs, name) + end + end + table.sort(customs) + for _, name in customs do + local a = A[name] + local code = CODE_OF_ACC[a.type] or 7 + local base = string.sub(name, 2) + if a.components == 1 then + add(base, code, a, 0) + else + for c = 0, a.components - 1 do + add(base .. "_" .. c, code, a, c) + end + end + end + -- the source order first (stable for the rest) + local rank: { [Column]: number } = {} + for i, c in cols do + rank[c] = (srcOrder[c.name] or (1000000 + i)) + end + table.sort(cols, function(a: Column, b: Column): boolean + return rank[a] < rank[b] + end) + -- faces + local faceRows: { Row }? = nil + local nf = 0 + if m.sizes then + local sizes = m.sizes :: { number } + nf = #sizes + local maxS, maxI = 0, 0 + for _, s in sizes do + maxS = math.max(maxS, s) + end + for _, c in m.corners do + maxI = math.max(maxI, c) + end + local fprops: { any } = if type(meta.faceProperties) == "table" then meta.faceProperties else {} + local idxName, idxType, idxCount = "vertex_indices", nil, nil + for _, fp in fprops do + if type(fp) == "table" and (fp.name == "vertex_indices" or fp.name == "vertex_index") then + idxName, idxType, idxCount = fp.name, fp.type, fp.countType + end + end + local cc = countCodeFor(maxS) + local srcCC = CODES[idxCount or ""] + if srcCC and srcCC <= 6 and SIZE[srcCC] >= SIZE[cc] then + cc = srcCC + end + local ic = if maxI < 2147483648 then 5 else 6 + local srcIC = CODES[idxType or ""] + if srcIC == 6 or (srcIC and srcIC <= 6 and maxI <= RANGE[srcIC][2]) then + ic = srcIC + end + local rows: { Row } = { + { kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } }, + } + -- per-face data of a single primitive + if #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fot: { number }? = nil + if type(ex) == "table" and ex.faceOfTriangle then + fot = Flatten.numbers(ex.faceOfTriangle, true) + end + local function perFace(vals: { number }, count: number): { number }? + if count == nf then + return vals + elseif fot and #fot == nf then + local out = table.create(nf) + for i = 1, nf do + local v = vals[fot[i] + 1] + if v == nil then + return nil + end + out[i] = v + end + return out + end + return nil + end + local extraRows: { [string]: Row } = {} + if type(ex) == "table" and type(ex.faceAttributes) == "table" then + for name, acc in ex.faceAttributes do + local vals = Flatten.numbers(acc, true) + local code = CODE_OF_ACC[acc.type] + if vals and code and acc.components == 1 then + local pv = perFace(vals, acc.count) + if pv then + extraRows[name] = { kind = "s", col = { name = name, ply = PLY_NAME[code], code = code, values = pv, stride = 1, offset = 0 } } + end + end + end + end + if type(ex) == "table" and type(ex.faceLists) == "table" then + for name, fl in ex.faceLists do + local sz = type(fl) == "table" and Flatten.numbers(fl.sizes, true) + local items = type(fl) == "table" and Flatten.numbers(fl.items, true) + local code = type(fl) == "table" and (CODES[fl.itemType or ""] or CODE_OF_ACC[fl.items and fl.items.type or ""]) + if sz and items and code and #sz == nf and fot == nil then + local mx = 0 + for _, s in sz do + mx = math.max(mx, s) + end + local lcc = countCodeFor(mx) + local scc = CODES[fl.countType or ""] + if scc and scc <= 6 and SIZE[scc] >= SIZE[lcc] then + lcc = scc + end + extraRows[name] = { kind = "l", col = { name = name, ply = spell(fl.itemType, code), code = code, countPly = spell(fl.countType, lcc), countCode = lcc, sizes = sz, items = items } } + end + end + end + -- the source order, then the rest by name + local placed: { [string]: boolean } = { [idxName] = true } + local ordered: { Row } = {} + for _, fp in fprops do + if type(fp) == "table" then + if fp.name == idxName then + table.insert(ordered, rows[1]) + elseif extraRows[fp.name] then + table.insert(ordered, extraRows[fp.name]) + placed[fp.name] = true + end + end + end + if not table.find(ordered, rows[1]) then + table.insert(ordered, 1, rows[1]) + end + local rest = {} + for name in extraRows do + if not placed[name] then + table.insert(rest, name) + end + end + table.sort(rest) + for _, name in rest do + table.insert(ordered, extraRows[name]) + end + rows = ordered + end + faceRows = rows + end + -- raw elements + type Raw = { name: string, count: number, rows: { Row } } + local raws: { [string]: Raw } = {} + local rawOrder: { string } = {} + if type(meta.elements) == "table" then + for _, el in meta.elements do + if type(el) == "table" and type(el.name) == "string" and type(el.count) == "number" and type(el.properties) == "table" and el.name ~= "vertex" and not raws[el.name] then + if el.name == "face" and faceRows then + continue + end + local rows: { Row } = {} + for _, pr in el.properties do + local code = CODES[pr.type or ""] + if not code then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": unknown property type") + end + if pr.countType then + local cc = CODES[pr.countType] + local sz = cc and bufNumbers(pr.sizes, 6, el.count) + local total = 0 + if sz then + for _, s in sz do + total += s + end + end + local items = sz and bufNumbers(pr.values, code, total) + if not (cc and sz and items) then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad list property " .. tostring(pr.name)) + end + table.insert(rows, { kind = "l", col = { name = pr.name, ply = pr.type, code = code, countPly = pr.countType, countCode = cc, sizes = sz, items = items } }) + else + local vals = bufNumbers(pr.values, code, el.count) + if not vals then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad property " .. tostring(pr.name)) + end + table.insert(rows, { kind = "s", col = { name = pr.name, ply = pr.type, code = code, values = vals, stride = 1, offset = 0 } }) + end + end + raws[el.name] = { name = el.name, count = el.count, rows = rows } + table.insert(rawOrder, el.name) + end + end + end + -- element order: the source's, then vertex, face, the rest + local order: { string } = {} + local seen: { [string]: boolean } = {} + local function want(name: string) + if seen[name] then + return + end + if name == "vertex" or (name == "face" and faceRows) or raws[name] then + seen[name] = true + table.insert(order, name) + end + end + if type(meta.order) == "table" then + for _, name in meta.order do + if type(name) == "string" then + want(name) + end + end + end + want("vertex") + want("face") + for _, name in rawOrder do + want(name) + end + -- header + local vrows: { Row } = {} + for _, c in cols do + table.insert(vrows, { kind = "s", col = c }) + end + local lines = { "ply", "format " .. enc .. " 1.0" } + local function noNewline(s: any): string + return (string.gsub(tostring(s), "[\r\n]", " ")) + end + for _, c in (if type(meta.comments) == "table" then meta.comments else {}) :: { any } do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in o.comments or {} do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in (if type(meta.objInfo) == "table" then meta.objInfo else {}) :: { any } do + table.insert(lines, "obj_info " .. noNewline(c)) + end + local function elementRows(name: string): (number, { Row }) + if name == "vertex" then + return nv, vrows + elseif name == "face" and faceRows then + return nf, faceRows + end + local raw = raws[name] + return raw.count, raw.rows + end + for _, name in order do + local n, rows = elementRows(name) + table.insert(lines, "element " .. noNewline(name) .. " " .. string.format("%d", n)) + for _, rw in rows do + if rw.kind == "s" then + local c = rw.col :: Column + table.insert(lines, "property " .. c.ply .. " " .. noNewline(c.name)) + else + local c = rw.col :: ListColumn + table.insert(lines, "property list " .. c.countPly .. " " .. c.ply .. " " .. noNewline(c.name)) + end + end + end + table.insert(lines, "end_header") + local header = table.concat(lines, "\n") .. "\n" + if enc == "ascii" then + local out = { header } + local body: { string } = {} + for _, name in order do + local n, rows = elementRows(name) + rowsAscii(body, n, rows) + end + if #body > 0 then + table.insert(out, table.concat(body, "\n")) + table.insert(out, "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + local w = Bytes.writer(#header + nv * 32 + nf * 16) + w:string(header) + for _, name in order do + local n, rows = elementRows(name) + rowsBinary(w, n, rows, enc == "binary_big_endian") + end + return w:finish(), nil +end + +return Ply diff --git a/src/Formats/model/stl/Decode.luau b/src/Formats/model/stl/Decode.luau new file mode 100644 index 0000000..d99ad3c --- /dev/null +++ b/src/Formats/model/stl/Decode.luau @@ -0,0 +1,77 @@ +--!strict +--!native +--!optimize 2 +-- model/stl/Decode: the binary STL facet loop (50 bytes per facet: normal, 3 vertices, u16 attribute) and the 5-5-5 +-- colour expansion of the VisCAM / SolidView and Materialise Magics conventions. The caller (init) has checked that +-- the facets fit in the data and allocated the outputs, so every index here is in range; nothing here throws. +local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift + +local Decode = {} + +-- binary(b, p, n, pos, nrm, attr) -> the OR of every attribute word. Copies the vertices (f32 bits as they are) into +-- pos (n * 36 bytes), the facet normal three times into nrm (n * 36 bytes) and the attributes into attr (n * 2 bytes). +function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number + local any = 0 + for i = 0, n - 1 do + local q = p + i * 50 + local o = i * 36 + local nx, ny, nz = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + writeu32(nrm, o, nx) + writeu32(nrm, o + 4, ny) + writeu32(nrm, o + 8, nz) + writeu32(nrm, o + 12, nx) + writeu32(nrm, o + 16, ny) + writeu32(nrm, o + 20, nz) + writeu32(nrm, o + 24, nx) + writeu32(nrm, o + 28, ny) + writeu32(nrm, o + 32, nz) + writeu32(pos, o, readu32(b, q + 12)) + writeu32(pos, o + 4, readu32(b, q + 16)) + writeu32(pos, o + 8, readu32(b, q + 20)) + writeu32(pos, o + 12, readu32(b, q + 24)) + writeu32(pos, o + 16, readu32(b, q + 28)) + writeu32(pos, o + 20, readu32(b, q + 32)) + writeu32(pos, o + 24, readu32(b, q + 36)) + writeu32(pos, o + 28, readu32(b, q + 40)) + writeu32(pos, o + 32, readu32(b, q + 44)) + local a = readu16(b, q + 48) + writeu16(attr, i * 2, a) + any = bor(any, a) + end + return any +end + +-- 5-bit -> 8-bit, rounded +local function x8(v: number): number + return (v * 255 + 15) // 31 +end + +-- colors(attr, n, magics, r, g, b, a, out): unorm8 RGBA per vertex (n * 12 bytes). VisCAM: bit 15 set = valid, +-- red in bits 10..14, blue in 0..4 (invalid facets get r, g, b, a). Magics: bit 15 clear = the facet's own colour, +-- red in bits 0..4, blue in 10..14 (set: the object colour r, g, b, a). +function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer) + for i = 0, n - 1 do + local w = readu16(attr, i * 2) + local r, g, bl, al = dr, dg, db, da + local own = if magics then w < 0x8000 else w >= 0x8000 + if own then + local lo, mid, hi = x8(band(w, 31)), x8(band(rshift(w, 5), 31)), x8(band(rshift(w, 10), 31)) + g, al = mid, 255 + if magics then + r, bl = lo, hi + else + r, bl = hi, lo + end + end + local o = i * 12 + for k = 0, 2 do + writeu8(out, o + k * 4, r) + writeu8(out, o + k * 4 + 1, g) + writeu8(out, o + k * 4 + 2, bl) + writeu8(out, o + k * 4 + 3, al) + end + end +end + +return Decode diff --git a/src/Formats/model/stl/init.luau b/src/Formats/model/stl/init.luau new file mode 100644 index 0000000..50cfe41 --- /dev/null +++ b/src/Formats/model/stl/init.luau @@ -0,0 +1,467 @@ +--!strict +-- model/stl: STL (3D Systems stereolithography), ASCII and binary, read + write. Written from the format description +-- (Wikipedia "STL (file format)" and the 3D Systems SLC spec). +-- Decode: a triangle soup, 3 vertices per facet, no indices: POSITION f32 x3, NORMAL f32 x3 (the facet normal from the +-- file on each of its vertices), COLOR_0 unorm8 x4 when the binary file uses a colour convention (VisCAM / SolidView: +-- attribute bit 15 = colour valid, RGB 5-5-5 with red high; Materialise Magics: "COLOR=" rgba in the header is the +-- object colour, bit 15 clear = the facet's own colour, red low). Other non-zero attribute words are kept per facet in +-- prim.extras.faceAttributes.attribute (u16). Binary files may start with "solid": a file whose size is exactly +-- 84 + 50 * count is binary. ASCII: keywords in any case, any whitespace, several solids (one primitive per solid in +-- one mesh, prim.extras.solid = its name), facets with more than 3 vertices are fan-triangulated, a missing final +-- endsolid is tolerated. meta.up = "z"; meta.source = { format, binary, header, colors, defaultColor, material, +-- solids, facets }. +-- Encode: every primitive of the scene in world space (node transforms applied; polygons / strips / fans +-- fan-triangulated, points and lines skipped), binary (default) or ASCII (one solid per primitive, named after +-- prim.extras.solid / the mesh / the node, made distinct), facet normals computed from the triangle +-- (right-hand rule) unless opts.normals = "attribute", colours from COLOR_0 (the facet's first vertex) in either +-- convention. Not supported: binary-only extensions other than the two colour conventions. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Decode = require("@formats/model/stl/Decode") +local Flatten = require("@formats/codecs/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Stl = { + name = "stl", + category = "model", + extensions = { "stl" }, + mime = { "model/stl", "application/sla" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFaces: number?, -- refuse more facets (default 2^25) + colors: ("auto" | "viscam" | "magics" | "none")?, -- binary colour convention (default "auto": "COLOR=" in the + -- header = magics, else any attribute with bit 15 set = viscam, else none) +} +export type EncodeOptions = { + ascii: boolean?, -- default false (binary) + colors: ("viscam" | "magics")?, -- write COLOR_0 (the first vertex of each facet) in that convention (binary only) + defaultColor: { number }?, -- magics: the object colour r, g, b, a 0..255 (default opaque white); facets of exactly + -- that colour refer to it, the others carry their own (alpha 255) + name: string?, -- the ASCII solid name (default: the mesh / node name, else "mesh") + header: string?, -- the binary header text (at most 80 bytes; default "formats-luau STL") + normals: ("compute" | "attribute")?, -- facet normals from the triangle (default) or the first vertex's NORMAL +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8, readu32 = buffer.readu8, buffer.readu32 +local writef32, writeu16, writeu32 = buffer.writef32, buffer.writeu16, buffer.writeu32 + +local function lower5(s: string): boolean + return string.lower(s) == "solid" +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Stl.sniff(r: Bytes.Reader): number + local size = r:remaining() + if size >= 84 then + local c = r:peek(4, 80) + local n = string.byte(c, 1) + string.byte(c, 2) * 256 + string.byte(c, 3) * 65536 + string.byte(c, 4) * 16777216 + if 84 + 50 * n == size then + return 0.9 + end + end + local head = r:peek(512) + local s = string.match(head, "^%s*(%a+)") + if s and lower5(s) then + local l = string.lower(head) + return if string.find(l, "facet", 1, true) or string.find(l, "endsolid", 1, true) then 0.9 else 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function soupPrim(n: number, pos: buffer, nrm: buffer): Types.Primitive + return { + attributes = { + POSITION = Types.Scene.accessor(pos, "f32", 3, n * 3), + NORMAL = Types.Scene.accessor(nrm, "f32", 3, n * 3), + }, + mode = "triangles", + } +end + +local function decodeBinary(r: Bytes.Reader, maxFaces: number, colors: string): (Types.Scene?, Err.Err?) + local b, base, size = r.buf, r.base, r.limit - r.base + local n = readu32(b, base + 80) + if n > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("%d facets is over the %d facet limit", n, maxFaces), base + 80) + end + if 84 + 50 * n > size then + return nil, Err.new(Err.TRUNCATED, string.format("%d facets need %d bytes, the file has %d", n, 84 + 50 * n, size), base + 80) + end + local pos, nrm, attr = buffer.create(n * 36), buffer.create(n * 36), buffer.create(n * 2) + local any = Decode.binary(b, base + 84, n, pos, nrm, attr) + local header = buffer.readstring(b, base, 80) + local cut = string.find(header, "\0", 1, true) -- the text before the first NUL + local text = if cut then string.sub(header, 1, cut - 1) else header + local mode = colors + local ci = string.find(header, "COLOR=", 1, true) + if mode == "auto" then + mode = if ci and ci + 9 <= 80 then "magics" elseif any >= 0x8000 then "viscam" else "none" + end + local prim = soupPrim(n, pos, nrm) + local source: { [string]: any } = { format = "stl", binary = true, header = text, facets = n } + if mode == "viscam" or mode == "magics" then + local dc = { 255, 255, 255, 255 } + if mode == "magics" and ci and ci + 9 <= 80 then + local o = base + ci + 5 -- the 4 bytes after "COLOR=" (ci is 1-based) + dc = { readu8(b, o), readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) } + source.defaultColor = dc + local mi = string.find(header, "MATERIAL=", 1, true) + if mi and mi + 8 + 12 <= 80 then + local m = base + mi + 8 + local function rgba(k: number): { number } + return { readu8(b, m + k), readu8(b, m + k + 1), readu8(b, m + k + 2), readu8(b, m + k + 3) } + end + source.material = { diffuse = rgba(0), specular = rgba(4), ambient = rgba(8) } + end + end + local col = buffer.create(n * 12) + Decode.colors(attr, n, mode == "magics", dc[1], dc[2], dc[3], dc[4], col) + prim.attributes.COLOR_0 = Types.Scene.accessor(col, "unorm8", 4, n * 3) + source.colors = mode + elseif any ~= 0 then + prim.extras = { faceAttributes = { attribute = Types.Scene.accessor(attr, "u16", 1, n) } } + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.up = "z" + scene.meta.source = source :: any + return scene, nil +end + +local function decodeAscii(r: Bytes.Reader, maxFaces: number): (Types.Scene?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local at = 1 + local function tok(): string? + local s, e = string.find(text, "%S+", at) + if not s then + return nil + end + at = (e :: number) + 1 + return string.sub(text, s, e) + end + local function restOfLine(): string + local e = string.find(text, "\n", at, true) or (#text + 1) + local line = string.sub(text, at, e - 1) + at = e + 1 + return string.match(line, "^%s*(.-)%s*$") or "" + end + local function num(): number? + local t = tok() + return if t then tonumber(t) else nil + end + type Solid = { name: string, pos: { number }, nrm: { number } } + local solids: { Solid } = {} + local facets = 0 + while true do + local t = tok() + if t == nil then + break + end + if string.lower(t) ~= "solid" then + return nil, Err.new(Err.CORRUPT, "expected solid, found " .. string.sub(t, 1, 20)) + end + local cur: Solid = { name = restOfLine(), pos = {}, nrm = {} } + table.insert(solids, cur) + local pos, nrm = cur.pos, cur.nrm + while true do + local w = tok() + if w == nil then + break -- a missing endsolid at the end + end + local lw = string.lower(w) + if lw == "endsolid" then + restOfLine() + break + elseif lw ~= "facet" then + return nil, Err.new(Err.CORRUPT, "expected facet or endsolid, found " .. string.sub(w, 1, 20)) + end + local nx, ny, nz = 0, 0, 0 + local k = tok() + if k and string.lower(k) == "normal" then + local a, bb, c = num(), num(), num() + if a == nil or bb == nil or c == nil then + return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad facet normal") + end + nx, ny, nz = a, bb, c + k = tok() + end + local l2 = tok() + if k == nil or l2 == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + end + if string.lower(k) ~= "outer" or string.lower(l2) ~= "loop" then + return nil, Err.new(Err.CORRUPT, "expected outer loop") + end + local vs: { number } = {} + while true do + local v = tok() + if v == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + end + local lv = string.lower(v) + if lv == "endloop" then + break + elseif lv ~= "vertex" then + return nil, Err.new(Err.CORRUPT, "expected vertex or endloop, found " .. string.sub(v, 1, 20)) + end + local x, y, z = num(), num(), num() + if x == nil or y == nil or z == nil then + return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad vertex") + end + table.insert(vs, x) + table.insert(vs, y) + table.insert(vs, z) + end + local e = tok() + if e == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + elseif string.lower(e) ~= "endfacet" then + return nil, Err.new(Err.CORRUPT, "expected endfacet") + end + local nvs = #vs // 3 + if nvs < 3 then + return nil, Err.new(Err.CORRUPT, "facet with fewer than 3 vertices") + end + for j = 2, nvs - 1 do + for _, vi in { 0, j - 1, j } do + table.insert(pos, vs[vi * 3 + 1]) + table.insert(pos, vs[vi * 3 + 2]) + table.insert(pos, vs[vi * 3 + 3]) + table.insert(nrm, nx) + table.insert(nrm, ny) + table.insert(nrm, nz) + end + facets += 1 + end + if facets > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("over the %d facet limit", maxFaces)) + end + end + end + if #solids == 0 then + return nil, Err.new(Err.TRUNCATED, "no solid") + end + local prims: { Types.Primitive } = {} + local names: { string } = {} + for i, s in solids do + local n = #s.pos // 9 + local pos, nrm = buffer.create(n * 36), buffer.create(n * 36) + for j = 1, n * 9 do + writef32(pos, (j - 1) * 4, s.pos[j]) + writef32(nrm, (j - 1) * 4, s.nrm[j]) + end + local prim = soupPrim(n, pos, nrm) + prim.extras = { solid = s.name } + prims[i] = prim + names[i] = s.name + end + local first = solids[1].name + local scene = Types.Scene.fromPrimitive(prims[1], if first ~= "" then first else nil) + for i = 2, #prims do + table.insert(scene.meshes[1].primitives, prims[i]) + end + scene.meta.up = "z" + scene.meta.source = { format = "stl", binary = false, solids = names, facets = facets } + return scene, nil +end + +function Stl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local colors = opts and opts.colors or "auto" + if colors ~= "auto" and colors ~= "viscam" and colors ~= "magics" and colors ~= "none" then + return nil, Err.new(Err.ARG, "colors must be auto, viscam, magics or none") + end + local size = r.limit - r.base + if size >= 84 and 84 + 50 * readu32(r.buf, r.base + 80) == size then + return decodeBinary(r, maxFaces, colors) + end + local s = string.match(buffer.readstring(r.buf, r.base, math.min(size, 256)), "^%s*(%a+)") + if s and lower5(s) then + return decodeAscii(r, maxFaces) + end + if size < 84 then + return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base) + end + -- binary with extra bytes after the facets (tolerated) or too few (TRUNCATED) + return decodeBinary(r, maxFaces, colors) +end + +-- ------------------------------------------------------------------------------------------------ encode +local scratch = buffer.create(4) +local function f32(v: number): number + writef32(scratch, 0, v) + return buffer.readf32(scratch, 0) +end + +-- a COLOR_0 component as 0..255 +local function byte(a: Flatten.Attr, v: number): number + if a.raw then + if a.type == "unorm16" then + return (v * 255 + 32767) // 65535 + end + return math.clamp(v, 0, 255) + end + return math.floor(math.clamp(v, 0, 1) * 255 + 0.5) +end + +local function to5(c: number): number + return (c * 31 + 127) // 255 +end + +local function keep(name: string): boolean + return name == "NORMAL" or name == "COLOR_0" +end + +function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local colors = o.colors + if colors ~= nil and colors ~= "viscam" and colors ~= "magics" then + return nil, Err.new(Err.ARG, "colors must be viscam or magics") + end + if o.normals ~= nil and o.normals ~= "compute" and o.normals ~= "attribute" then + return nil, Err.new(Err.ARG, "normals must be compute or attribute") + end + if o.header ~= nil and (type(o.header) ~= "string" or #o.header > 80) then + return nil, Err.new(Err.ARG, "header must be a string of at most 80 bytes") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = true }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local P = m.attrs.POSITION.values + local N = if o.normals == "attribute" and m.attrs.NORMAL then m.attrs.NORMAL.values else nil + local C = m.attrs.COLOR_0 + local corners = m.corners + local nf = #corners // 3 + -- facet normal (computed in double from the f32 vertices) and colour of facet f (0-based) + local function normal(f: number): (number, number, number) + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + if N then + return N[a * 3 + 1], N[a * 3 + 2], N[a * 3 + 3] + end + local ax, ay, az = P[a * 3 + 1], P[a * 3 + 2], P[a * 3 + 3] + local ux, uy, uz = P[b * 3 + 1] - ax, P[b * 3 + 2] - ay, P[b * 3 + 3] - az + local vx, vy, vz = P[c * 3 + 1] - ax, P[c * 3 + 2] - ay, P[c * 3 + 3] - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 and l < math.huge then + return nx / l, ny / l, nz / l + end + return 0, 0, 0 + end + if o.ascii then + local out = table.create(nf * 7 + 2 * #m.parts) + local used: { [string]: boolean } = {} + local function fmt(v: number): string? + v = f32(v) + if v ~= v or v == math.huge or v == -math.huge then + return nil + end + return string.format("%.9g", v) + end + for _, part in m.parts do + local name = o.name + if name == nil then + local ex = part.prim.extras + name = if ex and type(ex.solid) == "string" then ex.solid elseif part.mesh and part.mesh.name then part.mesh.name elseif part.node and part.node.name then part.node.name else "mesh" + end + name = string.gsub(tostring(name), "[\r\n]", " ") + if used[name] then -- distinct names: some readers merge solids by name + local k = 2 + while used[name .. "_" .. k] do + k += 1 + end + name = name .. "_" .. k + end + used[name] = true + table.insert(out, "solid " .. name .. "\n") + for f = part.firstFace, part.firstFace + part.faceCount - 1 do + local nx, ny, nz = normal(f) + table.insert(out, string.format(" facet normal %s %s %s\n outer loop\n", fmt(nx) or "0", fmt(ny) or "0", fmt(nz) or "0")) + for k = 1, 3 do + local v = corners[f * 3 + k] * 3 + local x, y, z = fmt(P[v + 1]), fmt(P[v + 2]), fmt(P[v + 3]) + if not (x and y and z) then + return nil, Err.new(Err.ARG, "ASCII STL cannot hold a non-finite coordinate") + end + table.insert(out, " vertex " .. x .. " " .. y .. " " .. z .. "\n") + end + table.insert(out, " endloop\n endfacet\n") + end + table.insert(out, "endsolid " .. name .. "\n") + end + if #m.parts == 0 then + table.insert(out, "solid " .. (o.name or "mesh") .. "\nendsolid " .. (o.name or "mesh") .. "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + -- binary + local buf = buffer.create(84 + 50 * nf) + local header = o.header or "formats-luau STL" + if colors == "magics" then + local dc = o.defaultColor or { 255, 255, 255, 255 } + if type(dc) ~= "table" or #dc < 4 then + return nil, Err.new(Err.ARG, "defaultColor must be { r, g, b, a }") + end + header = string.sub(header, 1, 69) .. " COLOR=" .. string.char(math.clamp(dc[1], 0, 255) // 1, math.clamp(dc[2], 0, 255) // 1, math.clamp(dc[3], 0, 255) // 1, math.clamp(dc[4], 0, 255) // 1) + end + local dcol: { number }? = nil + if colors == "magics" then + local dc = o.defaultColor or { 255, 255, 255, 255 } + dcol = { dc[1] // 1, dc[2] // 1, dc[3] // 1, dc[4] // 1 } + end + buffer.writestring(buf, 0, header) + writeu32(buf, 80, nf) + -- the attribute words: colours, or the raw words of a single STL-decoded primitive + local rawAttr: { number }? = nil + if colors == nil and #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fa = ex and ex.faceAttributes + local acc = fa and fa.attribute + if acc and acc.count == nf then + rawAttr = Flatten.numbers(acc, true) + end + end + for f = 0, nf - 1 do + local q = 84 + f * 50 + local nx, ny, nz = normal(f) + writef32(buf, q, nx) + writef32(buf, q + 4, ny) + writef32(buf, q + 8, nz) + for k = 0, 2 do + local v = corners[f * 3 + k + 1] * 3 + writef32(buf, q + 12 + k * 12, P[v + 1]) + writef32(buf, q + 16 + k * 12, P[v + 2]) + writef32(buf, q + 20 + k * 12, P[v + 3]) + end + local w = 0 + if colors and C then + local a = corners[f * 3 + 1] * C.components + local cv = C.values + local r5, g5, b5 = to5(byte(C, cv[a + 1])), to5(byte(C, cv[a + 2] or 0)), to5(byte(C, cv[a + 3] or 0)) + if colors == "viscam" then + w = 0x8000 + r5 * 1024 + g5 * 32 + b5 + elseif dcol and byte(C, cv[a + 1]) == dcol[1] and byte(C, cv[a + 2] or 0) == dcol[2] and byte(C, cv[a + 3] or 0) == dcol[3] and (if C.components >= 4 then byte(C, cv[a + 4]) else 255) == dcol[4] then + w = 0x8000 -- the object colour + else + w = r5 + g5 * 32 + b5 * 1024 + end + elseif colors == "magics" then + w = 0x8000 -- the object colour + elseif rawAttr then + w = math.clamp(rawAttr[f + 1] // 1, 0, 65535) + end + writeu16(buf, q + 48, w) + end + return buf, nil +end + +return Stl diff --git a/src/Formats/model/vox/Grid.luau b/src/Formats/model/vox/Grid.luau new file mode 100644 index 0000000..4a6601e --- /dev/null +++ b/src/Formats/model/vox/Grid.luau @@ -0,0 +1,61 @@ +--!strict +--!native +-- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI +-- records. Callers check every range first; nothing here throws. +local Grid = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the +-- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted. +-- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz. +function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number + local skipped = 0 + local sxy = sx * sy + for k = 0, n - 1 do + local p = off + k * 4 + local x, y, z, i = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) + if x < sx and y < sy and z < sz and i ~= 0 then + writeu8(dst, x + sx * y + sxy * z, i) + else + skipped += 1 + end + end + return skipped +end + +-- count(data, cells) -> the number of non-empty cells in data[0, cells) +function Grid.count(data: buffer, cells: number): number + local n = 0 + for k = 0, cells - 1 do + if readu8(data, k) ~= 0 then + n += 1 + end + end + return n +end + +-- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest). +-- The caller sizes dst with count() (sx, sy, sz <= 256). +function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number + local p = at + local k = 0 + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + local i = readu8(data, k) + if i ~= 0 then + writeu8(dst, p, x) + writeu8(dst, p + 1, y) + writeu8(dst, p + 2, z) + writeu8(dst, p + 3, i) + p += 4 + end + k += 1 + end + end + end + return p +end + +return Grid diff --git a/src/Formats/model/vox/init.luau b/src/Formats/model/vox/init.luau new file mode 100644 index 0000000..81277aa --- /dev/null +++ b/src/Formats/model/vox/init.luau @@ -0,0 +1,903 @@ +--!strict +-- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt) +-- and the files MagicaVoxel 0.99.x saves (version 150 and 200). +-- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP / +-- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials, +-- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown +-- chunks are kept raw and written back. +-- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per +-- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as +-- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is +-- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes. +-- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must +-- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk. +-- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Grid = require("@formats/model/vox/Grid") + +-- ------------------------------------------------------------------------------------------------ contract +local Vox = { + name = "vox", + category = "model", + extensions = { "vox" }, + mime = { "model/x-vox" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxCells: number?, -- refuse files whose grids hold more cells in total (default 2^27) +} +export type EncodeOptions = { + version: number?, -- the file version (default 200, what MagicaVoxel 0.99.7 writes; 150 is the older one) +} +type Dict = { [string]: string } +type GraphNode = { + kind: string, + id: number, + attrs: Dict, + child: number?, + layer: number?, + frames: { Dict }?, + children: { number }?, + models: { { model: number, attributes: Dict } }?, +} + +-- ------------------------------------------------------------------------------------------------ constants +-- the default palette (spec section 8): a 6 x 6 x 6 colour cube without black, then red, green, blue and grey ramps +local DEFAULT_PALETTE: { { number } } = {} +do + local steps = { 0xff, 0xcc, 0x99, 0x66, 0x33, 0x00 } + for _, r in steps do + for _, g in steps do + for _, b in steps do + if #DEFAULT_PALETTE < 215 then + table.insert(DEFAULT_PALETTE, { r, g, b, 255 }) + end + end + end + end + local ramp = { 0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + for ch = 1, 4 do + for _, v in ramp do + local c = { 0, 0, 0, 255 } + if ch == 4 then + c = { v, v, v, 255 } + else + c[ch] = v + end + table.insert(DEFAULT_PALETTE, c) + end + end +end +Vox.DEFAULT_PALETTE = DEFAULT_PALETTE + +local IDENTITY_R = 4 -- _r of the identity: row 0 -> column 0, row 1 -> column 1, no signs +local MAX_DEPTH = 256 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vox.sniff(r: Bytes.Reader): number + return if r:peek(4) == "VOX " and r:peek(4, 8) == "MAIN" then 1 elseif r:peek(4) == "VOX " then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function str(r: Bytes.Reader): string + local n = r:i32le() + if n < 0 or n > r:remaining() then + r:fail(Err.CORRUPT, "bad string length") + return "" + end + return r:string(n) +end + +local function dict(r: Bytes.Reader): Dict + local d: Dict = {} + local n = r:i32le() + if n < 0 or n * 8 > r:remaining() then + r:fail(Err.CORRUPT, "bad dictionary size") + return d + end + for _ = 1, n do + local k = str(r) + local v = str(r) + if r.err then + break + end + d[k] = v + end + return d +end + +local function ints(s: string?): { number } + local out = {} + if s then + for w in string.gmatch(s, "%S+") do + table.insert(out, tonumber(w) or 0) + end + end + return out +end + +-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation +local function rotation(b: number): { { number } }? + local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3) + if i0 > 2 or i1 > 2 or i0 == i1 then + return nil + end + local i2 = 3 - i0 - i1 + local function sign(bit: number): number + return if bit32.band(b, bit32.lshift(1, bit)) ~= 0 then -1 else 1 + end + return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } } +end + +-- the node transform of a frame dictionary (_r, _t) +local function applyFrame(node: Types.Node, f: Dict) + local t = ints(f._t) + local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 + local rb = tonumber(f._r) + local rows = if rb and rb ~= IDENTITY_R then rotation(rb) else nil + if not rows then + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + node.translation = { tx, ty, tz } + end + return + end + -- R[row][col], then the determinant: +1 -> a quaternion, -1 (a mirror) -> a matrix + local R = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } } + for row = 1, 3 do + R[row][rows[row][1] + 1] = rows[row][2] + end + local det = R[1][1] * (R[2][2] * R[3][3] - R[2][3] * R[3][2]) - R[1][2] * (R[2][1] * R[3][3] - R[2][3] * R[3][1]) + R[1][3] * (R[2][1] * R[3][2] - R[2][2] * R[3][1]) + if det < 0 then + node.matrix = { + R[1][1], R[2][1], R[3][1], 0, + R[1][2], R[2][2], R[3][2], 0, + R[1][3], R[2][3], R[3][3], 0, + tx, ty, tz, 1, + } + return + end + local m00, m11, m22 = R[1][1], R[2][2], R[3][3] + local tr = m00 + m11 + m22 + local x, y, z, w + if tr > 0 then + local s = math.sqrt(tr + 1) * 2 + w, x, y, z = 0.25 * s, (R[3][2] - R[2][3]) / s, (R[1][3] - R[3][1]) / s, (R[2][1] - R[1][2]) / s + elseif m00 > m11 and m00 > m22 then + local s = math.sqrt(1 + m00 - m11 - m22) * 2 + w, x, y, z = (R[3][2] - R[2][3]) / s, 0.25 * s, (R[1][2] + R[2][1]) / s, (R[1][3] + R[3][1]) / s + elseif m11 > m22 then + local s = math.sqrt(1 + m11 - m00 - m22) * 2 + w, x, y, z = (R[1][3] - R[3][1]) / s, (R[1][2] + R[2][1]) / s, 0.25 * s, (R[2][3] + R[3][2]) / s + else + local s = math.sqrt(1 + m22 - m00 - m11) * 2 + w, x, y, z = (R[2][1] - R[1][2]) / s, (R[1][3] + R[3][1]) / s, (R[2][3] + R[3][2]) / s, 0.25 * s + end + node.rotation = { x, y, z, w } + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + node.translation = { tx, ty, tz } + end +end + +-- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers +local function material(d: Dict): Types.VoxelMaterial + local m: Types.VoxelMaterial = { type = "diffuse" } + for k, v in d do + local key = if string.sub(k, 1, 1) == "_" then string.sub(k, 2) else k + if key == "type" then + m.type = if string.sub(v, 1, 1) == "_" then string.sub(v, 2) else v + else + m[key] = tonumber(v) or v + end + end + return m +end + +type Parsed = { + version: number, + models: { Types.Voxels }, + palette: { { number } }?, + materials: { [number]: Types.VoxelMaterial }, + graph: { [number]: GraphNode }, + meta: { [string]: any }, + skipped: number, +} + +local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?) + local maxCells = opts and opts.maxCells or 2 ^ 27 + if r:string(4) ~= "VOX " then + return nil, Err.new(Err.CORRUPT, "bad signature", r.base) + end + local version = r:u32le() + if r:string(4) ~= "MAIN" then + if r.err then + return nil, r.err + end + return nil, Err.new(Err.CORRUPT, "missing MAIN chunk", 8) + end + local mainN, mainM = r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if mainN < 0 or mainM < 0 or not r:skip(mainN) then + return nil, Err.new(Err.CORRUPT, "bad MAIN chunk", 12) + end + local out: Parsed = { version = version, models = {}, palette = nil, materials = {}, graph = {}, meta = {}, skipped = 0 } + local meta = out.meta + local unknown: { any } = {} + local layers, robjs, cams = {}, {}, {} + local stop = r:tell() + mainM + if stop > r:size() then + return nil, Err.new(Err.TRUNCATED, "the MAIN chunk runs past the end", r.base + 16) + end + local pending: { number }? = nil + local cells = 0 + while r:tell() + 12 <= stop do + local at = r:tell() + local id = r:string(4) + local n, m = r:i32le(), r:i32le() + if n < 0 or m < 0 then + return nil, Err.new(Err.CORRUPT, "bad size of chunk " .. id, at) + elseif n > stop - r:tell() or m > stop - r:tell() - n then + return nil, Err.new(Err.TRUNCATED, "chunk " .. id .. " runs past the end", at) + end + local c = r:slice(n) + if id == "SIZE" then + local sx, sy, sz = c:i32le(), c:i32le(), c:i32le() + if c.err or sx < 1 or sy < 1 or sz < 1 then + return nil, Err.new(Err.CORRUPT, "bad model size", at) + end + cells += sx * sy * sz + if cells > maxCells then + return nil, Err.new(Err.LIMIT, string.format("models hold over %d cells", maxCells), at) + end + pending = { sx, sy, sz } + elseif id == "XYZI" then + local size = pending + if not size then + return nil, Err.new(Err.CORRUPT, "XYZI without SIZE", at) + end + pending = nil + local count = c:i32le() + if c.err or count < 0 or count * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad voxel count", at) + end + local v = Types.Voxels.new(size[1], size[2], size[3], DEFAULT_PALETTE) + out.skipped += Grid.fill(v.data, size[1], size[2], size[3], c.buf, c.base + c:tell(), count) + table.insert(out.models, v) + elseif id == "RGBA" then + if n < 1024 then + return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at) + end + local pal = table.create(255) + for i = 1, 255 do + pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() } + end + out.palette = pal + elseif id == "MATL" then + local mid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad MATL chunk", at) + end + out.materials[mid] = material(d) + elseif id == "nTRN" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c), child = c:i32le() } + c:i32le() -- reserved + node.layer = c:i32le() + local nf = c:i32le() + if c.err or nf < 0 or nf * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nTRN chunk", at) + end + local frames = {} + for k = 1, nf do + frames[k] = dict(c) + end + node.frames = frames + if c.err then + return nil, Err.new(Err.CORRUPT, "bad nTRN frames", at) + end + out.graph[node.id] = node + elseif id == "nGRP" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) } + local nc = c:i32le() + if c.err or nc < 0 or nc * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nGRP chunk", at) + end + local children = table.create(nc) + for k = 1, nc do + children[k] = c:i32le() + end + node.children = children + out.graph[node.id] = node + elseif id == "nSHP" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) } + local nm = c:i32le() + if c.err or nm < 0 or nm * 8 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nSHP chunk", at) + end + local models = {} + for k = 1, nm do + models[k] = { model = c:i32le() + 1, attributes = dict(c) } + end + if c.err then + return nil, Err.new(Err.CORRUPT, "bad nSHP models", at) + end + node.models = models + out.graph[node.id] = node + elseif id == "LAYR" then + local lid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad LAYR chunk", at) + end + table.insert(layers, { id = lid, name = d._name, hidden = d._hidden == "1", attributes = d }) + elseif id == "rOBJ" then + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad rOBJ chunk", at) + end + table.insert(robjs, d) + elseif id == "rCAM" then + local cid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad rCAM chunk", at) + end + table.insert(cams, { id = cid, attributes = d }) + elseif id == "NOTE" then + local nn = c:i32le() + if c.err or nn < 0 or nn * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad NOTE chunk", at) + end + local notes = table.create(nn) + for k = 1, nn do + notes[k] = str(c) + end + if c.err then + return nil, Err.new(Err.CORRUPT, "bad NOTE names", at) + end + meta.notes = notes + elseif id == "IMAP" then + local map = {} + for k = 1, math.min(n, 256) do + map[k] = c:u8() + end + meta.indexMap = map + elseif id == "META" then + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad META chunk", at) + end + meta.info = d + else + if id == "PACK" then + meta.pack = c:i32le() + end + table.insert(unknown, { id = id, content = c:sub(0, n):bytes(n), children = nil :: buffer? }) + end + if m > 0 then + local kids = r:bytes(math.min(m, r:remaining())) + if #unknown > 0 and unknown[#unknown].children == nil and unknown[#unknown].id == id then + unknown[#unknown].children = kids + end + end + if r.err then + return nil, r.err + end + end + if r:tell() < stop then + return nil, Err.new(Err.TRUNCATED, "a partial chunk at the end", r.base + r:tell()) + end + if #out.models == 0 then + return nil, Err.new(Err.CORRUPT, "no models") + end + if #layers > 0 then + meta.layers = layers + end + if #robjs > 0 then + meta.renderObjects = robjs + end + if #cams > 0 then + meta.cameras = cams + end + if #unknown > 0 then + meta.chunks = unknown + end + return out, nil +end + +-- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node) +local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: number, depth: number, visiting: { [number]: boolean }, nmodels: number): number? + local t = graph[id] + if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then + return nil + end + visiting[id] = true + local node: Types.Node = { name = t.attrs._name, children = {} } + local index = #scene.nodes + 1 + scene.nodes[index] = node + local frames = t.frames or {} + if frames[1] then + applyFrame(node, frames[1]) + end + local vox: { [string]: any } = { attributes = t.attrs, layer = t.layer } + if #frames > 1 or (frames[1] and frames[1]._f) then + vox.frames = frames + end + node.extras = { vox = vox } + local child = if t.child then graph[t.child] else nil + if child and child.kind == "nGRP" then + vox.group = child.attrs + for _, c in child.children or {} do + local ci = build(scene, graph, c, depth + 1, visiting, nmodels) + if ci then + table.insert(node.children, ci) + end + end + elseif child and child.kind == "nSHP" then + local models = child.models or {} + vox.shape = { attributes = child.attrs, models = models } + local first = models[1] + if first and first.model >= 1 and first.model <= nmodels then + node.voxels = first.model + end + end + visiting[id] = nil + return index +end + +-- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err +function Vox.decodeVoxels(r: Bytes.Reader, opts: DecodeOptions?): ({ Types.Voxels }?, Err.Err?) + local p, err = parse(r, opts) + if not p then + return nil, err + end + local pal = p.palette or DEFAULT_PALETTE + local mats = if next(p.materials) then p.materials else nil + for _, v in p.models do + v.palette = pal + v.materials = mats + end + return p.models, nil +end + +function Vox.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local p, err = parse(r, opts) + if not p then + return nil, err + end + local scene = Types.Scene.new() + local pal = p.palette or DEFAULT_PALETTE + local mats = if next(p.materials) then p.materials else nil + for _, v in p.models do + v.palette = pal + v.materials = mats + end + scene.voxels = p.models + if p.graph[0] then + local root = build(scene, p.graph, 0, 0, {}, #p.models) + if root then + scene.roots = { root } + end + end + if #scene.nodes == 0 then + -- no scene graph (version 150 files): one node per model + for i = 1, #p.models do + scene.nodes[i] = { children = {}, voxels = i } + scene.roots[i] = i + end + end + scene.meta.up = "z" + scene.meta.vox = p.meta + scene.meta.source = { format = "vox", version = p.version, models = #p.models, palette = p.palette ~= nil, skippedVoxels = p.skipped } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function number(v: any): string + if type(v) ~= "number" then + return tostring(v) + end + if v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return string.format("%d", v) + end + for _, f in { "%.6g", "%.9g", "%.17g" } do + local s = string.format(f, v) + if tonumber(s) == v then + return s + end + end + return string.format("%.17g", v) +end + +local function sortedKeys(d: { [string]: any }): { string } + local keys = {} + for k in d do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + return keys +end + +local function wstr(w: Bytes.Writer, s: string) + w:u32le(#s) + w:string(s) +end + +local function wdict(w: Bytes.Writer, d: { [string]: any }?) + if not d then + w:u32le(0) + return + end + local keys = sortedKeys(d) + w:u32le(#keys) + for _, k in keys do + wstr(w, k) + wstr(w, number(d[k])) + end +end + +-- a node's transform as a frame dictionary (_r, _t) | nil, message +local function frameOf(node: Types.Node, base: Dict?): (Dict?, string?) + local f: Dict = {} + if base then + for k, v in base do + if k ~= "_r" and k ~= "_t" then + f[k] = v + end + end + end + local m = Types.Scene.nodeMatrix(node) + local cols, signs = {}, {} + for row = 0, 2 do + local best, bv, rest = 0, 0, 0 + for col = 0, 2 do + local v = m[col * 4 + row + 1] + if math.abs(v) > math.abs(bv) then + rest = math.max(rest, math.abs(bv)) + best, bv = col, v + else + rest = math.max(rest, math.abs(v)) + end + end + if math.abs(math.abs(bv) - 1) > 1e-4 or rest > 1e-4 or table.find(cols, best) then + return nil, "node rotation is not a multiple of 90 degrees (or has a scale)" + end + table.insert(cols, best) + signs[row + 1] = if bv < 0 then 1 else 0 + end + local rb = cols[1] + cols[2] * 4 + signs[1] * 16 + signs[2] * 32 + signs[3] * 64 + if rb ~= IDENTITY_R then + f._r = tostring(rb) + end + local tx, ty, tz = math.floor(m[13] + 0.5), math.floor(m[14] + 0.5), math.floor(m[15] + 0.5) + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + f._t = string.format("%d %d %d", tx, ty, tz) + end + return f, nil +end + +type Record = { kind: string, id: number, attrs: { [string]: any }?, child: number?, layer: number?, frames: { Dict }?, children: { number }?, models: { { model: number, attributes: Dict? } }? } + +function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local version = opts and opts.version or 200 + if type(version) ~= "number" or version < 0 then + return nil, Err.new(Err.ARG, "bad version") + end + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid") + end + local scene: Types.Scene + if value.kind == "voxels" then + scene = Types.Scene.new() + scene.voxels = { value } + scene.nodes[1] = { children = {}, voxels = 1 } + scene.roots[1] = 1 + elseif value.kind == "scene" then + scene = value + else + return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid") + end + local models = scene.voxels + if type(models) ~= "table" or #models == 0 then + return nil, Err.new(Err.ARG, "the scene has no voxels (MeshOps cannot voxelize meshes yet)") + end + for i, v in models do + local s = v.size + if type(s) ~= "table" or type(v.data) ~= "buffer" then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": not a Voxels grid") + end + for k = 1, 3 do + if type(s[k]) ~= "number" or s[k] < 1 or s[k] > 256 or s[k] ~= math.floor(s[k]) then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": size must be 1..256 per axis") + end + end + if buffer.len(v.data) < s[1] * s[2] * s[3] then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid") + end + end + local meta = if type(scene.meta) == "table" and type(scene.meta.vox) == "table" then scene.meta.vox else {} + local w = Bytes.writer(65536) + w:string("VOX ") + w:u32le(version) + w:string("MAIN") + w:u32le(0) + local mAt = w:tell() + w:u32le(0) + local function chunk(id: string, body: () -> ()) + w:string(id) + local at = w:tell() + w:u32le(0) + w:u32le(0) + body() + w:setU32le(at, w:tell() - at - 8) + end + if type(meta.info) == "table" then + chunk("META", function() + wdict(w, meta.info) + end) + end + -- models + for _, v in models do + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + chunk("SIZE", function() + w:u32le(sx) + w:u32le(sy) + w:u32le(sz) + end) + local count = Grid.count(v.data, sx * sy * sz) + chunk("XYZI", function() + w:u32le(count) + local at = w:reserve(count * 4) + Grid.write(w.buf, at, v.data, sx, sy, sz) + w.pos = at + count * 4 + end) + end + -- the scene graph + local records: { Record } = {} + local nextId = 0 + local function alloc(): number + local id = nextId + nextId += 1 + return id + end + local nodes = scene.nodes or {} + local visiting: { [number]: boolean } = {} + local failure: string? = nil + local function shape(model: number, vx: any?): number + local id = alloc() + local ms = {} + local saved = vx and vx.shape + if saved and type(saved.models) == "table" and saved.models[1] and saved.models[1].model == model then + for _, sm in saved.models do + if type(sm.model) == "number" and sm.model >= 1 and sm.model <= #models then + table.insert(ms, { model = sm.model - 1, attributes = sm.attributes }) + end + end + end + if #ms == 0 then + ms[1] = { model = model - 1, attributes = nil } + end + table.insert(records, { kind = "nSHP", id = id, attrs = saved and saved.attributes, models = ms }) + return id + end + local function visit(index: number, depth: number, layer: number?): number? + local node = nodes[index] + if not node or visiting[index] or depth > MAX_DEPTH then + failure = failure or "the node tree has a loop or is too deep" + return nil + end + visiting[index] = true + local vx = if type(node.extras) == "table" and type(node.extras.vox) == "table" then node.extras.vox else nil + local id = alloc() + local attrs: { [string]: any } = {} + if vx and type(vx.attributes) == "table" then + for k, v in vx.attributes do + attrs[k] = v + end + end + attrs._name = node.name + local saved = vx and type(vx.frames) == "table" and vx.frames or nil + local f, ferr = frameOf(node, saved and saved[1]) + if not f then + failure = failure or ferr + f = {} + end + local frames = { f :: Dict } + if saved then + for k = 2, #saved do + frames[k] = saved[k] + end + end + local rec: Record = { kind = "nTRN", id = id, attrs = attrs, layer = layer or (vx and tonumber(vx.layer)) or 0, frames = frames } + table.insert(records, rec) + local kids = node.children or {} + local hasVox = type(node.voxels) == "number" and node.voxels >= 1 and node.voxels <= #models + if hasVox and #kids == 0 then + rec.child = shape(node.voxels :: number, vx) + else + local gid = alloc() + local grp: Record = { kind = "nGRP", id = gid, attrs = vx and vx.group, children = {} } + table.insert(records, grp) + rec.child = gid + if hasVox then + local tid = alloc() + local t2: Record = { kind = "nTRN", id = tid, attrs = {}, layer = 0, frames = { {} } } + table.insert(records, t2) + table.insert(grp.children :: { number }, tid) + t2.child = shape(node.voxels :: number, vx) + end + for _, c in kids do + local cid = visit(c, depth + 1, nil) + if cid then + table.insert(grp.children :: { number }, cid) + end + end + end + visiting[index] = nil + return id + end + local roots = scene.roots or {} + local single = if #roots == 1 then nodes[roots[1]] else nil + if single and single.voxels == nil then + visit(roots[1], 0, -1) + elseif #roots > 0 then + local rid = alloc() + local gid = alloc() + local rec: Record = { kind = "nTRN", id = rid, attrs = {}, child = gid, layer = -1, frames = { {} } } + local grp: Record = { kind = "nGRP", id = gid, attrs = nil, children = {} } + table.insert(records, rec) + table.insert(records, grp) + for _, ri in roots do + local cid = visit(ri, 1, nil) + if cid then + table.insert(grp.children :: { number }, cid) + end + end + end + if failure then + return nil, Err.new(Err.ARG, failure) + end + for _, rec in records do + chunk(rec.kind, function() + w:u32le(rec.id) + wdict(w, rec.attrs) + if rec.kind == "nTRN" then + w:u32le(rec.child or 0) + w:u32le(0xFFFFFFFF) + w:u32le((rec.layer or 0) % 4294967296) + local frames = rec.frames or { {} } + w:u32le(#frames) + for _, f in frames do + wdict(w, f) + end + elseif rec.kind == "nGRP" then + local ch = rec.children or {} + w:u32le(#ch) + for _, c in ch do + w:u32le(c) + end + else + local ms = rec.models or {} + w:u32le(#ms) + for _, sm in ms do + w:u32le(sm.model) + wdict(w, sm.attributes) + end + end + end) + end + -- layers + if type(meta.layers) == "table" then + for _, l in meta.layers do + chunk("LAYR", function() + w:u32le(tonumber(l.id) or 0) + local d: { [string]: any } = {} + if type(l.attributes) == "table" then + for k, v in l.attributes do + d[k] = v + end + end + d._name = l.name + d._hidden = if l.hidden then "1" elseif d._hidden ~= nil then "0" else nil + wdict(w, d) + w:u32le(0xFFFFFFFF) + end) + end + end + -- palette + local pal = models[1].palette or DEFAULT_PALETTE + chunk("RGBA", function() + for i = 1, 256 do + local c = pal[i] + if type(c) == "table" then + w:u8(math.clamp(math.floor(tonumber(c[1]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[2]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[3]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[4]) or 255), 0, 255)) + else + w:u32le(0) + end + end + end) + if type(meta.indexMap) == "table" then + chunk("IMAP", function() + for k = 1, 256 do + w:u8(math.clamp(math.floor(tonumber(meta.indexMap[k]) or 0), 0, 255)) + end + end) + end + -- materials + local mats = models[1].materials + if type(mats) == "table" then + local ids = {} + for id in mats do + if type(id) == "number" then + table.insert(ids, id) + end + end + table.sort(ids) + for _, id in ids do + local m = mats[id] + chunk("MATL", function() + w:u32le(id) + local d: { [string]: any } = { _type = "_" .. tostring(m.type or "diffuse") } + for k, v in m do + if k ~= "type" and type(k) == "string" then + d["_" .. k] = v + end + end + wdict(w, d) + end) + end + end + if type(meta.renderObjects) == "table" then + for _, d in meta.renderObjects do + chunk("rOBJ", function() + wdict(w, d) + end) + end + end + if type(meta.cameras) == "table" then + for _, cam in meta.cameras do + chunk("rCAM", function() + w:u32le(tonumber(cam.id) or 0) + wdict(w, cam.attributes) + end) + end + end + if type(meta.notes) == "table" then + chunk("NOTE", function() + w:u32le(#meta.notes) + for _, s in meta.notes do + wstr(w, tostring(s)) + end + end) + end + if type(meta.chunks) == "table" then + for _, u in meta.chunks do + if type(u.id) == "string" and #u.id == 4 and type(u.content) == "buffer" and u.id ~= "PACK" then + w:string(u.id) + w:u32le(buffer.len(u.content)) + w:u32le(if u.children then buffer.len(u.children) else 0) + w:bytes(u.content) + if u.children then + w:bytes(u.children) + end + end + end + end + w:setU32le(mAt, w:tell() - mAt - 4) + return w:finish(), nil +end + +return Vox diff --git a/src/Formats/ops/MeshOps/Greedy.luau b/src/Formats/ops/MeshOps/Greedy.luau new file mode 100644 index 0000000..26ddb50 --- /dev/null +++ b/src/Formats/ops/MeshOps/Greedy.luau @@ -0,0 +1,167 @@ +--!strict +--!native +-- ops/MeshOps/Greedy: greedy meshing of a dense voxel grid (one byte per cell, 0 = empty): for each axis and each +-- slice between two layers of cells, the exposed faces are masked by palette index, and runs of equal faces are merged +-- into maximal rectangles (Mikola Lysenko's "Meshing in a Minecraft game", 2012). Faces between two filled cells are +-- hidden whatever their indices. Output: 4 vertices and 2 triangles per rectangle, counter-clockwise seen from the +-- outside. Never throws; the caller checks buffer.len(data) >= sx * sy * sz. +local Greedy = {} + +local readu8, readi32, writei32 = buffer.readu8, buffer.readi32, buffer.writei32 +local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 + +export type Out = { + positions: buffer, -- f32 x3 per vertex + normals: buffer, -- f32 x3 per vertex + index: buffer, -- u8 palette index per vertex + indices: buffer, -- u32, 6 per quad + vertices: number, + quads: number, +} + +-- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale +function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out + local cap = 1024 + local pos = buffer.create(cap * 48) + local nrm = buffer.create(cap * 48) + local idx = buffer.create(cap * 4) + local tri = buffer.create(cap * 24) + local quads = 0 + local maxFace = math.max(sx * sy, sy * sz, sz * sx) + local mask = buffer.create(maxFace * 4) + local corner = { 0, 0, 0 } + for d = 0, 2 do + -- u, v: the two other axes, cyclic so that e_u x e_v = e_d + local u, v = (d + 1) % 3, (d + 2) % 3 + local nd = if d == 0 then sx elseif d == 1 then sy else sz + local nu = if u == 0 then sx elseif u == 1 then sy else sz + local nv = if v == 0 then sx elseif v == 1 then sy else sz + local std = if d == 0 then 1 elseif d == 1 then sx else sx * sy + local stu = if u == 0 then 1 elseif u == 1 then sx else sx * sy + local stv = if v == 0 then 1 elseif v == 1 then sx else sx * sy + for slice = -1, nd - 1 do + -- the mask of faces between layer slice and slice + 1: +index (faces +d, owned by slice), -index (faces -d) + local any = false + for j = 0, nv - 1 do + for i = 0, nu - 1 do + local base = i * stu + j * stv + local a = if slice >= 0 then readu8(data, base + slice * std) else 0 + local b = if slice + 1 < nd then readu8(data, base + (slice + 1) * std) else 0 + local m = 0 + if a ~= 0 and b == 0 then + m = a + elseif a == 0 and b ~= 0 then + m = -b + end + if m ~= 0 then + any = true + end + writei32(mask, (i + j * nu) * 4, m) + end + end + if any then + for j = 0, nv - 1 do + local i = 0 + while i < nu do + local m = readi32(mask, (i + j * nu) * 4) + if m == 0 then + i += 1 + else + local w = 1 + while i + w < nu and readi32(mask, (i + w + j * nu) * 4) == m do + w += 1 + end + local h = 1 + local grow = true + while j + h < nv and grow do + for k = 0, w - 1 do + if readi32(mask, (i + k + (j + h) * nu) * 4) ~= m then + grow = false + break + end + end + if grow then + h += 1 + end + end + for jj = j, j + h - 1 do + for k = 0, w - 1 do + writei32(mask, (i + k + jj * nu) * 4, 0) + end + end + -- emit the rectangle + if quads == cap then + local ncap = cap * 2 + local function grow2(b: buffer, per: number): buffer + local nb = buffer.create(ncap * per) + buffer.copy(nb, 0, b, 0, cap * per) + return nb + end + pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24) + cap = ncap + end + corner[d + 1] = slice + 1 + corner[u + 1] = i + corner[v + 1] = j + local cx, cy, cz = corner[1], corner[2], corner[3] + -- the u and v edge vectors + local ux = if u == 0 then w else 0 + local uy = if u == 1 then w else 0 + local uz = if u == 2 then w else 0 + local vx = if v == 0 then h else 0 + local vy = if v == 1 then h else 0 + local vz = if v == 2 then h else 0 + local nsign = if m > 0 then 1 else -1 + local nx = if d == 0 then nsign else 0 + local ny = if d == 1 then nsign else 0 + local nz = if d == 2 then nsign else 0 + local col = if m > 0 then m else -m + local vb = quads * 48 + local px0, py0, pz0 = (cx + ox) * scale, (cy + oy) * scale, (cz + oz) * scale + writef32(pos, vb, px0) + writef32(pos, vb + 4, py0) + writef32(pos, vb + 8, pz0) + writef32(pos, vb + 12, px0 + ux * scale) + writef32(pos, vb + 16, py0 + uy * scale) + writef32(pos, vb + 20, pz0 + uz * scale) + writef32(pos, vb + 24, px0 + (ux + vx) * scale) + writef32(pos, vb + 28, py0 + (uy + vy) * scale) + writef32(pos, vb + 32, pz0 + (uz + vz) * scale) + writef32(pos, vb + 36, px0 + vx * scale) + writef32(pos, vb + 40, py0 + vy * scale) + writef32(pos, vb + 44, pz0 + vz * scale) + for k = 0, 3 do + writef32(nrm, vb + k * 12, nx) + writef32(nrm, vb + k * 12 + 4, ny) + writef32(nrm, vb + k * 12 + 8, nz) + writeu8(idx, quads * 4 + k, col) + end + local v0 = quads * 4 + local ib = quads * 24 + if m > 0 then + writeu32(tri, ib, v0) + writeu32(tri, ib + 4, v0 + 1) + writeu32(tri, ib + 8, v0 + 2) + writeu32(tri, ib + 12, v0) + writeu32(tri, ib + 16, v0 + 2) + writeu32(tri, ib + 20, v0 + 3) + else + writeu32(tri, ib, v0) + writeu32(tri, ib + 4, v0 + 2) + writeu32(tri, ib + 8, v0 + 1) + writeu32(tri, ib + 12, v0) + writeu32(tri, ib + 16, v0 + 3) + writeu32(tri, ib + 20, v0 + 2) + end + quads += 1 + i += w + end + end + end + end + end + end + return { positions = pos, normals = nrm, index = idx, indices = tri, vertices = quads * 4, quads = quads } +end + +return Greedy diff --git a/src/Formats/ops/MeshOps/init.luau b/src/Formats/ops/MeshOps/init.luau new file mode 100644 index 0000000..4bcfacd --- /dev/null +++ b/src/Formats/ops/MeshOps/init.luau @@ -0,0 +1,1087 @@ +--!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. Each call adds new meshes (call it once per scene, after editing the grids). +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 diff --git a/tests/codecs/base64.luau b/tests/codecs/base64.luau new file mode 100644 index 0000000..7d9e4b4 --- /dev/null +++ b/tests/codecs/base64.luau @@ -0,0 +1,46 @@ +-- codecs/Base64 tests: encode / decode against Python's base64 (standard, URL-safe, unpadded) for every length 0..70 +-- and some large inputs, whitespace and missing padding on decode, data: URIs, bad input, and the fuzz no-throw pass. +-- Fixtures: tools/fixtures/base64.py. +local T = require("@tests/T") +local Base64 = require("@formats/codecs/Base64") +local Cases = require("@tests/gen/base64_cases") + +local t = T.suite("base64") + +for _, c in Cases do + local b = buffer.fromstring(c.data) + t:eq(Base64.encode(b), c.std, "encode " .. #c.data) + t:eq(Base64.encode(b, { url = true }), c.url, "encode url " .. #c.data) + t:eq(Base64.encode(b, { pad = false }), c.nopad, "encode unpadded " .. #c.data) + for _, s in { c.std, c.url, c.nopad } do + local d, err = Base64.decode(s) + t:check(d and buffer.tostring(d) == c.data, "decode " .. #c.data .. ": " .. tostring(err)) + end + -- with line breaks every 76 characters (MIME) + local wrapped = string.gsub(c.std, "(" .. string.rep(".", 76) .. ")", "%1\r\n") + local d = Base64.decode(wrapped) + t:check(d and buffer.tostring(d) == c.data, "decode wrapped " .. #c.data) +end +-- a sub-range +t:eq(Base64.encode(buffer.fromstring("xxhelloyy"), nil, 2, 5), "aGVsbG8=", "encode a range") +-- data URIs +local b, mime = Base64.decodeDataUri("data:application/gltf-buffer;base64,AAEC") +t:check(b and buffer.len(b) == 3 and buffer.readu8(b, 2) == 2 and mime == "application/gltf-buffer", "data URI") +local b2, m2 = Base64.decodeDataUri("data:,a%20b") +t:check(b2 and buffer.tostring(b2) == "a b" and m2 == "text/plain", "percent-encoded data URI") +t:eq(Base64.dataUri(buffer.fromstring("hi"), "text/plain"), "data:text/plain;base64,aGk=", "dataUri") +-- bad input +t:check(Base64.decode("ab$d") == nil, "bad character") +t:check(Base64.decode("abcde") == nil, "a lone last character") +t:check(Base64.decode("ab==cd") == nil, "data after padding") +t:check(Base64.decodeDataUri("http://x") == nil, "not a data URI") +local samples = {} +for i, c in Cases do + if i % 10 == 0 then + table.insert(samples, c.std) + end +end +t:fuzz("decode", function(x: buffer) + return Base64.decode(x) +end, samples) +t:done() diff --git a/tests/compat.luau b/tests/compat.luau index 48163b3..2883d58 100644 --- a/tests/compat.luau +++ b/tests/compat.luau @@ -212,6 +212,12 @@ do count += 1 end t:eq(count, 3, "for over a mixed table visits every key") + local zero = { [0] = 5, 6, 7 } + local zsum = 0 + for _, v in zero do + zsum += v + end + t:eq(zsum, 18, "for over a table with key 0 visits it (LuaJIT keeps t[0] in the array part)") local w = {} for word in string.gmatch("a b c", "%a") do table.insert(w, word) diff --git a/tests/fixtures/gltf/AnimatedMorphCube/LICENSE.md b/tests/fixtures/gltf/AnimatedMorphCube/LICENSE.md new file mode 100644 index 0000000..ae8546c --- /dev/null +++ b/tests/fixtures/gltf/AnimatedMorphCube/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Animated Morph Cube + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.bin b/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.bin new file mode 100644 index 0000000..7520d98 Binary files /dev/null and b/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.bin differ diff --git a/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.gltf b/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.gltf new file mode 100644 index 0000000..870695e --- /dev/null +++ b/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.gltf @@ -0,0 +1,259 @@ +{ + "buffers":[ + { + "uri":"AnimatedMorphCube.bin", + "byteLength":1700 + } + ], + "asset":{ + "version":"2.0", + "generator":"gltfpack 0.13" + }, + "extensionsUsed":[ + "KHR_mesh_quantization" + ], + "extensionsRequired":[ + "KHR_mesh_quantization" + ], + "bufferViews":[ + { + "buffer":0, + "byteOffset":0, + "byteLength":288, + "byteStride":4, + "target":34962 + }, + { + "buffer":0, + "byteOffset":288, + "byteLength":576, + "byteStride":8, + "target":34962 + }, + { + "buffer":0, + "byteOffset":864, + "byteLength":72, + "target":34963 + }, + { + "buffer":0, + "byteOffset":936, + "byteLength":508 + }, + { + "buffer":0, + "byteOffset":1444, + "byteLength":254 + } + ], + "accessors":[ + { + "bufferView":0, + "byteOffset":0, + "componentType":5120, + "count":24, + "type":"VEC3", + "normalized":true + }, + { + "bufferView":1, + "byteOffset":0, + "componentType":5123, + "count":24, + "type":"VEC3", + "min":[ + 0, + 5451, + 0 + ], + "max":[ + 5481, + 10932, + 5481 + ] + }, + { + "bufferView":0, + "byteOffset":96, + "componentType":5120, + "count":24, + "type":"VEC3", + "normalized":true + }, + { + "bufferView":1, + "byteOffset":192, + "componentType":5122, + "count":24, + "type":"VEC3", + "min":[ + 0, + 0, + 0 + ], + "max":[ + 0, + 5188, + 0 + ] + }, + { + "bufferView":0, + "byteOffset":192, + "componentType":5120, + "count":24, + "type":"VEC3", + "normalized":true + }, + { + "bufferView":1, + "byteOffset":384, + "componentType":5122, + "count":24, + "type":"VEC3", + "min":[ + 0, + 0, + 0 + ], + "max":[ + 0, + 5451, + 0 + ] + }, + { + "bufferView":2, + "byteOffset":0, + "componentType":5123, + "count":36, + "type":"SCALAR" + }, + { + "bufferView":3, + "byteOffset":0, + "componentType":5126, + "count":127, + "type":"SCALAR", + "min":[ + 0 + ], + "max":[ + 4.19999981 + ] + }, + { + "bufferView":4, + "byteOffset":0, + "componentType":5121, + "count":254, + "type":"SCALAR", + "normalized":true + } + ], + "materials":[ + { + "name":"Material", + "pbrMetallicRoughness":{ + "baseColorFactor":[ + 0.603827417, + 0.603827417, + 0.603827417, + 1 + ], + "metallicFactor":0, + "roughnessFactor":0.5 + } + } + ], + "meshes":[ + { + "primitives":[ + { + "attributes":{ + "NORMAL":0, + "POSITION":1 + }, + "mode":4, + "targets":[ + { + "NORMAL":2, + "POSITION":3 + }, + { + "NORMAL":4, + "POSITION":5 + } + ], + "indices":6, + "material":0 + } + ], + "weights":[ + 0, + 0 + ] + } + ], + "animations":[ + { + "name":"Square", + "samplers":[ + { + "input":7, + "output":8 + } + ], + "channels":[ + { + "sampler":0, + "target":{ + "node":0, + "path":"weights" + } + } + ] + } + ], + "nodes":[ + { + "mesh":0, + "translation":[ + -0.0100000044, + -0.0298908409, + -0.00999999978 + ], + "scale":[ + 3.64900689e-06, + 3.64900689e-06, + 3.64900689e-06 + ] + }, + { + "name":"AnimatedMorphCube", + "rotation":[ + 0, + 0.707106709, + -0.707106829, + 0 + ], + "scale":[ + 100, + 100, + 100 + ], + "children":[ + 0 + ] + } + ], + "scenes":[ + { + "nodes":[ + 1 + ] + } + ], + "scene":0 +} \ No newline at end of file diff --git a/tests/fixtures/gltf/AnimatedTriangle/LICENSE.md b/tests/fixtures/gltf/AnimatedTriangle/LICENSE.md new file mode 100644 index 0000000..e940ed1 --- /dev/null +++ b/tests/fixtures/gltf/AnimatedTriangle/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Animated Triangle + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle.gltf b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle.gltf new file mode 100644 index 0000000..b7b1e25 --- /dev/null +++ b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle.gltf @@ -0,0 +1,118 @@ +{ + "scene" : 0, + "scenes" : [ + { + "nodes" : [ 0 ] + } + ], + + "nodes" : [ + { + "mesh" : 0, + "rotation" : [ 0.0, 0.0, 0.0, 1.0 ] + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 1 + }, + "indices" : 0 + } ] + } + ], + + "animations": [ + { + "samplers" : [ + { + "input" : 2, + "interpolation" : "LINEAR", + "output" : 3 + } + ], + "channels" : [ { + "sampler" : 0, + "target" : { + "node" : 0, + "path" : "rotation" + } + } ] + } + ], + + "buffers" : [ + { + "uri" : "AnimatedTriangle_geometry.bin", + "byteLength" : 44 + }, + { + "uri" : "AnimatedTriangle_animation.bin", + "byteLength" : 100 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 6, + "target" : 34963 + }, + { + "buffer" : 0, + "byteOffset" : 8, + "byteLength" : 36, + "target" : 34962 + }, + { + "buffer" : 1, + "byteOffset" : 0, + "byteLength" : 100 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 3, + "type" : "SCALAR", + "max" : [ 2 ], + "min" : [ 0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + }, + { + "bufferView" : 2, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 5, + "type" : "SCALAR", + "max" : [ 1.0 ], + "min" : [ 0.0 ] + }, + { + "bufferView" : 2, + "byteOffset" : 20, + "componentType" : 5126, + "count" : 5, + "type" : "VEC4", + "max" : [ 0.0, 0.0, 1.0, 1.0 ], + "min" : [ 0.0, 0.0, 0.0, -0.707 ] + } + ], + + "asset" : { + "version" : "2.0" + } + +} diff --git a/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_animation.bin b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_animation.bin new file mode 100644 index 0000000..fa20e9f Binary files /dev/null and b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_animation.bin differ diff --git a/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_geometry.bin b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_geometry.bin new file mode 100644 index 0000000..d642500 Binary files /dev/null and b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_geometry.bin differ diff --git a/tests/fixtures/gltf/AnisotropyStrengthTest/LICENSE.md b/tests/fixtures/gltf/AnisotropyStrengthTest/LICENSE.md new file mode 100644 index 0000000..329c208 --- /dev/null +++ b/tests/fixtures/gltf/AnisotropyStrengthTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Anisotropy Strength Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/AnisotropyStrengthTest/glTF-Binary/AnisotropyStrengthTest.glb b/tests/fixtures/gltf/AnisotropyStrengthTest/glTF-Binary/AnisotropyStrengthTest.glb new file mode 100644 index 0000000..6161291 Binary files /dev/null and b/tests/fixtures/gltf/AnisotropyStrengthTest/glTF-Binary/AnisotropyStrengthTest.glb differ diff --git a/tests/fixtures/gltf/AttenuationTest/LICENSE.md b/tests/fixtures/gltf/AttenuationTest/LICENSE.md new file mode 100644 index 0000000..4329dc8 --- /dev/null +++ b/tests/fixtures/gltf/AttenuationTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Attenuation Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/AttenuationTest/glTF-Binary/AttenuationTest.glb b/tests/fixtures/gltf/AttenuationTest/glTF-Binary/AttenuationTest.glb new file mode 100644 index 0000000..070457d Binary files /dev/null and b/tests/fixtures/gltf/AttenuationTest/glTF-Binary/AttenuationTest.glb differ diff --git a/tests/fixtures/gltf/Box/LICENSE.md b/tests/fixtures/gltf/Box/LICENSE.md new file mode 100644 index 0000000..87f5e5e --- /dev/null +++ b/tests/fixtures/gltf/Box/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Box + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/Box/glTF-Binary/Box.glb b/tests/fixtures/gltf/Box/glTF-Binary/Box.glb new file mode 100644 index 0000000..95ec886 Binary files /dev/null and b/tests/fixtures/gltf/Box/glTF-Binary/Box.glb differ diff --git a/tests/fixtures/gltf/Box/glTF/Box.gltf b/tests/fixtures/gltf/Box/glTF/Box.gltf new file mode 100644 index 0000000..7f603f0 --- /dev/null +++ b/tests/fixtures/gltf/Box/glTF/Box.gltf @@ -0,0 +1,142 @@ +{ + "asset": { + "generator": "COLLADA2GLTF", + "version": "2.0" + }, + "scene": 0, + "scenes": [ + { + "nodes": [ + 0 + ] + } + ], + "nodes": [ + { + "children": [ + 1 + ], + "matrix": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "mesh": 0 + } + ], + "meshes": [ + { + "primitives": [ + { + "attributes": { + "NORMAL": 1, + "POSITION": 2 + }, + "indices": 0, + "mode": 4, + "material": 0 + } + ], + "name": "Mesh" + } + ], + "accessors": [ + { + "bufferView": 0, + "byteOffset": 0, + "componentType": 5123, + "count": 36, + "max": [ + 23 + ], + "min": [ + 0 + ], + "type": "SCALAR" + }, + { + "bufferView": 1, + "byteOffset": 0, + "componentType": 5126, + "count": 24, + "max": [ + 1.0, + 1.0, + 1.0 + ], + "min": [ + -1.0, + -1.0, + -1.0 + ], + "type": "VEC3" + }, + { + "bufferView": 1, + "byteOffset": 288, + "componentType": 5126, + "count": 24, + "max": [ + 0.5, + 0.5, + 0.5 + ], + "min": [ + -0.5, + -0.5, + -0.5 + ], + "type": "VEC3" + } + ], + "materials": [ + { + "pbrMetallicRoughness": { + "baseColorFactor": [ + 0.800000011920929, + 0.0, + 0.0, + 1.0 + ], + "metallicFactor": 0.0 + }, + "name": "Red" + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteOffset": 576, + "byteLength": 72, + "target": 34963 + }, + { + "buffer": 0, + "byteOffset": 0, + "byteLength": 576, + "byteStride": 12, + "target": 34962 + } + ], + "buffers": [ + { + "byteLength": 648, + "uri": "Box0.bin" + } + ] +} diff --git a/tests/fixtures/gltf/Box/glTF/Box0.bin b/tests/fixtures/gltf/Box/glTF/Box0.bin new file mode 100644 index 0000000..d7798ab Binary files /dev/null and b/tests/fixtures/gltf/Box/glTF/Box0.bin differ diff --git a/tests/fixtures/gltf/BoxInterleaved/LICENSE.md b/tests/fixtures/gltf/BoxInterleaved/LICENSE.md new file mode 100644 index 0000000..2c7c940 --- /dev/null +++ b/tests/fixtures/gltf/BoxInterleaved/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Box with interleaved position and normal attributes + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/BoxInterleaved/glTF-Binary/BoxInterleaved.glb b/tests/fixtures/gltf/BoxInterleaved/glTF-Binary/BoxInterleaved.glb new file mode 100644 index 0000000..25cb404 Binary files /dev/null and b/tests/fixtures/gltf/BoxInterleaved/glTF-Binary/BoxInterleaved.glb differ diff --git a/tests/fixtures/gltf/BoxTextured/LICENSE.md b/tests/fixtures/gltf/BoxTextured/LICENSE.md new file mode 100644 index 0000000..c8993e0 --- /dev/null +++ b/tests/fixtures/gltf/BoxTextured/LICENSE.md @@ -0,0 +1,19 @@ +# LICENSE file for the model: Box Textured + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + + * [Cesium Trademark or Logo](../../LICENSES/LicenseRef-LegalMark-Cesium.txt) + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/BoxTextured/glTF-Embedded/BoxTextured.gltf b/tests/fixtures/gltf/BoxTextured/glTF-Embedded/BoxTextured.gltf new file mode 100644 index 0000000..2743fc1 --- /dev/null +++ b/tests/fixtures/gltf/BoxTextured/glTF-Embedded/BoxTextured.gltf @@ -0,0 +1,181 @@ +{ + "asset": { + "generator": "COLLADA2GLTF", + "version": "2.0" + }, + "scene": 0, + "scenes": [ + { + "nodes": [ + 0 + ] + } + ], + "nodes": [ + { + "children": [ + 1 + ], + "matrix": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "mesh": 0 + } + ], + "meshes": [ + { + "primitives": [ + { + "attributes": { + "NORMAL": 1, + "POSITION": 2, + "TEXCOORD_0": 3 + }, + "indices": 0, + "mode": 4, + "material": 0 + } + ], + "name": "Mesh" + } + ], + "accessors": [ + { + "bufferView": 0, + "byteOffset": 0, + "componentType": 5123, + "count": 36, + "max": [ + 23 + ], + "min": [ + 0 + ], + "type": "SCALAR" + }, + { + "bufferView": 1, + "byteOffset": 0, + "componentType": 5126, + "count": 24, + "max": [ + 1.0, + 1.0, + 1.0 + ], + "min": [ + -1.0, + -1.0, + -1.0 + ], + "type": "VEC3" + }, + { + "bufferView": 1, + "byteOffset": 288, + "componentType": 5126, + "count": 24, + "max": [ + 0.5, + 0.5, + 0.5 + ], + "min": [ + -0.5, + -0.5, + -0.5 + ], + "type": "VEC3" + }, + { + "bufferView": 2, + "byteOffset": 0, + "componentType": 5126, + "count": 24, + "max": [ + 6.0, + 1.0 + ], + "min": [ + 0.0, + 0.0 + ], + "type": "VEC2" + } + ], + "materials": [ + { + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 0 + }, + "metallicFactor": 0.0 + }, + "name": "Texture" + } + ], + "textures": [ + { + "sampler": 0, + "source": 0 + } + ], + "images": [ + { + "uri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAMAAABrrFhUAAAAYFBMVEXc3Ny+1ejU2t6tzOaXwuVyseJprN9srd9gqd9/tuKHuuPh7vn////1+fnL2+ns8Onm6+B+nlyyw6GXsH1zl0ljjTBahiFchydRggWLp2u9yq+mupHM1MPg3+HY3NPf3t2inO6qAAAOAUlEQVR42uzWh7nkOAwDYIkBINmE+u/yJl3aHDyW9NZ/B4D1wWznuVwul8vlchnf8AdEb03+1aX3Ll3+1T50DXLXVc2sKv0GN36TVWWm2uWufUCjSVezdD44/wMg6XTeed6LkDY+0LNvomqV6e4k7kiCXwCA9JusZws3m4d/vvhyR+CO34Unet1L6DJutv3y9/TJCAD8SQAimGbaRfbrYDQR6ZaIAPjLgIhIU5HtRkHUHDf8fQDcVHZ6/E0tnYdytz1+DY/Zq3QCPBAAz7Lexlh+9a0cAA8HhJeprNvBGK/dA98EEW4qsmgDImoIgG8ERJSKtBVpOXgCoFTaYoZoOU/jpTLWim9JgCcBkLZOBaN1TQR4IgRS1/gpjiZaCPBkCNQSp5F0C4ATAFFdpuc3B6eBm8x9/lpOcBrQS9uYd/lZApwKSJM5WzikmwOcDHDrMqMB0QxwAYhUmbl+84WbnH77pHMhnr2NU0/f5FJAVxkn5vcAl4I4sQExD04zfwikAC4IOOcy7g5wSYD3E47f5MLy7YexJsBlAan751+4AVEHuLZwlfflB7g84G0NqHMHCJXxlv13cAtwlTF//+Y2sH/+1RroCXAfh9+EkgQ3Ah7awJDidqqP4/IbwN3AZByVXx3cDvywBjSDG4rUw34A3FJkbweQcnBL4F/cnAdiAykMRZcBPqJI3gtkuf8pt6VnKshjxnkXiIYItS8cp3sEQB+eldcwoA6AYTQAqHPlVt0VVJMwvLkjn5xLEUToCANVeQFo+LzfWSOSRYx17XIEKS/B+Aog2lzeye0TWcCpMmCi0d+fy1eyD41QMhoJKGBsHnO5fCenRpMQ0vPOgMjl8pPc6pTw3VrB5Mc6ACUpcyRSa2c8PWcPCLJc5rBtTAXo7QsNwlAQpSwhEc0n2ekAYShkc1kiWwptoGs4MlwFISnLGGrXSnpqYApjoVyWkWbLqMMFnMdlDwA4vx40kcJVDyD7nqZI4QDXuwLomAy06gAIoyFRxACdUlIvsQZKhssSbCh0kFqqIePDeMit1AF9Mwpvnk0IgZeyhPE4WSip+39iYCnIjnr10np4FYauInKXOd09+uHFkWochUuAJPpWqL0jqJeRAhGS+ZkB+nV6wNaDgzC60vJrLp9k1Z4uuemYA1xICwTISeZXsjiCLqYccoFrLQOAKFojIsZGIihjyjExlMLF8MH74IMaRDNQC1GAVx60PHZ9NVyTVfbD4DTg+0duz02z56B//Gqmqe4uxP1mDwhx9wD83cIW/Qf+4xJhlF4xewshemsBIvLOWmPEWKv+RTUt/5uTXs0xdjpbDQFRdEZyzvw/OWcxTl3D6H576Ys5t5ftRjBCv9Ahmct3sljnCSM8P1rz3ZzbX5t9ACl7l2RzWSTb5IGHxzw3GyzeThyFwLtcVskPXzjzSbj8hF/O2okCvf69VVgS4aHvx3jBHv7znE4YIJu5bMLZgsKDmP87du9ArdZDNbrYJZsHxUKQW3NHXo+CtfsGANFwOQBr397ooxGfMQxDNGUNxVRP8f28bsHL/dcCEUw5jIk43/+5rMK3radxehlvH+sxQFTbiYIaTRxkc2mALeGB63UNQcAF9O5zNpFPlZ4QhDsPIHV9P1IujeQzU4G3e+VIbduK0CeAGSx+SAJ4rwXrHV9HAba0w6cFwiP+eKt3fB64FQB5IxmfJL9QlPIPb1eiHSEOw/Yaz7HjwnA45mj4/7/cx170sFoETPUDTTSOoigOhVDgBMDn0fYpbjn21TBU/VjeYZ/H8RAkAJrn8VT9mBURsKkxSE6x4hbj0PgMb4YxHhLb9b1nQ9ap7/wfdGOpiAB0JcITXgytu6Vkydy9KjT0xCI/JAA6dvNw7J/xdBkRQJt0pLjlwyz9D/Mux4vgeBUI16MOracF3vQZJOJCC8Cf8fxbS29g1pUhAzseZIATiYbzb8zSAkvNGIvgWQ5R3KlzS+9gbVfGbkCe7wC0as3eD8fGHNqAsxwhAOXglj7AvC5jN3CcEEpcjzq29un36PMU2YCzHNHFNrinTzCvNGTgLE9+YJK7T8OxtjqCALmGAjA2ngKYj+FeyPkhPpIoBk+fCRjGIwh4iQXQLUXwLmSAkwHekQ7BcCzV4+teAuQcCoB2raUQ5nXBdz7vrcc+qEdIAEoDiNBRK7ME4M2gcTYgRxAQOtL8iMfTEQRwimuWILwNTTF+DEt1foQbUp2i8RhHAK+4ANZaBu8A5SkOoOjd0lMIEMGKmzDMu+kZIalInMmNjuqxIQhgFBcI4ALkBkR2hqBoQ47RIgL4MxdWXCCE4/HZgFzCeixrt0RVwG116hgrboMUEBwMiWyAqEdwBKSXAK+4XaS4AQPFsdkAEAAF9UgQQCpu5ZZWwFvgBrbOP65HzS2ev+0hQC6E4kaw2A3oRjeA6rFJlo6vAOwAxoentQS0U9g7sUkG5Izq8cshrCMAKK5SihsAZAPwtTJ/Daoj2JAJI7RbcTHMh4JyA7wD6DwRBIDTIKG42HIAIeyVcQP8EcDTLgIwTqEAAsXF8Mcx2YDE9bgcgQC25gEoBHyAP0i7gZcL+fyBcQAgD1iACVgWgPJHIKDDdbgIKBmQsB41gx0QRGJEKowcQOuJhrX93mzgghypWfqWgDzhewGsuHQGgGHWxDJwEyFCebYeQSqMb4Z4xSXcQHgsCtwA40i1d1tTfoCALYprlrbBB40YWCkDQmQAgRunL0eR4lYNP/+lELdnA7KE8rwjtTZPRH8Aqbj73cB1syPXIJMKD4N5IjtEoOK6pc0wA1emsrExT/vWV5VeTADuEYKKW3naA0tDsaWBStCtnJmtIqDLE9UlhjKAWHEJmMfZwFKKTGNeXlmP1gx5ovoE2QyAgDMh6XIrd99Tj95UmeoUlQupuAS8y/hLOfhIztcjbpHBn07AX7bkMwA6G7gIduQ769EfmegW36m4a+oRXJnixjxCAMD9FPFeQM6h5dLRKQvI35WAQ4FIvCHVra0/iU7E1zOQ4vICiI9FJWinFqIRKvl6xgfizRBohS4HT0fB2m61G0Ct+dkZA9oTr8ZiAbz3Zuk4WK8rGbiA+TfGbDzjim9IAQdEKy4vAzgmhpFEOThDQD2t+ZQsmD/ohHyOG3j3zhQ/zdWKDOVfv/mPyv/QLiKnxXGwisu7gZiBq7wZDngLytWjN9VMAGbgejrLjPPpFq9/7fkjMHtlulwX3U7zeObhXMHTrJJbjz7fCWAUOrM+44pegmRLh8O8GRW8LvrjfBG5wOFox9WjzychjFLv81cvXuYvToD5Y8J3wNKjBBOch/MCh6MVN3/zeQVgvBbvHtcQiksB9FEi4OHoSOqRNf1MAMYyCkC4edoP1EBFgw7lfbkUAiVwByAVl4d5f2fB30r5ciUACMA/A1ZcHqidmgS/Hm0pgBgTXANAcZ8vAxhV4/S5YyGAXwM6AAfwZDcABTBohSYuxQAmxQLIFhzPQKWMACbjTx145ngNHJsBcTExRuYzSRyIYxnEfQfP2gp09fwTgSAPhtC4/o+fP3BqvAEgLuN+WYFCoxPgnltArkyXkyFGj9c/htkSBXAyqLluseAeroT1+K3/4fR/WQELAYwdLvsdCQgP964vv9z+Bt80Hq8DBQBHwgVa5to9/STMvc4FOv6VVeO2bXHBgyDeCVVz527ppzFToPp5Lf7Vvn2mua7CYADWAs45MwYhBKjsf5d3TG6vcVzxzTvld/QZRMnjXj6/vNVWWDgELEwpnyRNzf6UwIfElFYcNx2epB8fZhJamTAT5VMQZZxKC2KfH98/Pk1qiwVX9GJCUXiSW4xlQmJmyqchYiacSowtxlIwrfo4xM0cnuQy8ReifDbiX639OCjwNLeKlC+G1u6vzOFpDiVTvhNCMViiTnyr+lM0WKQfNu+Di8AyGpDvNACawzJujelOA8BhIa33GQL9FLCUW7hNABxFYTGVQnSTAKrDcm413SIA4mYKL3Brd0iA0iQOLzGZbjAJGIM5vMYb8g32gA4L3G4/yEXgdS6Fh58ADmsEpNFXAIcV1BoPPgEUVlEZ+GaAMgqsZYJE4x4CzWEta8jj34KsYTHxmA2wCGxBZczdAE/VYRMqhcffAayhFelmDXD5yXi4AJoobMatjdUIKRVx2NJYCVAuAttyGSgB4iIOG1NpiYapvypsTiUOciqgqSrswEc5F6WqsAsb4aKcKInBPhzk8scC4qmaw160JzB8/1tBr70aUt65fvA5gXxZac0N2PjfFxFFcdifBeQrRsCpCRzCarleAsQYxOEQ6hITX6/9m8JRVCISXWr3U0QdjqPWMF9IiuJwLKsT03Wmv8HhTFq6RATMUQyO52qhMNP5j7+JO5xB4fReSJxKMIWzuLUpnRgBpcfjP5FLzOfpZ7+TmdXCTGc1f4OzuZsEPD4CZmxi7nA+V6vt2AiIGWM1dbiGviIe94IZEWFp8ij/UhGkTEfU318pVIersVqIjtn5mMEF+WNBYNp38pcgBhelJrVNPYP9Wl9v/VflqlZbRGai7V8jTaUFUXW4NFeVVhAzbZcBfUlYmpg6jMC9timllLeSEsZq7uAwCjPZphtQn/liZjAUdzORUBK/ngIR94lfpTe+4bi6SQ0tIs+IFpU+w9JCFQFVGJSrqklosUyY5qJo9u/drteecCpxrl5VHcbmrupSewiIc2ukf5RTSoi9+Crei78NB4ceQ8H0q/yQfoHYSze4K/uZ1BpCay3GWGKMrbVQq4hYBzfmD2Az+Y3NwDv4P/BerM7m/ycU/vb29vb29vb2E95qsPCUXPMVAAAAAElFTkSuQmCC" + } + ], + "samplers": [ + { + "magFilter": 9729, + "minFilter": 9986, + "wrapS": 10497, + "wrapT": 10497 + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteOffset": 768, + "byteLength": 72, + "target": 34963 + }, + { + "buffer": 0, + "byteOffset": 0, + "byteLength": 576, + "byteStride": 12, + "target": 34962 + }, + { + "buffer": 0, + "byteOffset": 576, + "byteLength": 192, + "byteStride": 8, + "target": 34962 + } + ], + "buffers": [ + { + "byteLength": 840, + "uri": "data:application/octet-stream;base64,AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAvwAAAL8AAAA/AAAAPwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAA/AAAAPwAAAD8AAAC/AAAAPwAAAL8AAAC/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAvwAAAD8AAAC/AAAAPwAAAD8AAAC/AAAAPwAAAL8AAAA/AAAAvwAAAL8AAAA/AAAAPwAAAL8AAAC/AAAAvwAAAL8AAAC/AAAAvwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAPwAAAL8AAAC/AAAAPwAAAD8AAAC/AADAQAAAAAAAAKBAAAAAAAAAwED+/38/AACgQP7/fz8AAIBAAAAAAAAAoEAAAAAAAACAQAAAgD8AAKBAAACAPwAAAEAAAAAAAACAPwAAAAAAAABAAACAPwAAgD8AAIA/AABAQAAAAAAAAIBAAAAAAAAAQEAAAIA/AACAQAAAgD8AAEBAAAAAAAAAAEAAAAAAAABAQAAAgD8AAABAAACAPwAAAAAAAAAAAAAAAP7/fz8AAIA/AAAAAAAAgD/+/38/AAABAAIAAwACAAEABAAFAAYABwAGAAUACAAJAAoACwAKAAkADAANAA4ADwAOAA0AEAARABIAEwASABEAFAAVABYAFwAWABUA" + } + ] +} diff --git a/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured.gltf b/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured.gltf new file mode 100644 index 0000000..eff658f --- /dev/null +++ b/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured.gltf @@ -0,0 +1,181 @@ +{ + "asset": { + "generator": "COLLADA2GLTF", + "version": "2.0" + }, + "scene": 0, + "scenes": [ + { + "nodes": [ + 0 + ] + } + ], + "nodes": [ + { + "children": [ + 1 + ], + "matrix": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "mesh": 0 + } + ], + "meshes": [ + { + "primitives": [ + { + "attributes": { + "NORMAL": 1, + "POSITION": 2, + "TEXCOORD_0": 3 + }, + "indices": 0, + "mode": 4, + "material": 0 + } + ], + "name": "Mesh" + } + ], + "accessors": [ + { + "bufferView": 0, + "byteOffset": 0, + "componentType": 5123, + "count": 36, + "max": [ + 23 + ], + "min": [ + 0 + ], + "type": "SCALAR" + }, + { + "bufferView": 1, + "byteOffset": 0, + "componentType": 5126, + "count": 24, + "max": [ + 1.0, + 1.0, + 1.0 + ], + "min": [ + -1.0, + -1.0, + -1.0 + ], + "type": "VEC3" + }, + { + "bufferView": 1, + "byteOffset": 288, + "componentType": 5126, + "count": 24, + "max": [ + 0.5, + 0.5, + 0.5 + ], + "min": [ + -0.5, + -0.5, + -0.5 + ], + "type": "VEC3" + }, + { + "bufferView": 2, + "byteOffset": 0, + "componentType": 5126, + "count": 24, + "max": [ + 6.0, + 1.0 + ], + "min": [ + 0.0, + 0.0 + ], + "type": "VEC2" + } + ], + "materials": [ + { + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 0 + }, + "metallicFactor": 0.0 + }, + "name": "Texture" + } + ], + "textures": [ + { + "sampler": 0, + "source": 0 + } + ], + "images": [ + { + "uri": "CesiumLogoFlat.png" + } + ], + "samplers": [ + { + "magFilter": 9729, + "minFilter": 9986, + "wrapS": 10497, + "wrapT": 10497 + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteOffset": 768, + "byteLength": 72, + "target": 34963 + }, + { + "buffer": 0, + "byteOffset": 0, + "byteLength": 576, + "byteStride": 12, + "target": 34962 + }, + { + "buffer": 0, + "byteOffset": 576, + "byteLength": 192, + "byteStride": 8, + "target": 34962 + } + ], + "buffers": [ + { + "byteLength": 840, + "uri": "BoxTextured0.bin" + } + ] +} diff --git a/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured0.bin b/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured0.bin new file mode 100644 index 0000000..d2a7355 Binary files /dev/null and b/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured0.bin differ diff --git a/tests/fixtures/gltf/BoxTextured/glTF/CesiumLogoFlat.png b/tests/fixtures/gltf/BoxTextured/glTF/CesiumLogoFlat.png new file mode 100644 index 0000000..8d5a3ad Binary files /dev/null and b/tests/fixtures/gltf/BoxTextured/glTF/CesiumLogoFlat.png differ diff --git a/tests/fixtures/gltf/BoxVertexColors/LICENSE.md b/tests/fixtures/gltf/BoxVertexColors/LICENSE.md new file mode 100644 index 0000000..afa6d28 --- /dev/null +++ b/tests/fixtures/gltf/BoxVertexColors/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Box Vertex Colors + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/BoxVertexColors/glTF-Binary/BoxVertexColors.glb b/tests/fixtures/gltf/BoxVertexColors/glTF-Binary/BoxVertexColors.glb new file mode 100644 index 0000000..875d95a Binary files /dev/null and b/tests/fixtures/gltf/BoxVertexColors/glTF-Binary/BoxVertexColors.glb differ diff --git a/tests/fixtures/gltf/Cameras/LICENSE.md b/tests/fixtures/gltf/Cameras/LICENSE.md new file mode 100644 index 0000000..f718127 --- /dev/null +++ b/tests/fixtures/gltf/Cameras/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Cameras + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/Cameras/glTF/Cameras.bin b/tests/fixtures/gltf/Cameras/glTF/Cameras.bin new file mode 100644 index 0000000..a6edb3b Binary files /dev/null and b/tests/fixtures/gltf/Cameras/glTF/Cameras.bin differ diff --git a/tests/fixtures/gltf/Cameras/glTF/Cameras.gltf b/tests/fixtures/gltf/Cameras/glTF/Cameras.gltf new file mode 100644 index 0000000..48d5adf --- /dev/null +++ b/tests/fixtures/gltf/Cameras/glTF/Cameras.gltf @@ -0,0 +1,99 @@ +{ + "scene" : 0, + "scenes" : [ + { + "nodes" : [ 0, 1, 2 ] + } + ], + "nodes" : [ + { + "rotation" : [ -0.383, 0.0, 0.0, 0.92375 ], + "mesh" : 0 + }, + { + "translation" : [ 0.5, 0.5, 3.0 ], + "camera" : 0 + }, + { + "translation" : [ 0.5, 0.5, 3.0 ], + "camera" : 1 + } + ], + + "cameras" : [ + { + "type": "perspective", + "perspective": { + "aspectRatio": 1.0, + "yfov": 0.7, + "zfar": 100, + "znear": 0.01 + } + }, + { + "type": "orthographic", + "orthographic": { + "xmag": 1.0, + "ymag": 1.0, + "zfar": 100, + "znear": 0.01 + } + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 1 + }, + "indices" : 0 + } ] + } + ], + + "buffers" : [ + { + "uri" : "Cameras.bin", + "byteLength" : 60 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 12, + "target" : 34963 + }, + { + "buffer" : 0, + "byteOffset" : 12, + "byteLength" : 48, + "target" : 34962 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 6, + "type" : "SCALAR", + "max" : [ 3 ], + "min" : [ 0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 4, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + } + ], + + "asset" : { + "version" : "2.0" + } +} diff --git a/tests/fixtures/gltf/ClearCoatCarPaint/LICENSE.md b/tests/fixtures/gltf/ClearCoatCarPaint/LICENSE.md new file mode 100644 index 0000000..2ec4dac --- /dev/null +++ b/tests/fixtures/gltf/ClearCoatCarPaint/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Clear Coat Car Paint + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/ClearCoatCarPaint/glTF-Binary/ClearCoatCarPaint.glb b/tests/fixtures/gltf/ClearCoatCarPaint/glTF-Binary/ClearCoatCarPaint.glb new file mode 100644 index 0000000..6258704 Binary files /dev/null and b/tests/fixtures/gltf/ClearCoatCarPaint/glTF-Binary/ClearCoatCarPaint.glb differ diff --git a/tests/fixtures/gltf/EmissiveStrengthTest/LICENSE.md b/tests/fixtures/gltf/EmissiveStrengthTest/LICENSE.md new file mode 100644 index 0000000..b2e3125 --- /dev/null +++ b/tests/fixtures/gltf/EmissiveStrengthTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Emissive Strength Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/EmissiveStrengthTest/glTF-Binary/EmissiveStrengthTest.glb b/tests/fixtures/gltf/EmissiveStrengthTest/glTF-Binary/EmissiveStrengthTest.glb new file mode 100644 index 0000000..6020aa6 Binary files /dev/null and b/tests/fixtures/gltf/EmissiveStrengthTest/glTF-Binary/EmissiveStrengthTest.glb differ diff --git a/tests/fixtures/gltf/InterpolationTest/LICENSE.md b/tests/fixtures/gltf/InterpolationTest/LICENSE.md new file mode 100644 index 0000000..98cc3eb --- /dev/null +++ b/tests/fixtures/gltf/InterpolationTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Interpolation Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/InterpolationTest/glTF-Binary/InterpolationTest.glb b/tests/fixtures/gltf/InterpolationTest/glTF-Binary/InterpolationTest.glb new file mode 100644 index 0000000..4200fcc Binary files /dev/null and b/tests/fixtures/gltf/InterpolationTest/glTF-Binary/InterpolationTest.glb differ diff --git a/tests/fixtures/gltf/LightVisibility/LICENSE.md b/tests/fixtures/gltf/LightVisibility/LICENSE.md new file mode 100644 index 0000000..d95f2cf --- /dev/null +++ b/tests/fixtures/gltf/LightVisibility/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: LightVisibility + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/LightVisibility/glTF-Binary/LightVisibility.glb b/tests/fixtures/gltf/LightVisibility/glTF-Binary/LightVisibility.glb new file mode 100644 index 0000000..861a523 Binary files /dev/null and b/tests/fixtures/gltf/LightVisibility/glTF-Binary/LightVisibility.glb differ diff --git a/tests/fixtures/gltf/MeshPrimitiveModes/LICENSE.md b/tests/fixtures/gltf/MeshPrimitiveModes/LICENSE.md new file mode 100644 index 0000000..083a4b6 --- /dev/null +++ b/tests/fixtures/gltf/MeshPrimitiveModes/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Mesh Primitive Modes + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/MeshPrimitiveModes/glTF/MeshPrimitiveModes.gltf b/tests/fixtures/gltf/MeshPrimitiveModes/glTF/MeshPrimitiveModes.gltf new file mode 100644 index 0000000..b392211 --- /dev/null +++ b/tests/fixtures/gltf/MeshPrimitiveModes/glTF/MeshPrimitiveModes.gltf @@ -0,0 +1,233 @@ +{ + "asset": { + "version": "2.0" + }, + + "scene": 0, + "scenes": [ + { + "nodes": [0, 1, 2, 3, 4, 5, 6] + } + ], + + "nodes": [ + { + "translation": [-0, 3, 0], + "mesh": 0 + }, + { + "translation": [-2, 0, 0], + "mesh": 1 + }, + { + "translation": [0, 0, 0], + "mesh": 2 + }, + { + "translation": [2, 0, 0], + "mesh": 3 + }, + { + "translation": [-2, -3, 0], + "mesh": 4 + }, + { + "translation": [0, -3, 0], + "mesh": 5 + }, + { + "translation": [2, -3, 0], + "mesh": 6 + } + ], + + "meshes": [ + { + "name": "mesh with POINTS", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 0, + "mode": 0 + } + ] + }, + { + "name": "mesh with LINES", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 1, + "mode": 1 + } + ] + }, + { + "name": "mesh with LINE_LOOP", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 2, + "mode": 2 + } + ] + }, + { + "name": "mesh with LINE_STRIP", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 3, + "mode": 3 + } + ] + }, + { + "name": "mesh with TRIANGLES", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 4, + "mode": 4 + } + ] + }, + { + "name": "mesh with GL_TRIANGLE_STRIP", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 5, + "mode": 5 + } + ] + }, + { + "name": "mesh with GL_TRIANGLE_FAN", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 6, + "mode": 6 + } + ] + } + ], + + "buffers": [ + { + "uri": "buffer.bin", + "byteLength": 216 + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteOffset": 0, + "byteLength": 130, + "target": 34963 + }, + { + "buffer": 0, + "byteOffset": 132, + "byteLength": 84, + "target": 34962 + } + ], + "accessors": [ + { + "name": "indices for POINTS", + "bufferView": 0, + "byteOffset": 0, + "componentType": 5123, + "count": 7, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "indices for LINES", + "bufferView": 0, + "byteOffset": 14, + "componentType": 5123, + "count": 12, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "indices for LINE_LOOP", + "bufferView": 0, + "byteOffset": 38, + "componentType": 5123, + "count": 7, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "indices for LINE_STRIP", + "bufferView": 0, + "byteOffset": 52, + "componentType": 5123, + "count": 7, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "indices for TRIANGLES", + "bufferView": 0, + "byteOffset": 66, + "componentType": 5123, + "count": 18, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "indices for TRIANGLE_STRIP", + "bufferView": 0, + "byteOffset": 102, + "componentType": 5123, + "count": 6, + "type": "SCALAR", + "max": [6], + "min": [1] + }, + { + "name": "indices for TRIANGLE_FAN", + "bufferView": 0, + "byteOffset": 114, + "componentType": 5123, + "count": 8, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "positions", + "bufferView": 1, + "byteOffset": 0, + "componentType": 5126, + "count": 7, + "type": "VEC3", + "max": [0.866, 1.0, 0.0], + "min": [-0.866, -1.0, 0.0] + } + ] +} diff --git a/tests/fixtures/gltf/MeshPrimitiveModes/glTF/buffer.bin b/tests/fixtures/gltf/MeshPrimitiveModes/glTF/buffer.bin new file mode 100644 index 0000000..069020a Binary files /dev/null and b/tests/fixtures/gltf/MeshPrimitiveModes/glTF/buffer.bin differ diff --git a/tests/fixtures/gltf/MultiUVTest/LICENSE.md b/tests/fixtures/gltf/MultiUVTest/LICENSE.md new file mode 100644 index 0000000..367cc0d --- /dev/null +++ b/tests/fixtures/gltf/MultiUVTest/LICENSE.md @@ -0,0 +1,19 @@ +# LICENSE file for the model: MultiUV Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + + * [Khronos Trademark or Logo](../../LICENSES/LicenseRef-LegalMark-Khronos.txt) + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/MultiUVTest/glTF-Binary/MultiUVTest.glb b/tests/fixtures/gltf/MultiUVTest/glTF-Binary/MultiUVTest.glb new file mode 100644 index 0000000..69ed2fe Binary files /dev/null and b/tests/fixtures/gltf/MultiUVTest/glTF-Binary/MultiUVTest.glb differ diff --git a/tests/fixtures/gltf/MultipleScenes/LICENSE.md b/tests/fixtures/gltf/MultipleScenes/LICENSE.md new file mode 100644 index 0000000..1ba45c7 --- /dev/null +++ b/tests/fixtures/gltf/MultipleScenes/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Multiple Scenes + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes.gltf b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes.gltf new file mode 100644 index 0000000..a61070a --- /dev/null +++ b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes.gltf @@ -0,0 +1,118 @@ +{ + "scene" : 1, + "scenes" : [ + { + "nodes" : [ 0 ] + }, + { + "nodes" : [ 1 ] + } + ], + + "nodes" : [ + { + "mesh" : 0 + }, + { + "mesh" : 1 + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 1 + }, + "indices" : 0 + } ] + }, + { + "primitives" : [ { + "attributes" : { + "POSITION" : 3 + }, + "indices" : 2 + } ] + } + ], + + "buffers" : [ + { + "uri" : "MultipleScenes_triangle.bin", + "byteLength" : 44 + }, + { + "uri" : "MultipleScenes_square.bin", + "byteLength" : 60 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 6, + "target" : 34963 + }, + { + "buffer" : 0, + "byteOffset" : 8, + "byteLength" : 36, + "target" : 34962 + }, + { + "buffer" : 1, + "byteOffset" : 0, + "byteLength" : 12, + "target" : 34963 + }, + { + "buffer" : 1, + "byteOffset" : 12, + "byteLength" : 48, + "target" : 34962 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 3, + "type" : "SCALAR", + "max" : [ 2 ], + "min" : [ 0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + }, + { + "bufferView" : 2, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 6, + "type" : "SCALAR", + "max" : [ 3 ], + "min" : [ 0 ] + }, + { + "bufferView" : 3, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 4, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + } + ], + + "asset" : { + "version" : "2.0" + } +} diff --git a/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_square.bin b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_square.bin new file mode 100644 index 0000000..a6edb3b Binary files /dev/null and b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_square.bin differ diff --git a/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_triangle.bin b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_triangle.bin new file mode 100644 index 0000000..d642500 Binary files /dev/null and b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_triangle.bin differ diff --git a/tests/fixtures/gltf/NegativeScaleTest/LICENSE.md b/tests/fixtures/gltf/NegativeScaleTest/LICENSE.md new file mode 100644 index 0000000..7fbbd09 --- /dev/null +++ b/tests/fixtures/gltf/NegativeScaleTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Negative Scale Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/NegativeScaleTest/glTF-Binary/NegativeScaleTest.glb b/tests/fixtures/gltf/NegativeScaleTest/glTF-Binary/NegativeScaleTest.glb new file mode 100644 index 0000000..00efded Binary files /dev/null and b/tests/fixtures/gltf/NegativeScaleTest/glTF-Binary/NegativeScaleTest.glb differ diff --git a/tests/fixtures/gltf/PointLightIntensityTest/LICENSE.md b/tests/fixtures/gltf/PointLightIntensityTest/LICENSE.md new file mode 100644 index 0000000..3e0f6ce --- /dev/null +++ b/tests/fixtures/gltf/PointLightIntensityTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Point Light Intensity Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/PointLightIntensityTest/glTF-Binary/PointLightIntensityTest.glb b/tests/fixtures/gltf/PointLightIntensityTest/glTF-Binary/PointLightIntensityTest.glb new file mode 100644 index 0000000..ff8ae99 Binary files /dev/null and b/tests/fixtures/gltf/PointLightIntensityTest/glTF-Binary/PointLightIntensityTest.glb differ diff --git a/tests/fixtures/gltf/RiggedSimple/LICENSE.md b/tests/fixtures/gltf/RiggedSimple/LICENSE.md new file mode 100644 index 0000000..2a98e37 --- /dev/null +++ b/tests/fixtures/gltf/RiggedSimple/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Rigged Simple + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/RiggedSimple/glTF-Binary/RiggedSimple.glb b/tests/fixtures/gltf/RiggedSimple/glTF-Binary/RiggedSimple.glb new file mode 100644 index 0000000..d56b94e Binary files /dev/null and b/tests/fixtures/gltf/RiggedSimple/glTF-Binary/RiggedSimple.glb differ diff --git a/tests/fixtures/gltf/SimpleMeshes/LICENSE.md b/tests/fixtures/gltf/SimpleMeshes/LICENSE.md new file mode 100644 index 0000000..6c1201c --- /dev/null +++ b/tests/fixtures/gltf/SimpleMeshes/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Simple Meshes + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.bin b/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.bin new file mode 100644 index 0000000..291b43c Binary files /dev/null and b/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.bin differ diff --git a/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.gltf b/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.gltf new file mode 100644 index 0000000..c3f3d44 --- /dev/null +++ b/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.gltf @@ -0,0 +1,84 @@ +{ + "scene" : 0, + "scenes" : [ + { + "nodes" : [ 0, 1] + } + ], + "nodes" : [ + { + "mesh" : 0 + }, + { + "mesh" : 0, + "translation" : [ 1.0, 0.0, 0.0 ] + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 1, + "NORMAL" : 2 + }, + "indices" : 0 + } ] + } + ], + + "buffers" : [ + { + "uri" : "SimpleMeshes.bin", + "byteLength" : 80 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 6, + "target" : 34963 + }, + { + "buffer" : 0, + "byteOffset" : 8, + "byteLength" : 72, + "byteStride" : 12, + "target" : 34962 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 3, + "type" : "SCALAR", + "max" : [ 2 ], + "min" : [ 0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 36, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 0.0, 0.0, 1.0 ], + "min" : [ 0.0, 0.0, 1.0 ] + } + ], + + "asset" : { + "version" : "2.0" + } +} diff --git a/tests/fixtures/gltf/SimpleMorph/LICENSE.md b/tests/fixtures/gltf/SimpleMorph/LICENSE.md new file mode 100644 index 0000000..b889d88 --- /dev/null +++ b/tests/fixtures/gltf/SimpleMorph/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Simple Morph + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph.gltf b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph.gltf new file mode 100644 index 0000000..0d5f960 --- /dev/null +++ b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph.gltf @@ -0,0 +1,189 @@ +{ + "scene" : 0, + "scenes":[ + { + "nodes":[ + 0 + ] + } + ], + "nodes":[ + { + "mesh":0 + } + ], + "meshes":[ + { + "primitives":[ + { + "attributes":{ + "POSITION":1 + }, + "targets":[ + { + "POSITION":2 + }, + { + "POSITION":3 + } + ], + "indices":0 + } + ], + "weights":[ + 0.5, + 0.5 + ] + } + ], + "animations":[ + { + "samplers":[ + { + "input":4, + "interpolation":"LINEAR", + "output":5 + } + ], + "channels":[ + { + "sampler":0, + "target":{ + "node":0, + "path":"weights" + } + } + ] + } + ], + "buffers":[ + { + "uri" : "SimpleMorph_geometry.bin", + "byteLength":116 + }, + { + "uri" : "SimpleMorph_animation.bin", + "byteLength":60 + } + ], + "bufferViews":[ + { + "buffer":0, + "byteOffset":0, + "byteLength":6, + "target":34963 + }, + { + "buffer":0, + "byteOffset":8, + "byteLength":108, + "byteStride":12, + "target":34962 + }, + { + "buffer":1, + "byteOffset":0, + "byteLength":20 + }, + { + "buffer":1, + "byteOffset":20, + "byteLength":40 + } + ], + "accessors":[ + { + "bufferView":0, + "byteOffset":0, + "componentType":5123, + "count":3, + "type":"SCALAR", + "max":[ + 2 + ], + "min":[ + 0 + ] + }, + { + "bufferView":1, + "byteOffset":0, + "componentType":5126, + "count":3, + "type":"VEC3", + "max":[ + 1.0, + 0.5, + 0.0 + ], + "min":[ + 0.0, + 0.0, + 0.0 + ] + }, + { + "bufferView":1, + "byteOffset":36, + "componentType":5126, + "count":3, + "type":"VEC3", + "max":[ + 0.0, + 1.0, + 0.0 + ], + "min":[ + -1.0, + 0.0, + 0.0 + ] + }, + { + "bufferView":1, + "byteOffset":72, + "componentType":5126, + "count":3, + "type":"VEC3", + "max":[ + 1.0, + 1.0, + 0.0 + ], + "min":[ + 0.0, + 0.0, + 0.0 + ] + }, + { + "bufferView":2, + "byteOffset":0, + "componentType":5126, + "count":5, + "type":"SCALAR", + "max":[ + 4.0 + ], + "min":[ + 0.0 + ] + }, + { + "bufferView":3, + "byteOffset":0, + "componentType":5126, + "count":10, + "type":"SCALAR", + "max":[ + 1.0 + ], + "min":[ + 0.0 + ] + } + ], + "asset":{ + "version":"2.0" + } +} diff --git a/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_animation.bin b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_animation.bin new file mode 100644 index 0000000..bbd0ee6 Binary files /dev/null and b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_animation.bin differ diff --git a/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_geometry.bin b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_geometry.bin new file mode 100644 index 0000000..70b73c2 Binary files /dev/null and b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_geometry.bin differ diff --git a/tests/fixtures/gltf/SimpleSkin/LICENSE.md b/tests/fixtures/gltf/SimpleSkin/LICENSE.md new file mode 100644 index 0000000..8437c87 --- /dev/null +++ b/tests/fixtures/gltf/SimpleSkin/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Simple Skin + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin.gltf b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin.gltf new file mode 100644 index 0000000..1d586df --- /dev/null +++ b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin.gltf @@ -0,0 +1,131 @@ +{ + "scene" : 0, + "scenes" : [ { + "nodes" : [ 0, 1 ] + } ], + + "nodes" : [ { + "skin" : 0, + "mesh" : 0 + }, { + "children" : [ 2 ] + }, { + "translation" : [ 0.0, 1.0, 0.0 ], + "rotation" : [ 0.0, 0.0, 0.0, 1.0 ] + } ], + + "meshes" : [ { + "primitives" : [ { + "attributes" : { + "POSITION" : 1, + "JOINTS_0" : 2, + "WEIGHTS_0" : 3 + }, + "indices" : 0 + } ] + } ], + + "skins" : [ { + "inverseBindMatrices" : 4, + "joints" : [ 1, 2 ] + } ], + + "animations" : [ { + "channels" : [ { + "sampler" : 0, + "target" : { + "node" : 2, + "path" : "rotation" + } + } ], + "samplers" : [ { + "input" : 5, + "interpolation" : "LINEAR", + "output" : 6 + } ] + } ], + + "buffers" : [ { + "uri" : "SimpleSkin_geometry.bin", + "byteLength" : 168 + }, { + "uri" : "SimpleSkin_skinningData.bin", + "byteLength" : 320 + }, { + "uri" : "SimpleSkin_inverseBindMatrices.bin", + "byteLength" : 128 + }, { + "uri" : "SimpleSkin_animation.bin", + "byteLength" : 240 + } ], + + "bufferViews" : [ { + "buffer" : 0, + "byteLength" : 48, + "target" : 34963 + }, { + "buffer" : 0, + "byteOffset" : 48, + "byteLength" : 120, + "target" : 34962 + }, { + "buffer" : 1, + "byteLength" : 320, + "byteStride" : 16 + }, { + "buffer" : 2, + "byteLength" : 128 + }, { + "buffer" : 3, + "byteLength" : 240 + } ], + + "accessors" : [ { + "bufferView" : 0, + "componentType" : 5123, + "count" : 24, + "type" : "SCALAR" + }, { + "bufferView" : 1, + "componentType" : 5126, + "count" : 10, + "type" : "VEC3", + "max" : [ 0.5, 2.0, 0.0 ], + "min" : [ -0.5, 0.0, 0.0 ] + }, { + "bufferView" : 2, + "componentType" : 5123, + "count" : 10, + "type" : "VEC4" + }, { + "bufferView" : 2, + "byteOffset" : 160, + "componentType" : 5126, + "count" : 10, + "type" : "VEC4" + }, { + "bufferView" : 3, + "componentType" : 5126, + "count" : 2, + "type" : "MAT4" + }, { + "bufferView" : 4, + "componentType" : 5126, + "count" : 12, + "type" : "SCALAR", + "max" : [ 5.5 ], + "min" : [ 0.0 ] + }, { + "bufferView" : 4, + "byteOffset" : 48, + "componentType" : 5126, + "count" : 12, + "type" : "VEC4", + "max" : [ 0.0, 0.0, 0.707, 1.0 ], + "min" : [ 0.0, 0.0, -0.707, 0.707 ] + } ], + + "asset" : { + "version" : "2.0" + } +} \ No newline at end of file diff --git a/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_animation.bin b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_animation.bin new file mode 100644 index 0000000..ff550c6 Binary files /dev/null and b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_animation.bin differ diff --git a/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_geometry.bin b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_geometry.bin new file mode 100644 index 0000000..15375c4 Binary files /dev/null and b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_geometry.bin differ diff --git a/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_inverseBindMatrices.bin b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_inverseBindMatrices.bin new file mode 100644 index 0000000..5af0b5e Binary files /dev/null and b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_inverseBindMatrices.bin differ diff --git a/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_skinningData.bin b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_skinningData.bin new file mode 100644 index 0000000..fd0c165 Binary files /dev/null and b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_skinningData.bin differ diff --git a/tests/fixtures/gltf/SimpleSparseAccessor/LICENSE.md b/tests/fixtures/gltf/SimpleSparseAccessor/LICENSE.md new file mode 100644 index 0000000..acf8487 --- /dev/null +++ b/tests/fixtures/gltf/SimpleSparseAccessor/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Simple Sparse Accessor + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/SimpleSparseAccessor/glTF-Embedded/SimpleSparseAccessor.gltf b/tests/fixtures/gltf/SimpleSparseAccessor/glTF-Embedded/SimpleSparseAccessor.gltf new file mode 100644 index 0000000..ca69e2f --- /dev/null +++ b/tests/fixtures/gltf/SimpleSparseAccessor/glTF-Embedded/SimpleSparseAccessor.gltf @@ -0,0 +1,77 @@ +{ + "scene" : 0, + "scenes" : [ { + "nodes" : [ 0 ] + } ], + + "nodes" : [ { + "mesh" : 0 + } ], + + "meshes" : [ { + "primitives" : [ { + "attributes" : { + "POSITION" : 1 + }, + "indices" : 0 + } ] + } ], + + "buffers" : [ { + "uri" : "data:application/gltf-buffer;base64,AAAIAAcAAAABAAgAAQAJAAgAAQACAAkAAgAKAAkAAgADAAoAAwALAAoAAwAEAAsABAAMAAsABAAFAAwABQANAAwABQAGAA0AAAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAQAAAAAAAAAAAAABAQAAAAAAAAAAAAACAQAAAAAAAAAAAAACgQAAAAAAAAAAAAADAQAAAAAAAAAAAAAAAAAAAgD8AAAAAAACAPwAAgD8AAAAAAAAAQAAAgD8AAAAAAABAQAAAgD8AAAAAAACAQAAAgD8AAAAAAACgQAAAgD8AAAAAAADAQAAAgD8AAAAACAAKAAwAAAAAAIA/AAAAQAAAAAAAAEBAAABAQAAAAAAAAKBAAACAQAAAAAA=", + "byteLength" : 284 + } ], + + "bufferViews" : [ { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 72, + "target" : 34963 + }, { + "buffer" : 0, + "byteOffset" : 72, + "byteLength" : 168 + }, { + "buffer" : 0, + "byteOffset" : 240, + "byteLength" : 6 + }, { + "buffer" : 0, + "byteOffset" : 248, + "byteLength" : 36 + } ], + + "accessors" : [ { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 36, + "type" : "SCALAR", + "max" : [ 13 ], + "min" : [ 0 ] + }, { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 14, + "type" : "VEC3", + "max" : [ 6.0, 4.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ], + "sparse" : { + "count" : 3, + "indices" : { + "bufferView" : 2, + "byteOffset" : 0, + "componentType" : 5123 + }, + "values" : { + "bufferView" : 3, + "byteOffset" : 0 + } + } + } ], + + "asset" : { + "version" : "2.0" + } +} \ No newline at end of file diff --git a/tests/fixtures/gltf/TextureCoordinateTest/LICENSE.md b/tests/fixtures/gltf/TextureCoordinateTest/LICENSE.md new file mode 100644 index 0000000..ba67d93 --- /dev/null +++ b/tests/fixtures/gltf/TextureCoordinateTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Texture Coordinate Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/TextureCoordinateTest/glTF-Binary/TextureCoordinateTest.glb b/tests/fixtures/gltf/TextureCoordinateTest/glTF-Binary/TextureCoordinateTest.glb new file mode 100644 index 0000000..39d3da6 Binary files /dev/null and b/tests/fixtures/gltf/TextureCoordinateTest/glTF-Binary/TextureCoordinateTest.glb differ diff --git a/tests/fixtures/gltf/TextureTransformTest/LICENSE.md b/tests/fixtures/gltf/TextureTransformTest/LICENSE.md new file mode 100644 index 0000000..1315107 --- /dev/null +++ b/tests/fixtures/gltf/TextureTransformTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Texture Transform Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/Arrow.png b/tests/fixtures/gltf/TextureTransformTest/glTF/Arrow.png new file mode 100644 index 0000000..fe3405b Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/Arrow.png differ diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/Correct.png b/tests/fixtures/gltf/TextureTransformTest/glTF/Correct.png new file mode 100644 index 0000000..e332824 Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/Correct.png differ diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/Error.png b/tests/fixtures/gltf/TextureTransformTest/glTF/Error.png new file mode 100644 index 0000000..35acf6e Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/Error.png differ diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/NotSupported.png b/tests/fixtures/gltf/TextureTransformTest/glTF/NotSupported.png new file mode 100644 index 0000000..721e7fd Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/NotSupported.png differ diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.bin b/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.bin new file mode 100644 index 0000000..6765a13 Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.bin differ diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.gltf b/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.gltf new file mode 100644 index 0000000..6dde51d --- /dev/null +++ b/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.gltf @@ -0,0 +1,540 @@ +{ + "accessors": [ + { + "bufferView": 0, + "componentType": 5126, + "count": 4, + "type": "VEC3", + "max": [ + 0.5, + 0.5, + 0.0 + ], + "min": [ + -0.5, + -0.5, + 0.0 + ], + "name": "Positions" + }, + { + "bufferView": 1, + "componentType": 5126, + "count": 4, + "type": "VEC2", + "name": "UV0" + }, + { + "bufferView": 2, + "componentType": 5126, + "count": 4, + "type": "VEC2", + "name": "UV1" + }, + { + "bufferView": 3, + "componentType": 5125, + "count": 6, + "type": "SCALAR", + "name": "Indices" + } + ], + "asset": { + "version": "2.0" + }, + "buffers": [ + { + "uri": "TextureTransformTest.bin", + "byteLength": 136 + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteLength": 48, + "name": "Positions" + }, + { + "buffer": 0, + "byteOffset": 48, + "byteLength": 32, + "name": "UV0" + }, + { + "buffer": 0, + "byteOffset": 80, + "byteLength": 32, + "name": "UV1" + }, + { + "buffer": 0, + "byteOffset": 112, + "byteLength": 24, + "name": "Indices" + } + ], + "extensionsUsed": [ + "KHR_texture_transform" + ], + "images": [ + { + "uri": "UV.png" + }, + { + "uri": "Arrow.png" + }, + { + "uri": "Correct.png" + }, + { + "uri": "NotSupported.png" + }, + { + "uri": "Error.png" + } + ], + "materials": [ + { + "name": "Offset U", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 0, + "extensions": { + "KHR_texture_transform": { + "offset": [ + 0.5, + 0.0 + ] + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "Offset V", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 0, + "extensions": { + "KHR_texture_transform": { + "offset": [ + 0.0, + 0.5 + ] + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "Offset UV", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 0, + "extensions": { + "KHR_texture_transform": { + "offset": [ + 0.5, + 0.5 + ] + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "Rotation", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 1, + "extensions": { + "KHR_texture_transform": { + "rotation": 0.39269908169872415480783042290994 + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "Scale", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 1, + "extensions": { + "KHR_texture_transform": { + "scale": [ + 1.5, + 1.5 + ] + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "All", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 1, + "extensions": { + "KHR_texture_transform": { + "offset": [ + -0.2, + -0.1 + ], + "rotation": 0.3, + "scale": [ + 1.5, + 1.5 + ] + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "Correct", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 2 + }, + "metallicFactor": 0 + } + }, + { + "name": "NotSupported", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 3 + }, + "metallicFactor": 0 + } + }, + { + "name": "Error", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 4 + }, + "metallicFactor": 0 + } + } + ], + "meshes": [ + { + "name": "Offset U", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 2 + }, + "indices": 3, + "material": 0 + } + ] + }, + { + "name": "Offset V", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 2 + }, + "indices": 3, + "material": 1 + } + ] + }, + { + "name": "Offset UV", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 2 + }, + "indices": 3, + "material": 2 + } + ] + }, + { + "name": "Rotation", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 3 + } + ] + }, + { + "name": "Scale", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 4 + } + ] + }, + { + "name": "All", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 5 + } + ] + }, + { + "name": "Correct Marker", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 6 + } + ] + }, + { + "name": "Not Supported Marker", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 7 + } + ] + }, + { + "name": "Error Marker", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 8 + } + ] + } + ], + "nodes": [ + { + "name": "Offset U", + "mesh": 0, + "translation": [ + -1.1, + 0.55, + 0 + ] + }, + { + "name": "Offset V", + "mesh": 1, + "translation": [ + 0, + 0.55, + 0 + ] + }, + { + "name": "Offset UV", + "mesh": 2, + "translation": [ + 1.1, + 0.55, + 0 + ] + }, + { + "name": "Rotation", + "mesh": 3, + "translation": [ + -1.1, + -0.55, + 0 + ], + "children": [ + 4, + 5, + 6 + ] + }, + { + "name": "Rotation - Correct", + "mesh": 6, + "translation": [ + -0.07904822439840125109869401756656, + -0.51626748576241543174100150833647, + 0.01 + ], + "scale": [ + 0.15, + 0.15, + 0.15 + ] + }, + { + "name": "Rotation - Not Supported", + "mesh": 7, + "translation": [ + 0.27781745930520227684092879831533, + -0.27781745930520227684092879831533, + 0.01 + ], + "scale": [ + 0.15, + 0.15, + 0.15 + ] + }, + { + "name": "Rotation - Error", + "mesh": 8, + "translation": [ + 0.51626748576241543174100150833647, + 0.07904822439840125109869401756656, + 0.01 + ], + "scale": [ + 0.15, + 0.15, + 0.15 + ] + }, + { + "name": "Scale", + "mesh": 4, + "translation": [ + 0, + -0.55, + 0 + ], + "children": [ + 8, + 9 + ] + }, + { + "name": "Scale - Correct", + "mesh": 6, + "translation": [ + 0.01854497287013485122728586554355, + -0.01854497287013485122728586554355, + 0.01 + ], + "scale": [ + 0.1, + 0.1, + 0.1 + ] + }, + { + "name": "Scale - Not Supported", + "mesh": 7, + "translation": [ + 0.27781745930520227684092879831533, + -0.27781745930520227684092879831533, + 0.01 + ], + "scale": [ + 0.15, + 0.15, + 0.15 + ] + }, + { + "name": "All", + "mesh": 5, + "translation": [ + 1.1, + -0.55, + 0 + ], + "children": [ + 11 + ] + }, + { + "name": "All - Correct", + "mesh": 6, + "translation": [ + -0.07, + -0.25, + 0.01 + ], + "scale": [ + 0.1, + 0.1, + 0.1 + ] + } + ], + "scene": 0, + "scenes": [ + { + "nodes": [ + 0, + 1, + 2, + 3, + 7, + 10 + ] + } + ], + "textures": [ + { + "source": 0, + "sampler": 0 + }, + { + "source": 1, + "sampler": 0 + }, + { + "source": 2 + }, + { + "source": 3 + }, + { + "source": 4 + } + ], + "samplers": [ + { + "wrapS": 33071, + "wrapT": 33071, + "magFilter": 9729, + "minFilter": 9729 + } + ] +} \ No newline at end of file diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/UV.png b/tests/fixtures/gltf/TextureTransformTest/glTF/UV.png new file mode 100644 index 0000000..c1a6d4d Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/UV.png differ diff --git a/tests/fixtures/gltf/Triangle/LICENSE.md b/tests/fixtures/gltf/Triangle/LICENSE.md new file mode 100644 index 0000000..65dc616 --- /dev/null +++ b/tests/fixtures/gltf/Triangle/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Triangle + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/Triangle/glTF-Embedded/Triangle.gltf b/tests/fixtures/gltf/Triangle/glTF-Embedded/Triangle.gltf new file mode 100644 index 0000000..40cab5a --- /dev/null +++ b/tests/fixtures/gltf/Triangle/glTF-Embedded/Triangle.gltf @@ -0,0 +1,70 @@ +{ + "scene" : 0, + "scenes" : [ + { + "nodes" : [ 0 ] + } + ], + + "nodes" : [ + { + "mesh" : 0 + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 1 + }, + "indices" : 0 + } ] + } + ], + + "buffers" : [ + { + "uri" : "data:application/octet-stream;base64,AAABAAIAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAA=", + "byteLength" : 44 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 6, + "target" : 34963 + }, + { + "buffer" : 0, + "byteOffset" : 8, + "byteLength" : 36, + "target" : 34962 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 3, + "type" : "SCALAR", + "max" : [ 2 ], + "min" : [ 0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + } + ], + + "asset" : { + "version" : "2.0" + } +} diff --git a/tests/fixtures/gltf/TriangleWithoutIndices/LICENSE.md b/tests/fixtures/gltf/TriangleWithoutIndices/LICENSE.md new file mode 100644 index 0000000..4c12f0e --- /dev/null +++ b/tests/fixtures/gltf/TriangleWithoutIndices/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Triangle Without Indices + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.bin b/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.bin new file mode 100644 index 0000000..f9f96d8 Binary files /dev/null and b/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.bin differ diff --git a/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf b/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf new file mode 100644 index 0000000..b3acc55 --- /dev/null +++ b/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf @@ -0,0 +1,55 @@ +{ + "scene" : 0, + "scenes" : [ + { + "nodes" : [ 0 ] + } + ], + + "nodes" : [ + { + "mesh" : 0 + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 0 + } + } ] + } + ], + + "buffers" : [ + { + "uri" : "TriangleWithoutIndices.bin", + "byteLength" : 36 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 36, + "target" : 34962 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + } + ], + + "asset" : { + "version" : "2.0" + } +} + diff --git a/tests/fixtures/gltf/UnicodeTest/LICENSE.md b/tests/fixtures/gltf/UnicodeTest/LICENSE.md new file mode 100644 index 0000000..06103d1 --- /dev/null +++ b/tests/fixtures/gltf/UnicodeTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Unicode❤♻Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/UnicodeTest/glTF-Binary/UnicodeTest.glb b/tests/fixtures/gltf/UnicodeTest/glTF-Binary/UnicodeTest.glb new file mode 100644 index 0000000..e5e8409 Binary files /dev/null and b/tests/fixtures/gltf/UnicodeTest/glTF-Binary/UnicodeTest.glb differ diff --git a/tests/fixtures/gltf/UnlitTest/LICENSE.md b/tests/fixtures/gltf/UnlitTest/LICENSE.md new file mode 100644 index 0000000..2fc6a6a --- /dev/null +++ b/tests/fixtures/gltf/UnlitTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Unlit Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + + diff --git a/tests/fixtures/gltf/UnlitTest/glTF-Binary/UnlitTest.glb b/tests/fixtures/gltf/UnlitTest/glTF-Binary/UnlitTest.glb new file mode 100644 index 0000000..6998aea Binary files /dev/null and b/tests/fixtures/gltf/UnlitTest/glTF-Binary/UnlitTest.glb differ diff --git a/tests/fixtures/vox/MagicaVoxel-file-format-vox-extension.txt b/tests/fixtures/vox/MagicaVoxel-file-format-vox-extension.txt new file mode 100644 index 0000000..181b376 --- /dev/null +++ b/tests/fixtures/vox/MagicaVoxel-file-format-vox-extension.txt @@ -0,0 +1,165 @@ +* there can be multiple SIZE and XYZI chunks for multiple models; model id is their index in the stored order +* the palette chunk is always stored into the file, so default palette is not needed any more +* the MATT chunk is deprecated, replaced by the MATL chunk, see (4) +* (a), (b), (c) are special data types; (d) is the scene graph in the world editor + +================================= +(a) STRING type + +int32 : buffer size (in bytes) +int8xN : buffer (without the ending "\0") + +================================= +(b) DICT type + +int32 : num of key-value pairs + +// for each key-value pair +{ +STRING : key +STRING : value +}xN + +================================= +(c) ROTATION type + +store a row-major rotation in the bits of a byte + +for example : +R = + 0 1 0 + 0 0 -1 +-1 0 0 +==> +unsigned char _r = (1 << 0) | (2 << 2) | (0 << 4) | (1 << 5) | (1 << 6) + +bit | value +0-1 : 1 : index of the non-zero entry in the first row +2-3 : 2 : index of the non-zero entry in the second row +4 : 0 : the sign in the first row (0 : positive; 1 : negative) +5 : 1 : the sign in the second row (0 : positive; 1 : negative) +6 : 1 : the sign in the third row (0 : positive; 1 : negative) + +================================= +(d) Scene Graph + +T : Transform Node +G : Group Node +S : Shape Node + + T + | + G + / \ + T T + | | + G S + / \ + T T + | | + S S + +================================= +(1) Transform Node Chunk : "nTRN" + +int32 : node id +DICT : node attributes + (_name : string) + (_hidden : 0/1) +int32 : child node id +int32 : reserved id (must be -1) +int32 : layer id +int32 : num of frames (must be greater than 0) + +// for each frame +{ +DICT : frame attributes + (_r : int8) ROTATION, see (c) + (_t : int32x3) translation + (_f : int32) frame index, start from 0 +}xN + +================================= +(2) Group Node Chunk : "nGRP" + +int32 : node id +DICT : node attributes +int32 : num of children nodes + +// for each child +{ +int32 : child node id +}xN + +================================= +(3) Shape Node Chunk : "nSHP" + +int32 : node id +DICT : node attributes +int32 : num of models (must be greater than 0) + +// for each model +{ +int32 : model id +DICT : model attributes : reserved + (_f : int32) frame index, start from 0 +}xN + +================================= +(4) Material Chunk : "MATL" + +int32 : material id +DICT : material properties + (_type : str) _diffuse, _metal, _glass, _emit + (_weight : float) range 0 ~ 1 + (_rough : float) + (_spec : float) + (_ior : float) + (_att : float) + (_flux : float) + (_plastic) + +================================= +(5) Layer Chunk : "LAYR" + +int32 : layer id +DICT : layer attribute + (_name : string) + (_hidden : 0/1) +int32 : reserved id, must be -1 + +================================= +(6) Render Objects Chunk : "rOBJ" + +DICT : rendering attributes + +================================= +(7) Render Camera Chunk : "rCAM" + +int32 : camera id +DICT : camera attribute + (_mode : string) + (_focus : vec(3)) + (_angle : vec(3)) + (_radius : int) + (_frustum : float) + (_fov : int) + +================================= +(8) Palette Note Chunk : "NOTE" + +int32 : num of color names + +// for each name +{ +STRING : color name +}xN + +================================= +(9) Index MAP Chunk : "IMAP" + +size : 256 +// for each index +{ +int32 : palette index association +}x256 diff --git a/tests/fixtures/vox/MagicaVoxel-file-format-vox.txt b/tests/fixtures/vox/MagicaVoxel-file-format-vox.txt new file mode 100644 index 0000000..d15efe7 --- /dev/null +++ b/tests/fixtures/vox/MagicaVoxel-file-format-vox.txt @@ -0,0 +1,111 @@ +MagicaVoxel .vox File Format [10/18/2016] + +1. File Structure : RIFF style +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +1x4 | char | id 'VOX ' : 'V' 'O' 'X' 'space', 'V' is first +4 | int | version number : 150 + +Chunk 'MAIN' +{ + // pack of models + Chunk 'PACK' : optional + + // models + Chunk 'SIZE' + Chunk 'XYZI' + + Chunk 'SIZE' + Chunk 'XYZI' + + ... + + Chunk 'SIZE' + Chunk 'XYZI' + + // palette + Chunk 'RGBA' : optional +} +------------------------------------------------------------------------------- + + +2. Chunk Structure +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +1x4 | char | chunk id +4 | int | num bytes of chunk content (N) +4 | int | num bytes of children chunks (M) + +N | | chunk content + +M | | children chunks +------------------------------------------------------------------------------- + + +3. Chunk id 'MAIN' : the root chunk and parent chunk of all the other chunks + + +4. Chunk id 'PACK' : if it is absent, only one model in the file; only used for the animation in 0.98.2 +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +4 | int | numModels : num of SIZE and XYZI chunks +------------------------------------------------------------------------------- + + +5. Chunk id 'SIZE' : model size +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +4 | int | size x +4 | int | size y +4 | int | size z : gravity direction +------------------------------------------------------------------------------- + + +6. Chunk id 'XYZI' : model voxels, paired with the SIZE chunk +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +4 | int | numVoxels (N) +4 x N | int | (x, y, z, colorIndex) : 1 byte for each component +------------------------------------------------------------------------------- + + +7. Chunk id 'RGBA' : palette +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +4 x 256 | int | (R, G, B, A) : 1 byte for each component + | * + | * color [0-254] are mapped to palette index [1-255], e.g : + | + | for ( int i = 0; i <= 254; i++ ) { + | palette[i + 1] = ReadRGBA(); + | } +------------------------------------------------------------------------------- + + +8. Default Palette : if chunk 'RGBA' is absent +------------------------------------------------------------------------------- +unsigned int default_palette[256] = { + 0x00000000, 0xffffffff, 0xffccffff, 0xff99ffff, 0xff66ffff, 0xff33ffff, 0xff00ffff, 0xffffccff, 0xffccccff, 0xff99ccff, 0xff66ccff, 0xff33ccff, 0xff00ccff, 0xffff99ff, 0xffcc99ff, 0xff9999ff, + 0xff6699ff, 0xff3399ff, 0xff0099ff, 0xffff66ff, 0xffcc66ff, 0xff9966ff, 0xff6666ff, 0xff3366ff, 0xff0066ff, 0xffff33ff, 0xffcc33ff, 0xff9933ff, 0xff6633ff, 0xff3333ff, 0xff0033ff, 0xffff00ff, + 0xffcc00ff, 0xff9900ff, 0xff6600ff, 0xff3300ff, 0xff0000ff, 0xffffffcc, 0xffccffcc, 0xff99ffcc, 0xff66ffcc, 0xff33ffcc, 0xff00ffcc, 0xffffcccc, 0xffcccccc, 0xff99cccc, 0xff66cccc, 0xff33cccc, + 0xff00cccc, 0xffff99cc, 0xffcc99cc, 0xff9999cc, 0xff6699cc, 0xff3399cc, 0xff0099cc, 0xffff66cc, 0xffcc66cc, 0xff9966cc, 0xff6666cc, 0xff3366cc, 0xff0066cc, 0xffff33cc, 0xffcc33cc, 0xff9933cc, + 0xff6633cc, 0xff3333cc, 0xff0033cc, 0xffff00cc, 0xffcc00cc, 0xff9900cc, 0xff6600cc, 0xff3300cc, 0xff0000cc, 0xffffff99, 0xffccff99, 0xff99ff99, 0xff66ff99, 0xff33ff99, 0xff00ff99, 0xffffcc99, + 0xffcccc99, 0xff99cc99, 0xff66cc99, 0xff33cc99, 0xff00cc99, 0xffff9999, 0xffcc9999, 0xff999999, 0xff669999, 0xff339999, 0xff009999, 0xffff6699, 0xffcc6699, 0xff996699, 0xff666699, 0xff336699, + 0xff006699, 0xffff3399, 0xffcc3399, 0xff993399, 0xff663399, 0xff333399, 0xff003399, 0xffff0099, 0xffcc0099, 0xff990099, 0xff660099, 0xff330099, 0xff000099, 0xffffff66, 0xffccff66, 0xff99ff66, + 0xff66ff66, 0xff33ff66, 0xff00ff66, 0xffffcc66, 0xffcccc66, 0xff99cc66, 0xff66cc66, 0xff33cc66, 0xff00cc66, 0xffff9966, 0xffcc9966, 0xff999966, 0xff669966, 0xff339966, 0xff009966, 0xffff6666, + 0xffcc6666, 0xff996666, 0xff666666, 0xff336666, 0xff006666, 0xffff3366, 0xffcc3366, 0xff993366, 0xff663366, 0xff333366, 0xff003366, 0xffff0066, 0xffcc0066, 0xff990066, 0xff660066, 0xff330066, + 0xff000066, 0xffffff33, 0xffccff33, 0xff99ff33, 0xff66ff33, 0xff33ff33, 0xff00ff33, 0xffffcc33, 0xffcccc33, 0xff99cc33, 0xff66cc33, 0xff33cc33, 0xff00cc33, 0xffff9933, 0xffcc9933, 0xff999933, + 0xff669933, 0xff339933, 0xff009933, 0xffff6633, 0xffcc6633, 0xff996633, 0xff666633, 0xff336633, 0xff006633, 0xffff3333, 0xffcc3333, 0xff993333, 0xff663333, 0xff333333, 0xff003333, 0xffff0033, + 0xffcc0033, 0xff990033, 0xff660033, 0xff330033, 0xff000033, 0xffffff00, 0xffccff00, 0xff99ff00, 0xff66ff00, 0xff33ff00, 0xff00ff00, 0xffffcc00, 0xffcccc00, 0xff99cc00, 0xff66cc00, 0xff33cc00, + 0xff00cc00, 0xffff9900, 0xffcc9900, 0xff999900, 0xff669900, 0xff339900, 0xff009900, 0xffff6600, 0xffcc6600, 0xff996600, 0xff666600, 0xff336600, 0xff006600, 0xffff3300, 0xffcc3300, 0xff993300, + 0xff663300, 0xff333300, 0xff003300, 0xffff0000, 0xffcc0000, 0xff990000, 0xff660000, 0xff330000, 0xff0000ee, 0xff0000dd, 0xff0000bb, 0xff0000aa, 0xff000088, 0xff000077, 0xff000055, 0xff000044, + 0xff000022, 0xff000011, 0xff00ee00, 0xff00dd00, 0xff00bb00, 0xff00aa00, 0xff008800, 0xff007700, 0xff005500, 0xff004400, 0xff002200, 0xff001100, 0xffee0000, 0xffdd0000, 0xffbb0000, 0xffaa0000, + 0xff880000, 0xff770000, 0xff550000, 0xff440000, 0xff220000, 0xff110000, 0xffeeeeee, 0xffdddddd, 0xffbbbbbb, 0xffaaaaaa, 0xff888888, 0xff777777, 0xff555555, 0xff444444, 0xff222222, 0xff111111 +}; +------------------------------------------------------------------------------- diff --git a/tests/fixtures/vox/chr_knight.vox b/tests/fixtures/vox/chr_knight.vox new file mode 100644 index 0000000..3ec1006 Binary files /dev/null and b/tests/fixtures/vox/chr_knight.vox differ diff --git a/tests/fixtures/vox/chr_sword.vox b/tests/fixtures/vox/chr_sword.vox new file mode 100644 index 0000000..870b63e Binary files /dev/null and b/tests/fixtures/vox/chr_sword.vox differ diff --git a/tests/fixtures/vox/deer.vox b/tests/fixtures/vox/deer.vox new file mode 100644 index 0000000..759e055 Binary files /dev/null and b/tests/fixtures/vox/deer.vox differ diff --git a/tests/fixtures/vox/maze.vox b/tests/fixtures/vox/maze.vox new file mode 100644 index 0000000..2d14dd4 Binary files /dev/null and b/tests/fixtures/vox/maze.vox differ diff --git a/tests/fixtures/vox/ogt_chr_knight.vox b/tests/fixtures/vox/ogt_chr_knight.vox new file mode 100644 index 0000000..a5017f1 Binary files /dev/null and b/tests/fixtures/vox/ogt_chr_knight.vox differ diff --git a/tests/fixtures/vox/ogt_test_groups.vox b/tests/fixtures/vox/ogt_test_groups.vox new file mode 100644 index 0000000..41c26d5 Binary files /dev/null and b/tests/fixtures/vox/ogt_test_groups.vox differ diff --git a/tests/fixtures/vox/ogt_test_meta_chunk.vox b/tests/fixtures/vox/ogt_test_meta_chunk.vox new file mode 100644 index 0000000..9b566a0 Binary files /dev/null and b/tests/fixtures/vox/ogt_test_meta_chunk.vox differ diff --git a/tests/fixtures/vox/ogt_test_multiple_model_scene.vox b/tests/fixtures/vox/ogt_test_multiple_model_scene.vox new file mode 100644 index 0000000..2e74aeb Binary files /dev/null and b/tests/fixtures/vox/ogt_test_multiple_model_scene.vox differ diff --git a/tests/model/gltf.luau b/tests/model/gltf.luau new file mode 100644 index 0000000..b737320 --- /dev/null +++ b/tests/model/gltf.luau @@ -0,0 +1,351 @@ +-- model/gltf tests: Khronos glTF-Sample-Assets models (JSON with external / embedded buffers, GLB, sparse, interleaved, +-- quantized, morph targets, skins, animations, cameras, lights, texture transforms, material extensions), gltfpack +-- quantized variants and assimp's exporter output, against assimp (meshes, faces, bounds, animations, cameras, +-- lights) and trimesh (area, triangles); full-structure round trips through GLB, embedded .gltf and external files; +-- assimp / trimesh reading our output (gltf_xcheck); textures decoded lazily at the api layer; errors; the fuzz +-- no-throw pass. Fixtures: tools/fixtures/gltf.py. +local T = require("@tests/T") +local F = require("@formats") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/gltf_cases") +local Xcheck = require("@tests/gen/gltf_xcheck") + +local t = T.suite("gltf") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Gltf.decode(Bytes.reader(b), opts) +end + +t:eq(Gltf.name, "gltf", "name") +t:eq(Gltf.category, "model", "category") +t:check(Gltf.caps.decode and Gltf.caps.encode and table.find(Gltf.extensions, "glb"), "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +local function triArea(prim: any): number + local pos = prim.attributes.POSITION + local ind = prim.indices + if not ind then + return 0 + end + local area = 0 + local function P(i: number, k: number): number + return buffer.readf32(pos.data, (i * 3 + k) * 4) + end + for tri = 0, ind.count // 3 - 1 do + local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8) + local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) } + local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(x * x + y * y + z * z) / 2 + end + return area +end + +-- assimp's counts: one mesh per primitive, faces after strips / fans / loops are unrolled +local function counts(scene: any): (number, number) + local prims, faces = 0, 0 + -- the meshes of the default scene (assimp imports that one only) + local meshes, seen = {}, {} + for _, pl in Types.Scene.flatten(scene) do + if not seen[pl.mesh] then + seen[pl.mesh] = true + table.insert(meshes, scene.meshes[pl.mesh]) + end + end + for _, m in meshes do + for _, p in m.primitives do + prims += 1 + local n = if p.indices then p.indices.count else p.attributes.POSITION.count + local mode = p.mode + faces += if mode == "triangles" then n // 3 + elseif mode == "triangle_strip" or mode == "triangle_fan" then math.max(n - 2, 0) + elseif mode == "lines" then n // 2 + elseif mode == "line_strip" then math.max(n - 1, 0) + elseif mode == "line_loop" then n + else n + end + end + return prims, faces +end + +-- every value of two scenes equal (buffers by content), meta skipped +local function same(a: any, b: any, path: string, seen: { [any]: boolean }?, skip: { [string]: boolean }?): (boolean, string?) + local s = seen or {} + local sk = skip or { meta = true, extras = true } + if type(a) == "buffer" and type(b) == "buffer" then + return buffer.tostring(a) == buffer.tostring(b), path + end + if type(a) ~= "table" or type(b) ~= "table" then + if type(a) == "number" and type(b) == "number" then + return near(a, b, 1e-6), path + end + return a == b, path + end + if s[a] then + return true, nil + end + s[a] = true + for k, v in a do + if not sk[k] then + local ok, where = same(v, b[k], path .. "." .. tostring(k), s, sk) + if not ok then + return false, where + end + end + end + for k, v in b do + if not sk[k] and a[k] == nil and v ~= nil then + return false, path .. "." .. tostring(k) .. " (extra)" + end + end + return true, nil +end + +local byName = {} +local checked = { assimp = 0, trimesh = 0, roundTrips = 0 } +for i, c in Cases do + byName[c.name] = c + local scene, err = decode(c.data, { files = c.files }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + local ref = if c.like then nil else c.assimp + local prims, faces = counts(scene) + if ref and not ref.failed then + t:eq(prims, ref.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, ref.faces, c.name .. ": faces (assimp)") + if ref.animations then + t:eq(#scene.animations, ref.animations, c.name .. ": animations (assimp)") + end + if ref.cameras then + t:eq(#scene.cameras, ref.cameras, c.name .. ": cameras (assimp)") + end + if ref.lights then + t:eq(#scene.lights, ref.lights, c.name .. ": lights (assimp)") + end + checked.assimp += 1 + end + -- trimesh: the whole scene in world space (quantized variants: against the original model, within quantization) + local tm = if c.like then byName[c.like].trimesh else c.trimesh + local merged = MeshOps.merge(scene) + local onlyTriangles = true -- trimesh reads TRIANGLES primitives only (not strips / fans) + for _, m in scene.meshes do + for _, p in m.primitives do + if p.mode == "triangle_strip" or p.mode == "triangle_fan" then + onlyTriangles = false + end + end + end + -- trimesh ignores sparse accessors + local sparse = string.find(c.data, "\"sparse\"", 1, true) ~= nil + if tm and not tm.failed and tm.faces > 0 and onlyTriangles and not sparse then + local eps = if c.like then 2e-3 else 1e-5 + t:eq(merged.indices.count // 3, tm.faces, c.name .. ": triangles (trimesh)") + t:check(near(triArea(merged), tm.area, eps), string.format("%s: area %.6g, trimesh %.6g", c.name, triArea(merged), tm.area)) + local lo, hi = MeshOps.bounds(merged) + for k = 1, 3 do + t:check(near(lo[k], tm.bounds[k], eps * 10) and near(hi[k], tm.bounds[k + 3], eps * 10), c.name .. ": bounds (trimesh)") + end + checked.trimesh += 1 + end + -- round trips: GLB, embedded .gltf, external files + local glb, gerr = Gltf.encode(scene, { binary = true }) + t:check(glb, c.name .. ": encode glb: " .. tostring(gerr)) + local back = decode(glb) + t:check(back, c.name .. ": decode our glb") + local SKIP = { meta = true, extras = true, uri = true } -- embedded images lose their file names + local ok, where = same(scene, back, "scene", nil, SKIP) + t:check(ok, c.name .. ": glb round trip differs at " .. tostring(where)) + local text = Gltf.encode(scene) :: buffer + local back2 = decode(text) + local ok2, where2 = same(scene, back2, "scene", nil, SKIP) + t:check(ok2, c.name .. ": embedded .gltf round trip differs at " .. tostring(where2)) + local files = {} + local ext = Gltf.encode(scene, { external = true, files = files, name = "x.gltf" }) :: buffer + t:check(files["x.bin"] ~= nil or #scene.meshes == 0, c.name .. ": external .bin") + local back3 = decode(ext, { files = files }) + local ok3, where3 = same(scene, back3, "scene", nil, SKIP) + t:check(ok3, c.name .. ": external .gltf round trip differs at " .. tostring(where3)) + -- writing what we read back gives the same bytes + t:check(buffer.tostring(Gltf.encode(back, { binary = true }) :: buffer) == buffer.tostring(glb :: buffer), c.name .. ": writing is stable") + checked.roundTrips += 1 + c.index = i +end +t:note("%d files: %d against assimp, %d against trimesh, %d round trips", #Cases, checked.assimp, checked.trimesh, checked.roundTrips) + +-- the reference tools read our files like the originals +local nx = 0 +for _, x in Xcheck do + local c = Cases[x.case] + local a, ca = x.assimp, c.assimp + if not ca.failed then + t:check(not a.failed, x.name .. ": assimp reads our file") + t:eq(a.faces, ca.faces, x.name .. ": assimp faces of our file (" .. c.name .. ")") + t:eq(a.meshes, ca.meshes, x.name .. ": assimp meshes of our file") + for k = 1, 3 do + t:check(near(a.min[k], ca.min[k], 1e-4) and near(a.max[k], ca.max[k], 1e-4), x.name .. ": assimp bounds of our file (" .. c.name .. ")") + end + t:eq(a.animations, ca.animations, x.name .. ": assimp animations of our file") + t:eq(a.cameras, ca.cameras, x.name .. ": assimp cameras of our file") + t:eq(a.lights, ca.lights, x.name .. ": assimp lights of our file") + end + if c.trimesh and not c.trimesh.failed and c.trimesh.faces > 0 and c.name ~= "MeshPrimitiveModes/glTF" and not string.find(c.data, "\"sparse\"", 1, true) then + t:check(not x.trimesh.failed and near(x.trimesh.area, c.trimesh.area, 1e-5) and x.trimesh.faces == c.trimesh.faces, x.name .. ": trimesh area of our file (" .. c.name .. ")") + end + nx += 1 +end +t:note("%d of our files read back by assimp / trimesh like the originals", nx) + +-- details +do + local function load(name: string): any + local c = byName[name] + return decode(c.data, { files = c.files }) + end + local box = load("Box/glTF") + t:check(box.nodes[box.roots[1]].matrix ~= nil and box.meta.source.binary == false, "Box: a matrix node, JSON") + t:check(box.materials[1].metallic == 0 and near(box.materials[1].baseColor[1], 0.8, 1e-6), "Box: material") + local bt = load("BoxTextured/glTF") + local tex = bt.textures[1] + t:check(tex.uri == "CesiumLogoFlat.png" and tex.mime == "image/png" and buffer.tostring(tex.data) == byName["BoxTextured/glTF"].files["CesiumLogoFlat.png"], "BoxTextured: the image bytes from opts.files") + t:check(tex.sampler and tex.sampler.wrapS == "repeat" and tex.sampler.minFilter == "nearest_mipmap_linear", "sampler") + -- the api decodes textures lazily (PNG here) + local _, terrs = F.model.loadTextures(bt) + t:check(tex.image and tex.image.width == 256 and next(terrs) == nil, "F.model.loadTextures decodes the PNG") + local files = {} + local ext = Gltf.encode(bt, { external = true, files = files, name = "bt.gltf" }) :: buffer + t:check(files["CesiumLogoFlat.png"] ~= nil and string.find(buffer.tostring(ext), "\"uri\": \"CesiumLogoFlat.png\"", 1, true) ~= nil, "external images keep their file names") + local emb = load("BoxTextured/glTF-Embedded") + t:check(emb.textures[1].data and buffer.tostring(emb.textures[1].data) == buffer.tostring(tex.data), "embedded data: URI image = the external file") + local sparse = load("SimpleSparseAccessor/glTF-Embedded") + local pos = sparse.meshes[1].primitives[1].attributes.POSITION + local maxY = -math.huge + for v = 0, pos.count - 1 do + maxY = math.max(maxY, buffer.readf32(pos.data, v * 12 + 4)) + end + t:eq(maxY, 4, "sparse values substituted (the raised vertices, max = the accessor max)") + local cams = load("Cameras/glTF") + t:check(#cams.cameras == 2 and cams.cameras[1].type == "perspective" and cams.cameras[2].type == "orthographic", "cameras") + local skin = load("SimpleSkin/glTF") + t:check(#skin.skins == 1 and #skin.skins[1].joints == 2 and skin.skins[1].inverseBindMatrices.matrix and skin.skins[1].inverseBindMatrices.components == 16, "skin") + t:check(#skin.animations == 1 and skin.animations[1].channels[1].path == "rotation", "skin animation") + local morph = load("SimpleMorph/glTF") + t:check(#morph.meshes[1].primitives[1].targets == 2 and morph.meshes[1].weights[1] == 0.5, "morph targets, weights") + local q = load("AnimatedMorphCube/glTF-Quantized") + local qp = q.meshes[1].primitives[1] + t:check(qp.attributes.NORMAL.type == "snorm8" and qp.targets and qp.targets[1].POSITION.type == "i16", "quantized normals / target deltas") + local unlit = load("UnlitTest/glTF-Binary") + t:check(unlit.materials[1].extensions and unlit.materials[1].extensions.KHR_materials_unlit ~= nil, "KHR_materials_unlit") + local es = load("EmissiveStrengthTest/glTF-Binary") + local strength = 0 + for _, m in es.materials do + local e = m.extensions and m.extensions.KHR_materials_emissive_strength + if e then + strength = math.max(strength, e.emissiveStrength) + end + end + t:check(strength > 1, "KHR_materials_emissive_strength") + local cc = load("ClearCoatCarPaint/glTF-Binary") + local clear = cc.materials[1].extensions and cc.materials[1].extensions.KHR_materials_clearcoat + t:check(clear and clear.clearcoatFactor ~= nil, "KHR_materials_clearcoat") + local tt = load("TextureTransformTest/glTF") + local nt = 0 + for _, m in tt.materials do + if m.baseColorTexture and m.baseColorTexture.transform then + nt += 1 + end + end + t:check(nt >= 5, "KHR_texture_transform on " .. nt .. " materials") + local lights = load("PointLightIntensityTest/glTF-Binary") + t:check(#lights.lights > 0 and lights.lights[1].type == "point", "KHR_lights_punctual") + local ms = load("MultipleScenes/glTF") + t:check(#ms.meta.gltf.scenes == 2, "multiple scenes kept") + local modes = load("MeshPrimitiveModes/glTF") + local seen = {} + for _, m in modes.meshes do + for _, p in m.primitives do + seen[p.mode] = true + end + end + t:check(seen.points and seen.lines and seen.line_loop and seen.line_strip and seen.triangle_strip and seen.triangle_fan, "every primitive mode") + local inter = load("BoxInterleaved/glTF-Binary") + t:check(inter.meshes[1].primitives[1].attributes.NORMAL.count == 24, "interleaved (byteStride) attributes") + -- quantized output declares KHR_mesh_quantization + local qglb = Gltf.encode(q, { binary = true }) :: buffer + t:check(string.find(buffer.tostring(qglb), "KHR_mesh_quantization", 1, true) ~= nil, "KHR_mesh_quantization written") + -- a Scene made by hand (an OBJ-like mesh with u8 colours and polygons) writes and reads back + local s = Types.Scene.new() + local p = Types.Scene.accessor(nil, "f32", 3, 4) + for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } } do + for k = 1, 3 do + buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k]) + end + end + local col = Types.Scene.accessor(nil, "unorm8", 3, 4) + local faces = Types.Scene.accessor(nil, "u32", 1, 1) + buffer.writeu32(faces.data, 0, 4) + local ind = Types.Scene.accessor(nil, "u32", 1, 4) + for k = 0, 3 do + buffer.writeu32(ind.data, k * 4, k) + end + local s2 = Types.Scene.fromPrimitive({ attributes = { POSITION = p, COLOR_0 = col }, indices = ind, faces = faces, mode = "polygons" }, "quad") + local out = Gltf.encode(s2, { binary = true }) :: buffer + local back = decode(out) + t:check(back and back.meshes[1].primitives[1].indices.count == 6 and back.meshes[1].primitives[1].attributes.COLOR_0.type == "unorm8", "polygons fan-triangulated, unorm8 VEC3 colours (padded stride)") + -- through the api: the destination's extension picks GLB + local viaApi = F.save(s2, nil, { format = "glb" }) + t:check(viaApi and buffer.readstring(viaApi, 0, 4) == "glTF", "F.save format glb") + local viaApi2 = F.save(s2, nil, { format = "gltf" }) + t:check(viaApi2 and buffer.readstring(viaApi2, 0, 1) == "{", "F.save format gltf") + local loaded = F.load(viaApi) + t:check(loaded and loaded.kind == "scene" and loaded.meta.source.format == "gltf", "F.load detects GLB") +end + +-- errors +do + local _, e = decode("{ not json") + t:check(e and (e.code == Err.CORRUPT or e.code == Err.TRUNCATED), "bad JSON: " .. tostring(e)) + local _, e2 = decode('{"asset": {"version": "1.0"}}') + t:check(e2 and e2.code == Err.UNSUPPORTED, "glTF 1: " .. tostring(e2)) + local _, e3 = decode('{"asset": {"version": "2.0"}, "extensionsRequired": ["KHR_draco_mesh_compression"]}') + t:check(e3 and e3.code == Err.UNSUPPORTED, "Draco: " .. tostring(e3)) + local c = byName["Box/glTF"] + local _, e4 = decode(c.data) + t:check(e4 and e4.code == Err.IO, "missing .bin: " .. tostring(e4)) + local _, e5 = decode('{"asset": {"version": "2.0"}, "buffers": [{"byteLength": 4, "uri": "data:application/octet-stream;base64,AAAAAA=="}], "bufferViews": [{"buffer": 0, "byteLength": 4}], "accessors": [{"bufferView": 0, "componentType": 5126, "count": 2, "type": "SCALAR"}]}') + t:check(e5 and e5.code == Err.CORRUPT, "accessor past its view: " .. tostring(e5)) + local glb = byName["Box/glTF-Binary"].data + local _, e6 = decode(string.sub(glb, 1, 100)) + t:check(e6 and e6.code == Err.TRUNCATED, "truncated GLB: " .. tostring(e6)) + local _, e7 = Gltf.encode({} :: any) + t:check(e7 and e7.code == Err.ARG, "encode junk") + local bad = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(buffer.create(4), "f32", 3, 10) }, mode = "triangles" }) + local _, e8 = Gltf.encode(bad) + t:check(e8 and e8.code == Err.ARG, "encode a short accessor: " .. tostring(e8)) +end + +-- fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = Gltf.decode(Bytes.reader(b)) + if s then + Gltf.encode(s, { binary = true }) + MeshOps.merge(s) + end + return s + end, samples, { mutations = 20 }) +end + +t:done() diff --git a/tests/model/obj.luau b/tests/model/obj.luau new file mode 100644 index 0000000..e65810e --- /dev/null +++ b/tests/model/obj.luau @@ -0,0 +1,235 @@ +-- model/obj tests: OBJ / MTL files (materials and texture maps, objects and groups, n-gons, negative indices, vertex +-- colours, continuations, lines and points, a concave polygon, assimp's exporter output) against assimp (meshes, +-- vertices, faces, bounds, materials) and trimesh (area, triangles); MTL mapping; ear clipping (MeshOps) against the +-- exact polygon area; round trips through the writer, and assimp / trimesh reading our output (obj_xcheck); errors; +-- the fuzz no-throw pass. Fixtures: tools/fixtures/obj.py. +local T = require("@tests/T") +local Obj = require("@formats/model/obj") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/obj_cases") +local Xcheck = require("@tests/gen/obj_xcheck") + +local t = T.suite("obj") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Obj.decode(Bytes.reader(b), opts) +end + +t:eq(Obj.name, "obj", "name") +t:eq(Obj.category, "model", "category") +t:check(Obj.caps.decode and Obj.caps.encode, "caps") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +local function triArea(prim: any): number + local pos = prim.attributes.POSITION + local ind = prim.indices + local area = 0 + local function P(i: number, k: number): number + return buffer.readf32(pos.data, (i * 3 + k) * 4) + end + for tri = 0, ind.count // 3 - 1 do + local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8) + local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) } + local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(x * x + y * y + z * z) / 2 + end + return area +end + +-- the counts assimp reports: meshes (= our primitives), vertices, faces (triangles + line segments + points) +local function counts(scene: any): (number, number, number) + local prims, verts, faces = 0, 0, 0 + for _, m in scene.meshes do + for _, p in m.primitives do + prims += 1 + verts += p.attributes.POSITION.count + local n = if p.indices then p.indices.count else p.attributes.POSITION.count + faces += if p.mode == "triangles" then n // 3 elseif p.mode == "lines" then n // 2 else n + end + end + return prims, verts, faces +end + +local function checkAgainst(scene: any, assimp: any, trimesh: any?, label: string, vertices: boolean, fanArea: number) + local prims, verts, faces = counts(scene) + t:eq(prims, assimp.meshes, label .. ": meshes (assimp)") + if vertices then + t:eq(verts, assimp.vertices, label .. ": vertices (assimp)") + end + t:eq(faces, assimp.faces, label .. ": faces (assimp)") + local lo, hi = MeshOps.bounds(scene) + t:check(lo and hi, label .. ": bounds") + for k = 1, 3 do + t:check(near(lo[k], assimp.min[k], 1e-5) and near(hi[k], assimp.max[k], 1e-5), label .. ": bounds = assimp's") + end + local all = MeshOps.merge(scene) + t:check(near(triArea(all), fanArea, 1e-5), string.format("%s: area %g, exact fan area %g", label, triArea(all), fanArea)) + if trimesh then + local merged = MeshOps.merge(scene) + t:eq(merged.indices.count // 3, trimesh.faces, label .. ": triangles (trimesh)") + t:check(near(triArea(merged), trimesh.area, 1e-5), string.format("%s: area %g, trimesh %g", label, triArea(merged), trimesh.area)) + end +end + +local byName = {} +for _, c in Cases do + byName[c.name] = c + local scene, err = decode(c.data, { files = c.files }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + checkAgainst(scene, c.assimp, c.trimesh, c.name, not c.noVertexCount, c.fanArea) + if #scene.materials > 0 then + t:eq(#scene.materials, c.assimp.materials, c.name .. ": materials (assimp)") + end + -- round trip through our writer + local files = {} + local out, eerr = Obj.encode(scene, { name = "rt.obj", files = files }) + t:check(out, c.name .. ": encode: " .. tostring(eerr)) + local back, berr = decode(out, { files = files }) + t:check(back, c.name .. ": decode our OBJ: " .. tostring(berr)) + local p1, v1, f1 = counts(scene) + local p2, v2, f2 = counts(back) + t:check(p1 == p2 and v1 == v2 and f1 == f2, c.name .. ": round trip counts") + local m1, m2 = MeshOps.merge(scene), MeshOps.merge(back) + for _, attr in { "POSITION", "TEXCOORD_0", "NORMAL", "COLOR_0" } do + local a, b = m1.attributes[attr], m2.attributes[attr] + t:check((a == nil) == (b == nil), c.name .. ": round trip has " .. attr) + if a and b then + t:check(buffer.tostring(a.data) == buffer.tostring(b.data), c.name .. ": round trip " .. attr .. " exact") + end + end + if m1.indices then + t:check(buffer.tostring(m1.indices.data) == buffer.tostring(m2.indices.data), c.name .. ": round trip indices") + end + t:eq(#back.materials, #scene.materials, c.name .. ": round trip materials") +end + +-- the reference tools read our output like the original +for _, x in Xcheck do + local orig = byName[string.sub(x.name, 4)] + t:check(orig ~= nil, x.name .. ": a case") + t:eq(x.assimp.faces, orig.assimp.faces, x.name .. ": assimp faces of our file") + if not orig.noVertexCount then + t:eq(x.assimp.vertices, orig.assimp.vertices, x.name .. ": assimp vertices of our file") + end + t:eq(x.assimp.materials, orig.assimp.materials, x.name .. ": assimp materials of our file") + for k = 1, 3 do + t:check(near(x.assimp.min[k], orig.assimp.min[k], 1e-5) and near(x.assimp.max[k], orig.assimp.max[k], 1e-5), x.name .. ": assimp bounds of our file") + end + if orig.trimesh then + t:check(near(x.trimesh.area, orig.trimesh.area, 1e-5) and x.trimesh.faces == orig.trimesh.faces, x.name .. ": trimesh area of our file") + end +end +t:note("%d files match assimp / trimesh; %d of our files read back by assimp / trimesh", #Cases, #Xcheck) + +-- the cube in detail: nodes, materials, textures +do + local c = byName["cube.obj"] + local s = decode(c.data, { files = c.files }) + t:eq(#s.roots, 1, "one object") + local root = s.nodes[s.roots[1]] + t:check(root.name == "Cube" and #root.children == 2 and root.mesh == nil, "the object holds two groups") + t:check(s.nodes[root.children[1]].name == "top" and s.nodes[root.children[2]].name == "bottom", "group names") + local red, blue = s.materials[1], s.materials[2] + t:check(red.name == "red" and red.baseColor[1] == 1 and red.baseColor[2] == 0 and red.metallic == 0, "red: Kd, not metallic") + t:check(near(red.roughness, math.sqrt(2 / 52), 1e-9), "red: roughness from Ns") + local tex = s.textures[red.baseColorTexture.texture] + t:check(tex.uri == "textures/tex.png" and tex.mime == "image/png" and tex.data and buffer.len(tex.data) > 30, "map_Kd: uri, mime, bytes through opts.files") + t:check(red.baseColorTexture.transform.scale[1] == 2 and red.baseColorTexture.transform.offset[1] == 0.5, "map_Kd -s / -o") + t:check(red.normalTexture and red.normalTexture.scale == 0.5, "map_Bump -bm") + t:check(red.extras.obj.values.Ns[1] == 50 and red.extras.obj.values.illum[1] == 2, "Phong values in extras") + t:check(blue.baseColor[4] == 0.5 and blue.alphaMode == "blend" and blue.roughness == 0.25 and blue.metallic == 1 and blue.emissive[3] == 0.3, "blue: d, Pr, Pm, Ke") + t:check(s.nodes[root.children[1]].extras.obj.smoothing == "1", "smoothing group kept") + -- the uv flip + local top = s.meshes[s.nodes[root.children[1]].mesh].primitives[1] + t:check(top.attributes.TEXCOORD_0 ~= nil and buffer.readf32(top.attributes.TEXCOORD_0.data, 4) == 1, "vt 0 0 -> (0, 1) (top-left origin)") + local s2 = decode(c.data, { files = c.files, flipV = false }) + local top2 = s2.meshes[s2.nodes[s2.nodes[s2.roots[1]].children[1]].mesh].primitives[1] + t:check(buffer.readf32(top2.attributes.TEXCOORD_0.data, 4) == 0, "flipV = false") + -- without the MTL: named default materials, the library listed as missing + local s3 = decode(c.data) + t:check(#s3.materials == 2 and s3.meta.source.missingMtl[1] == "cube.mtl", "missing mtllib") + -- through opts.mtl / resolve + local s4 = decode(c.data, { mtl = c.files["cube.mtl"] }) + t:check(s4.materials[1].baseColor[1] == 1 and s4.textures[1].data == nil, "opts.mtl (texture bytes not found)") + local asked = {} + local s5 = decode(c.data, { resolve = function(uri: string): any + table.insert(asked, uri) + return c.files[uri] + end }) + t:check(s5.materials[2].baseColor[4] == 0.5 and table.find(asked, "cube.mtl") and table.find(asked, "textures/tex.png"), "opts.resolve") + -- the MTL written back keeps the maps and their options + local files = {} + Obj.encode(s, { name = "x.obj", files = files }) + local mtl = files["x.mtl"] + t:check(type(mtl) == "string" and string.find(mtl, "map_Kd -o 0.5 0 -s 2 2 textures/tex.png", 1, true) ~= nil, "MTL map_Kd written: " .. tostring(mtl)) + t:check(string.find(mtl, "newmtl blue", 1, true) and string.find(mtl, "\nd 0.5", 1, true), "MTL blue written") + t:check(files["textures/tex.png"] ~= nil, "texture bytes written to opts.files") +end + +-- polygons: triangulate = false keeps them; ear clipping gets the concave area right, the fan does not +do + local c = byName["concave.obj"] + local s = decode(c.data, { triangulate = false }) + local p = s.meshes[1].primitives[1] + t:check(p.mode == "polygons" and p.faces.count == 2 and p.indices.count == 14, "polygons kept") + local tri = MeshOps.triangulate(p) :: any + t:check(near(triArea(tri), c.polygonArea, 1e-9), "ear clipping area " .. triArea(tri) .. " = " .. c.polygonArea) + local fan = MeshOps.triangulate(p, { method = "fan" }) :: any + t:check(near(triArea(fan), c.trimesh.area, 1e-9), "fan area = trimesh's (fan) area") + -- n-gons written as n-gons + local out = Obj.encode(s) :: buffer + t:check(string.find(buffer.tostring(out), "\nf 7 8 9 10 11 12 13 14", 1, true) ~= nil, "an octagon written as one face") + local back = decode(out, { triangulate = false }) + t:eq(back.meshes[1].primitives[1].faces.count, 2, "polygons round trip") +end + +-- lines and points +do + local s = decode(byName["wire.obj"].data) + local modes = {} + for _, p in s.meshes[1].primitives do + modes[p.mode] = p + end + t:check(modes.lines and modes.lines.indices.count == 8 and modes.points and modes.triangles, "l (polyline -> 4 segments), p, f") +end + +-- errors +do + local _, e = decode("v 0 0 0\nf 1 2 3\n") + t:check(e and e.code == Err.CORRUPT, "index out of range: " .. tostring(e)) + local _, e2 = decode("v 0 0\n") + t:check(e2 and e2.code == Err.CORRUPT, "short vertex: " .. tostring(e2)) + local _, e3 = decode(byName["random.obj"].data, { maxVertices = 10 }) + t:check(e3 and e3.code == Err.LIMIT, "maxVertices: " .. tostring(e3)) + local _, e4 = Obj.encode({} :: any) + t:check(e4 and e4.code == Err.ARG, "encode junk") + t:check(Obj.sniff(Bytes.reader(buffer.fromstring(byName["cube.obj"].data))) > 0, "sniff an OBJ") + t:eq(Obj.sniff(Bytes.reader(buffer.fromstring("\137PNG\r\n\26\n"))), 0, "sniff a PNG") + local empty = decode("# nothing\n") + t:check(empty and #empty.nodes == 0, "an empty file is an empty scene") +end + +-- fuzz +do + local samples = {} + for _, c in Cases do + table.insert(samples, c.data) + end + t:fuzz("decode", function(b: buffer) + local s = Obj.decode(Bytes.reader(b), { triangulate = false }) + if s then + Obj.encode(s) + MeshOps.merge(s) + end + return s + end, samples, { mutations = 40 }) +end + +t:done() diff --git a/tests/model/off.luau b/tests/model/off.luau new file mode 100644 index 0000000..5a72e5b --- /dev/null +++ b/tests/model/off.luau @@ -0,0 +1,214 @@ +-- model/off tests: OFF files written by trimesh and by the generator (COFF integer / float colours, RGB / RGBA, NOFF, +-- STOFF, STCNOFF, face colours, colormap indices, comments, counts on the header line, CRLF, tabs, n-gons, a point +-- cloud) against the values they were written from (positions cross-checked with trimesh); our encoder's output read +-- back by trimesh, assimp and the generator's reader (verdicts from the fixture step); round trips (polygons, +-- triangles, face colours, scenes); the contract, error codes and the fuzz no-throw pass. Fixtures: +-- tools/fixtures/off.py. +local T = require("@tests/T") +local Off = require("@formats/model/off") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/off") +local Scenes = require("@tests/gen/off_scenes") + +local t = T.suite("off") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Off.decode(Bytes.reader(b), opts) +end + +local function same(a: any, b: any): boolean + if a == nil or b == nil then + return a == b + end + return a.type == b.type and a.components == b.components and a.count == b.count and buffer.tostring(a.data) == buffer.tostring(b.data) +end + +-- 1. the contract +t:eq(Off.name, "off", "name") +t:eq(Off.category, "model", "category") +t:check(table.find(Off.extensions, "off") ~= nil, "extensions") +t:check(Off.caps.decode and Off.caps.encode, "caps") + +-- 2. every fixture against the values it was written from; 3. round trips +for _, c in Fx.cases do + local label = c.name + local scene, err = decode(c.data) + t:check(scene, label .. ": " .. tostring(err)) + local src = scene.meta.source + t:check(src.format == "off" and src.keyword == c.keyword and src.vertices == c.vertices and src.faces == c.faces, label .. ": meta.source") + t:eq(src.colormap, c.colormap, label .. ": colormap flag") + local p = scene.meshes[1].primitives[1] + local A = p.attributes + t:eq(Crc32.of(A.POSITION.data), c.pos_crc, label .. ": POSITION crc") + t:check((A.NORMAL and Crc32.of(A.NORMAL.data)) == c.nrm_crc, label .. ": NORMAL") + t:check((A.TEXCOORD_0 and Crc32.of(A.TEXCOORD_0.data)) == c.tex_crc, label .. ": TEXCOORD_0") + if c.color then + t:check(A.COLOR_0 and A.COLOR_0.type == c.color.type and A.COLOR_0.components == 4, label .. ": COLOR_0 type") + t:eq(Crc32.of(A.COLOR_0.data), c.color.crc, label .. ": COLOR_0 crc") + else + t:check(A.COLOR_0 == nil, label .. ": no COLOR_0") + end + local ex = p.extras or {} + if c.faceColors then + t:check(ex.faceColors and ex.faceColors.type == c.faceColors.type and ex.faceColors.count == c.faces, label .. ": faceColors type") + t:eq(Crc32.of(ex.faceColors.data), c.faceColors.crc, label .. ": faceColors crc") + else + t:check(ex.faceColors == nil, label .. ": no faceColors") + end + if c.faces == 0 then + t:check(p.mode == "points" and p.indices == nil, label .. ": a point cloud") + else + t:eq(p.mode, "triangles", label .. ": mode") + t:eq(p.indices.count, c.tris * 3, label .. ": index count") + t:eq(Crc32.of(p.indices.data), if c.allTri then c.corners_crc else c.tri_crc, label .. ": indices crc") + if c.faceColors and not c.allTri then + t:eq(Crc32.of(ex.faceOfTriangle.data), c.fot_crc, label .. ": faceOfTriangle") + end + end + t:eq(Off.sniff(Bytes.reader(buffer.fromstring(c.data))), 0.9, label .. ": sniff") + -- polygons kept + local poly = decode(c.data, { triangulate = false }) + local pp = poly.meshes[1].primitives[1] + if c.faces > 0 and not c.allTri then + t:eq(pp.mode, "polygons", label .. ": polygons") + t:eq(Crc32.of(pp.indices.data), c.corners_crc, label .. ": corners") + t:eq(Crc32.of(pp.faces.data), c.sizes_crc, label .. ": sizes") + end + -- round trips: polygons in, polygons out; triangles in, triangles out (face colours through faceOfTriangle) + for _, s in { poly, scene } do + local out, eerr = Off.encode(s) + t:check(out, label .. ": encode: " .. tostring(eerr)) + local back, berr = decode(out, { triangulate = false }) + t:check(back, label .. ": decode our output: " .. tostring(berr)) + local bp, sp = back.meshes[1].primitives[1], s.meshes[1].primitives[1] + for name, a in sp.attributes do + t:check(same(bp.attributes[name], a), label .. ": " .. name .. " round trip") + end + t:eq(bp.mode, sp.mode, label .. ": mode round trip") + t:check(same(bp.indices, sp.indices) and same(bp.faces, sp.faces), label .. ": faces round trip") + local sfc = sp.extras and sp.extras.faceColors + local bfc = bp.extras and bp.extras.faceColors + if sfc and sp.extras.faceOfTriangle then + t:eq(bfc.count, sp.extras.faceOfTriangle.count, label .. ": a colour per triangle") + else + t:check(same(bfc, sfc), label .. ": faceColors round trip") + end + end +end +t:note("%d files match their source values and round-trip", #Fx.cases) + +for _, v in Fx.ours do + t:check(v.ok, "trimesh / assimp read our " .. v.name .. ": " .. v.detail) +end +t:note("%d encodings read back by trimesh, assimp and the generator", #Fx.ours) + +-- the encoder scenes: decode(encode()) gives the scene back (identity transforms) +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local attrs = {} + for name, a in p.attrs do + attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count) + end + local prim: any = { attributes = attrs, mode = p.mode } + if p.indices then + prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4) + end + if p.faceColors then + prim.extras = { faceColors = Types.Scene.accessor(buffer.fromstring(p.faceColors), "unorm8", 4, #p.faceColors // 4) } + end + table.insert(prims, prim) + end + scene.meshes[i] = { primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end +for _, spec in Scenes do + local scene = build(spec) + local sp = scene.meshes[1].primitives[1] + local out = Off.encode(scene) :: buffer + local back = decode(out, { triangulate = false }) + local bp = back.meshes[1].primitives[1] + if spec.name ~= "polys" then + for name, a in sp.attributes do + t:check(same(bp.attributes[name], a), spec.name .. ": " .. name .. " round trip") + end + end + t:eq(bp.mode, sp.mode, spec.name .. ": mode") + t:check(same(bp.indices, sp.indices) and same(bp.faces, sp.faces), spec.name .. ": faces") + t:check(same(bp.extras and bp.extras.faceColors, sp.extras and sp.extras.faceColors), spec.name .. ": face colours") +end +do + local scene = build(Scenes[1]) + local plain = buffer.tostring(Off.encode(scene, { colors = false, normals = false, texcoords = false }) :: buffer) + t:eq(string.sub(plain, 1, 4), "OFF\n", "plain OFF") + t:eq(string.sub(buffer.tostring(Off.encode(scene, { colors = false }) :: buffer), 1, 6), "STNOFF", "no colours") + local cm = buffer.tostring(Off.encode(scene, { comment = "made\nhere" }) :: buffer) + t:check(string.find(cm, "STCNOFF\n# made here\n", 1, true) ~= nil, "comment option") +end + +-- 4. error codes +do + local function code(s: string, opts: any?): string? + local _, e = decode(s, opts) + return e and e.code + end + t:check(decode("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n"), "a minimal file") + t:eq(code("PFF\n3 1 0\n"), Err.CORRUPT, "bad keyword") + t:eq(code("4OFF\n1 0 0\n0 0 0 1\n"), Err.UNSUPPORTED, "4OFF") + t:eq(code("nOFF\n4\n1 0 0\n0 0 0 0\n"), Err.UNSUPPORTED, "nOFF") + t:eq(code("OFF BINARY\n"), Err.UNSUPPORTED, "binary OFF") + t:eq(code("OFF\n"), Err.TRUNCATED, "no counts") + t:eq(code("# nothing\n\n"), Err.TRUNCATED, "empty") + t:eq(code("OFF\nx 1 0\n"), Err.CORRUPT, "bad counts") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n"), Err.TRUNCATED, "face missing") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 3\n"), Err.CORRUPT, "index out of range") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n4 0 1 2\n"), Err.CORRUPT, "short face") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 q 0\n0 1 0\n3 0 1 2\n"), Err.CORRUPT, "bad number") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0\n0 1 0\n3 0 1 2\n"), Err.CORRUPT, "short vertex") + t:eq(code("COFF\n3 1 0\n0 0 0 1 2\n1 0 0 1 2\n0 1 0 1 2\n3 0 1 2\n"), Err.CORRUPT, "two colour values") + t:eq(code("COFF\n3 1 0\n0 0 0 300 2 3\n1 0 0 1 2 3\n0 1 0 1 2 3\n3 0 1 2\n"), Err.CORRUPT, "colour over 255") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n", { maxVertices = 2 }), Err.LIMIT, "maxVertices") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n", { maxFaces = 0 }), Err.LIMIT, "maxFaces") + t:eq(code("OFF\n10000000 0 0\n1 2 3\n"), Err.TRUNCATED, "counts over the data") + local _, a1 = Off.encode({} :: any) + t:check(a1 and a1.code == Err.ARG, "encode a non-scene: " .. tostring(a1)) + local nan = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 1) }, mode = "points" }) + buffer.writef32(nan.meshes[1].primitives[1].attributes.POSITION.data, 0, math.huge) + local _, a2 = Off.encode(nan) + t:check(a2 and a2.code == Err.ARG, "infinite coordinate: " .. tostring(a2)) + t:eq(Off.sniff(Bytes.reader(buffer.fromstring("solid x\n"))), 0, "sniff an STL") +end + +-- 5. fuzz +do + local samples = {} + for _, c in Fx.cases do + table.insert(samples, c.data) + end + t:fuzz("decode", function(b: buffer) + return Off.decode(Bytes.reader(b)) + end, samples, { mutations = 20 }) + t:fuzz("decode polygons + re-encode", function(b: buffer) + local s = Off.decode(Bytes.reader(b), { triangulate = false }) + if s then + return Off.encode(s) + end + return nil + end, samples, { mutations = 6, garbage = 20 }) +end + +t:done() diff --git a/tests/model/ply.luau b/tests/model/ply.luau new file mode 100644 index 0000000..961f453 --- /dev/null +++ b/tests/model/ply.luau @@ -0,0 +1,379 @@ +-- model/ply tests: files written by plyfile (ascii / binary LE / BE, every property type and spelling, odd orders, +-- n-gons up to 300 vertices, face properties and lists, extra elements, comments, point clouds) and by assimp, against +-- plyfile's reading mapped to the Scene conventions (CRC-32 of every attribute, the indices triangulated or as +-- polygons, face data, raw elements); our encoder's output read back by plyfile and assimp (verdicts from the fixture +-- step); round trips in every encoding (fixtures and generated scenes, polygons and points); the contract, error +-- codes, the fuzz no-throw pass and a binary decode throughput note. Fixtures: tools/fixtures/ply.py. +local T = require("@tests/T") +local Ply = require("@formats/model/ply") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/ply") +local Scenes = require("@tests/gen/ply_scenes") + +local t = T.suite("ply") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Ply.decode(Bytes.reader(b), opts) +end + +local ENCODINGS = { "ascii", "binary_little_endian", "binary_big_endian" } + +-- 1. the contract +t:eq(Ply.name, "ply", "name") +t:eq(Ply.category, "model", "category") +t:check(table.find(Ply.extensions, "ply") ~= nil, "extensions") +t:check(Ply.caps.decode and Ply.caps.encode, "caps") + +-- a decoded scene against a reference case (triangulated) +local function verify(scene: any, c: any, label: string) + t:check(scene.kind == "scene" and #scene.meshes == 1 and #scene.meshes[1].primitives == 1, label .. ": one primitive") + local p = scene.meshes[1].primitives[1] + local n = 0 + for name, want in c.attrs do + local a = p.attributes[name] + t:check(a ~= nil, label .. ": attribute " .. name) + t:eq(a.type, want.type, label .. ": " .. name .. " type") + t:eq(a.components, want.components, label .. ": " .. name .. " components") + t:eq(a.count, c.vertices, label .. ": " .. name .. " count") + t:eq(Crc32.of(a.data), want.crc, label .. ": " .. name .. " crc") + n += 1 + end + local m = 0 + for _ in p.attributes do + m += 1 + end + t:eq(m, n, label .. ": no other attributes") + if c.faces > 0 then + t:eq(p.mode, "triangles", label .. ": mode") + t:eq(Crc32.of(p.indices.data), if c.allTri then c.corners_crc else c.tri_crc, label .. ": indices crc") + t:eq(p.indices.count, c.tris * 3, label .. ": index count") + local fa = c.faceAttributes + local ex = p.extras or {} + if next(fa) ~= nil and not c.allTri then + t:eq(Crc32.of(ex.faceOfTriangle.data), c.fot_crc, label .. ": faceOfTriangle") + else + t:check(ex.faceOfTriangle == nil, label .. ": no faceOfTriangle") + end + for name, want in fa do + if want.list then + local fl = ex.faceLists[name] + t:eq(Crc32.of(fl.sizes.data), want.sizes_crc, label .. ": face list " .. name .. " sizes") + t:eq(Crc32.of(fl.items.data), want.items_crc, label .. ": face list " .. name .. " items") + else + local a = ex.faceAttributes[name] + t:eq(a.type, want.type, label .. ": face attribute " .. name .. " type") + t:eq(Crc32.of(a.data), want.crc, label .. ": face attribute " .. name) + end + end + else + t:eq(p.mode, "points", label .. ": a point cloud") + t:check(p.indices == nil, label .. ": no indices") + end + local meta = scene.meta.ply + t:eq(#meta.comments, #c.comments, label .. ": comment count") + for i, s in c.comments do + t:eq(meta.comments[i], s, label .. ": comment") + end + t:eq(#meta.objInfo, #c.objInfo, label .. ": obj_info count") + for i, s in c.objInfo do + t:eq(meta.objInfo[i], s, label .. ": obj_info") + end + t:eq(table.concat(meta.order, ","), table.concat(c.order, ","), label .. ": element order") + t:eq(#meta.elements, #c.elements, label .. ": raw elements") + for i, want in c.elements do + local el = meta.elements[i] + t:eq(el.name, want.name, label .. ": element name") + t:eq(el.count, want.count, label .. ": element count") + for k, wp in want.props do + local pr = el.properties[k] + t:eq(pr.name, wp.name, label .. ": element property") + if wp.list then + t:eq(Crc32.of(pr.sizes), wp.sizes_crc, label .. ": " .. el.name .. "." .. pr.name .. " sizes") + t:eq(Crc32.of(pr.values), wp.values_crc, label .. ": " .. el.name .. "." .. pr.name .. " items") + else + t:eq(Crc32.of(pr.values), wp.crc, label .. ": " .. el.name .. "." .. pr.name) + end + end + end +end + +-- 2. every fixture against plyfile; 3. round trips of every fixture in every encoding +for _, c in Fx.cases do + local label = c.name + local scene, err = decode(c.data) + t:check(scene, label .. ": " .. tostring(err)) + t:eq(scene.meta.source.format, "ply", label .. ": meta.source.format") + t:eq(scene.meta.source.encoding, c.encoding, label .. ": encoding") + t:eq(scene.meta.source.vertices, c.vertices, label .. ": vertices") + t:eq(scene.meta.source.faces, c.faces, label .. ": faces") + verify(scene, c, label) + t:eq(Ply.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, label .. ": sniff") + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 4, c.data) + local s2 = Ply.decode(Bytes.reader(big, 4, #c.data)) + t:check(s2 and Crc32.of(s2.meshes[1].primitives[1].attributes.POSITION.data) == c.attrs.POSITION.crc, label .. ": decode from a sub-range") + -- polygons kept + local poly = decode(c.data, { triangulate = false }) + local pp = poly.meshes[1].primitives[1] + if c.faces > 0 and not c.allTri then + t:eq(pp.mode, "polygons", label .. ": polygons mode") + t:eq(Crc32.of(pp.indices.data), c.corners_crc, label .. ": polygon corners") + t:eq(Crc32.of(pp.faces.data), c.sizes_crc, label .. ": polygon sizes") + end + for _, enc in ENCODINGS do + local out, eerr = Ply.encode(scene, { format = enc }) + t:check(out, label .. " -> " .. enc .. ": " .. tostring(eerr)) + local back, berr = decode(out) + t:check(back, label .. " -> " .. enc .. ": decode: " .. tostring(berr)) + t:eq(back.meta.source.encoding, enc, label .. " -> " .. enc .. ": encoding") + local cc = table.clone(c) + if c.faces > 0 and not c.allTri then + -- written as triangles: the face data goes through faceOfTriangle, one row per triangle + cc.faces, cc.allTri, cc.corners_crc = c.tris, true, c.tri_crc + cc.faceAttributes = {} + local bp = back.meshes[1].primitives[1] + local fa = bp.extras and bp.extras.faceAttributes + for name in c.faceAttributes do + if not c.faceAttributes[name].list then + t:check(fa and fa[name] and fa[name].count == c.tris, label .. ": face attribute per triangle") + end + end + end + verify(back, cc, label .. " -> " .. enc) + -- polygons in, polygons out + local pout = Ply.encode(poly, { format = enc }) :: buffer + local pback = decode(pout, { triangulate = false }) + verify(decode(pout), c, label .. " -> " .. enc .. " (polygons)") + local bp = pback.meshes[1].primitives[1] + t:eq(bp.mode, pp.mode, label .. ": polygons round trip mode") + if pp.indices then + t:check(buffer.tostring(bp.indices.data) == buffer.tostring(pp.indices.data), label .. ": polygons round trip indices") + end + if pp.faces then + t:check(buffer.tostring(bp.faces.data) == buffer.tostring(pp.faces.data), label .. ": polygons round trip sizes") + end + -- binary output of a binary input with the same byte order is the same file, header included + if enc == c.encoding and enc ~= "ascii" and string.sub(label, 1, 6) ~= "assimp" then + t:check(buffer.tostring(pout) == c.data, label .. ": byte-exact re-encode") + end + end +end +t:note("%d files match plyfile and round-trip in 3 encodings", #Fx.cases) + +for _, v in Fx.ours do + t:check(v.ok, "plyfile / assimp read our " .. v.name .. ": " .. v.detail) +end +t:note("%d encodings read back by plyfile and assimp", #Fx.ours) + +-- the encoder scenes: decode(encode()) against the properties computed by the generator +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local attrs = {} + for name, a in p.attrs do + attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count) + end + local prim: any = { attributes = attrs, mode = p.mode } + if p.indices then + prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4) + end + table.insert(prims, prim) + end + scene.meshes[i] = { primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end +local ATTR_OF: { [string]: { string | number } } = { + x = { "POSITION", 0 }, + y = { "POSITION", 1 }, + z = { "POSITION", 2 }, + nx = { "NORMAL", 0 }, + ny = { "NORMAL", 1 }, + nz = { "NORMAL", 2 }, + red = { "COLOR_0", 0 }, + green = { "COLOR_0", 1 }, + blue = { "COLOR_0", 2 }, + alpha = { "COLOR_0", 3 }, + s = { "TEXCOORD_0", 0 }, + t = { "TEXCOORD_0", 1 }, +} +local READ: { [string]: (buffer, number) -> number } = { [" 0 then + -- trimesh keeps ASCII coordinates as doubles: compare with them rounded to f32 + local function f32(x: number): number + local sb = buffer.create(4) + buffer.writef32(sb, 0, x) + return buffer.readf32(sb, 0) + end + for a = 1, 3 do + t:check(lo[a] == f32(c.bounds[a]) and hi[a] == f32(c.bounds[a + 3]), label .. ": bounds") + end + end + end + local p1 = scene.meshes[1].primitives[1] + if c.col_crc then + t:eq(scene.meta.source.colors, c.colors, label .. ": colour convention") + t:check(p1.attributes.COLOR_0 and p1.attributes.COLOR_0.type == "unorm8" and p1.attributes.COLOR_0.components == 4, label .. ": COLOR_0 unorm8 x4") + t:eq(Crc32.of(p1.attributes.COLOR_0.data), c.col_crc, label .. ": COLOR_0 crc") + else + t:check(p1.attributes.COLOR_0 == nil, label .. ": no colours") + end + if c.defaultColor then + local d = scene.meta.source.defaultColor + t:check(d and d[1] == c.defaultColor[1] and d[2] == c.defaultColor[2] and d[3] == c.defaultColor[3] and d[4] == c.defaultColor[4], label .. ": magics default colour") + t:check(scene.meta.source.material and scene.meta.source.material.specular[1] == 4, label .. ": magics material") + end + if c.attr_crc then + local fa = p1.extras and p1.extras.faceAttributes and p1.extras.faceAttributes.attribute + t:check(fa and fa.type == "u16" and fa.count == c.facets, label .. ": raw attribute words") + t:eq(Crc32.of(fa.data), c.attr_crc, label .. ": attribute words crc") + end + if c.solids then + local prims = scene.meshes[1].primitives + t:eq(#prims, #c.solids, label .. ": one primitive per solid") + for i, name in c.solids do + t:eq(prims[i].extras.solid, name, label .. ": solid name") + t:eq(prims[i].attributes.POSITION.count, c.solidFacets[i] * 3, label .. ": solid facets") + end + end + -- inside a bigger buffer (the Reader's range) + local big = buffer.create(#c.data + 11) + buffer.writestring(big, 5, c.data) + local s2 = Stl.decode(Bytes.reader(big, 5, #c.data)) + t:check(s2 and Crc32.of(concat(s2, "POSITION") :: buffer) == c.pos_crc, label .. ": decode from a sub-range") + if label ~= "bin-trailing.stl" then -- no magic, and the size does not match: not recognisable + t:check(Stl.sniff(Bytes.reader(buffer.fromstring(c.data))) >= 0.5, label .. ": sniff") + end + -- re-encode (binary with the file's normals, and ASCII): the same triangles and normals + for _, ascii in { false, true } do + local opts: any = { ascii = ascii, normals = "attribute", colors = if c.col_crc then c.colors else nil } + if c.defaultColor then + opts.defaultColor = c.defaultColor + end + local out, eerr = Stl.encode(scene, opts) + t:check(out, label .. ": encode: " .. tostring(eerr)) + local back = decode(out) + t:check(back, label .. ": decode our output") + t:check(buffer.tostring(concat(back, "POSITION") :: buffer) == buffer.tostring(pos), label .. ": re-encoded POSITION (ascii " .. tostring(ascii) .. ")") + t:check(buffer.tostring(concat(back, "NORMAL") :: buffer) == buffer.tostring(concat(scene, "NORMAL") :: buffer), label .. ": re-encoded NORMAL") + if c.col_crc and not ascii then + t:eq(Crc32.of(back.meshes[1].primitives[1].attributes.COLOR_0.data), c.col_crc, label .. ": re-encoded colours") + end + if c.attr_crc and not ascii then + t:eq(Crc32.of(back.meshes[1].primitives[1].extras.faceAttributes.attribute.data), c.attr_crc, label .. ": re-encoded attribute words") + end + if c.solids and ascii then + t:eq(back.meshes[1].primitives[1].extras.solid, c.solids[1], label .. ": solid name round trip") + end + end +end +t:note("%d files match trimesh / the generator", #Fx.cases) + +-- 3. the reference tools read our output +for _, v in Fx.ours do + t:check(v.ok, "trimesh / assimp read our " .. v.name .. ": " .. v.detail) +end +t:note("%d encodings read back by trimesh and assimp", #Fx.ours) + +-- round trips of the encoder scenes: world-space soup as the generator computed it, colour words, idempotence +local function acc(s: string, ty: string, comps: number, count: number): Types.Accessor + return Types.Scene.accessor(buffer.fromstring(s), ty, comps, count) +end +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local prim: any = { attributes = { POSITION = acc(p.pos, p.posType or "f32", 3, p.count) }, mode = p.mode } + if p.indices then + prim.indices = acc(p.indices, "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = acc(p.faces, "u32", 1, #p.faces // 4) + end + if p.color then + prim.attributes.COLOR_0 = acc(p.color, "unorm8", 4, p.count) + end + table.insert(prims, prim) + end + scene.meshes[i] = { name = m.name, primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { name = n.name, mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end +local OPTS: { [string]: any } = { binary = {}, ascii = { ascii = true }, viscam = { colors = "viscam" }, magics = { colors = "magics" } } +for _, spec in Scenes do + local scene = build(spec) + local want = buffer.fromstring(spec.expect) + local nf = buffer.len(want) // 36 + for _, e in spec.encodings do + local label = spec.name .. "/" .. e + local out, err = Stl.encode(scene, OPTS[e]) + t:check(out, label .. ": encode: " .. tostring(err)) + local back, berr = decode(out) + t:check(back, label .. ": decode: " .. tostring(berr)) + local got = concat(back, "POSITION") :: buffer + t:eq(buffer.len(got), nf * 36, label .. ": facets") + local worst = 0 + for i = 0, nf * 9 - 1 do + worst = math.max(worst, math.abs(buffer.readf32(got, i * 4) - buffer.readf32(want, i * 4))) + end + t:check(if spec.exact then worst == 0 else worst < 1e-4, string.format("%s: positions off by %g", label, worst)) + -- facet normals: unit length, right-hand rule + local nrm = concat(back, "NORMAL") :: buffer + for f = 0, nf - 1 do + local o = f * 36 + local n = { buffer.readf32(nrm, o), buffer.readf32(nrm, o + 4), buffer.readf32(nrm, o + 8) } + local len = math.sqrt(n[1] ^ 2 + n[2] ^ 2 + n[3] ^ 2) + t:check(math.abs(len - 1) < 1e-5, label .. ": unit normal") + local p = {} + for k = 0, 8 do + p[k + 1] = buffer.readf32(got, o + k * 4) + end + local cx = (p[5] - p[2]) * (p[9] - p[3]) - (p[6] - p[3]) * (p[8] - p[2]) + local cy = (p[6] - p[3]) * (p[7] - p[1]) - (p[4] - p[1]) * (p[9] - p[3]) + local cz = (p[4] - p[1]) * (p[8] - p[2]) - (p[5] - p[2]) * (p[7] - p[1]) + t:check(cx * n[1] + cy * n[2] + cz * n[3] > 0, label .. ": normal follows the winding") + end + if e == "viscam" or e == "magics" then + local words = if e == "viscam" then spec.viscamWords else spec.magicsWords + for f = 0, nf - 1 do + t:eq(buffer.readu16(out :: buffer, 84 + f * 50 + 48), words[f + 1], label .. ": colour word") + end + t:eq(back.meta.source.colors, e, label .. ": detected convention") + -- the colours are on 5-bit steps: decode(encode()) gives the first vertex colour of each facet back + local col = back.meshes[1].primitives[1].attributes.COLOR_0.data + local src = scene.meshes[1].primitives[1] + local idx = src.indices :: Types.Accessor + for f = 0, nf - 1 do + local a = buffer.readu32(idx.data, f * 12) + t:eq(buffer.readu32(col, f * 12), buffer.readu32(src.attributes.COLOR_0.data, a * 4), label .. ": facet colour") + end + end + -- idempotent: encoding the decoded soup again gives the same file + local again = Stl.encode(back, { ascii = OPTS[e].ascii, colors = OPTS[e].colors, normals = "attribute" }) :: buffer + t:check(buffer.tostring(again) == buffer.tostring(out :: buffer), label .. ": re-encode is identical") + end +end +-- options: header, name, computed vs attribute normals +do + local scene = build(Scenes[1]) + local out = Stl.encode(scene, { header = "my header", ascii = false }) :: buffer + t:eq(buffer.readstring(out, 0, 9), "my header", "header option") + t:eq(decode(out).meta.source.header, "my header", "meta.source.header") + local a = buffer.tostring(Stl.encode(scene, { ascii = true, name = "part 7" }) :: buffer) + t:check(string.sub(a, 1, 12) == "solid part 7" and string.find(a, "endsolid part 7", 1, true) ~= nil, "name option") + local m = Stl.encode(scene, { colors = "magics", defaultColor = { 1, 2, 3, 4 } }) :: buffer + local d = decode(m).meta.source.defaultColor + t:check(d[1] == 1 and d[2] == 2 and d[3] == 3 and d[4] == 4, "defaultColor option") + -- points / lines only: an empty STL + local pts = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 4) }, mode = "points" }) + local e0 = Stl.encode(pts) :: buffer + t:eq(buffer.len(e0), 84, "points only: no facets") + -- a scene without nodes uses its meshes + local bare = Types.Scene.new() + bare.meshes[1] = scene.meshes[1] + t:eq(buffer.len(Stl.encode(bare) :: buffer), 84 + 50 * 60, "a scene without nodes") +end + +-- 4. error codes +do + local cube = Fx.cases[1].data + local _, e1 = decode(string.sub(cube, 1, 84 + 50 * 3 + 7)) + t:check(e1 and e1.code == Err.TRUNCATED, "cut binary: " .. tostring(e1)) + local _, e2 = decode("solid x\nfacet normal 1 2 zz\n") + t:check(e2 and e2.code == Err.CORRUPT, "bad number: " .. tostring(e2)) + local _, e3 = decode("solid x\nfacet normal 1 2 3\nouter loop\nvertex 1 2 3\n") + t:check(e3 and e3.code == Err.TRUNCATED, "cut ascii: " .. tostring(e3)) + local _, e4 = decode("solid x\nfacet normal 0 0 1\nouter loop\nvertex 1 2 3\nvertex 1 2 3\nendloop\nendfacet\nendsolid\n") + t:check(e4 and e4.code == Err.CORRUPT, "two-vertex facet: " .. tostring(e4)) + local _, e5 = decode("hello") + t:check(e5 and e5.code == Err.TRUNCATED, "tiny junk: " .. tostring(e5)) + local _, e6 = decode(cube, { maxFaces = 10 }) + t:check(e6 and e6.code == Err.LIMIT, "maxFaces: " .. tostring(e6)) + local _, e7 = decode(cube, { colors = "rainbow" }) + t:check(e7 and e7.code == Err.ARG, "bad colors option: " .. tostring(e7)) + local _, e8 = decode("solid x\nbanana\n") + t:check(e8 and e8.code == Err.CORRUPT, "bad keyword: " .. tostring(e8)) + local hdr = buffer.create(84) + buffer.writeu32(hdr, 80, 1000000) + local _, e9 = Stl.decode(Bytes.reader(hdr)) + t:check(e9 and e9.code == Err.TRUNCATED, "huge count: " .. tostring(e9)) + local _, a1 = Stl.encode({} :: any) + t:check(a1 and a1.code == Err.ARG, "encode a non-scene: " .. tostring(a1)) + local scene = build(Scenes[1]) + local _, a2 = Stl.encode(scene, { colors = "rgb" } :: any) + t:check(a2 and a2.code == Err.ARG, "bad colors: " .. tostring(a2)) + local bad = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 3) }, indices = Types.Scene.accessor(nil, "u32", 1, 3), mode = "triangles" }) + buffer.writeu32((bad.meshes[1].primitives[1].indices :: Types.Accessor).data, 4, 7) + local _, a3 = Stl.encode(bad) + t:check(a3 and a3.code == Err.ARG, "index out of range: " .. tostring(a3)) + local nan = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 3) }, mode = "triangles" }) + buffer.writef32(nan.meshes[1].primitives[1].attributes.POSITION.data, 0, 0 / 0) + local _, a4 = Stl.encode(nan, { ascii = true }) + t:check(a4 and a4.code == Err.ARG, "NaN in ASCII: " .. tostring(a4)) + t:check(Stl.encode(nan) ~= nil, "NaN in binary is fine") + local cyc = build(Scenes[3]) + cyc.nodes[2].children = { 1 } + local _, a5 = Stl.encode(cyc) + t:check(a5 and a5.code == Err.ARG, "cyclic nodes: " .. tostring(a5)) + t:eq(Stl.sniff(Bytes.reader(buffer.fromstring("ply\nformat ascii 1.0\n"))), 0, "sniff a PLY") +end + +-- 5. fuzz +do + local samples = {} + for i, c in Fx.cases do + if #c.data < 20000 or i % 3 == 0 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Stl.decode(Bytes.reader(b)) + end, samples, { mutations = 12 }) + t:fuzz("decode re-encode", function(b: buffer) + local s = Stl.decode(Bytes.reader(b)) + if s then + return Stl.encode(s, { ascii = true }) + end + return nil + end, samples, { mutations = 4, garbage = 20 }) +end + +-- throughput: a synthetic binary STL of 200k facets +do + local n = 200000 + local b = buffer.create(84 + 50 * n) + buffer.writeu32(b, 80, n) + for i = 0, n - 1 do + for k = 0, 11 do + buffer.writef32(b, 84 + i * 50 + k * 4, (i * 12 + k) % 1000 * 0.25) + end + end + local t0 = os.clock() + local s = Stl.decode(Bytes.reader(b)) + local dt = os.clock() - t0 + t:check(s and s.meshes[1].primitives[1].attributes.POSITION.count == n * 3, "bench decode") + t:note("binary decode: %d facets (%.1f MB) in %.3f s, %.0f MB/s", n, buffer.len(b) / 1e6, dt, buffer.len(b) / 1e6 / math.max(dt, 1e-6)) +end + +t:done() diff --git a/tests/model/vox.luau b/tests/model/vox.luau new file mode 100644 index 0000000..77d0ec2 --- /dev/null +++ b/tests/model/vox.luau @@ -0,0 +1,289 @@ +-- model/vox tests: MagicaVoxel files (ephtracy samples, opengametools scene files saved by MagicaVoxel 0.99.x) and +-- synthetic files with every chunk type, against an independent reader (tools/fixtures/vox.py): grids (CRC), palette, +-- the default palette (parsed from the spec text), scene graph world transforms (rotations, mirrors, nesting), layers, +-- materials, notes, cameras, render objects; greedy meshes (MeshOps) against the exposed face count; round trips +-- through the writer; error codes; the fuzz no-throw pass. Fixtures: tools/fixtures/vox.py. +local T = require("@tests/T") +local Vox = require("@formats/model/vox") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/vox_cases") +local DefaultPalette = require("@tests/gen/vox_default_palette") + +local t = T.suite("vox") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Vox.decode(Bytes.reader(b), opts) +end + +-- the contract +t:eq(Vox.name, "vox", "name") +t:eq(Vox.category, "model", "category") +t:check(Vox.extensions[1] == "vox" and Vox.caps.decode and Vox.caps.encode, "contract") + +-- the default palette = the spec's array +do + t:eq(#Vox.DEFAULT_PALETTE, 255, "default palette size") + local same = true + for i = 1, 255 do + for k = 1, 4 do + if Vox.DEFAULT_PALETTE[i][k] ~= DefaultPalette[i][k] then + same = false + end + end + end + t:check(same, "default palette equals the spec's") +end + +local function paletteCrc(pal: { { number } }): number + local b = buffer.create(255 * 4) + for i = 1, 255 do + for k = 1, 4 do + buffer.writeu8(b, (i - 1) * 4 + k - 1, pal[i][k]) + end + end + return Crc32.of(b) +end + +local function countKeys(tbl: any): number + local n = 0 + for _ in tbl or {} do + n += 1 + end + return n +end + +-- shape nodes depth first with world matrices (column-major 4x4) +local function shapes(scene: any): { any } + local out = {} + local function walk(i: number, parent: { number }) + local node = scene.nodes[i] + local world = Types.Scene.mul(parent, Types.Scene.nodeMatrix(node)) + if node.voxels then + table.insert(out, { name = node.name or "", model = node.voxels, world = world }) + end + for _, c in node.children do + walk(c, world) + end + end + for _, r in scene.roots do + walk(r, Types.Scene.IDENTITY) + end + return out +end + +local function checkScene(scene: any, c: any, label: string) + t:eq(scene.kind, "scene", label .. ": a Scene") + t:eq(scene.meta.up, "z", label .. ": z up") + t:eq(#scene.voxels, #c.models, label .. ": models") + for i, m in c.models do + local v = scene.voxels[i] + t:check(v.size[1] == m.size[1] and v.size[2] == m.size[2] and v.size[3] == m.size[3], label .. ": model " .. i .. " size") + t:eq(Crc32.of(v.data), m.crc, label .. ": model " .. i .. " grid") + end + t:eq(paletteCrc(scene.voxels[1].palette), c.paletteCrc, label .. ": palette") + local vm = scene.meta.vox + t:eq(#(vm.layers or {}), c.layers, label .. ": layers") + t:eq(countKeys(scene.voxels[1].materials), c.materials, label .. ": materials") + t:eq(#(vm.notes or {}), c.notes, label .. ": notes") + t:eq(#(vm.cameras or {}), c.cameras, label .. ": cameras") + t:eq(#(vm.renderObjects or {}), c.robjs, label .. ": render objects") + local glass = 0 + for _, m in scene.voxels[1].materials or {} do + if m.type == "glass" then + glass += 1 + end + end + t:eq(glass, c.glassMaterials, label .. ": glass materials") + if #c.shapes > 0 then + local got = shapes(scene) + t:eq(#got, #c.shapes, label .. ": shape nodes") + for k, want in c.shapes do + local g = got[k] + t:eq(g.name, want.name, label .. ": shape " .. k .. " name") + t:eq(g.model, want.model, label .. ": shape " .. k .. " model") + local ok = true + for row = 0, 2 do + for col = 0, 3 do + local w = want.world[row * 4 + col + 1] + local v = g.world[col * 4 + row + 1] + if math.abs(w - v) > 1e-6 then + ok = false + end + end + end + t:check(ok, label .. ": shape " .. k .. " (" .. want.name .. ") world transform") + end + end +end + +-- area and winding of a greedy mesh +local function meshFacts(prim: any): (number, boolean, number) + local pos, nrm = prim.attributes.POSITION.data, prim.attributes.NORMAL.data + local ind = prim.indices.data + local area, wound = 0, true + for tri = 0, prim.indices.count // 3 - 1 do + local a, b, c = buffer.readu32(ind, tri * 12), buffer.readu32(ind, tri * 12 + 4), buffer.readu32(ind, tri * 12 + 8) + local function p(i: number, k: number): number + return buffer.readf32(pos, i * 12 + k * 4) + end + local e1 = { p(b, 0) - p(a, 0), p(b, 1) - p(a, 1), p(b, 2) - p(a, 2) } + local e2 = { p(c, 0) - p(a, 0), p(c, 1) - p(a, 1), p(c, 2) - p(a, 2) } + local nx, ny, nz = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(nx * nx + ny * ny + nz * nz) / 2 + local dot = nx * buffer.readf32(nrm, a * 12) + ny * buffer.readf32(nrm, a * 12 + 4) + nz * buffer.readf32(nrm, a * 12 + 8) + if dot <= 0 then + wound = false + end + end + return area, wound, prim.indices.count // 3 +end + +local totalQuads, totalFaces = 0, 0 +for _, c in Cases do + local label = c.name + local scene, err = decode(c.data) + t:check(scene, label .. ": decode: " .. tostring(err)) + checkScene(scene, c, label) + t:eq(scene.meta.source.version, c.version, label .. ": version") + -- decodeVoxels, and from a sub-range of a bigger buffer + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local grids = Vox.decodeVoxels(Bytes.reader(big, 5, #c.data)) + t:check(grids and #grids == #c.models and Crc32.of(grids[1].data) == c.models[1].crc, label .. ": decodeVoxels from a sub-range") + -- greedy meshing: the area is the number of exposed unit faces, every triangle faces its normal + for i, m in c.models do + local prim, perr = MeshOps.voxelsToPrimitive(scene.voxels[i], { pivot = "corner" }) + t:check(prim, label .. ": mesh: " .. tostring(perr)) + local area, wound, tris = meshFacts(prim) + t:eq(area, m.faces, label .. ": model " .. i .. " greedy mesh area = exposed faces") + t:check(wound, label .. ": model " .. i .. " winding matches the normals") + t:check(tris <= m.faces * 2, label .. ": model " .. i .. " no more triangles than faces") + totalQuads += tris // 2 + totalFaces += m.faces + end + -- round trip through the writer + local out, eerr = Vox.encode(scene) + t:check(out, label .. ": encode: " .. tostring(eerr)) + local back, berr = Vox.decode(Bytes.reader(out :: buffer)) + t:check(back, label .. ": decode our file: " .. tostring(berr)) + checkScene(back, c, label .. " (round trip)") + t:eq(back.meta.source.version, 200, label .. ": written as version 200") + local out2 = Vox.encode(back) :: buffer + t:check(buffer.tostring(out2) == buffer.tostring(out :: buffer), label .. ": writing is stable") + if scene.meta.vox.info then + t:check(back.meta.vox.info and back.meta.vox.info._anim_range == scene.meta.vox.info._anim_range, label .. ": META") + end +end +t:note("%d files: grids, palettes, scene graphs and round trips match; greedy: %d quads for %d faces", #Cases, totalQuads, totalFaces) + +-- the synthetic scene in detail: names, hidden, layers, animation frames, materials, notes, IMAP, unknown chunks +do + local c + for _, x in Cases do + if x.name == "syn-scene" then + c = x + end + end + local scene = decode(c.data) + local byName = {} + for _, n in scene.nodes do + if n.name then + byName[n.name] = n + end + end + t:check(byName.group and byName.group.extras.vox.attributes._hidden == "1" and byName.group.extras.vox.layer == 1, "hidden group on layer 1") + t:check(byName.b and byName.b.matrix ~= nil, "a mirrored node keeps a matrix") + t:check(byName.a and byName.a.matrix == nil and byName.a.rotation == nil and byName.a.translation[3] == 3, "identity rotation: translation only") + t:check(byName.anim and #byName.anim.extras.vox.frames == 2 and #byName.anim.extras.vox.shape.models == 2, "animation frames and shape models") + local mats = scene.voxels[1].materials + t:check(mats[1].type == "glass" and mats[2].type == "emit" and mats[1].rough == 0.25 and mats[1].ior == 1.5 and mats[200].type == "emit", "materials") + t:check(scene.meta.vox.notes[2] == "second" and scene.meta.vox.indexMap[256] == 255, "notes, IMAP") + t:check(scene.meta.vox.layers[2].name == "one" and scene.meta.vox.layers[2].hidden, "layers") + t:check(scene.meta.vox.cameras[1].attributes._fov == "45", "rCAM") + t:check(scene.meta.vox.chunks and scene.meta.vox.chunks[1].id == "ZZZZ", "unknown chunk kept") + local back = Vox.decode(Bytes.reader(Vox.encode(scene) :: buffer)) :: any + local bn = {} + for _, n in back.nodes do + if n.name then + bn[n.name] = n + end + end + t:check(bn.anim and #bn.anim.extras.vox.frames == 2 and bn.anim.extras.vox.frames[2]._t == "4 4 4", "frames round trip") + t:check(back.meta.vox.chunks and buffer.tostring(back.meta.vox.chunks[1].content) == "unknown payload", "unknown chunk round trip") + t:check(back.voxels[1].materials[200].flux == 2, "material round trip") + -- meshVoxels: every shape node gets the mesh of its grid + MeshOps.meshVoxels(back) + local meshed = 0 + for _, n in back.nodes do + if n.voxels then + t:check(n.mesh ~= nil and back.meshes[n.mesh].primitives[1].attributes.COLOR_0 ~= nil, "meshVoxels sets node.mesh") + meshed += 1 + end + end + t:check(meshed == 4 and #back.meshes == 4, "four shapes meshed") + local lo, hi = MeshOps.bounds(back) + t:check(lo and hi and hi[1] > lo[1], "scene bounds of the meshed shapes") +end + +-- a Voxels grid alone; the centred pivot; sRGB colours +do + local v = Types.Voxels.new(3, 4, 5, Vox.DEFAULT_PALETTE) + Types.Voxels.set(v, 0, 0, 0, 1) + Types.Voxels.set(v, 2, 3, 4, 200) + local out, err = Vox.encode(v) + t:check(out, "encode a Voxels grid: " .. tostring(err)) + local back = Vox.decode(Bytes.reader(out :: buffer)) :: any + t:check(back and #back.voxels == 1 and Types.Voxels.get(back.voxels[1], 2, 3, 4) == 200 and Types.Voxels.get(back.voxels[1], 1, 1, 1) == 0, "Voxels round trip") + local prim = MeshOps.voxelsToPrimitive(v, { colors = "srgb", indexAttribute = true }) :: any + local lo, hi = MeshOps.bounds(prim) + t:check(lo and hi and lo[1] == -1 and lo[2] == -2 and lo[3] == -2 and hi[1] == 2 and hi[2] == 2 and hi[3] == 3, "centre pivot") + t:check(prim.attributes.COLOR_0.type == "unorm8" and prim.attributes._PALETTE_INDEX.type == "u8", "srgb colours, index attribute") + t:eq(prim.indices.count, 72, "two separate cubes: 12 quads") +end + +-- errors +do + local _, e = decode("nope") + t:check(e and e.code == Err.CORRUPT, "junk: " .. tostring(e)) + local c = Cases[1] + local _, e2 = decode(c.data, { maxCells = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "maxCells: " .. tostring(e2)) + local _, e3 = decode(string.sub(c.data, 1, 30)) + t:check(e3 ~= nil, "truncated: " .. tostring(e3)) + local _, e4 = Vox.encode({} :: any) + t:check(e4 and e4.code == Err.ARG, "encode junk") + local big = Types.Voxels.new(300, 1, 1) + local _, e5 = Vox.encode(big) + t:check(e5 and e5.code == Err.ARG, "over 256 cells: " .. tostring(e5)) + local s = Vox.decode(Bytes.reader(buffer.fromstring(Cases[1].data))) :: any + s.nodes[s.roots[1]].rotation = { 0, 0, math.sin(0.3), math.cos(0.3) } + local _, e6 = Vox.encode(s) + t:check(e6 and e6.code == Err.ARG, "a 34 degree rotation: " .. tostring(e6)) + local _, e7 = MeshOps.voxelsToPrimitive({} :: any) + t:check(e7 and e7.code == Err.ARG, "voxelsToPrimitive of junk") +end + +-- fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 100000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = Vox.decode(Bytes.reader(b)) + if s then + MeshOps.meshVoxels(s) + Vox.encode(s) + end + return s + end, samples, { mutations = 30, keepHeader = 8 }) +end + +t:done() diff --git a/tests/ops/meshops.luau b/tests/ops/meshops.luau new file mode 100644 index 0000000..9b5e153 --- /dev/null +++ b/tests/ops/meshops.luau @@ -0,0 +1,355 @@ +-- ops/MeshOps tests: triangulate (strips, fans, convex / concave / degenerate n-gons), transform (normals by the inverse +-- transpose, mirrors flip the winding), computeNormals (smooth sphere normals = the radial direction, flat cube normals), +-- computeTangents (orthogonal, unit, handedness), weld / unweld, bounds, merge (instances baked, mixed attributes), +-- scale / setUnit / setUp, greedy voxel meshing (exposed face area, winding, the checkerboard worst case), errors. +-- Analytic references (closed forms); the format tests check merge / bounds against assimp and trimesh. +local T = require("@tests/T") +local MeshOps = require("@formats/ops/MeshOps") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local F = require("@formats") + +local t = T.suite("meshops") +local S = Types.Scene + +local function f32(list: { number }, comps: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, #list // comps) + for i, v in list do + buffer.writef32(a.data, (i - 1) * 4, v) + end + return a +end +local function u32(list: { number }): Types.Accessor + local a = S.accessor(nil, "u32", 1, #list) + for i, v in list do + buffer.writeu32(a.data, (i - 1) * 4, v) + end + return a +end +local function idx(acc: Types.Accessor): { number } + local out = {} + for i = 0, acc.count - 1 do + out[i + 1] = buffer.readu32(acc.data, i * 4) + end + return out +end +local function get(acc: Types.Accessor, i: number, c: number): number + return (S.reader(acc) :: any)(i, c) +end +local function near(a: number, b: number, eps: number?): boolean + return math.abs(a - b) <= (eps or 1e-5) +end +local function area(prim: any): number + local pos, ind = prim.attributes.POSITION, prim.indices + local total = 0 + for tri = 0, ind.count // 3 - 1 do + local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8) + local e1 = { get(pos, b, 0) - get(pos, a, 0), get(pos, b, 1) - get(pos, a, 1), get(pos, b, 2) - get(pos, a, 2) } + local e2 = { get(pos, c, 0) - get(pos, a, 0), get(pos, c, 1) - get(pos, a, 1), get(pos, c, 2) - get(pos, a, 2) } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + total += math.sqrt(x * x + y * y + z * z) / 2 + end + return total +end + +-- a unit cube as 6 quads (polygons), 24 corners +local function cube(): Types.Primitive + local P = {} + local faces = { + { { 0, 0, 0 }, { 0, 1, 0 }, { 1, 1, 0 }, { 1, 0, 0 } }, + { { 0, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 0, 1, 1 } }, + { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 0, 1 }, { 0, 0, 1 } }, + { { 0, 1, 0 }, { 0, 1, 1 }, { 1, 1, 1 }, { 1, 1, 0 } }, + { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 1, 1 }, { 0, 1, 0 } }, + { { 1, 0, 0 }, { 1, 1, 0 }, { 1, 1, 1 }, { 1, 0, 1 } }, + } + local ind, sizes = {}, {} + for _, f in faces do + for _, v in f do + table.insert(P, v[1]) + table.insert(P, v[2]) + table.insert(P, v[3]) + table.insert(ind, #ind) + end + table.insert(sizes, 4) + end + return { attributes = { POSITION = f32(P, 3) }, indices = u32(ind), faces = u32(sizes), mode = "polygons" } +end + +-- triangulate +do + local c = cube() + local tri = MeshOps.triangulate(c) :: any + t:check(tri.mode == "triangles" and tri.indices.count == 36, "cube quads -> 12 triangles") + t:check(near(area(tri), 6), "cube area 6") + -- every triangle faces outward (the cube is centred at 0.5) + local nm = MeshOps.computeNormals(MeshOps.unweld(tri)) :: any + local outward = true + for v = 0, nm.attributes.POSITION.count - 1 do + local d = 0 + for k = 0, 2 do + d += (get(nm.attributes.POSITION, v, k) - 0.5) * get(nm.attributes.NORMAL, v, k) + end + if d <= 0 then + outward = false + end + end + t:check(outward, "triangulated winding keeps the faces outward") + -- strips and fans + local P = f32({ 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 2, 0, 1, 2, 0 }, 3) + local strip = MeshOps.triangulate({ attributes = { POSITION = P }, mode = "triangle_strip" }) :: any + t:check(table.concat(idx(strip.indices), ",") == "0,1,2,2,1,3,2,3,4,4,3,5", "strip unrolled with alternating winding") + t:check(near(area(strip), 2), "strip area") + local fan = MeshOps.triangulate({ attributes = { POSITION = P }, indices = u32({ 0, 1, 3, 2 }), mode = "triangle_fan" }) :: any + t:check(table.concat(idx(fan.indices), ",") == "0,1,3,0,3,2", "fan unrolled") + -- a concave n-gon (a star) by ear clipping vs the shoelace area + local star, sidx = {}, {} + local shoelace = 0 + for k = 0, 9 do + local r = if k % 2 == 0 then 2 else 0.8 + local a = math.pi * 2 * k / 10 + table.insert(star, r * math.cos(a)) + table.insert(star, 0) + table.insert(star, -r * math.sin(a)) + table.insert(sidx, k) + end + for k = 0, 9 do + local x1, z1 = star[k * 3 + 1], star[k * 3 + 3] + local x2, z2 = star[((k + 1) % 10) * 3 + 1], star[((k + 1) % 10) * 3 + 3] + shoelace += x1 * z2 - x2 * z1 + end + local sp = { attributes = { POSITION = f32(star, 3) }, indices = u32(sidx), faces = u32({ 10 }), mode = "polygons" } + local ear = MeshOps.triangulate(sp) :: any + t:check(ear.indices.count == 24 and near(area(ear), math.abs(shoelace) / 2, 1e-4), "star: ear clipping area " .. area(ear) .. " = " .. math.abs(shoelace) / 2) + t:check(area(MeshOps.triangulate(sp, { method = "fan" }) :: any) ~= area(ear), "the fan gets a concave polygon wrong") + -- degenerate polygons: collinear corners, faces of 1 or 2 corners are dropped + local deg = { attributes = { POSITION = f32({ 0, 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0 }, 3) }, indices = u32({ 0, 1, 2, 3, 0, 1 }), faces = u32({ 4, 2 }), mode = "polygons" } + local d = MeshOps.triangulate(deg) :: any + t:check(d and d.indices.count == 6 and near(area(d), 0), "collinear quad: two zero-area triangles, the 2-gon dropped") + local lines = { attributes = { POSITION = P }, mode = "lines" } + t:check(MeshOps.triangulate(lines) == lines, "lines come back unchanged") +end + +-- transform +do + local tri = MeshOps.triangulate(cube()) :: any + MeshOps.computeNormals(MeshOps.unweld(tri)) + local soup = MeshOps.computeNormals(MeshOps.unweld(tri)) :: any + -- non-uniform scale: normals by the inverse transpose stay perpendicular to the faces + local m = { 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 10, 20, 30, 1 } + MeshOps.transform(soup, m) + local lo, hi = MeshOps.bounds(soup) + t:check(lo and near(lo[1], 10) and near(hi[1], 12) and near(lo[2], 20) and near(hi[2], 21) and near(lo[3], 30) and near(hi[3], 30.5), "transformed bounds") + local ok = true + for tri0 = 0, soup.attributes.POSITION.count // 3 - 1 do + local a = tri0 * 3 + for e = 1, 2 do + local d = 0 + for k = 0, 2 do + d += (get(soup.attributes.POSITION, a + e, k) - get(soup.attributes.POSITION, a, k)) * get(soup.attributes.NORMAL, a, k) + end + if math.abs(d) > 1e-5 then + ok = false + end + end + end + t:check(ok, "normals stay perpendicular under non-uniform scale") + -- a mirror flips the winding: recomputed normals still agree with the transformed ones + local mir = MeshOps.computeNormals(MeshOps.unweld(MeshOps.triangulate(cube()) :: any)) :: any + local before = MeshOps.computeNormals(MeshOps.unweld(MeshOps.triangulate(cube()) :: any)) :: any + MeshOps.transform(mir, { -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }) + local saved = buffer.tostring(mir.attributes.NORMAL.data) + local re = MeshOps.computeNormals(MeshOps.unweld(mir)) :: any + local agree = true + for v = 0, re.attributes.NORMAL.count - 1 do + for k = 0, 2 do + if not near(get(re.attributes.NORMAL, v, k), buffer.readf32(buffer.fromstring(saved), (v * 3 + k) * 4), 1e-5) then + agree = false + end + end + end + t:check(agree and before ~= nil, "mirror: winding reversed (recomputed normals = transformed normals)") + local _, e = MeshOps.transform(mir, { 1, 2, 3 }) + t:check(e and e.code == Err.ARG, "transform: a bad matrix") +end + +-- normals, tangents on a UV sphere +do + local rings, segs = 16, 32 + local P, UV, ind = {}, {}, {} + for i = 0, rings do + local th = math.pi * i / rings + for j = 0, segs do + local ph = 2 * math.pi * j / segs + table.insert(P, math.sin(th) * math.cos(ph)) + table.insert(P, math.cos(th)) + table.insert(P, math.sin(th) * math.sin(ph)) + table.insert(UV, j / segs) + table.insert(UV, i / rings) + end + end + for i = 0, rings - 1 do + for j = 0, segs - 1 do + local a, b = i * (segs + 1) + j, i * (segs + 1) + j + 1 + local c, d = a + segs + 1, b + segs + 1 + for _, v in { a, b, c, b, d, c } do + table.insert(ind, v) + end + end + end + local sphere: any = { attributes = { POSITION = f32(P, 3), TEXCOORD_0 = f32(UV, 2) }, indices = u32(ind), mode = "triangles" } + MeshOps.computeNormals(sphere) + -- smooth normals of interior vertices (not on the seam / poles) point along the radius + local worst = 0 + for i = 1, rings - 1 do + for j = 1, segs - 1 do + local v = i * (segs + 1) + j + local dot = 0 + for k = 0, 2 do + dot += get(sphere.attributes.NORMAL, v, k) * get(sphere.attributes.POSITION, v, k) + end + worst = math.max(worst, 1 - dot) + end + end + t:check(worst < 1e-3, "sphere normals = radial directions (worst 1 - cos " .. worst .. ")") + t:check(get(sphere.attributes.NORMAL, (rings // 2) * (segs + 1) + 3, 1) < 1e-3, "outward, not inward") + MeshOps.computeTangents(sphere) + local tan = sphere.attributes.TANGENT + t:check(tan and tan.components == 4, "TANGENT vec4") + local ortho, unit, hand = 0, 0, true + for i = 1, rings - 1 do + for j = 1, segs - 1 do + local v = i * (segs + 1) + j + local d, l = 0, 0 + for k = 0, 2 do + d += get(tan, v, k) * get(sphere.attributes.NORMAL, v, k) + l += get(tan, v, k) ^ 2 + end + ortho = math.max(ortho, math.abs(d)) + unit = math.max(unit, math.abs(l - 1)) + if math.abs(get(tan, v, 3)) ~= 1 then + hand = false + end + -- u grows with phi: the tangent follows d/dphi = (-sin phi, 0, cos phi) + local ph = 2 * math.pi * j / segs + if get(tan, v, 0) * -math.sin(ph) + get(tan, v, 2) * math.cos(ph) < 0.99 then + hand = false + end + end + end + t:check(ortho < 1e-5 and unit < 1e-5 and hand, string.format("tangents orthogonal (%g), unit (%g), along +u", ortho, unit)) + local _, e = MeshOps.computeTangents({ attributes = { POSITION = f32(P, 3) }, indices = u32(ind), mode = "triangles" }) + t:check(e and e.code == Err.ARG, "computeTangents without uv") + -- flat normals on the cube: 36 corners, axis-aligned + local flat = MeshOps.computeNormals(MeshOps.triangulate(cube()) :: any, { flat = true }) :: any + t:check(flat.attributes.NORMAL.count == 36 and flat.indices == nil, "flat: unwelded corners") + local axis = true + for v = 0, 35 do + local s = math.abs(get(flat.attributes.NORMAL, v, 0)) + math.abs(get(flat.attributes.NORMAL, v, 1)) + math.abs(get(flat.attributes.NORMAL, v, 2)) + if not near(s, 1) then + axis = false + end + end + t:check(axis, "flat cube normals are axis-aligned") +end + +-- weld +do + local soup = MeshOps.unweld(MeshOps.triangulate(cube()) :: any) :: any + t:eq(soup.attributes.POSITION.count, 36, "unwelded cube: 36 vertices") + local w = MeshOps.weld(soup) :: any + t:check(w.attributes.POSITION.count == 8 and w.indices.count == 36, "welded by position: 8") + t:check(near(area(w), 6), "weld keeps the surface") + local withN = MeshOps.weld(MeshOps.computeNormals(soup, { flat = true }) :: any) :: any + t:eq(withN.attributes.POSITION.count, 24, "welded with flat normals: 24") + -- an epsilon merges near-identical positions + local P = f32({ 0, 0, 0, 1, 0, 0, 0, 1, 0, 1e-7, 0, 0, 1, 1e-7, 0, 0, 1, 1e-7 }, 3) + local two = { attributes = { POSITION = P }, mode = "triangles" } + t:eq((MeshOps.weld(two) :: any).attributes.POSITION.count, 6, "exact: 6") + t:eq((MeshOps.weld(two, { epsilon = 1e-4 }) :: any).attributes.POSITION.count, 3, "epsilon: 3") + local positionsOnly = MeshOps.weld(withN, { positionsOnly = true }) :: any + t:eq(positionsOnly.attributes.POSITION.count, 8, "positionsOnly: 8") +end + +-- merge, bounds +do + local s = S.new() + local tri = MeshOps.triangulate(cube()) :: any + tri.attributes.COLOR_0 = S.accessor(nil, "unorm8", 4, tri.attributes.POSITION.count) + buffer.fill(tri.attributes.COLOR_0.data, 0, 255) + s.meshes[1] = { primitives = { tri } } + local other = { attributes = { POSITION = f32({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3), _CUSTOM = S.accessor(nil, "u16", 1, 3) }, mode = "triangles", material = 2 } + s.meshes[2] = { primitives = { other } } + s.nodes = { + { children = { 2, 3 } }, + { children = {}, mesh = 1, translation = { 10, 0, 0 } }, + { children = {}, mesh = 1, translation = { -10, 0, 0 }, scale = { 2, 2, 2 } }, + { children = {}, mesh = 2, rotation = { 0, 0, math.sqrt(0.5), math.sqrt(0.5) } }, + } + s.roots = { 1, 4 } + local m = MeshOps.merge(s) :: any + t:check(m.indices.count == 36 * 2 + 3, "two cube instances and a triangle") + t:check(near(area(m), 6 + 24 + 0.5), "instances baked (scale 2: area x4)") + t:check(m.attributes.COLOR_0 and m.attributes._CUSTOM and m.attributes.COLOR_0.type == "f32", "attributes unioned (f32)") + local white = get(m.attributes.COLOR_0, m.attributes.POSITION.count - 1, 0) + t:eq(white, 1, "missing colours are white") + local lo, hi = MeshOps.bounds(s) + t:check(lo and near(lo[1], -10) and near(hi[1], 11) and near(lo[2], 0) and near(hi[2], 2), "scene bounds in world space") + local byMat = MeshOps.merge(s, { byMaterial = true }) :: any + t:check(#byMat == 2 and byMat[1].material == nil and byMat[2].material == 2, "byMaterial") + local _, e = MeshOps.merge(5 :: any) + t:check(e and e.code == Err.ARG, "merge junk") +end + +-- units and up axis +do + local s = S.fromPrimitive(MeshOps.triangulate(cube()) :: any) + s.nodes[1].translation = { 1, 2, 3 } + s.meta.unit = 0.01 -- centimetres + MeshOps.setUnit(s, 1) + local lo, hi = MeshOps.bounds(s) + t:check(lo and near(lo[1], 0.01) and near(hi[1], 0.02) and near(lo[3], 0.03), "cm -> m") + t:eq(s.meta.unit, 1, "meta.unit updated") + s.meta.up = "z" + MeshOps.setUp(s, "y") + local lo2, hi2 = MeshOps.bounds(s) + -- z-up (x, y, z) -> y-up (x, z, -y) + t:check(lo2 and near(lo2[2], 0.03) and near(hi2[2], 0.04) and near(lo2[3], -0.03) and near(hi2[3], -0.02), "z-up -> y-up") + t:check(MeshOps.setUp(s, "x" :: any) == nil, "setUp: bad axis") +end + +-- greedy voxels +do + local v = Types.Voxels.new(4, 4, 4) + for x = 0, 3 do + for y = 0, 3 do + for z = 0, 3 do + Types.Voxels.set(v, x, y, z, 1) + end + end + end + local p = MeshOps.voxelsToPrimitive(v, { pivot = "corner" }) :: any + t:check(p.indices.count == 36 and near(area(p), 96), "a full 4x4x4 block: 6 quads, area 96") + Types.Voxels.set(v, 1, 1, 3, 2) + local p2 = MeshOps.voxelsToPrimitive(v, { pivot = "corner" }) :: any + t:check(near(area(p2), 96) and p2.indices.count > 36, "a different colour splits the top face, same area") + local scaled = MeshOps.voxelsToPrimitive(v, { scale = 0.5 }) :: any + local lo, hi = MeshOps.bounds(scaled) + t:check(lo and near(lo[1], -1) and near(hi[1], 1), "scale and centre pivot") +end + +-- the api encodes image-only textures to PNG before a model writer sees them +do + local s = S.fromPrimitive(MeshOps.triangulate(cube()) :: any) + s.textures[1] = { image = Types.Image.new(2, 2) } + s.materials[1] = S.material("m") + s.materials[1].baseColorTexture = { texture = 1 } + s.meshes[1].primitives[1].material = 1 + local glb = F.save(s, nil, { format = "glb" }) + t:check(glb and s.textures[1].mime == "image/png" and s.textures[1].data ~= nil, "F.save: texture image -> PNG bytes") + local back = F.load(glb) + local _, errs = F.model.loadTextures(back) + t:check(back.textures[1].image and back.textures[1].image.width == 2 and next(errs) == nil, "PNG texture through GLB and back") +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 65f04c5..0201a14 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -389,3 +389,85 @@ do Hdr.encode(f) end) end +do + -- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a + -- 128^3 noise voxel grid through VOX and greedy meshing + local Types = require("@formats/Types") + local MeshOps = require("@formats/ops/MeshOps") + local Gltf = require("@formats/model/gltf") + local Obj = require("@formats/model/obj") + local Stl = require("@formats/model/stl") + local Ply = require("@formats/model/ply") + local Vox = require("@formats/model/vox") + local N = 400 + local pos = Types.Scene.accessor(nil, "f32", 3, N * N) + local uv = Types.Scene.accessor(nil, "f32", 2, N * N) + for y = 0, N - 1 do + for x = 0, N - 1 do + local i = y * N + x + buffer.writef32(pos.data, i * 12, x / N) + buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05) + buffer.writef32(pos.data, i * 12 + 8, y / N) + buffer.writef32(uv.data, i * 8, x / N) + buffer.writef32(uv.data, i * 8 + 4, y / N) + end + end + local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6) + local k = 0 + for y = 0, N - 2 do + for x = 0, N - 2 do + local a = y * N + x + for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do + buffer.writeu32(ind.data, k * 4, v) + k += 1 + end + end + end + local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any + MeshOps.computeNormals(prim) + local scene = Types.Scene.fromPrimitive(prim, "grid") + bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function() + MeshOps.computeNormals(prim) + end) + local glb = assert(Gltf.encode(scene, { binary = true })) + bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function() + Gltf.decode(Bytes.reader(glb)) + end) + bench("gltf glb encode", 3, buffer.len(glb), function() + Gltf.encode(scene, { binary = true }) + end) + local obj = assert(Obj.encode(scene)) + bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function() + Obj.decode(Bytes.reader(obj)) + end) + bench("obj encode", 2, buffer.len(obj), function() + Obj.encode(scene) + end) + local stl = assert(Stl.encode(scene)) + bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function() + Stl.decode(Bytes.reader(stl)) + end) + local ply = assert(Ply.encode(scene)) + bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function() + Ply.decode(Bytes.reader(ply)) + end) + local V = 128 + local grid = Types.Voxels.new(V, V, V) + for z = 0, V - 1 do + for y = 0, V - 1 do + for x = 0, V - 1 do + local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0 + if z < h then + Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6) + end + end + end + end + local vox = assert(Vox.encode(grid)) + bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function() + Vox.decode(Bytes.reader(vox)) + end) + bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function() + MeshOps.voxelsToPrimitive(grid) + end) +end diff --git a/tools/fixtures/_gltf_encode.luau b/tools/fixtures/_gltf_encode.luau new file mode 100644 index 0000000..b7c037f --- /dev/null +++ b/tools/fixtures/_gltf_encode.luau @@ -0,0 +1,34 @@ +-- tools/fixtures/_gltf_encode: run by tools/fixtures/gltf.py (luau CLI, repo root): decodes every glTF case with our +-- reader and encodes it with our writer as .glb and as .gltf with an external .bin and image files, printing +-- "\t" lines for the reference tools (assimp, trimesh) to read back. Files: rt_.glb, rt_.gltf. +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/gltf_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + local out = table.create(#s) + for i = 1, #s do + out[i] = HEX[string.byte(s, i)] + end + return table.concat(out) +end + +for i, c in Cases do + local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if scene then + local glb = assert(Gltf.encode(scene, { binary = true })) + print(string.format("rt_%d.glb\t%s", i, hex(buffer.tostring(glb)))) + local files = {} + local gltf = assert(Gltf.encode(scene, { external = true, files = files, name = "rt_" .. i .. ".gltf" })) + print(string.format("rt_%d.gltf\t%s", i, hex(buffer.tostring(gltf)))) + for name, data in files do + print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data))) + end + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end diff --git a/tools/fixtures/_model_ref.py b/tools/fixtures/_model_ref.py new file mode 100644 index 0000000..6cd3ede --- /dev/null +++ b/tools/fixtures/_model_ref.py @@ -0,0 +1,69 @@ +# Shared helpers for the model fixture generators (obj.py, gltf.py): reference tools through nix. +# assimp_info(ctx, paths, raw?) -> [ { meshes, materials, vertices, faces, nodes, min, max, perMesh = [ { vertices, faces } ] } ] +# trimesh_metrics(ctx, paths) -> [ { area, faces, bounds, volume? } ] (trimesh, process=False, every geometry merged) +# luau_encode(ctx, script) -> { name: bytes }: runs a Luau script (repo-relative, .luaurc aliases) that prints +# "\t" lines: how a generator gets our encoder's output for the reference tools to read back. +import json, os, re, subprocess, tempfile, shutil + +FLOAT = r"(-?[\d.]+(?:e[-+]?\d+)?|-?nan|-?inf)" + + +def assimp_info(ctx, paths, raw=False): + # raw: `assimp info -r` (no post-processing: no joined vertices, no merged identical meshes) + out = [] + for p in paths: + try: + txt = ctx.nix("assimp", ["assimp", "info", p] + (["-r"] if raw else [])).decode("utf-8", "replace") + except subprocess.CalledProcessError: + out.append({"failed": True}) + continue + + def num(label): + m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M) + return int(m.group(1)) if m else -1 + + def point(label): + m = re.search(label + r"\s+\(" + FLOAT + " " + FLOAT + " " + FLOAT + r"\)", txt) + return [float(m.group(i)) for i in (1, 2, 3)] if m else [] + + per = [{"vertices": int(a), "faces": int(c)} for a, b, c in re.findall(r"^\s+\d+ \(.*?\): \[(\d+) / (\d+) / (\d+) \|", txt, re.M)] + out.append({ + "meshes": num("Meshes"), "materials": num("Materials"), "vertices": num("Vertices"), "faces": num("Faces"), + "nodes": num("Nodes"), "min": point("Minimum point"), "max": point("Maximum point"), "perMesh": per, + }) + return out + + +TRIMESH = r""" +import json, sys, trimesh, numpy as np +res = [] +for p in json.loads(sys.stdin.read()): + try: + m = trimesh.load(p, force="mesh", process=False) + d = {"area": float(m.area), "faces": int(len(m.faces)), "bounds": [float(v) for v in np.asarray(m.bounds).ravel()] if len(m.faces) else []} + except Exception as e: + d = {"failed": True} + res.append(d) +print(json.dumps(res)) +""" + + +def trimesh_metrics(ctx, paths): + out = ctx.python(["trimesh", "numpy", "networkx", "lxml", "pillow"], TRIMESH, input=json.dumps(paths).encode()) + return json.loads(out) + + +def luau_encode(ctx, script): + exe = shutil.which("luau") + cmd = [exe, script] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script] + res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True) + files = {} + for line in res.stdout.decode().split("\n"): + if "\t" in line: + name, hexdata = line.split("\t", 1) + files[name] = bytes.fromhex(hexdata.strip()) + return files + + +def tempdir(): + return tempfile.mkdtemp(prefix="formats-model-") diff --git a/tools/fixtures/_obj_encode.luau b/tools/fixtures/_obj_encode.luau new file mode 100644 index 0000000..cc38920 --- /dev/null +++ b/tools/fixtures/_obj_encode.luau @@ -0,0 +1,32 @@ +-- tools/fixtures/_obj_encode: run by tools/fixtures/obj.py (luau CLI, repo root): decodes every OBJ case with our +-- reader, encodes it again with our writer and prints "\t" lines (the OBJ, its .mtl, textures) for the +-- reference tools (assimp, trimesh) to read back. +local Obj = require("@formats/model/obj") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/obj_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + local out = table.create(#s) + for i = 1, #s do + out[i] = HEX[string.byte(s, i)] + end + return table.concat(out) +end + +for _, c in Cases do + local scene, err = Obj.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if not scene then + error(c.name .. ": " .. tostring(err)) + end + local name = "rt_" .. c.name + local files = {} + local out = assert(Obj.encode(scene, { name = name, files = files })) + print(name .. "\t" .. hex(buffer.tostring(out))) + for fname, data in files do + print(fname .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data))) + end +end diff --git a/tools/fixtures/_off_encode.luau b/tools/fixtures/_off_encode.luau new file mode 100644 index 0000000..2fbb49c --- /dev/null +++ b/tools/fixtures/_off_encode.luau @@ -0,0 +1,56 @@ +-- tools/fixtures/_off_encode.luau: run by tools/fixtures/off.py under the luau CLI (no file I/O): encodes the scenes of +-- tests/gen/off_scenes with each listed option set ("default" = {}, "plain" = no colours / normals / texcoords) and +-- prints "/ " lines, which the fixture step hands to trimesh, assimp and its own reader. +local Off = require("@formats/model/off") +local Types = require("@formats/Types") +local Scenes = require("@tests/gen/off_scenes") + +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local attrs = {} + for name, a in p.attrs do + attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count) + end + local prim: any = { attributes = attrs, mode = p.mode } + if p.indices then + prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4) + end + if p.faceColors then + prim.extras = { faceColors = Types.Scene.accessor(buffer.fromstring(p.faceColors), "unorm8", 4, #p.faceColors // 4) } + end + table.insert(prims, prim) + end + scene.meshes[i] = { primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end + +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(out) +end + +local OPTS: { [string]: any } = { default = {}, plain = { colors = false, normals = false, texcoords = false } } +for _, spec in Scenes do + local scene = build(spec) + for e in spec.encodings do + local b, err = Off.encode(scene, OPTS[e]) + if not b then + error(spec.name .. "/" .. e .. ": " .. tostring(err)) + end + print(spec.name .. "/" .. e .. " " .. hex(b)) + end +end diff --git a/tools/fixtures/_off_reference.py b/tools/fixtures/_off_reference.py new file mode 100644 index 0000000..89f961a --- /dev/null +++ b/tools/fixtures/_off_reference.py @@ -0,0 +1,32 @@ +# OFF reference values (run by tools/fixtures/off.py through ctx.python(["trimesh", "numpy"], ...), python -I). +# stdin: JSON {"dir": tmp, "make": [name], "read": [name]} +# stdout: JSON {name (only the files trimesh reads): {"vertices": n, "pos_crc": crc of the f32 vertices, "faces": [[...]] or None (n-gons over 4)}} +# make: OFF files written by trimesh (an icosphere, a capsule) +# read: every file read with trimesh.exchange.off.load_off (positions; faces when all are triangles / quads, the +# only polygons trimesh keeps as they are) +import json, os, sys, zlib +import numpy as np +import trimesh +from trimesh.exchange import off as toff + +req = json.load(sys.stdin) +d = req["dir"] +out = {} +for name in req["make"]: + m = trimesh.creation.icosphere(subdivisions=2, radius=3.0) if "ico" in name else trimesh.creation.capsule(height=2.0, radius=0.5) + with open(os.path.join(d, name), "w") as f: + f.write(toff.export_off(m, digits=9)) +for name in req["read"]: + try: + with open(os.path.join(d, name), "rb") as f: + r = toff.load_off(f) + except Exception: # noqa: BLE001 - trimesh fails on polygons of more than 4 vertices: no reference then + continue + v = np.asarray(r["vertices"], dtype=np.float64).reshape(-1, 3) + res = {"vertices": len(v), "pos_crc": zlib.crc32(v.astype("= 0: + res["faces"] = [[int(x) for x in f] for f in np.asarray(faces)] + out[name] = res +json.dump(out, sys.stdout) diff --git a/tools/fixtures/_ply_encode.luau b/tools/fixtures/_ply_encode.luau new file mode 100644 index 0000000..0418d8a --- /dev/null +++ b/tools/fixtures/_ply_encode.luau @@ -0,0 +1,52 @@ +-- tools/fixtures/_ply_encode.luau: run by tools/fixtures/ply.py under the luau CLI (no file I/O): encodes the scenes of +-- tests/gen/ply_scenes in the three encodings and prints "/ " lines, which the fixture step +-- hands to plyfile and assimp. +local Ply = require("@formats/model/ply") +local Types = require("@formats/Types") +local Scenes = require("@tests/gen/ply_scenes") + +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local attrs = {} + for name, a in p.attrs do + attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count) + end + local prim: any = { attributes = attrs, mode = p.mode } + if p.indices then + prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4) + end + table.insert(prims, prim) + end + scene.meshes[i] = { primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end + +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(out) +end + +for _, spec in Scenes do + local scene = build(spec) + for _, e in { "ascii", "binary_little_endian", "binary_big_endian" } do + local b, err = Ply.encode(scene, { format = e }) + if not b then + error(spec.name .. "/" .. e .. ": " .. tostring(err)) + end + print(spec.name .. "/" .. e .. " " .. hex(b)) + end +end diff --git a/tools/fixtures/_ply_reference.py b/tools/fixtures/_ply_reference.py new file mode 100644 index 0000000..99e5381 --- /dev/null +++ b/tools/fixtures/_ply_reference.py @@ -0,0 +1,307 @@ +# PLY reference values (run by tools/fixtures/ply.py through ctx.python(["plyfile", "numpy"], ...), python -I). +# stdin: JSON {"dir": tmp, "make": [name], "ref": [name], "ours": [{name, file, scene}]} +# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}} +# make: PLY files written by plyfile (every encoding, every property type, odd orders, lists, extra elements) +# ref: every file read with plyfile, mapped to the library's Scene conventions here (independently of the Luau +# code): CRC-32 of each attribute's packed little-endian bytes, the triangulated / polygon indices, face +# properties, raw elements, comments +# ours: our encoder's output read back by plyfile and compared property by property with the scene it came from +import json, os, sys, zlib +import numpy as np +from plyfile import PlyData, PlyElement + +req = json.load(sys.stdin) +d = req["dir"] +out = {"ref": {}, "ours": {}} + + +def path(n): + return os.path.join(d, n) + + +def crc(a): + return zlib.crc32(np.ascontiguousarray(a).tobytes()) + + +def le(a): + a = np.asarray(a) + return a.astype(a.dtype.newbyteorder("<")) + + +def sphere(rng, n): + """a UV sphere with n x n quads (poles as triangle fans): vertices, quads and triangles""" + vs = [(0.0, 0.0, 1.0)] + for i in range(1, n): + th = np.pi * i / n + for j in range(n): + ph = 2 * np.pi * j / n + vs.append((np.sin(th) * np.cos(ph), np.sin(th) * np.sin(ph), np.cos(th))) + vs.append((0.0, 0.0, -1.0)) + faces = [] + for j in range(n): + faces.append([0, 1 + j, 1 + (j + 1) % n]) + for i in range(n - 2): + for j in range(n): + a = 1 + i * n + j + b = 1 + i * n + (j + 1) % n + faces.append([a, a + n, b + n, b]) + last = len(vs) - 1 + for j in range(n): + a = 1 + (n - 2) * n + faces.append([last, a + (j + 1) % n, a + j]) + return np.array(vs) * (1 + 0.05 * rng.random((len(vs), 1))), faces + + +def faces_el(faces, ct="u1", it="i4", name="vertex_indices", extra=()): + dt = [(name, "O")] + [(n, t) for n, t, _ in extra] + a = np.empty(len(faces), dtype=dt) + a[name] = [np.array(f, dtype=it) for f in faces] + for n, t, vals in extra: + a[n] = vals + return PlyElement.describe(a, "face", len_types={name: ct}, val_types={name: it[1:] if it[0] in "<>" else it}) + + +def make(name): + seed = sum(map(ord, name)) + rng = np.random.default_rng(seed) + comments, obj_info = [], [] + if name == "cube-le.ply": + v = np.array([(x, y, z) for x in (0, 1) for y in (0, 1) for z in (0, 1)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")]) + quads = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]] + tris = [t for q in quads for t in ([q[0], q[1], q[2]], [q[0], q[2], q[3]])] + els = [PlyElement.describe(v, "vertex"), faces_el(tris)] + text, byte_order = False, "<" + elif name == "colors-be.ply": + pos, faces = sphere(rng, 12) + n = len(pos) + v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("nx", "f4"), ("ny", "f4"), ("nz", "f4"), ("red", "u1"), + ("green", "u1"), ("blue", "u1"), ("alpha", "u1"), ("quality", "f4"), ("flags", "u2")]) + v["x"], v["y"], v["z"] = pos.T + nn = pos / np.linalg.norm(pos, axis=1)[:, None] + v["nx"], v["ny"], v["nz"] = nn.T + for c in ("red", "green", "blue", "alpha"): + v[c] = rng.integers(0, 256, n) + v["quality"] = rng.random(n) + v["flags"] = rng.integers(0, 65536, n) + els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u1", "u4")] + comments = ["made by plyfile", "big endian, quads and triangles"] + text, byte_order = False, ">" + elif name == "ascii-mixed.ply": + n = 40 + v = np.empty(n, dtype=[("red", "u1"), ("z", "f8"), ("y", "f8"), ("x", "f8"), ("s", "f4"), ("t", "f4"), ("intensity", "i1"), ("id", "i4")]) + v["red"] = rng.integers(0, 256, n) + for c in ("x", "y", "z"): + v[c] = rng.random(n) * 20 - 10 + v["s"], v["t"] = rng.random(n), rng.random(n) + v["intensity"] = rng.integers(-128, 128, n) + v["id"] = rng.integers(-2 ** 31, 2 ** 31, n) + faces = [list(rng.choice(n, size=int(rng.integers(3, 7)), replace=False)) for _ in range(25)] + f = faces_el(faces, "u1", "i4", "vertex_index", extra=[("material", "u1", rng.integers(0, 4, 25)), ("weight", "f4", rng.random(25))]) + e = np.empty(10, dtype=[("vertex1", "i4"), ("vertex2", "i4"), ("crease", "u1")]) + e["vertex1"], e["vertex2"], e["crease"] = rng.integers(0, n, 10), rng.integers(0, n, 10), rng.integers(0, 256, 10) + m = np.empty(3, dtype=[("params", "O"), ("index", "i2")]) + m["params"] = [np.array(rng.random(k), dtype="f4") for k in (2, 0, 5)] + m["index"] = [-1, 0, 7] + els = [PlyElement.describe(v, "vertex"), f, PlyElement.describe(e, "edge"), + PlyElement.describe(m, "material", len_types={"params": "u1"}, val_types={"params": "f4"})] + comments = ["ascii with odd property order", ""] + obj_info = ["num_cols 5", "num_rows 8"] + text, byte_order = True, "=" + elif name == "points-le.ply": + n = 500 + v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "u1"), ("green", "u1"), ("blue", "u1")]) + for c in ("x", "y", "z"): + v[c] = rng.random(n) * 100 + for c in ("red", "green", "blue"): + v[c] = rng.integers(0, 256, n) + els = [PlyElement.describe(v, "vertex")] + text, byte_order = False, "<" + elif name == "points-ascii-float.ply": + n = 60 + v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "f4"), ("green", "f4"), ("blue", "f4"), ("u", "f4"), ("v", "f4")]) + for c in v.dtype.names: + v[c] = rng.random(n) + els = [PlyElement.describe(v, "vertex")] + text, byte_order = True, "=" + elif name == "types-be.ply": + n = 400 + types = [("a", "i1"), ("b", "u1"), ("c", "i2"), ("d", "u2"), ("e", "i4"), ("f", "u4"), ("g", "f4"), ("h", "f8")] + v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")] + types) + v["x"], v["y"] = np.cos(np.arange(n) * 2 * np.pi / n), np.sin(np.arange(n) * 2 * np.pi / n) + v["z"] = 0 + for nm, t in types: + info = np.iinfo(t) if t[0] in "iu" else None + v[nm] = rng.integers(info.min, info.max, n, endpoint=True, dtype=t) if info else rng.standard_normal(n) * 1e3 + faces = [list(range(n - 1, 99, -1)), list(range(0, 100))] # a 300-gon (ushort count) and a 100-gon + els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u2", "i4")] + text, byte_order = False, ">" + elif name == "big-le.ply": + pos, faces = sphere(rng, 180) + tris = [t for q in faces for t in (([q[0], q[1], q[2]], [q[0], q[2], q[3]]) if len(q) == 4 else ([q[0], q[1], q[2]],))] + v = np.empty(len(pos), dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")]) + v["x"], v["y"], v["z"] = pos.T + els = [PlyElement.describe(v, "vertex"), faces_el(tris, "u1", "i4")] + text, byte_order = False, "<" + elif name == "tristrips.ply": + v = np.array([(i, i % 2, 0) for i in range(8)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")]) + s = np.empty(1, dtype=[("vertex_indices", "O")]) + s["vertex_indices"] = [np.array([0, 1, 2, 3, 4, -1, 4, 5, 6, 7], dtype="i4")] + els = [PlyElement.describe(v, "vertex"), PlyElement.describe(s, "tristrips", len_types={"vertex_indices": "i4"}, val_types={"vertex_indices": "i4"})] + text, byte_order = False, "<" + else: + raise ValueError(name) + PlyData(els, text=text, byte_order=byte_order, comments=comments, obj_info=obj_info).write(path(name)) + + +for name in req["make"]: + make(name) + +ACC = {"i1": "i8", "u1": "u8", "i2": "i16", "u2": "u16", "i4": "i32", "u4": "u32", "f4": "f32", "f8": "f64"} +PAIRS = [("u", "v"), ("s", "t"), ("texture_u", "texture_v"), ("texture_s", "texture_t")] + + +def kind(a): + return np.dtype(a.dtype).str[1:] + + +def index_list(f): + for n in ("vertex_indices", "vertex_index"): + if n in f.data.dtype.names and f.properties[[p.name for p in f.properties].index(n)].__class__.__name__ == "PlyListProperty": + return n + return None + + +def reference(name): + ply = PlyData.read(path(name)) + v = ply["vertex"].data + names = v.dtype.names + taken = set() + attrs = {} + + def group(attr, cols, acc_type, dt, fill=None): + arr = np.stack([v[c].astype(dt) for c in cols] + ([np.full(len(v), fill, dtype=dt)] if fill is not None else []), axis=1) + attrs[attr] = {"type": acc_type, "components": arr.shape[1], "crc": crc(le(arr))} + taken.update(cols) + + if all(c in names for c in "xyz"): + group("POSITION", ["x", "y", "z"], "f32", "" else "binary_little_endian") + res = {"vertices": len(v), "attrs": attrs, "encoding": encoding, + "comments": list(ply.comments), "objInfo": list(ply.obj_info), "order": [e.name for e in ply.elements]} + face = None + if "face" in ply: + f = ply["face"] + il = index_list(f) + if il: + face = f + if face is not None and len(face.data): + lists = [np.asarray(x, dtype=np.int64) for x in face.data[il]] + sizes = [len(x) for x in lists] + corners = np.concatenate(lists) if lists else np.zeros(0, dtype=np.int64) + res["faces"] = len(lists) + res["corners_crc"] = crc(corners.astype(" p["tol"]: + ok, detail = False, "%s: values differ" % p["name"] + break + elif not np.array_equal(got, want): + ok, detail = False, "%s: values differ" % p["name"] + break + if ok: + if o.get("faces") is None: + if "face" in ply: + ok, detail = False, "a point cloud with a face element" + else: + f = ply["face"].data + il = "vertex_indices" if "vertex_indices" in f.dtype.names else "vertex_index" + got = [list(map(int, x)) for x in f[il]] + if got != o["faces"]: + ok, detail = False, "faces differ" + else: + detail += ", %d faces" % len(got) + out["ours"][name] = [ok, detail] + except Exception as e: # noqa: BLE001 - a reference failure is a verdict + out["ours"][name] = [False, "plyfile: %s" % e] + +json.dump(out, sys.stdout) diff --git a/tools/fixtures/_stl_encode.luau b/tools/fixtures/_stl_encode.luau new file mode 100644 index 0000000..df10a1f --- /dev/null +++ b/tools/fixtures/_stl_encode.luau @@ -0,0 +1,56 @@ +-- tools/fixtures/_stl_encode.luau: run by tools/fixtures/stl.py under the luau CLI (no file I/O): encodes the scenes of +-- tests/gen/stl_scenes with every encoding they list and prints "/ " lines, which the fixture +-- step hands to trimesh and assimp. +local Stl = require("@formats/model/stl") +local Types = require("@formats/Types") +local Scenes = require("@tests/gen/stl_scenes") + +local function acc(s: string, t: string, comps: number, count: number): Types.Accessor + return Types.Scene.accessor(buffer.fromstring(s), t, comps, count) +end + +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local prim: any = { attributes = { POSITION = acc(p.pos, p.posType or "f32", 3, p.count) }, mode = p.mode } + if p.indices then + prim.indices = acc(p.indices, "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = acc(p.faces, "u32", 1, #p.faces // 4) + end + if p.color then + prim.attributes.COLOR_0 = acc(p.color, "unorm8", 4, p.count) + end + table.insert(prims, prim) + end + scene.meshes[i] = { name = m.name, primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { name = n.name, mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end + +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(out) +end + +local OPTS: { [string]: any } = { binary = {}, ascii = { ascii = true }, viscam = { colors = "viscam" }, magics = { colors = "magics" } } +for _, spec in Scenes do + local scene = build(spec) + for _, e in spec.encodings do + local b, err = Stl.encode(scene, OPTS[e]) + if not b then + error(spec.name .. "/" .. e .. ": " .. tostring(err)) + end + print(spec.name .. "/" .. e .. " " .. hex(b)) + end +end diff --git a/tools/fixtures/_stl_reference.py b/tools/fixtures/_stl_reference.py new file mode 100644 index 0000000..efbd5f1 --- /dev/null +++ b/tools/fixtures/_stl_reference.py @@ -0,0 +1,112 @@ +# STL reference values (run by tools/fixtures/stl.py through ctx.python(["trimesh", "numpy"], ...), python -I). +# stdin: JSON {"dir": tmp, "make": [[name, kind, file_type, seed]], "ref": [name], "ours": [{name, file, ...}]} +# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}} +# make: meshes made and exported by trimesh itself (binary / ascii STL) +# ref: every file read with trimesh.exchange.stl.load_stl (the raw arrays, no processing): facet count, CRC-32 of +# the f32 triangle vertices / facet normals (as the file has them), area, bounds, the raw attribute words +# ours: our encoder's output read back by trimesh and compared with the expected world-space triangles +import json, os, sys, zlib +import numpy as np +import trimesh +from trimesh.exchange import stl as tstl + +req = json.load(sys.stdin) +d = req["dir"] +out = {"ref": {}, "ours": {}} + + +def path(n): + return os.path.join(d, n) + + +for name, kind, ftype, seed in req["make"]: + rng = np.random.default_rng(seed) + if kind == "icosphere": + m = trimesh.creation.icosphere(subdivisions=3, radius=2.5) + elif kind == "box": + m = trimesh.creation.box(extents=(1.5, 2.0, 0.25)) + elif kind == "capsule": + m = trimesh.creation.capsule(height=3.0, radius=0.7) + else: + tri = (rng.random((1500, 3, 3)) * 200 - 100).astype(np.float32) + m = trimesh.Trimesh(vertices=tri.reshape(-1, 3), faces=np.arange(4500).reshape(-1, 3), process=False) + data = m.export(file_type=ftype) + with open(path(name), "wb") as f: + f.write(data.encode() if isinstance(data, str) else data) + + +def load(name): + with open(path(name), "rb") as f: + r = tstl.load_stl(f) + if "geometry" in r: # several solids + parts = list(r["geometry"].values()) + if not parts: + return np.zeros((0, 3)), np.zeros((0, 3), dtype=np.int64), np.zeros((0, 3)), None + vs, fs, ns, off = [], [], [], 0 + for g in parts: + vs.append(g["vertices"]) + fs.append(np.asarray(g["faces"]) + off) + ns.append(g["face_normals"]) + off += len(g["vertices"]) + # trimesh does not read normals written on the "outer loop" line: no normals then + nrm = None if any(x is None for x in ns) else np.concatenate(ns) + return np.concatenate(vs), np.concatenate(fs), nrm, None + attr = r.get("face_attributes", {}).get("stl") + return np.asarray(r["vertices"]), np.asarray(r["faces"]), np.asarray(r["face_normals"]), attr + + +def crc(a, dt): + return zlib.crc32(np.ascontiguousarray(np.asarray(a).astype(dt)).tobytes()) + + +for name in req["ref"]: + v, f, n, attr = load(name) + tri = v[f].astype(np.float32) # (n, 3, 3) + m = trimesh.Trimesh(vertices=v, faces=f, process=False) + res = { + "facets": int(len(f)), + "pos_crc": crc(tri, " tol: + out["ours"][name] = [False, "positions differ by %g" % err] + continue + # the stored facet normals: the right-hand rule normal of each triangle + t = want.astype(np.float64).reshape(-1, 3, 3) + cn = np.cross(t[:, 1] - t[:, 0], t[:, 2] - t[:, 0]) + ln = np.linalg.norm(cn, axis=1) + cn[ln > 0] /= ln[ln > 0, None] + nerr = float(np.abs(np.asarray(n, dtype=np.float64) - cn).max()) if len(want) else 0.0 + if nerr > 1e-4: + out["ours"][name] = [False, "facet normals differ by %g" % nerr] + continue + if "colors" in o: + want_words = o["colors"] + got = [int(x) for x in attr] if attr is not None else [] + if got != want_words: + out["ours"][name] = [False, "attribute words differ"] + continue + out["ours"][name] = [True, "%d facets, max error %g" % (len(want), err)] + except Exception as e: # noqa: BLE001 - a reference failure is a verdict + out["ours"][name] = [False, "trimesh: %s" % e] + +json.dump(out, sys.stdout) diff --git a/tools/fixtures/base64.py b/tools/fixtures/base64.py new file mode 100644 index 0000000..253a529 --- /dev/null +++ b/tools/fixtures/base64.py @@ -0,0 +1,13 @@ +# Base64 fixtures (tools/fixtures.py): random byte strings of every length 0..70 plus a few large ones, with Python's +# base64 (standard, URL-safe, unpadded) as the reference. +# tests/gen/base64_cases.luau { data, std, url, nopad } +import base64 + + +def generate(ctx): + rng = ctx.rng(3) + cases = [] + for n in list(range(71)) + [1000, 4097, 65536]: + d = bytes(rng.randrange(256) for _ in range(n)) + cases.append({"data": d, "std": base64.b64encode(d), "url": base64.urlsafe_b64encode(d), "nopad": base64.b64encode(d).rstrip(b"=")}) + ctx.emit("base64_cases", cases) diff --git a/tools/fixtures/gltf.py b/tools/fixtures/gltf.py new file mode 100644 index 0000000..a424fcf --- /dev/null +++ b/tools/fixtures/gltf.py @@ -0,0 +1,115 @@ +# glTF fixtures (tools/fixtures.py): Khronos glTF-Sample-Assets models (tests/fixtures/gltf, licences per model +# folder), gltfpack (meshoptimizer) quantized variants (KHR_mesh_quantization, normalized and integer positions, +# KHR_texture_transform), and files exported by assimp, with reference values from assimp (`assimp info`: meshes, faces, +# bounds, materials, animations, cameras, lights) and trimesh (area, triangles, bounds of the whole scene). +# tests/gen/gltf_cases.luau { name, main, data, files = { uri -> bytes }, assimp, trimesh, like? (the original of a +# quantized variant: compare against its references with a tolerance) } +# tests/gen/gltf_xcheck.luau our encoder's .glb and .gltf for every case (tools/fixtures/_gltf_encode.luau), read back +# by assimp and trimesh: { name, case, assimp, trimesh } +import importlib.util, json, os, struct + +INPUTS = ["tests/fixtures/gltf", "src/Formats/model/gltf", "src/Formats/codecs/Json", "src/Formats/codecs/Base64", + "tools/fixtures/_model_ref.py", "tools/fixtures/_gltf_encode.luau"] + + +def ref_module(ctx): + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def assimp_extra(ctx, path): + # cameras / lights / animations counts from assimp info (the shared helper parses meshes / faces / bounds) + import re, subprocess + try: + txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace") + except subprocess.CalledProcessError: + return {} + out = {} + for label in ("Animations", "Cameras", "Lights", "Bones"): + m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M) + if m: + out[label.lower()] = int(m.group(1)) + return out + + +def ply_torus(R=2.0, r=0.5, a=16, b=8): + import math + vs, fs = [], [] + for i in range(a): + for j in range(b): + u, v = 2 * math.pi * i / a, 2 * math.pi * j / b + vs.append(((R + r * math.cos(v)) * math.cos(u), r * math.sin(v), (R + r * math.cos(v)) * math.sin(u))) + for i in range(a): + for j in range(b): + p, q = i * b + j, ((i + 1) % a) * b + j + p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b + fs.append((p, p2, q2)) + fs.append((p, q2, q)) + head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs)) + return (head + "".join("%r %r %r\n" % v for v in vs) + "".join("3 %d %d %d\n" % f for f in fs)).encode() + + +def generate(ctx): + M = ref_module(ctx) + root = os.path.join(ctx.root, "tests", "fixtures", "gltf") + cases = [] + for model in sorted(os.listdir(root)): + for variant in sorted(os.listdir(os.path.join(root, model))): + d = os.path.join(root, model, variant) + if not os.path.isdir(d): + continue + mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")] + if not mains: + continue + files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]} + cases.append({"name": model + "/" + variant, "main": mains[0], "path": os.path.join(d, mains[0]), "files": files}) + # gltfpack variants of a few models: default (integer positions + texture transform), -vpn (normalized positions), + # -vpf (float positions, quantized normals / uvs) + tmp = M.tempdir() + for model, variant, main in (("BoxTextured", "glTF", "BoxTextured.gltf"), ("Box", "glTF-Binary", "Box.glb"), ("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("MultiUVTest", "glTF-Binary", "MultiUVTest.glb")): + for flag in ("", "-vpn", "-vpf", "-vpi"): + out = os.path.join(tmp, "%s_q%s.glb" % (model, flag)) + args = ["gltfpack", "-i", os.path.join(root, model, variant, main), "-o", out, "-kn", "-km"] + ([flag] if flag else []) + ctx.nix("meshoptimizer", args) + cases.append({"name": "gltfpack/%s%s" % (model, flag), "main": os.path.basename(out), "path": out, "files": {}, "like": model + "/" + variant}) + # assimp's glTF exporters + ply = os.path.join(tmp, "torus.ply") + with open(ply, "wb") as f: + f.write(ply_torus()) + for ext in ("glb", "gltf"): + out = os.path.join(tmp, "torus_assimp." + ext) + ctx.nix("assimp", ["assimp", "export", ply, out, "-f" + ("glb2" if ext == "glb" else "gltf2")]) + files = {} + for f in os.listdir(tmp): + if f.startswith("torus_assimp") and f.endswith(".bin"): + files[f] = open(os.path.join(tmp, f), "rb").read() + cases.append({"name": "assimp/torus." + ext, "main": os.path.basename(out), "path": out, "files": files}) + infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True) + tms = M.trimesh_metrics(ctx, [c["path"] for c in cases]) + for c, a, t in zip(cases, infos, tms): + a.update(assimp_extra(ctx, c["path"])) + c["assimp"] = a + c["trimesh"] = t + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("gltf_cases", cases) + + # the reference tools read our output + ours = M.luau_encode(ctx, "tools/fixtures/_gltf_encode.luau") + xtmp = M.tempdir() + names = [] + for name, data in sorted(ours.items()): + with open(os.path.join(xtmp, name), "wb") as f: + f.write(data) + if name.endswith(".glb") or name.endswith(".gltf"): + names.append(name) + paths = [os.path.join(xtmp, n) for n in names] + xi = M.assimp_info(ctx, paths, raw=True) + xt = M.trimesh_metrics(ctx, paths) + out = [] + for n, a, t in zip(names, xi, xt): + a.update(assimp_extra(ctx, os.path.join(xtmp, n))) + out.append({"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": a, "trimesh": t}) + ctx.emit("gltf_xcheck", out) diff --git a/tools/fixtures/obj.py b/tools/fixtures/obj.py new file mode 100644 index 0000000..5b66708 --- /dev/null +++ b/tools/fixtures/obj.py @@ -0,0 +1,257 @@ +# OBJ fixtures (tools/fixtures.py): OBJ / MTL files written here (materials, textures, objects and groups, n-gons, +# negative indices, vertex colours, continuation lines, comments, lines and points, a concave polygon) and files +# exported by assimp (from generated PLY meshes), with reference values from assimp (`assimp info`: meshes, materials, +# vertices, faces, bounds) and trimesh (area, triangle count, bounds). +# tests/gen/obj_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, trimesh = {...}, polygonArea? } +# tests/gen/obj_xcheck.luau our encoder's output for every case (tools/fixtures/_obj_encode.luau), read back by assimp +# and trimesh: { name, assimp, trimesh, want = the original's values } +import importlib.util, math, os, struct + +INPUTS = ["src/Formats/model/obj", "tools/fixtures/_model_ref.py", "tools/fixtures/_obj_encode.luau"] + + +def ref_module(ctx): + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def png_1x1(): + import zlib + def ch(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) + return b"\x89PNG\r\n\x1a\n" + ch(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0)) + ch(b"IDAT", zlib.compress(b"\0\xff\0\0\xff")) + ch(b"IEND", b"") + + +def fmt(v): + return "%.6g" % v + + +CUBE = """# a cube: one object, two groups, two materials, a textured quad +mtllib cube.mtl +o Cube +v 0 0 0 +v 1 0 0 +v 1 1 0 +v 0 1 0 +v 0 0 1 +v 1 0 1 +v 1 1 1 +v 0 1 1 +vt 0 0 +vt 1 0 +vt 1 1 +vt 0 1 +vn 0 0 1 +g top +usemtl red +s 1 +f 5/1/1 6/2/1 7/3/1 8/4/1 +g bottom +usemtl blue +f 1 4 3 2 +f 1 2 6 5 +f 2 3 7 6 +f 3 4 8 7 +f 4 1 5 8 +""" + +CUBE_MTL = """# materials +newmtl red +Ka 0.1 0.1 0.1 +Kd 1 0 0 +Ks 0.5 0.5 0.5 +Ns 50 +illum 2 +map_Kd -s 2 2 1 -o 0.5 0 0 textures/tex.png +map_Bump -bm 0.5 normal.png +newmtl blue +Kd 0 0 1 +d 0.5 +Pr 0.25 +Pm 1 +Ke 0.1 0.2 0.3 +""" + + +def sphere(rng, rings, segs, colors=False): + vs, fs = [], [] + for i in range(rings - 1): # no poles: assimp turns degenerate triangles into lines + th = math.pi * (i + 1) / rings + for j in range(segs): + ph = 2 * math.pi * j / segs + vs.append((math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph))) + for i in range(rings - 2): + for j in range(segs): + a, b = i * segs + j, i * segs + (j + 1) % segs + c, d = a + segs, b + segs + fs.append((a, c, d, b)) + return vs, fs + + +def random_obj(rng): + vs, fs = sphere(rng, 6, 9) + lines = ["# random sphere: quads, triangles, pentagons, negative indices, vertex colours, continuations"] + for v in vs: + lines.append("v %s %s %s %s %s %s" % (fmt(v[0]), fmt(v[1]), fmt(v[2]), fmt(rng.random()), fmt(rng.random()), fmt(rng.random()))) + for k in range(len(vs)): + lines.append("vt %s %s" % (fmt(rng.random()), fmt(rng.random()))) + lines.append("vn 0 1 0") + lines.append("vn 1 0 0") + lines.append("g sphere") + n = len(vs) + for i, f in enumerate(fs): + if i % 7 == 0: + # negative (relative) indices + lines.append("f " + " ".join("%d/%d" % (v - n, v - n) for v in f)) + elif i % 7 == 1: + lines.append("f " + " ".join("%d//%d" % (v + 1, 1 + i % 2) for v in f)) + elif i % 7 == 2: + lines.append("f %d/%d/1 %d/%d/2 \\\n %d/%d/1 %d/%d/2" % (f[0] + 1, f[0] + 1, f[1] + 1, f[1] + 1, f[2] + 1, f[2] + 1, f[3] + 1, f[3] + 1)) + elif i % 7 == 3: + lines.append("f %d %d %d" % (f[0] + 1, f[1] + 1, f[2] + 1)) + lines.append("f %d %d %d" % (f[0] + 1, f[2] + 1, f[3] + 1)) + else: + lines.append("f " + " ".join("%d/%d" % (v + 1, v + 1) for v in f)) + # a convex pentagon and a hexagon + base = len(vs) + for k in range(5): + lines.append("v %s %s 2" % (fmt(math.cos(2 * math.pi * k / 5)), fmt(math.sin(2 * math.pi * k / 5)))) + lines.append("g pentagon") + lines.append("f " + " ".join(str(base + k + 1) for k in range(5))) + return "\n".join(lines) + "\n" + + +def concave(): + # an L-shaped hexagon (area 3) and a U-shaped octagon (area 5) in the xz plane, as n-gons + L = [(0, 0), (2, 0), (2, 1), (1, 1), (1, 2), (0, 2)] + U = [(3, 0), (6, 0), (6, 2), (5, 2), (5, 1), (4, 1), (4, 2), (3, 2)] + lines = ["o shapes"] + for x, z in L + U: + lines.append("v %d 0 %d" % (x, z)) + lines.append("f " + " ".join(str(k + 1) for k in range(len(L)))) + lines.append("f " + " ".join(str(len(L) + k + 1) for k in range(len(U)))) + area = sum(abs(sum(p[i][0] * p[(i + 1) % len(p)][1] - p[(i + 1) % len(p)][0] * p[i][1] for i in range(len(p)))) / 2 for p in (L, U)) + return "\n".join(lines) + "\n", area + + +def lines_points(): + return """o wire +v 0 0 0 +v 1 0 0 +v 1 1 0 +v 0 1 0 +l 1 2 3 4 1 +p 1 3 +f 1 2 3 +""" + + +def ply_torus(rng, R=2.0, r=0.5, a=24, b=12): + vs, fs = [], [] + for i in range(a): + for j in range(b): + u, v = 2 * math.pi * i / a, 2 * math.pi * j / b + vs.append(((R + r * math.cos(v)) * math.cos(u), r * math.sin(v), (R + r * math.cos(v)) * math.sin(u))) + for i in range(a): + for j in range(b): + p, q = i * b + j, ((i + 1) % a) * b + j + p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b + fs.append((p, p2, q2, q)) + head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs)) + body = "".join("%r %r %r\n" % v for v in vs) + "".join("4 %d %d %d %d\n" % f for f in fs) + return (head + body).encode() + + +def fan_area(text): + # the area of every face fan-triangulated (an exact reference in double precision) + text = text.replace("\\\n", " ") + V, A = [], 0.0 + for l in text.split("\n"): + w = l.split() + if not w: + continue + if w[0] == "v": + V.append([float(x) for x in w[1:4]]) + elif w[0] == "f": + idx = [] + for c in w[1:]: + v = int(c.split("/")[0]) + idx.append(v - 1 if v > 0 else len(V) + v) + for k in range(1, len(idx) - 1): + a, b, c = V[idx[0]], V[idx[k]], V[idx[k + 1]] + e1 = [b[i] - a[i] for i in range(3)] + e2 = [c[i] - a[i] for i in range(3)] + x, y, z = e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0] + A += math.sqrt(x * x + y * y + z * z) / 2 + return A + + +def generate(ctx): + M = ref_module(ctx) + rng = ctx.rng(11) + tmp = M.tempdir() + cases = [] + + def add(name, data, files=None, **extra): + path = os.path.join(tmp, name) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as f: + f.write(data) + for fn, fd in (files or {}).items(): + p = os.path.join(tmp, fn) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(fd) + c = {"name": name, "data": data, "files": files or {}, "path": path, "fanArea": fan_area(data.decode())} + c.update(extra) + cases.append(c) + + png = png_1x1() + add("cube.obj", CUBE.encode(), {"cube.mtl": CUBE_MTL.encode(), "textures/tex.png": png, "normal.png": png}) + # assimp joins mixed-attribute corners differently (136 vertices where the file has 101 distinct v/vt/vn): no + # vertex count check for this one + # and trimesh gets its area wrong (12.60 for 12.52: mixed index forms?): only the exact fan area here + add("random.obj", random_obj(rng).encode(), noVertexCount=True, noTrimesh=True) + text, area = concave() + add("concave.obj", text.encode(), polygonArea=area) + add("wire.obj", lines_points().encode(), noTrimesh=True) + # assimp's OBJ exporter, from a PLY torus + ply = os.path.join(tmp, "torus.ply") + with open(ply, "wb") as f: + f.write(ply_torus(rng)) + out = os.path.join(tmp, "torus_assimp.obj") + ctx.nix("assimp", ["assimp", "export", ply, out]) + files = {} + if os.path.exists(out[:-4] + ".mtl"): + files["torus_assimp.mtl"] = open(out[:-4] + ".mtl", "rb").read() + add("torus_assimp.obj", open(out, "rb").read(), files) + + paths = [c["path"] for c in cases] + infos = M.assimp_info(ctx, paths) + tm = M.trimesh_metrics(ctx, [c["path"] for c in cases if not c.get("noTrimesh")]) + k = 0 + for c, info in zip(cases, infos): + c["assimp"] = info + if not c.get("noTrimesh"): + c["trimesh"] = tm[k] + k += 1 + for c in cases: + del c["path"] + ctx.emit("obj_cases", cases) + + # the reference tools read our encoder's output (decode -> encode in Luau, then assimp / trimesh) + ours = M.luau_encode(ctx, "tools/fixtures/_obj_encode.luau") + xtmp = M.tempdir() + names = [] + for name, data in sorted(ours.items()): + p = os.path.join(xtmp, name) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + if name.endswith(".obj"): + names.append(name) + xinfos = M.assimp_info(ctx, [os.path.join(xtmp, n) for n in names]) + xtm = M.trimesh_metrics(ctx, [os.path.join(xtmp, n) for n in names]) + ctx.emit("obj_xcheck", [{"name": n, "assimp": a, "trimesh": t} for n, a, t in zip(names, xinfos, xtm)]) diff --git a/tools/fixtures/off.py b/tools/fixtures/off.py new file mode 100644 index 0000000..a44c626 --- /dev/null +++ b/tools/fixtures/off.py @@ -0,0 +1,343 @@ +# OFF fixtures (tools/fixtures.py). +# tests/gen/off_scenes.luau scenes for the encoder (STCNOFF mesh, polygons under a TRS node, a float-colour point +# cloud, polygons with face colours) with the expected file content, computed here +# tests/gen/off.luau cases: OFF files written by trimesh and by hand here (COFF with integer / float colours, +# RGB / RGBA, NOFF, STOFF, STCNOFF, face colours of both kinds, colormap indices, comments +# everywhere, counts on the header line, CRLF and tabs, n-gons, a point cloud), with the +# values they were written from (positions cross-checked with trimesh's OFF reader); +# `ours`: our encoder's output (luau CLI: tools/fixtures/_off_encode.luau) read back by +# trimesh, assimp and a small reader here, as verdicts +import json, math, os, shutil, struct, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/model/off", "tools/fixtures/_off_reference.py", "tools/fixtures/_off_encode.luau"] + + +def f32(x): + return struct.unpack(" tol * max(1, abs(e))) if tol else f32(g) != f32(e): + return False, "vertex value %r, want %r" % (g, e) + if faces != want["faces"]: + return False, "faces differ" + if "faceColors" in want: + if [list(map(int, c)) for c in fcols] != want["faceColors"]: + return False, "face colours differ" + elif any(fcols): + return False, "unexpected face colours" + return True, "%d vertices, %d faces" % (len(verts), len(faces)) + + +def luau_cmd(): + exe = shutil.which("luau") + return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + + +def assimp_faces(ctx, path): + txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace") + for line in txt.split("\n"): + if line.startswith("Faces:"): + return int(line.split()[1]) + return None + + +def generate(ctx): + rng = ctx.rng(53) + tmp = tempfile.mkdtemp(prefix="formats-off-") + try: + _generate(ctx, rng, tmp) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +def _generate(ctx, rng, tmp): + sc = scenes(rng) + ctx.emit("off_scenes", sc) + cases = handmade(rng) + for c in cases: + with open(os.path.join(tmp, c["name"]), "wb") as f: + f.write(c["data"]) + make = ["trimesh-ico.off", "trimesh-capsule.off"] + enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_off_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode() + ours = [] + byname = {s["name"]: s for s in sc} + for line in enc.split("\n"): + if not line.strip(): + continue + label, hexdata = line.split(" ", 1) + scene_name, encoding = label.split("/") + fn = "ours-%s-%s.off" % (scene_name, encoding) + data = bytes.fromhex(hexdata.strip()) + with open(os.path.join(tmp, fn), "wb") as f: + f.write(data) + ours.append((label, fn, data, byname[scene_name]["encodings"][encoding])) + names = [c["name"] for c in cases if c["vertices"] > 0] + make + [o[1] for o in ours] + code = open(os.path.join(ctx.root, "tools", "fixtures", "_off_reference.py")).read() + try: + ref = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "read": names}).encode())) + except subprocess.CalledProcessError as e: + raise RuntimeError("off reference: " + e.stderr.decode(errors="replace")[-3000:]) + # trimesh agrees with the values the files were written from + for c in cases: + r = ref.get(c["name"]) + if r: + assert r["vertices"] == c["vertices"] and r["pos_crc"] == c["pos_crc"], c["name"] + for name in make: + with open(os.path.join(tmp, name), "rb") as f: + data = f.read() + r = ref[name] + tris = [x for f in r["faces"] for x in f] + cases.append({"name": name, "data": data, "keyword": "OFF", "vertices": r["vertices"], "faces": r["tris"], "pos_crc": r["pos_crc"], + "allTri": True, "tris": r["tris"], "tri_crc": crc(pack("I", tris)), "corners_crc": crc(pack("I", tris)), + "sizes_crc": crc(pack("I", [3] * r["tris"]))}) + verdicts = [] + for label, fn, data, want in ours: + ok, detail = check_ours(data.decode(), want) + r = ref.get(fn) + if ok and r and not want.get("tol"): + exp = pack("f", [c for v in want["vertices"] for c in v[:3]]) + if r["pos_crc"] != crc(exp): + ok, detail = False, "trimesh reads other positions" + if ok and want["faces"]: + got = assimp_faces(ctx, os.path.join(tmp, fn)) + exp_f = sum(len(f) - 2 for f in want["faces"]) + if got != exp_f: + ok, detail = False, "assimp reads %s faces, want %d" % (got, exp_f) + verdicts.append({"name": label, "ok": ok, "detail": detail}) + ctx.emit("off", {"cases": cases, "ours": verdicts}) diff --git a/tools/fixtures/ply.py b/tools/fixtures/ply.py new file mode 100644 index 0000000..327f05b --- /dev/null +++ b/tools/fixtures/ply.py @@ -0,0 +1,192 @@ +# PLY fixtures (tools/fixtures.py). +# tests/gen/ply_scenes.luau scenes for the encoder (an indexed mesh with every attribute kind and custom properties, +# polygons under a TRS node, a float-colour point cloud, two meshes merged, a mirrored +# polygon) with the expected vertex properties (names, types, values) and faces, computed +# here +# tests/gen/ply.luau cases: PLY files written by plyfile (ascii / binary LE / BE, every property type, odd +# orders, n-gons up to 300 vertices, face properties and lists, edge / material / tristrips +# elements, comments, obj_info, point clouds, a 65k-vertex sphere) and by assimp (OFF / OBJ +# -> PLY), each with reference values from plyfile mapped to the Scene conventions; +# `ours`: our encoder's output (luau CLI: tools/fixtures/_ply_encode.luau) read back by +# plyfile and assimp, as verdicts +import json, math, os, shutil, struct, subprocess, tempfile + +INPUTS = ["src/Formats/model/ply", "tools/fixtures/_ply_reference.py", "tools/fixtures/_ply_encode.luau"] + + +def f32(x): + return struct.unpack(" 3 else {})} for p in sc["props"]] + if "faces" in sc: + sc["faceSizes"] = pack("I", [len(f) for f in sc["faces"]]) + sc["faceCorners"] = pack("I", [c for f in sc["faces"] for c in f]) + return out + + +def luau_cmd(): + exe = shutil.which("luau") + return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + + +def assimp_faces(ctx, path): + txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace") + for line in txt.split("\n"): + if line.startswith("Faces:"): + return int(line.split()[1]) + return None + + +def generate(ctx): + rng = ctx.rng(47) + tmp = tempfile.mkdtemp(prefix="formats-ply-") + try: + _generate(ctx, rng, tmp) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +def _generate(ctx, rng, tmp): + sc = scenes(rng) + ctx.emit("ply_scenes", sc) + make = ["cube-le.ply", "colors-be.ply", "ascii-mixed.ply", "points-le.ply", "points-ascii-float.ply", "types-be.ply", "big-le.ply", "tristrips.ply"] + # assimp conversions: OFF -> PLY (ascii), OBJ -> PLY (binary) + off = "OFF\n6 3 0\n" + "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(6)) + off += "3 0 1 2\n4 1 3 4 2\n3 4 5 2\n" + obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(8)) + obj += "vn 0 0 1\nf 1//1 2//1 3//1 4//1\nf 5//1 6//1 7//1\nf 1//1 8//1 5//1\n" + with open(os.path.join(tmp, "in.off"), "w") as f: + f.write(off) + with open(os.path.join(tmp, "in.obj"), "w") as f: + f.write(obj) + ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.off"), os.path.join(tmp, "assimp-off.ply"), "-fply"]) + ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.obj"), os.path.join(tmp, "assimp-obj-b.ply"), "-fplyb"]) + refs = make + ["assimp-off.ply", "assimp-obj-b.ply"] + enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_ply_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode() + ours = [] + byname = {s["name"]: s for s in sc} + for line in enc.split("\n"): + if not line.strip(): + continue + label, hexdata = line.split(" ", 1) + scene_name, encoding = label.split("/") + s = byname[scene_name] + fn = "ours-%s-%s.ply" % (scene_name, encoding) + with open(os.path.join(tmp, fn), "wb") as f: + f.write(bytes.fromhex(hexdata.strip())) + ours.append({"name": label, "file": fn, "props": [{**p, "values": p["values"].hex()} for p in s["props"]], "faces": s.get("faces")}) + code = open(os.path.join(ctx.root, "tools", "fixtures", "_ply_reference.py")).read() + try: + res = json.loads(ctx.python(["plyfile", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refs, "ours": ours}).encode())) + except subprocess.CalledProcessError as e: + raise RuntimeError("ply reference: " + e.stderr.decode(errors="replace")[-3000:]) + verdicts = [] + for o in ours: + ok, detail = res["ours"][o["name"]] + if o["faces"]: + want = sum(len(f) - 2 for f in o["faces"]) + got = assimp_faces(ctx, os.path.join(tmp, o["file"])) + if got != want: + ok, detail = False, "assimp reads %s faces, want %d" % (got, want) + verdicts.append({"name": o["name"], "ok": ok, "detail": detail}) + cases = [] + for name in refs: + with open(os.path.join(tmp, name), "rb") as f: + data = f.read() + r = res["ref"][name] + c = {"name": name, "data": data} + c.update({k: v for k, v in r.items() if v is not None}) + cases.append(c) + ctx.emit("ply", {"cases": cases, "ours": verdicts}) diff --git a/tools/fixtures/stl.py b/tools/fixtures/stl.py new file mode 100644 index 0000000..c5baef9 --- /dev/null +++ b/tools/fixtures/stl.py @@ -0,0 +1,383 @@ +# STL fixtures (tools/fixtures.py). +# tests/gen/stl_scenes.luau scenes for the encoder (indexed grid with colours, polygons under a TRS node, a node tree +# with a matrix, a mirror and u16 positions) with the expected world-space triangle soup +# (computed here with numpy) and the expected colour attribute words +# tests/gen/stl.luau cases: STL files made by trimesh (binary / ascii), by assimp (obj / ply -> stl / stlb) +# and by hand here (binary starting with "solid", VisCAM and Magics colours, raw attribute +# words, odd ASCII: case, tabs, CRLF, several solids, quads, no endsolid, trailing bytes, +# empty), each with reference values from trimesh's raw STL reader (facets, CRC-32 of the +# f32 vertices and normals, area, bounds, attribute words); `ours`: our encoder's output +# (run through the luau CLI: tools/fixtures/_stl_encode.luau) read back by trimesh and +# assimp, as verdicts +import json, math, os, shutil, struct, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/model/stl", "tools/fixtures/_stl_reference.py", "tools/fixtures/_stl_encode.luau"] + + +def f32(x): + return struct.unpack(" ASCII and binary STL + obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(12)) + obj += "f 1 2 3 4\nf 5 6 7\nf 8 9 10 11 12\nf 2 4 6\n" + ply = "ply\nformat ascii 1.0\nelement vertex 5\nproperty float x\nproperty float y\nproperty float z\nelement face 3\nproperty list uchar int vertex_indices\nend_header\n" + ply += "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(5)) + ply += "3 0 1 2\n4 0 2 3 4\n3 4 3 1\n" + with open(os.path.join(tmp, "in.obj"), "w") as f: + f.write(obj) + with open(os.path.join(tmp, "in.ply"), "w") as f: + f.write(ply) + for src, dst, fid in (("in.obj", "assimp-obj.stl", "stl"), ("in.obj", "assimp-obj-b.stl", "stlb"), ("in.ply", "assimp-ply-b.stl", "stlb")): + ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, src), os.path.join(tmp, dst), "-f" + fid]) + for name, data in files.items(): + with open(os.path.join(tmp, name), "wb") as f: + f.write(data) + make = [["trimesh-icosphere.stl", "icosphere", "stl", 1], ["trimesh-icosphere-ascii.stl", "icosphere", "stl_ascii", 1], + ["trimesh-box.stl", "box", "stl", 2], ["trimesh-capsule-ascii.stl", "capsule", "stl_ascii", 3], + ["trimesh-soup.stl", "soup", "stl", 4], ["trimesh-soup-ascii.stl", "soup", "stl_ascii", 5]] + refnames = [m[0] for m in make] + ["assimp-obj.stl", "assimp-obj-b.stl", "assimp-ply-b.stl"] + refnames += [n for n, _, e in hand if not e.get("self")] + # our encoder's output (the luau CLI prints "/ " lines) + enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_stl_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode() + ours = [] + byname = {s["name"]: s for s in sc} + for line in enc.split("\n"): + if not line.strip(): + continue + label, hexdata = line.split(" ", 1) + scene_name, encoding = label.split("/") + s = byname[scene_name] + fn = "ours-%s-%s.stl" % (scene_name, encoding) + with open(os.path.join(tmp, fn), "wb") as f: + f.write(bytes.fromhex(hexdata.strip())) + o = {"name": label, "file": fn, "expect": s["expect"].hex(), "exact": s["exact"]} + if encoding == "viscam": + o["colors"] = s["viscamWords"] + elif encoding == "magics": + o["colors"] = s["magicsWords"] + ours.append(o) + code = open(os.path.join(ctx.root, "tools", "fixtures", "_stl_reference.py")).read() + try: + res = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refnames, "ours": ours}).encode())) + except subprocess.CalledProcessError as e: + raise RuntimeError("stl reference: " + e.stderr.decode(errors="replace")[-3000:]) + verdicts = [] + for o in ours: + ok, detail = res["ours"][o["name"]] + # assimp reads it too + faces, _ = assimp_info(ctx, os.path.join(tmp, o["file"])) + want = len(bytes.fromhex(o["expect"])) // 36 + if faces != want: + ok, detail = False, "assimp reads %s faces, want %d" % (faces, want) + verdicts.append({"name": o["name"], "ok": ok, "detail": detail}) + cases = [] + for name in refnames: + with open(os.path.join(tmp, name), "rb") as f: + data = f.read() + r = res["ref"][name] + c = {"name": name, "data": data, "facets": r["facets"], "pos_crc": r["pos_crc"], "area": r["area"], "bounds": r["bounds"]} + extra = next((e for n, _, e in hand if n == name), {}) + if "nrm_crc" in r: + c["nrm_crc"] = r["nrm_crc"] + elif "normals" in extra: # the normals written here (%.6e / repr of f32 values, read as f32) + c["nrm_crc"] = crc(b"".join(struct.pack("<3f", *n) * 3 for n in extra["normals"])) + if "cols" in extra: + c["colors"] = extra["colors"] + c["col_crc"] = crc(b"".join(bytes(col) * 3 for col in extra["cols"])) + # the colour words trimesh read must be the ones written + assert r.get("attr") is not None + if "defaultColor" in extra: + c["defaultColor"] = extra["defaultColor"] + if "words" in extra: + assert r["attr"] == extra["words"] + c["attr_crc"] = crc(struct.pack("<%dH" % len(extra["words"]), *extra["words"])) + if "solids" in extra: + c["solids"] = extra["solids"] + c["solidFacets"] = extra["solidFacets"] + c["binary"] = not data.lstrip()[:5].lower() == b"solid" or (len(data) >= 84 and 84 + 50 * struct.unpack("> 8) & 255, (w >> 16) & 255, w >> 24) for w in words] + + +# ---------------------------------------------------------------------------------------------- reader (reference) +def rd_dict(d, p): + n, = struct.unpack_from("> 2) & 3 + i2 = 3 - i0 - i1 + R = [[0] * 3 for _ in range(3)] + for row, (i, bit) in enumerate(((i0, 4), (i1, 5), (i2, 6))): + R[row][i] = -1 if b & (1 << bit) else 1 + return R + + +def matmul(A, B): # 3x4 affine (R | t) + R = [[sum(A[r][k] * B[k][c] for k in range(3)) for c in range(3)] for r in range(3)] + t = [sum(A[r][k] * B[k][3] for k in range(3)) + A[r][3] for r in range(3)] + return [R[r] + [t[r]] for r in range(3)] + + +def parse(d): + assert d[:4] == b"VOX " + version, = struct.unpack_from(" 1 else {}) for i, m in enumerate(models_))) + + +def rgba(rng): + return chunk("RGBA", bytes(rng.randrange(256) for _ in range(1024))) + + +def synthetic(rng): + out = [] + # 1. a plain v150 model without a palette (the default palette) + out.append(("syn-default-palette", vox(model(rng, 7, 5, 3), 150))) + # 2. full scene: nested groups, every rotation family, mirrors, hidden, layers, materials, notes, cameras, IMAP, META + ch = [] + for _ in range(4): + ch += model(rng, rng.randrange(1, 12), rng.randrange(1, 12), rng.randrange(1, 12)) + ch += [ + ntrn(0, 1, layer=-1), + ngrp(1, [2, 4, 8]), + ntrn(2, 3, {"_name": "a"}, [{"_r": "4", "_t": "1 2 3"}]), + nshp(3, [0]), + ntrn(4, 5, {"_name": "group", "_hidden": "1"}, [{"_r": "17", "_t": "-5 0 7"}], layer=1), # 90 deg about z + ngrp(5, [6, 10]), + ntrn(6, 7, {"_name": "b"}, [{"_r": "20", "_t": "0 0 -4"}]), # a mirror (x flipped) + nshp(7, [1]), + ntrn(8, 9, {"_name": "anim"}, [{"_r": "9", "_t": "3 3 3", "_f": "0"}, {"_r": "4", "_t": "4 4 4", "_f": "5"}]), + nshp(9, [2, 3]), + ntrn(10, 11, {"_name": "c"}, [{"_r": "98", "_t": "10 -20 30"}]), + nshp(11, [3]), + chunk("LAYR", struct.pack("