merge ws/quake

This commit is contained in:
4DBug committed 2026-11-01 20:08:48 -06:00
commit 58df9e8a3a
39 files changed
+10044 -1413

No files matched your search

+6 -1
View File
@@ -46,7 +46,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
## Formats
<!-- formats:begin -->
187 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
192 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
adds each format's capabilities.
| Category | Format | Extensions | Read | Write |
@@ -64,11 +64,13 @@ adds each format's capabilities.
| Images | ilbm | .iff .ilbm .lbm .pbm | yes | yes |
| Images | jpeg | .jpg .jpeg .jpe .jfif | yes | yes |
| Images | ktx | .ktx2 .ktx | yes | yes |
| Images | lmp | .lmp | yes | yes |
| Images | pcx | .pcx .pcc .dcx | yes | yes |
| Images | png | .png .apng | yes | yes |
| Images | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes |
| Images | qoi | .qoi | yes | yes |
| Images | sgi | .sgi .rgb .rgba .bw .int .inta | yes | yes |
| Images | spr | .spr | yes | yes |
| Images | sunras | .ras .sun .rs .im1 .im8 .im24 .im32 | yes | yes |
| Images | tga | .tga .icb .vda .vst .tpic | yes | yes |
| Images | tiff | .tif .tiff | yes | yes |
@@ -188,6 +190,7 @@ adds each format's capabilities.
| Archives | vpk | .vpk | yes | yes |
| Archives | vswap | .wl6 .wl1 .sod .sdm .vswap | yes | - |
| Archives | wad | .wad | yes | yes |
| Archives | wad2 | .wad | yes | yes |
| Archives | xz | .xz .txz .lzma | yes | - |
| Archives | yenc | .yenc .ync | yes | yes |
| Archives | z | .z .taz .tz | yes | yes |
@@ -201,6 +204,8 @@ adds each format's capabilities.
| Data | msgpack | .msgpack .mpk | yes | yes |
| Data | nbt | .nbt .dat .mcstructure .dat_old | yes | yes |
| Data | plist | .plist | yes | yes |
| Data | q3shader | .shader | yes | yes |
| Data | q3skin | .skin | yes | yes |
| Data | snbt | .snbt | yes | yes |
| Data | toml | .toml | yes | yes |
| Data | vdf | .vdf .acf .res .kv | yes | yes |
+1879 -48
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Binary file not shown.
+9 -9
View File
@@ -1,5 +1,5 @@
{
"Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [3117, "src/Rosetta/Types.luau"], [4200, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [4954, "src/Rosetta/codecs/image/Yuv.luau"], [5222, "src/Rosetta/codecs/model/Rbx/init.luau"], [5459, "src/Rosetta/codecs/video/Video/init.luau"], [6016, "src/Rosetta/containers/AudioWrap.luau"], [6519, "src/Rosetta/containers/Ogg/Mux.luau"], [6714, "src/Rosetta/containers/Ogg/Page.luau"], [6883, "src/Rosetta/core/Bytes.luau"], [7410, "src/Rosetta/core/Crc32.luau"], [7522, "src/Rosetta/core/Err.luau"], [7604, "src/Rosetta/core/Input.luau"], [7680, "src/Rosetta/host/init.luau"]],
"Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [3177, "src/Rosetta/Types.luau"], [4260, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [5014, "src/Rosetta/codecs/image/Yuv.luau"], [5282, "src/Rosetta/codecs/model/Rbx/init.luau"], [5519, "src/Rosetta/codecs/video/Video/init.luau"], [6076, "src/Rosetta/containers/AudioWrap.luau"], [6579, "src/Rosetta/containers/Ogg/Mux.luau"], [6774, "src/Rosetta/containers/Ogg/Page.luau"], [6943, "src/Rosetta/core/Bytes.luau"], [7470, "src/Rosetta/core/Crc32.luau"], [7582, "src/Rosetta/core/Err.luau"], [7664, "src/Rosetta/core/Input.luau"], [7740, "src/Rosetta/host/init.luau"]],
"Core_2": [[8, "src/Rosetta/ops/ImageOps/init.luau"], [652, "src/Rosetta/ops/ImageOps/Kernels.luau"]],
"Mpeg2": [[8, "src/Rosetta/codecs/video/Dsp.luau"], [731, "src/Rosetta/codecs/video/Mpeg1/init.luau"], [743, "src/Rosetta/codecs/video/Mpeg2/init.luau"], [1110, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], [2617, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], [2756, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"]],
"H263": [[8, "src/Rosetta/codecs/video/H263/init.luau"], [164, "src/Rosetta/codecs/video/H263/Decoder.luau"], [1022, "src/Rosetta/codecs/video/H263/Tables.luau"]],
@@ -27,28 +27,28 @@
"Hively": [[8, "src/Rosetta/codecs/audio/Hively/init.luau"], [204, "src/Rosetta/codecs/audio/Hively/Load.luau"], [453, "src/Rosetta/codecs/audio/Hively/Player.luau"], [1411, "src/Rosetta/codecs/audio/Hively/Tables.luau"]],
"SoundFont": [[8, "src/Rosetta/codecs/audio/SoundFont/init.luau"], [62, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], [205, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], [718, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"]],
"Draco": [[8, "src/Rosetta/codecs/model/Draco/init.luau"], [340, "src/Rosetta/codecs/model/Draco/Attributes.luau"], [809, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], [1998, "src/Rosetta/codecs/model/Draco/Int64.luau"], [2147, "src/Rosetta/codecs/model/Draco/KdTree.luau"], [2506, "src/Rosetta/codecs/model/Draco/Predict.luau"], [3468, "src/Rosetta/codecs/model/Draco/Reader.luau"]],
"archive_1": [[8, "src/Rosetta/archive/7z/init.luau"], [393, "src/Rosetta/archive/7z/Header.luau"], [920, "src/Rosetta/archive/adf/init.luau"], [1202, "src/Rosetta/archive/applesingle/init.luau"], [1388, "src/Rosetta/archive/ar/init.luau"], [1791, "src/Rosetta/archive/arj/init.luau"], [2001, "src/Rosetta/archive/binhex/init.luau"], [2250, "src/Rosetta/archive/br/init.luau"], [2325, "src/Rosetta/archive/bz2/init.luau"], [2389, "src/Rosetta/archive/cab/init.luau"], [2802, "src/Rosetta/archive/cab/Sum.luau"], [2843, "src/Rosetta/archive/cpio/init.luau"], [3011, "src/Rosetta/archive/d64/init.luau"], [3425, "src/Rosetta/archive/fat/init.luau"], [3547, "src/Rosetta/archive/grp/init.luau"], [3661, "src/Rosetta/archive/gzip/init.luau"], [3846, "src/Rosetta/archive/iso/init.luau"], [3918, "src/Rosetta/archive/lha/init.luau"], [4343, "src/Rosetta/archive/lz4/init.luau"], [4687, "src/Rosetta/archive/macbinary/init.luau"], [4885, "src/Rosetta/archive/mpq/init.luau"], [5291, "src/Rosetta/archive/mpq/Crypt.luau"], [5356, "src/Rosetta/archive/pak/init.luau"], [5490, "src/Rosetta/archive/rpm/init.luau"], [5814, "src/Rosetta/archive/tar/init.luau"], [5932, "src/Rosetta/archive/uu/init.luau"], [6202, "src/Rosetta/archive/vpk/init.luau"], [6513, "src/Rosetta/archive/vswap/init.luau"], [6783, "src/Rosetta/archive/wad/init.luau"], [7237, "src/Rosetta/archive/wad/Picture.luau"], [7339, "src/Rosetta/archive/xz/init.luau"], [7439, "src/Rosetta/archive/yenc/init.luau"], [7711, "src/Rosetta/archive/z/init.luau"], [7807, "src/Rosetta/archive/zip/init.luau"]],
"archive_2": [[8, "src/Rosetta/archive/zoo/init.luau"], [204, "src/Rosetta/archive/zst/init.luau"]],
"archive_1": [[8, "src/Rosetta/archive/7z/init.luau"], [393, "src/Rosetta/archive/7z/Header.luau"], [920, "src/Rosetta/archive/adf/init.luau"], [1202, "src/Rosetta/archive/applesingle/init.luau"], [1388, "src/Rosetta/archive/ar/init.luau"], [1791, "src/Rosetta/archive/arj/init.luau"], [2001, "src/Rosetta/archive/binhex/init.luau"], [2250, "src/Rosetta/archive/br/init.luau"], [2325, "src/Rosetta/archive/bz2/init.luau"], [2389, "src/Rosetta/archive/cab/init.luau"], [2802, "src/Rosetta/archive/cab/Sum.luau"], [2843, "src/Rosetta/archive/cpio/init.luau"], [3011, "src/Rosetta/archive/d64/init.luau"], [3425, "src/Rosetta/archive/fat/init.luau"], [3547, "src/Rosetta/archive/grp/init.luau"], [3661, "src/Rosetta/archive/gzip/init.luau"], [3846, "src/Rosetta/archive/iso/init.luau"], [3918, "src/Rosetta/archive/lha/init.luau"], [4343, "src/Rosetta/archive/lz4/init.luau"], [4687, "src/Rosetta/archive/macbinary/init.luau"], [4885, "src/Rosetta/archive/mpq/init.luau"], [5291, "src/Rosetta/archive/mpq/Crypt.luau"], [5356, "src/Rosetta/archive/pak/init.luau"], [5490, "src/Rosetta/archive/rpm/init.luau"], [5814, "src/Rosetta/archive/tar/init.luau"], [5932, "src/Rosetta/archive/uu/init.luau"], [6202, "src/Rosetta/archive/vpk/init.luau"], [6513, "src/Rosetta/archive/vswap/init.luau"], [6783, "src/Rosetta/archive/wad/init.luau"], [7237, "src/Rosetta/archive/wad/Picture.luau"], [7339, "src/Rosetta/archive/wad2/init.luau"], [7621, "src/Rosetta/archive/xz/init.luau"], [7721, "src/Rosetta/archive/yenc/init.luau"]],
"archive_2": [[8, "src/Rosetta/archive/z/init.luau"], [104, "src/Rosetta/archive/zip/init.luau"], [323, "src/Rosetta/archive/zoo/init.luau"], [519, "src/Rosetta/archive/zst/init.luau"]],
"audio": [[8, "src/Rosetta/audio/aac/init.luau"], [214, "src/Rosetta/audio/ac3/init.luau"], [360, "src/Rosetta/audio/adpcm/init.luau"], [505, "src/Rosetta/audio/adx/init.luau"], [736, "src/Rosetta/audio/aiff/init.luau"], [1127, "src/Rosetta/audio/ape/init.luau"], [1255, "src/Rosetta/audio/au/init.luau"], [1416, "src/Rosetta/audio/brstm/init.luau"], [1707, "src/Rosetta/audio/caf/init.luau"], [2369, "src/Rosetta/audio/flac/init.luau"], [2517, "src/Rosetta/audio/flac/Meta.luau"], [2739, "src/Rosetta/audio/flac/Stream.luau"], [3109, "src/Rosetta/audio/m4a/init.luau"], [3443, "src/Rosetta/audio/mp3/init.luau"], [3703, "src/Rosetta/audio/mp3/Index.luau"], [3894, "src/Rosetta/audio/mp3/Stream.luau"], [4121, "src/Rosetta/audio/mp3/Tags.luau"], [4433, "src/Rosetta/audio/mpc/init.luau"], [4527, "src/Rosetta/audio/opus/init.luau"], [4905, "src/Rosetta/audio/opus/Encode.luau"], [5016, "src/Rosetta/audio/qoa/init.luau"], [5196, "src/Rosetta/audio/tta/init.luau"], [5314, "src/Rosetta/audio/vag/init.luau"], [5537, "src/Rosetta/audio/voc/init.luau"], [5812, "src/Rosetta/audio/vorbis/init.luau"], [6266, "src/Rosetta/audio/vorbis/Encode.luau"], [7079, "src/Rosetta/audio/wav/init.luau"], [7700, "src/Rosetta/audio/wav/Codecs.luau"], [7866, "src/Rosetta/audio/wavpack/init.luau"]],
"cad": [[8, "src/Rosetta/cad/step/init.luau"], [390, "src/Rosetta/cad/step/Brep.luau"], [625, "src/Rosetta/cad/step/Parse.luau"], [1182, "src/Rosetta/cad/step/Write.luau"]],
"codecs_audio": [[8, "src/Rosetta/codecs/audio/Ac3/init.luau"], [167, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], [1052, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], [1153, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], [1455, "src/Rosetta/codecs/audio/Alac/init.luau"], [1689, "src/Rosetta/codecs/audio/Alac/Decode.luau"], [2108, "src/Rosetta/codecs/audio/Alac/Encode.luau"], [2520, "src/Rosetta/codecs/audio/Ape/init.luau"], [2735, "src/Rosetta/codecs/audio/Ape/Decode.luau"], [3496, "src/Rosetta/codecs/audio/ApeTag.luau"], [3593, "src/Rosetta/codecs/audio/Mdct/init.luau"], [3777, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], [3986, "src/Rosetta/codecs/audio/MidiRender.luau"], [4332, "src/Rosetta/codecs/audio/Pcm/init.luau"], [4595, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], [4892, "src/Rosetta/codecs/audio/Qoa/init.luau"], [5174, "src/Rosetta/codecs/audio/Resample/init.luau"], [5533, "src/Rosetta/codecs/audio/Stream.luau"], [5694, "src/Rosetta/codecs/audio/Tta/init.luau"], [5811, "src/Rosetta/codecs/audio/Tta/Decode.luau"], [6063, "src/Rosetta/codecs/audio/VorbisComment.luau"]],
"codecs_compress": [[8, "src/Rosetta/codecs/compress/Bzip2/init.luau"], [56, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], [572, "src/Rosetta/codecs/compress/Explode.luau"], [768, "src/Rosetta/codecs/compress/Lz4.luau"], [1037, "src/Rosetta/codecs/compress/Lzh/init.luau"], [1641, "src/Rosetta/codecs/compress/Lzw/init.luau"], [1909, "src/Rosetta/codecs/compress/Lzx.luau"], [2343, "src/Rosetta/codecs/compress/PackBits.luau"], [2433, "src/Rosetta/codecs/compress/Quantum.luau"], [2670, "src/Rosetta/codecs/compress/UnixCompress.luau"], [2974, "src/Rosetta/codecs/compress/Xxh32.luau"]],
"codecs_entropy": [[8, "src/Rosetta/codecs/entropy/Huffman.luau"], [290, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], [301, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], [515, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"]],
"codecs_font": [[8, "src/Rosetta/codecs/font/Bitmap.luau"], [209, "src/Rosetta/codecs/font/Cff/init.luau"], [850, "src/Rosetta/codecs/font/GlyphNames.luau"], [1000, "src/Rosetta/codecs/font/TrueType/init.luau"], [1314, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], [1706, "src/Rosetta/codecs/font/TrueType/Tables.luau"]],
"codecs_image": [[8, "src/Rosetta/codecs/image/Blend.luau"], [387, "src/Rosetta/codecs/image/Etc.luau"], [685, "src/Rosetta/codecs/image/Half.luau"], [754, "src/Rosetta/codecs/image/Miptex.luau"], [970, "src/Rosetta/codecs/image/Pixels.luau"], [1290, "src/Rosetta/codecs/image/Quantize/init.luau"], [1749, "src/Rosetta/codecs/image/Raster.luau"], [2446, "src/Rosetta/codecs/image/Texel.luau"], [2819, "src/Rosetta/codecs/image/Texture.luau"]],
"codecs_image": [[8, "src/Rosetta/codecs/image/Blend.luau"], [387, "src/Rosetta/codecs/image/Etc.luau"], [685, "src/Rosetta/codecs/image/Half.luau"], [754, "src/Rosetta/codecs/image/Miptex.luau"], [1054, "src/Rosetta/codecs/image/Pixels.luau"], [1374, "src/Rosetta/codecs/image/Quantize/init.luau"], [1833, "src/Rosetta/codecs/image/Raster.luau"], [2530, "src/Rosetta/codecs/image/Texel.luau"], [2903, "src/Rosetta/codecs/image/Texture.luau"]],
"codecs_model": [[8, "src/Rosetta/codecs/model/Brush.luau"], [648, "src/Rosetta/codecs/model/Displacement.luau"], [797, "src/Rosetta/codecs/model/DoomMap/init.luau"], [1242, "src/Rosetta/codecs/model/DoomMap/Udmf.luau"], [1492, "src/Rosetta/codecs/model/Mat4.luau"], [1751, "src/Rosetta/codecs/model/MeshFlatten.luau"], [2279, "src/Rosetta/codecs/model/Minecraft/init.luau"], [2831, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], [2910, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], [3017, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], [3223, "src/Rosetta/codecs/model/Patch.luau"], [3347, "src/Rosetta/codecs/model/Polygon.luau"], [3581, "src/Rosetta/codecs/model/Rbx/Binary.luau"], [4335, "src/Rosetta/codecs/model/Rig.luau"], [4578, "src/Rosetta/codecs/model/Sampler.luau"], [4738, "src/Rosetta/codecs/model/SourceAnim.luau"], [4959, "src/Rosetta/codecs/model/Vrml/init.luau"], [5107, "src/Rosetta/codecs/model/Vrml/Build.luau"], [5681, "src/Rosetta/codecs/model/Vrml/Fields.luau"], [5844, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], [6593, "src/Rosetta/codecs/model/Vrml/Parse.luau"], [7115, "src/Rosetta/codecs/model/Vrml/Write.luau"], [7842, "src/Rosetta/codecs/model/Vrml/Xml.luau"]],
"codecs_text": [[8, "src/Rosetta/codecs/text/Json/init.luau"], [277, "src/Rosetta/codecs/text/Json/Decode.luau"], [691, "src/Rosetta/codecs/text/Json/Encode.luau"], [993, "src/Rosetta/codecs/text/KeyValues/init.luau"], [1563, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], [1869, "src/Rosetta/codecs/text/Lexer/init.luau"], [2001, "src/Rosetta/codecs/text/Nbt/init.luau"], [2354, "src/Rosetta/codecs/text/Nbt/Binary.luau"], [3046, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], [3686, "src/Rosetta/codecs/text/Nbt/Value.luau"], [3924, "src/Rosetta/codecs/text/Text/init.luau"], [4015, "src/Rosetta/codecs/text/Url/init.luau"], [4220, "src/Rosetta/codecs/text/Xml/init.luau"], [4623, "src/Rosetta/codecs/text/Xml/Parse.luau"]],
"codecs_video": [[8, "src/Rosetta/codecs/video/Video/Source.luau"]],
"containers": [[8, "src/Rosetta/containers/Archive.luau"], [275, "src/Rosetta/containers/Avi/init.luau"], [827, "src/Rosetta/containers/Blend.luau"], [1566, "src/Rosetta/containers/Chunks.luau"], [1701, "src/Rosetta/containers/Cpio.luau"], [2129, "src/Rosetta/containers/Demux.luau"], [2404, "src/Rosetta/containers/Ebml/init.luau"], [2717, "src/Rosetta/containers/Fat.luau"], [3405, "src/Rosetta/containers/Iso9660.luau"], [3910, "src/Rosetta/containers/IsoBmff/init.luau"], [4080, "src/Rosetta/containers/IsoBmff/Box.luau"], [4268, "src/Rosetta/containers/IsoBmff/Demux.luau"], [5113, "src/Rosetta/containers/IsoBmff/Meta.luau"], [5634, "src/Rosetta/containers/IsoBmff/Mux.luau"], [6150, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], [6267, "src/Rosetta/containers/MacFile.luau"], [6416, "src/Rosetta/containers/Ogg/init.luau"], [6841, "src/Rosetta/containers/Riff/init.luau"], [7158, "src/Rosetta/containers/Tar.luau"], [7572, "src/Rosetta/containers/Zip/init.luau"]],
"core": [[8, "src/Rosetta/core/Adler32.luau"], [54, "src/Rosetta/core/Base64.luau"], [213, "src/Rosetta/core/Bits.luau"], [506, "src/Rosetta/core/Crc16.luau"], [558, "src/Rosetta/core/Md5.luau"], [717, "src/Rosetta/core/Sniff.luau"]],
"data": [[8, "src/Rosetta/data/cbor/init.luau"], [107, "src/Rosetta/data/cbor/Codec.luau"], [676, "src/Rosetta/data/csv/init.luau"], [988, "src/Rosetta/data/ini/init.luau"], [1234, "src/Rosetta/data/json/init.luau"], [1326, "src/Rosetta/data/msgpack/init.luau"], [1415, "src/Rosetta/data/msgpack/Codec.luau"], [1857, "src/Rosetta/data/nbt/init.luau"], [1916, "src/Rosetta/data/plist/init.luau"], [2222, "src/Rosetta/data/plist/Binary.luau"], [2489, "src/Rosetta/data/snbt/init.luau"], [2552, "src/Rosetta/data/toml/init.luau"], [2619, "src/Rosetta/data/toml/Decode.luau"], [3247, "src/Rosetta/data/toml/Encode.luau"], [3456, "src/Rosetta/data/vdf/init.luau"], [3557, "src/Rosetta/data/xml/init.luau"], [3613, "src/Rosetta/data/yaml/init.luau"], [3686, "src/Rosetta/data/yaml/Emit.luau"], [3976, "src/Rosetta/data/yaml/Parse.luau"]],
"data": [[8, "src/Rosetta/data/cbor/init.luau"], [107, "src/Rosetta/data/cbor/Codec.luau"], [676, "src/Rosetta/data/csv/init.luau"], [988, "src/Rosetta/data/ini/init.luau"], [1234, "src/Rosetta/data/json/init.luau"], [1326, "src/Rosetta/data/msgpack/init.luau"], [1415, "src/Rosetta/data/msgpack/Codec.luau"], [1857, "src/Rosetta/data/nbt/init.luau"], [1916, "src/Rosetta/data/plist/init.luau"], [2222, "src/Rosetta/data/plist/Binary.luau"], [2489, "src/Rosetta/data/q3shader/init.luau"], [2728, "src/Rosetta/data/q3skin/init.luau"], [2824, "src/Rosetta/data/snbt/init.luau"], [2887, "src/Rosetta/data/toml/init.luau"], [2954, "src/Rosetta/data/toml/Decode.luau"], [3582, "src/Rosetta/data/toml/Encode.luau"], [3791, "src/Rosetta/data/vdf/init.luau"], [3892, "src/Rosetta/data/xml/init.luau"], [3948, "src/Rosetta/data/yaml/init.luau"], [4021, "src/Rosetta/data/yaml/Emit.luau"], [4311, "src/Rosetta/data/yaml/Parse.luau"]],
"font": [[8, "src/Rosetta/font/bdf/init.luau"], [297, "src/Rosetta/font/bmfont/init.luau"], [724, "src/Rosetta/font/bmfont/Parse.luau"], [1177, "src/Rosetta/font/eot/init.luau"], [1409, "src/Rosetta/font/fon/init.luau"], [1692, "src/Rosetta/font/hershey/init.luau"], [1887, "src/Rosetta/font/pcf/init.luau"], [2167, "src/Rosetta/font/psf/init.luau"], [2487, "src/Rosetta/font/ttf/init.luau"], [2538, "src/Rosetta/font/type1/init.luau"], [2897, "src/Rosetta/font/type1/Charstring.luau"], [3175, "src/Rosetta/font/woff/init.luau"], [3307, "src/Rosetta/font/woff2/init.luau"], [3364, "src/Rosetta/font/woff2/Rebuild.luau"]],
"host": [[8, "src/Rosetta/host/Love.luau"], [151, "src/Rosetta/host/LuaJIT.luau"], [201, "src/Rosetta/host/Luau.luau"], [224, "src/Rosetta/host/Roblox.luau"]],
"image_1": [[8, "src/Rosetta/image/ani/init.luau"], [188, "src/Rosetta/image/art/init.luau"], [676, "src/Rosetta/image/blp/init.luau"], [934, "src/Rosetta/image/bmp/init.luau"], [1349, "src/Rosetta/image/dds/init.luau"], [1832, "src/Rosetta/image/exr/init.luau"], [2592, "src/Rosetta/image/exr/Codec.luau"], [2703, "src/Rosetta/image/exr/Piz.luau"], [3060, "src/Rosetta/image/gif/init.luau"], [3576, "src/Rosetta/image/gif/Decode.luau"], [3639, "src/Rosetta/image/hdr/init.luau"], [3868, "src/Rosetta/image/hdr/Codec.luau"], [4079, "src/Rosetta/image/icns/init.luau"], [4410, "src/Rosetta/image/ico/init.luau"], [4687, "src/Rosetta/image/ico/Dib.luau"], [4782, "src/Rosetta/image/ilbm/init.luau"], [5101, "src/Rosetta/image/jpeg/init.luau"], [5237, "src/Rosetta/image/ktx/init.luau"], [5897, "src/Rosetta/image/pcx/init.luau"], [6161, "src/Rosetta/image/pnm/init.luau"], [6539, "src/Rosetta/image/pnm/Codec.luau"], [6816, "src/Rosetta/image/qoi/init.luau"], [6938, "src/Rosetta/image/qoi/Codec.luau"], [7088, "src/Rosetta/image/sgi/init.luau"], [7373, "src/Rosetta/image/sunras/init.luau"], [7619, "src/Rosetta/image/tga/init.luau"]],
"image_2": [[8, "src/Rosetta/image/tga/Codec.luau"], [160, "src/Rosetta/image/tiff/init.luau"], [987, "src/Rosetta/image/tiff/Pixels.luau"], [1377, "src/Rosetta/image/tim/init.luau"], [1619, "src/Rosetta/image/vtf/init.luau"], [1854, "src/Rosetta/image/webp/init.luau"], [2464, "src/Rosetta/image/webp/Alpha.luau"], [2540, "src/Rosetta/image/webp/Anim.luau"], [2695, "src/Rosetta/image/xbm/init.luau"], [2856, "src/Rosetta/image/xpm/init.luau"], [3124, "src/Rosetta/image/xpm/Names.luau"]],
"image_1": [[8, "src/Rosetta/image/ani/init.luau"], [188, "src/Rosetta/image/art/init.luau"], [676, "src/Rosetta/image/blp/init.luau"], [934, "src/Rosetta/image/bmp/init.luau"], [1349, "src/Rosetta/image/dds/init.luau"], [1832, "src/Rosetta/image/exr/init.luau"], [2592, "src/Rosetta/image/exr/Codec.luau"], [2703, "src/Rosetta/image/exr/Piz.luau"], [3060, "src/Rosetta/image/gif/init.luau"], [3576, "src/Rosetta/image/gif/Decode.luau"], [3639, "src/Rosetta/image/hdr/init.luau"], [3868, "src/Rosetta/image/hdr/Codec.luau"], [4079, "src/Rosetta/image/icns/init.luau"], [4410, "src/Rosetta/image/ico/init.luau"], [4687, "src/Rosetta/image/ico/Dib.luau"], [4782, "src/Rosetta/image/ilbm/init.luau"], [5101, "src/Rosetta/image/jpeg/init.luau"], [5237, "src/Rosetta/image/ktx/init.luau"], [5897, "src/Rosetta/image/lmp/init.luau"], [6030, "src/Rosetta/image/pcx/init.luau"], [6294, "src/Rosetta/image/pnm/init.luau"], [6672, "src/Rosetta/image/pnm/Codec.luau"], [6949, "src/Rosetta/image/qoi/init.luau"], [7071, "src/Rosetta/image/qoi/Codec.luau"], [7221, "src/Rosetta/image/sgi/init.luau"], [7506, "src/Rosetta/image/spr/init.luau"]],
"image_2": [[8, "src/Rosetta/image/sunras/init.luau"], [254, "src/Rosetta/image/tga/init.luau"], [524, "src/Rosetta/image/tga/Codec.luau"], [676, "src/Rosetta/image/tiff/init.luau"], [1503, "src/Rosetta/image/tiff/Pixels.luau"], [1893, "src/Rosetta/image/tim/init.luau"], [2135, "src/Rosetta/image/vtf/init.luau"], [2370, "src/Rosetta/image/webp/init.luau"], [2980, "src/Rosetta/image/webp/Alpha.luau"], [3056, "src/Rosetta/image/webp/Anim.luau"], [3211, "src/Rosetta/image/xbm/init.luau"], [3372, "src/Rosetta/image/xpm/init.luau"], [3640, "src/Rosetta/image/xpm/Names.luau"]],
"layered": [[8, "src/Rosetta/layered/aseprite/init.luau"], [746, "src/Rosetta/layered/ora/init.luau"], [1033, "src/Rosetta/layered/psd/init.luau"], [1768, "src/Rosetta/layered/psd/Channels.luau"]],
"model_1": [[8, "src/Rosetta/model/3ds/init.luau"], [91, "src/Rosetta/model/3ds/Build.luau"], [738, "src/Rosetta/model/3ds/Read.luau"], [1234, "src/Rosetta/model/3ds/Write.luau"], [2039, "src/Rosetta/model/3mf/init.luau"], [2121, "src/Rosetta/model/3mf/Read.luau"], [2709, "src/Rosetta/model/3mf/Write.luau"], [3114, "src/Rosetta/model/b3d/init.luau"], [3169, "src/Rosetta/model/b3d/Read.luau"], [3740, "src/Rosetta/model/blend/init.luau"], [3836, "src/Rosetta/model/blend/Anim.luau"], [4182, "src/Rosetta/model/blend/Material.luau"], [4534, "src/Rosetta/model/blend/Mesh.luau"], [5169, "src/Rosetta/model/blend/Normals.luau"], [5330, "src/Rosetta/model/blend/Prim.luau"], [5779, "src/Rosetta/model/blend/Read.luau"], [6679, "src/Rosetta/model/bsp/init.luau"], [6824, "src/Rosetta/model/bsp/Brush.luau"], [7087, "src/Rosetta/model/bsp/Quake3.luau"]],
"model_2": [[8, "src/Rosetta/model/buildmap/init.luau"], [280, "src/Rosetta/model/buildmap/Geometry.luau"], [683, "src/Rosetta/model/d3map/init.luau"], [965, "src/Rosetta/model/d3map/Parse.luau"], [1163, "src/Rosetta/model/dae/init.luau"], [1352, "src/Rosetta/model/dae/Math.luau"], [1399, "src/Rosetta/model/dae/Read.luau"], [3249, "src/Rosetta/model/dae/Write.luau"], [3618, "src/Rosetta/model/fbx/init.luau"], [3766, "src/Rosetta/model/fbx/Ascii.luau"], [4036, "src/Rosetta/model/fbx/Binary.luau"], [4491, "src/Rosetta/model/fbx/Read.luau"], [5853, "src/Rosetta/model/fbx/Write.luau"], [6838, "src/Rosetta/model/fbx/Xform.luau"], [6879, "src/Rosetta/model/gltf/init.luau"], [7116, "src/Rosetta/model/gltf/Pack.luau"]],
"model_1": [[8, "src/Rosetta/model/3ds/init.luau"], [91, "src/Rosetta/model/3ds/Build.luau"], [738, "src/Rosetta/model/3ds/Read.luau"], [1234, "src/Rosetta/model/3ds/Write.luau"], [2039, "src/Rosetta/model/3mf/init.luau"], [2121, "src/Rosetta/model/3mf/Read.luau"], [2709, "src/Rosetta/model/3mf/Write.luau"], [3114, "src/Rosetta/model/b3d/init.luau"], [3169, "src/Rosetta/model/b3d/Read.luau"], [3740, "src/Rosetta/model/blend/init.luau"], [3836, "src/Rosetta/model/blend/Anim.luau"], [4182, "src/Rosetta/model/blend/Material.luau"], [4534, "src/Rosetta/model/blend/Mesh.luau"], [5169, "src/Rosetta/model/blend/Normals.luau"], [5330, "src/Rosetta/model/blend/Prim.luau"], [5779, "src/Rosetta/model/blend/Read.luau"], [6679, "src/Rosetta/model/bsp/init.luau"], [6870, "src/Rosetta/model/bsp/Lightmap.luau"], [6936, "src/Rosetta/model/bsp/Quake.luau"]],
"model_2": [[8, "src/Rosetta/model/bsp/Quake3.luau"], [236, "src/Rosetta/model/bsp/Tree.luau"], [624, "src/Rosetta/model/buildmap/init.luau"], [896, "src/Rosetta/model/buildmap/Geometry.luau"], [1299, "src/Rosetta/model/d3map/init.luau"], [1581, "src/Rosetta/model/d3map/Parse.luau"], [1779, "src/Rosetta/model/dae/init.luau"], [1968, "src/Rosetta/model/dae/Math.luau"], [2015, "src/Rosetta/model/dae/Read.luau"], [3865, "src/Rosetta/model/dae/Write.luau"], [4234, "src/Rosetta/model/fbx/init.luau"], [4382, "src/Rosetta/model/fbx/Ascii.luau"], [4652, "src/Rosetta/model/fbx/Binary.luau"], [5107, "src/Rosetta/model/fbx/Read.luau"], [6469, "src/Rosetta/model/fbx/Write.luau"], [7454, "src/Rosetta/model/fbx/Xform.luau"], [7495, "src/Rosetta/model/gltf/init.luau"], [7732, "src/Rosetta/model/gltf/Pack.luau"]],
"model_3": [[8, "src/Rosetta/model/gltf/Read.luau"], [739, "src/Rosetta/model/gltf/Write.luau"], [1419, "src/Rosetta/model/iqm/init.luau"], [1495, "src/Rosetta/model/iqm/Read.luau"], [1850, "src/Rosetta/model/iqm/Write.luau"], [2537, "src/Rosetta/model/ldraw/init.luau"], [2615, "src/Rosetta/model/ldraw/Colors.luau"], [2933, "src/Rosetta/model/ldraw/Read.luau"], [3510, "src/Rosetta/model/lwo/init.luau"], [3586, "src/Rosetta/model/lwo/Build.luau"], [4048, "src/Rosetta/model/lwo/Parse.luau"], [4591, "src/Rosetta/model/map/init.luau"], [4908, "src/Rosetta/model/map/Build.luau"], [5151, "src/Rosetta/model/map/Parse.luau"], [5536, "src/Rosetta/model/map/Write.luau"], [5682, "src/Rosetta/model/mca/init.luau"], [6024, "src/Rosetta/model/mca/Chunk.luau"], [6157, "src/Rosetta/model/mca/Lz4Block.luau"], [6227, "src/Rosetta/model/md2/init.luau"], [6426, "src/Rosetta/model/md3/init.luau"], [6654, "src/Rosetta/model/md5/init.luau"], [6735, "src/Rosetta/model/md5/Read.luau"], [7168, "src/Rosetta/model/mdl/init.luau"], [7250, "src/Rosetta/model/mdl/HalfLife.luau"]],
"model_4": [[8, "src/Rosetta/model/mdl/Quake.luau"], [226, "src/Rosetta/model/ms3d/init.luau"], [298, "src/Rosetta/model/ms3d/Read.luau"], [744, "src/Rosetta/model/ms3d/Write.luau"], [1213, "src/Rosetta/model/obj/init.luau"], [1955, "src/Rosetta/model/obj/Mtl.luau"], [2242, "src/Rosetta/model/off/init.luau"], [2704, "src/Rosetta/model/ply/init.luau"], [3809, "src/Rosetta/model/ply/Binary.luau"], [4010, "src/Rosetta/model/pmx/init.luau"], [4079, "src/Rosetta/model/pmx/Build.luau"], [4375, "src/Rosetta/model/pmx/Pmd.luau"], [4710, "src/Rosetta/model/pmx/Read.luau"], [5114, "src/Rosetta/model/proc/init.luau"], [5496, "src/Rosetta/model/qb/init.luau"], [5889, "src/Rosetta/model/rbxm/init.luau"], [6481, "src/Rosetta/model/rbxmx/init.luau"], [7134, "src/Rosetta/model/robloxmesh/init.luau"]],
"model_5": [[8, "src/Rosetta/model/robloxmesh/Parse.luau"], [465, "src/Rosetta/model/robloxmesh/Write.luau"], [574, "src/Rosetta/model/schematic/init.luau"], [895, "src/Rosetta/model/schematic/Common.luau"], [1015, "src/Rosetta/model/schematic/Litematic.luau"], [1226, "src/Rosetta/model/schematic/Mcedit.luau"], [1470, "src/Rosetta/model/schematic/Sponge.luau"], [1599, "src/Rosetta/model/smd/init.luau"], [1666, "src/Rosetta/model/smd/Read.luau"], [1935, "src/Rosetta/model/smd/Write.luau"], [2178, "src/Rosetta/model/sourcemdl/init.luau"], [2349, "src/Rosetta/model/sourcemdl/Build.luau"], [2779, "src/Rosetta/model/sourcemdl/Material.luau"], [2940, "src/Rosetta/model/sourcemdl/Mdl.luau"], [3467, "src/Rosetta/model/sourcemdl/Phy.luau"], [3590, "src/Rosetta/model/sourcemdl/Vtx.luau"], [3772, "src/Rosetta/model/sourcemdl/Vvd.luau"], [3866, "src/Rosetta/model/stl/init.luau"], [4316, "src/Rosetta/model/stl/Decode.luau"], [4390, "src/Rosetta/model/udmf/init.luau"], [4473, "src/Rosetta/model/usda/init.luau"], [4682, "src/Rosetta/model/usda/Build.luau"], [5960, "src/Rosetta/model/usda/Parse.luau"], [6758, "src/Rosetta/model/usda/Write.luau"], [7575, "src/Rosetta/model/vbsp/init.luau"]],
+1932 -94
View File
File diff suppressed because it is too large. Load diff
+1881 -50
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+6 -1
View File
@@ -18,11 +18,13 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| image | ilbm | .iff .ilbm .lbm .pbm | yes | yes | alpha: true, palette: true, depths: 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 | `tests/image/ilbm.luau` |
| image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` |
| image | ktx | .ktx2 .ktx | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" | `tests/image/ktx.luau` |
| image | lmp | .lmp | yes | yes | alpha: true, depths: 8, variants: "qpic", "palette", "colormap" | `tests/image/lmp.luau` |
| image | pcx | .pcx .pcc .dcx | yes | yes | alpha: true, palette: true, depths: 1, 2, 4, 8, 24, 32 | `tests/image/pcx.luau` |
| image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` |
| image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` |
| image | sgi | .sgi .rgb .rgba .bw .int .inta | yes | yes | alpha: true, depths: 8, 16 | `tests/image/sgi.luau` |
| image | spr | .spr | yes | yes | alpha: true, animation: true, variants: "quake", "halflife", "spr32" | `tests/image/spr.luau` |
| 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` |
@@ -67,7 +69,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| 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 | blend | .blend | yes | - | materials: true, textures: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true, compressed: true | `tests/model/blend.luau` |
| model | bsp | .bsp | yes | - | variants: "quake", "halflife", "quake2", "quake3", lightmaps: "quake3" | `tests/model/bsp.luau` |
| model | bsp | .bsp | yes | - | variants: "quake", "bsp2", "2psb", "halflife", "quake2", "quake3", lightmaps: true, collision: true, visibility: true | `tests/model/bsp.luau` |
| model | buildmap | .map | yes | yes | sprites: true, slopes: true | `tests/model/buildmap.luau` |
| model | d3map | .map | yes | - | patches: true, variants: "doom3", "quake4" | `tests/model/d3map.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` |
@@ -142,6 +144,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| archive | vpk | .vpk | yes | yes | versions: 1, 2, multipart: true | `tests/archive/vpk.luau` |
| archive | vswap | .wl6 .wl1 .sod .sdm .vswap | yes | - | images: true, sounds: true | `tests/archive/vswap.luau` |
| archive | wad | .wad | yes | yes | images: true, maps: true, variants: "iwad", "pwad" | `tests/archive/wad.luau` |
| archive | wad2 | .wad | yes | yes | images: true, variants: "wad2", "wad3" | `tests/archive/wad2.luau` |
| archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` |
| archive | yenc | .yenc .ync | yes | yes | multipart: true | `tests/archive/yenc.luau` |
| archive | z | .z .taz .tz | yes | yes | stream: true, bits: 9, 16 | `tests/archive/z.luau` |
@@ -155,6 +158,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| data | msgpack | .msgpack .mpk | yes | yes | binary: true, ordered: true | `tests/data/msgpack.luau` |
| data | nbt | .nbt .dat .mcstructure .dat_old | yes | yes | binary: true, ordered: true, typed: true | `tests/data/nbt.luau` |
| data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` |
| data | q3shader | .shader | yes | yes | | `tests/data/q3shader.luau` |
| data | q3skin | .skin | yes | yes | | `tests/data/q3skin.luau` |
| data | snbt | .snbt | yes | yes | ordered: true, typed: true | `tests/data/snbt.luau` |
| data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` |
| data | vdf | .vdf .acf .res .kv | yes | yes | ordered: true, binary: true | `tests/data/vdf.luau` |
+22
View File
@@ -232,6 +232,28 @@ local data = assert(Wad.mapData(wad, "E1M1"))
assert(#data.sectors == 2 and #data.things == 2)
```
Quake's and Half-Life's texture WADs (WAD2 / WAD3, format `wad2`; Doom's IWAD / PWAD is `wad`) list their lumps
by name; `image` decodes miptex textures (any mip level), qpic pictures, the console font and the palette lump. Quake 1
lumps use the WAD's own `palette` lump (gfx.wad), `palette` or `gfx/palette.lmp` through `files` / `resolve` (Quake's
palette is not redistributable, so rosetta never embeds it); WAD3 lumps carry their own. `addImage` writes images
back as lumps (WAD3: with a palette made by median cut):
```luau
local Wad2 = F.format("wad2")
local gfx = assert(F.archive.load(gfxWadBytes))
assert(gfx.format == "wad2" and gfx.meta.source.variant == "wad2")
local brick = assert(Wad2.image(gfx, "brick")) -- through the WAD's palette lump
local small = assert(Wad2.image(gfx, "brick", { mip = 2 })) -- 8 x 8
assert(brick.width == 32 and small.width == 8)
local disc = assert(Wad2.image(gfx, "disc")) -- a qpic: index 255 transparent
assert(disc.meta.source.kind == "qpic")
local hl = Wad2.new("wad3")
assert(Wad2.addImage(hl, "{FENCE", brick)) -- '{' textures key index 255
local wad3 = assert(F.save(hl))
assert(F.archive.load(wad3).meta.source.variant == "wad3")
```
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):
+19
View File
@@ -326,6 +326,25 @@ local bin = assert(F.save(acf, nil, { format = "vdf", binary = true }))
assert(F.data.load(bin, { format = "vdf" }).AppState.appid == "440")
```
## Quake III shaders and skins
Quake III `.shader` scripts load as a list of shaders: `{ name, directives, stages }`, each directive its tokens
(`{ "surfaceparm", "nolightmap" }`), each stage a list of directives; they write back. `.skin` files (format
`q3skin`) are lists of `{ surface, shader }` (tags have an empty shader).
```luau
local Q3Shader = F.format("q3shader")
local shaders = assert(F.data.load(shaderText, { format = "q3shader" }))
local wall = assert(Q3Shader.find(shaders, "textures/base_wall/metalfloor_wall_10"))
assert(Q3Shader.directive(wall.directives, "surfaceparm")[2] == "metalsteps")
assert(wall.stages[1][1][2] == "$lightmap" and #wall.stages == 2)
local again = assert(F.saveString(shaders, { format = "q3shader" }))
assert(#assert(F.data.load(again, { format = "q3shader" })) == #shaders)
local skin = assert(F.data.load(skinText, { format = "q3skin" }))
assert(F.format("q3skin").shader(skin, "h_head") == "models/players/sarge/band.tga")
```
## Save and convert
Data values have no `kind`, so saving needs `opts.format` or a destination extension (an `XmlNode` document too):
+22
View File
@@ -233,6 +233,28 @@ assert(buffer.tostring(assert(F.save(raw, nil, { format = "art" }))) == buffer.t
Doom's graphics come from WAD lumps rather than files: `F.format("wad").image(wad, name)` (see
[archive.md](archive.md#game-archives)).
Quake's `.lmp` pictures (qpics), `palette.lmp` and `colormap.lmp`, and Quake / Half-Life sprites (`.spr`) load
too. Quake pictures and sprites are 8-bit images over Quake's palette, which is not redistributable: pass it as
`palette` (768 bytes) or as `gfx/palette.lmp` through `files` / `resolve` (without it they load grey,
`meta.source.palette = false`). Half-Life sprites carry their own palette. Sprite frames are `img.frames` on one
canvas around the sprite's origin (`meta.origin`); frame groups give the delays.
```luau
local disc = assert(F.image.load(discLmpBytes, { name = "disc.lmp", palette = quakePaletteBytes }))
assert(disc.width == 24 and disc.meta.source.palette) -- index 255 is transparent
local pal = assert(F.image.load(quakePaletteBytes, { format = "lmp" })) -- a 16 x 16 swatch
assert(#pal.meta.palette == 256)
local back = assert(F.save(disc, nil, { format = "lmp", palette = quakePaletteBytes }))
assert(buffer.len(back) == buffer.len(discLmpBytes))
local flame = assert(F.image.load(flameSprBytes)) -- Half-Life: its own palette
assert(#flame.frames == 3 and flame.meta.source.texFormat == "alphatest")
local spr = assert(F.save(flame, nil, { format = "spr" })) -- version 2; version = 1 (Quake) needs palette
assert(#F.image.load(spr).frames == 3)
```
Doom's graphics come from WAD lumps rather than files: `F.format("wad").image(wad, name)`, and Quake / Half-Life
textures from WAD2 / WAD3: `F.format("wad2").image(wad, name)` (see [archive.md](archive.md#game-archives)).
## Formats
+61
View File
@@ -472,6 +472,7 @@ Game model formats load as Scenes too, with what games need: skins (joints + inv
| BSP (Quake 1 / 2 / 3, Half-Life) | each model a mesh, a primitive per texture (and Quake III lightmap); entities in `meta.entities` | - |
| VBSP (Source 19 / 20 / 21) | each model a mesh, a primitive per material, displacements; static props as nodes; lights; entities; the pak lump | - |
| VMF (Hammer, read + write) | a mesh per entity with solids, displacements; point entities as nodes; cameras; visgroups | - |
| BSP (Quake 1 / 2 / 3, Half-Life; BSP2, 2PSB) | each model a mesh, a primitive per texture; lightmaps as `TEXCOORD_1`; entities in `meta.entities`; tree, hulls and PVS in `meta.bsp` | - |
```luau
local tank = assert(F.model.load(md2Bytes))
@@ -675,6 +676,64 @@ local start = room.nodes[3]
assert(start.extras.classname == "info_player_start" and start.translation[3] == 1)
```
## Quake maps: editor `.map` and compiled BSP
`model/map` reads and writes the editor maps of Quake, Half-Life (Valve 220), Quake II (with content / surface flags)
and Quake III (`brushDef` brush primitives, `patchDef2` / `patchDef3` patches). Every entity is a node (child of the
`map` root) with `extras.classname`, `extras.keys` (an ordered object) and `extras.brushes` (the brushes as written);
entities with brushes get a mesh, a primitive per texture. Point entities stand at their `origin`. Brushes become
polygons the way qbsp builds them (`codecs/model/Brush`; tested against ericw-tools); `hull = true` drops the faces
inside or touching other brushes of the same entity, `merge = true` merges coplanar faces. Texture coordinates need
texture sizes: they come from `textureSizes`, the worldspawn's WADs (`"wad"` key), Quake II `.wal` files or Quake III
images (with `decodeImage`) through `files` / `resolve`; unknown textures count as 64 x 64
(`material.extras.map.sizeKnown = false`).
```luau
local Map = F.format("map")
local room = assert(F.model.load(roomMapText, { files = { ["gfx/tex.wad"] = texWadBytes }, hull = true }))
assert(room.meta.source.variant == "quake" and room.meta.up == "z")
local world = room.nodes[2] -- node 1 is the "map" root
assert(world.extras.classname == "worldspawn" and world.mesh)
local door = room.nodes[3]
assert(door.name == "door1" and door.extras.keys.angle == "90")
assert(room.materials[1].extras.map.sizeKnown) -- sizes from the WAD
local start = room.nodes[4] -- a point entity at its origin
assert(start.translation[1] == -128)
start.translation = { 0, 0, 24 } -- edit and write back
door.extras.keys.speed = "200"
local text = buffer.tostring(assert(F.save(room, nil, { format = "map" })))
assert(string.find(text, '"origin" "0 0 24"', 1, true))
local valve = assert(F.save(room, nil, { format = "map", variant = "valve220" })) -- Quake standard -> Valve 220 axes
assert(F.model.load(valve).meta.source.variant == "valve220")
local parsed = assert(Map.parse(roomMapText)) -- the raw entities: keys, brushes, faces as written
assert(#parsed.entities == 4 and parsed.entities[1].brushes[1].faces[1].texture)
```
Compiled `.bsp` maps carry what the engines need beyond the triangles. Quake 1 (BSP 29, BSP2, 2PSB), Half-Life and
Quake II lightmaps (the first light style) are packed into one atlas texture named `"lightmap"`, mapped by
`TEXCOORD_1` and named by each material's `extras.bsp.lightmap` (Quake III keeps its own 128 x 128 pages). Coloured
Quake light comes from the map's `.lit` (`lit`, or `<map>.lit` through `files` / `resolve` with `name`). The BSP tree,
the collision hulls (Quake 1 clipnodes, Quake II / III brushes) and the visibility data are tables in `meta.bsp`,
with point queries on the format module:
```luau
local Bsp = F.format("bsp")
local map = assert(F.model.load(roomBspBytes))
assert(map.meta.source.variant == "quake")
local prim = map.meshes[1].primitives[1]
assert(prim.attributes.TEXCOORD_1) -- lightmap coordinates
local atlas = map.textures[map.materials[prim.material].extras.bsp.lightmap]
assert(atlas.name == "lightmap" and atlas.image.width > 0)
assert(Bsp.contents(map, -128, -128, 100) == -1) -- CONTENTS_EMPTY in the room
assert(Bsp.contents(map, 0, 0, -8) == -2) -- CONTENTS_SOLID: the floor
assert(Bsp.contents(map, -250, 0, 100, 1) == -2) -- hull 1 (player size) touches the wall
local here = assert(Bsp.leafAt(map, -128, -128, 24))
local seen = assert(Bsp.pvs(map, here)) -- leaves potentially visible from here
assert(table.find(seen, Bsp.leafAt(map, 0, 0, 220)))
assert(#map.meta.bsp.planes > 0 and #map.meta.bsp.clipnodes > 0)
```
## Blitz3D (B3D)
`.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS;
@@ -965,6 +1024,8 @@ assert(bones[1]:str("name") == "lower" and bones[1]:list("childbase")[1]:str("na
| Source MDL (v44-49) + VVD / VTX / PHY | yes | - | skeleton, body parts, LODs, flexes, animations, VMT materials: see above |
| MD2, MD3, MDL, MD5, BSP, VBSP | yes | - | game models and maps: see "Game models" above |
| VMF | yes | yes (round trip, builders) | Hammer maps: see "Hammer maps (VMF)" above |
| MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above; BSP lightmaps, hulls, PVS: "Quake maps" |
| Quake / Half-Life / Quake II / Quake III `.map` | yes | yes | entities as nodes, brushes CSG'd, patches: see "Quake maps" |
| SMD | yes | yes | Valve studiomdl data |
| Doom 3 / Quake 4 `.proc` | yes | | render geometry per area, portals and BSP nodes as data |
| Doom 3 / Quake 4 `.map` (d3map) | yes | | brushDef3, patchDef2 / 3, entities as nodes |
+61 -1
View File
@@ -170,6 +170,18 @@ local list: { Entry } = {
return require("@rosetta/image/ktx")
end,
},
{
name = "lmp",
category = "image",
path = "image/lmp",
extensions = { "lmp" },
mime = { "image/x-quake-lmp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } },
load = function()
return require("@rosetta/image/lmp")
end,
},
{
name = "pcx",
category = "image",
@@ -230,6 +242,18 @@ local list: { Entry } = {
return require("@rosetta/image/sgi")
end,
},
{
name = "spr",
category = "image",
path = "image/spr",
extensions = { "spr" },
mime = { "image/x-quake-sprite" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } },
load = function()
return require("@rosetta/image/spr")
end,
},
{
name = "sunras",
category = "image",
@@ -765,7 +789,7 @@ local list: { Entry } = {
extensions = { "bsp" },
mime = { "model/x-bsp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" },
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true },
load = function()
return require("@rosetta/model/bsp")
end,
@@ -1658,6 +1682,18 @@ local list: { Entry } = {
return require("@rosetta/archive/wad")
end,
},
{
name = "wad2",
category = "archive",
path = "archive/wad2",
extensions = { "wad" },
mime = { "application/x-quake-wad" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } },
load = function()
return require("@rosetta/archive/wad2")
end,
},
{
name = "xz",
category = "archive",
@@ -1814,6 +1850,30 @@ local list: { Entry } = {
return require("@rosetta/data/plist")
end,
},
{
name = "q3shader",
category = "data",
path = "data/q3shader",
extensions = { "shader" },
mime = { "text/x-quake3-shader" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
load = function()
return require("@rosetta/data/q3shader")
end,
},
{
name = "q3skin",
category = "data",
path = "data/q3skin",
extensions = { "skin" },
mime = { "text/x-quake3-skin" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
load = function()
return require("@rosetta/data/q3skin")
end,
},
{
name = "snbt",
category = "data",
+280
View File
@@ -0,0 +1,280 @@
--!strict
-- archive/wad2: Quake WAD2 and Half-Life WAD3 texture / graphics WADs (wad.h of the Quake source, the GoldSrc WAD3
-- layout; no code taken), read and write. Lumps by name (repeats "<name>~<n>"); Wad2.image decodes miptex, qpic,
-- conchars, palette and GoldSrc font lumps through codecs/image/Miptex (Quake 1 needs a palette: the WAD's own
-- "palette" lump, opts.palette or gfx/palette.lmp through files / resolve; else grey). Not supported: compressed lumps.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Archive = require("@rosetta/containers/Archive")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Miptex = require("@rosetta/codecs/image/Miptex")
-- ------------------------------------------------------------------------------------------------ contract
local Wad2 = {
name = "wad2",
category = "archive",
extensions = { "wad" },
mime = { "application/x-quake-wad" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = { maxEntries: number? } -- default 1e6
export type EncodeOptions = { variant: ("wad2" | "wad3")? } -- default: the source's, else wad3 when a lump is type 0x43
export type ImageOptions = {
palette: (buffer | string)?, -- 768 bytes (Quake 1)
mip: number?, -- miptex level 0..3, default 0
keyed: boolean?, -- index 255 transparent; default: qpics, conchars and '{' textures
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
}
export type AddOptions = {
kind: ("miptex" | "qpic")?, -- default "miptex"
palette: (buffer | string)?, -- 768 bytes; required for WAD2 lumps, made by median cut for WAD3 without it
}
-- ------------------------------------------------------------------------------------------------ constants
local T = Miptex.TYPES
-- ------------------------------------------------------------------------------------------------ sniff
function Wad2.sniff(r: Bytes.Reader): number
if r:remaining() < 12 then
return 0
end
local m = r:peek(4)
return if m == "WAD2" or m == "WAD3" then 0.9 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
return Wad2.encode(archive, opts)
end
function Wad2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local size = r.limit - r.base
local lumps, msg, magic = Miptex.wad(r.buf, r.base, size, opts and opts.maxEntries)
if not lumps then
return nil, Err.from(msg, 0)
end
local a = Archive.new("wad2", encode)
local seen: { [string]: number } = {}
for _, l in lumps do
if l.compression ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "compressed lump " .. l.name)
end
local entry = l.name
local k = seen[string.lower(entry)]
if k then
seen[string.lower(entry)] = k + 1
entry = entry .. "~" .. (k + 1)
else
seen[string.lower(entry)] = 1
end
Archive.put(a, { name = entry, size = l.disksize, dir = false, method = "store", type = l.type, lump = l.name, load = Archive.slice(r.buf, r.base + l.offset, l.disksize) })
end
a.meta.source = { format = "wad2", variant = string.lower(magic :: string), lumps = #lumps }
a.meta.wad2 = { buf = r.buf, base = r.base, lumps = lumps, goldsrc = magic == "WAD3" }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function guessType(name: string, data: buffer, goldsrc: boolean): number
local n = buffer.len(data)
if string.lower(name) == "palette" and n == 768 then
return T.palette
end
if n >= 40 then
local w, h = buffer.readu32(data, 16), buffer.readu32(data, 20)
if w > 0 and h > 0 and w < 65536 and h < 65536 and buffer.readu32(data, 24) == 40 then
return if goldsrc then 0x43 else T.miptex
end
end
if n >= 8 then
local w, h = buffer.readu32(data, 0), buffer.readu32(data, 4)
if w > 0 and h > 0 and 8 + w * h <= n then
return T.qpic
end
end
return T.miptex
end
function Wad2.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 variant = opts and opts.variant or (if type(src) == "table" and src.format == "wad2" then src.variant else nil)
if not variant then
variant = "wad2"
for _, it in items do
if (it.entry :: any).type == 0x43 then
variant = "wad3"
end
end
end
if variant ~= "wad2" and variant ~= "wad3" then
return nil, Err.new(Err.ARG, "variant must be wad2 or wad3")
end
local list: { { name: string, data: buffer, type: number } } = {}
for _, it in items do
if not it.entry.dir then
local e: any = it.entry
local name = e.lump or string.gsub(string.match(e.name, "([^/\\]*)$") or e.name, "~%d+$", "")
if #name == 0 or #name > 15 then
return nil, Err.new(Err.ARG, "lump name must be 1..15 bytes: " .. e.name)
end
local typ = if type(e.type) == "number" then e.type else guessType(name, it.data, variant == "wad3")
table.insert(list, { name = name, data = it.data, type = typ })
end
end
local w = Bytes.writer()
w:string(if variant == "wad3" then "WAD3" else "WAD2")
w:u32le(#list)
w:u32le(0)
local offs: { number } = {}
for i, l in list do
offs[i] = w:tell()
w:bytes(l.data)
w:fill(0, (4 - buffer.len(l.data) % 4) % 4)
end
local dir = w:tell()
for i, l in list do
w:u32le(offs[i])
w:u32le(buffer.len(l.data))
w:u32le(buffer.len(l.data))
w:u8(l.type)
w:u8(0)
w:u16le(0)
w:string(l.name)
w:fill(0, 16 - #l.name)
end
w:setU32le(8, dir)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
local function info(a: any): any
return type(a) == "table" and type(a.meta) == "table" and a.meta.wad2 or nil
end
function Wad2.new(variant: ("wad2" | "wad3")?): any
local a = Archive.new("wad2", encode)
a.meta.source = { format = "wad2", variant = variant or "wad2" }
return a
end
function Wad2.lumps(a: any): { Miptex.Lump }?
local w = info(a)
return w and w.lumps
end
-- the WAD's own "palette" lump (gfx.wad) as a 1024-byte rgba8 palette
function Wad2.palette(a: any): buffer?
local w = info(a)
local l = w and Miptex.find(w.lumps, "palette")
if l and l.disksize >= 768 then
return Pixels.palette(w.buf, w.base + l.offset, 256)
end
return nil
end
function Wad2.image(a: any, name: string, opts: ImageOptions?): (Types.Image?, Err.Err?)
local w = info(a)
if not w then
return nil, Err.new(Err.ARG, "expected a decoded WAD2 / WAD3 archive")
end
local l = Miptex.find(w.lumps, tostring(name))
if not l then
return nil, Err.new(Err.ARG, "no lump named " .. tostring(name))
end
local b, at, size = w.buf, w.base + l.offset, l.disksize
local pal: buffer? = nil
if not w.goldsrc then
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil
if raw and buffer.len(raw) >= 768 then
pal = Pixels.palette(raw, 0, 256)
else
pal = Wad2.palette(a)
if not pal then
local lmp = Input.sibling(opts, "gfx/palette.lmp")
pal = if lmp and buffer.len(lmp) >= 768 then Pixels.palette(lmp, 0, 256) else nil
end
end
end
local keyed: boolean? = if opts then opts.keyed else nil
local img: Types.Image?, msg: string?
local kind: string
if l.type == T.palette and size >= 768 then
kind = "palette"
local out = Types.Image.new(16, 16)
buffer.copy(out.pixels, 0, Pixels.palette(b, at, 256), 0, 1024)
img = out
elseif string.lower(l.name) == "conchars" and size == 128 * 128 then
-- gfx.wad's console font: raw 128 x 128 pixels, no header, index 0 transparent
kind = "conchars"
local out = Types.Image.new(128, 128)
Pixels.indexed(b, at, 128, 8, out.pixels, 128, 128, true, Pixels.keyed(pal or Pixels.grey(), if keyed == false then -1 else 0))
img = out
elseif l.type == T.qpic then
kind = "qpic"
img, msg = Miptex.qpic(b, at, size, { palette = pal, goldsrc = w.goldsrc, keyed = keyed } :: any)
elseif l.type == T.font and w.goldsrc and size >= 16 + 1024 then
-- GoldSrc qfont_t: width (256), height, rowcount, rowheight, charinfo[256] (u16 offset, u16 width), pixels, palette
kind = "font"
local fw, fh = buffer.readu32(b, at), buffer.readu32(b, at + 4)
local p = 16 + 1024 + fw * fh
if fw == 0 or fh == 0 or fw * fh > 2 ^ 24 or p + 2 > size then
return nil, Err.new(Err.CORRUPT, "bad font lump " .. l.name, l.offset)
end
local n = buffer.readu16(b, at + p)
local fpal = if n > 0 and n <= 256 and p + 2 + n * 3 <= size then Pixels.palette(b, at + p + 2, n) else Pixels.grey()
local out = Types.Image.new(fw, fh)
Pixels.indexed(b, at + 16 + 1024, fw, 8, out.pixels, fw, fh, true, if keyed == false then fpal else Pixels.keyed(fpal, 255))
local glyphs = {}
for c = 0, 255 do
glyphs[c + 1] = { offset = buffer.readu16(b, at + 16 + c * 4), width = buffer.readu16(b, at + 18 + c * 4) }
end
out.meta.font = { rows = buffer.readu32(b, at + 8), rowHeight = buffer.readu32(b, at + 12), glyphs = glyphs }
img = out
else
kind = "miptex"
img, msg = Miptex.decode(b, at, size, { palette = pal, goldsrc = w.goldsrc, mip = if opts then opts.mip else nil, keyed = keyed } :: any)
end
if not img then
return nil, Err.from(msg, l.offset)
end
img.meta.source = { format = "wad2", kind = kind, lump = l.name, type = l.type, palette = w.goldsrc or pal ~= nil }
return img, nil
end
-- adds an rgba8 image as a miptex (sizes multiples of 16) or qpic lump; WAD3 lumps carry their own palette
function Wad2.addImage(a: any, name: string, img: Types.Image, opts: AddOptions?): (boolean, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" then
return false, Err.new(Err.ARG, "expected an rgba8 Image")
end
local src = type(a) == "table" and type(a.meta) == "table" and a.meta.source
local goldsrc = type(src) == "table" and src.variant == "wad3"
local raw = opts and opts.palette and Bytes.toBuffer(opts.palette)
local pal = if raw and buffer.len(raw) >= 768 then Pixels.palette(raw, 0, 256) else nil
local kind = opts and opts.kind or "miptex"
local data, msg
if kind == "qpic" then
data, msg = Miptex.encodeQpic(img, pal, goldsrc)
else
data, msg = Miptex.encode(img, name, pal, goldsrc)
end
if not data then
return false, Err.new(Err.ARG, msg or "cannot encode")
end
Archive.put(a, { name = name, size = buffer.len(data), dir = false, method = "store", lump = name, data = data,
type = if kind == "qpic" then T.qpic elseif goldsrc then 0x43 else T.miptex })
return true, nil
end
return Wad2
+99 -15
View File
@@ -113,30 +113,28 @@ function Miptex.encode(img: Types.Image, name: string, palette: buffer?, goldsrc
if #name > 15 then
return nil, "miptex name over 15 bytes"
end
local colors: { { number } }
if palette then
colors = Pixels.colorList(palette)
elseif goldsrc then
colors = Quantize.palette(img.pixels, w, h, 256)
else
if not palette and not goldsrc then
return nil, "a Quake miptex needs a palette"
end
local keyed = string.sub(name, 1, 1) == "{"
local _, colors = Miptex.indices(img, palette, keyed)
if keyed and not palette then
colors[256] = { 0, 0, 255, 255 } -- GoldSrc '{' textures: index 255 is the (blue) key colour
end
local pal1024 = palette or buffer.create(1024)
if not palette then
for i, c in colors do
buffer.writeu32(pal1024, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1])
end
end
local levels: { buffer } = {}
local px, lw, lh = img.pixels, w, h
for m = 0, 3 do
if m > 0 then
px, lw, lh = halve(px, lw, lh)
end
local idx = Quantize.map(px, lw, lh, colors, { transparentIndex = if keyed then 255 else nil })
if keyed then
for k = 0, lw * lh - 1 do
if readu8(px, k * 4 + 3) < 128 then
buffer.writeu8(idx, k, 255)
end
end
end
levels[m + 1] = idx
local lvl = { kind = "image", width = lw, height = lh, format = "rgba8", pixels = px, loops = 0, meta = {} } :: any
levels[m + 1] = (Miptex.indices(lvl, pal1024, keyed))
end
local total = 40
for _, l in levels do
@@ -211,4 +209,90 @@ function Miptex.find(lumps: { Lump }, name: string): Lump?
return best
end
-- qpic (Quake .lmp / WAD2 type 0x42: u32 width, height, 8-bit pixels; GoldSrc adds u16 count + count * 3 palette bytes)
-- -> rgba8. keyed: index 255 transparent (Quake's Draw_TransPic), default true
function Miptex.qpic(b: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?)
if size < 8 or at < 0 or at + 8 > buffer.len(b) then
return nil, "truncated qpic header"
end
local w, h = readu32(b, at), readu32(b, at + 4)
if w == 0 or h == 0 then
return nil, "empty qpic"
end
if w * h > (opts and opts.maxPixels or 2 ^ 24) then
return nil, "limit: qpic " .. w .. " x " .. h
end
if 8 + w * h > size or at + 8 + w * h > buffer.len(b) then
return nil, "truncated qpic pixels"
end
local own: buffer? = nil
if opts and opts.goldsrc then
local p = 8 + w * h
if p + 2 <= size then
local n = buffer.readu16(b, at + p)
if n > 0 and n <= 256 and p + 2 + n * 3 <= size then
own = Pixels.palette(b, at + p + 2, n)
end
end
end
local pal = own or (opts and opts.palette) or Pixels.grey()
local keyed = if opts and opts.keyed ~= nil then opts.keyed else true
if keyed then
pal = Pixels.keyed(pal, 255)
end
local img = Types.Image.new(w, h)
Pixels.indexed(b, at + 8, w, 8, img.pixels, w, h, true, pal)
img.meta.source = { format = "qpic", palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil }
return img, nil
end
-- palette indices of an rgba8 image (nearest entry; alpha < 128 -> 255 when keyed and the image has any) and the
-- palette used
function Miptex.indices(img: Types.Image, palette: buffer?, keyed: boolean): (buffer, { { number } })
if keyed then
local any = false
for k = 0, img.width * img.height - 1 do
if readu8(img.pixels, k * 4 + 3) < 128 then
any = true
break
end
end
keyed = any
end
local colors = if palette then Pixels.colorList(palette) else Quantize.palette(img.pixels, img.width, img.height, if keyed then 255 else 256)
local idx = Quantize.map(img.pixels, img.width, img.height, colors, { transparentIndex = if keyed and palette then 255 else nil })
if keyed then
for k = 0, img.width * img.height - 1 do
if readu8(img.pixels, k * 4 + 3) < 128 then
buffer.writeu8(idx, k, 255)
end
end
end
return idx, colors
end
-- an rgba8 image -> qpic bytes (goldsrc: with its palette, made by median cut when none is given)
function Miptex.encodeQpic(img: Types.Image, palette: buffer?, goldsrc: boolean?, keyed: boolean?): (buffer?, string?)
if not palette and not goldsrc then
return nil, "a Quake qpic needs a palette"
end
local w, h = img.width, img.height
local idx, colors = Miptex.indices(img, palette, keyed ~= false)
local out = buffer.create(8 + w * h + (if goldsrc then 2 + 768 else 0))
buffer.writeu32(out, 0, w)
buffer.writeu32(out, 4, h)
buffer.copy(out, 8, idx, 0, w * h)
if goldsrc then
local p = 8 + w * h
buffer.writeu16(out, p, 256)
for i = 0, 255 do
local c = colors[i + 1] or { 0, 0, 0 }
buffer.writeu8(out, p + 2 + i * 3, c[1])
buffer.writeu8(out, p + 3 + i * 3, c[2])
buffer.writeu8(out, p + 4 + i * 3, c[3])
end
end
return out, nil
end
return Miptex
+3 -3
View File
@@ -269,13 +269,13 @@ function Pixels.grey(): buffer
return pal
end
-- a copy of a 1024-byte palette with entry index fully transparent (Quake / GoldSrc: index 255 of sprites, qpics and
-- '{' textures)
-- a copy of a 1024-byte palette with entry index transparent (alpha 0, colour kept as Pillow does; Quake / GoldSrc:
-- index 255 of sprites, qpics and '{' textures)
function Pixels.keyed(pal: buffer, index: number): buffer
local out = buffer.create(1024)
buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024))
if index >= 0 and index < 256 then
writeu32(out, index * 4, 0)
writeu8(out, index * 4 + 3, 0)
end
return out
end
+237
View File
@@ -0,0 +1,237 @@
--!strict
-- data/q3shader: Quake III shader scripts (.shader; the Quake III Arena Shader Manual, tr_shader.c tokenizing: no code
-- taken), read and write. A script is a list of shaders { name, directives, stages }; a directive is its tokens
-- ({ "surfaceparm", "nolightmap" }, one line each), a stage is a list of directives. Keywords keep their case.
-- Comments (// and /* */) are dropped.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
-- ------------------------------------------------------------------------------------------------ contract
local Q3Shader = {
name = "q3shader",
category = "data",
extensions = { "shader" },
mime = { "text/x-quake3-shader" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Directive = { string }
export type Shader = { name: string, directives: { Directive }, stages: { { Directive } } }
export type EncodeOptions = { indent: string? } -- default "\t"
-- ------------------------------------------------------------------------------------------------ constants
local KEYWORDS = { "surfaceparm", "map", "clampmap", "animmap", "blendfunc", "rgbgen", "alphagen", "tcgen", "tcmod",
"cull", "deformvertexes", "qer_editorimage", "nopicmip", "nomipmaps", "skyparms", "q3map_", "depthwrite", "alphafunc" }
-- ------------------------------------------------------------------------------------------------ sniff
function Q3Shader.sniff(r: Bytes.Reader): number
local head = r:peek(math.min(r:remaining(), 2048))
if #head < 4 or string.find(head, "[%z\1-\8\14-\31]") then
return 0
end
local s = string.gsub(string.gsub(head, "/%*.-%*/", " "), "//[^\n]*", "")
if not string.match(s, "^%s*[^%s{}\"]+%s*{") then
return 0
end
local lower = string.lower(s)
for _, k in KEYWORDS do
if string.find(lower, "%f[%w_]" .. k) then
return 0.7
end
end
return 0.2
end
-- ------------------------------------------------------------------------------------------------ decode
-- the token lines of a script; braces are lines of their own
local function lex(text: string): ({ { string } }?, string?)
local lines: { { string } } = {}
local cur: { string } = {}
local i, n = 1, #text
local function flush()
if #cur > 0 then
table.insert(lines, cur)
cur = {}
end
end
while i <= n do
local c = string.sub(text, i, i)
if c == "\n" then
flush()
i += 1
elseif string.match(c, "%s") then
i += 1
elseif string.sub(text, i, i + 1) == "//" then
local e = string.find(text, "\n", i, true)
i = e or n + 1
elseif string.sub(text, i, i + 1) == "/*" then
local _, e = string.find(text, "*/", i + 2, true)
if not e then
return nil, "unterminated comment"
end
for _ in string.gmatch(string.sub(text, i, e), "\n") do
flush()
end
i = e + 1
elseif c == "{" or c == "}" then
flush()
table.insert(lines, { c })
i += 1
elseif c == '"' then
local e = string.find(text, '"', i + 1, true)
if not e then
return nil, "unterminated string"
end
table.insert(cur, string.sub(text, i + 1, e - 1))
i = e + 1
else
local _, e = string.find(text, "^[^%s{}\"]+", i)
local stop = e :: number
local tok = string.sub(text, i, stop)
local cm = string.find(tok, "//", 1, true)
if cm and cm > 1 then
tok = string.sub(tok, 1, cm - 1)
stop = i + cm - 2
end
table.insert(cur, tok)
i = stop + 1
end
end
flush()
return lines, nil
end
function Q3Shader.decode(r: Bytes.Reader): ({ Shader }?, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local lines, msg = lex(text)
if not lines then
return nil, Err.new(Err.CORRUPT, msg or "bad script")
end
local out: { Shader } = {}
local k = 1
while k <= #lines do
local l = lines[k]
if #l ~= 1 or l[1] == "{" or l[1] == "}" then
return nil, Err.new(Err.CORRUPT, "expected a shader name, got '" .. table.concat(l, " ") .. "'")
end
local sh: Shader = { name = l[1], directives = {}, stages = {} }
k += 1
if not lines[k] or lines[k][1] ~= "{" then
return nil, Err.new(Err.CORRUPT, "expected '{' after " .. sh.name)
end
k += 1
local stage: { Directive }? = nil
local closed = false
while k <= #lines do
local d = lines[k]
k += 1
if d[1] == "{" then
if stage then
return nil, Err.new(Err.CORRUPT, "nested stage in " .. sh.name)
end
stage = {}
elseif d[1] == "}" then
if stage then
table.insert(sh.stages, stage)
stage = nil
else
closed = true
break
end
elseif stage then
table.insert(stage, d)
else
table.insert(sh.directives, d)
end
end
if not closed then
return nil, Err.new(Err.TRUNCATED, "shader " .. sh.name .. " not closed")
end
table.insert(out, sh)
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function tokens(d: any): (string?, string?)
if type(d) ~= "table" or #d == 0 then
return nil, "a directive is a list of strings"
end
local parts = {}
for _, t in d do
local s = tostring(t)
if s == "" or string.find(s, "[%s{}]") then
if string.find(s, '"', 1, true) or string.find(s, "\n") then
return nil, "token cannot hold quotes or line breaks: " .. s
end
s = '"' .. s .. '"'
end
table.insert(parts, s)
end
return table.concat(parts, " "), nil
end
function Q3Shader.encode(list: { Shader }, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(list) ~= "table" then
return nil, Err.new(Err.ARG, "expected a list of shaders")
end
local ind = opts and opts.indent or "\t"
local out: { string } = {}
for _, sh in list do
if type(sh) ~= "table" or type(sh.name) ~= "string" or sh.name == "" or string.find(sh.name, "[%s{}\"]") then
return nil, Err.new(Err.ARG, "a shader needs a name without spaces")
end
table.insert(out, sh.name)
table.insert(out, "{")
for _, d in sh.directives or {} do
local line, e = tokens(d)
if not line then
return nil, Err.new(Err.ARG, e or "bad directive")
end
table.insert(out, ind .. line)
end
for _, st in sh.stages or {} do
table.insert(out, ind .. "{")
for _, d in st do
local line, e = tokens(d)
if not line then
return nil, Err.new(Err.ARG, e or "bad directive")
end
table.insert(out, ind .. ind .. line)
end
table.insert(out, ind .. "}")
end
table.insert(out, "}")
table.insert(out, "")
end
return buffer.fromstring(table.concat(out, "\n")), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- the shader named name (case-insensitive, as the game looks them up)
function Q3Shader.find(list: { Shader }, name: string): Shader?
local want = string.lower(name)
for _, sh in list do
if string.lower(sh.name) == want then
return sh
end
end
return nil
end
-- the first directive starting with keyword (case-insensitive) in a shader or stage directive list
function Q3Shader.directive(list: { Directive }, keyword: string): Directive?
local want = string.lower(keyword)
for _, d in list do
if string.lower(d[1] or "") == want then
return d
end
end
return nil
end
return Q3Shader
+94
View File
@@ -0,0 +1,94 @@
--!strict
-- data/q3skin: Quake III model skins (.skin: "surface,shader" lines, "tag_*," for tags; tr_image.c RE_RegisterSkin, no
-- code taken), read and write. Decodes to a list of { surface, shader } in file order (shader "" for tags).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
-- ------------------------------------------------------------------------------------------------ contract
local Q3Skin = {
name = "q3skin",
category = "data",
extensions = { "skin" },
mime = { "text/x-quake3-skin" },
deps = { "core/Err", "core/Bytes" },
caps = { decode = true, encode = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Entry = { surface: string, shader: string }
-- ------------------------------------------------------------------------------------------------ sniff
function Q3Skin.sniff(r: Bytes.Reader): number
local head = r:peek(math.min(r:remaining(), 1024))
if #head < 3 or string.find(head, "[%z\1-\8\14-\31]") then
return 0
end
local lines, good, paths = 0, 0, 0
for line in string.gmatch(head, "[^\r\n]+") do
if not string.match(line, "^%s*$") then
lines += 1
local surface, shader = string.match(line, "^%s*([%w_%-]+)%s*,%s*([^,%s]*)%s*$")
if surface and shader == "" and string.sub(string.lower(surface), 1, 4) == "tag_" then
good += 1
elseif shader and string.find(shader, "/", 1, true) then
good += 1
paths += 1
end
end
end
return if lines > 0 and good == lines and paths > 0 then 0.5 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Q3Skin.decode(r: Bytes.Reader): ({ Entry }?, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local out: { Entry } = {}
local n = 0
for line in string.gmatch(text, "[^\r\n]+") do
n += 1
local s = string.match(line, "^%s*(.-)%s*$") :: string
if s ~= "" and string.sub(s, 1, 2) ~= "//" then
local surface, shader = string.match(s, "^([^,]-)%s*,%s*(.-)$")
if not surface or surface == "" then
return nil, Err.new(Err.CORRUPT, "line " .. n .. ": expected surface,shader")
end
table.insert(out, { surface = surface, shader = shader :: string })
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Q3Skin.encode(list: { Entry }): (buffer?, Err.Err?)
if type(list) ~= "table" then
return nil, Err.new(Err.ARG, "expected a list of { surface, shader }")
end
local out: { string } = {}
for _, e in list do
if type(e) ~= "table" or type(e.surface) ~= "string" or e.surface == "" or string.find(e.surface, "[,\r\n]") then
return nil, Err.new(Err.ARG, "a skin entry needs a surface name without commas")
end
local sh = if e.shader == nil then "" else tostring(e.shader)
if string.find(sh, "[,\r\n]") then
return nil, Err.new(Err.ARG, "a shader path cannot hold commas or line breaks")
end
table.insert(out, e.surface .. "," .. sh)
end
table.insert(out, "")
return buffer.fromstring(table.concat(out, "\n")), nil
end
-- the shader of a surface (case-insensitive)
function Q3Skin.shader(list: { Entry }, surface: string): string?
local want = string.lower(surface)
for _, e in list do
if string.lower(e.surface) == want then
return e.shader
end
end
return nil
end
return Q3Skin
+131
View File
@@ -0,0 +1,131 @@
--!strict
-- image/lmp: Quake .lmp lumps (wad.h / draw.c of the Quake source; no code taken), read and write: qpic pictures (u32
-- width, height, 8-bit pixels; index 255 transparent), palette.lmp (768 bytes: a 16 x 16 swatch) and colormap.lmp (64
-- light levels x 256: a 256 x 64 image). Pictures and colormaps need Quake's palette, which is never embedded (GPL):
-- opts.palette or gfx/palette.lmp through files / resolve; else grey (meta.source.palette = false).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Miptex = require("@rosetta/codecs/image/Miptex")
-- ------------------------------------------------------------------------------------------------ contract
local Lmp = {
name = "lmp",
category = "image",
extensions = { "lmp" },
mime = { "image/x-quake-lmp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
palette: (buffer | string)?, -- 768 bytes
kind: ("qpic" | "palette" | "colormap")?, -- default: from the size
keyed: boolean?, -- qpic index 255 transparent, default true
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
maxPixels: number?, -- default 2^24
}
export type EncodeOptions = {
palette: (buffer | string)?, -- 768 bytes: required for qpics
kind: ("qpic" | "palette")?, -- default "qpic"; "palette" writes a 16 x 16 swatch as 768 bytes
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
}
-- ------------------------------------------------------------------------------------------------ sniff
local function kindOf(r: Bytes.Reader): string?
local n = r:remaining()
if n == 768 then
return "palette"
elseif n == 16385 or n == 16384 then
return "colormap"
end
if n < 9 then
return nil
end
local w, h = buffer.readu32(r.buf, r.pos), buffer.readu32(r.buf, r.pos + 4)
if w > 0 and h > 0 and w <= 4096 and h <= 4096 and 8 + w * h == n then
return "qpic"
end
return nil
end
function Lmp.sniff(r: Bytes.Reader): number
local k = kindOf(r)
return if k == "qpic" then 0.3 elseif k then 0.05 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function palette(opts: any?): buffer?
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
if raw and buffer.len(raw) >= 768 then
return Pixels.palette(raw, 0, 256)
end
return nil
end
function Lmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local kind = opts and opts.kind or kindOf(r)
local b, at, n = r.buf, r.base, r.limit - r.base
if kind == "palette" then
if n < 768 then
return nil, Err.new(Err.TRUNCATED, "palette", 0)
end
local img = Types.Image.new(16, 16)
buffer.copy(img.pixels, 0, Pixels.palette(b, at, 256), 0, 1024)
local list = Pixels.colorList(img.pixels)
img.meta.palette = list
img.meta.source = { format = "lmp", kind = "palette" }
return img, nil
end
local pal = palette(opts)
if kind == "colormap" then
local rows = math.min(64, n // 256)
if rows < 1 then
return nil, Err.new(Err.TRUNCATED, "colormap", 0)
end
local img = Types.Image.new(256, rows)
Pixels.indexed(b, at, 256, 8, img.pixels, 256, rows, true, pal or Pixels.grey())
img.meta.source = { format = "lmp", kind = "colormap", palette = pal ~= nil }
return img, nil
end
if kind ~= "qpic" and n >= 8 then
kind = "qpic"
end
local img, msg = Miptex.qpic(b, at, n, { palette = pal, keyed = opts and opts.keyed, maxPixels = opts and opts.maxPixels })
if not img then
return nil, Err.from(msg, 0)
end
img.meta.source = { format = "lmp", kind = "qpic", palette = pal ~= nil, keyed = (opts == nil or opts.keyed ~= false) or nil }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Lmp.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
if opts and opts.kind == "palette" then
if img.width * img.height < 256 then
return nil, Err.new(Err.ARG, "a palette needs 256 pixels (16 x 16)")
end
return Pixels.paletteBytes(img.pixels, 256), nil
end
local pal = palette(opts)
if not pal then
return nil, Err.new(Err.ARG, "a qpic needs Quake's palette (opts.palette or gfx/palette.lmp; it is not embedded)")
end
local out, msg = Miptex.encodeQpic(img, pal, false, true)
if not out then
return nil, Err.new(Err.ARG, msg or "cannot encode")
end
return out, nil
end
return Lmp
+311
View File
@@ -0,0 +1,311 @@
--!strict
-- image/spr: Quake (IDSP 1), Half-Life (IDSP 2, own palette, texture formats) and DarkPlaces SPR32 (IDSP 32, rgba)
-- sprites, read and write (spritegn.h of the Quake source, the GoldSrc sprite layout; no code taken). Frames and frame
-- groups become Image frames on one canvas around the sprite origin (meta.origin); group intervals give the delays.
-- Quake sprites need Quake's palette (opts.palette or gfx/palette.lmp through files / resolve; never embedded).
-- Not supported: Quake II sprites (IDS2: frames are separate .pcx files).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Miptex = require("@rosetta/codecs/image/Miptex")
-- ------------------------------------------------------------------------------------------------ contract
local Spr = {
name = "spr",
category = "image",
extensions = { "spr" },
mime = { "image/x-quake-sprite" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" },
caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
palette: (buffer | string)?, -- Quake: 768 bytes
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
maxPixels: number?, -- per frame, default 2^24
maxFrames: number?, -- default 4096
}
export type EncodeOptions = {
version: number?, -- 2 (Half-Life, default), 1 (Quake: needs opts.palette) or 32 (rgba)
palette: (buffer | string)?,
type: number?, -- orientation: 0 parallel upright, 1 facing upright, 2 parallel (default), 3 oriented, 4 parallel oriented
texFormat: number?, -- Half-Life: 0 normal, 1 additive, 2 index alpha, 3 alpha test (default: 3 when any pixel is transparent)
delay: number?, -- seconds per frame when the image has none, default 0.1
}
-- ------------------------------------------------------------------------------------------------ constants
local TEX_FORMATS = { [0] = "normal", "additive", "indexalpha", "alphatest" }
-- ------------------------------------------------------------------------------------------------ sniff
function Spr.sniff(r: Bytes.Reader): number
if r:remaining() < 36 or r:peek(4) ~= "IDSP" then
return 0
end
local v = buffer.readi32(r.buf, r.pos + 4)
return if v == 1 or v == 2 or v == 32 then 1 else 0.3
end
-- ------------------------------------------------------------------------------------------------ decode
type Raw = { x: number, y: number, w: number, h: number, at: number, delay: number }
function Spr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
if r:string(4) ~= "IDSP" then
return nil, r.err or Err.new(Err.CORRUPT, "bad magic", 0)
end
local version = r:i32le()
if version ~= 1 and version ~= 2 and version ~= 32 then
return nil, Err.new(Err.UNSUPPORTED, "sprite version " .. tostring(version), 4)
end
local stype = r:i32le()
local texFormat = if version == 2 then r:i32le() else 3
local radius = r:f32le()
local mw, mh, nframes = r:i32le(), r:i32le(), r:i32le()
local beam, sync = r:f32le(), r:i32le()
if r.err then
return nil, r.err
end
local maxFrames = opts and opts.maxFrames or 4096
local maxPixels = opts and opts.maxPixels or 2 ^ 24
if nframes < 1 or nframes > maxFrames then
return nil, Err.new(if nframes < 1 then Err.CORRUPT else Err.LIMIT, "frame count " .. nframes, 24)
end
local pal: buffer
local own = false
if version == 2 then
local n = r:u16le()
if r.err then
return nil, r.err
end
if n < 1 or n > 256 or not r:need(n * 3) then
return nil, r.err or Err.new(Err.CORRUPT, "palette size " .. n, r:tell() - 2)
end
pal = Pixels.palette(r.buf, r.pos, n)
r:skip(n * 3)
own = true
else
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
own = raw ~= nil and buffer.len(raw) >= 768
pal = if raw and own then Pixels.palette(raw, 0, 256) else Pixels.grey()
end
local bpp = if version == 32 then 4 else 1
local raws: { Raw } = {}
local groups: { { type: string, count: number } } = {}
local function single(delay: number): Err.Err?
local x, y, w, h = r:i32le(), r:i32le(), r:i32le(), r:i32le()
if r.err then
return r.err
end
if w < 1 or h < 1 then
return Err.new(Err.CORRUPT, "frame size " .. w .. " x " .. h, r:tell() - 8)
end
if w * h > maxPixels then
return Err.new(Err.LIMIT, "frame " .. w .. " x " .. h)
end
if not r:need(w * h * bpp) then
return r.err
end
table.insert(raws, { x = x, y = y, w = w, h = h, at = r.pos, delay = delay })
r:skip(w * h * bpp)
return nil
end
for _ = 1, nframes do
local ft = r:i32le()
if r.err then
return nil, r.err
end
if ft == 0 then
local e = single(0.1)
if e then
return nil, e
end
table.insert(groups, { type = "single", count = 1 })
else
local n = r:i32le()
if r.err then
return nil, r.err
end
if n < 1 or #raws + n > maxFrames then
return nil, Err.new(if n < 1 then Err.CORRUPT else Err.LIMIT, "group of " .. n .. " frames", r:tell() - 4)
end
local ivs = {}
for k = 1, n do
ivs[k] = r:f32le()
end
if r.err then
return nil, r.err
end
for k = 1, n do
-- intervals are cumulative end times (R_GetSpriteFrame)
local e = single(math.max(0, ivs[k] - (if k > 1 then ivs[k - 1] else 0)))
if e then
return nil, e
end
end
table.insert(groups, { type = "group", count = n })
end
end
local minX: number, maxX: number, minY: number, maxY: number = math.huge, -math.huge, math.huge, -math.huge
for _, f in raws do
minX = math.min(minX, f.x)
maxX = math.max(maxX, f.x + f.w)
maxY = math.max(maxY, f.y)
minY = math.min(minY, f.y - f.h)
end
local cw, ch = maxX - minX, maxY - minY
if cw * ch > maxPixels then
return nil, Err.new(Err.LIMIT, "canvas " .. cw .. " x " .. ch)
end
local fpal = pal
if version ~= 2 or texFormat == 3 then
fpal = Pixels.keyed(pal, 255)
end
local b = r.buf
local frames: { any } = {}
for _, f in raws do
local img = Types.Image.new(f.w, f.h)
if version == 32 then
buffer.copy(img.pixels, 0, b, f.at, f.w * f.h * 4)
elseif version == 2 and texFormat == 2 then
-- index alpha: the colour is the last palette entry, the index is the alpha
local c = bit32.band(buffer.readu32(pal, 255 * 4), 0xFFFFFF)
for k = 0, f.w * f.h - 1 do
buffer.writeu32(img.pixels, k * 4, c + buffer.readu8(b, f.at + k) * 0x1000000)
end
else
Pixels.indexed(b, f.at, f.w, 8, img.pixels, f.w, f.h, true, fpal)
end
table.insert(frames, { image = img, delay = f.delay, x = f.x - minX, y = maxY - f.y, dispose = "background", blend = "source" })
end
local out = Types.Image.new(cw, ch)
local f1 = frames[1]
for yy = 0, f1.image.height - 1 do
buffer.copy(out.pixels, ((f1.y + yy) * cw + f1.x) * 4, f1.image.pixels, yy * f1.image.width * 4, f1.image.width * 4)
end
out.frames = if #frames > 1 then frames else nil
out.loops = 0
out.meta.origin = { -minX, maxY }
out.meta.source = {
format = "spr", version = version, type = stype, texFormat = if version == 2 then TEX_FORMATS[texFormat] or texFormat else nil,
radius = radius, width = mw, height = mh, beamLength = beam, sync = sync, groups = groups,
palette = own, origins = (function()
local o = {}
for i, f in raws do
o[i] = { f.x, f.y }
end
return o
end)(),
}
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Spr.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 version = opts and opts.version or 2
if version ~= 1 and version ~= 2 and version ~= 32 then
return nil, Err.new(Err.ARG, "version must be 1, 2 or 32")
end
local list: { { image: Types.Image, x: number, y: number, delay: number } } = {}
if img.frames and #img.frames > 0 then
for _, f in img.frames do
if f.image.format ~= "rgba8" then
return nil, Err.new(Err.ARG, "frames must be rgba8")
end
table.insert(list, { image = f.image, x = f.x, y = f.y, delay = f.delay })
end
else
table.insert(list, { image = img, x = 0, y = 0, delay = opts and opts.delay or 0.1 })
end
local origin = img.meta and img.meta.origin or { img.width // 2, img.height // 2 }
local mw: number, mh: number, alpha = 0, 0, false
for _, f in list do
mw = math.max(mw, f.image.width)
mh = math.max(mh, f.image.height)
local px = f.image.pixels
for k = 0, f.image.width * f.image.height - 1 do
if buffer.readu8(px, k * 4 + 3) < 128 then
alpha = true
break
end
end
end
local pal: buffer? = nil
if version == 1 then
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil
if not raw or buffer.len(raw) < 768 then
return nil, Err.new(Err.ARG, "a Quake sprite needs Quake's palette (opts.palette; it is not embedded)")
end
pal = Pixels.palette(raw, 0, 256)
elseif version == 2 then
local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil
if raw and buffer.len(raw) >= 768 then
pal = Pixels.palette(raw, 0, 256)
else
-- one palette for every frame: the frames side by side
local tw = 0
for _, f in list do
tw += f.image.width
end
local strip = Types.Image.new(tw, mh)
local x0 = 0
for _, f in list do
for yy = 0, f.image.height - 1 do
buffer.copy(strip.pixels, (yy * tw + x0) * 4, f.image.pixels, yy * f.image.width * 4, f.image.width * 4)
end
x0 += f.image.width
end
local _, colors = Miptex.indices(strip, nil, alpha)
local p = buffer.create(1024)
for i, c in colors do
buffer.writeu32(p, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1])
end
if alpha then
buffer.writeu32(p, 255 * 4, 0xFFFF0000) -- the alpha-test key: blue
end
pal = p
end
end
local texFormat = opts and opts.texFormat or (if alpha then 3 else 0)
local w = Bytes.writer()
w:string("IDSP")
w:u32le(version)
w:u32le(opts and opts.type or 2)
if version == 2 then
w:u32le(texFormat)
end
w:f32le(math.sqrt(mw * mw + mh * mh) / 2)
w:u32le(mw)
w:u32le(mh)
w:u32le(#list)
w:f32le(0)
w:u32le(0)
if version == 2 then
w:u16le(256)
w:bytes(Pixels.paletteBytes(pal :: buffer, 256))
end
for _, f in list do
local fw, fh = f.image.width, f.image.height
w:u32le(0)
w:u32le(bit32.band(f.x - origin[1], 0xFFFFFFFF))
w:u32le(bit32.band(origin[2] - f.y, 0xFFFFFFFF))
w:u32le(fw)
w:u32le(fh)
if version == 32 then
w:bytes(f.image.pixels, 0, fw * fh * 4)
else
local idx = Miptex.indices(f.image, pal, alpha and texFormat == 3 or version == 1)
w:bytes(idx, 0, fw * fh)
end
end
return w:finish(), nil
end
return Spr
+64
View File
@@ -0,0 +1,64 @@
--!strict
-- model/bsp/Lightmap: packs face lightmaps (w x h luxels each) into one atlas, shelf by shelf, tallest first, each
-- with a one-luxel border that repeats its edge (bilinear filtering stays inside the face).
local Lightmap = {}
export type Rect = { x: number, y: number, w: number, h: number } -- x, y: the first luxel inside the border
-- nil, message past maxPixels
function Lightmap.pack(sizes: { { number } }, maxPixels: number): (number, number, { Rect }?, string?)
local area, widest = 0, 1
for _, s in sizes do
area += (s[1] + 2) * (s[2] + 2)
widest = math.max(widest, s[1] + 2)
end
local W = 64
while W * W < area * 1.2 and W < 4096 do
W *= 2
end
W = math.max(W, widest)
local order = table.create(#sizes) :: { number }
for i = 1, #sizes do
order[i] = i
end
table.sort(order, function(a: number, b: number): boolean
local ha, hb = sizes[a][2], sizes[b][2]
if ha ~= hb then
return ha > hb
end
return a < b
end)
local out = table.create(#sizes) :: { Rect }
local x, y, rowH = 0, 0, 0
for _, i in order do
local w, h = sizes[i][1] + 2, sizes[i][2] + 2
if x + w > W then
x, y, rowH = 0, y + rowH, 0
end
out[i] = { x = x + 1, y = y + 1, w = sizes[i][1], h = sizes[i][2] }
x += w
rowH = math.max(rowH, h)
end
local H = math.max(1, y + rowH)
if W * H > maxPixels then
return 0, 0, nil, "limit: lightmap atlas " .. W .. " x " .. H
end
return W, H, out, nil
end
-- copies the outermost luxels of a rect into its border (rgba8 pixels, atlas width W)
function Lightmap.border(px: buffer, W: number, r: Rect)
local function copy(dx: number, dy: number, sx: number, sy: number)
buffer.writeu32(px, (dy * W + dx) * 4, buffer.readu32(px, (sy * W + sx) * 4))
end
for yy = r.y, r.y + r.h - 1 do
copy(r.x - 1, yy, r.x, yy)
copy(r.x + r.w, yy, r.x + r.w - 1, yy)
end
for xx = r.x - 1, r.x + r.w do
copy(xx, r.y - 1, xx, r.y)
copy(xx, r.y + r.h, xx, r.y + r.h - 1)
end
end
return Lightmap
@@ -1,15 +1,17 @@
--!strict
-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the
-- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture
-- size.
-- model/bsp/Quake: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from
-- bspfile.h of the Quake / Quake II source releases and ericw-tools (BSP2 / 2PSB; no code taken). Texture coordinates:
-- s = v . s.xyz + s.w over the texture size; lightmaps (style 0) packed into one atlas as TEXCOORD_1, extents as
-- CalcSurfaceExtents (16 texels per luxel).
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Lightmap = require("@rosetta/model/bsp/Lightmap")
local Miptex = require("@rosetta/codecs/image/Miptex")
local Brush = {}
local Quake = {}
local Scene = Types.Scene
local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32
local readi32, readu16, readf32, readu32, readu8 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32, buffer.readu8
local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Lump = { at: number, size: number }
@@ -18,10 +20,12 @@ export type Options = {
wal: ((name: string) -> buffer?)?, -- Quake II: a texture's .wal file (for its size)
maxPixels: number?,
maxVertices: number?,
lit: buffer?, -- Quake 1 coloured light (.lit: "QLIT", version 1, RGB per luxel)
lightmaps: boolean?, -- default true
}
type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean }
type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } }
type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number }, lm: { number } } -- lm: face, s, t per vertex
local function cstr(b: buffer, at: number, n: number): string
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
@@ -58,11 +62,14 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer
return out, nil
end
function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?)
function Quake.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?)
local q2 = variant == "q2"
local big = variant == "bsp2" or variant == "2psb"
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 fSize: number = if big then 28 else 20
local eSize: number = if big then 8 else 4
local nV, nE, nSE, nF = V.size // 12, E.size // eSize, SE.size // 4, Fc.size // fSize
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
@@ -125,11 +132,28 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
local batches: { [number]: { [number]: Batch } } = {}
local orders: { [number]: { number } } = {}
local skipped = 0
-- lightmaps: record 1 = a white luxel (sky / liquids), 2 = black (unlit faces), then one per lit face
local LT = lumps.lighting
local useLight = LT.size > 0 and not (opts and opts.lightmaps == false)
local rgb = variant == "hl" or q2
local lit = opts and opts.lit
if lit and (buffer.len(lit) < 8 or buffer.readstring(lit, 0, 4) ~= "QLIT" or buffer.readi32(lit, 4) ~= 1) then
lit = nil
end
local lmSizes: { { number } } = { { 1, 1 }, { 1, 1 } }
local lmFaces: { { face: number, ofs: number, smin: number, tmin: number, styles: number } } = { { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 }, { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 } }
local lumaTotal = 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 fo = base + Fc.at + f * fSize
local plane = if big then readi32(b, fo) else readu16(b, fo)
local side = if big then readi32(b, fo + 4) else readu16(b, fo + 2)
local firstEdge = if big then readi32(b, fo + 8) else readi32(b, fo + 4)
local numEdges = if big then readi32(b, fo + 12) else readu16(b, fo + 8)
local texinfo = if big then readi32(b, fo + 16) else readu16(b, fo + 10)
local styles = if big then fo + 20 else fo + 12
local lightofs = if big then readi32(b, fo + 24) else readi32(b, fo + 16)
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
if not model or numEdges < 3 or plane < 0 or texinfo < 0 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then
skipped += 1
continue
end
@@ -142,7 +166,13 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
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)
local eo = base + E.at + e * eSize
local v
if big then
v = if se >= 0 then readu32(b, eo) else readu32(b, eo + 4)
else
v = if se >= 0 then readu16(b, eo) else readu16(b, eo + 2)
end
if v >= nV then
ok = false
break
@@ -186,6 +216,37 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
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 rec = 2
if useLight then
local tflags = readi32(b, tio + (if q2 then 32 else 36))
local special = if q2 then bit32.band(tflags, 0x8C) ~= 0 else bit32.band(tflags, 1) ~= 0
if special then
rec = 1
elseif lightofs >= 0 then
local smin: number, smax: number, tmin: number, tmax: number = math.huge, -math.huge, math.huge, -math.huge
for k = 0, n - 1 do
local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3]
local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to
smin, smax = math.min(smin, sv), math.max(smax, sv)
tmin, tmax = math.min(tmin, tv), math.max(tmax, tv)
end
local bs, bt0 = math.floor(smin / 16), math.floor(tmin / 16)
local lw, lh = math.ceil((smax :: number) / 16) - bs + 1, math.ceil((tmax :: number) / 16) - bt0 + 1
local ns = 0
for k = 0, 3 do
if readu8(b, styles + k) ~= 255 then
ns += 1
end
end
local bytes = lw * lh * (if rgb then 3 else 1)
lumaTotal += lw * lh
if ns > 0 and lw > 0 and lh > 0 and lw <= 256 and lh <= 256 and lightofs + bytes <= LT.size and lumaTotal <= maxPixels then
table.insert(lmSizes, { lw, lh })
table.insert(lmFaces, { face = f, ofs = lightofs, smin = bs * 16, tmin = bt0 * 16, styles = ns })
rec = #lmFaces
end
end
end
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
@@ -193,7 +254,7 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
batches[model] = bm
local bt = bm[ti]
if not bt then
bt = { tex = ti, pos = {}, nrm = {}, uv = {} }
bt = { tex = ti, pos = {}, nrm = {}, uv = {}, lm = {} }
bm[ti] = bt
local ol = orders[model] or {}
orders[model] = ol
@@ -206,21 +267,69 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
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
local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to
uu[#uu + 1] = sv / w
uu[#uu + 1] = tv / h
local ll = batch.lm
ll[#ll + 1], ll[#ll + 2], ll[#ll + 3] = rec, sv, tv
end
end
end
local atlasW, atlasH, rects = 0, 0, nil :: { Lightmap.Rect }?
local lmTex: number? = nil
local atlas: Types.Image? = nil
if useLight and #lmFaces > 2 then
local W, H, rs, err = Lightmap.pack(lmSizes, maxPixels)
if not rs then
return nil, err
end
atlasW, atlasH, rects = W, H, rs
local img = Types.Image.new(W, H)
local px = img.pixels
local la = base + LT.at
buffer.writeu32(px, (rs[1].y * W + rs[1].x) * 4, 0xFFFFFFFF)
buffer.writeu32(px, (rs[2].y * W + rs[2].x) * 4, 0xFF000000)
local placed = {}
for i = 3, #lmFaces do
local lf, r = lmFaces[i], rs[i]
for yy = 0, r.h - 1 do
for xx = 0, r.w - 1 do
local k = yy * r.w + xx
local cr: number, cg: number, cb: number = 0, 0, 0
if rgb then
local o = la + lf.ofs + k * 3
cr, cg, cb = readu8(b, o), readu8(b, o + 1), readu8(b, o + 2)
elseif lit and 8 + (lf.ofs + k) * 3 + 3 <= buffer.len(lit) then
local o = 8 + (lf.ofs + k) * 3
cr, cg, cb = readu8(lit, o), readu8(lit, o + 1), readu8(lit, o + 2)
else
local v = readu8(b, la + lf.ofs + k)
cr, cg, cb = v, v, v
end
writeu32(px, ((r.y + yy) * W + r.x + xx) * 4, 0xFF000000 + (cb :: number) * 65536 + (cg :: number) * 256 + (cr :: number))
end
end
table.insert(placed, { face = lf.face, x = r.x, y = r.y, w = r.w, h = r.h, styles = lf.styles })
end
for i = 1, #lmFaces do
Lightmap.border(px, W, rs[i])
end
img.meta.source = { format = "bsp", lightmap = "atlas", coloured = rgb or lit ~= nil }
atlas = img
scene.meta.lightmaps = placed
lmTex = #texs + 1
end
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
mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height, lightmap = lmTex, lightmapTexCoord = if lmTex then 1 else nil } } :: any
table.insert(scene.materials, mat)
end
if atlas then
table.insert(scene.textures, { name = "lightmap", image = atlas })
end
local root: Types.Node = { name = "bsp", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
@@ -242,8 +351,23 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
for k = 0, nv - 1 do
writeu32(ib, k * 4, k)
end
local attrs: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }
if rects then
local lb = buffer.create(nv * 8)
for k = 0, nv - 1 do
local rec, sv, tv = bt.lm[k * 3 + 1], bt.lm[k * 3 + 2], bt.lm[k * 3 + 3]
local r, lf = rects[rec], lmFaces[rec]
local lu, lv = r.x + 0.5, r.y + 0.5
if rec > 2 then
lu, lv = r.x + (sv - lf.smin) / 16 + 0.5, r.y + (tv - lf.tmin) / 16 + 0.5
end
writef32(lb, k * 8, lu / atlasW)
writef32(lb, k * 8 + 4, lv / atlasH)
end
attrs.TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv)
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) },
attributes = attrs,
indices = Scene.accessor(ib, "u32", 1, nv),
mode = "triangles" :: any,
material = if ti > 0 then ti else nil,
@@ -258,4 +382,4 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
return scene, nil
end
return Brush
return Quake
+386
View File
@@ -0,0 +1,386 @@
--!strict
-- model/bsp/Tree: the BSP tree, collision hulls and visibility of Quake 1 / BSP2 / 2PSB / Half-Life / Quake II / Quake
-- III maps as tables (bspfile.h layouts; Unofficial Quake 3 Map Specs), plus point queries: the leaf and contents at a
-- point (Quake 1 hulls 0..3 through nodes / clipnodes as SV_HullPointContents; Quake II leaf contents; Quake III the
-- contents of the leaf's brushes) and the potentially visible set of a leaf (run-length zero bytes, as Mod_DecompressVis).
local Tree = {}
local readi32, readu16, readi16, readf32, readu8, readu32 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8, buffer.readu32
export type Lump = { at: number, size: number }
export type Plane = { normal: { number }, dist: number, type: number? }
export type Node = { plane: number, children: { number }, mins: { number }, maxs: { number }, firstFace: number?, numFaces: number? } -- children: >= 0 node, < 0 leaf -(child + 1)
export type Leaf = {
contents: number?,
cluster: number?,
area: number?,
visofs: number?,
mins: { number },
maxs: { number },
firstFace: number?,
numFaces: number?,
firstBrush: number?,
numBrushes: number?,
ambient: { number }?,
}
export type ClipNode = { plane: number, children: { number } } -- children: >= 0 clipnode, < 0 contents
export type Model = { mins: { number }, maxs: { number }, origin: { number }?, headnodes: { number }, visleafs: number?, firstFace: number, numFaces: number }
export type Brush = { firstSide: number, numSides: number, contents: number }
export type Side = { plane: number, texinfo: number }
export type Data = {
variant: string,
planes: { Plane },
nodes: { Node },
leaves: { Leaf },
clipnodes: { ClipNode }?,
models: { Model },
brushes: { Brush }?,
brushSides: { Side }?,
leafBrushes: { number }?,
leafFaces: { number }?,
visibility: buffer?, -- the raw lump
numClusters: number?,
clusterBytes: number?, -- Quake III bytes per cluster vector
}
local function v3(b: buffer, o: number, kind: string): { number }
if kind == "f" then
return { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) }
elseif kind == "i" then
return { readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) }
end
return { readi16(b, o), readi16(b, o + 2), readi16(b, o + 4) }
end
local function slice(b: buffer, base: number, l: Lump): buffer?
if l.size <= 0 then
return nil
end
local out = buffer.create(l.size)
buffer.copy(out, 0, b, base + l.at, l.size)
return out
end
-- nil, message past maxItems
function Tree.read(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, maxItems: number?): (Data?, string?)
local limit = maxItems or 2 ^ 22
local q2, q3 = variant == "q2", variant == "q3"
local bsp2, rmq = variant == "bsp2", variant == "2psb"
local d: Data = { variant = variant, planes = {}, nodes = {}, leaves = {}, models = {} }
local function count(l: Lump?, size: number): number
return if l then l.size // size else 0
end
local P = lumps.planes
local pSize = if q3 then 16 else 20
local np = count(P, pSize)
if np > limit then
return nil, "limit: too many planes"
end
for i = 0, np - 1 do
local o = base + P.at + i * pSize
d.planes[i + 1] = { normal = v3(b, o, "f"), dist = readf32(b, o + 12), type = if q3 then nil else readi32(b, o + 16) }
end
local N = lumps.nodes
local nSize = if q3 then 36 elseif q2 then 28 elseif bsp2 then 44 elseif rmq then 32 else 24
local nn = count(N, nSize)
if nn > limit then
return nil, "limit: too many nodes"
end
for i = 0, nn - 1 do
local o = base + N.at + i * nSize
local node: any
if q3 or q2 or bsp2 or rmq then
local bk = if q3 then "i" elseif bsp2 then "f" else "s"
local bs = if bk == "s" then 6 else 12
node = { plane = readi32(b, o), children = { readi32(b, o + 4), readi32(b, o + 8) }, mins = v3(b, o + 12, bk), maxs = v3(b, o + 12 + bs, bk) }
if not q3 then
local fo = o + 12 + bs * 2
if q2 then
node.firstFace, node.numFaces = readu16(b, fo), readu16(b, fo + 2)
else
node.firstFace, node.numFaces = readu32(b, fo), readu32(b, fo + 4)
end
end
else
local c = {}
for k = 0, 1 do
local p = readu16(b, o + 4 + k * 2)
c[k + 1] = if p < nn then p else -(65535 - p) - 1 -- Quakespasm Mod_LoadNodes_S: leaf 65535 - p
end
node = { plane = readi32(b, o), children = c, mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"), firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22) }
end
d.nodes[i + 1] = node
end
local L = lumps.leaves or lumps.leafs
local lSize = if q3 then 48 elseif q2 then 28 elseif bsp2 then 44 elseif rmq then 32 else 28
local nl = count(L, lSize)
if nl > limit then
return nil, "limit: too many leaves"
end
for i = 0, nl - 1 do
local o = base + L.at + i * lSize
local leaf: any
if q3 then
leaf = { cluster = readi32(b, o), area = readi32(b, o + 4), mins = v3(b, o + 8, "i"), maxs = v3(b, o + 20, "i"),
firstFace = readi32(b, o + 32), numFaces = readi32(b, o + 36), firstBrush = readi32(b, o + 40), numBrushes = readi32(b, o + 44) }
elseif q2 then
leaf = { contents = readi32(b, o), cluster = readi16(b, o + 4), area = readi16(b, o + 6), mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"),
firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22), firstBrush = readu16(b, o + 24), numBrushes = readu16(b, o + 26) }
else
local bk = if bsp2 then "f" else "s"
local bs = if bsp2 then 12 else 6
local fo = o + 8 + bs * 2
local big = bsp2 or rmq
leaf = { contents = readi32(b, o), visofs = readi32(b, o + 4), mins = v3(b, o + 8, bk), maxs = v3(b, o + 8 + bs, bk),
firstFace = if big then readu32(b, fo) else readu16(b, fo), numFaces = if big then readu32(b, fo + 4) else readu16(b, fo + 2) }
local ao = fo + (if big then 8 else 4)
leaf.ambient = { readu8(b, ao), readu8(b, ao + 1), readu8(b, ao + 2), readu8(b, ao + 3) }
end
d.leaves[i + 1] = leaf
end
if not q2 and not q3 then
local C = lumps.clipnodes
local cSize = if bsp2 or rmq then 12 else 8
local nc = count(C, cSize)
if nc > limit then
return nil, "limit: too many clipnodes"
end
local cl: { ClipNode } = {}
for i = 0, nc - 1 do
local o = base + C.at + i * cSize
local c
if cSize == 12 then
c = { readi32(b, o + 4), readi32(b, o + 8) }
else
c = {}
for k = 0, 1 do
local p = readu16(b, o + 4 + k * 2)
c[k + 1] = if p > nc then p - 65536 else p -- Quakespasm Mod_LoadClipnodes
end
end
cl[i + 1] = { plane = readi32(b, o), children = c }
end
d.clipnodes = cl
end
local M = lumps.models
local mSize = if q3 then 40 elseif q2 then 48 else 64
for i = 0, count(M, mSize) - 1 do
local o = base + M.at + i * mSize
local m: any
if q3 then
m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), headnodes = { 0 }, firstFace = readi32(b, o + 24), numFaces = readi32(b, o + 28) }
elseif q2 then
m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"), headnodes = { readi32(b, o + 36) }, firstFace = readi32(b, o + 40), numFaces = readi32(b, o + 44) }
else
m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"),
headnodes = { readi32(b, o + 36), readi32(b, o + 40), readi32(b, o + 44), readi32(b, o + 48) },
visleafs = readi32(b, o + 52), firstFace = readi32(b, o + 56), numFaces = readi32(b, o + 60) }
end
d.models[i + 1] = m
end
if q2 or q3 then
local B, S = lumps.brushes, lumps.brushsides
local nb, ns = count(B, 12), count(S, if q3 then 8 else 4)
if nb > limit or ns > limit then
return nil, "limit: too many brushes"
end
local brushes: { Brush }, sides: { Side } = {}, {}
for i = 0, nb - 1 do
local o = base + B.at + i * 12
brushes[i + 1] = { firstSide = readi32(b, o), numSides = readi32(b, o + 4), contents = readi32(b, o + 8) } -- Quake III: a texture index
end
for i = 0, ns - 1 do
if q3 then
local o = base + S.at + i * 8
sides[i + 1] = { plane = readi32(b, o), texinfo = readi32(b, o + 4) }
else
local o = base + S.at + i * 4
sides[i + 1] = { plane = readu16(b, o), texinfo = readi16(b, o + 2) }
end
end
d.brushes, d.brushSides = brushes, sides
local LB = lumps.leafbrushes
local lbs: { number } = {}
for i = 0, count(LB, if q3 then 4 else 2) - 1 do
lbs[i + 1] = if q3 then readi32(b, base + LB.at + i * 4) else readu16(b, base + LB.at + i * 2)
end
d.leafBrushes = lbs
if q3 then
-- brush contents come from the texture's contents flags
local T = lumps.textures
local nt = count(T, 72)
for _, br in brushes do
local t = br.contents
br.contents = if t >= 0 and t < nt then readi32(b, base + T.at + t * 72 + 68) else 0
end
end
end
local VL = lumps.visibility or lumps.visdata
d.visibility = if VL then slice(b, base, VL) else nil
local vis = d.visibility
if vis and q2 and buffer.len(vis) >= 4 then
d.numClusters = readi32(vis, 0)
elseif vis and q3 and buffer.len(vis) >= 8 then
d.numClusters, d.clusterBytes = readi32(vis, 0), readi32(vis, 4)
end
return d, nil
end
local function side(d: Data, plane: number, x: number, y: number, z: number): number
local p = d.planes[plane + 1]
if not p then
return 0
end
local n = p.normal
return x * n[1] + y * n[2] + z * n[3] - p.dist
end
-- the leaf (0-based) at a point, walking the tree of model (0-based, default 0)
function Tree.leafAt(d: Data, x: number, y: number, z: number, model: number?): number?
local m = d.models[(model or 0) + 1]
local node = if m then m.headnodes[1] else 0
for _ = 1, #d.nodes + 1 do
if node < 0 then
return -node - 1
end
local nd = d.nodes[node + 1]
if not nd then
return nil
end
node = if side(d, nd.plane, x, y, z) >= 0 then nd.children[1] else nd.children[2]
end
return nil
end
-- Quake 1: CONTENTS_* (-1 empty, -2 solid, -3 water, -4 slime, -5 lava, -6 sky) in hull 0..3; Quake II: the leaf's
-- CONTENTS_* bits; Quake III: the contents bits of the brushes holding the point
function Tree.contents(d: Data, x: number, y: number, z: number, hull: number?, model: number?): number?
local h = hull or 0
if (d.variant == "q1" or d.variant == "hl" or d.variant == "bsp2" or d.variant == "2psb") and h > 0 then
local m = d.models[(model or 0) + 1]
local cl = d.clipnodes or {}
local node = if m then m.headnodes[h + 1] or -1 else -1
for _ = 1, #cl + 1 do
if node < 0 then
return node
end
local c = cl[node + 1]
if not c then
return nil
end
node = if side(d, c.plane, x, y, z) >= 0 then c.children[1] else c.children[2]
end
return nil
end
local leaf = Tree.leafAt(d, x, y, z, model)
local lf = leaf and d.leaves[leaf + 1]
if not lf then
return nil
end
if d.variant ~= "q3" then
return lf.contents
end
local out = 0
local lbs: { number }, brushes: { Brush }, sides: { Side } = d.leafBrushes or {}, d.brushes or {}, d.brushSides or {}
local fb: number, nb: number = lf.firstBrush or 0, lf.numBrushes or 0
for k = fb, fb + nb - 1 do
local br = brushes[(lbs[k + 1] or -1) + 1]
if br then
local inside = true
for s = br.firstSide, br.firstSide + br.numSides - 1 do
local sd = sides[s + 1]
if not sd or side(d, sd.plane, x, y, z) > 0 then
inside = false
break
end
end
if inside then
out = bit32.bor(out, br.contents)
end
end
end
return out
end
local function decompress(vis: buffer, at: number, bytes: number, out: { boolean })
local n = buffer.len(vis)
local i = 0
while i < bytes and at < n do
local c = readu8(vis, at)
if c ~= 0 then
for bit = 0, 7 do
if bit32.band(c, bit32.lshift(1, bit)) ~= 0 then
out[i * 8 + bit + 1] = true
end
end
i += 1
at += 1
else
if at + 1 >= n then
break
end
i += readu8(vis, at + 1)
at += 2
end
end
end
-- the leaves (0-based, sorted) potentially visible from a leaf; nil without visibility data (everything visible)
function Tree.pvs(d: Data, leaf: number): { number }?
local lf = d.leaves[leaf + 1]
local vis = d.visibility
if not lf or not vis then
return nil
end
local out: { number } = {}
if d.variant == "q2" or d.variant == "q3" then
local nc = d.numClusters or 0
local c = lf.cluster or -1
if c < 0 or c >= nc then
return out
end
local bits: { boolean } = {}
if d.variant == "q2" then
if 4 + nc * 8 > buffer.len(vis) then
return nil
end
decompress(vis, readi32(vis, 4 + c * 8), (nc + 7) // 8, bits)
else
local sz = d.clusterBytes or 0
local o = 8 + c * sz
for k = 0, sz - 1 do
if o + k < buffer.len(vis) then
local v = readu8(vis, o + k)
for bit = 0, 7 do
if bit32.band(v, bit32.lshift(1, bit)) ~= 0 then
bits[k * 8 + bit + 1] = true
end
end
end
end
end
for i, l in d.leaves do
local cl = l.cluster or -1
if cl >= 0 and bits[cl + 1] then
table.insert(out, i - 1)
end
end
return out
end
-- Quake 1: bit k = leaf k + 1 (leaf 0 is the shared solid leaf), visleafs bits
local visofs = lf.visofs or -1
if leaf == 0 or visofs < 0 then
return out
end
local n = d.models[1] and d.models[1].visleafs or (#d.leaves - 1)
local bits: { boolean } = {}
decompress(vis, visofs, (n + 7) // 8, bits)
for k = 0, n - 1 do
if bits[k + 1] then
table.insert(out, k + 1)
end
end
return out
end
return Tree
+54 -8
View File
@@ -1,15 +1,18 @@
--!strict
-- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW
-- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up.
-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing.
-- model/bsp: compiled game maps, read: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30), Quake II (IBSP 38), Quake III
-- / RTCW (IBSP 46 / 47). Lightmaps (Quake 1 / 2 / Half-Life: one atlas, Quake III: its pages) as TEXCOORD_1; the tree,
-- collision hulls / brushes and visibility in meta.bsp with point queries (Bsp.leafAt / contents / pvs). Quake textures
-- need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. Not supported: Source engine VBSP,
-- light styles other than the first, BSPX lumps, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Brush = require("@rosetta/model/bsp/Brush")
local Quake = require("@rosetta/model/bsp/Quake")
local Quake3 = require("@rosetta/model/bsp/Quake3")
local Tree = require("@rosetta/model/bsp/Tree")
-- ------------------------------------------------------------------------------------------------ contract
local Bsp = {
@@ -18,7 +21,7 @@ local Bsp = {
extensions = { "bsp" },
mime = { "model/x-bsp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" },
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -27,6 +30,10 @@ export type DecodeOptions = {
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
patchLevel: number?, -- default 4
lit: (buffer | string)?, -- Quake 1: the map's .lit file (coloured light); also found as "<map>.lit" through files / resolve
lightmaps: boolean?, -- default true
tree: boolean?, -- meta.bsp (tree, hulls, visibility), default true
name: string?, -- the file name (finds the .lit)
maxPixels: number?, -- default 2^24
maxVertices: number?, -- default 2^24
}
@@ -46,6 +53,9 @@ function Bsp.sniff(r: Bytes.Reader): number
end
local m = r:peek(4)
local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0))
if m == "BSP2" or m == "2PSB" then
v = 29
end
if m == "IBSP" then
return if v == 38 or v == 46 or v == 47 then 1 else 0.3
end
@@ -88,6 +98,8 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
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 == "BSP2" or m == "2PSB" then
names, dir, variant = Q1_LUMPS, 4, string.lower(m)
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
@@ -114,13 +126,15 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
if pal and buffer.len(pal) < 768 then
pal = nil
end
scene, msg = Brush.decode(b, base, lumps, variant, {
scene, msg = Quake.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,
lit = if opts and opts.lit then Bytes.toBuffer(opts.lit) else (if opts and opts.name then Input.sibling(opts, (string.gsub(opts.name :: string, "%.[^./\\]*$", "")) .. ".lit") else nil),
lightmaps = opts and opts.lightmaps,
})
end
if not scene then
@@ -132,12 +146,44 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
scene.meta.entities = entities(text)
scene.meta.source = {
format = "bsp",
variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant],
variant = ({ q1 = "quake", bsp2 = "quake", ["2psb"] = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant],
layout = if variant == "bsp2" then "BSP2" elseif variant == "2psb" then "2PSB" else nil,
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,
palette = if variant == "q1" or variant == "bsp2" or variant == "2psb" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil,
}
if not (opts and opts.tree == false) then
local tree, terr = Tree.read(b, base, lumps, variant)
if not tree then
return nil, Err.from(terr)
end
scene.meta.bsp = tree
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ extras
local function tree(scene: any): Tree.Data?
return type(scene) == "table" and type(scene.meta) == "table" and scene.meta.bsp or nil
end
-- the leaf (0-based) at a point, in the tree of a model (0 = the world)
function Bsp.leafAt(scene: Types.Scene, x: number, y: number, z: number, model: number?): number?
local d = tree(scene)
return if d then Tree.leafAt(d, x, y, z, model) else nil
end
-- the contents at a point: Quake 1 CONTENTS_* (-1 empty, -2 solid, ...; hull 0 point, 1 player, 2 shambler, 3 crouch
-- in Half-Life), Quake II / III contents bits
function Bsp.contents(scene: Types.Scene, x: number, y: number, z: number, hull: number?, model: number?): number?
local d = tree(scene)
return if d then Tree.contents(d, x, y, z, hull, model) else nil
end
-- the leaves (0-based) potentially visible from a leaf; nil when the map has no visibility data
function Bsp.pvs(scene: Types.Scene, leaf: number): { number }?
local d = tree(scene)
return if d then Tree.pvs(d, leaf) else nil
end
return Bsp
+95
View File
@@ -0,0 +1,95 @@
-- archive/wad2 tests: WAD2 / WAD3 lumps, miptex / qpic / conchars / font / palette images against pixels decoded in
-- the fixture, ericw-tools qbsp's copy of a miptex, write round trips, adding images, errors, the fuzz pass.
-- Fixtures: tools/fixtures/wad2.py.
local T = require("@tests/T")
local F = require("@rosetta")
local Wad2 = require("@rosetta/archive/wad2")
local Miptex = require("@rosetta/codecs/image/Miptex")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/wad2")
local t = T.suite("wad2")
t:eq(Wad2.name, "wad2", "name")
for _, v in { "wad2", "wad3" } do
local c = Fx[v]
t:eq(F.detect(c.data), "wad2", v .. ": F.detect")
local a, err = Wad2.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, v .. ": " .. tostring(err))
t:eq(a.meta.source.variant, v, v .. ": variant")
local names = {}
for _, e in a:list() do
table.insert(names, e.name)
end
t:eq(table.concat(names, ","), table.concat(c.names, ","), v .. ": lump names in order")
for name, want in c.images do
local img, ierr = Wad2.image(a, name)
t:check(img, v .. ": image " .. name .. ": " .. tostring(ierr))
t:eq(img.width .. "x" .. img.height, want.w .. "x" .. want.h, v .. ": " .. name .. " size")
t:eq(Crc32.of(img.pixels), want.crc, v .. ": " .. name .. " pixels")
t:eq(img.meta.source.kind, want.kind, v .. ": " .. name .. " kind")
if want.mip2 then
local m2 = assert(Wad2.image(a, name, { mip = 2 }))
t:eq(Crc32.of(m2.pixels), want.mip2, v .. ": " .. name .. " mip 2")
end
end
-- write: the same lumps back
local out = assert(F.save(a))
local b = assert(Wad2.decode(Bytes.reader(out)))
t:eq(b.meta.source.variant, v, v .. ": variant kept")
for _, e in a:list() do
t:check(buffer.tostring(assert(a:read(e.name))) == buffer.tostring(assert(b:read(e.name))), v .. ": round trip " .. e.name)
t:eq((b:list()[1] :: any).type, (a:list()[1] :: any).type, v .. ": lump types kept")
end
end
do
local a = assert(Wad2.decode(Bytes.reader(buffer.fromstring(Fx.wad2.data))))
t:eq(Wad2.image(a, "palette").width, 16, "palette lump as a 16 x 16 image")
t:check(Wad2.palette(a) ~= nil, "the WAD's palette")
-- an explicit palette wins over the WAD's
local grey = string.rep("\0", 768)
local g = assert(Wad2.image(a, "brick", { palette = grey }))
t:eq(buffer.readu32(g.pixels, 0), 0xFF000000, "explicit palette")
-- qbsp copied brick into the BSP: same pixels
local m = assert(Miptex.decode(buffer.fromstring(Fx.bsp.miptex), 0, #Fx.bsp.miptex, { palette = Wad2.palette(a) }))
t:eq(Crc32.of(m.pixels), Fx.wad2.images.brick.crc, "qbsp's copy of the miptex")
-- adding images: palette colours map back exactly
local brick = assert(Wad2.image(a, "brick"))
local n = Wad2.new("wad2")
t:check(Wad2.addImage(n, "copy", brick, { palette = Fx.wad2.palette }), "addImage miptex")
t:check(Wad2.addImage(n, "pic", brick, { palette = Fx.wad2.palette, kind = "qpic" }), "addImage qpic")
local _, e1 = Wad2.addImage(n, "odd", F.ops.image.new(10, 10), { palette = Fx.wad2.palette })
t:check(e1 and e1.code == Err.ARG, "miptex sizes: multiples of 16")
local _, e2 = Wad2.addImage(n, "nopal", brick)
t:check(e2 and e2.code == Err.ARG, "WAD2 needs a palette")
local nb = assert(Wad2.decode(Bytes.reader(assert(F.save(n)))))
t:eq(Crc32.of(assert(Wad2.image(nb, "copy", { palette = Fx.wad2.palette })).pixels), Fx.wad2.images.brick.crc, "added miptex decodes the same")
t:eq(Crc32.of(assert(Wad2.image(nb, "pic", { palette = Fx.wad2.palette, keyed = false })).pixels), Fx.wad2.images.brick.crc, "added qpic decodes the same")
-- WAD3: its own palette from median cut (at most 256 colours: exact)
local w3 = assert(Wad2.decode(Bytes.reader(buffer.fromstring(Fx.wad3.data))))
local crete = assert(Wad2.image(w3, "crete"))
local n3 = Wad2.new("wad3")
t:check(Wad2.addImage(n3, "CRETE2", crete), "addImage into WAD3")
local d3 = assert(Wad2.decode(Bytes.reader(assert(F.save(n3)))))
t:eq(d3.meta.source.variant, "wad3", "WAD3 written")
t:eq(Crc32.of(assert(Wad2.image(d3, "CRETE2")).pixels), Fx.wad3.images.CRETE.crc, "WAD3 miptex with a made palette")
t:check(assert(Wad2.image(w3, "CONCHARS")).meta.font.glyphs[66].width == 8, "font glyph table")
local _, e3 = Wad2.image(w3, "missing")
t:check(e3 and e3.code == Err.ARG, "missing lump")
local _, e4 = Wad2.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.wad2.data, 1, 20))))
t:check(e4 and e4.code == Err.TRUNCATED, "truncated directory: " .. tostring(e4))
end
t:fuzz("decode", function(b: buffer)
local a = Wad2.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
Wad2.image(a, e.name)
end
end
return a
end, { Fx.wad2.data, Fx.wad3.data }, { mutations = 80 })
t:done()
+57
View File
@@ -0,0 +1,57 @@
-- data/q3shader tests: shader scripts against an independent tokenizer (tools/fixtures/q3shader.py), write round
-- trips, lookups, errors, the fuzz pass.
local T = require("@tests/T")
local F = require("@rosetta")
local Q3Shader = require("@rosetta/data/q3shader")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/q3shader")
local t = T.suite("q3shader")
t:eq(Q3Shader.name, "q3shader", "name")
local function dump(v: any): string
if type(v) ~= "table" then
return tostring(v)
end
local parts = {}
if v.name then
table.insert(parts, "name=" .. v.name)
table.insert(parts, "d=" .. dump(v.directives))
table.insert(parts, "s=" .. dump(v.stages))
elseif v.surface then
table.insert(parts, v.surface .. "=" .. v.shader)
else
for _, x in v do
table.insert(parts, dump(x))
end
end
return "{" .. table.concat(parts, "|") .. "}"
end
local samples = {}
for i, c in Fx.scripts do
t:eq(F.detect(c.text), "q3shader", "script " .. i .. ": F.detect")
local list, err = Q3Shader.decode(Bytes.reader(buffer.fromstring(c.text)))
t:check(list, "script " .. i .. ": " .. tostring(err))
t:eq(dump(list), dump(c.shaders), "script " .. i .. ": structure")
local out = assert(Q3Shader.encode(list :: any))
t:eq(dump(Q3Shader.decode(Bytes.reader(out))), dump(c.shaders), "script " .. i .. ": round trip")
table.insert(samples, c.text)
end
do
local list = assert(Q3Shader.decode(Bytes.reader(buffer.fromstring(Fx.scripts[2].text))))
local sky = assert(Q3Shader.find(list, "TEXTURES/SKIES/HELLSKY"))
t:eq(assert(Q3Shader.directive(sky.directives, "skyparms"))[2], "env/hell sky", "quoted token")
t:eq(#sky.stages, 1, "stage on brace lines")
local again = assert(F.data.load(Fx.scripts[1].text))
t:eq(#again, 2, "F.data.load")
local _, e1 = Q3Shader.decode(Bytes.reader(buffer.fromstring("textures/x\n{\n{\nmap a\n")))
t:check(e1 and e1.code == Err.TRUNCATED, "unclosed shader")
local _, e2 = Q3Shader.encode({ { name = "has space", directives = {}, stages = {} } } :: any)
t:check(e2 and e2.code == Err.ARG, "bad name")
end
t:fuzz("decode", function(b: buffer)
return Q3Shader.decode(Bytes.reader(b))
end, samples)
t:done()
+36
View File
@@ -0,0 +1,36 @@
-- data/q3skin tests: Quake III .skin files against tools/fixtures/q3shader.py's parse, write round trips, lookup,
-- errors, the fuzz pass.
local T = require("@tests/T")
local F = require("@rosetta")
local Q3Skin = require("@rosetta/data/q3skin")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/q3shader")
local t = T.suite("q3skin")
t:eq(Q3Skin.name, "q3skin", "name")
local function dump(list: any): string
local parts = {}
for _, e in list do
table.insert(parts, e.surface .. "=" .. e.shader)
end
return table.concat(parts, "|")
end
for i, c in Fx.skins do
local list, err = Q3Skin.decode(Bytes.reader(buffer.fromstring(c.text)))
t:check(list, "skin " .. i .. ": " .. tostring(err))
t:eq(dump(list), dump(c.entries), "skin " .. i .. ": entries")
t:eq(dump(Q3Skin.decode(Bytes.reader(assert(Q3Skin.encode(list :: any))))), dump(c.entries), "skin " .. i .. ": round trip")
t:eq(F.detect(c.text, { name = "x.skin" }), "q3skin", "skin " .. i .. ": F.detect")
end
t:eq(Q3Skin.shader(assert(Q3Skin.decode(Bytes.reader(buffer.fromstring(Fx.skins[1].text)))), "H_HEAD"), "models/players/sarge/band.tga", "skin lookup")
local _, e1 = Q3Skin.encode({ { surface = "a,b", shader = "x" } })
t:check(e1 and e1.code == Err.ARG, "comma in a surface name")
local _, e2 = Q3Skin.decode(Bytes.reader(buffer.fromstring("no comma here\n")))
t:check(e2 and e2.code == Err.CORRUPT, "line without a comma")
t:fuzz("decode", function(b: buffer)
return Q3Skin.decode(Bytes.reader(b))
end, { Fx.skins[1].text, Fx.skins[2].text })
t:done()
+48
View File
@@ -0,0 +1,48 @@
-- image/lmp tests: qpic pictures, palette.lmp and colormap.lmp against Pillow (tools/fixtures/lmp.py), the palette
-- through files, the grey fallback, the qpic writer round trip, errors, the fuzz pass.
local T = require("@tests/T")
local F = require("@rosetta")
local Lmp = require("@rosetta/image/lmp")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/lmp")
local t = T.suite("lmp")
t:eq(Lmp.name, "lmp", "name")
local samples = {}
for _, p in Fx.pics do
local img, err = Lmp.decode(Bytes.reader(buffer.fromstring(p.data)), { palette = Fx.palette })
t:check(img, p.name .. ": " .. tostring(err))
t:eq(img.width .. "x" .. img.height, p.w .. "x" .. p.h, p.name .. ": size")
t:eq(Crc32.of(img.pixels), p.crc, p.name .. ": pixels = Pillow (index 255 transparent)")
local opaque = assert(Lmp.decode(Bytes.reader(buffer.fromstring(p.data)), { files = { ["gfx/palette.lmp"] = Fx.palette }, keyed = false }))
t:eq(Crc32.of(opaque.pixels), p.crcOpaque, p.name .. ": opaque, palette through files")
t:eq(opaque.meta.source.palette, true, p.name .. ": palette found")
-- write back: the palette colours map to the same indices
local out = assert(Lmp.encode(img, { palette = Fx.palette }))
t:check(buffer.tostring(out) == p.data, p.name .. ": writer gives the same bytes")
table.insert(samples, p.data)
end
do
local p = Fx.pics[2]
t:eq(F.detect(p.data, { name = "conback.lmp" }), "lmp", "F.detect by size + extension")
local grey = assert(Lmp.decode(Bytes.reader(buffer.fromstring(p.data))))
t:eq(grey.meta.source.palette, false, "no palette: grey")
local cm = assert(Lmp.decode(Bytes.reader(buffer.fromstring(Fx.colormap.data)), { palette = Fx.palette }))
t:eq(cm.width .. "x" .. cm.height, "256x64", "colormap size")
t:eq(Crc32.of(cm.pixels), Fx.colormap.crc, "colormap = Pillow")
local pal = assert(Lmp.decode(Bytes.reader(buffer.fromstring(Fx.palette))))
t:eq(Crc32.of(pal.pixels), Fx.palcrc, "palette.lmp swatch = Pillow")
t:eq(#pal.meta.palette, 256, "palette entries")
t:check(buffer.tostring(assert(Lmp.encode(pal, { kind = "palette" }))) == Fx.palette, "palette round trip")
local _, e1 = Lmp.encode(grey)
t:check(e1 and e1.code == Err.ARG, "qpic writer needs the palette")
local _, e2 = Lmp.decode(Bytes.reader(buffer.fromstring(string.sub(p.data, 1, 30))), { kind = "qpic" })
t:check(e2 and e2.code == Err.CORRUPT or e2 and e2.code == Err.TRUNCATED, "truncated qpic: " .. tostring(e2))
end
t:fuzz("decode", function(b: buffer)
return Lmp.decode(Bytes.reader(b), { palette = Fx.palette, kind = "qpic" })
end, samples)
t:done()
+67
View File
@@ -0,0 +1,67 @@
-- image/spr tests: Quake / Half-Life (alpha test, index alpha, normal) / SPR32 sprites against the frames written by
-- tools/fixtures/spr.py (pixels, canvas positions from the origins, group delays), the writer round trips (versions 1,
-- 2 and 32), errors, the fuzz pass.
local T = require("@tests/T")
local F = require("@rosetta")
local Spr = require("@rosetta/image/spr")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/spr")
local t = T.suite("spr")
t:eq(Spr.name, "spr", "name")
local samples = {}
for _, s in Fx.sprites do
t:eq(F.detect(s.data), "spr", s.name .. ": F.detect")
local img, err = Spr.decode(Bytes.reader(buffer.fromstring(s.data)), { palette = Fx.palette })
t:check(img, s.name .. ": " .. tostring(err))
t:eq(img.width .. "x" .. img.height, s.w .. "x" .. s.h, s.name .. ": canvas")
t:eq(img.meta.origin[1] .. " " .. img.meta.origin[2], s.origin[1] .. " " .. s.origin[2], s.name .. ": origin")
local frames = img.frames or { { image = img, x = 0, y = 0, delay = 0.1 } }
t:eq(#frames, #s.frames, s.name .. ": frames")
for i, want in s.frames do
local f = frames[i]
t:eq(f.x .. "," .. f.y .. " " .. f.image.width .. "x" .. f.image.height, want.x .. "," .. want.y .. " " .. want.w .. "x" .. want.h, s.name .. ": frame " .. i .. " placement")
t:eq(Crc32.of(f.image.pixels), want.crc, s.name .. ": frame " .. i .. " pixels")
t:check(math.abs(f.delay - want.delay) < 1e-6, s.name .. ": frame " .. i .. " delay")
end
t:eq(img.meta.source.version, s.version, s.name .. ": version")
-- write in the same version and read back the same frames
local out, eerr = Spr.encode(img, { version = s.version, palette = if s.version == 2 then Fx.hlpalette else Fx.palette, texFormat = s.tex })
t:check(out, s.name .. ": encode " .. tostring(eerr))
local back = assert(Spr.decode(Bytes.reader(out :: buffer), { palette = Fx.palette }))
local bf = back.frames or { { image = back, x = 0, y = 0 } }
local same = #bf == #frames
for i, f in frames do
local g = bf[i]
same = same and g and g.x == f.x and g.y == f.y
if s.version == 32 or s.version == 1 or s.tex == 0 or s.tex == 3 then
same = same and Crc32.of(g.image.pixels) == Crc32.of(f.image.pixels)
end
end
t:check(same, s.name .. ": round trip keeps frames, placement and pixels")
table.insert(samples, s.data)
end
do
local q = Fx.sprites[1]
local img = assert(Spr.decode(Bytes.reader(buffer.fromstring(q.data)), { palette = Fx.palette }))
-- Half-Life from a Quake sprite: a made palette
local hl = assert(Spr.encode(img))
local back = assert(Spr.decode(Bytes.reader(hl)))
t:eq(back.meta.source.version, 2, "default version 2")
t:eq(back.meta.source.texFormat, "alphatest", "transparent pixels: alpha test")
local grey = assert(Spr.decode(Bytes.reader(buffer.fromstring(q.data))))
t:eq(grey.meta.source.palette, false, "Quake sprite without a palette: grey")
local _, e1 = Spr.encode(img, { version = 1 })
t:check(e1 and e1.code == Err.ARG, "version 1 needs a palette")
local _, e2 = Spr.decode(Bytes.reader(buffer.fromstring("IDS2" .. string.rep("\0", 40))))
t:check(e2 and e2.code == Err.CORRUPT, "Quake II sprite: not IDSP")
local _, e3 = Spr.decode(Bytes.reader(buffer.fromstring(string.sub(q.data, 1, 60))), { palette = Fx.palette })
t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3))
end
t:fuzz("decode", function(b: buffer)
return Spr.decode(Bytes.reader(b), { palette = Fx.palette })
end, samples)
t:done()
+159
View File
@@ -90,6 +90,40 @@ do
t:eq(grey.meta.source.palette, false, "q1 without a palette: grey")
end
-- Half-Life / Quake II RGB lightmaps
for _, name in { "hl", "q2" } do
local c = Fx[name]
local s = assert(Bsp.decode(Bytes.reader(buffer.fromstring(c.data)))) :: any
local data = buffer.fromstring(c.data)
local la = buffer.readi32(data, (if name == "q2" then 8 + 7 * 8 else 4 + 8 * 8))
local atlas
for _, tx in s.textures do
if tx.name == "lightmap" then
atlas = tx.image
end
end
local placed = {}
for _, r in s.meta.lightmaps do
placed[r.face] = r
end
local bad = 0
for _, want in c.lightmaps do
local r = placed[want.face]
if not r or r.w ~= want.w or r.h ~= want.h then
bad += 1
else
for k = 0, want.w * want.h - 1 do
local px = buffer.readu32(atlas.pixels, ((r.y + k // want.w) * atlas.width + r.x + k % want.w) * 4)
local o = la + want.ofs + k * 3
if px ~= 0xFF000000 + buffer.readu8(data, o + 2) * 65536 + buffer.readu8(data, o + 1) * 256 + buffer.readu8(data, o) then
bad += 1
end
end
end
end
t:check(#c.lightmaps == 12 and bad == 0, name .. ": RGB lightmaps (" .. bad .. " wrong)")
end
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")
@@ -214,4 +248,129 @@ do
end
t:eq(threw, 0, "q3: mutated lumps never throw")
end
-- ericw-tools maps: BSP 29 / BSP2 / 2PSB, lightmap atlas, .lit, visibility and hulls
do
local base: any = nil
for _, name in { "bsp29", "bsp2", "2psb" } do
local c = Fx.ericw[name]
local s, err = Bsp.decode(Bytes.reader(buffer.fromstring(c.data)), { lit = c.lit })
t:check(s, name .. ": " .. tostring(err))
local sc = s :: any
t:eq(F.detect(c.data), "bsp", name .. ": F.detect")
t:eq(sc.meta.source.variant, "quake", name .. ": variant")
t:eq(sc.meta.source.layout, ({ bsp29 = nil, bsp2 = "BSP2", ["2psb"] = "2PSB" } :: any)[name], name .. ": layout")
t:eq(sc.meta.skippedFaces, 0, name .. ": every face read")
-- the same compile in three layouts: the same triangles
local all = {}
for _, mesh in sc.meshes do
for _, p in mesh.primitives do
for _, x in Soup.list(Soup.positions(p)) do
table.insert(all, x)
end
end
end
if base then
t:check(near(all, base, 0), name .. ": geometry equals BSP 29's")
else
base = all
end
-- lightmaps: sizes as CalcSurfaceExtents, luxels copied from the lump (coloured from the .lit)
local placed = {}
for _, r in sc.meta.lightmaps do
placed[r.face] = r
end
local atlas
for _, tx in sc.textures do
if tx.name == "lightmap" then
atlas = tx.image
end
end
t:check(atlas ~= nil, name .. ": lightmap atlas")
local data = buffer.fromstring(c.data)
local litBuf = buffer.fromstring(c.lit)
local sizeBad, pixBad = 0, 0
for _, want in c.lightmaps do
local r = placed[want.face]
if not r or r.w ~= want.w or r.h ~= want.h then
sizeBad += 1
else
for k = 0, want.w * want.h - 1, 7 do
local x, y = r.x + k % want.w, r.y + k // want.w
local px = buffer.readu32(atlas.pixels, (y * atlas.width + x) * 4)
local o = 8 + (want.ofs + k) * 3
local exp = 0xFF000000 + buffer.readu8(litBuf, o + 2) * 65536 + buffer.readu8(litBuf, o + 1) * 256 + buffer.readu8(litBuf, o)
if px ~= exp then
pixBad += 1
end
end
end
end
t:eq(sizeBad, 0, name .. ": lightmap sizes (" .. #c.lightmaps .. " faces)")
t:eq(pixBad, 0, name .. ": lightmap luxels from the .lit")
local _ = data
local prim = sc.meshes[1].primitives[1]
t:check(prim.attributes.TEXCOORD_1 ~= nil, name .. ": TEXCOORD_1")
local mat = sc.materials[prim.material]
t:eq(sc.textures[mat.extras.bsp.lightmap].name, "lightmap", name .. ": material names the atlas")
local lu = Types.Scene.reader(prim.attributes.TEXCOORD_1) :: any
local inRange = true
for k = 0, prim.attributes.TEXCOORD_1.count - 1 do
if lu(k, 0) < 0 or lu(k, 0) > 1 or lu(k, 1) < 0 or lu(k, 1) > 1 then
inRange = false
end
end
t:check(inRange, name .. ": lightmap coordinates inside the atlas")
local grey = assert(Bsp.decode(Bytes.reader(buffer.fromstring(c.data)))) :: any
local gr
for _, r in grey.meta.lightmaps do
if r.face == c.lightmaps[1].face then
gr = r
end
end
local gimg
for _, tx in grey.textures do
if tx.name == "lightmap" then
gimg = tx.image
end
end
local v = buffer.readu8(data, 0)
local _ = v
local px = buffer.readu32(gimg.pixels, (gr.y * gimg.width + gr.x) * 4)
t:eq(bit32.band(px, 0xFF), bit32.band(bit32.rshift(px, 8), 0xFF), name .. ": without .lit: grey luxels")
-- visibility as vis wrote it
t:eq(#sc.meta.bsp.leaves, c.leaves, name .. ": leaves")
local pvsBad = 0
for leaf, want in c.pvs do
local got = Bsp.pvs(sc, leaf - 1) or {}
if table.concat(got, ",") ~= table.concat(want, ",") then
pvsBad += 1
end
end
t:eq(pvsBad, 0, name .. ": PVS of every leaf")
t:check(c.visible > 0, name .. ": vis ran")
-- contents in the point hull and the clipping hulls
local cBad = 0
for _, pr in c.probes do
for h = 0, 2 do
local got = Bsp.contents(sc, pr.p[1], pr.p[2], pr.p[3], h)
if got ~= pr.c[h + 1] then
cBad += 1
t:note("%s: contents at %s hull %d: %s, want %s", name, table.concat(pr.p, " "), h, tostring(got), tostring(pr.c[h + 1]))
end
end
end
t:eq(cBad, 0, name .. ": contents at the probes")
t:eq(Bsp.contents(sc, -128, -128, 100, 0), -1, name .. ": the room is empty")
t:eq(Bsp.contents(sc, 0, 0, 100, 0), -2, name .. ": the pillar is solid")
t:eq(Bsp.contents(sc, -250, 0, 100, 1), -2, name .. ": hull 1 is solid near a wall")
t:eq(Bsp.contents(sc, 0, 0, -8, 0), -2, name .. ": the floor is solid")
local leaf = Bsp.leafAt(sc, -128, -128, 24)
t:check(leaf and leaf > 0, name .. ": player start leaf")
local seen = Bsp.pvs(sc, leaf :: number) or {}
t:check(table.find(seen, Bsp.leafAt(sc, 0, 0, 220) :: number) ~= nil, name .. ": the light's leaf is visible from the start")
end
t:fuzz("bsp2", function(b: buffer)
return Bsp.decode(Bytes.reader(b), { lit = Fx.ericw.bsp2.lit })
end, { Fx.ericw.bsp2.data, Fx.ericw["2psb"].data, Fx.ericw.bsp29.data }, { mutations = 60 })
end
t:done()
+190
View File
@@ -1982,3 +1982,193 @@ do
BuildMap.decode(Bytes.reader(map))
end)
end
do
local Xml = require("@rosetta/codecs/text/Xml")
local XB = require("@tests/gen/xml_bench")
local doc = assert(Xml.decode(XB.text))
bench("xml decode (DOM)", 5, #XB.text, function()
Xml.decode(XB.text)
end)
bench("xml events", 5, #XB.text, function()
for _ in Xml.events(XB.text) do
end
end)
bench("xml encode", 5, #XB.text, function()
Xml.encode(doc)
end)
end
-- ws-arch codecs: zstd, brotli, bzip2, xz / lzma
do
-- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a
-- 128^3 noise voxel grid through VOX and greedy meshing
local Types = require("@rosetta/Types")
local MeshOps = require("@rosetta/ops/MeshOps")
local Gltf = require("@rosetta/model/gltf")
local Obj = require("@rosetta/model/obj")
local Stl = require("@rosetta/model/stl")
local Ply = require("@rosetta/model/ply")
local Vox = require("@rosetta/model/vox")
local N = 400
local pos = Types.Scene.accessor(nil, "f32", 3, N * N)
local uv = Types.Scene.accessor(nil, "f32", 2, N * N)
for y = 0, N - 1 do
for x = 0, N - 1 do
local i = y * N + x
buffer.writef32(pos.data, i * 12, x / N)
buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05)
buffer.writef32(pos.data, i * 12 + 8, y / N)
buffer.writef32(uv.data, i * 8, x / N)
buffer.writef32(uv.data, i * 8 + 4, y / N)
end
end
local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6)
local k = 0
for y = 0, N - 2 do
for x = 0, N - 2 do
local a = y * N + x
for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do
buffer.writeu32(ind.data, k * 4, v)
k += 1
end
end
end
local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any
MeshOps.computeNormals(prim)
local scene = Types.Scene.fromPrimitive(prim, "grid")
bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function()
MeshOps.computeNormals(prim)
end)
local glb = assert(Gltf.encode(scene, { binary = true }))
bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function()
Gltf.decode(Bytes.reader(glb))
end)
bench("gltf glb encode", 3, buffer.len(glb), function()
Gltf.encode(scene, { binary = true })
end)
local obj = assert(Obj.encode(scene))
bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function()
Obj.decode(Bytes.reader(obj))
end)
bench("obj encode", 2, buffer.len(obj), function()
Obj.encode(scene)
end)
local stl = assert(Stl.encode(scene))
bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function()
Stl.decode(Bytes.reader(stl))
end)
local ply = assert(Ply.encode(scene))
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
Ply.decode(Bytes.reader(ply))
end)
local Fbx = require("@rosetta/model/fbx")
local fbx = assert(Fbx.encode(scene))
bench("fbx binary decode (" .. buffer.len(fbx) // 1000 .. " KB)", 3, buffer.len(fbx), function()
Fbx.decode(Bytes.reader(fbx))
end)
bench("fbx binary encode (zlib arrays)", 2, buffer.len(fbx), function()
Fbx.encode(scene)
end)
bench("fbx binary encode (raw arrays)", 3, buffer.len(fbx), function()
Fbx.encode(scene, { compress = false })
end)
local fbxa = assert(Fbx.encode(scene, { ascii = true }))
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
Fbx.decode(Bytes.reader(fbxa))
end)
local ThreeMf = require("@rosetta/model/3mf")
local tmf = assert(ThreeMf.encode(scene))
bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
ThreeMf.decode(Bytes.reader(tmf))
end)
bench("3mf encode", 2, buffer.len(tmf), function()
ThreeMf.encode(scene)
end)
local Wrl = require("@rosetta/model/vrml")
local X3d = require("@rosetta/model/x3d")
local wrl = assert(Wrl.encode(scene))
bench("vrml decode (" .. buffer.len(wrl) // 1000 .. " KB)", 2, buffer.len(wrl), function()
Wrl.decode(Bytes.reader(wrl))
end)
bench("vrml encode", 2, buffer.len(wrl), function()
Wrl.encode(scene)
end)
local x3d = assert(X3d.encode(scene))
bench("x3d xml decode (" .. buffer.len(x3d) // 1000 .. " KB)", 2, buffer.len(x3d), function()
X3d.decode(Bytes.reader(x3d))
end)
local V = 128
local grid = Types.Voxels.new(V, V, V)
for z = 0, V - 1 do
for y = 0, V - 1 do
for x = 0, V - 1 do
local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0
if z < h then
Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6)
end
end
end
end
local vox = assert(Vox.encode(grid))
bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function()
Vox.decode(Bytes.reader(vox))
end)
bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function()
MeshOps.voxelsToPrimitive(grid)
end)
end
-- ------------------------------------------------------------------------------------------- ws-video2-flv: fps
do
-- H.263 / Sorenson Spark (codecs/video/H263, tools/fixtures/h263.py): CIF mandelbrot zooms (1 Mbit/s, an I picture
-- every 12), one picture per decode, planes only (frameImage copies excluded) and with the yuv420p Image copies
local H263 = require("@rosetta/codecs/video/H263")
local Base64 = require("@rosetta/core/Base64")
local HB = require("@tests/gen/h263_bench")
local function run(tag: string)
for _, c in HB do
local file = Base64.decode(c.file) :: buffer
for _, images in { false, true } do
local n = #c.units
local dt = bench(string.format("%s %dx%d%s%s", c.name, c.width, c.height, if images then " +img" else "", tag), 3, c.width * c.height * 3 // 2 * n, function()
local dec = H263.new({ flv = c.flv })
for _, u in c.units do
if images then
dec:image(file, u[1], u[2])
else
dec:decode(file, u[1], u[2])
end
end
end)
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. n .. " frames)", n / dt))
end
end
end
jitTune(false)
run("")
if runtime == "luajit" then
jitTune(true)
run(" (jit tuned)")
jitTune(false)
end
end
-- ws-quake: .map brushes to polygons (codecs/model/Brush clip + CSG hull + merge; MB/s of map text) and a compiled
-- BSP with its lightmap atlas and tree (MB/s of file); fixtures tools/fixtures/map.py, tools/fixtures/bsp.py
do
local MapFmt = require("@rosetta/model/map")
local BspFmt = require("@rosetta/model/bsp")
local Bytes = require("@rosetta/core/Bytes")
local MF = require("@tests/gen/map")
local BF = require("@tests/gen/bsp")
local text = buffer.fromstring(MF.quake.text)
bench("map decode (brushes)", 5, buffer.len(text), function()
assert(MapFmt.decode(Bytes.reader(text), { files = MF.quake.files }))
end)
bench("map decode (hull + merge)", 5, buffer.len(text), function()
assert(MapFmt.decode(Bytes.reader(text), { files = MF.quake.files, hull = true, merge = true }))
end)
local bsp = buffer.fromstring(BF.ericw.bsp29.data)
bench("bsp decode (lightmaps, tree)", 5, buffer.len(bsp), function()
assert(BspFmt.decode(Bytes.reader(bsp)))
end)
end
+50 -1
View File
@@ -5,7 +5,7 @@
# miptex(name, w, h, rng, palette=None) -> bytes (four mip levels of random indices; WAD3 / BSP 30 add the palette)
# compile(ctx, text, files, qbsp_args, light_args=None, vis=False) -> { bsp, obj?, log }
# read_bsp(data) -> dict of the parsed lumps
import os, shutil, struct, subprocess, tempfile
import math, os, shutil, struct, subprocess, tempfile
Q1_LUMPS = ["entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting",
"clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models"]
@@ -151,3 +151,52 @@ def face_plane(b, f):
if f["side"]:
return (-nx, -ny, -nz, -d)
return (nx, ny, nz, d)
def write_bsp(b, lumps):
# reassembles a Quake 1 family BSP (b from read_bsp: its variant decides the header) from raw lumps
head = {"BSP2": b"BSP2", "2PSB": b"2PSB"}.get(b["variant"]) or struct.pack("<i", int(b["variant"][3:]))
off = len(head) + 8 * len(Q1_LUMPS)
body, dirs = b"", []
for n in Q1_LUMPS:
d = lumps[n]
dirs.append(struct.pack("<ii", off + len(body), len(d)))
body += d + b"\0" * ((4 - len(d) % 4) % 4)
return head + b"".join(dirs) + body
def extents(b, f):
# CalcSurfaceExtents: lightmap size in luxels (16 texels each) and the texture mins
ti = b["texinfo"][f["texinfo"]]
pts = face_points(b, f)
out = []
for j in range(2):
vals = [p[0] * ti[j * 4] + p[1] * ti[j * 4 + 1] + p[2] * ti[j * 4 + 2] + ti[j * 4 + 3] for p in pts]
lo, hi = math.floor(min(vals) / 16), math.ceil(max(vals) / 16)
out.append(hi - lo + 1)
return out
def light(b, rng, rgb=False):
# fills the lighting lump with random luxels at the extents of every face that is not TEX_SPECIAL (the nix light
# has no ray tracing backend); returns the new BSP bytes and { face: (w, h, ofs) }
big = b["variant"] in ("BSP2", "2PSB")
faces = bytearray(b["lumps"]["faces"])
size = 28 if big else 20
data = b""
out = {}
for i, f in enumerate(b["faces"]):
ti = b["texinfo"][f["texinfo"]]
o = i * size + (20 if big else 12)
if ti[9] & 1:
faces[o:o + 8] = bytes([255, 255, 255, 255]) + struct.pack("<i", -1)
continue
w, h = extents(b, f)
ofs = len(data)
data += bytes(rng.randrange(256) for _ in range(w * h * (3 if rgb else 1)))
faces[o:o + 8] = bytes([0, 255, 255, 255]) + struct.pack("<i", ofs)
out[i] = (w, h, ofs)
lumps = dict(b["lumps"])
lumps["faces"] = bytes(faces)
lumps["lighting"] = data
return write_bsp(b, lumps), out
+105 -4
View File
@@ -6,11 +6,14 @@
# q3: polygon, mesh and patch faces, two lightmaps, vertex colours; plus a .pk3 (zip) of it for assimp.
# References: the expected triangles per model and texture (positions, normals, texture coordinates, computed here
# with the documented rules), texture CRCs, entities; assimp's soup of the Quake III map.
# ericw: the room of map.py compiled by ericw-tools (qbsp with hulls + vis) as BSP 29, BSP2 and 2PSB; the lighting lump
# filled here at the extents of CalcSurfaceExtents (the nix light has no ray tracer), plus a .lit; expected: lightmap
# sizes per face, the PVS of every leaf (Mod_DecompressVis), contents at probe points in hulls 0..2 (SV_HullPointContents).
# tests/gen/bsp.luau { q1 = { data, palette, models = { [model] = { [texture] = { pos, uv, nrm } } }, textures,
# entities }, hl = ..., q2 = { ..., wal }, q3 = { ..., lightmaps, patchArea, assimp } }
import importlib.util, io, math, os, struct, zipfile, zlib
INPUTS = ["tools/fixtures/_quake_ref.py"]
INPUTS = ["tools/fixtures/_quake_ref.py", "tools/fixtures/_qbsp.py", "tools/fixtures/map.py"]
def ref(ctx):
@@ -110,7 +113,23 @@ def brush_map(rng, variant, pal):
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("<i", s) for s in surfedges)
L["faces"] = b"".join(struct.pack("<HHiHH4Bi", p, sd, fe, ne, ti, 0, 255, 255, 255, -1) for p, sd, fe, ne, ti in flist)
# Half-Life / Quake II: RGB lightmaps at the CalcSurfaceExtents sizes (Quake 1 is covered by the ericw maps)
light, lms, fb = b"", [], b""
for fi, (p, sd, fe, ne, ti) in enumerate(flist):
if variant == "q1":
fb += struct.pack("<HHiHH4Bi", p, sd, fe, ne, ti, 255, 255, 255, 255, -1)
continue
s4, t4 = tis[ti]
pts = [verts[edges[abs(surfedges[fe + k])][0 if surfedges[fe + k] >= 0 else 1]] for k in range(ne)]
size = []
for v in (s4, t4):
vals = [q[0] * v[0] + q[1] * v[1] + q[2] * v[2] + v[3] for q in pts]
size.append(math.ceil(max(vals) / 16) - math.floor(min(vals) / 16) + 1)
lms.append({"face": fi, "w": size[0], "h": size[1], "ofs": len(light)})
fb += struct.pack("<HHiHH4Bi", p, sd, fe, ne, ti, 0, 255, 255, 255, len(light))
light += bytes(rng.randrange(256) for _ in range(size[0] * size[1] * 3))
L["faces"] = fb
L["lighting"] = light
if q2:
L["texinfo"] = b"".join(struct.pack("<8fii32si", *s, *t, 0, 0, texnames[k].encode(), -1) for s, t, k in texinfo)
L["models"] = b"".join(struct.pack("<9fiii", *([0.0] * 9), 0, first, 6) for first in (0, 6))
@@ -148,7 +167,7 @@ def brush_map(rng, variant, pal):
dirs.append((off + len(body), len(d)))
body += d + b"\0" * ((4 - len(d) % 4) % 4)
data = head + b"".join(struct.pack("<ii", *d) for d in dirs) + body
out = {"data": data, "models": {str(k): v for k, v in models.items()}, "names": texnames}
out = {"data": data, "models": {str(k): v for k, v in models.items()}, "names": texnames, "lightmaps": lms}
if not q2:
out["textures"] = mips
else:
@@ -222,6 +241,88 @@ def q3_map(rng):
return {"data": data, "models": expect, "lightmaps": lmcrc, "patchArea": 32.0 * 32.0, "shaders": [s.decode() for s in shaders]}
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def pvs(b, leaf):
lf = b["leaves"][leaf]
vis, ofs = b["lumps"]["visibility"], lf[1]
n = b["models"][0][13]
if leaf == 0 or ofs < 0:
return []
bits, i = [], 0
while len(bits) < n and ofs < len(vis):
c = vis[ofs]
if c:
bits += [(c >> k) & 1 for k in range(8)]
ofs += 1
else:
bits += [0] * (8 * vis[ofs + 1])
ofs += 2
return [k + 1 for k in range(n) if k < len(bits) and bits[k]]
def contents(b, hull, p):
def side(plane):
nx, ny, nz, d, _ = b["planes"][plane]
return p[0] * nx + p[1] * ny + p[2] * nz - d
head = b["models"][0][9 + hull]
if hull == 0:
n = head
nn = len(b["nodes"])
while True:
nd = b["nodes"][n]
c = nd[1] if side(nd[0]) >= 0 else nd[2]
if b["variant"] == "bsp29":
c &= 0xFFFF
if c >= nn:
return b["leaves"][65535 - c][0]
elif c < 0:
return b["leaves"][-c - 1][0]
n = c
n = head
nc = len(b["clipnodes"])
while n >= 0:
cn = b["clipnodes"][n]
c = cn[1] if side(cn[0]) >= 0 else cn[2]
if b["variant"] == "bsp29":
c &= 0xFFFF
if c > nc:
c -= 65536
n = c
return n
def ericw(ctx, rng):
H = load(ctx, "_qbsp")
M = load(ctx, "map")
B = load(ctx, "brush")
world, door = M.layout(rng)
wad = H.wad([(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in M.TEX])
text = M.write(B, "quake", world, door, rng, "tex.wad")
probes = [(0, 0, 220), (-128, -128, 24), (200, 200, 100), (0, 0, 100), (-264, 0, 100), (0, 0, -8), (40, 0, 100),
(-240, -240, 30), (100, -150, 64), (300, 300, 300)]
out = {}
for name, args in (("bsp29", []), ("bsp2", ["-bsp2"]), ("2psb", ["-2psb"])):
res = H.compile(ctx, text, {"tex.wad": wad}, ["-nopercent"] + args, vis=True)
b = H.read_bsp(res["bsp"])
data, lm = H.light(b, rng)
b = H.read_bsp(data)
lit = b"QLIT" + struct.pack("<i", 1) + bytes(rng.randrange(256) for _ in range(len(b["lumps"]["lighting"]) * 3))
out[name] = {
"data": data, "lit": lit,
"lightmaps": [{"face": f, "w": w, "h": h, "ofs": o} for f, (w, h, o) in sorted(lm.items())],
"pvs": [pvs(b, i) for i in range(len(b["leaves"]))],
"probes": [{"p": list(p), "c": [contents(b, h, p) for h in range(3)]} for p in probes],
"faces": len(b["faces"]), "leaves": len(b["leaves"]), "visible": len(b["lumps"]["visibility"]),
}
return out
def generate(ctx):
rng = ctx.rng(101)
R = ref(ctx)
@@ -235,4 +336,4 @@ def generate(ctx):
with zipfile.ZipFile(zbuf, "w") as z:
z.writestr("maps/test.bsp", q3["data"])
q3["assimp"] = R.assimp_soup(ctx, zbuf.getvalue(), "pk3")
ctx.emit("bsp", {"q1": q1, "hl": hl, "q2": q2, "q3": q3})
ctx.emit("bsp", {"q1": q1, "hl": hl, "q2": q2, "q3": q3, "ericw": ericw(ctx, rng)})
+49
View File
@@ -0,0 +1,49 @@
# Docs inputs for the Quake sections of the scene / archive / image / data pages (tools/fixtures.py; tools/docs_check.py
# explains the inputs): the room .map of map.py with its WAD2, the same room compiled by ericw-tools (qbsp + vis, the
# lighting lump filled by _qbsp.light), a gfx.wad-like WAD2 (wad2.py's writer), a qpic .lmp and a random palette.lmp
# (Quake's own is GPL), a Half-Life sprite (spr.py), a shader script and a .skin (q3shader.py).
# tests/gen/docs_quake.luau { files = { [name] = bytes }, vars = { roomMapText = "room.map", ... } }
import importlib.util, os, struct
INPUTS = ["tools/docs_check.py", "tools/fixtures/_qbsp.py", "tools/fixtures/map.py", "tools/fixtures/spr.py",
"tools/fixtures/q3shader.py"]
def mod(ctx, name):
spec = importlib.util.spec_from_file_location("fx_" + name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
rng = ctx.rng(9)
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
check = importlib.util.module_from_spec(spec)
spec.loader.exec_module(check)
H, M, B = mod(ctx, "_qbsp"), mod(ctx, "map"), mod(ctx, "brush")
files = {}
pal = bytes(rng.randrange(256) for _ in range(768))
texwad = H.wad([(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in M.TEX])
world, door = M.layout(rng)
text = M.write(B, "quake", world, door, rng, "gfx/tex.wad")
files["room.map"] = text
files["tex.wad"] = texwad
res = H.compile(ctx, text.replace("gfx/tex.wad", "tex.wad"), {"tex.wad": texwad}, ["-nopercent"], vis=True)
files["room.bsp"], _ = H.light(H.read_bsp(res["bsp"]), rng)
qp = bytes(rng.randrange(256) for _ in range(24 * 24))
files["palette.lmp"] = pal
files["disc.lmp"] = struct.pack("<II", 24, 24) + qp
mips = [bytes(rng.randrange(256) for _ in range((32 >> m) * (32 >> m))) for m in range(4)]
files["gfx.wad"] = H.wad([("palette", 0x40, pal), ("disc", 0x42, files["disc.lmp"]),
("brick", 0x44, H.miptex("brick", 32, 32, rng, pixels=mips))])
S = mod(ctx, "spr")
files["flame.spr"] = S.sprite(rng, 2, [("single", (-16, 16, 32, 32)), ("group", [0.1, 0.2], [(-8, 8, 16, 16), (-8, 8, 16, 16)])], pal)["data"]
Q = mod(ctx, "q3shader")
files["base.shader"] = Q.SCRIPTS[0]
files["sarge.skin"] = Q.SKINS[0]
check.emit_inputs(ctx, files, {
"roomMapText": "room.map", "texWadBytes": "tex.wad", "roomBspBytes": "room.bsp", "quakePaletteBytes": "palette.lmp",
"discLmpBytes": "disc.lmp", "gfxWadBytes": "gfx.wad", "flameSprBytes": "flame.spr", "shaderText": "base.shader",
"skinText": "sarge.skin",
})
+39
View File
@@ -0,0 +1,39 @@
# image/lmp fixtures (tools/fixtures.py): qpic .lmp pictures, a palette.lmp and a colormap.lmp written from wad.h /
# draw.c; reference rgba from Pillow (a "P" image with the palette, index 255 transparent for qpics). The palette is
# random: Quake's own is GPL and never committed.
# tests/gen/lmp.luau { palette, pics = { { name, data, w, h, crc, crcOpaque } }, colormap = { data, crc }, palcrc }
import json, struct, zlib
CODE = r"""
import json, sys, zlib, io
from PIL import Image
job = json.loads(sys.stdin.read())
out = {}
pal = bytes.fromhex(job["pal"])
for k, (w, h, hexpix, key) in job["imgs"].items():
im = Image.frombytes("P", (w, h), bytes.fromhex(hexpix))
im.putpalette(pal)
if key is not None:
im.info["transparency"] = key
out[k] = zlib.crc32(im.convert("RGBA").tobytes())
print(json.dumps(out))
"""
def generate(ctx):
rng = ctx.rng(31)
pal = bytes(rng.randrange(256) for _ in range(768))
imgs, pics = {}, []
for name, w, h in (("disc", 24, 24), ("conback", 64, 40), ("num_0", 24, 24), ("wide", 3, 1)):
pix = bytes(rng.randrange(256) for _ in range(w * h))
imgs[name] = [w, h, pix.hex(), 255]
imgs[name + "_o"] = [w, h, pix.hex(), None]
pics.append({"name": name, "data": struct.pack("<II", w, h) + pix, "w": w, "h": h})
cmap = bytes(rng.randrange(256) for _ in range(64 * 256)) + b"\0"
imgs["colormap"] = [256, 64, cmap[:16384].hex(), None]
imgs["palette"] = [16, 16, bytes(range(256)).hex(), None]
ref = json.loads(ctx.python(["pillow"], CODE, input=json.dumps({"pal": pal.hex(), "imgs": imgs}).encode()))
for p in pics:
p["crc"] = ref[p["name"]]
p["crcOpaque"] = ref[p["name"] + "_o"]
ctx.emit("lmp", {"palette": pal, "pics": pics, "colormap": {"data": cmap, "crc": ref["colormap"]}, "palcrc": ref["palette"]})
+117
View File
@@ -0,0 +1,117 @@
# data/q3shader and data/q3skin fixtures (tools/fixtures.py): shader scripts in the style of the Quake III Arena
# Shader Manual (comments, quoted tokens, braces on their own lines or not, several stages) and .skin files; reference
# structure from an independent tokenizer here (COM_ParseExt rules: tokens per line, // and /* */ comments).
# tests/gen/q3shader.luau { scripts = { { text, shaders = { { name, directives, stages } } } }, skins = { { text, entries } } }
import re
SCRIPTS = [
"""// base walls
textures/base_wall/metalfloor_wall_10
{
qer_editorimage textures/base_wall/metalfloor_wall_10.tga
surfaceparm metalsteps
{
map $lightmap
rgbGen identity
}
{
map textures/base_wall/metalfloor_wall_10.tga
blendFunc GL_DST_COLOR GL_ZERO
rgbGen identity
}
}
textures/sfx/flame1 {
surfaceparm nolightmap
cull none /* both sides */
q3map_surfacelight 2500
{
animMap 10 textures/sfx/flame1.tga textures/sfx/flame2.tga textures/sfx/flame3.tga
blendFunc GL_ONE GL_ONE
tcMod scale 1 1 // per frame
}
}
""",
"""/*
* a sky and a quoted path
*/
textures/skies/hellsky
{
skyparms "env/hell sky" 512 -
surfaceparm noimpact
surfaceparm sky
{ map textures/skies/clouds.tga
tcMod scroll 0.05 0.06 }
}
models/players/sarge/band
{
deformVertexes wave 100 sin 0 2 0 1
{
map models/players/sarge/band.tga
alphaFunc GE128
depthWrite
}
}
""",
]
SKINS = [
"tag_head,\ntag_torso,\nh_head,models/players/sarge/band.tga\nh_cap,models/players/sarge/cigar.tga\n",
"u_torso,models/players/sarge/default.tga\r\nl_legs,models/players/sarge/default.tga\r\n",
]
def tokenize(text):
text = re.sub(r"/\*.*?\*/", lambda m: "\n" * m.group(0).count("\n"), text, flags=re.S)
lines = []
for raw in text.split("\n"):
raw = raw.split("//")[0] if '"' not in raw else raw
cur = []
for m in re.finditer(r'"([^"]*)"|([{}])|([^\s{}"]+)', raw):
if m.group(2):
if cur:
lines.append(cur)
cur = []
lines.append([m.group(2)])
else:
cur.append(m.group(1) if m.group(1) is not None else m.group(3))
if cur:
lines.append(cur)
return lines
def parse(text):
lines = tokenize(text)
out, k = [], 0
while k < len(lines):
sh = {"name": lines[k][0], "directives": [], "stages": []}
k += 2
stage = None
while True:
d = lines[k]
k += 1
if d == ["{"]:
stage = []
elif d == ["}"]:
if stage is None:
break
sh["stages"].append(stage)
stage = None
elif stage is not None:
stage.append(d)
else:
sh["directives"].append(d)
out.append(sh)
return out
def generate(ctx):
skins = []
for s in SKINS:
entries = []
for line in s.replace("\r", "").split("\n"):
if line.strip():
a, b = line.split(",", 1)
entries.append({"surface": a.strip(), "shader": b.strip()})
skins.append({"text": s, "entries": entries})
ctx.emit("q3shader", {"scripts": [{"text": s, "shaders": parse(s)} for s in SCRIPTS], "skins": skins})
+82
View File
@@ -0,0 +1,82 @@
# image/spr fixtures (tools/fixtures.py): sprites written from spritegn.h (Quake IDSP 1: two single frames and a
# group of three; Half-Life IDSP 2 with its palette, alpha test and index alpha; DarkPlaces SPR32); expected frame
# pixels (rgba CRCs), canvas positions from the frame origins, and group delays from the cumulative intervals.
# tests/gen/spr.luau { palette, sprites = { { name, data, version, w, h, origin, frames = { { x, y, w, h, crc, delay } } } } }
import struct, zlib
def frame_bytes(rng, w, h, bpp):
return bytes(rng.randrange(256) for _ in range(w * h * bpp))
def rgba(pix, pal, key=None, mode=None):
out = bytearray()
for i in pix:
if mode == "indexalpha":
out += pal[255 * 3:255 * 3 + 3] + bytes([i])
elif key is not None and i == key:
out += pal[i * 3:i * 3 + 3] + b"\0"
else:
out += pal[i * 3:i * 3 + 3] + b"\xff"
return zlib.crc32(bytes(out))
def sprite(rng, version, layout, pal, tex=3):
# layout: list of ("single", (ox, oy, w, h)) or ("group", [intervals], [(ox, oy, w, h)])
singles = []
body = b""
frames = []
for item in layout:
if item[0] == "single":
body += struct.pack("<i", 0)
entries = [(item[1], 0.1)]
else:
ivs = item[1]
body += struct.pack("<ii", 1, len(ivs)) + b"".join(struct.pack("<f", v) for v in ivs)
entries = [(f, ivs[k] - (ivs[k - 1] if k else 0)) for k, f in enumerate(item[2])]
for (ox, oy, w, h), delay in entries:
pix = frame_bytes(rng, w, h, 4 if version == 32 else 1)
body += struct.pack("<iiii", ox, oy, w, h) + pix
if version == 32:
crc = zlib.crc32(pix)
elif version == 2 and tex == 2:
crc = rgba(pix, pal, mode="indexalpha")
elif version == 2 and tex != 3:
crc = rgba(pix, pal)
else:
crc = rgba(pix, pal, 255)
frames.append({"ox": ox, "oy": oy, "w": w, "h": h, "crc": crc, "delay": struct.unpack("<f", struct.pack("<f", delay))[0]})
n = len(layout)
mw = max(f["w"] for f in frames)
mh = max(f["h"] for f in frames)
if version == 2:
head = b"IDSP" + struct.pack("<iiifiiifi", 2, 2, tex, 16.0, mw, mh, n, 0.0, 0) + struct.pack("<H", 256) + pal
else:
head = b"IDSP" + struct.pack("<iifiiifi", version, 2, 16.0, mw, mh, n, 0.0, 0)
minx = min(f["ox"] for f in frames)
maxy = max(f["oy"] for f in frames)
for f in frames:
f["x"], f["y"] = f["ox"] - minx, maxy - f["oy"]
w = max(f["ox"] + f["w"] for f in frames) - minx
h = maxy - min(f["oy"] - f["h"] for f in frames)
return {"data": head + body, "version": version, "w": w, "h": h, "origin": [-minx, maxy], "frames": frames}
def generate(ctx):
rng = ctx.rng(64)
pal = bytes(rng.randrange(256) for _ in range(768))
hlpal = bytes(rng.randrange(256) for _ in range(768))
sprites = []
q = sprite(rng, 1, [("single", (-8, 8, 16, 16)), ("single", (-12, 20, 24, 28)),
("group", [0.1, 0.25, 0.5], [(-4, 4, 8, 8), (-6, 6, 12, 12), (-8, 10, 16, 20)])], pal)
q["name"] = "quake"
sprites.append(q)
for tex, name in ((3, "hl_alphatest"), (2, "hl_indexalpha"), (0, "hl_normal")):
s = sprite(rng, 2, [("single", (-16, 16, 32, 32)), ("single", (-10, 12, 20, 24))], hlpal, tex)
s["name"] = name
s["tex"] = tex
sprites.append(s)
s32 = sprite(rng, 32, [("single", (-5, 5, 10, 10)), ("group", [0.2, 0.4], [(-5, 5, 10, 10), (-3, 9, 6, 12)])], pal)
s32["name"] = "spr32"
sprites.append(s32)
ctx.emit("spr", {"palette": pal, "hlpalette": hlpal, "sprites": sprites})
+77
View File
@@ -0,0 +1,77 @@
# archive/wad2 fixtures (tools/fixtures.py): a Quake gfx.wad-like WAD2 (palette, conchars, a qpic, miptex textures, one
# '{' keyed) and a Half-Life WAD3 (miptex with their palettes, a qpic with its palette, a font), written with
# tools/fixtures/_qbsp.py's WAD writer from wad.h; expected pixels decoded here (index -> palette, 255 or 0 keyed);
# plus the WAD2 compiled into a map by ericw-tools qbsp (it reads the miptex lumps: the BSP's copies must match).
# tests/gen/wad2.luau { wad2 = { data, palette, images = { [name] = { w, h, crc, kind } } }, wad3 = ..., bsp }
import importlib.util, os, struct, zlib
INPUTS = ["tools/fixtures/_qbsp.py"]
def helper(ctx):
spec = importlib.util.spec_from_file_location("_qbsp", os.path.join(ctx.root, "tools", "fixtures", "_qbsp.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def rgba(pix, pal, key=None):
out = bytearray()
for i in pix:
if key is not None and i == key:
out += pal[i * 3:i * 3 + 3] + b"\0"
else:
out += pal[i * 3:i * 3 + 3] + b"\xff"
return zlib.crc32(bytes(out))
def generate(ctx):
H = helper(ctx)
rng = ctx.rng(22)
pal = bytes(rng.randrange(256) for _ in range(768))
images = {}
lumps = [("palette", 0x40, pal)]
con = bytes(rng.randrange(256) for _ in range(128 * 128))
lumps.append(("conchars", 0x44, con))
images["conchars"] = {"w": 128, "h": 128, "crc": rgba(con, pal, 0), "kind": "conchars"}
qw, qh = 24, 10
qp = bytes(rng.randrange(256) for _ in range(qw * qh))
lumps.append(("disc", 0x42, struct.pack("<II", qw, qh) + qp))
images["disc"] = {"w": qw, "h": qh, "crc": rgba(qp, pal, 255), "kind": "qpic"}
for name, w, h in (("brick", 32, 16), ("{fence", 16, 16)):
mips = [bytes(rng.randrange(256) for _ in range((w >> m) * (h >> m))) for m in range(4)]
lumps.append((name, 0x44, H.miptex(name, w, h, rng, pixels=mips)))
images[name] = {"w": w, "h": h, "crc": rgba(mips[0], pal, 255 if name[0] == "{" else None), "kind": "miptex",
"mip2": rgba(mips[2], pal, 255 if name[0] == "{" else None)}
wad2 = H.wad(lumps)
out = {"wad2": {"data": wad2, "palette": pal, "images": images, "names": [l[0] for l in lumps]}}
# WAD3
images3 = {}
lumps3 = []
for name, w, h in (("CRETE", 32, 32), ("{GRATE", 16, 32)):
p3 = bytes(rng.randrange(256) for _ in range(768))
mips = [bytes(rng.randrange(256) for _ in range((w >> m) * (h >> m))) for m in range(4)]
lumps3.append((name, 0x43, H.miptex(name, w, h, rng, p3, pixels=mips)))
images3[name] = {"w": w, "h": h, "crc": rgba(mips[0], p3, 255 if name[0] == "{" else None), "kind": "miptex"}
p3 = bytes(rng.randrange(256) for _ in range(768))
qp = bytes(rng.randrange(256) for _ in range(20 * 12))
lumps3.append(("LOGO", 0x42, struct.pack("<II", 20, 12) + qp + struct.pack("<H", 256) + p3))
images3["LOGO"] = {"w": 20, "h": 12, "crc": rgba(qp, p3, 255), "kind": "qpic"}
fw, fh = 256, 16
fp = bytes(rng.randrange(256) for _ in range(fw * fh))
chars = b"".join(struct.pack("<HH", (c % 32) * 8, 8) for c in range(256))
lumps3.append(("CONCHARS", 0x46, struct.pack("<IIII", fw, fh, 2, 8) + chars + fp + struct.pack("<H", 256) + p3))
images3["CONCHARS"] = {"w": fw, "h": fh, "crc": rgba(fp, p3, 255), "kind": "font"}
out["wad3"] = {"data": H.wad(lumps3, b"WAD3"), "images": images3, "names": [l[0] for l in lumps3]}
# qbsp copies the miptex it uses into the BSP
text = ('{\n"classname" "worldspawn"\n"wad" "gfx.wad"\n{\n'
"( 0 0 0 ) ( 0 1 0 ) ( 0 0 1 ) brick 0 0 0 1 1\n( 0 0 0 ) ( 0 0 1 ) ( 1 0 0 ) brick 0 0 0 1 1\n"
"( 0 0 0 ) ( 1 0 0 ) ( 0 1 0 ) brick 0 0 0 1 1\n( 64 64 64 ) ( 64 65 64 ) ( 65 64 64 ) brick 0 0 0 1 1\n"
"( 64 64 64 ) ( 65 64 64 ) ( 64 64 65 ) brick 0 0 0 1 1\n( 64 64 64 ) ( 64 64 65 ) ( 64 65 64 ) brick 0 0 0 1 1\n"
'}\n}\n{\n"classname" "info_player_start"\n"origin" "32 32 32"\n}\n')
res = H.compile(ctx, text, {"gfx.wad": wad2}, ["-nofill", "-noclip", "-nopercent"])
b = H.read_bsp(res["bsp"])
L = b["lumps"]["miptex"]
o = struct.unpack_from("<i", L, 4)[0]
out["bsp"] = {"miptex": L[o:o + 40 + 32 * 16 * 85 // 64]}
ctx.emit("wad2", out)