diff --git a/README.md b/README.md index b2500f1..fb0e714 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,8 @@ local opus = F.save(F.ops.audio.resample(mono, 48000), nil, { format = "opus", b -- video: MP4 / MOV, MKV / WebM, AVI, MPEG-TS / PS, Y4M (+ animated images) -> VideoDecoder local v = F.video.open(mp4Bytes) -- v:nextFrame() -> frame (image yuv420p or rgba8, pts) --- models: glTF / GLB, OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX -> Scene +-- models: glTF / GLB (+ Draco), OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX, 3DS, MS3D, LWO, .x, IQM, B3D, +-- PMX / PMD, VRML, X3D, LDraw -> Scene local scene = F.model.load(glbBytes) local prim = F.ops.mesh.merge(scene) -- one triangle primitive in world space diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 7a68bd6..2b29a0a 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -48,6 +48,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | pmx | .pmx .pmd | yes | - | materials: true, skins: true, morphTargets: true, pmd: true | `tests/model/pmx.luau` | | model | qb | .qb | yes | yes | voxels: true, truecolor: true | `tests/model/qb.luau` | | model | rbxm | .rbxm .rbxl | yes | yes | tree: true, compression: "none", "lz4", "zstd" | `tests/model/rbxm.luau` | | model | rbxmx | .rbxmx .rbxlx | yes | yes | tree: true | `tests/model/rbxmx.luau` | @@ -56,7 +57,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | +| model | vrml | .wrl .wrz .vrml | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true | `tests/model/vrml.luau` | | model | x | .x | yes | - | text: true, binary: true, compressed: true, materials: true, skins: true, animation: true, polygons: true, vertexColors: true | `tests/model/x.luau` | +| model | x3d | .x3d .x3dv .x3dz .x3dvz .x3db | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true, xml: true, classic: true | `tests/model/x3d.luau` | | cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary", extraFiles: true | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | @@ -148,6 +151,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl, - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each - codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for + - codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 1676ff7..36177af 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -1,10 +1,10 @@ # Scene (3D models) and Voxels Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D, B3D, LDraw, LightWave -LWO, DirectX .x, IQM) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, -flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats -(STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through -`F.ops.mesh`. +LWO, DirectX .x, IQM, PMX / PMD, VRML, X3D) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes +made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. +Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). +Editing goes through `F.ops.mesh`. ```luau local scene = assert(F.model.load(texturedGltfText)) @@ -310,7 +310,8 @@ the binary container. | glTF | `external = true` writes `.bin` and the images into `opts.files` (default: embedded `data:` URIs) | `binary`, `external`, `name` | | OBJ | `.mtl` and texture files into `opts.files` | `name`, `mtlName`, `normals`, `texcoords`, `colors`, `flipV` | | STL | | `ascii = true` (default binary), `normals = "attribute"` | -| PLY, OFF, FBX, DAE, 3MF, USDA, VOX, 3DS, MS3D | see [FORMATS.md](../FORMATS.md) and the format's options | | +| PLY, OFF, FBX, DAE, 3MF, USDA, VOX, 3DS, MS3D, IQM | see [FORMATS.md](../FORMATS.md) and the format's options | | +| VRML, X3D | texture images into `opts.files` (else `url` = the texture's uri) | `name`, `flipV`; X3D `encoding = "x3dv"` (or a `.x3dv` destination) for the classic encoding | Mesh-only writers (STL, PLY, OFF, OBJ) bake the node transforms into the vertices. Extra files go into the `opts.files` table you pass, named after `opts.name`: @@ -337,6 +338,60 @@ assert(F.save(scene, "out/box.obj")) -- box.obj + box.mtl assert(F.convert("assets/Box.glb", "stl", { out = "out/box.stl" })) ``` +## MikuMikuDance (PMX / PMD) + +`.pmx` (PMX 2.0 / 2.1) and `.pmd` files load as one skinned mesh with one primitive per material. MMD is left-handed, +so z is negated and the winding reversed on load; `meta.up` is `"y"` (one unit is about 8 cm). Bones become nodes (a +translation relative to the parent bone) under the model's root node and one `Skin`; every vertex carries `JOINTS_0` / +`WEIGHTS_0` (BDEF1 / 2 / 4, SDEF and QDEF all as linear weights, normalized; the SDEF C / R0 / R1 vectors as +`_SDEF_C` / `_SDEF_R0` / `_SDEF_R1` and the deform type as `_DEFORM` when a file uses them), the additional UVs as +`_UVA1` .. `_UVA4` (vec4) and the edge scale as `_EDGE_SCALE`. Vertex morphs are morph targets (`mesh.extras.targetNames` +holds their names); the other morphs (group, bone, UV, material, flip, impulse) are in `mesh.extras.pmx.morphs`. +Materials take the diffuse colour as `baseColor`, the specular power as roughness and the no-cull flag as +`doubleSided`; the MMD terms (specular, ambient, edge, sphere map and its mode, toon texture or shared toon index, memo) +are in `material.extras.pmx`, bone flags / IK / inherit settings in `node.extras.pmx`, display frames, rigid bodies and +joints in `meta.source`. Textures are referenced by their file names (`opts.files` / `opts.resolve` give the bytes). +`morphs = false` skips the morph targets. + +## VRML and X3D + +VRML97 (`.wrl`, gzipped `.wrz`) and X3D (XML `.x3d`, classic `.x3dv`, gzipped `.x3dz` / `.x3dvz`) share one reader: the +scene graph becomes nodes (a `Transform` with a `center` or `scaleOrientation` adds an inner node), `DEF` / `USE` +shares meshes and materials, `PROTO` / `ProtoInstance` are expanded, Box / Sphere / Cone / Cylinder are tessellated +(`opts.segments`, default 32), polygons are fan-triangulated unless `triangulate = false`, texture coordinates are +flipped to glTF's top-left origin, viewpoints become cameras, lights become lights, and ROUTEs from a `TimeSensor` +through position / orientation interpolators to a `Transform` become animations. `Inline` files and textures come +from `opts.files` / `opts.resolve`. Binary X3D (`.x3db`) is `UNSUPPORTED`. + +```luau +local wrl = [[#VRML V2.0 utf8 +DEF Red Transform { translation 2 0 0 children Shape { + appearance Appearance { material Material { diffuseColor 1 0 0 } } + geometry Box { size 1 2 3 } } } +DEF Cam Viewpoint { position 0 0 10 } +]] +local scene = assert(F.load(wrl)) -- detected by the #VRML header +assert(scene.meta.source.format == "vrml" and #scene.cameras == 1) +assert(scene.nodes[1].name == "Red" and scene.materials[1].baseColor[1] == 1) +local lo, hi = F.ops.mesh.bounds(scene) +assert(lo[1] == 1.5 and hi[1] == 2.5) -- the Box, moved by its Transform +``` + +Both write too: VRML97 text, X3D XML, or the classic X3D encoding. Shared meshes are written once and `USE`d; textures +with bytes go into `opts.files`: + +```luau +local x3d = [[ + +]] +local quad = assert(F.load(x3d, { triangulate = false })) +assert(quad.meshes[1].primitives[1].mode == "polygons" and quad.meshes[1].primitives[1].faces.count == 1) +local out = assert(F.save(quad, nil, { format = "wrl" })) -- VRML97 +assert(buffer.readstring(out, 0, 15) == "#VRML V2.0 utf8") +local classic = assert(F.save(quad, nil, { format = "x3dv" })) -- the classic X3D encoding +assert(F.load(classic, { triangulate = false }).meshes[1].primitives[1].faces.count == 1) +``` + ## Voxels MagicaVoxel `.vox` files load as a Scene with `meta.up = "z"`, units of one voxel, and grids in `scene.voxels`; each @@ -633,6 +688,9 @@ assert(back.meshes[1].primitives[1].indices.count == 3) | Minecraft `.schem` / `.schematic` / `.litematic` | yes | yes | block grids, see [voxel.md](voxel.md) | | Minecraft region `.mca` | yes | | block grids of chosen chunks, see [voxel.md](voxel.md) | | Qubicle `.qb` | yes | yes | true-colour grids, see [voxel.md](voxel.md) | +| PMX / PMD (MikuMikuDance) | yes | | bones + skin, vertex morphs, MMD materials and physics in extras | +| VRML97 (WRL / WRZ) | yes | yes | primitives, PROTO, Inline, ROUTE animations, cameras, lights | +| X3D (XML / classic) | yes | yes | the VRML reader plus the X3D triangle / quad / line sets; no binary `.x3db` | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 62e06f3..ede3b72 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -530,6 +530,18 @@ local list: { Entry } = { return require("@formats/model/ply") end, }, + { + name = "pmx", + category = "model", + path = "model/pmx", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, + load = function() + return require("@formats/model/pmx") + end, + }, { name = "qb", category = "model", @@ -626,6 +638,18 @@ local list: { Entry } = { return require("@formats/model/vox") end, }, + { + name = "vrml", + category = "model", + path = "model/vrml", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, + load = function() + return require("@formats/model/vrml") + end, + }, { name = "x", category = "model", @@ -638,6 +662,18 @@ local list: { Entry } = { return require("@formats/model/x") end, }, + { + name = "x3d", + category = "model", + path = "model/x3d", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, + load = function() + return require("@formats/model/x3d") + end, + }, { name = "step", category = "cad", diff --git a/src/Formats/codecs/model/Vrml/Build.luau b/src/Formats/codecs/model/Vrml/Build.luau new file mode 100644 index 0000000..8ddc054 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Build.luau @@ -0,0 +1,590 @@ +--!strict +-- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene. +-- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation, +-- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through +-- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when +-- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. +-- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial +-- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture +-- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform: +-- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight / +-- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a +-- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in +-- meta.source.skipped. Never throws: bad data returns nil, message. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Fields = require("@formats/codecs/model/Vrml/Fields") +local Geometry = require("@formats/codecs/model/Vrml/Geometry") + +local Build = {} + +local S = Types.Scene +local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.str, Fields.strs, Fields.node, Fields.nodes +local deg = math.deg + +export type Options = Geometry.Options & { + fetch: ((uri: string) -> buffer?)?, -- reads textures and Inline files + load: ((data: buffer) -> (any, string?))?, -- an Inline file's bytes -> its graph + format: string?, -- meta.source.format + maxInline: number?, -- Inline nesting (default 8) +} + +local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true } +local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true } +local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" } +-- nodes with nothing to show (not counted as skipped) +local QUIET = { + WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, + PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, + CoordinateInterpolator = true, NormalInterpolator = true, TouchSensor = true, ProximitySensor = true, + VisibilitySensor = true, PlaneSensor = true, CylinderSensor = true, SphereSensor = true, Script = true, Sound = true, + AudioClip = true, MetadataString = true, MetadataFloat = true, MetadataInteger = true, MetadataDouble = true, + MetadataSet = true, MetadataBoolean = true, BooleanFilter = true, BooleanToggle = true, BooleanTrigger = true, + BooleanSequencer = true, IntegerSequencer = true, IntegerTrigger = true, TimeTrigger = true, KeySensor = true, + StringSensor = true, LoadSensor = true, +} +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", gif = "image/gif", bmp = "image/bmp", webp = "image/webp", ktx2 = "image/ktx2", dds = "image/vnd-ms.dds", tga = "image/x-tga" } + +local function quat(r: { number }): { number } + return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4])) +end +local function qmul(a: { number }, b: { number }): { number } + return { + a[4] * b[1] + a[1] * b[4] + a[2] * b[3] - a[3] * b[2], + a[4] * b[2] - a[1] * b[3] + a[2] * b[4] + a[3] * b[1], + a[4] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[4], + a[4] * b[4] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], + } +end +local function qrot(q: { number }, v: { number }): { number } + local m = Mat4.fromQuat(q) + local x, y, z = Mat4.point(m, v[1], v[2], v[3]) + return { x, y, z } +end +local function isZero(v: { number }): boolean + return v[1] == 0 and v[2] == 0 and v[3] == 0 +end +local function isIdentityQ(q: { number }): boolean + return q[1] == 0 and q[2] == 0 and q[3] == 0 +end +-- the rotation taking unit vector a onto b +local function between(a: { number }, b: { number }): { number } + local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local bx, by, bz = b[1] / l, b[2] / l, b[3] / l + local d = a[1] * bx + a[2] * by + a[3] * bz + if d < -0.999999 then + -- opposite: half a turn about any perpendicular axis + return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 } + end + local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx + local w = 1 + d + local n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w) + return { cx / n, cy / n, cz / n, w / n } +end + +type Ctx = { + scene: Types.Scene, + opts: Options, + meshes: { [any]: any }, + materials: { [any]: any }, + textures: { [any]: number }, + instances: { [any]: { { node: number, center: { number }, so: { number } } } }, + skipped: { [string]: number }, + depth: number, + inline: number, + failure: string?, +} + +local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number + local nodes_ = ctx.scene.nodes + table.insert(nodes_, n) + local i = #nodes_ + if parent then + table.insert(nodes_[parent].children, i) + else + table.insert(ctx.scene.roots, i) + end + return i +end + +-- ------------------------------------------------------------------------------------------------ materials +local function texture(ctx: Ctx, t: any): number? + if not t then + return nil + end + if t.type == "MultiTexture" then + return texture(ctx, nodes(t, "texture")[1]) + end + local cached = ctx.textures[t] + if cached then + return cached + end + local tex: Types.Texture = { name = t.def } + if t.type == "ImageTexture" or t.type == "MovieTexture" then + local urls = strs(t, "url") + local fetch = ctx.opts.fetch + for _, u in urls do + local clean = string.match(u, "^([^#?]*)") or u + if not tex.uri and not string.find(clean, "^%a[%w+.-]*://") then + tex.uri = clean + end + local data = fetch and fetch(clean) + if data then + tex.uri, tex.data = clean, data + break + end + end + tex.uri = tex.uri or urls[1] + local ext = tex.uri and string.match(tex.uri, "%.(%w+)$") + tex.mime = if ext then MIME[string.lower(ext)] else nil + elseif t.type == "PixelTexture" then + -- SFImage: width height components pixels (0xRRGGBBAA style integers, MSB first) + local v = nums(t, "image") or {} + local w, h, c = math.floor(v[1] or 0), math.floor(v[2] or 0), math.floor(v[3] or 0) + if w > 0 and h > 0 and c >= 1 and c <= 4 and w * h <= 2 ^ 24 and #v >= 3 + w * h then + local img = Types.Image.new(w, h) + for i = 0, w * h - 1 do + local px = math.floor(v[4 + i]) % 2 ^ (8 * c) + local b = table.create(4, 0) + for k = c, 1, -1 do + b[k] = px % 256 + px //= 256 + end + local r, g, bl, a + if c <= 2 then + r, g, bl, a = b[1], b[1], b[1], if c == 2 then b[2] else 255 + else + r, g, bl, a = b[1], b[2], b[3], if c == 4 then b[4] else 255 + end + -- the image's first row is the bottom one + local row = h - 1 - i // w + local o = (row * w + i % w) * 4 + buffer.writeu8(img.pixels, o, r) + buffer.writeu8(img.pixels, o + 1, g) + buffer.writeu8(img.pixels, o + 2, bl) + buffer.writeu8(img.pixels, o + 3, a) + end + tex.image = img + end + else + ctx.skipped[t.type] = (ctx.skipped[t.type] or 0) + 1 + return nil + end + local rs, rt = bool(t, "repeatS", true), bool(t, "repeatT", true) + if not rs or not rt then + tex.sampler = { wrapS = if rs then "repeat" else "clamp", wrapT = if rt then "repeat" else "clamp" } + end + table.insert(ctx.scene.textures, tex) + ctx.textures[t] = #ctx.scene.textures + return #ctx.scene.textures +end + +local function textureRef(ctx: Ctx, t: any, xf: any): Types.TextureRef? + local i = texture(ctx, t) + if not i then + return nil + end + local ref: Types.TextureRef = { texture = i } + if xf and xf.type == "TextureTransform" then + local tr, sc, rot = vec(xf, "translation", { 0, 0 }), vec(xf, "scale", { 1, 1 }), num(xf, "rotation", 0) + if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot ~= 0 then + ref.transform = { offset = tr, scale = sc, rotation = rot } + end + end + return ref +end + +local function material(ctx: Ctx, app: any, solid: boolean): number? + if not app and solid then + return nil + end + local key = app or "default" + local cache = ctx.materials[key] + if type(cache) ~= "table" then + cache = {} + ctx.materials[key] = cache + end + local hit = (cache :: any)[solid] + if hit then + return hit + end + local m = S.material(app and app.def) + m.metallic = 0 + local x: { [string]: any } = {} + local mat = app and node(app, "material") + local tex = app and node(app, "texture") + local xf = app and node(app, "textureTransform") + if mat and mat.type == "TwoSidedMaterial" then + m.doubleSided = true + x.twoSided = true + end + if mat and (mat.type == "Material" or mat.type == "TwoSidedMaterial") then + local d, e, sp = vec(mat, "diffuseColor", { 0.8, 0.8, 0.8 }), vec(mat, "emissiveColor", { 0, 0, 0 }), vec(mat, "specularColor", { 0, 0, 0 }) + local sh, tr, amb = num(mat, "shininess", 0.2), num(mat, "transparency", 0), num(mat, "ambientIntensity", 0.2) + m.name = mat.def or m.name + m.baseColor = { d[1], d[2], d[3], 1 - tr } + m.emissive = e + m.roughness = math.clamp(math.sqrt(2 / (math.max(sh, 0) * 128 + 2)), 0, 1) + x.diffuseColor, x.emissiveColor, x.specularColor, x.shininess, x.transparency, x.ambientIntensity = d, e, sp, sh, tr, amb + if tr > 0 then + m.alphaMode = "blend" + end + -- X3D 4 texture fields + local dt = node(mat, "diffuseTexture") + if dt then + m.baseColorTexture = textureRef(ctx, dt, nil) + end + local nt = node(mat, "normalTexture") + if nt then + m.normalTexture = textureRef(ctx, nt, nil) + end + elseif mat and mat.type == "PhysicalMaterial" then + local b, e = vec(mat, "baseColor", { 1, 1, 1 }), vec(mat, "emissiveColor", { 0, 0, 0 }) + local tr = num(mat, "transparency", 0) + m.name = mat.def or m.name + m.baseColor = { b[1], b[2], b[3], 1 - tr } + m.emissive, m.metallic, m.roughness = e, num(mat, "metallic", 1), num(mat, "roughness", 1) + if tr > 0 then + m.alphaMode = "blend" + end + local slots: { [string]: string } = { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" } + for field, slot in slots do + local t = node(mat, field) + if t then + (m :: any)[slot] = textureRef(ctx, t, nil) + end + end + elseif mat and mat.type == "UnlitMaterial" then + local e = vec(mat, "emissiveColor", { 1, 1, 1 }) + m.name = mat.def or m.name + m.baseColor = { e[1], e[2], e[3], 1 - num(mat, "transparency", 0) } + m.extensions = { KHR_materials_unlit = {} } + else + -- no material: unlit white (the specifications' default) + m.extensions = { KHR_materials_unlit = {} } + end + if tex and not m.baseColorTexture then + m.baseColorTexture = textureRef(ctx, tex, xf) + if m.baseColorTexture and xf then + x.textureCenter = vec(xf, "center", { 0, 0 }) + end + end + if not solid then + m.doubleSided = true + end + m.extras = { vrml = x } + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + ;(cache :: any)[solid] = idx + return idx +end + +-- ------------------------------------------------------------------------------------------------ nodes +local walk: (ctx: Ctx, n: any, parent: number?) -> () + +local function shape(ctx: Ctx, n: any, parent: number?) + local geo = node(n, "geometry") + if not geo then + return + end + local mi = ctx.meshes[n] + if mi == nil then + local prim, solidOrErr = Geometry.primitive(geo, ctx.opts) + if not prim then + if solidOrErr then + ctx.failure = ctx.failure or solidOrErr + else + ctx.skipped[geo.type] = (ctx.skipped[geo.type] or 0) + 1 + end + ctx.meshes[n] = false :: any + return + end + local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count + if count == 0 then + -- nothing to draw (no valid faces / points) + ctx.meshes[n] = false + return + end + prim.material = material(ctx, node(n, "appearance"), solidOrErr == true) + table.insert(ctx.scene.meshes, { name = n.def or geo.def, primitives = { prim } }) + mi = #ctx.scene.meshes + ctx.meshes[n] = mi + elseif mi == false then + return + end + addNode(ctx, { name = n.def, children = {}, mesh = mi }, parent) +end + +local function viewpoint(ctx: Ctx, n: any, parent: number?) + local cam: any + if n.type == "OrthoViewpoint" then + local f = vec(n, "fieldOfView", { -1, -1, 1, 1 }) + cam = { type = "orthographic", xmag = (f[3] - f[1]) / 2, ymag = (f[4] - f[2]) / 2, znear = 0.125, zfar = 1e4 } + else + cam = { type = "perspective", yfov = num(n, "fieldOfView", 0.785398), znear = 0.125 } + end + cam.name = n.def or str(n, "description") + table.insert(ctx.scene.cameras, cam) + local o = vec(n, "orientation", { 0, 0, 1, 0 }) + local nd: Types.Node = { name = cam.name, children = {}, camera = #ctx.scene.cameras, translation = vec(n, "position", { 0, 0, 10 }) } + if o[4] ~= 0 then + nd.rotation = quat(o) + end + addNode(ctx, nd, parent) +end + +local function light(ctx: Ctx, n: any, parent: number?) + local t = n.type + local l: Types.Light = { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) } + local nd: Types.Node = { name = n.def, children = {} } + local x: { [string]: any } = { ambientIntensity = num(n, "ambientIntensity", 0), on = bool(n, "on", true), global = bool(n, "global", t == "DirectionalLight") } + if t == "DirectionalLight" then + l.type = "directional" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + else + nd.translation = vec(n, "location", { 0, 0, 0 }) + l.range = num(n, "radius", 100) + x.attenuation = vec(n, "attenuation", { 1, 0, 0 }) + if t == "SpotLight" then + l.type = "spot" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + local cut = num(n, "cutOffAngle", 0.785398) + l.outerCone = cut + l.innerCone = math.min(num(n, "beamWidth", 1.570796), cut) + end + end + ;(l :: any).extras = { vrml = x } + table.insert(ctx.scene.lights, l) + nd.light = #ctx.scene.lights + addNode(ctx, nd, parent) +end + +local function children(ctx: Ctx, n: any, parent: number?) + if n.type == "Switch" then + local which = math.floor(num(n, "whichChoice", -1)) + local list = nodes(n, "choice") + if #list == 0 then + list = nodes(n, "children") + end + local c = list[which + 1] + if which >= 0 and c then + walk(ctx, c, parent) + end + return + elseif n.type == "LOD" then + local list = nodes(n, "level") + if #list == 0 then + list = nodes(n, "children") + end + if list[1] then + walk(ctx, list[1], parent) + end + return + end + for _, f in CHILDREN do + for _, c in nodes(n, f) do + walk(ctx, c, parent) + end + end +end + +local function transform(ctx: Ctx, n: any, parent: number?) + local t, c = vec(n, "translation", { 0, 0, 0 }), vec(n, "center", { 0, 0, 0 }) + local r, s, so = vec(n, "rotation", { 0, 0, 1, 0 }), vec(n, "scale", { 1, 1, 1 }), vec(n, "scaleOrientation", { 0, 0, 1, 0 }) + local qr, qs = quat(r), quat(so) + local outer: Types.Node = { name = n.def, children = {} } + local tt = { t[1] + c[1], t[2] + c[2], t[3] + c[3] } + if not isZero(tt) then + outer.translation = tt + end + local q = if isIdentityQ(qs) then qr else qmul(qr, qs) + if not isIdentityQ(q) then + outer.rotation = q + end + if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then + outer.scale = s + end + local oi = addNode(ctx, outer, parent) + local list = ctx.instances[n] + if not list then + list = {} + ctx.instances[n] = list + end + table.insert(list, { node = oi, center = c, so = qs }) + local holder = oi + if not isZero(c) or not isIdentityQ(qs) then + local inv = { -qs[1], -qs[2], -qs[3], qs[4] } + local inner: Types.Node = { children = {}, translation = qrot(inv, { -c[1], -c[2], -c[3] }) } + if not isIdentityQ(inv) then + inner.rotation = inv + end + holder = addNode(ctx, inner, oi) + end + children(ctx, n, holder) +end + +local function inline(ctx: Ctx, n: any, parent: number?) + local fetch, load = ctx.opts.fetch, ctx.opts.load + if not fetch or not load or ctx.inline >= (ctx.opts.maxInline or 8) or not bool(n, "load", true) then + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 + return + end + for _, u in strs(n, "url") do + local data = fetch(string.match(u, "^([^#?]*)") or u) + if data then + local g = load(data) + if g then + local holder = addNode(ctx, { name = n.def, children = {} }, parent) + ctx.inline += 1 + for _, root in g.roots do + walk(ctx, root, holder) + end + ctx.inline -= 1 + return + end + end + end + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 +end + +function walk(ctx: Ctx, n: any, parent: number?) + if ctx.failure or type(n) ~= "table" then + return + end + ctx.depth += 1 + if ctx.depth > 200 then + ctx.failure = "limit: scene nested deeper than 200" + return + end + local t = n.type + if TRANSFORM[t] then + transform(ctx, n, parent) + elseif GROUP[t] then + local holder = parent + if n.def or parent == nil then + holder = addNode(ctx, { name = n.def, children = {} }, parent) + end + children(ctx, n, holder) + elseif t == "Shape" then + shape(ctx, n, parent) + elseif t == "CADFace" then + for _, s in nodes(n, "shape") do + walk(ctx, s, parent) + end + elseif t == "Viewpoint" or t == "OrthoViewpoint" then + viewpoint(ctx, n, parent) + elseif t == "DirectionalLight" or t == "PointLight" or t == "SpotLight" then + light(ctx, n, parent) + elseif t == "Inline" then + inline(ctx, n, parent) + elseif t == "WorldInfo" then + local src = ctx.scene.meta.source :: any + src.title = str(n, "title") + local info = strs(n, "info") + src.info = if #info > 0 then info else nil + elseif not QUIET[t] then + ctx.skipped[t] = (ctx.skipped[t] or 0) + 1 + end + ctx.depth -= 1 +end + +-- ------------------------------------------------------------------------------------------------ animation +local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } + +local function animations(ctx: Ctx, routes: { any }) + -- interpolator -> its TimeSensor + local timer: { [any]: any } = {} + for _, r in routes do + if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then + timer[r.to] = r.from + end + end + local anims: { [any]: Types.Animation } = {} + local order: { any } = {} + for _, r in routes do + local path = TARGET[r.toField] + local it = r.from + local inst = ctx.instances[r.to] + if not (path and inst and (it.type == "PositionInterpolator" or it.type == "OrientationInterpolator")) then + continue + end + if (path == "rotation") ~= (it.type == "OrientationInterpolator") then + continue + end + local key: { number }, kv: { number } = nums(it, "key") or {}, nums(it, "keyValue") or {} + local comps = if path == "rotation" then 4 else 3 + local n = math.min(#key, #kv // comps) + if n == 0 then + continue + end + local ts = timer[it] + local cycle = if ts then num(ts, "cycleInterval", 1) else 1 + local input = S.accessor(nil, "f32", 1, n) + for i = 0, n - 1 do + buffer.writef32(input.data, i * 4, key[i + 1] * cycle) + end + local id = ts or "routes" + local anim = anims[id] + if not anim then + anim = { name = if ts then ts.def else nil, channels = {} } + anims[id] = anim + table.insert(order, id) + end + for _, at in inst do + local out = S.accessor(nil, "f32", if path == "rotation" then 4 else 3, n) + local prev: { number }? = nil + for i = 0, n - 1 do + local v: { number } + if path == "rotation" then + v = quat({ kv[i * 4 + 1], kv[i * 4 + 2], kv[i * 4 + 3], kv[i * 4 + 4] }) + if not isIdentityQ(at.so) then + v = qmul(v, at.so) + end + if prev and prev[1] * v[1] + prev[2] * v[2] + prev[3] * v[3] + prev[4] * v[4] < 0 then + v = { -v[1], -v[2], -v[3], -v[4] } + end + prev = v + elseif path == "translation" then + v = { kv[i * 3 + 1] + at.center[1], kv[i * 3 + 2] + at.center[2], kv[i * 3 + 3] + at.center[3] } + else + v = { kv[i * 3 + 1], kv[i * 3 + 2], kv[i * 3 + 3] } + end + for c = 1, #v do + buffer.writef32(out.data, (i * #v + c - 1) * 4, v[c]) + end + end + table.insert(anim.channels, { node = at.node, path = path :: any, input = input, output = out, interpolation = "LINEAR" :: any }) + end + end + for _, id in order do + table.insert(ctx.scene.animations, anims[id]) + end +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(graph: any, opts: Options): (Types.Scene?, string?) + local scene = S.new() + scene.meta.up = "y" + local units = graph.units or {} + scene.meta.unit = if units.length and units.length.factor > 0 then units.length.factor else 1 + local h = graph.header or {} + local skipped: { [string]: number } = {} + scene.meta.source = { + format = opts.format or "vrml", version = h.version, encoding = h.encoding, profile = h.profile, x3d = h.x3d, + xml = h.xml, meta = graph.meta, components = graph.components, skipped = skipped, + } + local ctx: Ctx = { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil } + for _, n in graph.roots do + walk(ctx, n, nil) + end + if ctx.failure then + return nil, ctx.failure + end + animations(ctx, graph.routes or {}) + return scene, nil +end + +return Build diff --git a/src/Formats/codecs/model/Vrml/Fields.luau b/src/Formats/codecs/model/Vrml/Fields.luau new file mode 100644 index 0000000..c9ec1e2 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Fields.luau @@ -0,0 +1,168 @@ +--!strict +-- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding +-- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here +-- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans +-- true / false). Never throws. +local Fields = {} + +local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte + +-- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted +local function mfString(s: string): { string } + local out = {} + local p = find(s, "[^%s,]") + if not p or byte(s, p) ~= 34 then + return if p then { (string.match(s, "^%s*(.-)%s*$") :: string) } else {} + end + local n = #s + while p and p <= n do + if byte(s, p) ~= 34 then + break + end + local q = p + 1 + local parts = {} + while true do + local e = find(s, '["\\]', q) + if not e then + table.insert(parts, sub(s, q)) + table.insert(out, table.concat(parts)) + return out + end + table.insert(parts, sub(s, q, e - 1)) + if byte(s, e) == 92 then + table.insert(parts, sub(s, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + break + end + end + table.insert(out, table.concat(parts)) + p = find(s, "[^%s,]", p) + end + return out +end + +-- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent +function Fields.nums(node: any, name: string): { number }? + local v = node.fields[name] + if v == nil then + return nil + end + if type(v) == "string" then + local out = {} + for w in gmatch(v, "[^%s,]+") do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "true" or w == "TRUE" then + table.insert(out, 1) + elseif w == "false" or w == "FALSE" then + table.insert(out, 0) + end + end + node.fields[name] = out + return out + end + if type(v) ~= "table" then + return nil + end + local ok = true + for _, x in v do + if type(x) ~= "number" then + ok = false + break + end + end + if ok then + return v + end + local out = {} + for _, x in v do + if type(x) == "number" then + table.insert(out, x) + elseif type(x) == "boolean" then + table.insert(out, if x then 1 else 0) + end + end + return out +end + +function Fields.num(node: any, name: string, default: number): number + local v = Fields.nums(node, name) + return if v and type(v[1]) == "number" then v[1] else default +end + +-- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter) +function Fields.vec(node: any, name: string, default: { number }): { number } + local v = Fields.nums(node, name) + if not v or #v < #default then + return default + end + local out: { number } = {} + for i = 1, #default do + out[i] = v[i] + end + return out +end + +function Fields.bool(node: any, name: string, default: boolean): boolean + local v = node.fields[name] + if type(v) == "string" then + local w = string.lower(string.match(v, "^%s*(%S*)") :: string) + return if w == "true" then true elseif w == "false" then false else default + end + if type(v) == "table" and type(v[1]) == "boolean" then + return v[1] + end + return default +end + +function Fields.strs(node: any, name: string): { string } + local v = node.fields[name] + if type(v) == "string" then + local out = mfString(v) + node.fields[name] = out + return out + end + local out = {} + if type(v) == "table" then + for _, x in v do + if type(x) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.str(node: any, name: string, default: string?): string? + local v = node.fields[name] + if type(v) == "string" then + return v + end + if type(v) == "table" and type(v[1]) == "string" then + return v[1] + end + return default +end + +-- nodes(node, name) -> the nodes of an SFNode / MFNode field +function Fields.nodes(node: any, name: string): { any } + local v = node.fields[name] + local out = {} + if type(v) == "table" then + for _, x in v do + if type(x) == "table" and type(x.type) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.node(node: any, name: string): any + return Fields.nodes(node, name)[1] +end + +return Fields diff --git a/src/Formats/codecs/model/Vrml/Geometry.luau b/src/Formats/codecs/model/Vrml/Geometry.luau new file mode 100644 index 0000000..306562d --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Geometry.luau @@ -0,0 +1,770 @@ +--!strict +-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no +-- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face +-- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets +-- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet, +-- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale, +-- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone, +-- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to +-- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data. +local Types = require("@formats/Types") +local Fields = require("@formats/codecs/model/Vrml/Fields") + +local Geometry = {} + +local S = Types.Scene +local nums, num, vec, bool, node = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.node +local sqrt, sin, cos, pi = math.sqrt, math.sin, math.cos, math.pi + +export type Options = { flipV: boolean?, triangulate: boolean?, segments: number?, maxVertices: number? } + +local function f32(list: { number }, comps: number, count: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, count) + local d = a.data + for i = 1, math.min(#list, comps * count) do + buffer.writef32(d, (i - 1) * 4, list[i]) + 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 + +-- the colour node's values and component count (Color: 3, ColorRGBA: 4) +local function colors(n: any): ({ number }?, number) + local c = node(n, "color") + if not c then + return nil, 3 + end + local comps = if c.type == "ColorRGBA" then 4 else 3 + return nums(c, "color") or {}, comps +end + +local function points(n: any, field: string, sub: string): { number }? + local c = node(n, field) + return if c then nums(c, sub) or {} else nil +end + +-- ------------------------------------------------------------------------------------------------ polygon meshes +-- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil: +-- the coordinate index) or per-face indices. +type PolyIn = { + P: { number }, -- coordinates, 3 per point + corners: { number }, -- coordinate index per corner, face after face + sizes: { number }, -- corners per face + N: { number }?, nIdx: { number }?, nFace: boolean?, -- normals; per-corner or per-face indices (nil: identity) + C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?, + T: { number }?, tIdx: { number }?, + ccw: boolean, +} + +local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) + local P, corners, sizes = m.P, m.corners, m.sizes + local np = #P // 3 + local N, C, T = m.N, m.C, m.T + local cc = m.cComps or 3 + -- the attribute index of corner k (1-based) in face f (1-based) + local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number + if perFace then + return if list and #list > 0 then (list[f] or 0) else f - 1 + end + return if list and #list > 0 then (list[k] or c) else c + end + local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0) + local vkey: { [string]: number } = {} + local vsrc: { { number } } = {} -- per output vertex: coord, normal, colour, texcoord indices + local out: { number } = {} + local outSizes: { number } = {} + local k = 0 + for f, size in sizes do + local face: { number } = {} + local valid = size >= 3 + for q = 1, size do + k += 1 + local c = corners[k] + if c == nil or c < 0 or c >= np then + valid = false + end + face[q] = k + end + if valid then + local verts: { number } = {} + for q, kk in face do + local c = corners[kk] + if simple then + verts[q] = c + else + local ni = if N then idx(m.nIdx, m.nFace, f, kk, c) else -1 + local ci = if C then idx(m.cIdx, m.cFace, f, kk, c) else -1 + local ti = if T then idx(m.tIdx, false, f, kk, c) else -1 + local key = c .. ":" .. ni .. ":" .. ci .. ":" .. ti + local v = vkey[key] + if not v then + v = #vsrc + vsrc[v + 1] = { c, ni, ci, ti } + vkey[key] = v + if v >= maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + end + verts[q] = v + end + end + if not m.ccw then + for a = 2, (size + 1) // 2 do + verts[a], verts[size + 2 - a] = verts[size + 2 - a], verts[a] + end + end + if o.triangulate == false then + table.insert(outSizes, size) + for _, v in verts do + table.insert(out, v) + end + else + for a = 2, size - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[a]) + table.insert(out, verts[a + 1]) + end + end + end + end + local nv = if simple then np else #vsrc + if nv > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local flipV = o.flipV ~= false + local pos = S.accessor(nil, "f32", 3, nv) + local nrm = if N then S.accessor(nil, "f32", 3, nv) else nil + local col = if C then S.accessor(nil, "f32", cc, nv) else nil + local tex = if T then S.accessor(nil, "f32", 2, nv) else nil + local wf = buffer.writef32 + for v = 0, nv - 1 do + local s = if simple then nil else vsrc[v + 1] + local c = if s then s[1] else v + for q = 0, 2 do + wf(pos.data, (v * 3 + q) * 4, P[c * 3 + q + 1] or 0) + end + if nrm and N then + local ni = if s then s[2] else v + for q = 0, 2 do + wf(nrm.data, (v * 3 + q) * 4, N[ni * 3 + q + 1] or 0) + end + end + if col and C then + local ci = if s then s[3] else v + for q = 0, cc - 1 do + wf(col.data, (v * cc + q) * 4, C[ci * cc + q + 1] or 1) + end + end + if tex and T then + local ti = if s then s[4] else v + local tt = T[ti * 2 + 2] or 0 + wf(tex.data, v * 8, T[ti * 2 + 1] or 0) + wf(tex.data, v * 8 + 4, if flipV then 1 - tt else tt) + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = pos } + attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex + local prim: Types.Primitive = { attributes = attrs, indices = u32(out), mode = "triangles" } + if o.triangulate == false then + prim.mode = "polygons" + prim.faces = u32(outSizes) + end + return prim +end + +-- split a -1 separated index list into corners + sizes +local function split(list: { number }): ({ number }, { number }) + local corners, sizes = {}, {} + local run = 0 + for _, x in list do + if x < 0 then + if run > 0 then + table.insert(sizes, run) + end + run = 0 + else + table.insert(corners, x) + run += 1 + end + end + if run > 0 then + table.insert(sizes, run) + end + return corners, sizes +end + +-- per-face index lists keep only the entries of faces (the -1 separators of per-corner lists match the corners) +local function cornerList(list: { number }?): { number }? + if not list or #list == 0 then + return nil + end + local out = {} + for _, x in list do + if x >= 0 then + table.insert(out, x) + end + end + return out +end + +local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local P = points(n, "coord", "point") or {} + local corners, sizes = split(nums(n, "coordIndex") or {}) + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, nIdx = if nPer then cornerList(nums(n, "normalIndex")) else nums(n, "normalIndex"), + C = C, cComps = cc, cFace = not cPer, cIdx = if cPer then cornerList(nums(n, "colorIndex")) else nums(n, "colorIndex"), + T = if tc and tc.type ~= "TextureCoordinateGenerator" then (nums(if tc.type == "MultiTextureCoordinate" then (node(tc, "texCoord") or tc) else tc, "point") or {}) else nil, + tIdx = cornerList(nums(n, "texCoordIndex")), + } + return polyMesh(m, o, maxV) +end + +-- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts +local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local t = n.type + local P = points(n, "coord", "point") or {} + local np = #P // 3 + local index = nums(n, "index") + local seq: { number } + if string.sub(t, 1, 7) == "Indexed" then + seq = index or {} + else + seq = {} + for i = 0, np - 1 do + seq[i + 1] = i + end + end + local corners, sizes = {}, {} + local function tri(a: number, b: number, c: number) + table.insert(corners, a) + table.insert(corners, b) + table.insert(corners, c) + table.insert(sizes, 3) + end + -- runs: -1 separated (indexed fans / strips) or fanCount / stripCount (plain fans / strips) + local function runs(): { { number } } + local out = {} + local counts = nums(n, if string.find(t, "Fan", 1, true) then "fanCount" else "stripCount") + if string.sub(t, 1, 7) == "Indexed" or not counts then + local cur = {} + for _, x in seq do + if x < 0 then + table.insert(out, cur) + cur = {} + else + table.insert(cur, x) + end + end + table.insert(out, cur) + else + local at = 1 + for _, c in counts do + local cur = {} + for q = 0, c - 1 do + cur[q + 1] = seq[at + q] + end + at += c + table.insert(out, cur) + end + end + return out + end + if t == "IndexedTriangleSet" or t == "TriangleSet" then + for i = 1, #seq - 2, 3 do + tri(seq[i], seq[i + 1], seq[i + 2]) + end + elseif t == "IndexedQuadSet" or t == "QuadSet" then + for i = 1, #seq - 3, 4 do + for q = 0, 3 do + table.insert(corners, seq[i + q]) + end + table.insert(sizes, 4) + end + elseif string.find(t, "Fan", 1, true) then + for _, r in runs() do + for i = 2, #r - 1 do + tri(r[1], r[i], r[i + 1]) + end + end + else + for _, r in runs() do + for i = 1, #r - 2 do + if i % 2 == 1 then + tri(r[i], r[i + 1], r[i + 2]) + else + tri(r[i + 1], r[i], r[i + 2]) + end + end + end + end + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, C = C, cComps = cc, cFace = not cPer, + T = if tc and tc.type == "TextureCoordinate" then nums(tc, "point") or {} else nil, + } + return polyMesh(m, o, maxV) +end + +local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimension", 0)) + local dx, dz = num(n, "xSpacing", 1), num(n, "zSpacing", 1) + local h: { number } = nums(n, "height") or {} + if nx < 2 or nz < 2 then + return nil, nil + end + if nx * nz > maxV then + return nil, "limit: elevation grid of " .. nx .. " x " .. nz + end + local P: { number }, T: { number }, corners: { number }, sizes: { number } = {}, {}, {}, {} + for z = 0, nz - 1 do + for x = 0, nx - 1 do + table.insert(P, x * dx) + table.insert(P, h[z * nx + x + 1] or 0) + table.insert(P, z * dz) + table.insert(T, x / (nx - 1)) + table.insert(T, z / (nz - 1)) + end + end + for z = 0, nz - 2 do + for x = 0, nx - 2 do + local a = z * nx + x + -- counter-clockwise seen from +y: a, a + nx, a + nx + 1, a + 1 + for _, c in { a, a + nx, a + nx + 1, a + 1 } do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not bool(n, "normalPerVertex", true), C = C, cComps = cc, + cFace = not bool(n, "colorPerVertex", true), T = if tc then nums(tc, "point") or {} else T, + } + return polyMesh(m, o, maxV) +end + +-- ------------------------------------------------------------------------------------------------ Extrusion +local function cross(a: { number }, b: { number }): { number } + return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } +end +local function sub3(a: { number }, b: { number }): { number } + return { a[1] - b[1], a[2] - b[2], a[3] - b[3] } +end +local function norm(a: { number }): ({ number }, number) + local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) + return if l > 1e-12 then { a[1] / l, a[2] / l, a[3] / l } else { 0, 0, 0 }, l +end +-- rotate v about the unit axis k by angle a (Rodrigues) +local function rotate(v: { number }, k: { number }, a: number): { number } + local c, s = cos(a), sin(a) + local d = (k[1] * v[1] + k[2] * v[2] + k[3] * v[3]) * (1 - c) + local kv = cross(k, v) + return { v[1] * c + kv[1] * s + k[1] * d, v[2] * c + kv[2] * s + k[2] * d, v[3] * c + kv[3] * s + k[3] * d } +end + +local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local sp = nums(n, "spine") or { 0, 0, 0, 0, 1, 0 } + local cs = nums(n, "crossSection") or { 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 } + local sc = nums(n, "scale") or { 1, 1 } + local ori = nums(n, "orientation") or { 0, 0, 1, 0 } + local ns, nc = #sp // 3, #cs // 2 + if ns < 2 or nc < 2 then + return nil, nil + end + if ns * nc > maxV then + return nil, "limit: extrusion of " .. ns .. " x " .. nc + end + local spine = {} + for i = 1, ns do + spine[i] = { sp[i * 3 - 2], sp[i * 3 - 1], sp[i * 3] } + end + local function same(a: { number }, b: { number }): boolean + return math.abs(a[1] - b[1]) < 1e-9 and math.abs(a[2] - b[2]) < 1e-9 and math.abs(a[3] - b[3]) < 1e-9 + end + local closedSpine = same(spine[1], spine[ns]) + local closedCs = math.abs(cs[1] - cs[nc * 2 - 1]) < 1e-9 and math.abs(cs[2] - cs[nc * 2]) < 1e-9 + -- spine-aligned cross-section planes: Y along the spine, Z from the bend, X = Y x Z + local Ys: { { number } }, Zs: { [number]: { number } } = {}, {} + for i = 1, ns do + local prev = if i > 1 then spine[i - 1] elseif closedSpine then spine[ns - 1] else nil + local nxt = if i < ns then spine[i + 1] elseif closedSpine then spine[2] else nil + local y = sub3(nxt or spine[i], prev or spine[i]) + Ys[i] = norm(y) + if prev and nxt then + local z, l = norm(cross(sub3(nxt, spine[i]), sub3(prev, spine[i]))) + Zs[i] = if l > 1e-12 then z else nil + end + end + -- missing Z: copy a neighbour's; a straight spine rotates (0, 0, 1) like (0, 1, 0) onto the spine direction + local firstZ = nil + for i = 1, ns do + if Zs[i] then + firstZ = Zs[i] + break + end + end + for i = 1, ns do + if not Ys[i] or (Ys[i][1] == 0 and Ys[i][2] == 0 and Ys[i][3] == 0) then + Ys[i] = Ys[i - 1] or { 0, 1, 0 } + end + end + for i = 1, ns do + if not Zs[i] then + if firstZ then + Zs[i] = Zs[i - 1] or firstZ + else + local y = Ys[i] + local axis, l = norm(cross({ 0, 1, 0 }, y)) + local ang = math.acos(math.clamp(y[2], -1, 1)) + Zs[i] = if l > 1e-12 then rotate({ 0, 0, 1 }, axis, ang) elseif y[2] < 0 then { 0, 0, -1 } else { 0, 0, 1 } + end + end + if i > 1 and Zs[i][1] * Zs[i - 1][1] + Zs[i][2] * Zs[i - 1][2] + Zs[i][3] * Zs[i - 1][3] < 0 then + Zs[i] = { -Zs[i][1], -Zs[i][2], -Zs[i][3] } + end + end + local nr = if closedSpine then ns - 1 else ns + local nring = if closedCs then nc - 1 else nc + local P = {} + for i = 1, nr do + local y, z = Ys[i], Zs[i] + local x = cross(y, z) + local si = if #sc >= i * 2 then i else 1 + local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1 + local oi = if #ori >= i * 4 then i else 1 + local ax, ang = norm({ ori[oi * 4 - 3] or 0, ori[oi * 4 - 2] or 0, ori[oi * 4 - 1] or 1 }), ori[oi * 4] or 0 + for j = 1, nring do + local v = { cs[j * 2 - 1] * sx, 0, cs[j * 2] * sz } + if ang ~= 0 then + v = rotate(v, ax, ang) + end + local s = spine[i] + table.insert(P, s[1] + x[1] * v[1] + y[1] * v[2] + z[1] * v[3]) + table.insert(P, s[2] + x[2] * v[1] + y[2] * v[2] + z[2] * v[3]) + table.insert(P, s[3] + x[3] * v[1] + y[3] * v[2] + z[3] * v[3]) + end + end + local corners, sizes = {}, {} + local function at(i: number, j: number): number + return ((i - 1) % nr) * nring + (j - 1) % nring + end + for i = 1, ns - 1 do + for j = 1, nc - 1 do + for _, c in { at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1) } do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + if not closedSpine then + if bool(n, "beginCap", true) then + for j = 1, nring do + table.insert(corners, at(1, j)) + end + table.insert(sizes, nring) + end + if bool(n, "endCap", true) then + for j = nring, 1, -1 do + table.insert(corners, at(ns, j)) + end + table.insert(sizes, nring) + end + end + return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV) +end + +-- ------------------------------------------------------------------------------------------------ lines, points +local function lines(n: any, maxV: number): (any, string?) + local P = points(n, "coord", "point") or {} + local np = #P // 3 + local C, cc = colors(n) + local perVertex = bool(n, "colorPerVertex", true) + local runs: { { number } } = {} + if n.type == "LineSet" then + local at = 0 + for _, c in nums(n, "vertexCount") or {} do + local r = {} + for q = 0, c - 1 do + r[q + 1] = at + q + end + at += c + table.insert(runs, r) + end + else + local corners, sizes = split(nums(n, "coordIndex") or {}) + local k = 0 + for _, s in sizes do + local r = {} + for q = 1, s do + r[q] = corners[k + q] + end + k += s + table.insert(runs, r) + end + end + local cIdx = nums(n, "colorIndex") or {} + local cList = if perVertex then cornerList(cIdx) else nil + local vkey: { [string]: number } = {} + local src: { { number } } = {} + local out: { number } = {} + local k = 0 + for li, r in runs do + local prev: number? = nil + for _, c in r do + k += 1 + if c == nil or c < 0 or c >= np then + prev = nil + continue + end + local ci = if not C then -1 elseif perVertex then (if cList then cList[k] or c else c) else (cIdx[li] or li - 1) + local key = c .. ":" .. ci + local v = vkey[key] + if not v then + v = #src + src[v + 1] = { c, ci } + vkey[key] = v + end + if prev then + table.insert(out, prev) + table.insert(out, v) + end + prev = v + end + end + if #src > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local pos = S.accessor(nil, "f32", 3, #src) + local col = if C then S.accessor(nil, "f32", cc, #src) else nil + for v, s in src do + for q = 0, 2 do + buffer.writef32(pos.data, ((v - 1) * 3 + q) * 4, P[s[1] * 3 + q + 1]) + end + if col and C then + for q = 0, cc - 1 do + buffer.writef32(col.data, ((v - 1) * cc + q) * 4, C[s[2] * cc + q + 1] or 1) + end + end + end + return { attributes = { POSITION = pos, COLOR_0 = col } :: any, indices = u32(out), mode = "lines" } +end + +local function pointSet(n: any, maxV: number): (any, string?) + local P = points(n, "coord", "point") or {} + local np = #P // 3 + if np > maxV then + return nil, "limit: more than " .. maxV .. " points" + end + local C, cc = colors(n) + local attrs: { [string]: Types.Accessor } = { POSITION = f32(P, 3, np) } + if C then + local col = S.accessor(nil, "f32", cc, np) + for i = 0, np * cc - 1 do + buffer.writef32(col.data, i * 4, C[i + 1] or 1) + end + attrs.COLOR_0 = col + end + return { attributes = attrs, mode = "points" } +end + +-- ------------------------------------------------------------------------------------------------ primitives +-- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles) +local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive + local nv = #P // 3 + if o.flipV ~= false then + for i = 2, #T, 2 do + T[i] = 1 - T[i] + end + end + return { + attributes = { POSITION = f32(P, 3, nv), NORMAL = f32(N, 3, nv), TEXCOORD_0 = f32(T, 2, nv) }, + indices = u32(I), + mode = "triangles", + } +end + +local function box(n: any, o: Options): Types.Primitive + local s = vec(n, "size", { 2, 2, 2 }) + local hx, hy, hz = s[1] / 2, s[2] / 2, s[3] / 2 + local P, N, T, I = {}, {}, {}, {} + -- faces: normal, u axis, v axis (the specification's texture orientation) + local FACES = { + { { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 } }, + { { 1, 0, 0 }, { 0, 0, -1 }, { 0, 1, 0 } }, { { -1, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } }, + { { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 } }, { { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, 1 } }, + } + for f, face in FACES do + local nn, u, v = face[1], face[2], face[3] + for _, c in { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } } do + for q = 1, 3 do + local h = if q == 1 then hx elseif q == 2 then hy else hz + table.insert(P, (nn[q] + u[q] * c[1] + v[q] * c[2]) * h) + table.insert(N, nn[q]) + end + table.insert(T, (c[1] + 1) / 2) + table.insert(T, (c[2] + 1) / 2) + end + local b = (f - 1) * 4 + for _, x in { 0, 1, 2, 0, 2, 3 } do + table.insert(I, b + x) + end + end + return direct(P, N, T, I, o) +end + +-- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z) +-- and runs counter-clockwise seen from +y +local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?) + for i = 0, segs do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + if N then + table.insert(N, x * (nr or 1)) + table.insert(N, ny or 0) + table.insert(N, z * (nr or 1)) + end + if T then + table.insert(T, i / segs) + table.insert(T, t) + end + end +end + +-- a cap disc at height y facing ny (+1 / -1) +local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number) + local b = #P // 3 + for i = 0, segs - 1 do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + table.insert(N, 0) + table.insert(N, ny) + table.insert(N, 0) + -- the specification maps the cap like a top view: s = x, t = -z (top) or z (bottom) + table.insert(T, x / 2 + 0.5) + table.insert(T, (if ny > 0 then -z else z) / 2 + 0.5) + end + for i = 1, segs - 2 do + -- the ring runs counter-clockwise seen from +y: in order for the top, reversed for the bottom + if ny > 0 then + table.insert(I, b) + table.insert(I, b + i) + table.insert(I, b + i + 1) + else + table.insert(I, b) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end + end +end + +-- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper) +local function band(I: { number }, a: number, b: number, segs: number) + for i = 0, segs - 1 do + table.insert(I, a + i) + table.insert(I, a + i + 1) + table.insert(I, b + i + 1) + table.insert(I, a + i) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end +end + +local function sphere(n: any, o: Options, segs: number): Types.Primitive + local r = num(n, "radius", 1) + local rings = math.max(2, segs // 2) + local P, N, T, I = {}, {}, {}, {} + for j = 0, rings do + local phi = pi * j / rings -- from the bottom + local y, rr = -cos(phi), sin(phi) + ring(P, N, T, segs, y * r, rr * r, j / rings, y, rr) + end + for j = 0, rings - 1 do + band(I, j * (segs + 1), (j + 1) * (segs + 1), segs) + end + return direct(P, N, T, I, o) +end + +local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types.Primitive + local r = num(n, if cone then "bottomRadius" else "radius", 1) + local h = num(n, "height", 2) + local P, N, T, I = {}, {}, {}, {} + if bool(n, "side", true) then + -- side normals: a cone's lean outwards by its slope + local l = sqrt(r * r + h * h) + local ny, nr = if cone and l > 0 then r / l else 0, if cone and l > 0 then h / l else 1 + ring(P, N, T, segs, -h / 2, r, 0, ny, nr) + ring(P, N, T, segs, h / 2, if cone then 0 else r, 1, ny, nr) + band(I, 0, segs + 1, segs) + end + if not cone and bool(n, "top", true) then + cap(P, N, T, I, segs, h / 2, r, 1) + end + if bool(n, "bottom", true) then + cap(P, N, T, I, segs, -h / 2, r, -1) + end + return direct(P, N, T, I, o) +end + +-- ------------------------------------------------------------------------------------------------ dispatch +-- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here); +-- the second value of a success is the node's solid flag +function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any) + local t = n.type + local maxV = o.maxVertices or 2 ^ 24 + local segs = math.clamp(math.floor(o.segments or 32), 3, 1024) + local solid = bool(n, "solid", true) + local prim: Types.Primitive?, err: string? = nil, nil + if t == "IndexedFaceSet" then + prim, err = faceSet(n, o, maxV) + elseif t == "IndexedTriangleSet" or t == "TriangleSet" or t == "IndexedTriangleFanSet" or t == "TriangleFanSet" or t == "IndexedTriangleStripSet" or t == "TriangleStripSet" or t == "IndexedQuadSet" or t == "QuadSet" then + prim, err = triSet(n, o, maxV) + elseif t == "ElevationGrid" then + prim, err = elevationGrid(n, o, maxV) + elseif t == "Extrusion" then + prim, err = extrusion(n, o, maxV) + elseif t == "IndexedLineSet" or t == "LineSet" then + prim, err = lines(n, maxV) + solid = false + elseif t == "PointSet" then + prim, err = pointSet(n, maxV) + solid = false + elseif t == "Box" then + prim = box(n, o) + elseif t == "Sphere" then + prim = sphere(n, o, segs) + elseif t == "Cylinder" then + prim = cylinder(n, o, segs, false) + elseif t == "Cone" then + prim = cylinder(n, o, segs, true) + else + return nil, nil + end + if not prim then + return nil, err + end + return prim, solid +end + +return Geometry diff --git a/src/Formats/codecs/model/Vrml/Parse.luau b/src/Formats/codecs/model/Vrml/Parse.luau new file mode 100644 index 0000000..8dd2ac5 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Parse.luau @@ -0,0 +1,536 @@ +--!strict +-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into +-- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are +-- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers, +-- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO +-- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside +-- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations, +-- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are +-- returned as nil, message ("line N: ..."). +local Parse = {} + +export type Node = { type: string, def: string?, fields: { [string]: any } } +export type Route = { from: Node, fromField: string, to: Node, toField: string } +export type Proto = { name: string, fields: { [string]: any }, body: { Node }, routes: { Route }, extern: boolean? } +export type Graph = { + roots: { Node }, + routes: { Route }, + header: { [string]: any }, -- version ("2.0" / "3.3" ...), encoding, x3d (boolean), profile + meta: { [string]: string }, -- META / WorldInfo statements + components: { string }, + units: { [string]: { name: string, factor: number } }, + protos: { [string]: Proto }, +} +-- an IS reference in a PROTO body: fields[name] = { is = "protoField" } +export type IsRef = { is: string } + +local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local ID1 = "^[^%c%s%d\"#',%+%-%.%[\\%]{}][^%c%s\"#',%.%[\\%]{}]*" +local MAX_DEPTH = 200 +local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true } +local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true } + +-- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared) +local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node + local done = memo[node] + if done then + return done + end + local out: Node = { type = node.type, def = node.def, fields = {} } + memo[node] = out + for k, v in node.fields do + if type(v) == "table" and type((v :: any).is) == "string" then + local name = (v :: any).is + local val = values[name] + if val == nil then + val = defaults[name] + end + out.fields[k] = val + elseif type(v) == "table" then + local arr = table.create(#v) + for i, x in v do + arr[i] = if type(x) == "table" and x.type then copy(x, values, defaults, memo) else x + end + out.fields[k] = arr + else + out.fields[k] = v + end + end + return out +end + +-- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO +function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node? + if proto.extern or #proto.body == 0 then + return nil + end + local memo = {} + local first: Node? = nil + for _, n in proto.body do + local c = copy(n, values, proto.fields, memo) + first = first or c + end + if routes then + for _, r in proto.routes do + local from, to = memo[r.from], memo[r.to] + if from and to then + table.insert(routes, { from = from, fromField = r.fromField, to = to, toField = r.toField }) + end + end + end + local f = first :: Node + if def then + -- the instance gets its own copy of the node so its DEF name is its own + local out: Node = { type = f.type, def = def, fields = f.fields } + return out + end + return f +end + +function Parse.parse(text: string): (Graph?, string?) + local n = #text + local p = 1 + local graph: Graph = { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} } + local defs: { [string]: Node } = {} + local protos: { [string]: Proto } = graph.protos + local routes: { Route } = graph.routes + local failure: string? = nil + local depth = 0 + + local function line(at: number): number + local l = 1 + for _ in gmatch(sub(text, 1, at), "\n") do + l += 1 + end + return l + end + local function fail(msg: string) + if not failure then + failure = "line " .. line(p) .. ": " .. msg + end + end + + -- header line: #VRML V2.0 utf8 / #X3D V3.3 utf8 + local v, enc = match(text, "^#VRML V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding = v, enc + if v ~= "2.0" then + return nil, "unsupported: VRML " .. v .. " (only VRML97 / X3D)" + end + else + v, enc = match(text, "^#X3D V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding, graph.header.x3d = v, enc, true + end + end + + -- the lexer: skip blanks, commas and comments; returns the next token kind and value + -- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof" + local function skip() + while true do + local q = find(text, "[^%s,]", p) + if not q then + p = n + 1 + return + end + p = q + if byte(text, p) == 35 then -- '#' + local e = find(text, "[\r\n]", p) + p = if e then e else n + 1 + else + return + end + end + end + local function token(): (string, any) + skip() + if p > n then + return "eof", nil + end + local c = byte(text, p) + if c == 123 or c == 125 or c == 91 or c == 93 then -- { } [ ] + p += 1 + return string.char(c), nil + elseif c == 34 then -- a string: \" and \\ escapes + local q = p + 1 + local parts = {} + while true do + local e = find(text, '["\\]', q) + if not e then + fail("unterminated string") + p = n + 1 + return "eof", nil + end + table.insert(parts, sub(text, q, e - 1)) + if byte(text, e) == 92 then + table.insert(parts, sub(text, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + return "str", table.concat(parts) + end + end + end + if (c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46 then + local s, e = find(text, "^[+-]?0[xX]%x+", p) + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*[eE][+-]?%d+", p) + end + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*", p) + end + local num = tonumber(sub(text, p, e)) + if num then + p = (e :: number) + 1 + return "num", num + end + if c == 46 then + p += 1 + return ".", nil + end + -- +inf / -nan style words: read the word + local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) + local w = sub(text, p, we) + p = (we :: number) + 1 + local wl = string.lower(w) + local val = if find(wl, "inf", 1, true) then (if c == 45 then -math.huge else math.huge) elseif find(wl, "nan", 1, true) then 0 else nil + if val == nil then + fail("bad number " .. w) + return "eof", nil + end + return "num", val + end + local s, e = find(text, ID1, p) + if s then + p = (e :: number) + 1 + return "id", sub(text, s, e) + end + fail("unexpected character " .. sub(text, p, p)) + p = n + 1 + return "eof", nil + end + local function peek(): (string, any) + local save = p + local k, val = token() + p = save + return k, val + end + + local parseNode: (first: string) -> (Node?, boolean) + local parseProto: (extern: boolean) -> () + local parseRoute: () -> () + + -- a field value (after its name): an array of numbers / strings / booleans / nodes + local function value(): any + local k, val = token() + if k == "[" then + local out = {} + -- fast path: a bracket of plain numbers (big coordinate arrays) + local close = find(text, "]", p, true) + if close then + local seg = sub(text, p, close - 1) + if not find(seg, "[{}\"#]") then + local ok = true + for w in gmatch(seg, "[^%s,]+") do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "TRUE" or w == "FALSE" then + table.insert(out, w == "TRUE") + else + ok = false + break + end + end + if ok then + p = close + 1 + return out + end + table.clear(out) + end + end + while not failure do + k, val = token() + if k == "]" then + return out + elseif k == "num" or k == "str" then + table.insert(out, val) + elseif k == "id" and (val == "TRUE" or val == "FALSE") then + table.insert(out, val == "TRUE") + elseif k == "id" and val == "NULL" then + continue + elseif k == "id" then + local node = parseNode(val) + if node then + table.insert(out, node) + end + else + fail("unexpected " .. k .. " in a [ ] value") + return out + end + end + return out + elseif k == "num" then + local out = { val } + while true do + local save = p + local k2, v2 = token() + if k2 ~= "num" then + p = save + break + end + table.insert(out, v2) + end + return out + elseif k == "str" then + return { val } + elseif k == "id" then + if val == "TRUE" or val == "FALSE" then + return { val == "TRUE" } + elseif val == "NULL" then + return {} + end + local node = parseNode(val) + return if node then { node } else {} + end + fail("missing field value") + return {} + end + + -- the fields of a node body, up to its "}" + local function body(node: Node) + while not failure do + local k, name = token() + if k == "}" then + return + elseif k ~= "id" then + fail("expected a field name in " .. node.type .. ", got " .. k) + return + end + if name == "ROUTE" then + parseRoute() + elseif name == "PROTO" or name == "EXTERNPROTO" then + parseProto(name == "EXTERNPROTO") + elseif DECL[name] then + -- Script / shader interface: [ | IS ] + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad interface declaration in " .. node.type) + return + end + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[fname] = { is = ref } + elseif HAS_VALUE[name] then + node.fields[fname] = value() + end + else + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[name] = { is = ref } + else + node.fields[name] = value() + end + end + end + end + + -- a node statement starting with the id `first` (DEF name Type { }, USE name, Type { }) + function parseNode(first: string): (Node?, boolean) + if first == "USE" then + local k, name = token() + if k ~= "id" then + fail("USE without a name") + return nil, false + end + local node = defs[name] + if not node then + fail("USE of an undefined name " .. tostring(name)) + end + return node, true + end + local def: string? = nil + local typ = first + if first == "DEF" then + local k, name = token() + local k2, t2 = token() + if k ~= "id" or k2 ~= "id" then + fail("bad DEF") + return nil, false + end + def, typ = name, t2 + end + local k = token() + if k ~= "{" then + fail("expected { after " .. typ) + return nil, false + end + depth += 1 + if depth > MAX_DEPTH then + fail("limit: nodes nested deeper than " .. MAX_DEPTH) + return nil, false + end + local node: Node = { type = typ, def = def, fields = {} } + body(node) + depth -= 1 + local proto = protos[typ] + if proto and not proto.extern then + local inst = Parse.expand(proto, node.fields, def, routes) + if inst then + node = inst + end + elseif proto then + (node :: any).extern = true + end + if def then + defs[def] = node + end + return node, false + end + + -- ROUTE from.field TO to.field + function parseRoute() + local function path(): (string?, string?) + local k1, a = token() + local k2 = token() + local k3, b = token() + if k1 ~= "id" or k2 ~= "." or k3 ~= "id" then + return nil, nil + end + return a, b + end + local a, af = path() + local k, to = token() + local b, bf = path() + if not (a and af and b and bf) or k ~= "id" or to ~= "TO" then + fail("bad ROUTE") + return + end + local from, dst = defs[a :: string], defs[b :: string] + if from and dst then + table.insert(routes, { from = from, fromField = af :: string, to = dst, toField = bf :: string }) + end + end + + -- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url + function parseProto(extern: boolean) + local k, name = token() + if k ~= "id" or token() ~= "[" then + fail("bad PROTO") + return + end + local proto: Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + while not failure do + local k2, access = token() + if k2 == "]" then + break + elseif k2 ~= "id" or not DECL[access] then + fail("bad PROTO interface") + return + end + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad PROTO interface") + return + end + if HAS_VALUE[access] and not extern then + proto.fields[fname] = value() + end + end + if extern then + value() -- the url list + protos[name] = proto + return + end + if token() ~= "{" then + fail("PROTO " .. tostring(name) .. " without a body") + return + end + -- the body has its own DEF names and its own routes + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + while not failure do + local k3, w = token() + if k3 == "}" then + break + elseif k3 ~= "id" then + fail("bad PROTO body") + break + elseif w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + else + local node = parseNode(w) + if node then + table.insert(proto.body, node) + end + end + end + defs, routes = outerDefs, outerRoutes + protos[name] = proto + end + + -- statements + while not failure do + local k, w = token() + if k == "eof" then + break + elseif k ~= "id" then + fail("unexpected " .. k) + break + end + if w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + elseif w == "PROFILE" then + local _, prof = token() + graph.header.profile = prof + elseif w == "COMPONENT" then + local _, comp = token() -- name:level is one id + table.insert(graph.components, tostring(comp)) + elseif w == "META" then + local _, key = token() + local _, val = token() + graph.meta[tostring(key)] = tostring(val) + elseif w == "UNIT" then + local _, cat = token() + local _, uname = token() + local _, factor = token() + if type(cat) == "string" and type(factor) == "number" then + graph.units[cat] = { name = tostring(uname), factor = factor } + end + elseif w == "IMPORT" or w == "EXPORT" then + -- IMPORT inline.name AS name / EXPORT name AS name: no effect on the scene + local _, _a = token() + if peek() == "." then + token() + token() + end + local pk, pv = peek() + if pk == "id" and pv == "AS" then + token() + token() + end + else + local node = parseNode(w) + if node then + table.insert(graph.roots, node) + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return Parse diff --git a/src/Formats/codecs/model/Vrml/Write.luau b/src/Formats/codecs/model/Vrml/Write.luau new file mode 100644 index 0000000..8c0ad97 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Write.luau @@ -0,0 +1,750 @@ +--!strict +-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text, +-- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS; +-- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal, +-- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines -> +-- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material +-- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of +-- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or +-- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights -> +-- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and +-- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped). +-- Never throws: returns nil, message. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") +local Xml = require("@formats/codecs/text/Xml") + +local Write = {} + +export type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? } + +-- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers +-- per line), "bool", "str", "mstr" (MFString), "node", "nodes" +type WNode = { type: string, def: string?, use: string?, fields: { { any } } } + +local format, concat = string.format, table.concat + +local function fmt(v: number): string + if v ~= v then + return "0" + elseif v == math.huge then + return "1e38" + elseif v == -math.huge then + return "-1e38" + elseif v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return format("%d", v) + end + return format("%.9g", v) +end + +local function W(t: string, def: string?): WNode + return { type = t, def = def, fields = {} } +end +local function F(n: WNode, name: string, kind: string, value: any, per: number?) + table.insert(n.fields, { name, kind, value, per }) +end + +-- names: valid, unique DEF names +local function namer(): (string?, string) -> string + local used: { [string]: boolean } = {} + return function(name: string?, fallback: string): string + local s = string.gsub(name or "", "[^%w_]", "_") + if s == "" or string.find(s, "^%d") then + s = fallback .. (if s ~= "" then "_" .. s else "") + end + local base, k = s, 1 + while used[s] do + k += 1 + s = base .. "_" .. k + end + used[s] = true + return s + end +end + +-- axis-angle of a quaternion (x, y, z, w) +local function axisAngle(q: { number }): { number } + local x, y, z, w = q[1], q[2], q[3], q[4] + local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + local s = math.sqrt(math.max(0, 1 - w * w)) + if s < 1e-9 then + return { 0, 0, 1, 0 } + end + return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function values(acc: any): { number }? + return (Flatten.numbers(acc)) +end + +local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean): (WNode?, string?) + local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } } + local keep = function(n: string): boolean + return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0" + end + local m, err = Flatten.merge(tmp, keep, { triangulate = false }) + if not m then + return nil, err + end + if not m.sizes or #m.sizes == 0 then + return nil, nil + end + local g = W("IndexedFaceSet") + local coord = W("Coordinate") + F(coord, "point", "mf", m.attrs.POSITION.values, 3) + F(g, "coord", "node", coord) + local idx = {} + local p = 0 + for _, s in m.sizes do + for k = 1, s do + table.insert(idx, m.corners[p + k]) + end + table.insert(idx, -1) + p += s + end + F(g, "coordIndex", "mf", idx, 0) + local nrm = m.attrs.NORMAL + if nrm then + local nn = W("Normal") + F(nn, "vector", "mf", nrm.values, 3) + F(g, "normal", "node", nn) + end + local tc = m.attrs.TEXCOORD_0 + if tc then + local t = W("TextureCoordinate") + local vals, c = {}, tc.components + for i = 0, m.count - 1 do + local s, tt = tc.values[i * c + 1], tc.values[i * c + 2] + table.insert(vals, s) + table.insert(vals, if o.flipV ~= false then 1 - tt else tt) + end + F(t, "point", "mf", vals, 2) + F(g, "texCoord", "node", t) + end + local col = m.attrs.COLOR_0 + if col then + local c = col.components + local rgba = c >= 4 and x3d + local cn = W(if rgba then "ColorRGBA" else "Color") + local vals = {} + local scale = if col.raw then (if col.type == "unorm8" then 255 elseif col.type == "unorm16" then 65535 else 1) else 1 + for i = 0, m.count - 1 do + for k = 1, if rgba then 4 else 3 do + table.insert(vals, (col.values[i * c + k] or 1) / scale) + end + end + F(cn, "color", "mf", vals, if rgba then 4 else 3) + F(g, "color", "node", cn) + end + F(g, "solid", "bool", not doubleSided) + return g, nil +end + +-- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points) +local function coordNode(prim: any): (WNode?, number) + local pos = values(prim.attributes.POSITION) + if not pos then + return nil, 0 + end + local nv, pc = prim.attributes.POSITION.count, prim.attributes.POSITION.components + local p3 = {} + for i = 0, nv - 1 do + for k = 1, 3 do + table.insert(p3, pos[i * pc + k] or 0) + end + end + local coord = W("Coordinate") + F(coord, "point", "mf", p3, 3) + return coord, nv +end +local function colorNode(prim: any, nv: number, x3d: boolean): WNode? + local acc = prim.attributes.COLOR_0 + local col = acc and values(acc) + if not col then + return nil + end + local c = acc.components + local rgba = c >= 4 and x3d + local vals = {} + for i = 0, nv - 1 do + for k = 1, if rgba then 4 else 3 do + table.insert(vals, col[i * c + k] or 1) + end + end + local cn = W(if rgba then "ColorRGBA" else "Color") + F(cn, "color", "mf", vals, if rgba then 4 else 3) + return cn +end + +local function lineSet(prim: any, x3d: boolean): (WNode?, string?) + local coord, nv = coordNode(prim) + if not coord then + return nil, "lines without POSITION" + end + local ind: { number } + if prim.indices then + ind = values(prim.indices) or {} + else + ind = {} + for i = 0, nv - 1 do + ind[i + 1] = i + end + end + local idx = {} + local mode = prim.mode + if mode == "lines" then + for i = 1, #ind - 1, 2 do + table.insert(idx, ind[i]) + table.insert(idx, ind[i + 1]) + table.insert(idx, -1) + end + else + for _, v in ind do + table.insert(idx, v) + end + if mode == "line_loop" and #ind > 0 then + table.insert(idx, ind[1]) + end + table.insert(idx, -1) + end + for _, v in idx do + if v >= nv then + return nil, "line index out of range" + end + end + local g = W("IndexedLineSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + F(g, "coordIndex", "mf", idx, 0) + return g, nil +end + +local function pointSet(prim: any, x3d: boolean): (WNode?, string?) + local coord, nv = coordNode(prim) + if not coord then + return nil, "points without POSITION" + end + local g = W("PointSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + return g, nil +end + +-- ------------------------------------------------------------------------------------------------ materials +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" } + +local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string? + if written[i] then + return written[i] + end + local tex = scene.textures[i] + if not tex then + return nil + end + local url = tex.uri + if tex.data and type(o.files) == "table" then + local base = string.match(o.name or "model", "([^/\\]+)$") or "model" + base = string.gsub(base, "%.[^.]*$", "") + local ext = EXT[tex.mime or ""] or (url and string.match(url, "%.(%w+)$")) or "png" + local file = if url and not string.find(url, "^data:") and not string.find(url, "[/\\]") then url else format("%s_%d.%s", base, i, ext) + o.files[file] = tex.data + url = file + end + if url then + written[i] = url + end + return url +end + +local function appearance(scene: any, mi: number, o: Options, written: { [number]: string }): WNode + local m = scene.materials[mi] + local app = W("Appearance") + local mat = W("Material") + local x = m.extras and m.extras.vrml or {} + local c = m.baseColor or { 1, 1, 1, 1 } + F(mat, "diffuseColor", "sf", { c[1], c[2], c[3] }) + local e = m.emissive or { 0, 0, 0 } + if e[1] ~= 0 or e[2] ~= 0 or e[3] ~= 0 then + F(mat, "emissiveColor", "sf", { e[1], e[2], e[3] }) + end + if type(x.specularColor) == "table" then + F(mat, "specularColor", "sf", x.specularColor) + end + local sh = x.shininess + if type(sh) ~= "number" then + local r = math.max(m.roughness or 1, 1e-3) + sh = math.clamp((2 / (r * r) - 2) / 128, 0, 1) + end + F(mat, "shininess", "sf", { sh }) + if type(x.ambientIntensity) == "number" then + F(mat, "ambientIntensity", "sf", { x.ambientIntensity }) + end + if (c[4] or 1) < 1 then + F(mat, "transparency", "sf", { 1 - c[4] }) + end + F(app, "material", "node", mat) + local ref = m.baseColorTexture + if ref and type(ref.texture) == "number" then + local url = textureUrl(scene, ref.texture, o, written) + local img = scene.textures[ref.texture] and scene.textures[ref.texture].image + if url or (img and img.format == "rgba8" and img.width * img.height <= 2 ^ 20) then + local it + if url then + it = W("ImageTexture") + F(it, "url", "mstr", { url }) + else + -- a decoded image only: PixelTexture (SFImage: width height 4, then 0xRRGGBBAA from the bottom row up) + it = W("PixelTexture") + local w, h = img.width, img.height + local v = { w, h, 4 } + for row = h - 1, 0, -1 do + for x = 0, w - 1 do + table.insert(v, buffer.readu32(img.pixels, (row * w + x) * 4)) + end + end + -- the pixels are little-endian RGBA bytes: swap to 0xRRGGBBAA + for i = 4, #v do + local p = v[i] + v[i] = (p % 256) * 16777216 + (p // 256 % 256) * 65536 + (p // 65536 % 256) * 256 + p // 16777216 + end + F(it, "image", "sf", v) + end + local s = scene.textures[ref.texture].sampler + if s and s.wrapS == "clamp" then + F(it, "repeatS", "bool", false) + end + if s and s.wrapT == "clamp" then + F(it, "repeatT", "bool", false) + end + F(app, "texture", "node", it) + local tf = ref.transform + if tf then + local tt = W("TextureTransform") + if tf.offset then + F(tt, "translation", "sf", tf.offset) + end + if tf.scale then + F(tt, "scale", "sf", tf.scale) + end + if tf.rotation then + F(tt, "rotation", "sf", { tf.rotation }) + end + F(app, "textureTransform", "node", tt) + end + end + end + return app +end + +-- ------------------------------------------------------------------------------------------------ the tree +function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?) + local x3d = o.encoding == "x3dv" or o.encoding == "xml" + local name = namer() + local nodeDef: { [number]: string } = {} + local meshShapes: { [number]: { WNode } } = {} + local appDef: { [any]: string } = {} + local written: { [number]: string } = {} + local failure: string? = nil + + local function shapes(mi: number): { WNode } + local done = meshShapes[mi] + if done then + -- USE the shapes written before + local out = {} + for _, s in done do + table.insert(out, { type = "Shape", use = s.def, fields = {} }) + end + return out + end + local mesh = scene.meshes[mi] + local out = {} + for pi, prim in (if mesh then mesh.primitives else {}) :: { any } do + local mode = prim.mode or "triangles" + local mat = if type(prim.material) == "number" then scene.materials[prim.material] else nil + local geo, err + if mode == "lines" or mode == "line_strip" or mode == "line_loop" then + geo, err = lineSet(prim, x3d) + elseif mode == "points" then + geo, err = pointSet(prim, x3d) + else + geo, err = faceSet(prim, mat ~= nil and mat.doubleSided == true, o, x3d) + end + if err then + failure = failure or err + end + if geo then + local sh = W("Shape", name((mesh.name or "mesh") .. (if #mesh.primitives > 1 then "_" .. pi else ""), "Shape")) + if mat then + local key = prim.material + if appDef[key] then + F(sh, "appearance", "node", { type = "Appearance", use = appDef[key], fields = {} }) + else + local app = appearance(scene, prim.material, o, written) + app.def = name(mat.name, "Material") + appDef[key] = app.def + F(sh, "appearance", "node", app) + end + end + F(sh, "geometry", "node", geo) + table.insert(out, sh) + end + end + meshShapes[mi] = out + return out + end + + local visiting: { [number]: boolean } = {} + local function transform(ni: number): WNode? + local n = scene.nodes[ni] + if type(n) ~= "table" or visiting[ni] then + return nil + end + visiting[ni] = true + local def = name(n.name, "Node") + nodeDef[ni] = def + local t = W("Transform", def) + local tr, rot, sc = n.translation, n.rotation, n.scale + if n.matrix then + tr, rot, sc = Mat4.decompose(n.matrix) + end + if tr and (tr[1] ~= 0 or tr[2] ~= 0 or tr[3] ~= 0) then + F(t, "translation", "sf", { tr[1], tr[2], tr[3] }) + end + if rot then + local aa = axisAngle(rot) + if aa[4] ~= 0 then + F(t, "rotation", "sf", aa) + end + end + if sc and (sc[1] ~= 1 or sc[2] ~= 1 or sc[3] ~= 1) then + F(t, "scale", "sf", { sc[1], sc[2], sc[3] }) + end + local kids: { WNode } = {} + if type(n.mesh) == "number" then + for _, s in shapes(n.mesh) do + table.insert(kids, s) + end + end + local cam = if type(n.camera) == "number" then scene.cameras[n.camera] else nil + if cam then + local v + if cam.type == "orthographic" and x3d then + v = W("OrthoViewpoint") + local xm, ym = cam.xmag or 1, cam.ymag or 1 + F(v, "fieldOfView", "sf", { -xm, -ym, xm, ym }) + else + v = W("Viewpoint") + F(v, "fieldOfView", "sf", { cam.yfov or 0.785398 }) + end + F(v, "position", "sf", { 0, 0, 0 }) + if cam.name then + F(v, "description", "str", cam.name) + end + table.insert(kids, v) + end + local l = if type(n.light) == "number" then scene.lights[n.light] else nil + if l then + local typ = if l.type == "directional" then "DirectionalLight" elseif l.type == "spot" then "SpotLight" else "PointLight" + local ln = W(typ) + local c = l.color or { 1, 1, 1 } + F(ln, "color", "sf", { c[1], c[2], c[3] }) + F(ln, "intensity", "sf", { math.clamp(l.intensity or 1, 0, 1) }) + if typ ~= "PointLight" then + F(ln, "direction", "sf", { 0, 0, -1 }) + end + if typ ~= "DirectionalLight" then + F(ln, "location", "sf", { 0, 0, 0 }) + F(ln, "radius", "sf", { l.range or 100 }) + end + if typ == "SpotLight" then + F(ln, "cutOffAngle", "sf", { l.outerCone or 0.785398 }) + F(ln, "beamWidth", "sf", { l.innerCone or 0 }) + end + table.insert(kids, ln) + end + for _, c in n.children or {} do + local ct = transform(c) + if ct then + table.insert(kids, ct) + end + end + if #kids > 0 then + F(t, "children", "nodes", kids) + end + visiting[ni] = nil + return t + end + + local roots: { WNode } = {} + local list = scene.roots + if type(list) ~= "table" or #list == 0 then + -- no roots: every node without a parent + local child = {} + for _, n in scene.nodes do + for _, c in n.children or {} do + child[c] = true + end + end + list = {} + for i = 1, #scene.nodes do + if not child[i] then + table.insert(list, i) + end + end + end + for _, ri in list do + local t = transform(ri) + if t then + table.insert(roots, t) + end + end + if #scene.nodes == 0 then + for mi = 1, #scene.meshes do + for _, s in shapes(mi) do + table.insert(roots, s) + end + end + end + + -- animations: a TimeSensor per animation, an interpolator per channel + local routes: { { string } } = {} + for ai, anim in scene.animations or {} do + local tmax = 0 + local chans = {} + for _, ch in anim.channels or {} do + local target = nodeDef[ch.node] + if target and (ch.path == "translation" or ch.path == "rotation" or ch.path == "scale") then + local input, output = values(ch.input), values(ch.output) + if input and output and #input > 0 then + tmax = math.max(tmax, input[#input]) + table.insert(chans, { ch, target, input, output }) + end + end + end + if #chans > 0 then + local cycle = if tmax > 0 then tmax else 1 + local ts = W("TimeSensor", name(anim.name, "Animation" .. ai)) + F(ts, "cycleInterval", "sf", { cycle }) + F(ts, "loop", "bool", true) + table.insert(roots, ts) + for k, c in chans do + local ch, target, input, output = c[1], c[2], c[3], c[4] + local rot = ch.path == "rotation" + local it = W(if rot then "OrientationInterpolator" else "PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator")) + local keys = {} + for i, tv in input do + keys[i] = tv / cycle + end + local comps = if rot then 4 else 3 + local stride = #output // #input + -- CUBICSPLINE stores in-tangent, value, out-tangent per key + local off = if ch.interpolation == "CUBICSPLINE" and stride == comps * 3 then comps else 0 + local kv = {} + for i = 0, #input - 1 do + local v = {} + for q = 1, comps do + v[q] = output[i * stride + off + q] or 0 + end + if rot then + v = axisAngle(v) + end + for _, x in v do + table.insert(kv, x) + end + end + F(it, "key", "mf", keys, 0) + F(it, "keyValue", "mf", kv, comps) + table.insert(roots, it) + table.insert(routes, { ts.def :: string, "fraction_changed", it.def :: string, "set_fraction" }) + table.insert(routes, { it.def :: string, "value_changed", target, "set_" .. ch.path }) + end + end + end + if failure then + return nil, nil, failure + end + return roots, routes, nil +end + +-- ------------------------------------------------------------------------------------------------ serializers +local function numbers(vals: { number }, per: number?, indent: string): string + local out = table.create(#vals) + for i, v in vals do + out[i] = fmt(v) + end + if per == 0 then + -- index lists: one face per line + local lines, cur = {}, {} + for i, v in vals do + table.insert(cur, out[i]) + if v == -1 then + table.insert(lines, concat(cur, " ")) + cur = {} + end + end + if #cur > 0 then + table.insert(lines, concat(cur, " ")) + end + return concat(lines, "\n" .. indent) + end + if per and per > 0 then + local lines = {} + for i = 1, #out, per do + table.insert(lines, concat(out, " ", i, math.min(i + per - 1, #out))) + end + return concat(lines, ",\n" .. indent) + end + return concat(out, " ") +end + +local function quote(s: string): string + return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"' +end + +local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): string + local out = {} + if x3d then + table.insert(out, "#X3D V3.3 utf8\nPROFILE Interchange\n# written by formats-luau\n") + else + table.insert(out, "#VRML V2.0 utf8\n# written by formats-luau\n") + end + local function emit(n: WNode, ind: string): string + if n.use then + return "USE " .. n.use + end + local parts = { (if n.def then "DEF " .. n.def .. " " else "") .. n.type .. " {" } + local ind2 = ind .. " " + for _, f in n.fields do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + local s + if kind == "sf" then + s = numbers(v, nil, ind2) + elseif kind == "mf" then + s = "[\n" .. ind2 .. " " .. numbers(v, per, ind2 .. " ") .. "\n" .. ind2 .. "]" + elseif kind == "bool" then + s = if v then "TRUE" else "FALSE" + elseif kind == "str" then + s = quote(v) + elseif kind == "mstr" then + local q = {} + for i, x in v do + q[i] = quote(x) + end + s = "[ " .. concat(q, " ") .. " ]" + elseif kind == "node" then + s = emit(v, ind2) + else + local q = {} + for i, x in v do + q[i] = ind2 .. " " .. emit(x, ind2 .. " ") + end + s = "[\n" .. concat(q, "\n") .. "\n" .. ind2 .. "]" + end + table.insert(parts, ind2 .. fname .. " " .. s) + end + table.insert(parts, ind .. "}") + return concat(parts, "\n") + end + for _, r in roots do + table.insert(out, emit(r, "")) + end + for _, r in routes do + table.insert(out, format("ROUTE %s.%s TO %s.%s", r[1], r[2], r[3], r[4])) + end + return concat(out, "\n") .. "\n" +end + +-- the containerField a child element needs when it is not its type's default +local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" } + +local function xml(roots: { WNode }, routes: { { string } }): (string?, string?) + local function element(n: WNode, field: string): any + local attrs = Types.object() + local kids = {} + if (DEFAULT[n.type] or "children") ~= field then + Types.set(attrs, "containerField", field) + end + if n.use then + Types.set(attrs, "USE", n.use) + return Xml.element(n.type, attrs :: any) + end + if n.def then + Types.set(attrs, "DEF", n.def) + end + for _, f in n.fields do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + if kind == "sf" then + Types.set(attrs, fname, numbers(v, nil, "")) + elseif kind == "mf" then + local s = numbers(v, per, "") + Types.set(attrs, fname, (string.gsub(s, "\n", " "))) + elseif kind == "bool" then + Types.set(attrs, fname, if v then "true" else "false") + elseif kind == "str" then + Types.set(attrs, fname, v) + elseif kind == "mstr" then + local q = {} + for i, x in v do + q[i] = quote(x) + end + Types.set(attrs, fname, concat(q, " ")) + elseif kind == "node" then + table.insert(kids, element(v, fname)) + else + for _, x in v do + table.insert(kids, element(x, fname)) + end + end + end + return Xml.element(n.type, attrs :: any, kids) + end + local sceneKids = {} + for _, r in roots do + table.insert(sceneKids, element(r, "children")) + end + for _, r in routes do + local a = Types.object() + Types.set(a, "fromNode", r[1]) + Types.set(a, "fromField", r[2]) + Types.set(a, "toNode", r[3]) + Types.set(a, "toField", r[4]) + table.insert(sceneKids, Xml.element("ROUTE", a :: any)) + end + local ra = Types.object() + Types.set(ra, "profile", "Interchange") + Types.set(ra, "version", "3.3") + local meta = Types.object() + Types.set(meta, "name", "generator") + Types.set(meta, "content", "formats-luau") + local root = Xml.element("X3D", ra :: any, { Xml.element("head", nil, { Xml.element("meta", meta :: any) }), Xml.element("Scene", nil, sceneKids) }) + local s, err = Xml.encode(Xml.document(root, { version = "1.0", encoding = "UTF-8" }), { indent = 2 }) + if not s then + return nil, if err then err.message else "xml" + end + return s, nil +end + +-- text(scene, opts) -> the file text +function Write.text(scene: any, o: Options): (string?, string?) + local roots, routes, err = Write.graph(scene, o) + if not roots or not routes then + return nil, err + end + if o.encoding == "xml" then + return xml(roots, routes) + end + return classic(roots, routes, o.encoding == "x3dv"), nil +end + +return Write diff --git a/src/Formats/codecs/model/Vrml/Xml.luau b/src/Formats/codecs/model/Vrml/Xml.luau new file mode 100644 index 0000000..93066e8 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Xml.luau @@ -0,0 +1,238 @@ +--!strict +-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one +-- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes; +-- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their +-- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE; +-- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and +-- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head / +-- meta, UNIT, component and the profile go into the graph header. Never throws. +local Xml = require("@formats/codecs/text/Xml") +local Parse = require("@formats/codecs/model/Vrml/Parse") + +local VXml = {} + +local GEOMETRY = { + "Box", "Sphere", "Cone", "Cylinder", "IndexedFaceSet", "IndexedLineSet", "LineSet", "PointSet", "ElevationGrid", + "Extrusion", "Text", "IndexedTriangleSet", "TriangleSet", "IndexedTriangleFanSet", "TriangleFanSet", + "IndexedTriangleStripSet", "TriangleStripSet", "IndexedQuadSet", "QuadSet", "Arc2D", "ArcClose2D", "Circle2D", + "Disk2D", "Polyline2D", "Polypoint2D", "Rectangle2D", "TriangleSet2D", "GeoElevationGrid", "NurbsPatchSurface", +} +local CONTAINER: { [string]: string } = { + Appearance = "appearance", Material = "material", PhysicalMaterial = "material", TwoSidedMaterial = "material", + UnlitMaterial = "material", ImageTexture = "texture", PixelTexture = "texture", MovieTexture = "texture", + MultiTexture = "texture", ImageCubeMapTexture = "texture", TextureTransform = "textureTransform", + Coordinate = "coord", CoordinateDouble = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", + TextureCoordinate = "texCoord", MultiTextureCoordinate = "texCoord", TextureCoordinateGenerator = "texCoord", + FontStyle = "fontStyle", TextureProperties = "textureProperties", FillProperties = "fillProperties", + LineProperties = "lineProperties", +} +for _, g in GEOMETRY do + CONTAINER[g] = "geometry" +end + +local function container(el: Xml.Node, typ: string): string + local c = el.attrs.containerField + if type(c) == "string" and c ~= "" then + return c + end + if string.sub(typ, 1, 8) == "Metadata" then + return "metadata" + end + return CONTAINER[typ] or "children" +end + +function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?) + local root = doc.root or doc + if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then + return nil, "no root element" + end + local graph: Parse.Graph = { roots = {}, routes = {}, header = { x3d = true, xml = true }, meta = {}, components = {}, units = {}, protos = {} } + graph.header.version, graph.header.profile = root.attrs.version, root.attrs.profile + local defs: { [string]: Parse.Node } = {} + local protos = graph.protos + local routes = graph.routes + local depth = 0 + local failure: string? = nil + + local convert: (el: Xml.Node) -> Parse.Node? + local function route(el: Xml.Node) + local a = el.attrs + local from, to = defs[a.fromNode or ""], defs[a.toNode or ""] + local ff, tf = a.fromField, a.toField + if from and to and type(ff) == "string" and type(tf) == "string" then + table.insert(routes, { from = from, fromField = ff, to = to, toField = tf }) + end + end + local declare: (el: Xml.Node, extern: boolean) -> () + + -- the child elements of a node into its fields + local function children(el: Xml.Node, node: Parse.Node) + for _, ch in el.children do + if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then + continue + end + local name = Xml.localName(ch.name) + if name == "ROUTE" then + route(ch) + elseif name == "IS" then + for _, c in Xml.children(ch, "connect") do + local nf, pf = c.attrs.nodeField, c.attrs.protoField + if nf and pf then + node.fields[nf] = { is = pf } + end + end + elseif name == "ProtoDeclare" or name == "ExternProtoDeclare" then + declare(ch, name == "ExternProtoDeclare") + elseif name == "field" or name == "fieldValue" then + continue -- Script / shader interfaces + else + local c = convert(ch) + if c then + local f = container(ch, if name == "ProtoInstance" then "" else name) + local list = node.fields[f] + if type(list) ~= "table" or (list :: any).is then + list = {} + node.fields[f] = list + end + table.insert(list, c) + end + end + end + end + + -- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes + local function fieldValue(el: Xml.Node): any + if el.attrs.value ~= nil then + return el.attrs.value + end + local list = {} + for _, ch in el.children do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local c = convert(ch) + if c then + table.insert(list, c) + end + end + end + return list + end + + function declare(el: Xml.Node, extern: boolean) + local name = el.attrs.name + if not name then + return + end + local proto: Parse.Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + local iface = if extern then el else Xml.child(el, "ProtoInterface") + if iface then + for _, f in Xml.children(iface, "field") do + if f.attrs.name then + proto.fields[f.attrs.name] = fieldValue(f) + end + end + end + local bodyEl = Xml.child(el, "ProtoBody") + if bodyEl and not extern then + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + for _, ch in bodyEl.children do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local nm = Xml.localName(ch.name) + if nm == "ROUTE" then + route(ch) + elseif nm == "ProtoDeclare" or nm == "ExternProtoDeclare" then + declare(ch, nm == "ExternProtoDeclare") + else + local c = convert(ch) + if c then + table.insert(proto.body, c) + end + end + end + end + defs, routes = outerDefs, outerRoutes + end + protos[name] = proto + end + + function convert(el: Xml.Node): Parse.Node? + local a = el.attrs + if a.USE then + return defs[a.USE] + end + depth += 1 + if depth > 200 then + failure = failure or "limit: nodes nested deeper than 200" + depth -= 1 + return nil + end + local typ = Xml.localName(el.name) + local node: any + if typ == "ProtoInstance" then + local proto = protos[a.name or ""] + local values = {} + for _, fv in Xml.children(el, "fieldValue") do + if fv.attrs.name then + values[fv.attrs.name] = fieldValue(fv) + end + end + local inst = proto and Parse.expand(proto, values, a.DEF, routes) + node = inst or { type = a.name or "ProtoInstance", def = a.DEF, fields = values } + else + node = { type = typ, def = a.DEF, fields = {} } + for k, v in a do + if k ~= "DEF" and k ~= "USE" and k ~= "containerField" and k ~= "class" and not string.find(k, ":", 1, true) then + node.fields[k] = v + end + end + children(el, node) + end + depth -= 1 + if a.DEF then + defs[a.DEF] = node + end + return node + end + + for _, ch in root.children do + if type(ch) ~= "table" then + continue + end + local name = Xml.localName(ch.name) + if name == "head" then + for _, h in ch.children do + if type(h) == "table" then + local hn = Xml.localName(h.name) + if hn == "meta" and h.attrs.name then + graph.meta[h.attrs.name] = h.attrs.content or "" + elseif hn == "component" and h.attrs.name then + table.insert(graph.components, h.attrs.name .. ":" .. (h.attrs.level or "1")) + elseif hn == "unit" and h.attrs.category then + graph.units[h.attrs.category] = { name = h.attrs.name or "", factor = tonumber(h.attrs.conversionFactor) or 1 } + end + end + end + elseif name == "Scene" then + local scene: Parse.Node = { type = "Scene", fields = {} } + children(ch, scene) + local list = scene.fields.children + if type(list) == "table" then + graph.roots = list + end + for f, v in scene.fields do + -- a top-level node with another containerField still shows + if f ~= "children" and type(v) == "table" then + for _, x in v do + table.insert(graph.roots, x) + end + end + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return VXml diff --git a/src/Formats/codecs/model/Vrml/init.luau b/src/Formats/codecs/model/Vrml/init.luau new file mode 100644 index 0000000..6e37e4d --- /dev/null +++ b/src/Formats/codecs/model/Vrml/init.luau @@ -0,0 +1,160 @@ +--!strict +-- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, +-- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding +-- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a +-- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated +-- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2. +-- +-- local graph, err = Vrml.graph(bytes) -- classic or XML, by content +-- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } }) +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local XmlCodec = require("@formats/codecs/text/Xml") +local Parse = require("@formats/codecs/model/Vrml/Parse") +local VXml = require("@formats/codecs/model/Vrml/Xml") +local Build = require("@formats/codecs/model/Vrml/Build") +local Write = require("@formats/codecs/model/Vrml/Write") + +local Vrml = {} + +export type Graph = Parse.Graph +export type Node = Parse.Node +export type Options = Build.Options & { + files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) + resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) + maxBytes: number?, -- the inflated size of a gzipped file (default 2^28) +} + +-- the bytes as text: gzip inflated, UTF-8 BOM dropped +local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?) + local b = if type(data) == "string" then buffer.fromstring(data) else data + if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then + local out, err = Deflate.gunzip(b) + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflated file over maxBytes") + end + b = out + end + local s = buffer.tostring(b) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + return s, nil +end + +local function code(msg: string): string + if string.find(msg, "unsupported", 1, true) then + return Err.UNSUPPORTED + elseif string.find(msg, "limit", 1, true) then + return Err.LIMIT + elseif string.find(msg, "unterminated", 1, true) then + return Err.TRUNCATED + end + return Err.CORRUPT +end + +-- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv) +function Vrml.parse(s: string): (Graph?, Err.Err?) + local g, msg = Parse.parse(s) + if not g then + return nil, Err.new(code(msg or "parse error"), msg or "parse error") + end + return g, nil +end + +-- parseXml(text | XML document) -> the graph of an X3D XML file +function Vrml.parseXml(src: any): (Graph?, Err.Err?) + local doc = src + if type(src) == "string" then + local d, err = XmlCodec.decode(src) + if not d and err and err.code == Err.TRUNCATED and not string.find(src, "", 1, true) then + -- VTK's X3D exporter leaves the root element open + d = XmlCodec.decode(src .. "\n\n") + end + if not d then + return nil, err + end + doc = d + end + local g, msg = VXml.graph(doc) + if not g then + return nil, Err.new(code(msg or "bad X3D"), msg or "bad X3D") + end + return g, nil +end + +-- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED +function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?) + local s, err = text(data, opts and opts.maxBytes) + if not s then + return nil, err + end + local head = string.match(s, "^%s*(.?)") + if head == "<" then + return Vrml.parseXml(s) + end + if string.sub(s, 1, 4) == "\224\0\0\1" or string.sub(s, 1, 4) == "$EXI" then + return nil, Err.new(Err.UNSUPPORTED, "binary X3D (Fast Infoset / EXI encoding)") + end + return Vrml.parse(s) +end + +-- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve +function Vrml.fetcher(opts: Options?): (uri: string) -> buffer? + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +-- build(graph, opts?) -> Scene +function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.fetch = o.fetch or Vrml.fetcher(opts) + o.load = o.load or function(data: buffer): (any, string?) + local g, err = Vrml.graph(data, opts) + return g, if err then err.message else nil + end + local scene, msg = Build.scene(graph, o) + if not scene then + return nil, Err.new(code(msg or "build failed"), msg or "build failed") + end + return scene, nil +end + +-- decode(bytes, opts?) -> Scene: graph + build +function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?) + local g, err = Vrml.graph(data, opts) + if not g then + return nil, err + end + return Vrml.build(g, opts) +end + +-- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files +function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, 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 s, msg = Write.text(scene, opts or {}) + if not s then + return nil, Err.new(Err.ARG, msg or "the scene could not be written") + end + return s, nil +end + +return Vrml diff --git a/src/Formats/model/pmx/Build.luau b/src/Formats/model/pmx/Build.luau new file mode 100644 index 0000000..213cfd9 --- /dev/null +++ b/src/Formats/model/pmx/Build.luau @@ -0,0 +1,307 @@ +--!strict +-- model/pmx/Build: the parsed PMX / PMD model (model/pmx/Read, model/pmx/Pmd) to a Scene. MMD is left-handed (y up, +-- x right, z forward), so positions / normals / bone positions get z negated and every triangle its winding reversed +-- (glTF's right-handed, counter-clockwise front faces); UVs are already top-left. One primitive per material, with +-- the material's vertices only (JOINTS_0 / WEIGHTS_0, the additional UVs as _UVA1.._UVA4 vec4, SDEF C / R0 / R1 as +-- _SDEF_C / _SDEF_R0 / _SDEF_R1 and the deform type as _DEFORM when a vertex uses SDEF / QDEF, _EDGE_SCALE); vertex +-- morphs become morph targets (POSITION deltas, names in mesh.extras.targetNames); bones become nodes (a parent-relative +-- translation each) and one skin with translation-only inverse bind matrices. +local Types = require("@formats/Types") + +local Build = {} + +local readf32, writef32, readi32, readu32 = buffer.readf32, buffer.writef32, buffer.readi32, buffer.readu32 +local S = Types.Scene + +local SPHERE = { [0] = "off", "multiply", "add", "subtexture" } +local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +-- fetch(uri) -> buffer?: opts.files (by the name as written, with "/" separators, or the base name) / opts.resolve +local function fetcher(opts: any): (string) -> buffer? + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + local slash = string.gsub(uri, "\\", "/") + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[slash] or opts.files[string.match(slash, "([^/]+)$") or slash] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, slash) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +local function lh(v: { number }?): { number }? + return if v then { v[1], v[2], -v[3] } else nil +end + +-- the scene index of a file texture index (0-based, -1 = none) +local function texIndex(m: any, i: number?): number? + return if type(i) == "number" and i >= 0 and i < #m.textures then i + 1 else nil +end + +local function material(m: any, mat: any): Types.Material + local out = S.material(mat.name) + local d = mat.diffuse + out.baseColor = { d[1], d[2], d[3], d[4] } + out.metallic = 0 + out.roughness = math.clamp(math.sqrt(2 / (math.max(mat.power or 0, 0) + 2)), 0, 1) + out.doubleSided = bit32.btest(mat.flags, 0x01) + if d[4] < 1 then + out.alphaMode = "blend" + end + local t = texIndex(m, mat.texture) + if t then + out.baseColorTexture = { texture = t } + end + local x: { [string]: any } = { + nameEn = mat.nameEn, diffuse = d, specular = mat.specular, specularPower = mat.power, ambient = mat.ambient, + flags = mat.flags, edge = bit32.btest(mat.flags, 0x10), edgeColor = mat.edgeColor, edgeSize = mat.edgeSize, + sphereTexture = texIndex(m, mat.sphere), sphereMode = SPHERE[mat.sphereMode] or mat.sphereMode, + toonTexture = texIndex(m, mat.toon), memo = mat.memo, indexCount = mat.count, + } + if mat.toonShared then + x.toonShared = mat.toonShared + x.toonFile = string.format("toon%02d.bmp", mat.toonShared + 1) + end + out.extras = { pmx = x } + return out +end + +-- bone parents that form a tree: an invalid index, the bone itself or a cycle makes a root +local function parents(bones: { any }): { number } + local nb = #bones + local par = table.create(nb, 0) + for i, b in bones do + local p = b.parent + if type(p) == "number" and p >= 0 and p < nb and p + 1 ~= i then + par[i] = p + 1 + end + end + for i = 1, nb do + local seen, j, steps = {}, i, 0 + while par[j] ~= 0 and steps <= nb do + seen[j] = true + j = par[j] + steps += 1 + if seen[j] then + par[i] = 0 + break + end + end + end + return par +end + +-- the primitive of one material: indices [first, first + n) of the face list, its vertices renumbered +local function primitive(m: any, first: number, n: number, morphs: { any }, sdef: boolean): Types.Primitive + local map: { [number]: number } = {} + local verts: { number } = {} + local ind = S.accessor(nil, "u32", 1, n) + for t = 0, n // 3 - 1 do + -- reversed winding: a, c, b + for c = 0, 2 do + local src = readu32(m.indices, (first + t * 3 + c) * 4) + local v = map[src] + if not v then + v = #verts + verts[v + 1] = src + map[src] = v + end + buffer.writeu32(ind.data, (t * 3 + (if c == 0 then 0 elseif c == 1 then 2 else 1)) * 4, v) + end + end + local nv = #verts + local nb = #m.bones + local pos, nrm, uv = S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 2, nv) + local jo, we = S.accessor(nil, "u16", 4, nv), S.accessor(nil, "f32", 4, nv) + local edge = S.accessor(nil, "f32", 1, nv) + local attrs: { [string]: Types.Accessor } = { POSITION = pos, NORMAL = nrm, TEXCOORD_0 = uv, _EDGE_SCALE = edge } + if nb > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = jo, we + end + local uvas = {} + for a = 1, #m.uva do + uvas[a] = S.accessor(nil, "f32", 4, nv) + attrs["_UVA" .. a] = uvas[a] + end + local sd: { Types.Accessor }? = nil + local deform: Types.Accessor? = nil + if sdef then + sd = { S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv) } + attrs._SDEF_C, attrs._SDEF_R0, attrs._SDEF_R1 = sd[1], sd[2], sd[3] + deform = S.accessor(nil, "u8", 1, nv) + attrs._DEFORM = deform + end + for v = 0, nv - 1 do + local src = verts[v + 1] + for c = 0, 2 do + local sgn = if c == 2 then -1 else 1 + writef32(pos.data, (v * 3 + c) * 4, sgn * readf32(m.positions, (src * 3 + c) * 4)) + writef32(nrm.data, (v * 3 + c) * 4, sgn * readf32(m.normals, (src * 3 + c) * 4)) + end + buffer.copy(uv.data, v * 8, m.uvs, src * 8, 8) + buffer.copy(edge.data, v * 4, m.edge, src * 4, 4) + for a, acc in uvas do + buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16) + end + -- weights: invalid bones get weight 0, the rest is normalized + local sum = 0 + local js, ws = table.create(4, 0), table.create(4, 0) + for c = 0, 3 do + local j = readi32(m.joints, src * 16 + c * 4) + local w = readf32(m.weights, src * 16 + c * 4) + if j >= 0 and j < nb and w > 0 and w == w then + js[c + 1], ws[c + 1] = j, w + sum += w + end + end + for c = 0, 3 do + buffer.writeu16(jo.data, (v * 4 + c) * 2, js[c + 1]) + writef32(we.data, (v * 4 + c) * 4, if sum > 0 then ws[c + 1] / sum else (if c == 0 then 1 else 0)) + end + if sd and deform then + buffer.writeu8(deform.data, v, buffer.readu8(m.deform, src)) + if m.sdef then + for q = 0, 2 do + for c = 0, 2 do + local x = readf32(m.sdef, src * 36 + q * 12 + c * 4) + writef32(sd[q + 1].data, (v * 3 + c) * 4, if c == 2 then -x else x) + end + end + end + end + end + local prim: Types.Primitive = { attributes = attrs, indices = ind, mode = "triangles" } + if #morphs > 0 then + local targets: { { [string]: Types.Accessor } } = {} + for k, mo in morphs do + local d = S.accessor(nil, "f32", 3, nv) + for o, src in mo.vertices do + local v = map[src] + if v then + for c = 0, 2 do + local x = readf32(mo.deltas, ((o - 1) * 3 + c) * 4) + writef32(d.data, (v * 3 + c) * 4, if c == 2 then -x else x) + end + end + end + targets[k] = { POSITION = d } + end + prim.targets = targets + end + return prim +end + +function Build.scene(m: any, opts: any): (any, ...any) + local scene = S.new() + scene.meta.up = "y" + local fetch = fetcher(opts) + for i, path in m.textures do + local uri = string.gsub(path, "\\", "/") + local tex: Types.Texture = { name = path, uri = uri } + local data = fetch(path) + if data then + tex.data = data + end + local ext = string.match(uri, "%.(%w+)$") + tex.mime = if ext then MIME[string.lower(ext)] else nil + scene.textures[i] = tex + end + for i, mat in m.materials do + scene.materials[i] = material(m, mat) + end + + -- vertex morphs -> targets (others stay in mesh.extras.pmx.morphs) + local vmorphs, names, others = {}, {}, {} + local wantMorphs = not (opts and opts.morphs == false) + for _, mo in m.morphs do + if mo.type == 1 and wantMorphs then + table.insert(vmorphs, mo) + table.insert(names, mo.name) + elseif mo.type ~= 1 then + table.insert(others, { name = mo.name, nameEn = mo.nameEn, panel = mo.panel, type = MORPH[mo.type] or mo.type, offsets = mo.offsets }) + end + end + local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 28 + if #vmorphs * m.vertexCount * 12 > maxBytes then + return nil, string.format("limit: %d vertex morphs on %d vertices (maxBytes; morphs = false skips them)", #vmorphs, m.vertexCount), "limit" + end + local sdef = false + for v = 0, m.vertexCount - 1 do + local k = buffer.readu8(m.deform, v) + if k == 3 or k == 4 then + sdef = true + break + end + end + local mesh: Types.Mesh = { name = m.name, primitives = {} } + local first = 0 + for i, mat in m.materials do + local n = mat.count + if type(n) ~= "number" or n < 0 or n % 3 ~= 0 or first + n > m.indexCount then + return nil, string.format("material %d: %s face indices past the face list", i, tostring(n)) + end + local prim = primitive(m, first, n, vmorphs, sdef) + prim.material = i + table.insert(mesh.primitives, prim) + first += n + end + if first < m.indexCount then + -- faces no material covers + table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef)) + end + mesh.extras = { targetNames = if #names > 0 then names else nil, pmx = if #others > 0 then { morphs = others } else nil } + if #vmorphs > 0 then + mesh.weights = table.create(#vmorphs, 0) + end + scene.meshes[1] = mesh + + -- nodes: 1 = the model, 2 = the mesh, then one per bone + scene.nodes[1] = { name = m.name, children = { 2 } } + scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + local bones = m.bones + local nb = #bones + if nb > 0 then + local par = parents(bones) + local world: { { number } } = {} + for i, b in bones do + world[i] = lh(b.pos) or { 0, 0, 0 } + end + local ibm = S.accessor(nil, "f32", 16, nb) + ibm.matrix = true + local joints: { number } = {} + for i, b in bones do + local w, p = world[i], par[i] + local t = if p ~= 0 then { w[1] - world[p][1], w[2] - world[p][2], w[3] - world[p][3] } else { w[1], w[2], w[3] } + local x: { [string]: any } = { nameEn = b.nameEn, index = i - 1, layer = b.layer, flags = b.flags, position = b.pos } + x.tail, x.inherit, x.axis, x.localX, x.localZ, x.externalKey, x.ik = b.tail, b.inherit, b.axis, b.localX, b.localZ, b.externalKey, b.ik + scene.nodes[2 + i] = { name = b.name, children = {}, translation = t, extras = { pmx = x } } + joints[i] = 2 + i + for c = 0, 15 do + local val = if c % 5 == 0 then 1 elseif c >= 12 and c <= 14 then -w[c - 11] else 0 + writef32(ibm.data, ((i - 1) * 16 + c) * 4, val) + end + end + for i = 1, nb do + local p = par[i] + table.insert(scene.nodes[if p ~= 0 then 2 + p else 1].children, 2 + i) + end + scene.skins[1] = { name = m.name, joints = joints, inverseBindMatrices = ibm } + scene.nodes[2].skin = 1 + end + scene.meta.source = { + format = "pmx", version = m.version, encoding = m.encoding, name = m.name, nameEn = m.nameEn, comment = m.comment, + commentEn = m.commentEn, additionalUV = #m.uva, displayFrames = m.frames, rigidBodies = m.rigidBodies, joints = m.jointsList, + softBodies = m.softBodies, toonTextures = m.toonTextures, + } + return scene +end + +return Build diff --git a/src/Formats/model/pmx/Pmd.luau b/src/Formats/model/pmx/Pmd.luau new file mode 100644 index 0000000..affdd3a --- /dev/null +++ b/src/Formats/model/pmx/Pmd.luau @@ -0,0 +1,339 @@ +--!strict +-- model/pmx/Pmd: the PMD 1.0 parser (MikuMikuDance's original model format), into the same model table as +-- model/pmx/Read so model/pmx/Build makes the Scene. Written from the PMD layout as documented by the MMD community +-- (MMDAgent / mmd_tools notes); no third-party code. Reads vertices (two bones, weight 0..100, edge flag), faces, +-- materials ("texture*sphere" names, toon index), bones, IK chains, skins (the base skin + vertex morphs relative to +-- it), display lists, the optional English names, toon texture names, rigid bodies and joints. Names are Shift-JIS in +-- the file: ASCII names are kept, others use the English name when there is one, else the raw bytes (in +-- extras / meta.source as `nameSjis`). Never throws: returns nil, message[, kind]. +local Bytes = require("@formats/core/Bytes") + +local Pmd = {} + +local function vec(r: Bytes.Reader, n: number): { number } + local v: { number } = {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +local function ascii(s: string): boolean + return not string.find(s, "[\128-\255]") +end + +local function counted(r: Bytes.Reader, n: number, size: number, what: string): (boolean, ...any) + if n * size > r.limit - r.pos then + return false, string.format("%d %s do not fit in the file", n, what) + end + return true +end + +function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any) + if not r:match("Pmd") then + return nil, "not a PMD file" + end + local version = r:f32le() + if version ~= 1 then + return nil, "unsupported: PMD version " .. tostring(version), "unsupported" + end + local m: { [string]: any } = { version = 1.0, encoding = "shift_jis", uva = {}, sdef = nil } + m.nameSjis, m.commentSjis = r:fixed(20), r:fixed(256) + local buf = r.buf + + -- vertices: 38 bytes each + local nv = r:u32le() + if r.err then + return nil, "truncated", "truncated" + end + local ok, e = counted(r, nv, 38, "vertices") + if not ok then + return nil, e, "truncated" + end + local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24 + if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local deform, joints, weights, edge = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16), buffer.create(nv * 4) + for v = 0, nv - 1 do + local p = r.pos + v * 38 + buffer.copy(pos, v * 12, buf, p, 12) + buffer.copy(nrm, v * 12, buf, p + 12, 12) + buffer.copy(uv, v * 8, buf, p + 24, 8) + local b0, b1 = buffer.readu16(buf, p + 32), buffer.readu16(buf, p + 34) + local w = math.clamp(buffer.readu8(buf, p + 36), 0, 100) / 100 + local single = b0 == b1 or w == 1 + buffer.writeu8(deform, v, if single then 0 else 1) + buffer.writei32(joints, v * 16, b0) + buffer.writei32(joints, v * 16 + 4, if single then -1 else b1) + buffer.writei32(joints, v * 16 + 8, -1) + buffer.writei32(joints, v * 16 + 12, -1) + buffer.writef32(weights, v * 16, if single then 1 else w) + buffer.writef32(weights, v * 16 + 4, if single then 0 else 1 - w) + buffer.writef32(edge, v * 4, if buffer.readu8(buf, p + 37) ~= 0 then 0 else 1) + end + r.pos += nv * 38 + m.vertexCount, m.positions, m.normals, m.uvs, m.deform, m.joints, m.weights, m.edge = nv, pos, nrm, uv, deform, joints, weights, edge + + -- faces: u16 indices + local ni = r:u32le() + ok, e = counted(r, ni, 2, "face indices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + for i = 0, ni - 1 do + local x = buffer.readu16(buf, r.pos + i * 2) + if x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv) + end + buffer.writeu32(ind, i * 4, x) + end + r.pos += ni * 2 + m.indexCount, m.indices = ni, ind + + -- materials: 70 bytes each; texture names collected into the texture list + local nm = r:u32le() + ok, e = counted(r, nm, 70, "materials") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.textures = {} + local texIndex: { [string]: number } = {} + local function tex(name: string): number + if name == "" then + return -1 + end + local i = texIndex[name] + if not i then + table.insert(m.textures, name) + i = #m.textures - 1 + texIndex[name] = i + end + return i + end + m.materials = table.create(nm) + local toonIdx = {} + for i = 1, nm do + local mat: { [string]: any } = { name = "material" .. (i - 1), nameEn = "material" .. (i - 1) } + local d = vec(r, 4) + mat.diffuse, mat.power, mat.specular, mat.ambient = d, r:f32le(), vec(r, 3), vec(r, 3) + local toon, edgeFlag = r:u8(), r:u8() + mat.count = r:u32le() + local file = r:fixed(20) + mat.flags = (if edgeFlag ~= 0 then 0x10 else 0) + (if d[4] < 1 then 0x01 else 0) + mat.edgeColor, mat.edgeSize, mat.memo = { 0, 0, 0, 1 }, 1, "" + mat.texture, mat.sphere, mat.sphereMode = -1, -1, 0 + for part in string.gmatch(file, "[^*]+") do + local ext = string.lower(string.match(part, "%.(%w+)$") or "") + if ext == "sph" or ext == "spa" then + mat.sphere, mat.sphereMode = tex(part), if ext == "sph" then 1 else 2 + else + mat.texture = tex(part) + end + end + toonIdx[i] = toon + m.materials[i] = mat + end + + -- bones: 39 bytes each + local nb = r:u16le() + ok, e = counted(r, nb, 39, "bones") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.bones = table.create(nb) + for i = 1, nb do + local b: { [string]: any } = { nameSjis = r:fixed(20) } + local parent, tail, kind, ikParent = r:u16le(), r:u16le(), r:u8(), r:u16le() + b.pos = vec(r, 3) + b.parent = if parent == 0xFFFF then -1 else parent + b.tail = if tail ~= 0 and tail ~= 0xFFFF then tail else { 0, 0, 0 } + b.layer, b.pmdType, b.ikParent = 0, kind, ikParent + -- PMX-style flags: tail index, rotatable, translatable (type 1), visible (not type 7), enabled + b.flags = (if type(b.tail) == "number" then 0x1 else 0) + 0x2 + (if kind == 1 then 0x4 else 0) + (if kind ~= 7 then 0x8 else 0) + 0x10 + m.bones[i] = b + end + + -- IK chains + local nik = r:u16le() + for _ = 1, nik do + local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le() + local links = table.create(len) + for l = 1, len do + links[l] = { bone = r:u16le() } + end + if r.err then + return nil, "truncated", "truncated" + end + local b = m.bones[bone + 1] + if b then + b.flags = bit32.bor(b.flags, 0x20) + -- PMD's limit is in units of 4 radians (PMX stores radians) + b.ik = { target = target, loops = loops, limit = limit * 4, links = links } + end + end + + -- skins: the base (absolute positions of every vertex a morph moves), then morphs relative to it + local ns = r:u16le() + if r.err then + return nil, "truncated", "truncated" + end + m.morphs = {} + local base: { number } = {} + for s = 1, ns do + local name = r:fixed(20) + local n, panel = r:u32le(), r:u8() + ok, e = counted(r, n, 16, "skin vertices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if s == 1 and panel == 0 then + for o = 1, n do + base[o] = r:u32le() + r:skip(12) + end + else + local vi, deltas = table.create(n), buffer.create(n * 12) + for o = 1, n do + local k = r:u32le() + local v = base[k + 1] + if not v or v >= nv then + return nil, string.format("skin %d: base vertex %d out of range", s - 1, k) + end + vi[o] = v + buffer.copy(deltas, (o - 1) * 12, buf, r.pos, 12) + r:skip(12) + end + table.insert(m.morphs, { nameSjis = name, panel = panel, type = 1, vertices = vi, deltas = deltas }) + end + end + + -- display lists (skin list, bone group names, bone groups) + local nsd = r:u8() + r:skip(nsd * 2) + local ng = r:u8() + local groups: { { [string]: any } } = {} + for g = 1, ng do + groups[g] = { nameSjis = r:fixed(50), special = false, items = {} } + end + local nbd = r:u32le() + ok, e = counted(r, nbd, 3, "bone display entries") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + for _ = 1, nbd do + local bone, g = r:u16le(), r:u8() + local grp = groups[g] + if grp then + table.insert(grp.items, { bone = bone }) + end + end + m.frames = groups + + -- optional: English names, toon textures, physics + local function name(t: { [string]: any }, en: string?) + local raw = t.nameSjis or "" + t.nameEn = en + t.name = if ascii(raw) then raw elseif en and en ~= "" then en else raw + if ascii(raw) then + t.nameSjis = nil + end + end + local en: any = {} + if r.limit - r.pos >= 1 and r:u8() == 1 then + en.name, en.comment = r:fixed(20), r:fixed(256) + en.bones = table.create(nb) + for i = 1, nb do + en.bones[i] = r:fixed(20) + end + en.morphs = {} + for i = 1, #m.morphs do + en.morphs[i] = r:fixed(20) + end + en.groups = {} + for i = 1, ng do + en.groups[i] = r:fixed(50) + end + end + local model = { nameSjis = m.nameSjis } + name(model, en.name) + m.name, m.nameEn = model.name, en.name + m.comment, m.commentEn = if ascii(m.commentSjis) then m.commentSjis else (en.comment or m.commentSjis), en.comment + if ascii(m.nameSjis) then + m.nameSjis = nil + end + for i, b in m.bones do + name(b, en.bones and en.bones[i]) + end + for i, mo in m.morphs do + name(mo, en.morphs and en.morphs[i]) + end + for i, g in groups do + name(g, en.groups and en.groups[i]) + end + local toons: { string } = {} + for i = 1, 10 do + toons[i] = string.format("toon%02d.bmp", i) + end + if r.limit - r.pos >= 1000 then + for i = 1, 10 do + toons[i] = r:fixed(100) + end + end + m.toonTextures = toons + for i, mat in m.materials do + local t = toonIdx[i] + if t < 10 then + if toons[t + 1] == string.format("toon%02d.bmp", t + 1) then + mat.toonShared = t + else + mat.toon = tex(toons[t + 1]) + end + else + mat.toon = -1 + end + end + m.rigidBodies, m.jointsList = {}, {} + if r.limit - r.pos >= 4 then + local nr = r:u32le() + ok, e = counted(r, nr, 83, "rigid bodies") + if not ok then + return nil, e, "truncated" + end + for i = 1, nr do + local b: { [string]: any } = { name = r:fixed(20), bone = r:u16le(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + if b.bone == 0xFFFF then + b.bone = -1 + end + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj = r:u32le() + ok, e = counted(r, nj, 124, "joints") + if not ok then + return nil, e, "truncated" + end + for i = 1, nj do + local j: { [string]: any } = { name = r:fixed(20), type = 0, a = r:u32le(), b = r:u32le() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Pmd diff --git a/src/Formats/model/pmx/Read.luau b/src/Formats/model/pmx/Read.luau new file mode 100644 index 0000000..cd7f90d --- /dev/null +++ b/src/Formats/model/pmx/Read.luau @@ -0,0 +1,411 @@ +--!strict +-- model/pmx/Read: the PMX 2.0 / 2.1 parser (MikuMikuDance / PmxEditor model files), into the plain model table that +-- model/pmx/Build turns into a Scene. Written from the PMX 2.0 / 2.1 specification notes that ship with PmxEditor. +-- Reads every section: header globals (UTF-16LE / UTF-8 text, additional UV count, index sizes 1 / 2 / 4), vertices +-- (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), faces, textures, materials, bones (tail, inherit, fixed / local axes, +-- external parent, IK), morphs (group, vertex, bone, UV, UV1-4, material, flip, impulse), display frames, rigid bodies, +-- joints; 2.1 soft bodies are counted, not parsed. Values stay as in the file (left-handed, 0-based indices). +-- Never throws: returns nil, message[, kind]. +local Bytes = require("@formats/core/Bytes") +local Text = require("@formats/codecs/text/Text") + +local Read = {} + +export type Model = { [string]: any } + +local readu8, readu16, readi32 = buffer.readu8, buffer.readu16, buffer.readi32 + +-- index readers: vertex indices are unsigned for sizes 1 / 2, every other index is signed (-1 = none) +local function indexReader(r: Bytes.Reader, size: number, vertex: boolean): () -> number + if size == 1 then + return if vertex then function() return r:u8() end else function() return r:i8() end + elseif size == 2 then + return if vertex then function() return r:u16le() end else function() return r:i16le() end + end + return function() return r:i32le() end +end + +local function vec(r: Bytes.Reader, n: number): { number } + local v: { number } = {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +-- a count field: i32 >= 0 and at most remaining / minSize records +local function count(r: Bytes.Reader, minSize: number, what: string): (any, ...any) + local n = r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + if n < 0 then + return nil, "negative " .. what .. " count" + end + if n * minSize > r.limit - r.pos then + return nil, string.format("%d %s do not fit in the file", n, what), "truncated" + end + return n +end + +function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any) + if not r:match("PMX ") then + return nil, "not a PMX file" + end + local version = r:f32le() + local nglobals = r:u8() + if r.err then + return nil, "truncated", "truncated" + end + if version < 1.95 or version > 2.15 then + return nil, "unsupported: PMX version " .. tostring(version), "unsupported" + end + version = if version > 2.05 then 2.1 else 2.0 + if nglobals < 8 then + return nil, "only " .. nglobals .. " header globals" + end + local g: { number } = {} + for i = 1, nglobals do + g[i] = r:u8() + end + local utf8 = g[1] == 1 + if g[1] > 1 then + return nil, "unknown text encoding " .. g[1] + end + local uva = g[2] + if uva > 4 then + return nil, uva .. " additional UVs (at most 4)" + end + for i = 3, 8 do + if g[i] ~= 1 and g[i] ~= 2 and g[i] ~= 4 then + return nil, "bad index size " .. g[i] + end + end + local vsize, tsize, msize, bsize, morsize, rsize = g[3], g[4], g[5], g[6], g[7], g[8] + local buf = r.buf + local function text(): string + local n = r:i32le() + if r.err or n < 0 or n > r.limit - r.pos then + r:need(r.limit - r.pos + 1) + return "" + end + local p = r.pos + r.pos += n + if utf8 then + return buffer.readstring(buf, p, n) + end + return Text.utf16(buf, p, n) + end + local vidx = indexReader(r, vsize, true) + local tidx = indexReader(r, tsize, false) + local midx = indexReader(r, msize, false) + local bidx = indexReader(r, bsize, false) + local moidx = indexReader(r, morsize, false) + local ridx = indexReader(r, rsize, false) + local m: Model = { version = version, encoding = if utf8 then "utf8" else "utf16", additionalUV = uva, indexSizes = { vsize, tsize, msize, bsize, morsize, rsize } } + m.name, m.nameEn, m.comment, m.commentEn = text(), text(), text(), text() + if r.err then + return nil, "truncated", "truncated" + end + + -- vertices: position, normal, uv, additional uvs, deform, edge scale + local nv, e, k = count(r, 8 * 4 + 1 + bsize + 4 + uva * 16, "vertices") + if not nv then + return nil, e, k + end + local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24 + if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv :: number, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local uvas = {} + for a = 1, uva do + uvas[a] = buffer.create(nv * 16) + end + local deform, joints, weights = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16) + local edge = buffer.create(nv * 4) + local sdef: buffer? = nil + local writef32, writei32 = buffer.writef32, buffer.writei32 + for v = 0, nv - 1 do + if not r:need(32 + uva * 16 + 1) then + return nil, "truncated", "truncated" + end + local p = r.pos + for c = 0, 2 do + writef32(pos, (v * 3 + c) * 4, buffer.readf32(buf, p + c * 4)) + writef32(nrm, (v * 3 + c) * 4, buffer.readf32(buf, p + 12 + c * 4)) + end + writef32(uv, v * 8, buffer.readf32(buf, p + 24)) + writef32(uv, v * 8 + 4, buffer.readf32(buf, p + 28)) + p += 32 + for a = 1, uva do + buffer.copy(uvas[a], v * 16, buf, p, 16) + p += 16 + end + local kind = readu8(buf, p) + r.pos = p + 1 + buffer.writeu8(deform, v, kind) + local o = v * 16 + if kind == 0 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, -1) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + writef32(weights, o, 1) + elseif kind == 1 or kind == 3 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, bidx()) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + local w = r:f32le() + writef32(weights, o, w) + writef32(weights, o + 4, 1 - w) + if kind == 3 then + local sd = sdef or buffer.create(nv * 36) + sdef = sd + for c = 0, 8 do + writef32(sd, v * 36 + c * 4, r:f32le()) + end + end + elseif kind == 2 or kind == 4 then + for c = 0, 3 do + writei32(joints, o + c * 4, bidx()) + end + for c = 0, 3 do + writef32(weights, o + c * 4, r:f32le()) + end + else + return nil, "unknown vertex deform type " .. kind + end + writef32(edge, v * 4, r:f32le()) + if r.err then + return nil, "truncated", "truncated" + end + end + m.vertexCount, m.positions, m.normals, m.uvs, m.uva = nv, pos, nrm, uv, uvas + m.deform, m.joints, m.weights, m.sdef, m.edge = deform, joints, weights, sdef, edge + + -- faces: vertex index triples + local ni + ni, e, k = count(r, vsize, "face indices") + if not ni then + return nil, e, k + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + local p = r.pos + for i = 0, ni - 1 do + local x = if vsize == 1 then readu8(buf, p + i) elseif vsize == 2 then readu16(buf, p + i * 2) else readi32(buf, p + i * 4) + if x < 0 or x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv :: number), nil + end + buffer.writeu32(ind, i * 4, x) + end + r.pos = p + ni * vsize + m.indexCount, m.indices = ni, ind + + -- textures + local nt + nt, e, k = count(r, 4, "textures") + if not nt then + return nil, e, k + end + m.textures = table.create(nt) + for i = 1, nt do + m.textures[i] = text() + end + + -- materials + local nm + nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials") + if not nm then + return nil, e, k + end + m.materials = table.create(nm) + for i = 1, nm do + local mat: { [string]: any } = { name = text(), nameEn = text() } + mat.diffuse, mat.specular, mat.power, mat.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + mat.flags = r:u8() + mat.edgeColor, mat.edgeSize = vec(r, 4), r:f32le() + mat.texture, mat.sphere, mat.sphereMode = tidx(), tidx(), r:u8() + if r:u8() == 1 then + mat.toonShared = r:u8() + else + mat.toon = tidx() + end + mat.memo, mat.count = text(), r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + m.materials[i] = mat + end + + -- bones + local nb + nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones") + if not nb then + return nil, e, k + end + m.bones = table.create(nb) + for i = 1, nb do + local b: { [string]: any } = { name = text(), nameEn = text() } + b.pos, b.parent, b.layer = vec(r, 3), bidx(), r:i32le() + local fl = r:u16le() + b.flags = fl + b.tail = if bit32.btest(fl, 0x1) then bidx() else vec(r, 3) + if bit32.btest(fl, 0x300) then + b.inherit = { bone = bidx(), influence = r:f32le(), rotation = bit32.btest(fl, 0x100), translation = bit32.btest(fl, 0x200) } + end + if bit32.btest(fl, 0x400) then + b.axis = vec(r, 3) + end + if bit32.btest(fl, 0x800) then + b.localX, b.localZ = vec(r, 3), vec(r, 3) + end + if bit32.btest(fl, 0x2000) then + b.externalKey = r:i32le() + end + if bit32.btest(fl, 0x20) then + local ik: { [string]: any } = { target = bidx(), loops = r:i32le(), limit = r:f32le() } + local nl + nl, e, k = count(r, bsize + 1, "IK links") + if not nl then + return nil, e, k + end + ik.links = table.create(nl) + for l = 1, nl do + local link: { [string]: any } = { bone = bidx() } + if r:u8() == 1 then + link.min, link.max = vec(r, 3), vec(r, 3) + end + ik.links[l] = link + end + b.ik = ik + end + if r.err then + return nil, "truncated", "truncated" + end + m.bones[i] = b + end + + -- morphs + local nmo + nmo, e, k = count(r, 8 + 2 + 4, "morphs") + if not nmo then + return nil, e, k + end + local SIZE = { [0] = morsize + 4, vsize + 12, bsize + 28, vsize + 16, vsize + 16, vsize + 16, vsize + 16, vsize + 16, msize + 1 + 112, morsize + 4, rsize + 25 } + m.morphs = table.create(nmo) + for i = 1, nmo do + local mo: { [string]: any } = { name = text(), nameEn = text(), panel = r:u8(), type = r:u8() } + local t = mo.type + local size = SIZE[t] + if not size then + return nil, "unknown morph type " .. t + end + local no + no, e, k = count(r, size, "morph offsets") + if not no then + return nil, e, k + end + if t == 1 then + -- vertex morphs: packed (index list + deltas), they become morph targets + local vi, d = table.create(no), buffer.create(no * 12) + for o = 1, no do + local x = vidx() + vi[o] = x + for c = 0, 2 do + writef32(d, ((o - 1) * 3 + c) * 4, r:f32le()) + end + end + mo.vertices, mo.deltas = vi, d + else + local offs = table.create(no) + for o = 1, no do + local off: { [string]: any } + if t == 0 or t == 9 then + off = { morph = moidx(), weight = r:f32le() } + elseif t == 2 then + off = { bone = bidx(), translation = vec(r, 3), rotation = vec(r, 4) } + elseif t <= 7 then + off = { vertex = vidx(), value = vec(r, 4) } + elseif t == 8 then + off = { material = midx(), operation = r:u8() } + off.diffuse, off.specular, off.specularPower, off.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + off.edgeColor, off.edgeSize, off.textureTint, off.sphereTint, off.toonTint = vec(r, 4), r:f32le(), vec(r, 4), vec(r, 4), vec(r, 4) + else + off = { rigidBody = ridx(), localFrame = r:u8() == 1, velocity = vec(r, 3), torque = vec(r, 3) } + end + offs[o] = off + end + mo.offsets = offs + end + if r.err then + return nil, "truncated", "truncated" + end + m.morphs[i] = mo + end + + -- display frames, rigid bodies, joints: optional at the end (some tools stop after the morphs) + m.frames, m.rigidBodies, m.jointsList = {}, {}, {} + if r.limit - r.pos >= 4 then + local nf + nf, e, k = count(r, 8 + 1 + 4, "display frames") + if not nf then + return nil, e, k + end + for i = 1, nf do + local f: { [string]: any } = { name = text(), nameEn = text(), special = r:u8() == 1 } + local nitem + nitem, e, k = count(r, 1 + math.min(bsize, morsize), "display frame items") + if not nitem then + return nil, e, k + end + f.items = table.create(nitem) + for q = 1, nitem do + local kind = r:u8() + f.items[q] = if kind == 0 then { bone = bidx() } else { morph = moidx() } + end + m.frames[i] = f + end + end + if r.limit - r.pos >= 4 then + local nr + nr, e, k = count(r, 8 + bsize + 4 + 36 + 20 + 1, "rigid bodies") + if not nr then + return nil, e, k + end + for i = 1, nr do + local b: { [string]: any } = { name = text(), nameEn = text(), bone = bidx(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj + nj, e, k = count(r, 8 + 1 + 2 * rsize + 96, "joints") + if not nj then + return nil, e, k + end + for i = 1, nj do + local j: { [string]: any } = { name = text(), nameEn = text(), type = r:u8(), a = ridx(), b = ridx() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if version >= 2.1 and r.limit - r.pos >= 4 then + m.softBodies = r:i32le() + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Read diff --git a/src/Formats/model/pmx/init.luau b/src/Formats/model/pmx/init.luau new file mode 100644 index 0000000..5a671b1 --- /dev/null +++ b/src/Formats/model/pmx/init.luau @@ -0,0 +1,77 @@ +--!strict +-- model/pmx: MikuMikuDance models, PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (the original MMD +-- format, as documented by the MMD community). New code, no third-party code. +-- Reads: UTF-16 / UTF-8 text (PMD: Shift-JIS names kept when ASCII, else the English names), vertices with BDEF1 / +-- BDEF2 / BDEF4 / SDEF / QDEF weights -> JOINTS_0 / WEIGHTS_0 (normalized; SDEF C / R0 / R1 as _SDEF_C / _SDEF_R0 / +-- _SDEF_R1, the deform type as _DEFORM, additional UVs as _UVA1.._UVA4 vec4, edge scale as _EDGE_SCALE), faces (one +-- primitive per material), textures (uri, data through opts.files / opts.resolve), materials (diffuse -> baseColor, +-- specular power -> roughness, no-cull -> doubleSided; diffuse / specular / ambient, edge, sphere map and mode, toon +-- texture or shared toon index, memo in material.extras.pmx), bones (nodes with parent-relative translations, one skin; +-- tail, inherit, axes, IK in node.extras.pmx), vertex morphs -> morph targets (POSITION deltas, mesh.extras.targetNames), +-- the other morphs (group, bone, UV, material, flip, impulse), display frames, rigid bodies and joints as extras +-- (mesh.extras.pmx.morphs, meta.source). MMD's left-handed coordinates become right-handed: z is negated and the +-- winding reversed (extras keep the file's values and 0-based indices). meta.up = "y" (one unit is about 8 cm). +-- Not supported: writing, PMX 2.1 soft bodies (counted in meta.source.softBodies), VMD motions / VPD poses. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/pmx/Read") +local Pmd = require("@formats/model/pmx/Pmd") +local Build = require("@formats/model/pmx/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Pmx = { + name = "pmx", + category = "model", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + files: { [string]: any }?, -- texture files by name (buffer or string; "/" or "\" separators, or the base name) + resolve: ((uri: string) -> any)?, -- or: reads a texture file (the api sets it for paths) + morphs: boolean?, -- vertex morphs as morph targets (default true) + maxVertices: number?, -- default 2^24 + maxBytes: number?, -- morph target bytes (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Pmx.sniff(r: Bytes.Reader): number + local head = r:peek(8) + if string.sub(head, 1, 4) == "PMX " then + return 1 + end + if string.sub(head, 1, 7) == "Pmd\0\0\128\63" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Pmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local pmd = r:peek(3) == "Pmd" + local m: any, msg: string?, kind: string? + if pmd then + m, msg, kind = Pmd.parse(r, opts) + else + m, msg, kind = Read.parse(r, opts) + end + if not m then + return nil, Err.from(msg, r.pos - r.base, kind) + end + local scene, berr, bkind = Build.scene(m, opts) + if not scene then + return nil, Err.from(berr, nil, bkind) + end + if pmd and scene.meta.source then + scene.meta.source.pmd = true + end + return scene, nil +end + +return Pmx diff --git a/src/Formats/model/vrml/init.luau b/src/Formats/model/vrml/init.luau new file mode 100644 index 0000000..c9192c1 --- /dev/null +++ b/src/Formats/model/vrml/init.luau @@ -0,0 +1,77 @@ +--!strict +-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl files, plain or gzipped (.wrz), a thin format over +-- codecs/model/Vrml (the scene-graph engine model/x3d shares). New code. +-- Reads: the scene graph (Transform with center / scaleOrientation, Group, Anchor, Billboard, Collision, Switch, LOD, +-- Inline through opts.files / opts.resolve), DEF / USE (shared meshes and materials), PROTO instances (expanded) and +-- EXTERNPROTO, Shape / Appearance / Material / ImageTexture / PixelTexture / TextureTransform, IndexedFaceSet (coord, +-- normal, color, texCoord with their own indices, per-vertex / per-face normals and colours, ccw, solid -> doubleSided), +-- IndexedLineSet, PointSet, ElevationGrid, Extrusion, the primitives Box / Sphere / Cone / Cylinder tessellated +-- (opts.segments), Viewpoint -> cameras, DirectionalLight / PointLight / SpotLight -> lights, TimeSensor -> +-- Position- / OrientationInterpolator -> Transform ROUTEs -> animations, WorldInfo -> meta.source.title / info. Polygons +-- are fan-triangulated unless opts.triangulate = false; texture t is flipped to glTF's top-left origin unless +-- opts.flipV = false. meta.up = "y", meta.unit = 1 (metres). +-- Writes: VRML97 text (see codecs/model/Vrml/Write: Transforms from the node tree, Shapes with IndexedFaceSet / +-- IndexedLineSet / PointSet, Appearance / Material / ImageTexture (texture files into opts.files), Viewpoints, lights, +-- TimeSensor + interpolator animations; DEF / USE for shared meshes and materials). +-- Not supported: VRML 1.0, Text / FontStyle (no glyphs), Script behaviour, sensors, sound, NURBS, morph targets and +-- skins on write (the rest pose is written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Vrml = require("@formats/codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local Wrl = { + name = "vrml", + category = "model", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) + resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention) + segments: number?, -- Sphere / Cone / Cylinder segments around (default 32) + maxVertices: number?, -- per geometry (default 2^24) +} +export type EncodeOptions = { + files: { [string]: any }?, -- receives the texture images (else url = texture.uri) + name: string?, -- the destination's file name (names the image files) + flipV: boolean?, -- default true (the inverse of decode) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Wrl.sniff(r: Bytes.Reader): number + local head = r:peek(16) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + return if string.sub(head, 1, 10) == "#VRML V2.0" then 1 elseif string.sub(head, 1, 6) == "#VRML " then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Wrl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.format = "vrml" + return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Wrl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.encoding = "vrml97" + local text, err = Vrml.encode(scene, o) + if not text then + return nil, err + end + return buffer.fromstring(text), nil +end + +return Wrl diff --git a/src/Formats/model/x3d/init.luau b/src/Formats/model/x3d/init.luau new file mode 100644 index 0000000..860efa7 --- /dev/null +++ b/src/Formats/model/x3d/init.luau @@ -0,0 +1,85 @@ +--!strict +-- model/x3d: X3D (ISO/IEC 19775-1) in its XML encoding (.x3d, ISO/IEC 19776-1) and its classic VRML encoding (.x3dv, +-- 19776-2), plain or gzipped (.x3dz / .x3dvz), a thin format over codecs/model/Vrml (the engine model/vrml shares). +-- New code. +-- Reads: everything model/vrml reads, plus the X3D nodes: IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, +-- TriangleFanSet, IndexedTriangleStripSet, TriangleStripSet, IndexedQuadSet, QuadSet, LineSet, ColorRGBA, +-- CoordinateDouble, MultiTexture / MultiTextureCoordinate (the first), PhysicalMaterial / UnlitMaterial / +-- TwoSidedMaterial, OrthoViewpoint, CAD groups; XML ProtoDeclare / ProtoInstance, ROUTE elements, containerField; +-- head meta, components and UNIT length (-> meta.unit). +-- Writes: X3D 3.3 XML (default) or the classic encoding (opts.encoding = "x3dv"; the api passes the extension), the +-- same scene graph as model/vrml writes (ColorRGBA for colours with alpha, OrthoViewpoint for orthographic cameras). +-- Not supported: the binary encodings (.x3db Fast Infoset / EXI: UNSUPPORTED), X3D JSON, Text, NURBS, shaders, +-- H-Anim skinning, scripts. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Vrml = require("@formats/codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local X3d = { + name = "x3d", + category = "model", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) + resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention) + segments: number?, -- Sphere / Cone / Cylinder segments around (default 32) + maxVertices: number?, -- per geometry (default 2^24) +} +export type EncodeOptions = { + encoding: ("xml" | "x3dv")?, -- default "xml" + format: string?, -- the api passes the extension: "x3dv" / "x3dvz" select the classic encoding + files: { [string]: any }?, -- receives the texture images (else url = texture.uri) + name: string?, -- the destination's file name (names the image files) + flipV: boolean?, -- default true (the inverse of decode) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function X3d.sniff(r: Bytes.Reader): number + local head = r:peek(1024) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + if string.sub(head, 1, 5) == "#X3D " then + return 1 + end + if string.sub(head, 1, 4) == "\224\0\0\1" and string.find(head, "x3d", 1, true) then + return 0.9 + end + if string.find(head, "]") or string.find(head, " meta.unit") +end + +-- ------------------------------------------------------------------------------------------------ XML adapter +do + local g = assert(Vrml.graph([[ + + + + + + + +]])) + t:check(g.header.xml and g.header.version == "4.0", "XML header") + t:eq(g.components[1], "Shaders:1", "head component") + local grp = g.roots[1] + local kids = Fields.nodes(grp, "children") + t:eq(#kids, 2, "ProtoInstances in children") + t:eq(Fields.num(Fields.node(kids[1], "geometry"), "radius", -1), 5, "fieldValue") + t:eq(Fields.num(Fields.node(kids[2], "geometry"), "radius", -1), 2, "ProtoInterface default") + local shape = g.roots[2] + local box = Fields.node(shape, "geometry") + t:eq(table.concat(Fields.vec(box, "size", { 9, 9, 9 }), " "), "1 2 3", "numbers with commas") + t:eq(Fields.bool(box, "solid", true), false, "XML booleans (any case)") + local tex = Fields.node(Fields.node(shape, "appearance"), "texture") + local urls = Fields.strs(tex, "url") + t:check(#urls == 2 and urls[2] == "b.png", "quoted MFString") + t:eq(g.roots[3], grp, "USE in XML") + local single = { type = "ImageTexture", fields = { url = "plain name.png" } } + t:eq(Fields.strs(single, "url")[1], "plain name.png", "unquoted single MFString") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local function code(text: string): string? + local _, e = Vrml.graph(text) + return e and e.code + end + t:eq(code("#VRML V2.0 utf8\nShape { geometry Box { }"), Err.CORRUPT, "unclosed node") + t:eq(code("#VRML V2.0 utf8\nShape { geometry USE X }"), Err.CORRUPT, "undefined USE") + t:eq(code("#VRML V2.0 utf8\nROUTE A.b TO"), Err.CORRUPT, "bad ROUTE") + t:eq(code("#VRML V2.0 utf8\nWorldInfo { title \"x }"), Err.TRUNCATED, "unterminated string") + t:eq(code("#VRML V1.0 ascii\n"), Err.UNSUPPORTED, "VRML 1.0") + t:eq(code("\224\0\0\1rest"), Err.UNSUPPORTED, "Fast Infoset X3D") + t:eq(code("#VRML V2.0 utf8\n" .. string.rep("Group { children ", 250)), Err.LIMIT, "nesting limit") + t:eq(code(""), Err.CORRUPT, "bad XML") + local _, e = Vrml.encode({} :: any) + t:eq(e and e.code, Err.ARG, "encode junk") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = { + "#VRML V2.0 utf8\nPROTO P [ field SFFloat a 1 ] { Box { size IS a IS a } }\nDEF X P { a 2 } USE X ROUTE X.a TO X.b\n", + "#X3D V3.3 utf8\nPROFILE Full\nShape { geometry Extrusion { spine [ 0 0 0 0 1 0 1 1 1 ] crossSection [ 0 0 1 0 1 1 0 0 ] } }\n", + "", + } + t:fuzz("graph + build", function(b: buffer) + local g = Vrml.graph(b) + if g then + return Vrml.build(g) + end + return nil + end, samples, { mutations = 400 }) +end + +t:done() diff --git a/tests/model/_vrml_common.luau b/tests/model/_vrml_common.luau new file mode 100644 index 0000000..8ac98a0 --- /dev/null +++ b/tests/model/_vrml_common.luau @@ -0,0 +1,109 @@ +-- tests/model/_vrml_common: helpers shared by the VRML and X3D tests (tests/model/vrml.luau, x3d.luau): counts over +-- placed primitives (instances count, as the reference readers count them) and world bounds that include lines and +-- points (MeshOps.merge skips them). +local Types = require("@formats/Types") + +local C = {} + +export type Stats = { prims: number, unique: number, polys: number, lines: number, points: number, lo: { number }, hi: { number }, area: number } + +function C.near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +function C.stats(scene: any): Stats + local s: Stats = { prims = 0, unique = 0, polys = 0, lines = 0, points = 0, lo = { math.huge, math.huge, math.huge }, hi = { -math.huge, -math.huge, -math.huge }, area = 0 } + local seen = {} + for _, pl in Types.Scene.flatten(scene) do + local p = pl.primitive + s.prims += 1 + if not seen[p] then + seen[p] = true + s.unique += 1 + end + local P = p.attributes.POSITION + local nf = 0 + if p.mode == "polygons" then + nf = p.faces.count + elseif p.mode == "lines" then + s.lines += (if p.indices then p.indices.count else P.count) // 2 + elseif p.mode == "points" then + s.points += P.count + elseif p.mode == "triangle_strip" or p.mode == "triangle_fan" then + nf = math.max(0, (if p.indices then p.indices.count else P.count) - 2) + elseif p.mode == "line_strip" or p.mode == "line_loop" then + local n = if p.indices then p.indices.count else P.count + s.lines += if p.mode == "line_loop" then n else math.max(0, n - 1) + else + nf = (if p.indices then p.indices.count else P.count) // 3 + end + s.polys += nf + local m = pl.matrix + local get = assert(Types.Scene.reader(P)) + local w = {} + for v = 0, P.count - 1 do + local x, y, z = get(v, 0), get(v, 1), get(v, 2) + local wx, wy, wz = m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] + w[v] = { wx, wy, wz } + s.lo[1], s.lo[2], s.lo[3] = math.min(s.lo[1], wx), math.min(s.lo[2], wy), math.min(s.lo[3], wz) + s.hi[1], s.hi[2], s.hi[3] = math.max(s.hi[1], wx), math.max(s.hi[2], wy), math.max(s.hi[3], wz) + end + -- world area of the faces (fan-triangulated polygons) + local mode = p.mode + if mode == "triangles" or mode == "polygons" or mode == "triangle_strip" or mode == "triangle_fan" then + local ir = if p.indices then Types.Scene.reader(p.indices) else nil + local ind = function(i: number, _c: number): number + return if ir then ir(i, 0) else i + end + local count = if p.indices then p.indices.count else P.count + local function tri(a: number, b: number, c: number) + local A, B, Cc = w[a], w[b], w[c] + if A and B and Cc then + local e1 = { B[1] - A[1], B[2] - A[2], B[3] - A[3] } + local e2 = { Cc[1] - A[1], Cc[2] - A[2], Cc[3] - A[3] } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + s.area += math.sqrt(x * x + y * y + z * z) / 2 + end + end + if mode == "triangles" then + for t = 0, count // 3 - 1 do + tri(ind(t * 3, 0), ind(t * 3 + 1, 0), ind(t * 3 + 2, 0)) + end + elseif mode == "triangle_strip" then + for t = 0, count - 3 do + tri(ind(t, 0), ind(t + 1, 0), ind(t + 2, 0)) + end + elseif mode == "triangle_fan" then + for t = 1, count - 2 do + tri(ind(0, 0), ind(t, 0), ind(t + 1, 0)) + end + else + local at = 0 + local sizes = assert(Types.Scene.reader(p.faces)) + for f = 0, p.faces.count - 1 do + local n = sizes(f, 0) + for k = 1, n - 2 do + tri(ind(at, 0), ind(at + k, 0), ind(at + k + 1, 0)) + end + at += n + end + end + end + end + return s +end + +function C.boundsNear(lo: { number }, hi: { number }, wlo: { number }, whi: { number }, eps: number): boolean + for k = 1, 3 do + if not C.near(lo[k], wlo[k], eps) or not C.near(hi[k], whi[k], eps) then + return false + end + end + return true +end + +function C.fmt(lo: { number }, hi: { number }): string + return string.format("%.5g %.5g %.5g / %.5g %.5g %.5g", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]) +end + +return C diff --git a/tests/model/pmx.luau b/tests/model/pmx.luau new file mode 100644 index 0000000..6612131 --- /dev/null +++ b/tests/model/pmx.luau @@ -0,0 +1,263 @@ +-- model/pmx tests: assimp's MMD model (Alicia_blade.pmx) and synthetic PMX 2.0 / 2.1 models (UTF-16 / UTF-8, index +-- sizes 1 / 2 / 4, additional UVs, BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF, every morph type, IK / inherit / axis bones, +-- display frames, rigid bodies, joints) against assimp (meshes, faces per mesh, materials, bones, world bounds) and the +-- generator's facts (vertices, weights, bones, morphs, textures); the same models as PMD against their PMX decode; +-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/pmx.py. +local T = require("@tests/T") +local F = require("@formats") +local Pmx = require("@formats/model/pmx") +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/pmx_cases") +local Pmds = require("@tests/gen/pmx_pmd") + +local t = T.suite("pmx") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Pmx.decode(Bytes.reader(b), opts) +end + +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 + +t:eq(Pmx.name, "pmx", "name") +t:eq(Pmx.category, "model", "category") +t:check(Pmx.caps.decode and not Pmx.caps.encode, "contract") + +local function faces(scene: any): (number, { number }) + local n, per = 0, {} + for i, p in scene.meshes[1].primitives do + per[i] = p.indices.count // 3 + n += per[i] + end + return n, per +end + +local function bounds(scene: any): ({ number }, { number }) + return MeshOps.bounds(MeshOps.merge(scene)) +end + +-- a file vertex in the decoded primitives: position (z negated) and uv +local function findVertex(scene: any, pos: { number }, uv: { number }): (any, number?) + for _, p in scene.meshes[1].primitives do + local P, U = p.attributes.POSITION, p.attributes.TEXCOORD_0 + for v = 0, P.count - 1 do + local x, y, z = buffer.readf32(P.data, v * 12), buffer.readf32(P.data, v * 12 + 4), buffer.readf32(P.data, v * 12 + 8) + if near(x, pos[1], 1e-6) and near(y, pos[2], 1e-6) and near(z, -pos[3], 1e-6) and near(buffer.readf32(U.data, v * 8), uv[1], 1e-6) and near(buffer.readf32(U.data, v * 8 + 4), uv[2], 1e-6) then + return p, v + end + end + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes = {} +local checked = { assimp = 0, expect = 0 } +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + scenes[i] = scene + local a = c.assimp + local nf, per = faces(scene) + if not a.skip then + t:eq(#scene.meshes[1].primitives, a.meshes, c.name .. ": meshes (assimp)") + t:eq(nf, a.faces, c.name .. ": faces (assimp)") + t:eq(#scene.materials, a.materials, c.name .. ": materials (assimp)") + local ok = true + for k, pm in a.perMesh do + ok = ok and per[k] == pm.faces + end + t:check(ok, c.name .. ": faces per material (assimp)") + t:eq(#scene.skins[1].joints * #scene.meshes[1].primitives, a.bones, c.name .. ": bones x meshes (assimp)") + if a.min then + local lo, hi = bounds(scene) + local okb = true + for k = 1, 3 do + okb = okb and near(lo[k], a.min[k], 1e-5) and near(hi[k], a.max[k], 1e-5) + end + t:check(okb, string.format("%s: world bounds (assimp) %s / %s", c.name, table.concat(lo, " "), table.concat(hi, " "))) + end + checked.assimp += 1 + end + local x = c.expect + if x then + local src = scene.meta.source + t:eq(src.version, x.version, c.name .. ": version") + t:eq(src.name, x.name, c.name .. ": model name") + t:eq(#scene.skins[1].joints, x.bones, c.name .. ": bones") + t:eq(#scene.nodes, 2 + x.bones, c.name .. ": nodes") + t:eq(#scene.textures, x.textures, c.name .. ": textures") + t:eq(#src.rigidBodies, x.rigid, c.name .. ": rigid bodies") + t:eq(#src.joints, x.joints, c.name .. ": joints") + t:eq(#src.displayFrames, x.frames, c.name .. ": display frames") + local mesh = scene.meshes[1] + local vertexMorphs = x.morphTypes["1"] or 0 + t:eq(#(mesh.extras.targetNames or {}), vertexMorphs, c.name .. ": vertex morphs -> targets") + t:eq(#mesh.primitives[1].targets, vertexMorphs, c.name .. ": targets per primitive") + t:eq(#((mesh.extras.pmx or {}).morphs or {}), x.morphs - vertexMorphs, c.name .. ": other morphs in extras") + t:check(x.uva == 0 or mesh.primitives[1].attributes["_UVA" .. x.uva] ~= nil, c.name .. ": additional UVs") + -- unique vertices: a material boundary can split a ring, so at least the file's count + local nv = 0 + for _, p in mesh.primitives do + nv += p.attributes.POSITION.count + end + t:check(nv >= x.vertices and nv <= x.vertices * 2, c.name .. ": vertices " .. nv .. " / " .. x.vertices) + for _, s in x.samples do + local p, v = findVertex(scene, s.pos, s.uv) + t:check(p ~= nil, c.name .. ": vertex " .. s.index .. " found") + if p and v then + local J, W = p.attributes.JOINTS_0, p.attributes.WEIGHTS_0 + local want: { [number]: number } = {} + local sum = 0 + local ws = if s.deform == 1 or s.deform == 3 then { s.weights[1], 1 - s.weights[1] } elseif s.deform == 0 then { 1 } else s.weights + for k, b in s.bones do + if b >= 0 and ws[k] and ws[k] > 0 then + want[b] = (want[b] or 0) + ws[k] + sum += ws[k] + end + end + local got: { [number]: number } = {} + for k = 0, 3 do + local w = buffer.readf32(W.data, (v * 4 + k) * 4) + if w > 0 then + local j = buffer.readu16(J.data, (v * 4 + k) * 2) + got[j] = (got[j] or 0) + w + end + end + local ok = true + for b, w in want do + ok = ok and got[b] ~= nil and near(got[b], w / sum, 1e-5) + end + t:check(ok, c.name .. ": vertex " .. s.index .. " weights (deform " .. s.deform .. ")") + if s.deform == 3 then + t:check(p.attributes._SDEF_C ~= nil and buffer.readu8(p.attributes._DEFORM.data, v) == 3, c.name .. ": SDEF attributes") + end + end + end + -- the texture named tex\body.png came from files["tex/body.png"] + t:check(scene.textures[1].uri == "tex/body.png" and scene.textures[1].data ~= nil and scene.textures[1].mime == "image/png", c.name .. ": texture data") + local m1 = scene.materials[1] + t:check(m1.baseColorTexture and m1.baseColorTexture.texture == 1 and m1.doubleSided, c.name .. ": material 1 texture, no-cull") + t:check(m1.extras.pmx.sphereTexture == 2 and m1.extras.pmx.sphereMode == "multiply" and m1.extras.pmx.toonShared == 3, c.name .. ": sphere / toon") + t:check(scene.materials[2].alphaMode == "blend", c.name .. ": translucent material") + local ik = nil + for _, n in scene.nodes do + if n.extras and n.extras.pmx and n.extras.pmx.ik then + ik = n.extras.pmx.ik + end + end + t:check(ik and ik.loops == 40 and #ik.links == 2, c.name .. ": IK bone") + checked.expect += 1 + end +end +t:note("%d files: %d against assimp, %d against the generator", #Cases, checked.assimp, checked.expect) + +-- skins: every joint's inverse bind matrix undoes its world translation +do + local s = scenes[2] + if s then + local skin = s.skins[1] + local ok = true + local world = {} + -- world matrices by walking from the root + local function walk(n: number, parent: { number }) + local w = Types.Scene.mul(parent, Types.Scene.nodeMatrix(s.nodes[n])) + world[n] = w + for _, c in s.nodes[n].children do + walk(c, w) + end + end + walk(1, Types.Scene.IDENTITY) + for k, j in skin.joints do + local w = world[j] + for c = 0, 2 do + ok = ok and near(buffer.readf32(skin.inverseBindMatrices.data, ((k - 1) * 16 + 12 + c) * 4), -w[13 + c], 1e-5) + end + end + t:check(ok, "inverse bind matrices = -world bone positions") + end +end + +-- ------------------------------------------------------------------------------------------------ PMD +for _, c in Pmds do + local s, err = decode(c.data) + t:check(s, c.name .. ": decode: " .. tostring(err)) + local ref = scenes[c.pmx] + if s and ref then + t:check(s.meta.source.pmd == true and s.meta.source.format == "pmx", c.name .. ": meta.source") + local a, pa = faces(s) + local b, pb = faces(ref) + t:eq(a, b, c.name .. ": faces (= PMX)") + t:eq(#pa, #pb, c.name .. ": primitives (= PMX)") + t:eq(#s.skins[1].joints, #ref.skins[1].joints, c.name .. ": bones (= PMX)") + t:eq(#s.meshes[1].extras.targetNames, #ref.meshes[1].extras.targetNames, c.name .. ": vertex morphs (= PMX)") + local lo, hi = bounds(s) + local lo2, hi2 = bounds(ref) + local ok = true + for k = 1, 3 do + ok = ok and near(lo[k], lo2[k], 1e-6) and near(hi[k], hi2[k], 1e-6) + end + t:check(ok, c.name .. ": bounds (= PMX)") + -- the same morph deltas + local d1 = s.meshes[1].primitives[1].targets[1].POSITION + local d2 = ref.meshes[1].primitives[1].targets[1].POSITION + t:check(d1.count == d2.count and buffer.tostring(d1.data) == buffer.tostring(d2.data), c.name .. ": morph deltas (= PMX)") + t:eq(s.meshes[1].extras.targetNames[1], "up", c.name .. ": English morph names") + t:eq(s.materials[1].extras.pmx.sphereMode, "multiply", c.name .. ": texture*sphere name") + end +end + +-- ------------------------------------------------------------------------------------------------ api, errors +do + local c = Cases[2] + t:eq(F.detect(c.data), "pmx", "F.detect pmx") + t:eq(F.detect(Pmds[1].data), "pmx", "F.detect pmd") + local s = F.load(c.data, { files = c.files }) + t:check(s and s.kind == "scene" and s.meta.up == "y", "F.load") + local _, e1 = decode(string.sub(c.data, 1, 300)) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local _, e2 = decode("PMX " .. "\0\0\64\64" .. string.sub(c.data, 9)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 2.0 -> 3.0: " .. tostring(e2)) + local _, e3 = decode(string.sub(c.data, 1, 11) .. "\3" .. string.sub(c.data, 13)) + t:check(e3 and e3.code == Err.CORRUPT, "index size 3: " .. tostring(e3)) + local _, e4 = decode(c.data, { maxVertices = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = decode(c.data, { maxBytes = 100 }) + t:check(e5 and e5.code == Err.LIMIT, "maxBytes (morph targets): " .. tostring(e5)) + local s2 = decode(c.data, { maxBytes = 100, morphs = false }) + t:check(s2 and s2.meshes[1].primitives[1].targets == nil, "morphs = false") + local _, e6 = decode("Pmd\0\0\0\64" .. string.rep("\0", 300)) + t:check(e6 and e6.code == Err.UNSUPPORTED, "PMD version 2: " .. tostring(e6)) + local _, e7 = decode(string.sub(Pmds[1].data, 1, 400)) + t:check(e7 and (e7.code == Err.TRUNCATED or e7.code == Err.CORRUPT), "PMD truncated: " .. tostring(e7)) +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 120000 then + table.insert(samples, c.data) + end + end + for _, c in Pmds do + table.insert(samples, c.data) + end + t:fuzz("decode", function(b: buffer) + local s = Pmx.decode(Bytes.reader(b)) + if s then + MeshOps.merge(s) + end + return s + end, samples, { mutations = 16, keepHeader = 16 }) +end + +t:done() diff --git a/tests/model/vrml.luau b/tests/model/vrml.luau new file mode 100644 index 0000000..5638328 --- /dev/null +++ b/tests/model/vrml.luau @@ -0,0 +1,410 @@ +-- model/vrml tests: assimp's WRL test models (HelloWorld, Wuson, the MotionCaptureROM animation), scenes and glTF +-- samples written by VTK's VRML exporter, and hand-written feature files (PROTO, DEF / USE, per-face colours and +-- separate indices, primitives, ElevationGrid, Extrusion, Switch, LOD, lights, viewpoints, ROUTE animations, +-- PixelTexture, Inline), against VTK's vtkVRMLImporter (polygons, points, world bounds where VTK's transforms are +-- right) and exact expectations; the writer: round trips of every case and of glTF sample models (world triangles, +-- materials, textures, cameras, lights, animation samples), VTK reading our files like the originals; errors; the +-- fuzz no-throw pass. Fixtures: tools/fixtures/vrml.py. +local T = require("@tests/T") +local F = require("@formats") +local Vrml = require("@formats/model/vrml") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Deflate = require("@formats/codecs/compress/Deflate") +local C = require("@tests/model/_vrml_common") +local Cases = require("@tests/gen/vrml_cases") +local GltfCases = require("@tests/gen/vrml_gltf") +local Xcheck = require("@tests/gen/vrml_xcheck") + +local t = T.suite("vrml") +local near = C.near + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Vrml.decode(Bytes.reader(b), opts) +end + +t:eq(Vrml.name, "vrml", "name") +t:eq(Vrml.category, "model", "category") +t:check(Vrml.caps.decode and Vrml.caps.encode, "contract") + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes, byName = {}, {} +local checked = { vtk = 0, bounds = 0, none = 0 } +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files, triangulate = false }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + scenes[i], byName[c.name] = scene, scene + local s = C.stats(scene) + local v = c.vtk + if v.failed or v.actors == 0 then + checked.none += 1 + continue + end + checked.vtk += 1 + if not c.primitives then + t:eq(s.polys, v.polys, c.name .. ": polygons (VTK)") + end + t:eq(s.points, v.verts, c.name .. ": points (VTK)") + t:check((s.lines > 0) == (v.lines > 0), c.name .. ": lines (VTK)") + if c.vtkTransforms and v.min then + t:check(C.boundsNear(s.lo, s.hi, v.min, v.max, if c.primitives then 2e-2 else 1e-5), c.name .. ": world bounds (VTK) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(v.min, v.max)) + checked.bounds += 1 + end +end +t:note("%d files: %d against VTK (%d with bounds), %d VTK cannot read", #Cases, checked.vtk, checked.bounds, checked.none) + +-- ------------------------------------------------------------------------------------------------ exact expectations +local function prims(scene: any): { any } + local out = {} + for _, pl in Types.Scene.flatten(scene) do + table.insert(out, pl) + end + return out +end + +do + local hw = byName["assimp/HelloWorld.wrl"] + if hw then + t:eq(#hw.cameras, 1, "HelloWorld: viewpoint") + t:eq(hw.cameras[1].name, "ViewUpClose", "HelloWorld: viewpoint DEF name") + t:eq(hw.meta.source.title, "Hello World!", "HelloWorld: WorldInfo title") + t:eq(hw.meta.source.skipped.Text, 1, "HelloWorld: Text skipped") + local tex = hw.textures[1] + t:check(tex and tex.uri == "earth-topo.png" and tex.data and tex.mime == "image/png", "HelloWorld: texture from files") + t:eq(hw.materials[1].name, "MaterialOffWhite", "HelloWorld: material DEF name") + t:check(near(hw.materials[1].baseColor[1], 0.980392, 1e-6), "HelloWorld: diffuseColor") + end + local mc = byName["assimp/MotionCaptureROM.WRL"] + if mc then + t:eq(#mc.animations, 1, "MotionCaptureROM: one TimeSensor animation") + local a = mc.animations[1] + t:check(#a.channels >= 20, "MotionCaptureROM: channels " .. #a.channels) + local tmax = 0 + for _, ch in a.channels do + tmax = math.max(tmax, buffer.readf32(ch.input.data, (ch.input.count - 1) * 4)) + end + t:check(near(tmax, 45.27, 1e-4), "MotionCaptureROM: key times x cycleInterval " .. tmax) + end + + -- PROTO expansion, DEF / USE of a Shape (one mesh, two nodes) + local pu = byName["feature/feat_proto_use.wrl"] + if pu then + local s = C.stats(pu) + t:eq(#pu.meshes, 3, "proto: meshes (two instances + a shared shape)") + t:eq(s.prims, 4, "proto: placed primitives") + t:check(C.boundsNear(s.lo, s.hi, { -1, -0.5, -0.5 }, { 3.5, 6, 0.5 }, 1e-4), "proto: bounds " .. C.fmt(s.lo, s.hi)) + local cols = {} + for _, m in pu.materials do + table.insert(cols, string.format("%g %g %g", m.baseColor[1], m.baseColor[2], m.baseColor[3])) + end + table.sort(cols) + t:eq(table.concat(cols, ", "), "0 1 0, 1 0 0", "proto: IS fields (instance value, default)") + end + + -- separate indices, per-face normals / colours, ccw FALSE, solid FALSE + local ix = byName["feature/feat_indices.wrl"] + if ix then + local p1 = ix.meshes[1].primitives[1] + t:eq(p1.attributes.POSITION.count, 8, "indices: corners split by normal / colour / texture index") + t:eq(p1.faces.count, 2, "indices: two quads") + local N, Col, Tx = p1.attributes.NORMAL, p1.attributes.COLOR_0, p1.attributes.TEXCOORD_0 + t:check(buffer.readf32(N.data, 8) == 1 and buffer.readf32(Col.data, 0) == 1 and buffer.readf32(Col.data, 8) == 0, "indices: face 1 normal / colour") + t:check(buffer.readf32(Tx.data, 4) == 1, "indices: t flipped (0 -> 1)") + -- ccw FALSE: the first face is written reversed (0 3 2 1) + t:eq(buffer.readu32(p1.indices.data, 4), 3, "indices: ccw FALSE reverses the winding") + local m = ix.materials[p1.material] + t:check(m.doubleSided and m.alphaMode == "blend" and near(m.baseColor[4], 0.75, 1e-6), "indices: solid FALSE, transparency") + t:check(m.extras.vrml.shininess == 0.5 and m.extras.vrml.specularColor[1] == 1, "indices: Phong terms in extras") + local p2 = ix.meshes[2].primitives[1] + t:eq(p2.attributes.POSITION.count, 5, "indices: per-vertex colour indices") + t:check(p2.material == nil, "indices: no appearance, no material") + end + + -- primitives: exact bounds, unit normals + local pr = byName["feature/feat_primitives.wrl"] + if pr then + local s = C.stats(pr) + t:check(C.boundsNear(s.lo, s.hi, { -4.5, -2, -1.5 }, { 9, 2, 1.5 }, 1e-6), "primitives: bounds " .. C.fmt(s.lo, s.hi)) + local box = pr.meshes[1].primitives[1] + t:eq(box.attributes.POSITION.count, 24, "Box: 24 vertices") + t:eq(box.indices.count, 36, "Box: 12 triangles") + local sph = pr.meshes[2].primitives[1] + local ok = true + local P, N = sph.attributes.POSITION, sph.attributes.NORMAL + for v = 0, P.count - 1 do + for k = 0, 2 do + ok = ok and near(buffer.readf32(P.data, (v * 3 + k) * 4) / 1.5, buffer.readf32(N.data, (v * 3 + k) * 4), 1e-5) + end + end + t:check(ok, "Sphere: normals = position / radius") + -- outward winding: the Box's first triangle faces +z + local function faceNormal(prim: any, tri: number): { number } + local function p(i: number): { number } + local v = buffer.readu32(prim.indices.data, (tri * 3 + i) * 4) + return { buffer.readf32(prim.attributes.POSITION.data, v * 12), buffer.readf32(prim.attributes.POSITION.data, v * 12 + 4), buffer.readf32(prim.attributes.POSITION.data, v * 12 + 8) } + end + local a, b, c = p(0), p(1), p(2) + local e1, e2 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] }, { c[1] - a[1], c[2] - a[2], c[3] - a[3] } + return { e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] } + end + t:check(faceNormal(box, 0)[3] > 0, "Box: counter-clockwise front faces") + local cyl = pr.meshes[4].primitives[1] + local last = cyl.indices.count // 3 - 1 + t:check(faceNormal(cyl, last)[2] < 0, "Cylinder: bottom cap faces down") + t:check(faceNormal(cyl, 0)[3] < 0 or faceNormal(cyl, 0)[1] ~= 0, "Cylinder: side faces outwards") + end + + local ge = byName["feature/feat_grid_extrusion.wrl"] + if ge then + local grid, ex = ge.meshes[1].primitives[1], ge.meshes[2].primitives[1] + t:eq(grid.attributes.POSITION.count, 12, "ElevationGrid: vertices") + t:eq(grid.faces.count, 6, "ElevationGrid: quads") + t:eq(ex.attributes.POSITION.count, 16, "Extrusion: closed cross section shares its seam") + t:eq(ex.faces.count, 14, "Extrusion: sides + caps") + local s = C.stats(ge) + t:check(near(s.hi[2], 3, 1e-6) and near(s.hi[3], 4, 1e-6), "ElevationGrid: heights and spacing") + end + + local sc = byName["feature/feat_scene.wrl"] + if sc then + t:eq(sc.meta.source.title, "feature scene", "scene: title") + t:eq(#sc.cameras, 1, "scene: viewpoint") + t:check(near(sc.cameras[1].yfov, 0.9, 1e-9) and sc.cameras[1].name == "Cam", "scene: fieldOfView") + local types = {} + for _, l in sc.lights do + types[l.type] = l + end + t:check(types.directional and types.point and types.spot, "scene: three light types") + t:check(types.point.range == 10 and near(types.spot.outerCone, 0.6, 1e-9) and near(types.spot.innerCone, 0.4, 1e-9), "scene: radius, cones") + -- the directional light's node turns -z onto its direction (0, -1, -1) + for _, n in sc.nodes do + if n.light and sc.lights[n.light].type == "directional" then + local m = Mat4.fromQuat(n.rotation) + local x, y, z = Mat4.point(m, 0, 0, -1) + t:check(near(x, 0, 1e-6) and near(y, -math.sqrt(0.5), 1e-6) and near(z, -math.sqrt(0.5), 1e-6), "scene: light direction") + end + end + t:eq(#sc.animations, 1, "scene: animation") + local a = sc.animations[1] + t:eq(a.name, "Clock", "scene: animation named after its TimeSensor") + t:eq(#a.channels, 2, "scene: translation + rotation channels") + local tr = a.channels[1].path == "translation" and a.channels[1] or a.channels[2] + t:check(near(buffer.readf32(tr.input.data, 8), 4, 1e-6), "scene: key 1 x cycleInterval 4") + -- translation keys move the outer node: key + center + t:check(near(buffer.readf32(tr.output.data, 12), 1, 1e-6) and near(buffer.readf32(tr.output.data, 16), 2, 1e-6), "scene: translation key + center") + -- PixelTexture: the first row of the file is the bottom one + local img + for _, tex in sc.textures do + img = img or tex.image + end + t:check(img and img.width == 2 and buffer.readu8(img.pixels, 2) == 255 and buffer.readu8(img.pixels, 8) == 255 and buffer.readu8(img.pixels, 9) == 0, "scene: PixelTexture pixels") + -- Switch whichChoice 1: the sphere only; LOD: the first level; Inline: part.wrl + local s = C.stats(sc) + t:check(near(s.lo[2], -3.1, 1e-6), "scene: Inline file placed") + -- center / scaleOrientation: the line set's first point (0, 0, 0) under T C R SR S -SR -C + local mover = nil + for _, pl in prims(sc) do + if pl.primitive.mode == "lines" then + mover = pl + end + end + if mover then + local sr = Mat4.axisAngle(0, 0, 1, math.deg(0.5)) + local m = Mat4.mul(Mat4.translation(1, 0, 0), Mat4.mul(Mat4.fromQuat(sr), Mat4.mul(Mat4.scaling(1, 2, 1), Mat4.mul(Mat4.fromQuat({ -sr[1], -sr[2], -sr[3], sr[4] }), Mat4.translation(-1, 0, 0))))) + local ok = true + for k = 1, 16 do + ok = ok and near(mover.matrix[k], m[k], 1e-6) + end + t:check(ok, "scene: Transform center / scaleOrientation") + end + t:eq(sc.meta.unit, 1, "scene: metres") + end +end + +-- ------------------------------------------------------------------------------------------------ writer +local function compare(a: any, b: any, label: string) + local sa, sb = C.stats(a), C.stats(b) + t:eq(sb.prims, sa.prims, label .. ": placed primitives") + t:eq(sb.polys, sa.polys, label .. ": faces") + t:eq(sb.lines, sa.lines, label .. ": line segments") + t:eq(sb.points, sa.points, label .. ": points") + if sa.prims > 0 and sa.lo[1] <= sa.hi[1] then + t:check(C.boundsNear(sa.lo, sa.hi, sb.lo, sb.hi, 1e-5), label .. ": bounds " .. C.fmt(sa.lo, sa.hi) .. " vs " .. C.fmt(sb.lo, sb.hi)) + t:check(near(sa.area, sb.area, 1e-4), string.format("%s: area %.6g / %.6g", label, sa.area, sb.area)) + end + t:eq(#b.materials, #a.materials, label .. ": materials") + for k, m in a.materials do + local m2 = b.materials[k] + if m2 then + local ok = true + for q = 1, 4 do + ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6) + end + t:check(ok, label .. ": material " .. k .. " colour") + t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture") + end + end + t:eq(#b.cameras, #a.cameras, label .. ": cameras") + t:eq(#b.lights, #a.lights, label .. ": lights") +end + +local rt = 0 +for i, c in Cases do + local a = scenes[i] + if a then + local files = {} + local out, err = Vrml.encode(a, { files = files, name = "rt.wrl" }) + t:check(out, c.name .. ": encode: " .. tostring(err)) + if out then + local b, e2 = decode(out, { files = files, triangulate = false }) + t:check(b, c.name .. ": re-decode: " .. tostring(e2)) + if b then + compare(a, b, c.name .. " (round trip)") + t:eq(#b.animations, #a.animations, c.name .. " (round trip): animations") + rt += 1 + end + end + end +end + +-- glTF samples through VRML: world triangles, materials, textures, cameras, lights, animation samples +local gltfScenes = {} +for i, c in GltfCases do + local g = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if not g then + continue + end + gltfScenes[i] = g + local files = {} + local out, err = Vrml.encode(g, { files = files, name = "model.wrl" }) + t:check(out, c.name .. ": encode: " .. tostring(err)) + if not out then + continue + end + local b = decode(out, { files = files }) + t:check(b, c.name .. ": decode our VRML") + if not b then + continue + end + local ga = C.stats(g) + local sb = C.stats(b) + t:check(C.boundsNear(ga.lo, ga.hi, sb.lo, sb.hi, 1e-5), c.name .. ": bounds through VRML " .. C.fmt(ga.lo, ga.hi) .. " vs " .. C.fmt(sb.lo, sb.hi)) + t:check(near(ga.area, sb.area, 1e-4), c.name .. ": area through VRML") + t:eq(sb.points, ga.points, c.name .. ": points through VRML") + t:eq(#b.cameras, #g.cameras, c.name .. ": cameras through VRML") + for k, tex in g.textures do + local t2 = b.textures[k] + if tex.data and t2 then + t:check(t2.data and buffer.tostring(t2.data) == buffer.tostring(tex.data), c.name .. ": texture " .. k .. " bytes") + end + end + -- animations: the translation / rotation / scale channels, sampled at their keys + local want = 0 + for _, a in g.animations do + for _, ch in a.channels do + if ch.path ~= "weights" then + want += 1 + end + end + end + local got = 0 + for _, a in b.animations do + got += #a.channels + end + t:eq(got, want, c.name .. ": animation channels through VRML") + rt += 1 +end +t:note("%d round trips", rt) + +-- VTK reads our files like the originals +local xc = 0 +for _, x in Xcheck do + local v = x.vtk + local src = if x.case then scenes[x.case] else (if x.gltf then gltfScenes[x.gltf] else nil) + local srcCase = if x.case then Cases[x.case] else nil + if src and not v.failed and v.actors > 0 then + local s = C.stats(src) + if not (srcCase and srcCase.primitives) then + -- our IndexedFaceSets keep polygons; VTK counts them + t:eq(v.polys, s.polys, x.name .. ": polygons (VTK reads our file)") + end + t:eq(v.verts, s.points, x.name .. ": points (VTK reads our file)") + if x.vtkTransforms and v.min and s.lo[1] <= s.hi[1] then + t:check(C.boundsNear(s.lo, s.hi, v.min, v.max, 1e-4), x.name .. ": bounds (VTK reads our file) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(v.min, v.max)) + end + xc += 1 + end +end +t:note("%d of our files read by VTK", xc) + +-- ------------------------------------------------------------------------------------------------ api, options, errors +do + local text = Cases[1].data + t:eq(F.detect(text), "vrml", "F.detect") + local s = F.load(text, { files = Cases[1].files }) + t:check(s and s.meta.source.format == "vrml", "F.load") + local gz = Deflate.gzip(text) + local sg = decode(gz :: buffer) + t:check(sg and #sg.meshes == #s.meshes, "gzipped .wrz") + local tri = decode(Cases[1].data) + t:check(tri and tri.meshes[1].primitives[1].mode == "triangles", "triangulated by default") + local seg = decode(Cases[1].data, { segments = 8 }) + t:check(seg and seg.meshes[1].primitives[1].attributes.POSITION.count < s.meshes[1].primitives[1].attributes.POSITION.count, "segments option") + local _, e1 = decode("#VRML V1.0 ascii\nSeparator { }") + t:check(e1 and e1.code == Err.UNSUPPORTED, "VRML 1.0: " .. tostring(e1)) + local _, e2 = decode("#VRML V2.0 utf8\nShape { geometry Box { size 1 1 1 }") + t:check(e2 and e2.code == Err.CORRUPT, "unclosed node: " .. tostring(e2)) + local _, e3 = decode("#VRML V2.0 utf8\nShape { appearance USE Nothing }") + t:check(e3 and e3.code == Err.CORRUPT, "USE of an undefined name: " .. tostring(e3)) + local _, e4 = decode('#VRML V2.0 utf8\nWorldInfo { title "open') + t:check(e4 and e4.code == Err.TRUNCATED, "unterminated string: " .. tostring(e4)) + local deep = "#VRML V2.0 utf8\n" .. string.rep("Group { children [ ", 300) .. string.rep("] } ", 300) + local _, e5 = decode(deep) + t:check(e5 and e5.code == Err.LIMIT, "nesting limit: " .. tostring(e5)) + local _, e6 = decode("#VRML V2.0 utf8\nShape { geometry ElevationGrid { xDimension 5000 zDimension 5000 } }", { maxVertices = 1000 }) + t:check(e6 and e6.code == Err.LIMIT, "maxVertices: " .. tostring(e6)) + local _, e7 = Vrml.encode({} :: any) + t:check(e7 and e7.code == Err.ARG, "encode junk") + -- a quad written as one polygon and read back as one + local p = Types.Scene.accessor(nil, "f32", 3, 4) + for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } } do + for k = 1, 3 do + buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k]) + end + end + local faces = Types.Scene.accessor(nil, "u32", 1, 1) + buffer.writeu32(faces.data, 0, 4) + local ind = Types.Scene.accessor(nil, "u32", 1, 4) + for k = 0, 3 do + buffer.writeu32(ind.data, k * 4, k) + end + local quad = Types.Scene.fromPrimitive({ attributes = { POSITION = p }, indices = ind, faces = faces, mode = "polygons" }, "quad") + local q = decode(Vrml.encode(quad) :: buffer, { triangulate = false }) + t:check(q and q.meshes[1].primitives[1].faces.count == 1 and q.nodes[1].name == "quad", "a quad stays one polygon, names kept") +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 = Vrml.decode(Bytes.reader(b), { files = {} }) + if s then + Vrml.encode(s) + end + return s + end, samples, { mutations = 16, keepHeader = 16 }) +end + +t:done() diff --git a/tests/model/x3d.luau b/tests/model/x3d.luau new file mode 100644 index 0000000..6a04f64 --- /dev/null +++ b/tests/model/x3d.luau @@ -0,0 +1,308 @@ +-- model/x3d tests: assimp's X3D / X3DV / X3DB test models, scenes and glTF samples written by VTK's X3D exporter and +-- by assimp's X3D exporter, and hand-written feature files (the X3D triangle / quad / line sets, ColorRGBA, +-- ProtoDeclare / ProtoInstance with SFNode defaults, PhysicalMaterial, UnlitMaterial, OrthoViewpoint, ROUTE +-- animation, UNIT, the classic encoding's header statements), against assimp's X3D reader (meshes, faces, materials, +-- world bounds) and exact expectations; .x3dv against the same model as .x3d; the writer (XML and classic): round +-- trips, and assimp reading our X3D like the originals; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/x3d.py. +local T = require("@tests/T") +local F = require("@formats") +local X3d = require("@formats/model/x3d") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local C = require("@tests/model/_vrml_common") +local Cases = require("@tests/gen/x3d_cases") +local VrmlCases = require("@tests/gen/vrml_cases") +local GltfCases = require("@tests/gen/vrml_gltf") +local Xcheck = require("@tests/gen/x3d_xcheck") +local Gltf = require("@formats/model/gltf") +local Vrml = require("@formats/model/vrml") + +local t = T.suite("x3d") +local near = C.near + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return X3d.decode(Bytes.reader(b), opts) +end + +t:eq(X3d.name, "x3d", "name") +t:eq(X3d.category, "model", "category") +t:check(X3d.caps.decode and X3d.caps.encode, "contract") + +-- assimp's own quirks (its reading is not the specification's): USE'd groups lose their parents' transforms; its X3D +-- exporter writes points and lines as 1- / 2-vertex faces (not valid IndexedFaceSet faces, dropped here) +local QUIRK = { ["assimp/X3D/ComputerKeyboard.x3d"] = "all", ["assimp-export/assimp_MeshPrimitiveModes.x3d"] = "all" } + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes, byName = {}, {} +local checked = { assimp = 0, none = 0 } +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files, triangulate = false }) + if string.find(c.name, "%.x3db$") then + t:check(scene == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": binary X3D is UNSUPPORTED: " .. tostring(err)) + continue + end + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + scenes[i], byName[c.name] = scene, scene + local a = c.assimp + -- (VTK's exporter leaves out: assimp then reads nothing) + local unclosed = a.meshes == 0 and not string.find(c.data, "", 1, true) + if a.skip or a.failed or unclosed or string.find(c.name, "^feature/") then + checked.none += 1 + continue + end + local s = C.stats(scene) + local quirk = QUIRK[c.name] + if quirk ~= "all" then + if quirk ~= "counts" then + t:eq(s.prims, a.meshes, c.name .. ": meshes (assimp: one per placed shape)") + end + if not c.primitives and quirk ~= "counts" then + t:eq(s.polys + s.lines + s.points, a.faces, c.name .. ": faces (assimp)") + end + t:check(#scene.materials <= a.materials, c.name .. ": materials (assimp counts one per use)") + if a.min then + t:check(C.boundsNear(s.lo, s.hi, a.min, a.max, if c.primitives then 5e-3 else 1e-5), c.name .. ": world bounds (assimp) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(a.min, a.max)) + end + end + checked.assimp += 1 +end +t:note("%d files: %d against assimp, %d without a reference", #Cases, checked.assimp, checked.none) + +-- ------------------------------------------------------------------------------------------------ exact expectations +do + local kb = byName["assimp/X3D/ComputerKeyboard.x3d"] + if kb then + local s = C.stats(kb) + t:eq(#kb.meshes, 3, "keyboard: three extrusions (the keys are USE'd)") + t:check(s.prims > 50, "keyboard: every USE placed: " .. s.prims) + t:eq(#kb.animations, 1, "keyboard: the push animation") + t:check(#kb.animations[1].channels == s.prims - 2, "keyboard: one channel per escape-button instance") + t:check(near(s.hi[3], 0.980018, 1e-5) and near(s.lo[2], -0.0002, 1e-3), "keyboard: the base under its rotation") + end + local hw, hv = byName["assimp/X3D/HelloWorld.x3d"], byName["assimp/X3DV/HelloWorld.x3dv"] + if hw and hv then + local a, b = C.stats(hw), C.stats(hv) + t:check(a.polys == b.polys and C.boundsNear(a.lo, a.hi, b.lo, b.hi, 1e-9), ".x3dv = .x3d: geometry") + t:eq(hv.materials[1].baseColor[2], hw.materials[1].baseColor[2], ".x3dv = .x3d: material") + t:check(hv.textures[1].data and hw.textures[1].data, ".x3dv / .x3d: texture from files") + t:eq(hv.meta.source.profile, "Immersive", ".x3dv: PROFILE") + t:eq(hw.meta.source.profile, "Immersive", ".x3d: profile") + t:eq(hv.meta.source.meta.title, "HelloWorld.x3d", ".x3dv: META") + t:eq(hw.meta.source.meta.creator, "Don Brutzman", ".x3d: head meta") + end + local ls = byName["assimp/X3D/IndexedLineSet.x3d"] + if ls then + local p = ls.meshes[1].primitives[1] + t:check(p.mode == "lines" and p.indices.count == 8, "IndexedLineSet: a closed polyline as 4 segments") + t:check(ls.materials[1].emissive[1] == 1, "IndexedLineSet: emissive colour") + end + + local sets = byName["feature/feat_sets.x3d"] + if sets then + local m = sets.meshes + local function tris(k: number): number + local p = m[k].primitives[1] + return if p.mode == "polygons" then p.faces.count else p.indices.count // 3 + end + t:eq(tris(1), 2, "IndexedTriangleSet") + local col = m[1].primitives[1].attributes.COLOR_0 + t:check(col and col.components == 4 and buffer.readf32(col.data, (2 * 4 + 3) * 4) == 0.5, "ColorRGBA alpha") + t:check(sets.materials[m[1].primitives[1].material].doubleSided, "solid false") + t:eq(tris(2), 3, "TriangleFanSet fanCount") + t:eq(tris(3), 3, "IndexedTriangleStripSet runs") + t:check(m[4].primitives[1].faces.count == 1 and m[4].primitives[1].indices.count == 4, "IndexedQuadSet: one quad") + t:eq(tris(5), 2, "TriangleSet") + t:check(m[6].primitives[1].mode == "lines" and m[6].primitives[1].indices.count == 6, "LineSet vertexCount") + -- strips alternate their winding: every triangle of the strip faces +z + local p = m[3].primitives[1] + local ok = true + local P = p.attributes.POSITION + local function v(i: number): (number, number) + local k = buffer.readu32(p.indices.data, i * 4) + return buffer.readf32(P.data, k * 12), buffer.readf32(P.data, k * 12 + 4) + end + local at = 0 + for f = 0, p.faces.count - 1 do + local ax, ay = v(at) + local bx, by = v(at + 1) + local cx, cy = v(at + 2) + ok = ok and (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > 0 + at += buffer.readu32(p.faces.data, f * 4) + end + t:check(ok, "IndexedTriangleStripSet: counter-clockwise triangles") + end + + local pr = byName["feature/feat_proto.x3d"] + if pr then + local s = C.stats(pr) + t:check(C.boundsNear(s.lo, s.hi, { -1.1, -2, -0.5 }, { 1.1, 5, 0.5 }, 1e-6), "protos: instances placed and sized " .. C.fmt(s.lo, s.hi)) + t:eq(pr.meta.unit, 0.01, "UNIT length") + t:eq(pr.meta.source.meta.title, "protos", "head meta") + local kinds = {} + for _, m in pr.materials do + if m.extensions and m.extensions.KHR_materials_unlit then + kinds.unlit = m + elseif m.metallic == 0.25 then + kinds.physical = m + elseif m.baseColor[3] == 1 and m.baseColor[1] == 0 then + kinds.default = m + end + end + t:check(kinds.physical and kinds.physical.roughness == 0.75, "PhysicalMaterial") + t:check(kinds.unlit and kinds.unlit.baseColor[2] == 1, "UnlitMaterial") + t:check(kinds.default ~= nil, "SFNode field default (the proto's appearance)") + t:eq(#pr.materials, 3, "the default appearance is shared by both instances") + local cam = pr.cameras[1] + t:check(cam and cam.type == "orthographic" and cam.xmag == 2 and cam.ymag == 1, "OrthoViewpoint") + local a = pr.animations[1] + t:check(a and a.name == "Clock" and #a.channels == 1 and a.channels[1].path == "rotation", "ROUTE elements -> animation") + t:check(a and near(buffer.readf32(a.channels[1].input.data, 8), 2, 1e-6), "key times x cycleInterval") + -- quaternion keys stay on one hemisphere (0, pi, 2 pi about y) + local q = a and a.channels[1].output + t:check(q and buffer.readf32(q.data, 2 * 16 + 12) < 0, "rotation keys continuous") + end + local cl = byName["feature/feat_classic.x3dv"] + if cl then + local s = C.stats(cl) + t:check(C.boundsNear(s.lo, s.hi, { 1, 2, 3 }, { 2, 3, 4 }, 1e-6), "classic: DEF Transform") + t:eq(cl.meta.unit, 0.001, "classic: UNIT") + t:eq(cl.meta.source.components[1], "Geometry2D:1", "classic: COMPONENT") + t:eq(cl.meta.source.meta.title, "classic", "classic: META") + t:eq(cl.meshes[1].primitives[1].attributes.COLOR_0.components, 4, "classic: ColorRGBA") + end +end + +-- ------------------------------------------------------------------------------------------------ writer +local function compare(a: any, b: any, label: string) + local sa, sb = C.stats(a), C.stats(b) + t:eq(sb.prims, sa.prims, label .. ": placed primitives") + t:eq(sb.polys, sa.polys, label .. ": faces") + t:eq(sb.lines, sa.lines, label .. ": line segments") + t:eq(sb.points, sa.points, label .. ": points") + if sa.prims > 0 and sa.lo[1] <= sa.hi[1] then + t:check(C.boundsNear(sa.lo, sa.hi, sb.lo, sb.hi, 1e-5), label .. ": bounds") + t:check(near(sa.area, sb.area, 1e-4), label .. ": area") + end + t:eq(#b.materials, #a.materials, label .. ": materials") + t:eq(#b.cameras, #a.cameras, label .. ": cameras") + t:eq(#b.lights, #a.lights, label .. ": lights") + t:eq(#b.animations, #a.animations, label .. ": animations") + for k, cam in a.cameras do + t:eq(b.cameras[k].type, cam.type, label .. ": camera type") + end +end +local rt = 0 +for i, c in Cases do + local a = scenes[i] + if a then + for _, enc in { "xml", "x3dv" } do + local files = {} + local out, err = X3d.encode(a, { files = files, encoding = enc :: any }) + t:check(out, c.name .. ": encode " .. enc .. ": " .. tostring(err)) + local b = out and decode(out, { files = files, triangulate = false }) + t:check(b, c.name .. ": decode our " .. enc) + if b then + compare(a, b, c.name .. " (" .. enc .. ")") + rt += 1 + end + end + end +end +t:note("%d round trips", rt) + +-- assimp reads our X3D like the source +local sources: { [string]: { any } } = { xcase = {}, wcase = {}, xgltf = {} } +for i, c in Cases do + sources.xcase[i] = { scenes[i], c } +end +for i, c in VrmlCases do + sources.wcase[i] = { Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }), c } +end +for i, c in GltfCases do + sources.xgltf[i] = { Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }), c } +end +-- assimp loses its place in the tree after an empty (a leaf node: an empty, a locator) +local function hasEmpty(scene: any): boolean + for _, n in scene.nodes do + if #n.children == 0 and not n.mesh and not n.camera and not n.light then + return true + end + end + return false +end +local xc, skipped = 0, 0 +for _, x in Xcheck do + local a = x.assimp + local kind = if x.xcase then "xcase" elseif x.wcase then "wcase" else "xgltf" + local src = sources[kind][x[kind]] + if src and src[1] and (a.failed or a.meshes == 0) and hasEmpty(src[1]) then + skipped += 1 + elseif src and src[1] and not a.failed then + local s = C.stats(src[1]) + t:eq(a.meshes, s.prims, x.name .. ": meshes (assimp reads our file)") + t:eq(a.faces, s.polys + s.lines + s.points, x.name .. ": faces (assimp reads our file)") + -- (shared meshes are written once and USE'd: assimp places USE'd nodes without their parents' transforms) + -- (MotionCaptureROM: assimp misplaces this deep hierarchy; an independent evaluation of our file's transforms + -- agrees with ours) + local deep = src[2].name == "assimp/MotionCaptureROM.WRL" + if a.min and s.lo[1] <= s.hi[1] and s.prims == s.unique and not deep then + t:check(C.boundsNear(s.lo, s.hi, a.min, a.max, 1e-4), x.name .. ": bounds (assimp reads our file) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(a.min, a.max)) + end + xc += 1 + elseif src and src[1] then + t:check(false, x.name .. ": assimp cannot read our file (" .. src[2].name .. ")") + end +end +t:note("%d of our files read by assimp (%d skipped: empty nodes)", xc, skipped) + +-- ------------------------------------------------------------------------------------------------ api, errors +do + local hw = Cases[2] + t:eq(F.detect(hw.data), "x3d", "F.detect .x3d") + t:eq(F.detect(Cases[5].data), "x3d", "F.detect .x3dv") + local s = F.load(hw.data, { files = hw.files }) + t:check(s and s.meta.source.format == "x3d", "F.load") + local x3dv = F.save(s, nil, { format = "x3dv" }) + t:check(x3dv and buffer.readstring(x3dv, 0, 5) == "#X3D ", "F.save format x3dv: the classic encoding") + local xml = F.save(s, nil, { format = "x3d" }) + t:check(xml and string.find(buffer.tostring(xml), "") + t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "mismatched XML: " .. tostring(e1)) + local _, e2 = decode("") + t:check(e2 and e2.code == Err.CORRUPT, "not X3D: " .. tostring(e2)) + -- VTK leaves the root element open: read anyway + local open = decode("\n") + t:check(open and #open.meshes == 1, "an unclosed root (VTK's exporter)") + local _, e3 = X3d.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "encode junk") + -- containerField and USE in XML + local u = decode([[ + + ]]) + local us = u and C.stats(u) + t:check(us and #u.meshes == 2 and us.prims == 3 and near(us.hi[1], 6, 1e-9) and near(us.hi[2], 2, 1e-6), "USE / containerField / Switch in XML") +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 = X3d.decode(Bytes.reader(b), { files = {} }) + if s then + X3d.encode(s) + end + return s + end, samples, { mutations = 16, keepHeader = 16 }) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 7369aa5..77fbfda 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -919,6 +919,19 @@ do bench("3mf encode", 2, buffer.len(tmf), function() ThreeMf.encode(scene) end) + local Wrl = require("@formats/model/vrml") + local X3d = require("@formats/model/x3d") + local wrl = assert(Wrl.encode(scene)) + bench("vrml decode (" .. buffer.len(wrl) // 1000 .. " KB)", 2, buffer.len(wrl), function() + Wrl.decode(Bytes.reader(wrl)) + end) + bench("vrml encode", 2, buffer.len(wrl), function() + Wrl.encode(scene) + end) + local x3d = assert(X3d.encode(scene)) + bench("x3d xml decode (" .. buffer.len(x3d) // 1000 .. " KB)", 2, buffer.len(x3d), function() + X3d.decode(Bytes.reader(x3d)) + end) local V = 128 local grid = Types.Voxels.new(V, V, V) for z = 0, V - 1 do diff --git a/tools/fixtures/_pmx_writer.py b/tools/fixtures/_pmx_writer.py new file mode 100644 index 0000000..dcace7d --- /dev/null +++ b/tools/fixtures/_pmx_writer.py @@ -0,0 +1,265 @@ +# A small PMX 2.0 / 2.1 (and PMD 1.0) writer for tools/fixtures/pmx.py: synthetic MikuMikuDance models that use every +# vertex deform type (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), both text encodings, every index size, additional UVs, +# several materials (texture / sphere / toon references), a bone chain with IK / inherit / fixed-axis / local-axis +# bones, every morph type, display frames, rigid bodies and joints. Written from the PMX 2.0 / 2.1 specification notes +# (PmxEditor's "PMX仕様") and the PMD layout; no third-party code. +import math, struct + + +def f32s(*v): + return struct.pack("<%df" % len(v), *v) + + +class Pmx: + def __init__(self, version=2.0, utf8=False, sizes=(2, 1, 1, 2, 1, 1), uva=0): + self.version, self.utf8, self.uva = version, utf8, uva + self.vsize, self.tsize, self.msize, self.bsize, self.morsize, self.rsize = sizes + + def text(self, s): + b = s.encode("utf-8") if self.utf8 else s.encode("utf-16-le") + return struct.pack("= 2.1: + out += struct.pack("= 2.1 else [])) + verts = [] + for r in range(rings): + y = r * 2.0 + for s in range(seg): + a = 2 * math.pi * s / seg + x, z = math.cos(a) * 1.5, math.sin(a) * 1.5 + 0.25 * r + b0 = min(nbones - 1, r * nbones // rings) + b1 = min(nbones - 1, b0 + 1) + k = kinds[(r * seg + s) % len(kinds)] + w = rnd.random() + if k == 0: + bones, weights = [b0], [1.0] + elif k in (1, 3): + bones, weights = [b0, b1], [w] + else: + ws = [rnd.random() + 0.1 for _ in range(4)] + bones, weights = [b0, b1, max(0, b0 - 1), -1 if k == 2 else nbones - 1], [x / sum(ws) * 0.9 for x in ws] + verts.append({ + "pos": (x, y, z), "normal": (math.cos(a), 0.0, math.sin(a)), "uv": (s / seg, r / (rings - 1)), + "uva": [(rnd.random(), rnd.random(), rnd.random(), rnd.random()) for _ in range(uva)], + "deform": k, "bones": bones, "weights": weights, "edge": 1.0, + "sdef": ((0.0, y, 0.0), (0.0, y - 1, 0.0), (0.0, y + 1, 0.0)), + }) + faces = [] + for r in range(rings - 1): + for s in range(seg): + a, b = r * seg + s, r * seg + (s + 1) % seg + c, d = a + seg, b + seg + faces += [a, c, b, b, c, d] + ntri = len(faces) // 3 + counts, left = [], ntri + for k in range(nmat): + n = left if k == nmat - 1 else max(1, ntri // nmat) + counts.append(n * 3) + left -= n + mats = [] + for k in range(nmat): + mats.append({ + "name": "材質%d" % k, "nameEn": "mat%d" % k, "diffuse": (0.8, 0.2 + 0.2 * k, 0.1, 1.0 if k != 1 else 0.5), + "specular": (0.1, 0.1, 0.1), "power": 5.0 + 10 * k, "ambient": (0.4, 0.1, 0.05), "flags": [0x01 | 0x10, 0x04 | 0x08, 0x02][k % 3], + "edgeColor": (0, 0, 0, 1), "edgeSize": 1.0, "texture": 0 if k == 0 else -1, "sphere": 1 if k == 0 else -1, + "sphereMode": 1 if k == 0 else 0, "toonShared": 3 if k != 2 else None, "toon": 2, "memo": "memo %d" % k, "count": counts[k], + }) + bones = [] + for i in range(nbones): + fl = 0x1A | (1 if i < nbones - 1 else 0) + b = {"name": "骨%d" % i, "nameEn": "bone%d" % i, "pos": (0.0, i * (rings - 1) * 2.0 / max(1, nbones - 1), 0.25 * i), "parent": i - 1, + "layer": 0, "flags": fl, "tail": i + 1 if i < nbones - 1 else (0.0, 1.0, 0.0)} + if i == 1: + b["flags"] |= 0x100 + b["inherit"] = (0, 0.5) + if i == 2: + b["flags"] |= 0x400 | 0x800 + b["axis"] = (0.0, 1.0, 0.0) + b["localX"], b["localZ"] = (1.0, 0.0, 0.0), (0.0, 0.0, 1.0) + bones.append(b) + # an IK bone at the end targeting the last chain bone + bones.append({"name": "IK", "nameEn": "leg IK", "pos": (2.0, 0.0, 0.0), "parent": -1, "layer": 1, "flags": 0x1E | 0x20, "tail": (0.0, 0.0, 1.0), + "ik": {"target": nbones - 1, "loops": 40, "limit": 2.0, "links": [{"bone": nbones - 2, "min": (-3.14, 0, 0), "max": (-0.01, 0, 0)}, {"bone": max(0, nbones - 3)}]}}) + morphs = [ + {"name": "上", "nameEn": "up", "panel": 1, "type": 1, "offsets": [(i, (0.0, 0.5, -0.25)) for i in range(0, len(verts), 3)]}, + {"name": "広", "nameEn": "wide", "panel": 2, "type": 1, "offsets": [(i, (0.3, 0.0, 0.1)) for i in range(1, len(verts), 2)]}, + {"name": "uv", "nameEn": "uv", "panel": 3, "type": 3, "offsets": [(0, (0.1, 0.2, 0, 0))]}, + {"name": "骨", "nameEn": "bonem", "panel": 4, "type": 2, "offsets": [(1, (0, 1, 0), (0, 0, 0, 1))]}, + {"name": "材", "nameEn": "matm", "panel": 4, "type": 8, "offsets": [(-1, 0, (1,) * 28)]}, + {"name": "群", "nameEn": "group", "panel": 4, "type": 0, "offsets": [(0, 0.5), (1, 1.0)]}, + ] + if uva: + morphs.append({"name": "uva", "nameEn": "uva1", "panel": 3, "type": 4, "offsets": [(2, (0.5, 0.5, 0.5, 0.5))]}) + if version >= 2.1 and flips: # assimp 6 rejects these morph types + morphs.append({"name": "flip", "nameEn": "flip", "panel": 4, "type": 9, "offsets": [(0, 1.0)]}) + morphs.append({"name": "imp", "nameEn": "impulse", "panel": 4, "type": 10, "offsets": [(0, 1, (0, 1, 0), (0, 0, 0))]}) + frames = [{"name": "Root", "nameEn": "Root", "special": 1, "items": [(0, 0)]}, + {"name": "表情", "nameEn": "Exp", "special": 1, "items": [(1, 0), (1, 1)]}] + rigid = [{"name": "rb%d" % i, "nameEn": "rb%d" % i, "bone": i, "group": i, "mask": 0xFFFF, "shape": i % 3, "size": (1, 2, 3), + "pos": (0, i, 0), "rot": (0, 0, 0), "mass": 1.0, "mode": i % 3} for i in range(2)] + joints = [{"name": "j0", "nameEn": "j0", "a": 0, "b": 1, "pos": (0, 1, 0)}] + return {"name": name, "nameEn": name + " en", "comment": "コメント", "commentEn": "comment", "vertices": verts, "indices": faces, + "textures": ["tex\\body.png", "s.sph", "toon.bmp"], "materials": mats, "bones": bones, "morphs": morphs, + "frames": frames, "rigid": rigid, "joints": joints} + + +def pmd(m): + """the same model as PMD 1.0 (BDEF2-style weights only, ASCII names, toon list, English names)""" + def name(s, n): + b = s.encode("ascii", "replace")[: n - 1] + return b + b"\0" * (n - len(b)) + out = bytearray(b"Pmd") + struct.pack("= 0 else "" + if mat["sphere"] >= 0: + tex += "*" + m["textures"][mat["sphere"]] + out += f32s(*mat["diffuse"], mat["power"], *mat["specular"], *mat["ambient"]) + out += struct.pack("\t" lines for +-- VTK (.wrl) and assimp (.x3d) to read back. Files: case_.wrl, gltf_.wrl, xcase_.x3d, xgltf_.x3d. +local Vrml = require("@formats/model/vrml") +local X3d = require("@formats/model/x3d") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/vrml_cases") +local GltfCases = require("@tests/gen/vrml_gltf") +local ok, X3dCases = pcall(require, "@tests/gen/x3d_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +local function both(scene: any, wrl: string, x3d: string) + local a = Vrml.encode(scene) + if a then + print(wrl .. "\t" .. hex(a)) + end + local b = X3d.encode(scene) + if b then + print(x3d .. "\t" .. hex(b)) + end +end + +for i, c in Cases do + local scene = Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }) + if scene then + both(scene, string.format("case_%d.wrl", i), string.format("wcase_%d.x3d", i)) + end +end +for i, c in GltfCases do + local scene = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if scene then + both(scene, string.format("gltf_%d.wrl", i), string.format("xgltf_%d.x3d", i)) + end +end +if ok and type(X3dCases) == "table" then + for i, c in X3dCases do + local scene = X3d.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }) + if scene then + both(scene, string.format("xcase_%d.wrl", i), string.format("xcase_%d.x3d", i)) + end + end +end diff --git a/tools/fixtures/_vrml_ref.py b/tools/fixtures/_vrml_ref.py new file mode 100644 index 0000000..2a0b137 --- /dev/null +++ b/tools/fixtures/_vrml_ref.py @@ -0,0 +1,241 @@ +# Shared helpers for tools/fixtures/vrml.py and x3d.py: VTK (nixpkgs python3 vtk) as the VRML97 reference reader and +# as a writer of more .wrl / .x3d inputs, assimp's X3D reader for .x3d, and the hand-written feature files. +# vtk_read(ctx, paths) -> [ { actors, polys, lines, verts, points, min, max } | { failed } ] (vtkVRMLImporter) +# vtk_export(ctx, outdir, gltf_paths) -> [ (name, wrl path, x3d path) ] (vtkVRMLExporter / vtkX3DExporter scenes) +# FEATURES: { name: VRML97 text } covering PROTO, DEF / USE, Switch, LOD, primitives, per-face colours, separate +# indices, ElevationGrid, Extrusion, ROUTE animation, lights, viewpoints, Inline, PixelTexture +import json + +VTK_READ = r""" +import json, os, sys, vtk +vtk.vtkObject.GlobalWarningDisplayOff() + +def read(p): + imp = vtk.vtkVRMLImporter(); imp.SetFileName(p) + rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw) + imp.Update() + acts = imp.GetRenderer().GetActors(); acts.InitTraversal() + out = {"actors": 0, "polys": 0, "lines": 0, "verts": 0, "points": 0} + lo, hi = [1e30] * 3, [-1e30] * 3 + for i in range(acts.GetNumberOfItems()): + a = acts.GetNextActor() + m = a.GetMapper() + if not m: + continue + m.Update() + d = m.GetInput() + if d is None or d.GetNumberOfPoints() == 0: + continue + out["actors"] += 1 + out["polys"] += d.GetNumberOfPolys() + d.GetNumberOfStrips() + out["lines"] += d.GetNumberOfLines() + out["verts"] += d.GetNumberOfVerts() + out["points"] += d.GetNumberOfPoints() + # tight world bounds: every point through the actor's matrix (GetBounds boxes the local bounds) + mat = a.GetMatrix() + pts = d.GetPoints() + for j in range(d.GetNumberOfPoints()): + p = pts.GetPoint(j) + w = mat.MultiplyPoint((p[0], p[1], p[2], 1.0)) + for k in range(3): + lo[k] = min(lo[k], w[k]); hi[k] = max(hi[k], w[k]) + if out["actors"]: + out["min"], out["max"] = lo, hi + return out + +# one child process per file: vtkVRMLImporter crashes on some valid files +res = [] +for p in json.loads(sys.stdin.read()): + r, w = os.pipe() + pid = os.fork() + if pid == 0: + os.close(r) + try: + data = json.dumps(read(p)) + except Exception: + data = json.dumps({"failed": True}) + os.write(w, data.encode()) + os._exit(0) + os.close(w) + chunks = [] + while True: + b = os.read(r, 65536) + if not b: + break + chunks.append(b) + os.close(r) + _, status = os.waitpid(pid, 0) + try: + res.append(json.loads(b"".join(chunks).decode()) if status == 0 else {"failed": True, "crashed": True}) + except ValueError: + res.append({"failed": True}) +print("RESULT " + json.dumps(res)) +""" + +VTK_EXPORT = r""" +import json, os, sys, vtk +vtk.vtkObject.GlobalWarningDisplayOff() +args = json.loads(sys.stdin.read()) +out, gltfs = args["out"], args["gltf"] +made = [] + +def export(ren, name): + rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); rw.AddRenderer(ren) + ren.ResetCamera() + w = vtk.vtkVRMLExporter(); w.SetRenderWindow(rw); w.SetFileName(os.path.join(out, name + ".wrl")); w.Write() + x = vtk.vtkX3DExporter(); x.SetRenderWindow(rw); x.SetFileName(os.path.join(out, name + ".x3d")); x.SetBinary(0); x.Write() + made.append(name) + +def actor(src, pos=(0, 0, 0), scale=(1, 1, 1), rot=(0, 0, 0), color=None, scalars=False): + m = vtk.vtkPolyDataMapper(); m.SetInputConnection(src.GetOutputPort()) + if not scalars: + m.ScalarVisibilityOff() + a = vtk.vtkActor(); a.SetMapper(m); a.SetPosition(*pos); a.SetScale(*scale) + a.RotateX(rot[0]); a.RotateY(rot[1]); a.RotateZ(rot[2]) + if color: + a.GetProperty().SetColor(*color) + return a + +# 1. primitives as polygon meshes, transformed, coloured, one with point scalars +ren = vtk.vtkRenderer() +s = vtk.vtkSphereSource(); s.SetThetaResolution(16); s.SetPhiResolution(8) +ren.AddActor(actor(s, (1, 2, 3), (2, 2, 2), (30, 0, 0), (0.9, 0.2, 0.1))) +c = vtk.vtkConeSource(); c.SetResolution(12) +ren.AddActor(actor(c, (-3, 0, 1), (1, 3, 1), (0, 45, 10), (0.2, 0.8, 0.3))) +cube = vtk.vtkCubeSource(); cube.SetXLength(2); cube.SetYLength(1); cube.SetZLength(0.5) +ren.AddActor(actor(cube, (0, -2, 0), (1, 1, 1), (0, 0, 20), (0.3, 0.3, 0.9))) +keep = [vtk.vtkSphereSource(), vtk.vtkSphereSource(), vtk.vtkCubeSource()] +el = vtk.vtkElevationFilter(); el.SetInputConnection(keep[0].GetOutputPort()); el.SetLowPoint(0, -0.5, 0); el.SetHighPoint(0, 0.5, 0) +ren.AddActor(actor(el, (4, 4, 0), scalars=True)) +light = vtk.vtkLight(); light.SetPosition(5, 5, 5); light.SetFocalPoint(0, 0, 0); light.SetColor(1, 0.9, 0.8) +ren.AddLight(light) +export(ren, "vtk_shapes") + +# 2. lines and points +ren = vtk.vtkRenderer() +ls = vtk.vtkLineSource(); ls.SetPoint1(0, 0, 0); ls.SetPoint2(3, 1, 2); ls.SetResolution(5) +ren.AddActor(actor(ls, (1, 0, 0), color=(1, 1, 0))) +pts = vtk.vtkPointSource(); pts.SetNumberOfPoints(40); pts.SetRadius(2); pts.SetCenter(0, 5, 0) +ren.AddActor(actor(pts)) +ren.AddActor(actor(keep[2], (0, 0, -4))) +export(ren, "vtk_lines_points") + +# 3. a textured plane (PixelTexture) and a strip mesh +ren = vtk.vtkRenderer() +pl = vtk.vtkPlaneSource(); pl.SetResolution(3, 2) +img = vtk.vtkImageCanvasSource2D(); img.SetScalarTypeToUnsignedChar(); img.SetNumberOfScalarComponents(3); img.SetExtent(0, 7, 0, 3, 0, 0) +img.SetDrawColor(200, 30, 30); img.FillBox(0, 7, 0, 3); img.SetDrawColor(20, 30, 200); img.FillBox(0, 3, 0, 1); img.Update() +tex = vtk.vtkTexture(); tex.SetInputConnection(img.GetOutputPort()) +a = actor(pl, (0, 0, 1), (4, 2, 1)); a.SetTexture(tex) +ren.AddActor(a) +strip = vtk.vtkStripper(); strip.SetInputConnection(keep[1].GetOutputPort()) +ren.AddActor(actor(strip, (0, 3, 0))) +export(ren, "vtk_texture_strips") + +# 4. glTF sample models through VTK's glTF importer +for g in gltfs: + try: + imp = vtk.vtkGLTFImporter(); imp.SetFileName(g) + rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw); imp.Update() + name = "vtk_gltf_" + os.path.splitext(os.path.basename(g))[0] + export(imp.GetRenderer(), name) + except Exception: + pass +print("RESULT " + json.dumps(made)) +""" + + +def vtk_xform_ok(data): + """False when vtkVRMLImporter's transforms are wrong for the file: it ignores center and scaleOrientation""" + import re + return not re.search(rb"\b(center|scaleOrientation)\s+[-+\d.]", data) + + +def _run(ctx, code, arg): + out = ctx.python(["vtk"], code, input=json.dumps(arg).encode()).decode("utf-8", "replace") + for line in out.split("\n"): + if line.startswith("RESULT "): + return json.loads(line[7:]) + raise RuntimeError("vtk script printed no result") + + +def vtk_read(ctx, paths): + return _run(ctx, VTK_READ, paths) if paths else [] + + +def vtk_export(ctx, outdir, gltfs): + return _run(ctx, VTK_EXPORT, {"out": outdir, "gltf": gltfs}) + + +FEATURES = { + "feat_proto_use.wrl": """#VRML V2.0 utf8 +PROTO Brick [ field SFVec3f size 1 1 1 field SFColor col 1 0 0 exposedField SFVec3f where 0 0 0 ] { + Transform { translation IS where children Shape { + appearance Appearance { material Material { diffuseColor IS col } } + geometry Box { size IS size } } } +} +DEF A Brick { size 2 1 1 col 0 1 0 where 0 0 0 } +Brick { where 3 0 0 } +Transform { translation 0 3 0 children [ DEF S Shape { geometry IndexedFaceSet { + coord DEF C Coordinate { point [ 0 0 0, 1 0 0, 1 1 0, 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ] } } ] } +Transform { translation 0 5 0 rotation 0 0 1 1.5708 children USE S } +""", + "feat_indices.wrl": """#VRML V2.0 utf8 +# separate normal / colour / texture indices, per-face colours, ccw FALSE, solid FALSE +Shape { + appearance Appearance { material Material { diffuseColor 0.5 0.5 0.5 transparency 0.25 shininess 0.5 specularColor 1 1 1 } } + geometry IndexedFaceSet { + solid FALSE ccw FALSE + coord Coordinate { point [ 0 0 0, 2 0 0, 2 2 0, 0 2 0, 0 0 2, 2 0 2 ] } + coordIndex [ 0 1 2 3 -1, 0 4 5 1 -1 ] + normal Normal { vector [ 0 0 1, 0 -1 0 ] } + normalPerVertex FALSE normalIndex [ 0 1 ] + color Color { color [ 1 0 0, 0 0 1 ] } + colorPerVertex FALSE + texCoord TextureCoordinate { point [ 0 0, 1 0, 1 1, 0 1 ] } + texCoordIndex [ 0 1 2 3 -1, 3 2 1 0 -1 ] + } +} +Shape { geometry IndexedFaceSet { + coord Coordinate { point [ 5 0 0, 6 0 0, 6 1 0, 5 1 0 ] } + coordIndex [ 0 1 2 -1 0 2 3 ] + color Color { color [ 1 0 0, 0 1 0, 0 0 1, 1 1 1 ] } colorIndex [ 3 2 1 -1 0 1 2 -1 ] } } +""", + "feat_primitives.wrl": """#VRML V2.0 utf8 +Transform { translation -4 0 0 children Shape { geometry Box { size 1 2 3 } } } +Transform { translation 0 0 0 children Shape { geometry Sphere { radius 1.5 } } } +Transform { translation 4 0 0 children Shape { geometry Cone { bottomRadius 1 height 3 } } } +Transform { translation 8 0 0 scale 2 1 1 children Shape { geometry Cylinder { radius 0.5 height 4 } } } +""", + "feat_grid_extrusion.wrl": """#VRML V2.0 utf8 +Shape { geometry ElevationGrid { xDimension 4 zDimension 3 xSpacing 1 zSpacing 2 + height [ 0 1 0 1, 1 2 1 0, 0 0 1 3 ] } } +Transform { translation 6 0 0 children Shape { geometry Extrusion { + crossSection [ 1 1, 1 -1, -1 -1, -1 1, 1 1 ] spine [ 0 0 0, 0 1 0, 1 2 0, 2 2 0 ] scale [ 1 1, 0.5 0.5, 0.5 0.5, 1 1 ] } } } +""", + "feat_scene.wrl": """#VRML V2.0 utf8 +WorldInfo { title "feature scene" info [ "made for formats-luau" ] } +DEF Cam Viewpoint { position 0 1 8 orientation 0 1 0 0.3 fieldOfView 0.9 description "front" } +DEF Sun DirectionalLight { direction 0 -1 -1 intensity 0.8 color 1 1 0.9 } +DEF Bulb PointLight { location 1 2 3 radius 10 } +DEF Spot SpotLight { location 0 5 0 direction 0 -1 0 cutOffAngle 0.6 beamWidth 0.4 } +DEF Sw Switch { whichChoice 1 choice [ + Shape { geometry Box { } } + Transform { translation 0 2 0 children Shape { geometry Sphere { radius 0.5 } } } ] } +LOD { range [ 10 ] level [ Shape { geometry Box { size 0.5 0.5 0.5 } } Shape { geometry Sphere { } } ] } +DEF Mover Transform { center 1 0 0 scaleOrientation 0 0 1 0.5 scale 1 2 1 children [ + Shape { geometry IndexedLineSet { coord Coordinate { point [ 0 0 0, 1 0 0, 1 1 0 ] } coordIndex [ 0 1 2 -1 ] color Color { color [ 1 0 0, 0 1 0, 0 0 1 ] } } } + Shape { geometry PointSet { coord Coordinate { point [ 0 0 1, 1 0 1 ] } } } ] } +DEF Clock TimeSensor { cycleInterval 4 loop TRUE } +DEF Path PositionInterpolator { key [ 0 0.5 1 ] keyValue [ 0 0 0, 0 2 0, 0 0 0 ] } +DEF Turn OrientationInterpolator { key [ 0 1 ] keyValue [ 0 1 0 0, 0 1 0 3.14 ] } +ROUTE Clock.fraction_changed TO Path.set_fraction +ROUTE Clock.fraction_changed TO Turn.set_fraction +ROUTE Path.value_changed TO Mover.set_translation +ROUTE Turn.value_changed TO Mover.set_rotation +Shape { appearance Appearance { texture PixelTexture { image 2 2 3 0xFF0000 0x00FF00 0x0000FF 0xFFFFFF } } geometry Box { } } +Inline { url [ "part.wrl" ] } +""", +} +# the Inline target of feat_scene.wrl +INLINE = {"part.wrl": "#VRML V2.0 utf8\nTransform { translation 0 -3 0 children Shape { geometry Box { size 4 0.2 4 } } }\n"} diff --git a/tools/fixtures/pmx.py b/tools/fixtures/pmx.py new file mode 100644 index 0000000..8fccaba --- /dev/null +++ b/tools/fixtures/pmx.py @@ -0,0 +1,77 @@ +# PMX / PMD fixtures (tools/fixtures.py): assimp's MMD test model (test/models-nonbsd/MMD/Alicia_blade.pmx, read from +# the nixpkgs assimp source, never committed) and synthetic models from tools/fixtures/_pmx_writer.py (PMX 2.0 / 2.1, +# UTF-16 / UTF-8, index sizes 1 / 2 / 4, additional UVs, every deform and morph type), with assimp's counts +# (`assimp info -r`: meshes, faces, vertices, materials, bones) and world bounds (assimp's PreTransformVertices +# export), plus the generator's own facts (vertex / bone / morph counts, sample vertices). The same synthetic models as +# PMD 1.0 (no reference reads PMD: the test compares them with the PMX decode). +# tests/gen/pmx_cases.luau { name, data, files = { name -> bytes }, assimp, expect? } +# tests/gen/pmx_pmd.luau { name, data, pmx (the case index of the same model) } +import importlib.util, os, struct, zlib + +INPUTS = ["tools/fixtures/_pmx_writer.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def tiny_png(): + raw = b"".join(b"\0" + bytes([200, 40, 40]) * 2 for _ in range(2)) + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 2, 2, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"") + + +def generate(ctx): + M = load(ctx, "_model_ref") + Fbx = load(ctx, "fbx") + W = load(ctx, "_pmx_writer") + tmp = M.tempdir() + cases, pmds = [], [] + src = os.path.join(Fbx.assimp_src(ctx), "test", "models-nonbsd", "MMD", "Alicia_blade.pmx") + if os.path.exists(src): + cases.append({"name": "assimp/Alicia_blade.pmx", "path": src, "files": {}}) + variants = [ + ("small_utf16_i1.pmx", dict(version=2.0, utf8=False, sizes=(1, 1, 1, 1, 1, 1), uva=0), dict(rings=4, seg=6, nbones=3, nmat=2)), + ("utf8_i2_uva2.pmx", dict(version=2.0, utf8=True, sizes=(2, 2, 2, 2, 2, 2), uva=2), dict(rings=12, seg=16, nbones=5, nmat=3)), + ("v21_utf16_i4_uva4.pmx", dict(version=2.1, utf8=False, sizes=(4, 4, 4, 4, 4, 4), uva=4), dict(rings=30, seg=20, nbones=8, nmat=3)), + ("v21_utf8_mixed.pmx", dict(version=2.1, utf8=True, sizes=(2, 1, 1, 2, 1, 1), uva=1), dict(rings=8, seg=10, nbones=4, nmat=3, deform=[4, 3, 1], flips=True)), + ] + png = tiny_png() + for fname, wopts, topts in variants: + uva = wopts["uva"] + model = W.tube(version=wopts["version"], uva=uva, seed=len(cases), name=fname[:-4], **topts) + data = W.Pmx(**wopts).build(model) + path = os.path.join(tmp, fname) + with open(path, "wb") as f: + f.write(data) + vs = model["vertices"] + samples = [] + for i in (0, 1, 2, 3, len(vs) - 1): + v = vs[i] + samples.append({"index": i, "pos": list(v["pos"]), "uv": list(v["uv"]), "deform": v["deform"], "bones": v["bones"], "weights": v["weights"]}) + types = {} + for mo in model["morphs"]: + types[str(mo["type"])] = types.get(str(mo["type"]), 0) + 1 + expect = {"vertices": len(vs), "bones": len(model["bones"]), "morphs": len(model["morphs"]), "morphTypes": types, + "textures": len(model["textures"]), "uva": uva, "samples": samples, "name": model["name"], "version": wopts["version"], + "rigid": len(model["rigid"]), "joints": len(model["joints"]), "frames": len(model["frames"])} + cases.append({"name": "gen/" + fname, "path": path, "files": {"tex/body.png": png}, "expect": expect}) + if wopts["version"] == 2.0 and wopts["sizes"][0] <= 2: + pmds.append({"name": "gen/" + fname[:-4] + ".pmd", "data": W.pmd(model), "pmx": len(cases)}) + infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True) + for c, a in zip(cases, infos): + a.update(Fbx.assimp_extra(ctx, c["path"])) + a.pop("min", None) + a.pop("max", None) + a.update(Fbx.ptv_bounds(ctx, c["path"], tmp)) + if a.get("failed") and c.get("expect", {}).get("morphTypes", {}).get("9"): + a = {"skip": True} # flip / impulse morphs: assimp's MMD reader stops there + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("pmx_cases", cases) + ctx.emit("pmx_pmd", pmds) diff --git a/tools/fixtures/vrml.py b/tools/fixtures/vrml.py new file mode 100644 index 0000000..c5673a2 --- /dev/null +++ b/tools/fixtures/vrml.py @@ -0,0 +1,99 @@ +# VRML97 fixtures (tools/fixtures.py): assimp's WRL test models (test/models/WRL, read from the nixpkgs assimp source, +# never committed; assimp itself is built without its VRML reader), scenes and glTF sample models written by VTK's +# vtkVRMLExporter, and the hand-written feature files of tools/fixtures/_vrml_ref.py, with VTK's vtkVRMLImporter as +# the reference (polygons, lines, world bounds). Then our encoder's output (tools/fixtures/_vrml_encode.luau) read back +# by VTK. +# tests/gen/vrml_cases.luau { name, data, files = { name -> bytes }, vtk, primitives (bool: tessellated shapes) } +# tests/gen/vrml_gltf.luau glTF sample models for the writer round trips: { name, data, files } +# tests/gen/vrml_xcheck.luau { name, case?, gltf?, vtk } +import importlib.util, os, re + +INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/vrml", "tests/fixtures/gltf", "tools/fixtures/_vrml_ref.py", + "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/_vrml_encode.luau"] + +GLTF = ["Box", "BoxTextured", "BoxVertexColors", "Cameras", "MeshPrimitiveModes", "SimpleMeshes", "AnimatedTriangle", "InterpolationTest", + "NegativeScaleTest", "TextureCoordinateTest", "MultiUVTest"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def primitives(data): + return bool(re.search(rb"\b(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\s*\{|<(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\b", data)) + + +def gltf_picks(ctx): + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in GLTF: + d0 = os.path.join(gl, model) + if not os.path.isdir(d0): + continue + for variant in ("glTF", "glTF-Embedded", "glTF-Binary"): + d = os.path.join(d0, variant) + if not os.path.isdir(d): + continue + mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")] + if mains: + picks.append({"name": model + "/" + variant, "path": os.path.join(d, mains[0]), "data": open(os.path.join(d, mains[0]), "rb").read(), + "files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}}) + break + return picks + + +def generate(ctx): + M = load(ctx, "_model_ref") + Fbx = load(ctx, "fbx") + R = load(ctx, "_vrml_ref") + tmp = M.tempdir() + cases = [] + src = os.path.join(Fbx.assimp_src(ctx), "test", "models", "WRL") + for f in sorted(os.listdir(src)): + if f.lower().endswith(".wrl"): + files = {} + if f == "HelloWorld.wrl": + files["earth-topo.png"] = open(os.path.join(src, "earth-topo.png"), "rb").read() + cases.append({"name": "assimp/" + f, "path": os.path.join(src, f), "files": files}) + picks = gltf_picks(ctx) + for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks if p["path"].endswith((".gltf", ".glb"))]): + cases.append({"name": "vtk/" + name + ".wrl", "path": os.path.join(tmp, name + ".wrl"), "files": {}}) + for name, text in sorted(R.FEATURES.items()): + p = os.path.join(tmp, name) + with open(p, "w") as f: + f.write(text) + cases.append({"name": "feature/" + name, "path": p, "files": dict(R.INLINE)}) + for name, text in R.INLINE.items(): + with open(os.path.join(tmp, name), "w") as f: + f.write(text) + refs = R.vtk_read(ctx, [c["path"] for c in cases]) + for c, v in zip(cases, refs): + c["data"] = open(c["path"], "rb").read() + c["vtk"] = v + c["primitives"] = primitives(c["data"]) + c["vtkTransforms"] = R.vtk_xform_ok(c["data"]) + del c["path"] + ctx.emit("vrml_cases", cases) + for p in picks: + del p["path"] + ctx.emit("vrml_gltf", picks) + + # VTK reads our output + ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau") + xtmp = M.tempdir() + names = sorted(n for n in ours if n.endswith(".wrl")) + for name, data in ours.items(): + with open(os.path.join(xtmp, name), "wb") as f: + f.write(data) + refs = R.vtk_read(ctx, [os.path.join(xtmp, n) for n in names]) + out = [] + for n, v in zip(names, refs): + e = {"name": n, "vtk": v, "vtkTransforms": R.vtk_xform_ok(ours[n])} + m = re.match(r"(case|gltf)_(\d+)\.wrl$", n) + if m: + e[m.group(1)] = int(m.group(2)) + out.append(e) + ctx.emit("vrml_xcheck", out) diff --git a/tools/fixtures/x3d.py b/tools/fixtures/x3d.py new file mode 100644 index 0000000..0826081 --- /dev/null +++ b/tools/fixtures/x3d.py @@ -0,0 +1,135 @@ +# X3D fixtures (tools/fixtures.py): assimp's X3D / X3DV / X3DB test models (test/models/X3D*, read from the nixpkgs +# assimp source, never committed), scenes and glTF sample models written by VTK's vtkX3DExporter, glTF sample models +# written by assimp's X3D exporter, and hand-written feature files (below), with assimp's X3D reader as the reference +# (`assimp info -r`: meshes, faces, materials; world bounds from its PreTransformVertices export). Then our encoder's +# X3D output (tools/fixtures/_vrml_encode.luau) read back by assimp. +# tests/gen/x3d_cases.luau { name, data, files = { name -> bytes }, assimp, primitives (bool) } +# tests/gen/x3d_xcheck.luau { name, case? / gltf? / wcase?, assimp } +import importlib.util, os, re, subprocess + +INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/x3d", "src/Formats/model/vrml", "tests/fixtures/gltf", + "tools/fixtures/_vrml_ref.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/vrml.py", + "tools/fixtures/_vrml_encode.luau"] + +FEATURES = { + "feat_sets.x3d": """ + + + + + + + + + + +""", + "feat_proto.x3d": """ + + + + + + + + + + + + + + + + + + + + + + +""", + "feat_classic.x3dv": """#X3D V3.3 utf8 +PROFILE Interchange +COMPONENT Geometry2D:1 +META "title" "classic" +UNIT length millimetre 0.001 +DEF Root Transform { translation 1 2 3 children [ + Shape { appearance Appearance { material Material { diffuseColor 0 1 0 } } + geometry IndexedFaceSet { coord Coordinate { point [ 0 0 0 1 0 0 1 1 0 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ] + color ColorRGBA { color [ 1 0 0 1, 0 1 0 1, 0 0 1 1, 1 1 1 0.5 ] } } } + Shape { geometry IndexedTriangleSet { index [ 0 1 2 ] coord Coordinate { point [ 0 0 1 1 0 1 0 1 1 ] } } } +] } +""", +} + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def reference(ctx, M, Fbx, path, tmp): + a = M.assimp_info(ctx, [path], raw=True)[0] + if not a.get("failed"): + a.pop("min", None) + a.pop("max", None) + a.update(Fbx.assimp_extra(ctx, path)) + a.update(Fbx.ptv_bounds(ctx, path, tmp)) + return a + + +def generate(ctx): + M = load(ctx, "_model_ref") + Fbx = load(ctx, "fbx") + R = load(ctx, "_vrml_ref") + V = load(ctx, "vrml") + tmp = M.tempdir() + cases = [] + root = os.path.join(Fbx.assimp_src(ctx), "test", "models") + for sub in ("X3D", "X3DV", "X3DB"): + d = os.path.join(root, sub) + for f in sorted(os.listdir(d)): + if f.lower().endswith((".x3d", ".x3dv", ".x3db")): + files = {} + if f.startswith("HelloWorld"): + files["earth-topo.png"] = open(os.path.join(d, "earth-topo.png"), "rb").read() + cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f), "files": files}) + picks = V.gltf_picks(ctx) + for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks]): + cases.append({"name": "vtk/" + name + ".x3d", "path": os.path.join(tmp, name + ".x3d"), "files": {}}) + for p in picks: + out = os.path.join(tmp, "assimp_" + p["name"].split("/")[0] + ".x3d") + try: + ctx.nix("assimp", ["assimp", "export", p["path"], out, "-fx3d"]) + except subprocess.CalledProcessError: + continue + cases.append({"name": "assimp-export/" + os.path.basename(out), "path": out, "files": dict(p["files"])}) + for name, text in sorted(FEATURES.items()): + path = os.path.join(tmp, name) + with open(path, "w") as f: + f.write(text) + cases.append({"name": "feature/" + name, "path": path, "files": {}}) + for c in cases: + c["data"] = open(c["path"], "rb").read() + c["primitives"] = V.primitives(c["data"]) + c["assimp"] = reference(ctx, M, Fbx, c["path"], tmp) if c["path"].endswith(".x3d") else {"skip": True} + del c["path"] + ctx.emit("x3d_cases", cases) + + # assimp reads our X3D output + ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau") + xtmp = M.tempdir() + out = [] + for name in sorted(n for n in ours if n.endswith(".x3d")): + path = os.path.join(xtmp, name) + with open(path, "wb") as f: + # assimp 6 cannot read quoted MFString urls (url='"a.png"', which the X3D encoding requires) + f.write(re.sub(rb'url=""([^&"]*)""', rb'url="\1"', ours[name])) + e = {"name": name, "assimp": reference(ctx, M, Fbx, path, xtmp)} + m = re.match(r"(xcase|xgltf|wcase)_(\d+)\.x3d$", name) + if m: + e[m.group(1)] = int(m.group(2)) + out.append(e) + ctx.emit("x3d_xcheck", out)