diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 2e232e2..f68bf78 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | ani | .ani | yes | yes | alpha: true, animation: true, frames: true | `tests/image/ani.luau` | +| image | blp | .blp | yes | yes | alpha: true, variants: "blp1", "blp2", compressions: "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" | `tests/image/blp.luau` | | image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` | | image | dds | .dds | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" | `tests/image/dds.luau` | | image | exr | .exr | yes | yes | alpha: true, float: true, hdr: true, depths: 16, 32, multipart: true, tiled: true | `tests/image/exr.luau` | @@ -24,6 +25,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | sunras | .ras .sun .rs .im1 .im8 .im24 .im32 | yes | yes | alpha: true, palette: true, depths: 1, 8, 24, 32 | `tests/image/sunras.luau` | | image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` | | image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` | +| image | tim | .tim | yes | yes | alpha: true, palette: true, depths: 4, 8, 16, 24 | `tests/image/tim.luau` | +| image | vtf | .vtf | yes | - | alpha: true, animation: true, versions: "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" | `tests/image/vtf.luau` | | image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` | | image | xbm | .xbm .bm | yes | yes | depths: 1 | `tests/image/xbm.luau` | | image | xpm | .xpm .pm | yes | yes | alpha: true, palette: true, depths: 8 | `tests/image/xpm.luau` | @@ -62,6 +65,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | 3ds | .3ds | yes | yes | materials: true, textures: true, animation: true, cameras: true, lights: true, instancing: true | `tests/model/3ds.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | b3d | .b3d | yes | - | materials: true, textures: true, skins: true, animation: true, colors: true | `tests/model/b3d.luau` | +| model | bsp | .bsp | yes | - | variants: "quake", "halflife", "quake2", "quake3", lightmaps: "quake3" | `tests/model/bsp.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, draco: true | `tests/model/gltf.luau` | @@ -69,6 +73,10 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | ldraw | .ldr .mpd .dat | yes | - | materials: true, lines: true, instancing: true | `tests/model/ldraw.luau` | | model | lwo | .lwo .lxo | yes | - | materials: true, polygons: true, vertexColors: true, morphTargets: true | `tests/model/lwo.luau` | | model | mca | .mca .mcr | yes | - | voxels: true, blocks: true | `tests/model/mca.luau` | +| model | md2 | .md2 | yes | - | morph: true, animation: true | `tests/model/md2.luau` | +| model | md3 | .md3 | yes | - | morph: true, animation: true, tags: true | `tests/model/md3.luau` | +| model | md5 | .md5mesh .md5anim | yes | - | skins: true, animation: true | `tests/model/md5.luau` | +| model | mdl | .mdl | yes | - | variants: "quake", "halflife", morph: true, skins: true, animation: true | `tests/model/mdl.luau` | | model | ms3d | .ms3d | yes | yes | materials: true, skins: true, animation: true | `tests/model/ms3d.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | @@ -79,6 +87,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | rbxmx | .rbxmx .rbxlx | yes | yes | tree: true | `tests/model/rbxmx.luau` | | model | robloxmesh | .mesh | yes | yes | skinning: true, lods: true, versions: "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" | `tests/model/robloxmesh.luau` | | model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` | +| model | smd | .smd | yes | yes | skins: true, animation: true | `tests/model/smd.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | @@ -93,9 +102,13 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | 7z | .7z | yes | - | methods: "copy", "lzma", "lzma2", "deflate", "bcj", "delta", encrypted: false | `tests/archive/7z.luau` | | archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` | | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | +| archive | grp | .grp | yes | yes | | `tests/archive/grp.luau` | | archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` | +| archive | mpq | .mpq .w3x .w3m .sc2map .sc2data .s2ma .scm .scx | yes | - | versions: 1, 2, 3, 4, methods: "zlib", "implode", "bzip2", "lzma", "sparse", encryption: true | `tests/archive/mpq.luau` | | archive | pak | .pak .sin | yes | yes | variants: "quake", "sin" | `tests/archive/pak.luau` | | archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | +| archive | vpk | .vpk | yes | yes | versions: 1, 2, multipart: true | `tests/archive/vpk.luau` | +| archive | wad | .wad | yes | yes | images: true, maps: true, variants: "iwad", "pwad" | `tests/archive/wad.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | | archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` | | archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` | @@ -172,6 +185,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written - codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec - codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. + - codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ - codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder - codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and @@ -203,6 +217,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks - codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. + - codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map - 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 diff --git a/docs/guide/archive.md b/docs/guide/archive.md index 5524350..87a140b 100644 --- a/docs/guide/archive.md +++ b/docs/guide/archive.md @@ -185,6 +185,70 @@ local gzipped = assert(F.save("some text", nil, { format = "gzip", name = "note. assert(F.archive.load(gzipped, { unwrap = false }):list()[1].name == "note.txt") ``` +## Game archives + +The game archive formats load as the same `Archive`: Quake / Half-Life PAK, Doom WAD, Build GRP, Valve VPK and +Blizzard MPQ (read-only). PAK, WAD, GRP and VPK are writable (and any Archive converts to them). + +```luau +local pak = assert(F.archive.load(pakBytes)) -- Quake PAK: 56-byte names, stored files +assert(pak.format == "pak" and pak:read("default.cfg")) +local grp = assert(F.archive.load(grpBytes)) -- Duke Nukem 3D GRP +assert(grp:list()[1].name == "GAME.CON") + +local new = F.format("pak").new() +new:add("maps/e1m1.bsp", "...") +local bytes = assert(F.save(new)) -- a PAK; F.save(zip, nil, { format = "pak" }) converts +assert(F.archive.load(bytes):read("maps/e1m1.bsp")) +``` + +A WAD's lumps keep their order; lumps of a map are named `"/"` (`"E1M1/THINGS"`) and repeated names get +`"~2"`, `"~3"`, ... so every entry is unique (writing strips both again). The format module turns lumps into game +data: graphics (flats, patches, sprites, menu pictures) into Images through the `PLAYPAL` palette, wall textures +composed from their patches, and maps into a Scene (z up, map units: floors and ceilings triangulated from the +sector outlines, walls, things as nodes standing on their floor). + +```luau +local Wad = F.format("wad") +local wad = assert(F.archive.load(wadBytes)) +for _, l in Wad.lumps(wad) do + print(l.name, l.size, l.namespace, l.map) -- "FLOOR" 4096 "flats" nil, "THINGS" 20 nil "E1M1", ... +end +local flat = assert(Wad.image(wad, "FLOOR")) -- 64 x 64 rgba8 +local patch = assert(Wad.image(wad, "TALL")) -- a picture: meta.offset = { left, top }, alpha 0 = hole +assert(flat.width == 64 and patch.height == 300) + +assert(Wad.maps(wad)[1] == "E1M1") +local map = assert(Wad.map(wad, "E1M1")) -- a Scene; Wad.mapData(wad, "E1M1") gives the raw tables +assert(map.meta.up == "z" and #map.meshes[1].primitives > 0) +local thing = map.nodes[2] -- things are child nodes of the map node +assert(thing.extras.thing.type == 1) -- player 1 start +local data = assert(Wad.mapData(wad, "E1M1")) +assert(#data.sectors == 2 and #data.things == 2) +``` + +VPK directories (`pak01_dir.vpk`) hold small files themselves and point to numbered part files for the rest; pass +those through `files` or `resolve` (loading a path does it for you): + +```luau +local vpk = assert(F.archive.load(vpkBytes)) +assert(vpk:read("scripts/game.txt")) -- CRC-32 checked on read +-- multi-part: F.archive.load(dir, { name = "pak01_dir.vpk", files = { ["pak01_000.vpk"] = part0 } }) +local out = assert(F.save(vpk)) -- one self-contained version 2 file (with its MD5s) +assert(F.archive.load(out):read("materials/brick/wall.vmt")) +``` + +MPQ archives are read through their hash table, so names come from the archive's `(listfile)`; files it does not +list appear as `File00000012.xxx` (their block index), and `names` adds names to look up: + +```luau +local mpq = assert(F.archive.load(mpqBytes)) -- also .w3x / .w3m / .SC2Map +local script = assert(mpq:read("war3map.j")) -- zlib / PKWARE implode / bzip2 / LZMA / sparse sectors +assert(buffer.len(script) == buffer.len(assert(mpq:read("readme.txt")))) +local named = assert(F.archive.load(mpqBytes, { names = { "war3map.w3e" } })) +assert(#named:list() >= 2) +``` + ## Formats | Format | Read | Write | Notes | @@ -197,6 +261,11 @@ assert(F.archive.load(gzipped, { unwrap = false }):list()[1].name == "note.txt") | zstd (`.zst`, `.tzst`) | yes | - | single stream; no dictionaries | | bzip2 (`.bz2`, `.tbz2`) | yes | - | single stream | | Brotli (`.br`) | yes | - | single stream; no magic number, so pass a `.br` name or `format = "br"` | +| PAK (`.pak`) | yes | yes | Quake / Quake II / Half-Life (and SiN `SPAK`) | +| WAD (`.wad`) | yes | yes | IWAD / PWAD; lumps, graphics, wall textures and maps through `F.format("wad")` | +| GRP (`.grp`) | yes | yes | Build engine | +| VPK (`.vpk`) | yes | yes | versions 1 / 2, multi-part reading, preload bytes; writes one directory file | +| MPQ (`.mpq`, `.w3x`, `.sc2map`, ...) | yes | - | versions 1-4 (classic tables), encryption; no Huffman / ADPCM (WAVE) sectors | Full capability list: [FORMATS.md](../FORMATS.md). diff --git a/docs/guide/image.md b/docs/guide/image.md index 8c919d6..45ccbef 100644 --- a/docs/guide/image.md +++ b/docs/guide/image.md @@ -194,6 +194,28 @@ Encoder options: | ICO | `cursor`, `png` (PNG entries); `frames` become entries (each up to 256 x 256) | | PNM | the subtype from the extension or `format`: `pbm`, `pgm`, `ppm`, `pam`, `pfm` | +## Game textures + +PlayStation TIM, Blizzard BLP and Valve VTF load as Images too (rgba8; the mip and texel facts in +`meta.source`): + +```luau +local face = assert(F.image.load(timBytes)) -- 4 / 8-bit CLUT, 15 or 24-bit +assert(face.meta.source.bpp == 16) +local tim = assert(F.save(face, nil, { format = "tim", bpp = 16 })) -- TIM writes 4 / 8 / 16 / 24-bit + +local icon = assert(F.image.load(blpBytes)) -- BLP1 JPEG / palette, BLP2 palette / DXT / BGRA +assert(icon.width == 4 and icon.meta.source.compression == "bgra") + +local wall = assert(F.image.load(vtfBytes)) -- every common VTF texel format, frames, mips +assert(wall.meta.source.texel == "RGBA8888") +local small = assert(F.image.load(vtfBytes, { mip = 1 })) -- or face = n (cube maps), slice = n (volumes) +assert(F.detect(tim) == "tim") +``` + +Doom's graphics come from WAD lumps rather than files: `F.format("wad").image(wad, name)` (see +[archive.md](archive.md#game-archives)). + ## Formats Read and write unless noted; see [FORMATS.md](../FORMATS.md) for depths and details. @@ -207,6 +229,9 @@ Read and write unless noted; see [FORMATS.md](../FORMATS.md) for depths and deta | TIFF | pages | yes | 1..32-bit, float | | BMP, TGA, QOI, ICO / CUR, PNM / PAM / PFM | ICO entries | yes | | | HDR | | no | float (`native` gives rgbaf32) | +| TIM | | yes | PlayStation; 4 / 8-bit CLUT, 15 / 24-bit | +| BLP | | yes | Blizzard BLP1 / BLP2 (DXT through the BCn codec); writes BLP2 BGRA | +| VTF | frames | yes | Valve; read only; mips / faces / slices by option | | DDS, KTX / KTX2 | faces / layers / slices | yes | GPU textures: BC1..BC7, ETC / EAC, every uncompressed layout; mips in `meta.mipmaps` | | OpenEXR | parts (`opts.part`) | yes | half / float / uint, NONE / RLE / ZIPS / ZIP / PIZ, tiles; writes NONE / ZIPS / ZIP | | PCX, SGI, Sun Raster, IFF ILBM / PBM, XPM, XBM | | yes (XBM 1-bit) | old paint / workstation formats; ILBM reads HAM and EHB | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 36177af..d799755 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -455,6 +455,57 @@ local vox = assert(F.save(grid, nil, { format = "vox" })) -- a grid alone saves assert(F.load(vox).voxels[1].size[1] == 4) ``` +## Game models + +Game model formats load as Scenes too, with what games need: skins (joints + inverse bind matrices, `JOINTS_0` / +`WEIGHTS_0`) and animations, vertex-animated models as morph targets. Units are as the game stores them, z up +(`meta.up = "z"`). + +| Format | What loads | Animations | +|---|---|---| +| MD2 (Quake II) | one primitive; skins as texture URIs | every frame a morph target (weight k = 1 shows frame k); one animation per frame-name group (`run1`..`run6` -> `run`) | +| MD3 (Quake III) | a primitive per surface; shaders as URIs; tags as nodes | frames as morph targets, tag motion, one animation | +| MDL (Quake 1, Half-Life 1) | Quake: skins decoded through the palette; Half-Life: bones, body parts, textures with their own palettes | Quake: morph targets per frame group; Half-Life: every sequence | +| MD5 (Doom 3 `.md5mesh` / `.md5anim`) | skeleton, weighted meshes, shaders as URIs | the `.md5anim` files named in `anims` | +| SMD (Valve, read + write) | skeleton, weight links, a primitive per material | the skeleton frames | +| BSP (Quake 1 / 2 / 3, Half-Life) | each model a mesh, a primitive per texture (and Quake III lightmap); entities in `meta.entities` | - | + +```luau +local tank = assert(F.model.load(md2Bytes)) +local prim = tank.meshes[1].primitives[1] +assert(#prim.targets == 5 and #tank.meshes[1].weights == 5) -- 5 frames +assert(tank.animations[1].name == "stand" and tank.animations[2].name == "run") +assert(tank.textures[1].uri == "models/tank/skin.pcx") +assert(tank.meta.up == "z") +``` + +MD5 animations are separate files: name them in `anims` (they are found through `files` or `resolve`, which the api +fills in for paths), or load a `.md5anim` alone as a skeleton with its animation: + +```luau +local imp = assert(F.model.load(md5meshBytes, { anims = { "idle.md5anim" }, files = { ["idle.md5anim"] = md5animBytes } })) +assert(#imp.skins == 1 and imp.animations[1].name == "idle") +assert(imp.meshes[1].primitives[1].attributes.JOINTS_0) +local idle = assert(F.model.load(md5animBytes, { format = "md5" })) +assert(#idle.animations == 1) +``` + +Quake's palette (`gfx/palette.lmp`, inside the game's PAK) is not redistributable, so Quake MDL skins and Quake 1 +BSP textures need it passed in (`palette`, or through `files` / `resolve`); without it they decode as grey ramps +(`meta.source.palette = false`). Half-Life models and maps carry their own palettes. + +```luau +local map = assert(F.model.load(bspBytes)) -- a Half-Life map +assert(map.meta.source.variant == "halflife") +assert(map.meta.entities[1].classname == "worldspawn") +local world = map.meshes[1] -- "world"; brush entities are "*1", "*2", ... +assert(world.name == "world" and map.meshes[2].name == "*1") + +local barney = assert(F.model.load(smdBytes)) +local again = assert(F.save(barney, nil, { format = "smd" })) -- SMD writes back (bind pose, weights) +assert(F.model.load(again).skins[1]) +``` + ## Blitz3D (B3D) `.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS; @@ -692,6 +743,8 @@ assert(back.meshes[1].primitives[1].indices.count == 3) | 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) | +| MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | +| SMD | yes | yes | Valve studiomdl data | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 186b69f..053798f 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -46,9 +46,10 @@ | `src/Formats/music/{mtm,669,stm,ult,okt,med,ptm,far,umx}/`, `src/Formats/codecs/audio/Tracker/Load.luau` (loaders and effect conversions ported from OpenMPT's Load_*.cpp / ModCommand / UMXTools) | libopenmpt 0.8.9 (OpenMPT Project Developers, Olivier Lapicque) | BSD-3-Clause: [openmpt-LICENSE.txt](openmpt-LICENSE.txt) | | `src/Formats/codecs/video/Dsp.luau` (the 8x8 IDCT: jrevdct.c translated to Luau, branch tree and constants unchanged) | IJG jrevdct.c as shipped in ffmpeg (libavcodec/jrevdct.c; IJG-licensed, not LGPL: ffmpeg's LICENSE.md) | IJG: [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | +| `tests/gen/wad` (cut down from the nix freedoom package at fixture time, not committed) | Freedoom 0.13 (freedoom.github.io) | BSD-3-Clause: [freedoom-COPYING.txt](freedoom-COPYING.txt) | +| `src/Formats/codecs/compress/Explode.luau` (the PKWARE DCL code tables and bit order) | blast.c 1.3 (Mark Adler, zlib contrib) | zlib: [blast-LICENSE.txt](blast-LICENSE.txt) | | `src/Formats/codecs/video/Theora/` (Header, Decoder) | a Luau port of the libtheora 1.2.0 decoder (Xiph.Org; decinfo.c, dequant.c, quant.c, huffdec.c, decode.c, state.c, idct.c, fragment.c) checked against the Theora I specification; the token storage is simplified (coefficients per fragment) and the post-processing is not ported | BSD 3-clause: [libtheora-BSD.txt](libtheora-BSD.txt) | | `src/Formats/codecs/model/Draco/` | Luau port of the Draco 1.5.7 decoder (Google): compression/{decode, mesh, attributes, entropy, bit_coders, point_cloud}, mesh/corner_table, mesh/mesh_attribute_corner_table, core/{decoder_buffer, varint_decoding, math_utils}, attributes/attribute_{quantization,octahedron}_transform | Apache-2.0: [draco-LICENSE.txt](draco-LICENSE.txt) | -| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | | `src/Formats/model/ldraw/Colors.luau` (the built-in colour table) | the !COLOUR list of LDConfig.ldr (LDraw.org Parts Library, UPDATE 2025-05-20), reformatted | CC BY 2.0 / CC BY 4.0: [LDRAW_COLOURS.txt](LDRAW_COLOURS.txt) | | `tests/gen/ldraw_*` (read at fixture time from the nix store, not committed) | LDraw.org Parts Library parts and sample models (complete.zip, as packaged for nixpkgs' LeoCAD) | CC BY 2.0 / CC BY 4.0, test data | | `src/Formats/codecs/image/Bcn/Decode.luau` (the BC1..BC7 block decoders and the BPTC tables; changed to follow the D3D11 rules) | Pillow 12 `src/libImaging/BcnDecode.c` | CC0 1.0: [pillow-bcn-CC0.txt](pillow-bcn-CC0.txt) | diff --git a/licenses/blast-LICENSE.txt b/licenses/blast-LICENSE.txt new file mode 100644 index 0000000..3e75ff4 --- /dev/null +++ b/licenses/blast-LICENSE.txt @@ -0,0 +1,24 @@ +codecs/compress/Explode takes the PKWARE DCL constant code tables (litlen / lenlen / distlen, base, extra) and the +bit-order conventions from blast.c, distributed with zlib (contrib/blast). The decoder itself is new code. + +blast.c +Copyright (C) 2003, 2012, 2013 Mark Adler +version 1.3, 24 Aug 2013 + +This software is provided 'as-is', without any express or implied +warranty. In no event will the author be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + +Mark Adler madler@alumni.caltech.edu diff --git a/licenses/freedoom-COPYING.txt b/licenses/freedoom-COPYING.txt new file mode 100644 index 0000000..57a9f63 --- /dev/null +++ b/licenses/freedoom-COPYING.txt @@ -0,0 +1,30 @@ +Copyright © 2001-2024 +Contributors to the Freedoom project. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Freedoom project nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS +IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +For a list of contributors to the Freedoom project, see the file +CREDITS. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 8d02b08..562341e 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/ani") end, }, + { + name = "blp", + category = "image", + path = "image/blp", + extensions = { "blp" }, + mime = { "image/x-blp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" }, + caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } }, + load = function() + return require("@formats/image/blp") + end, + }, { name = "bmp", category = "image", @@ -242,6 +254,30 @@ local list: { Entry } = { return require("@formats/image/tiff") end, }, + { + name = "tim", + category = "image", + path = "image/tim", + extensions = { "tim" }, + mime = { "image/x-tim" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } }, + load = function() + return require("@formats/image/tim") + end, + }, + { + name = "vtf", + category = "image", + path = "image/vtf", + extensions = { "vtf" }, + mime = { "image/x-vtf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" }, + caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } }, + load = function() + return require("@formats/image/vtf") + end, + }, { name = "webp", category = "image", @@ -698,6 +734,18 @@ local list: { Entry } = { return require("@formats/model/b3d") end, }, + { + name = "bsp", + category = "model", + path = "model/bsp", + extensions = { "bsp" }, + mime = { "model/x-bsp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, + load = function() + return require("@formats/model/bsp") + end, + }, { name = "dae", category = "model", @@ -782,6 +830,54 @@ local list: { Entry } = { return require("@formats/model/mca") end, }, + { + name = "md2", + category = "model", + path = "model/md2", + extensions = { "md2" }, + mime = { "model/x-md2" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true }, + load = function() + return require("@formats/model/md2") + end, + }, + { + name = "md3", + category = "model", + path = "model/md3", + extensions = { "md3" }, + mime = { "model/x-md3" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true, tags = true }, + load = function() + return require("@formats/model/md3") + end, + }, + { + name = "md5", + category = "model", + path = "model/md5", + extensions = { "md5mesh", "md5anim" }, + mime = { "model/x-md5mesh", "model/x-md5anim" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, skins = true, animation = true }, + load = function() + return require("@formats/model/md5") + end, + }, + { + name = "mdl", + category = "model", + path = "model/mdl", + extensions = { "mdl" }, + mime = { "model/x-mdl" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, + load = function() + return require("@formats/model/mdl") + end, + }, { name = "ms3d", category = "model", @@ -902,6 +998,18 @@ local list: { Entry } = { return require("@formats/model/schematic") end, }, + { + name = "smd", + category = "model", + path = "model/smd", + extensions = { "smd" }, + mime = { "model/x-smd", "text/plain" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" }, + caps = { decode = true, encode = true, skins = true, animation = true }, + load = function() + return require("@formats/model/smd") + end, + }, { name = "stl", category = "model", @@ -1070,6 +1178,18 @@ local list: { Entry } = { return require("@formats/archive/bz2") end, }, + { + name = "grp", + category = "archive", + path = "archive/grp", + extensions = { "grp" }, + mime = { "application/x-build-grp" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true }, + load = function() + return require("@formats/archive/grp") + end, + }, { name = "gzip", category = "archive", @@ -1082,6 +1202,18 @@ local list: { Entry } = { return require("@formats/archive/gzip") end, }, + { + name = "mpq", + category = "archive", + path = "archive/mpq", + extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, + mime = { "application/x-mpq" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, + caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, + load = function() + return require("@formats/archive/mpq") + end, + }, { name = "pak", category = "archive", @@ -1106,6 +1238,30 @@ local list: { Entry } = { return require("@formats/archive/tar") end, }, + { + name = "vpk", + category = "archive", + path = "archive/vpk", + extensions = { "vpk" }, + mime = { "application/x-vpk" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, + caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, + load = function() + return require("@formats/archive/vpk") + end, + }, + { + name = "wad", + category = "archive", + path = "archive/wad", + extensions = { "wad" }, + mime = { "application/x-doom" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" }, + caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, + load = function() + return require("@formats/archive/wad") + end, + }, { name = "xz", category = "archive", diff --git a/src/Formats/archive/grp/init.luau b/src/Formats/archive/grp/init.luau new file mode 100644 index 0000000..a7ad03e --- /dev/null +++ b/src/Formats/archive/grp/init.luau @@ -0,0 +1,115 @@ +--!strict +-- archive/grp: Build engine GRP archives (Duke Nukem 3D, Shadow Warrior, Blood: "KenSilverman", a u32 file count, +-- 16-byte entries of a 12-byte name and a u32 size, then the files back to back), read into the standard Archive +-- (entries read lazily) and written from any Archive value (names upper-cased to 8.3 by the caller's choice: they +-- are stored as given, at most 12 bytes). Written from Ken Silverman's GRP description (kenbuild); no code taken. +-- Not supported: the "GRP 2" / RFF / SSI variants. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Archive = require("@formats/containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Grp = { + name = "grp", + category = "archive", + extensions = { "grp" }, + mime = { "application/x-build-grp" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { maxEntries: number? } -- default 1e6 +export type EncodeOptions = { upper: boolean? } -- upper-case the names (Build looks them up case-insensitively; default false) + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "KenSilverman" + +-- ------------------------------------------------------------------------------------------------ sniff +function Grp.sniff(r: Bytes.Reader): number + return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Grp.encode(archive, opts) +end + +function Grp.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + if not r:match(MAGIC) then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local count = r:u32le() + if r.err then + return nil, r.err + end + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many entries: " .. count) + end + if count * 16 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 12) + end + local a = Archive.new("grp", encode) + local at = 16 + count * 16 + local size = r.limit - r.base + for i = 0, count - 1 do + local name = r:fixed(12) + local n = r:u32le() + if at + n > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", 16 + i * 16) + end + Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) + at += n + end + if r.err then + return nil, r.err + end + a.meta.source = { format = "grp", entries = count } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Grp.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local files: { { name: string, data: buffer } } = {} + for _, it in items do + if not it.entry.dir then + local name = it.entry.name + if opts and opts.upper then + name = string.upper(name) + end + if #name > 12 then + return nil, Err.new(Err.ARG, "name longer than 12 bytes: " .. name) + end + table.insert(files, { name = name, data = it.data }) + end + end + local w = Bytes.writer() + w:string(MAGIC) + w:u32le(#files) + for _, f in files do + w:string(f.name) + w:fill(0, 12 - #f.name) + w:u32le(buffer.len(f.data)) + end + for _, f in files do + w:bytes(f.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty GRP Archive: a:add(name, data); a:write() +function Grp.new(): any + local a = Archive.new("grp", encode) + a.meta.source = { format = "grp" } + return a +end + +return Grp diff --git a/src/Formats/archive/mpq/Crypt.luau b/src/Formats/archive/mpq/Crypt.luau new file mode 100644 index 0000000..255918e --- /dev/null +++ b/src/Formats/archive/mpq/Crypt.luau @@ -0,0 +1,65 @@ +--!strict +--!native +-- archive/mpq/Crypt: the MPQ encryption table, the name hash (types 0 = table index, 1 / 2 = name check, 3 = file +-- key) and block decryption in place. Written from the MPQ format description (Justin Olbrantz / Jean-Francois +-- Roy, "The MoPaQ Archive Format"; StormLib's documentation); no code taken. All arithmetic is mod 2^32 and every +-- value handed to bit32 is an integer in 0..2^32 - 1 (both runtimes agree). +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot + +local Crypt = {} + +local TWO32 = 4294967296 +local TABLE = buffer.create(0x500 * 4) +do + local seed = 0x00100001 + for i1 = 0, 255 do + local i2 = i1 + for _ = 0, 4 do + seed = (seed * 125 + 3) % 0x2AAAAB + local t1 = band(seed, 0xFFFF) * 65536 + seed = (seed * 125 + 3) % 0x2AAAAB + local t2 = band(seed, 0xFFFF) + writeu32(TABLE, i2 * 4, t1 + t2) + i2 += 0x100 + end + end +end + +-- hash(name, kind) -> u32: ASCII upper case, '/' as '\' +function Crypt.hash(name: string, kind: number): number + local s1, s2 = 0x7FED7FED, 0xEEEEEEEE + local base = kind * 0x100 + for i = 1, #name do + local c = string.byte(name, i) + if c >= 97 and c <= 122 then + c -= 32 + elseif c == 47 then + c = 92 + end + s1 = bxor(readu32(TABLE, (base + c) * 4), (s1 + s2) % TWO32) + s2 = (c + s1 + s2 + lshift(s2, 5) + 3) % TWO32 + end + return s1 +end + +-- decrypt(buf, at, n, key): n bytes (whole u32s; a trailing partial word is left as is) at buf[at..] in place +function Crypt.decrypt(buf: buffer, at: number, n: number, key: number) + local s2 = 0xEEEEEEEE + local k = key % TWO32 + for i = 0, n // 4 - 1 do + local o = at + i * 4 + s2 = (s2 + readu32(TABLE, (0x400 + band(k, 0xFF)) * 4)) % TWO32 + local ch = bxor(readu32(buf, o), (k + s2) % TWO32) + k = bor((lshift(bnot(k), 0x15) + 0x11111111) % TWO32, rshift(k, 0x0B)) + s2 = (ch + s2 + lshift(s2, 5) + 3) % TWO32 + writeu32(buf, o, ch) + end +end + +-- base name of an archived path (the file key uses it) +function Crypt.baseName(name: string): string + return string.match(name, "([^\\/]*)$") or name +end + +return Crypt diff --git a/src/Formats/archive/mpq/init.luau b/src/Formats/archive/mpq/init.luau new file mode 100644 index 0000000..ced21c0 --- /dev/null +++ b/src/Formats/archive/mpq/init.luau @@ -0,0 +1,419 @@ +--!strict +-- archive/mpq: Blizzard MPQ archives (MoPaQ: Diablo, StarCraft, Warcraft II / III, WoW, StarCraft II), read into the +-- standard Archive. Supports: header versions 1-4 with the classic hash and block tables (encrypted, found at offset +-- 0, at any 512-byte boundary (prefixed archives / installers) or through the "MPQ\x1B" user data header), the hi-block +-- table (files past 4 GB), names from "(listfile)" (plus opts.names), unnamed files as "File00000123.xxx" (block +-- index), encrypted files (key from the name, MPQ_FILE_FIX_KEY), sector offset tables, single-unit files, imploded +-- files (codecs/compress/Explode), compressed sectors: zlib (codecs/compress/Deflate), PKWARE DCL implode, bzip2 +-- (codecs/compress/Bzip2), LZMA (codecs/compress/Lzma), sparse, and combinations; deleted and delete-marker blocks +-- are skipped. Written from the MPQ format description (Justin Olbrantz / Jean-Francois Roy, "The MoPaQ Archive +-- Format", and StormLib's documentation); no code taken. +-- Not supported (Err.UNSUPPORTED on read): Huffman and IMA ADPCM sectors (WAVE files), patch files, the HET / BET +-- tables of archives without classic tables, encrypted files whose name is unknown, compressed hash / block tables, +-- writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Archive = require("@formats/containers/Archive") +local Deflate = require("@formats/codecs/compress/Deflate") +local Bzip2 = require("@formats/codecs/compress/Bzip2") +local Lzma = require("@formats/codecs/compress/Lzma") +local Explode = require("@formats/codecs/compress/Explode") +local Crypt = require("@formats/archive/mpq/Crypt") + +-- ------------------------------------------------------------------------------------------------ contract +local Mpq = { + name = "mpq", + category = "archive", + extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, + mime = { "application/x-mpq" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, + caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + names: { string }?, -- extra file names to look up (beside the archive's own "(listfile)") + maxEntries: number?, -- default 1e6 + maxBytes: number?, -- the largest file read (default 2^30) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FLAG_IMPLODE, FLAG_COMPRESS, FLAG_ENCRYPTED, FLAG_FIX_KEY = 0x100, 0x200, 0x10000, 0x20000 +local FLAG_PATCH, FLAG_SINGLE, FLAG_DELETE, FLAG_CRC, FLAG_EXISTS = 0x100000, 0x1000000, 0x2000000, 0x4000000, 0x80000000 +local KEY_HASH_TABLE, KEY_BLOCK_TABLE = Crypt.hash("(hash table)", 3), Crypt.hash("(block table)", 3) +local TWO32 = 4294967296 +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ sniff +function Mpq.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "MPQ\x1A" or m == "MPQ\x1B" then + return 1 + end + -- a prefixed archive (an installer stub): the header on a 512-byte boundary in the first 64 KB + for at = 512, math.min(65536, r:remaining() - 32), 512 do + if r:peek(4, at) == "MPQ\x1A" then + return 0.6 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sparse: a big-endian u32 size, then runs: 0x80 | (n - 1) followed by n bytes, or n - 3 meaning n zeros +local function unsparse(b: buffer, at: number, n: number, want: number): (buffer?, string?) + local out = buffer.create(want) + local p, stop, o = at + 4, at + n, 0 + while p < stop and o < want do + local c = buffer.readu8(b, p) + p += 1 + if c >= 0x80 then + local k = c - 0x7F + if p + k > stop then + return nil, "sparse run past the end" + end + k = math.min(k, want - o) + buffer.copy(out, o, b, p, k) + p += k + o += k + else + o = math.min(want, o + c + 3) + end + end + return out, nil +end + +-- one compressed sector (mask byte first) -> want bytes +local function decompress(b: buffer, at: number, n: number, want: number): (buffer?, Err.Err?) + if n < 1 then + return nil, Err.new(Err.CORRUPT, "empty compressed sector") + end + local mask = buffer.readu8(b, at) + local cur: buffer, cat: number, cn: number = b, at + 1, n - 1 + if mask == 0x12 then + if cn < 14 or buffer.readu8(b, cat) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "LZMA sector with a filter") + end + local props = buffer.readstring(b, cat + 1, 5) + local out, e = Lzma.lzma(b, cat + 14, cn - 14, props, want, { maxBytes = want }) + if not out then + return nil, e + end + return out, nil + end + if band(mask, 0xC1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, string.format("Huffman / ADPCM sector (mask 0x%02x)", mask)) + end + if band(mask, 0x10) ~= 0 then + local out, e = Bzip2.decompress(cur, cat, cn, { maxBytes = want }) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x08) ~= 0 then + local out, e = Explode.decompress(cur, cat, cn, want) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x02) ~= 0 then + local out, e = Deflate.zlib(cur, cat, cn) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x20) ~= 0 then + local out, msg = unsparse(cur, cat, cn, want) + if not out then + return nil, Err.from(msg) + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x3A) ~= mask then + return nil, Err.new(Err.UNSUPPORTED, string.format("compression mask 0x%02x", mask)) + end + if cn ~= want then + return nil, Err.new(Err.CORRUPT, "sector decompressed to " .. tostring(cn) .. " bytes, expected " .. tostring(want)) + end + if cur == b then + local len = cn :: number + local copy = buffer.create(len) + buffer.copy(copy, 0, b, cat, len) + return copy, nil + end + return cur, nil +end + +type Block = { offset: number, csize: number, size: number, flags: number } + +-- read a file's bytes (the archive buffer, the absolute block offset, the file name for the key) +local function readFile(b: buffer, limit: number, blk: Block, at: number, name: string?, sectorSize: number, maxBytes: number): (buffer?, Err.Err?) + local flags = blk.flags + if band(flags, FLAG_PATCH) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "patch files") + end + if blk.size > maxBytes then + return nil, Err.new(Err.LIMIT, "file of " .. blk.size .. " bytes") + end + if at + blk.csize > limit then + return nil, Err.new(Err.TRUNCATED, "file data past the end") + end + local encrypted = band(flags, FLAG_ENCRYPTED) ~= 0 + local key = 0 + if encrypted then + if not name then + return nil, Err.new(Err.UNSUPPORTED, "encrypted file without a known name") + end + key = Crypt.hash(Crypt.baseName(name), 3) + if band(flags, FLAG_FIX_KEY) ~= 0 then + key = bit32.bxor((key + blk.offset) % TWO32, blk.size % TWO32) + end + end + local compressed = band(flags, FLAG_COMPRESS + FLAG_IMPLODE) ~= 0 + local imploded = band(flags, FLAG_IMPLODE) ~= 0 + local function sector(src: buffer, sat: number, sn: number, want: number, k: number): (buffer?, Err.Err?) + local raw = buffer.create(sn) + buffer.copy(raw, 0, src, sat, sn) + if encrypted then + Crypt.decrypt(raw, 0, sn, k) + end + if compressed and sn < want then + if imploded then + return Explode.decompress(raw, 0, sn, want) + end + return decompress(raw, 0, sn, want) + end + if sn ~= want then + if sn > want then + local cut = buffer.create(want) + buffer.copy(cut, 0, raw, 0, want) + return cut, nil + end + return nil, Err.new(Err.CORRUPT, "stored sector of " .. sn .. " bytes, expected " .. want) + end + return raw, nil + end + if band(flags, FLAG_SINGLE) ~= 0 then + local out, e = sector(b, at, blk.csize, blk.size, key) + if out and buffer.len(out) ~= blk.size then + return nil, Err.new(Err.CORRUPT, "file size mismatch") + end + return out, e + end + local out = buffer.create(blk.size) + local nsec = (blk.size + sectorSize - 1) // sectorSize + if not compressed then + -- stored in sectors (each decrypted with key + its index) + for i = 0, nsec - 1 do + local want = math.min(sectorSize, blk.size - i * sectorSize) + local s, e = sector(b, at + i * sectorSize, want, want, key + i) + if not s then + return nil, e + end + buffer.copy(out, i * sectorSize, s, 0, want) + end + return out, nil + end + local entries = nsec + 1 + (if band(flags, FLAG_CRC) ~= 0 then 1 else 0) + if entries * 4 > blk.csize then + return nil, Err.new(Err.CORRUPT, "sector table larger than the file") + end + local tbl = buffer.create(entries * 4) + buffer.copy(tbl, 0, b, at, entries * 4) + if encrypted then + Crypt.decrypt(tbl, 0, entries * 4, (key - 1) % TWO32) + end + for i = 0, nsec - 1 do + local s0, s1 = buffer.readu32(tbl, i * 4), buffer.readu32(tbl, i * 4 + 4) + if s1 < s0 or s1 > blk.csize then + return nil, Err.new(Err.CORRUPT, "bad sector offset table") + end + local want = math.min(sectorSize, blk.size - i * sectorSize) + local s, e = sector(b, at + s0, s1 - s0, want, key + i) + if not s then + return nil, e + end + if buffer.len(s) ~= want then + return nil, Err.new(Err.CORRUPT, "sector " .. i .. " decompressed to " .. buffer.len(s) .. " bytes, expected " .. want) + end + buffer.copy(out, i * sectorSize, s, 0, want) + end + return out, nil +end + +local function encode(_archive: any, _opts: any?): (buffer?, Err.Err?) + return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only") +end + +-- the header: its absolute offset in r (0, a 512-byte boundary, or behind "MPQ\x1B") | nil +local function findHeader(r: Bytes.Reader): number? + local size = r.limit - r.base + local p = 0 + while p + 32 <= size do + local m = buffer.readstring(r.buf, r.base + p, 4) + if m == "MPQ\x1A" then + return p + elseif m == "MPQ\x1B" and p + 12 <= size then + local at = p + buffer.readu32(r.buf, r.base + p + 8) + if at + 32 <= size and buffer.readstring(r.buf, r.base + at, 4) == "MPQ\x1A" then + return at + end + end + p += 512 + end + return nil +end + +function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local found = findHeader(r) + if not found then + return nil, Err.new(if r:remaining() < 32 then Err.TRUNCATED else Err.CORRUPT, "no MPQ header", 0) + end + local h: number = found + local hr = r:sub(h) + hr:skip(4) + local headerSize, archiveSize = hr:u32le(), hr:u32le() + local version, shift = hr:u16le(), hr:u16le() + local hashPos, blockPos, hashCount, blockCount = hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() + local hiBlockPos, hashHi, blockHi = 0, 0, 0 + if version >= 1 and headerSize >= 44 then + hiBlockPos = hr:u64le() + hashHi, blockHi = hr:u16le(), hr:u16le() + end + if hr.err then + return nil, hr.err + end + if shift > 20 then + return nil, Err.new(Err.CORRUPT, "bad sector size shift " .. shift, h + 14) + end + local sectorSize = 512 * 2 ^ shift + if hashCount == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no classic hash table (HET / BET only)") + end + local maxEntries: number = opts and opts.maxEntries or 1e6 + if hashCount > maxEntries * 4 or blockCount > maxEntries then + return nil, Err.new(Err.LIMIT, "too many entries") + end + local size = r.limit - r.base + local hashAt = h + hashPos + hashHi * TWO32 + local blockAt = h + blockPos + blockHi * TWO32 + if hashAt + hashCount * 16 > size or blockAt + blockCount * 16 > size then + return nil, Err.new(Err.TRUNCATED, "hash / block table past the end", h + 16) + end + local hashes = buffer.create(hashCount * 16) + buffer.copy(hashes, 0, r.buf, r.base + hashAt, hashCount * 16) + Crypt.decrypt(hashes, 0, hashCount * 16, KEY_HASH_TABLE) + local blocksBuf = buffer.create(blockCount * 16) + buffer.copy(blocksBuf, 0, r.buf, r.base + blockAt, blockCount * 16) + Crypt.decrypt(blocksBuf, 0, blockCount * 16, KEY_BLOCK_TABLE) + local hiAt = if hiBlockPos > 0 then h + hiBlockPos else -1 + if hiAt >= 0 and hiAt + blockCount * 2 > size then + hiAt = -1 + end + local blocks: { Block } = {} + for i = 0, blockCount - 1 do + local hi = if hiAt >= 0 then buffer.readu16(r.buf, r.base + hiAt + i * 2) else 0 + blocks[i + 1] = { + offset = buffer.readu32(blocksBuf, i * 16) + hi * TWO32, + csize = buffer.readu32(blocksBuf, i * 16 + 4), + size = buffer.readu32(blocksBuf, i * 16 + 8), + flags = buffer.readu32(blocksBuf, i * 16 + 12), + } + end + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + local mask = hashCount - 1 + local pow2 = band(hashCount, mask) == 0 + -- lookup(name) -> block index (1-based) | nil + local function lookup(name: string): number? + local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2) + local start = if pow2 then band(h0, mask) else h0 % hashCount + for k = 0, hashCount - 1 do + local o = ((start + k) % hashCount) * 16 + local bi = buffer.readu32(hashes, o + 12) + if bi == 0xFFFFFFFF then + return nil + end + if bi ~= 0xFFFFFFFE and buffer.readu32(hashes, o) == h1 and buffer.readu32(hashes, o + 4) == h2 and bi < blockCount then + return bi + 1 + end + end + return nil + end + local function usable(bi: number): boolean + local f = blocks[bi].flags + return band(f, FLAG_EXISTS) ~= 0 and band(f, FLAG_DELETE) == 0 + end + local function blockData(bi: number, name: string?): (buffer?, Err.Err?) + local blk = blocks[bi] + return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes) + end + -- names: (listfile) and opts.names + local names: { string } = {} + for _, internal in { "(attributes)", "(signature)", "(user data)" } do + table.insert(names, internal) + end + local lf = lookup("(listfile)") + if lf and usable(lf) then + table.insert(names, "(listfile)") + local data = blockData(lf, "(listfile)") + if data then + for line in string.gmatch(buffer.tostring(data), "[^\r\n;]+") do + local nm = string.match(line, "^%s*(.-)%s*$") + if nm and nm ~= "" then + table.insert(names, nm) + end + end + end + end + if opts and type(opts.names) == "table" then + for _, nm in opts.names do + if type(nm) == "string" then + table.insert(names, nm) + end + end + end + local a = Archive.new("mpq", encode) + local named: { [number]: string } = {} + local function add(bi: number, name: string?) + local blk = blocks[bi] + local entryName = name or string.format("File%08d.xxx", bi - 1) + Archive.put(a, { + name = entryName, + size = blk.size, + compressedSize = blk.csize, + dir = false, + method = if band(blk.flags, FLAG_IMPLODE) ~= 0 then "implode" elseif band(blk.flags, FLAG_COMPRESS) ~= 0 then "compress" else "store", + encrypted = band(blk.flags, FLAG_ENCRYPTED) ~= 0, + flags = blk.flags, + block = bi - 1, + load = function(): (buffer?, Err.Err?) + return blockData(bi, name) + end, + }) + end + for _, nm in names do + local bi = lookup(nm) + if bi and usable(bi) and not named[bi] then + named[bi] = nm + add(bi, nm) + end + end + for bi = 1, blockCount do + if not named[bi] and usable(bi) and blocks[bi].size > 0 then + add(bi, nil) + end + end + a.meta.source = { format = "mpq", version = version + 1, sectorSize = sectorSize, offset = h, archiveSize = archiveSize, hashTable = hashCount, blockTable = blockCount } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- hash(name, kind) -> the MPQ name hash (kind 0 = table index, 1 / 2 = name checks, 3 = file key) +Mpq.hash = Crypt.hash + +return Mpq diff --git a/src/Formats/archive/vpk/init.luau b/src/Formats/archive/vpk/init.luau new file mode 100644 index 0000000..a26fddc --- /dev/null +++ b/src/Formats/archive/vpk/init.luau @@ -0,0 +1,317 @@ +--!strict +-- archive/vpk: Valve VPK archives (Source / Source 2: version 1 and 2 directory files, "pak01_dir.vpk"), read into the +-- standard Archive and written from any Archive value. Reading: the extension / path / name tree, preload bytes +-- (stored in the tree) followed by the data, data embedded in the directory file (archive index 0x7fff) or in the +-- numbered part files "_NNN.vpk", found through opts.resolve(fileName) / opts.files[fileName] (the name comes +-- from opts.name, "x_dir.vpk" -> "x_000.vpk", default "pak01"); each entry's CRC-32 is checked on read; version 2's +-- MD5 section is kept in meta. Writing: one self-contained directory file (every entry embedded, no preload), +-- version 2 by default with its tree / chunk / file MD5s (version = 1 for the older header). Written from the +-- Valve Developer Community VPK file format page; no code taken. +-- Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Input = require("@formats/core/Input") +local Crc32 = require("@formats/core/Crc32") +local Md5 = require("@formats/core/Md5") +local Archive = require("@formats/containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Vpk = { + name = "vpk", + category = "archive", + extensions = { "vpk" }, + mime = { "application/x-vpk" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, + caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + verify: boolean?, -- check each entry's CRC-32 on read (default true) + resolve: ((name: string) -> (buffer | string)?)?, -- the part files ("pak01_000.vpk", ...) + files: { [string]: buffer | string }?, + name: string?, -- the directory file's name ("pak01_dir.vpk"), for the part file names + maxEntries: number?, -- default 1e6 +} +export type EncodeOptions = { version: number? } -- 1 or 2 (default: the source's, else 2) + +-- ------------------------------------------------------------------------------------------------ constants +local SIGNATURE = 0x55AA1234 +local EMBEDDED = 0x7FFF + +-- ------------------------------------------------------------------------------------------------ sniff +function Vpk.sniff(r: Bytes.Reader): number + if r:remaining() < 12 or r:peek(4) ~= "\x34\x12\xAA\x55" then + return 0 + end + local v = r:peekU8(4) + return if v == 1 or v == 2 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Vpk.encode(archive, opts) +end + +-- the part file `index` as a buffer (cached per archive) +local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?) + local cache: { [number]: buffer } = {} + local prefix = "pak01" + if opts and type(opts.name) == "string" then + local base = string.match(opts.name, "([^/\\]+)$") or opts.name + prefix = string.match(base, "^(.*)_dir%.[vV][pP][kK]$") or string.match(base, "^(.*)%.[vV][pP][kK]$") or base + end + return function(index: number): (buffer?, Err.Err?) + local hit = cache[index] + if hit then + return hit, nil + end + local name = string.format("%s_%03d.vpk", prefix, index) + local b = Input.sibling(opts, name) + if not b then + return nil, Err.new(Err.UNSUPPORTED, "part file " .. name .. " not available (opts.resolve / opts.files)") + end + cache[index] = b + return b, nil + end +end + +local function loader(r: Bytes.Reader, e: any, dataBase: number, part: (number) -> (buffer?, Err.Err?), verify: boolean): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local src: buffer, at: number + if e.archiveIndex == EMBEDDED then + src, at = r.buf, r.base + dataBase + e.archiveOffset + if dataBase + e.archiveOffset + e.length > r.limit - r.base then + return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end") + end + else + local b, err = part(e.archiveIndex) + if not b then + return nil, err + end + src, at = b, e.archiveOffset + if at + e.length > buffer.len(b) then + return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end of part " .. e.archiveIndex) + end + end + local out = buffer.create(e.preloadLength + e.length) + buffer.copy(out, 0, r.buf, e.preloadAt, e.preloadLength) + buffer.copy(out, e.preloadLength, src, at, e.length) + if verify and Crc32.of(out) ~= e.crc32 then + return nil, Err.new(Err.CHECKSUM, "entry " .. e.name .. ": CRC-32 mismatch") + end + return out, nil + end +end + +function Vpk.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local sig, version, treeSize = r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if sig ~= SIGNATURE then + return nil, Err.new(Err.CORRUPT, "bad signature", 0) + end + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "VPK version " .. version, 4) + end + local v2: any = nil + if version == 2 then + v2 = { fileDataSize = r:u32le(), archiveMd5Size = r:u32le(), otherMd5Size = r:u32le(), signatureSize = r:u32le() } + if r.err then + return nil, r.err + end + end + local headerLen = r:tell() - r.base + if headerLen + treeSize > r.limit - r.base then + return nil, Err.new(Err.TRUNCATED, "tree past the end", 8) + end + local t = r:sub(headerLen, treeSize) + local a = Archive.new("vpk", encode) + local part = partLoader(opts) + local verify = not (opts and opts.verify == false) + local maxEntries = opts and opts.maxEntries or 1e6 + local count = 0 + local parts: { [number]: boolean } = {} + local dataBase = headerLen + treeSize + while true do + local ext = t:cstring() + if t.err then + return nil, t.err + end + if ext == "" then + break + end + while true do + local path = t:cstring() + if t.err then + return nil, t.err + end + if path == "" then + break + end + while true do + local name = t:cstring() + if t.err then + return nil, t.err + end + if name == "" then + break + end + local e: any = { crc32 = t:u32le(), preloadLength = t:u16le(), archiveIndex = t:u16le(), archiveOffset = t:u32le(), length = t:u32le() } + local term = t:u16le() + e.preloadAt = t.pos + t:skip(e.preloadLength) + if t.err then + return nil, t.err + end + if term ~= 0xFFFF then + return nil, Err.new(Err.CORRUPT, "bad entry terminator", t:tell() + headerLen) + end + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "too many entries") + end + local full = (if path == " " then "" else path .. "/") .. name .. (if ext == " " then "" else "." .. ext) + e.name = full + if e.archiveIndex ~= EMBEDDED then + parts[e.archiveIndex] = true + end + Archive.put(a, { + name = full, + size = e.preloadLength + e.length, + dir = false, + method = "store", + crc32 = e.crc32, + archiveIndex = if e.archiveIndex == EMBEDDED then nil else e.archiveIndex, + preload = e.preloadLength, + load = loader(r, e, dataBase, part, verify), + }) + end + end + end + local partList: { number } = {} + for k in parts do + table.insert(partList, k) + end + table.sort(partList) + a.meta.source = { format = "vpk", version = version, entries = count, parts = partList } + if v2 then + local md5At = dataBase + v2.fileDataSize + if v2.otherMd5Size == 48 and md5At + v2.archiveMd5Size + 48 <= r.limit - r.base then + local m = r:sub(md5At + v2.archiveMd5Size, 48) + v2.treeMd5, v2.chunkHashesMd5, v2.fileMd5 = m:string(16), m:string(16), m:string(16) + end + a.meta.source.v2 = v2 + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vpk.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local version = opts and opts.version or (if type(src) == "table" and src.format == "vpk" then src.version else nil) or 2 + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.ARG, "version must be 1 or 2") + end + -- group by extension, then path, keeping first-seen order + local exts: { string } = {} + local byExt: { [string]: { paths: { string }, byPath: { [string]: { { name: string, data: buffer } } } } } = {} + for _, it in items do + if not it.entry.dir then + local full = string.gsub(it.entry.name, "\\", "/") + local dir, file = string.match(full, "^(.*)/([^/]*)$") + if not dir then + dir, file = " ", full + end + local stem, ext = string.match(file :: string, "^(.*)%.([^.]*)$") + if not stem or stem == "" then + stem, ext = file, " " + end + if stem == "" or dir == "" or string.find(full, "\0", 1, true) then + return nil, Err.new(Err.ARG, "bad entry name: " .. it.entry.name) + end + local g = byExt[ext :: string] + if not g then + g = { paths = {}, byPath = {} } + byExt[ext :: string] = g + table.insert(exts, ext :: string) + end + local l = g.byPath[dir :: string] + if not l then + l = {} + g.byPath[dir :: string] = l + table.insert(g.paths, dir :: string) + end + table.insert(l, { name = stem :: string, data = it.data }) + end + end + local tree = Bytes.writer() + local data = Bytes.writer() + for _, ext in exts do + tree:cstring(ext) + local g = byExt[ext] + for _, path in g.paths do + tree:cstring(path) + for _, f in g.byPath[path] do + tree:cstring(f.name) + tree:u32le(Crc32.of(f.data)) + tree:u16le(0) + tree:u16le(EMBEDDED) + tree:u32le(data:tell()) + tree:u32le(buffer.len(f.data)) + tree:u16le(0xFFFF) + data:bytes(f.data) + end + tree:u8(0) + end + tree:u8(0) + end + tree:u8(0) + local tb, db = tree:finish(), data:finish() + local w = Bytes.writer(buffer.len(tb) + buffer.len(db) + 128) + w:u32le(SIGNATURE) + w:u32le(version) + w:u32le(buffer.len(tb)) + if version == 2 then + w:u32le(buffer.len(db)) + w:u32le(0) + w:u32le(48) + w:u32le(0) + end + w:bytes(tb) + w:bytes(db) + if version == 2 then + local treeMd5 = Md5.new() + treeMd5:update(tb) + local tmd = treeMd5:digest() + local chunkMd5 = Md5.new():digest() + local file = Md5.new() + local sofar = w:finish() + file:update(sofar) + file:update(buffer.fromstring(tmd .. chunkMd5)) + local out = Bytes.writer(buffer.len(sofar) + 48) + out:bytes(sofar) + out:string(tmd) + out:string(chunkMd5) + out:string(file:digest()) + return out:finish(), nil + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(version?) -> an empty VPK Archive (version 2 by default): a:add(name, data); a:write() +function Vpk.new(version: number?): any + local a = Archive.new("vpk", encode) + a.meta.source = { format = "vpk", version = version or 2 } + return a +end + +return Vpk diff --git a/src/Formats/archive/wad/Map.luau b/src/Formats/archive/wad/Map.luau new file mode 100644 index 0000000..dce8a28 --- /dev/null +++ b/src/Formats/archive/wad/Map.luau @@ -0,0 +1,441 @@ +--!strict +-- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS, +-- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a +-- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with +-- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the +-- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one +-- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z +-- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not +-- supported. +local Types = require("@formats/Types") +local Polygon = require("@formats/codecs/model/Polygon") + +local Map = {} + +local Scene = Types.Scene +local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16 +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +export type Lump = { buf: buffer, at: number, size: number } +export type Thing = { x: number, y: number, z: number?, angle: number, type: number, flags: number, tid: number?, special: number?, args: { number }? } +export type Linedef = { v1: number, v2: number, flags: number, special: number, tag: number?, args: { number }?, front: number?, back: number? } +export type Sidedef = { xoff: number, yoff: number, upper: string, lower: string, middle: string, sector: number } +export type Sector = { floor: number, ceiling: number, floorFlat: string, ceilingFlat: string, light: number, special: number, tag: number } +export type MapData = { + format: "doom" | "hexen", + things: { Thing }, + linedefs: { Linedef }, + sidedefs: { Sidedef }, + vertices: { number }, -- x1, y1, x2, y2, ... + sectors: { Sector }, +} +-- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows +export type Textures = { + size: (kind: string, name: string) -> (number?, number?), + image: ((kind: string, name: string) -> Types.Image?)?, +} + +-- ------------------------------------------------------------------------------------------------ parse +local function name8(b: buffer, at: number): string + local s = buffer.readstring(b, at, 8) + local z = string.find(s, "\0", 1, true) + return string.upper(if z then string.sub(s, 1, z - 1) else s) +end + +local function side(v: number): number? + return if v == 0xFFFF then nil else v + 1 +end + +-- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump) +function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?) + for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do + if not lumps[k] then + return nil, "map has no " .. k + end + end + local m: MapData = { format = if hexen then "hexen" else "doom", things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {} } + local v = lumps.VERTEXES + for i = 0, v.size // 4 - 1 do + table.insert(m.vertices, readi16(v.buf, v.at + i * 4)) + table.insert(m.vertices, readi16(v.buf, v.at + i * 4 + 2)) + end + local s = lumps.SECTORS + for i = 0, s.size // 26 - 1 do + local o = s.at + i * 26 + table.insert(m.sectors, { + floor = readi16(s.buf, o), + ceiling = readi16(s.buf, o + 2), + floorFlat = name8(s.buf, o + 4), + ceilingFlat = name8(s.buf, o + 12), + light = readi16(s.buf, o + 20), + special = readu16(s.buf, o + 22), + tag = readu16(s.buf, o + 24), + }) + end + local sd = lumps.SIDEDEFS + for i = 0, sd.size // 30 - 1 do + local o = sd.at + i * 30 + table.insert(m.sidedefs, { + xoff = readi16(sd.buf, o), + yoff = readi16(sd.buf, o + 2), + upper = name8(sd.buf, o + 4), + lower = name8(sd.buf, o + 12), + middle = name8(sd.buf, o + 20), + sector = readu16(sd.buf, o + 28) + 1, + }) + end + local l = lumps.LINEDEFS + local ls = if hexen then 16 else 14 + for i = 0, l.size // ls - 1 do + local o = l.at + i * ls + local b = l.buf + if hexen then + table.insert(m.linedefs, { + v1 = readu16(b, o) + 1, + v2 = readu16(b, o + 2) + 1, + flags = readu16(b, o + 4), + special = readu8(b, o + 6), + args = { readu8(b, o + 7), readu8(b, o + 8), readu8(b, o + 9), readu8(b, o + 10), readu8(b, o + 11) }, + front = side(readu16(b, o + 12)), + back = side(readu16(b, o + 14)), + }) + else + table.insert(m.linedefs, { + v1 = readu16(b, o) + 1, + v2 = readu16(b, o + 2) + 1, + flags = readu16(b, o + 4), + special = readu16(b, o + 6), + tag = readu16(b, o + 8), + front = side(readu16(b, o + 10)), + back = side(readu16(b, o + 12)), + }) + end + end + local t = lumps.THINGS + if t then + local ts = if hexen then 20 else 10 + for i = 0, t.size // ts - 1 do + local o = t.at + i * ts + local b = t.buf + if hexen then + table.insert(m.things, { + tid = readi16(b, o), + x = readi16(b, o + 2), + y = readi16(b, o + 4), + z = readi16(b, o + 6), + angle = readi16(b, o + 8), + type = readu16(b, o + 10), + flags = readu16(b, o + 12), + special = readu8(b, o + 14), + args = { readu8(b, o + 15), readu8(b, o + 16), readu8(b, o + 17), readu8(b, o + 18), readu8(b, o + 19) }, + }) + else + table.insert(m.things, { + x = readi16(b, o), + y = readi16(b, o + 2), + angle = readi16(b, o + 4), + type = readu16(b, o + 6), + flags = readu16(b, o + 8), + }) + end + end + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ sector outlines +-- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1; +-- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks; +-- chains that do not close are dropped +local function loops(m: MapData): { [number]: { { number } } } + local edges: { [number]: { { number } } } = {} + local nv = #m.vertices // 2 + local function add(sec: number, a: number, b: number) + local e = edges[sec] or {} + edges[sec] = e + table.insert(e, { a, b }) + end + for _, ld in m.linedefs do + if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then + local fs = ld.front and m.sidedefs[ld.front] + local bs = ld.back and m.sidedefs[ld.back] + local f = fs and fs.sector + local b = bs and bs.sector + if f ~= b then + if f and m.sectors[f] then + add(f, ld.v1, ld.v2) + end + if b and m.sectors[b] then + add(b, ld.v2, ld.v1) + end + end + end + end + local V = m.vertices + local out: { [number]: { { number } } } = {} + for sec, list in edges do + local from: { [number]: { number } } = {} + for i, e in list do + local l = from[e[1]] or {} + from[e[1]] = l + table.insert(l, i) + end + local used: { [number]: boolean } = {} + local res: { { number } } = {} + for start = 1, #list do + if not used[start] then + used[start] = true + local loop = { list[start][1] } + local cur = start + local closed = false + for _ = 1, #list do + local e = list[cur] + local at = e[2] + if at == loop[1] then + closed = true + break + end + table.insert(loop, at) + local cands = from[at] + local best, bestT = nil :: number?, math.huge + if cands then + local ix, iy = V[at * 2 - 1] - V[e[1] * 2 - 1], V[at * 2] - V[e[1] * 2] + for _, c in cands do + if not used[c] then + local n2 = list[c][2] + local ox, oy = V[n2 * 2 - 1] - V[at * 2 - 1], V[n2 * 2] - V[at * 2] + local t = math.atan2(ix * oy - iy * ox, ix * ox + iy * oy) + if t < bestT then + best, bestT = c, t + end + end + end + end + if not best then + break + end + used[best] = true + cur = best + end + if closed and #loop >= 3 then + table.insert(res, loop) + end + end + end + out[sec] = res + end + return out +end + +local function insideLoop(V: { number }, loop: { number }, x: number, y: number): boolean + local c = false + local n = #loop + local j = n + for i = 1, n do + local ax, ay = V[loop[i] * 2 - 1], V[loop[i] * 2] + local bx, by = V[loop[j] * 2 - 1], V[loop[j] * 2] + if (ay > y) ~= (by > y) and x < (bx - ax) * (y - ay) / (by - ay) + ax then + c = not c + end + j = i + end + return c +end + +-- ------------------------------------------------------------------------------------------------ scene +type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv: { number } } + +local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4 + +-- scene(m, tex, name) -> Scene +function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene + local batches: { [string]: Batch } = {} + local order: { string } = {} + local function batch(kind: string, tname: string): Batch + local key = kind .. ":" .. tname + local b = batches[key] + if not b then + b = { kind = kind, name = tname, pos = {}, nrm = {}, uv = {} } + batches[key] = b + table.insert(order, key) + end + return b + end + local function vert(b: Batch, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number) + local p, n, t = b.pos, b.nrm, b.uv + p[#p + 1], p[#p + 2], p[#p + 3] = x, y, z + n[#n + 1], n[#n + 2], n[#n + 3] = nx, ny, nz + t[#t + 1], t[#t + 2] = u, v + end + local V = m.vertices + local nv = #V // 2 + -- floors and ceilings + local secLoops = loops(m) + for sec, ls in secLoops do + local s = m.sectors[sec] + local flat: { { number } } = {} + for li, loop in ls do + local f: { number } = {} + for _, vi in loop do + table.insert(f, V[vi * 2 - 1]) + table.insert(f, V[vi * 2]) + end + flat[li] = f + end + local tris = Polygon.triangulate(flat) + for pass = 1, 2 do + local tname = if pass == 1 then s.floorFlat else s.ceilingFlat + local fw, fh = tex.size("flat", tname) + local w, h = fw or 64, fh or 64 + local z = if pass == 1 then s.floor else s.ceiling + local b = batch("flat", tname) + local nz = if pass == 1 then 1 else -1 + for k = 1, #tris, 6 do + for c = 0, 2 do + local cc = if pass == 1 then c else 2 - c + local loop = ls[tris[k + cc * 2]] + local vi = loop[tris[k + cc * 2 + 1]] + local x, y = V[vi * 2 - 1], V[vi * 2] + vert(b, x, y, z, 0, 0, nz, x / w, -y / h) + end + end + end + end + -- walls + local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number) + if tname == "-" or tname == "" or zt <= zb then + return + end + local tw, th = tex.size("texture", tname) + local w, h = tw or 64, th or 128 + local b = batch("texture", tname) + local dx, dy = x2 - x1, y2 - y1 + local l = math.sqrt(dx * dx + dy * dy) + local nx, ny = dy / l, -dx / l + local u0, u1 = xoff / w, (xoff + len) / w + local vb, vt = (texTop - zb + yoff) / h, (texTop - zt + yoff) / h + vert(b, x1, y1, zb, nx, ny, 0, u0, vb) + vert(b, x2, y2, zb, nx, ny, 0, u1, vb) + vert(b, x2, y2, zt, nx, ny, 0, u1, vt) + vert(b, x1, y1, zb, nx, ny, 0, u0, vb) + vert(b, x2, y2, zt, nx, ny, 0, u1, vt) + vert(b, x1, y1, zt, nx, ny, 0, u0, vt) + end + for _, ld in m.linedefs do + if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then + local ax, ay, bx, by = V[ld.v1 * 2 - 1], V[ld.v1 * 2], V[ld.v2 * 2 - 1], V[ld.v2 * 2] + local len = math.sqrt((bx - ax) ^ 2 + (by - ay) ^ 2) + for sideN = 1, 2 do + local sdi = if sideN == 1 then ld.front else ld.back + local odi = if sideN == 1 then ld.back else ld.front + local sd = sdi and m.sidedefs[sdi] + local me = sd and m.sectors[sd.sector] + if sd and me then + local x1, y1, x2, y2 = ax, ay, bx, by + if sideN == 2 then + x1, y1, x2, y2 = bx, by, ax, ay + end + local od = odi and m.sidedefs[odi] + local other = od and m.sectors[od.sector] + if not other then + local th = select(2, tex.size("texture", sd.middle)) or 128 + local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.floor + th else me.ceiling + quad(sd.middle, x1, y1, x2, y2, me.floor, me.ceiling, sd.xoff, len, top, sd.yoff) + else + if other.floor > me.floor then + local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.ceiling else other.floor + quad(sd.lower, x1, y1, x2, y2, me.floor, other.floor, sd.xoff, len, top, sd.yoff) + end + local sky = string.sub(me.ceilingFlat, 1, 5) == "F_SKY" and string.sub(other.ceilingFlat, 1, 5) == "F_SKY" + if other.ceiling < me.ceiling and not sky then + local th = select(2, tex.size("texture", sd.upper)) or 128 + local top = if bit32.band(ld.flags, UPPER_UNPEGGED) ~= 0 then me.ceiling else other.ceiling + th + quad(sd.upper, x1, y1, x2, y2, other.ceiling, me.ceiling, sd.xoff, len, top, sd.yoff) + end + if sd.middle ~= "-" and sd.middle ~= "" and bit32.band(ld.flags, TWO_SIDED) ~= 0 then + local th = select(2, tex.size("texture", sd.middle)) or 128 + local lo, hi = math.max(me.floor, other.floor), math.min(me.ceiling, other.ceiling) + local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then lo + th else hi + quad(sd.middle, x1, y1, x2, y2, math.max(lo, top + sd.yoff - th), math.min(hi, top + sd.yoff), sd.xoff, len, top, sd.yoff) + end + end + end + end + end + end + -- the scene + local scene = Scene.new() + scene.meta.up = "z" + local mesh: Types.Mesh = { name = name, primitives = {} } + local texIndex: { [string]: number } = {} + for _, key in order do + local b = batches[key] + local n = #b.pos // 3 + if n > 0 then + local pb, nb, ub, ib = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) + for i = 1, n * 3 do + writef32(pb, (i - 1) * 4, b.pos[i]) + writef32(nb, (i - 1) * 4, b.nrm[i]) + end + for i = 1, n * 2 do + writef32(ub, (i - 1) * 4, b.uv[i]) + end + for i = 0, n - 1 do + writeu32(ib, i * 4, i) + end + local ti = texIndex[key] + if not ti then + table.insert(scene.textures, { name = b.name, uri = b.name, image = if tex.image then tex.image(b.kind, b.name) else nil, extras = { wad = { kind = b.kind } } }) + ti = #scene.textures + texIndex[key] = ti + end + local mat = Scene.material(b.name) + mat.metallic = 0 + mat.baseColorTexture = { texture = ti } + mat.extras = { wad = { kind = b.kind } } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { + attributes = { + POSITION = Scene.accessor(pb, "f32", 3, n), + NORMAL = Scene.accessor(nb, "f32", 3, n), + TEXCOORD_0 = Scene.accessor(ub, "f32", 2, n), + }, + indices = Scene.accessor(ib, "u32", 1, n), + mode = "triangles" :: any, + material = #scene.materials, + extras = { wad = { kind = b.kind, texture = b.name } }, + }) + end + end + table.insert(scene.meshes, mesh) + scene.nodes[1] = { name = name, children = {}, mesh = 1 } + scene.roots[1] = 1 + -- things, on the floor of the sector under them + for i, th in m.things do + local z = th.z or 0 + for sec, ls in secLoops do + local inside = false + for _, loop in ls do + if insideLoop(V, loop, th.x, th.y) then + inside = not inside + end + end + if inside then + z += m.sectors[sec].floor + break + end + end + local a = math.rad(th.angle) / 2 + table.insert(scene.nodes, { + name = "thing " .. i, + children = {}, + translation = { th.x, th.y, z }, + rotation = { 0, 0, math.sin(a), math.cos(a) }, + extras = { thing = { type = th.type, angle = th.angle, flags = th.flags, tid = th.tid, special = th.special, args = th.args } }, + }) + table.insert(scene.nodes[1].children, #scene.nodes) + end + return scene +end + +return Map diff --git a/src/Formats/archive/wad/Picture.luau b/src/Formats/archive/wad/Picture.luau new file mode 100644 index 0000000..c6b0a30 --- /dev/null +++ b/src/Formats/archive/wad/Picture.luau @@ -0,0 +1,109 @@ +--!strict +--!native +-- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column +-- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of +-- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative) +-- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip). +-- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's +-- r_data.c description; no code taken. Never throws: every read is checked against the lump's end. +local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32 + +local Picture = {} + +-- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it) +function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number) + if n < 8 then + return nil, 0, 0, 0 + end + local w, h = readu16(b, at), readu16(b, at + 2) + if w == 0 or h == 0 or w > 4096 or h > 4096 or 8 + w * 4 > n then + return nil, 0, 0, 0 + end + for x = 0, w - 1 do + local o = readu32(b, at + 8 + x * 4) + if o < 8 + w * 4 or o >= n then + return nil, 0, 0, 0 + end + end + return w, h, readi16(b, at + 4), readi16(b, at + 6) +end + +-- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed) +function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?) + local stop = at + n + for x = 0, w - 1 do + local p = at + readu32(b, at + 8 + x * 4) + local top = -1 + while true do + if p >= stop then + return false, "column " .. x .. " runs past the end" + end + local delta = readu8(b, p) + if delta == 255 then + break + end + if p + 3 > stop then + return false, "post header past the end" + end + local len = readu8(b, p + 1) + top = if delta <= top then top + delta else delta + if p + 4 + len > stop then + return false, "post past the end" + end + local src = p + 3 + for k = 0, len - 1 do + local y = top + k + if y < h then + writeu32(out, (y * w + x) * 4, readu32(pal, readu8(b, src + k) * 4)) + end + end + p += 4 + len + end + end + return true, nil +end + +-- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits) +function Picture.flatSize(n: number): (number?, number) + if n == 4096 then + return 64, 64 + elseif n == 4160 then + return 64, 64 -- Heretic / Hexen: 64 x 65, the last row is padding + elseif n == 8192 then + return 64, 128 + elseif n == 12800 then + return 64, 200 -- Heretic / Hexen scrolling flats + end + local s = math.floor(math.sqrt(n) + 0.5) + if s * s == n and s > 0 then + return s, s + end + if n > 0 and n % 64 == 0 then + return 64, n // 64 + end + return nil, 0 +end + +-- flat(b, at, w, h, pal, out): raw indexes, row by row +function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer) + for i = 0, w * h - 1 do + writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4)) + end +end + +-- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy), +-- clipped (composite wall textures from patches) +function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number) + local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1 + for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do + local so, d = y * sw, (y + oy) * dw + ox + for x = x0, x1 do + local v = readu32(src, (so + x) * 4) + if v ~= 0 then + writeu32(dst, (d + x) * 4, v) + end + end + end +end + +return Picture diff --git a/src/Formats/archive/wad/init.luau b/src/Formats/archive/wad/init.luau new file mode 100644 index 0000000..9ab61f0 --- /dev/null +++ b/src/Formats/archive/wad/init.luau @@ -0,0 +1,474 @@ +--!strict +-- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the +-- standard Archive and written from any Archive value, plus the lumps as game data: +-- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map +-- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer +-- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image +-- (meta.offset = { left, top } for pictures; transparent pixels alpha 0) +-- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES) +-- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts) +-- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene +-- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map) +-- Entry names: the lump names, except lumps of a map, named "/" ("MAP01/THINGS"), and later lumps +-- repeating an earlier name, named "~" (n = 2, 3, ...), so every entry is unique; writing strips both again +-- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom +-- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken. +-- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant, +-- big-endian (Jaguar) WADs, compressed Jaguar lumps. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Archive = require("@formats/containers/Archive") +local Pixels = require("@formats/codecs/image/Pixels") +local Picture = require("@formats/archive/wad/Picture") +local Map = require("@formats/archive/wad/Map") + +-- ------------------------------------------------------------------------------------------------ contract +local Wad = { + name = "wad", + category = "archive", + extensions = { "wad" }, + mime = { "application/x-doom" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" }, + caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { maxEntries: number? } -- default 1e6 +export type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD" +export type Lump = { + name: string, -- the lump name as stored (upper case) + entry: string, -- the Archive entry name + index: number, -- 1-based position in the directory + offset: number, + size: number, + namespace: string?, -- "sprites" | "patches" | "flats" | "colormaps" | "textures" (between *_START / *_END markers) + map: string?, -- the map this lump belongs to + marker: boolean?, -- a zero-size marker (F_START, MAP01, ...) +} +export type MapOptions = { + textures: boolean?, -- build texture images (flats / composed wall textures) into scene.textures (default true) + palette: number?, -- PLAYPAL palette index (default 0) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAP_LUMPS: { [string]: boolean } = { + THINGS = true, LINEDEFS = true, SIDEDEFS = true, VERTEXES = true, SEGS = true, SSECTORS = true, NODES = true, + SECTORS = true, REJECT = true, BLOCKMAP = true, BEHAVIOR = true, SCRIPTS = true, LEAFS = true, LIGHTS = true, + MACROS = true, GL_VERT = true, GL_SEGS = true, GL_SSECT = true, GL_NODES = true, GL_PVS = true, +} +-- namespace markers: first letter(s) before _START / _END +local NAMESPACES: { [string]: string } = { S = "sprites", SS = "sprites", P = "patches", PP = "patches", P1 = "patches", P2 = "patches", + P3 = "patches", F = "flats", FF = "flats", F1 = "flats", F2 = "flats", F3 = "flats", C = "colormaps", + TX = "textures", HI = "hires", A = "acs", V = "voices" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Wad.sniff(r: Bytes.Reader): number + if r:remaining() < 12 then + return 0 + end + local m = r:peek(4) + if m ~= "IWAD" and m ~= "PWAD" then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Wad.encode(archive, opts) +end + +local function nameAt(b: buffer, at: number): string + local s = buffer.readstring(b, at, 8) + local z = string.find(s, "\0", 1, true) + return string.upper(if z then string.sub(s, 1, z - 1) else s) +end + +function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local kind = r:string(4) + local count, dirOfs = r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if kind ~= "IWAD" and kind ~= "PWAD" then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local size = r.limit - r.base + if count < 0 or dirOfs < 0 then + return nil, Err.new(Err.CORRUPT, "negative directory field", 4) + end + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many lumps: " .. count) + end + if dirOfs + count * 16 > size then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 8) + end + local a = Archive.new("wad", encode) + local lumps: { Lump } = {} + local seen: { [string]: number } = {} + local b = r.buf + local ns: string? = nil + local map: string? = nil + local udmf = false + for i = 0, count - 1 do + local o = r.base + dirOfs + i * 16 + local at, n = buffer.readi32(b, o), buffer.readi32(b, o + 4) + local name = nameAt(b, o + 8) + if n < 0 or at < 0 or (n > 0 and at + n > size) then + return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dirOfs + i * 16) + end + -- map membership: a lump followed by THINGS (binary) or TEXTMAP (UDMF) starts a map + local nextName = if i + 1 < count then nameAt(b, o + 24) else "" + local inMap: string? = nil + if map then + if udmf then + inMap = map + if name == "ENDMAP" then + map = nil + end + elseif MAP_LUMPS[name] then + inMap = map + else + map = nil + end + end + local isMapMarker = not inMap and (nextName == "THINGS" or nextName == "TEXTMAP") + if isMapMarker then + map, udmf = name, nextName == "TEXTMAP" + end + -- namespaces + local marker: boolean = false + local pre = string.match(name, "^(%w+)_START$") + local post = string.match(name, "^(%w+)_END$") + if pre and NAMESPACES[pre] then + ns = NAMESPACES[pre] + marker = true + elseif post and NAMESPACES[post] then + ns = if #post > 1 and NAMESPACES[string.sub(post, 1, 1)] == ns and (string.match(post, "%d$")) then ns else nil + marker = true + end + local entry = if inMap then inMap .. "/" .. name else name + local k = seen[entry] + if k then + k += 1 + seen[entry] = k + entry = entry .. "~" .. k + else + seen[entry] = 1 + end + local lump: Lump = { name = name, entry = entry, index = i + 1, offset = at, size = n, namespace = if marker then nil else ns, map = inMap, marker = (n == 0 and (marker or isMapMarker)) or nil } + table.insert(lumps, lump) + Archive.put(a, { name = entry, size = n, dir = false, method = "store", lump = name, namespace = lump.namespace, map = inMap, load = Archive.slice(b, r.base + at, n) }) + end + a.meta.source = { format = "wad", type = kind, lumps = count } + a.meta.wad = { lumps = lumps, buf = b, base = r.base } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Wad.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local kind = opts and opts.type or (if type(src) == "table" and src.format == "wad" then src.type else nil) or "PWAD" + if kind ~= "IWAD" and kind ~= "PWAD" then + return nil, Err.new(Err.ARG, "type must be IWAD or PWAD") + end + local list: { { name: string, data: buffer } } = {} + for _, it in items do + if not it.entry.dir then + local base = string.match(it.entry.name, "([^/\\]*)$") or it.entry.name + base = string.upper((string.gsub(base, "~%d+$", ""))) + if #base > 8 or #base == 0 then + return nil, Err.new(Err.ARG, "lump name must be 1..8 bytes: " .. it.entry.name) + end + table.insert(list, { name = base, data = it.data }) + end + end + local w = Bytes.writer() + w:string(kind) + w:u32le(#list) + w:u32le(0) + local offs: { number } = {} + for i, l in list do + offs[i] = w:tell() + w:bytes(l.data) + end + local dirOfs = w:tell() + for i, l in list do + w:u32le(offs[i]) + w:u32le(buffer.len(l.data)) + w:string(l.name) + w:fill(0, 8 - #l.name) + end + w:setU32le(8, dirOfs) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function info(a: any): any + return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil +end + +-- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given +local function find(w: any, name: string, ns: string?): Lump? + local up = string.upper(name) + local best: Lump? = nil + for _, l in w.lumps do + if l.name == up and not l.map then + if ns == nil or l.namespace == ns then + best = l + elseif not best then + best = l + end + end + end + if best and ns and best.namespace ~= ns then + for _, l in w.lumps do + if l.name == up and l.namespace == ns then + best = l + end + end + end + return best +end + +-- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write() +function Wad.new(kind: ("IWAD" | "PWAD")?): any + local a = Archive.new("wad", encode) + a.meta.source = { format = "wad", type = kind or "PWAD" } + return a +end + +-- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD) +function Wad.lumps(a: any): { Lump }? + local w = info(a) + return w and w.lumps +end + +-- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err +function Wad.palette(a: any, index: number?): (buffer?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local l = find(w, "PLAYPAL") + local i = index or 0 + if not l or l.size < (i + 1) * 768 then + return nil, Err.new(Err.UNSUPPORTED, "no PLAYPAL palette " .. i) + end + return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil +end + +-- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic) +-- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding. +function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local kind = opts and opts.kind + local l = find(w, name, if kind == "flat" then "flats" else nil) + if not l then + return nil, Err.new(Err.ARG, "no lump named " .. tostring(name)) + end + local pal, perr = Wad.palette(a, opts and opts.palette) + if not pal then + return nil, perr + end + local at = w.base + l.offset + local pw, ph, left, top = Picture.header(w.buf, at, l.size) + local asFlat = kind == "flat" or (kind ~= "picture" and (l.namespace == "flats" or not pw)) + if asFlat then + local fw, fh = Picture.flatSize(l.size) + if not fw then + return nil, Err.new(Err.UNSUPPORTED, "lump " .. l.name .. " is neither a picture nor a flat") + end + local img = Types.Image.new(fw, fh) + Picture.flat(w.buf, at, fw, fh, pal, img.pixels) + img.meta.source = { format = "wad", kind = "flat", lump = l.name } + return img, nil + end + if not pw then + return nil, Err.new(Err.CORRUPT, "lump " .. l.name .. " is not a valid picture") + end + local img = Types.Image.new(pw, ph) + local ok, msg = Picture.decode(w.buf, at, l.size, pal, img.pixels, pw, ph) + if not ok then + return nil, Err.from(msg, l.offset) + end + img.meta.offset = { left, top } + img.meta.source = { format = "wad", kind = "picture", lump = l.name, left = left, top = top } + return img, nil +end + +-- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } } +local function textureDefs(w: any): { [string]: any } + if w.textures then + return w.textures + end + local defs: { [string]: any } = {} + w.textures = defs + local pn = find(w, "PNAMES") + local names: { string } = {} + if pn and pn.size >= 4 then + local at = w.base + pn.offset + local n = math.min(buffer.readi32(w.buf, at), (pn.size - 4) // 8) + for i = 0, n - 1 do + names[i + 1] = nameAt(w.buf, at + 4 + i * 8) + end + end + for _, tl in { "TEXTURE1", "TEXTURE2" } do + local l = find(w, tl) + if l and l.size >= 4 then + local r = Bytes.reader(w.buf, w.base + l.offset, l.size) + local n = r:i32le() + if n > 0 and n * 4 <= l.size - 4 then + for i = 0, n - 1 do + r:seek(4 + i * 4) + local o = r:i32le() + if o > 0 and o + 22 <= l.size then + r:seek(o) + local tname = string.upper(r:fixed(8)) + r:skip(4) + local tw, th = r:i16le(), r:i16le() + r:skip(4) + local pc = r:i16le() + local patches = {} + for _ = 1, math.max(0, pc) do + local px, py, pi = r:i16le(), r:i16le(), r:i16le() + r:skip(4) + if names[pi + 1] then + table.insert(patches, { x = px, y = py, patch = names[pi + 1] }) + end + end + if not r.err and tw > 0 and th > 0 and defs[tname] == nil then + defs[tname] = { width = tw, height = th, patches = patches } + end + r.err = nil + end + end + end + end + end + return defs +end + +-- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette) +function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local def = textureDefs(w)[string.upper(name)] + if not def then + return nil, Err.new(Err.ARG, "no texture named " .. tostring(name)) + end + if def.width * def.height > 4096 * 4096 then + return nil, Err.new(Err.LIMIT, "texture too big") + end + local img = Types.Image.new(def.width, def.height) + for _, p in def.patches do + local pimg = Wad.image(a, p.patch, { palette = opts and opts.palette, kind = "picture" }) + if pimg then + Picture.blit(pimg.pixels, pimg.width, pimg.height, img.pixels, def.width, def.height, p.x, p.y) + end + end + img.meta.source = { format = "wad", kind = "texture", texture = string.upper(name), patches = #def.patches } + return img, nil +end + +-- maps(a) -> { map names } in file order +function Wad.maps(a: any): { string } + local w = info(a) + local out: { string } = {} + if w then + local seen: { [string]: boolean } = {} + for _, l in w.lumps do + if l.map and not seen[l.map] then + seen[l.map] = true + table.insert(out, l.map) + end + end + end + return out +end + +-- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references) +function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local up = string.upper(name) + local lumps: { [string]: Map.Lump } = {} + for _, l in w.lumps do + if l.map == up and lumps[l.name] == nil then + lumps[l.name] = { buf = w.buf, at = w.base + l.offset, size = l.size } + end + end + if not next(lumps) then + return nil, Err.new(Err.ARG, "no map named " .. tostring(name)) + end + if lumps.TEXTMAP then + return nil, Err.new(Err.UNSUPPORTED, "UDMF (TEXTMAP) maps") + end + local m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil) + if not m then + return nil, Err.from(msg) + end + return m, nil +end + +-- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and +-- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes +-- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData +function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?) + local m, err = Wad.mapData(a, name) + if not m then + return nil, err + end + local w = info(a) + local defs = textureDefs(w) + local images = not (opts and opts.textures == false) + local cache: { [string]: any } = {} + local pal = opts and opts.palette + local function image(kind: string, tname: string): Types.Image? + local key = kind .. ":" .. tname + local c = cache[key] + if c == nil then + local img = if kind == "flat" then Wad.image(a, tname, { kind = "flat", palette = pal }) else Wad.texture(a, tname, { palette = pal }) + c = img or false + cache[key] = c + end + return if c then c else nil + end + local tex: Map.Textures = { + size = function(kind: string, tname: string): (number?, number?) + if kind == "texture" then + local d = defs[tname] + if d then + return d.width, d.height + end + return nil, nil + end + local l = find(w, tname, "flats") + if l then + local fw, fh = Picture.flatSize(l.size) + return fw, fh + end + return nil, nil + end, + image = if images then image else nil, + } + local scene = Map.scene(m, tex, string.upper(name)) + scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 } + return scene, nil +end + +return Wad diff --git a/src/Formats/codecs/compress/Explode.luau b/src/Formats/codecs/compress/Explode.luau new file mode 100644 index 0000000..bd3c870 --- /dev/null +++ b/src/Formats/codecs/compress/Explode.luau @@ -0,0 +1,204 @@ +--!strict +--!native +--!optimize 2 +-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ +-- archive sectors, old installers, some game data files). A codec (layer 3). Written after the format as documented +-- by Mark Adler's blast.c (zlib licence, licenses/blast-LICENSE.txt): the same constant code tables (run-length +-- coded Huffman code lengths, length bases / extra bits), the bit order (LSB first, Huffman codes inverted); the +-- decoder itself is new code. +-- Supports: literal coding off (raw bytes) and on (Huffman coded), 1 / 2 / 4 KB dictionaries, the end code; stops +-- early at maxOut bytes (MPQ sectors whose stream has no end code). +-- +-- local out, err = Explode.decompress(buf, offset?, length?, maxOut?) -- buffer | nil, Err +-- +-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / ARG / LIMIT). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Explode = {} + +local MAXBITS = 13 + +-- blast.c's tables: each byte is (count - 1) << 4 | code length +local LITLEN = { 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, + 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, 8, 12, 5, + 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, + 61, 12, 45, 44, 173 } +local LENLEN = { 2, 35, 36, 53, 38, 23 } +local DISTLEN = { 2, 20, 53, 230, 247, 151, 248 } +local BASE = { 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264 } +local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 } + +type Code = { count: { number }, symbol: { number } } + +-- canonical code from run-length coded lengths +local function construct(rep: { number }): Code + local lengths: { number } = {} + for _, b in rep do + local len = b % 16 + for _ = 0, b // 16 do + table.insert(lengths, len) + end + end + local count = table.create(MAXBITS + 1, 0) + for _, l in lengths do + count[l + 1] += 1 + end + local offs = table.create(MAXBITS + 2, 0) + for l = 1, MAXBITS do + offs[l + 2] = offs[l + 1] + count[l + 1] + end + local symbol = table.create(#lengths, 0) + for s, l in lengths do + if l ~= 0 then + offs[l + 1] += 1 + symbol[offs[l + 1]] = s - 1 + end + end + return { count = count, symbol = symbol } +end + +local LIT = construct(LITLEN) +local LEN = construct(LENLEN) +local DIST = construct(DISTLEN) + +-- decompress(buf, offset?, length?, maxOut?) -> buffer | nil, Err +function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?) + local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length) + if not b then + return nil, aerr + end + local src: buffer = b + local p, stop = o, o + l + if l < 2 then + return nil, Err.new(Err.TRUNCATED, "implode header", 0) + end + local lit, dict = readu8(src, p), readu8(src, p + 1) + p += 2 + if lit > 1 then + return nil, Err.new(Err.CORRUPT, "bad literal mode " .. lit, 0) + end + if dict < 4 or dict > 6 then + return nil, Err.new(Err.CORRUPT, "bad dictionary size " .. dict, 1) + end + local limit = maxOut or 2 ^ 30 + local cap = math.max(64, math.min(limit, l * 8)) + local out = buffer.create(cap) + local n = 0 + local bitbuf, bitcnt = 0, 0 + local truncated = false + + local function bits(need: number): number + while bitcnt < need do + if p >= stop then + truncated = true + return 0 + end + bitbuf += readu8(src, p) * 2 ^ bitcnt + p += 1 + bitcnt += 8 + end + local v = bitbuf % 2 ^ need + bitbuf = (bitbuf - v) / 2 ^ need + bitcnt -= need + return v + end + + local function decode(h: Code): number + local code, first, index = 0, 0, 0 + local count, symbol = h.count, h.symbol + for len = 1, MAXBITS do + local bit = bits(1) + if truncated then + return -1 + end + code += 1 - bit + local c = count[len + 1] + if code < first + c then + return symbol[index + code - first + 1] + end + index += c + first = (first + c) * 2 + code *= 2 + end + return -2 + end + + while n < limit do + local flag = bits(1) + if truncated then + break + end + if flag == 1 then + local sym = decode(LEN) + if sym < 0 then + if truncated then + break + end + return nil, Err.new(Err.CORRUPT, "bad length code", p - o) + end + local len = BASE[sym + 1] + bits(EXTRA[sym + 1]) + if truncated then + break + end + if len == 519 then + break + end + local shift = if len == 2 then 2 else dict + local d = decode(DIST) + if d < 0 then + if truncated then + break + end + return nil, Err.new(Err.CORRUPT, "bad distance code", p - o) + end + local dist = d * 2 ^ shift + bits(shift) + 1 + if truncated then + break + end + if dist > n then + return nil, Err.new(Err.CORRUPT, "distance too far back", p - o) + end + if n + len > limit then + len = limit - n + end + if n + len > cap then + cap = math.max(cap * 2, n + len) + local grown = buffer.create(cap) + buffer.copy(grown, 0, out, 0, n) + out = grown + end + local from = n - dist + for k = 0, len - 1 do + writeu8(out, n + k, readu8(out, from + k)) + end + n += len + else + local sym = if lit == 1 then decode(LIT) else bits(8) + if truncated then + break + end + if sym < 0 then + return nil, Err.new(Err.CORRUPT, "bad literal code", p - o) + end + if n >= cap then + cap *= 2 + local grown = buffer.create(cap) + buffer.copy(grown, 0, out, 0, n) + out = grown + end + writeu8(out, n, sym) + n += 1 + end + end + if truncated and n < limit and not maxOut then + return nil, Err.new(Err.TRUNCATED, "no end code", l) + end + local res = buffer.create(n) + buffer.copy(res, 0, out, 0, n) + return res, nil +end + +return Explode diff --git a/src/Formats/codecs/image/Jpeg/Color.luau b/src/Formats/codecs/image/Jpeg/Color.luau index 86e7d13..06fddb1 100644 --- a/src/Formats/codecs/image/Jpeg/Color.luau +++ b/src/Formats/codecs/image/Jpeg/Color.luau @@ -31,6 +31,7 @@ Color.RGB = 2 Color.CMYK = 3 Color.YCCK = 4 Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted +Color.RAW = 6 -- no conversion: components 1..4 as R, G, B, A (opts.raw: BLP1's BGRA JPEGs, ...) export type Comp = { plane: buffer, -- u16 samples, stride per row @@ -177,6 +178,19 @@ function Color.run(P: Params) if nc >= 4 then s3, b3 = fetch(comps[4], y, outW) end + if space == 6 then + for x = 0, outW - 1 do + local i = x * 2 + local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) + local c3 = if nc >= 4 then readu16(s3, b3 + i) else maxv + if toByte then + c0, c1, c2, c3 = readu8(toByte, c0), readu8(toByte, c1), readu8(toByte, c2), readu8(toByte, c3) + end + writeu32(out, o, c0 + c1 * 256 + c2 * 65536 + c3 * 16777216) + o += 4 + end + continue + end if space == 1 and not toByte then -- the common case: 8-bit YCbCr for x = 0, outW - 1 do diff --git a/src/Formats/codecs/image/Jpeg/Decode.luau b/src/Formats/codecs/image/Jpeg/Decode.luau index efb1a64..57e19e0 100644 --- a/src/Formats/codecs/image/Jpeg/Decode.luau +++ b/src/Formats/codecs/image/Jpeg/Decode.luau @@ -228,6 +228,7 @@ export type State = { icc: buffer?, comments: { string }, truncated: boolean, + raw: boolean, -- opts.raw: no colour conversion scale: number, avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back) endPos: number, -- the byte after the EOI marker (or the end of the data) @@ -259,6 +260,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: icc = nil, comments = {}, truncated = false, + raw = opts ~= nil and opts.raw == true, scale = scale, avi1 = nil, endPos = n, @@ -644,6 +646,9 @@ function Decode.output(st: State): (number?, any, any, string?) if space == "cmyk" and st.adobe == nil then spaceId = Color.CMYK_PLAIN end + if st.raw then + spaceId = Color.RAW + end local t = yccTables(maxv) local tb = nil if maxv == 4095 then diff --git a/src/Formats/codecs/image/Jpeg/init.luau b/src/Formats/codecs/image/Jpeg/init.luau index 32710ae..ec0c5b6 100644 --- a/src/Formats/codecs/image/Jpeg/init.luau +++ b/src/Formats/codecs/image/Jpeg/init.luau @@ -43,6 +43,7 @@ export type DecodeOptions = { native: boolean?, -- grey files decode to gray8 (default false: rgba8) yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so) + raw: boolean?, -- no colour conversion: 3 / 4 components as R, G, B (, A) bytes (default false; BLP1 BGRA JPEGs) maxPixels: number?, -- refuse larger images (default 2^26) } export type EncodeOptions = { diff --git a/src/Formats/codecs/model/Polygon.luau b/src/Formats/codecs/model/Polygon.luau new file mode 100644 index 0000000..56ac89d --- /dev/null +++ b/src/Formats/codecs/model/Polygon.luau @@ -0,0 +1,248 @@ +--!strict +-- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map +-- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the +-- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the +-- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so +-- every input terminates). New in formats-luau, after the classic "ear clipping with hole bridging" method +-- (D. Eberly, Triangulation by Ear Clipping); no code taken. +-- +-- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } }) +-- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair +-- -- (1-based), counter-clockwise +-- +-- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored. +local Polygon = {} + +type Pt = { x: number, y: number, loop: number, index: number } + +local function area(pts: { Pt }): number + local a = 0 + local n = #pts + for i = 1, n do + local p, q = pts[i], pts[i % n + 1] + a += p.x * q.y - q.x * p.y + end + return a / 2 +end + +local function inside(pts: { Pt }, x: number, y: number): boolean + local c = false + local n = #pts + local j = n + for i = 1, n do + local a, b = pts[i], pts[j] + if (a.y > y) ~= (b.y > y) and x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x then + c = not c + end + j = i + end + return c +end + +local function cross(o: Pt, a: Pt, b: Pt): number + return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) +end + +-- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count) +local function crosses(p1: Pt, p2: Pt, q1: Pt, q2: Pt): boolean + if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then + return false + end + local d1, d2 = cross(q1, q2, p1), cross(q1, q2, p2) + local d3, d4 = cross(p1, p2, q1), cross(p1, p2, q2) + return ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)) +end + +local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean + for _, r in rings do + local n = #r + for i = 1, n do + if crosses(m, v, r[i], r[i % n + 1]) then + return false + end + end + end + return true +end + +-- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible +-- vertices; others = every ring the bridge must not cross +local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt } + local mi = 1 + for i, p in h do + if p.x > h[mi].x then + mi = i + end + end + local m = h[mi] + local best, bestD = 0, math.huge + for pass = 1, 2 do + for i, v in outer do + if pass == 2 or v.x >= m.x then + local d = (v.x - m.x) ^ 2 + (v.y - m.y) ^ 2 + if d < bestD and visible(m, v, others) then + best, bestD = i, d + end + end + end + if best > 0 then + break + end + end + if best == 0 then + best = 1 + end + local out: { Pt } = {} + for i = 1, best do + table.insert(out, outer[i]) + end + local n = #h + for k = 0, n do + table.insert(out, h[(mi - 1 + k) % n + 1]) + end + for i = best, #outer do + table.insert(out, outer[i]) + end + return out +end + +local function inTri(a: Pt, b: Pt, c: Pt, p: Pt): boolean + return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0 +end + +-- ear clipping of one counter-clockwise ring +local function clip(ring: { Pt }, out: { number }) + local pts = table.clone(ring) + local guard = #pts * #pts + 16 + while #pts > 3 and guard > 0 do + guard -= 1 + local n = #pts + local found, bestI, bestScore = 0, 1, -math.huge + for i = 1, n do + local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1] + local cr = cross(a, b, c) + if cr > 0 then + local ok = true + for k = 1, n do + local p = pts[k] + if p ~= a and p ~= b and p ~= c and not (p.x == b.x and p.y == b.y) and not (p.x == a.x and p.y == a.y) and not (p.x == c.x and p.y == c.y) and inTri(a, b, c, p) then + ok = false + break + end + end + if ok then + found = i + break + end + end + if cr > bestScore then + bestI, bestScore = i, cr + end + end + local i = if found > 0 then found else bestI + local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1] + if cross(a, b, c) ~= 0 then + table.insert(out, a.loop) + table.insert(out, a.index) + table.insert(out, b.loop) + table.insert(out, b.index) + table.insert(out, c.loop) + table.insert(out, c.index) + end + table.remove(pts, i) + end + if #pts == 3 and cross(pts[1], pts[2], pts[3]) > 0 then + for k = 1, 3 do + table.insert(out, pts[k].loop) + table.insert(out, pts[k].index) + end + end +end + +-- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly) +function Polygon.triangulate(loops: { { number } }): { number } + local rings: { { Pt } } = {} + local areas: { number } = {} + for li, l in loops do + local pts: { Pt } = {} + for k = 1, #l - 1, 2 do + local x, y = l[k], l[k + 1] + if type(x) == "number" and type(y) == "number" and x == x and y == y then + table.insert(pts, { x = x, y = y, loop = li, index = (k + 1) // 2 }) + end + end + local a = if #pts >= 3 then area(pts) else 0 + if a ~= 0 then + table.insert(rings, pts) + table.insert(areas, math.abs(a)) + if a < 0 then -- counter-clockwise for now; holes are flipped below + local r: { Pt } = {} + for k = #pts, 1, -1 do + table.insert(r, pts[k]) + end + rings[#rings] = r + end + end + end + -- nesting: the parent of a ring is the smallest ring containing its first point + local n = #rings + local depth, parent = table.create(n, 0), table.create(n, 0) + for i = 1, n do + local p = rings[i][1] + for j = 1, n do + if j ~= i and areas[j] > areas[i] and inside(rings[j], p.x, p.y) then + depth[i] += 1 + if parent[i] == 0 or areas[j] < areas[parent[i]] then + parent[i] = j + end + end + end + end + local holes: { [number]: { number } } = {} + for i = 1, n do + if depth[i] % 2 == 1 and parent[i] > 0 then + local list = holes[parent[i]] or {} + holes[parent[i]] = list + table.insert(list, i) + end + end + local out: { number } = {} + for i = 1, n do + if depth[i] % 2 == 0 then + local ring = rings[i] + local hs = holes[i] + if hs then + table.sort(hs, function(a: number, b: number): boolean + local ma, mb = -math.huge, -math.huge + for _, p in rings[a] do + ma = math.max(ma, p.x) + end + for _, p in rings[b] do + mb = math.max(mb, p.x) + end + return ma > mb + end) + local flipped: { { Pt } } = {} + for _, h in hs do + local r: { Pt } = {} + local src = rings[h] + for k = #src, 1, -1 do + table.insert(r, src[k]) + end + table.insert(flipped, r) + end + for k, h in flipped do + local others: { { Pt } } = { ring } + for k2 = k + 1, #flipped do + table.insert(others, flipped[k2]) + end + ring = bridge(ring, h, others) + end + end + clip(ring, out) + end + end + return out +end + +return Polygon diff --git a/src/Formats/codecs/model/Rig.luau b/src/Formats/codecs/model/Rig.luau index 53bf256..ce01dd8 100644 --- a/src/Formats/codecs/model/Rig.luau +++ b/src/Formats/codecs/model/Rig.luau @@ -101,16 +101,58 @@ function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, r end end +-- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a +-- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored +-- normals cannot be used (Quake's precomputed normal table is not redistributable here). +function Rig.normals(pos: buffer, count: number, indices: { number }): buffer + local out = buffer.create(count * 12) + local acc = table.create(count * 3, 0) + for k = 1, #indices - 2, 3 do + local a, b, c = indices[k], indices[k + 1], indices[k + 2] + if a >= 0 and b >= 0 and c >= 0 and a < count and b < count and c < count then + local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) + local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az + local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + end + for v = 0, count - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, v * 12, x) + writef32(out, v * 12 + 4, y) + writef32(out, v * 12 + 8, z) + end + return out +end + -- ------------------------------------------------------------------------------------------------ skeletons local function trs(j: Joint): { number } return Mat4.compose(j.translation, j.rotation, j.scale) end --- skeleton(scene, joints, space, root?) -> (joint node indices, skin index): one node per joint (TRS relative to its +-- angles(x, y, z) -> quaternion { x, y, z, w } of the Euler angles in radians applied x first, then y, then z +-- (R = Rz * Ry * Rx: the Quake / Half-Life "AngleQuaternion" convention of MDL bones and SMD skeletons) +function Rig.angles(x: number, y: number, z: number): { number } + local sy, cy = math.sin(z / 2), math.cos(z / 2) + local sp, cp = math.sin(y / 2), math.cos(y / 2) + local sr, cr = math.sin(x / 2), math.cos(x / 2) + return { sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy } +end + +-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index, world matrices): one node per joint (TRS relative to its -- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse -- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's -- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root. -function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number) +function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number, { { number } }) local n = #joints local world: { { number } } = {} local nodes: { number } = {} @@ -152,19 +194,28 @@ function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "w local acc = Scene.accessor(ibm, "f32", 16, n) acc.matrix = true table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = if n > 0 then nodes[1] else nil }) - return nodes, #scene.skins + return nodes, #scene.skins, world end -- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with --- 0-based joint indices (into the skin's joints); the four largest weights are kept and normalised to sum 1. +-- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept +-- and normalised to sum 1. function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) local n = #lists local jb, wb = buffer.create(n * 8), buffer.create(n * 16) for v, l in lists do local pairs_: { { number } } = {} + local at: { [number]: { number } } = {} for k = 1, #l - 1, 2 do if l[k + 1] > 0 then - table.insert(pairs_, { l[k], l[k + 1] }) + local same = at[l[k]] + if same then + same[2] += l[k + 1] -- the same joint twice: one influence + else + local e = { l[k], l[k + 1] } + at[l[k]] = e + table.insert(pairs_, e) + end end end table.sort(pairs_, function(a: { number }, b: { number }): boolean diff --git a/src/Formats/core/Input.luau b/src/Formats/core/Input.luau index df745fa..c62df2f 100644 --- a/src/Formats/core/Input.luau +++ b/src/Formats/core/Input.luau @@ -59,4 +59,24 @@ function Input.extension(name: string?): string? return if ext then string.lower(ext) else nil end +-- sibling(opts, uri) -> buffer | nil: a file the data being decoded refers to (a palette, an animation, an archive +-- part, ...): opts.files[uri] (a buffer or a string), else opts.resolve(uri) (errors in it count as not found) +function Input.sibling(opts: any?, uri: string): buffer? + if type(opts) ~= "table" then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, got = pcall(opts.resolve, uri) + v = if ok then got else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil +end + return Input diff --git a/src/Formats/image/blp/init.luau b/src/Formats/image/blp/init.luau new file mode 100644 index 0000000..1a15d1b --- /dev/null +++ b/src/Formats/image/blp/init.luau @@ -0,0 +1,266 @@ +--!strict +-- image/blp: Blizzard BLP textures (Warcraft III: BLP1; World of Warcraft: BLP2), read, and BLP2 written +-- (uncompressed BGRA). Written from the wowdev.wiki BLP page; no code taken. +-- Decode, mip 0 (meta.source.mips counts the levels) to rgba8: +-- BLP1 JPEG: the shared JPEG header + the mip's data through codecs/image/Jpeg; 4-component files (the usual +-- Warcraft III layout) are BGRA without colour conversion, 3-component ones YCbCr -> BGR (R and B swapped back); +-- BLP1 palette: 8-bit indexes into a BGRA palette, then an 8-bit alpha plane when alphaBits is 8 (else opaque); +-- BLP2 palette: indexes + a 1 / 4 / 8-bit alpha plane (LSB first), DXT1 / DXT3 / DXT5 (codecs/image/Bcn: alpha +-- type 0 / 1 / 7), uncompressed BGRA. +-- Encode: BLP2 uncompressed BGRA with 8-bit alpha (opts.mips = true adds the box-filtered mip chain). +-- Not supported: BLP0 (external .b00 mip files), BLP2 JPEG (never used by the games). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Jpeg = require("@formats/codecs/image/Jpeg") +local Bcn = require("@formats/codecs/image/Bcn") + +-- ------------------------------------------------------------------------------------------------ contract +local Blp = { + name = "blp", + category = "image", + extensions = { "blp" }, + mime = { "image/x-blp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" }, + caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { maxPixels: number? } -- default 2^26 +export type EncodeOptions = { mips: boolean? } -- write the mip chain (default false) + +-- ------------------------------------------------------------------------------------------------ constants +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Blp.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m == "BLP1" or m == "BLP2" then 1 elseif m == "BLP0" then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- BGRA u32 (b at the lowest address) -> RGBA u32 with the given alpha +local function swap(v: number, a: number): number + local b, g, r = v % 256, (v // 256) % 256, (v // 65536) % 256 + return r + g * 256 + b * 65536 + a * 16777216 +end + +-- alpha of pixel i from a packed plane at p of depth bits +local function alphaAt(b: buffer, p: number, depth: number, i: number): number + if depth == 8 then + return readu8(b, p + i) + elseif depth == 4 then + local v = readu8(b, p + i // 2) + local n = if i % 2 == 0 then v % 16 else v // 16 + return n * 17 + elseif depth == 1 then + local v = readu8(b, p + i // 8) + return if bit32.band(v, bit32.lshift(1, i % 8)) ~= 0 then 255 else 0 + end + return 255 +end + +function Blp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local size = r.limit - r.base + local b, base = r.buf, r.base + local magic = r:peek(4) + if magic == "BLP0" then + return nil, Err.new(Err.UNSUPPORTED, "BLP0 (mips in external files)", 0) + end + if magic ~= "BLP1" and magic ~= "BLP2" then + return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0) + end + local v2 = magic == "BLP2" + local headerSize = if v2 then 20 + 128 + 1024 else 28 + 128 + if size < headerSize then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local kind = readu32(b, base + 4) -- BLP1: 0 = JPEG, 1 = palette; BLP2: 1 (0 = JPEG) + local compression = if v2 then readu8(b, base + 8) elseif kind == 0 then 0 else 1 + local alphaDepth = if v2 then readu8(b, base + 9) else readu32(b, base + 8) + local alphaType = if v2 then readu8(b, base + 10) else 0 + local w, h = readu32(b, base + 12), readu32(b, base + 16) + local mipsAt = if v2 then 20 else 28 + if w == 0 or h == 0 or w > 65535 or h > 65535 then + return nil, Err.new(Err.CORRUPT, "bad size " .. w .. " x " .. h, 12) + end + if w * h > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + local offs: { number }, lens: { number } = {}, {} + local mips = 0 + for i = 0, 15 do + offs[i + 1] = readu32(b, base + mipsAt + i * 4) + lens[i + 1] = readu32(b, base + mipsAt + 64 + i * 4) + if offs[i + 1] ~= 0 and lens[i + 1] ~= 0 then + mips += 1 + end + end + local at, len = offs[1], lens[1] + if at + len > size or len == 0 then + return nil, Err.new(Err.TRUNCATED, "mip 0 past the end", mipsAt) + end + local img = Types.Image.new(w, h) + local px = img.pixels + local n = w * h + local src = base + at + local name: string + if (not v2 and kind == 0) or (v2 and kind == 0) then + if v2 then + return nil, Err.new(Err.UNSUPPORTED, "BLP2 JPEG") + end + -- the JPEG header shared by the mips, then the mip's own data + if size < headerSize + 4 then + return nil, Err.new(Err.TRUNCATED, "JPEG header size", headerSize) + end + local hs = readu32(b, base + headerSize) + if hs > 0x10000 or headerSize + 4 + hs > size then + return nil, Err.new(Err.CORRUPT, "bad JPEG header size", headerSize) + end + local jpg = buffer.create(hs + len) + buffer.copy(jpg, 0, b, base + headerSize + 4, hs) + buffer.copy(jpg, hs, b, src, len) + local info = Jpeg.info(jpg) + local four = info ~= nil and (info :: any).components == 4 + local dec, err = Jpeg.decode(jpg, 0, nil, { raw = four, maxPixels = opts and opts.maxPixels }) + if not dec then + return nil, err + end + local dw, dh = math.min(dec.width, w), math.min(dec.height, h) + for y = 0, dh - 1 do + for x = 0, dw - 1 do + local v = readu32(dec.pixels, (y * dec.width + x) * 4) + local a = if four and alphaDepth > 0 then v // 16777216 else 255 + writeu32(px, (y * w + x) * 4, swap(v, a)) + end + end + name = "jpeg" + elseif compression == 1 then + local palAt = base + (if v2 then 148 else headerSize) + local dataAt = src + if not v2 then + -- BLP1: the palette follows the header; the mip offsets point past it + if headerSize + 1024 > size then + return nil, Err.new(Err.TRUNCATED, "palette", headerSize) + end + end + local depth = if v2 then alphaDepth else (if alphaDepth >= 8 then 8 else 0) + local need = n + (if depth == 8 then n elseif depth == 4 then (n + 1) // 2 elseif depth == 1 then (n + 7) // 8 else 0) + if at + need > size then + return nil, Err.new(Err.TRUNCATED, "palette mip past the end", at) + end + for i = 0, n - 1 do + local e = readu32(b, palAt + readu8(b, dataAt + i) * 4) + writeu32(px, i * 4, swap(e, if depth > 0 then alphaAt(b, dataAt + n, depth, i) else 255)) + end + name = "palette" + elseif compression == 2 then + local kindName = if alphaType == 7 then "bc3" elseif alphaType == 1 then "bc2" else "bc1" + local want: number = Bcn.size(kindName, w, h) or 0 + if len < want then + return nil, Err.new(Err.TRUNCATED, "DXT mip shorter than " .. want .. " bytes", mipsAt + 64) + end + local dec, err = Bcn.decode(kindName, b, src, w, h) + if not dec then + return nil, Err.from(err) + end + buffer.copy(px, 0, dec, 0, n * 4) + if kindName == "bc1" and alphaDepth == 0 then + for i = 0, n - 1 do + writeu8(px, i * 4 + 3, 255) + end + end + name = ({ bc1 = "dxt1", bc2 = "dxt3", bc3 = "dxt5" } :: { [string]: string })[kindName] + elseif compression == 3 then + if len < n * 4 then + return nil, Err.new(Err.TRUNCATED, "BGRA mip too short", mipsAt + 64) + end + for i = 0, n - 1 do + local v = readu32(b, src + i * 4) + writeu32(px, i * 4, swap(v, v // 16777216)) + end + name = "bgra" + else + return nil, Err.new(Err.UNSUPPORTED, "compression " .. tostring(compression)) + end + img.meta.source = { format = "blp", version = if v2 then 2 else 1, compression = name, alphaDepth = alphaDepth, alphaType = alphaType, mips = mips } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- halve(px, w, h) -> the next mip (2 x 2 box filter; odd edges repeat) +local function halve(px: buffer, w: number, h: number): (buffer, number, number) + local nw, nh = math.max(1, w // 2), math.max(1, h // 2) + local out = buffer.create(nw * nh * 4) + for y = 0, nh - 1 do + for x = 0, nw - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s += readu8(px, (sy * w + sx) * 4 + c) + end + end + writeu8(out, (y * nw + x) * 4 + c, (s + 2) // 4) + end + end + end + return out, nw, nh +end + +function Blp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "bad size") + end + local levels: { buffer } = { img.pixels } + local sizes: { { number } } = { { w, h } } + if opts and opts.mips then + local p, cw, ch = img.pixels, w, h + while (cw > 1 or ch > 1) and #levels < 16 do + p, cw, ch = halve(p, cw, ch) + table.insert(levels, p) + table.insert(sizes, { cw, ch }) + end + end + local out = Bytes.writer(1172 + w * h * 6) + out:string("BLP2") + out:u32le(1) + out:u8(3) -- uncompressed BGRA + out:u8(8) -- alpha depth + out:u8(8) -- alpha type + out:u8(if #levels > 1 then 1 else 0) + out:u32le(w) + out:u32le(h) + local at = 1172 + for i = 1, 16 do + local l = levels[i] + out:u32le(if l then at else 0) + if l then + at += buffer.len(l) + end + end + for i = 1, 16 do + local l = levels[i] + out:u32le(if l then buffer.len(l) else 0) + end + out:fill(0, 1024) + for _, l in levels do + local p = out:reserve(buffer.len(l)) + local o = out.buf + for i = 0, buffer.len(l) // 4 - 1 do + local v = readu32(l, i * 4) + writeu32(o, p + i * 4, swap(v, v // 16777216)) + end + out.pos = p + buffer.len(l) + end + return out:finish(), nil +end + +return Blp diff --git a/src/Formats/image/tim/init.luau b/src/Formats/image/tim/init.luau new file mode 100644 index 0000000..91af052 --- /dev/null +++ b/src/Formats/image/tim/init.luau @@ -0,0 +1,247 @@ +--!strict +-- image/tim: PlayStation TIM images (magic 0x10), read and write. Written from the PSX "File Formats" documentation +-- (Sony, TIM: pmode, CLUT and image blocks with their VRAM positions); no code taken. +-- Decode: 4-bit and 8-bit CLUT images (opts.clut picks the palette row, default 0), 15-bit direct and 24-bit +-- direct, to rgba8: PSX colours are 1-5-5-5 STP-B-G-R, channels expanded as (v << 3) | (v >> 2); the colour 0x0000 +-- is transparent (alpha 0) as on the hardware, others opaque (the STP bit is kept in meta.source.stp = true when +-- any pixel or CLUT entry has it). meta.source = { format, bpp, clut = { x, y, colours, count }?, x, y (VRAM) }. +-- Encode: rgba8 to 16-bit direct (default), 24-bit (opts.bpp = 24, alpha dropped) or 4 / 8-bit CLUT when the image +-- has at most 16 / 256 PSX colours (opts.bpp = 4 / 8; Err.ARG otherwise); alpha below 128 becomes 0x0000; opaque +-- black is written as 0x8000 (STP set) so it stays opaque. Not supported: mixed mode (pmode 4) images. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Tim = { + name = "tim", + category = "image", + extensions = { "tim" }, + mime = { "image/x-tim" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + clut: number?, -- the CLUT row to use for indexed images (0-based, default 0) + maxPixels: number?, -- default 2^26 +} +export type EncodeOptions = { + bpp: number?, -- 4, 8, 16 (default) or 24 + x: number?, -- VRAM position of the image (default 0, 0) + y: number?, + clutX: number?, -- VRAM position of the CLUT (default 0, 480) + clutY: number?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8, readu16, writeu32, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu32, buffer.writeu16, buffer.readu32 +local BPP = { [0] = 4, [1] = 8, [2] = 16, [3] = 24 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Tim.sniff(r: Bytes.Reader): number + if r:remaining() < 20 or r:peek(4) ~= "\16\0\0\0" then + return 0 + end + local flags = r:peekU8(4) + if flags > 0x0F or (flags % 8) > 3 or r:peek(3, 5) ~= "\0\0\0" then + return 0 + end + return 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function colour(c: number): number + if c == 0 then + return 0 + end + local r, g, b = c % 32, (c // 32) % 32, (c // 1024) % 32 + r, g, b = r * 8 + r // 4, g * 8 + g // 4, b * 8 + b // 4 + return 0xFF000000 + b * 65536 + g * 256 + r +end + +function Tim.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local magic, flags = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if magic ~= 0x10 then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local pmode = flags % 8 + local bpp = BPP[pmode] + if not bpp then + return nil, Err.new(Err.UNSUPPORTED, "pmode " .. pmode .. " (mixed / unknown)", 4) + end + local stp = false + local pal: buffer? = nil + local clutInfo: any = nil + if bit32.band(flags, 8) ~= 0 then + local start = r:tell() + local bnum, cx, cy, cw, ch = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + if r.err then + return nil, r.err + end + if bnum < 12 or cw * ch * 2 > bnum - 12 then + return nil, Err.new(Err.CORRUPT, "bad CLUT block", start) + end + if not r:need(cw * ch * 2) then + return nil, r.err + end + local row = math.clamp(math.floor(opts and opts.clut or 0), 0, math.max(ch - 1, 0)) + pal = buffer.create(256 * 4) + local p = r.pos + row * cw * 2 + for i = 0, math.min(cw, 256) - 1 do + local c = readu16(r.buf, p + i * 2) + if c >= 0x8000 then + stp = true + end + writeu32(pal :: buffer, i * 4, if c == 0x8000 then 0xFF000000 else colour(c % 0x8000)) + end + clutInfo = { x = cx, y = cy, colours = cw, count = ch, row = row } + r:seek(start + bnum) + if r.err then + return nil, r.err + end + elseif bpp <= 8 then + return nil, Err.new(Err.CORRUPT, "indexed image without a CLUT", 4) + end + local start = r:tell() + local bnum, ix, iy, iw, ih = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + if r.err then + return nil, r.err + end + local w = if bpp == 4 then iw * 4 elseif bpp == 8 then iw * 2 elseif bpp == 16 then iw else (iw * 2) // 3 + local stride = iw * 2 + if w * ih > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + if bnum < 12 or stride * ih > bnum - 12 then + return nil, Err.new(Err.CORRUPT, "bad image block", start) + end + if not r:need(stride * ih) then + return nil, r.err + end + local img = Types.Image.new(w, ih) + local px, src, at = img.pixels, r.buf, r.pos + for y = 0, ih - 1 do + local row = at + y * stride + local d = y * w * 4 + if bpp == 4 then + for x = 0, w - 1 do + local v = readu8(src, row + x // 2) + local i = if x % 2 == 0 then v % 16 else v // 16 + writeu32(px, d + x * 4, readu32(pal :: buffer, i * 4)) + end + elseif bpp == 8 then + for x = 0, w - 1 do + writeu32(px, d + x * 4, readu32(pal :: buffer, readu8(src, row + x) * 4)) + end + elseif bpp == 16 then + for x = 0, w - 1 do + local c = readu16(src, row + x * 2) + if c >= 0x8000 then + stp = true + end + writeu32(px, d + x * 4, if c == 0x8000 then 0xFF000000 else colour(c % 0x8000)) + end + else + for x = 0, w - 1 do + local o = row + x * 3 + writeu32(px, d + x * 4, 0xFF000000 + readu8(src, o + 2) * 65536 + readu8(src, o + 1) * 256 + readu8(src, o)) + end + end + end + img.meta.source = { format = "tim", bpp = bpp, x = ix, y = iy, clut = clutInfo, stp = stp or nil } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- rgba8 pixel -> PSX colour +local function psx(v: number): number + local r, g, b, a = v % 256, (v // 256) % 256, (v // 65536) % 256, v // 16777216 + if a < 128 then + return 0 + end + local c = (b // 8) * 1024 + (g // 8) * 32 + r // 8 + return if c == 0 then 0x8000 else c +end + +function Tim.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local w, h = img.width, img.height + local bpp = opts and opts.bpp or 16 + local per = ({ [4] = 4, [8] = 2, [16] = 1, [24] = 2 / 3 } :: { [number]: number })[bpp] + if not per then + return nil, Err.new(Err.ARG, "bpp must be 4, 8, 16 or 24") + end + local iw = if bpp == 24 then (w * 3 + 1) // 2 else math.ceil(w / per) + if iw > 0xFFFF or h > 0xFFFF then + return nil, Err.new(Err.ARG, "image too wide for TIM") + end + local px = img.pixels + local out = Bytes.writer(64 + iw * 2 * h) + out:u32le(0x10) + local colours: { number } = {} + local index: { [number]: number } = {} + if bpp <= 8 then + for i = 0, w * h - 1 do + local c = psx(readu32(px, i * 4)) + if not index[c] then + table.insert(colours, c) + index[c] = #colours - 1 + if #colours > (if bpp == 4 then 16 else 256) then + return nil, Err.new(Err.ARG, "more than " .. (if bpp == 4 then 16 else 256) .. " colours for a " .. bpp .. "-bit TIM") + end + end + end + local n = if bpp == 4 then 16 else 256 + out:u32le(8 + (if bpp == 4 then 0 else 1)) + out:u32le(12 + n * 2) + out:u16le(opts and opts.clutX or 0) + out:u16le(opts and opts.clutY or 480) + out:u16le(n) + out:u16le(1) + for i = 1, n do + out:u16le(colours[i] or 0) + end + else + out:u32le(if bpp == 16 then 2 else 3) + end + out:u32le(12 + iw * 2 * h) + out:u16le(opts and opts.x or 0) + out:u16le(opts and opts.y or 0) + out:u16le(iw) + out:u16le(h) + local at = out:reserve(iw * 2 * h) + local b = out.buf + buffer.fill(b, at, 0, iw * 2 * h) + for y = 0, h - 1 do + local row = at + y * iw * 2 + for x = 0, w - 1 do + local v = readu32(px, (y * w + x) * 4) + if bpp == 4 then + local i = index[psx(v)] + local o = row + x // 2 + buffer.writeu8(b, o, buffer.readu8(b, o) + (if x % 2 == 0 then i else i * 16)) + elseif bpp == 8 then + buffer.writeu8(b, row + x, index[psx(v)]) + elseif bpp == 16 then + writeu16(b, row + x * 2, psx(v)) + else + buffer.writeu8(b, row + x * 3, v % 256) + buffer.writeu8(b, row + x * 3 + 1, (v // 256) % 256) + buffer.writeu8(b, row + x * 3 + 2, (v // 65536) % 256) + end + end + end + out.pos = at + iw * 2 * h + return out:finish(), nil +end + +return Tim diff --git a/src/Formats/image/vtf/init.luau b/src/Formats/image/vtf/init.luau new file mode 100644 index 0000000..8cd5435 --- /dev/null +++ b/src/Formats/image/vtf/init.luau @@ -0,0 +1,245 @@ +--!strict +-- image/vtf: Valve Texture Format (VTF 7.0 - 7.5: Source engine textures), read. Written from the Valve Developer +-- Community "VTF (Valve Texture Format)" page; no code taken. +-- Decode: the high-resolution image (located by the 7.3+ resource directory or after the low-resolution thumbnail +-- for 7.0 - 7.2), mip 0 of slice 0 and face 0 (opts.mip / opts.face / opts.slice pick others), frame 1 as the Image +-- and every frame of an animated texture in img.frames (opts.frames ~= false; delay opts.delay, default 0.1 s), to +-- rgba8. Texel formats: RGBA8888, ABGR8888, RGB888, BGR888, RGB565, I8, IA88, A8, RGB888 / BGR888 bluescreen (pure +-- blue transparent), ARGB8888, BGRA8888, BGRX8888, BGR565, BGRX5551, BGRA5551, BGRA4444, UV88, UVWQ8888, UVLX8888, +-- RGBA16161616 (integers) / RGBA16161616F (halves, clamped), R32F, RGB323232F, RGBA32323232F (all through +-- codecs/image/Texel), DXT1 (+ one-bit alpha), +-- DXT3, DXT5, ATI1N, ATI2N (ids 35 / 34 since Alien Swarm, 38 / 37 in Source 2013) through codecs/image/Bcn. meta.source = { format, version, flags, frames, faces, depth, mips, +-- texel, reflectivity, bumpScale }. +-- Not supported: P8 (never implemented by Valve), the newer Strata / Source 2 formats, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Bcn = require("@formats/codecs/image/Bcn") +local Texel = require("@formats/codecs/image/Texel") + +-- ------------------------------------------------------------------------------------------------ contract +local Vtf = { + name = "vtf", + category = "image", + extensions = { "vtf" }, + mime = { "image/x-vtf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" }, + caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + mip: number?, -- mip level (0 = full size, default) + face: number?, -- cube map face (0-based, default 0) + slice: number?, -- volume slice (0-based, default 0) + frames: boolean?, -- decode every frame into img.frames (default true) + delay: number?, -- frame delay in seconds (default 0.1) + maxPixels: number?, -- default 2^26 +} + +-- ------------------------------------------------------------------------------------------------ constants +local M = Texel.masked +-- format id -> a codecs/image/Texel format (name or bit-mask descriptor) | { texel, bluescreen = true } | a BCn kind +local FORMATS: { [number]: any } = { + [0] = "rgba8", -- RGBA8888 + [1] = M(4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF), -- ABGR8888 + [2] = "rgb8", -- RGB888 + [3] = "bgr8", -- BGR888 + [4] = "r5g6b5", -- RGB565: red in the low bits (as VTFLib / srctools read it) + [5] = "l8", -- I8 + [6] = "la8", -- IA88 + [8] = "a8", -- A8 + [9] = { texel = "rgb8", bluescreen = true }, -- RGB888_BLUESCREEN + [10] = { texel = "bgr8", bluescreen = true }, -- BGR888_BLUESCREEN + [11] = M(4, 0xFF000000, 0x000000FF, 0x0000FF00, 0x00FF0000), -- ARGB8888: VTFLib's layout (G, B, A, R in memory) + [12] = "bgra8", -- BGRA8888 + [13] = "bc1", -- DXT1 + [14] = "bc2", -- DXT3 + [15] = "bc3", -- DXT5 + [16] = "bgrx8", -- BGRX8888 + [17] = "b5g6r5", -- BGR565: blue in the low bits + [18] = "b5g5r5x1", -- BGRX5551 + [19] = "b4g4r4a4", -- BGRA4444 + [20] = "bc1a", -- DXT1_ONEBITALPHA + [21] = "b5g5r5a1", -- BGRA5551 + [22] = "rg8", -- UV88 + [23] = "rgba8", -- UVWQ8888 + [24] = "rgba16f", -- RGBA16161616F + [25] = "rgba16", -- RGBA16161616 + [26] = "rgba8", -- UVLX8888 + [27] = "r32f", -- R32F + [28] = "rgb32f", -- RGB323232F + [29] = "rgba32f", -- RGBA32323232F + [34] = "bc5", -- ATI2N (Alien Swarm and later) + [35] = "bc4", -- ATI1N (Alien Swarm and later) + [37] = "bc5", -- ATI2N (Source 2013) + [38] = "bc4", -- ATI1N (Source 2013) +} +local BCN: { [string]: boolean } = { bc1 = true, bc1a = true, bc2 = true, bc3 = true, bc4 = true, bc5 = true } +local NAMES: { [number]: string } = { [0] = "RGBA8888", "ABGR8888", "RGB888", "BGR888", "RGB565", "I8", "IA88", "P8", "A8", "RGB888_BLUESCREEN", + "BGR888_BLUESCREEN", "ARGB8888", "BGRA8888", "DXT1", "DXT3", "DXT5", "BGRX8888", "BGR565", "BGRX5551", "BGRA4444", + "DXT1_ONEBITALPHA", "BGRA5551", "UV88", "UVWQ8888", "RGBA16161616F", "RGBA16161616", "UVLX8888", "R32F", "RGB323232F", + "RGBA32323232F", "NV_DST16", "NV_DST24", "NV_INTZ", "NV_RAWZ", "ATI2N", "ATI1N", "NV_NULL", "ATI2N", "ATI1N" } +local ENVMAP = 0x4000 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vtf.sniff(r: Bytes.Reader): number + return if r:peek(4) == "VTF\0" and r:peekU8(4) == 7 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- bytes of one w x h image in format f +local function imageSize(f: any, w: number, h: number): number + if type(f) == "string" and BCN[f] then + return Bcn.size(if f == "bc1a" then "bc1" else f, w, h) or 0 + end + return Texel.size(if type(f) == "table" and f.texel then f.texel else f, w, h) or 0 +end + +function Vtf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local size = r.limit - r.base + local b, base = r.buf, r.base + if size < 64 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if buffer.readstring(b, base, 4) ~= "VTF\0" then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local major, minor = buffer.readu32(b, base + 4), buffer.readu32(b, base + 8) + if major ~= 7 or minor > 5 then + return nil, Err.new(Err.UNSUPPORTED, "VTF version " .. major .. "." .. minor, 4) + end + local headerSize = buffer.readu32(b, base + 12) + local w, h = buffer.readu16(b, base + 16), buffer.readu16(b, base + 18) + local flags = buffer.readu32(b, base + 20) + local frames, firstFrame = buffer.readu16(b, base + 24), buffer.readu16(b, base + 26) + local refl = { buffer.readf32(b, base + 32), buffer.readf32(b, base + 36), buffer.readf32(b, base + 40) } + local bump = buffer.readf32(b, base + 48) + local fmtId = buffer.readi32(b, base + 52) + local mips = buffer.readu8(b, base + 56) + local lowFmt = buffer.readi32(b, base + 57) + local lowW, lowH = buffer.readu8(b, base + 61), buffer.readu8(b, base + 62) + local depth = if minor >= 2 and size >= 65 then math.max(1, buffer.readu16(b, base + 63)) else 1 + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "zero size", 16) + end + if w * h > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + local f: any = FORMATS[fmtId] + if not f then + return nil, Err.new(Err.UNSUPPORTED, "texel format " .. (NAMES[fmtId] or tostring(fmtId)), 52) + end + frames = math.max(1, frames) + mips = math.max(1, mips) + local faces = 1 + if bit32.band(flags, ENVMAP) ~= 0 then + faces = if minor < 5 and firstFrame ~= 0xFFFF then 7 else 6 + end + -- where the high-resolution data starts + local dataAt: number? = nil + if minor >= 3 then + if size < 80 then + return nil, Err.new(Err.TRUNCATED, "resource directory", 68) + end + local nres = buffer.readu32(b, base + 68) + if nres > 32 or 80 + nres * 8 > size then + return nil, Err.new(Err.CORRUPT, "bad resource count", 68) + end + for i = 0, nres - 1 do + local o = base + 80 + i * 8 + if buffer.readu8(b, o) == 0x30 and buffer.readu8(b, o + 1) == 0 and buffer.readu8(b, o + 2) == 0 then + dataAt = buffer.readu32(b, o + 4) + end + end + if not dataAt then + return nil, Err.new(Err.CORRUPT, "no high-resolution image resource", 80) + end + else + local lf = FORMATS[lowFmt] + local lowSize = if lowFmt >= 0 and lowW > 0 and lowH > 0 and lf then imageSize(lf, lowW, lowH) else 0 + dataAt = headerSize + lowSize + end + -- the chain: mips smallest first; per mip: frames, faces, slices + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, mips - 1) + local face = math.clamp(math.floor(opts and opts.face or 0), 0, faces - 1) + local slice = math.clamp(math.floor(opts and opts.slice or 0), 0, depth - 1) + local off = dataAt :: number + for m = mips - 1, mip + 1, -1 do + local mw, mh, md = math.max(1, w // 2 ^ m), math.max(1, h // 2 ^ m), math.max(1, depth // 2 ^ m) + off += imageSize(f, mw, mh) * md * faces * frames + end + local mw, mh, md = math.max(1, w // 2 ^ mip), math.max(1, h // 2 ^ mip), math.max(1, depth // 2 ^ mip) + local one = imageSize(f, mw, mh) + local function image(frame: number): (Types.Image?, Err.Err?) + local at = off + ((frame * faces + face) * md + math.min(slice, md - 1)) * one + if at + one > size or at < 0 then + return nil, Err.new(Err.TRUNCATED, "image data past the end", at) + end + local img = Types.Image.new(mw, mh) + if type(f) == "string" and BCN[f] then + local kind = if f == "bc1a" then "bc1" else f + local px, e = Bcn.decode(kind, b, base + at, mw, mh) + if not px then + return nil, Err.from(e) + end + buffer.copy(img.pixels, 0, px, 0, mw * mh * 4) + if f == "bc1" then + -- plain DXT1 carries no alpha: the transparent colour of 3-colour blocks reads as opaque black + for i = 0, mw * mh - 1 do + buffer.writeu8(img.pixels, i * 4 + 3, 255) + end + end + else + local blue = type(f) == "table" and f.bluescreen == true + local px, e = Texel.decode(if blue then f.texel else f, b, base + at, mw, mh) + if not px then + return nil, Err.from(e) + end + buffer.copy(img.pixels, 0, px, 0, mw * mh * 4) + if blue then + -- pure blue is the transparent key + for i = 0, mw * mh - 1 do + if buffer.readu32(img.pixels, i * 4) == 0xFFFF0000 then + buffer.writeu32(img.pixels, i * 4, 0) + end + end + end + end + return img, nil + end + local img, err = image(0) + if not img then + return nil, err + end + if frames > 1 and not (opts and opts.frames == false) then + local delay = opts and opts.delay or 0.1 + local list: { Types.Frame } = { { image = img, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } :: any } + for fr = 1, frames - 1 do + local fi, ferr = image(fr) + if not fi then + return nil, ferr + end + table.insert(list, { image = fi, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } :: any) + end + img.frames = list + img.loops = 0 + end + img.meta.source = { + format = "vtf", + version = major .. "." .. minor, + flags = flags, + frames = frames, + faces = faces, + depth = depth, + mips = mips, + texel = NAMES[fmtId], + reflectivity = refl, + bumpScale = bump, + } + return img, nil +end + +return Vtf diff --git a/src/Formats/model/bsp/Brush.luau b/src/Formats/model/bsp/Brush.luau new file mode 100644 index 0000000..e5362a9 --- /dev/null +++ b/src/Formats/model/bsp/Brush.luau @@ -0,0 +1,291 @@ +--!strict +-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex +-- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture +-- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the +-- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake / +-- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the +-- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from +-- opts.resolve("textures/.wal") when available, else texture coordinates stay in texels: extras.bsp.texels). +-- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken. +-- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls. +local Types = require("@formats/Types") +local Pixels = require("@formats/codecs/image/Pixels") + +local Brush = {} + +local Scene = Types.Scene +local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32 +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +export type Lump = { at: number, size: number } +export type Options = { + palette: buffer?, + wal: ((name: string) -> buffer?)?, -- Quake II: the .wal file of a texture (for its size) + maxPixels: number?, + maxVertices: number?, +} + +type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean } +type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } } + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +-- miptex lump (Quake / Half-Life) -> textures +local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer?, maxPixels: number): ({ Tex }?, string?) + local out: { Tex } = {} + if l.size < 4 then + return out, nil + end + local at = base + l.at + local n = readi32(b, at) + if n < 0 or n > 65536 or 4 + n * 4 > l.size then + return nil, "bad miptex lump" + end + local gpal = if pal then Pixels.palette(pal, 0, 256) else nil + for i = 0, n - 1 do + local o = readi32(b, at + 4 + i * 4) + if o < 0 or o + 40 > l.size then + out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } + else + local m = at + o + local name = cstr(b, m, 16) + local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) + local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } + if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then + local px = m + off0 + local need = w * h + local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2 + if o + off0 + need <= l.size then + local p = gpal + if hl then + p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil + end + local img = Types.Image.new(w, h) + if p then + Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) + else + for k = 0, need - 1 do + writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) + end + end + img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + t.image = img + end + end + out[i + 1] = t + end + end + return out, nil +end + +-- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message +-- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes, +-- models, miptex (q1 / hl) +function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?) + local q2 = variant == "q2" + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models + local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, Fc.size // 20 + local tiSize = if q2 then 76 else 40 + local nTI, nP = TI.size // tiSize, P.size // 20 + local mSize = if q2 then 48 else 64 + local nM = M.size // mSize + if nF > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many faces" + end + -- textures + local texs: { Tex } = {} + local texOf: { number } = {} -- texinfo -> texture index (1-based) + if q2 then + local byName: { [string]: number } = {} + for i = 0, nTI - 1 do + local name = cstr(b, base + TI.at + i * 76 + 40, 32) + local ti = byName[name] + if not ti then + local w, h, texels = 1, 1, true + local wal = opts and opts.wal and opts.wal(name) + if wal and buffer.len(wal) >= 40 then + w, h, texels = math.max(1, readu32(wal, 32)), math.max(1, readu32(wal, 36)), false + end + table.insert(texs, { name = name, width = w, height = h, image = nil, texels = texels }) + ti = #texs + byName[name] = ti + end + texOf[i + 1] = ti + end + else + local list, err = miptex(b, base, lumps.miptex, variant == "hl", opts and opts.palette, maxPixels) + if not list then + return nil, err + end + texs = list + for i = 0, nTI - 1 do + local mt = readi32(b, base + TI.at + i * 40 + 32) + texOf[i + 1] = if mt >= 0 and mt < #texs then mt + 1 else 0 + end + end + -- faces of each model + local scene = Scene.new() + scene.meta.up = "z" + local faceModel: { number } = {} + local models: { { first: number, count: number, origin: { number } } } = {} + for m = 0, nM - 1 do + local o = base + M.at + m * mSize + local origin = { readf32(b, o + 24), readf32(b, o + 28), readf32(b, o + 32) } + local fo = if q2 then 40 else 56 + local first, count = readi32(b, o + fo), readi32(b, o + fo + 4) + table.insert(models, { first = first, count = count, origin = origin }) + if first >= 0 and count >= 0 and first + count <= nF then + for f = first, first + count - 1 do + faceModel[f + 1] = faceModel[f + 1] or (m + 1) + end + end + end + if #models == 0 then + table.insert(models, { first = 0, count = nF, origin = { 0, 0, 0 } }) + for f = 1, nF do + faceModel[f] = 1 + end + end + local batches: { [number]: { [number]: Batch } } = {} + local orders: { [number]: { number } } = {} + local skipped = 0 + for f = 0, nF - 1 do + local fo = base + Fc.at + f * 20 + local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10) + local model = faceModel[f + 1] + if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then + skipped += 1 + continue + end + -- the polygon + local poly: { number } = {} + local ok = true + for k = 0, numEdges - 1 do + local se = readi32(b, base + SE.at + (firstEdge + k) * 4) + local e = math.abs(se) + if e >= nE then + ok = false + break + end + local v = if se >= 0 then readu16(b, base + E.at + e * 4) else readu16(b, base + E.at + e * 4 + 2) + if v >= nV then + ok = false + break + end + local vo = base + V.at + v * 12 + table.insert(poly, readf32(b, vo)) + table.insert(poly, readf32(b, vo + 4)) + table.insert(poly, readf32(b, vo + 8)) + end + if not ok then + skipped += 1 + continue + end + local po = base + P.at + plane * 20 + local nx, ny, nz = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8) + if side ~= 0 then + nx, ny, nz = -nx, -ny, -nz + end + -- orient counter-clockwise about the normal (Newell's normal of the polygon as stored) + local n = #poly // 3 + local ax, ay, az = 0, 0, 0 + for k = 0, n - 1 do + local j = (k + 1) % n + local x1, y1, z1 = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local x2, y2, z2 = poly[j * 3 + 1], poly[j * 3 + 2], poly[j * 3 + 3] + ax += (y1 - y2) * (z1 + z2) + ay += (z1 - z2) * (x1 + x2) + az += (x1 - x2) * (y1 + y2) + end + local order: { number } = {} + if ax * nx + ay * ny + az * nz >= 0 then + for k = 0, n - 1 do + order[k + 1] = k + end + else + order[1] = 0 + for k = 1, n - 1 do + order[k + 1] = n - k + end + end + local tio = base + TI.at + texinfo * tiSize + local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12) + local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28) + local ti = texOf[texinfo + 1] or 0 + local tex = texs[ti] + local w, h = if tex then tex.width else 1, if tex then tex.height else 1 + local bm = batches[model] or {} + batches[model] = bm + local bt = bm[ti] + if not bt then + bt = { tex = ti, pos = {}, nrm = {}, uv = {} } + bm[ti] = bt + local ol = orders[model] or {} + orders[model] = ol + table.insert(ol, ti) + end + local batch: Batch = bt + for k = 2, n - 1 do + for _, c in { order[1], order[k], order[k + 1] } do + local x, y, z = poly[c * 3 + 1], poly[c * 3 + 2], poly[c * 3 + 3] + local pp, nn, uu = batch.pos, batch.nrm, batch.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz + uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w + uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h + end + end + end + -- textures, materials + for i, t in texs do + local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) } + table.insert(scene.textures, tex) + local mat = Scene.material(t.name) + mat.metallic = 0 + local extras: any = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } + mat.extras = extras + mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any + table.insert(scene.materials, mat) + end + -- meshes and nodes + local root: Types.Node = { name = "bsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + for m, mdl in models do + local list = orders[m] + if list then + local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} } + for _, ti in list do + local bt = batches[m][ti] + local nv = #bt.pos // 3 + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, bt.pos[k]) + writef32(nb, (k - 1) * 4, bt.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, bt.uv[k]) + end + for k = 0, nv - 1 do + writeu32(ib, k * 4, k) + end + table.insert(mesh.primitives, { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, nv), + mode = "triangles" :: any, + material = if ti > 0 then ti else nil, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1, origin = mdl.origin } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.skippedFaces = skipped + return scene, nil +end + +return Brush diff --git a/src/Formats/model/bsp/Quake3.luau b/src/Formats/model/bsp/Quake3.luau new file mode 100644 index 0000000..242af04 --- /dev/null +++ b/src/Formats/model/bsp/Quake3.luau @@ -0,0 +1,261 @@ +--!strict +-- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a +-- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches +-- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap +-- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1 +-- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as +-- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped. +-- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken. +local Types = require("@formats/Types") + +local Quake3 = {} + +local Scene = Types.Scene +local readi32, readf32, readu8 = buffer.readi32, buffer.readf32, buffer.readu8 +local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.writeu8 + +export type Lump = { at: number, size: number } +export type Options = { patchLevel: number?, maxVertices: number? } + +type Batch = { shader: number, lightmap: number, verts: { number } } -- vertex records (indices into the vertex lump, or -1 - k for patch vertices) + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +-- decode(b, base, lumps, opts) -> Scene | nil, message +function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: Options?): (Types.Scene?, string?) + local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps + local nT, nM, nV, nMV, nF, nLM = T.size // 72, M.size // 40, VX.size // 44, MV.size // 4, F.size // 104, LM.size // 49152 + local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16) + local maxV = opts and opts.maxVertices or 2 ^ 24 + -- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids + local extra: { number } = {} + local function vertex(i: number): { number } + local o = base + VX.at + i * 44 + local v = table.create(14, 0) + for k = 0, 9 do + v[k + 1] = readf32(b, o + k * 4) + end + for k = 0, 3 do + v[11 + k] = readu8(b, o + 40 + k) + end + return v + end + local function addExtra(v: { number }): number + for k = 1, 14 do + table.insert(extra, v[k]) + end + return -(#extra // 14) + end + local faceModel: { number } = {} + for m = 0, nM - 1 do + local o = base + M.at + m * 40 + local first, count = readi32(b, o + 24), readi32(b, o + 28) + if first >= 0 and count >= 0 and first + count <= nF then + for f = first, first + count - 1 do + faceModel[f + 1] = faceModel[f + 1] or (m + 1) + end + end + end + local batches: { [number]: { [string]: Batch } } = {} + local orders: { [number]: { string } } = {} + local counts = { polygons = 0, meshes = 0, patches = 0, billboards = 0, skipped = 0 } + local total = 0 + for f = 0, nF - 1 do + local o = base + F.at + f * 104 + local shader, kind, first, n, mv, nmv, lm = readi32(b, o), readi32(b, o + 8), readi32(b, o + 12), readi32(b, o + 16), readi32(b, o + 20), readi32(b, o + 24), readi32(b, o + 28) + local model = faceModel[f + 1] or 1 + local tris: { number } = {} + if (kind == 1 or kind == 3) and first >= 0 and n >= 0 and first + n <= nV and mv >= 0 and nmv >= 0 and mv + nmv <= nMV then + for k = 0, nmv - 3, 3 do + local ok = true + local tri = {} + for c = 0, 2 do + local idx = readi32(b, base + MV.at + (mv + k + c) * 4) + if idx < 0 or idx >= n then + ok = false + end + tri[c + 1] = first + idx + end + if ok then + table.insert(tris, tri[3]) + table.insert(tris, tri[2]) + table.insert(tris, tri[1]) + end + end + counts[if kind == 1 then "polygons" else "meshes"] += 1 + elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then + local w, h = readi32(b, o + 96), readi32(b, o + 100) + if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + counts.patches += 1 + local L = level + for py = 0, (h - 1) // 2 - 1 do + for px = 0, (w - 1) // 2 - 1 do + -- the 3x3 control points of this sub-patch + local ctrl: { { number } } = {} + for j = 0, 2 do + for i = 0, 2 do + ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) + end + end + local grid: { number } = {} + for gy = 0, L do + local tv = gy / L + for gx = 0, L do + local tu = gx / L + local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } + local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } + local v = table.create(14, 0) + for j = 0, 2 do + for i = 0, 2 do + local wgt = bu[i + 1] * bv[j + 1] + local cp = ctrl[j * 3 + i + 1] + for k = 1, 14 do + v[k] += cp[k] * wgt + end + end + end + local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) + if l > 0 then + v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l + end + grid[gy * (L + 1) + gx + 1] = addExtra(v) + end + end + for gy = 0, L - 1 do + for gx = 0, L - 1 do + local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] + local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] + -- counter-clockwise for Quake's clockwise-front control grids + for _, v in { a, d, c2, c2, d, e } do + table.insert(tris, v) + end + end + end + end + end + else + counts.skipped += 1 + end + elseif kind == 4 then + counts.billboards += 1 + else + counts.skipped += 1 + end + total += #tris + if total > maxV then + return nil, "limit: too many vertices" + end + if #tris > 0 then + local key = shader .. ":" .. lm + local bm = batches[model] or {} + batches[model] = bm + local bt = bm[key] + if not bt then + bt = { shader = shader, lightmap = lm, verts = {} } + bm[key] = bt + local ol = orders[model] or {} + orders[model] = ol + table.insert(ol, key) + end + for _, v in tris do + table.insert(bt.verts, v) + end + end + end + local scene = Scene.new() + scene.meta.up = "z" + -- shaders, lightmaps + for i = 0, nT - 1 do + local name = cstr(b, base + T.at + i * 72, 64) + table.insert(scene.textures, { name = name, uri = name }) + end + local lmTex: { [number]: number } = {} + for i = 0, nLM - 1 do + local img = Types.Image.new(128, 128) + local o = base + LM.at + i * 49152 + for k = 0, 128 * 128 - 1 do + writeu8(img.pixels, k * 4, readu8(b, o + k * 3)) + writeu8(img.pixels, k * 4 + 1, readu8(b, o + k * 3 + 1)) + writeu8(img.pixels, k * 4 + 2, readu8(b, o + k * 3 + 2)) + writeu8(img.pixels, k * 4 + 3, 255) + end + img.meta.source = { format = "bsp", lightmap = i } + table.insert(scene.textures, { name = "lightmap " .. i, image = img }) + lmTex[i] = #scene.textures + end + local matOf: { [string]: number } = {} + local root: Types.Node = { name = "bsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local modelCount = math.max(nM, 1) + for m = 1, modelCount do + local list = orders[m] + if list then + local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} } + for _, key in list do + local bt = batches[m][key] + local nv = #bt.verts + local pb, nb, ub, lb, cb, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 8), buffer.create(nv * 4), buffer.create(nv * 4) + for k, id in bt.verts do + local v: { number } + if id >= 0 then + v = vertex(id) + else + local e = (-id - 1) * 14 + v = table.move(extra, e + 1, e + 14, 1, table.create(14, 0)) :: { number } + end + local o = (k - 1) + writef32(pb, o * 12, v[1]) + writef32(pb, o * 12 + 4, v[2]) + writef32(pb, o * 12 + 8, v[3]) + writef32(ub, o * 8, v[4]) + writef32(ub, o * 8 + 4, v[5]) + writef32(lb, o * 8, v[6]) + writef32(lb, o * 8 + 4, v[7]) + writef32(nb, o * 12, v[8]) + writef32(nb, o * 12 + 4, v[9]) + writef32(nb, o * 12 + 8, v[10]) + for c = 0, 3 do + writeu8(cb, o * 4 + c, math.clamp(math.floor(v[11 + c] + 0.5), 0, 255)) + end + writeu32(ib, o * 4, o) + end + local mi = matOf[key] + if not mi then + local name = if bt.shader >= 0 and bt.shader < nT then scene.textures[bt.shader + 1].name else "noshader" + local mat = Scene.material(name) + mat.metallic = 0 + if bt.shader >= 0 and bt.shader < nT then + mat.baseColorTexture = { texture = bt.shader + 1 } + end + local lt = lmTex[bt.lightmap] + mat.extras = { bsp = { lightmap = lt, lightmapTexCoord = if lt then 1 else nil } } + table.insert(scene.materials, mat) + mi = #scene.materials + matOf[key] = mi + end + table.insert(mesh.primitives, { + attributes = { + POSITION = Scene.accessor(pb, "f32", 3, nv), + NORMAL = Scene.accessor(nb, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv), + TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv), + COLOR_0 = Scene.accessor(cb, "unorm8", 4, nv), + }, + indices = Scene.accessor(ib, "u32", 1, nv), + mode = "triangles" :: any, + material = mi, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1 } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.faces = counts + return scene, nil +end + +return Quake3 diff --git a/src/Formats/model/bsp/init.luau b/src/Formats/model/bsp/init.luau new file mode 100644 index 0000000..8835a87 --- /dev/null +++ b/src/Formats/model/bsp/init.luau @@ -0,0 +1,150 @@ +--!strict +-- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38) +-- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a +-- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III +-- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as +-- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not +-- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey. +-- Quake II .wal sizes come from opts.resolve("textures/.wal") / opts.files. Units are map units, z up. +-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Input = require("@formats/core/Input") +local Types = require("@formats/Types") +local Brush = require("@formats/model/bsp/Brush") +local Quake3 = require("@formats/model/bsp/Quake3") + +-- ------------------------------------------------------------------------------------------------ contract +local Bsp = { + name = "bsp", + category = "model", + extensions = { "bsp" }, + mime = { "model/x-bsp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + palette: (buffer | string)?, -- Quake 1: the 768-byte palette + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + patchLevel: number?, -- Quake III patch subdivisions (default 4) + maxPixels: number?, -- default 2^24 + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ constants +local Q1_LUMPS = { "entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", + "clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models" } +local Q2_LUMPS = { "entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves", + "leaffaces", "leafbrushes", "edges", "surfedges", "models", "brushes", "brushsides", "pop", "areas", "areaportals" } +local Q3_LUMPS = { "entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes", + "brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Bsp.sniff(r: Bytes.Reader): number + if r:remaining() < 64 then + return 0 + end + local m = r:peek(4) + local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0)) + if m == "IBSP" then + return if v == 38 or v == 46 or v == 47 then 1 else 0.3 + end + if v == 29 or v == 30 then + -- no magic: check that the lump directory fits the file + local size = r:remaining() + for i = 0, 14 do + local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8) + if o < 0 or n < 0 or o + n > size then + return 0 + end + end + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the entities text -> { { key = value } } +local function entities(text: string): { { [string]: string } } + local out: { { [string]: string } } = {} + for block in string.gmatch(text, "%b{}") do + local e: { [string]: string } = {} + for k, v in string.gmatch(block, '"([^"]*)"%s*"([^"]*)"') do + e[k] = v + end + table.insert(out, e) + end + return out +end + +function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if size < 8 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local b, base = r.buf, r.base + local m = r:peek(4) + local version = buffer.readi32(b, base + (if m == "IBSP" then 4 else 0)) + local names: { string }, dir: number, variant: string + if m == "IBSP" and version == 38 then + names, dir, variant = Q2_LUMPS, 8, "q2" + elseif m == "IBSP" and (version == 46 or version == 47) then + names, dir, variant = Q3_LUMPS, 8, "q3" + elseif m ~= "IBSP" and (version == 29 or version == 30) then + names, dir, variant = Q1_LUMPS, 4, if version == 30 then "hl" else "q1" + elseif m == "VBSP" then + return nil, Err.new(Err.UNSUPPORTED, "Source engine VBSP maps", 0) + else + return nil, Err.new(Err.UNSUPPORTED, "BSP version " .. version, 0) + end + if dir + #names * 8 > size then + return nil, Err.new(Err.TRUNCATED, "lump directory", dir) + end + local lumps: { [string]: { at: number, size: number } } = {} + for i, name in names do + local o, n = buffer.readi32(b, base + dir + (i - 1) * 8), buffer.readi32(b, base + dir + (i - 1) * 8 + 4) + if o < 0 or n < 0 or o + n > size then + return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dir + (i - 1) * 8) + end + lumps[name] = { at = o, size = n } + end + local scene: Types.Scene?, msg: string? + if variant == "q3" then + scene, msg = Quake3.decode(b, base, lumps, opts :: any) + else + local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp") + if pal and buffer.len(pal) < 768 then + pal = nil + end + scene, msg = Brush.decode(b, base, lumps, variant, { + palette = pal, + wal = function(name: string): buffer? + return Input.sibling(opts, "textures/" .. name .. ".wal") + end, + maxPixels = opts and opts.maxPixels, + maxVertices = opts and opts.maxVertices, + }) + end + if not scene then + return nil, Err.from(msg) + end + local e = lumps.entities + local text = buffer.readstring(b, base + e.at, e.size) + text = string.match(text, "^[^%z]*") :: string + scene.meta.entities = entities(text) + scene.meta.source = { + format = "bsp", + variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant], + version = version, + entities = text, + palette = if variant == "q1" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil, + } + return scene, nil +end + +return Bsp diff --git a/src/Formats/model/md2/init.luau b/src/Formats/model/md2/init.luau new file mode 100644 index 0000000..cc241fb --- /dev/null +++ b/src/Formats/model/md2/init.luau @@ -0,0 +1,209 @@ +--!strict +-- model/md2: Quake II MD2 models ("IDP2" version 8), read into a Scene. Written from the MD2 format description in the +-- Quake II source release (qfiles.h: dmdl_t) and the "MD2 file format" notes (David Henry); no code taken. +-- Decode: one primitive: the triangles (welded on (vertex, texture coordinate) pairs; MD2 front faces are clockwise, +-- the indices are reversed to counter-clockwise as glTF wants), POSITION of frame opts.frame (default 1), +-- TEXCOORD_0 = s / skinwidth, t / skinheight (top-left origin), NORMAL computed from the geometry (the stored +-- indexes into Quake's normal table are kept as meta.source.normalIndexes = false: that table is not +-- redistributable here); every frame as a morph target (codecs/model/Rig: weight k = 1 shows frame k) and one +-- animation per frame-name group ("run1".."run6" -> "run", 10 frames per second, LINEAR); the skins as texture +-- URIs (the first is the material's base colour texture; mesh.extras.skins lists all). Units are Quake units, z up. +-- meta.source = { format, frames, frameNames, skinWidth, skinHeight }. +-- Not supported: the GL command list (the triangles carry the same geometry), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Rig = require("@formats/codecs/model/Rig") + +-- ------------------------------------------------------------------------------------------------ contract +local Md2 = { + name = "md2", + category = "model", + extensions = { "md2" }, + mime = { "model/x-md2" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + frame: number?, -- the frame used as the base POSITION (1-based, default 1) + morph: boolean?, -- every frame as a morph target + the animations (default true) + fps: number?, -- animation frame rate (default 10) + maxVertices: number?, -- frames x vertices (default 2^24) +} + +-- ------------------------------------------------------------------------------------------------ constants +local Scene = Types.Scene +local readu8, readu16, readi16, readf32, writef32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readf32, buffer.writef32, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Md2.sniff(r: Bytes.Reader): number + if r:remaining() < 68 then + return 0 + end + return if Sniff.magic(r, "IDP2") == 1 and r:peekU8(4) == 8 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- group frame names by their name without trailing digits, in file order +local function groups(names: { string }, fps: number): { Rig.Range } + local out: { Rig.Range } = {} + for i, n in names do + local stem = string.match(n, "^(.-)_?%d*$") or n + if stem == "" then + stem = n + end + local last = out[#out] + if last and last.name == stem and last.last == i - 1 then + last.last = i + else + table.insert(out, { name = stem, first = i, last = i, fps = fps }) + end + end + return out +end + +function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if not r:match("IDP2") then + return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0) + end + local h: { number } = {} + for i = 1, 16 do + h[i] = r:i32le() + end + if r.err then + return nil, r.err + end + local version, sw, sh, frameSize, nSkins, nXyz, nSt, nTris, _, nFrames, oSkins, oSt, oTris, oFrames = table.unpack(h, 1, 14) + if version ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "MD2 version " .. version, 4) + end + if nSkins < 0 or nXyz <= 0 or nSt < 0 or nTris < 0 or nFrames <= 0 or sw < 0 or sh < 0 then + return nil, Err.new(Err.CORRUPT, "bad counts", 8) + end + if nFrames * nXyz > (opts and opts.maxVertices or 2 ^ 24) then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if not (inside(oSkins, nSkins * 64) and inside(oSt, nSt * 4) and inside(oTris, nTris * 12) and inside(oFrames, nFrames * frameSize)) then + return nil, Err.new(Err.TRUNCATED, "a section runs past the end", 44) + end + if frameSize < 40 + nXyz * 4 then + return nil, Err.new(Err.CORRUPT, "frame size too small", 16) + end + local b, base = r.buf, r.base + -- skins + local skins: { string } = {} + for i = 0, nSkins - 1 do + local s = buffer.readstring(b, base + oSkins + i * 64, 64) + table.insert(skins, (string.match(s, "^[^%z]*")) :: string) + end + -- weld (xyz, st) pairs + local key: { [number]: number } = {} + local vx: { number }, vst: { number } = {}, {} + local indices: { number } = {} + for t = 0, nTris - 1 do + local o = base + oTris + t * 12 + local corner: { number } = {} + for c = 0, 2 do + local xi, si = readu16(b, o + c * 2), readu16(b, o + 6 + c * 2) + if xi >= nXyz or (nSt > 0 and si >= nSt) then + return nil, Err.new(Err.CORRUPT, "triangle " .. t .. " index out of range", oTris + t * 12) + end + local k = xi * 65536 + si + local v = key[k] + if not v then + table.insert(vx, xi) + table.insert(vst, si) + v = #vx - 1 + key[k] = v + end + corner[c + 1] = v + end + table.insert(indices, corner[3]) + table.insert(indices, corner[2]) + table.insert(indices, corner[1]) + end + local nv = #vx + local uv = buffer.create(nv * 8) + for i = 1, nv do + if nSt > 0 then + local o = base + oSt + vst[i] * 4 + writef32(uv, (i - 1) * 8, readi16(b, o) / math.max(sw, 1)) + writef32(uv, (i - 1) * 8 + 4, readi16(b, o + 2) / math.max(sh, 1)) + end + end + -- frames + local frames: { buffer } = {} + local normals: { buffer } = {} + local names: { string } = {} + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames) + for f = 1, nFrames do + if morph or f == want then + local o = base + oFrames + (f - 1) * frameSize + local sx, sy, sz = readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) + local tx, ty, tz = readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) + local pos = buffer.create(nv * 12) + for i = 1, nv do + local p = o + 40 + vx[i] * 4 + writef32(pos, (i - 1) * 12, readu8(b, p) * sx + tx) + writef32(pos, (i - 1) * 12 + 4, readu8(b, p + 1) * sy + ty) + writef32(pos, (i - 1) * 12 + 8, readu8(b, p + 2) * sz + tz) + end + frames[f] = pos + normals[f] = Rig.normals(pos, nv, indices) + end + local nm = buffer.readstring(b, base + oFrames + (f - 1) * frameSize + 24, 16) + names[f] = (string.match(nm, "^[^%z]*")) :: string + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(frames[want], "f32", 3, nv), + NORMAL = Scene.accessor(normals[want], "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + }, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles", + } + local scene = Scene.new() + scene.meta.up = "z" + if #skins > 0 then + for _, s in skins do + table.insert(scene.textures, { name = s, uri = s }) + end + local mat = Scene.material(skins[1]) + mat.metallic = 0 + mat.baseColorTexture = { texture = 1 } + table.insert(scene.materials, mat) + prim.material = 1 + end + scene.meshes[1] = { primitives = { prim }, extras = { skins = skins } } + scene.nodes[1] = { children = {}, mesh = 1 } + scene.roots[1] = 1 + if morph then + local fr: { buffer } = {} + for f = 1, nFrames do + fr[f] = frames[f] + end + Rig.morph(prim, fr, normals) + local w = table.create(nFrames, 0) + scene.meshes[1].weights = w + Rig.morphAnimation(scene, 1, nFrames, groups(names, opts and opts.fps or 10), "LINEAR") + end + scene.meta.source = { format = "md2", frames = nFrames, frameNames = names, skinWidth = sw, skinHeight = sh, normalIndexes = false } + return scene, nil +end + +return Md2 diff --git a/src/Formats/model/md3/init.luau b/src/Formats/model/md3/init.luau new file mode 100644 index 0000000..67fc41c --- /dev/null +++ b/src/Formats/model/md3/init.luau @@ -0,0 +1,234 @@ +--!strict +-- model/md3: Quake III Arena MD3 models ("IDP3" version 15), read into a Scene. Written from the MD3 format +-- description in the Quake III source release (qfiles.h: md3Header_t, md3Surface_t) and the "MD3 file format" +-- notes (PhaethonH); no code taken. +-- Decode: one mesh, one primitive per surface (indices reversed to counter-clockwise; POSITION of frame opts.frame +-- (default 1) in units of 1/64; NORMAL from the stored latitude / longitude bytes; TEXCOORD_0 as stored, top-left +-- origin); every frame as a morph target of each primitive (codecs/model/Rig) and one animation "frames" over all +-- of them (opts.fps, default 15); the first shader of each surface as its material's texture URI; tags as child nodes +-- (origin + axis of frame 1; their per-frame motion as translation / rotation channels of the same animation). +-- Units are Quake units, z up. meta.source = { format, name, frames, frameNames, tags }. +-- Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Rig = require("@formats/codecs/model/Rig") + +-- ------------------------------------------------------------------------------------------------ contract +local Md3 = { + name = "md3", + category = "model", + extensions = { "md3" }, + mime = { "model/x-md3" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true, tags = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + frame: number?, -- the frame used as the base POSITION / NORMAL (1-based, default 1) + morph: boolean?, -- every frame as a morph target + the animation (default true) + fps: number?, -- animation frame rate (default 15) + maxVertices: number?, -- frames x vertices over all surfaces (default 2^24) +} + +-- ------------------------------------------------------------------------------------------------ constants +local Scene = Types.Scene +local readi16, readu8, readi32, readf32, writef32, writeu32 = buffer.readi16, buffer.readu8, buffer.readi32, buffer.readf32, buffer.writef32, buffer.writeu32 +local K = math.pi / 128 -- the engine maps a byte to 2 pi / 256 (tr_surface.c LatLongToNormal) + +-- ------------------------------------------------------------------------------------------------ sniff +function Md3.sniff(r: Bytes.Reader): number + if r:remaining() < 108 then + return 0 + end + return if Sniff.magic(r, "IDP3") == 1 and r:peekU8(4) == 15 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +function Md3.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if size < 108 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if not r:match("IDP3") then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local version = r:i32le() + if version ~= 15 then + return nil, Err.new(Err.UNSUPPORTED, "MD3 version " .. version, 4) + end + local b, base = r.buf, r.base + local name = cstr(b, base + 8, 64) + r:skip(68) + local nFrames, nTags, nSurf, _nSkins = r:i32le(), r:i32le(), r:i32le(), r:i32le() + local oFrames, oTags, oSurf = r:i32le(), r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if nFrames <= 0 or nTags < 0 or nSurf < 0 or nFrames > 65536 or nTags > 4096 or nSurf > 4096 then + return nil, Err.new(Err.CORRUPT, "bad counts", 76) + end + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if not inside(oFrames, nFrames * 56) or not inside(oTags, nFrames * nTags * 112) then + return nil, Err.new(Err.TRUNCATED, "frames / tags past the end", 88) + end + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames) + local maxV = opts and opts.maxVertices or 2 ^ 24 + local scene = Scene.new() + scene.meta.up = "z" + local mesh: Types.Mesh = { name = if name ~= "" then name else nil, primitives = {} } + scene.meshes[1] = mesh + scene.nodes[1] = { name = mesh.name, children = {}, mesh = 1 } + scene.roots[1] = 1 + local total = 0 + local so = oSurf + for s = 1, nSurf do + if not inside(so, 108) or cstr(b, base + so, 4) ~= "IDP3" then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad header", so) + end + local p = base + so + local sname = cstr(b, p + 4, 64) + local sFrames, nShaders, nVerts, nTris = readi32(b, p + 72), readi32(b, p + 76), readi32(b, p + 80), readi32(b, p + 84) + local oTri, oSh, oSt, oXyz, oEnd = readi32(b, p + 88), readi32(b, p + 92), readi32(b, p + 96), readi32(b, p + 100), readi32(b, p + 104) + if sFrames ~= nFrames or nShaders < 0 or nVerts < 0 or nTris < 0 or oEnd <= 0 then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad counts", so + 72) + end + total += nVerts * nFrames + if total > maxV then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + if not (inside(so + oTri, nTris * 12) and inside(so + oSh, nShaders * 68) and inside(so + oSt, nVerts * 8) and inside(so + oXyz, nVerts * nFrames * 8)) then + return nil, Err.new(Err.TRUNCATED, "surface " .. s .. " past the end", so) + end + local ib = buffer.create(nTris * 12) + local idx = table.create(nTris * 3, 0) :: { number } + for t = 0, nTris - 1 do + for c = 0, 2 do + local v = readi32(b, p + oTri + t * 12 + c * 4) + if v < 0 or v >= nVerts then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": triangle index out of range", so + oTri + t * 12) + end + idx[t * 3 + 3 - c] = v + end + end + for i, v in idx do + writeu32(ib, (i - 1) * 4, v) + end + local uv = buffer.create(nVerts * 8) + buffer.copy(uv, 0, b, p + oSt, nVerts * 8) + local frames: { buffer }, normals: { buffer } = {}, {} + for f = 1, nFrames do + if morph or f == want then + local pos, nrm = buffer.create(nVerts * 12), buffer.create(nVerts * 12) + local q = p + oXyz + (f - 1) * nVerts * 8 + for v = 0, nVerts - 1 do + local o = q + v * 8 + writef32(pos, v * 12, readi16(b, o) / 64) + writef32(pos, v * 12 + 4, readi16(b, o + 2) / 64) + writef32(pos, v * 12 + 8, readi16(b, o + 4) / 64) + local lng, lat = readu8(b, o + 6) * K, readu8(b, o + 7) * K + writef32(nrm, v * 12, math.cos(lat) * math.sin(lng)) + writef32(nrm, v * 12 + 4, math.sin(lat) * math.sin(lng)) + writef32(nrm, v * 12 + 8, math.cos(lng)) + end + frames[f], normals[f] = pos, nrm + end + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(frames[want], "f32", 3, nVerts), + NORMAL = Scene.accessor(normals[want], "f32", 3, nVerts), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nVerts), + }, + indices = Scene.accessor(ib, "u32", 1, nTris * 3), + mode = "triangles", + extras = { md3 = { surface = sname } }, + } + if morph then + Rig.morph(prim, frames, normals) + end + local shaders: { string } = {} + for k = 0, nShaders - 1 do + table.insert(shaders, cstr(b, p + oSh + k * 68, 64)) + end + local mat = Scene.material(sname) + mat.metallic = 0 + if shaders[1] and shaders[1] ~= "" then + table.insert(scene.textures, { name = shaders[1], uri = shaders[1] }) + mat.baseColorTexture = { texture = #scene.textures } + end + mat.extras = { md3 = { shaders = shaders } } + table.insert(scene.materials, mat) + prim.material = #scene.materials + table.insert(mesh.primitives, prim) + so += oEnd + end + -- frames and tags + local frameNames: { string } = {} + for f = 0, nFrames - 1 do + frameNames[f + 1] = cstr(b, base + oFrames + f * 56 + 40, 16) + end + local tagNodes: { number } = {} + local tracks: { [number]: Rig.Track } = {} + local tagNames: { string } = {} + for k = 0, nTags - 1 do + local tr: Rig.Track = { translation = {}, rotation = {} } + local first: any = nil + for f = 0, nFrames - 1 do + local o = base + oTags + (f * nTags + k) * 112 + local t = { readf32(b, o + 64), readf32(b, o + 68), readf32(b, o + 72) } + local a: { number } = {} + for i = 0, 8 do + a[i + 1] = readf32(b, o + 76 + i * 4) + end + local m = { a[1], a[2], a[3], 0, a[4], a[5], a[6], 0, a[7], a[8], a[9], 0, t[1], t[2], t[3], 1 } + local q = Mat4.quat(m) + for c = 1, 3 do + table.insert(tr.translation :: { number }, t[c]) + end + for c = 1, 4 do + table.insert(tr.rotation :: { number }, q[c]) + end + if f == want - 1 then + first = { name = cstr(b, o, 64), t = t, q = q } + end + end + table.insert(tagNames, first.name) + table.insert(scene.nodes, { name = first.name, children = {}, translation = first.t, rotation = first.q, extras = { md3 = { tag = true } } }) + table.insert(scene.nodes[1].children, #scene.nodes) + tagNodes[k + 1] = #scene.nodes + tracks[k + 1] = tr + end + if morph and nFrames > 1 then + scene.meshes[1].weights = table.create(nFrames, 0) + local fps = opts and opts.fps or 15 + Rig.morphAnimation(scene, 1, nFrames, { { name = "frames", first = 1, last = nFrames, fps = fps } }, "LINEAR") + if nTags > 0 then + local times: { number } = {} + for f = 1, nFrames do + times[f] = (f - 1) / fps + end + local ai = Rig.animation(scene, "tags", tagNodes, times, tracks) + local tagAnim = table.remove(scene.animations, ai) :: Types.Animation + for _, ch in tagAnim.channels do + table.insert(scene.animations[1].channels, ch) + end + end + end + scene.meta.source = { format = "md3", name = name, frames = nFrames, frameNames = frameNames, tags = tagNames } + return scene, nil +end + +return Md3 diff --git a/src/Formats/model/md5/Read.luau b/src/Formats/model/md5/Read.luau new file mode 100644 index 0000000..6ed3fba --- /dev/null +++ b/src/Formats/model/md5/Read.luau @@ -0,0 +1,440 @@ +--!strict +-- model/md5/Read: Doom 3 / Quake 4 MD5 text (MD5Version 10) to Scenes. md5mesh: joints (model-space bind pose: +-- position + unit quaternion with w = -sqrt(1 - x² - y² - z²)) -> joint nodes and a Skin, each mesh -> a primitive +-- (positions from the weights in the bind pose, normals computed, texture coordinates as stored, triangles reversed +-- to counter-clockwise, JOINTS_0 / WEIGHTS_0 from the weights), its shader -> a material / texture URI. md5anim: +-- hierarchy + baseframe (parent-relative) + frames of animated components -> translation / rotation channels at +-- frameRate, applied to the joint nodes of the same names. Written from the format notes of the Doom 3 modding +-- community (modwiki "MD5 (file format)", David Henry's "The MD5 Mesh and Animation Formats"); no code taken. +local Types = require("@formats/Types") +local Rig = require("@formats/codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +export type Options = { maxVertices: number? } + +-- ------------------------------------------------------------------------------------------------ tokens +type Lexer = { text: string, pos: number, err: string? } + +local function token(L: Lexer): string? + local s = L.text + while true do + local a = string.find(s, "%S", L.pos) + if not a then + L.pos = #s + 1 + return nil + end + if string.sub(s, a, a + 1) == "//" then + local nl = string.find(s, "\n", a, true) + L.pos = if nl then nl + 1 else #s + 1 + else + L.pos = a + break + end + end + local c = string.sub(s, L.pos, L.pos) + if c == '"' then + local e = string.find(s, '"', L.pos + 1, true) + if not e then + L.err = "unterminated string" + L.pos = #s + 1 + return nil + end + local v = string.sub(s, L.pos + 1, e - 1) + L.pos = e + 1 + return '"' .. v + end + if c == "(" or c == ")" or c == "{" or c == "}" then + L.pos += 1 + return c + end + local e = string.find(s, '[%s(){}"]', L.pos) or (#s + 1) + local v = string.sub(s, L.pos, e - 1) + L.pos = e + return v +end + +local function num(L: Lexer): number + local t = token(L) + local v = t and tonumber(t) + if not v then + L.err = L.err or ("expected a number, got " .. tostring(t)) + return 0 + end + return v +end + +local function str(L: Lexer): string + local t = token(L) + if not t or string.sub(t, 1, 1) ~= '"' then + L.err = L.err or ("expected a string, got " .. tostring(t)) + return "" + end + return string.sub(t, 2) +end + +local function expect(L: Lexer, want: string) + local t = token(L) + if t ~= want then + L.err = L.err or ("expected " .. want .. ", got " .. tostring(t)) + end +end + +local function vec(L: Lexer, n: number): { number } + expect(L, "(") + local v = table.create(n, 0) + for i = 1, n do + v[i] = num(L) + end + expect(L, ")") + return v +end + +-- the unit quaternion from its x, y, z (w <= 0, as id's tools store it) +local function quat(x: number, y: number, z: number): { number } + local t = 1 - x * x - y * y - z * z + return { x, y, z, if t < 0 then 0 else -math.sqrt(t) } +end + +local function rotate(q: { number }, vx: number, vy: number, vz: number): (number, number, number) + local qx, qy, qz, qw = q[1], q[2], q[3], q[4] + -- v + 2 w (q x v) + 2 q x (q x v) + local tx, ty, tz = 2 * (qy * vz - qz * vy), 2 * (qz * vx - qx * vz), 2 * (qx * vy - qy * vx) + return vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx) +end + +-- ------------------------------------------------------------------------------------------------ md5mesh +type MeshJoint = { name: string, parent: number, pos: { number }, q: { number } } + +-- mesh(text, opts) -> Scene, joint node indices by name | nil, message +function Read.mesh(text: string, opts: Options?): (Types.Scene?, any) + local L: Lexer = { text = text, pos = 1, err = nil } + local joints: { MeshJoint } = {} + local scene = Scene.new() + scene.meta.up = "z" + local root: Types.Node = { name = "md5", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local version: number? = nil + local mesh: Types.Mesh = { primitives = {} } + local maxV = opts and opts.maxVertices or 2 ^ 24 + local total = 0 + local skinIndex = 0 + local nodes: { number } = {} + while not L.err do + local t = token(L) + if not t then + break + end + if t == "MD5Version" then + version = num(L) + elseif t == "commandline" then + str(L) + elseif t == "numJoints" or t == "numMeshes" then + num(L) + elseif t == "joints" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if not s or string.sub(s, 1, 1) ~= '"' then + return nil, "bad joint line" + end + local parent = num(L) + local p, q = vec(L, 3), vec(L, 3) + table.insert(joints, { name = string.sub(s, 2), parent = parent + 1, pos = p, q = quat(q[1], q[2], q[3]) }) + end + local list: { Rig.Joint } = {} + for i, j in joints do + list[i] = { name = j.name, parent = j.parent, translation = j.pos, rotation = j.q } + end + local n, si = Rig.skeleton(scene, list, "world", 1) + nodes, skinIndex = n, si + elseif t == "mesh" then + expect(L, "{") + local shader = "" + local verts: { { number } } = {} -- s, t, startWeight, countWeight + local tris: { number } = {} + local weights: { { number } } = {} -- joint, bias, x, y, z + while not L.err do + local k = token(L) + if k == "}" then + break + elseif k == "shader" then + shader = str(L) + elseif k == "numverts" or k == "numtris" or k == "numweights" then + local n = num(L) + total += if k == "numverts" then n else 0 + if total > maxV then + return nil, "limit: too many vertices" + end + elseif k == "vert" then + local i = num(L) + local st = vec(L, 2) + verts[i + 1] = { st[1], st[2], num(L), num(L) } + elseif k == "tri" then + num(L) + local a, b, c = num(L), num(L), num(L) + table.insert(tris, c) + table.insert(tris, b) + table.insert(tris, a) + elseif k == "weight" then + local i = num(L) + local j, bias = num(L), num(L) + local p = vec(L, 3) + weights[i + 1] = { j, bias, p[1], p[2], p[3] } + else + return nil, "unknown mesh keyword " .. tostring(k) + end + end + local nv = #verts + local pos, uv = buffer.create(nv * 12), buffer.create(nv * 8) + local lists: { { number } } = {} + for vi = 1, nv do + local v = verts[vi] + if not v then + return nil, "missing vert " .. (vi - 1) + end + local x, y, z = 0, 0, 0 + local l: { number } = {} + for w = v[3] + 1, v[3] + v[4] do + local wt = weights[w] + local j = wt and joints[wt[1] + 1] + if not wt or not j then + return nil, "vert " .. (vi - 1) .. ": bad weight " .. (w - 1) + end + local rx, ry, rz = rotate(j.q, wt[3], wt[4], wt[5]) + x += (j.pos[1] + rx) * wt[2] + y += (j.pos[2] + ry) * wt[2] + z += (j.pos[3] + rz) * wt[2] + table.insert(l, wt[1]) + table.insert(l, wt[2]) + end + writef32(pos, (vi - 1) * 12, x) + writef32(pos, (vi - 1) * 12 + 4, y) + writef32(pos, (vi - 1) * 12 + 8, z) + writef32(uv, (vi - 1) * 8, v[1]) + writef32(uv, (vi - 1) * 8 + 4, v[2]) + lists[vi] = l + end + for _, ix in tris do + if ix < 0 or ix >= nv then + return nil, "triangle index out of range" + end + end + local ib = buffer.create(#tris * 4) + for i, ix in tris do + writeu32(ib, (i - 1) * 4, ix) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(Rig.normals(pos, nv, tris), "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if #joints > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local mat = Scene.material(shader) + mat.metallic = 0 + table.insert(scene.textures, { name = shader, uri = shader }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #tris), mode = "triangles" :: any, material = #scene.materials }) + else + return nil, "unknown keyword " .. t + end + end + if L.err then + return nil, L.err + end + if version ~= 10 then + return nil, if version then "unsupported: MD5Version " .. version else "no MD5Version" + end + if #mesh.primitives > 0 then + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #joints > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + local byName: { [string]: number } = {} + for i, j in joints do + byName[j.name] = nodes[i] + end + scene.meta.source = { format = "md5", kind = "mesh", joints = #joints, meshes = #mesh.primitives } + return scene, byName +end + +-- ------------------------------------------------------------------------------------------------ md5anim +export type Anim = { + frameRate: number, + frames: number, + joints: { { name: string, parent: number } }, + base: { { number } }, -- per joint: px py pz qx qy qz + tracks: { Rig.Track }, -- per joint: translation / rotation keys, one per frame +} + +-- anim(text) -> Anim | nil, message +function Read.anim(text: string): (Anim?, string?) + local L: Lexer = { text = text, pos = 1, err = nil } + local a: Anim = { frameRate = 24, frames = 0, joints = {}, base = {}, tracks = {} } + local hier: { { number } } = {} -- flags, startIndex + local version: number? = nil + local nComp = 0 + local frames: { { number } } = {} + while not L.err do + local t = token(L) + if not t then + break + end + if t == "MD5Version" then + version = num(L) + elseif t == "commandline" then + str(L) + elseif t == "numFrames" then + a.frames = num(L) + elseif t == "numJoints" then + num(L) + elseif t == "frameRate" then + a.frameRate = num(L) + elseif t == "numAnimatedComponents" then + nComp = num(L) + if nComp < 0 or nComp > 2 ^ 20 then + return nil, "bad numAnimatedComponents" + end + elseif t == "hierarchy" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if not s or string.sub(s, 1, 1) ~= '"' then + return nil, "bad hierarchy line" + end + local parent, flags, start = num(L), num(L), num(L) + table.insert(a.joints, { name = string.sub(s, 2), parent = parent + 1 }) + table.insert(hier, { flags, start }) + end + elseif t == "bounds" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" or s == nil then + break + end + end + elseif t == "baseframe" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if s ~= "(" then + return nil, "bad baseframe line" + end + L.pos -= 1 + local p, q = vec(L, 3), vec(L, 3) + table.insert(a.base, { p[1], p[2], p[3], q[1], q[2], q[3] }) + end + elseif t == "frame" then + local fi = num(L) + expect(L, "{") + local vals = table.create(nComp, 0) + for k = 1, nComp do + vals[k] = num(L) + end + expect(L, "}") + if fi < 0 or fi > 2 ^ 20 then + return nil, "bad frame index" + end + frames[fi + 1] = vals + else + return nil, "unknown keyword " .. t + end + end + if L.err then + return nil, L.err + end + if version ~= 10 then + return nil, if version then "unsupported: MD5Version " .. version else "no MD5Version" + end + if #a.base ~= #a.joints then + return nil, "baseframe and hierarchy disagree" + end + for f = 1, a.frames do + if not frames[f] then + return nil, "missing frame " .. (f - 1) + end + end + for j, h in hier do + local tr: { number }, rot: { number } = {}, {} + local flags, start = h[1], h[2] + for f = 1, a.frames do + local v = table.clone(a.base[j]) + local k = start + 1 + for bit = 0, 5 do + if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then + v[bit + 1] = frames[f][k] or v[bit + 1] + k += 1 + end + end + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = quat(v[4], v[5], v[6]) + for c = 1, 4 do + table.insert(rot, q[c]) + end + end + a.tracks[j] = { translation = tr, rotation = rot } + end + return a, nil +end + +-- addAnim(scene, nodes by joint name, anim, name) -> channels added +function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim, name: string): number + local nodes: { number } = {} + local tracks: { [number]: Rig.Track } = {} + for j, jt in a.joints do + local nd = byName[jt.name] + if nd then + table.insert(nodes, nd) + tracks[#nodes] = a.tracks[j] + end + end + local times: { number } = {} + local rate = if a.frameRate > 0 then a.frameRate else 24 + for f = 1, a.frames do + times[f] = (f - 1) / rate + end + local ai = Rig.animation(scene, name, nodes, times, tracks, "LINEAR") + return #scene.animations[ai].channels +end + +-- animScene(a, name) -> a Scene of the animation's skeleton (baseframe pose) with the animation +function Read.animScene(a: Anim, name: string): Types.Scene + local scene = Scene.new() + scene.meta.up = "z" + table.insert(scene.nodes, { name = "md5", children = {} }) + scene.roots[1] = 1 + local list: { Rig.Joint } = {} + for j, jt in a.joints do + local b = a.base[j] + list[j] = { name = jt.name, parent = jt.parent, translation = { b[1], b[2], b[3] }, rotation = quat(b[4], b[5], b[6]) } + end + local nodes = Rig.skeleton(scene, list, "local", 1) + local byName: { [string]: number } = {} + for j, jt in a.joints do + byName[jt.name] = nodes[j] + end + Read.addAnim(scene, byName, a, name) + scene.meta.source = { format = "md5", kind = "anim", joints = #a.joints, frames = a.frames, frameRate = a.frameRate } + return scene +end + +return Read diff --git a/src/Formats/model/md5/init.luau b/src/Formats/model/md5/init.luau new file mode 100644 index 0000000..80f307a --- /dev/null +++ b/src/Formats/model/md5/init.luau @@ -0,0 +1,83 @@ +--!strict +-- model/md5: Doom 3 / Quake 4 MD5 models (MD5Version 10 text): .md5mesh (skeleton, skin, meshes) and .md5anim +-- (skeletal animation), read into a Scene through model/md5/Read. A .md5mesh loads its animations from +-- opts.anims = { "idle.md5anim", ... } (each found through opts.files[name] or opts.resolve(name); joints matched by +-- name; the animation is named after the file without its extension); a missing one fails with UNSUPPORTED unless +-- opts.skipMissing. A .md5anim alone loads as its skeleton (baseframe pose) with the animation. Units are Doom +-- units, z up. Not supported: writing, .md5camera. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Input = require("@formats/core/Input") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Read = require("@formats/model/md5/Read") + +-- ------------------------------------------------------------------------------------------------ contract +local Md5 = { + name = "md5", + category = "model", + extensions = { "md5mesh", "md5anim" }, + mime = { "model/x-md5mesh", "model/x-md5anim" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + anims: { string }?, -- .md5anim files to load with a .md5mesh + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + skipMissing: boolean?, -- ignore animations that cannot be found (default false: UNSUPPORTED) + name: string?, -- the file name (names a standalone animation) + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Md5.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 512, true) + head = string.gsub(head, "^//[^\n]*\n%s*", "") + return if string.match(head, "^MD5Version%s+%d+") then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function stem(name: string): string + local base = string.match(name, "([^/\\]+)$") or name + return (string.gsub(base, "%.[^.]*$", "")) +end + +function Md5.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = Sniff.dropBom(r:string(r:remaining())) + if string.find(text, "numAnimatedComponents", 1, true) then + local a, msg = Read.anim(text) + if not a then + return nil, Err.from(msg) + end + return Read.animScene(a, if opts and type(opts.name) == "string" then stem(opts.name) else "animation"), nil + end + local scene, byName = Read.mesh(text, opts :: any) + if not scene then + return nil, Err.from(byName) + end + if opts and type(opts.anims) == "table" then + for _, name in opts.anims do + local got = if type(name) == "string" then Input.sibling(opts, name) else nil + local src = if got then buffer.tostring(got) else nil + if not src then + if not opts.skipMissing then + return nil, Err.new(Err.UNSUPPORTED, "animation " .. tostring(name) .. " not available (opts.resolve / opts.files)") + end + else + local a, msg = Read.anim(Sniff.dropBom(src)) + if not a then + return nil, Err.from("animation " .. name .. ": " .. tostring(msg)) + end + Read.addAnim(scene, byName, a, stem(name)) + end + end + end + return scene, nil +end + +return Md5 diff --git a/src/Formats/model/mdl/HalfLife.luau b/src/Formats/model/mdl/HalfLife.luau new file mode 100644 index 0000000..53dbc01 --- /dev/null +++ b/src/Formats/model/mdl/HalfLife.luau @@ -0,0 +1,340 @@ +--!strict +-- model/mdl/HalfLife: Half-Life 1 (GoldSrc) studio models ("IDST" version 10) to a Scene. Written from the studio.h +-- layout of the Half-Life SDK and the format notes of the HLMV / Crowbar communities; no code taken. +-- Bones -> joint nodes and a Skin (bind pose from the bone defaults; Euler angles through Rig.angles), body parts -> +-- one mesh per body part (its first model, or opts.bodies[part]), its meshes -> primitives (triangle strips and fans +-- unrolled to counter-clockwise triangles; vertices transformed to model space by their bone's bind pose; JOINTS_0 = +-- that bone, WEIGHTS_0 = 1), textures (8-bit + their own palette) -> texture.image, the first skin family -> +-- materials, sequences of the main file -> animations (frames at the sequence's fps; the first blend only). +-- Not supported: sequence groups in other files (those sequences are listed in meta, without channels), bone +-- controllers, hitboxes / attachments / events (counted in meta), textures in a separate "t.mdl" (pass it +-- as opts.textures = that file's bytes). +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Pixels = require("@formats/codecs/image/Pixels") +local Rig = require("@formats/codecs/model/Rig") + +local HalfLife = {} + +local Scene = Types.Scene +local readi32, readi16, readu16, readu8, readf32 = buffer.readi32, buffer.readi16, buffer.readu16, buffer.readu8, buffer.readf32 +local writef32, writeu32, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu16 + +type Bone = { name: string, parent: number, value: { number }, scale: { number } } +export type Options = { bodies: { number }?, textures: buffer?, maxPixels: number?, maxVertices: number? } + +local function str(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +-- the textures of a studio header at base (this file or a separate texture file) -> { Image }, names | nil, message +local function textures(b: buffer, base: number, size: number, maxPixels: number): ({ Types.Image }?, { string } | string) + local n, at = readi32(b, base + 180), readi32(b, base + 184) + if n < 0 or n > 4096 or at < 0 or at + n * 80 > size then + return nil, "bad texture table" + end + local out: { Types.Image } = {} + local names: { string } = {} + for i = 0, n - 1 do + local o = base + at + i * 80 + local w, h, data = readi32(b, o + 68), readi32(b, o + 72), readi32(b, o + 76) + if w <= 0 or h <= 0 or w * h > maxPixels or data < 0 or data + w * h + 768 > size then + return nil, "bad texture " .. i + end + local img = Types.Image.new(w, h) + local pal = Pixels.palette(b, base + data + w * h, 256) + Pixels.indexed(b, base + data, w, 8, img.pixels, w, h, true, pal) + local flags = readi32(b, o + 64) + img.meta.source = { format = "mdl", flags = flags } + out[i + 1] = img + names[i + 1] = str(b, o, 64) + end + return out, names +end + +-- one animation value: bone default + stored value * scale (frame f, 0-based) +local function animValue(b: buffer, at: number, limit: number, f: number): number? + local p = at + local k = f + for _ = 1, 65536 do + if p + 2 > limit then + return nil + end + local valid, total = readu8(b, p), readu8(b, p + 1) + if total == 0 then + return nil + end + if total > k then + local idx = if valid > k then k + 1 else valid + if p + idx * 2 + 2 > limit then + return nil + end + return readi16(b, p + idx * 2) + end + k -= total + p += (valid + 1) * 2 + end + return nil +end + +-- decode(b, base, size, opts) -> Scene | nil, message +function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?) + if size < 244 then + return nil, "truncated header" + end + local limit = base + size + local function hdr(o: number): number + return readi32(b, base + o) + end + local nBones, oBones = hdr(140), hdr(144) + local nSeq, oSeq = hdr(164), hdr(168) + local nTex = hdr(180) + local nSkinRef, nFamilies, oSkins = hdr(192), hdr(196), hdr(200) + local nParts, oParts = hdr(204), hdr(208) + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if nBones < 0 or nBones > 256 or not inside(oBones, nBones * 112) then + return nil, "bad bone table" + end + if nSeq < 0 or nSeq > 4096 or not inside(oSeq, nSeq * 176) then + return nil, "bad sequence table" + end + if nParts < 0 or nParts > 256 or not inside(oParts, nParts * 76) then + return nil, "bad body part table" + end + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + local scene = Scene.new() + scene.meta.up = "z" + -- bones + local bones: { Bone } = {} + local joints: { Rig.Joint } = {} + for i = 0, nBones - 1 do + local o = base + oBones + i * 112 + local value, scale = {}, {} + for k = 0, 5 do + value[k + 1] = readf32(b, o + 64 + k * 4) + scale[k + 1] = readf32(b, o + 88 + k * 4) + end + local parent = readi32(b, o + 32) + bones[i + 1] = { name = str(b, o, 32), parent = parent + 1, value = value, scale = scale } + joints[i + 1] = { name = bones[i + 1].name, parent = parent + 1, translation = { value[1], value[2], value[3] }, rotation = Rig.angles(value[4], value[5], value[6]) } + end + local root: Types.Node = { name = str(b, base + 8, 64), children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local jointNodes, skinIndex, world = Rig.skeleton(scene, joints, "local", 1) + -- textures and skins + local texSrc, texBase, texSize = b, base, size + if nTex == 0 and opts and opts.textures then + texSrc, texBase, texSize = opts.textures, 0, buffer.len(opts.textures) + if texSize < 244 or buffer.readstring(texSrc, 0, 4) ~= "IDST" then + return nil, "opts.textures is not a studio texture file" + end + nSkinRef, nFamilies, oSkins = readi32(texSrc, 192), readi32(texSrc, 196), readi32(texSrc, 200) + end + local images, texNames = textures(texSrc, texBase, texSize, maxPixels) + if not images then + return nil, texNames :: string + end + local names = texNames :: { string } + for i, img in images do + table.insert(scene.textures, { name = names[i], image = img, uri = names[i] }) + local mat = Scene.material(names[i]) + mat.metallic = 0 + mat.baseColorTexture = { texture = i } + table.insert(scene.materials, mat) + end + local skinMap: { number } = {} + if nSkinRef > 0 and nFamilies > 0 and oSkins >= 0 and oSkins + nSkinRef * 2 <= texSize then + for r = 0, nSkinRef - 1 do + skinMap[r + 1] = readi16(texSrc, texBase + oSkins + r * 2) + 1 + end + end + -- body parts + local totalVerts = 0 + for part = 0, nParts - 1 do + local po = base + oParts + part * 76 + local pname = str(b, po, 64) + local nModels, oModels = readi32(b, po + 64), readi32(b, po + 72) + local pick = (opts and opts.bodies and opts.bodies[part + 1]) or 1 + if nModels > 0 and pick >= 1 and pick <= nModels and inside(oModels, nModels * 112) then + local mo = base + oModels + (pick - 1) * 112 + local nMesh, oMesh = readi32(b, mo + 72), readi32(b, mo + 76) + local nVerts, oVertInfo, oVerts = readi32(b, mo + 80), readi32(b, mo + 84), readi32(b, mo + 88) + local nNorms, oNormInfo, oNorms = readi32(b, mo + 92), readi32(b, mo + 96), readi32(b, mo + 100) + if nMesh < 0 or nMesh > 4096 or not inside(oMesh, nMesh * 20) or nVerts < 0 or not inside(oVertInfo, nVerts) or not inside(oVerts, nVerts * 12) or nNorms < 0 or not inside(oNormInfo, nNorms) or not inside(oNorms, nNorms * 12) then + return nil, "body part " .. pname .. ": bad model tables" + end + local mesh: Types.Mesh = { name = pname, primitives = {}, extras = { mdl = { model = str(b, mo, 64), models = nModels } } } + for m = 0, nMesh - 1 do + local me = base + oMesh + m * 20 + local oTri, skinref = readi32(b, me + 4), readi32(b, me + 8) + local tex = skinMap[skinref + 1] or (skinref + 1) + local img = images[tex] + local tw, th = if img then img.width else 1, if img then img.height else 1 + -- triangle commands + local weld: { [string]: number } = {} + local corners: { { number } } = {} + local indices: { number } = {} + local p = base + oTri + if oTri < 0 or oTri >= size then + return nil, "bad triangle command offset" + end + while true do + if p + 2 > limit then + return nil, "truncated triangle commands" + end + local n = readi16(b, p) + p += 2 + if n == 0 then + break + end + local fan = n < 0 + n = math.abs(n) + if p + n * 8 > limit then + return nil, "truncated triangle commands" + end + local ids: { number } = {} + for k = 0, n - 1 do + local o = p + k * 8 + local vi, ni, s, t = readu16(b, o), readu16(b, o + 2), readi16(b, o + 4), readi16(b, o + 6) + if vi >= nVerts or ni >= nNorms then + return nil, "triangle command vertex out of range" + end + local key = vi .. ":" .. ni .. ":" .. s .. ":" .. t + local id = weld[key] + if not id then + table.insert(corners, { vi, ni, s, t }) + id = #corners - 1 + weld[key] = id + end + ids[k + 1] = id + end + p += n * 8 + for k = 3, n do + local a, c2, c3 + if fan then + a, c2, c3 = ids[1], ids[k - 1], ids[k] + elseif k % 2 == 1 then + a, c2, c3 = ids[k - 2], ids[k - 1], ids[k] + else + a, c2, c3 = ids[k - 1], ids[k - 2], ids[k] + end + -- studio models wind clockwise: reverse + table.insert(indices, c3) + table.insert(indices, c2) + table.insert(indices, a) + end + end + local nv = #corners + totalVerts += nv + if totalVerts > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many vertices" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) + for i, c in corners do + local o = (i - 1) * 12 + local bone = readu8(b, base + oVertInfo + c[1]) + local nbone = readu8(b, base + oNormInfo + c[2]) + local vo, no = base + oVerts + c[1] * 12, base + oNorms + c[2] * 12 + local x, y, z = readf32(b, vo), readf32(b, vo + 4), readf32(b, vo + 8) + local m4 = world[bone + 1] + if m4 then + x, y, z = Mat4.point(m4, x, y, z) + end + writef32(pos, o, x) + writef32(pos, o + 4, y) + writef32(pos, o + 8, z) + local nx, ny, nz = readf32(b, no), readf32(b, no + 4), readf32(b, no + 8) + local n4 = world[nbone + 1] + if n4 then + nx, ny, nz = n4[1] * nx + n4[5] * ny + n4[9] * nz, n4[2] * nx + n4[6] * ny + n4[10] * nz, n4[3] * nx + n4[7] * ny + n4[11] * nz + end + writef32(nrm, o, nx) + writef32(nrm, o + 4, ny) + writef32(nrm, o + 8, nz) + writef32(uv, (i - 1) * 8, c[3] / tw) + writef32(uv, (i - 1) * 8 + 4, c[4] / th) + writeu16(jb, (i - 1) * 8, math.min(bone, math.max(0, nBones - 1))) + writef32(wb, (i - 1) * 16, 1) + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(nrm, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if nBones > 0 then + attrs.JOINTS_0 = Scene.accessor(jb, "u16", 4, nv) + attrs.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, nv) + end + table.insert(mesh.primitives, { + attributes = attrs, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles" :: any, + material = if img then tex else nil, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = pname, children = {}, mesh = #scene.meshes, skin = if nBones > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + end + -- sequences + local seqs: { any } = {} + for s = 0, nSeq - 1 do + local so = base + oSeq + s * 176 + local label, fps, nFrames = str(b, so, 32), readf32(b, so + 32), readi32(b, so + 56) + local nBlends, oAnim, group = readi32(b, so + 120), readi32(b, so + 124), readi32(b, so + 156) + table.insert(seqs, { name = label, fps = fps, frames = nFrames, blends = nBlends, group = group }) + if group == 0 and nFrames > 0 and nFrames <= 65536 and nBones > 0 and inside(oAnim, nBones * 12) then + local rate = if fps > 0 then fps else 30 + local times: { number } = {} + for f = 0, nFrames - 1 do + times[f + 1] = f / rate + end + local tracks: { [number]: Rig.Track } = {} + for j = 1, nBones do + local bn = bones[j] + local ao = base + oAnim + (j - 1) * 12 + local tr, rot = {}, {} + for f = 0, nFrames - 1 do + local v: { number } = {} + for k = 0, 5 do + local off = readu16(b, ao + k * 2) + local raw = if off ~= 0 then animValue(b, ao + off, limit, f) else nil + v[k + 1] = bn.value[k + 1] + (raw or 0) * bn.scale[k + 1] + end + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = Rig.angles(v[4], v[5], v[6]) + for k = 1, 4 do + table.insert(rot, q[k]) + end + end + tracks[j] = { translation = tr, rotation = rot } + end + Rig.animation(scene, label, jointNodes, times, tracks, "LINEAR") + end + end + scene.meta.source = { + format = "mdl", + variant = "halflife", + name = root.name, + bones = nBones, + sequences = seqs, + textures = #images, + skinFamilies = nFamilies, + hitboxes = hdr(156), + attachments = hdr(212), + } + return scene, nil +end + +return HalfLife diff --git a/src/Formats/model/mdl/Quake.luau b/src/Formats/model/mdl/Quake.luau new file mode 100644 index 0000000..c13a77e --- /dev/null +++ b/src/Formats/model/mdl/Quake.luau @@ -0,0 +1,222 @@ +--!strict +-- model/mdl/Quake: Quake 1 MDL ("IDPO" version 6) to a Scene. Written from the Quake specs (Olivier Montanuy et +-- al., "Quake Specs 3.4", section 5) and the modelgen.h layout of the Quake source release; no code taken. +-- Skins (single and grouped: the first picture of a group) become texture.image through a 768-byte palette; +-- texture coordinates on the seam of back-facing triangles move half a skin width (the vertices are welded per +-- side); simple and grouped frames become morph targets with one animation per frame-name group. +local Types = require("@formats/Types") +local Pixels = require("@formats/codecs/image/Pixels") +local Rig = require("@formats/codecs/model/Rig") + +local Quake = {} + +local Scene = Types.Scene +local readi32, readf32, readu8, writef32, writeu32 = buffer.readi32, buffer.readf32, buffer.readu8, buffer.writef32, buffer.writeu32 + +export type Options = { frame: number?, morph: boolean?, fps: number?, maxVertices: number?, maxPixels: number? } + +local function name16(b: buffer, at: number): string + return (string.match(buffer.readstring(b, at, 16), "^[^%z]*")) :: string +end + +-- decode(b, base, size, palette, opts) -> Scene | nil, message (offsets relative to base) +function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, opts: Options?): (Types.Scene?, string?) + if size < 84 then + return nil, "truncated header" + end + local scale = { readf32(b, base + 8), readf32(b, base + 12), readf32(b, base + 16) } + local origin = { readf32(b, base + 20), readf32(b, base + 24), readf32(b, base + 28) } + local nSkins, sw, sh = readi32(b, base + 48), readi32(b, base + 52), readi32(b, base + 56) + local nVerts, nTris, nFrames = readi32(b, base + 60), readi32(b, base + 64), readi32(b, base + 68) + if nSkins < 0 or sw < 0 or sh < 0 or nVerts <= 0 or nTris < 0 or nFrames <= 0 or nSkins > 1024 or nFrames > 65536 then + return nil, "bad counts" + end + if sw * sh > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: skin too big" + end + if nFrames * nVerts > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many vertices" + end + local p = 84 + local function need(n: number): boolean + return n >= 0 and p + n <= size + end + -- skins + local pal = if palette then Pixels.palette(palette, 0, 256) else nil + local skins: { Types.Image } = {} + local px = sw * sh + for _ = 1, nSkins do + if not need(4) then + return nil, "truncated skins" + end + local group = readi32(b, base + p) + p += 4 + local count = 1 + if group ~= 0 then + if not need(4) then + return nil, "truncated skin group" + end + count = readi32(b, base + p) + p += 4 + if count <= 0 or count > 256 or not need(count * 4) then + return nil, "bad skin group" + end + p += count * 4 + end + if not need(count * px) then + return nil, "truncated skin pixels" + end + local img = Types.Image.new(sw, sh) + if pal then + Pixels.indexed(b, base + p, sw, 8, img.pixels, sw, sh, true, pal) + else + for i = 0, px - 1 do + local v = readu8(b, base + p + i) + writeu32(img.pixels, i * 4, 0xFF000000 + v * 0x10101) + end + end + img.meta.source = { format = "mdl", palette = pal ~= nil, frames = count } + table.insert(skins, img) + p += count * px + end + -- texture coordinates and triangles + if not need(nVerts * 12 + nTris * 16) then + return nil, "truncated vertices / triangles" + end + local stAt = p + p += nVerts * 12 + local weld: { [number]: number } = {} + local src: { number }, uvs: { number } = {}, {} + local indices: { number } = {} + for t = 0, nTris - 1 do + local o = base + p + t * 16 + local front = readi32(b, o) ~= 0 + local c: { number } = {} + for k = 1, 3 do + local v = readi32(b, o + k * 4) + if v < 0 or v >= nVerts then + return nil, "triangle vertex out of range" + end + local so = base + stAt + v * 12 + local seam = readi32(b, so) ~= 0 and not front + local key = v * 2 + (if seam then 1 else 0) + local id = weld[key] + if not id then + table.insert(src, v) + local s = readi32(b, so + 4) + (if seam then sw / 2 else 0) + table.insert(uvs, (s + 0.5) / math.max(sw, 1)) + table.insert(uvs, (readi32(b, so + 8) + 0.5) / math.max(sh, 1)) + id = #src - 1 + weld[key] = id + end + c[k] = id + end + -- Quake's front faces are clockwise + table.insert(indices, c[3]) + table.insert(indices, c[2]) + table.insert(indices, c[1]) + end + p += nTris * 16 + -- frames: simple (type 0) or groups of simple frames + local frameAt: { number } = {} + local names: { string } = {} + local fsize = 24 + nVerts * 4 + for _ = 1, nFrames do + if not need(4) then + return nil, "truncated frames" + end + local kind = readi32(b, base + p) + p += 4 + if kind == 0 then + if not need(fsize) then + return nil, "truncated frame" + end + table.insert(frameAt, p + 8) + table.insert(names, name16(b, base + p + 8)) + p += fsize + else + if not need(12) then + return nil, "truncated frame group" + end + local count = readi32(b, base + p) + if count <= 0 or count > 4096 or not need(12 + count * 4 + count * fsize) then + return nil, "bad frame group" + end + p += 12 + count * 4 + for _ = 1, count do + table.insert(frameAt, p + 8) + table.insert(names, name16(b, base + p + 8)) + p += fsize + end + end + end + local nv = #src + local total = #frameAt + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, total) + local positions: { buffer }, normals: { buffer } = {}, {} + for f, at in frameAt do + if morph or f == want then + local pos = buffer.create(nv * 12) + local vo = base + at + 16 + for i, v in src do + for k = 0, 2 do + writef32(pos, (i - 1) * 12 + k * 4, readu8(b, vo + v * 4 + k) * scale[k + 1] + origin[k + 1]) + end + end + positions[f] = pos + normals[f] = Rig.normals(pos, nv, indices) + end + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local uvb = buffer.create(nv * 8) + for i, v in uvs do + writef32(uvb, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(positions[want], "f32", 3, nv), + NORMAL = Scene.accessor(normals[want], "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uvb, "f32", 2, nv), + }, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles", + } + local scene = Scene.new() + scene.meta.up = "z" + for i, img in skins do + table.insert(scene.textures, { name = "skin " .. i, image = img, sampler = { filter = "nearest" :: any } }) + end + if #skins > 0 then + local mat = Scene.material("skin") + mat.metallic = 0 + mat.baseColorTexture = { texture = 1 } + scene.materials[1] = mat + prim.material = 1 + end + scene.meshes[1] = { primitives = { prim } } + scene.nodes[1] = { children = {}, mesh = 1 } + scene.roots[1] = 1 + if morph then + Rig.morph(prim, positions, normals) + scene.meshes[1].weights = table.create(total, 0) + local ranges: { Rig.Range } = {} + for i, n in names do + local stem = string.match(n, "^(.-)%d*$") or n + local last = ranges[#ranges] + if last and last.name == stem then + last.last = i + else + table.insert(ranges, { name = if stem ~= "" then stem else n, first = i, last = i, fps = opts and opts.fps or 10 }) + end + end + Rig.morphAnimation(scene, 1, total, ranges, "LINEAR") + end + scene.meta.source = { format = "mdl", variant = "quake", frames = total, frameNames = names, skinWidth = sw, skinHeight = sh, palette = pal ~= nil } + return scene, nil +end + +return Quake diff --git a/src/Formats/model/mdl/init.luau b/src/Formats/model/mdl/init.luau new file mode 100644 index 0000000..ca3e9a9 --- /dev/null +++ b/src/Formats/model/mdl/init.luau @@ -0,0 +1,84 @@ +--!strict +-- model/mdl: Quake 1 ("IDPO" version 6: model/mdl/Quake) and Half-Life 1 / GoldSrc ("IDST" version 10: +-- model/mdl/HalfLife) models, read into a Scene. See the two submodules for what each maps. Quake skins need the +-- game's 768-byte palette (gfx/palette.lmp, not redistributable: never built in): opts.palette (a buffer / string), +-- else opts.resolve("gfx/palette.lmp") / opts.files["gfx/palette.lmp"], else a grey ramp (meta.source.palette = +-- false). Half-Life textures carry their own palettes. Source engine MDL ("IDST" version 44+, with .vvd / .vtx +-- files) is UNSUPPORTED. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Input = require("@formats/core/Input") +local Types = require("@formats/Types") +local Quake = require("@formats/model/mdl/Quake") +local HalfLife = require("@formats/model/mdl/HalfLife") + +-- ------------------------------------------------------------------------------------------------ contract +local Mdl = { + name = "mdl", + category = "model", + extensions = { "mdl" }, + mime = { "model/x-mdl" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + palette: (buffer | string)?, -- Quake: the 768-byte palette (default: resolved gfx/palette.lmp, else grey) + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + frame: number?, -- Quake: the frame used as the base POSITION (default 1) + morph: boolean?, -- Quake: frames as morph targets + animations (default true) + fps: number?, -- Quake: animation frame rate (default 10) + bodies: { number }?, -- Half-Life: the model picked for each body part (1-based, default 1) + textures: (buffer | string)?, -- Half-Life: the "t.mdl" texture file of a model without textures + maxPixels: number?, -- default 2^24 + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Mdl.sniff(r: Bytes.Reader): number + local m = r:peek(4) + local v = r:peekU8(4) + if (m == "IDPO" and v == 6) or (m == "IDST" and v == 10) then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if size < 8 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local magic, version = r:peek(4), buffer.readi32(r.buf, r.base + 4) + local scene: Types.Scene?, msg: string? + if magic == "IDPO" then + if version ~= 6 then + return nil, Err.new(Err.UNSUPPORTED, "Quake MDL version " .. version, 4) + end + local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp") + if pal and buffer.len(pal) < 768 then + pal = nil + end + scene, msg = Quake.decode(r.buf, r.base, size, pal, opts :: any) + elseif magic == "IDST" then + if version ~= 10 then + return nil, Err.new(Err.UNSUPPORTED, "studio model version " .. version .. " (Source engine models need .vvd / .vtx)", 4) + end + local o: any = opts and table.clone(opts :: any) or {} + o.textures = if opts and opts.textures then Bytes.toBuffer(opts.textures) else nil + scene, msg = HalfLife.decode(r.buf, r.base, size, o) + else + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +return Mdl diff --git a/src/Formats/model/smd/Read.luau b/src/Formats/model/smd/Read.luau new file mode 100644 index 0000000..7d1c725 --- /dev/null +++ b/src/Formats/model/smd/Read.luau @@ -0,0 +1,275 @@ +--!strict +-- model/smd/Read: Valve SMD text (GoldSrc / Source studiomdl input: version 1) to a Scene. Sections "nodes" (id, +-- "name", parent), "skeleton" ("time n" blocks of "bone px py pz rx ry rz", Euler radians, R = Rz Ry Rx; a bone +-- missing from a later frame keeps its previous pose), "triangles" (a material line, then three vertex lines "bone px +-- py pz nx ny nz u v [links (bone weight)...]": model-space positions, v up), "vertexanimation" (skipped, counted). +-- Bones -> joint nodes and a Skin (bind pose = the first skeleton frame), triangles -> one primitive per material +-- (welded vertices, counter-clockwise as stored, TEXCOORD_0 v flipped to top-left, JOINTS_0 / WEIGHTS_0: the links, +-- the rest of the weight to the parent bone; GoldSrc lines without links: the parent bone), skeleton frames beyond +-- the first -> one animation (opts.fps, default 30). An animation SMD (no triangles) is a skeleton + its animation. +local Types = require("@formats/Types") +local Rig = require("@formats/codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +export type Options = { fps: number?, name: string?, maxVertices: number? } + +type Bone = { id: number, name: string, parent: number } +local ZERO: { number } = { 0, 0, 0, 0, 0, 0 } + +-- read(text, opts) -> Scene | nil, message +function Read.read(text: string, opts: Options?): (Types.Scene?, string?) + local lines: { string } = {} + for line in string.gmatch(text, "[^\r\n]*") do + table.insert(lines, line) + end + local i = 1 + local n = #lines + local function nextLine(): string? + while i <= n do + local l = lines[i] + i += 1 + local s = string.match(l, "^%s*(.-)%s*$") :: string + s = string.gsub(s, "%s*//.*$", "") :: string + if s ~= "" then + return s + end + end + return nil + end + local bones: { Bone } = {} + local byId: { [number]: number } = {} -- SMD bone id -> index into bones (1-based) + local frames: { { [number]: { number } } } = {} -- frames[f][bone index] = { px, py, pz, rx, ry, rz } + local times: { number } = {} + type Batch = { name: string, keys: { [string]: number }, verts: { { number } }, indices: { number } } + local batches: { Batch } = {} + local byMat: { [string]: Batch } = {} + local version: number? = nil + local vertexAnimations = 0 + local maxV = opts and opts.maxVertices or 2 ^ 24 + local total = 0 + while true do + local l = nextLine() + if not l then + break + end + local kw = string.lower(string.match(l, "^(%S+)") or "") + if kw == "version" then + version = tonumber(string.match(l, "^%S+%s+(%S+)")) + elseif kw == "nodes" then + while true do + local s = nextLine() + if not s then + return nil, "truncated: nodes without end" + end + if string.lower(s) == "end" then + break + end + local id, name, parent = string.match(s, '^(%-?%d+)%s+"(.-)"%s+(%-?%d+)') + if not id then + id, name, parent = string.match(s, "^(%-?%d+)%s+(%S+)%s+(%-?%d+)") + end + if not id then + return nil, "bad node line: " .. s + end + table.insert(bones, { id = tonumber(id) :: number, name = name :: string, parent = tonumber(parent) :: number }) + byId[tonumber(id) :: number] = #bones + end + elseif kw == "skeleton" then + local cur: { [number]: { number } }? = nil + while true do + local s = nextLine() + if not s then + return nil, "truncated: skeleton without end" + end + local low = string.lower(s) + if low == "end" then + break + end + local tm = string.match(low, "^time%s+(%-?[%d%.]+)") + if tm then + local prev = frames[#frames] + local f: { [number]: { number } } = {} + if prev then + for k, v in prev do + f[k] = v + end + end + table.insert(frames, f) + table.insert(times, tonumber(tm) :: number) + cur = f + else + local nums: { number } = {} + for tok in string.gmatch(s, "%S+") do + table.insert(nums, tonumber(tok) or 0 / 0) + end + local bi = byId[nums[1]] + if not cur or #nums < 7 or not bi then + return nil, "bad skeleton line: " .. s + end + cur[bi] = { nums[2], nums[3], nums[4], nums[5], nums[6], nums[7] } + end + end + elseif kw == "triangles" then + while true do + local mat = nextLine() + if not mat then + return nil, "truncated: triangles without end" + end + if string.lower(mat) == "end" then + break + end + local b = byMat[mat] + if not b then + b = { name = mat, keys = {}, verts = {}, indices = {} } + byMat[mat] = b + table.insert(batches, b) + end + for _ = 1, 3 do + local s = nextLine() + if not s then + return nil, "truncated triangle" + end + local nums: { number } = {} + for tok in string.gmatch(s, "%S+") do + local v = tonumber(tok) + if not v then + return nil, "bad vertex line: " .. s + end + table.insert(nums, v) + end + if #nums < 9 then + return nil, "short vertex line: " .. s + end + local id = b.keys[s] + if not id then + total += 1 + if total > maxV then + return nil, "limit: too many vertices" + end + table.insert(b.verts, nums) + id = #b.verts - 1 + b.keys[s] = id + end + table.insert(b.indices, id) + end + end + elseif kw == "vertexanimation" then + vertexAnimations += 1 + while true do + local s = nextLine() + if not s or string.lower(s) == "end" then + break + end + end + else + return nil, "unknown section " .. kw + end + end + if version ~= 1 then + return nil, if version == nil then "no version line" else "unsupported: SMD version " .. tostring(version) + end + local scene = Scene.new() + scene.meta.up = "z" + local root: Types.Node = { name = opts and opts.name or "smd", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + -- skeleton (bind pose: the first frame) + local joints: { Rig.Joint } = {} + local bind: { [number]: { number } } = frames[1] or {} + for k, bn in bones do + local v: { number } = bind[k] or ZERO + local parent = if bn.parent >= 0 then byId[bn.parent] or 0 else 0 + joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) } + end + local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1) + -- meshes + if #batches > 0 then + local mesh: Types.Mesh = { primitives = {} } + for _, b in batches do + local nv = #b.verts + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local lists: { { number } } = {} + for vi, v in b.verts do + local o = (vi - 1) * 12 + writef32(pos, o, v[2]) + writef32(pos, o + 4, v[3]) + writef32(pos, o + 8, v[4]) + writef32(nrm, o, v[5]) + writef32(nrm, o + 4, v[6]) + writef32(nrm, o + 8, v[7]) + writef32(uv, (vi - 1) * 8, v[8]) + writef32(uv, (vi - 1) * 8 + 4, 1 - v[9]) + local l: { number } = {} + local sum = 0 + local nl = if #v >= 10 then math.floor(v[10]) else 0 + for k = 0, nl - 1 do + local bi, w = byId[v[11 + k * 2]], v[12 + k * 2] + if bi and w then + table.insert(l, bi - 1) + table.insert(l, w) + sum += w + end + end + local parent = byId[v[1]] + if parent and sum < 0.999 then + table.insert(l, parent - 1) + table.insert(l, 1 - sum) + end + lists[vi] = l + end + local ib = buffer.create(#b.indices * 4) + for k, id in b.indices do + writeu32(ib, (k - 1) * 4, id) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(nrm, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if #bones > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local mat = Scene.material(b.name) + mat.metallic = 0 + table.insert(scene.textures, { name = b.name, uri = b.name }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #b.indices), mode = "triangles" :: any, material = #scene.materials }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #bones > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + -- animation + if #frames > 1 or (#frames == 1 and #batches == 0) then + local fps = opts and opts.fps or 30 + local t: { number } = {} + for k, tm in times do + t[k] = (tm - times[1]) / fps + end + local tracks: { [number]: Rig.Track } = {} + for k = 1, #bones do + local tr: { number }, rot: { number } = {}, {} + for _, f in frames do + local v: { number } = f[k] or bind[k] or ZERO + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = Rig.angles(v[4], v[5], v[6]) + for c = 1, 4 do + table.insert(rot, q[c]) + end + end + tracks[k] = { translation = tr, rotation = rot } + end + Rig.animation(scene, opts and opts.name or "animation", jointNodes, t, tracks, "LINEAR") + end + scene.meta.source = { format = "smd", version = version, bones = #bones, frames = #frames, vertexAnimations = vertexAnimations, kind = if #batches > 0 then "reference" else "animation" } + return scene, nil +end + +return Read diff --git a/src/Formats/model/smd/Write.luau b/src/Formats/model/smd/Write.luau new file mode 100644 index 0000000..ed5c2bc --- /dev/null +++ b/src/Formats/model/smd/Write.luau @@ -0,0 +1,250 @@ +--!strict +-- model/smd/Write: a Scene to Valve SMD text (version 1). Bones: the joints of the first skin (parents from the node +-- tree: the nearest ancestor that is also a joint), or one "root" bone for a static scene; "skeleton": the bind pose +-- (each joint node's TRS: rotation as Euler radians, R = Rz Ry Rx), or, with opts.animation = i, that animation sampled +-- at its key times (translation / scale linearly, rotation by normalised linear interpolation); "triangles": every +-- triangle of the scene in world space (codecs/model/MeshFlatten), one material line per triangle (the material +-- name, else "default"), vertex lines with the Source links (opts.links ~= false; GoldSrc style otherwise: the +-- strongest joint as the parent bone only). Animation SMDs (opts.animation set) carry no triangles unless +-- opts.triangles is true. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") + +local Write = {} + +export type Options = { animation: number?, links: boolean?, triangles: boolean? } + +local fmt = string.format + +local function num(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + local s = fmt("%.6f", v) + if s == "-0.000000" then + return "0.000000" + end + return s +end + +-- quaternion -> x, y, z Euler radians with R = Rz(z) Ry(y) Rx(x) +local function angles(q: { number }): (number, number, number) + local m = Mat4.fromQuat(q) + local r31, r32, r33, r21, r11 = m[3], m[7], m[11], m[2], m[1] + local y = math.asin(math.clamp(-r31, -1, 1)) + local x, z + if math.abs(r31) < 0.9999999 then + x = math.atan2(r32, r33) + z = math.atan2(r21, r11) + else + x = math.atan2(-m[10], m[6]) + z = 0 + end + return x, y, z +end + +local function lerp(a: { number }, b: { number }, t: number): { number } + local out: { number } = {} + for i = 1, #a do + out[i] = a[i] + (b[i] - a[i]) * t + end + return out +end + +-- the value of channel ch at time tm (nil when the channel has no keys) +local function sample(ch: Types.Channel, tm: number): { number }? + local input, output = ch.input, ch.output + local n = input.count + if n == 0 then + return nil + end + local comps = if ch.path == "rotation" then 4 else 3 + local function key(k: number): { number } + local out: { number } = {} + for c = 0, comps - 1 do + out[c + 1] = buffer.readf32(output.data, (k * comps + c) * 4) + end + return out + end + local times = input.data + if tm <= buffer.readf32(times, 0) then + return key(0) + end + for k = 1, n - 1 do + local t1 = buffer.readf32(times, k * 4) + if tm <= t1 then + local t0 = buffer.readf32(times, (k - 1) * 4) + local f = if ch.interpolation == "STEP" or t1 <= t0 then 0 else (tm - t0) / (t1 - t0) + local a, b = key(k - 1), key(k) + if comps == 4 then + if a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] < 0 then + b = { -b[1], -b[2], -b[3], -b[4] } + end + local q = lerp(a, b, f) + local l = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + return if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else a + end + return lerp(a, b, f) + end + end + return key(n - 1) +end + +-- write(scene, opts) -> text | nil, message +function Write.write(scene: Types.Scene, opts: Options?): (string?, string?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, "expected a Scene" + end + local out: { string } = { "version 1", "nodes" } + local skin = scene.skins and scene.skins[1] + local joints: { number } = if skin then skin.joints else {} + local jointOf: { [number]: number } = {} -- node index -> bone id (0-based) + for k, nd in joints do + jointOf[nd] = k - 1 + end + local parentOf: { [number]: number } = {} + for ni, nd in scene.nodes do + for _, c in nd.children do + parentOf[c] = ni + end + end + if #joints == 0 then + table.insert(out, '0 "root" -1') + else + for k, nd in joints do + local p = parentOf[nd] + while p and jointOf[p] == nil do + p = parentOf[p] + end + local name = scene.nodes[nd] and scene.nodes[nd].name or ("bone" .. (k - 1)) + table.insert(out, fmt('%d "%s" %d', k - 1, string.gsub(name, '"', "'"), if p then jointOf[p] else -1)) + end + end + table.insert(out, "end") + table.insert(out, "skeleton") + local function pose(tr: { number }?, rot: { number }?): string + local t = tr or { 0, 0, 0 } + local x, y, z = angles(rot or { 0, 0, 0, 1 }) + return table.concat({ num(t[1]), num(t[2]), num(t[3]), num(x), num(y), num(z) }, " ") + end + local animIndex = opts and opts.animation + local anim = animIndex and scene.animations[animIndex] + if animIndex and not anim then + return nil, "no animation " .. tostring(animIndex) + end + if anim then + local keyset: { [number]: boolean } = {} + for _, ch in anim.channels do + for k = 0, ch.input.count - 1 do + keyset[buffer.readf32(ch.input.data, k * 4)] = true + end + end + local keys: { number } = {} + for tm in keyset do + table.insert(keys, tm) + end + table.sort(keys) + local byNode: { [number]: { [string]: Types.Channel } } = {} + for _, ch in anim.channels do + local m = byNode[ch.node] or {} + byNode[ch.node] = m + m[ch.path] = ch + end + for f, tm in keys do + table.insert(out, "time " .. (f - 1)) + for k, nd in joints do + local node = scene.nodes[nd] + local chs: { [string]: Types.Channel } = byNode[nd] or {} + local tch, rch = chs.translation, chs.rotation + local tr = if tch then sample(tch, tm) else node.translation + local rot = if rch then sample(rch, tm) else node.rotation + table.insert(out, (k - 1) .. " " .. pose(tr, rot)) + end + end + else + table.insert(out, "time 0") + if #joints == 0 then + table.insert(out, "0 " .. pose(nil, nil)) + else + for k, nd in joints do + local node = scene.nodes[nd] + local tr, rot = node.translation, node.rotation + if node.matrix then + local t, r = Mat4.decompose(node.matrix) + tr, rot = t, r + end + table.insert(out, (k - 1) .. " " .. pose(tr, rot)) + end + end + end + table.insert(out, "end") + -- triangles + if not anim or (opts and opts.triangles) then + local m, err = Flatten.merge(scene, function(name: string): boolean + return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0" + end, { triangulate = true }) + if not m then + return nil, err + end + local A = m.attrs + local P, N, UV, J, W = A.POSITION, A.NORMAL, A.TEXCOORD_0, A.JOINTS_0, A.WEIGHTS_0 + local links = not (opts and opts.links == false) + local nbones = math.max(1, #joints) + if #m.corners > 0 then + table.insert(out, "triangles") + for _, part in m.parts do + local mat = part.prim.material and scene.materials[part.prim.material] + local mname = if mat and mat.name and mat.name ~= "" then mat.name else "default" + for f = part.firstFace, part.firstFace + part.faceCount - 1 do + table.insert(out, mname) + for c = 0, 2 do + local v = m.corners[f * 3 + c + 1] + local px, py, pz = P.values[v * 3 + 1], P.values[v * 3 + 2], P.values[v * 3 + 3] + local nx, ny, nz = 0, 0, 1 + if N then + nx, ny, nz = N.values[v * 3 + 1], N.values[v * 3 + 2], N.values[v * 3 + 3] + end + local u, w = 0, 0 + if UV then + local k = UV.components + u, w = UV.values[v * k + 1], UV.values[v * k + 2] + end + local parent = 0 + local lk: { string } = {} + if J and W and #joints > 0 then + local jk, wk = J.components, W.components + local best, bestW = 0, -1 + local count = 0 + for c2 = 1, math.min(4, jk, wk) do + local jw = W.values[v * wk + c2] + local jj = math.clamp(math.floor(J.values[v * jk + c2] or 0), 0, nbones - 1) + if jw and jw > 0 then + count += 1 + table.insert(lk, fmt("%d %s", jj, num(jw))) + if jw > bestW then + best, bestW = jj, jw + end + end + end + parent = best + if count > 0 then + table.insert(lk, 1, tostring(count)) + end + end + local line = fmt("%d %s %s %s %s %s %s %s %s", parent, num(px), num(py), num(pz), num(nx), num(ny), num(nz), num(u), num(1 - w)) + if links and #lk > 0 then + line ..= " " .. table.concat(lk, " ") + end + table.insert(out, line) + end + end + end + table.insert(out, "end") + end + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write diff --git a/src/Formats/model/smd/init.luau b/src/Formats/model/smd/init.luau new file mode 100644 index 0000000..8df0ce5 --- /dev/null +++ b/src/Formats/model/smd/init.luau @@ -0,0 +1,69 @@ +--!strict +-- model/smd: Valve SMD (studiomdl data, GoldSrc and Source: "version 1" text), read and write. Written from the +-- Valve Developer Community "SMD file format" page; no code taken. Read: model/smd/Read (bones -> joint nodes + a +-- Skin, triangles -> a primitive per material with JOINTS_0 / WEIGHTS_0, skeleton frames -> an animation; animation +-- SMDs too). Write: model/smd/Write (the first skin's joints or one root bone, the bind pose or opts.animation, +-- world-space triangles with Source weight links). Units as stored (inches in Valve's games), z up. +-- Not supported: vertex animation (flex) sections (skipped, counted in meta.source.vertexAnimations). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Read = require("@formats/model/smd/Read") +local Write = require("@formats/model/smd/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Smd = { + name = "smd", + category = "model", + extensions = { "smd" }, + mime = { "model/x-smd", "text/plain" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" }, + caps = { decode = true, encode = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + fps: number?, -- skeleton frames per second (default 30) + name: string?, -- the root node / animation name (the api passes the file name) + maxVertices: number?, -- default 2^24 +} +export type EncodeOptions = Write.Options + +-- ------------------------------------------------------------------------------------------------ sniff +function Smd.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 256, true) + head = string.gsub(head, "^//[^\n]*\n%s*", "") + if string.match(head, "^version%s+1%s") and string.find(head, "nodes", 1, true) then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Smd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = Sniff.dropBom(r:string(r:remaining())) + local o: any = opts and table.clone(opts :: any) or {} + if type(o.name) == "string" then + o.name = string.match(o.name, "([^/\\]+)$") or o.name + o.name = string.gsub(o.name, "%.[sS][mM][dD]$", "") + end + local scene, msg = Read.read(text, o) + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Smd.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local text, msg = Write.write(scene, opts) + if not text then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return buffer.fromstring(text), nil +end + +return Smd diff --git a/tests/archive/grp.luau b/tests/archive/grp.luau new file mode 100644 index 0000000..0a11a97 --- /dev/null +++ b/tests/archive/grp.luau @@ -0,0 +1,64 @@ +-- archive/grp tests: Build GRP archives written by tools/fixtures/grp.py list the entries an independent Python +-- reader sees (names, sizes, data CRCs); our writer produces the same bytes as the Python writer and round-trips; +-- conversion from a zip; errors; the fuzz pass. Fixtures: tools/fixtures/grp.py. +local T = require("@tests/T") +local F = require("@formats") +local Grp = require("@formats/archive/grp") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/grp") + +local t = T.suite("grp") +t:eq(Grp.name, "grp", "name") + +for _, c in Fx do + local a, err = Grp.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + local list = a:list() + t:eq(#list, #c.entries, c.name .. ": entry count") + for i, w in c.entries do + t:eq(list[i].name, w.name, c.name .. ": name " .. i) + t:eq(list[i].size, w.size, c.name .. ": size " .. w.name) + t:eq(Crc32.of((a:read(w.name))), w.crc, c.name .. ": data " .. w.name) + end + t:eq(F.detect(c.data), "grp", c.name .. ": F.detect") + local n = Grp.new() + for _, f in c.files do + n:add(f.name, f.data) + end + t:check(buffer.tostring(n:write() :: buffer) == c.data, c.name .. ": bytes identical to the Python writer") + t:check(buffer.tostring(F.save(a) :: buffer) == c.data, c.name .. ": decode + F.save is lossless") +end + +do + local zip = F.format("zip").create() + zip:add("readme.txt", "hi") + local g = F.load(F.save(zip, nil, { format = "grp", upper = true }) :: buffer) + t:check(g.format == "grp" and g:list()[1].name == "README.TXT", "zip -> grp, upper-cased") + local c = Fx[1] + local _, e1 = Grp.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, #c.data - 1)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local _, e2 = Grp.decode(Bytes.reader(buffer.fromstring("KenSilverman\255\255\255\255"))) + t:check(e2 and e2.code == Err.LIMIT, "count limit: " .. tostring(e2)) + local long = Grp.new() + long:add("THIRTEEN.CHAR", "x") + local _, e3 = long:write() + t:check(e3 and e3.code == Err.ARG, "a 13-byte name does not fit") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local a = Grp.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + return a +end, samples, { mutations = 40 }) + +t:done() diff --git a/tests/archive/mpq.luau b/tests/archive/mpq.luau new file mode 100644 index 0000000..37cff05 --- /dev/null +++ b/tests/archive/mpq.luau @@ -0,0 +1,127 @@ +-- archive/mpq tests: archives written by StormLib (tools/fixtures/mpq.py; header versions 1-4) list every file and +-- read back its exact bytes: zlib, PKWARE implode, bzip2, LZMA and sparse sectors, imploded files, single-unit, +-- stored, encrypted (plain and fix-key) and sector-CRC files; a prefixed archive; an archive without a listfile +-- (names by block index, opts.names); Huffman sectors are UNSUPPORTED; the hash helper; errors; the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Mpq = require("@formats/archive/mpq") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/mpq") + +local t = T.suite("mpq") +t:eq(Mpq.name, "mpq", "name") +-- the classic test vector: the hash table key +t:eq(Mpq.hash("(hash table)", 3), 0xC3AF3770, "hash of (hash table)") +t:eq(Mpq.hash("(block table)", 3), 0xEC83B3A3, "hash of (block table)") + +for _, c in Fx.archives do + local a, err = Mpq.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "mpq", c.name .. ": F.detect") + local by = {} + for _, e in a:list() do + by[e.name] = e + end + local ok = 0 + for _, w in c.files do + if c.unnamed then + continue + end + local e = by[w.name] + t:check(e, c.name .. ": has " .. w.name) + if w.size > 0 then + local b, rerr = a:read(w.name) + if w.huffman then + t:check(rerr and rerr.code == Err.UNSUPPORTED, c.name .. ": " .. w.name .. ": Huffman is unsupported: " .. tostring(rerr)) + else + t:check(b, c.name .. ": read " .. w.name .. ": " .. tostring(rerr)) + t:eq(e.size, w.size, c.name .. ": size " .. w.name) + t:eq(Crc32.of(b), w.crc, c.name .. ": data " .. w.name) + ok += 1 + end + end + end + if c.unnamed then + -- no listfile: unnamed entries; unencrypted ones read by block index, names through opts.names + local n = 0 + for _, e in a:list() do + if string.match(e.name, "^File%d+%.xxx$") then + n += 1 + local b, rerr = a:read(e.name) + if (e :: any).encrypted then + t:check(rerr and rerr.code == Err.UNSUPPORTED, c.name .. ": encrypted without a name") + else + t:check(b, c.name .. ": read " .. e.name .. ": " .. tostring(rerr)) + end + end + end + t:check(n > 0, c.name .. ": entries named by block index") + local names = {} + for _, w in c.files do + table.insert(names, w.name) + end + local b = Mpq.decode(Bytes.reader(buffer.fromstring(c.data)), { names = names }) :: any + for _, w in c.files do + if w.size > 0 then + t:eq(Crc32.of((b:read(w.name))), w.crc, c.name .. ": opts.names " .. w.name) + end + end + end + t:note("%-9s v%d, %2d entries, %2d files checked", c.name, a.meta.source.version, #a:list(), ok) +end + +-- errors +do + local c = Fx.archives[1] + local _, e1 = Mpq.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 200)))) + t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "truncated: " .. tostring(e1)) + local _, e2 = Mpq.decode(Bytes.reader(buffer.fromstring(string.rep("x", 64)))) + t:check(e2 and e2.code == Err.CORRUPT, "no header") + local a = Mpq.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + local _, e3 = a:write() + t:check(e3 and e3.code == Err.UNSUPPORTED, "read-only") +end + +local samples = {} +for _, c in Fx.archives do + if c.name == "v1" or c.name == "nolist" or c.name == "v4" then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + local a = Mpq.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + return a +end, samples, { mutations = 60 }) +do + -- mutations inside the file data (the tables intact) + local c = Fx.archives[1] + local rand = T.rng(5) + local threw = 0 + for _ = 1, 80 do + local b = buffer.fromstring(c.data) + for _ = 1, 1 + rand(8) do + buffer.writeu8(b, 32 + rand(#c.data // 2), rand(256)) + end + local ok = pcall(function() + local a = Mpq.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + end) + if not ok then + threw += 1 + end + end + t:eq(threw, 0, "mutated file data never throws") +end + +t:done() diff --git a/tests/archive/vpk.luau b/tests/archive/vpk.luau new file mode 100644 index 0000000..fe92edf --- /dev/null +++ b/tests/archive/vpk.luau @@ -0,0 +1,132 @@ +-- archive/vpk tests: version 1 and 2 directory files written by Python's vpk package list the entries it reads back +-- (names, sizes, CRC-32s); a multi-part archive (part files through opts.files and opts.resolve, preload bytes, an +-- embedded entry); our writer's version 1 / 2 output read back by the vpk package (MD5 verify for version 2) and by +-- us; CRC checks; errors; the fuzz pass. Fixtures: tools/fixtures/vpk.py. +local T = require("@tests/T") +local F = require("@formats") +local Vpk = require("@formats/archive/vpk") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/vpk") +local Src = require("@tests/gen/vpk_src") + +local t = T.suite("vpk") +t:eq(Vpk.name, "vpk", "name") + +local function check(a: any, want: { any }, label: string) + local by = {} + for _, e in a:list() do + by[e.name] = e + end + t:eq(#a:list(), #want, label .. ": entry count") + for _, w in want do + local e = by[w.name] + t:check(e, label .. ": has " .. w.name) + if e then + t:eq(e.size, w.size, label .. ": size " .. w.name) + local b, err = a:read(w.name) + t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err)) + t:eq(Crc32.of(b), w.crc, label .. ": data " .. w.name) + end + end +end + +-- 1. Python's vpk package +for _, c in Fx.cases do + local a, err = Vpk.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + check(a, c.entries, c.name) + t:eq(a.meta.source.version, c.version, c.name .. ": version") + t:eq(F.detect(c.data), "vpk", c.name .. ": F.detect") + if c.version == 2 then + t:check(a.meta.source.v2.fileMd5 and #a.meta.source.v2.fileMd5 == 16, c.name .. ": MD5 section") + end +end + +-- 2. multi-part +do + local m = Fx.multi + local a = Vpk.decode(Bytes.reader(buffer.fromstring(m.dir)), { files = m.parts, name = "maps/pak01_dir.vpk" }) + check(a, m.entries, "multi (opts.files)") + t:eq(#a.meta.source.parts, 2, "two part files") + local asked = {} + local b = Vpk.decode(Bytes.reader(buffer.fromstring(m.dir)), { + resolve = function(name: string): string? + table.insert(asked, name) + return m.parts[name] + end, + }) + check(b, m.entries, "multi (opts.resolve, default pak01 name)") + t:check(table.find(asked, "pak01_001.vpk") ~= nil, "resolve gets the part file name") + local c = Vpk.decode(Bytes.reader(buffer.fromstring(m.dir))) + local _, e = c:read("materials/a.vmt") + t:check(e and e.code == Err.UNSUPPORTED, "missing part: " .. tostring(e)) + t:eq(buffer.tostring((c:read("root.txt"))), "embedded", "embedded entry without the parts") + -- multi-part -> single file + local one = F.load(F.save(b) :: buffer) + check(one, m.entries, "multi -> one directory file") +end + +-- 3. our writer, read back by the vpk package and by us +for k, v in Fx.ours do + t:check(v.ok, k .. ": the vpk package verifies our MD5s") + t:eq(#v.entries, #Fx.want, k .. ": the vpk package lists every entry") + for i, w in Fx.want do + local g = v.entries[i] + t:check(g and g.name == w.name and g.size == w.size and g.crc == w.crc, k .. ": " .. w.name) + end + local a = Vpk.new(v.version) + for _, f in Src do + a:add(f.name, f.data) + end + check(Vpk.decode(Bytes.reader(a:write() :: buffer)), Fx.want, k .. ": round trip") +end + +-- 4. errors +do + local c = Fx.cases[2] + local bad = buffer.fromstring(c.data) + -- flip a byte in the last entry's data (before the 48-byte MD5 section) + local at = #c.data - 49 + buffer.writeu8(bad, at, bit32.bxor(buffer.readu8(bad, at), 0xFF)) + local a = Vpk.decode(Bytes.reader(bad)) + local failed = 0 + for _, e in a:list() do + local _, err = a:read(e.name) + if err and err.code == Err.CHECKSUM then + failed += 1 + end + end + t:eq(failed, 1, "a damaged entry fails its CRC") + local nv = Vpk.decode(Bytes.reader(bad), { verify = false }) + local ok = true + for _, e in nv:list() do + ok = ok and nv:read(e.name) ~= nil + end + t:check(ok, "verify = false") + local _, e1 = Vpk.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 40)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated tree: " .. tostring(e1)) + local v3 = buffer.fromstring(c.data) + buffer.writeu32(v3, 4, 3) + local _, e2 = Vpk.decode(Bytes.reader(v3)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 3") + local _, e3 = Vpk.new(3):write() + t:check(e3 and e3.code == Err.ARG, "write version 3") +end + +local samples = { Fx.multi.dir } +for _, c in Fx.cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local a = Vpk.decode(Bytes.reader(b), { files = Fx.multi.parts }) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + return a +end, samples, { mutations = 60 }) + +t:done() diff --git a/tests/archive/wad.luau b/tests/archive/wad.luau new file mode 100644 index 0000000..52ef1f3 --- /dev/null +++ b/tests/archive/wad.luau @@ -0,0 +1,247 @@ +-- archive/wad tests: a cut-down Freedoom IWAD (tools/fixtures/wad.py) lists its lumps (names, sizes, data CRCs, +-- namespaces, map lumps as "MAP01/THINGS"); every flat, patch, sprite and graphic decodes to the pixels DeuTex +-- extracts (RGBA CRC, offsets); composed wall textures; MAP01 parses to the counts of an independent parse and its +-- Scene's floor area matches Green's theorem over the sectors' sides; a hand-made room with a pillar (exact areas, +-- walls, things on floors), a UDMF stub, duplicate names, a tall patch; the writer round-trips byte for byte; +-- errors; the fuzz pass. Fixtures: tools/fixtures/wad.py. +local T = require("@tests/T") +local F = require("@formats") +local Wad = require("@formats/archive/wad") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/wad") + +local t = T.suite("wad") +t:eq(Wad.name, "wad", "name") + +local fd = Fx.freedoom +local a, err = Wad.decode(Bytes.reader(buffer.fromstring(fd.data))) +t:check(a, "freedoom: " .. tostring(err)) +t:eq(F.detect(fd.data), "wad", "F.detect") +t:eq(a.meta.source.type, "IWAD", "IWAD") + +-- 1. lumps +do + local lumps = Wad.lumps(a) :: { Wad.Lump } + t:eq(#lumps, #fd.lumps, "lump count") + local list = a:list() + for i, w in fd.lumps do + t:eq(lumps[i].name, w.name, "lump " .. i) + t:eq(lumps[i].size, w.size, "size " .. w.name) + t:eq(Crc32.of((a:read(list[i].name))), w.crc, "data " .. w.name) + end + t:eq(list[2].name, "MAP01/THINGS", "map lumps are named after their map") + t:eq(lumps[2].map, "MAP01", "map membership") + t:check(lumps[1].marker, "map marker") + local byName = {} + for _, l in lumps do + byName[l.name] = l + end + t:eq(byName.BLOOD1.namespace, "flats", "flats namespace") + t:eq(byName.BOS2A1.namespace, "sprites", "sprites namespace") + t:eq(byName.AG128_1.namespace, "patches", "patches namespace") + t:eq(byName.PLAYPAL.namespace, nil, "no namespace") + t:eq(#Wad.maps(a), 1, "one map") +end + +-- 2. images against DeuTex +do + local n = 0 + for _, w in fd.images do + local img, e = Wad.image(a, w.name) + t:check(img, w.name .. ": " .. tostring(e)) + t:eq(img.width, w.width, w.name .. ": width") + t:eq(img.height, w.height, w.name .. ": height") + if w.kind == "flats" then + t:eq(Crc32.of(img.pixels), w.crc, w.name .. ": flat pixels against DeuTex") + else + t:eq(Crc32.of(img.pixels), w.crc, w.name .. ": picture pixels against DeuTex") + if w.left then + t:eq(img.meta.offset[1], w.left, w.name .. ": left offset") + t:eq(img.meta.offset[2], w.top, w.name .. ": top offset") + end + end + n += 1 + end + t:note("%d graphics match DeuTex", n) + for _, tx in fd.textures do + local img, e = Wad.texture(a, tx.name) + t:check(img, tx.name .. ": " .. tostring(e)) + t:check(img.width == tx.width and img.height == tx.height, tx.name .. ": texture size") + t:eq(img.meta.source.patches, #tx.patches, tx.name .. ": patch count") + end +end + +-- 3. MAP01 +do + local m = Wad.mapData(a, "MAP01") :: any + local r = fd.map + t:eq(#m.things, r.things, "things") + t:eq(#m.linedefs, r.linedefs, "linedefs") + t:eq(#m.sidedefs, r.sidedefs, "sidedefs") + t:eq(#m.vertices // 2, r.vertices, "vertices") + t:eq(#m.sectors, r.sectors, "sectors") + for i, th in r.thingList do + local g = m.things[i] + t:check(g.x == th.x and g.y == th.y and g.type == th.type and g.angle == th.angle, "thing " .. i) + end + local t0 = T.clock() + local s, e = Wad.map(a, "MAP01") + t:check(s, "map scene: " .. tostring(e)) + local floor, nprim = 0, 0 + for _, p in s.meshes[1].primitives do + nprim += 1 + local pos = Types.Scene.reader(p.attributes.POSITION) :: any + local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any + for k = 0, p.attributes.POSITION.count - 1, 3 do + if nrm(k, 2) > 0.5 then + local ax, ay, bx, by, cx, cy = pos(k, 0), pos(k, 1), pos(k + 1, 0), pos(k + 1, 1), pos(k + 2, 0), pos(k + 2, 1) + floor += ((bx - ax) * (cy - ay) - (by - ay) * (cx - ax)) / 2 + end + end + end + t:check(math.abs(floor - r.floorArea) <= r.floorArea * 0.01, string.format("floor area %.0f vs %.0f", floor, r.floorArea)) + t:check(#s.nodes == 1 + r.things, "a node per thing") + t:eq(s.meta.up, "z", "z up") + local withImage = 0 + for _, tex in s.textures do + if tex.image then + withImage += 1 + end + end + t:note("MAP01: %d primitives, %d textures (%d with images in the cut-down WAD), floor area %.0f of %.0f, %.2f s", nprim, #s.textures, withImage, floor, r.floorArea, T.clock() - t0) + local lean = Wad.map(a, "MAP01", { textures = false }) :: any + t:check(lean.textures[1].image == nil and lean.textures[1].uri ~= nil, "textures = false") +end + +-- 4. the hand-made room +do + local rm = Wad.decode(Bytes.reader(buffer.fromstring(Fx.room.data))) + t:check(rm, "room decodes") + local names = {} + for _, e in rm:list() do + table.insert(names, e.name) + end + t:eq(names[2], "E1M1/THINGS", "E1M1 lumps") + t:eq(names[16], "E1M2/TEXTMAP", "UDMF lumps belong to their map") + t:eq(names[17], "E1M2/ENDMAP", "up to ENDMAP") + t:eq(names[18], "DEMO1", "after the map") + t:eq(names[19], "DEMO1~2", "duplicate names get ~n") + local _, ue = Wad.map(rm, "E1M2") + t:check(ue and ue.code == Err.UNSUPPORTED, "UDMF unsupported") + local s = Wad.map(rm, "E1M1") :: any + local area = { floor = 0, ceil = 0, wall = 0 } + for _, p in s.meshes[1].primitives do + local pos = Types.Scene.reader(p.attributes.POSITION) :: any + local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any + for k = 0, p.attributes.POSITION.count - 1, 3 do + local ux, uy, uz = pos(k + 1, 0) - pos(k, 0), pos(k + 1, 1) - pos(k, 1), pos(k + 1, 2) - pos(k, 2) + local vx, vy, vz = pos(k + 2, 0) - pos(k, 0), pos(k + 2, 1) - pos(k, 1), pos(k + 2, 2) - pos(k, 2) + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local ar = math.sqrt(cx * cx + cy * cy + cz * cz) / 2 + -- the winding agrees with the normal + t:check(cx * nrm(k, 0) + cy * nrm(k, 1) + cz * nrm(k, 2) > 0, "winding faces the normal") + if nrm(k, 2) > 0.5 then + area.floor += ar + elseif nrm(k, 2) < -0.5 then + area.ceil += ar + else + area.wall += ar + end + end + end + t:eq(area.floor, 256 * 256, "floors: the room around the pillar + the pillar top") + t:eq(area.ceil, 256 * 256, "ceilings") + t:eq(area.wall, 4 * 256 * 128 + 4 * 64 * 32, "outer walls + the pillar's lower walls") + t:eq(s.nodes[2].translation[3], 0, "thing on the room floor") + t:eq(s.nodes[3].translation[3], 32, "thing on the pillar") + t:eq(s.nodes[2].extras.thing.type, 1, "thing type") + local tall = Wad.image(rm, "TALL") :: any + t:eq(tall.height, 300, "tall patch height") + t:eq(buffer.readu32(tall.pixels, 0), 0, "tall patch: transparent above the first post") + t:eq(buffer.readu32(tall.pixels, 100 * 4), buffer.readu32((Wad.palette(rm) :: buffer), 7 * 4), "tall patch: first post") + t:eq(buffer.readu32(tall.pixels, 249 * 4), buffer.readu32((Wad.palette(rm) :: buffer), 9 * 4), "tall patch: relative topdelta 100 + 50") + t:eq(buffer.readu32(tall.pixels, 260 * 4), 0, "tall patch: transparent below") + local flat = Wad.image(rm, "FLOOR") :: any + t:check(flat.width == 64 and flat.height == 64, "flat 64 x 64") + -- writer: lossless for decoded WADs (map lumps and ~n names stripped back) + t:check(buffer.tostring(F.save(rm) :: buffer) == Fx.room.data, "room: decode + save is byte-identical") +end + +-- 5. writer +do + t:check(buffer.tostring(F.save(a) :: buffer) == fd.data, "freedoom: decode + save is byte-identical") + local p = Wad.new() + p:add("dir/demo1", "abc") + p:add("MAP02/THINGS", "") + local back = Wad.decode(Bytes.reader(p:write() :: buffer)) + t:eq(Wad.lumps(back)[1].name, "DEMO1", "names upper-cased, paths stripped") + t:eq(back.meta.source.type, "PWAD", "PWAD by default") + local long = Wad.new() + long:add("NINECHARS", "x") + local _, e = long:write() + t:check(e and e.code == Err.ARG, "9-byte lump name") + local zip = F.format("zip").create() + zip:add("x.lmp", "1") + t:eq(Wad.lumps(F.load(F.save(zip, nil, { format = "wad" }) :: buffer))[1].name, "X.LMP", "zip -> wad") +end + +-- 6. errors +do + local _, e1 = Wad.decode(Bytes.reader(buffer.fromstring(string.sub(fd.data, 1, 100)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local _, e2 = Wad.image(a, "NOPE") + t:check(e2 and e2.code == Err.ARG, "missing lump") + local _, e3 = Wad.image({}, "X") + t:check(e3 and e3.code == Err.ARG, "not a WAD") + local _, e4 = Wad.map(a, "MAP99") + t:check(e4 and e4.code == Err.ARG, "missing map") +end + +-- 7. fuzz: the directory, then the lumps of the room (maps, pictures) +t:fuzz("decode", function(b: buffer) + local w = Wad.decode(Bytes.reader(b)) + if w then + for _, l in Wad.lumps(w) :: any do + if not l.map and l.size > 0 then + Wad.image(w, l.name) + end + end + for _, m in Wad.maps(w) do + Wad.map(w, m) + end + Wad.texture(w, "X") + end + return w +end, { Fx.room.data }, { mutations = 300 }) +do + -- mutate inside the lumps of the real map and pictures (the directory kept intact) + local rand = T.rng(9) + local threw = 0 + for i = 1, 60 do + local b = buffer.fromstring(fd.data) + for _ = 1, 1 + rand(20) do + local at = 12 + rand(#fd.data - 12 - (#fd.lumps * 16)) + buffer.writeu8(b, at, rand(256)) + end + local ok = pcall(function() + local w = Wad.decode(Bytes.reader(b)) + if w then + if i % 6 == 0 then + Wad.map(w, "MAP01") + end + for _, im in fd.images do + Wad.image(w, im.name) + end + end + end) + if not ok then + threw += 1 + end + end + t:eq(threw, 0, "mutated lumps never throw") +end + +t:done() diff --git a/tests/codecs/explode.luau b/tests/codecs/explode.luau new file mode 100644 index 0000000..7894062 --- /dev/null +++ b/tests/codecs/explode.luau @@ -0,0 +1,33 @@ +-- codecs/compress/Explode tests: PKWARE DCL streams written by StormLib's SCompImplode (tools/fixtures/mpq.py: +-- text, noise, a short repeat, zeros) decompress to the source bytes; maxOut stops early; hand-made streams with +-- coded literals; bad headers and truncations; the fuzz pass. +local T = require("@tests/T") +local Explode = require("@formats/codecs/compress/Explode") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/mpq") + +local t = T.suite("codecs/explode") +local samples = {} +for _, c in Fx.implode do + local out, err = Explode.decompress(c.data) + t:check(out, c.name .. ": " .. tostring(err)) + t:eq(buffer.len(out), c.size, c.name .. ": size") + t:eq(Crc32.of(out), c.crc, c.name .. ": data") + t:note("%-6s %6d -> %6d bytes (header %d %d)", c.name, #c.data, c.size, string.byte(c.data, 1), string.byte(c.data, 2)) + local part = Explode.decompress(c.data, nil, nil, 7) + t:eq(buffer.len(part), math.min(7, c.size), c.name .. ": maxOut") + table.insert(samples, c.data) +end +-- a stream with coded literals: header 1 (Huffman literals), 4 (1 KB); then only the end code would need the tables: +-- check the header checks instead +local _, e1 = Explode.decompress("\2\4\0") +t:check(e1 and e1.code == Err.CORRUPT, "literal mode 2") +local _, e2 = Explode.decompress("\0\7\0") +t:check(e2 and e2.code == Err.CORRUPT, "dictionary 7") +local _, e3 = Explode.decompress(string.sub(Fx.implode[1].data, 1, 20)) +t:check(e3 and e3.code == Err.TRUNCATED, "truncated") +t:fuzz("decompress", function(b: buffer) + return Explode.decompress(b) +end, samples, { mutations = 40 }) +t:done() diff --git a/tests/codecs/polygon.luau b/tests/codecs/polygon.luau new file mode 100644 index 0000000..c7f158a --- /dev/null +++ b/tests/codecs/polygon.luau @@ -0,0 +1,69 @@ +-- codecs/model/Polygon tests: convex / concave / holed / nested polygons triangulate to the exact area in +-- counter-clockwise triangles, either input orientation; degenerate loops; a fuzz of random loops never throws. +local T = require("@tests/T") +local Polygon = require("@formats/codecs/model/Polygon") + +local t = T.suite("codecs/polygon") + +local function area(loops: { { number } }, tris: { number }): (number, boolean) + local a, ccw = 0, true + for k = 1, #tris, 6 do + local p = {} + for c = 0, 2 do + local l = loops[tris[k + c * 2]] + local i = tris[k + c * 2 + 1] + p[c * 2 + 1], p[c * 2 + 2] = l[i * 2 - 1], l[i * 2] + end + local s = ((p[3] - p[1]) * (p[6] - p[2]) - (p[4] - p[2]) * (p[5] - p[1])) / 2 + if s <= 0 then + ccw = false + end + a += s + end + return a, ccw +end + +local cases = { + { "square", { { 0, 0, 10, 0, 10, 10, 0, 10 } }, 100 }, + { "clockwise square", { { 0, 0, 0, 10, 10, 10, 10, 0 } }, 100 }, + { "L shape", { { 0, 0, 20, 0, 20, 10, 10, 10, 10, 20, 0, 20 } }, 300 }, + { "comb", { { 0, 0, 50, 0, 50, 10, 40, 10, 40, 2, 30, 2, 30, 10, 20, 10, 20, 2, 10, 2, 10, 10, 0, 10 } }, 50 * 2 + 3 * 10 * 8 }, + { "square with a hole", { { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 2, 4, 4, 4, 4, 2 } }, 96 }, + { "two holes", { { 0, 0, 30, 0, 30, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 }, { 20, 2, 28, 2, 28, 8, 20, 8 } }, 300 - 4 - 48 }, + { "island in a hole", { { 0, 0, 30, 0, 30, 30, 0, 30 }, { 5, 5, 25, 5, 25, 25, 5, 25 }, { 10, 10, 20, 10, 20, 20, 10, 20 } }, 900 - 400 + 100 }, + { "degenerate loops ignored", { { 0, 0, 1, 1 }, { 0, 0, 5, 5, 10, 10 }, { 0, 0, 4, 0, 4, 4, 0, 4 } }, 16 }, +} +for _, c in cases do + local tris = Polygon.triangulate(c[2]) + local a, ccw = area(c[2], tris) + t:check(math.abs(a - c[3]) < 1e-9, c[1] .. ": area " .. a .. " want " .. c[3]) + t:check(ccw, c[1] .. ": counter-clockwise triangles") +end + +-- random star polygons with a random hole: area preserved, never throws +local rand = T.rng(3) +local threw = 0 +for i = 1, 200 do + local n = 3 + rand(30) + local outer = {} + for k = 0, n - 1 do + local ang = k / n * math.pi * 2 + local r = 50 + rand(50) + table.insert(outer, math.floor(math.cos(ang) * r)) + table.insert(outer, math.floor(math.sin(ang) * r)) + end + local hole = { -5, -5, 5, -5, 5, 5, -5, 5 } + local ok = pcall(Polygon.triangulate, if i % 2 == 0 then { outer, hole } else { outer }) + if not ok then + threw += 1 + end + local garbage = {} + for _ = 1, rand(40) do + table.insert(garbage, rand(20) - 10) + end + if not pcall(Polygon.triangulate, { garbage, { 0 / 0, 1, 2 } }) then + threw += 1 + end +end +t:eq(threw, 0, "random and garbage loops never throw") +t:done() diff --git a/tests/image/blp.luau b/tests/image/blp.luau new file mode 100644 index 0000000..03388f5 --- /dev/null +++ b/tests/image/blp.luau @@ -0,0 +1,89 @@ +-- image/blp tests: BLP1 / BLP2 palette files written by Pillow and DXT1 / DXT3 / DXT5 / palette-with-alpha files +-- written by tools/fixtures/blp.py decode to Pillow's RGBA; BLP1 JPEG (3 components) to Pillow's, 4 components (BGRA) +-- within a PSNR of the source; BLP2 BGRA and BLP1 palette + alpha against the writer; our BLP2 writer round-trips +-- (with mips); errors; the fuzz pass. Fixtures: tools/fixtures/blp.py. +local T = require("@tests/T") +local F = require("@formats") +local Blp = require("@formats/image/blp") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/blp") + +local t = T.suite("blp") +t:eq(Blp.name, "blp", "name") + +local function psnr(a: buffer, b: string): number + local se = 0 + for i = 0, #b - 1 do + local d = buffer.readu8(a, i) - string.byte(b, i + 1) + se += d * d + end + if se == 0 then + return math.huge + end + return 10 * math.log10(255 * 255 / (se / #b)) +end + +for _, c in Fx do + local img, err = Blp.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(img, c.name .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "blp", c.name .. ": F.detect") + t:check(img.width == c.width and img.height == c.height, c.name .. ": size") + if c.crc then + t:eq(Crc32.of(img.pixels), c.crc, c.name .. ": pixels against Pillow") + elseif c.ref then + local worst, alpha = 0, true + for i = 0, #c.ref - 1 do + local d = math.abs(buffer.readu8(img.pixels, i) - string.byte(c.ref, i + 1)) + if i % 4 == 3 then + alpha = alpha and d == 0 + else + worst = math.max(worst, d) + end + end + t:check(worst <= c.tol, c.name .. ": colours within " .. c.tol .. " of Pillow (worst " .. worst .. ")") + t:check(alpha, c.name .. ": alpha equal to Pillow's") + elseif c.rgbref then + local ok = true + for i = 0, img.width * img.height - 1 do + for k = 0, 2 do + ok = ok and buffer.readu8(img.pixels, i * 4 + k) == string.byte(c.rgbref, i * 4 + k + 1) + end + ok = ok and buffer.readu8(img.pixels, i * 4 + 3) == string.byte(c.alpha, i + 1) + end + t:check(ok, c.name .. ": RGB against Pillow, alpha plane against the writer") + elseif c.psnr then + local p = psnr(img.pixels, c.rgba) + t:check(p >= c.psnr, string.format("%s: PSNR %.1f dB", c.name, p)) + t:note("%s: PSNR %.1f dB against the source", c.name, p) + else + t:check(buffer.tostring(img.pixels) == c.rgba, c.name .. ": pixels against the writer") + end + -- our writer: BLP2 BGRA, lossless + local enc = Blp.encode(img, { mips = true }) :: buffer + local back = Blp.decode(Bytes.reader(enc)) :: any + t:eq(Crc32.of(back.pixels), Crc32.of(img.pixels), c.name .. ": BLP2 BGRA round trip") + t:check(back.meta.source.mips > 1 or (img.width == 1 and img.height == 1), c.name .. ": mips written") +end + +do + local _, e1 = Blp.decode(Bytes.reader(buffer.fromstring(string.sub(Fx[3].data, 1, 1200)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local _, e2 = Blp.decode(Bytes.reader(buffer.fromstring("BLP0" .. string.rep("\0", 200)))) + t:check(e2 and e2.code == Err.UNSUPPORTED, "BLP0") + local _, e3 = Blp.encode({ format = "rgba16" } :: any) + t:check(e3 and e3.code == Err.ARG, "encode needs rgba8") + local one = Types.Image.new(1, 1) + t:check(Blp.decode(Bytes.reader(Blp.encode(one) :: buffer)) ~= nil, "1 x 1") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return Blp.decode(Bytes.reader(b)) +end, samples, { mutations = 40 }) +t:done() diff --git a/tests/image/tim.luau b/tests/image/tim.luau new file mode 100644 index 0000000..6f81fd7 --- /dev/null +++ b/tests/image/tim.luau @@ -0,0 +1,95 @@ +-- image/tim tests: PlayStation TIM files written by tools/fixtures/tim.py (4 / 8-bit CLUT, 15-bit, 24-bit) decode to +-- ImageMagick's RGB, colour 0x0000 is transparent, CLUT rows, the VRAM position; the encoder round-trips 16 / 24 / +-- 8 / 4-bit; errors; the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Tim = require("@formats/image/tim") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/tim") + +local t = T.suite("tim") +t:eq(Tim.name, "tim", "name") + +local function rgb(img: any): buffer + local n = img.width * img.height + local out = buffer.create(n * 3) + for i = 0, n - 1 do + buffer.copy(out, i * 3, img.pixels, i * 4, 3) + end + return out +end + +for _, c in Fx do + local img, err = Tim.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(img, c.name .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "tim", c.name .. ": F.detect") + t:check(img.width == c.width and img.height == c.height, c.name .. ": size") + -- transparent pixels: compare RGB with ImageMagick where opaque (it reads 0x0000 as black) + t:eq(Crc32.of(rgb(img)), c.rgb[1], c.name .. ": RGB against ImageMagick") + local tr = 0 + for i = 0, img.width * img.height - 1 do + if buffer.readu8(img.pixels, i * 4 + 3) == 0 then + tr += 1 + end + end + t:eq(tr, c.transparent, c.name .. ": transparent pixels") + t:eq(img.meta.source.bpp, c.bpp, c.name .. ": bpp") + t:eq(img.meta.source.x, 320, c.name .. ": VRAM x") + if c.cluts > 1 then + local other = Tim.decode(Bytes.reader(buffer.fromstring(c.data)), { clut = 1 }) :: any + t:check(Crc32.of(other.pixels) ~= Crc32.of(img.pixels) and other.meta.source.clut.row == 1, c.name .. ": second CLUT row") + end + -- round trips: decoded 4 / 8 / 15-bit pixels are PSX colours, so every depth that fits is lossless (24-bit only + -- round-trips as 24-bit) + for _, bpp in (if c.bpp == 24 then { 24 } else { 16, 24, 8, 4 }) do + local enc, eerr = Tim.encode(img, { bpp = bpp }) + if bpp == 24 then + -- 24-bit drops alpha: compare RGB + local back = Tim.decode(Bytes.reader(enc :: buffer)) :: any + t:eq(Crc32.of(rgb(back)), Crc32.of(rgb(img)), c.name .. ": 24-bit round trip (RGB)") + elseif enc then + -- 4 / 8-bit rows hold whole 16-bit units: odd widths come back padded on the right + local back = Tim.decode(Bytes.reader(enc)) :: any + local same = back.height == img.height and back.width >= img.width + for y = 0, img.height - 1 do + for x = 0, img.width - 1 do + same = same and buffer.readu32(back.pixels, (y * back.width + x) * 4) == buffer.readu32(img.pixels, (y * img.width + x) * 4) + end + end + t:check(same, c.name .. ": " .. bpp .. "-bit round trip") + else + t:check(eerr and eerr.code == Err.ARG, c.name .. ": " .. bpp .. "-bit refused (too many colours)") + end + end +end + +do + local img = Types.Image.new(3, 1) + buffer.writeu32(img.pixels, 0, 0xFF000000) -- opaque black + buffer.writeu32(img.pixels, 4, 0x00FFFFFF) -- transparent + buffer.writeu32(img.pixels, 8, 0xFF0000FF) -- red + local back = Tim.decode(Bytes.reader(Tim.encode(img) :: buffer)) :: any + t:eq(buffer.readu32(back.pixels, 0), 0xFF000000, "opaque black stays opaque (STP)") + t:eq(buffer.readu32(back.pixels, 4), 0, "transparent") + t:eq(buffer.readu32(back.pixels, 8), 0xFF0000FF, "red") + local _, e1 = Tim.encode(img, { bpp = 12 }) + t:check(e1 and e1.code == Err.ARG, "bpp 12") + local _, e2 = Tim.decode(Bytes.reader(buffer.fromstring(string.sub(Fx[1].data, 1, 40)))) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2)) + local mixed = buffer.fromstring(Fx[3].data) + buffer.writeu8(mixed, 4, 4) + local _, e3 = Tim.decode(Bytes.reader(mixed)) + t:check(e3 and e3.code == Err.UNSUPPORTED, "mixed mode") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return Tim.decode(Bytes.reader(b)) +end, samples, { mutations = 60 }) +t:done() diff --git a/tests/image/vtf.luau b/tests/image/vtf.luau new file mode 100644 index 0000000..6ba4e64 --- /dev/null +++ b/tests/image/vtf.luau @@ -0,0 +1,74 @@ +-- image/vtf tests: VTFs written by srctools (tools/fixtures/vtf.py: every texel format it writes, versions 7.2 / 7.4 +-- / 7.5, mips, two-frame animations) decode to srctools' own RGBA (DXT within its libsquish rounding), frames, the +-- mip / thumbnail layout; the half / float / 16-bit formats srctools cannot write against the fixture writer; errors; +-- the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Vtf = require("@formats/image/vtf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/vtf") + +local t = T.suite("vtf") +t:eq(Vtf.name, "vtf", "name") + +local function compare(px: buffer, want: string, tol: number): (number, number) + local worst, at = 0, -1 + for i = 0, #want - 1 do + local d = math.abs(buffer.readu8(px, i) - string.byte(want, i + 1)) + if d > worst then + worst, at = d, i + end + end + return worst, at +end + +local exact = 0 +for _, c in Fx do + local img, err = Vtf.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(img, c.name .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "vtf", c.name .. ": F.detect") + t:check(img.width == c.width and img.height == c.height, c.name .. ": size") + local worst, at = compare(img.pixels, c.rgba, c.tol) + t:check(worst <= c.tol, string.format("%s (%s): within %d of srctools (worst %d at byte %d)", c.name, c.version, c.tol, worst, at)) + if worst == 0 then + exact += 1 + end + t:eq(img.meta.source.texel, c.name, c.name .. ": texel format") + t:check(img.meta.source.mips > 1 or c.mips == 1, c.name .. ": mips counted") + if c.frames > 1 then + t:eq(#img.frames, c.frames, c.name .. ": frames") + local lw = compare(img.frames[c.frames].image.pixels, c.last, c.tol) + t:check(lw <= c.tol, c.name .. ": last frame") + end + if c.mips ~= 1 then + local small = Vtf.decode(Bytes.reader(buffer.fromstring(c.data)), { mip = 1 }) :: any + t:check(small and small.width == math.max(1, c.width // 2), c.name .. ": mip 1") + end +end +t:note("%d of %d files exactly equal to their reference (srctools or the fixture writer)", exact, #Fx) + +do + local c = Fx[1] + local _, e1 = Vtf.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, #c.data - 20)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local bad = buffer.fromstring(c.data) + buffer.writeu32(bad, 8, 9) + local _, e2 = Vtf.decode(Bytes.reader(bad)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 7.9") + local p8 = buffer.fromstring(c.data) + buffer.writei32(p8, 52, 7) + local _, e3 = Vtf.decode(Bytes.reader(p8)) + t:check(e3 and e3.code == Err.UNSUPPORTED, "P8") +end + +local samples = {} +for i, c in Fx do + if i % 3 == 0 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return Vtf.decode(Bytes.reader(b)) +end, samples, { mutations = 30 }) +t:done() diff --git a/tests/model/_soup.luau b/tests/model/_soup.luau new file mode 100644 index 0000000..ae41da3 --- /dev/null +++ b/tests/model/_soup.luau @@ -0,0 +1,99 @@ +-- tests/model/_soup: helpers for the game model tests: a primitive's triangle soup (positions, morph target frames, +-- texture coordinates in index order) and a tolerant comparison against assimp's soup. +local Types = require("@formats/Types") + +local Soup = {} + +-- positions(prim, target?) -> f32 x3 buffer of the corners in index order (target k adds morph target k's deltas) +function Soup.positions(prim: any, target: number?): buffer + local pos = Types.Scene.reader(prim.attributes.POSITION) :: any + local d = if target then Types.Scene.reader(prim.targets[target].POSITION) :: any else nil + local idx = prim.indices + local n = idx.count + local out = buffer.create(n * 12) + for k = 0, n - 1 do + local v = buffer.readu32(idx.data, k * 4) + for c = 0, 2 do + buffer.writef32(out, k * 12 + c * 4, pos(v, c) + (if d then d(v, c) else 0)) + end + end + return out +end + +-- uvs(prim, set?, flip?) -> { u, v, ... } of the corners in index order (flip: v -> 1 - v, assimp's convention; +-- "neg": v -> -v, assimp's Half-Life loader) +function Soup.uvs(prim: any, set: number?, flip: (boolean | string)?): { number } + local tc = Types.Scene.reader(prim.attributes["TEXCOORD_" .. (set or 0)]) :: any + local idx = prim.indices + local out = {} + for k = 0, idx.count - 1 do + local v = buffer.readu32(idx.data, k * 4) + table.insert(out, tc(v, 0)) + table.insert(out, if flip == "neg" then -tc(v, 1) elseif flip then 1 - tc(v, 1) else tc(v, 1)) + end + return out +end + +-- close(a: buffer f32 | {number}, b: {number}, tol) -> true | false, first index that differs +function Soup.close(a: any, b: { number }, tol: number): (boolean, number?) + local n = if type(a) == "buffer" then buffer.len(a) // 4 else #a + if n ~= #b then + return false, -1 + end + for i = 1, n do + local x = if type(a) == "buffer" then buffer.readf32(a, (i - 1) * 4) else a[i] + if math.abs(x - b[i]) > tol * math.max(1, math.abs(b[i])) then + return false, i + end + end + return true, nil +end + +-- triangles(a, b, tol, stride?) -> true when the triangle lists a and b (flat numbers, stride per corner: 3 for +-- positions, 2 for texture coordinates) hold the same triangles in the same order, each up to a cyclic rotation of +-- its corners (assimp rotates them); false, the first differing triangle otherwise +function Soup.triangles(a: { number }, b: { number }, tol: number, stride: number?): (boolean, number?) + local s = stride or 3 + if #a ~= #b then + return false, -1 + end + local per = 3 * s + for t = 0, #a // per - 1 do + local found = false + for rot = 0, 2 do + local same = true + for c = 0, 2 do + local ca, cb = t * per + c * s, t * per + ((c + rot) % 3) * s + for k = 1, s do + if math.abs(a[ca + k] - b[cb + k]) > tol * math.max(1, math.abs(b[cb + k])) then + same = false + end + end + end + if same then + found = true + break + end + end + if not found then + return false, t + end + end + return true, nil +end + +-- list(buf) -> the f32 values of a buffer as numbers +function Soup.list(b: buffer): { number } + local out = table.create(buffer.len(b) // 4) + for i = 0, buffer.len(b) // 4 - 1 do + out[i + 1] = buffer.readf32(b, i * 4) + end + return out +end + +-- slice(list, from, n) -> n values from index from (1-based) +function Soup.slice(list: { number }, from: number, n: number): { number } + return table.move(list, from, from + n - 1, 1, table.create(n)) +end + +return Soup diff --git a/tests/model/bsp.luau b/tests/model/bsp.luau new file mode 100644 index 0000000..8dd7399 --- /dev/null +++ b/tests/model/bsp.luau @@ -0,0 +1,226 @@ +-- model/bsp tests: Quake 1, Half-Life, Quake II and Quake III maps written by tools/fixtures/bsp.py: every model's +-- triangles per texture (positions, normals, texture coordinates against the documented rules), counter-clockwise +-- about the face normals, embedded textures (Quake through the palette, Half-Life through its own), WAD / .wal +-- textures as URIs, entities; Quake III: polygon / mesh faces against assimp's soup (of a .pk3) and the writer, +-- lightmaps, vertex colours, a tessellated patch; errors; the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Bsp = require("@formats/model/bsp") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Soup = require("@tests/model/_soup") +local Fx = require("@tests/gen/bsp") + +local t = T.suite("bsp") +t:eq(Bsp.name, "bsp", "name") + +local function near(a: { number }, b: { number }, tol: number): boolean + if #a ~= #b then + return false + end + for i = 1, #b do + if math.abs(a[i] - b[i]) > tol * math.max(1, math.abs(b[i])) then + return false + end + end + return true +end + +local function meshOf(s: any, model: number): any + for _, n in s.nodes do + if n.mesh and n.extras and n.extras.bsp and n.extras.bsp.model == model then + return s.meshes[n.mesh] + end + end + return nil +end + +-- winding: every triangle's geometric normal agrees with its NORMAL +local function windingOk(p: any): boolean + local pos = Types.Scene.reader(p.attributes.POSITION) :: any + local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any + local idx = p.indices + for k = 0, idx.count - 1, 3 do + local a, b, c = buffer.readu32(idx.data, k * 4), buffer.readu32(idx.data, k * 4 + 4), buffer.readu32(idx.data, k * 4 + 8) + local ux, uy, uz = pos(b, 0) - pos(a, 0), pos(b, 1) - pos(a, 1), pos(b, 2) - pos(a, 2) + local vx, vy, vz = pos(c, 0) - pos(a, 0), pos(c, 1) - pos(a, 1), pos(c, 2) - pos(a, 2) + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + if cx * nrm(a, 0) + cy * nrm(a, 1) + cz * nrm(a, 2) <= 0 then + return false + end + end + return true +end + +local function brush(label: string, c: any, opts: any) + local s, err = Bsp.decode(Bytes.reader(buffer.fromstring(c.data)), opts) + t:check(s, label .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "bsp", label .. ": F.detect") + for model, texs in c.models do + local mesh = meshOf(s, tonumber(model) :: number) + t:check(mesh, label .. ": model " .. model) + for tname, want in texs do + local prim + for _, p in mesh.primitives do + if p.material and s.materials[p.material].name == tname then + prim = p + end + end + t:check(prim, label .. ": model " .. model .. " texture " .. tname) + t:check(near(Soup.list(Soup.positions(prim)), want.pos, 1e-6), label .. ": " .. tname .. " positions") + t:check(near(Soup.uvs(prim, 0), want.uv, 1e-5), label .. ": " .. tname .. " texture coordinates") + t:check(near(Soup.list(prim.attributes.NORMAL.data), want.nrm, 1e-6), label .. ": " .. tname .. " normals") + t:check(windingOk(prim), label .. ": " .. tname .. " counter-clockwise") + end + end + t:eq(#s.meta.entities, 3, label .. ": entities") + t:eq(s.meta.entities[2].classname, "info_player_start", label .. ": entity classname") + t:eq(s.meta.entities[3].model, "*1", label .. ": brush entity model") + return s +end + +-- 1. Quake 1, Half-Life +do + local q1 = brush("q1", Fx.q1, { palette = Fx.q1.palette }) + t:eq(Crc32.of(q1.textures[1].image.pixels), Fx.q1.textures[1], "q1: embedded texture through the palette") + t:eq(q1.textures[2].uri, "+0door", "q1: WAD texture as a URI") + t:eq(q1.meta.source.variant, "quake", "q1: variant") + local hl = brush("hl", Fx.hl, nil) + t:eq(Crc32.of(hl.textures[1].image.pixels), Fx.hl.textures[1], "hl: embedded texture through its own palette") + t:eq(hl.meta.source.variant, "halflife", "hl: variant") + local grey = Bsp.decode(Bytes.reader(buffer.fromstring(Fx.q1.data))) :: any + t:eq(grey.meta.source.palette, false, "q1 without a palette: grey") +end + +-- 2. Quake II +do + local q2 = brush("q2", Fx.q2, { files = { ["textures/brick.wal"] = Fx.q2.wal } }) + t:eq(q2.textures[1].uri, "textures/brick.wal", "q2: .wal URI") + t:eq(q2.materials[1].extras.bsp.width, 16, "q2: size from the .wal") + t:eq(q2.materials[2].extras.bsp.texels, true, "q2: texel coordinates without the .wal") +end + +-- 3. Quake III +do + local q = Fx.q3 + local s, err = Bsp.decode(Bytes.reader(buffer.fromstring(q.data))) + t:check(s, "q3: " .. tostring(err)) + t:eq(F.detect(q.data), "bsp", "q3: F.detect") + for model, keys in q.models do + local mesh = meshOf(s, tonumber(model) :: number) + for key, want in keys do + local sh, lm = string.match(key, "^(%-?%d+):(%-?%d+)$") + local prim + for _, p in mesh.primitives do + local mat = s.materials[p.material] + local lt = mat.extras.bsp.lightmap + local tex = mat.baseColorTexture and mat.baseColorTexture.texture + if tex == tonumber(sh) :: number + 1 and ((lt and s.textures[lt].image.meta.source.lightmap) or -1) == tonumber(lm) then + prim = p + end + end + t:check(prim, "q3: model " .. model .. " batch " .. key) + t:check(near(Soup.list(Soup.positions(prim)), want.pos, 1e-6), "q3: " .. key .. " positions") + t:check(near(Soup.uvs(prim, 0), want.uv, 1e-6), "q3: " .. key .. " texture coordinates") + t:check(near(Soup.uvs(prim, 1), want.lm, 1e-6), "q3: " .. key .. " lightmap coordinates") + local col = {} + local cr = Types.Scene.reader(prim.attributes.COLOR_0) :: any + for k = 0, prim.indices.count - 1 do + local v = buffer.readu32(prim.indices.data, k * 4) + for c = 0, 3 do + table.insert(col, math.floor(cr(v, c) * 255 + 0.5)) + end + end + t:check(near(col, want.col, 0), "q3: " .. key .. " vertex colours") + t:check(windingOk(prim), "q3: " .. key .. " counter-clockwise about the normals") + end + end + -- assimp: the polygon / mesh faces + local all = {} + local apos = q.assimp.pos + for _, mesh in s.meshes do + for _, p in mesh.primitives do + local mat = s.materials[p.material] + if mat.name ~= "textures/base/floor" or p.indices.count == 6 then + if p.indices.count == 6 then + for _, x in Soup.list(Soup.positions(p)) do + table.insert(all, x) + end + end + end + end + end + t:eq(q.assimp.faces, 6, "q3: assimp reads the 3 quads") + -- compare triangle sets: every assimp triangle is one of ours (up to corner rotation); assimp keeps the stored + -- clockwise order, we reverse it + local found = 0 + for k = 0, #apos // 9 - 1 do + local tri = Soup.slice(apos, k * 9 + 1, 9) + tri = { tri[7], tri[8], tri[9], tri[4], tri[5], tri[6], tri[1], tri[2], tri[3] } + for j = 0, #all // 9 - 1 do + if Soup.triangles(Soup.slice(all, j * 9 + 1, 9), tri, 1e-5) then + found += 1 + break + end + end + end + t:eq(found, 6, "q3: every assimp triangle matches one of ours") + t:eq(#q.lightmaps, 2, "q3: lightmaps") + for i, crc in q.lightmaps do + local tex + for _, tx in s.textures do + if tx.image and tx.image.meta.source.lightmap == i - 1 then + tex = tx + end + end + t:eq(Crc32.of(tex.image.pixels), crc, "q3: lightmap " .. i) + end + -- the patch: a flat 32 x 32 square at z = 100, tessellated + local area = 0 + for _, mesh in s.meshes do + for _, p in mesh.primitives do + local pos = Types.Scene.reader(p.attributes.POSITION) :: any + if pos(0, 2) == 100 then + t:check(windingOk(p), "q3: patch counter-clockwise") + for k = 0, p.indices.count - 1, 3 do + local ux, uy = pos(k + 1, 0) - pos(k, 0), pos(k + 1, 1) - pos(k, 1) + local vx, vy = pos(k + 2, 0) - pos(k, 0), pos(k + 2, 1) - pos(k, 1) + area += (ux * vy - uy * vx) / 2 + end + end + end + end + t:check(math.abs(math.abs(area) - q.patchArea) < 1e-3, "q3: patch area " .. area) + t:eq(s.meta.faces.patches, 1, "q3: one patch") + local lean = Bsp.decode(Bytes.reader(buffer.fromstring(q.data)), { patchLevel = 1 }) :: any + t:check(lean ~= nil, "q3: patchLevel 1") +end + +-- 4. errors, fuzz +do + local _, e1 = Bsp.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.q1.data, 1, 100)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local _, e2 = Bsp.decode(Bytes.reader(buffer.fromstring("VBSP" .. string.rep("\0", 100)))) + t:check(e2 and e2.code == Err.UNSUPPORTED, "VBSP") +end +t:fuzz("decode", function(b: buffer) + return Bsp.decode(Bytes.reader(b), { palette = Fx.q1.palette }) +end, { Fx.q1.data, Fx.hl.data, Fx.q2.data }, { mutations = 80 }) +do + local rand = T.rng(13) + local threw = 0 + local q = Fx.q3.data + for _ = 1, 60 do + local b = buffer.fromstring(q) + for _ = 1, 1 + rand(10) do + buffer.writeu8(b, 8 + 17 * 8 + rand(#q - 8 - 17 * 8 - 98304), rand(256)) + end + if not pcall(Bsp.decode, Bytes.reader(b)) then + threw += 1 + end + end + t:eq(threw, 0, "q3: mutated lumps never throw") +end +t:done() diff --git a/tests/model/md2.luau b/tests/model/md2.luau new file mode 100644 index 0000000..61322c9 --- /dev/null +++ b/tests/model/md2.luau @@ -0,0 +1,83 @@ +-- model/md2 tests: MD2 files written by tools/fixtures/md2.py decode to assimp's frame-0 triangle soup (positions, +-- texture coordinates) and to the writer's exact positions for every frame (base + morph target deltas), frame +-- groups as animations, skins as texture URIs, opts.frame / morph = false, errors, the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Md2 = require("@formats/model/md2") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Soup = require("@tests/model/_soup") +local Fx = require("@tests/gen/md2") + +local t = T.suite("md2") +t:eq(Md2.name, "md2", "name") + +for _, c in Fx do + local s, err = Md2.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(s, c.name .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "md2", c.name .. ": F.detect") + local prim = s.meshes[1].primitives[1] + t:eq(prim.indices.count, c.tris * 3, c.name .. ": triangles") + -- assimp, frame 0 + local ok, at = Soup.close(Soup.positions(prim), c.assimp.pos, 1e-5) + t:check(ok, c.name .. ": positions against assimp (" .. tostring(at) .. ")") + local uok, uat = Soup.close(Soup.uvs(prim, 0, true), c.assimp.uv, 1e-6) + t:check(uok, c.name .. ": texture coordinates against assimp (" .. tostring(uat) .. ")") + -- every frame, exact + t:eq(Crc32.of(Soup.positions(prim)), c.crcs[1], c.name .. ": frame 1 exact") + for k = 1, c.frames do + local f = Soup.positions(prim, k) + -- base + delta in f32 can differ from the frame by an ulp; compare to the decoded frame directly + local frame = Md2.decode(Bytes.reader(buffer.fromstring(c.data)), { frame = k, morph = false }) :: any + t:eq(Crc32.of(Soup.positions(frame.meshes[1].primitives[1])), c.crcs[k], c.name .. ": frame " .. k .. " exact (opts.frame)") + local fok = Soup.close(f, (function() + local list = {} + local fp = Soup.positions(frame.meshes[1].primitives[1]) + for i = 0, buffer.len(fp) // 4 - 1 do + list[i + 1] = buffer.readf32(fp, i * 4) + end + return list + end)(), 1e-5) + t:check(fok, c.name .. ": morph target " .. k .. " = frame " .. k) + end + -- animations from the frame names + local groups = {} + for _, a in s.animations do + table.insert(groups, a.name) + end + t:eq(#s.meshes[1].weights, c.frames, c.name .. ": one weight per frame") + t:eq(s.meta.source.frameNames[1], c.names[1], c.name .. ": frame names") + if c.name == "monster" then + t:eq(table.concat(groups, ","), "stand,run,attack,pain", c.name .. ": animation groups") + t:eq(s.animations[2].channels[1].input.count, 4, c.name .. ": run has 4 keys") + end + -- skins + t:eq(#s.textures, #c.skins, c.name .. ": skins") + if #c.skins > 0 then + t:eq(s.textures[1].uri, c.skins[1], c.name .. ": skin uri") + t:eq(s.materials[prim.material].baseColorTexture.texture, 1, c.name .. ": material") + end + t:eq(s.meta.up, "z", c.name .. ": z up") +end + +do + local c = Fx[1] + local lean = Md2.decode(Bytes.reader(buffer.fromstring(c.data)), { morph = false }) :: any + t:check(lean.meshes[1].primitives[1].targets == nil and #lean.animations == 0, "morph = false") + local _, e1 = Md2.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 300)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local bad = buffer.fromstring(c.data) + buffer.writei32(bad, 4, 7) + local _, e2 = Md2.decode(Bytes.reader(bad)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 7") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return Md2.decode(Bytes.reader(b)) +end, samples, { mutations = 80 }) +t:done() diff --git a/tests/model/md3.luau b/tests/model/md3.luau new file mode 100644 index 0000000..2c41b71 --- /dev/null +++ b/tests/model/md3.luau @@ -0,0 +1,109 @@ +-- model/md3 tests: MD3 files written by tools/fixtures/md3.py (several surfaces, frames, tags) decode to assimp's +-- frame-0 triangle soup (every surface: positions, texture coordinates) and to the writer's exact positions and +-- normals for every frame, shaders as texture URIs, tags as nodes with their per-frame channels, errors, the fuzz +-- pass. +local T = require("@tests/T") +local F = require("@formats") +local Md3 = require("@formats/model/md3") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Soup = require("@tests/model/_soup") +local Fx = require("@tests/gen/md3") + +local t = T.suite("md3") +t:eq(Md3.name, "md3", "name") + +local function normals(prim: any): buffer + local n = Types.Scene.reader(prim.attributes.NORMAL) :: any + local idx = prim.indices + local out = buffer.create(idx.count * 12) + for k = 0, idx.count - 1 do + local v = buffer.readu32(idx.data, k * 4) + for c = 0, 2 do + buffer.writef32(out, k * 12 + c * 4, n(v, c)) + end + end + return out +end + +for _, c in Fx do + local s, err = Md3.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(s, c.name .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "md3", c.name .. ": F.detect") + local prims = s.meshes[1].primitives + t:eq(#prims, #c.surfaces, c.name .. ": a primitive per surface") + -- assimp: every surface's frame 0 (assimp orders the meshes differently and rotates triangle corners: match each + -- assimp mesh to the surface whose triangles it holds) + t:eq(c.assimp.meshes, #c.surfaces, c.name .. ": assimp meshes") + local matched = 0 + for mi, m in c.assimp.per do + local nextStart = if c.assimp.per[mi + 1] then c.assimp.per[mi + 1].start else c.assimp.faces + local nf = nextStart - m.start + local apos = Soup.slice(c.assimp.pos, m.start * 9 + 1, nf * 9) + local auv = Soup.slice(c.assimp.uv, m.start * 6 + 1, nf * 6) + for _, p in prims do + if p.indices.count == nf * 3 and Soup.triangles(Soup.list(Soup.positions(p)), apos, 1e-5) then + t:check(Soup.triangles(Soup.uvs(p, 0, true), auv, 1e-5, 2), c.name .. ": texture coordinates against assimp") + matched += 1 + break + end + end + end + t:eq(matched, #c.surfaces, c.name .. ": every surface matches assimp's positions") + for si, w in c.surfaces do + t:eq(Crc32.of(Soup.positions(prims[si])), w.crcs[1], c.name .. ": " .. w.name .. " frame 1") + t:eq(s.textures[s.materials[prims[si].material].baseColorTexture.texture].uri, w.shader, c.name .. ": shader") + for k = 1, c.frames do + local fs = Md3.decode(Bytes.reader(buffer.fromstring(c.data)), { frame = k, morph = false }) :: any + local fp = fs.meshes[1].primitives[si] + t:eq(Crc32.of(Soup.positions(fp)), w.crcs[k], c.name .. ": " .. w.name .. " frame " .. k) + local nb = normals(fp) + -- normals are computed in double then stored as f32: compare by CRC of the fixture's f32 values + t:eq(Crc32.of(nb), w.ncrcs[k], c.name .. ": " .. w.name .. " normals frame " .. k) + end + if c.frames > 1 then + t:eq(#prims[si].targets, c.frames, c.name .. ": morph targets") + end + end + -- tags + local ntags = #c.tags // c.frames + t:eq(#s.meta.source.tags, ntags, c.name .. ": tags") + for _, tg in c.tags do + if tg.frame == 1 then + local node + for _, n in s.nodes do + if n.name == tg.name then + node = n + end + end + t:check(node and math.abs(node.translation[1] - tg.origin[1]) < 1e-6, c.name .. ": tag " .. tg.name .. " origin") + -- the rotation about z by angle + t:check(node and math.abs(node.rotation[3] - math.sin(tg.angle / 2)) < 1e-5, c.name .. ": tag " .. tg.name .. " rotation") + end + end + if c.frames > 1 then + t:eq(#s.animations, 1, c.name .. ": one animation") + t:eq(#s.animations[1].channels, 1 + 2 * ntags, c.name .. ": weights + tag channels") + end +end + +do + local c = Fx[1] + local _, e1 = Md3.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 500)))) + t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "truncated: " .. tostring(e1)) + local bad = buffer.fromstring(c.data) + buffer.writei32(bad, 4, 14) + local _, e2 = Md3.decode(Bytes.reader(bad)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 14") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return Md3.decode(Bytes.reader(b)) +end, samples, { mutations = 80 }) +t:done() diff --git a/tests/model/md5.luau b/tests/model/md5.luau new file mode 100644 index 0000000..ba9e9de --- /dev/null +++ b/tests/model/md5.luau @@ -0,0 +1,153 @@ +-- model/md5 tests: an .md5mesh and two .md5anim files written by tools/fixtures/md5.py: the bind pose against +-- assimp's triangle soup (positions, texture coordinates) and the writer's exact weighted positions, the joints' +-- model-space pose through the node tree, weights, animations through opts.files / opts.resolve (every frame's +-- parent-relative pose), a standalone .md5anim, missing animations, errors, the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Md5 = require("@formats/model/md5") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Soup = require("@tests/model/_soup") +local Fx = require("@tests/gen/md5") + +local t = T.suite("md5") +t:eq(Md5.name, "md5", "name") + +local function near(a: { number }, b: { number }, tol: number): boolean + for i = 1, #b do + if math.abs(a[i] - b[i]) > tol * math.max(1, math.abs(b[i])) then + return false + end + end + return true +end +local function sameQ(a: { number }, b: { number }): boolean + return near(a, b, 1e-5) or near(a, { -b[1], -b[2], -b[3], -b[4] }, 1e-5) +end + +local M = Fx.mesh +local files = {} +for _, a in Fx.anims do + files[a.name .. ".md5anim"] = a.data +end +local s, err = Md5.decode(Bytes.reader(buffer.fromstring(M.data)), { anims = { "idle.md5anim", "walk.md5anim" }, files = files }) +t:check(s, "md5mesh: " .. tostring(err)) +t:eq(F.detect(M.data), "md5", "F.detect") + +-- 1. geometry +do + local prims = s.meshes[1].primitives + t:eq(#prims, #M.positions, "a primitive per mesh") + for i, p in prims do + local pos = Soup.list(p.attributes.POSITION.data) + t:check(near(pos, M.positions[i], 1e-5), "mesh " .. i .. ": weighted positions exact") + t:eq(p.indices.count, M.tris[i] * 3, "mesh " .. i .. ": triangles") + t:check(near(Soup.list(p.attributes.TEXCOORD_0.data), M.uvs[i], 1e-6), "mesh " .. i .. ": texture coordinates") + t:eq(s.textures[s.materials[p.material].baseColorTexture.texture].uri, "models/test/skin" .. (i - 1), "mesh " .. i .. ": shader") + end + local matched = 0 + for mi, m in M.assimp.per do + local nextStart = if M.assimp.per[mi + 1] then M.assimp.per[mi + 1].start else M.assimp.faces + local nf = nextStart - m.start + local apos = Soup.slice(M.assimp.pos, m.start * 9 + 1, nf * 9) + local auv = Soup.slice(M.assimp.uv, m.start * 6 + 1, nf * 6) + for _, p in prims do + if p.indices.count == nf * 3 and Soup.triangles(Soup.list(Soup.positions(p)), apos, 1e-4) then + t:check(Soup.triangles(Soup.uvs(p, 0, true), auv, 1e-5, 2), "texture coordinates against assimp") + matched += 1 + break + end + end + end + t:eq(matched, #M.positions, "every mesh matches assimp's bind pose") +end + +-- 2. skeleton: the model-space joint poses through the node tree +do + local skin = s.skins[1] + t:eq(#skin.joints, #M.joints, "joints") + local parent = {} + for ni, nd in s.nodes do + for _, c in nd.children do + parent[c] = ni + end + end + local function world(ni: number): { number } + local m = Types.Scene.nodeMatrix(s.nodes[ni]) + local p = parent[ni] + return if p then Types.Scene.mul(world(p), m) else m + end + for i, j in M.joints do + local nd = skin.joints[i] + t:eq(s.nodes[nd].name, j.name, "joint name " .. i) + local w = world(nd) + t:check(near({ w[13], w[14], w[15] }, j.pos, 1e-4), "joint " .. j.name .. " model-space position") + end + t:check(s.meshes[1].primitives[1].attributes.JOINTS_0 ~= nil, "skinned") +end + +-- 3. animations +local function checkAnim(scene: any, a: any, anim: any, label: string) + t:eq(anim.name, a.name, label .. ": name") + local byNode = {} + for _, ch in anim.channels do + byNode[ch.node .. ch.path] = ch + end + local skin = scene.skins[1] + local ok = true + for f, pose in a.poses do + for ji, jp in pose do + local nd = skin.joints[ji] + local tr, rot = byNode[nd .. "translation"], byNode[nd .. "rotation"] + local tv, qv = {}, {} + for k = 1, 3 do + tv[k] = buffer.readf32(tr.output.data, ((f - 1) * 3 + k - 1) * 4) + end + for k = 1, 4 do + qv[k] = buffer.readf32(rot.output.data, ((f - 1) * 4 + k - 1) * 4) + end + ok = ok and near(tv, jp.t, 1e-5) and sameQ(qv, jp.q) + end + end + t:check(ok, label .. ": every frame's pose") + t:eq(anim.channels[1].input.count, a.frames, label .. ": keys") + t:check(math.abs(buffer.readf32(anim.channels[1].input.data, 4) - 1 / a.rate) < 1e-6, label .. ": frame rate") +end +t:eq(#s.animations, 2, "two animations") +for i, a in Fx.anims do + checkAnim(s, a, s.animations[i], "mesh + " .. a.name) +end +do + local asked = {} + local r = Md5.decode(Bytes.reader(buffer.fromstring(M.data)), { + anims = { "walk.md5anim" }, + resolve = function(name: string): string? + table.insert(asked, name) + return files[name] + end, + }) :: any + t:check(r and #r.animations == 1 and asked[1] == "walk.md5anim", "opts.resolve") + local _, e = Md5.decode(Bytes.reader(buffer.fromstring(M.data)), { anims = { "run.md5anim" } }) + t:check(e and e.code == Err.UNSUPPORTED, "missing animation") + local skip = Md5.decode(Bytes.reader(buffer.fromstring(M.data)), { anims = { "run.md5anim" }, skipMissing = true }) :: any + t:check(skip and #skip.animations == 0, "skipMissing") + -- a standalone .md5anim + local a = Fx.anims[2] + local alone = Md5.decode(Bytes.reader(buffer.fromstring(a.data)), { name = "models/walk.md5anim" }) :: any + t:check(alone and #alone.skins == 1, "md5anim alone: skeleton") + checkAnim(alone, a, alone.animations[1], "md5anim alone") + t:eq(alone.meta.source.kind, "anim", "md5anim alone: kind") +end + +-- 4. errors, fuzz +do + local _, e1 = Md5.decode(Bytes.reader(buffer.fromstring("MD5Version 11\n"))) + t:check(e1 and e1.code == Err.UNSUPPORTED, "version 11") + local _, e2 = Md5.decode(Bytes.reader(buffer.fromstring(string.sub(M.data, 1, 900)))) + t:check(e2 ~= nil, "truncated: " .. tostring(e2)) +end +t:fuzz("decode", function(b: buffer) + return Md5.decode(Bytes.reader(b), { anims = { "idle.md5anim" }, files = files }) +end, { M.data, Fx.anims[1].data }, { mutations = 80 }) +t:done() diff --git a/tests/model/mdl.luau b/tests/model/mdl.luau new file mode 100644 index 0000000..6371cd2 --- /dev/null +++ b/tests/model/mdl.luau @@ -0,0 +1,155 @@ +-- model/mdl tests: a Quake 1 and a Half-Life 1 model written by tools/fixtures/mdl.py. Quake: assimp's frame-0 +-- triangle soup (positions, texture coordinates), every frame exact, skins through opts.palette / opts.resolve / +-- the grey ramp, frame-name animations. Half-Life: assimp's bind-pose soup per mesh (positions, texture +-- coordinates), the bones' TRS, the skin, every sequence's animation values against the writer's, textures with +-- their palettes, the skin family. Errors and the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Mdl = require("@formats/model/mdl") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Soup = require("@tests/model/_soup") +local Fx = require("@tests/gen/mdl") + +local t = T.suite("mdl") +t:eq(Mdl.name, "mdl", "name") + +local function near(a: { number }, b: { number }, tol: number): boolean + for i = 1, #b do + if math.abs(a[i] - b[i]) > tol then + return false + end + end + return true +end + +-- assimp mesh mi of a soup -> positions, uvs +local function assimpMesh(a: any, mi: number): ({ number }, { number }, number) + local m = a.per[mi] + local nextStart = if a.per[mi + 1] then a.per[mi + 1].start else a.faces + local nf = nextStart - m.start + return Soup.slice(a.pos, m.start * 9 + 1, nf * 9), Soup.slice(a.uv, m.start * 6 + 1, nf * 6), nf +end + +-- 1. Quake +do + local q = Fx.quake + local s, err = Mdl.decode(Bytes.reader(buffer.fromstring(q.data)), { palette = q.palette }) + t:check(s, "quake: " .. tostring(err)) + t:eq(F.detect(q.data), "mdl", "quake: F.detect") + local prim = s.meshes[1].primitives[1] + local apos, auv = assimpMesh(q.assimp, 1) + t:check(Soup.triangles(Soup.list(Soup.positions(prim)), apos, 1e-5), "quake: positions against assimp") + t:check(Soup.triangles(Soup.uvs(prim, 0, true), auv, 1e-5, 2), "quake: texture coordinates against assimp") + t:check(Soup.close(Soup.uvs(prim, 0), q.uv, 1e-6), "quake: texture coordinates (seam) against the writer") + t:eq(#q.crcs, s.meta.source.frames, "quake: frames (groups unrolled)") + for k, crc in q.crcs do + local f = Mdl.decode(Bytes.reader(buffer.fromstring(q.data)), { frame = k, morph = false, palette = q.palette }) :: any + t:eq(Crc32.of(Soup.positions(f.meshes[1].primitives[1])), crc, "quake: frame " .. k) + end + t:eq(#prim.targets, #q.crcs, "quake: morph targets") + local groups = {} + for _, a in s.animations do + table.insert(groups, a.name) + end + t:eq(table.concat(groups, ","), "stand,walk,death", "quake: animation groups") + t:eq(#s.textures, #q.skins, "quake: skins") + for i, crc in q.skins do + t:eq(Crc32.of(s.textures[i].image.pixels), crc, "quake: skin " .. i .. " through the palette") + end + local viaResolve = Mdl.decode(Bytes.reader(buffer.fromstring(q.data)), { + resolve = function(uri: string): string? + return if uri == "gfx/palette.lmp" then q.palette else nil + end, + }) :: any + t:eq(Crc32.of(viaResolve.textures[1].image.pixels), q.skins[1], "quake: palette through opts.resolve") + local grey = Mdl.decode(Bytes.reader(buffer.fromstring(q.data))) :: any + t:eq(Crc32.of(grey.textures[1].image.pixels), q.grey, "quake: grey ramp without a palette") + t:eq(grey.meta.source.palette, false, "quake: meta.source.palette") +end + +-- 2. Half-Life +do + local h = Fx.halflife + local s, err = Mdl.decode(Bytes.reader(buffer.fromstring(h.data))) + t:check(s, "halflife: " .. tostring(err)) + t:eq(F.detect(h.data), "mdl", "halflife: F.detect") + local mesh = s.meshes[1] + t:eq(#mesh.primitives, #h.tris, "halflife: a primitive per mesh") + t:eq(h.assimp.meshes, #h.tris, "halflife: assimp meshes") + local matched = 0 + for mi = 1, h.assimp.meshes do + local apos, auv, nf = assimpMesh(h.assimp, mi) + for _, p in mesh.primitives do + if p.indices.count == nf * 3 and Soup.triangles(Soup.list(Soup.positions(p)), apos, 1e-4) then + -- assimp's Half-Life loader stores v = -t / height + t:check(Soup.triangles(Soup.uvs(p, 0, "neg"), auv, 1e-5, 2), "halflife: texture coordinates against assimp") + matched += 1 + break + end + end + end + t:eq(matched, #h.tris, "halflife: every mesh matches assimp's bind-pose positions") + for i, p in mesh.primitives do + t:eq(p.indices.count, h.tris[i] * 3, "halflife: mesh " .. i .. " triangles") + t:check(p.attributes.JOINTS_0 and p.attributes.WEIGHTS_0, "halflife: skinned") + end + -- bones + local skin = s.skins[1] + t:eq(#skin.joints, #h.bones, "halflife: joints") + for i, bn in h.bones do + local node = s.nodes[skin.joints[i]] + t:eq(node.name, bn.name, "halflife: bone name " .. i) + t:check(near(node.translation, bn.t, 1e-6) and near(node.rotation, bn.q, 1e-6), "halflife: bone " .. bn.name .. " TRS") + end + -- animations + t:eq(#s.animations, #h.sequences, "halflife: sequences") + for si, sq in h.sequences do + local a = s.animations[si] + t:eq(a.name, sq.name, "halflife: sequence name") + local byNode = {} + for _, ch in a.channels do + byNode[ch.node .. ch.path] = ch + end + local ok = true + for bi, frames in sq.bones do + local node = skin.joints[bi] + local tch, rch = byNode[node .. "translation"], byNode[node .. "rotation"] + for f, fr in frames do + for k = 1, 3 do + ok = ok and math.abs(buffer.readf32(tch.output.data, ((f - 1) * 3 + k - 1) * 4) - fr.t[k]) < 1e-4 + end + for k = 1, 4 do + ok = ok and math.abs(buffer.readf32(rch.output.data, ((f - 1) * 4 + k - 1) * 4) - fr.q[k]) < 1e-5 + end + end + t:eq(tch.input.count, sq.frames, "halflife: " .. sq.name .. " keys") + t:check(math.abs(buffer.readf32(tch.input.data, 4) - 1 / sq.fps) < 1e-6, "halflife: " .. sq.name .. " fps") + end + t:check(ok, "halflife: " .. sq.name .. ": every value against the writer") + end + -- textures, skin family 0 + for i, tx in h.textures do + t:eq(s.textures[i].name, tx.name, "halflife: texture name") + t:eq(Crc32.of(s.textures[i].image.pixels), tx.crc, "halflife: texture " .. i .. " through its palette") + end + t:eq(mesh.primitives[1].material, 1, "halflife: mesh 1 -> skin ref 0 -> texture 1") + t:eq(mesh.primitives[2].material, 2, "halflife: mesh 2 -> skin ref 1 -> texture 2") +end + +-- 3. errors, fuzz +do + local _, e1 = Mdl.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.quake.data, 1, 200)))) + t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "quake truncated: " .. tostring(e1)) + local _, e2 = Mdl.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.halflife.data, 1, 300)))) + t:check(e2 ~= nil, "halflife truncated: " .. tostring(e2)) + local src = buffer.fromstring(Fx.halflife.data) + buffer.writei32(src, 4, 48) + local _, e3 = Mdl.decode(Bytes.reader(src)) + t:check(e3 and e3.code == Err.UNSUPPORTED, "Source engine MDL") +end +t:fuzz("decode", function(b: buffer) + return Mdl.decode(Bytes.reader(b), { palette = Fx.quake.palette }) +end, { Fx.quake.data, Fx.halflife.data }, { mutations = 200 }) +t:done() diff --git a/tests/model/smd.luau b/tests/model/smd.luau new file mode 100644 index 0000000..7b384c0 --- /dev/null +++ b/tests/model/smd.luau @@ -0,0 +1,176 @@ +-- model/smd tests: SMD files written by tools/fixtures/smd.py decode to assimp's triangle soup (positions, texture +-- coordinates per material) and to the writer's exact values (bind pose TRS, per-vertex weights and joints, every +-- skeleton frame of the animation); an animation-only SMD; our writer's output re-read by us (same soup, weights, +-- poses) and by assimp (faces, bones); errors; the fuzz pass. Fixtures: tools/fixtures/smd.py. +local T = require("@tests/T") +local F = require("@formats") +local Smd = require("@formats/model/smd") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Soup = require("@tests/model/_soup") +local Fx = require("@tests/gen/smd") + +local t = T.suite("smd") +t:eq(Smd.name, "smd", "name") + +local function near(a: { number }, b: { number }, tol: number): boolean + for i = 1, #b do + if math.abs(a[i] - b[i]) > tol then + return false + end + end + return true +end +-- same rotation (q or -q) +local function sameQ(a: { number }, b: { number }): boolean + return near(a, b, 1e-5) or near(a, { -b[1], -b[2], -b[3], -b[4] }, 1e-5) +end + +local function check(s: any, c: any, label: string) + local skin = s.skins[1] + t:eq(#skin.joints, #c.bones, label .. ": joints") + for i, bn in c.bones do + local node = s.nodes[skin.joints[i]] + t:eq(node.name, bn.name, label .. ": bone name " .. i) + local pose = c.frames[1][i] + t:check(near(node.translation, pose.t, 1e-5) and sameQ(node.rotation, pose.q), label .. ": bind pose " .. bn.name) + end + if #c.tris > 0 then + local prims = s.meshes[1].primitives + t:eq(#prims, #c.materials, label .. ": a primitive per material") + -- every triangle of the writer, in file order per material + for pi, p in prims do + local mat = s.materials[p.material].name + local pos = Types.Scene.reader(p.attributes.POSITION) :: any + local uv = Types.Scene.reader(p.attributes.TEXCOORD_0) :: any + local jr = Types.Scene.reader(p.attributes.JOINTS_0) :: any + local wr = Types.Scene.reader(p.attributes.WEIGHTS_0) :: any + local k = 0 + local ok, wok = true, true + for _, tri in c.tris do + if tri.material == mat then + for ci, cn in tri.corners do + local v = buffer.readu32(p.indices.data, (k * 3 + ci - 1) * 4) + ok = ok and near({ pos(v, 0), pos(v, 1), pos(v, 2) }, cn.p, 1e-5) and near({ uv(v, 0), 1 - uv(v, 1) }, cn.uv, 1e-6) + local got = {} + for wi = 0, 3 do + if wr(v, wi) > 0 then + got[jr(v, wi)] = wr(v, wi) + end + end + for _, w in cn.w do + wok = wok and got[w[1]] ~= nil and math.abs(got[w[1]] - w[2]) < 1e-5 + end + end + k += 1 + end + end + t:check(ok, label .. ": " .. mat .. " positions / texture coordinates") + t:check(wok, label .. ": " .. mat .. " joints / weights") + t:eq(p.indices.count, k * 3, label .. ": " .. mat .. " triangles") + local _ = pi + end + end + if #c.frames > 1 then + local a = s.animations[1] + local byNode = {} + for _, ch in a.channels do + byNode[ch.node .. ch.path] = ch + end + local ok = true + for f, pose in c.frames do + for i, bp in pose do + local node = skin.joints[i] + local tr, rot = byNode[node .. "translation"], byNode[node .. "rotation"] + local tv, qv = {}, {} + for k = 1, 3 do + tv[k] = buffer.readf32(tr.output.data, ((f - 1) * 3 + k - 1) * 4) + end + for k = 1, 4 do + qv[k] = buffer.readf32(rot.output.data, ((f - 1) * 4 + k - 1) * 4) + end + ok = ok and near(tv, bp.t, 1e-5) and sameQ(qv, bp.q) + end + end + t:check(ok, label .. ": every skeleton frame") + t:eq(a.channels[1].input.count, #c.frames, label .. ": keys") + end +end + +for _, c in Fx.cases do + local s, err = Smd.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(s, c.name .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "smd", c.name .. ": F.detect") + check(s, c, c.name) + if not c.assimp.failed then + local matched = 0 + for mi, m in c.assimp.per do + local nextStart = if c.assimp.per[mi + 1] then c.assimp.per[mi + 1].start else c.assimp.faces + local nf = nextStart - m.start + local apos = Soup.slice(c.assimp.pos, m.start * 9 + 1, nf * 9) + local auv = Soup.slice(c.assimp.uv, m.start * 6 + 1, nf * 6) + for _, p in s.meshes[1].primitives do + if p.indices.count == nf * 3 and Soup.triangles(Soup.list(Soup.positions(p)), apos, 1e-5) then + t:check(Soup.triangles(Soup.uvs(p, 0, true), auv, 1e-5, 2), c.name .. ": texture coordinates against assimp") + matched += 1 + break + end + end + end + t:eq(matched, #c.materials, c.name .. ": every material mesh matches assimp's positions") + end + -- our writer, read back by us + local out = Smd.encode(s) :: buffer + local back, berr = Smd.decode(Bytes.reader(out)) + t:check(back, c.name .. ": re-read our SMD: " .. tostring(berr)) + local again = table.clone(c) + again.frames = { c.frames[1] } + check(back, again, c.name .. " (written)") + if #c.frames > 1 then + local anim = Smd.decode(Bytes.reader(Smd.encode(s, { animation = 1 }) :: buffer)) :: any + local only = table.clone(c) + only.tris = {} + check(anim, only, c.name .. " (written animation)") + end + -- assimp reads our output + local ours = Fx.ours[c.name] + if ours and #c.tris > 0 then + t:eq(ours.faces, #c.tris, c.name .. ": assimp reads our triangles") + local soupOk = ours.soup and not ours.soup.failed and ours.soup.faces == #c.tris + t:check(soupOk, c.name .. ": assimp soup of our file") + end +end + +-- a scene without a skin writes one root bone +do + local prim: any = { + attributes = { POSITION = Types.Scene.accessor(buffer.create(36), "f32", 3, 3) }, + mode = "triangles", + } + buffer.writef32(prim.attributes.POSITION.data, 12, 1) + buffer.writef32(prim.attributes.POSITION.data, 28, 1) + local text = buffer.tostring(Smd.encode(Types.Scene.fromPrimitive(prim)) :: buffer) + t:check(string.find(text, '0 "root" -1', 1, true) ~= nil, "static scene: a root bone") + local back = Smd.decode(Bytes.reader(buffer.fromstring(text))) :: any + t:eq(back.meshes[1].primitives[1].indices.count, 3, "static scene round trip") + local _, e1 = Smd.encode({ kind = "image" } :: any) + t:check(e1 and e1.code == Err.ARG, "encode a non-scene") + local _, e2 = Smd.decode(Bytes.reader(buffer.fromstring("version 1\nnodes\n0 \"a\" -1\n"))) + t:check(e2 and e2.code == Err.TRUNCATED, "nodes without end: " .. tostring(e2)) + local _, e3 = Smd.decode(Bytes.reader(buffer.fromstring("version 2\nnodes\nend\n"))) + t:check(e3 and e3.code == Err.UNSUPPORTED, "version 2") +end + +local samples = {} +for _, c in Fx.cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local s = Smd.decode(Bytes.reader(b)) + if s then + Smd.encode(s) + end + return s +end, samples, { mutations = 60 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 7e1ef28..366db73 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1138,6 +1138,48 @@ do jitTune(false) end end +do + -- game formats (ws-game): PKWARE DCL explode (StormLib's implode streams from tools/fixtures/mpq.py), reading every + -- file of a StormLib MPQ (MB/s of file data), Freedoom's MAP01 to a Scene (tools/fixtures/wad.py: sector + -- outlines, triangulation, walls; MB/s of map lumps), an MD2 with every frame as a morph target + local Explode = require("@formats/codecs/compress/Explode") + local Mpq = require("@formats/archive/mpq") + local Wad = require("@formats/archive/wad") + local MQ = require("@tests/gen/mpq") + local WD = require("@tests/gen/wad") + for _, c in MQ.implode do + if c.name == "text" or c.name == "ascii-4096" or c.name == "binary-2048" then + local data = buffer.fromstring(c.data) + bench("explode " .. c.name .. " (" .. c.size .. " B)", 20, c.size, function() + Explode.decompress(data) + end) + end + end + local arch = MQ.archives[1] + local mb = buffer.fromstring(arch.data) + local a = assert(Mpq.decode(Bytes.reader(mb))) + local total = 0 + for _, e in a:list() do + total += e.size + end + bench("mpq read every file (v1)", 5, total, function() + local m = Mpq.decode(Bytes.reader(mb)) + for _, e in m:list() do + m:read(e.name) + end + end) + local wb = buffer.fromstring(WD.freedoom.data) + local w = assert(Wad.decode(Bytes.reader(wb))) + local lumps = 0 + for _, l in Wad.lumps(w) :: any do + if l.map == "MAP01" then + lumps += l.size + end + end + bench("wad MAP01 -> Scene (no textures)", 3, lumps, function() + Wad.map(w, "MAP01", { textures = false }) + end) +end do -- Draco (codecs/model/Draco): the Stanford bunny (35k points, 69k faces, Edgebreaker valence, normals) and a UV -- sphere with seams; MB/s of decoded output (u32 indices + f32 attributes per point), plus triangles per second. diff --git a/tools/fixtures/_quake_ref.py b/tools/fixtures/_quake_ref.py new file mode 100644 index 0000000..7788f2e --- /dev/null +++ b/tools/fixtures/_quake_ref.py @@ -0,0 +1,36 @@ +# Shared helpers for the Quake-family model fixtures (md2.py, md3.py, mdl.py): assimp's triangle soup. +# assimp_soup(ctx, data, ext) -> { pos = [floats], uv = [floats], meshes, faces } | { failed = True }: every triangle +# mesh of `assimp export -f assjson`, faces in order, each face's corners in assimp's index order (positions x3, +# texture coordinates u, v of set 0); per = [ { name, start } ]: each mesh's name and first face +import json, os, shutil, subprocess, tempfile + + +def assimp_soup(ctx, data, ext): + tmp = tempfile.mkdtemp(prefix="formats-quake-") + try: + src = os.path.join(tmp, "in." + ext) + open(src, "wb").write(data) + out = os.path.join(tmp, "out.json") + try: + ctx.nix("assimp", ["assimp", "export", src, out, "-f", "assjson"]) + except subprocess.CalledProcessError: + return {"failed": True} + j = json.load(open(out)) + finally: + shutil.rmtree(tmp) + pos, uv, faces, meshes, per = [], [], 0, 0, [] + for m in j.get("meshes", []): + if m.get("primitivetypes") != 4: + continue + meshes += 1 + per.append({"name": m.get("name", ""), "start": faces}) + v = m["vertices"] + t = (m.get("texturecoords") or [[]])[0] + nc = (m.get("numuvcomponents") or [2])[0] + for f in m["faces"]: + faces += 1 + for i in f: + pos += v[i * 3:i * 3 + 3] + if t: + uv += t[i * nc:i * nc + 2] + return {"pos": pos, "uv": uv, "faces": faces, "meshes": meshes, "per": per} diff --git a/tools/fixtures/_smd_encode.luau b/tools/fixtures/_smd_encode.luau new file mode 100644 index 0000000..2e9bde2 --- /dev/null +++ b/tools/fixtures/_smd_encode.luau @@ -0,0 +1,22 @@ +-- tools/fixtures/_smd_encode.luau: run by tools/fixtures/smd.py under the luau CLI: decodes the reference SMDs of +-- tests/gen/smd_src and writes them back with our encoder (bind pose; links; and the animation as an animation SMD), +-- printing "\t" lines for assimp to read back. +local Smd = require("@formats/model/smd") +local Bytes = require("@formats/core/Bytes") +local Src = require("@tests/gen/smd_src") + +local function hex(b: buffer): string + return (string.gsub(buffer.tostring(b), ".", function(c: string): string + return string.format("%02x", string.byte(c)) + end)) +end + +for _, c in Src do + local s = Smd.decode(Bytes.reader(buffer.fromstring(c.data))) + if s then + print(c.name .. "\t" .. hex(Smd.encode(s) :: buffer)) + if #s.animations > 0 then + print(c.name .. "-anim\t" .. hex(Smd.encode(s, { animation = 1 }) :: buffer)) + end + end +end diff --git a/tools/fixtures/_vpk_encode.luau b/tools/fixtures/_vpk_encode.luau new file mode 100644 index 0000000..3b1db18 --- /dev/null +++ b/tools/fixtures/_vpk_encode.luau @@ -0,0 +1,20 @@ +-- tools/fixtures/_vpk_encode.luau: run by tools/fixtures/vpk.py under the luau CLI: writes the files of +-- tests/gen/vpk_src as VPK version 1 and 2 with our encoder and prints "\t" lines for Python's vpk +-- package to read back (and verify the version 2 MD5s). +local Vpk = require("@formats/archive/vpk") +local Src = require("@tests/gen/vpk_src") + +local function hex(b: buffer): string + local s = buffer.tostring(b) + return (string.gsub(s, ".", function(c: string): string + return string.format("%02x", string.byte(c)) + end)) +end + +for _, version in { 1, 2 } do + local a = Vpk.new(version) + for _, f in Src do + a:add(f.name, f.data) + end + print("v" .. version .. "\t" .. hex(a:write() :: buffer)) +end diff --git a/tools/fixtures/blp.py b/tools/fixtures/blp.py new file mode 100644 index 0000000..1089607 --- /dev/null +++ b/tools/fixtures/blp.py @@ -0,0 +1,159 @@ +# Blizzard BLP fixtures (tools/fixtures.py). Pillow (nix python3 pillow) is the reference decoder: it writes BLP2 +# palette files itself (not BLP1: Pillow 12 writes BLP1 mip offsets as if the header were BLP2's, 8 bytes short), and decodes the files written here from the wowdev.wiki layout: BLP2 DXT1 / DXT3 / DXT5 +# (random blocks), palette with 1 / 4 / 8-bit alpha planes, mip chains, and BLP1 JPEG (a Pillow +# JPEG split into the shared header and the mip data). Pillow's RGBA -> CRC-32. Two cases Pillow reads differently +# from the games (or not at all) are checked against this writer instead: uncompressed BGRA (Pillow 12 has no +# encoding 3), BLP1 palette files with an 8-bit alpha plane, and BLP1 +# JPEGs of 4 components (BGRA without colour conversion: CMYK written inverted by Pillow, its Adobe marker removed) +# whose reference is the source pixels (PSNR). +# tests/gen/blp.luau { { name, data, width, height, crc?, rgba?, psnr? } } +import io, json, struct, zlib + +CODE = r""" +import io, json, sys, zlib, random, struct +from PIL import Image +args = json.loads(sys.stdin.read()) +rng = random.Random(args["seed"]) +out = {} + +def rgba_crc(im): + return zlib.crc32(im.convert("RGBA").tobytes()) + +# 1. Pillow-written palette BLPs +pal_img = Image.new("P", (13, 7)) +pal_img.putpalette(bytes(rng.randrange(256) for _ in range(768))) +pal_img.putdata([rng.randrange(256) for _ in range(13 * 7)]) +for v in ("BLP2",): + b = io.BytesIO() + pal_img.save(b, "BLP", blp_version=v) + data = b.getvalue() + out["pillow-" + v.lower()] = {"data": data.hex(), "crc": rgba_crc(Image.open(io.BytesIO(data))), "w": 13, "h": 7} + +# 2. Pillow decodes the hand-made files +for name, hexdata in args["files"].items(): + try: + im = Image.open(io.BytesIO(bytes.fromhex(hexdata))) + im.load() + out[name] = {"crc": rgba_crc(im), "w": im.size[0], "h": im.size[1], "rgba": im.convert("RGBA").tobytes().hex()} + except Exception as e: + out[name] = {"failed": str(e)} + +# 3. JPEGs for BLP1: a 3-component one and a 4-component (CMYK) one +src = Image.new("RGB", (24, 16)) +src.putdata([(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(24 * 16)]) +src = src.resize((24, 16)) +b = io.BytesIO(); src.save(b, "JPEG", quality=95) +out["jpeg3"] = b.getvalue().hex() +# smooth RGBA source pixels for the 4-component file, stored as B, G, R, A components +px = [((x * 10) % 256, (y * 15) % 256, ((x + y) * 7) % 256, (255 - x * 8) % 256) for y in range(16) for x in range(24)] +cm = Image.new("CMYK", (24, 16)) +# Pillow stores CMYK inverted: write 255 - (b, g, r, a) so the stored components are B, G, R, A +cm.putdata([(255 - p[2], 255 - p[1], 255 - p[0], 255 - p[3]) for p in px]) +b = io.BytesIO(); cm.save(b, "JPEG", quality=98) +out["jpeg4"] = b.getvalue().hex() +out["jpeg4src"] = bytes(c for p in px for c in p).hex() +print(json.dumps(out)) +""" + + +def blp2(kind, comp, adepth, atype, w, h, mips, palette=b"\0" * 1024): + offs, lens, at = [], [], 1172 + for m in mips: + offs.append(at) + lens.append(len(m)) + at += len(m) + offs += [0] * (16 - len(mips)) + lens += [0] * (16 - len(mips)) + head = b"BLP2" + struct.pack(" 1 else 0, w, h) + return head + struct.pack("<16I", *offs) + struct.pack("<16I", *lens) + palette + b"".join(mips) + + +def blp1(comp, adepth, w, h, mips, extra=b""): + base = 156 + len(extra) + offs, lens, at = [], [], base + for m in mips: + offs.append(at) + lens.append(len(m)) + at += len(m) + offs += [0] * (16 - len(mips)) + lens += [0] * (16 - len(mips)) + return b"BLP1" + struct.pack("<6I", comp, adepth, w, h, 4, 1 if len(mips) > 1 else 0) + struct.pack("<16I", *offs) + struct.pack("<16I", *lens) + extra + b"".join(mips) + + +def split_jpeg(j): + # the shared header: everything before the first SOS marker + k = j.index(b"\xff\xda") + return j[:k], j[k:] + + +def strip_adobe(j): + i = j.find(b"\xff\xee") + if i < 0: + return j + n = struct.unpack(">H", j[i + 2:i + 4])[0] + return j[:i] + j[i + 2 + n:] + + +def generate(ctx): + rng = ctx.rng(121) + w, h = 16, 12 + files = {} + for name, atype, bs in (("dxt1", 0, 8), ("dxt3", 1, 16), ("dxt5", 7, 16)): + blocks = rng.randbytes((w // 4) * (h // 4) * bs) + files[name] = blp2(1, 2, 1 if name == "dxt1" else 8, atype, w, h, [blocks, rng.randbytes(2 * 2 * bs)]) # mip 1: 8 x 6 + bgra = rng.randbytes(w * h * 4) + own = [{"name": "bgra", "data": blp2(1, 3, 8, 8, w, h, [bgra]), "width": w, "height": h, + "rgba": b"".join(bytes((bgra[i + 2], bgra[i + 1], bgra[i], bgra[i + 3])) for i in range(0, len(bgra), 4))}] + pal = bytes(rng.randrange(256) for _ in range(1024)) + alphas = {} + for depth in (0, 1, 4, 8): + idx = rng.randbytes(w * h) + alpha = rng.randbytes({0: 0, 1: w * h // 8, 4: w * h // 2, 8: w * h}[depth]) + files["palette-a%d" % depth] = blp2(1, 1, depth, 0, w, h, [idx + alpha], pal) + # the alpha plane (LSB first), expanded to 8 bits + if depth == 1: + alphas[depth] = bytes(255 if alpha[i // 8] >> (i % 8) & 1 else 0 for i in range(w * h)) + elif depth == 4: + alphas[depth] = bytes(((alpha[i // 2] >> (4 * (i % 2))) & 15) * 17 for i in range(w * h)) + elif depth == 8: + alphas[depth] = alpha + res = json.loads(ctx.python(["pillow"], CODE, input=json.dumps({"seed": 5, "files": {k: v.hex() for k, v in files.items()}}).encode())) + out = [] + for name in ("pillow-blp2",): + r = res[name] + out.append({"name": name, "data": bytes.fromhex(r["data"]), "width": r["w"], "height": r["h"], "crc": r["crc"]}) + for name, data in files.items(): + r = res[name] + if "failed" in r: + raise SystemExit("blp: Pillow cannot read %s: %s" % (name, r["failed"])) + e = {"name": name, "data": data, "width": r["w"], "height": r["h"]} + if name.startswith("dxt"): + # Pillow's own DXT decoder expands the 5 / 6-bit endpoints by shifting only (r << 3), the D3D rule + # replicates the top bits (r << 3 | r >> 2), and divides by 3 without rounding: colours compared within + # 8, alpha exactly + e["ref"], e["tol"] = bytes.fromhex(r["rgba"]), 8 + elif name.startswith("palette-a") and name != "palette-a0": + # Pillow ignores the alpha plane (it takes the palette's alpha): RGB from Pillow, alpha from the writer + e["rgbref"], e["alpha"] = bytes.fromhex(r["rgba"]), alphas[int(name[-1])] + else: + e["crc"] = r["crc"] + out.append(e) + out += own + # BLP1 JPEG, 3 components: Pillow decodes it (YCbCr -> RGB, then R / B swapped) + j3 = bytes.fromhex(res["jpeg3"]) + hd, body = split_jpeg(j3) + d = blp1(0, 0, 24, 16, [body], struct.pack("= 0 else [0] + [k - i for i in range(1, k)] + out = [] + for i in range(1, k - 1): + out += [order[0], order[i], order[i + 1]] + return out + + +def brush_map(rng, variant, pal): + q2 = variant == "q2" + faces = [(f, 0) for f in box((-64, -64, 0), (64, 64, 128))] + [(f, 1) for f in box((-8, -8, 8), (8, 8, 40))] + verts, edges, surfedges, planes, texinfo, flist = [], [(0, 0)], [], [], [], [] + vindex = {} + + def vid(p): + p = tuple(f32(c) for c in p) + if p not in vindex: + vindex[p] = len(verts) + verts.append(p) + return vindex[p] + texnames = ["brick", "door"] if q2 else ["brick", "+0door"] + sizes = [(16, 8), (8, 8)] + tis = [] + for t in range(2): + s = [f32(rng.uniform(-1, 1)) for _ in range(3)] + [f32(rng.uniform(-8, 8))] + tt = [f32(rng.uniform(-1, 1)) for _ in range(3)] + [f32(rng.uniform(-8, 8))] + tis.append((s, tt)) + texinfo.append((s, tt, t)) + models = {} + for i, ((poly, n), model) in enumerate(faces): + tex = model + side = i % 3 == 2 + pn = tuple(-c for c in n) if side else n + planes.append((pn, 0.0)) + first = len(surfedges) + ids = [vid(p) for p in poly] + for k in range(len(ids)): + a, b = ids[k], ids[(k + 1) % len(ids)] + if k % 2 == 0: + edges.append((a, b)) + surfedges.append(len(edges) - 1) + else: + edges.append((b, a)) + surfedges.append(-(len(edges) - 1)) + flist.append((len(planes) - 1, 1 if side else 0, first, len(ids), tex)) + # expected triangles + fp = [tuple(f32(c) for c in p) for p in poly] + s, tt = tis[tex] + w, h = (sizes[tex] if variant != "q2" else (sizes[tex] if tex == 0 else (1, 1))) + e = models.setdefault(model, {}).setdefault(texnames[tex], {"pos": [], "uv": [], "nrm": []}) + for c in ccw_fan(fp, n): + x, y, z = fp[c] + e["pos"] += [x, y, z] + e["nrm"] += list(n) + e["uv"] += [(x * s[0] + y * s[1] + z * s[2] + s[3]) / w, (x * tt[0] + y * tt[1] + z * tt[2] + tt[3]) / h] + # lumps + L = {} + L["entities"] = ENTS + L["planes"] = b"".join(struct.pack("<4fi", *n, d, 0) for n, d in planes) + L["vertices"] = b"".join(struct.pack("<3f", *v) for v in verts) + L["edges"] = b"".join(struct.pack("<2H", *e) for e in edges) + L["surfedges"] = b"".join(struct.pack(" 7 else (0, 0) + fb += struct.pack("<8i2i2i3f6f3f2i", sh, -1, kind, first, n, mv, nmv, lm, 0, 0, 0, 0, *([0.0] * 12), w, h) + L["faces"] = fb + lms = [bytes(rng.randrange(256) for _ in range(128 * 128 * 3)) for _ in range(2)] + L["lightmaps"] = b"".join(lms) + names = ["entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes", + "brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata"] + off = 8 + 8 * len(names) + body, dirs = b"", [] + for n in names: + d = L.get(n, b"") + dirs.append((off + len(body), len(d))) + body += d + b"\0" * ((4 - len(d) % 4) % 4) + data = b"IBSP" + struct.pack("> 8) & 255) * math.pi / 128 + lng = (n & 255) * math.pi / 128 + return (math.cos(lat) * math.sin(lng), math.sin(lat) * math.sin(lng), math.cos(lng)) + + +def surface(rng, name, shader, nframes, nverts, ntris): + tris = [tuple(rng.sample(range(nverts), 3)) for _ in range(ntris)] + st = [(f32(rng.uniform(0, 1)), f32(rng.uniform(0, 1))) for _ in range(nverts)] + xyz = [[(rng.randrange(-3000, 3000), rng.randrange(-3000, 3000), rng.randrange(-3000, 3000), rng.randrange(65536)) for _ in range(nverts)] for _ in range(nframes)] + o_tri = 108 + o_sh = o_tri + 12 * ntris + o_st = o_sh + 68 + o_xyz = o_st + 8 * nverts + o_end = o_xyz + 8 * nverts * nframes + out = struct.pack("<4s64siiiiiiiiii", b"IDP3", name.encode(), 0, nframes, 1, nverts, ntris, o_tri, o_sh, o_st, o_xyz, o_end) + for t in tris: + out += struct.pack("<3i", *t) + out += struct.pack("<64si", shader.encode(), 0) + for s in st: + out += struct.pack("<2f", *s) + for f in xyz: + for x, y, z, n in f: + out += struct.pack("<3hH", x, y, z, n) + crcs, ncrcs = [], [] + for f in xyz: + soup, nsoup = b"", b"" + for t in tris: + for c in (2, 1, 0): + x, y, z, n = f[t[c]] + soup += struct.pack("<3f", x / 64, y / 64, z / 64) + nsoup += struct.pack("<3f", *normal(n)) + crcs.append(zlib.crc32(soup)) + ncrcs.append(zlib.crc32(nsoup)) + return out, {"name": name, "shader": shader, "tris": ntris, "crcs": crcs, "ncrcs": ncrcs} + + +def md3(rng, nframes, surfs, ntags): + frames = b"" + for i in range(nframes): + frames += struct.pack("<10f16s", *([0.0] * 10), b"frame%d" % i) + tags, tagref = b"", [] + for f in range(nframes): + for k in range(ntags): + o = tuple(f32(rng.uniform(-10, 10)) for _ in range(3)) + ang = rng.uniform(0, math.pi) + ax = ((math.cos(ang), math.sin(ang), 0.0), (-math.sin(ang), math.cos(ang), 0.0), (0.0, 0.0, 1.0)) + tags += struct.pack("<64s12f", b"tag_%d" % k, *o, *[c for a in ax for c in a]) + tagref.append({"name": "tag_%d" % k, "frame": f + 1, "origin": list(o), "angle": ang}) + body, info = b"", [] + for args in surfs: + s, i = surface(rng, args[0], args[1], nframes, args[2], args[3]) + body += s + info.append(i) + o_frames = 108 + o_tags = o_frames + len(frames) + o_surf = o_tags + len(tags) + o_end = o_surf + len(body) + head = struct.pack("<4si64siiiiiiiii", b"IDP3", 15, b"models/test/test.md3", 0, nframes, ntags, len(surfs), 0, o_frames, o_tags, o_surf, o_end) + return head + frames + tags + body, info, tagref + + +def generate(ctx): + rng = ctx.rng(63) + R = ref(ctx) + out = [] + for name, nframes, surfs, ntags in [("two-surfaces", 4, [("body", "models/test/body.tga", 30, 40), ("head", "models/test/head", 12, 10)], 2), + ("one-frame", 1, [("s", "textures/x.tga", 8, 6)], 0)]: + data, info, tags = md3(rng, nframes, surfs, ntags) + out.append({"name": name, "data": data, "frames": nframes, "surfaces": info, "tags": tags, "assimp": R.assimp_soup(ctx, data, "md3")}) + ctx.emit("md3", out) diff --git a/tools/fixtures/md5.py b/tools/fixtures/md5.py new file mode 100644 index 0000000..f2a9b56 --- /dev/null +++ b/tools/fixtures/md5.py @@ -0,0 +1,145 @@ +# Doom 3 MD5 fixtures (tools/fixtures.py): an .md5mesh (random joint hierarchy in model space, two meshes whose +# vertices hang off 1-3 weights) and two .md5anim files (animated component flags, baseframe, frames) written here +# from the format notes; references: assimp's triangle soup of the bind pose (positions, texture coordinates) and +# this writer's own values (bind positions from the weights, joints, every frame's parent-relative pose). +# tests/gen/md5.luau { mesh = { data, joints, positions = { per mesh: { x, y, z, ... } }, tris, assimp }, +# anims = { { name, data, frames, rate, poses = { [frame] = { [joint] = { t, q } } } } } } +import importlib.util, math, os, random + +INPUTS = ["tools/fixtures/_quake_ref.py"] + + +def ref(ctx): + spec = importlib.util.spec_from_file_location("_quake_ref", os.path.join(ctx.root, "tools", "fixtures", "_quake_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def r6(v): + return float("%.6f" % v) + + +def quat_w(x, y, z): + t = 1 - x * x - y * y - z * z + return 0.0 if t < 0 else -math.sqrt(t) + + +def rand_q(rng): + # a random unit quaternion with w <= 0 (stored as x, y, z) + while True: + q = [rng.uniform(-1, 1) for _ in range(4)] + n = math.sqrt(sum(c * c for c in q)) + if n > 0.1: + q = [c / n for c in q] + if q[3] > 0: + q = [-c for c in q] + return [r6(q[0]), r6(q[1]), r6(q[2])] + + +def rotate(q, v): + qx, qy, qz, qw = q + vx, vy, vz = v + tx, ty, tz = 2 * (qy * vz - qz * vy), 2 * (qz * vx - qx * vz), 2 * (qx * vy - qy * vx) + return (vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx)) + + +def mesh(rng, njoints=5): + joints = [] + lines = ["MD5Version 10", 'commandline "written by tools/fixtures/md5.py"', "", "numJoints %d" % njoints, "numMeshes 2", "", "joints {"] + for i in range(njoints): + parent = -1 if i == 0 else rng.randrange(i) + p = [r6(rng.uniform(-30, 30)) for _ in range(3)] + q = rand_q(rng) + joints.append({"name": "joint%d" % i, "parent": parent + 1, "pos": p, "q": q + [quat_w(*q)]}) + lines.append('\t"joint%d"\t%d ( %s ) ( %s )\t\t// comment' % (i, parent, " ".join("%.6f" % c for c in p), " ".join("%.6f" % c for c in q))) + lines.append("}") + positions, tris_all, uvs = [], [], [] + for m in range(2): + nverts, ntris = 8 + m * 4, 6 + m * 2 + verts, weights = [], [] + for v in range(nverts): + k = rng.randrange(1, 4) + ws = [rng.uniform(0.2, 1) for _ in range(k)] + s = sum(ws) + ws = [r6(w / s) for w in ws] + start = len(weights) + for j, w in zip(rng.sample(range(njoints), k), ws): # distinct joints per vertex (assimp 6 crashes on repeats) + weights.append((j, w, [r6(rng.uniform(-5, 5)) for _ in range(3)])) + verts.append(([r6(rng.random()), r6(rng.random())], start, k)) + # every vertex in some triangle (assimp 6's MD5 loader corrupts memory on unused vertices) + order = list(range(nverts)) + rng.shuffle(order) + tris = [(order[i % nverts], order[(i + 1) % nverts], order[(i + 2) % nverts]) for i in range(0, nverts, 3)] + tris += [tuple(rng.sample(range(nverts), 3)) for _ in range(ntris - len(tris))] + lines += ["", "mesh {", '\tshader "models/test/skin%d"' % m, "", "\tnumverts %d" % nverts] + for i, (st, start, k) in enumerate(verts): + lines.append("\tvert %d ( %.6f %.6f ) %d %d" % (i, st[0], st[1], start, k)) + lines.append("\n\tnumtris %d" % ntris) + for i, t in enumerate(tris): + lines.append("\ttri %d %d %d %d" % (i, *t)) + lines.append("\n\tnumweights %d" % len(weights)) + for i, (j, b, p) in enumerate(weights): + lines.append("\tweight %d %d %.6f ( %s )" % (i, j, b, " ".join("%.6f" % c for c in p))) + lines.append("}") + pos = [] + for st, start, k in verts: + acc = [0.0, 0.0, 0.0] + for j, b, p in weights[start:start + k]: + jt = joints[j] + r = rotate(jt["q"], p) + for c in range(3): + acc[c] += (jt["pos"][c] + r[c]) * b + pos += acc + positions.append(pos) + tris_all.append(len(tris)) + uvs.append([c for st, s, k in verts for c in st]) + return "\n".join(lines) + "\n", {"joints": joints, "positions": positions, "tris": tris_all, "uvs": uvs} + + +def anim(rng, joints, nframes, rate, name): + nj = len(joints) + flags = [rng.randrange(64) for _ in range(nj)] + base = [[r6(rng.uniform(-10, 10)) for _ in range(3)] + rand_q(rng) for _ in range(nj)] + starts, n = [], 0 + for f in flags: + starts.append(n) + n += bin(f).count("1") + lines = ["MD5Version 10", 'commandline ""', "", "numFrames %d" % nframes, "numJoints %d" % nj, "frameRate %d" % rate, "numAnimatedComponents %d" % n, "", "hierarchy {"] + for i, j in enumerate(joints): + lines.append('\t"%s"\t%d %d %d' % (j["name"], j["parent"] - 1, flags[i], starts[i])) + lines += ["}", "", "bounds {"] + ["\t( -1 -1 -1 ) ( 1 1 1 )"] * nframes + ["}", "", "baseframe {"] + for b in base: + lines.append("\t( %s ) ( %s )" % (" ".join("%.6f" % c for c in b[:3]), " ".join("%.6f" % c for c in b[3:]))) + lines.append("}") + poses = [] + for f in range(nframes): + vals, pose = [], [] + for i in range(nj): + v = list(base[i]) + for bit in range(6): + if flags[i] & (1 << bit): + if bit < 3: + x = r6(rng.uniform(-10, 10)) + else: + x = r6(rng.uniform(-0.5, 0.5)) + v[bit] = x + vals.append(x) + pose.append({"t": v[:3], "q": v[3:] + [quat_w(*v[3:])]}) + poses.append(pose) + lines += ["", "frame %d {" % f, "\t" + " ".join("%.6f" % x for x in vals), "}"] + return "\n".join(lines) + "\n", {"name": name, "frames": nframes, "rate": rate, "poses": poses} + + +def generate(ctx): + rng = ctx.rng(97) + R = ref(ctx) + text, info = mesh(rng) + data = text.encode() + info.update({"data": data, "assimp": R.assimp_soup(ctx, data, "md5mesh")}) + anims = [] + for name, nf, rate in (("idle", 4, 24), ("walk", 7, 30)): + t, a = anim(rng, info["joints"], nf, rate, name) + a["data"] = t.encode() + anims.append(a) + ctx.emit("md5", {"mesh": info, "anims": anims}) diff --git a/tools/fixtures/mdl.py b/tools/fixtures/mdl.py new file mode 100644 index 0000000..bdaeaca --- /dev/null +++ b/tools/fixtures/mdl.py @@ -0,0 +1,261 @@ +# MDL fixtures (tools/fixtures.py). Quake 1 ("IDPO" 6) and Half-Life 1 ("IDST" 10) models written here from the +# Quake specs / studio.h layouts, with random data; references: assimp's triangle soup (frame 0 / bind pose: +# positions, texture coordinates; for Quake from a copy without the skin group, which assimp 6 misreads) and this writer's own exact values: +# quake: every frame's positions (CRC-32 of the f32 soup in our corner order), the skins through a test palette +# (CRC-32 of the RGBA pixels), frame names; +# halflife: bones (bind pose), body parts / meshes / triangle strips and fans, two textures with their own +# palettes and a skin family, two sequences with run-length coded animation values (the values per frame +# and bone, computed here). +# tests/gen/mdl.luau { quake = { ... }, halflife = { ... } } +import importlib.util, math, os, struct, zlib + +INPUTS = ["tools/fixtures/_quake_ref.py"] + + +def ref(ctx): + spec = importlib.util.spec_from_file_location("_quake_ref", os.path.join(ctx.root, "tools", "fixtures", "_quake_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def f32(x): + return struct.unpack("> 0x0B) + s2 = ((ch if decrypt else v) + s2 + (s2 << 5) + 3) & M + out.append(ch) + return out + + +def drop_listfile(data): + import struct + hash_pos, n = struct.unpack_from(" 0.001: + weights[parent] = weights.get(parent, 0) + rest + lines.append(s) + corners.append({"p": p, "n": n, "uv": uv, "w": [[b, w] for b, w in sorted(weights.items(), key=lambda x: -x[1])]}) + tris.append({"material": mat, "corners": corners}) + lines.append("end") + return "\r\n".join(lines) + "\r\n", {"bones": bones, "frames": frames, "tris": tris} + + +def assimp_info(ctx, data, Q): + tmp = tempfile.mkdtemp(prefix="formats-smd-") + try: + p = os.path.join(tmp, "in.smd") + open(p, "wb").write(data) + try: + txt = ctx.nix("assimp", ["assimp", "info", p]).decode("utf-8", "replace") + except subprocess.CalledProcessError: + return {"failed": True} + finally: + shutil.rmtree(tmp) + import re + def num(label): + m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M) + return int(m.group(1)) if m else -1 + return {"faces": num("Faces"), "bones": num("Bones"), "animations": num("Animations")} + + +def generate(ctx): + rng = ctx.rng(83) + Q = mod(ctx, "_quake_ref") + specs = [("source", 5, 3, 12, ["skin.bmp", "metal.vtf"], True, False), ("goldsrc", 3, 1, 8, ["chrome.bmp"], False, False), + ("animation", 4, 6, 0, [], True, True)] + cases, src = [], [] + for name, nb, nf, nt, mats, links, anim in specs: + text, info = smd(rng, nb, nf, nt, mats, links, anim) + data = text.encode() + src.append({"name": name, "data": data}) + info.update({"name": name, "data": data, "assimp": Q.assimp_soup(ctx, data, "smd") if not anim else {"failed": True}, + "materials": mats}) + cases.append(info) + ctx.emit("smd_src", src) + import importlib + ours = {} + m = mod(ctx, "_model_ref") + for k, b in m.luau_encode(ctx, "tools/fixtures/_smd_encode.luau").items(): + ours[k] = assimp_info(ctx, b, Q) + ours[k]["soup"] = Q.assimp_soup(ctx, b, "smd") if not k.endswith("-anim") else {"failed": True} + ctx.emit("smd", {"cases": cases, "ours": ours}) diff --git a/tools/fixtures/tim.py b/tools/fixtures/tim.py new file mode 100644 index 0000000..db9f07c --- /dev/null +++ b/tools/fixtures/tim.py @@ -0,0 +1,73 @@ +# PlayStation TIM fixtures (tools/fixtures.py): TIM files written here (4-bit with two CLUTs, 8-bit, 15-bit direct +# with STP bits and 0x0000 transparency, 24-bit with an odd width, VRAM positions) decoded by ImageMagick's TIM +# reader (nix imagemagick, RGB: it ignores alpha) -> CRC-32 of the RGB bytes per CLUT row, plus the transparent +# pixel count (colour 0x0000) computed here. +# ImageMagick cannot read several CLUT rows: the 2-row file's reference is a copy with row 0 only. +# tests/gen/tim.luau { { name, data, width, height, bpp, rgb = { crc of CLUT row 0 }, transparent, cluts } } +import os, shutil, struct, tempfile, zlib + + +def tim(rng, bpp, w, h, cluts=1): + flags = {4: 0, 8: 1, 16: 2, 24: 3}[bpp] + out = b"" + colours = [] + if bpp <= 8: + n = 16 if bpp == 4 else 256 + flags |= 8 + for _ in range(cluts): + row = [rng.randrange(65536) for _ in range(n)] + row[0] = 0 + row[1] = 0x8000 + colours.append(row) + out += struct.pack(" 1: + n = 16 if bpp == 4 else 256 + ref = struct.pack(" the RGBA of frame 0, mip 0 (and the last frame) as +# reference. Formats whose conversion differs from the DXT rule (srctools / libsquish round 5 / 6-bit endpoints +# differently) are compared within a tolerance. +# tests/gen/vtf.luau { { name, data, width, height, frames, version, fmt, rgba, last?, tol } } +import json + +CODE = r""" +import io, json, random, sys +import srctools.vtf as V +args = json.loads(sys.stdin.read()) +rng = random.Random(args["seed"]) +out = [] +FMTS = ["RGBA8888", "ABGR8888", "RGB888", "BGR888", "RGB565", "I8", "IA88", "A8", "RGB888_BLUESCREEN", "BGR888_BLUESCREEN", + "ARGB8888", "BGRA8888", "DXT1", "DXT3", "DXT5", "BGRX8888", "BGR565", "BGRX5551", "BGRA4444", "DXT1_ONEBITALPHA", + "BGRA5551", "UV88", "UVWQ8888", "RGBA16161616F", "RGBA16161616", "UVLX8888", "ATI1N", "ATI2N"] +for i, name in enumerate(FMTS): + fmt = V.ImageFormats[name] + version = [(7, 2), (7, 4), (7, 5)][i % 3] + w, h = [(16, 8), (8, 8), (4, 16)][i % 3] if not name.startswith(("DXT", "ATI")) else (16, 8) + frames = 2 if i % 4 == 0 else 1 + try: + vtf = V.VTF(w, h, version, fmt=fmt, frames=frames) + for f in range(frames): + px = bytes(rng.randrange(256) for _ in range(w * h * 4)) + if "BLUESCREEN" in name: + px = bytearray(px) + for k in range(0, len(px), 16): + px[k:k + 4] = b"\x00\x00\xff\xff" + px = bytes(px) + vtf.get(frame=f).copy_from(px) + b = io.BytesIO() + vtf.save(b) + data = b.getvalue() + back = V.VTF.read(io.BytesIO(data)) + back.load() + rgba = bytes(back.get(frame=0)._data) + e = {"name": name, "data": data.hex(), "width": w, "height": h, "frames": frames, "version": "%d.%d" % version, "rgba": rgba.hex()} + if frames > 1: + e["last"] = bytes(back.get(frame=frames - 1)._data).hex() + out.append(e) + except Exception as ex: + out.append({"name": name, "failed": repr(ex)}) +print(json.dumps(out)) +""" + +# codecs/image/Texel rescales 5 / 6-bit fields with rounding (round(v * 255 / 31)); srctools replicates bits +# (v << 3 | v >> 2): within 1 +TOL = {"RGB565": 1, "BGR565": 1, "BGRX5551": 1, "BGRA5551": 1, "DXT1": 8, "DXT3": 8, "DXT5": 8, "DXT1_ONEBITALPHA": 8, "ATI1N": 2, "ATI2N": 2, "RGBA16161616F": 1, "RGBA16161616": 1} + + +def own(rng): + # 7.2 files written here for the formats srctools cannot write (one mip, no thumbnail); expected RGBA by the + # documented rules: halves / floats clamped to 0..1 and rounded, 16-bit integers (v + 128) // 257 + import struct, math + out = [] + w, h = 4, 4 + def header(fmt): + hd = bytearray(80) + struct.pack_into("<4sIIIHHIHH", hd, 0, b"VTF\0", 7, 2, 80, w, h, 0, 1, 0) + struct.pack_into("= 1 else math.floor(f * 255 + 0.5) + for name, fmt, kind, ch in (("RGBA16161616F", 24, "e", 4), ("RGBA16161616", 25, "H", 4), ("R32F", 27, "f", 1), + ("RGB323232F", 28, "f", 3), ("RGBA32323232F", 29, "f", 4)): + vals, rgba = [], bytearray() + for i in range(w * h): + px = [0, 0, 0, 255] + for k in range(ch): + if kind == "H": + v = rng.randrange(65536) + px[k] = (v + 128) // 257 + else: + v = rng.uniform(-0.5, 1.5) + v = struct.unpack("<" + kind, struct.pack("<" + kind, v))[0] + px[k] = c8(v) + vals.append(v) + if ch == 1: + px[1] = px[2] = px[0] + rgba += bytes(px) + data = header(fmt) + struct.pack("<%d%s" % (len(vals), kind), *vals) + out.append({"name": name, "data": data, "width": w, "height": h, "frames": 1, "version": "7.2", "rgba": bytes(rgba), "tol": 1 if kind == "H" else 0, "mips": 1}) + return out + + +def generate(ctx): + res = json.loads(ctx.python(["srctools", "pillow"], CODE, input=json.dumps({"seed": 7}).encode())) + out = [] + for e in res: + if "failed" in e: + print("fixtures: vtf: srctools cannot write %s: %s" % (e["name"], e["failed"])) + continue + c = {"name": e["name"], "data": bytes.fromhex(e["data"]), "width": e["width"], "height": e["height"], "frames": e["frames"], + "version": e["version"], "rgba": bytes.fromhex(e["rgba"]), "tol": TOL.get(e["name"], 0)} + if "last" in e: + c["last"] = bytes.fromhex(e["last"]) + out.append(c) + out += own(ctx.rng(9)) + ctx.emit("vtf", out) diff --git a/tools/fixtures/wad.py b/tools/fixtures/wad.py new file mode 100644 index 0000000..b1111dc --- /dev/null +++ b/tools/fixtures/wad.py @@ -0,0 +1,190 @@ +# Doom WAD fixtures (tools/fixtures.py). Freedoom (BSD licence, licenses/freedoom-COPYING.txt; the nix freedoom +# package, never committed) is cut down to a small IWAD here: MAP01's lumps, PLAYPAL, COLORMAP, PNAMES, TEXTURE1, +# TITLEPIC, and the first sprites / patches / flats of each namespace (the WAD writer below keeps Freedoom's layout: +# lumps in order, the directory at the end). References: +# - DeuTex (nix deutex) extracts every graphic of the cut-down WAD as PNG; Pillow turns them into RGBA (DeuTex's +# transparent index -> 0, 0, 0, 0; flats compared as RGB, all opaque) -> CRC-32 per lump; +# - an independent Python parse of the map lumps: counts, the things, and each sector's floor area by Green's +# theorem over its directed sides (no outline chaining), for the triangulation; +# - a hand-made PWAD: a square room with a square pillar sector inside (exact areas and walls), a UDMF map stub, +# tall-patch and namespace cases. +# tests/gen/wad.luau { freedoom = { data, lumps = { { name, entry, size, crc, namespace? } }, images = { { name, +# kind, width, height, left, top, crc } }, map = { name, things, linedefs, sidedefs, +# vertices, sectors, floorArea, thingList = { { x, y, type, angle } } }, textures = { ... } }, +# room = { data, ... } } +import glob, os, shutil, struct, subprocess, tempfile, zlib + +FREEDOOM = "share/games/doom/freedoom2.wad" + +TO_RGBA = r""" +import json, sys, zlib +from PIL import Image +out = {} +for path in json.loads(sys.stdin.read()): + im = Image.open(path) + t = im.info.get("transparency") + idx = im.load() + rgba = im.convert("RGBA") + px = bytearray(rgba.tobytes()) + if t is not None and "/flats/" not in path: + w, h = im.size + for y in range(h): + for x in range(w): + if idx[x, y] == t: + o = (y * w + x) * 4 + px[o:o + 4] = b"\0\0\0\0" + else: + for o in range(3, len(px), 4): + px[o] = 255 + out[path] = {"w": im.size[0], "h": im.size[1], "crc": zlib.crc32(bytes(px))} +print(json.dumps(out)) +""" + + +def lumps_of(data): + n, ofs = struct.unpack_from(" v2 (clockwise); pillar lines: front = room (outside), back = pillar + lines = b"" + for i, (a, b) in enumerate([(0, 3), (3, 2), (2, 1), (1, 0)]): + lines += struct.pack("