diff --git a/.gitignore b/.gitignore index b551782b..6f02e77c 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,12 @@ __pycache__/ # Local toolchain .local/ + +# Rust builds and locally derived reference/preview data +target/ +.reference/ +derived/ + +# Decoded original style references are not shipped mod artwork. +examples/mods/*/art/source/ + diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..5e0dbc33 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,936 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "const-random", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "no-std-compat" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b93853da6d84c2e3c7d730d6473e8817692dd89be387eb01b94d7f108ecb5b8c" +dependencies = [ + "spin", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "raptor-replica" +version = "0.1.0" +dependencies = [ + "anyhow", + "image", + "rhai", + "schemars", + "sdl2", + "semver", + "serde", + "serde_json", + "sha2", + "tempfile", + "toml", +] + +[[package]] +name = "rhai" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0334639972c0ea5a3fd366aa36116754a11431b619fec3ed559b3f73bcbcebf5" +dependencies = [ + "ahash", + "bitflags 2.13.2", + "no-std-compat", + "num-traits", + "once_cell", + "rhai_codegen", + "serde", + "smallvec", + "smartstring", + "thin-vec", + "web-time", +] + +[[package]] +name = "rhai_codegen" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cd3a7535e50bf36857e7be7bec276d334e8c2dfa469c2201226fd01638ea5ca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "sdl2" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d42407afc6a8ab67e36f92e80b8ba34cbdc55aaeed05249efe9a2e8d0e9feef" +dependencies = [ + "bitflags 1.3.2", + "lazy_static", + "libc", + "sdl2-sys", +] + +[[package]] +name = "sdl2-sys" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff61407fc75d4b0bbc93dc7e4d6c196439965fbef8e4a4f003a36095823eac0" +dependencies = [ + "cfg-if", + "libc", + "version-compare", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" +dependencies = [ + "serde", +] + +[[package]] +name = "smartstring" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29" +dependencies = [ + "autocfg", + "static_assertions", + "version_check", +] + +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thin-vec" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6a4b9ba8738cb4a4f399d37e266becfd475e75eb73425b87a05a2f2039ba63e" + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "version-compare" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579a42fc0b8e0c63b76519a339be31bed574929511fa53c1a3acae26eb258f29" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zerocopy" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..812a200c --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "raptor-replica" +version = "0.1.0" +edition = "2024" +rust-version = "1.88" +license = "GPL-2.0-or-later" +description = "Rust Raptor engine with deterministic simulation and local modding" + +[features] +default = ["desktop"] +desktop = ["dep:sdl2"] + +[dependencies] +anyhow = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "0.8" +semver = { version = "1", features = ["serde"] } +sha2 = "0.10" +rhai = { version = "1.23", features = ["serde", "sync"] } +schemars = "0.8" +image = { version = "0.25", default-features = false, features = ["png"] } +sdl2 = { version = "0.38", optional = true } + +[dev-dependencies] +tempfile = "3" + +[profile.release] +lto = "thin" + + +[[bin]] +name = "raptor-rust" +path = "src/main.rs" diff --git a/PLAN.md b/PLAN.md index bf7af9ae..d3582174 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1,37 +1,30 @@ -# RaptorReplica — Raptor: Call of the Shadows +# Rust rewrite milestones -**Status: PLAYABLE** — original engine, original data, extracted into a -modern asset tree. Full documentation lives in [`docs/`](docs/README.md): +The C++ engine remains playable and retained as a reference. The Rust engine runs independently alongside it on branch `codex/rust-rewrite`. Both are selectable through `play.sh`. Original catalog/reference assets remain ignored; authored mod images and sounds are tracked in Git. -- [docs/README.md](docs/README.md) — overview, layout, quick start -- [docs/architecture.md](docs/architecture.md) — startup flow, asset handles, subsystems -- [docs/glb-format.md](docs/glb-format.md) — reverse-engineered GLB archive format + cipher -- [docs/asset-pipeline.md](docs/asset-pipeline.md) — data/ tree, INDEX catalog, editing content -- [docs/building.md](docs/building.md) — dependencies, build, config/save paths -- [docs/upstream-patches.md](docs/upstream-patches.md) — every diff against the vendored engine +The registered game has three sectors with nine waves each. Archive slots are asset containers, not five independent campaigns. -Run with `./play.sh`. +## Implemented -## The 5 mission packs +- Checked asset decoders, typed namespaced registries and original content registration. +- Independent integer simulation at 70/3 Hz; deterministic RNG and SDL2 input/interpolated indexed rendering. +- Original / Scale2x / Scale3x / Scale4x modes, joined terrain filtering, sharp bitmap text and separate derived cache. +- Rust MUS, GENMIDI FM synthesis and digital DSP mixing, with native PCM comparisons. +- Menus, shop, equipment, mission selection, pilot slots, atomic saves, read-only legacy import and original AGX cinematics. +- Local mods, dependencies/conflicts, explicit overrides/priority/hashes, bounded deterministic Rhai hooks and transactional commands. +- In-game enable/disable and pending changes, save diagnostics, schemas, validation CLI and scripted Aurora example. +- Optional source-hashed HD loader/setting; one accepted player-frame proof with original fallback. +- C++/Rust replay recording and comparison tools, synthetic tests and local-original-data checks. -The registered data ships 5 campaign packs (each mission: mountain → valley -→ sky phases + boss). Pack presence is detected from catalog slots at boot; -slot 2 or 3 present flips the engine to registered mode. +## Acceptance gates -## Roadmap (on top of the source) +1. **Foundation and complete playable first mission:** verify the entire mission through its boss, damage, rewards, collision/order and RNG against the rebuilt reference. Short replay equality is evidence, not completion of this gate. +2. **Complete game:** verify all 27 waves and four difficulties, equipment, training/campaign progression, cinematics, demos, menus and legacy imports. +3. **Modding release:** finish lifecycle/error/save acceptance and stabilize API version 1. +4. **Visual completion and cutover:** approve complete sprite sequences, check palette/layer/clipping/seam fidelity at 1080p and measure display performance. Make Rust the default only after preceding gates pass. -1. Extra mission packs authored as new cataloged assets in the original - formats. -2. QoL patches kept as documented diffs against upstream (see - [docs/upstream-patches.md](docs/upstream-patches.md)): resolution options, - audio device selection, keybind config surface. Landed so far: decoupled - interpolated rendering (presentation at display rate, simulation at the - original 70/3 Hz), borderless window mode (`Video/borderless`), removal - of menu cursor snapping. -3. Track upstream (skynettx/raptor) and rebase the documented diffs. +Not all gates have passed. See [validation instructions](docs/rust-rewrite.md) and [HD coverage](docs/hd-art.md). Online mod distribution, an editor, total conversions, external MIDI/SoundFonts and additional desktop targets remain outside scope. -## Legal +## New content -- `raptor/` is GPLv2+; this project inherits GPL for anything built on it. -- `data/` is derived from the user's own purchased copy (copyrighted); - it is gitignored and never committed. +Separate agents are building Iron Coast mission 1, three individual weapon mods and three individual enemy mods using the public API. Each package will ship local SD/HD artwork and procedurally generated sound effects, with definitions, scripts, images and sounds tracked together in Git. These packages remain in development until validation and play tests pass. diff --git a/README.md b/README.md new file mode 100644 index 00000000..fb6f2582 --- /dev/null +++ b/README.md @@ -0,0 +1,21 @@ +# RaptorReplica + +A Linux replica of Raptor: Call of the Shadows, with the retained C++ engine and an independent Rust engine under development. + +```sh +./play.sh --engine rust +./play.sh --engine legacy +``` + +The C++ engine remains the launcher default while Rust gameplay parity and full-game acceptance are verified. Rust includes SDL2 input, interpolated indexed rendering, audio, all 27 original mission definitions, deterministic simulation, pilot slots, separate saves, cinematics, an in-game mod manager, bounded Rhai scripting, crisp sprite filters and an optional HD artwork setting. + +The local HD proof replaces one player frame; other frames use original artwork. It is not a complete remaster. Longer reference replays, full campaign playthroughs and presentation fidelity remain in validation. + +- [Building and running](docs/building.md) +- [Rust implementation and validation](docs/rust-rewrite.md) +- [Mod API and schemas](docs/modding-api.md) +- [Optional HD artwork](docs/hd-art.md) +- [Asset extraction](docs/asset-pipeline.md) +- [Milestones](PLAN.md) + +Code is GPL-2.0-or-later; the vendored Rust FM emulator is LGPL-2.1-or-later. Original game catalog assets, local HD remaster proofs, builds, caches and recordings stay outside Git. Authored mod SD/HD images and sounds are included in Git. Supply your own licensed data in `data/`. diff --git a/build.rs b/build.rs new file mode 100644 index 00000000..093629ca --- /dev/null +++ b/build.rs @@ -0,0 +1,9 @@ +fn main() { + println!("cargo:rerun-if-env-changed=HOME"); + if let Ok(home) = std::env::var("HOME") { + let local = std::path::Path::new(&home).join(".local/lib"); + if local.join("libSDL2.so").exists() { + println!("cargo:rustc-link-search=native={}", local.display()); + } + } +} diff --git a/docs/README.md b/docs/README.md index cbab7e6a..f980602c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,5 +1,10 @@ # RaptorReplica +The retained C++ engine described below is the playable reference. An independent +Rust rewrite is now selectable with `./play.sh --engine rust`; see +[Rust implementation and validation](rust-rewrite.md), [modding API](modding-api.md) +and [optional HD art](hd-art.md). Full Rust cutover acceptance remains in progress. + A faithful, playable replica of **Raptor: Call of the Shadows** (Cygnus Studios, 1994) running the reconstructed original engine on Linux, with the original game data extracted into a modern, editable asset tree. diff --git a/docs/building.md b/docs/building.md index c616bf4f..7035cb45 100644 --- a/docs/building.md +++ b/docs/building.md @@ -1,5 +1,11 @@ # Building and running +For the independent Rust engine, use `./play.sh --engine rust`. Rust 1.88+, +Cargo and SDL2 development libraries are required. The launcher builds in release +mode and sets the local SDL2 library path. See [Rust build/test commands and +separate profile locations](rust-rewrite.md). The sections below describe the +retained C++ engine; its launcher now rebuilds the target before each launch. + ## Requirements - Linux with X11 (developed and verified on Arch, Cinnamon) diff --git a/docs/hd-art.md b/docs/hd-art.md new file mode 100644 index 00000000..b9303579 --- /dev/null +++ b/docs/hd-art.md @@ -0,0 +1,62 @@ +# Optional HD artwork + +The Rust Options screen includes **HD art**. It starts disabled. Enable it to use reviewed artwork from `data/hd/hd.json`; each missing or rejected frame keeps the selected original / 2x / 3x / 4x crisp treatment. The scale setting still determines the indexed rendering resolution, and the HD toggle can be changed while paused. HD art is presentation only: simulation, collision sizes, banking positions and save content IDs stay unchanged. + +The current local proof covers **the light player ship's straight banking frame only** (`0x1011d`, frame 3 of 7). The other six frames, the dark-sector ship, enemies, projectiles and terrain retain original art. Switching into a bank therefore changes visual style. This proof is suitable for evaluating the look; it is not a finished remaster. Original and generated game pixels are excluded from Git. + +The source was decoded with `tools/hd_art_source.py`, inspected, and passed to the **built-in image_gen tool** using the imagegen skill. The optional proof and its exact generation prompt are saved locally at: + +- `data/hd/light-player-straight-hd-v1.png` +- `data/hd/prompts/light-player-straight-v1.txt` +- `data/hd/provenance.json` +- `data/hd/source/light-player-straight.png` + +The PNG has real alpha transparency, is 1254x1254, and was copied unchanged from the tool's output. At the original 32x32 logical resolution, its visible alpha footprint overlaps the source by 92.1% intersection-over-union; its bounds are `(3,0)..(29,31)` against `(2,0)..(29,31)` for the original. The nose, wing layout, silver/gunmetal body and dark red accents remain recognizable, but panel detail and some contours differ. Further artistic review and a complete, consistent banking sequence are required before enabling HD art by default. An additional extreme-bank attempt is saved as `data/hd/light-player-bank-0-hd-v1.png` with `prompts/light-player-bank-0-v1.txt`, but is excluded from the active pack because its footprint overlap is only 62.2% and its engine ends are shortened. The original extreme-bank sprite continues to render. + +## Pack format + +The following is metadata only; artwork belongs in a separately distributed local pack. Decimal IDs are shown alongside their hexadecimal meaning. + +```json +{ + "format_version": 1, + "name": "Source-aligned HD artwork", + "description": "Optional artwork; original fallback for uncovered frames", + "sequences": [ + { + "name": "Light player banking", + "base_asset": 65818, + "frame_count": 7, + "frames": [ + { + "frame": 3, + "file": "light-player-straight-hd-v1.png", + "logical_width": 32, + "logical_height": 32, + "origin": [0, 0], + "source_sha256": "SHA-256 of the exact original 0x1011d catalog payload" + } + ] + } + ] +} +``` + +`base_asset` is `0x1011a`; the supplied frame targets `base_asset + frame`, so frames never depend on filenames or glob ordering. `frame_count` declares the whole original animation sequence and `frames` explicitly declares replacement coverage. An optional `crop: [x,y,width,height]` selects a rectangle from a PNG atlas. + +Version 1 requires exact original logical canvas dimensions and the original top-left anchor `[0,0]`. Canvas alignment is retained even when transparent margins surround the visible image. The PNG or crop must have the same aspect ratio as the original canvas and at least twice its logical resolution. The source hash prevents artwork silently matching a changed original asset. Duplicate IDs, invalid sequence metadata, bad paths, crop bounds, missing transparency and unreasonable image allocations are rejected. Paths must remain inside the pack directory, including after symlink resolution. Open **D: details** from the main menu to inspect rejected frames and coverage. + +HD frames are resampled directly to the selected presentation canvas and quantized to the game palette. They bypass ScaleNx filtering, preserve transparent pixels and use the normal layer order. Indexed output allows palette effects to apply consistently; subtle RGB shades and alpha edges are reduced by the original palette and binary sprite transparency. Terrain is currently composed at original resolution before its joined ScaleNx pass; use crisp terrain until a dedicated HD terrain composition path is validated. + +## Source and sequence review + +Use the existing catalog decoder to prepare a transparent reference without redrawing it: + +```sh +python3 tools/hd_art_source.py --asset 1011d \ + --output data/hd/source/light-player-straight.png --preview-scale 16 +``` + +Inspect every source frame before generating its replacement. Request the same orthographic camera, silhouette, canvas placement, orientation, material colors and lighting for every frame. Preserve the generated alpha. Do not substitute rotations of one frame for the original bank poses: compare the complete sequence at its logical size and at the intended display resolution. Verify that the nose, engine exits, wing extremes and animation pivots remain aligned and that no clipping or background halos appear. + +Keep image-generation prompts and provenance alongside the artwork. Never overwrite original catalog assets. The loader deliberately accepts partial coverage so a reviewed sprite can be previewed before the complete pack is ready, while preserving per-frame fallback. diff --git a/docs/modding-api.md b/docs/modding-api.md new file mode 100644 index 00000000..aaa14ac3 --- /dev/null +++ b/docs/modding-api.md @@ -0,0 +1,194 @@ +# Rust modding API, version 1 + +This is an experimental API for the Rust engine. It provides local content packages, deterministic Rhai callbacks, checked commands, an in-game manager and save compatibility checks. The rewrite is still undergoing gameplay parity work; this document describes the implemented API, not a claim that the full remaster has passed its acceptance checks. API compatibility is currently exact: `api_version = 1`. + +## Try the example + +`examples/mods/aurora/` adds two projectiles, a pulse cannon, a repair cell, two enemies, a mission and a campaign. The weapon adds angled shots in Rhai; enemy movement, item rewards and mission objectives also use scripts. Its artwork references asset IDs in the locally extracted original catalog. The example contains no original or generated game artwork. + +Validate the package against your original game data: + +```sh +cargo run --no-default-features -- --data data --mods examples/mods --validate-mods aurora +``` + +Run its mission without a window: + +```sh +cargo run --no-default-features -- --data data --mods examples/mods \ + --enabled aurora --headless aurora:field_trials --ticks 700 +``` + +For the in-game manager, copy `examples/mods/aurora` into the `mods/` directory under `$XDG_DATA_HOME/RaptorReplica` (default `~/.local/share/RaptorReplica/mods/`), or start the Rust engine with `--mods examples/mods`. Open **Mods**, toggle Aurora, then select **Apply selections**. Select its mission from the mission menu. Mods alter the active content set; existing pilots retain the exact mod versions and hashes required by their saves. Use a separate new pilot when trying a different set of mods. + +In the Mods screen, Enter toggles a package or activates the selected action. Rescan after editing a package on disk. Load dependencies before dependents; independent packages retain your chosen priority. Later explicit overrides win. Changes made through the pause menu remain pending until the main menu. Candidate registries and scripts are validated before the active set changes. + +## Package layout and manifest + +```text +mods/ + aurora/ + mod.toml + content.json + scripts/ + weapon.rhai + art/ + cannon.png +``` + +```toml +id = "aurora" +name = "Aurora Field Trials" +version = "1.0.0" +api_version = 1 +content = "content.json" +scripts = ["scripts/weapon.rhai"] +description = "A new weapon and mission." +conflicts = ["alternate_aurora"] + +[dependencies] +common_tools = "^1.2" +``` + +IDs use lowercase ASCII letters, digits, `_` and `-`, with a maximum of 64 bytes. `base` is reserved. Package versions and dependency requirements use semantic version syntax. Dependencies must be explicitly enabled; the loader will not quietly enable or install them. Cycles, missing packages, unsupported API versions, incompatible dependency versions and declared conflicts reject activation. Two installed folders claiming the same ID make that ID unusable; rename or remove one folder, then rescan. + +All package paths are relative. Absolute paths, parent traversal, symlinks and special files are rejected. Packages are limited to 10,000 files, 16 directory levels, 64 MiB per file and 256 MiB in total. Manifests are limited to 64 KiB; display names to 128 bytes; descriptions to 4 KiB; script declarations to 64, with a 1 MiB limit per source file. Every file, including artwork and documentation, contributes to the package SHA-256 hash. A package changed after discovery requires rescanning before it can be applied. + +## Content definitions and overrides + +`content.json` has optional `weapons`, `items`, `enemies`, `missions`, `campaigns`, `sounds` and `overrides` arrays. Unknown fields are rejected. IDs have the form `namespace:name`, for example `aurora:pulse_cannon`. IDs are stable save references and unique across content types. Keep item and projectile IDs distinct: the item `aurora:pulse_cannon` refers to the weapon/projectile `aurora:pulse_projectile` through its `weapon` property. + +New definitions must belong to the package namespace. An existing definition may be replaced only when its ID appears in `overrides` and the replacement retains the same content type. Overrides are complete replacements, not field merges. An override targeting a missing ID, a replacement without explicit permission, an override without its replacement, or duplicate IDs within a pack rejects the whole pack. The manager exposes the override history and its winning owner. + +```json +{ + "overrides": ["base:projectile_forward_guns"], + "weapons": [{ + "id": "base:projectile_forward_guns", + "name": "Modified Forward Guns", + "damage": 2, + "speed": 8, + "cooldown": 2, + "behavior": "straight", + "target": "air", + "offsets": [[-8, 0], [8, 0]] + }] +} +``` + +`legacy` fields exist to map original numeric definitions into the base registries. New mods should omit them: they select legacy engine behavior and are not a general scripting extension mechanism. + +| Definition | Properties and behavior | +| --- | --- | +| Weapon/projectile | Damage, integer speed, cooldown in simulation ticks, targeting (`air`, `ground`, `all`), behavior (`straight`, `homing`, `beam`, `spread`, `bomb`, `energy_grab`), firing offsets, optional animation and script. Scripts can emit additional projectiles with explicit velocity. | +| Item | Price, maximum and initial count, optional weapon, shield/credit effects, consumable/special flags, artwork and script. `initial_count` controls how many units a purchase or pickup adds. | +| Enemy | Health, speed, rewards, air/ground and boss flags, firing cooldown, path points and repeat flag, weapon, dropped item, animation and script. Scripts can query entities and change enemy movement. | +| Mission | Duration, `auto_complete` (default true), optional briefing artwork, ordered tick-based spawns, terrain tile definitions and row-major layout, column count, next mission, optional music asset and script. Scripts can manage objectives, spawn waves and decide success/failure. | +| Campaign | Name, optional menu artwork and ordered mission IDs. Missions and campaigns appear through the same registries as original content. | + +Simulation uses integer coordinates in the original 320×200 logical canvas and runs at 70/3 Hz: one tick is 3/70 seconds. Artwork detail does not enlarge collision boxes. Script movement and projectile speed are bounded to 128 logical pixels per tick; spawn and movement coordinates must stay within ±32,768. + +JSON Schemas are checked into `schemas/`: `mod-v1.json`, `content-v1.json`, `hook-v1.json`, `weapon-projectile-v1.json`, `item-v1.json`, `enemy-v1.json`, `mission-v1.json` and `campaign-v1.json` and `sound-v1.json`. Schemas describe serialization shape; the validation CLI also checks references, numeric limits, package paths, dependencies, artwork and script compilation. Generate them from the Rust types with: + +```sh +cargo run --no-default-features -- --schemas schemas +``` + +## Artwork + +An `art` object requires exactly one of `asset` (an original numeric catalog ID) or `png` (a package-relative PNG path), plus `logical_width` and `logical_height`. `frames` defaults to 1. `nearest = true` opts that artwork out of Scale2x/3x/4x filtering. + +```json +{ + "png": "art/cannon.png", + "logical_width": 16, + "logical_height": 16, + "frames": 4 +} +``` + +PNG animations are horizontal strips of equally sized frames. For example, four 64×64 frames use a 256×64 PNG and may declare logical dimensions of 16×16. The strip width must divide evenly by `frames`; supply consistent canvases and alignment across frames. Alpha below 128 is transparent. Opaque colors are mapped to the selected game palette so palette effects remain compatible. Artwork already detailed enough for the selected rendering scale bypasses automatic sprite enlargement. Original asset animations use consecutive catalog IDs. Terrain artwork and destroyed terrain replacements follow the same format. + +Artwork dimensions and decoding allocation are bounded. PNGs may be up to 4096 pixels in either direction, with at most 4,194,304 pixels and a 64 MiB decoding allocation limit. Logical dimensions are separately validated and stay independent of physical PNG resolution. The extracted original catalog and local base-game remaster proofs stay outside version control; authored mod artwork and sounds are included in Git. + +## Rhai callbacks + +Every callback takes `(event, state, random)` and returns a map containing `commands` and `state`. All scripts referenced by definitions must appear in `manifest.scripts`. A missing optional callback does nothing; a declared callback with the wrong parameter count is rejected during compilation. + +```javascript +fn on_fire(event, state, random) { + let shots = if state.contains("shots") { state.shots + 1 } else { 1 }; + #{ + commands: [#{ + op: "projectile", + weapon: "aurora:pulse_projectile", + x: event.x, + y: event.y, + vx: (random[0] % 3) - 1, + vy: -8 + }], + state: #{ shots: shots } + } +} +``` + +| Callback | Definition and event fields | +| --- | --- | +| `on_spawn` | Enemy: `entity`, `x`, `y`. | +| `on_tick` | Enemy: `entity`, `x`, `y`, `health`, `tick`, `player_x`, `player_y`. Mission: `tick`, `player_x`, `player_y`. | +| `on_fire` | Weapon or firing enemy: `entity`, `x`, `y`, `hostile`, `tick`; enemy callbacks also include `weapon`. Player entity is zero. The normal shot has already been emitted. Enemy callbacks run for each emitted gun shot. | +| `on_hit` | Weapon/projectile and damaged enemy: `entity`, `projectile`, `damage`, `x`, `y`; enemy events also include `weapon` and remaining `health`. Scripted enemy damage uses `scripted = true` and omits projectile-specific fields. | +| `on_death` | Enemy: `entity`, `x`, `y`. The entity is retired; use queries to act on surviving entities. | +| `on_pickup` | Item: pickup `entity`. The item and its standard effects have already been awarded. | +| `on_use` | Selected special item without a weapon: player `entity = 0`, `x`, `y`, `tick`. Triggered on the rising edge of special input; standard effects and consumption happen first. | +| `on_mission_start` | Mission: `tick = 0`. Runs when the first simulation step dispatches events. | +| `on_mission_end` | Mission: `success`, `tick`. | + +Every dispatched event also includes `tick`, `player`, `entities`, `projectiles`, `pickups` and `objectives`. `player` is a snapshot including position, velocity, shields, credits, inventory and selected equipment. `entities` is the current enemy array; each entry includes `entity`, `definition`, position, health, animation and movement state. Projectiles and pickups likewise carry stable entity IDs. These are read-only snapshots: return commands to change the simulation. Later callbacks in a tick can observe commands committed by earlier callbacks. Events raised by commands, such as a spawned enemy, are dispatched on the following tick. + +`state` is JSON-serializable and shared by all callbacks in the same script file. It starts as an empty map, is keyed by `mod_id/script_path`, and is saved with the pilot. Avoid values dependent on wall time, filesystem access or rendering rate. `random` contains 32 deterministic nonnegative integers in the range 0–32,767. Each successful callback advances that script's saved RNG by exactly 32 values, whether or not the script reads them. Missing callbacks do not advance state or RNG. + +Commands apply only after a callback returns and passes validation. If a callback or any command fails, the complete simulation tick restores its previous world, script state and script RNG. Runtime errors identify the mod, source file, callback and Rhai source location when available. In the desktop engine a script failure returns to the pause screen with the error; fix the package, rescan and reload at the main menu. + +## Commands + +Use the `op` field shown below. All fields listed are required unless stated otherwise. Entity zero identifies the player for damage; movement commands currently address enemies. + +| `op` | Fields | Effect | +| --- | --- | --- | +| `spawn` | `enemy`, `x`, `y` | Spawn a registered enemy. | +| `projectile` | `weapon`, `x`, `y`, `vx`, `vy`, optional `hostile` (false) | Spawn a projectile using a registered weapon. | +| `damage` | `entity`, `amount` | Deal 0–100,000 damage to the player or an existing enemy. | +| `despawn` | `entity` | Remove an existing enemy or projectile. | +| `move` | `entity`, `x`, `y` | Move an enemy and rebase its movement path. | +| `velocity` | `entity`, `vx`, `vy` | Set enemy velocity. | +| `give_item` | `item`, `count` | Add registered inventory, clamped to item capacity; adding a new entry beyond the 20-item limit fails. | +| `consume_item` | `item`, `count` | Remove owned inventory; insufficient quantity fails. | +| `credits` | signed `amount` | Adjust credits with saturation at valid limits. | +| `shield` | signed `amount` | Adjust ordinary shield, clamped to 0–100. | +| `effect` | `x`, `y` | Add an explosion effect. | +| `sound` | numeric `asset` | Queue an original digital sound asset for playback. | +| `play_sound` | namespaced `sound` ID | Queue a validated package-local sound. | +| `objective` | `key`, integer `value` | Set an objective counter. Use a namespaced key. | +| `complete` | none | Complete the mission. | +| `fail` | none | Fail the mission. | + +Rhai uses an explicit package allowlist for arithmetic, strings, collections, iteration and function helpers. The default language/time packages are excluded, so wall-clock timestamps and native `sleep` cannot be reached, including through function pointers. There are no exposed filesystem, network or OS interfaces. Dynamic `eval` and imports are disabled. Limits are 100,000 operations per callback and a shared 500,000-operation budget per simulation tick; 32 call levels; expression depths of 64/32; arrays of 4,096 entries; maps of 1,024 entries; strings of 16 KiB; 256 commands per callback; and 64 KiB of serialized state per script. See the [Rhai execution-limit API](https://docs.rs/rhai/latest/rhai/struct.Engine.html) for the underlying engine controls. Scripts cannot increase these limits. + +## Saves and compatibility + +Rust pilots use separate, versioned JSON files under `$XDG_DATA_HOME/RaptorReplica`, and settings use TOML under `$XDG_CONFIG_HOME/RaptorReplica`. Atomic writes replace completed saves after file and directory synchronization. Legacy saves are read and imported; their original bytes are not modified. + +Each pilot records the ordered mod IDs, package versions, full content hashes, script states and script RNG positions. Loading requires the same active pins and all referenced equipment, missions and progression. Changing a package without changing its version still changes its hash and blocks that save. Disabling a mod preserves its saved inventory and progression; it never silently discards them. Restore the matching package/version and load order, or use another pilot. This API does not yet provide mod save migrations. + +## Validation tests + +`cargo test --no-default-features --test modding` uses synthetic definitions and temporary packages. It checks dependency ordering, version/API failures, conflicts, cycles, duplicate namespaces, changed hashes, traversal/symlinks, file/depth limits, explicit override priority, registry rollback, script budgets, command failure rollback, RNG resumption, incompatible saves and example callbacks. These tests do not require the original game assets. The validation CLI above provides local integration coverage against the separately installed asset catalog. + +## SD/HD artwork and local sound effects + +An artwork definition may add `hd_png`, a separate package-relative PNG with the same logical canvas, frame count and aspect ratio as the SD `png` or original `asset`. HD inputs require at least twice the logical resolution. The Options HD toggle selects it; missing variants retain SD artwork. Detailed mod terrain is drawn on the higher-resolution canvas over the joined SD fallback. Authored mod art/audio is included in Git; original catalog references remain excluded. + +`sounds` definitions have `id`, `name`, `file` (relative path) and optional `volume` (0–127, default127), `pan` (0–255, default127), `pitch` (0–255, default128) and `priority` (0–100000, default1). Lower numeric priority wins, matching the original DSP. Play one with `#{op:"play_sound",sound:"your_mod:shot"}`. WAV inputs must be uncompressed PCM8/16, mono/stereo, 8–48kHz, at most30seconds/8MiB. Stereo is mixed to mono and converted to the original unsigned8-bit digital format; channel/pan/pitch/volume use the original mixer. Original DMX patches are also accepted. Invalid/missing audio rejects activation. + +For objective-driven missions set `auto_complete=false` and explicitly return `complete` or `fail`. Scripted endings dispatch `on_mission_end` in the same transaction. Commands can create further hook events, bounded by the shared execution budget and an8192-event tick limit. diff --git a/docs/rust-rewrite.md b/docs/rust-rewrite.md new file mode 100644 index 00000000..c4ba43cb --- /dev/null +++ b/docs/rust-rewrite.md @@ -0,0 +1,85 @@ +# Rust engine and validation + +The Rust binary never calls or embeds the C++ engine. SDL2 provides window/input/controller/audio services. Simulation and the validation CLI build without SDL2. The C++ checkout stays available for controlled reference comparisons and normal play until full acceptance passes. + +| Module | Responsibility | +| --- | --- | +| assets | Checked catalog, palettes, raw/span pictures, libraries, maps and demo records. | +| content, legacy_tables | Typed registries and generated original numeric mappings. | +| simulation | Rational clock, integer motion, shared RNG, collision/weapon/enemy/terrain rules, script transactions. | +| render, hd | Indexed canvas, ScaleNx, caches, PNG/palette conversion and optional source-hashed HD art. | +| audio, sound | Original MUS/GENMIDI FM and digital DSP behavior; package-local PCM WAV decoding. | +| cinematics | Checked AGX delta frames and movie timing. | +| persistence | TOML settings, versioned JSON pilots, atomic writes and read-only legacy import. | +| modding | Packages, dependency ordering, overrides, bounded Rhai callbacks/state and save pins. | +| desktop | SDL2 services, UI, shop/equipment, mod manager, settings and interpolation. | + +## Build and run + +Rust 1.88+, Cargo and SDL2 development libraries are required. A local SDL2 installation in `~/.local/lib` is supported. The launcher sets the library path and uses a release build: + +```sh +./play.sh --engine rust +./play.sh --engine rust --mods examples/mods +``` + +For development and tests: + +```sh +export LD_LIBRARY_PATH="$HOME/.local/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +cargo test --locked +cargo test --locked --no-default-features +RAPTOR_TEST_DATA="$PWD/data" cargo test --locked +RAPTOR_TEST_DATA="$PWD/data" cargo test --locked -- --ignored +``` + +Synthetic fixtures contain no copyrighted or generated game pixels. Original integration checks are opt-in and local. Native audio comparisons compile a small retained-source harness with g++ and SDL2 headers; pure Rust playback itself uses no C++ runtime. + +## Profiles and settings + +Rust uses `$XDG_DATA_HOME/RaptorReplica/pilot-NNNN.json` and `mods/`, `$XDG_CONFIG_HOME/RaptorReplica/config.toml`, and `$XDG_CACHE_HOME/RaptorReplica/` for derived assets. Normal XDG defaults apply. Pilots record active package versions/hashes and script state/RNG. Missing or changed requirements block loading, without deleting equipment or replacing the save. + +Legacy `~/.local/share/Raptor/SETUP.INI` and pilot files are imported read-only. All difficulties, waves, portrait and training metadata are retained. Rust writes only its separate versioned files. Explicit CLI import output cannot be the original file. + +Options include scaling, scanlines, aspect correction, fullscreen/borderless, input bindings/controller, volumes and optional HD art. New/load pilot controls keep incompatible save slots separate. The Mods screen applies validated selections at the main menu; selections made during flight remain pending until returning there. + +## Local asset and platform checks + +```sh +cargo run --locked --no-default-features -- --data data --verify-assets +cargo run --locked --no-default-features -- --data data --mods examples/mods --validate-mods aurora +cargo run --locked --no-default-features -- --data data --mods examples/mods \ + --enabled aurora --headless aurora:field_trials --ticks 700 +SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy cargo run --locked -- \ + --data data --profile-root .reference/smoke --smoke-frames 5 \ + --screenshot .reference/menu.png +``` + +Use real SDL video for interactive/display-performance checks. Dummy screenshots verify raster placement, not GPU/vsync performance. `--preview-mission ID` starts a mission; `--preview-cinematic intro|landing|death|end1|end2|end3` previews movies. Frame-limited runs do not save pilots/settings; cache stays within the selected profile. + +## Controlled reference replays + +Rebuild the current C++ source before recording. Trace output is opt-in during legacy demo playback and records complete updates after palette/stat processing, which also consumes the shared RNG. + +```sh +mkdir -p .reference +cmake --build raptor/build --target raptor --parallel 8 +(cd data && env SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \ + XDG_DATA_HOME="$PWD/../.reference/legacy-profile" \ + RAPTOR_REFERENCE_TRACE="$PWD/../.reference/cpp-demo.jsonl" \ + RAPTOR_REFERENCE_TICKS=1000 \ + ../raptor/build/bin/raptor PLAY "$PWD/demos/DEMO1G1_REC") +cargo run --locked --no-default-features -- --data data \ + --replay DEMO1G1_REC --ticks 1000 --trace .reference/rust-demo.jsonl +python3 tools/compare_replays.py .reference/cpp-demo.jsonl .reference/rust-demo.jsonl +``` + +The first 1,000 steps of DEMO1G1_REC have matched all captured fields: RNG, player coordinates/bank/shields/credits, ordered enemy position/health/animation/path state and ordered projectile assets/positions. The comparator fails at first divergence or unequal lengths. This is a subset of full state: add inventory, effects, objectives and all internal AI state before declaring complete parity. That demo starts sector 1 wave 3, so it does not validate the first mission or every campaign. Recordings stay ignored in `.reference/`. + +## Audio and remaining acceptance + +The Rust FM/DSP implementation has synthetic sample-by-sample native comparisons and a four-second original intro-music comparison at 44.1kHz. These establish those cases, not every track/input/output rate. The Rust core retains the original envelope/noise semantics and LGPL source provenance. + +Longer replays, all campaign/difficulty paths and end-to-end boss playthroughs still require verification. Original cinematics decode/play locally but exact fade/transition/custom-palette fidelity needs comparison. Some menu layouts differ. HD coverage is partial and display performance must be measured before cutover. + +Scale2x/3x follows the [published algorithm](https://www.scale2x.it/algorithm); Scale4x applies Scale2x twice. WAV parsing follows the [RIFF chunk format](https://learn.microsoft.com/en-us/windows/win32/xaudio2/resource-interchange-file-format--riff-). Original catalog/reference assets remain outside version control. Authored mod artwork and sounds are tracked. diff --git a/examples/mods/aurora/README.md b/examples/mods/aurora/README.md new file mode 100644 index 00000000..b94981d3 --- /dev/null +++ b/examples/mods/aurora/README.md @@ -0,0 +1,15 @@ +# Aurora Field Trials + +This API v1 example adds a scripted pulse cannon, a repair pickup, weaving drones, a guardian, a mission and a campaign. It references the player's installed original sprite catalog; no game artwork is included. + +From the repository root: + +```sh +cargo run --no-default-features -- --mods examples/mods --validate-mods aurora +cargo run --no-default-features -- --mods examples/mods --enabled aurora \ + --headless aurora:field_trials --ticks 700 +``` + +To play, start the Rust engine with `--mods examples/mods`, enable Aurora in **Mods**, apply the selection at the main menu, create a separate pilot and choose **Aurora Field Trials**. The mission equips its cannon on the first simulation step. Keep existing pilots' required mod sets available. + +Content IDs intentionally separate the inventory item `aurora:pulse_cannon` from its projectile `aurora:pulse_projectile`. The scripts demonstrate `on_fire`, `on_hit`, `on_spawn`, `on_tick`, `on_death`, `on_pickup`, `on_use`, `on_mission_start` and `on_mission_end`. See `docs/modding-api.md` for the complete API and compatibility rules. diff --git a/examples/mods/aurora/content.json b/examples/mods/aurora/content.json new file mode 100644 index 00000000..f3d81674 --- /dev/null +++ b/examples/mods/aurora/content.json @@ -0,0 +1,247 @@ +{ + "weapons": [ + { + "id": "aurora:pulse_projectile", + "name": "Aurora Pulse", + "damage": 3, + "speed": 8, + "cooldown": 9, + "behavior": "straight", + "target": "all", + "offsets": [ + [ + 0, + -4 + ] + ], + "art": { + "asset": 65999, + "logical_width": 8, + "logical_height": 8, + "frames": 2 + }, + "script": "scripts/weapon.rhai" + }, + { + "id": "aurora:drone_projectile", + "name": "Drone Pulse", + "damage": 3, + "speed": 3, + "cooldown": 32, + "behavior": "straight", + "target": "all", + "art": { + "asset": 65999, + "logical_width": 8, + "logical_height": 8, + "frames": 2 + } + } + ], + "items": [ + { + "id": "aurora:pulse_cannon", + "name": "Aurora Pulse Cannon", + "price": 4000, + "max_count": 1, + "weapon": "aurora:pulse_projectile", + "art": { + "asset": 66225, + "logical_width": 16, + "logical_height": 16 + } + }, + { + "id": "aurora:repair_cell", + "name": "Aurora Repair Cell", + "price": 100, + "max_count": 10, + "consumable": true, + "shield": 12, + "art": { + "asset": 66225, + "logical_width": 16, + "logical_height": 16 + }, + "script": "scripts/cell.rhai", + "special": true + } + ], + "enemies": [ + { + "id": "aurora:weaver", + "name": "Aurora Weaver", + "health": 16, + "speed": 2, + "reward": 100, + "cooldown": 32, + "weapon": "aurora:drone_projectile", + "drop": "aurora:repair_cell", + "art": { + "asset": 66296, + "logical_width": 32, + "logical_height": 24 + }, + "script": "scripts/drone.rhai" + }, + { + "id": "aurora:guardian", + "name": "Aurora Guardian", + "health": 160, + "speed": 1, + "reward": 1500, + "boss": true, + "cooldown": 20, + "weapon": "aurora:drone_projectile", + "drop": "aurora:repair_cell", + "path": [ + [ + 0, + 60 + ], + [ + 40, + 60 + ], + [ + -40, + 60 + ] + ], + "repeat": true, + "art": { + "asset": 66310, + "logical_width": 80, + "logical_height": 40 + }, + "script": "scripts/drone.rhai" + } + ], + "missions": [ + { + "id": "aurora:field_trials", + "name": "Aurora Field Trials", + "duration": 650, + "spawns": [ + { + "tick": 30, + "enemy": "aurora:weaver", + "x": 70, + "y": -24 + }, + { + "tick": 60, + "enemy": "aurora:weaver", + "x": 200, + "y": -24 + }, + { + "tick": 110, + "enemy": "aurora:weaver", + "x": 140, + "y": -24 + }, + { + "tick": 150, + "enemy": "aurora:weaver", + "x": 90, + "y": -24 + }, + { + "tick": 180, + "enemy": "aurora:weaver", + "x": 190, + "y": -24 + }, + { + "tick": 230, + "enemy": "aurora:weaver", + "x": 150, + "y": -24 + }, + { + "tick": 300, + "enemy": "aurora:guardian", + "x": 120, + "y": -40 + } + ], + "tiles": [ + { + "art": { + "asset": 66400, + "logical_width": 32, + "logical_height": 32 + } + } + ], + "columns": 9, + "layout": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "script": "scripts/mission.rhai" + } + ], + "campaigns": [ + { + "id": "aurora:trials", + "name": "Aurora Trials", + "missions": [ + "aurora:field_trials" + ] + } + ] +} diff --git a/examples/mods/aurora/mod.toml b/examples/mods/aurora/mod.toml new file mode 100644 index 00000000..458f864a --- /dev/null +++ b/examples/mods/aurora/mod.toml @@ -0,0 +1,7 @@ +id = "aurora" +name = "Aurora Field Trials" +version = "1.0.0" +api_version = 1 +description = "A short mission with a scripted pulse cannon, weaving drones and repair cells. Uses your installed original artwork." +content = "content.json" +scripts = ["scripts/weapon.rhai", "scripts/drone.rhai", "scripts/cell.rhai", "scripts/mission.rhai"] diff --git a/examples/mods/aurora/scripts/cell.rhai b/examples/mods/aurora/scripts/cell.rhai new file mode 100644 index 00000000..f40e08b4 --- /dev/null +++ b/examples/mods/aurora/scripts/cell.rhai @@ -0,0 +1,11 @@ +fn on_pickup(event, state, random) { + let recovered = if state.contains("recovered") { state.recovered + 1 } else { 1 }; + #{ commands: [#{ op: "credits", amount: 25 }], state: #{ recovered: recovered } } +} + +// A selected repair cell can also be consumed with the special-action button. +fn on_use(event, state, random) { + let used = if state.contains("used") { state.used + 1 } else { 1 }; + state.used = used; + #{ commands: [#{ op: "objective", key: "aurora:repairs_used", value: used }], state: state } +} diff --git a/examples/mods/aurora/scripts/drone.rhai b/examples/mods/aurora/scripts/drone.rhai new file mode 100644 index 00000000..cc6195cb --- /dev/null +++ b/examples/mods/aurora/scripts/drone.rhai @@ -0,0 +1,16 @@ +fn on_spawn(event, state, random) { + #{ commands: [], state: state } +} + +fn on_tick(event, state, random) { + // on_tick may be queued on the same step as on_death; do not command a retired entity. + if event.health <= 0 { return #{ commands: [], state: state }; } + let sideways = if (event.tick / 24) % 2 == 0 { 1 } else { -1 }; + #{ commands: [#{ op: "velocity", entity: event.entity, vx: sideways, vy: 1 }], state: state } +} + +fn on_death(event, state, random) { + let destroyed = if state.contains("destroyed") { state.destroyed + 1 } else { 1 }; + #{ commands: [#{ op: "objective", key: "aurora:destroyed", value: destroyed }], + state: #{ destroyed: destroyed } } +} diff --git a/examples/mods/aurora/scripts/mission.rhai b/examples/mods/aurora/scripts/mission.rhai new file mode 100644 index 00000000..3ed3b06e --- /dev/null +++ b/examples/mods/aurora/scripts/mission.rhai @@ -0,0 +1,10 @@ +fn on_mission_start(event, state, random) { + #{ commands: [ + #{ op: "give_item", item: "aurora:pulse_cannon", count: 1 }, + #{ op: "objective", key: "aurora:destroyed", value: 0 } + ], state: state } +} + +fn on_mission_end(event, state, random) { + #{ commands: [#{ op: "objective", key: "aurora:trial_finished", value: 1 }], state: state } +} diff --git a/examples/mods/aurora/scripts/weapon.rhai b/examples/mods/aurora/scripts/weapon.rhai new file mode 100644 index 00000000..dad5cba7 --- /dev/null +++ b/examples/mods/aurora/scripts/weapon.rhai @@ -0,0 +1,13 @@ +// The normal centre projectile is emitted by the engine. Add two angled pulses. +fn on_fire(event, state, random) { + let shots = if state.contains("shots") { state.shots + 1 } else { 1 }; + let spread = 1 + random[0] % 2; + #{ commands: [ + #{ op: "projectile", weapon: "aurora:pulse_projectile", x: event.x - 6, y: event.y, vx: -spread, vy: -8 }, + #{ op: "projectile", weapon: "aurora:pulse_projectile", x: event.x + 6, y: event.y, vx: spread, vy: -8 } + ], state: #{ shots: shots } } +} + +fn on_hit(event, state, random) { + #{ commands: [#{ op: "effect", x: event.x, y: event.y }], state: state } +} diff --git a/play.sh b/play.sh index a3ffb0e9..f35fa821 100755 --- a/play.sh +++ b/play.sh @@ -1,31 +1,34 @@ #!/bin/sh -# Launch Raptor: Call of the Shadows (original engine + extracted data). -# -# Layout: -# data/ asset tree the engine loads: INDEX catalog plus -# music/, sprites/, ... (see docs/asset-pipeline.md) -# raptor/build/bin/ built engine -# -# The engine resolves the catalog and assets relative to its working -# directory, so we run it from data/. Saves and SETUP.INI go to -# ~/.local/share/Raptor (SDL pref path) — nothing is written into the repo. -set -e +# Keep the reference engine as the default until Rust parity is validated. +set -eu cd "$(dirname "$0")" ROOT="$PWD" - -if [ ! -f data/INDEX ]; then - echo "Missing data/INDEX — restore the data/ asset tree" >&2 - echo " (see docs/asset-pipeline.md and tools/glbextract.py)" >&2 - exit 1 +ENGINE=legacy +if [ "${1:-}" = --engine ]; then + [ "$#" -ge 2 ] || { echo 'Usage: ./play.sh --engine legacy|rust [arguments]' >&2; exit 2; } + ENGINE="$2" + shift 2 fi - -BIN=raptor/build/bin/raptor -if [ ! -x "$BIN" ]; then - echo "Building raptor (first run)..." >&2 - cmake -E make_directory raptor/build - ( cd raptor/build && cmake .. -DCMAKE_BUILD_TYPE=Release ${CMAKE_PREFIX_PATH:+-DCMAKE_PREFIX_PATH=$CMAKE_PREFIX_PATH} && make -j"$(nproc)" ) -fi - export LD_LIBRARY_PATH="${LD_LIBRARY_PATH:+$LD_LIBRARY_PATH:}$HOME/.local/lib" -cd data -exec "$ROOT/$BIN" +case "$ENGINE" in + rust) + exec cargo run --locked --release --manifest-path "$ROOT/Cargo.toml" --bin raptor-rust -- --data "$ROOT/data" "$@" + ;; + legacy) + if [ ! -f data/INDEX ]; then + echo 'Missing data/INDEX; see docs/asset-pipeline.md' >&2 + exit 1 + fi + CMAKE=cmake + if ! command -v cmake >/dev/null 2>&1; then + CMAKE="$HOME/.local/opt/cmake/bin/cmake" + fi + if [ ! -x raptor/build/bin/raptor ]; then + "$CMAKE" -S raptor -B raptor/build -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$HOME/.local${CMAKE_PREFIX_PATH:+;$CMAKE_PREFIX_PATH}" + fi + "$CMAKE" --build raptor/build --target raptor --parallel "$(nproc)" + cd data + exec "$ROOT/raptor/build/bin/raptor" "$@" + ;; + *) echo "Unknown engine: $ENGINE (choose legacy or rust)" >&2; exit 2 ;; +esac diff --git a/raptor/src/rap.cpp b/raptor/src/rap.cpp index 382981d3..d15fad9f 100644 --- a/raptor/src/rap.cpp +++ b/raptor/src/rap.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include "SDL.h" #include "common.h" #include "glbapi.h" @@ -52,9 +53,19 @@ struct bday_t { int wRandSeed = 1; -int wrand(void) +__attribute__((noinline)) int wrand(void) { wRandSeed = ((long long)wRandSeed * 1103515245) + 12345; + static const bool trace_rng = getenv("RAPTOR_REFERENCE_RNG_TRACE") != NULL; + if (trace_rng && gl_cnt >= 242 && gl_cnt <= 247) + { + void *callers[2]; + const int count = backtrace(callers, 2); + char **symbols = backtrace_symbols(callers, count); + fprintf(stderr, "reference RNG gl_cnt=%d seed=%d caller=%s\n", + gl_cnt, wRandSeed, symbols && count > 1 ? symbols[1] : "unknown"); + free(symbols); + } return (wRandSeed >> 16) & 0x7fff; } @@ -64,6 +75,53 @@ void wsrand(int seed) wRandSeed = seed; } +// Opt-in development trace. Normal game launches never open a trace file. +// Record after the complete simulation update, before rendering/interpolation. +extern SHOTS first_shots, last_shots; +extern ESHOT first_eshot, last_eshot; +static void RAP_ReferenceStep() +{ + const char *path = getenv("RAPTOR_REFERENCE_TRACE"); + if (!path || demo_mode != DEMO_PLAYBACK) + return; + static FILE *trace = NULL; + static int count = 0; + if (!trace) + { + trace = fopen(path, "w"); + if (!trace) + { + perror("reference trace"); + exit(1); + } + } + fprintf(trace, "{\"tick\":%d,\"rng\":%d,\"player\":[%d,%d,%d,%d,%d,%u],\"enemies\":[", + ++count, wRandSeed, playerx, playery, playerpic, + OBJS_GetAmt(S_ENERGY), OBJS_GetAmt(S_SUPER_SHIELD), plr.score); + int comma = 0; + for (SPRITE_SHIP *e = first_enemy.next; e != &last_enemy; e = e->next) + { + fprintf(trace, "%s[%d,%d,%d,%d,%d,%d,%d]", comma++ ? "," : "", + LE_LONG(e->lib->item), e->x, e->y, e->hits, e->curframe, + e->move.x, e->move.y); + } + fprintf(trace, "],\"projectiles\":["); + comma = 0; + for (ESHOT *p = first_eshot.next; p != &last_eshot; p = p->next) + fprintf(trace, "%s[%d,%d,%d,1]", comma++ ? "," : "", p->lib->item, p->x, p->y); + for (SHOTS *p = first_shots.next; p != &last_shots; p = p->next) + fprintf(trace, "%s[%d,%d,%d,0]", comma++ ? "," : "", p->lib->lumpnum, p->x, p->y); + fprintf(trace, "]}\n"); + fflush(trace); + const char *limit = getenv("RAPTOR_REFERENCE_TICKS"); + int ticks = limit ? atoi(limit) : 1000; + if (count >= (ticks > 0 && ticks <= 12000 ? ticks : 1000)) + { + fclose(trace); + exit(0); + } +} + #define MAX_BDAY 6 bday_t bday[MAX_BDAY]; @@ -1125,6 +1183,7 @@ Do_Game( } RAP_ThinkStats(); + RAP_ReferenceStep(); if (startfadeflag) { @@ -1608,7 +1667,7 @@ main( RAP_ClearPlayer(); - if (!godmode) + if (!godmode && !getenv("RAPTOR_REFERENCE_TRACE")) INTRO_Credits(); if (demo_flag != DEMO_PLAYBACK) diff --git a/schemas/campaign-v1.json b/schemas/campaign-v1.json new file mode 100644 index 00000000..cff2a9b0 --- /dev/null +++ b/schemas/campaign-v1.json @@ -0,0 +1,89 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "CampaignDef", + "type": "object", + "required": [ + "id", + "missions", + "name" + ], + "properties": { + "art": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": "string" + }, + "missions": { + "type": "array", + "items": { + "type": "string" + } + }, + "name": { + "type": "string" + } + }, + "additionalProperties": false, + "definitions": { + "Art": { + "type": "object", + "required": [ + "logical_height", + "logical_width" + ], + "properties": { + "asset": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "frames": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "hd_png": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "logical_height": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "logical_width": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "nearest": { + "default": false, + "type": "boolean" + }, + "png": { + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/schemas/content-v1.json b/schemas/content-v1.json new file mode 100644 index 00000000..9014be1a --- /dev/null +++ b/schemas/content-v1.json @@ -0,0 +1,632 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ContentPack", + "type": "object", + "properties": { + "campaigns": { + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/CampaignDef" + } + }, + "enemies": { + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/EnemyDef" + } + }, + "items": { + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/ItemDef" + } + }, + "missions": { + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/MissionDef" + } + }, + "overrides": { + "default": [], + "type": "array", + "items": { + "type": "string" + } + }, + "sounds": { + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/SoundDef" + } + }, + "weapons": { + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/WeaponDef" + } + } + }, + "additionalProperties": false, + "definitions": { + "Art": { + "type": "object", + "required": [ + "logical_height", + "logical_width" + ], + "properties": { + "asset": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "frames": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "hd_png": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "logical_height": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "logical_width": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "nearest": { + "default": false, + "type": "boolean" + }, + "png": { + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + }, + "CampaignDef": { + "type": "object", + "required": [ + "id", + "missions", + "name" + ], + "properties": { + "art": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": "string" + }, + "missions": { + "type": "array", + "items": { + "type": "string" + } + }, + "name": { + "type": "string" + } + }, + "additionalProperties": false + }, + "EnemyDef": { + "type": "object", + "required": [ + "id", + "name" + ], + "properties": { + "art": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "boss": { + "default": false, + "type": "boolean" + }, + "cooldown": { + "default": 10, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "drop": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "ground": { + "default": false, + "type": "boolean" + }, + "health": { + "default": 100, + "type": "integer", + "format": "int32" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "default": [], + "type": "array", + "items": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + }, + "maxItems": 2, + "minItems": 2 + } + }, + "repeat": { + "default": false, + "type": "boolean" + }, + "reward": { + "default": 0, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "script": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "speed": { + "default": 2, + "type": "integer", + "format": "int32" + }, + "weapon": { + "default": null, + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + }, + "ItemDef": { + "type": "object", + "required": [ + "id", + "name", + "price" + ], + "properties": { + "art": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "consumable": { + "default": false, + "type": "boolean" + }, + "credits": { + "default": 0, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "id": { + "type": "string" + }, + "initial_count": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "legacy": { + "default": null, + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "max_count": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "name": { + "type": "string" + }, + "price": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "script": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "shield": { + "default": 0, + "type": "integer", + "format": "int32" + }, + "special": { + "default": false, + "type": "boolean" + }, + "weapon": { + "default": null, + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + }, + "MissionDef": { + "type": "object", + "required": [ + "duration", + "id", + "name" + ], + "properties": { + "art": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "auto_complete": { + "default": true, + "type": "boolean" + }, + "columns": { + "default": 0, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "duration": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "id": { + "type": "string" + }, + "layout": { + "default": [], + "type": "array", + "items": { + "type": "integer", + "format": "uint", + "minimum": 0.0 + } + }, + "legacy_map": { + "default": null, + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "music": { + "default": null, + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "name": { + "type": "string" + }, + "next": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "script": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "spawns": { + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/SpawnDef" + } + }, + "tiles": { + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/TileDef" + } + } + }, + "additionalProperties": false + }, + "SoundDef": { + "type": "object", + "required": [ + "file", + "id", + "name" + ], + "properties": { + "file": { + "type": "string" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "pan": { + "default": 127, + "type": "integer", + "format": "int32" + }, + "pitch": { + "default": 128, + "type": "integer", + "format": "int32" + }, + "priority": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "volume": { + "default": 127, + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + "SpawnDef": { + "type": "object", + "required": [ + "enemy", + "tick", + "x", + "y" + ], + "properties": { + "difficulty": { + "default": 0, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "enemy": { + "type": "string" + }, + "tick": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "x": { + "type": "integer", + "format": "int32" + }, + "y": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + "Target": { + "type": "string", + "enum": [ + "air", + "ground", + "all" + ] + }, + "TileDef": { + "type": "object", + "required": [ + "art" + ], + "properties": { + "art": { + "$ref": "#/definitions/Art" + }, + "destroyed": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "health": { + "default": 0, + "type": "integer", + "format": "int32" + }, + "reward": { + "default": 0, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + } + }, + "additionalProperties": false + }, + "WeaponBehavior": { + "type": "string", + "enum": [ + "straight", + "homing", + "beam", + "spread", + "bomb", + "energy_grab" + ] + }, + "WeaponDef": { + "type": "object", + "required": [ + "behavior", + "cooldown", + "damage", + "id", + "name", + "speed", + "target" + ], + "properties": { + "art": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "behavior": { + "$ref": "#/definitions/WeaponBehavior" + }, + "cooldown": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "damage": { + "type": "integer", + "format": "int32" + }, + "id": { + "type": "string" + }, + "legacy": { + "default": null, + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "name": { + "type": "string" + }, + "offsets": { + "default": [], + "type": "array", + "items": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + }, + "maxItems": 2, + "minItems": 2 + } + }, + "script": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "speed": { + "type": "integer", + "format": "int32" + }, + "target": { + "$ref": "#/definitions/Target" + } + }, + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/schemas/enemy-v1.json b/schemas/enemy-v1.json new file mode 100644 index 00000000..b8007405 --- /dev/null +++ b/schemas/enemy-v1.json @@ -0,0 +1,150 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "EnemyDef", + "type": "object", + "required": [ + "id", + "name" + ], + "properties": { + "art": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "boss": { + "default": false, + "type": "boolean" + }, + "cooldown": { + "default": 10, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "drop": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "ground": { + "default": false, + "type": "boolean" + }, + "health": { + "default": 100, + "type": "integer", + "format": "int32" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "default": [], + "type": "array", + "items": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + }, + "maxItems": 2, + "minItems": 2 + } + }, + "repeat": { + "default": false, + "type": "boolean" + }, + "reward": { + "default": 0, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "script": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "speed": { + "default": 2, + "type": "integer", + "format": "int32" + }, + "weapon": { + "default": null, + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false, + "definitions": { + "Art": { + "type": "object", + "required": [ + "logical_height", + "logical_width" + ], + "properties": { + "asset": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "frames": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "hd_png": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "logical_height": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "logical_width": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "nearest": { + "default": false, + "type": "boolean" + }, + "png": { + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/schemas/hook-v1.json b/schemas/hook-v1.json new file mode 100644 index 00000000..7093f7fe --- /dev/null +++ b/schemas/hook-v1.json @@ -0,0 +1,420 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "HookResult", + "type": "object", + "properties": { + "commands": { + "description": "Transactional commands, applied in order only when the callback succeeds.", + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/Command" + } + }, + "state": { + "description": "JSON-serializable state shared by callbacks in this script; maximum 64 KiB.", + "default": null + } + }, + "additionalProperties": false, + "definitions": { + "Command": { + "oneOf": [ + { + "description": "Add an enemy at an integer position in the original logical canvas.", + "type": "object", + "required": [ + "enemy", + "op", + "x", + "y" + ], + "properties": { + "enemy": { + "type": "string" + }, + "op": { + "type": "string", + "enum": [ + "spawn" + ] + }, + "x": { + "type": "integer", + "format": "int32" + }, + "y": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "op", + "vx", + "vy", + "weapon", + "x", + "y" + ], + "properties": { + "hostile": { + "default": false, + "type": "boolean" + }, + "op": { + "type": "string", + "enum": [ + "projectile" + ] + }, + "vx": { + "type": "integer", + "format": "int32" + }, + "vy": { + "type": "integer", + "format": "int32" + }, + "weapon": { + "type": "string" + }, + "x": { + "type": "integer", + "format": "int32" + }, + "y": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "amount", + "entity", + "op" + ], + "properties": { + "amount": { + "type": "integer", + "format": "int32" + }, + "entity": { + "description": "Enemy entity ID; zero addresses the player.", + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "op": { + "type": "string", + "enum": [ + "damage" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "entity", + "op" + ], + "properties": { + "entity": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "op": { + "type": "string", + "enum": [ + "despawn" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "entity", + "op", + "x", + "y" + ], + "properties": { + "entity": { + "description": "Existing enemy entity ID.", + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "op": { + "type": "string", + "enum": [ + "move" + ] + }, + "x": { + "type": "integer", + "format": "int32" + }, + "y": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "entity", + "op", + "vx", + "vy" + ], + "properties": { + "entity": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "op": { + "type": "string", + "enum": [ + "velocity" + ] + }, + "vx": { + "type": "integer", + "format": "int32" + }, + "vy": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "count", + "item", + "op" + ], + "properties": { + "count": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "item": { + "type": "string" + }, + "op": { + "type": "string", + "enum": [ + "give_item" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "count", + "item", + "op" + ], + "properties": { + "count": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "item": { + "type": "string" + }, + "op": { + "type": "string", + "enum": [ + "consume_item" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "amount", + "op" + ], + "properties": { + "amount": { + "type": "integer", + "format": "int32" + }, + "op": { + "type": "string", + "enum": [ + "credits" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "amount", + "op" + ], + "properties": { + "amount": { + "type": "integer", + "format": "int32" + }, + "op": { + "type": "string", + "enum": [ + "shield" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "op", + "x", + "y" + ], + "properties": { + "op": { + "type": "string", + "enum": [ + "effect" + ] + }, + "x": { + "type": "integer", + "format": "int32" + }, + "y": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "asset", + "op" + ], + "properties": { + "asset": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "op": { + "type": "string", + "enum": [ + "sound" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "op", + "sound" + ], + "properties": { + "op": { + "type": "string", + "enum": [ + "play_sound" + ] + }, + "sound": { + "type": "string" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "key", + "op", + "value" + ], + "properties": { + "key": { + "description": "Stable namespaced objective key, at most 128 bytes.", + "type": "string" + }, + "op": { + "type": "string", + "enum": [ + "objective" + ] + }, + "value": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "op" + ], + "properties": { + "op": { + "type": "string", + "enum": [ + "complete" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "op" + ], + "properties": { + "op": { + "type": "string", + "enum": [ + "fail" + ] + } + }, + "additionalProperties": false + } + ] + } + } +} \ No newline at end of file diff --git a/schemas/item-v1.json b/schemas/item-v1.json new file mode 100644 index 00000000..d254e481 --- /dev/null +++ b/schemas/item-v1.json @@ -0,0 +1,142 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ItemDef", + "type": "object", + "required": [ + "id", + "name", + "price" + ], + "properties": { + "art": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "consumable": { + "default": false, + "type": "boolean" + }, + "credits": { + "default": 0, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "id": { + "type": "string" + }, + "initial_count": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "legacy": { + "default": null, + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "max_count": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "name": { + "type": "string" + }, + "price": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "script": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "shield": { + "default": 0, + "type": "integer", + "format": "int32" + }, + "special": { + "default": false, + "type": "boolean" + }, + "weapon": { + "default": null, + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false, + "definitions": { + "Art": { + "type": "object", + "required": [ + "logical_height", + "logical_width" + ], + "properties": { + "asset": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "frames": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "hd_png": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "logical_height": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "logical_width": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "nearest": { + "default": false, + "type": "boolean" + }, + "png": { + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/schemas/mission-v1.json b/schemas/mission-v1.json new file mode 100644 index 00000000..30e5a047 --- /dev/null +++ b/schemas/mission-v1.json @@ -0,0 +1,221 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "MissionDef", + "type": "object", + "required": [ + "duration", + "id", + "name" + ], + "properties": { + "art": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "auto_complete": { + "default": true, + "type": "boolean" + }, + "columns": { + "default": 0, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "duration": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "id": { + "type": "string" + }, + "layout": { + "default": [], + "type": "array", + "items": { + "type": "integer", + "format": "uint", + "minimum": 0.0 + } + }, + "legacy_map": { + "default": null, + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "music": { + "default": null, + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "name": { + "type": "string" + }, + "next": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "script": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "spawns": { + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/SpawnDef" + } + }, + "tiles": { + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/TileDef" + } + } + }, + "additionalProperties": false, + "definitions": { + "Art": { + "type": "object", + "required": [ + "logical_height", + "logical_width" + ], + "properties": { + "asset": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "frames": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "hd_png": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "logical_height": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "logical_width": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "nearest": { + "default": false, + "type": "boolean" + }, + "png": { + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + }, + "SpawnDef": { + "type": "object", + "required": [ + "enemy", + "tick", + "x", + "y" + ], + "properties": { + "difficulty": { + "default": 0, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "enemy": { + "type": "string" + }, + "tick": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "x": { + "type": "integer", + "format": "int32" + }, + "y": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + "TileDef": { + "type": "object", + "required": [ + "art" + ], + "properties": { + "art": { + "$ref": "#/definitions/Art" + }, + "destroyed": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "health": { + "default": 0, + "type": "integer", + "format": "int32" + }, + "reward": { + "default": 0, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + } + }, + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/schemas/mod-v1.json b/schemas/mod-v1.json new file mode 100644 index 00000000..0b7e89f3 --- /dev/null +++ b/schemas/mod-v1.json @@ -0,0 +1,65 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Manifest", + "type": "object", + "required": [ + "api_version", + "id", + "name", + "version" + ], + "properties": { + "api_version": { + "description": "Exact supported content/script API major version.", + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "conflicts": { + "description": "IDs which cannot be enabled at the same time as this package.", + "default": [], + "type": "array", + "items": { + "type": "string" + } + }, + "content": { + "description": "Relative path to the JSON content pack. Defaults to `content.json`.", + "default": "content.json", + "type": "string" + }, + "dependencies": { + "description": "Required, explicitly enabled mod IDs mapped to semantic version requirements.", + "default": {}, + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "description": { + "default": "", + "type": "string" + }, + "id": { + "description": "Unique lowercase namespace; `base` is reserved for the original game.", + "type": "string" + }, + "name": { + "description": "Display name shown in the in-game manager.", + "type": "string" + }, + "scripts": { + "description": "Relative paths to every Rhai source referenced by this content pack.", + "default": [], + "type": "array", + "items": { + "type": "string" + } + }, + "version": { + "description": "Semantic package version, saved together with a SHA-256 content hash.", + "type": "string" + } + }, + "additionalProperties": false +} \ No newline at end of file diff --git a/schemas/sound-v1.json b/schemas/sound-v1.json new file mode 100644 index 00000000..63e585af --- /dev/null +++ b/schemas/sound-v1.json @@ -0,0 +1,43 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SoundDef", + "type": "object", + "required": [ + "file", + "id", + "name" + ], + "properties": { + "file": { + "type": "string" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "pan": { + "default": 127, + "type": "integer", + "format": "int32" + }, + "pitch": { + "default": 128, + "type": "integer", + "format": "int32" + }, + "priority": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "volume": { + "default": 127, + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false +} \ No newline at end of file diff --git a/schemas/weapon-projectile-v1.json b/schemas/weapon-projectile-v1.json new file mode 100644 index 00000000..355fca0b --- /dev/null +++ b/schemas/weapon-projectile-v1.json @@ -0,0 +1,154 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "WeaponDef", + "type": "object", + "required": [ + "behavior", + "cooldown", + "damage", + "id", + "name", + "speed", + "target" + ], + "properties": { + "art": { + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Art" + }, + { + "type": "null" + } + ] + }, + "behavior": { + "$ref": "#/definitions/WeaponBehavior" + }, + "cooldown": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "damage": { + "type": "integer", + "format": "int32" + }, + "id": { + "type": "string" + }, + "legacy": { + "default": null, + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "name": { + "type": "string" + }, + "offsets": { + "default": [], + "type": "array", + "items": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + }, + "maxItems": 2, + "minItems": 2 + } + }, + "script": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "speed": { + "type": "integer", + "format": "int32" + }, + "target": { + "$ref": "#/definitions/Target" + } + }, + "additionalProperties": false, + "definitions": { + "Art": { + "type": "object", + "required": [ + "logical_height", + "logical_width" + ], + "properties": { + "asset": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0.0 + }, + "frames": { + "default": 1, + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "hd_png": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "logical_height": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "logical_width": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "nearest": { + "default": false, + "type": "boolean" + }, + "png": { + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + }, + "Target": { + "type": "string", + "enum": [ + "air", + "ground", + "all" + ] + }, + "WeaponBehavior": { + "type": "string", + "enum": [ + "straight", + "homing", + "beam", + "spread", + "bomb", + "energy_grab" + ] + } + } +} \ No newline at end of file diff --git a/src/assets.rs b/src/assets.rs new file mode 100644 index 00000000..aad17f04 --- /dev/null +++ b/src/assets.rs @@ -0,0 +1,428 @@ +//! Checked decoders for the loose catalog and the original little-endian assets. +use anyhow::{Context, Result, bail, ensure}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, HashMap}, + fs, + path::{Component, Path, PathBuf}, +}; + +pub const TRANSPARENT: u16 = 256; +#[derive(Debug, Clone)] +pub struct Entry { + pub id: u32, + pub size: usize, + pub path: PathBuf, +} +#[derive(Debug, Clone)] +pub struct Catalog { + pub root: PathBuf, + pub entries: BTreeMap, + names: BTreeMap, +} +pub fn contained(root: &Path, relative: &Path) -> Result { + ensure!( + !relative.is_absolute() + && relative + .components() + .all(|c| matches!(c, Component::Normal(_))), + "asset path must stay inside its root: {}", + relative.display() + ); + let root = root.canonicalize().context("asset root does not exist")?; + let path = root + .join(relative) + .canonicalize() + .with_context(|| format!("missing asset {}", relative.display()))?; + ensure!(path.starts_with(&root), "asset symlink escapes its root"); + Ok(path) +} +impl Catalog { + pub fn open(root: impl AsRef) -> Result { + let root = root.as_ref().to_path_buf(); + let index = fs::read_to_string(root.join("INDEX"))?; + let mut entries = BTreeMap::new(); + let mut names = BTreeMap::new(); + for (line_no, line) in index.lines().enumerate() { + if line.trim().is_empty() { + continue; + } + let fields: Vec<_> = line.split_whitespace().collect(); + ensure!( + fields.len() == 3, + "INDEX line {}: expected id, size, path", + line_no + 1 + ); + let id = u32::from_str_radix(fields[0], 16)?; + let size = fields[1].parse::()?; + ensure!(size <= 64 * 1024 * 1024, "asset exceeds 64 MiB"); + let path = PathBuf::from(fields[2]); + contained(&root, &path)?; + ensure!( + entries + .insert( + id, + Entry { + id, + size, + path: path.clone() + } + ) + .is_none(), + "duplicate asset id {id:x}" + ); + let name = path + .file_name() + .context("missing asset name")? + .to_string_lossy() + .to_ascii_uppercase(); + names.entry(name).or_insert(id); + } + ensure!(!entries.is_empty(), "empty catalog"); + Ok(Self { + root, + entries, + names, + }) + } + pub fn id(&self, name: &str) -> Result { + self.names + .get(&name.to_ascii_uppercase()) + .copied() + .with_context(|| format!("missing asset {name}")) + } + pub fn read(&self, id: u32) -> Result> { + let entry = self + .entries + .get(&id) + .with_context(|| format!("unknown asset {id:x}"))?; + let data = fs::read(contained(&self.root, &entry.path)?)?; + ensure!( + data.len() == entry.size, + "asset {id:x}: INDEX size {} != actual {}", + entry.size, + data.len() + ); + Ok(data) + } + pub fn named(&self, name: &str) -> Result> { + self.read(self.id(name)?) + } + pub fn sprite(&self, id: u32) -> Result { + Sprite::decode(&self.read(id)?).with_context(|| format!("sprite {id:x}")) + } + pub fn verify(&self) -> Result { + for id in self.entries.keys() { + self.read(*id)?; + } + Ok(self.entries.len()) + } + pub fn palette(&self) -> Result<[[u8; 3]; 256]> { + decode_palette(&self.named("PALETTE_DAT")?) + } +} +pub fn i32_at(data: &[u8], off: usize) -> Result { + let end = off.checked_add(4).context("32-bit field offset overflow")?; + Ok(i32::from_le_bytes( + data.get(off..end) + .context("truncated 32-bit field")? + .try_into()?, + )) +} +pub fn i16_at(data: &[u8], off: usize) -> Result { + let end = off.checked_add(2).context("16-bit field offset overflow")?; + Ok(i16::from_le_bytes( + data.get(off..end) + .context("truncated 16-bit field")? + .try_into()?, + )) +} +pub fn decode_palette(data: &[u8]) -> Result<[[u8; 3]; 256]> { + ensure!(data.len() == 768, "palette must contain 768 bytes"); + Ok(std::array::from_fn(|i| { + std::array::from_fn(|j| { + let x = data[i * 3 + j]; + (x.min(63) << 2) | (x.min(63) >> 4) + }) + })) +} +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Sprite { + pub width: usize, + pub height: usize, + pub pixels: Vec, +} +impl Sprite { + pub fn blank(width: usize, height: usize) -> Self { + Self { + width, + height, + pixels: vec![TRANSPARENT; width * height], + } + } + pub fn decode(data: &[u8]) -> Result { + let typ = i32_at(data, 0)?; + let width = i32_at(data, 12)?; + let height = i32_at(data, 16)?; + ensure!( + (1..=4096).contains(&width) + && (1..=4096).contains(&height) + && width as i64 * height as i64 <= 1_048_576, + "invalid sprite dimensions {width}x{height}" + ); + let mut out = Self::blank(width as usize, height as usize); + match typ { + 1 => { + let bytes = data + .get(20..20 + out.pixels.len()) + .context("truncated raw picture")?; + for (dst, src) in out.pixels.iter_mut().zip(bytes) { + *dst = *src as u16; + } + } + 0 => { + let mut off = 20; + let mut runs = 0; + loop { + let x = i32_at(data, off)?; + let y = i32_at(data, off + 4)?; + let dest = i32_at(data, off + 8)?; + let len = i32_at(data, off + 12)?; + off += 16; + if dest == -1 { + break; + } + ensure!( + x >= 0 + && y >= 0 + && len > 0 + && x.checked_add(len).is_some_and(|n| n <= width) + && y < height, + "invalid sprite span" + ); + let bytes = data + .get(off..off + len as usize) + .context("truncated sprite span")?; + let start = y as usize * out.width + x as usize; + for (dst, src) in out.pixels[start..start + len as usize] + .iter_mut() + .zip(bytes) + { + *dst = *src as u16; + } + off += len as usize; + runs += 1; + ensure!(runs <= out.pixels.len(), "too many sprite spans"); + } + } + _ => bail!("unsupported picture type {typ}"), + } + Ok(out) + } + pub fn png(path: &Path, palette: &[[u8; 3]; 256]) -> Result { + let mut reader = image::ImageReader::open(path)?.with_guessed_format()?; + ensure!( + reader.format() == Some(image::ImageFormat::Png), + "mod artwork must be PNG" + ); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(4096); + limits.max_image_height = Some(4096); + limits.max_alloc = Some(64 * 1024 * 1024); + reader.limits(limits); + let image = reader.decode()?.into_rgba8(); + ensure!( + image.width() <= 4096 + && image.height() <= 4096 + && image.width() as u64 * image.height() as u64 <= 4_194_304, + "PNG exceeds 4096px" + ); + let mut out = Self::blank(image.width() as usize, image.height() as usize); + // Palette art repeats colors extensively. Cache by RGB (alpha is handled + // separately) so terrain atlases do not search 256 entries per pixel. + let mut colors = HashMap::<[u8; 3], u16>::new(); + for (dst, p) in out.pixels.iter_mut().zip(image.pixels()) { + if p[3] < 128 { + continue; + } + *dst = *colors.entry([p[0], p[1], p[2]]).or_insert_with(|| { + palette + .iter() + .enumerate() + .min_by_key(|(_, c)| { + (0..3) + .map(|j| (p[j] as i32 - c[j] as i32).pow(2)) + .sum::() + }) + .unwrap() + .0 as u16 + }); + } + Ok(out) + } +} +#[derive(Debug, Clone)] +pub struct LegacyMap { + pub tiles: Vec<(u16, u16)>, + pub spawns: Vec, +} +#[derive(Debug, Clone)] +pub struct LegacySpawn { + pub link: i32, + pub library: usize, + pub x: i32, + pub row: i32, + pub game: usize, + pub difficulty: i32, +} +impl LegacyMap { + pub fn decode(data: &[u8]) -> Result { + let size = i32_at(data, 0)?; + let off = i32_at(data, 4)?; + let count = i32_at(data, 8)?; + ensure!( + size >= 5412 && size as usize == data.len() && off == 5412 && count >= 0, + "invalid map header" + ); + ensure!( + (count as usize) < 65536 && 5412 + count as usize * 24 <= data.len(), + "truncated map spawns" + ); + let mut tiles = Vec::new(); + for i in 0..1350 { + let off = 12 + i * 4; + let flat = i16_at(data, off)?; + let game = i16_at(data, off + 2)?; + ensure!( + flat >= 0 && (0..4).contains(&game), + "invalid tile reference" + ); + tiles.push((flat as u16, game as u16)); + } + let mut spawns = Vec::new(); + for i in 0..count as usize { + let o = 5412 + i * 24; + let lib = i32_at(data, o + 4)?; + let game = i32_at(data, o + 16)?; + ensure!(lib >= 0 && (0..4).contains(&game), "invalid enemy library"); + spawns.push(LegacySpawn { + link: i32_at(data, o)?, + library: lib as usize, + x: i32_at(data, o + 8)?, + row: i32_at(data, o + 12)?, + game: game as usize, + difficulty: i32_at(data, o + 20)?, + }); + } + Ok(Self { tiles, spawns }) + } +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LegacyEnemy { + pub name: String, + pub fields: Vec, + pub shoot_type: Vec, + pub engine_x: Vec, + pub engine_y: Vec, + pub engine_width: Vec, + pub gun_x: Vec, + pub gun_y: Vec, + pub flight_x: Vec, + pub flight_y: Vec, +} +impl LegacyEnemy { + pub const SIZE: usize = 528; + pub fn library(data: &[u8]) -> Result> { + ensure!(data.len() % Self::SIZE == 0, "truncated enemy library"); + data.chunks_exact(Self::SIZE) + .map(|record| { + let name = + String::from_utf8(record[..16].split(|x| *x == 0).next().unwrap().to_vec())?; + let fields = (0..26) + .map(|i| i32_at(record, 16 + i * 4)) + .collect::>>()?; + let shorts = |offset: usize, count: usize| -> Result> { + (0..count).map(|i| i16_at(record, offset + i * 2)).collect() + }; + ensure!( + (0..=30).contains(&fields[19]) && (0..=24).contains(&fields[22]), + "invalid enemy path or guns" + ); + Ok(Self { + name, + fields, + shoot_type: shorts(120, 24)?, + engine_x: shorts(168, 24)?, + engine_y: shorts(216, 24)?, + engine_width: shorts(264, 24)?, + gun_x: shorts(312, 24)?, + gun_y: shorts(360, 24)?, + flight_x: shorts(408, 30)?, + flight_y: shorts(468, 30)?, + }) + }) + .collect() + } +} +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub struct DemoFrame { + pub buttons: [bool; 4], + pub x: i16, + pub y: i16, + pub bank: i16, +} +pub fn decode_demo(data: &[u8]) -> Result<(usize, usize, Vec)> { + ensure!(data.len() >= 12 && data.len() % 12 == 0, "truncated demo"); + let count = i16_at(data, 8)?; + ensure!( + count >= 0 && count as usize * 12 <= data.len(), + "invalid demo frame count" + ); + let sector = i16_at(data, 4)?; + let wave = i16_at(data, 6)?; + ensure!( + (0..3).contains(§or) && (0..9).contains(&wave), + "invalid demo mission" + ); + let frames = data[12..] + .chunks_exact(12) + .take(count as usize) + .map(|f| { + Ok(DemoFrame { + buttons: std::array::from_fn(|i| f[i] != 0), + x: i16_at(f, 4)?, + y: i16_at(f, 6)?, + bank: i16_at(f, 8)?, + }) + }) + .collect::>()?; + Ok((sector as usize, wave as usize, frames)) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn truncation_is_an_error() { + for n in 0..20 { + assert!(Sprite::decode(&vec![0; n]).is_err()); + } + } + #[test] + fn raw_picture() { + let mut b = Vec::new(); + for x in [1i32, 0, 0, 2, 1] { + b.extend(x.to_le_bytes()) + } + b.extend([0, 7]); + assert_eq!(Sprite::decode(&b).unwrap().pixels, vec![0, 7]); + } + #[test] + fn span_outside_canvas_rejected() { + let mut b = Vec::new(); + for x in [0i32, 0, 0, 2, 1, 1, 0, 1, 2] { + b.extend(x.to_le_bytes()) + } + b.extend([3, 4]); + assert!(Sprite::decode(&b).is_err()); + } +} diff --git a/src/audio.rs b/src/audio.rs new file mode 100644 index 00000000..b8fb4f8d --- /dev/null +++ b/src/audio.rs @@ -0,0 +1,873 @@ +//! Checked MUS decoding, the original GENMIDI/OPL3 driver behavior and digital DSP mixing. +//! +//! Driver and DSP behavior is ported from the retained GPL-2.0-or-later sources. +//! The OPL driver credits Id Software (1993–1996) and Simon Howard (2005–2014). +use crate::assets::{i16_at, i32_at}; +use anyhow::{Context, Result, bail, ensure}; +mod opl3; +use opl3::Chip as Opl3Chip; +use std::collections::VecDeque; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MusicEvent { + Off(u8, u8), + On(u8, u8, u8), + OnInherited(u8, u8), + Bend(u8, u8), + System(u8, u8), + Control(u8, u8, u8), + End, +} +#[derive(Debug, Clone)] +pub struct MusScore { + pub groups: Vec<(u32, Vec)>, + pub channels: u8, +} +impl MusScore { + pub fn decode(bytes: &[u8]) -> Result { + ensure!(bytes.get(..4) == Some(b"MUS\x1a"), "invalid MUS signature"); + let length = i16_at(bytes, 4)? as u16 as usize; + let start = i16_at(bytes, 6)? as u16 as usize; + let channels = i16_at(bytes, 8)? as u16; + let instruments = i16_at(bytes, 12)? as u16 as usize; + ensure!(channels <= 15, "MUS has too many primary channels"); + ensure!( + start >= 16 + instruments * 2 + && start.checked_add(length).is_some_and(|e| e <= bytes.len()), + "MUS score range is invalid" + ); + let data = &bytes[start..start + length]; + let mut p = 0usize; + let mut tick = 0u32; + let mut groups = Vec::new(); + let mut pending = Vec::new(); + let mut ended = false; + let byte = |p: &mut usize| -> Result { + let value = *data.get(*p).context("truncated MUS event")?; + *p += 1; + Ok(value) + }; + while p < data.len() { + let descriptor = byte(&mut p)?; + let channel = descriptor & 15; + let kind = (descriptor >> 4) & 7; + let event = match kind { + 0 => MusicEvent::Off(channel, byte(&mut p)? & 127), + 1 => { + let key = byte(&mut p)?; + if key & 128 != 0 { + let velocity = byte(&mut p)?; + ensure!(velocity <= 127, "invalid MUS note velocity"); + MusicEvent::On(channel, key & 127, velocity) + } else { + MusicEvent::OnInherited(channel, key) + } + } + 2 => MusicEvent::Bend(channel, byte(&mut p)?), + 3 => { + let control = byte(&mut p)?; + ensure!((10..=14).contains(&control), "invalid MUS system event"); + MusicEvent::System(channel, control) + } + 4 => { + let control = byte(&mut p)?; + let value = byte(&mut p)?; + ensure!( + control <= 14 && value <= 127, + "invalid MUS controller event" + ); + MusicEvent::Control(channel, control, value) + } + 6 => MusicEvent::End, + _ => bail!("unsupported MUS event {kind}"), + }; + let end = matches!(event, MusicEvent::End); + pending.push(event); + if descriptor & 128 != 0 || end { + groups.push((tick, std::mem::take(&mut pending))); + if end { + ended = true; + break; + } + let mut delay = 0u32; + for n in 0..5 { + let v = byte(&mut p)?; + delay = delay + .checked_mul(128) + .and_then(|x| x.checked_add((v & 127) as u32)) + .context("MUS delay overflow")?; + if v & 128 == 0 { + break; + } + ensure!(n < 4, "MUS delay too long"); + } + tick = tick.checked_add(delay).context("MUS time overflow")?; + } + } + ensure!(ended, "MUS score has no end event"); + Ok(Self { + groups, + channels: channels as u8, + }) + } +} +#[derive(Clone)] +struct Instrument { + flags: u16, + fixed: u8, + fine: u8, + voice: [[u8; 16]; 2], +} +#[derive(Clone, Copy, Default)] +struct Voice { + channel: u8, + key: u8, + frequency: u16, + velocity: u8, + active: bool, + instrument: usize, + part: usize, + note: i32, + loaded: bool, + car_volume: u8, + mod_volume: u8, +} +#[derive(Clone, PartialEq, Eq)] +pub struct DigitalSample { + pub rate: u32, + pub data: Vec, +} +impl DigitalSample { + pub fn decode(data: &[u8]) -> Result { + ensure!(i16_at(data, 0)? == 3, "not a digital sound patch"); + let rate = i16_at(data, 2)? as u16 as u32; + let length = i32_at(data, 4)?; + ensure!( + rate > 0 && length > 32 && length as usize <= data.len().saturating_sub(8), + "invalid digital sound header" + ); + // DMX patches include sixteen bytes of padding at each end. + Ok(Self { + rate, + data: data[24..8 + length as usize - 16].to_vec(), + }) + } +} +struct SampleVoice { + sample: DigitalSample, + position: usize, + step: usize, + fraction: usize, + remaining: usize, + left: [i16; 256], + right: [i16; 256], + priority: i32, +} +struct Fade { + level: i32, + target: i32, + add: i32, + remainder: i32, + steps: i32, + accumulator: i32, +} +pub struct Mixer { + chip: Opl3Chip, + rate: u32, + instruments: Vec, + voices: [Voice; 18], + free: VecDeque, + allocated: Vec, + pan: [u8; 16], + program: [usize; 16], + volume: [u8; 16], + channel_volume: [u8; 16], + velocity: [u8; 16], + bend: [u8; 16], + score: Option, + group: usize, + score_tick: u32, + music_phase: u32, + fader_phase: u32, + last_volume: u8, + fade: Option, + looping: bool, + digital: [Option; 8], + digital_channels: usize, + digital_phase: u32, + digital_hold: [i32; 2], + pub music_volume: u8, + pub fx_volume: u8, +} +impl Mixer { + pub fn new(rate: u32, genmidi: &[u8]) -> Result { + ensure!( + genmidi.get(..8) == Some(b"#OPL_II#") && genmidi.len() >= 8 + 175 * 36, + "invalid GENMIDI instrument table" + ); + ensure!((8000..=192000).contains(&rate), "invalid mixer sample rate"); + let instruments = genmidi[8..8 + 175 * 36] + .chunks_exact(36) + .map(|b| Instrument { + flags: u16::from_le_bytes([b[0], b[1]]), + fixed: b[3], + fine: b[2], + voice: [b[4..20].try_into().unwrap(), b[20..36].try_into().unwrap()], + }) + .collect(); + let mut chip = Opl3Chip::new(rate); + initialize_chip(&mut chip); + Ok(Self { + chip, + rate, + instruments, + voices: [Voice::default(); 18], + free: (0..18).collect(), + allocated: vec![], + pan: [0x30; 16], + program: [0; 16], + volume: [127; 16], + channel_volume: [100; 16], + velocity: [0; 16], + bend: [128; 16], + score: None, + group: 0, + score_tick: 0, + music_phase: 0, + fader_phase: 0, + last_volume: 0, + fade: None, + looping: false, + digital: std::array::from_fn(|_| None), + digital_channels: 2, + digital_phase: 0, + digital_hold: [0; 2], + music_volume: 85, + fx_volume: 85, + }) + } + pub fn play(&mut self, score: MusScore, looping: bool) { + self.play_with_fade(score, looping, false); + } + pub fn play_with_fade(&mut self, score: MusScore, looping: bool, fade_in: bool) { + self.all_off(); + self.score = Some(score); + self.looping = looping; + self.group = 0; + self.score_tick = 0; + self.fade = None; + self.reset_channels(); + if fade_in { + self.fade = Some(make_fade(0, 127)); + } + } + pub fn stop(&mut self) { + self.all_off(); + self.score = None; + self.fade = None; + } + pub fn stop_with_fade(&mut self) { + let level = self + .fade + .as_ref() + .map_or(self.music_volume as i32, |f| f.level); + if level == 0 { + self.stop(); + } else { + self.fade = Some(make_fade(level, 0)); + } + } + pub fn set_fx_channels(&mut self, count: usize) { + self.digital_channels = count.clamp(1, 8); + for slot in &mut self.digital[self.digital_channels..] { + *slot = None; + } + } + fn release(&mut self, n: usize) { + self.chip + .write_reg_buffered(register(0xb0, n), (self.voices[n].frequency >> 8) as u8); + self.voices[n].active = false; + self.allocated.retain(|v| *v != n); + self.free.push_back(n); + } + fn all_off(&mut self) { + for n in self.allocated.clone() { + self.release(n); + } + } + fn off(&mut self, channel: u8, key: u8) { + for n in self.allocated.clone() { + if self.voices[n].channel == channel && self.voices[n].key == key { + self.release(n); + } + } + } + fn channel_off(&mut self, channel: u8) { + for n in self.allocated.clone() { + if self.voices[n].channel == channel { + self.release(n); + } + } + } + fn reset_channels(&mut self) { + self.channel_volume.fill(100); + let channels = self.score.as_ref().map_or(15, |s| s.channels); + for c in 0..16 { + self.channel_off(c); + if c < channels || c == 15 { + self.bend[c as usize] = 128; + self.pan[c as usize] = 0x30; + self.set_channel_volume( + c, + 100.min(self.music_volume.min(127)).min(self.fade_level()), + ); + } + } + } + fn on(&mut self, channel: u8, key: u8, velocity: u8) { + if velocity == 0 { + self.off(channel, key); + return; + } + if channel == 15 && !(35..=81).contains(&key) { + return; + } + let instrument = if channel == 15 { + 128 + (key - 35) as usize + } else { + self.program[channel as usize].min(127) + }; + if self.free.is_empty() { + let mut result = self.allocated[0]; + for &n in &self.allocated { + if self.voices[n].part != 0 || self.voices[n].channel >= self.voices[result].channel + { + result = n; + } + } + self.release(result); + } + self.voice_on(channel, key, velocity, instrument, 0); + if self.instruments[instrument].flags & 4 != 0 { + self.voice_on(channel, key, velocity, instrument, 1); + } + } + fn voice_on(&mut self, channel: u8, key: u8, velocity: u8, instrument: usize, part: usize) { + let Some(n) = self.free.pop_front() else { + return; + }; + let ins = self.instruments[instrument].clone(); + let v = ins.voice[part]; + if !self.voices[n].loaded + || self.voices[n].instrument != instrument + || self.voices[n].part != part + { + let op = operator(n); + let bank = (n as u16 / 9) << 8; + for (offset, base) in [(3u16, 7usize), (0, 0)] { + let level = v[base + 4] + | if base == 7 || v[6] & 1 != 0 { + 63 + } else { + v[base + 5] + }; + if base == 7 { + self.voices[n].car_volume = level; + } else { + self.voices[n].mod_volume = level; + } + for (reg, value) in [ + (0x40, level), + (0x20, v[base]), + (0x60, v[base + 1]), + (0x80, v[base + 2]), + (0xe0, v[base + 3]), + ] { + self.chip + .write_reg_buffered((reg + op + offset) | bank, value); + } + } + self.chip + .write_reg_buffered(register(0xc0, n), v[6] | self.pan[channel as usize]); + } + let note = if ins.flags & 1 != 0 { + ins.fixed as i32 + } else { + (if channel == 15 { 60 } else { key as i32 }) + + i16::from_le_bytes([v[14], v[15]]) as i32 + }; + let old = self.voices[n]; + self.voices[n] = Voice { + channel, + key, + frequency: 0, + velocity, + active: true, + instrument, + part, + note, + loaded: true, + ..old + }; + self.allocated.push(n); + self.voice_volume(n); + self.voice_frequency(n); + } + fn voice_volume(&mut self, n: usize) { + let voice = self.voices[n]; + let v = self.instruments[voice.instrument].voice[voice.part]; + let midi = 2 + * (crate::legacy_tables::VOLUME_CURVE[self.volume[voice.channel as usize] as usize] + + 1); + let full = (crate::legacy_tables::VOLUME_CURVE[voice.velocity as usize] * midi) >> 9; + let car = (63 - full) as u8; + if car != voice.car_volume & 63 { + let op = operator(n); + let bank = (n as u16 / 9) << 8; + self.voices[n].car_volume = (voice.car_volume & 192) | car; + self.chip + .write_reg_buffered((0x43 + op) | bank, self.voices[n].car_volume); + if v[6] & 1 != 0 && v[5] != 63 { + let level = (voice.mod_volume & 192) | v[5].max(car); + if level != voice.mod_volume { + self.voices[n].mod_volume = level; + self.chip + .write_reg_buffered((0x40 + op) | bank, level | (v[4] & 192)); + } + } + } + } + fn voice_frequency(&mut self, n: usize) { + let voice = self.voices[n]; + let ins = &self.instruments[voice.instrument]; + let fine = if voice.part != 0 { + ins.fine as i32 / 2 - 64 + } else { + 0 + }; + let f = frequency(voice.note, self.bend[voice.channel as usize], fine); + if f != voice.frequency { + self.voices[n].frequency = f; + self.chip.write_reg_buffered(register(0xa0, n), f as u8); + self.chip + .write_reg_buffered(register(0xb0, n), ((f >> 8) as u8) | 0x20); + } + } + fn set_channel_volume(&mut self, c: u8, v: u8) { + self.volume[c as usize] = v.min(127); + // Preserve original physical voice iteration order, which affects buffered writes. + for n in 0..18 { + if self.voices[n].active && self.voices[n].channel == c { + self.voice_volume(n); + } + } + } + fn event(&mut self, e: MusicEvent) { + match e { + MusicEvent::Off(c, k) => self.off(c, k), + MusicEvent::On(c, k, v) => { + self.velocity[c as usize] = v; + self.on(c, k, v); + } + MusicEvent::OnInherited(c, k) => self.on(c, k, self.velocity[c as usize]), + MusicEvent::Bend(c, b) => { + self.bend[c as usize] = b; + let (updated, others): (Vec<_>, Vec<_>) = self + .allocated + .iter() + .copied() + .partition(|n| self.voices[*n].channel == c); + for &n in &updated { + self.voice_frequency(n); + } + self.allocated = others.into_iter().chain(updated).collect(); + } + MusicEvent::System(c, 10 | 11 | 14) => { + self.channel_off(c); + if matches!(e, MusicEvent::System(_, 14)) { + self.bend[c as usize] = 128; + self.pan[c as usize] = 0x30; + } + } + MusicEvent::Control(c, 0, p) => self.program[c as usize] = p.min(127) as usize, + MusicEvent::Control(c, 3, v) => { + self.channel_volume[c as usize] = v; + self.set_channel_volume( + c, + v.min(self.music_volume.min(127)).min(self.fade_level()), + ); + } + MusicEvent::Control(c, 4, p) => { + let pan = if p >= 96 { + 0x10 + } else if p <= 48 { + 0x20 + } else { + 0x30 + }; + if self.pan[c as usize] != pan { + self.pan[c as usize] = pan; + for n in 0..18 { + let voice = self.voices[n]; + if voice.active && voice.channel == c { + self.chip.write_reg_buffered( + register(0xc0, n), + self.instruments[voice.instrument].voice[voice.part][6] | pan, + ); + } + } + } + } + MusicEvent::Control(c, 10 | 11, _) => self.channel_off(c), + MusicEvent::Control(c, 14, _) => { + self.channel_off(c); + self.set_channel_volume( + c, + self.velocity[c as usize] + .min(self.music_volume.min(127)) + .min(self.fade_level()), + ); + } + _ => {} + } + } + fn fade_level(&self) -> u8 { + self.fade + .as_ref() + .map_or(127, |f| f.level.clamp(0, 127) as u8) + } + fn service_music(&mut self) { + // Events are serviced at 70Hz after that output sample, matching MUS_Mix. + let mut restarts = 0; + loop { + let group = self + .score + .as_ref() + .and_then(|s| s.groups.get(self.group)) + .filter(|(time, _)| *time <= self.score_tick) + .cloned(); + let Some((time, events)) = group else { + break; + }; + self.group += 1; + for event in events { + if matches!(event, MusicEvent::End) { + if self.looping && time > 0 && restarts == 0 { + self.group = 0; + self.score_tick = 0; + self.reset_channels(); + restarts += 1; + } else { + self.score = None; + } + } else { + self.event(event); + } + } + if self.score.is_none() { + break; + } + } + self.score_tick = self.score_tick.saturating_add(1); + } + fn service_fader(&mut self) { + let mut update = self.last_volume != self.music_volume; + self.last_volume = self.music_volume; + if let Some(f) = &mut self.fade { + update = true; + if f.level < self.music_volume as i32 || f.target < self.music_volume as i32 { + let mut count = f.add; + f.accumulator += f.remainder; + if f.accumulator >= f.steps { + f.accumulator -= f.steps; + count += 1; + } + if f.target < f.level { + f.level = (f.level - count).max(0); + } else { + f.level = (f.level + count) + .min(f.target) + .min(self.music_volume.min(127) as i32); + } + } + if f.level == 0 && f.target == 0 { + self.stop(); + return; + } + if f.level >= f.target && f.target != 0 { + self.fade = None; + } else if f.target != 0 && f.level >= self.music_volume.min(127) as i32 { + self.fade = None; + } + } + if update { + let channels = self.score.as_ref().map_or(15, |s| s.channels); + for c in 0..16 { + if c < channels || c == 15 { + let v = self.music_volume.min(127).min(self.fade_level()); + self.set_channel_volume( + c, + if c == 15 { + v + } else { + v.min(self.channel_volume[c as usize]) + }, + ); + } + } + } + } + pub fn sample( + &mut self, + sample: DigitalSample, + pan: i32, + pitch: i32, + volume: i32, + priority: i32, + ) { + if sample.data.is_empty() || sample.rate == 0 { + return; + } + let pan = pan.clamp(0, 255) as usize; + let step = ((DSP_PITCH[pitch.clamp(0, 255) as usize] as u64 * sample.rate as u64 + + 11025 / 2) + / 11025) + .max(1) as usize; + let remaining = sample.data.len().saturating_mul(256) / step; + if remaining == 0 { + return; + } + let slot = if let Some(n) = self.digital[..self.digital_channels] + .iter() + .position(Option::is_none) + { + n + } else { + let mut lowest = 0; + let mut fewest = usize::MAX; + let mut best = 0; + for (n, v) in self.digital[..self.digital_channels].iter().enumerate() { + let v = v.as_ref().unwrap(); + if v.priority > lowest { + lowest = v.priority; + best = n; + } else if v.priority == lowest && v.remaining < fewest { + fewest = v.remaining; + best = n; + } + } + if lowest < priority || lowest == 0 { + return; + } + if lowest == priority && self.digital[best].as_ref().unwrap().sample != sample { + if let Some(n) = self.digital[..self.digital_channels] + .iter() + .position(|v| v.as_ref().is_some_and(|v| v.sample == sample)) + { + best = n; + } + } + best + }; + let volume = volume.clamp(0, 127) * self.fx_volume.min(127) as i32 / 127; + let left = volume_table(DSP_PAN[255 - pan] as i32 * volume / 127); + let right = volume_table(DSP_PAN[pan] as i32 * volume / 127); + self.digital[slot] = Some(SampleVoice { + sample, + position: 0, + step, + fraction: (step & 255) >> 1, + remaining, + left, + right, + priority, + }); + } + fn service_digital(&mut self) { + let mut sample = [0i32; 2]; + for slot in &mut self.digital[..self.digital_channels] { + if let Some(v) = slot { + if let Some(value) = v.sample.data.get(v.position) { + sample[0] += v.left[*value as usize] as i32; + sample[1] += v.right[*value as usize] as i32; + } + v.fraction += v.step & 255; + let carry = usize::from(v.fraction >= 256); + v.fraction &= 255; + v.position = v.position.saturating_add((v.step >> 8) + carry); + v.remaining -= 1; + if v.remaining == 0 { + *slot = None; + } + } + } + self.digital_hold = sample.map(|v| v.clamp(-128, 127) * 128); + } + pub fn mix(&mut self, out: &mut [i16]) { + // A partial stereo frame is explicitly silent, not leftover caller memory. + out.fill(0); + for frame in out.chunks_exact_mut(2) { + let mut fm = [0i16; 2]; + self.chip.generate_resampled(&mut fm); + self.music_phase += 70; + while self.music_phase >= self.rate { + self.music_phase -= self.rate; + self.service_music(); + } + self.fader_phase += 50; + while self.fader_phase >= self.rate { + self.fader_phase -= self.rate; + self.service_fader(); + } + self.digital_phase += 11025; + while self.digital_phase >= self.rate { + self.digital_phase -= self.rate; + self.service_digital(); + } + frame[0] = (fm[0] as i32 + self.digital_hold[0]).clamp(-32768, 32767) as i16; + frame[1] = (fm[1] as i32 + self.digital_hold[1]).clamp(-32768, 32767) as i16; + } + } +} +fn make_fade(level: i32, target: i32) -> Fade { + let steps = (target - level).abs(); + Fade { + level, + target, + add: steps / 51, + remainder: steps % 51, + steps: steps.max(1), + accumulator: -((steps % 51) >> 1), + } +} +fn volume_table(volume: i32) -> [i16; 256] { + let mut value = -(volume / 2); + let step = volume >> 8; + let sub = volume & 255; + let mut accumulator = sub >> 1; + std::array::from_fn(|_| { + let out = value as i16; + value += step; + accumulator += sub; + while accumulator >= 256 { + value += 1; + accumulator -= 256; + } + out + }) +} +fn initialize_chip(chip: &mut Opl3Chip) { + for r in 0x40..=0x55 { + chip.write_reg_buffered(r, 63); + } + for r in 0x60..=0xf5 { + chip.write_reg_buffered(r, 0); + } + for r in 1..0x40 { + chip.write_reg_buffered(r, 0); + } + chip.write_reg_buffered(4, 0x60); + chip.write_reg_buffered(4, 0x80); + chip.write_reg_buffered(1, 0x20); + chip.write_reg_buffered(0x105, 1); + for r in 0x40..=0x55 { + chip.write_reg_buffered(r | 0x100, 63); + } + for r in 0x60..=0xf5 { + chip.write_reg_buffered(r | 0x100, 0); + } + for r in 1..0x40 { + chip.write_reg_buffered(r | 0x100, 0); + } + chip.write_reg_buffered(8, 0x40); + chip.write_reg_buffered(0x105, 1); +} +fn register(reg: u16, n: usize) -> u16 { + (reg + n as u16 % 9) | ((n as u16 / 9) << 8) +} +fn operator(n: usize) -> u16 { + [0, 1, 2, 8, 9, 10, 16, 17, 18][n % 9] +} +fn frequency(mut note: i32, bend: u8, fine: i32) -> u16 { + while note < 0 { + note += 12; + } + while note > 95 { + note -= 12; + } + let index = (64 + 32 * note + (bend as i32 / 2 - 64) + fine).max(0) as usize; + if index < 284 { + crate::legacy_tables::FREQUENCY_CURVE[index] + } else { + crate::legacy_tables::FREQUENCY_CURVE[(index - 284) % 384 + 284] + | ((((index - 284) / 384).min(7) as u16) << 10) + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn truncated_scores_are_rejected() { + for n in 0..16 { + assert!(MusScore::decode(&vec![0; n]).is_err()); + } + } + #[test] + fn simple_score() { + let mut data = b"MUS\x1a".to_vec(); + data.extend([5, 0, 16, 0, 1, 0, 0, 0, 0, 0, 0, 0]); + data.extend([0x90, 0x80 | 60, 100, 1, 0x60]); + let s = MusScore::decode(&data).unwrap(); + assert_eq!(s.groups.len(), 2); + } + #[test] + fn bad_digital_length() { + assert!(DigitalSample::decode(&[3, 0, 68, 172, 99, 0, 0, 0, 128]).is_err()); + } +} + +// Exact lookup values from the original digital mixer. +const DSP_PITCH: [u16; 256] = [ + 0x0040, 0x0040, 0x0041, 0x0042, 0x0042, 0x0043, 0x0044, 0x0045, 0x0045, 0x0046, 0x0047, 0x0048, + 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, + 0x0053, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, + 0x005E, 0x005F, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, + 0x006B, 0x006C, 0x006E, 0x006F, 0x0070, 0x0071, 0x0072, 0x0074, 0x0075, 0x0076, 0x0077, 0x0079, + 0x007A, 0x007B, 0x007D, 0x007E, 0x0080, 0x0081, 0x0082, 0x0084, 0x0085, 0x0087, 0x0088, 0x008A, + 0x008B, 0x008D, 0x008E, 0x0090, 0x0091, 0x0093, 0x0095, 0x0096, 0x0098, 0x0099, 0x009B, 0x009D, + 0x009F, 0x00A0, 0x00A2, 0x00A4, 0x00A6, 0x00A7, 0x00A9, 0x00AB, 0x00AD, 0x00AF, 0x00B1, 0x00B3, + 0x00B5, 0x00B7, 0x00B9, 0x00BB, 0x00BD, 0x00BF, 0x00C1, 0x00C3, 0x00C5, 0x00C7, 0x00C9, 0x00CB, + 0x00CE, 0x00D0, 0x00D2, 0x00D5, 0x00D7, 0x00D9, 0x00DC, 0x00DE, 0x00E0, 0x00E3, 0x00E5, 0x00E8, + 0x00EA, 0x00ED, 0x00EF, 0x00F2, 0x00F5, 0x00F7, 0x00FA, 0x00FD, 0x0100, 0x0102, 0x0105, 0x0108, + 0x010B, 0x010E, 0x0111, 0x0114, 0x0117, 0x011A, 0x011D, 0x0120, 0x0123, 0x0126, 0x0129, 0x012D, + 0x0130, 0x0133, 0x0137, 0x013A, 0x013D, 0x0141, 0x0144, 0x0148, 0x014C, 0x014F, 0x0153, 0x0157, + 0x015A, 0x015E, 0x0162, 0x0166, 0x016A, 0x016E, 0x0172, 0x0176, 0x017A, 0x017E, 0x0182, 0x0186, + 0x018A, 0x018F, 0x0193, 0x0197, 0x019C, 0x01A0, 0x01A5, 0x01A9, 0x01AE, 0x01B3, 0x01B8, 0x01BC, + 0x01C1, 0x01C6, 0x01CB, 0x01D0, 0x01D5, 0x01DA, 0x01DF, 0x01E5, 0x01EA, 0x01EF, 0x01F5, 0x01FA, + 0x0200, 0x0205, 0x020B, 0x0210, 0x0216, 0x021C, 0x0222, 0x0228, 0x022E, 0x0234, 0x023A, 0x0240, + 0x0247, 0x024D, 0x0253, 0x025A, 0x0260, 0x0267, 0x026E, 0x0275, 0x027B, 0x0282, 0x0289, 0x0290, + 0x0298, 0x029F, 0x02A6, 0x02AD, 0x02B5, 0x02BC, 0x02C4, 0x02CC, 0x02D4, 0x02DC, 0x02E3, 0x02EC, + 0x02F4, 0x02FC, 0x0304, 0x030D, 0x0315, 0x031E, 0x0326, 0x032F, 0x0338, 0x0341, 0x034A, 0x0353, + 0x035D, 0x0366, 0x036F, 0x0379, 0x0383, 0x038D, 0x0396, 0x03A0, 0x03AB, 0x03B5, 0x03BF, 0x03CA, + 0x03D4, 0x03DF, 0x03EA, 0x03F5, +]; + +// Exact lookup values from the original digital mixer. +const DSP_PAN: [u8; 256] = [ + 0x0E, 0x13, 0x19, 0x1D, 0x22, 0x26, 0x2A, 0x2F, 0x33, 0x37, 0x3B, 0x3F, 0x41, 0x45, 0x49, 0x4C, + 0x50, 0x53, 0x55, 0x59, 0x5C, 0x5E, 0x61, 0x65, 0x67, 0x6A, 0x6C, 0x6F, 0x71, 0x74, 0x75, 0x78, + 0x7A, 0x7D, 0x7F, 0x80, 0x83, 0x85, 0x86, 0x89, 0x8B, 0x8C, 0x8E, 0x90, 0x92, 0x93, 0x95, 0x96, + 0x99, 0x9A, 0x9C, 0x9D, 0x9E, 0xA0, 0xA2, 0xA3, 0xA5, 0xA6, 0xA7, 0xA9, 0xAA, 0xAB, 0xAC, 0xAE, + 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, + 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCD, + 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD2, 0xD3, 0xD3, 0xD4, 0xD5, 0xD6, 0xD6, 0xD6, 0xD7, 0xD8, + 0xD9, 0xD9, 0xD9, 0xDA, 0xDB, 0xDC, 0xDC, 0xDC, 0xDD, 0xDE, 0xDE, 0xDF, 0xDF, 0xE0, 0xE0, 0xE1, + 0xE1, 0xE1, 0xE2, 0xE3, 0xE4, 0xE4, 0xE4, 0xE5, 0xE5, 0xE6, 0xE6, 0xE6, 0xE7, 0xE7, 0xE7, 0xE8, + 0xE9, 0xE9, 0xE9, 0xE9, 0xEA, 0xEB, 0xEB, 0xEB, 0xEC, 0xEC, 0xEC, 0xEC, 0xED, 0xED, 0xED, 0xEE, + 0xEE, 0xEF, 0xEF, 0xEF, 0xF0, 0xF0, 0xF0, 0xF0, 0xF1, 0xF1, 0xF1, 0xF2, 0xF2, 0xF2, 0xF2, 0xF3, + 0xF3, 0xF3, 0xF3, 0xF4, 0xF4, 0xF4, 0xF5, 0xF5, 0xF5, 0xF5, 0xF6, 0xF6, 0xF6, 0xF6, 0xF7, 0xF7, + 0xF7, 0xF7, 0xF7, 0xF7, 0xF8, 0xF8, 0xF8, 0xF8, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xF9, 0xFA, + 0xFA, 0xFA, 0xFA, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, + 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, +]; diff --git a/src/audio/LICENSE-LGPL-2.1.txt b/src/audio/LICENSE-LGPL-2.1.txt new file mode 100644 index 00000000..8000a6fa --- /dev/null +++ b/src/audio/LICENSE-LGPL-2.1.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random + Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/src/audio/opl3.rs b/src/audio/opl3.rs new file mode 100644 index 00000000..06475465 --- /dev/null +++ b/src/audio/opl3.rs @@ -0,0 +1,1512 @@ +// Vendored from nuked-opl3 0.1.0, reconciled with raptor/src/opl3.cpp. +// Legacy compatibility: per-slot LFSR, envelope timer phases and checked decoding. +#![allow(dead_code)] +// Pure-Rust port of Nuked-OPL3 1.8. +// +// Copyright (C) 2013-2020 Nuke.YKT +// Copyright (C) 2026 Tony Gies (Rust port) +// +// This file is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as +// published by the Free Software Foundation, either version 2.1 +// of the License, or (at your option) any later version. +// +// This file is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this file. If not, see . +// +// The original C implementation stores self-referential pointers between the +// chip, channels, slots, modulation inputs, and channel outputs. This module +// keeps the same state machine and sample ordering, but represents those links +// as stable indices so the chip can be moved safely in Rust. + +const WRITEBUF_SIZE: usize = 1024; +const WRITEBUF_DELAY: u64 = 2; +const RSM_FRAC: u32 = 10; +const NATIVE_RATE: u32 = 49_716; +const CHANNEL_SAMPLE_DELAY: bool = true; + +const CH_2OP: u8 = 0; +const CH_4OP: u8 = 1; +const CH_4OP2: u8 = 2; +const CH_DRUM: u8 = 3; + +const EGK_NORM: u8 = 0x01; +const EGK_DRUM: u8 = 0x02; + +const ENV_ATTACK: u8 = 0; +const ENV_DECAY: u8 = 1; +const ENV_SUSTAIN: u8 = 2; +const ENV_RELEASE: u8 = 3; + +const LOGSINROM: [u16; 256] = [ + 0x859, 0x6c3, 0x607, 0x58b, 0x52e, 0x4e4, 0x4a6, 0x471, 0x443, 0x41a, 0x3f5, 0x3d3, 0x3b5, + 0x398, 0x37e, 0x365, 0x34e, 0x339, 0x324, 0x311, 0x2ff, 0x2ed, 0x2dc, 0x2cd, 0x2bd, 0x2af, + 0x2a0, 0x293, 0x286, 0x279, 0x26d, 0x261, 0x256, 0x24b, 0x240, 0x236, 0x22c, 0x222, 0x218, + 0x20f, 0x206, 0x1fd, 0x1f5, 0x1ec, 0x1e4, 0x1dc, 0x1d4, 0x1cd, 0x1c5, 0x1be, 0x1b7, 0x1b0, + 0x1a9, 0x1a2, 0x19b, 0x195, 0x18f, 0x188, 0x182, 0x17c, 0x177, 0x171, 0x16b, 0x166, 0x160, + 0x15b, 0x155, 0x150, 0x14b, 0x146, 0x141, 0x13c, 0x137, 0x133, 0x12e, 0x129, 0x125, 0x121, + 0x11c, 0x118, 0x114, 0x10f, 0x10b, 0x107, 0x103, 0x0ff, 0x0fb, 0x0f8, 0x0f4, 0x0f0, 0x0ec, + 0x0e9, 0x0e5, 0x0e2, 0x0de, 0x0db, 0x0d7, 0x0d4, 0x0d1, 0x0cd, 0x0ca, 0x0c7, 0x0c4, 0x0c1, + 0x0be, 0x0bb, 0x0b8, 0x0b5, 0x0b2, 0x0af, 0x0ac, 0x0a9, 0x0a7, 0x0a4, 0x0a1, 0x09f, 0x09c, + 0x099, 0x097, 0x094, 0x092, 0x08f, 0x08d, 0x08a, 0x088, 0x086, 0x083, 0x081, 0x07f, 0x07d, + 0x07a, 0x078, 0x076, 0x074, 0x072, 0x070, 0x06e, 0x06c, 0x06a, 0x068, 0x066, 0x064, 0x062, + 0x060, 0x05e, 0x05c, 0x05b, 0x059, 0x057, 0x055, 0x053, 0x052, 0x050, 0x04e, 0x04d, 0x04b, + 0x04a, 0x048, 0x046, 0x045, 0x043, 0x042, 0x040, 0x03f, 0x03e, 0x03c, 0x03b, 0x039, 0x038, + 0x037, 0x035, 0x034, 0x033, 0x031, 0x030, 0x02f, 0x02e, 0x02d, 0x02b, 0x02a, 0x029, 0x028, + 0x027, 0x026, 0x025, 0x024, 0x023, 0x022, 0x021, 0x020, 0x01f, 0x01e, 0x01d, 0x01c, 0x01b, + 0x01a, 0x019, 0x018, 0x017, 0x017, 0x016, 0x015, 0x014, 0x014, 0x013, 0x012, 0x011, 0x011, + 0x010, 0x00f, 0x00f, 0x00e, 0x00d, 0x00d, 0x00c, 0x00c, 0x00b, 0x00a, 0x00a, 0x009, 0x009, + 0x008, 0x008, 0x007, 0x007, 0x007, 0x006, 0x006, 0x005, 0x005, 0x005, 0x004, 0x004, 0x004, + 0x003, 0x003, 0x003, 0x002, 0x002, 0x002, 0x002, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, + 0x001, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, +]; + +// Pre-shifted by 1: stores `original_exprom[i] << 1` so the runtime `<< 1` in +// envelope_calc_exp can be dropped. Max value 0x7fa << 1 = 0xff4, still fits in u16. +const EXPROM: [u16; 256] = [ + 0xff4, 0xfea, 0xfde, 0xfd4, 0xfc8, 0xfbe, 0xfb4, 0xfa8, 0xf9e, 0xf92, 0xf88, 0xf7e, 0xf72, + 0xf68, 0xf5c, 0xf52, 0xf48, 0xf3e, 0xf32, 0xf28, 0xf1e, 0xf14, 0xf08, 0xefe, 0xef4, 0xeea, + 0xee0, 0xed4, 0xeca, 0xec0, 0xeb6, 0xeac, 0xea2, 0xe98, 0xe8e, 0xe84, 0xe7a, 0xe70, 0xe66, + 0xe5c, 0xe52, 0xe48, 0xe3e, 0xe34, 0xe2a, 0xe20, 0xe16, 0xe0c, 0xe04, 0xdfa, 0xdf0, 0xde6, + 0xddc, 0xdd2, 0xdca, 0xdc0, 0xdb6, 0xdac, 0xda4, 0xd9a, 0xd90, 0xd88, 0xd7e, 0xd74, 0xd6a, + 0xd62, 0xd58, 0xd50, 0xd46, 0xd3c, 0xd34, 0xd2a, 0xd22, 0xd18, 0xd10, 0xd06, 0xcfe, 0xcf4, + 0xcec, 0xce2, 0xcda, 0xcd0, 0xcc8, 0xcbe, 0xcb6, 0xcae, 0xca4, 0xc9c, 0xc92, 0xc8a, 0xc82, + 0xc78, 0xc70, 0xc68, 0xc60, 0xc56, 0xc4e, 0xc46, 0xc3c, 0xc34, 0xc2c, 0xc24, 0xc1c, 0xc12, + 0xc0a, 0xc02, 0xbfa, 0xbf2, 0xbea, 0xbe0, 0xbd8, 0xbd0, 0xbc8, 0xbc0, 0xbb8, 0xbb0, 0xba8, + 0xba0, 0xb98, 0xb90, 0xb88, 0xb80, 0xb78, 0xb70, 0xb68, 0xb60, 0xb58, 0xb50, 0xb48, 0xb40, + 0xb38, 0xb32, 0xb2a, 0xb22, 0xb1a, 0xb12, 0xb0a, 0xb02, 0xafc, 0xaf4, 0xaec, 0xae4, 0xade, + 0xad6, 0xace, 0xac6, 0xac0, 0xab8, 0xab0, 0xaa8, 0xaa2, 0xa9a, 0xa92, 0xa8c, 0xa84, 0xa7c, + 0xa76, 0xa6e, 0xa68, 0xa60, 0xa58, 0xa52, 0xa4a, 0xa44, 0xa3c, 0xa36, 0xa2e, 0xa28, 0xa20, + 0xa18, 0xa12, 0xa0c, 0xa04, 0x9fe, 0x9f6, 0x9f0, 0x9e8, 0x9e2, 0x9da, 0x9d4, 0x9ce, 0x9c6, + 0x9c0, 0x9b8, 0x9b2, 0x9ac, 0x9a4, 0x99e, 0x998, 0x990, 0x98a, 0x984, 0x97c, 0x976, 0x970, + 0x96a, 0x962, 0x95c, 0x956, 0x950, 0x948, 0x942, 0x93c, 0x936, 0x930, 0x928, 0x922, 0x91c, + 0x916, 0x910, 0x90a, 0x904, 0x8fc, 0x8f6, 0x8f0, 0x8ea, 0x8e4, 0x8de, 0x8d8, 0x8d2, 0x8cc, + 0x8c6, 0x8c0, 0x8ba, 0x8b4, 0x8ae, 0x8a8, 0x8a2, 0x89c, 0x896, 0x890, 0x88a, 0x884, 0x87e, + 0x878, 0x872, 0x86c, 0x866, 0x860, 0x85a, 0x854, 0x850, 0x84a, 0x844, 0x83e, 0x838, 0x832, + 0x82c, 0x828, 0x822, 0x81c, 0x816, 0x810, 0x80c, 0x806, 0x800, +]; + +const MT: [u8; 16] = [1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 24, 24, 30, 30]; +const KSLROM: [u8; 16] = [ + 0, 32, 40, 45, 48, 51, 53, 55, 56, 58, 59, 60, 61, 62, 63, 64, +]; +const KSLSHIFT: [u8; 4] = [8, 1, 2, 0]; +const EG_INCSTEP: [[u8; 4]; 4] = [[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 1, 0]]; +const AD_SLOT: [i8; 0x20] = [ + 0, 1, 2, 3, 4, 5, -1, -1, 6, 7, 8, 9, 10, 11, -1, -1, 12, 13, 14, 15, 16, 17, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, +]; +const CH_SLOT: [usize; 18] = [ + 0, 1, 2, 6, 7, 8, 12, 13, 14, 18, 19, 20, 24, 25, 26, 30, 31, 32, +]; +#[derive(Clone, Copy, Debug)] +struct Slot { + channel: usize, + mod_idx: usize, + prout: i16, + eg_rout: u16, + eg_out: u16, + eg_gen: u8, + eg_ksl: u8, + eg_tl_ksl: u16, + eg_ks: u8, + // Per-eg_gen cached rate fields. Index into these by eg_gen (or 0 when in + // the key-on/release reset case). Refreshed by refresh_eg_rates whenever + // any contributing input changes (eg_ks, reg_ar/dr/rr, reg_type). + eg_rate_hi: [u8; 4], + eg_rate_lo: [u8; 4], + eg_rate_nonzero_mask: u8, + trem_enabled: bool, + reg_vib: u8, + reg_type: u8, + reg_ksr: u8, + reg_mult: u8, + reg_ksl: u8, + reg_tl: u8, + reg_ar: u8, + reg_dr: u8, + reg_sl: u8, + reg_rr: u8, + reg_wf: u8, + key: u8, + pg_reset: u32, + pg_phase: u32, + pg_inc: u32, + pg_inc_vib: [u32; 8], + pg_phase_out: u16, + slot_num: usize, +} + +impl Default for Slot { + fn default() -> Self { + Self { + channel: 0, + mod_idx: 72, + prout: 0, + eg_rout: 0, + eg_out: 0, + eg_gen: 0, + eg_ksl: 0, + eg_tl_ksl: 0, + eg_ks: 0, + eg_rate_hi: [0; 4], + eg_rate_lo: [0; 4], + eg_rate_nonzero_mask: 0, + trem_enabled: false, + reg_vib: 0, + reg_type: 0, + reg_ksr: 0, + reg_mult: 0, + reg_ksl: 0, + reg_tl: 0, + reg_ar: 0, + reg_dr: 0, + reg_sl: 0, + reg_rr: 0, + reg_wf: 0, + key: 0, + pg_reset: 0, + pg_phase: 0, + pg_inc: 0, + pg_inc_vib: [0; 8], + pg_phase_out: 0, + slot_num: 0, + } + } +} + +#[derive(Clone, Copy, Debug)] +struct Channel { + slotz: [usize; 2], + pair: Option, + out: [usize; 4], + chtype: u8, + f_num: u16, + block: u8, + fb: u8, + con: u8, + alg: u8, + ksv: u8, + cha: u16, + chb: u16, + chc: u16, + chd: u16, + mix_mask: u8, + leftpan: i32, + rightpan: i32, + ch_num: usize, +} + +impl Default for Channel { + fn default() -> Self { + Self { + slotz: [0, 0], + pair: None, + out: [72; 4], + chtype: CH_2OP, + f_num: 0, + block: 0, + fb: 0, + con: 0, + alg: 0, + ksv: 0, + cha: 0, + chb: 0, + chc: 0, + chd: 0, + mix_mask: 0, + leftpan: 0, + rightpan: 0, + ch_num: 0, + } + } +} + +#[derive(Clone, Copy, Debug, Default)] +struct WriteBuf { + time: u64, + reg: u16, + data: u8, +} + +#[derive(Clone, Debug)] +pub(crate) struct Chip { + channels: [Channel; 18], + slots: [Slot; 36], + outputs: [i16; 74], + timer: u16, + eg_timer: u64, + eg_timerrem: u8, + eg_state: u8, + eg_add: u8, + eg_timer_lo: u8, + newm: u8, + nts: u8, + rhy: u8, + vibpos: u8, + vibshift: u8, + tremolo: u8, + tremolopos: u8, + tremoloshift: u8, + noise: u32, + noise_hh: u8, + noise_sd: u8, + mixbuff: [i32; 4], + rm_hh_bit2: u8, + rm_hh_bit3: u8, + rm_hh_bit7: u8, + rm_hh_bit8: u8, + rm_tc_bit3: u8, + rm_tc_bit5: u8, + stereoext: u8, + rateratio: i32, + samplecnt: i32, + oldsamples: [i16; 4], + samples: [i16; 4], + writebuf_samplecnt: u64, + writebuf_cur: usize, + writebuf_last: usize, + writebuf_lasttime: u64, + writebuf: [WriteBuf; WRITEBUF_SIZE], +} + +impl Default for Chip { + fn default() -> Self { + Self { + channels: [Channel::default(); 18], + slots: [Slot::default(); 36], + outputs: [0; 74], + timer: 0, + eg_timer: 0, + eg_timerrem: 0, + eg_state: 0, + eg_add: 0, + eg_timer_lo: 0, + newm: 0, + nts: 0, + rhy: 0, + vibpos: 0, + vibshift: 0, + tremolo: 0, + tremolopos: 0, + tremoloshift: 0, + noise: 0, + noise_hh: 0, + noise_sd: 0, + mixbuff: [0; 4], + rm_hh_bit2: 0, + rm_hh_bit3: 0, + rm_hh_bit7: 0, + rm_hh_bit8: 0, + rm_tc_bit3: 0, + rm_tc_bit5: 0, + stereoext: 0, + rateratio: 0, + samplecnt: 0, + oldsamples: [0; 4], + samples: [0; 4], + writebuf_samplecnt: 0, + writebuf_cur: 0, + writebuf_last: 0, + writebuf_lasttime: 0, + writebuf: [WriteBuf::default(); WRITEBUF_SIZE], + } + } +} + +impl Chip { + pub(crate) fn new(sample_rate: u32) -> Self { + let mut chip = Self::default(); + chip.reset(sample_rate); + chip + } + + pub(crate) fn reset(&mut self, sample_rate: u32) { + *self = Self::default(); + + for slotnum in 0..36 { + self.slots[slotnum] = Slot { + eg_rout: 0x1ff, + eg_out: 0x1ff, + eg_gen: ENV_RELEASE, + slot_num: slotnum, + ..Slot::default() + }; + } + + for (channum, &local_ch_slot) in CH_SLOT.iter().enumerate() { + self.channels[channum] = Channel { + slotz: [local_ch_slot, local_ch_slot + 3], + pair: if (channum % 9) < 3 { + Some(channum + 3) + } else if (channum % 9) < 6 { + Some(channum - 3) + } else { + None + }, + chtype: CH_2OP, + cha: 0xffff, + chb: 0xffff, + mix_mask: 0x03, + leftpan: 0x10000, + rightpan: 0x10000, + ch_num: channum, + ..Channel::default() + }; + self.slots[local_ch_slot].channel = channum; + self.slots[local_ch_slot + 3].channel = channum; + self.channel_setup_alg(channum); + } + + self.noise = 1; + self.rateratio = ((sample_rate << RSM_FRAC) / NATIVE_RATE) as i32; + self.tremoloshift = 4; + self.vibshift = 1; + } + + pub(crate) fn generate(&mut self, buf: &mut [i16]) { + let mut samples = [0; 4]; + self.generate_4ch(&mut samples); + buf[0] = samples[0]; + buf[1] = samples[1]; + } + + pub(crate) fn generate_resampled(&mut self, buf: &mut [i16]) { + let mut samples = [0; 4]; + self.generate_4ch_resampled(&mut samples); + buf[0] = samples[0]; + buf[1] = samples[1]; + } + + pub(crate) fn generate_stream(&mut self, buf: &mut [i16], numsamples: usize) { + for frame in buf.chunks_exact_mut(2).take(numsamples) { + self.generate_resampled(frame); + } + } + + pub(crate) fn generate_4ch(&mut self, buf4: &mut [i16]) { + buf4[1] = clip_sample(self.mixbuff[1]); + buf4[3] = clip_sample(self.mixbuff[3]); + + if CHANNEL_SAMPLE_DELAY { + for slot in 0..15 { + self.process_slot(slot); + } + + let mix = self.mix(false); + self.mixbuff[0] = mix[0]; + self.mixbuff[2] = mix[1]; + + for slot in 15..18 { + self.process_slot(slot); + } + + buf4[0] = clip_sample(self.mixbuff[0]); + buf4[2] = clip_sample(self.mixbuff[2]); + + for slot in 18..33 { + self.process_slot(slot); + } + + let mix = self.mix(true); + self.mixbuff[1] = mix[0]; + self.mixbuff[3] = mix[1]; + + for slot in 33..36 { + self.process_slot(slot); + } + } else { + for slot in 0..36 { + self.process_slot(slot); + } + + let mix = self.mix(false); + self.mixbuff[0] = mix[0]; + self.mixbuff[2] = mix[1]; + + buf4[0] = clip_sample(self.mixbuff[0]); + buf4[2] = clip_sample(self.mixbuff[2]); + + let mix = self.mix(true); + self.mixbuff[1] = mix[0]; + self.mixbuff[3] = mix[1]; + } + + self.update_timers_and_lfo(); + self.drain_writebuf(); + } + + pub(crate) fn generate_4ch_resampled(&mut self, buf4: &mut [i16]) { + while self.samplecnt >= self.rateratio { + self.oldsamples = self.samples; + let mut samples = [0; 4]; + self.generate_4ch(&mut samples); + self.samples = samples; + self.samplecnt -= self.rateratio; + } + + for (ii, out) in buf4.iter_mut().enumerate() { + *out = ((self.oldsamples[ii] as i32 * (self.rateratio - self.samplecnt) + + self.samples[ii] as i32 * self.samplecnt) + / self.rateratio) as i16; + } + self.samplecnt += 1 << RSM_FRAC; + } + + pub(crate) fn generate_4ch_stream( + &mut self, + buf1: &mut [i16], + buf2: &mut [i16], + numsamples: usize, + ) { + let mut samples = [0; 4]; + for frame in 0..numsamples { + self.generate_4ch_resampled(&mut samples); + let idx = frame * 2; + buf1[idx] = samples[0]; + buf1[idx + 1] = samples[1]; + buf2[idx] = samples[2]; + buf2[idx + 1] = samples[3]; + } + } + + pub(crate) fn active_voice_count(&self) -> usize { + self.slots[..36] + .iter() + .filter(|slot| !(slot.key == 0 && slot.eg_rout == 0x1ff && slot.eg_gen == ENV_RELEASE)) + .count() + } + + pub(crate) fn write_reg_buffered(&mut self, reg: u16, data: u8) { + let writebuf_last = self.writebuf_last; + + if (self.writebuf[writebuf_last].reg & 0x200) != 0 { + let reg = self.writebuf[writebuf_last].reg & 0x1ff; + let data = self.writebuf[writebuf_last].data; + let time = self.writebuf[writebuf_last].time; + self.write_reg(reg, data); + self.writebuf_cur = (writebuf_last + 1) % WRITEBUF_SIZE; + self.writebuf_samplecnt = time; + } + + self.writebuf[writebuf_last].reg = reg | 0x200; + self.writebuf[writebuf_last].data = data; + let mut time = self.writebuf_lasttime.wrapping_add(WRITEBUF_DELAY); + if time < self.writebuf_samplecnt { + time = self.writebuf_samplecnt; + } + + self.writebuf[writebuf_last].time = time; + self.writebuf_lasttime = time; + self.writebuf_last = (writebuf_last + 1) % WRITEBUF_SIZE; + } + + pub(crate) fn write_reg(&mut self, reg: u16, value: u8) { + let high = ((reg >> 8) & 0x01) as usize; + let regm = (reg & 0xff) as u8; + + match regm & 0xf0 { + 0x00 => { + if high != 0 { + match regm & 0x0f { + 0x04 => self.channel_set_4op(value), + 0x05 => { + self.newm = value & 0x01; + if false { + self.stereoext = (value >> 1) & 0x01; + } + } + _ => {} + } + } else if (regm & 0x0f) == 0x08 { + self.nts = (value >> 6) & 0x01; + } + } + 0x20 | 0x30 => { + if let Some(slot) = decoded_slot(high, regm) { + self.slot_write_20(slot, value); + } + } + 0x40 | 0x50 => { + if let Some(slot) = decoded_slot(high, regm) { + self.slot_write_40(slot, value); + } + } + 0x60 | 0x70 => { + if let Some(slot) = decoded_slot(high, regm) { + self.slot_write_60(slot, value); + } + } + 0x80 | 0x90 => { + if let Some(slot) = decoded_slot(high, regm) { + self.slot_write_80(slot, value); + } + } + 0xe0 | 0xf0 => { + if let Some(slot) = decoded_slot(high, regm) { + self.slot_write_e0(slot, value); + } + } + 0xa0 => { + if (regm & 0x0f) < 9 { + self.channel_write_a0(9 * high + (regm & 0x0f) as usize, value); + } + } + 0xb0 => { + if regm == 0xbd && high == 0 { + self.tremoloshift = (((value >> 7) ^ 1) << 1) + 2; + let vibshift = ((value >> 6) & 0x01) ^ 1; + if self.vibshift != vibshift { + self.vibshift = vibshift; + for ii in 0..36 { + self.phase_update_inc(ii); + } + } + self.channel_update_rhythm(value); + } else if (regm & 0x0f) < 9 { + let channel = 9 * high + (regm & 0x0f) as usize; + self.channel_write_b0(channel, value); + if (value & 0x20) != 0 { + self.channel_key_on(channel); + } else { + self.channel_key_off(channel); + } + } + } + 0xc0 => { + if (regm & 0x0f) < 9 { + self.channel_write_c0(9 * high + (regm & 0x0f) as usize, value); + } + } + 0xd0 if false && (regm & 0x0f) < 9 => { + self.channel_write_d0(9 * high + (regm & 0x0f) as usize, value); + } + _ => {} + } + } + + fn process_slot(&mut self, slot: usize) { + self.slot_calc_fb(slot); + + // Two fast paths skip the full envelope_calc + phase_generate work: + // + // * Dead-slot path: key off and eg_rout already at full attenuation. + // * Sustain-rate-zero: key on, in sustain phase, with the cached sustain + // rate equal to zero (the common "hold forever" case). + // + // Both still need slot_calc_fb above and slot_generate below so the + // waveform's sign bit can flip slot.out to -1 even at full attenuation + // (used as a modulator). Rhythm slots 13/16/17 are excluded so their + // rm_hh_bit*/rm_tc_bit* updates and rhythm-mode phase overrides keep + // running. + let slot_num = self.slots[slot].slot_num; + let is_rhythm = matches!(slot_num, 13 | 16 | 17); + if !is_rhythm { + let key = self.slots[slot].key; + let eg_rout = self.slots[slot].eg_rout; + let eg_gen = self.slots[slot].eg_gen; + let dead = key == 0 && eg_rout == 0x1ff; + let sustain_zero = key != 0 + && eg_gen == ENV_SUSTAIN + && (self.slots[slot].eg_rate_nonzero_mask & (1 << ENV_SUSTAIN)) == 0; + + if dead || sustain_zero { + // Mirror envelope_calc's tail: a key-off forces eg_gen back to + // RELEASE. Without this the next key-on can't tell that the + // slot is fully released and skips the attack-reset branch. + if dead { + self.slots[slot].eg_gen = ENV_RELEASE; + } + // Mirror the eg_off clamp in envelope_calc so eg_rout is held + // at 0x1ff once any of bits 3..8 latch high (and we're not in + // attack, where the clamp is suppressed). + if self.slots[slot].eg_gen != ENV_ATTACK && (eg_rout & 0x1f8) == 0x1f8 { + self.slots[slot].eg_rout = 0x1ff; + } + let trem = if self.slots[slot].trem_enabled { + self.tremolo + } else { + 0 + }; + self.slots[slot].eg_out = + self.slots[slot].eg_rout + self.slots[slot].eg_tl_ksl + u16::from(trem); + self.slots[slot].pg_reset = 0; + + if self.slots[slot].reg_vib == 0 { + let phase = (self.slots[slot].pg_phase >> 9) as u16; + self.slots[slot].pg_phase_out = phase; + self.slots[slot].pg_phase = self.slots[slot] + .pg_phase + .wrapping_add(self.slots[slot].pg_inc); + } else { + // Vibrato is rare for held notes; fall through to the + // standard phase generator. + self.phase_generate(slot); + } + + // On the dead path, eg_rout was 0x1ff so eg_out is also + // >= 0x1ff and the silent-regime shortcut applies. On the + // sustain-zero path, eg_rout sits wherever sustain landed, + // so the full path is needed. + if dead { + self.slot_generate_silent(slot); + } else { + self.slot_generate(slot); + } + return; + } + } + + self.envelope_calc(slot); + self.phase_generate(slot); + self.slot_generate(slot); + } + + #[inline(always)] + fn slot_calc_fb(&mut self, slot: usize) { + let channel = self.slots[slot].channel; + let fb = self.channels[channel].fb; + self.outputs[slot * 2 + 1] = if fb != 0 { + (self.slots[slot].prout.wrapping_add(self.outputs[slot * 2])) >> (0x09 - fb) + } else { + 0 + }; + self.slots[slot].prout = self.outputs[slot * 2]; + } + + fn envelope_calc(&mut self, slot: usize) { + let trem = if self.slots[slot].trem_enabled { + self.tremolo + } else { + 0 + }; + + self.slots[slot].eg_out = + self.slots[slot].eg_rout + self.slots[slot].eg_tl_ksl + trem as u16; + + let mut reset = 0; + // Pick the rate cache slot. The key-on/release reset case reuses the + // attack rate (index 0), matching the original branch in the C code. + let rate_idx = if self.slots[slot].key != 0 && self.slots[slot].eg_gen == ENV_RELEASE { + reset = 1; + 0 + } else { + (self.slots[slot].eg_gen & 0x03) as usize + }; + self.slots[slot].pg_reset = reset; + + let rate_hi = self.slots[slot].eg_rate_hi[rate_idx]; + let rate_lo = self.slots[slot].eg_rate_lo[rate_idx]; + let nonzero = ((self.slots[slot].eg_rate_nonzero_mask >> rate_idx) & 1) != 0; + + let eg_shift = rate_hi + self.eg_add; + let mut shift = 0; + if nonzero { + if rate_hi < 12 { + if self.eg_state != 0 { + shift = match eg_shift { + 12 => 1, + 13 => (rate_lo >> 1) & 0x01, + 14 => rate_lo & 0x01, + _ => 0, + }; + } + } else { + shift = (rate_hi & 0x03) + EG_INCSTEP[rate_lo as usize][(self.timer & 3) as usize]; + if (shift & 0x04) != 0 { + shift = 0x03; + } + if shift == 0 { + shift = self.eg_state; + } + } + } + + let mut eg_rout = self.slots[slot].eg_rout; + let mut eg_inc: i32 = 0; + let eg_off = (self.slots[slot].eg_rout & 0x1f8) == 0x1f8; + + if reset != 0 && rate_hi == 0x0f { + eg_rout = 0; + } + if self.slots[slot].eg_gen != ENV_ATTACK && reset == 0 && eg_off { + eg_rout = 0x1ff; + } + + match self.slots[slot].eg_gen { + ENV_ATTACK => { + if self.slots[slot].eg_rout == 0 { + self.slots[slot].eg_gen = ENV_DECAY; + } else if self.slots[slot].key != 0 && shift > 0 && rate_hi != 0x0f { + eg_inc = (!(self.slots[slot].eg_rout as i32)) >> (4 - shift); + } + } + ENV_DECAY => { + if (self.slots[slot].eg_rout >> 4) == self.slots[slot].reg_sl as u16 { + self.slots[slot].eg_gen = ENV_SUSTAIN; + } else if !eg_off && reset == 0 && shift > 0 { + eg_inc = 1 << (shift - 1); + } + } + ENV_SUSTAIN | ENV_RELEASE if !eg_off && reset == 0 && shift > 0 => { + eg_inc = 1 << (shift - 1); + } + _ => {} + } + + self.slots[slot].eg_rout = ((eg_rout as i32 + eg_inc) & 0x1ff) as u16; + if reset != 0 { + self.slots[slot].eg_gen = ENV_ATTACK; + } + if self.slots[slot].key == 0 { + self.slots[slot].eg_gen = ENV_RELEASE; + } + } + + fn phase_generate(&mut self, slot: usize) { + let phase_delta = if self.slots[slot].reg_vib != 0 { + self.slots[slot].pg_inc_vib[self.vibpos as usize] + } else { + self.slots[slot].pg_inc + }; + + let phase = (self.slots[slot].pg_phase >> 9) as u16; + if self.slots[slot].pg_reset != 0 { + self.slots[slot].pg_phase = 0; + } + self.slots[slot].pg_phase = self.slots[slot].pg_phase.wrapping_add(phase_delta); + + let rhy_enabled = (self.rhy & 0x20) != 0; + self.slots[slot].pg_phase_out = phase; + match self.slots[slot].slot_num { + 13 => { + self.rm_hh_bit2 = ((phase >> 2) & 1) as u8; + self.rm_hh_bit3 = ((phase >> 3) & 1) as u8; + self.rm_hh_bit7 = ((phase >> 7) & 1) as u8; + self.rm_hh_bit8 = ((phase >> 8) & 1) as u8; + if rhy_enabled { + let rm_xor = (self.rm_hh_bit2 ^ self.rm_hh_bit7) + | (self.rm_hh_bit3 ^ self.rm_tc_bit5) + | (self.rm_tc_bit3 ^ self.rm_tc_bit5); + self.slots[slot].pg_phase_out = (rm_xor as u16) << 9; + if (rm_xor ^ (self.noise & 1) as u8) != 0 { + self.slots[slot].pg_phase_out |= 0xd0; + } else { + self.slots[slot].pg_phase_out |= 0x34; + } + } + } + 16 => { + if rhy_enabled { + self.slots[slot].pg_phase_out = ((self.rm_hh_bit8 as u16) << 9) + | (((self.rm_hh_bit8 ^ (self.noise & 1) as u8) as u16) << 8); + } + } + 17 if rhy_enabled => { + self.rm_tc_bit3 = ((phase >> 3) & 1) as u8; + self.rm_tc_bit5 = ((phase >> 5) & 1) as u8; + let rm_xor = (self.rm_hh_bit2 ^ self.rm_hh_bit7) + | (self.rm_hh_bit3 ^ self.rm_tc_bit5) + | (self.rm_tc_bit3 ^ self.rm_tc_bit5); + self.slots[slot].pg_phase_out = ((rm_xor as u16) << 9) | 0x80; + } + _ => {} + } + let noise = self.noise; + let n_bit = ((noise >> 14) ^ noise) & 1; + self.noise = (noise >> 1) | (n_bit << 22); + } + + fn slot_generate(&mut self, slot: usize) { + let mod_value = self.outputs[self.slots[slot].mod_idx]; + let phase = (self.slots[slot].pg_phase_out as i32 + mod_value as i32) as u16; + self.outputs[slot * 2] = + envelope_calc_sin(self.slots[slot].reg_wf, phase, self.slots[slot].eg_out); + } + + /// Silent-regime variant of slot_generate. When the caller has proven + /// eg_out >= 0x180, the post-clamp exprom lookup in envelope_calc_exp + /// is shifted right by at least 12 bits. The exprom max value is + /// 0xff4, so the result is always 0 and the final output reduces to + /// just the sign bit of the WF_ROM entry. Verified bit-exact across + /// all 8 waveforms and all phases against the full path. + fn slot_generate_silent(&mut self, slot: usize) { + let mod_value = self.outputs[self.slots[slot].mod_idx]; + let phase = (self.slots[slot].pg_phase_out as i32 + mod_value as i32) as u16; + let idx = (((self.slots[slot].reg_wf & 0x07) as usize) << 10) | ((phase & 0x3ff) as usize); + self.outputs[slot * 2] = (WF_ROM[idx] as i16) >> 15; + } + + fn mix(&self, right: bool) -> [i32; 2] { + let mut mix = [0, 0]; + let active_bit = if right { 0x02 } else { 0x01 }; + for channel in &self.channels { + if (channel.mix_mask & active_bit) == 0 { + continue; + } + + let sum = self.outputs[channel.out[0]] as i32 + + self.outputs[channel.out[1]] as i32 + + self.outputs[channel.out[2]] as i32 + + self.outputs[channel.out[3]] as i32; + let accm = sum as i16; + let main = if false { + let pan = if right { + channel.rightpan + } else { + channel.leftpan + }; + ((accm as i32).wrapping_mul(pan) >> 16) as i16 + } else { + let main_mask = if right { channel.chb } else { channel.cha }; + masked_accm(accm, main_mask) + }; + let rear_mask = if right { channel.chd } else { channel.chc }; + mix[0] += main as i32; + mix[1] += masked_accm(accm, rear_mask) as i32; + } + mix + } + + fn update_timers_and_lfo(&mut self) { + if (self.timer & 0x3f) == 0x3f { + self.tremolopos = (self.tremolopos + 1) % 210; + } + self.tremolo = if self.tremolopos < 105 { + self.tremolopos >> self.tremoloshift + } else { + (210 - self.tremolopos) >> self.tremoloshift + }; + + if (self.timer & 0x3ff) == 0x3ff { + self.vibpos = (self.vibpos + 1) & 7; + } + + self.timer = self.timer.wrapping_add(1); + + { + // Same shape as the C session-6 ctz path: only the low 13 bits + // matter, narrowed to u32 so trailing_zeros maps to a single x86 + // bsf/tzcnt. eg_add stays 0 when those bits are all zero (matches + // the original "shift > 12" guard). + let masked = (self.eg_timer & 0x1fff) as u32; + self.eg_add = if masked == 0 { + 0 + } else { + (masked.trailing_zeros() + 1) as u8 + }; + self.eg_timer_lo = (self.eg_timer & 0x3) as u8; + } + + if self.eg_timerrem != 0 || self.eg_state != 0 { + if self.eg_timer == 0xfffffffff { + self.eg_timer = 0; + self.eg_timerrem = 1; + } else { + self.eg_timer += 1; + self.eg_timerrem = 0; + } + } + + self.eg_state ^= 1; + } + + fn drain_writebuf(&mut self) { + loop { + let entry = self.writebuf[self.writebuf_cur]; + if entry.time > self.writebuf_samplecnt || (entry.reg & 0x200) == 0 { + break; + } + self.writebuf[self.writebuf_cur].reg &= 0x1ff; + self.write_reg(entry.reg & 0x1ff, entry.data); + self.writebuf_cur = (self.writebuf_cur + 1) % WRITEBUF_SIZE; + } + self.writebuf_samplecnt = self.writebuf_samplecnt.wrapping_add(1); + } + + fn slot_write_20(&mut self, slot: usize, data: u8) { + self.slots[slot].trem_enabled = ((data >> 7) & 0x01) != 0; + self.slots[slot].reg_vib = (data >> 6) & 0x01; + self.slots[slot].reg_type = (data >> 5) & 0x01; + self.slots[slot].reg_ksr = (data >> 4) & 0x01; + self.slots[slot].reg_mult = data & 0x0f; + self.envelope_update_rate(slot); + self.phase_update_inc(slot); + } + + fn slot_write_40(&mut self, slot: usize, data: u8) { + self.slots[slot].reg_ksl = (data >> 6) & 0x03; + self.slots[slot].reg_tl = data & 0x3f; + self.envelope_update_ksl(slot); + } + + fn slot_write_60(&mut self, slot: usize, data: u8) { + self.slots[slot].reg_ar = (data >> 4) & 0x0f; + self.slots[slot].reg_dr = data & 0x0f; + self.refresh_eg_rates(slot); + } + + fn slot_write_80(&mut self, slot: usize, data: u8) { + self.slots[slot].reg_sl = (data >> 4) & 0x0f; + if self.slots[slot].reg_sl == 0x0f { + self.slots[slot].reg_sl = 0x1f; + } + self.slots[slot].reg_rr = data & 0x0f; + self.refresh_eg_rates(slot); + } + + fn slot_write_e0(&mut self, slot: usize, data: u8) { + self.slots[slot].reg_wf = data & 0x07; + if self.newm == 0 { + self.slots[slot].reg_wf &= 0x03; + } + } + + fn envelope_update_ksl(&mut self, slot: usize) { + let channel = self.slots[slot].channel; + let mut ksl = ((KSLROM[(self.channels[channel].f_num >> 6) as usize] as i16) << 2) + - (((0x08 - self.channels[channel].block) as i16) << 5); + if ksl < 0 { + ksl = 0; + } + self.slots[slot].eg_ksl = ksl as u8; + self.slots[slot].eg_tl_ksl = ((self.slots[slot].reg_tl as u16) << 2) + + ((self.slots[slot].eg_ksl as u16) >> KSLSHIFT[self.slots[slot].reg_ksl as usize]); + } + + fn envelope_update_rate(&mut self, slot: usize) { + let channel = self.slots[slot].channel; + self.slots[slot].eg_ks = + self.channels[channel].ksv >> ((self.slots[slot].reg_ksr ^ 1) << 1); + self.refresh_eg_rates(slot); + } + + fn refresh_eg_rates(&mut self, slot: usize) { + let s = &mut self.slots[slot]; + let ks = s.eg_ks; + let mut nz_mask: u8 = 0; + for idx in 0..4 { + // Mirror the per-state reg_rate selection used by envelope_calc. + let reg_rate = match idx { + // ENV_ATTACK (also reused for the key-on/release reset case) + 0 => s.reg_ar, + // ENV_DECAY + 1 => s.reg_dr, + // ENV_SUSTAIN: percussive types hold at 0 instead of releasing + 2 => { + if s.reg_type == 0 { + s.reg_rr + } else { + 0 + } + } + // ENV_RELEASE + _ => s.reg_rr, + }; + let rate = ks + (reg_rate << 2); + let mut rate_hi = rate >> 2; + if (rate_hi & 0x10) != 0 { + rate_hi = 0x0f; + } + s.eg_rate_hi[idx] = rate_hi; + s.eg_rate_lo[idx] = rate & 0x03; + if reg_rate != 0 { + nz_mask |= 1 << idx; + } + } + s.eg_rate_nonzero_mask = nz_mask; + } + + fn phase_update_inc(&mut self, slot: usize) { + let channel = self.slots[slot].channel; + let basefreq = ((self.channels[channel].f_num as u32) << self.channels[channel].block) >> 1; + self.slots[slot].pg_inc = (basefreq * MT[self.slots[slot].reg_mult as usize] as u32) >> 1; + + let reg_mult = self.slots[slot].reg_mult as usize; + let block = self.channels[channel].block; + for vibpos in 0..8 { + let mut f_num = self.channels[channel].f_num; + let mut range = ((f_num >> 7) & 7) as i8; + if (vibpos & 3) == 0 { + range = 0; + } else if (vibpos & 1) != 0 { + range >>= 1; + } + range >>= self.vibshift; + if (vibpos & 4) != 0 { + range = -range; + } + f_num = (f_num as i32 + range as i32) as u16; + let basefreq_vib = ((f_num as u32) << block) >> 1; + self.slots[slot].pg_inc_vib[vibpos] = (basefreq_vib * MT[reg_mult] as u32) >> 1; + } + } + + fn envelope_key_on(&mut self, slot: usize, key_type: u8) { + self.slots[slot].key |= key_type; + } + + fn envelope_key_off(&mut self, slot: usize, key_type: u8) { + self.slots[slot].key &= !key_type; + } + + fn channel_update_rhythm(&mut self, data: u8) { + self.rhy = data & 0x3f; + if (self.rhy & 0x20) != 0 { + self.channels[6].out = [ + self.channels[6].slotz[1] * 2, + self.channels[6].slotz[1] * 2, + 72, + 72, + ]; + self.channels[7].out = [ + self.channels[7].slotz[0] * 2, + self.channels[7].slotz[0] * 2, + self.channels[7].slotz[1] * 2, + self.channels[7].slotz[1] * 2, + ]; + self.channels[8].out = [ + self.channels[8].slotz[0] * 2, + self.channels[8].slotz[0] * 2, + self.channels[8].slotz[1] * 2, + self.channels[8].slotz[1] * 2, + ]; + for channel in 6..9 { + self.channels[channel].chtype = CH_DRUM; + } + for channel in 6..9 { + self.channel_setup_alg(channel); + } + + self.set_drum_key(7, 0, self.rhy & 0x01); + self.set_drum_key(8, 1, self.rhy & 0x02); + self.set_drum_key(8, 0, self.rhy & 0x04); + self.set_drum_key(7, 1, self.rhy & 0x08); + self.set_drum_key(6, 0, self.rhy & 0x10); + self.set_drum_key(6, 1, self.rhy & 0x10); + } else { + for channel in 6..9 { + self.channels[channel].chtype = CH_2OP; + self.channel_setup_alg(channel); + let slot0 = self.channels[channel].slotz[0]; + let slot1 = self.channels[channel].slotz[1]; + self.envelope_key_off(slot0, EGK_DRUM); + self.envelope_key_off(slot1, EGK_DRUM); + } + } + } + + fn set_drum_key(&mut self, channel: usize, slot_index: usize, mask: u8) { + let slot = self.channels[channel].slotz[slot_index]; + if mask != 0 { + self.envelope_key_on(slot, EGK_DRUM); + } else { + self.envelope_key_off(slot, EGK_DRUM); + } + } + + fn channel_write_a0(&mut self, channel: usize, data: u8) { + if self.newm != 0 && self.channels[channel].chtype == CH_4OP2 { + return; + } + + self.channels[channel].f_num = (self.channels[channel].f_num & 0x300) | data as u16; + self.channels[channel].ksv = (self.channels[channel].block << 1) + | ((self.channels[channel].f_num >> (0x09 - self.nts)) as u8 & 0x01); + self.update_channel_slots_frequency_dependent(channel); + + if self.newm != 0 && self.channels[channel].chtype == CH_4OP { + let pair = self.channels[channel].pair.unwrap(); + self.channels[pair].f_num = self.channels[channel].f_num; + self.channels[pair].ksv = self.channels[channel].ksv; + self.update_channel_slots_frequency_dependent(pair); + } + } + + fn channel_write_b0(&mut self, channel: usize, data: u8) { + if self.newm != 0 && self.channels[channel].chtype == CH_4OP2 { + return; + } + + self.channels[channel].f_num = + (self.channels[channel].f_num & 0xff) | (((data & 0x03) as u16) << 8); + self.channels[channel].block = (data >> 2) & 0x07; + self.channels[channel].ksv = (self.channels[channel].block << 1) + | ((self.channels[channel].f_num >> (0x09 - self.nts)) as u8 & 0x01); + self.update_channel_slots_frequency_dependent(channel); + + if self.newm != 0 && self.channels[channel].chtype == CH_4OP { + let pair = self.channels[channel].pair.unwrap(); + self.channels[pair].f_num = self.channels[channel].f_num; + self.channels[pair].block = self.channels[channel].block; + self.channels[pair].ksv = self.channels[channel].ksv; + self.update_channel_slots_frequency_dependent(pair); + } + } + + fn update_channel_slots_frequency_dependent(&mut self, channel: usize) { + let slot0 = self.channels[channel].slotz[0]; + let slot1 = self.channels[channel].slotz[1]; + self.envelope_update_ksl(slot0); + self.envelope_update_ksl(slot1); + self.envelope_update_rate(slot0); + self.envelope_update_rate(slot1); + self.phase_update_inc(slot0); + self.phase_update_inc(slot1); + } + + fn channel_write_c0(&mut self, channel: usize, data: u8) { + self.channels[channel].fb = (data & 0x0e) >> 1; + self.channels[channel].con = data & 0x01; + self.channel_update_alg(channel); + + if self.newm != 0 { + self.channels[channel].cha = if ((data >> 4) & 0x01) != 0 { 0xffff } else { 0 }; + self.channels[channel].chb = if ((data >> 5) & 0x01) != 0 { 0xffff } else { 0 }; + self.channels[channel].chc = if ((data >> 6) & 0x01) != 0 { 0xffff } else { 0 }; + self.channels[channel].chd = if ((data >> 7) & 0x01) != 0 { 0xffff } else { 0 }; + } else { + self.channels[channel].cha = 0xffff; + self.channels[channel].chb = 0xffff; + self.channels[channel].chc = 0; + self.channels[channel].chd = 0; + } + + if false && self.stereoext == 0 { + self.channels[channel].leftpan = pan_from_channel_mask(self.channels[channel].cha); + self.channels[channel].rightpan = pan_from_channel_mask(self.channels[channel].chb); + } + self.refresh_channel_mix_mask(channel); + } + + fn channel_write_d0(&mut self, channel: usize, data: u8) { + if self.stereoext != 0 { + self.channels[channel].leftpan = panpot(data ^ 0xff); + self.channels[channel].rightpan = panpot(data); + self.refresh_channel_mix_mask(channel); + } + } + + fn refresh_channel_mix_mask(&mut self, channel: usize) { + let ch = &mut self.channels[channel]; + let left_active = if false { + ch.leftpan != 0 || ch.chc != 0 + } else { + ch.cha != 0 || ch.chc != 0 + }; + let right_active = if false { + ch.rightpan != 0 || ch.chd != 0 + } else { + ch.chb != 0 || ch.chd != 0 + }; + ch.mix_mask = u8::from(left_active) | (u8::from(right_active) << 1); + } + + fn channel_key_on(&mut self, channel: usize) { + if self.newm != 0 { + match self.channels[channel].chtype { + CH_4OP => { + let pair = self.channels[channel].pair.unwrap(); + self.key_channel_slots(channel, true, EGK_NORM); + self.key_channel_slots(pair, true, EGK_NORM); + } + CH_2OP | CH_DRUM => self.key_channel_slots(channel, true, EGK_NORM), + _ => {} + } + } else { + self.key_channel_slots(channel, true, EGK_NORM); + } + } + + fn channel_key_off(&mut self, channel: usize) { + if self.newm != 0 { + match self.channels[channel].chtype { + CH_4OP => { + let pair = self.channels[channel].pair.unwrap(); + self.key_channel_slots(channel, false, EGK_NORM); + self.key_channel_slots(pair, false, EGK_NORM); + } + CH_2OP | CH_DRUM => self.key_channel_slots(channel, false, EGK_NORM), + _ => {} + } + } else { + self.key_channel_slots(channel, false, EGK_NORM); + } + } + + fn key_channel_slots(&mut self, channel: usize, on: bool, key_type: u8) { + let slot0 = self.channels[channel].slotz[0]; + let slot1 = self.channels[channel].slotz[1]; + if on { + self.envelope_key_on(slot0, key_type); + self.envelope_key_on(slot1, key_type); + } else { + self.envelope_key_off(slot0, key_type); + self.envelope_key_off(slot1, key_type); + } + } + + fn channel_set_4op(&mut self, data: u8) { + for bit in 0..6 { + let mut chnum = bit; + if bit >= 3 { + chnum += 9 - 3; + } + let chnum = chnum as usize; + if ((data >> bit) & 0x01) != 0 { + self.channels[chnum].chtype = CH_4OP; + self.channels[chnum + 3].chtype = CH_4OP2; + self.channel_update_alg(chnum); + } else { + self.channels[chnum].chtype = CH_2OP; + self.channels[chnum + 3].chtype = CH_2OP; + self.channel_update_alg(chnum); + self.channel_update_alg(chnum + 3); + } + } + } + + fn channel_update_alg(&mut self, channel: usize) { + self.channels[channel].alg = self.channels[channel].con; + if self.newm != 0 { + match self.channels[channel].chtype { + CH_4OP => { + let pair = self.channels[channel].pair.unwrap(); + self.channels[pair].alg = + 0x04 | (self.channels[channel].con << 1) | self.channels[pair].con; + self.channels[channel].alg = 0x08; + self.channel_setup_alg(pair); + } + CH_4OP2 => { + let pair = self.channels[channel].pair.unwrap(); + self.channels[channel].alg = + 0x04 | (self.channels[pair].con << 1) | self.channels[channel].con; + self.channels[pair].alg = 0x08; + self.channel_setup_alg(channel); + } + _ => self.channel_setup_alg(channel), + } + } else { + self.channel_setup_alg(channel); + } + } + + fn channel_setup_alg(&mut self, channel: usize) { + let slot0 = self.channels[channel].slotz[0]; + let slot1 = self.channels[channel].slotz[1]; + + if self.channels[channel].chtype == CH_DRUM { + if self.channels[channel].ch_num == 7 || self.channels[channel].ch_num == 8 { + self.slots[slot0].mod_idx = 72; + self.slots[slot1].mod_idx = 72; + return; + } + match self.channels[channel].alg & 0x01 { + 0x00 => { + self.slots[slot0].mod_idx = slot0 * 2 + 1; + self.slots[slot1].mod_idx = slot0 * 2; + } + 0x01 => { + self.slots[slot0].mod_idx = slot0 * 2 + 1; + self.slots[slot1].mod_idx = 72; + } + _ => {} + } + return; + } + + if (self.channels[channel].alg & 0x08) != 0 { + return; + } + + if (self.channels[channel].alg & 0x04) != 0 { + let pair = self.channels[channel].pair.unwrap(); + let pslot0 = self.channels[pair].slotz[0]; + let pslot1 = self.channels[pair].slotz[1]; + // Pair becomes the muted secondary in a 4-op voice; clear its + // outputs and the matching count so the mix loop skips it. + self.channels[pair].out = [72; 4]; + match self.channels[channel].alg & 0x03 { + 0x00 => { + self.slots[pslot0].mod_idx = pslot0 * 2 + 1; + self.slots[pslot1].mod_idx = pslot0 * 2; + self.slots[slot0].mod_idx = pslot1 * 2; + self.slots[slot1].mod_idx = slot0 * 2; + self.channels[channel].out = [slot1 * 2, 72, 72, 72]; + } + 0x01 => { + self.slots[pslot0].mod_idx = pslot0 * 2 + 1; + self.slots[pslot1].mod_idx = pslot0 * 2; + self.slots[slot0].mod_idx = 72; + self.slots[slot1].mod_idx = slot0 * 2; + self.channels[channel].out = [pslot1 * 2, slot1 * 2, 72, 72]; + } + 0x02 => { + self.slots[pslot0].mod_idx = pslot0 * 2 + 1; + self.slots[pslot1].mod_idx = 72; + self.slots[slot0].mod_idx = pslot1 * 2; + self.slots[slot1].mod_idx = slot0 * 2; + self.channels[channel].out = [pslot0 * 2, slot1 * 2, 72, 72]; + } + 0x03 => { + self.slots[pslot0].mod_idx = pslot0 * 2 + 1; + self.slots[pslot1].mod_idx = 72; + self.slots[slot0].mod_idx = pslot1 * 2; + self.slots[slot1].mod_idx = 72; + self.channels[channel].out = [pslot0 * 2, slot0 * 2, slot1 * 2, 72]; + } + _ => {} + } + } else { + match self.channels[channel].alg & 0x01 { + 0x00 => { + self.slots[slot0].mod_idx = slot0 * 2 + 1; + self.slots[slot1].mod_idx = slot0 * 2; + self.channels[channel].out = [slot1 * 2, 72, 72, 72]; + } + 0x01 => { + self.slots[slot0].mod_idx = slot0 * 2 + 1; + self.slots[slot1].mod_idx = 72; + self.channels[channel].out = [slot0 * 2, slot1 * 2, 72, 72]; + } + _ => {} + } + } + } +} + +fn decoded_slot(high: usize, regm: u8) -> Option { + let decoded = AD_SLOT[(regm & 0x1f) as usize]; + (decoded >= 0).then(|| 18 * high + decoded as usize) +} + +fn clip_sample(sample: i32) -> i16 { + sample.clamp(-32768, 32767) as i16 +} + +fn masked_accm(accm: i16, mask: u16) -> i16 { + ((accm as i32) & mask as i32) as i16 +} + +fn pan_from_channel_mask(mask: u16) -> i32 { + ((mask as u32) << 16) as i32 +} + +fn panpot(value: u8) -> i32 { + ((value as f64 * std::f64::consts::PI / 512.0).sin() * 65536.0) as i32 +} + +fn envelope_calc_exp(mut level: u32) -> i16 { + if level > 0x1fff { + level = 0x1fff; + } + ((EXPROM[(level & 0xff) as usize] as u32) >> (level >> 8)) as i16 +} + +// Unified waveform LUT: for each (waveform, phase & 0x3ff) it stores a 16-bit +// entry whose top bit is the sign-flip mask and whose low 15 bits are the +// logsin-domain addend that gets fed into envelope_calc_exp. This collapses the +// eight per-waveform branches plus their internal sub-branches into a single +// indexed load. +const WF_ROM: [u16; 8 * 1024] = build_wf_rom(); + +const fn build_wf_rom() -> [u16; 8 * 1024] { + let mut table = [0u16; 8 * 1024]; + let mut wf: usize = 0; + while wf < 8 { + let mut phase: u16 = 0; + while phase < 1024 { + let (out, neg) = wf_entry(wf as u8, phase); + table[wf * 1024 + phase as usize] = ((neg as u16) << 15) | (out & 0x7fff); + phase += 1; + } + wf += 1; + } + table +} + +const fn wf_entry(wf: u8, phase: u16) -> (u16, bool) { + let phase = phase & 0x3ff; + match wf { + 0 => { + let neg = (phase & 0x200) != 0; + let out = if (phase & 0x100) != 0 { + LOGSINROM[((phase & 0xff) ^ 0xff) as usize] + } else { + LOGSINROM[(phase & 0xff) as usize] + }; + (out, neg) + } + 1 => { + let out = if (phase & 0x200) != 0 { + 0x1000 + } else if (phase & 0x100) != 0 { + LOGSINROM[((phase & 0xff) ^ 0xff) as usize] + } else { + LOGSINROM[(phase & 0xff) as usize] + }; + (out, false) + } + 2 => { + let out = if (phase & 0x100) != 0 { + LOGSINROM[((phase & 0xff) ^ 0xff) as usize] + } else { + LOGSINROM[(phase & 0xff) as usize] + }; + (out, false) + } + 3 => { + let out = if (phase & 0x100) != 0 { + 0x1000 + } else { + LOGSINROM[(phase & 0xff) as usize] + }; + (out, false) + } + 4 => { + let neg = (phase & 0x300) == 0x100; + let out = if (phase & 0x200) != 0 { + 0x1000 + } else if (phase & 0x80) != 0 { + LOGSINROM[(((phase ^ 0xff) << 1) & 0xff) as usize] + } else { + LOGSINROM[((phase << 1) & 0xff) as usize] + }; + (out, neg) + } + 5 => { + let out = if (phase & 0x200) != 0 { + 0x1000 + } else if (phase & 0x80) != 0 { + LOGSINROM[(((phase ^ 0xff) << 1) & 0xff) as usize] + } else { + LOGSINROM[((phase << 1) & 0xff) as usize] + }; + (out, false) + } + 6 => { + let neg = (phase & 0x200) != 0; + (0, neg) + } + _ => { + // wf = 7: triangle. Sign flips on the upper half, and the phase is + // mirrored into 0..=0x1ff before the << 3. + let neg = (phase & 0x200) != 0; + let inner = if neg { (phase & 0x1ff) ^ 0x1ff } else { phase }; + (inner << 3, neg) + } + } +} + +fn envelope_calc_sin(waveform: u8, phase: u16, envelope: u16) -> i16 { + let idx = (((waveform & 0x07) as usize) << 10) | ((phase & 0x3ff) as usize); + let entry = WF_ROM[idx]; + let out = (entry & 0x7fff) as u32; + let neg = if (entry & 0x8000) != 0 { 0xffffu16 } else { 0 }; + (envelope_calc_exp(out + ((envelope as u32) << 3)) as u16 ^ neg) as i16 +} diff --git a/src/cinematics.rs b/src/cinematics.rs new file mode 100644 index 00000000..50918d11 --- /dev/null +++ b/src/cinematics.rs @@ -0,0 +1,444 @@ +//! Checked original AGX cinematic deltas and a platform-independent 70 Hz player. +//! MDS catalog files are RIFF MIDI streams; they are not the movie format. +use crate::{ + assets::{Catalog, Sprite}, + audio::DigitalSample, + simulation::{LegacyRng, SoundEvent}, +}; +use anyhow::{Context, Result, ensure}; + +#[derive(Debug, Clone)] +pub struct DeltaFrame { + fill: Option, + spans: Vec<(usize, Vec)>, +} +impl DeltaFrame { + pub fn decode(bytes: &[u8], first: bool) -> Result { + let fill = if first { + Some(*bytes.first().context("missing cinematic fill byte")?) + } else { + None + }; + let mut offset = usize::from(first); + let mut spans = Vec::new(); + loop { + let header = bytes + .get(offset..offset + 8) + .context("truncated AGX span header")?; + offset += 8; + let read = |n: usize| u16::from_le_bytes([header[n], header[n + 1]]) as usize; + if read(0) == 0 { + break; + } + let position = read(4); + let length = read(6); + ensure!( + length > 0 + && position + .checked_add(length) + .is_some_and(|end| end <= 320 * 200), + "AGX span exceeds 320x200 canvas" + ); + let pixels = bytes + .get(offset..offset + length) + .context("truncated AGX span pixels")?; + offset += length; + spans.push((position, pixels.to_vec())); + ensure!(spans.len() <= 64000, "too many AGX spans"); + } + Ok(Self { fill, spans }) + } + pub fn apply(&self, canvas: &mut Sprite) -> Result<()> { + ensure!( + canvas.width == 320 && canvas.height == 200 && canvas.pixels.len() == 64000, + "AGX requires original 320x200 canvas" + ); + if let Some(fill) = self.fill { + canvas.pixels.fill(fill as u16); + } + for (start, pixels) in &self.spans { + for (destination, source) in canvas.pixels[*start..*start + pixels.len()] + .iter_mut() + .zip(pixels) + { + *destination = *source as u16; + } + } + Ok(()) + } +} +#[derive(Debug, Clone, Copy)] +pub enum Kind { + Intro, + Landing, + Death, + CampaignEnd(u8), +} +#[derive(Clone)] +struct ClipSpec { + name: &'static str, + count: u32, + dwell: u32, + repeats: u32, + fade_in: u32, + fade_out: u32, + fade_color: [u8; 3], + background: Option<&'static str>, +} +fn clip(name: &'static str, count: u32, dwell: u32, repeats: u32) -> ClipSpec { + ClipSpec { + name, + count, + dwell, + repeats, + fade_in: 0, + fade_out: 0, + fade_color: [0; 3], + background: None, + } +} +fn specs(kind: Kind) -> Vec { + match kind { + Kind::Intro => { + let mut city = clip("CHASE_AGX", 30, 8, 1); + city.fade_in = 128; + let mut side = clip("SHIPSD1_AGX", 20, 18, 2); + side.background = Some("FX_JETSND"); + let mut pilot = clip("PILOT_AGX", 21, 10, 1); + pilot.background = Some("FX_IJETSND"); + let mut side_before_fire = side.clone(); + side_before_fire.repeats = 1; + let mut firing = clip("SHIPSD2_AGX", 20, 18, 1); + firing.background = Some("FX_JETSND"); + let mut explosion = clip("EXPLO_AGX", 22, 12, 1); + explosion.background = Some("FX_EJETSND"); + explosion.fade_out = 60; + explosion.fade_color = [255, 113, 12]; + vec![city, side, pilot, side_before_fire, firing, explosion] + } + Kind::Landing => { + let mut landing = clip("LANDING_AGX", 33, 10, 1); + landing.fade_out = 64; + vec![landing] + } + Kind::Death => { + let mut ground = clip("SDEATH_AGX", 6, 3, 8); + ground.fade_out = 100; + vec![clip("DOWN_AGX", 30, 11, 1), ground] + } + Kind::CampaignEnd(sector) => { + let mut ending = match sector { + 0 => clip("GAME1END_AGX", 5, 4, 8), + 1 => clip("GAME2END_AGX", 25, 4, 1), + _ => clip("GAME3END_AGX", 39, 8, 1), + }; + ending.fade_out = 120; + if sector >= 2 { + ending.background = Some("FX_JETSND"); + } + let mut base = clip("BASE_AGX", 30, 10, 1); + base.fade_in = 128; + let mut clips = vec![ending, base]; + clips.extend(specs(Kind::Landing)); + clips + } + } +} +struct Clip { + spec: ClipSpec, + frames: Vec, + background: Option<(SoundEvent, u64)>, +} +#[derive(Clone, Copy)] +enum Phase { + FadeIn(u32), + Frame(u32), + FadeOut(u32), + Finished, +} +pub struct Cinematic { + pub image: Sprite, + pub sounds: Vec, + clips: Vec, + current: usize, + frame: usize, + repetition: u32, + phase: Phase, + clock: u64, + ticks: u64, + background_at: u64, + rng: LegacyRng, +} +impl Cinematic { + pub fn load(catalog: &Catalog, kind: Kind) -> Result { + let mut clips = Vec::new(); + let mut total = 0_usize; + for spec in specs(kind) { + let start = catalog.id(spec.name)?; + let mut frames = Vec::new(); + for index in 0..spec.count { + let bytes = catalog.read(start + index)?; + total += bytes.len(); + ensure!(total <= 32 * 1024 * 1024, "cinematic exceeds 32 MiB"); + frames.push( + DeltaFrame::decode(&bytes, index == 0) + .with_context(|| format!("{} frame {}", spec.name, index))?, + ); + } + let background = spec + .background + .and_then(|name| sound(name, 127, &mut LegacyRng::new(0))) + .and_then(|event| { + let sample = catalog + .read(event.asset) + .and_then(|b| DigitalSample::decode(&b)) + .ok()?; + let ticks = (sample.data.len() as u64 * 70 * 128) + .div_ceil(sample.rate as u64 * event.pitch.clamp(1, 255) as u64) + .max(1); + Some((event, ticks)) + }); + clips.push(Clip { + spec, + frames, + background, + }); + } + let mut result = Self { + image: Sprite::blank(320, 200), + sounds: Vec::new(), + clips, + current: 0, + frame: 0, + repetition: 0, + phase: Phase::Finished, + clock: 0, + ticks: 0, + background_at: 0, + rng: LegacyRng::new(0), + }; + result.begin()?; + Ok(result) + } + fn begin(&mut self) -> Result<()> { + if self.current == self.clips.len() { + self.phase = Phase::Finished; + return Ok(()); + } + self.frame = 0; + self.repetition = 0; + self.clips[self.current].frames[0].apply(&mut self.image)?; + let spec = &self.clips[self.current].spec; + self.phase = if spec.fade_in > 0 { + Phase::FadeIn(spec.fade_in) + } else { + Phase::Frame(spec.dwell) + }; + self.background_at = self.ticks; + self.frame_sound(); + Ok(()) + } + fn frame_sound(&mut self) { + let name = self.clips[self.current].spec.name; + let sound_name = match name { + "CHASE_AGX" if self.frame == 4 || self.frame == 9 => Some("FX_FLYBY"), + "SHIPSD2_AGX" if self.frame > 1 => Some("FX_INTROGUN"), + "EXPLO_AGX" if self.frame == 21 || self.frame >= 8 && self.frame % 2 == 1 => { + Some("FX_AIREXPLO") + } + "EXPLO_AGX" if (2..10).contains(&self.frame) => Some("FX_INTROHIT"), + "GAME2END_AGX" if self.frame == 22 || self.frame == 24 => Some("FX_AIREXPLO"), + "GAME3END_AGX" if self.frame == 30 || self.frame == 32 => Some("FX_AIREXPLO"), + _ => None, + }; + let pan = match (name, self.frame) { + ("CHASE_AGX", 4) => 210, + ("CHASE_AGX", 9) => 100, + ("GAME3END_AGX", _) => 100, + ("EXPLO_AGX", _) => 110 + self.rng.next_value() % 40, + _ => 127, + }; + if let Some(event) = sound_name.and_then(|name| sound(name, pan, &mut self.rng)) { + self.sounds.push(event); + } + } + pub fn advance(&mut self, nanos: u64) -> Result<()> { + self.clock = self.clock.saturating_add(nanos.min(1_000_000_000) * 70); + while self.clock >= 1_000_000_000 && !self.finished() { + self.clock -= 1_000_000_000; + self.ticks += 1; + if let Some((event, period)) = &self.clips[self.current].background { + if self.ticks >= self.background_at { + self.sounds.push(event.clone()); + self.background_at = self.ticks + period; + } + } + match self.phase { + Phase::FadeIn(n) if n > 1 => self.phase = Phase::FadeIn(n - 1), + Phase::FadeIn(_) => self.phase = Phase::Frame(self.clips[self.current].spec.dwell), + Phase::Frame(n) if n > 1 => self.phase = Phase::Frame(n - 1), + Phase::Frame(_) => { + if self.frame + 1 < self.clips[self.current].frames.len() { + self.frame += 1; + } else if self.repetition + 1 < self.clips[self.current].spec.repeats { + self.repetition += 1; + self.frame = 0; + } else { + let fade = self.clips[self.current].spec.fade_out; + if fade > 0 { + self.phase = Phase::FadeOut(fade); + } else { + self.current += 1; + self.begin()?; + } + continue; + } + self.clips[self.current].frames[self.frame].apply(&mut self.image)?; + self.phase = Phase::Frame(self.clips[self.current].spec.dwell); + self.frame_sound(); + } + Phase::FadeOut(n) if n > 1 => self.phase = Phase::FadeOut(n - 1), + Phase::FadeOut(_) => { + self.current += 1; + self.begin()?; + } + Phase::Finished => {} + } + } + Ok(()) + } + pub fn finished(&self) -> bool { + matches!(self.phase, Phase::Finished) + } + pub fn palette(&self, base: &[[u8; 3]; 256]) -> [[u8; 3]; 256] { + let (progress, total, target) = match self.phase { + Phase::FadeIn(remaining) => { + let total = self.clips[self.current].spec.fade_in; + (total - remaining, total, [0; 3]) + } + Phase::FadeOut(remaining) => { + let spec = &self.clips[self.current].spec; + (remaining, spec.fade_out, spec.fade_color) + } + _ => return *base, + }; + std::array::from_fn(|i| { + std::array::from_fn(|j| { + ((base[i][j] as u32 * progress + target[j] as u32 * (total - progress)) + / total.max(1)) as u8 + }) + }) + } +} +fn sound(name: &str, pan: i32, rng: &mut LegacyRng) -> Option { + let definition = crate::legacy_tables::sounds() + .into_iter() + .find(|sound| sound.name == name)?; + let pitch = definition.pitch + + if definition.random { + rng.next_value() % 40 - 20 + } else { + 0 + }; + Some(SoundEvent { + asset: definition.asset, + pan, + pitch, + volume: definition.volume, + priority: definition.priority, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + fn delta(first: bool, offset: u16, pixels: &[u8]) -> Vec { + let mut bytes = if first { vec![5] } else { vec![] }; + for value in [1_u16, 0, offset, pixels.len() as u16] { + bytes.extend(value.to_le_bytes()); + } + bytes.extend(pixels); + bytes.extend([0; 8]); + bytes + } + #[test] + fn deltas_preserve_unchanged_pixels_and_initial_fill() { + let mut canvas = Sprite::blank(320, 200); + DeltaFrame::decode(&delta(true, 4, &[1, 2, 3]), true) + .unwrap() + .apply(&mut canvas) + .unwrap(); + assert_eq!(&canvas.pixels[..8], &[5, 5, 5, 5, 1, 2, 3, 5]); + DeltaFrame::decode(&delta(false, 5, &[9]), false) + .unwrap() + .apply(&mut canvas) + .unwrap(); + assert_eq!(&canvas.pixels[4..8], &[1, 9, 3, 5]); + } + #[test] + fn malformed_delta_cannot_write_outside_canvas() { + assert!(DeltaFrame::decode(&delta(false, 63999, &[1, 2]), false).is_err()); + let valid = delta(false, 5, &[1, 2]); + for length in 0..valid.len() - 8 { + assert!(DeltaFrame::decode(&valid[..length], false).is_err()); + } + } + #[test] + fn player_timing_is_independent_of_render_rate() { + fn player() -> Cinematic { + let frames = vec![ + DeltaFrame::decode(&delta(true, 0, &[1]), true).unwrap(), + DeltaFrame::decode(&delta(false, 0, &[2]), false).unwrap(), + ]; + let mut p = Cinematic { + image: Sprite::blank(320, 200), + sounds: vec![], + clips: vec![Clip { + spec: clip("fixture", 2, 8, 2), + frames, + background: None, + }], + current: 0, + frame: 0, + repetition: 0, + phase: Phase::Finished, + clock: 0, + ticks: 0, + background_at: 0, + rng: LegacyRng::new(0), + }; + p.begin().unwrap(); + p + } + let mut a = player(); + let mut b = player(); + a.advance(300_000_000).unwrap(); + for _ in 0..30 { + b.advance(10_000_000).unwrap(); + } + assert_eq!(a.image, b.image); + assert_eq!(a.frame, b.frame); + assert_eq!(a.repetition, b.repetition); + assert_eq!(a.ticks, b.ticks); + } + #[test] + #[ignore = "requires original local game assets"] + fn all_original_cinematic_sequences_decode() { + let root = std::env::var("RAPTOR_TEST_DATA") + .expect("set RAPTOR_TEST_DATA to the original asset directory"); + let catalog = Catalog::open(root).unwrap(); + for kind in [ + Kind::Intro, + Kind::Landing, + Kind::Death, + Kind::CampaignEnd(0), + Kind::CampaignEnd(1), + Kind::CampaignEnd(2), + ] { + let mut movie = Cinematic::load(&catalog, kind).unwrap(); + while !movie.finished() { + movie.advance(1_000_000_000).unwrap(); + } + } + } +} diff --git a/src/content.rs b/src/content.rs new file mode 100644 index 00000000..f75cb45a --- /dev/null +++ b/src/content.rs @@ -0,0 +1,905 @@ +//! Versioned, namespaced content shared by the base game and mods. +use crate::assets::{Catalog, LegacyEnemy, LegacyMap, Sprite}; +use anyhow::{Context, Result, ensure}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeMap, path::PathBuf}; + +pub const API_VERSION: u32 = 1; +#[derive( + Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema, +)] +#[serde(transparent)] +pub struct ContentId(pub String); +impl ContentId { + pub fn new(value: impl Into) -> Result { + let id = Self(value.into()); + id.validate()?; + Ok(id) + } + pub fn validate(&self) -> Result<()> { + let (ns, name) = self + .0 + .split_once(':') + .context("content IDs require namespace:name")?; + ensure!( + !ns.is_empty() + && !name.is_empty() + && !name.contains(':') + && self.0.len() <= 128 + && self + .0 + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || ":_-/.".contains(c)), + "invalid content ID {}", + self.0 + ); + Ok(()) + } +} +impl From<&str> for ContentId { + fn from(s: &str) -> Self { + Self(s.into()) + } +} +impl std::fmt::Display for ContentId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Art { + pub asset: Option, + pub png: Option, + #[serde(default)] + pub hd_png: Option, + pub logical_width: u32, + pub logical_height: u32, + #[serde(default = "one")] + pub frames: u32, + #[serde(default)] + pub nearest: bool, +} +fn one() -> u32 { + 1 +} +fn yes() -> bool { + true +} +fn shield() -> i32 { + 100 +} +fn speed() -> i32 { + 2 +} +fn rate() -> u32 { + 10 +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Target { + Air, + Ground, + All, +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum WeaponBehavior { + Straight, + Homing, + Beam, + Spread, + Bomb, + EnergyGrab, +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WeaponDef { + pub id: ContentId, + pub name: String, + pub damage: i32, + pub speed: i32, + pub cooldown: u32, + pub behavior: WeaponBehavior, + pub target: Target, + #[serde(default)] + pub art: Option, + #[serde(default)] + pub offsets: Vec<[i32; 2]>, + #[serde(default)] + pub script: Option, + #[serde(default)] + pub legacy: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ItemDef { + pub id: ContentId, + pub name: String, + pub price: u32, + #[serde(default = "one")] + pub max_count: u32, + #[serde(default = "one")] + pub initial_count: u32, + #[serde(default)] + pub weapon: Option, + #[serde(default)] + pub shield: i32, + #[serde(default)] + pub credits: u32, + #[serde(default)] + pub consumable: bool, + #[serde(default)] + pub special: bool, + #[serde(default)] + pub art: Option, + #[serde(default)] + pub script: Option, + #[serde(default)] + pub legacy: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct EnemyDef { + pub id: ContentId, + pub name: String, + #[serde(default = "shield")] + pub health: i32, + #[serde(default = "speed")] + pub speed: i32, + #[serde(default)] + pub reward: u32, + #[serde(default)] + pub ground: bool, + #[serde(default)] + pub boss: bool, + #[serde(default = "rate")] + pub cooldown: u32, + #[serde(default)] + pub path: Vec<[i32; 2]>, + #[serde(default)] + pub repeat: bool, + #[serde(default)] + pub weapon: Option, + #[serde(default)] + pub drop: Option, + #[serde(default)] + pub art: Option, + #[serde(default)] + pub script: Option, + #[serde(skip)] + #[schemars(skip)] + pub legacy: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct SpawnDef { + pub tick: u64, + pub enemy: ContentId, + pub x: i32, + pub y: i32, + #[serde(default)] + pub difficulty: u32, +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct TileDef { + pub art: Art, + #[serde(default)] + pub health: i32, + #[serde(default)] + pub reward: u32, + #[serde(default)] + pub destroyed: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct MissionDef { + pub id: ContentId, + pub name: String, + #[serde(default)] + pub art: Option, + pub duration: u64, + #[serde(default = "yes")] + pub auto_complete: bool, + #[serde(default)] + pub spawns: Vec, + #[serde(default)] + pub tiles: Vec, + #[serde(default)] + pub columns: u32, + #[serde(default)] + pub layout: Vec, + #[serde(default)] + pub next: Option, + #[serde(default)] + pub music: Option, + #[serde(default)] + pub script: Option, + #[serde(default)] + pub legacy_map: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CampaignDef { + pub id: ContentId, + pub name: String, + #[serde(default)] + pub art: Option, + pub missions: Vec, +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct SoundDef { + pub id: ContentId, + pub name: String, + pub file: String, + #[serde(default = "sound_volume")] + pub volume: i32, + #[serde(default = "sound_volume")] + pub pan: i32, + #[serde(default = "sound_pitch")] + pub pitch: i32, + #[serde(default = "one")] + pub priority: u32, +} +fn sound_volume() -> i32 { + 127 +} +fn sound_pitch() -> i32 { + 128 +} +#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ContentPack { + #[serde(default)] + pub sounds: Vec, + #[serde(default)] + pub weapons: Vec, + #[serde(default)] + pub items: Vec, + #[serde(default)] + pub enemies: Vec, + #[serde(default)] + pub missions: Vec, + #[serde(default)] + pub campaigns: Vec, + #[serde(default)] + pub overrides: Vec, +} +#[derive(Debug, Clone, Default)] +pub struct Registry { + pub sounds: BTreeMap, + pub weapons: BTreeMap, + pub items: BTreeMap, + pub enemies: BTreeMap, + pub missions: BTreeMap, + pub campaigns: BTreeMap, + pub owners: BTreeMap, + pub asset_roots: BTreeMap, + pub overrides: Vec, +} +impl Registry { + pub fn apply(&mut self, pack: ContentPack, owner: &str) -> Result<()> { + let mut candidate = self.clone(); + candidate.apply_inner(pack, owner)?; + *self = candidate; + Ok(()) + } + fn apply_inner(&mut self, pack: ContentPack, owner: &str) -> Result<()> { + let overrides: std::collections::BTreeSet<_> = pack.overrides.into_iter().collect(); + let mut supplied = std::collections::BTreeSet::new(); + macro_rules! insert { + ($values:expr,$map:ident) => { + for value in $values { + value.id.validate()?; + ensure!( + supplied.insert(value.id.clone()), + "duplicate definition {}", + value.id + ); + let exists = self.owners.contains_key(&value.id); + ensure!( + !exists || self.$map.contains_key(&value.id), + "override cannot change content type: {}", + value.id + ); + ensure!( + exists == overrides.contains(&value.id), + "{}: {} requires an explicit override and override targets must exist", + owner, + value.id + ); + if !exists { + ensure!( + value.id.0.starts_with(&format!("{owner}:")), + "{} does not belong to namespace {owner}", + value.id + ); + } + if exists { + self.overrides.push(format!( + "{}: {} -> {owner}", + value.id, self.owners[&value.id] + )); + } + self.owners.insert(value.id.clone(), owner.into()); + self.$map.insert(value.id.clone(), value); + } + }; + } + insert!(pack.weapons, weapons); + insert!(pack.items, items); + insert!(pack.enemies, enemies); + insert!(pack.missions, missions); + insert!(pack.campaigns, campaigns); + insert!(pack.sounds, sounds); + ensure!( + overrides.is_subset(&supplied), + "override has no replacement definition" + ); + Ok(()) + } + pub fn validate(&self) -> Result<()> { + let label = |name: &str, script: &Option| -> Result<()> { + ensure!( + !name.trim().is_empty() && name.len() <= 128, + "content name must contain 1–128 bytes" + ); + ensure!( + script + .as_ref() + .is_none_or(|s| !s.is_empty() && s.len() <= 4096), + "invalid script path length" + ); + Ok(()) + }; + let art = |a: &Option| -> Result<()> { + if let Some(a) = a { + ensure!( + a.logical_width > 0 + && a.logical_height > 0 + && a.logical_width <= 4096 + && a.logical_height <= 4096 + && a.frames > 0 + && a.frames <= 256 + && (a.logical_width as u64 * a.logical_height as u64) <= 1_048_576, + "invalid artwork dimensions/frames" + ); + ensure!( + a.asset.is_some() != a.png.is_some(), + "art requires exactly one of asset or png" + ); + ensure!( + a.png + .as_ref() + .is_none_or(|p| !p.is_empty() && p.len() <= 4096), + "invalid artwork path length" + ); + ensure!( + a.hd_png + .as_ref() + .is_none_or(|p| !p.is_empty() && p.len() <= 4096), + "invalid HD artwork path length" + ); + ensure!( + a.asset + .is_none_or(|id| id.checked_add(a.frames - 1).is_some()), + "art animation asset ID overflow" + ); + } + Ok(()) + }; + for w in self.weapons.values() { + label(&w.name, &w.script)?; + ensure!( + w.damage > 0 + && w.damage <= 100000 + && w.cooldown > 0 + && w.speed.unsigned_abs() <= 128 + && w.offsets.len() <= 64, + "invalid weapon {}", + w.id + ); + ensure!( + w.offsets + .iter() + .flatten() + .all(|n| n.unsigned_abs() <= 32768), + "weapon offset outside world bounds" + ); + ensure!( + w.legacy.is_none_or(|n| n < 15), + "invalid original projectile ID" + ); + art(&w.art)?; + } + for i in self.items.values() { + label(&i.name, &i.script)?; + ensure!( + i.max_count > 0 + && i.max_count <= 1_000_000 + && i.initial_count > 0 + && i.initial_count <= i.max_count, + "invalid item {}", + i.id + ); + ensure!( + i.shield.unsigned_abs() <= 100000 && i.legacy.is_none_or(|n| n < 24), + "invalid item effects/original ID" + ); + if let Some(w) = &i.weapon { + ensure!( + self.weapons.contains_key(w), + "item {} references missing weapon {w}", + i.id + ); + } + art(&i.art)?; + } + for e in self.enemies.values() { + label(&e.name, &e.script)?; + ensure!( + e.health > 0 + && e.health <= 100000 + && e.cooldown > 0 + && e.speed.unsigned_abs() <= 128 + && e.path.len() <= 1024, + "invalid enemy {}", + e.id + ); + ensure!( + e.path.iter().flatten().all(|v| v.unsigned_abs() <= 32768), + "enemy path outside world bounds" + ); + if let Some(w) = &e.weapon { + ensure!( + self.weapons.contains_key(w), + "enemy {} references missing weapon {w}", + e.id + ); + } + if let Some(i) = &e.drop { + ensure!( + self.items.contains_key(i), + "enemy {} references missing drop {i}", + e.id + ); + } + art(&e.art)?; + } + for m in self.missions.values() { + label(&m.name, &m.script)?; + art(&m.art)?; + ensure!( + m.duration > 0 + && m.duration <= 1_000_000 + && m.spawns.len() <= 100000 + && m.tiles.len() <= 65536 + && m.layout.len() <= 2_000_000, + "invalid mission {}", + m.id + ); + if !m.layout.is_empty() { + ensure!( + (1..=128).contains(&m.columns) + && m.layout.len() % m.columns as usize == 0 + && m.layout.iter().all(|i| *i < m.tiles.len()), + "invalid mission terrain {}", + m.id + ); + } + for tile in &m.tiles { + ensure!( + (if m.legacy_map.is_some() { -32768 } else { 0 }..=100000) + .contains(&tile.health), + "invalid terrain health" + ); + art(&Some(tile.art.clone()))?; + art(&tile.destroyed)?; + } + ensure!( + m.spawns.windows(2).all(|w| w[0].tick <= w[1].tick), + "mission {} spawns must be sorted by tick", + m.id + ); + for s in &m.spawns { + ensure!( + s.tick <= 1_000_000 + && s.difficulty <= if m.legacy_map.is_some() { 5 } else { 3 }, + "invalid spawn tick/difficulty" + ); + ensure!( + s.x.unsigned_abs() <= 32768 && s.y.unsigned_abs() <= 32768, + "spawn coordinate outside world bounds" + ); + ensure!( + self.enemies.contains_key(&s.enemy), + "mission {} references missing enemy {}", + m.id, + s.enemy + ); + } + if let Some(next) = &m.next { + ensure!( + self.missions.contains_key(next), + "missing next mission {next}" + ); + } + } + for c in self.campaigns.values() { + label(&c.name, &None)?; + art(&c.art)?; + ensure!(c.missions.len() <= 100000, "campaign exceeds mission limit"); + ensure!(!c.missions.is_empty(), "empty campaign {}", c.id); + for m in &c.missions { + ensure!( + self.missions.contains_key(m), + "campaign {} references missing mission {m}", + c.id + ); + } + } + for sound in self.sounds.values() { + label(&sound.name, &None)?; + ensure!( + !sound.file.is_empty() + && sound.file.len() <= 4096 + && (0..=127).contains(&sound.volume) + && (0..=255).contains(&sound.pan) + && (0..=255).contains(&sound.pitch) + && sound.priority <= 100000, + "invalid sound definition {}", + sound.id + ); + } + Ok(()) + } + pub fn base(catalog: &Catalog) -> Result { + let mut reg = Self::default(); + let mut pack = ContentPack::default(); + for o in crate::legacy_tables::objects() { + let id = ContentId::from(o.id); + let weapon = if o.index < 15 { + Some(ContentId(format!( + "base:projectile_{}", + o.id.strip_prefix("base:").unwrap() + ))) + } else { + None + }; + let art = if o.asset > 0 { + let s = catalog.sprite(o.asset)?; + Some(Art { + asset: Some(o.asset), + png: None, + hd_png: None, + logical_width: s.width as u32, + logical_height: s.height as u32, + frames: o.frames.max(1), + nearest: false, + }) + } else { + None + }; + pack.items.push(ItemDef { + id: id.clone(), + name: o.name.into(), + price: o.cost, + max_count: o.max_count.max(1), + initial_count: o.initial_count, + weapon, + shield: if o.index == 16 { + 25 + } else if o.index == 15 { + 100 + } else { + 0 + }, + credits: if o.index >= 18 { o.cost } else { 0 }, + consumable: o.index == 11, + special: o.special, + art, + script: None, + legacy: Some(o.index), + }); + } + for w in crate::legacy_tables::weapons() { + let sprite = if w.asset > 0 { + Some(catalog.sprite(w.asset)?) + } else { + None + }; + pack.weapons.push(WeaponDef { + id: ContentId(format!( + "base:projectile_{}", + w.id.strip_prefix("base:").unwrap() + )), + name: w.name.into(), + damage: w.damage.max(1), + speed: w.speed, + cooldown: w.cooldown.max(1), + behavior: match w.index { + 4 | 8 | 7 | 2 => WeaponBehavior::Homing, + 5 | 12 | 13 | 14 => WeaponBehavior::Beam, + 9 | 11 => WeaponBehavior::Bomb, + 10 => WeaponBehavior::EnergyGrab, + 6 => WeaponBehavior::Spread, + _ => WeaponBehavior::Straight, + }, + target: match w.target { + 1 => Target::Air, + 2 | 3 | 4 => Target::Ground, + _ => Target::All, + }, + art: sprite.map(|sprite| Art { + asset: Some(w.asset), + png: None, + hd_png: None, + logical_width: sprite.width as u32, + logical_height: sprite.height as u32, + frames: w.frames.max(1), + nearest: false, + }), + offsets: if w.index == 0 { + vec![[-13, 0], [13, 0]] + } else { + vec![[0, 0]] + }, + script: None, + legacy: Some(w.index), + }); + } + pack.weapons.push(WeaponDef { + id: "base:enemy_bullet".into(), + name: "Enemy cannon".into(), + damage: 3, + speed: 4, + cooldown: 12, + behavior: WeaponBehavior::Straight, + target: Target::All, + art: Some(Art { + asset: Some(0x101d6), + png: None, + hd_png: None, + logical_width: 8, + logical_height: 8, + frames: 2, + nearest: false, + }), + offsets: vec![[0, 0]], + script: None, + legacy: None, + }); + for game in 0..4 { + let Ok(bytes) = catalog.named(&format!("SPRITE{}_ITM", game + 1)) else { + continue; + }; + for (n, legacy) in LegacyEnemy::library(&bytes)?.into_iter().enumerate() { + let Ok(asset) = catalog.id(&legacy.name) else { + continue; + }; + let Ok(s) = catalog.sprite(asset) else { + continue; + }; + let f = &legacy.fields; + pack.enemies.push(EnemyDef { + id: ContentId(format!("base:enemy_{game}_{n}")), + name: legacy.name.clone(), + health: f[13].max(1), + speed: f[18].clamp(0, 128), + reward: f[14].max(0) as u32, + ground: f[21] >= 3, + boss: f[12] != 0, + cooldown: f[3].max(1) as u32, + path: legacy + .flight_x + .iter() + .zip(&legacy.flight_y) + .take(f[19].max(0) as usize) + .map(|(x, y)| [*x as i32, *y as i32]) + .collect(), + repeat: f[21] == 0, + weapon: if f[22] > 0 { + Some("base:enemy_bullet".into()) + } else { + None + }, + drop: pack + .items + .iter() + .find(|i| i.legacy == Some(f[1] as u32)) + .map(|i| i.id.clone()), + art: Some(Art { + asset: Some(asset), + png: None, + hd_png: None, + logical_width: s.width as u32, + logical_height: s.height as u32, + frames: f[7].max(1) as u32, + nearest: false, + }), + script: None, + legacy: Some(legacy), + }); + } + } + for sector in 1..=3 { + let mut missions = Vec::new(); + for wave in 1..=9 { + let Ok(id) = catalog.id(&format!("MAP{wave}G{sector}_MAP")) else { + continue; + }; + let map = LegacyMap::decode(&catalog.read(id)?)?; + let mut spawns = Vec::new(); + let mut group_row = None; + for s in &map.spawns { + let row = *group_row.get_or_insert(s.row); + let eid = ContentId(format!("base:enemy_{}_{}", s.game, s.library)); + if pack.enemies.iter().any(|e| e.id == eid) { + spawns.push(SpawnDef { + tick: if row >= 139 { + 0 + } else { + (56 + (138 - row) * 32) as u64 + }, + enemy: eid, + x: 16 + s.x * 32, + y: (if row >= 139 { -136 } else { -112 }) - (row - s.row) * 32, + difficulty: s.difficulty.max(0) as u32, + }); + } + if s.link == 1 || s.link == -1 { + group_row = None; + } + } + spawns.sort_by_key(|s| s.tick); + let mut tiles = Vec::new(); + let mut layout = Vec::new(); + let mut lookup = BTreeMap::new(); + for (flat, game) in map.tiles { + let key = (flat, game); + let pos = if let Some(p) = lookup.get(&key) { + *p + } else { + let start = catalog.id(&format!("STARTG{}TILES", game + 1))? + 1; + let lib = catalog.named(&format!("FLATSG{}_ITM", game + 1))?; + let o = flat as usize * 8; + let destroyed = crate::assets::i32_at(&lib, o)?; + let health = crate::assets::i16_at(&lib, o + 4)?; + let bounty = crate::assets::i16_at(&lib, o + 6)?; + let make = |asset| Art { + asset: Some(asset), + png: None, + hd_png: None, + logical_width: 32, + logical_height: 32, + frames: 1, + nearest: false, + }; + let n = tiles.len(); + tiles.push(TileDef { + art: make(start + flat as u32), + health: if destroyed != flat as i32 { + health as i32 + } else { + 0 + }, + reward: bounty.max(0) as u32, + destroyed: if destroyed != flat as i32 { + Some(make(start + destroyed as u32)) + } else { + None + }, + }); + lookup.insert(key, n); + n + }; + layout.push(pos); + } + let mid = ContentId(format!("base:sector_{sector}_wave_{wave}")); + missions.push(mid.clone()); + pack.missions.push(MissionDef { + id: mid, + name: format!("Sector {sector} / Wave {wave}"), + art: None, + duration: 4700, + auto_complete: true, + spawns, + tiles, + columns: 9, + layout, + next: if wave < 9 { + Some(ContentId(format!("base:sector_{sector}_wave_{}", wave + 1))) + } else { + None + }, + music: catalog + .id(&format!( + "RAP{}_MUS", + [ + [8, 2, 4, 7, 6, 2, 3, 4, 6], + [3, 2, 4, 8, 6, 2, 8, 1, 6], + [8, 4, 1, 7, 6, 2, 3, 4, 6], + ][sector - 1][wave - 1] + )) + .ok(), + script: None, + legacy_map: Some(id), + }); + } + if !missions.is_empty() { + pack.campaigns.push(CampaignDef { + id: ContentId(format!("base:sector_{sector}")), + name: ["Bravo Sector", "Tango Sector", "Outer Regions"][sector - 1].into(), + art: None, + missions, + }); + } + } + reg.apply(pack, "base")?; + reg.validate()?; + Ok(reg) + } + pub fn art(&self, id: &ContentId) -> Option<&Art> { + self.enemies + .get(id) + .and_then(|e| e.art.as_ref()) + .or_else(|| self.items.get(id).and_then(|e| e.art.as_ref())) + .or_else(|| self.weapons.get(id).and_then(|e| e.art.as_ref())) + .or_else(|| self.missions.get(id).and_then(|e| e.art.as_ref())) + .or_else(|| self.campaigns.get(id).and_then(|e| e.art.as_ref())) + } +} +pub fn art_sprite( + catalog: &Catalog, + registry: &Registry, + owner: &str, + art: &Art, + frame: u32, +) -> Result { + art_sprite_variant(catalog, registry, owner, art, frame, false) +} +pub fn art_sprite_variant( + catalog: &Catalog, + registry: &Registry, + owner: &str, + art: &Art, + frame: u32, + hd: bool, +) -> Result { + ensure!(art.frames > 0, "art animation must have frames"); + let png = if hd { + art.hd_png.as_ref().or(art.png.as_ref()) + } else { + art.png.as_ref() + }; + if let Some(id) = art.asset.filter(|_| !(hd && art.hd_png.is_some())) { + catalog.sprite( + id.checked_add(frame % art.frames) + .context("art asset ID overflow")?, + ) + } else { + let root = registry + .asset_roots + .get(owner) + .context("unknown artwork owner")?; + let path = + crate::assets::contained(root, std::path::Path::new(png.context("missing PNG")?))?; + let sprite = Sprite::png(&path, &catalog.palette()?)?; + ensure!( + sprite.width % art.frames as usize == 0, + "PNG strip width must be divisible by frame count" + ); + let width = sprite.width / art.frames as usize; + let x = (frame % art.frames) as usize * width; + let mut out = Sprite::blank(width, sprite.height); + for y in 0..out.height { + out.pixels[y * width..(y + 1) * width].copy_from_slice( + &sprite.pixels[y * sprite.width + x..y * sprite.width + x + width], + ); + } + Ok(out) + } +} diff --git a/src/desktop.rs b/src/desktop.rs new file mode 100644 index 00000000..72306071 --- /dev/null +++ b/src/desktop.rs @@ -0,0 +1,1981 @@ +//! SDL host, interpolated scene presentation and local game menus. +use crate::{ + assets::{Catalog, Sprite}, + audio::{DigitalSample, Mixer, MusScore}, + cinematics::{Cinematic, Kind as MovieKind}, + content::{Art, ContentId, Registry, art_sprite_variant}, + hd::HdAssets, + modding::{self, ActiveMods, Discovery}, + persistence::{Config, Paths, Pilot}, + render::{BitmapFont, Canvas, SpriteCache, nearest, upscale}, + simulation::{Clock, Input, Outcome, World}, +}; +use anyhow::{Context, Result, anyhow}; +use sdl2::{ + audio::{AudioCallback, AudioDevice, AudioSpecDesired}, + controller::{Axis, Button}, + event::Event, + keyboard::{Keycode, Scancode}, + pixels::PixelFormatEnum, + rect::Rect, + video::FullscreenType, +}; +use std::{ + collections::BTreeMap, + path::PathBuf, + time::{Duration, Instant}, +}; + +impl AudioCallback for Mixer { + type Channel = i16; + fn callback(&mut self, out: &mut [i16]) { + self.mix(out) + } +} +#[derive(Clone, Copy, PartialEq, Eq)] +enum Screen { + Main, + Missions, + Shop, + Inventory, + Mods, + Options, + Game, + Pause, + Results, + Help, + Credits, + Pilots, + Diagnostics, + Bindings, + Cinematic, +} +struct Host { + catalog: Catalog, + base: Registry, + active: ActiveMods, + paths: Paths, + mods_root: PathBuf, + discovery: Discovery, + config: Config, + hd: HdAssets, + read_only: bool, + pending: Vec, + pilot: Pilot, + slot: usize, + pilot_error: Option, + queued_cycle: bool, + queued_bomb: bool, + awaiting_binding: Option, + world: Option, + cinematic: Option, + movie_return: Screen, + screen: Screen, + previous: Screen, + selected: usize, + message: String, + font: BitmapFont, + cache: SpriteCache, + raw: BTreeMap, + mod_art: BTreeMap, + palette: [[u8; 3]; 256], + audio: Option>, + mod_audio: BTreeMap, + desired_music: Option, + clock: Clock, +} +impl Host { + fn new( + catalog: Catalog, + base: Registry, + paths: Paths, + mods_root: PathBuf, + read_only: bool, + ) -> Result { + let config = Config::load(&paths)?; + let discovery = modding::discover(&mods_root); + let mut message = String::new(); + let mut active = + match ActiveMods::build(&base, &discovery, &config.enabled_mods, Some(&catalog)) { + Ok(a) => a, + Err(e) => { + message = format!("Mod load failed: {e:#}"); + ActiveMods::build(&base, &discovery, &[], Some(&catalog))? + } + }; + let mut pilot_error = None; + let mut pilot = if paths.save_path(0).exists() { + match Pilot::load(&paths.save_path(0), &active.registry, &active.pins) { + Ok(p) => p, + Err(e) => { + message = format!("Saved pilot unavailable: {e:#}"); + pilot_error = Some(message.clone()); + Pilot::default() + } + } + } else { + let legacy = paths.legacy.join("CHAR0000.FIL"); + if legacy.exists() { + match Pilot::import_legacy(&legacy, &active.registry) { + Ok(p) => p, + Err(e) => { + message = format!("Legacy import failed: {e:#}"); + Pilot::default() + } + } + } else { + Pilot::default() + } + }; + if !paths.save_path(0).exists() { + pilot.mods = active.pins.clone(); + } + restore_scripts(&mut active.scripts, &pilot); + let hd = HdAssets::load(&catalog.root.join("hd"), &catalog); + let palette = catalog.palette()?; + let font = BitmapFont::decode(&catalog.named("SYSTEM_FNT")?)?; + let cache = SpriteCache::new(Some(paths.cache.join("sprites"))); + let pending = config.enabled_mods.clone(); + Ok(Self { + catalog, + base, + active, + paths, + mods_root, + discovery, + config, + hd, + read_only, + pending, + pilot, + slot: 0, + pilot_error, + queued_cycle: false, + queued_bomb: false, + awaiting_binding: None, + world: None, + cinematic: None, + movie_return: Screen::Main, + screen: Screen::Main, + previous: Screen::Main, + selected: 0, + message, + font, + cache, + raw: BTreeMap::new(), + mod_art: BTreeMap::new(), + palette, + audio: None, + mod_audio: BTreeMap::new(), + desired_music: None, + clock: Clock::default(), + }) + } + fn go(&mut self, screen: Screen) { + self.screen = screen; + self.selected = 0; + } + fn save_config(&self) -> Result<()> { + if self.read_only { + return Ok(()); + } + self.config.save(&self.paths) + } + fn save(&mut self) -> Result<()> { + if self.read_only { + return Ok(()); + } + self.require_pilot()?; + self.pilot.script_state = self.active.scripts.states.clone(); + self.pilot.script_rng = self.active.scripts.rng.clone(); + self.pilot + .validate(&self.active.registry, &self.active.pins)?; + self.pilot.save(&self.paths.save_path(self.slot))?; + self.save_config() + } + fn music(&mut self, name: &str) { + self.desired_music = self.catalog.id(name).ok(); + let score = self.catalog.named(name).and_then(|b| MusScore::decode(&b)); + if let (Some(device), Ok(score)) = (&mut self.audio, score) { + device.lock().play_with_fade(score, true, true); + } + } + fn start(&mut self, id: ContentId) -> Result<()> { + self.require_pilot()?; + self.pilot.mission = id.clone(); + self.pilot.difficulty = self.config.difficulty; + self.active.scripts.states = self.pilot.script_state.clone(); + self.active.scripts.rng = self.pilot.script_rng.clone(); + self.world = Some(World::new(&id, &self.pilot, &self.active.registry)?); + if let Some(music) = self.active.registry.missions[&id].music { + self.desired_music = Some(music); + if let Ok(score) = self.catalog.read(music).and_then(|b| MusScore::decode(&b)) { + if let Some(audio) = &mut self.audio { + audio.lock().play_with_fade(score, true, true); + } + } + } + self.clock = Clock::default(); + self.go(Screen::Game); + Ok(()) + } + fn show_movie(&mut self, kind: MovieKind, return_to: Screen) -> Result<()> { + let movie = Cinematic::load(&self.catalog, kind)?; + self.cinematic = Some(movie); + self.movie_return = return_to; + match kind { + MovieKind::Intro => self.music("RINTRO_MUS"), + MovieKind::Death => self.music("RAP5_MUS"), + _ => {} + } + self.go(Screen::Cinematic); + Ok(()) + } + fn finish_movie(&mut self) { + self.cinematic = None; + self.go(self.movie_return); + if self.screen == Screen::Main { + self.music("MAINMENU_MUS"); + } + } + fn items(&self) -> Vec { + self.active + .registry + .items + .values() + .filter(|i| i.legacy.is_none_or(|n| n < 18)) + .map(|i| i.id.clone()) + .collect() + } + fn missions(&self) -> Vec { + let mut ids: Vec<_> = self + .active + .registry + .campaigns + .values() + .flat_map(|c| c.missions.clone()) + .collect(); + let mut seen = std::collections::BTreeSet::new(); + ids.retain(|id| seen.insert(id.clone())); + for id in self.active.registry.missions.keys() { + if seen.insert(id.clone()) { + ids.push(id.clone()); + } + } + ids + } + fn rows(&self) -> Vec { + match self.screen { + Screen::Main => vec![ + "Continue / Hangar", + "Select Mission", + "Shop", + "Inventory", + "Mods", + "Options", + "Load Pilot", + "Help", + "Credits", + "Watch intro", + "Quit", + ] + .into_iter() + .map(str::to_string) + .collect(), + Screen::Missions => self + .missions() + .iter() + .map(|id| { + format!( + "{}{}", + if self.pilot.completed.contains(id) { + "+ " + } else { + " " + }, + self.active.registry.missions[id].name + ) + }) + .collect(), + Screen::Shop => self + .items() + .iter() + .map(|id| { + let i = &self.active.registry.items[id]; + format!("{} ${}", i.name, i.price) + }) + .collect(), + Screen::Inventory => self + .pilot + .inventory + .iter() + .filter_map(|(id, n)| { + self.active.registry.items.get(id).map(|i| { + format!( + "{} x{}{}", + i.name, + n, + if self.pilot.selected.as_ref() == Some(id) { + " [EQUIPPED]" + } else { + "" + } + ) + }) + }) + .collect(), + Screen::Pilots => self + .slots() + .iter() + .map(|n| format!("Pilot slot {:04}", n)) + .collect(), + Screen::Diagnostics => self.diagnostics(), + Screen::Bindings => ACTIONS + .iter() + .map(|action| { + format!( + "{}: {}", + action, + self.config + .bindings + .get(*action) + .map(String::as_str) + .unwrap_or("unbound") + ) + }) + .chain(std::iter::once("Restore default bindings".into())) + .collect(), + Screen::Mods => { + let mut r = vec!["Apply selections".into(), "Rescan installed mods".into()]; + let mut ids = self.pending.clone(); + for id in self.discovery.mods.keys() { + if !ids.contains(id) { + ids.push(id.clone()); + } + } + for id in ids { + if let Some(m) = self.discovery.mods.get(&id) { + r.push(format!( + "[{}] {} {}", + if self.pending.contains(&id) { "X" } else { " " }, + m.manifest.name, + m.manifest.version + )); + } + } + r + } + Screen::Options => vec![ + if self.config.scale == 1 { + "Sprite scale: original".into() + } else { + format!("Sprite scale: {}x crisp", self.config.scale) + }, + format!("Scanlines: {}", self.config.scanlines), + format!("Fullscreen: {}", self.config.fullscreen), + format!("Borderless: {}", self.config.borderless), + format!("4:3 aspect: {}", self.config.aspect_correct), + format!("Music volume: {}", self.config.music_volume), + format!("Effects volume: {}", self.config.fx_volume), + format!("Controls: {}", self.config.control), + format!( + "Difficulty: {}", + ["Training", "Rookie", "Veteran", "Elite"][self.config.difficulty as usize] + ), + format!("Resolution: {}x{}", self.config.width, self.config.height), + format!( + "HD art: {} ({} frames)", + if self.config.hd_mode { "on" } else { "off" }, + self.hd.coverage() + ), + "Keyboard bindings".into(), + format!("Effects channels: {}", self.config.fx_channels), + ], + Screen::Pause => vec!["Resume", "Options", "Mods", "Return to main menu"] + .into_iter() + .map(str::to_string) + .collect(), + Screen::Results => vec!["Return to hangar".into()], + _ => vec![], + } + } + fn mod_ids(&self) -> Vec { + let mut ids = self + .pending + .iter() + .filter(|id| self.discovery.mods.contains_key(*id)) + .cloned() + .collect::>(); + for id in self.discovery.mods.keys() { + if !ids.contains(id) { + ids.push(id.clone()); + } + } + ids + } + fn require_pilot(&self) -> Result<()> { + if let Some(error) = &self.pilot_error { + return Err(anyhow!( + "{error}. Restore matching mods, load a compatible pilot, or press N to create a separate pilot." + )); + } + self.pilot + .validate(&self.active.registry, &self.active.pins) + } + fn slots(&self) -> Vec { + (0..1000) + .filter(|n| self.paths.save_path(*n).is_file()) + .collect() + } + fn new_pilot(&mut self) -> Result<()> { + let slot = (0..1000) + .find(|n| !self.paths.save_path(*n).exists()) + .context("all pilot slots are occupied")?; + self.slot = slot; + self.pilot = Pilot { + mods: self.active.pins.clone(), + ..Pilot::default() + }; + self.pilot_error = None; + self.active.scripts.states.clear(); + self.active.scripts.rng.clear(); + self.message = format!("New pilot in slot {slot:04}"); + Ok(()) + } + fn diagnostics(&self) -> Vec { + let mut lines = vec![self.message.clone()]; + if let Some(e) = &self.pilot_error { + lines.push(e.clone()); + } + lines.extend(self.discovery.errors.clone()); + lines.extend(self.hd.diagnostics.clone()); + lines.push(format!( + "HD art coverage: {} supplied frames; remaining artwork uses original sprites", + self.hd.coverage() + )); + lines.push(format!( + "Active order: {}", + self.active + .pins + .iter() + .map(|m| m.id.clone()) + .collect::>() + .join(", ") + )); + lines.extend(self.active.registry.overrides.clone()); + for m in self.discovery.mods.values() { + lines.push(format!( + "{} {}: {}", + m.manifest.id, m.manifest.version, m.manifest.description + )); + lines.push(format!( + "Dependencies: {:?}; conflicts: {:?}", + m.manifest.dependencies, m.manifest.conflicts + )); + } + lines + .into_iter() + .flat_map(|s| { + s.chars() + .collect::>() + .chunks(52) + .map(|c| c.iter().collect::()) + .collect::>() + }) + .collect() + } + fn apply_mods(&mut self) -> Result<()> { + let mut candidate = ActiveMods::build( + &self.base, + &self.discovery, + &self.pending, + Some(&self.catalog), + )?; + let mut config = self.config.clone(); + config.enabled_mods = self.pending.clone(); + if !self.read_only { + config.save(&self.paths)?; + } + let saved = self.paths.save_path(self.slot); + match pilot_for_mods(&saved, &self.pilot, &candidate.registry, &candidate.pins) { + Ok(pilot) => { + restore_scripts(&mut candidate.scripts, &pilot); + self.pilot = pilot; + self.pilot_error = None; + } + Err(e) => self.pilot_error = Some(format!("Pilot slot {:04}: {e:#}", self.slot)), + } + self.config = config; + self.active = candidate; + self.mod_audio.clear(); + self.mod_art.clear(); + if self.pilot_error.is_some() { + self.message = + "Mods applied; pilot requires its saved mods. D: details / N: new pilot".into(); + } else { + self.message = "Mods applied".into(); + } + Ok(()) + } + fn activate(&mut self) -> Result { + match self.screen { + Screen::Main => match self.selected { + 0 => self.start(self.pilot.mission.clone())?, + 1 => self.go(Screen::Missions), + 2 => { + self.go(Screen::Shop); + self.music("HANGAR_MUS"); + } + 3 => self.go(Screen::Inventory), + 4 => self.go(Screen::Mods), + 5 => { + self.previous = Screen::Main; + self.go(Screen::Options) + } + 6 => self.go(Screen::Pilots), + 7 => self.go(Screen::Help), + 8 => self.go(Screen::Credits), + 9 => self.show_movie(MovieKind::Intro, Screen::Main)?, + 10 => return Ok(false), + _ => {} + }, + Screen::Missions => { + if let Some(id) = self.missions().get(self.selected) { + self.start(id.clone())?; + } + } + Screen::Pilots => { + if let Some(slot) = self.slots().get(self.selected).copied() { + let p = Pilot::load( + &self.paths.save_path(slot), + &self.active.registry, + &self.active.pins, + )?; + restore_scripts(&mut self.active.scripts, &p); + self.pilot = p; + self.slot = slot; + self.pilot_error = None; + self.message = format!("Loaded pilot slot {slot:04}"); + self.go(Screen::Main); + } + } + Screen::Shop => { + self.require_pilot()?; + if let Some(id) = self.items().get(self.selected) { + self.pilot.buy(id, &self.active.registry)?; + self.save()?; + self.message = "Purchase complete".into(); + } + } + Screen::Inventory => { + self.require_pilot()?; + if let Some(id) = self.pilot.inventory.keys().nth(self.selected).cloned() { + if self + .active + .registry + .items + .get(&id) + .is_some_and(|i| i.special) + { + self.pilot.selected = Some(id); + self.save()?; + self.message = "Weapon equipped".into(); + } + } + } + Screen::Mods => { + if self.selected == 0 { + if self.world.is_some() { + self.config.enabled_mods = self.pending.clone(); + self.save_config()?; + self.message = "Changes pending until the main menu".into(); + } else { + self.apply_mods()?; + } + } else if self.selected == 1 { + self.discovery = modding::discover(&self.mods_root); + self.message = self.discovery.errors.join("; "); + } else if let Some(id) = self.mod_ids().get(self.selected - 2).cloned() { + if let Some(n) = self.pending.iter().position(|s| s == &id) { + self.pending.remove(n); + } else { + self.pending.push(id); + } + } + } + Screen::Options => match self.selected { + 0 => self.config.scale = self.config.scale % 4 + 1, + 1 => self.config.scanlines = !self.config.scanlines, + 2 => self.config.fullscreen = !self.config.fullscreen, + 3 => self.config.borderless = !self.config.borderless, + 4 => self.config.aspect_correct = !self.config.aspect_correct, + 5 => self.config.music_volume = (self.config.music_volume + 16) % 128, + 6 => self.config.fx_volume = (self.config.fx_volume + 16) % 128, + 7 => { + self.config.control = match self.config.control.as_str() { + "keyboard" => "mouse", + "mouse" => "controller", + _ => "keyboard", + } + .into() + } + 8 => self.config.difficulty = (self.config.difficulty + 1) % 4, + 9 => { + if self.config.width == 1280 { + self.config.width = 1920; + self.config.height = 1080 + } else { + self.config.width = 1280; + self.config.height = 960 + } + } + 10 => self.config.hd_mode = !self.config.hd_mode, + 11 => self.go(Screen::Bindings), + 12 => self.config.fx_channels = self.config.fx_channels % 8 + 1, + _ => {} + }, + Screen::Bindings => { + if let Some(action) = ACTIONS.get(self.selected) { + self.awaiting_binding = Some(action.to_string()); + self.message = format!("Press a key for {action}; ESC cancels"); + } else { + self.config.bindings = Config::default().bindings; + self.save_config()?; + self.message = "Default bindings restored".into(); + } + } + Screen::Pause => match self.selected { + 0 => self.go(Screen::Game), + 1 => { + self.previous = Screen::Pause; + self.go(Screen::Options) + } + 2 => self.go(Screen::Mods), + 3 => self.return_main()?, + _ => {} + }, + Screen::Results => self.return_main()?, + _ => {} + } + Ok(true) + } + fn return_main(&mut self) -> Result<()> { + self.world = None; + self.clock = Clock::default(); + if self.pending + != self + .active + .pins + .iter() + .map(|m| m.id.clone()) + .collect::>() + { + if let Err(e) = self.apply_mods() { + self.message = format!("Mod changes pending: {e:#}"); + } + } + self.go(Screen::Main); + self.music("MAINMENU_MUS"); + Ok(()) + } + fn back(&mut self) -> Result<()> { + match self.screen { + Screen::Cinematic => self.finish_movie(), + Screen::Game => self.go(Screen::Pause), + Screen::Pause => self.go(Screen::Game), + Screen::Options => { + self.save_config()?; + self.go(self.previous) + } + Screen::Mods if self.world.is_some() => self.go(Screen::Pause), + Screen::Diagnostics => self.go(self.previous), + Screen::Bindings => { + self.awaiting_binding = None; + self.save_config()?; + self.go(Screen::Options); + } + Screen::Results => self.return_main()?, + _ => self.go(Screen::Main), + } + Ok(()) + } + fn update(&mut self, input: Input, nanos: u64) -> Result<()> { + if self.screen == Screen::Cinematic { + let movie = self + .cinematic + .as_mut() + .context("missing active cinematic")?; + movie.advance(nanos)?; + let sounds = std::mem::take(&mut movie.sounds); + let finished = movie.finished(); + if let Some(audio) = &mut self.audio { + for event in sounds { + if let Ok(sample) = self + .catalog + .read(event.asset) + .and_then(|b| DigitalSample::decode(&b)) + { + audio.lock().sample( + sample, + event.pan, + event.pitch, + event.volume, + event.priority, + ); + } + } + } + if finished { + self.finish_movie(); + } + return Ok(()); + } + if self.screen != Screen::Game { + return Ok(()); + } + self.queued_cycle |= input.cycle; + self.queued_bomb |= input.bomb; + let steps = self.clock.advance(nanos); + let mut input = input; + input.cycle = self.queued_cycle; + input.bomb = self.queued_bomb; + for _ in 0..steps { + let w = self.world.as_mut().context("missing active mission")?; + w.step(input, &self.active.registry, &mut self.active.scripts)?; + input.cycle = false; + input.bomb = false; + self.queued_cycle = false; + self.queued_bomb = false; + if let Some(audio) = &mut self.audio { + for event in &w.sound_events { + if let Ok(sample) = self + .catalog + .read(event.asset) + .and_then(|b| DigitalSample::decode(&b)) + { + audio.lock().sample( + sample, + event.pan, + event.pitch, + event.volume, + event.priority, + ); + } + } + for id in &w.mod_sounds { + let definition = self + .active + .registry + .sounds + .get(id) + .context("missing mod sound")?; + if !self.mod_audio.contains_key(id) { + let owner = &self.active.registry.owners[id]; + let root = &self.active.registry.asset_roots[owner]; + let path = + crate::assets::contained(root, std::path::Path::new(&definition.file))?; + let sample = crate::sound::decode(&std::fs::read(path)?)?; + if self.mod_audio.values().map(|s| s.data.len()).sum::() + + sample.data.len() + > 64 * 1024 * 1024 + { + self.mod_audio.clear(); + } + self.mod_audio.insert(id.clone(), sample); + } + audio.lock().sample( + self.mod_audio[id].clone(), + definition.pan, + definition.pitch, + definition.volume, + definition.priority as i32, + ); + } + } + if w.outcome != Outcome::Playing { + let outcome = w.outcome; + let mission = w.mission.clone(); + let mut pilot = w.pilot(&self.pilot); + if outcome == Outcome::Complete { + pilot.complete_mission(&self.active.registry)?; + self.config.difficulty = pilot.difficulty; + self.pilot = pilot; + self.save()?; + self.message = "Mission complete".into(); + } else { + self.message = "Ship lost - previous hangar save retained".into(); + } + let kind = if outcome == Outcome::Failed { + MovieKind::Death + } else if mission.0.ends_with("_wave_9") { + let sector = mission + .0 + .strip_prefix("base:sector_") + .and_then(|s| s.split('_').next()) + .and_then(|s| s.parse::().ok()) + .unwrap_or(1); + MovieKind::CampaignEnd(sector.saturating_sub(1)) + } else { + MovieKind::Landing + }; + if mission.0.starts_with("base:") { + if let Err(e) = self.show_movie(kind, Screen::Results) { + self.message = format!("Cinematic unavailable: {e:#}"); + self.go(Screen::Results); + } + } else { + self.go(Screen::Results); + } + break; + } + } + Ok(()) + } + fn raw(&mut self, id: u32) -> Result { + if let Some(s) = self.raw.get(&id) { + return Ok(s.clone()); + } + let s = self.catalog.sprite(id)?; + self.raw.insert(id, s.clone()); + Ok(s) + } + fn art( + &mut self, + canvas: &mut Canvas, + art: &Art, + owner: &str, + frame: u32, + x: f32, + y: f32, + ) -> Result<()> { + let key = if art.png.is_some() || art.hd_png.is_some() { + Some(format!( + "{owner}:{}:{frame}:{}:{}", + serde_json::to_string(art)?, + canvas.scale, + self.config.hd_mode + )) + } else { + None + }; + if let Some(sprite) = key.as_ref().and_then(|k| self.mod_art.get(k)) { + canvas.blit( + sprite, + (x * canvas.scale as f32).round() as i32, + (y * canvas.scale as f32).round() as i32, + ); + return Ok(()); + } + if let Some(id) = art.asset { + if self.config.hd_mode && art.hd_png.is_none() { + if let Some(sprite) = + self.hd + .sprite(id + frame % art.frames, canvas.scale, &self.palette)? + { + if sprite.width == art.logical_width as usize * canvas.scale + && sprite.height == art.logical_height as usize * canvas.scale + { + canvas.blit( + &sprite, + (x * canvas.scale as f32).round() as i32, + (y * canvas.scale as f32).round() as i32, + ); + return Ok(()); + } + } + } + } + let sprite = if let Some(id) = art + .asset + .filter(|_| !(self.config.hd_mode && art.hd_png.is_some())) + { + self.raw(id + frame % art.frames)? + } else { + art_sprite_variant( + &self.catalog, + &self.active.registry, + owner, + art, + frame, + self.config.hd_mode, + )? + }; + let scaled = if sprite.width == art.logical_width as usize + && sprite.height == art.logical_height as usize + { + self.cache.get(&sprite, canvas.scale, art.nearest)?.clone() + } else { + let mut out = Sprite::blank( + art.logical_width as usize * canvas.scale, + art.logical_height as usize * canvas.scale, + ); + for yy in 0..out.height { + for xx in 0..out.width { + out.pixels[yy * out.width + xx] = + sprite.pixels[(yy * sprite.height / out.height) * sprite.width + + xx * sprite.width / out.width]; + } + } + out + }; + canvas.blit( + &scaled, + (x * canvas.scale as f32).round() as i32, + (y * canvas.scale as f32).round() as i32, + ); + if let Some(key) = key { + if self + .mod_art + .values() + .map(|s| s.pixels.len() * 2) + .sum::() + + scaled.pixels.len() * 2 + > 128 * 1024 * 1024 + { + self.mod_art.clear(); + } + self.mod_art.insert(key, scaled); + } + Ok(()) + } + fn scene(&mut self, canvas: &mut Canvas) -> Result<()> { + let Some(world) = self.world.clone() else { + return Ok(()); + }; + let mission = self.active.registry.missions[&world.mission].clone(); + let alpha = self.clock.alpha(); + let interp = + |current: i32, previous: i32| previous as f32 + (current - previous) as f32 * alpha; + // Compose a joined terrain layer with a two-pixel gutter before filtering. + let mut terrain = Canvas::new(1); + terrain.image = Sprite { + width: 320, + height: 204, + pixels: vec![0; 320 * 204], + }; + let rows = if mission.columns > 0 { + mission.layout.len() / mission.columns as usize + } else { + 0 + }; + let offset = 200 - rows as i32 * 32 + world.scroll; + for (row, tiles) in mission + .layout + .chunks(mission.columns.max(1) as usize) + .enumerate() + { + let y = offset + row as i32 * 32; + if !(-34..202).contains(&y) { + continue; + } + for (col, index) in tiles.iter().enumerate() { + let n = row * mission.columns as usize + col; + let tile = &mission.tiles[*index]; + let art = if if mission.legacy_map.is_some() { + world.terrain_settled[n] + } else { + world.terrain_dead[n] + } { + tile.destroyed.as_ref().unwrap_or(&tile.art) + } else { + &tile.art + }; + let owner = self.active.registry.owners[&world.mission].clone(); + let mut original = art.clone(); + original.hd_png = None; + self.art( + &mut terrain, + &original, + &owner, + 0, + 16.0 + col as f32 * 32.0, + (y + 2) as f32, + )?; + } + } + let bg = upscale(&terrain.image, canvas.scale)?; + let shift = if world.tick > 0 { alpha - 1.0 } else { 0.0 }; + canvas.blit( + &bg, + 0, + (-2.0 * canvas.scale as f32 + shift * canvas.scale as f32).round() as i32, + ); + if self.config.hd_mode { + // Keep detailed terrain on the presentation canvas. The joined + // SD layer underneath supplies context and fallback at its edges. + for (row, tiles) in mission + .layout + .chunks(mission.columns.max(1) as usize) + .enumerate() + { + let y = offset + row as i32 * 32; + if !(-34..202).contains(&y) { + continue; + } + for (col, index) in tiles.iter().enumerate() { + let n = row * mission.columns as usize + col; + let tile = &mission.tiles[*index]; + let dead = if mission.legacy_map.is_some() { + world.terrain_settled[n] + } else { + world.terrain_dead[n] + }; + let art = if dead { + tile.destroyed.as_ref().unwrap_or(&tile.art) + } else { + &tile.art + }; + if art.hd_png.is_some() { + let owner = self.active.registry.owners[&world.mission].clone(); + self.art( + canvas, + art, + &owner, + 0, + 16.0 + col as f32 * 32.0, + y as f32 + shift, + )?; + } + } + } + } + for ground in [true, false] { + for e in &world.enemies { + let def = self.active.registry.enemies[&e.definition].clone(); + if def.ground != ground { + continue; + } + if let Some(art) = def.art { + let owner = self.active.registry.owners[&e.definition].clone(); + self.art( + canvas, + &art, + &owner, + if def.legacy.is_some() { + e.art_frame + } else { + e.frame + }, + interp(e.x, e.px), + interp(e.y, e.py), + )?; + } + } + } + for p in &world.projectiles { + let def = self.active.registry.weapons[&p.weapon].clone(); + let x = interp(p.x, p.px); + let y = interp(p.y, p.py); + if p.legacy.is_some() || p.legacy_enemy.is_some() { + if let Some(asset) = World::projectile_asset(p, &self.active.registry) { + let frame = if let Some(shot) = &p.legacy_enemy { + shot.art_frame % shot.frames.max(1) + } else { + p.legacy.as_ref().map_or(0, |shot| shot.art_frame) + }; + let original = self.raw(asset + frame)?; + let hd = if self.config.hd_mode { + self.hd.sprite(asset + frame, canvas.scale, &self.palette)? + } else { + None + }; + let sprite = match hd { + Some(sprite) => sprite, + None => self.cache.get(&original, canvas.scale, false)?.clone(), + }; + canvas.blit( + &sprite, + (x * canvas.scale as f32).round() as i32, + (y * canvas.scale as f32).round() as i32, + ); + } + continue; + } + if matches!(def.behavior, crate::content::WeaponBehavior::Beam) { + canvas.rect(x as i32, 0, 2, world.player.y, 255); + } else if let Some(art) = def.art { + let owner = self.active.registry.owners[&p.weapon].clone(); + self.art( + canvas, + &art, + &owner, + p.age / 2, + x - art.logical_width as f32 / 2.0, + y - art.logical_height as f32 / 2.0, + )?; + } else { + canvas.rect(x as i32, y as i32, 2, 4, if p.hostile { 34 } else { 255 }); + } + } + let dark = matches!( + world.mission.0.as_str(), + "base:sector_2_wave_8" | "base:sector_3_wave_3" + ); + let player = self.catalog.id(if dark { + if world.player_flash { + "FPLAYER_PIC" + } else { + "DPLAYER_PIC" + } + } else { + "LPLAYER_PIC" + })?; + let player_frame = player + world.player.bank.clamp(0, 6) as u32; + let s = self.raw(player_frame)?; + let hd = if self.config.hd_mode { + self.hd.sprite(player_frame, canvas.scale, &self.palette)? + } else { + None + }; + let scaled = match hd { + Some(sprite) => sprite, + None => self.cache.get(&s, canvas.scale, false)?.clone(), + }; + canvas.blit( + &scaled, + (interp(world.player.x, world.player.px) * canvas.scale as f32) as i32, + (interp(world.player.y, world.player.py) * canvas.scale as f32) as i32, + ); + for pickup in &world.pickups { + if pickup + .legacy + .as_ref() + .is_some_and(|legacy| legacy.countdown.is_some()) + { + if let Ok(asset) = self.catalog.id("N$_PIC") { + let original = self.raw(asset)?; + let sprite = self.cache.get(&original, canvas.scale, false)?.clone(); + canvas.blit( + &sprite, + pickup.x * canvas.scale as i32, + pickup.y * canvas.scale as i32, + ); + } + continue; + } + if let Some(art) = self.active.registry.items[&pickup.item].art.clone() { + let owner = self.active.registry.owners[&pickup.item].clone(); + self.art( + canvas, + &art, + &owner, + pickup + .legacy + .as_ref() + .map_or((world.tick / 3) as u32, |legacy| legacy.art_frame), + pickup.x as f32, + pickup.y as f32, + )?; + } + } + for effect in &world.effects { + if let Ok(id) = self.catalog.id("AIRMED_BLK") { + if let Ok(s) = self.raw(id + effect.age as u32 / 2) { + let scaled = self.cache.get(&s, canvas.scale, false)?.clone(); + canvas.blit( + &scaled, + (effect.x - s.width as i32 / 2) * canvas.scale as i32, + (effect.y - s.height as i32 / 2) * canvas.scale as i32, + ); + } + } else { + canvas.rect( + effect.x - effect.age as i32 / 2, + effect.y - 2, + effect.age as i32 + 2, + 4, + 50, + ); + } + } + // The original shield bars sit beside the playfield. A full-width + // bottom panel would cover the player's engines at its initial y=160. + canvas.rect(0, 0, 16, 200, 0); + canvas.rect(304, 0, 16, 200, 0); + for (x, amount) in [(8, world.player.super_shield), (308, world.player.shield)] { + for level in 0..amount.clamp(0, 100) { + canvas.rect(x, 199 - level * 2, 4, 1, (74 - level * 27 / 100) as u16); + } + } + self.font.text( + canvas, + 132, + 2, + &format!("${:08}", world.player.credits), + 100, + ); + Ok(()) + } + fn draw(&mut self) -> Result { + let mut canvas = Canvas::new(self.config.scale); + canvas.clear(0); + if let Some(movie) = &self.cinematic { + canvas.blit(&nearest(&movie.image, canvas.scale), 0, 0); + return Ok(canvas); + } + if self.world.is_some() { + self.scene(&mut canvas)?; + if self.screen == Screen::Game { + return Ok(canvas); + } + } else if let Ok(id) = self.catalog.id("NEWMAIN_PIC") { + let s = self.raw(id)?; + canvas.blit(&nearest(&s, canvas.scale), 0, 0); + } + canvas.rect(12, 8, 296, 184, closest(&self.palette, [10, 15, 32])); + canvas.rect(12, 8, 296, 1, 100); + canvas.rect(12, 191, 296, 1, 100); + let title = match self.screen { + Screen::Main => "RAPTOR / RUST", + Screen::Missions => "MISSION SELECT", + Screen::Shop => "HANGAR / SHOP", + Screen::Inventory => "INVENTORY / EQUIPMENT", + Screen::Mods => "MOD MANAGER", + Screen::Options => "OPTIONS", + Screen::Pause => "PAUSED", + Screen::Results => "FLIGHT REPORT", + Screen::Help => "FLIGHT CONTROLS", + Screen::Credits => "CREDITS", + Screen::Pilots => "LOAD PILOT", + Screen::Diagnostics => "MOD / SAVE DIAGNOSTICS", + Screen::Bindings => "KEYBOARD BINDINGS", + Screen::Cinematic => "", + Screen::Game => "", + }; + self.font.text(&mut canvas, 22, 17, title, 50); + self.font.text( + &mut canvas, + 22, + 29, + &format!("PILOT {} ${}", self.pilot.callsign, self.pilot.credits), + 100, + ); + let rows = self.rows(); + let card = if self.screen == Screen::Missions { + self.missions().get(self.selected).and_then(|id| { + self.active.registry.missions[id] + .art + .clone() + .map(|art| (art, self.active.registry.owners[id].clone())) + }) + } else { + None + }; + let first = self.selected.saturating_sub(8); + for (index, row) in rows.iter().enumerate().skip(first).take(10) { + let y = 46 + (index - first) as i32 * 11; + if index == self.selected { + canvas.rect( + 20, + y - 2, + if card.is_some() { 126 } else { 280 }, + 10, + closest(&self.palette, [25, 45, 65]), + ); + } + self.font.text( + &mut canvas, + 24, + y, + &if card.is_some() { + row.chars().take(20).collect::() + } else { + row.clone() + }, + if index == self.selected { 50 } else { 100 }, + ); + } + if let Some((mut art, owner)) = card { + let height = (150 * art.logical_height / art.logical_width).min(108); + art.logical_width = 150; + art.logical_height = height; + self.art(&mut canvas, &art, &owner, 0, 154.0, 52.0)?; + } + if self.screen == Screen::Mods { + if self.selected >= 2 { + if let Some(id) = self.mod_ids().get(self.selected - 2) { + let m = &self.discovery.mods[id]; + self.font + .text(&mut canvas, 22, 160, &m.manifest.description, 100); + } + } + self.font.text( + &mut canvas, + 22, + 171, + "ENTER toggle/apply LEFT/RIGHT priority", + 50, + ); + } else if self.screen == Screen::Help { + let key = |action: &str| { + self.config + .bindings + .get(action) + .map(String::as_str) + .unwrap_or("unbound") + }; + for (n, line) in [ + format!( + "Move: {} / {} / {} / {}", + key("left"), + key("right"), + key("up"), + key("down") + ), + format!("Fire: {} Special: {}", key("fire"), key("special")), + format!("Cycle: {} Mega bomb: {}", key("cycle"), key("bomb")), + "ESC: pause O: options".into(), + "Mouse / controller selectable in Options".into(), + "ENTER: choose ESC: back".into(), + "Shop: ENTER buy Inventory: S sell".into(), + ] + .iter() + .enumerate() + { + self.font + .text(&mut canvas, 24, 49 + n as i32 * 14, line, 100); + } + } else if self.screen == Screen::Credits { + for (n, line) in [ + "Raptor: Cygnus Studios / Apogee", + "Reconstructed engine: nukeykt / skynettx", + "Rust replica: GPL v2 or later", + "FM core: Nuked-OPL3 / Tony Gies", + "Game assets: your original purchased copy", + ] + .iter() + .enumerate() + { + self.font + .text(&mut canvas, 24, 52 + n as i32 * 16, line, 100); + } + } else { + self.font.text( + &mut canvas, + 22, + 171, + "ENTER choose ESC back N new pilot D details", + 50, + ); + } + if !self.message.is_empty() { + self.font.text(&mut canvas, 22, 181, &self.message, 34); + } + Ok(canvas) + } +} +const ACTIONS: [&str; 8] = [ + "up", "down", "left", "right", "fire", "special", "cycle", "bomb", +]; +fn binding_matches(config: &Config, action: &str, key: Option) -> bool { + key.is_some() + && config + .bindings + .get(action) + .and_then(|value| Scancode::from_name(value)) + == key +} +// A failed load uses a display placeholder; never validate that placeholder +// in place of the existing file when mods are changed. +fn pilot_for_mods( + path: &std::path::Path, + current: &Pilot, + registry: &Registry, + pins: &[modding::ModPin], +) -> Result { + if path.exists() { + Pilot::load(path, registry, pins) + } else { + current.validate(registry, pins)?; + Ok(current.clone()) + } +} +fn restore_scripts(runtime: &mut modding::ScriptRuntime, pilot: &Pilot) { + runtime.states = pilot.script_state.clone(); + runtime.rng = pilot.script_rng.clone(); +} +fn mission_palette(base: &[[u8; 3]; 256], world: Option<&World>) -> [[u8; 3]; 256] { + let mut palette = *base; + let Some(world) = world else { + return palette; + }; + if world.tick < 3 { + return palette; + } + let updates = (world.tick - 1) / 2; + let water = (updates - (updates + 3) / 4) % 5; + let fire = (updates / 2) % 5; + for index in 0..5 { + palette[240 + index] = base[240 + (index + water as usize) % 5]; + palette[245 + index] = base[245 + (index + fire as usize) % 5]; + } + const GLOW: [u8; 20] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]; + for (index, phase) in [(250, 0_u64), (251, 8_u64)] { + let amount = GLOW[((phase + updates - 1) % 20) as usize]; + palette[index] = base[index].map(|value| { + let value = (value >> 2).saturating_sub(amount); + (value << 2) | (value >> 4) + }); + } + if updates >= 2 { + palette[if (updates / 2 - 1) % 2 == 0 { 252 } else { 253 }] = [0; 3]; + } + if !world.palette_blue { + palette[254] = [0; 3]; + } + if (updates - 1) % 6 >= 3 { + palette[255] = [0; 3]; + } + palette +} +fn closest(palette: &[[u8; 3]; 256], rgb: [u8; 3]) -> u16 { + palette + .iter() + .enumerate() + .min_by_key(|(_, c)| { + (0..3) + .map(|i| (c[i] as i32 - rgb[i] as i32).pow(2)) + .sum::() + }) + .unwrap() + .0 as u16 +} +fn viewport(w: u32, h: u32, aspect: bool) -> Rect { + if aspect { + let width = w.min(h * 4 / 3); + let height = h.min(w * 3 / 4); + Rect::new( + ((w - width) / 2) as i32, + ((h - height) / 2) as i32, + width, + height, + ) + } else { + Rect::new(0, 0, w, h) + } +} +pub fn run( + catalog: Catalog, + base: Registry, + paths: Paths, + mods_root: PathBuf, + frames: Option, + screenshot: Option, + preview: Option, + movie_preview: Option, +) -> Result<()> { + let mut host = Host::new(catalog, base, paths, mods_root, frames.is_some())?; + if let Some(id) = preview { + if frames.is_some() { + host.new_pilot()?; + } + host.start(id)?; + } + if let Some(kind) = movie_preview { + host.show_movie(kind, Screen::Main)?; + } + let sdl = sdl2::init().map_err(|e| anyhow!(e))?; + let video = sdl.video().map_err(|e| anyhow!(e))?; + let window = video + .window( + "RaptorReplica - Rust", + host.config.width, + host.config.height, + ) + .position_centered() + .resizable() + .allow_highdpi() + .build()?; + let mut canvas = match window.into_canvas().accelerated().present_vsync().build() { + Ok(c) => c, + Err(_) => video + .window( + "RaptorReplica - Rust", + host.config.width, + host.config.height, + ) + .resizable() + .build()? + .into_canvas() + .software() + .build()?, + }; + let creator = canvas.texture_creator(); + let mut texture = creator.create_texture_streaming( + PixelFormatEnum::RGBA32, + (320 * host.config.scale) as u32, + (200 * host.config.scale) as u32, + )?; + let mut applied = (0usize, false, false, 0u32, 0u32); + let mut events = sdl.event_pump().map_err(|e| anyhow!(e))?; + let controllers = sdl.game_controller().map_err(|e| anyhow!(e))?; + let mut controller = (0..controllers.num_joysticks().unwrap_or(0)) + .filter(|index| controllers.is_game_controller(*index)) + .find_map(|index| controllers.open(index).ok()); + if let Ok(audio) = sdl.audio() { + let genmidi = host.catalog.named("GENMIDI_OP2")?; + let desired = AudioSpecDesired { + freq: Some(44100), + channels: Some(2), + samples: Some(512), + }; + match audio.open_playback(None, &desired, |spec| { + Mixer::new(spec.freq as u32, &genmidi).expect("validated instrument table") + }) { + Ok(device) => { + let mut device = device; + device.lock().set_fx_channels(host.config.fx_channels); + device.resume(); + host.audio = Some(device) + } + Err(e) => host.message = format!("Audio unavailable: {e}"), + } + } + if let Some(music) = host.desired_music { + if let Ok(score) = host.catalog.read(music).and_then(|b| MusScore::decode(&b)) { + if let Some(audio) = &mut host.audio { + audio.lock().play_with_fade(score, true, true); + } + } + } else { + host.music("MAINMENU_MUS"); + } + let mut previous = Instant::now(); + let mut count = 0u32; + let mut cycle = false; + let mut bomb = false; + let mut quit = false; + while !quit { + for event in events.poll_iter() { + match event { + Event::Quit { .. } => quit = true, + Event::ControllerDeviceAdded { which, .. } => { + controller = controllers.open(which).ok(); + } + Event::ControllerDeviceRemoved { which, .. } => { + if controller + .as_ref() + .is_some_and(|c| c.instance_id() == which) + { + controller = (0..controllers.num_joysticks().unwrap_or(0)) + .filter(|index| controllers.is_game_controller(*index)) + .find_map(|index| controllers.open(index).ok()); + } + } + Event::ControllerButtonDown { button, .. } => { + if host.screen == Screen::Cinematic { + host.finish_movie(); + continue; + } + if button == Button::Start { + if let Err(e) = host.back() { + host.message = e.to_string() + } + } else if host.screen != Screen::Game { + match button { + Button::DPadUp => host.selected = host.selected.saturating_sub(1), + Button::DPadDown => { + host.selected = + (host.selected + 1).min(host.rows().len().saturating_sub(1)) + } + Button::A => match host.activate() { + Ok(r) => quit = !r, + Err(e) => host.message = format!("{e:#}"), + }, + Button::B => { + if let Err(e) = host.back() { + host.message = e.to_string(); + } + } + _ => {} + } + } else if button == Button::X { + cycle = true + } else if button == Button::Y { + bomb = true + } + } + Event::MouseWheel { y, .. } if host.screen != Screen::Game => { + if y > 0 { + host.selected = host.selected.saturating_sub(y as usize); + } else { + host.selected = host + .selected + .saturating_add(y.unsigned_abs() as usize) + .min(host.rows().len().saturating_sub(1)); + } + } + Event::MouseButtonDown { x, y, .. } if host.screen != Screen::Game => { + if host.screen == Screen::Cinematic { + host.finish_movie(); + continue; + } + let (w, h) = canvas.window().size(); + let rect = viewport(w, h, host.config.aspect_correct); + let yy = (y - rect.y()) * 200 / rect.height() as i32; + let xx = (x - rect.x()) * 320 / rect.width() as i32; + if (20..300).contains(&xx) && (44..156).contains(&yy) { + let first = host.selected.saturating_sub(8); + let selection = first + ((yy - 44) / 11) as usize; + if selection < host.rows().len() { + host.selected = selection; + match host.activate() { + Ok(r) => quit = !r, + Err(e) => host.message = format!("{e:#}"), + } + } + } + } + Event::KeyDown { + keycode: Some(key), + scancode: physical_key, + keymod, + repeat: false, + .. + } => { + if host.screen == Screen::Cinematic { + host.finish_movie(); + continue; + } + if let Some(action) = host.awaiting_binding.take() { + if key == Keycode::Escape { + host.message = "Binding change cancelled".into(); + } else if let Some(scancode) = physical_key { + host.config + .bindings + .insert(action.clone(), scancode.name().to_string()); + host.message = format!("{action}: {}", scancode.name()); + if let Err(e) = host.save_config() { + host.message = e.to_string(); + } + } + continue; + } + if host.screen == Screen::Game + && ACTIONS + .iter() + .any(|action| binding_matches(&host.config, action, physical_key)) + { + cycle |= binding_matches(&host.config, "cycle", physical_key); + bomb |= binding_matches(&host.config, "bomb", physical_key); + continue; + } + if key == Keycode::Return + && keymod + .intersects(sdl2::keyboard::Mod::LALTMOD | sdl2::keyboard::Mod::RALTMOD) + { + host.config.fullscreen = !host.config.fullscreen; + continue; + } + if key == Keycode::Escape || key == Keycode::P && host.screen == Screen::Game { + if let Err(e) = host.back() { + host.message = e.to_string() + } + continue; + } + if host.screen == Screen::Game { + match key { + Keycode::O => { + host.previous = Screen::Pause; + host.go(Screen::Options) + } + _ if binding_matches(&host.config, "cycle", physical_key) => { + cycle = true + } + _ if binding_matches(&host.config, "bomb", physical_key) => bomb = true, + _ => {} + } + continue; + } + match key { + Keycode::Up => host.selected = host.selected.saturating_sub(1), + Keycode::Down => { + host.selected = + (host.selected + 1).min(host.rows().len().saturating_sub(1)) + } + Keycode::Return => match host.activate() { + Ok(r) => quit = !r, + Err(e) => host.message = format!("{e:#}"), + }, + Keycode::D if host.world.is_none() => { + host.previous = host.screen; + host.go(Screen::Diagnostics); + } + Keycode::N if host.world.is_none() => { + if let Err(e) = host.new_pilot() { + host.message = e.to_string(); + } + } + Keycode::S if host.screen == Screen::Inventory => { + if let Some(id) = + host.pilot.inventory.keys().nth(host.selected).cloned() + { + if let Err(e) = host + .pilot + .sell(&id, &host.active.registry) + .and_then(|_| host.save()) + { + host.message = e.to_string() + } + } + } + Keycode::Left | Keycode::Right + if host.screen == Screen::Mods && host.selected >= 2 => + { + if let Some(id) = host.mod_ids().get(host.selected - 2) { + if let Some(n) = host.pending.iter().position(|m| m == id) { + let next = if key == Keycode::Left { + n.saturating_sub(1) + } else { + (n + 1).min(host.pending.len() - 1) + }; + host.pending.swap(n, next); + } + } + } + _ => {} + } + } + _ => {} + } + } + let desired = ( + host.config.scale, + host.config.fullscreen, + host.config.borderless, + host.config.width, + host.config.height, + ); + if desired != applied { + if host.config.scale != applied.0 { + texture = creator.create_texture_streaming( + PixelFormatEnum::RGBA32, + (320 * host.config.scale) as u32, + (200 * host.config.scale) as u32, + )?; + } + if let Err(e) = canvas + .window_mut() + .set_fullscreen(if host.config.fullscreen { + FullscreenType::Desktop + } else { + FullscreenType::Off + }) + { + host.message = e; + } + canvas.window_mut().set_bordered(!host.config.borderless); + if !host.config.fullscreen { + let _ = canvas + .window_mut() + .set_size(host.config.width, host.config.height); + } + applied = desired; + } + let now = Instant::now(); + let elapsed = now.duration_since(previous).as_nanos().min(250_000_000) as u64; + let elapsed = if frames.is_some() { + 16_666_667 + } else { + elapsed + }; + previous = now; + let keyboard = events.keyboard_state(); + let pressed = |action: &str| { + host.config + .bindings + .get(action) + .and_then(|key| Scancode::from_name(key)) + .is_some_and(|key| keyboard.is_scancode_pressed(key)) + }; + let mut input = Input { + dx: pressed("right") as i32 - pressed("left") as i32, + dy: pressed("down") as i32 - pressed("up") as i32, + fire: pressed("fire") || frames.is_some() && host.screen == Screen::Game, + special: pressed("special"), + cycle, + bomb, + ..Input::default() + }; + if host.config.control == "mouse" { + let mouse = events.mouse_state(); + let (w, h) = canvas.window().size(); + let r = viewport(w, h, host.config.aspect_correct); + input.absolute = Some([ + (mouse.x() - r.x()) * 320 / r.width() as i32 - 16, + (mouse.y() - r.y()) * 200 / r.height() as i32 - 16, + ]); + input.fire = mouse.left(); + input.special = mouse.right(); + } + if host.config.control == "controller" { + if let Some(c) = &controller { + input.dx = if i32::from(c.axis(Axis::LeftX)).abs() > 8000 { + c.axis(Axis::LeftX).signum() as i32 + } else { + 0 + }; + input.dy = if i32::from(c.axis(Axis::LeftY)).abs() > 8000 { + c.axis(Axis::LeftY).signum() as i32 + } else { + 0 + }; + if input.dx == 0 { + input.dx = + c.button(Button::DPadRight) as i32 - c.button(Button::DPadLeft) as i32; + } + if input.dy == 0 { + input.dy = c.button(Button::DPadDown) as i32 - c.button(Button::DPadUp) as i32; + } + input.fire = c.button(Button::A); + input.special = c.button(Button::B); + } + } + if let Err(e) = host.update(input, elapsed) { + host.message = format!("Mission paused: {e:#}"); + host.go(Screen::Pause); + } + cycle = false; + bomb = false; + if let Some(audio) = &mut host.audio { + let mut mixer = audio.lock(); + mixer.set_fx_channels(host.config.fx_channels); + mixer.music_volume = host.config.music_volume; + mixer.fx_volume = host.config.fx_volume; + } + let image = host.draw()?; + let palette = if let Some(movie) = &host.cinematic { + movie.palette(&host.palette) + } else { + mission_palette(&host.palette, host.world.as_ref()) + }; + let rgba = image.rgba(&palette, host.config.scanlines); + texture.update(None, &rgba, image.image.width * 4)?; + let (w, h) = canvas.output_size().map_err(|e| anyhow!(e))?; + canvas.set_draw_color(sdl2::pixels::Color::BLACK); + canvas.clear(); + canvas + .copy(&texture, None, viewport(w, h, host.config.aspect_correct)) + .map_err(|e| anyhow!(e))?; + if frames.is_some_and(|n| count + 1 >= n) { + if let Some(path) = &screenshot { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let presented = canvas + .read_pixels(None, PixelFormatEnum::RGBA32) + .map_err(|e| anyhow!(e))?; + image::save_buffer(path, &presented, w, h, image::ColorType::Rgba8)?; + } + } + canvas.present(); + count += 1; + if frames.is_some_and(|n| count >= n) { + quit = true; + } + if frames.is_some() { + std::thread::sleep(Duration::from_millis(1)); + } + } + if frames.is_none() { + host.config.save(&host.paths)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn loading_a_pilot_restores_scripts_before_hangar_saves() { + let (_, mut pilot) = fixture(); + pilot.script_state.insert( + "weapon:behavior.rhai".into(), + serde_json::json!({"shots": 42}), + ); + pilot.script_rng.insert( + "weapon:behavior.rhai".into(), + crate::simulation::LegacyRng::new(731), + ); + let mut runtime = modding::ScriptRuntime::new(); + restore_scripts(&mut runtime, &pilot); + let mut resaved = pilot.clone(); + resaved.script_state = runtime.states.clone(); + resaved.script_rng = runtime.rng.clone(); + assert_eq!(resaved.script_state, pilot.script_state); + assert_eq!(resaved.script_rng["weapon:behavior.rhai"].seed, 731); + restore_scripts(&mut runtime, &Pilot::default()); + assert!(runtime.states.is_empty()); + assert!(runtime.rng.is_empty()); + } + fn fixture() -> (Registry, Pilot) { + let mut registry = Registry::default(); + let mut pilot = Pilot::default(); + pilot.inventory.clear(); + let mission: crate::content::MissionDef = serde_json::from_value(serde_json::json!({ + "id": pilot.mission, "name": "Save safety fixture", "duration": 100 + })) + .unwrap(); + registry.missions.insert(mission.id.clone(), mission); + (registry, pilot) + } + #[test] + fn applying_mods_checks_saved_pilot_instead_of_display_placeholder() { + let (registry, placeholder) = fixture(); + assert!(placeholder.validate(®istry, &[]).is_ok()); + let pin = modding::ModPin { + id: "example".into(), + version: "1.0.0".into(), + hash: "required".into(), + }; + let mut saved = placeholder.clone(); + saved.mods = vec![pin.clone()]; + saved.callsign = "SAVED PILOT".into(); + saved.credits = 4242; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("pilot.json"); + saved.save(&path).unwrap(); + let before = std::fs::read(&path).unwrap(); + assert!(pilot_for_mods(&path, &placeholder, ®istry, &[]).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), before); + let restored = pilot_for_mods(&path, &placeholder, ®istry, &[pin]).unwrap(); + assert_eq!(restored.callsign, "SAVED PILOT"); + assert_eq!(restored.credits, 4242); + } + #[test] + fn corrupt_existing_slot_cannot_be_replaced_by_valid_placeholder() { + let (registry, placeholder) = fixture(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("pilot.json"); + std::fs::write(&path, b"corrupt existing save").unwrap(); + assert!(pilot_for_mods(&path, &placeholder, ®istry, &[]).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), b"corrupt existing save"); + let unused = dir.path().join("unused.json"); + assert_eq!( + pilot_for_mods(&unused, &placeholder, ®istry, &[]) + .unwrap() + .callsign, + placeholder.callsign + ); + } + #[test] + fn full_hd_window_retains_centered_four_three_viewport() { + assert_eq!(viewport(1920, 1080, true), Rect::new(240, 0, 1440, 1080)); + assert_eq!(viewport(1920, 1080, false), Rect::new(0, 0, 1920, 1080)); + } + #[test] + fn palette_effects_do_not_consume_simulation_rng() { + let (registry, pilot) = fixture(); + let mut world = World::new(&pilot.mission, &pilot, ®istry).unwrap(); + world.tick = 7; + world.palette_blue = false; + let before = world.rng.seed; + let base = [[255, 128, 64]; 256]; + let first = mission_palette(&base, Some(&world)); + assert_eq!(first, mission_palette(&base, Some(&world))); + assert_eq!(world.rng.seed, before); + assert_eq!(first[254], [0; 3]); + world.palette_blue = true; + assert_eq!(mission_palette(&base, Some(&world))[254], base[254]); + } +} diff --git a/src/hd.rs b/src/hd.rs new file mode 100644 index 00000000..427b3558 --- /dev/null +++ b/src/hd.rs @@ -0,0 +1,439 @@ +//! Opt-in remaster artwork tied to the original asset ID and animation canvas. +//! Missing or rejected frames fall back to the original crisp sprite. +use crate::assets::{Catalog, Sprite, contained}; +use anyhow::{Context, Result, ensure}; +use image::{ + ImageReader, RgbaImage, + imageops::{self, FilterType}, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + fs, + path::{Path, PathBuf}, +}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Manifest { + pub format_version: u32, + pub name: String, + #[serde(default)] + pub description: String, + pub sequences: Vec, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Sequence { + pub name: String, + pub base_asset: u32, + pub frame_count: u32, + pub frames: Vec, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Frame { + pub frame: u32, + pub file: PathBuf, + pub logical_width: u32, + pub logical_height: u32, + /// Anchor relative to the original canvas. Version 1 requires [0, 0]. + pub origin: [i32; 2], + /// Exact original catalog payload, so changes cannot quietly misalign art. + pub source_sha256: String, + /// Optional pixel rectangle [x, y, width, height] in an atlas PNG. + #[serde(default)] + pub crop: Option<[u32; 4]>, +} +struct Replacement { + frame: Frame, + rgba: RgbaImage, +} +#[derive(Default)] +pub struct HdAssets { + replacements: BTreeMap, + scaled: BTreeMap<(u32, usize), Sprite>, + pub diagnostics: Vec, +} +impl HdAssets { + pub fn load(root: &Path, catalog: &Catalog) -> Self { + let mut result = Self::default(); + if !root.exists() { + return result; + } + match result.read(root, catalog) { + Ok(()) => {} + Err(e) => { + // Reject the complete pack if its sequence metadata is invalid. + result.replacements.clear(); + result + .diagnostics + .push(format!("HD pack {}: {e:#}", root.display())); + } + } + result + } + fn read(&mut self, root: &Path, catalog: &Catalog) -> Result<()> { + let bytes = fs::read(contained(root, Path::new("hd.json"))?)?; + ensure!(bytes.len() <= 256 * 1024, "HD metadata exceeds 256 KiB"); + let manifest: Manifest = serde_json::from_slice(&bytes)?; + ensure!( + manifest.format_version == 1, + "unsupported HD artwork format {}", + manifest.format_version + ); + ensure!(manifest.sequences.len() <= 512, "too many HD sequences"); + let mut ids = BTreeMap::new(); + for sequence in &manifest.sequences { + ensure!( + (1..=512).contains(&sequence.frame_count), + "invalid frame count for {}", + sequence.name + ); + ensure!( + sequence.frames.len() <= sequence.frame_count as usize, + "too many supplied frames for {}", + sequence.name + ); + for frame in &sequence.frames { + ensure!( + frame.frame < sequence.frame_count, + "{}: frame {} outside sequence", + sequence.name, + frame.frame + ); + let id = sequence + .base_asset + .checked_add(frame.frame) + .context("HD asset ID overflow")?; + ensure!(ids.insert(id, ()).is_none(), "duplicate HD asset {id:05x}"); + ensure!(self.replacements.len() < 4096, "too many HD frames"); + match Self::read_frame(root, catalog, id, frame) { + Ok(replacement) => { + if self + .replacements + .values() + .map(|r| r.rgba.as_raw().len()) + .sum::() + + replacement.rgba.as_raw().len() + > 128 * 1024 * 1024 + { + self.diagnostics.push(format!( + "HD {id:05x}: pack exceeds 128 MiB artwork budget; using original" + )); + } else { + self.replacements.insert(id, replacement); + } + } + Err(e) => self.diagnostics.push(format!( + "HD {} frame {} ({id:05x}): {e:#}; using original", + sequence.name, frame.frame + )), + } + } + if sequence.frames.len() != sequence.frame_count as usize { + self.diagnostics.push(format!( + "HD {}: {} of {} frames supplied; uncovered frames use original artwork", + sequence.name, + sequence.frames.len(), + sequence.frame_count + )); + } + } + Ok(()) + } + fn read_frame(root: &Path, catalog: &Catalog, id: u32, frame: &Frame) -> Result { + let source = catalog.read(id)?; + let original = Sprite::decode(&source)?; + validate_frame(frame, &original, &source)?; + let path = contained(root, &frame.file)?; + ensure!( + fs::metadata(&path)?.len() <= 32 * 1024 * 1024, + "HD PNG exceeds 32 MiB" + ); + let mut reader = ImageReader::open(path)?.with_guessed_format()?; + ensure!( + reader.format() == Some(image::ImageFormat::Png), + "HD artwork must be PNG" + ); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(4096); + limits.max_image_height = Some(4096); + limits.max_alloc = Some(64 * 1024 * 1024); + reader.limits(limits); + let mut rgba = reader.decode()?.into_rgba8(); + ensure!( + rgba.width() as u64 * rgba.height() as u64 <= 4_194_304, + "HD PNG exceeds pixel limit" + ); + if let Some([x, y, width, height]) = frame.crop { + ensure!( + width > 0 + && height > 0 + && x.checked_add(width).is_some_and(|n| n <= rgba.width()) + && y.checked_add(height).is_some_and(|n| n <= rgba.height()), + "HD atlas crop exceeds its PNG" + ); + rgba = imageops::crop_imm(&rgba, x, y, width, height).to_image(); + } + ensure!( + rgba.width() as u64 * frame.logical_height as u64 + == rgba.height() as u64 * frame.logical_width as u64, + "HD frame aspect must match the original canvas" + ); + ensure!( + rgba.width() >= frame.logical_width * 2 && rgba.height() >= frame.logical_height * 2, + "HD artwork must supply at least twice the logical resolution" + ); + ensure!( + rgba.pixels().any(|p| p[3] == 0), + "HD frame needs a transparent background" + ); + ensure!( + rgba.pixels().any(|p| p[3] >= 128), + "HD frame has no visible pixels" + ); + Ok(Replacement { + frame: frame.clone(), + rgba, + }) + } + pub fn coverage(&self) -> usize { + self.replacements.len() + } + /// Return already detailed artwork at the canvas resolution; never run ScaleNx on it. + pub fn sprite( + &mut self, + id: u32, + scale: usize, + palette: &[[u8; 3]; 256], + ) -> Result> { + ensure!( + (1..=4).contains(&scale), + "HD presentation scale must be 1..4" + ); + let Some(replacement) = self.replacements.get(&id) else { + return Ok(None); + }; + if !self.scaled.contains_key(&(id, scale)) { + let width = replacement.frame.logical_width as usize * scale; + let height = replacement.frame.logical_height as usize * scale; + let resized = imageops::resize( + &replacement.rgba, + width as u32, + height as u32, + FilterType::Lanczos3, + ); + let mut sprite = Sprite::blank(width, height); + let mut colors = BTreeMap::new(); + for (destination, pixel) in sprite.pixels.iter_mut().zip(resized.pixels()) { + if pixel[3] < 128 { + continue; + } + let key = [pixel[0], pixel[1], pixel[2]]; + *destination = *colors.entry(key).or_insert_with(|| closest(palette, key)); + } + if self + .scaled + .values() + .map(|s| s.pixels.len() * 2) + .sum::() + + sprite.pixels.len() * 2 + > 64 * 1024 * 1024 + { + self.scaled.clear(); + } + self.scaled.insert((id, scale), sprite); + } + Ok(self.scaled.get(&(id, scale)).cloned()) + } +} +fn validate_frame(frame: &Frame, original: &Sprite, source: &[u8]) -> Result<()> { + ensure!( + frame.logical_width as usize == original.width + && frame.logical_height as usize == original.height, + "HD logical dimensions must equal original {}x{}", + original.width, + original.height + ); + ensure!( + frame.origin == [0, 0], + "HD format 1 preserves the original top-left anchor [0, 0]" + ); + ensure!( + frame.source_sha256 == format!("{:x}", Sha256::digest(source)), + "original source hash changed; regenerate or review this frame" + ); + Ok(()) +} +fn closest(palette: &[[u8; 3]; 256], rgb: [u8; 3]) -> u16 { + palette + .iter() + .enumerate() + .min_by_key(|(_, c)| { + (0..3) + .map(|j| (c[j] as i32 - rgb[j] as i32).pow(2)) + .sum::() + }) + .unwrap() + .0 as u16 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::assets::TRANSPARENT; + fn frame(source: &[u8]) -> Frame { + Frame { + frame: 0, + file: "ship.png".into(), + logical_width: 2, + logical_height: 2, + origin: [0, 0], + source_sha256: format!("{:x}", Sha256::digest(source)), + crop: None, + } + } + #[test] + fn metadata_cannot_change_original_canvas_or_anchor() { + let source = b"source"; + let original = Sprite::blank(2, 2); + let mut f = frame(source); + assert!(validate_frame(&f, &original, source).is_ok()); + f.logical_width = 3; + assert!(validate_frame(&f, &original, source).is_err()); + f.logical_width = 2; + f.origin = [1, 0]; + assert!(validate_frame(&f, &original, source).is_err()); + f.origin = [0, 0]; + assert!(validate_frame(&f, &original, b"changed").is_err()); + } + #[test] + fn detailed_art_preserves_canvas_and_transparency_without_filtering_twice() { + let source = b"source"; + let mut rgba = RgbaImage::new(8, 8); + for y in 2..6 { + for x in 2..6 { + rgba.put_pixel(x, y, image::Rgba([255, 0, 0, 255])); + } + } + let mut art = HdAssets::default(); + art.replacements.insert( + 1, + Replacement { + frame: frame(source), + rgba, + }, + ); + let mut palette = [[0; 3]; 256]; + palette[100] = [255, 0, 0]; + let s = art.sprite(1, 4, &palette).unwrap().unwrap(); + assert_eq!((s.width, s.height), (8, 8)); + assert_eq!(s.pixels[0], TRANSPARENT); + assert_eq!(s.pixels[3 * 8 + 3], 100); + assert!(art.sprite(2, 4, &palette).unwrap().is_none()); + } + fn fixture() -> (tempfile::TempDir, Catalog, Manifest) { + let dir = tempfile::tempdir().unwrap(); + let mut source = Vec::new(); + for n in [1_i32, 0, 0, 2, 2] { + source.extend(n.to_le_bytes()); + } + source.extend([1, 2, 3, 4]); + fs::write(dir.path().join("source"), &source).unwrap(); + fs::write( + dir.path().join("INDEX"), + format!("00001 {} source\n", source.len()), + ) + .unwrap(); + fs::create_dir(dir.path().join("hd")).unwrap(); + let mut png = RgbaImage::new(8, 8); + for y in 2..6 { + for x in 2..6 { + png.put_pixel(x, y, image::Rgba([100, 20, 20, 255])); + } + } + png.save(dir.path().join("hd/ship.png")).unwrap(); + let manifest = Manifest { + format_version: 1, + name: "Fixture".into(), + description: String::new(), + sequences: vec![Sequence { + name: "ship".into(), + base_asset: 1, + frame_count: 2, + frames: vec![frame(&source)], + }], + }; + let catalog = Catalog::open(dir.path()).unwrap(); + (dir, catalog, manifest) + } + fn pack(dir: &Path, catalog: &Catalog, manifest: &Manifest) -> HdAssets { + fs::write( + dir.join("hd/hd.json"), + serde_json::to_vec(manifest).unwrap(), + ) + .unwrap(); + HdAssets::load(&dir.join("hd"), catalog) + } + #[test] + fn source_checked_pack_reports_partial_coverage_and_rejects_changed_data() { + let (dir, catalog, mut manifest) = fixture(); + let assets = pack(dir.path(), &catalog, &manifest); + assert_eq!(assets.coverage(), 1); + assert!(assets.diagnostics[0].contains("1 of 2 frames")); + manifest.sequences[0].frames[0].source_sha256 = "changed".into(); + let assets = pack(dir.path(), &catalog, &manifest); + assert_eq!(assets.coverage(), 0); + assert!( + assets + .diagnostics + .iter() + .any(|m| m.contains("source hash changed")) + ); + } + #[test] + fn invalid_atlas_and_path_cannot_escape_original_canvas() { + let (dir, catalog, mut manifest) = fixture(); + manifest.sequences[0].frames[0].crop = Some([0, 0, 9, 8]); + let assets = pack(dir.path(), &catalog, &manifest); + assert_eq!(assets.coverage(), 0); + assert!( + assets + .diagnostics + .iter() + .any(|m| m.contains("crop exceeds")) + ); + manifest.sequences[0].frames[0].crop = None; + manifest.sequences[0].frames[0].file = "../source".into(); + let assets = pack(dir.path(), &catalog, &manifest); + assert_eq!(assets.coverage(), 0); + assert!(assets.diagnostics.iter().any(|m| m.contains("stay inside"))); + } + #[test] + fn duplicate_sequence_ids_reject_pack_atomically() { + let (dir, catalog, mut manifest) = fixture(); + let duplicate = manifest.sequences[0].clone(); + manifest.sequences.push(duplicate); + let assets = pack(dir.path(), &catalog, &manifest); + assert_eq!(assets.coverage(), 0); + assert!( + assets + .diagnostics + .iter() + .any(|m| m.contains("duplicate HD asset")) + ); + } + #[test] + fn missing_pack_is_clean_fallback() { + let dir = tempfile::tempdir().unwrap(); + // Build a real minimal catalog so the public loading path is exercised. + fs::write(dir.path().join("a"), []).unwrap(); + fs::write(dir.path().join("INDEX"), "00001 0 a\n").unwrap(); + let catalog = Catalog::open(dir.path()).unwrap(); + let art = HdAssets::load(&dir.path().join("missing"), &catalog); + assert_eq!(art.coverage(), 0); + assert!(art.diagnostics.is_empty()); + } +} diff --git a/src/legacy_tables.rs b/src/legacy_tables.rs new file mode 100644 index 00000000..e756c391 --- /dev/null +++ b/src/legacy_tables.rs @@ -0,0 +1,953 @@ +// Generated by tools/generate_legacy_tables.py; source is GPL-2.0-or-later. +pub struct LegacyObject { + pub index: u32, + pub id: &'static str, + pub name: &'static str, + pub asset: u32, + pub frames: u32, + pub cost: u32, + pub max_count: u32, + pub initial_count: u32, + pub special: bool, +} +pub struct LegacyWeapon { + pub index: u32, + pub id: &'static str, + pub name: &'static str, + pub asset: u32, + pub frames: u32, + pub damage: i32, + pub speed: i32, + pub cooldown: u32, + pub target: u32, + pub maxspeed: i32, + pub startframe: u32, + pub delay: bool, + pub plot: bool, + pub moving: bool, + pub follow_x: bool, + pub follow_y: bool, + pub effect: bool, + pub beam: u32, +} +pub fn objects() -> Vec { + vec![ + LegacyObject { + index: 0, + id: "base:forward_guns", + name: "Forward Guns", + asset: 66224, + frames: 1, + cost: 12000, + max_count: 1, + initial_count: 1, + special: false, + }, + LegacyObject { + index: 1, + id: "base:plasma_guns", + name: "Plasma Guns", + asset: 66225, + frames: 2, + cost: 78800, + max_count: 1, + initial_count: 1, + special: false, + }, + LegacyObject { + index: 2, + id: "base:micro_missile", + name: "Micro Missile", + asset: 66227, + frames: 2, + cost: 175600, + max_count: 1, + initial_count: 1, + special: false, + }, + LegacyObject { + index: 3, + id: "base:dumb_missile", + name: "Dumb Missile", + asset: 66229, + frames: 1, + cost: 145200, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 4, + id: "base:mini_gun", + name: "Mini Gun", + asset: 66230, + frames: 4, + cost: 250650, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 5, + id: "base:turret", + name: "Turret", + asset: 66234, + frames: 4, + cost: 512850, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 6, + id: "base:missile_pods", + name: "Missile Pods", + asset: 66238, + frames: 1, + cost: 204950, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 7, + id: "base:air_missile", + name: "Air Missile", + asset: 66239, + frames: 1, + cost: 63500, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 8, + id: "base:grd_missile", + name: "Grd Missile", + asset: 66240, + frames: 1, + cost: 110000, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 9, + id: "base:bomb", + name: "Bomb", + asset: 66266, + frames: 1, + cost: 98200, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 10, + id: "base:energy_grab", + name: "Energy Grab", + asset: 66241, + frames: 4, + cost: 300750, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 11, + id: "base:mega_bomb", + name: "Mega Bomb", + asset: 66245, + frames: 1, + cost: 32250, + max_count: 5, + initial_count: 1, + special: false, + }, + LegacyObject { + index: 12, + id: "base:pulse_cannon", + name: "Pulse Cannon", + asset: 66246, + frames: 2, + cost: 725000, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 13, + id: "base:forward_laser", + name: "Forward Laser", + asset: 66248, + frames: 4, + cost: 1750000, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 14, + id: "base:death_ray", + name: "Death Ray", + asset: 66252, + frames: 4, + cost: 950000, + max_count: 1, + initial_count: 1, + special: true, + }, + LegacyObject { + index: 15, + id: "base:super_shield", + name: "Super Shield", + asset: 66256, + frames: 1, + cost: 78500, + max_count: 100, + initial_count: 100, + special: false, + }, + LegacyObject { + index: 16, + id: "base:energy", + name: "Energy", + asset: 66257, + frames: 4, + cost: 10000, + max_count: 100, + initial_count: 25, + special: false, + }, + LegacyObject { + index: 17, + id: "base:detect", + name: "Detect", + asset: 66261, + frames: 1, + cost: 10000, + max_count: 1, + initial_count: 1, + special: false, + }, + LegacyObject { + index: 18, + id: "base:itembuy1", + name: "Itembuy1", + asset: 66261, + frames: 1, + cost: 93800, + max_count: 93800, + initial_count: 93800, + special: false, + }, + LegacyObject { + index: 19, + id: "base:itembuy2", + name: "Itembuy2", + asset: 66262, + frames: 1, + cost: 76000, + max_count: 76000, + initial_count: 76000, + special: false, + }, + LegacyObject { + index: 20, + id: "base:itembuy3", + name: "Itembuy3", + asset: 66263, + frames: 1, + cost: 55700, + max_count: 55700, + initial_count: 55700, + special: false, + }, + LegacyObject { + index: 21, + id: "base:itembuy4", + name: "Itembuy4", + asset: 66264, + frames: 1, + cost: 35200, + max_count: 35200, + initial_count: 35200, + special: false, + }, + LegacyObject { + index: 22, + id: "base:itembuy5", + name: "Itembuy5", + asset: 66265, + frames: 1, + cost: 122500, + max_count: 122500, + initial_count: 122500, + special: false, + }, + LegacyObject { + index: 23, + id: "base:itembuy6", + name: "Itembuy6", + asset: 66267, + frames: 4, + cost: 50, + max_count: 50, + initial_count: 50, + special: false, + }, + ] +} +pub fn weapons() -> Vec { + vec![ + LegacyWeapon { + index: 0, + id: "base:forward_guns", + name: "Forward Guns", + asset: 65987, + frames: 4, + damage: 1, + speed: 8, + cooldown: 2, + target: 0, + maxspeed: 16, + startframe: 0, + delay: false, + plot: false, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 1, + id: "base:plasma_guns", + name: "Plasma Guns", + asset: 65999, + frames: 2, + damage: 2, + speed: 4, + cooldown: 10, + target: 1, + maxspeed: 8, + startframe: 0, + delay: false, + plot: false, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 2, + id: "base:micro_missile", + name: "Micro Missile", + asset: 65985, + frames: 2, + damage: 2, + speed: 2, + cooldown: 4, + target: 3, + maxspeed: 8, + startframe: 0, + delay: false, + plot: false, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 3, + id: "base:dumb_missile", + name: "Dumb Missile", + asset: 65978, + frames: 3, + damage: 4, + speed: 2, + cooldown: 10, + target: 0, + maxspeed: 12, + startframe: 1, + delay: true, + plot: true, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 4, + id: "base:mini_gun", + name: "Mini Gun", + asset: 65987, + frames: 4, + damage: 1, + speed: 8, + cooldown: 1, + target: 3, + maxspeed: 10, + startframe: 1, + delay: false, + plot: true, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 5, + id: "base:turret", + name: "Turret", + asset: 0, + frames: 0, + damage: 5, + speed: 0, + cooldown: 6, + target: 0, + maxspeed: 0, + startframe: 0, + delay: false, + plot: false, + moving: false, + follow_x: false, + follow_y: false, + effect: false, + beam: 1, + }, + LegacyWeapon { + index: 6, + id: "base:missile_pods", + name: "Missile Pods", + asset: 65981, + frames: 2, + damage: 4, + speed: 1, + cooldown: 5, + target: 1, + maxspeed: 16, + startframe: 0, + delay: false, + plot: false, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 7, + id: "base:air_missile", + name: "Air Missile", + asset: 65981, + frames: 2, + damage: 4, + speed: 1, + cooldown: 10, + target: 1, + maxspeed: 12, + startframe: 0, + delay: false, + plot: false, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 8, + id: "base:grd_missile", + name: "Grd Missile", + asset: 65983, + frames: 2, + damage: 20, + speed: 1, + cooldown: 20, + target: 2, + maxspeed: 6, + startframe: 0, + delay: false, + plot: false, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 9, + id: "base:bomb", + name: "Bomb", + asset: 66003, + frames: 1, + damage: 50, + speed: 1, + cooldown: 30, + target: 4, + maxspeed: 4, + startframe: 0, + delay: false, + plot: false, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 10, + id: "base:energy_grab", + name: "Energy Grab", + asset: 66077, + frames: 6, + damage: 3, + speed: 4, + cooldown: 2, + target: 5, + maxspeed: 8, + startframe: 0, + delay: false, + plot: false, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 11, + id: "base:mega_bomb", + name: "Mega Bomb", + asset: 65995, + frames: 4, + damage: 50, + speed: 2, + cooldown: 60, + target: 0, + maxspeed: 2, + startframe: 0, + delay: false, + plot: true, + moving: true, + follow_x: false, + follow_y: false, + effect: true, + beam: 0, + }, + LegacyWeapon { + index: 12, + id: "base:pulse_cannon", + name: "Pulse Cannon", + asset: 66083, + frames: 2, + damage: 5, + speed: 8, + cooldown: 3, + target: 0, + maxspeed: 8, + startframe: 0, + delay: false, + plot: false, + moving: true, + follow_x: false, + follow_y: false, + effect: false, + beam: 0, + }, + LegacyWeapon { + index: 13, + id: "base:forward_laser", + name: "Forward Laser", + asset: 66101, + frames: 4, + damage: 10, + speed: 0, + cooldown: 7, + target: 1, + maxspeed: 0, + startframe: 0, + delay: false, + plot: false, + moving: false, + follow_x: true, + follow_y: true, + effect: true, + beam: 2, + }, + LegacyWeapon { + index: 14, + id: "base:death_ray", + name: "Death Ray", + asset: 66097, + frames: 4, + damage: 6, + speed: 0, + cooldown: 7, + target: 3, + maxspeed: 0, + startframe: 0, + delay: false, + plot: false, + moving: false, + follow_x: true, + follow_y: true, + effect: true, + beam: 2, + }, + ] +} +pub const O_GUN1: [i32; 8] = [1, 3, 5, 6, 5, 3, 1, 0]; +pub const O_GUN2: [i32; 8] = [1, 3, 6, 9, 6, 3, 2, 0]; +pub const O_GUN3: [i32; 8] = [2, 6, 8, 11, 8, 6, 2, 0]; +pub struct LegacySound { + pub name: &'static str, + pub asset: u32, + pub pitch: i32, + pub random: bool, + pub volume: i32, + pub priority: i32, +} +pub fn sounds() -> Vec { + vec![ + LegacySound { + name: "FX_MON1", + asset: 194, + pitch: 128, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_MON2", + asset: 199, + pitch: 128, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_MON3", + asset: 204, + pitch: 128, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_MON4", + asset: 209, + pitch: 128, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_MON5", + asset: 214, + pitch: 128, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_MON6", + asset: 219, + pitch: 128, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_DAVE", + asset: 224, + pitch: 128, + random: false, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_THEME", + asset: 99, + pitch: 128, + random: false, + volume: 127, + priority: 0, + }, + LegacySound { + name: "FX_AIREXPLO", + asset: 104, + pitch: 128, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_AIREXPLO2", + asset: 109, + pitch: 128, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_BONUS", + asset: 114, + pitch: 128, + random: false, + volume: 127, + priority: 0, + }, + LegacySound { + name: "FX_CRASH", + asset: 119, + pitch: 128, + random: false, + volume: 127, + priority: 0, + }, + LegacySound { + name: "FX_DOOR", + asset: 124, + pitch: 120, + random: false, + volume: 127, + priority: 0, + }, + LegacySound { + name: "FX_FLYBY", + asset: 129, + pitch: 120, + random: false, + volume: 127, + priority: 0, + }, + LegacySound { + name: "FX_EGRAB", + asset: 134, + pitch: 128, + random: false, + volume: 40, + priority: 2, + }, + LegacySound { + name: "FX_GEXPLO", + asset: 139, + pitch: 128, + random: true, + volume: 127, + priority: 2, + }, + LegacySound { + name: "FX_GUN", + asset: 144, + pitch: 125, + random: true, + volume: 30, + priority: 10, + }, + LegacySound { + name: "FX_JETSND", + asset: 149, + pitch: 120, + random: false, + volume: 120, + priority: 4, + }, + LegacySound { + name: "FX_LASER", + asset: 154, + pitch: 120, + random: false, + volume: 50, + priority: 2, + }, + LegacySound { + name: "FX_MISSLE", + asset: 159, + pitch: 120, + random: true, + volume: 50, + priority: 3, + }, + LegacySound { + name: "FX_SWEP", + asset: 164, + pitch: 128, + random: false, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_TURRET", + asset: 169, + pitch: 128, + random: true, + volume: 60, + priority: 1, + }, + LegacySound { + name: "FX_WARNING", + asset: 174, + pitch: 128, + random: false, + volume: 100, + priority: 2, + }, + LegacySound { + name: "FX_BOSS1", + asset: 179, + pitch: 127, + random: false, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_IJETSND", + asset: 149, + pitch: 235, + random: false, + volume: 45, + priority: 1, + }, + LegacySound { + name: "FX_EJETSND", + asset: 149, + pitch: 65, + random: false, + volume: 120, + priority: 1, + }, + LegacySound { + name: "FX_INTROHIT", + asset: 144, + pitch: 215, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_INTROGUN", + asset: 144, + pitch: 110, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_ENEMYSHOT", + asset: 189, + pitch: 100, + random: true, + volume: 50, + priority: 1, + }, + LegacySound { + name: "FX_ENEMYLASER", + asset: 154, + pitch: 70, + random: true, + volume: 120, + priority: 1, + }, + LegacySound { + name: "FX_ENEMYMISSLE", + asset: 159, + pitch: 140, + random: true, + volume: 55, + priority: 2, + }, + LegacySound { + name: "FX_ENEMYPLASMA", + asset: 189, + pitch: 127, + random: true, + volume: 127, + priority: 2, + }, + LegacySound { + name: "FX_SHIT", + asset: 184, + pitch: 132, + random: true, + volume: 127, + priority: 1, + }, + LegacySound { + name: "FX_HIT", + asset: 144, + pitch: 214, + random: true, + volume: 100, + priority: 1, + }, + LegacySound { + name: "FX_NOSHOOT", + asset: 189, + pitch: 254, + random: false, + volume: 40, + priority: 2, + }, + LegacySound { + name: "FX_PULSE", + asset: 189, + pitch: 100, + random: true, + volume: 50, + priority: 2, + }, + ] +} +pub const FREQUENCY_CURVE: [u16; 668] = [ + 307, 307, 308, 308, 309, 310, 310, 311, 311, 312, 312, 313, 313, 314, 315, 315, 316, 316, 317, + 317, 318, 319, 319, 320, 320, 321, 322, 322, 323, 323, 324, 324, 325, 326, 326, 327, 327, 328, + 329, 329, 330, 330, 331, 332, 332, 333, 333, 334, 335, 335, 336, 336, 337, 338, 338, 339, 339, + 340, 341, 341, 342, 343, 343, 344, 344, 345, 346, 346, 347, 347, 348, 349, 349, 350, 351, 351, + 352, 353, 353, 354, 354, 355, 356, 356, 357, 358, 358, 359, 360, 360, 361, 362, 362, 363, 364, + 364, 365, 366, 366, 367, 368, 368, 369, 370, 370, 371, 372, 372, 373, 374, 374, 375, 376, 376, + 377, 378, 378, 379, 380, 380, 381, 382, 382, 383, 384, 385, 385, 386, 387, 387, 388, 389, 389, + 390, 391, 392, 392, 393, 394, 394, 395, 396, 397, 397, 398, 399, 399, 400, 401, 402, 402, 403, + 404, 404, 405, 406, 407, 407, 408, 409, 410, 410, 411, 412, 413, 413, 414, 415, 416, 416, 417, + 418, 419, 419, 420, 421, 422, 422, 423, 424, 425, 425, 426, 427, 428, 429, 429, 430, 431, 432, + 432, 433, 434, 435, 436, 436, 437, 438, 439, 440, 440, 441, 442, 443, 444, 444, 445, 446, 447, + 448, 448, 449, 450, 451, 452, 452, 453, 454, 455, 456, 457, 457, 458, 459, 460, 461, 462, 462, + 463, 464, 465, 466, 467, 467, 468, 469, 470, 471, 472, 472, 473, 474, 475, 476, 477, 478, 478, + 479, 480, 481, 482, 483, 484, 485, 485, 486, 487, 488, 489, 490, 491, 492, 493, 493, 494, 495, + 496, 497, 498, 499, 500, 501, 502, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, + 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 528, 529, 530, + 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, + 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, + 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 580, 581, 582, 583, 584, 585, 586, 587, 588, + 589, 590, 591, 592, 593, 594, 595, 596, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, + 610, 611, 612, 613, 614, 615, 616, 617, 618, 620, 621, 622, 623, 624, 625, 626, 627, 629, 630, + 631, 632, 633, 634, 635, 637, 638, 639, 640, 641, 642, 644, 645, 646, 647, 648, 649, 651, 652, + 653, 654, 655, 656, 658, 659, 660, 661, 662, 664, 665, 666, 667, 668, 670, 671, 672, 673, 674, + 676, 677, 678, 679, 681, 682, 683, 684, 686, 687, 688, 689, 690, 692, 693, 694, 695, 697, 698, + 699, 701, 702, 703, 704, 706, 707, 708, 709, 711, 712, 713, 715, 716, 717, 718, 720, 721, 722, + 724, 725, 726, 728, 729, 730, 732, 733, 734, 736, 737, 738, 740, 741, 742, 744, 745, 746, 748, + 749, 750, 752, 753, 754, 756, 757, 758, 760, 761, 763, 764, 765, 767, 768, 770, 771, 772, 774, + 775, 777, 778, 779, 781, 782, 784, 785, 786, 788, 789, 791, 792, 794, 795, 796, 798, 799, 801, + 802, 804, 805, 807, 808, 809, 811, 812, 814, 815, 817, 818, 820, 821, 823, 824, 826, 827, 829, + 830, 832, 833, 835, 836, 838, 839, 841, 842, 844, 845, 847, 848, 850, 851, 853, 855, 856, 858, + 859, 861, 862, 864, 865, 867, 869, 870, 872, 873, 875, 876, 878, 880, 881, 883, 884, 886, 888, + 889, 891, 892, 894, 896, 897, 899, 900, 902, 904, 905, 907, 909, 910, 912, 914, 915, 917, 919, + 920, 922, 924, 925, 927, 929, 930, 932, 934, 935, 937, 939, 940, 942, 944, 945, 947, 949, 951, + 952, 954, 956, 957, 959, 961, 963, 964, 966, 968, 970, 971, 973, 975, 977, 978, 980, 982, 984, + 986, 987, 989, 991, 993, 995, 996, 998, 1000, 1002, 1004, 1005, 1007, 1009, 1011, 1013, 1014, + 1016, 1018, 1020, 1022, 876, +]; +pub const VOLUME_CURVE: [u16; 128] = [ + 0, 1, 3, 5, 6, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 27, 29, 30, 32, 33, 34, 36, + 37, 39, 41, 43, 45, 47, 49, 50, 52, 54, 55, 57, 59, 60, 61, 63, 64, 66, 67, 68, 69, 71, 72, 73, + 74, 75, 76, 77, 79, 80, 81, 82, 83, 84, 84, 85, 86, 87, 88, 89, 90, 91, 92, 92, 93, 94, 95, 96, + 96, 97, 98, 99, 99, 100, 101, 101, 102, 103, 103, 104, 105, 105, 106, 107, 107, 108, 109, 109, + 110, 110, 111, 112, 112, 113, 113, 114, 114, 115, 115, 116, 117, 117, 118, 118, 119, 119, 120, + 120, 121, 121, 122, 122, 123, 123, 123, 124, 124, 125, 125, 126, 126, 127, 127, +]; diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 00000000..ad8b064f --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,13 @@ +pub mod assets; +pub mod audio; +pub mod cinematics; +pub mod content; +#[cfg(feature = "desktop")] +pub mod desktop; +pub mod hd; +mod legacy_tables; +pub mod modding; +pub mod persistence; +pub mod render; +pub mod simulation; +pub mod sound; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 00000000..25076aba --- /dev/null +++ b/src/main.rs @@ -0,0 +1,201 @@ +use anyhow::{Context, Result}; +use raptor_replica::{ + assets::{Catalog, decode_demo}, + content::{ContentId, Registry}, + modding::{self, ActiveMods}, + persistence::{Paths, Pilot}, + simulation::{Input, World}, +}; +use std::path::PathBuf; +fn main() { + if let Err(e) = run() { + eprintln!("{e:#}"); + std::process::exit(1) + } +} +fn run() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let arg = |key: &str| { + args.iter() + .position(|s| s == key) + .and_then(|i| args.get(i + 1)) + }; + if args.iter().any(|a| a == "--help" || a == "-h") { + println!( + "raptor-rust [--data DIR] [--mods DIR]\n --verify-assets Check catalog and all original mission definitions\n --validate-mods ID,... Validate selected local mod packages\n --schemas DIR Write mod API JSON schemas\n --headless MISSION --ticks N Deterministic simulation smoke run\n --replay ASSET_NAME --trace FILE Record legacy demo simulation states\n --import-legacy FILE --output FILE\n --smoke-frames N Exit desktop after N rendered frames\n --screenshot FILE Save the final desktop frame as PNG\n --preview-mission ID Start a mission directly\n --preview-cinematic KIND intro, landing, death, end1, end2, end3\n --profile-root DIR Use a separate pilot/config/cache directory\n --enabled ID,... Enable mods for headless/replay commands" + ); + return Ok(()); + } + if let Some(path) = arg("--schemas") { + modding::write_schemas(&PathBuf::from(path))?; + println!("Wrote API v1 schemas to {path}"); + return Ok(()); + } + let data = arg("--data") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("data")); + let catalog = Catalog::open(data)?; + let base = Registry::base(&catalog)?; + if args.iter().any(|a| a == "--verify-assets") { + println!( + "Verified {} assets; {} missions, {} enemies, {} weapons, {} items", + catalog.verify()?, + base.missions.len(), + base.enemies.len(), + base.weapons.len(), + base.items.len() + ); + return Ok(()); + } + let mut paths = Paths::discover()?; + if let Some(root) = arg("--profile-root") { + let root = PathBuf::from(root); + paths.data = root.join("data"); + paths.config = root.join("config"); + paths.cache = root.join("cache"); + paths.legacy = root.join("legacy"); + } + let root = arg("--mods") + .map(PathBuf::from) + .unwrap_or_else(|| paths.mods()); + let discovery = modding::discover(&root); + if let Some(ids) = arg("--validate-mods") { + let enabled = ids + .split(',') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect::>(); + let active = ActiveMods::build(&base, &discovery, &enabled, Some(&catalog))?; + println!( + "Validated {} mods; {} override(s)", + active.pins.len(), + active.registry.overrides.len() + ); + for err in discovery.errors { + eprintln!("Discovery: {err}"); + } + return Ok(()); + } + if let Some(path) = arg("--import-legacy") { + let output = PathBuf::from(arg("--output").context("--import-legacy requires --output")?); + let source = PathBuf::from(path).canonicalize()?; + anyhow::ensure!( + output.canonicalize().ok().as_ref() != Some(&source), + "legacy import output must be separate from the original save" + ); + let pilot = Pilot::import_legacy(&PathBuf::from(path), &base)?; + pilot.save(&output)?; + println!("Imported pilot to {}", output.display()); + return Ok(()); + } + let enabled = arg("--enabled") + .map(|s| { + s.split(',') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect::>() + }) + .unwrap_or_default(); + if let Some(id) = arg("--headless") { + let mut active = ActiveMods::build(&base, &discovery, &enabled, Some(&catalog))?; + let mut pilot = Pilot::default(); + pilot.mission = ContentId::new(id)?; + let mut world = World::new(&pilot.mission, &pilot, &active.registry)?; + let ticks = arg("--ticks") + .map(|s| s.parse()) + .transpose()? + .unwrap_or(500); + for _ in 0..ticks { + world.step( + Input { + fire: true, + ..Input::default() + }, + &active.registry, + &mut active.scripts, + )?; + if world.outcome != raptor_replica::simulation::Outcome::Playing { + break; + } + } + println!( + "tick={} outcome={:?} enemies={} credits={} digest={}", + world.tick, + world.outcome, + world.enemies.len(), + world.player.credits, + world.digest() + ); + return Ok(()); + } + if let Some(name) = arg("--replay") { + let (sector, wave, frames) = decode_demo(&catalog.named(name)?)?; + let mission = ContentId(format!("base:sector_{}_wave_{}", sector + 1, wave + 1)); + let mut pilot = Pilot::demo(sector, &base)?; + pilot.mission = mission.clone(); + let mut active = ActiveMods::build(&base, &discovery, &enabled, Some(&catalog))?; + let mut world = World::new(&mission, &pilot, &active.registry)?; + let mut trace = arg("--trace") + .map(|path| std::fs::File::create(path)) + .transpose()?; + let limit = arg("--ticks") + .map(|s| s.parse::()) + .transpose()? + .unwrap_or(frames.len()); + for f in frames.into_iter().take(limit) { + world.step( + Input { + fire: f.buttons[0], + cycle: f.buttons[1], + bomb: f.buttons[2], + absolute: Some([f.x as i32, f.y as i32]), + demo_bank: Some(f.bank as i32), + ..Input::default() + }, + &active.registry, + &mut active.scripts, + )?; + if let Some(file) = &mut trace { + use std::io::Write; + writeln!(file, "{}", world.reference_state(&active.registry))?; + } + } + println!("Replay tick={} digest={}", world.tick, world.digest()); + return Ok(()); + } + #[cfg(feature = "desktop")] + { + let movie = arg("--preview-cinematic") + .map(|s| match s.as_str() { + "intro" => Ok(raptor_replica::cinematics::Kind::Intro), + "landing" => Ok(raptor_replica::cinematics::Kind::Landing), + "death" => Ok(raptor_replica::cinematics::Kind::Death), + "end1" => Ok(raptor_replica::cinematics::Kind::CampaignEnd(0)), + "end2" => Ok(raptor_replica::cinematics::Kind::CampaignEnd(1)), + "end3" => Ok(raptor_replica::cinematics::Kind::CampaignEnd(2)), + _ => Err(anyhow::anyhow!("unknown cinematic {s}")), + }) + .transpose()?; + raptor_replica::desktop::run( + catalog, + base, + paths, + root, + arg("--smoke-frames").map(|s| s.parse()).transpose()?, + arg("--screenshot").map(PathBuf::from), + arg("--preview-mission") + .map(|s| ContentId::new(s)) + .transpose()?, + movie, + )?; + } + #[cfg(not(feature = "desktop"))] + { + let _ = (catalog, base, paths, root); + return Err(anyhow::anyhow!( + "desktop support is disabled; use a headless command" + )); + } + #[cfg(feature = "desktop")] + Ok(()) +} diff --git a/src/modding.rs b/src/modding.rs new file mode 100644 index 00000000..600c6e49 --- /dev/null +++ b/src/modding.rs @@ -0,0 +1,814 @@ +//! Local mod discovery, dependency ordering and transactional script callbacks. +use crate::{ + assets::{Catalog, contained}, + content::{API_VERSION, ContentPack, Registry}, + simulation::LegacyRng, +}; +use anyhow::{Context, Result, ensure}; +use rhai::{ + AST, Dynamic, Engine, Scope, + packages::{ + ArithmeticPackage, BasicArrayPackage, BasicFnPackage, BasicIteratorPackage, + BasicMapPackage, BasicMathPackage, BasicStringPackage, BitFieldPackage, LogicPackage, + MoreStringPackage, Package, + }, +}; +use schemars::JsonSchema; +use semver::{Version, VersionReq}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + path::{Path, PathBuf}, +}; +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Manifest { + /// Unique lowercase namespace; `base` is reserved for the original game. + pub id: String, + /// Display name shown in the in-game manager. + pub name: String, + /// Semantic package version, saved together with a SHA-256 content hash. + pub version: String, + /// Exact supported content/script API major version. + pub api_version: u32, + #[serde(default)] + pub description: String, + /// Required, explicitly enabled mod IDs mapped to semantic version requirements. + #[serde(default)] + pub dependencies: BTreeMap, + /// IDs which cannot be enabled at the same time as this package. + #[serde(default)] + pub conflicts: Vec, + /// Relative path to the JSON content pack. Defaults to `content.json`. + #[serde(default = "content_file")] + pub content: String, + /// Relative paths to every Rhai source referenced by this content pack. + #[serde(default)] + pub scripts: Vec, +} +fn content_file() -> String { + "content.json".into() +} +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ModPin { + pub id: String, + pub version: String, + pub hash: String, +} +#[derive(Debug, Clone)] +pub struct InstalledMod { + pub root: PathBuf, + pub manifest: Manifest, + pub hash: String, +} +#[derive(Debug, Default)] +pub struct Discovery { + pub mods: BTreeMap, + pub errors: Vec, + /// Directory inventoried by this snapshot, used to reject new duplicate packages. + pub root: Option, +} +const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024; +const MAX_PACKAGE_BYTES: u64 = 256 * 1024 * 1024; +const MAX_FILES: usize = 10000; +const MAX_DEPTH: usize = 16; + +fn namespace(id: &str) -> bool { + !id.is_empty() + && id.len() <= 64 + && id != "base" + && id + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "_-".contains(c)) +} +fn relative_path(value: &str) -> Result<()> { + let path = Path::new(value); + ensure!( + !value.is_empty() + && value.len() <= 512 + && !path.is_absolute() + && path + .components() + .all(|c| matches!(c, std::path::Component::Normal(_))), + "package paths must be relative and may not contain parent traversal: {value}" + ); + Ok(()) +} +fn read_package_file(root: &Path, relative: &Path) -> Result> { + let path = contained(root, relative)?; + let metadata = fs::symlink_metadata(&path)?; + ensure!(metadata.is_file(), "package entry must be a regular file"); + ensure!(metadata.len() <= MAX_FILE_BYTES, "mod file exceeds 64 MiB"); + let data = fs::read(path)?; + ensure!( + data.len() as u64 <= MAX_FILE_BYTES, + "mod file exceeds 64 MiB" + ); + Ok(data) +} +fn load_package(path: &Path) -> Result { + ensure!( + fs::symlink_metadata(path)?.is_dir(), + "mod folder must be a real directory" + ); + let root = path.canonicalize()?; + let mut files = Vec::new(); + let mut bytes = 0; + walk(&root, &root, &mut files, &mut bytes, 0)?; + files.sort(); + let manifest_data = read_package_file(&root, Path::new("mod.toml"))?; + ensure!( + manifest_data.len() <= 64 * 1024, + "mod manifest exceeds 64 KiB" + ); + let manifest: Manifest = toml::from_str(std::str::from_utf8(&manifest_data)?)?; + ensure!(namespace(&manifest.id), "invalid/reserved mod namespace"); + ensure!( + !manifest.name.trim().is_empty() && manifest.name.len() <= 128, + "invalid mod display name" + ); + ensure!( + manifest.description.len() <= 4096, + "mod description exceeds 4 KiB" + ); + Version::parse(&manifest.version).context("invalid package version")?; + ensure!( + manifest.dependencies.len() <= 128 && manifest.conflicts.len() <= 128, + "too many dependencies/conflicts" + ); + for (dependency, version) in &manifest.dependencies { + ensure!( + namespace(dependency) && dependency != &manifest.id, + "invalid/self dependency {dependency}" + ); + VersionReq::parse(version) + .with_context(|| format!("invalid version requirement for {dependency}"))?; + } + let conflicts: BTreeSet<_> = manifest.conflicts.iter().collect(); + ensure!( + conflicts.len() == manifest.conflicts.len(), + "duplicate conflict declaration" + ); + for conflict in &manifest.conflicts { + ensure!( + namespace(conflict) && conflict != &manifest.id, + "invalid/self conflict {conflict}" + ); + } + relative_path(&manifest.content)?; + contained(&root, Path::new(&manifest.content))?; + ensure!( + manifest.scripts.len() <= 64, + "too many scripts (maximum 64)" + ); + let scripts: BTreeSet<_> = manifest.scripts.iter().collect(); + ensure!( + scripts.len() == manifest.scripts.len(), + "duplicate script declaration" + ); + for script in &manifest.scripts { + relative_path(script)?; + contained(&root, Path::new(script))?; + } + let mut hash = Sha256::new(); + hash.update(b"raptor-mod-package-v1\0"); + for relative in files { + let name = relative + .to_str() + .context("package filenames must be UTF-8")?; + let data = read_package_file(&root, &relative)?; + hash.update((name.len() as u64).to_le_bytes()); + hash.update(name.as_bytes()); + hash.update((data.len() as u64).to_le_bytes()); + hash.update(data); + } + Ok(InstalledMod { + root, + manifest, + hash: format!("{:x}", hash.finalize()), + }) +} +pub fn discover(root: &Path) -> Discovery { + let mut out = Discovery::default(); + out.root = Some(root.canonicalize().unwrap_or_else(|_| root.to_path_buf())); + if !root.exists() { + return out; + } + let entries = match fs::read_dir(root) { + Ok(e) => e, + Err(e) => { + out.errors.push(e.to_string()); + return out; + } + }; + let mut entries: Vec<_> = entries.collect(); + entries.sort_by_key(|e| e.as_ref().ok().map(|e| e.path())); + let mut ambiguous = BTreeSet::new(); + for entry in entries { + let e = match entry { + Ok(e) => e, + Err(err) => { + out.errors.push(format!("{}: {err}", root.display())); + continue; + } + }; + let kind = match e.file_type() { + Ok(kind) => kind, + Err(err) => { + out.errors.push(format!("{}: {err}", e.path().display())); + continue; + } + }; + if kind.is_symlink() { + out.errors.push(format!( + "{}: mod folders may not be symlinks", + e.path().display() + )); + continue; + } + if !kind.is_dir() { + continue; + } + match load_package(&e.path()) { + Ok(m) => { + let id = m.manifest.id.clone(); + if ambiguous.contains(&id) || out.mods.contains_key(&id) { + out.errors.push(format!("duplicate installed mod {id}")); + ambiguous.insert(id.clone()); + out.mods.remove(&id); + } else { + out.mods.insert(id, m); + } + } + Err(err) => out.errors.push(format!("{}: {err:#}", e.path().display())), + } + } + out +} +fn walk( + root: &Path, + current: &Path, + files: &mut Vec, + bytes: &mut u64, + depth: usize, +) -> Result<()> { + ensure!( + depth <= MAX_DEPTH, + "mod package directory depth exceeds {MAX_DEPTH}" + ); + for e in fs::read_dir(current)? { + let e = e?; + let relative = e.path().strip_prefix(root)?.to_path_buf(); + ensure!( + !e.file_type()?.is_symlink(), + "mod packages may not contain symlinks" + ); + if e.file_type()?.is_dir() { + walk(root, &e.path(), files, bytes, depth + 1)? + } else { + ensure!( + e.file_type()?.is_file(), + "mod entries must be regular files" + ); + ensure!( + e.metadata()?.len() <= MAX_FILE_BYTES, + "mod file exceeds 64 MiB" + ); + *bytes = bytes + .checked_add(e.metadata()?.len()) + .context("package size overflow")?; + ensure!(*bytes <= MAX_PACKAGE_BYTES, "mod package exceeds 256 MiB"); + files.push(relative); + ensure!(files.len() <= MAX_FILES, "mod package has too many files"); + } + } + Ok(()) +} +pub fn order(discovery: &Discovery, enabled: &[String]) -> Result> { + let selected: BTreeSet<_> = enabled.iter().cloned().collect(); + ensure!( + selected.len() == enabled.len(), + "duplicate mod in load order" + ); + let mut result = Vec::new(); + let mut visiting = BTreeSet::new(); + let mut done = BTreeSet::new(); + fn visit( + id: &str, + d: &Discovery, + selected: &BTreeSet, + visiting: &mut BTreeSet, + done: &mut BTreeSet, + result: &mut Vec, + ) -> Result<()> { + if done.contains(id) { + return Ok(()); + } + ensure!(visiting.insert(id.into()), "cyclic mod dependency at {id}"); + let m = d + .mods + .get(id) + .with_context(|| format!("mod {id} is not installed"))?; + ensure!( + m.manifest.api_version == API_VERSION, + "{id}: requires API {}, game provides {API_VERSION}", + m.manifest.api_version + ); + for (dep, requirement) in &m.manifest.dependencies { + ensure!(selected.contains(dep), "{id} requires enabled mod {dep}"); + let v = &d + .mods + .get(dep) + .with_context(|| format!("missing dependency {dep}"))? + .manifest + .version; + ensure!( + VersionReq::parse(requirement)?.matches(&Version::parse(v)?), + "{id} requires {dep} {requirement}, installed {v}" + ); + visit(dep, d, selected, visiting, done, result)?; + } + for conflict in &m.manifest.conflicts { + ensure!( + !selected.contains(conflict), + "{id} conflicts with {conflict}" + ); + } + visiting.remove(id); + done.insert(id.into()); + result.push(id.into()); + Ok(()) + } + for id in enabled { + visit( + id, + discovery, + &selected, + &mut visiting, + &mut done, + &mut result, + )?; + } + Ok(result) +} +pub struct ActiveMods { + pub registry: Registry, + pub pins: Vec, + pub scripts: ScriptRuntime, +} +impl ActiveMods { + pub fn build( + base: &Registry, + discovery: &Discovery, + enabled: &[String], + catalog: Option<&Catalog>, + ) -> Result { + let mut registry = base.clone(); + let mut pins = Vec::new(); + let mut scripts = ScriptRuntime::new(); + let ordered = order(discovery, enabled)?; + let refreshed = discovery.root.as_ref().map(|root| discover(root)); + for id in &ordered { + let previous = &discovery.mods[id]; + if let Some(refreshed) = &refreshed { + ensure!( + refreshed.mods.contains_key(id), + "{id}: package removed, invalid or duplicated since discovery; rescan the Mods screen ({})", + refreshed.errors.join("; ") + ); + } + let current = load_package(&previous.root).with_context(|| { + format!("{id}: package changed or was removed; rescan the Mods screen") + })?; + ensure!( + current.manifest.id == *id && current.hash == previous.hash, + "{id}: package changed since discovery; rescan the Mods screen before applying" + ); + } + for id in &ordered { + let m = &discovery.mods[id]; + let content: ContentPack = serde_json::from_slice(&read_package_file( + &m.root, + Path::new(&m.manifest.content), + )?) + .with_context(|| format!("{id}: invalid content"))?; + registry.asset_roots.insert(id.clone(), m.root.clone()); + registry.apply(content, &id)?; + for path in &m.manifest.scripts { + let source = read_package_file(&m.root, Path::new(path))?; + let source = std::str::from_utf8(&source) + .with_context(|| format!("{id}/{path}: source must be UTF-8"))?; + scripts.add(&id, path, &source)?; + } + pins.push(ModPin { + id: id.clone(), + version: m.manifest.version.clone(), + hash: m.hash.clone(), + }); + } + registry.validate()?; + let validate_art = |owner: &str, art: &crate::content::Art| -> Result<()> { + for png in art.png.iter().chain(art.hd_png.iter()) { + let root = registry + .asset_roots + .get(owner) + .context("missing PNG root")?; + let path = contained(root, Path::new(png))?; + let palette = catalog + .map(|cat| cat.palette()) + .transpose()? + .unwrap_or([[0; 3]; 256]); + let sprite = crate::assets::Sprite::png(&path, &palette)?; + ensure!( + sprite.width % art.frames as usize == 0, + "{owner}/{png}: PNG strip width must divide evenly into frames" + ); + ensure!( + sprite.width / art.frames as usize * art.logical_height as usize + == sprite.height * art.logical_width as usize, + "{owner}/{png}: artwork canvas aspect differs from logical canvas" + ); + if art.hd_png.as_ref() == Some(png) { + ensure!( + sprite.width / art.frames as usize >= 2 * art.logical_width as usize + && sprite.height >= 2 * art.logical_height as usize, + "{owner}/{png}: HD artwork needs at least twice the logical resolution" + ); + } + } + if let (Some(id), Some(cat)) = (art.asset, catalog) { + for frame in 0..art.frames { + cat.sprite(id.checked_add(frame).context("asset ID overflow")?)?; + } + } + Ok(()) + }; + for (id, owner) in ®istry.owners { + if owner == "base" { + continue; + } + if let Some(art) = registry.art(id) { + validate_art(owner, art)?; + } + if let Some(sound) = registry.sounds.get(id) { + let root = registry + .asset_roots + .get(owner) + .context("missing sound root")?; + let bytes = read_package_file(root, Path::new(&sound.file))?; + crate::sound::decode(&bytes) + .with_context(|| format!("{owner}/{}: invalid sound", sound.file))?; + } + if let Some(m) = registry.missions.get(id) { + for tile in &m.tiles { + validate_art(owner, &tile.art)?; + if let Some(a) = &tile.destroyed { + validate_art(owner, a)?; + } + } + } + } + let validate_script = |owner: &str, path: &Option| -> Result<()> { + if let Some(path) = path { + ensure!( + scripts.has(owner, path), + "{owner}: script {path} must appear in manifest.scripts" + ); + } + Ok(()) + }; + for (id, owner) in ®istry.owners { + if let Some(w) = registry.weapons.get(id) { + validate_script(owner, &w.script)?; + } + if let Some(e) = registry.enemies.get(id) { + validate_script(owner, &e.script)?; + } + if let Some(i) = registry.items.get(id) { + validate_script(owner, &i.script)?; + } + if let Some(m) = registry.missions.get(id) { + validate_script(owner, &m.script)?; + } + } + for id in &ordered { + ensure!( + load_package(&discovery.mods[id].root)?.hash == discovery.mods[id].hash, + "{id}: package changed while loading; rescan the Mods screen before applying" + ); + } + Ok(Self { + registry, + pins, + scripts, + }) + } +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] +pub enum Command { + /// Add an enemy at an integer position in the original logical canvas. + Spawn { + enemy: String, + x: i32, + y: i32, + }, + Projectile { + weapon: String, + x: i32, + y: i32, + vx: i32, + vy: i32, + #[serde(default)] + hostile: bool, + }, + Damage { + /// Enemy entity ID; zero addresses the player. + entity: u64, + amount: i32, + }, + Despawn { + entity: u64, + }, + Move { + /// Existing enemy entity ID. + entity: u64, + x: i32, + y: i32, + }, + Velocity { + entity: u64, + vx: i32, + vy: i32, + }, + GiveItem { + item: String, + count: u32, + }, + ConsumeItem { + item: String, + count: u32, + }, + Credits { + amount: i32, + }, + Shield { + amount: i32, + }, + Effect { + x: i32, + y: i32, + }, + Sound { + asset: u32, + }, + PlaySound { + sound: String, + }, + Objective { + /// Stable namespaced objective key, at most 128 bytes. + key: String, + value: i32, + }, + Complete, + Fail, +} +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct HookResult { + /// Transactional commands, applied in order only when the callback succeeds. + #[serde(default)] + pub commands: Vec, + /// JSON-serializable state shared by callbacks in this script; maximum 64 KiB. + #[serde(default)] + pub state: serde_json::Value, +} +pub struct ScriptRuntime { + engine: Engine, + scripts: BTreeMap<(String, String), AST>, + pub states: BTreeMap, + pub rng: BTreeMap, + budget: std::sync::Arc, +} +impl ScriptRuntime { + pub fn new() -> Self { + // Rhai's default StandardPackage includes wall-clock timestamps and native sleep. + // Use an explicit package allowlist so timing cannot bypass operation limits, + // including through dynamically created function pointers. + let mut engine = Engine::new_raw(); + ArithmeticPackage::new().register_into_engine(&mut engine); + BasicStringPackage::new().register_into_engine(&mut engine); + BasicIteratorPackage::new().register_into_engine(&mut engine); + BasicFnPackage::new().register_into_engine(&mut engine); + BitFieldPackage::new().register_into_engine(&mut engine); + LogicPackage::new().register_into_engine(&mut engine); + BasicMathPackage::new().register_into_engine(&mut engine); + BasicArrayPackage::new().register_into_engine(&mut engine); + BasicMapPackage::new().register_into_engine(&mut engine); + MoreStringPackage::new().register_into_engine(&mut engine); + engine + .set_max_operations(100000) + .set_max_call_levels(32) + .set_max_expr_depths(64, 32) + .set_max_array_size(4096) + .set_max_map_size(1024) + .set_max_string_size(16384) + .set_max_modules(0); + engine.disable_symbol("eval"); + engine.disable_symbol("import"); + engine.on_print(|_| {}); + engine.on_debug(|_, _, _| {}); + let budget = std::sync::Arc::new(std::sync::atomic::AtomicI64::new(500000)); + let counter = budget.clone(); + engine.on_progress(move |_| { + if counter.fetch_sub(1, std::sync::atomic::Ordering::Relaxed) <= 0 { + Some(Dynamic::UNIT) + } else { + None + } + }); + Self { + engine, + scripts: BTreeMap::new(), + states: BTreeMap::new(), + rng: BTreeMap::new(), + budget, + } + } + pub fn begin_tick(&self) { + self.budget + .store(500000, std::sync::atomic::Ordering::Relaxed); + } + pub fn add(&mut self, owner: &str, path: &str, source: &str) -> Result<()> { + ensure!( + source.len() <= 1024 * 1024, + "{owner}/{path}: script source exceeds 1 MiB" + ); + let mut ast = self + .engine + .compile(source) + .map_err(|e| anyhow::anyhow!("{owner}/{path}: {e}"))?; + for function in ast.iter_functions() { + if [ + "on_spawn", + "on_tick", + "on_fire", + "on_hit", + "on_death", + "on_pickup", + "on_use", + "on_mission_start", + "on_mission_end", + ] + .contains(&function.name) + { + ensure!( + function.params.len() == 3, + "{owner}/{path}::{}: callbacks require (event, state, random)", + function.name + ); + } + } + ast.set_source(format!("{owner}/{path}")); + self.scripts.insert((owner.into(), path.into()), ast); + Ok(()) + } + pub fn has(&self, owner: &str, path: &str) -> bool { + self.scripts.contains_key(&(owner.into(), path.into())) + } + pub fn invoke( + &mut self, + owner: &str, + path: &str, + hook: &str, + event: &serde_json::Value, + seed: i32, + ) -> Result> { + let ast = self + .scripts + .get(&(owner.into(), path.into())) + .with_context(|| format!("{owner}/{path}::{hook}: script is not loaded"))?; + if !ast + .iter_functions() + .any(|f| f.name == hook && f.params.len() == 3) + { + return Ok(vec![]); + } + let key = format!("{owner}/{path}"); + let mut rng = *self.rng.get(&key).unwrap_or(&LegacyRng::new(seed)); + let random: Vec = (0..32).map(|_| rng.next_value()).collect(); + let state = self + .states + .get(&key) + .cloned() + .unwrap_or_else(|| serde_json::json!({})); + let event = rhai::serde::to_dynamic(event.clone())?; + let state = rhai::serde::to_dynamic(state)?; + let random = rhai::serde::to_dynamic(random)?; + let value = self + .engine + .call_fn::(&mut Scope::new(), ast, hook, (event, state, random)) + .map_err(|e| anyhow::anyhow!("{owner}/{path}::{hook}: {e}"))?; + let result: HookResult = rhai::serde::from_dynamic(&value) + .map_err(|e| anyhow::anyhow!("{owner}/{path}::{hook}: invalid result: {e}"))?; + ensure!( + result.commands.len() <= 256, + "{owner}/{path}::{hook}: callback emitted too many commands" + ); + ensure!( + serde_json::to_vec(&result.state)?.len() <= 65536, + "{owner}/{path}::{hook}: callback state exceeds 64 KiB" + ); + // World command validation is performed by the caller before committing these values. + self.states.insert(key.clone(), result.state); + self.rng.insert(key, rng); + Ok(result.commands) + } + pub fn checkpoints( + &self, + ) -> ( + BTreeMap, + BTreeMap, + ) { + (self.states.clone(), self.rng.clone()) + } + pub fn restore( + &mut self, + c: ( + BTreeMap, + BTreeMap, + ), + ) { + self.states = c.0; + self.rng = c.1; + } +} +impl Default for ScriptRuntime { + fn default() -> Self { + Self::new() + } +} +pub fn write_schemas(root: &Path) -> Result<()> { + fs::create_dir_all(root)?; + macro_rules! schema { + ($name:expr,$ty:ty) => { + crate::persistence::atomic_write( + &root.join($name), + &serde_json::to_vec_pretty(&schemars::schema_for!($ty))?, + )?; + }; + } + schema!("mod-v1.json", Manifest); + schema!("content-v1.json", ContentPack); + schema!("hook-v1.json", HookResult); + schema!("weapon-projectile-v1.json", crate::content::WeaponDef); + schema!("item-v1.json", crate::content::ItemDef); + schema!("enemy-v1.json", crate::content::EnemyDef); + schema!("mission-v1.json", crate::content::MissionDef); + schema!("campaign-v1.json", crate::content::CampaignDef); + schema!("sound-v1.json", crate::content::SoundDef); + Ok(()) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn bounded_script_and_state_rollback() { + let mut rt = ScriptRuntime::new(); + rt.add("test", "bad.rhai", "fn on_tick(e,s,r) { while true {} }") + .unwrap(); + assert!( + rt.invoke("test", "bad.rhai", "on_tick", &serde_json::json!({}), 1) + .is_err() + ); + assert!(rt.states.is_empty()); + } + #[test] + fn script_can_emit_commands() { + let mut rt = ScriptRuntime::new(); + rt.add("test","good.rhai","fn on_fire(e,s,r) { #{ commands: [#{ op: \"credits\", amount: 7 }], state: #{ calls: 1 } } }").unwrap(); + assert_eq!( + rt.invoke("test", "good.rhai", "on_fire", &serde_json::json!({}), 1) + .unwrap() + .len(), + 1 + ); + assert_eq!(rt.states["test/good.rhai"]["calls"], 1); + } + #[test] + fn io_is_not_exposed() { + let mut rt = ScriptRuntime::new(); + rt.add( + "test", + "io.rhai", + "fn on_tick(e,s,r){ read_file(\"/etc/passwd\") }", + ) + .unwrap(); + assert!( + rt.invoke("test", "io.rhai", "on_tick", &serde_json::json!({}), 1) + .is_err() + ); + } +} diff --git a/src/persistence.rs b/src/persistence.rs new file mode 100644 index 00000000..2644d01f --- /dev/null +++ b/src/persistence.rs @@ -0,0 +1,591 @@ +use crate::{ + content::{ContentId, Registry}, + modding::ModPin, +}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeMap, + fs::{self, OpenOptions}, + io::Write, + path::{Path, PathBuf}, +}; + +#[derive(Debug, Clone)] +pub struct Paths { + pub data: PathBuf, + pub config: PathBuf, + pub cache: PathBuf, + pub legacy: PathBuf, +} +impl Paths { + pub fn discover() -> Result { + let home = PathBuf::from(std::env::var_os("HOME").context("HOME is unset")?); + let dir = |name: &str, fallback: &str| { + std::env::var_os(name) + .map(PathBuf::from) + .unwrap_or_else(|| home.join(fallback)) + }; + Ok(Self { + data: dir("XDG_DATA_HOME", ".local/share").join("RaptorReplica"), + config: dir("XDG_CONFIG_HOME", ".config").join("RaptorReplica"), + cache: dir("XDG_CACHE_HOME", ".cache").join("RaptorReplica"), + legacy: home.join(".local/share/Raptor"), + }) + } + pub fn mods(&self) -> PathBuf { + self.data.join("mods") + } + pub fn save_path(&self, slot: usize) -> PathBuf { + self.data.join(format!("pilot-{slot:04}.json")) + } +} +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Config { + pub hd_mode: bool, + pub scale: usize, + pub scanlines: bool, + pub fullscreen: bool, + pub borderless: bool, + pub aspect_correct: bool, + pub width: u32, + pub height: u32, + pub music_volume: u8, + pub fx_volume: u8, + pub fx_channels: usize, + pub control: String, + pub difficulty: u32, + pub bindings: BTreeMap, + pub enabled_mods: Vec, +} +impl Default for Config { + fn default() -> Self { + Self { + hd_mode: false, + scale: 4, + scanlines: false, + fullscreen: false, + borderless: false, + aspect_correct: true, + width: 1280, + height: 960, + music_volume: 85, + fx_volume: 85, + fx_channels: 2, + control: "keyboard".into(), + difficulty: 2, + bindings: [ + ("up", "Up"), + ("down", "Down"), + ("left", "Left"), + ("right", "Right"), + ("fire", "Left Ctrl"), + ("special", "Left Alt"), + ("cycle", "Space"), + ("bomb", "Right Shift"), + ] + .into_iter() + .map(|(k, v)| (k.into(), v.into())) + .collect(), + enabled_mods: vec![], + } + } +} +impl Config { + pub fn load(paths: &Paths) -> Result { + let path = paths.config.join("config.toml"); + let mut c = if path.exists() { + toml::from_str(&fs::read_to_string(path)?)? + } else { + Self::import_ini(&paths.legacy.join("SETUP.INI"))? + }; + ensure!( + matches!(c.scale, 1 | 2 | 3 | 4) + && c.width >= 320 + && c.height >= 200 + && c.width <= 7680 + && c.height <= 4320 + && (1..=8).contains(&c.fx_channels) + && c.difficulty <= 3, + "invalid video/difficulty settings" + ); + c.music_volume = c.music_volume.min(127); + c.fx_volume = c.fx_volume.min(127); + Ok(c) + } + pub fn save(&self, paths: &Paths) -> Result<()> { + atomic_write( + &paths.config.join("config.toml"), + toml::to_string_pretty(self)?.as_bytes(), + ) + } + pub fn import_ini(path: &Path) -> Result { + let mut config = Self::default(); + if !path.exists() { + return Ok(config); + } + let mut section = String::new(); + for line in fs::read_to_string(path)?.lines() { + let line = line.trim(); + if line.starts_with('[') && line.ends_with(']') { + section = line[1..line.len() - 1].to_ascii_lowercase(); + continue; + } + let Some((k, v)) = line.split_once('=') else { + continue; + }; + let k = k.trim().to_ascii_lowercase(); + let value = v.trim().parse::().unwrap_or(0); + match (section.as_str(), k.as_str()) { + ("video", "fullscreen") => config.fullscreen = value != 0, + ("video", "borderless") => config.borderless = value != 0, + ("video", "upscaler") => { + config.scale = if [2, 3, 4].contains(&value) { + value as usize + } else { + 1 + } + } + ("video", "scanlines") => config.scanlines = value != 0, + ("video", "aspect_ratio_correct") => config.aspect_correct = value != 0, + ("music", "volume") => config.music_volume = value.clamp(0, 127) as u8, + ("soundfx", "volume") => config.fx_volume = value.clamp(0, 127) as u8, + ("soundfx", "channels") => config.fx_channels = value.clamp(1, 8) as usize, + ("setup", "control") => { + config.control = match value { + 1 => "mouse", + 2 => "controller", + _ => "keyboard", + } + .into() + } + ("keyboard", _) => { + let action = match k.as_str() { + "moveup" => "up", + "movedn" => "down", + "moveleft" => "left", + "moveright" => "right", + "fire" => "fire", + "firesp" => "special", + "changesp" => "cycle", + "megafire" => "bomb", + _ => continue, + }; + if let Some(key) = legacy_scancode(value) { + config.bindings.insert(action.into(), key.into()); + } + } + _ => {} + } + } + Ok(config) + } +} +fn legacy_scancode(n: i32) -> Option<&'static str> { + Some(match n { + 72 => "Up", + 80 => "Down", + 75 => "Left", + 77 => "Right", + 29 => "Left Ctrl", + 56 => "Left Alt", + 57 => "Space", + 54 => "Right Shift", + 17 => "W", + 30 => "A", + 31 => "S", + 32 => "D", + 16 => "Q", + 18 => "E", + 28 => "Return", + _ => return None, + }) +} +pub fn atomic_write(path: &Path, data: &[u8]) -> Result<()> { + let parent = path.parent().context("output has no parent")?; + fs::create_dir_all(parent)?; + let mut n = 0u32; + let (temp, mut file) = loop { + let p = parent.join(format!( + ".{}.{}.{}.tmp", + path.file_name() + .context("missing output name")? + .to_string_lossy(), + std::process::id(), + n + )); + match OpenOptions::new().write(true).create_new(true).open(&p) { + Ok(f) => break (p, f), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, + Err(e) => return Err(e.into()), + } + }; + let result = (|| -> Result<()> { + file.write_all(data)?; + file.sync_all()?; + fs::rename(&temp, path)?; + fs::File::open(parent)?.sync_all()?; + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_file(temp); + } + result +} +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LegacyProgress { + pub portrait: i32, + pub sector: u32, + pub waves: [u32; 3], + pub difficulties: [u32; 4], + pub training: bool, + pub training_completed: bool, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Pilot { + pub version: u32, + pub name: String, + pub callsign: String, + pub credits: u32, + pub difficulty: u32, + pub inventory: BTreeMap, + pub selected: Option, + pub completed: Vec, + pub mission: ContentId, + pub mods: Vec, + pub script_state: BTreeMap, + #[serde(default)] + pub script_rng: BTreeMap, + #[serde(default)] + pub legacy_progress: Option, +} +impl Default for Pilot { + fn default() -> Self { + Self { + version: 1, + name: "Pilot".into(), + callsign: "RAPTOR".into(), + credits: 0, + difficulty: 2, + inventory: [("base:forward_guns".into(), 1), ("base:energy".into(), 100)] + .into_iter() + .collect(), + selected: None, + completed: vec![], + mission: "base:sector_1_wave_1".into(), + mods: vec![], + script_state: BTreeMap::new(), + script_rng: BTreeMap::new(), + legacy_progress: None, + } + } +} +impl Pilot { + pub fn complete_mission(&mut self, registry: &Registry) -> Result<()> { + let mission = registry + .missions + .get(&self.mission) + .context("completed mission is unavailable")?; + if !self.completed.contains(&self.mission) { + self.completed.push(self.mission.clone()); + } + let original = self + .mission + .0 + .strip_prefix("base:sector_") + .and_then(|s| s.split_once("_wave_")) + .and_then(|(s, w)| Some((s.parse::().ok()?, w.parse::().ok()?))) + .filter(|(s, w)| (1..=3).contains(s) && (1..=9).contains(w)); + if let Some((sector, wave)) = original.filter(|_| mission.legacy_map.is_some()) { + let sector = sector - 1; + let mut progress = self.legacy_progress.clone().unwrap_or(LegacyProgress { + portrait: 0, + sector: sector as u32, + waves: [0; 3], + difficulties: [self.difficulty; 4], + training: false, + training_completed: false, + }); + progress.difficulties[sector] = self.difficulty; + let limit = if self.difficulty == 0 { 4 } else { 9 }; + if wave >= limit { + if self.difficulty == 0 && !progress.training_completed { + // Original graduation resets the training ship and awards + // three 25-unit shields plus the initial 10,000 credits. + self.inventory = [("base:forward_guns".into(), 1), ("base:energy".into(), 75)] + .into_iter() + .collect(); + self.selected = None; + self.credits = 10000; + progress.training_completed = true; + for difficulty in &mut progress.difficulties { + if *difficulty == 0 { + *difficulty = 1; + } + } + } + progress.difficulties[sector] = (self.difficulty + 1).min(3); + progress.waves[sector] = 0; + if limit == 4 { + progress.waves = [0; 3]; + progress.sector = 0; + } else { + progress.sector = ((sector + 1) % 3) as u32; + } + } else { + progress.sector = sector as u32; + progress.waves[sector] = wave; + } + let next_sector = progress.sector as usize; + self.difficulty = progress.difficulties[next_sector]; + self.mission = ContentId(format!( + "base:sector_{}_wave_{}", + next_sector + 1, + progress.waves[next_sector] + 1 + )); + self.legacy_progress = Some(progress); + } else if let Some(next) = &mission.next { + self.mission = next.clone(); + } + self.validate(registry, &self.mods) + } + pub fn demo(sector: usize, registry: &Registry) -> Result { + let mut p = Self { + difficulty: 3, + credits: 10000, + ..Self::default() + }; + p.inventory.insert("base:detect".into(), 1); + let equipment: &[(u32, u32)] = match sector { + 0 => &[(2, 1), (11, 1), (4, 1), (7, 1), (5, 1), (14, 1)], + 1 => &[(11, 4), (15, 100), (1, 1), (2, 1), (5, 1), (8, 1)], + 2 => &[(11, 4), (15, 100), (1, 1), (2, 1), (13, 1), (8, 1)], + _ => anyhow::bail!("invalid demo sector"), + }; + for (index, count) in equipment { + let item = registry + .items + .values() + .find(|i| i.legacy == Some(*index)) + .context("missing demo item")?; + p.inventory.insert(item.id.clone(), *count); + } + if sector == 1 { + p.credits += 0x50003; + } else if sector == 2 { + p.credits += 0xd5fff; + } + // DEMO_MakePlayer advances once after OBJS_Add selects the first + // special weapon. Match that ordering rather than inventory sorting. + p.selected = registry + .items + .values() + .find(|i| i.legacy == Some([5, 8, 8][sector])) + .map(|i| i.id.clone()); + Ok(p) + } + pub fn save(&self, path: &Path) -> Result<()> { + atomic_write(path, &serde_json::to_vec_pretty(self)?) + } + pub fn load(path: &Path, registry: &Registry, pins: &[ModPin]) -> Result { + let p: Self = serde_json::from_slice(&fs::read(path)?)?; + p.validate(registry, pins)?; + Ok(p) + } + pub fn validate(&self, registry: &Registry, pins: &[ModPin]) -> Result<()> { + let p = self; + ensure!(p.version == 1, "unsupported save version {}", p.version); + ensure!( + p.difficulty <= 3 && p.inventory.len() <= 20, + "invalid pilot difficulty/inventory" + ); + ensure!( + p.mods == pins, + "save requires these mod versions/content: {:?}; enable the matching mods in the Mods screen", + p.mods + ); + ensure!( + registry.missions.contains_key(&p.mission), + "save mission {} is unavailable", + p.mission + ); + for (id, count) in &p.inventory { + ensure!( + registry.items.contains_key(id), + "saved item {id} is unavailable" + ); + ensure!( + *count <= registry.items[id].max_count, + "saved quantity of {id} exceeds capacity" + ); + } + if let Some(id) = &p.selected { + ensure!( + p.inventory.get(id).is_some_and(|n| *n > 0) + && registry.items.get(id).is_some_and(|i| i.special), + "equipped item {id} is unavailable" + ); + } + for id in &p.completed { + ensure!( + registry.missions.contains_key(id), + "completed mission {id} is unavailable" + ); + } + if let Some(progress) = &p.legacy_progress { + ensure!( + progress.sector < 3 + && progress.waves.iter().all(|w| *w < 9) + && progress.difficulties.iter().all(|d| *d < 4), + "invalid saved campaign progression" + ); + } + ensure!( + serde_json::to_vec(&p.script_state)?.len() <= 4 * 1024 * 1024, + "saved script state exceeds limit" + ); + Ok(()) + } + pub fn buy(&mut self, id: &ContentId, registry: &Registry) -> Result<()> { + let item = registry.items.get(id).context("unknown shop item")?; + ensure!(self.credits >= item.price, "not enough credits"); + let count = self.inventory.get(id).copied().unwrap_or(0); + ensure!(count < item.max_count, "item capacity reached"); + ensure!( + count > 0 || self.inventory.len() < 20, + "ship inventory is full" + ); + self.credits -= item.price; + self.inventory.insert( + id.clone(), + count.saturating_add(item.initial_count).min(item.max_count), + ); + Ok(()) + } + pub fn sell(&mut self, id: &ContentId, registry: &Registry) -> Result<()> { + let item = registry.items.get(id).context("unknown shop item")?; + ensure!( + id.0 != "base:forward_guns" && id.0 != "base:energy", + "essential ship equipment cannot be sold" + ); + let count = self.inventory.get_mut(id).context("item is not owned")?; + ensure!(*count > 0, "item is not owned"); + *count -= 1; + self.credits = self.credits.saturating_add(item.price / 2); + if *count == 0 { + self.inventory.remove(id); + if self.selected.as_ref() == Some(id) { + self.selected = None; + } + } + Ok(()) + } + pub fn import_legacy(path: &Path, registry: &Registry) -> Result { + let bytes = fs::read(path)?; + ensure!( + (88..=88 + 20 * 24).contains(&bytes.len()) && (bytes.len() - 88) % 24 == 0, + "invalid legacy save length" + ); + let head = decrypt(&bytes[..88], b"CASTLE"); + let body = decrypt(&bytes[88..], b"CASTLE"); + let val = |o| crate::assets::i32_at(&head, o); + let count = val(60)?; + ensure!( + count >= 0 && count as usize <= (body.len() / 24), + "truncated legacy inventory" + ); + let sector = val(44)?; + ensure!((0..3).contains(§or), "invalid legacy sector"); + let wave = val(48 + sector as usize * 4)?; + ensure!((0..9).contains(&wave), "invalid legacy wave"); + let difficulty = val(64 + sector as usize * 4)?; + ensure!((0..4).contains(&difficulty), "invalid legacy difficulty"); + let waves = [val(48)?, val(52)?, val(56)?]; + let difficulties = [val(64)?, val(68)?, val(72)?, val(76)?]; + ensure!( + waves.iter().all(|w| (0..9).contains(w)), + "invalid legacy campaign progress" + ); + ensure!( + difficulties.iter().all(|d| (0..4).contains(d)), + "invalid legacy campaign difficulty" + ); + ensure!( + [val(80)?, val(84)?].iter().all(|f| *f == 0 || *f == 1), + "invalid legacy training flags" + ); + let text = |r: std::ops::Range| { + String::from_utf8_lossy(head[r].split(|b| *b == 0).next().unwrap()).into_owned() + }; + let mut p = Self { + name: text(0..20), + callsign: text(20..32), + credits: val(36)? as u32, + difficulty: difficulty as u32, + mission: ContentId(format!("base:sector_{}_wave_{}", sector + 1, wave + 1)), + inventory: BTreeMap::new(), + legacy_progress: Some(LegacyProgress { + portrait: val(32)?, + sector: sector as u32, + waves: waves.map(|w| w as u32), + difficulties: difficulties.map(|d| d as u32), + training: val(80)? != 0, + training_completed: val(84)? != 0, + }), + ..Self::default() + }; + let special = val(40)?; + for r in body.chunks_exact(24).take(count as usize) { + let count = crate::assets::i32_at(r, 8)?; + let typ = crate::assets::i32_at(r, 12)?; + ensure!(count >= 0, "negative legacy item count"); + let item = registry + .items + .values() + .find(|i| i.legacy == Some(typ as u32)) + .context("unknown legacy item")?; + p.inventory.insert(item.id.clone(), count as u32); + if typ == special { + p.selected = Some(item.id.clone()); + } + } + for s in 0..3 { + let w = val(48 + s * 4)?; + for i in 1..=w { + p.completed + .push(ContentId(format!("base:sector_{}_wave_{i}", s + 1))); + } + } + p.validate(registry, &[])?; + Ok(p) + } +} +fn decrypt(bytes: &[u8], key: &[u8]) -> Vec { + let mut index = 25 % key.len(); + let mut previous = key[index]; + bytes + .iter() + .map(|x| { + let clear = x.wrapping_sub(key[index]).wrapping_sub(previous); + previous = *x; + index = (index + 1) % key.len(); + clear + }) + .collect() +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn writes_replace_atomically() { + let tmp = tempfile::tempdir().unwrap(); + let p = tmp.path().join("save.json"); + atomic_write(&p, b"first").unwrap(); + atomic_write(&p, b"second").unwrap(); + assert_eq!(fs::read(p).unwrap(), b"second"); + assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 1); + } +} diff --git a/src/render.rs b/src/render.rs new file mode 100644 index 00000000..60e455f7 --- /dev/null +++ b/src/render.rs @@ -0,0 +1,379 @@ +//! Palette-indexed rendering. Filters copy colors, never blend palette entries. +use crate::assets::{Sprite, TRANSPARENT}; +use anyhow::{Result, ensure}; +use sha2::{Digest, Sha256}; +use std::{collections::BTreeMap, fs, path::PathBuf}; + +pub fn upscale(sprite: &Sprite, factor: usize) -> Result { + ensure!( + matches!(factor, 1 | 2 | 3 | 4), + "scale must be 1, 2, 3 or 4" + ); + ensure!( + sprite.width > 0 + && sprite.height > 0 + && sprite.pixels.len() == sprite.width * sprite.height, + "invalid indexed image" + ); + ensure!( + sprite.width as u64 * sprite.height as u64 * (factor * factor) as u64 <= 16_777_216, + "derived image exceeds pixel limit" + ); + if factor == 1 { + return Ok(sprite.clone()); + } + if factor == 4 { + return upscale(&upscale(sprite, 2)?, 2); + } + let mut out = Sprite::blank(sprite.width * factor, sprite.height * factor); + for y in 0..sprite.height { + for x in 0..sprite.width { + let sample = |dx: isize, dy: isize| { + sprite.pixels[(y as isize + dy).clamp(0, sprite.height as isize - 1) as usize + * sprite.width + + (x as isize + dx).clamp(0, sprite.width as isize - 1) as usize] + }; + let [a, b, c, d, e, f, g, h, i] = [ + sample(-1, -1), + sample(0, -1), + sample(1, -1), + sample(-1, 0), + sample(0, 0), + sample(1, 0), + sample(-1, 1), + sample(0, 1), + sample(1, 1), + ]; + let p = if factor == 2 { + if b != h && d != f { + [ + if d == b { d } else { e }, + if b == f { f } else { e }, + if d == h { d } else { e }, + if h == f { f } else { e }, + e, + e, + e, + e, + e, + ] + } else { + [e; 9] + } + } else if b != h && d != f { + [ + if d == b { d } else { e }, + if (d == b && e != c) || (b == f && e != a) { + b + } else { + e + }, + if b == f { f } else { e }, + if (d == b && e != g) || (d == h && e != a) { + d + } else { + e + }, + e, + if (b == f && e != i) || (h == f && e != c) { + f + } else { + e + }, + if d == h { d } else { e }, + if (d == h && e != i) || (h == f && e != g) { + h + } else { + e + }, + if h == f { f } else { e }, + ] + } else { + [e; 9] + }; + for dy in 0..factor { + for dx in 0..factor { + out.pixels[(y * factor + dy) * out.width + x * factor + dx] = + p[dy * factor + dx]; + } + } + } + } + Ok(out) +} +pub fn nearest(sprite: &Sprite, factor: usize) -> Sprite { + let mut out = Sprite::blank(sprite.width * factor, sprite.height * factor); + for y in 0..out.height { + for x in 0..out.width { + out.pixels[y * out.width + x] = sprite.pixels[(y / factor) * sprite.width + x / factor]; + } + } + out +} +pub struct SpriteCache { + memory: BTreeMap, + root: Option, +} +impl SpriteCache { + pub fn new(root: Option) -> Self { + Self { + memory: BTreeMap::new(), + root, + } + } + pub fn get(&mut self, sprite: &Sprite, factor: usize, pixelated: bool) -> Result<&Sprite> { + let mut hash = Sha256::new(); + hash.update(b"raptor-scale-v1"); + hash.update(sprite.width.to_le_bytes()); + hash.update(sprite.height.to_le_bytes()); + hash.update([factor as u8, pixelated as u8]); + for p in &sprite.pixels { + hash.update(p.to_le_bytes()); + } + let key = format!("{:x}", hash.finalize()); + if !self.memory.contains_key(&key) { + let saved = self + .root + .as_ref() + .and_then(|r| fs::read(r.join(format!("{key}.json"))).ok()) + .and_then(|b| serde_json::from_slice::(&b).ok()) + .filter(|s| { + s.width == sprite.width * factor + && s.height == sprite.height * factor + && s.pixels.len() == s.width * s.height + && s.pixels.iter().all(|p| *p <= TRANSPARENT) + }); + let scaled = if let Some(s) = saved { + s + } else if pixelated { + nearest(sprite, factor) + } else { + upscale(sprite, factor)? + }; + if let Some(root) = &self.root { + fs::create_dir_all(root)?; + if !root.join(format!("{key}.json")).exists() { + crate::persistence::atomic_write( + &root.join(format!("{key}.json")), + &serde_json::to_vec(&scaled)?, + )?; + } + } + if self + .memory + .values() + .map(|s| s.pixels.len() * 2) + .sum::() + + scaled.pixels.len() * 2 + > 128 * 1024 * 1024 + { + self.memory.clear(); + } + self.memory.insert(key.clone(), scaled); + } + Ok(&self.memory[&key]) + } +} +pub struct Canvas { + pub image: Sprite, + pub scale: usize, +} +impl Canvas { + pub fn new(scale: usize) -> Self { + Self { + image: Sprite { + width: 320 * scale, + height: 200 * scale, + pixels: vec![0; 320 * 200 * scale * scale], + }, + scale, + } + } + pub fn clear(&mut self, color: u16) { + self.image.pixels.fill(color) + } + pub fn blit(&mut self, sprite: &Sprite, x: i32, y: i32) { + for sy in 0..sprite.height { + let yy = y + sy as i32; + if yy < 0 || yy >= self.image.height as i32 { + continue; + } + for sx in 0..sprite.width { + let xx = x + sx as i32; + if xx < 0 || xx >= self.image.width as i32 { + continue; + } + let c = sprite.pixels[sy * sprite.width + sx]; + if c != TRANSPARENT { + self.image.pixels[yy as usize * self.image.width + xx as usize] = c; + } + } + } + } + pub fn rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: u16) { + let s = self.scale as i32; + for yy in (y * s).max(0)..((y + h) * s).min(self.image.height as i32) { + for xx in (x * s).max(0)..((x + w) * s).min(self.image.width as i32) { + self.image.pixels[yy as usize * self.image.width + xx as usize] = color; + } + } + } + pub fn shade(&mut self, mask: &Sprite, x: i32, y: i32, table: &[u8; 256]) { + for sy in 0..mask.height { + let yy = y + sy as i32; + if yy < 0 || yy >= self.image.height as i32 { + continue; + } + for sx in 0..mask.width { + let xx = x + sx as i32; + if xx < 0 + || xx >= self.image.width as i32 + || mask.pixels[sy * mask.width + sx] == TRANSPARENT + { + continue; + } + let p = &mut self.image.pixels[yy as usize * self.image.width + xx as usize]; + if *p < 256 { + *p = table[*p as usize] as u16; + } + } + } + } + pub fn rgba(&self, palette: &[[u8; 3]; 256], scanlines: bool) -> Vec { + let mut out = vec![0; self.image.pixels.len() * 4]; + for (i, p) in self.image.pixels.iter().enumerate() { + let color = palette[(*p).min(255) as usize]; + let dark = scanlines && (i / self.image.width) % (self.scale * 3) == self.scale * 2; + for j in 0..3 { + out[i * 4 + j] = if dark { color[j] / 2 } else { color[j] }; + } + out[i * 4 + 3] = 255; + } + out + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn uniform_image_unchanged() { + let s = Sprite { + width: 2, + height: 2, + pixels: vec![9; 4], + }; + for n in [2, 3, 4] { + assert!(upscale(&s, n).unwrap().pixels.iter().all(|p| *p == 9)); + } + } + #[test] + fn scale_four_is_two_passes() { + let s = Sprite { + width: 3, + height: 3, + pixels: vec![0, 1, 0, 1, 1, 0, 0, 0, TRANSPARENT], + }; + assert_eq!( + upscale(&s, 4).unwrap(), + upscale(&upscale(&s, 2).unwrap(), 2).unwrap() + ); + } + #[test] + fn scale_three_guard_preserves_cross() { + let s = Sprite { + width: 3, + height: 3, + pixels: vec![1, 2, 3, 4, 5, 4, 6, 2, 7], + }; + let out = upscale(&s, 3).unwrap(); + for y in 3..6 { + for x in 3..6 { + assert_eq!(out.pixels[y * 9 + x], 5) + } + } + } + #[test] + fn clipped_transparency() { + let mut c = Canvas::new(1); + c.clear(3); + c.blit( + &Sprite { + width: 2, + height: 1, + pixels: vec![8, TRANSPARENT], + }, + -1, + 0, + ); + assert_eq!(c.image.pixels[0], 3); + } +} + +pub struct BitmapFont { + height: usize, + glyphs: Vec>, + widths: Vec, +} +impl BitmapFont { + pub fn decode(bytes: &[u8]) -> Result { + let height = crate::assets::i32_at(bytes, 0)?; + ensure!( + (1..=64).contains(&height) && bytes.len() >= 772, + "invalid bitmap font" + ); + let mut glyphs = Vec::new(); + let mut widths = Vec::new(); + for ch in 0..256 { + let offset = crate::assets::i16_at(bytes, 4 + ch * 2)?; + let width = bytes[516 + ch] as usize; + widths.push(width); + if offset < 0 || width == 0 { + glyphs.push(None); + continue; + } + let start = 772 + offset as usize; + let len = width * height as usize; + let data = bytes + .get(start..start + len) + .ok_or_else(|| anyhow::anyhow!("truncated font glyph {ch}"))?; + glyphs.push(Some(Sprite { + width, + height: height as usize, + pixels: data + .iter() + .map(|v| if *v == 0 { TRANSPARENT } else { *v as u16 }) + .collect(), + })); + } + Ok(Self { + height: height as usize, + glyphs, + widths, + }) + } + pub fn text(&self, canvas: &mut Canvas, x: i32, y: i32, text: &str, color: u16) { + let mut cursor = x; + for ch in text.bytes() { + if let Some(g) = &self.glyphs[ch as usize] { + let mut glyph = g.clone(); + for p in &mut glyph.pixels { + if *p != TRANSPARENT { + *p = (*p + color.saturating_sub(1)).min(255); + } + } + canvas.blit( + &nearest(&glyph, canvas.scale), + cursor * canvas.scale as i32, + y * canvas.scale as i32, + ); + } + cursor += self.widths[ch as usize] as i32 + 1; + if cursor > 314 { + break; + } + } + } + pub fn height(&self) -> usize { + self.height + } +} diff --git a/src/simulation.rs b/src/simulation.rs new file mode 100644 index 00000000..aec8ead5 --- /dev/null +++ b/src/simulation.rs @@ -0,0 +1,2352 @@ +//! SDL-independent fixed-step simulation and checked mod command application. +use crate::{ + content::{ContentId, Registry, Target, WeaponBehavior}, + modding::{Command, ScriptRuntime}, + persistence::Pilot, +}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +pub const TICK_NUMERATOR: u64 = 3; +pub const TICK_DENOMINATOR: u64 = 70; +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +pub struct LegacyRng { + pub seed: i32, +} +impl LegacyRng { + pub fn new(seed: i32) -> Self { + Self { seed } + } + pub fn next_value(&mut self) -> i32 { + self.seed = self.seed.wrapping_mul(1103515245).wrapping_add(12345); + (self.seed >> 16) & 0x7fff + } +} +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)] +pub struct Input { + pub dx: i32, + pub dy: i32, + pub fire: bool, + pub special: bool, + pub cycle: bool, + pub bomb: bool, + pub absolute: Option<[i32; 2]>, + pub demo_bank: Option, +} +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct LineMove { + pub x: i32, + pub y: i32, + pub tx: i32, + pub ty: i32, + pub dx: i32, + pub dy: i32, + pub ax: i32, + pub ay: i32, + pub error: i32, + pub remaining: i32, + pub done: bool, +} +impl LineMove { + pub fn new(x: i32, y: i32, tx: i32, ty: i32) -> Self { + let dx = (tx - x).abs(); + let dy = (ty - y).abs(); + let mut m = Self { + x, + y, + tx, + ty, + dx, + dy, + ax: if tx < x { -1 } else { 1 }, + ay: if ty < y { -1 } else { 1 }, + error: if dx >= dy { -(dy >> 1) } else { dx >> 1 }, + remaining: dx.max(dy) + 1, + done: false, + }; + if dx == 0 && dy == 0 { + m.done = true; + } + m + } + pub fn initial(&mut self) { + if self.remaining == 0 { + self.done = true; + return; + } + self.point(); + self.remaining -= 1; + } + fn point(&mut self) { + if self.dx >= self.dy { + self.x += self.ax; + self.error += self.dy; + if self.error > 0 { + self.y += self.ay; + self.error -= self.dx; + } + } else { + self.y += self.ay; + self.error += self.dx; + if self.error > 0 { + self.x += self.ax; + self.error -= self.dy; + } + } + } + pub fn advance_shot(&mut self, speed: i32) { + // MoveSobj crosses the endpoint before marking done; enemies instead stop at it. + for _ in 0..speed.max(0) { + self.remaining -= 1; + self.point(); + } + if self.remaining < 1 { + self.done = true; + } + } + pub fn advance(&mut self, speed: i32) -> i32 { + if self.done { + return speed; + } + let mut left = speed; + while left > 0 { + left -= 1; + self.remaining -= 1; + if self.remaining == 0 { + self.done = true; + return left; + } + if self.dx >= self.dy { + self.x += self.ax; + self.error += self.dy; + if self.error > 0 { + self.y += self.ay; + self.error -= self.dx; + } + } else { + self.y += self.ay; + self.error += self.dx; + if self.error > 0 { + self.x += self.ax; + self.error -= self.dy; + } + } + } + left + } +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Player { + pub x: i32, + pub y: i32, + pub px: i32, + pub py: i32, + pub bank: i32, + pub shield: i32, + pub super_shield: i32, + pub credits: u32, + pub inventory: BTreeMap, + pub selected: Option, + pub vx: i32, + pub vy: i32, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Enemy { + pub entity: u64, + pub definition: ContentId, + pub x: i32, + pub y: i32, + pub px: i32, + pub py: i32, + pub sx: i32, + pub sy: i32, + pub width: i32, + pub height: i32, + pub health: i32, + pub age: u32, + pub cooldown: u32, + pub path_index: usize, + pub reversed: bool, + pub movement: LineMove, + pub frame: u32, + pub art_frame: u32, + pub animation_on: bool, + pub animation_frames: u32, + pub multi: u32, + pub frame_timer: i32, + pub countdown: i32, + pub shoot_on: bool, + pub shootagain: i32, + pub shootcount: i32, + pub shootflag: i32, + pub kami: u32, + pub vx: i32, + pub vy: i32, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LegacyProjectile { + pub movement: LineMove, + pub speed: i32, + pub frame: u32, + pub art_frame: u32, + pub delay: bool, + pub hit: bool, + pub start: [i32; 2], +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EnemyProjectile { + pub movement: LineMove, + pub kind: i16, + pub asset: u32, + pub frames: u32, + pub frame: u32, + pub art_frame: u32, + pub speed: i32, + pub maximum_speed: i32, + pub damage: i32, + pub position: usize, + pub enemy: u64, + pub gun: usize, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Projectile { + pub entity: u64, + pub weapon: ContentId, + pub x: i32, + pub y: i32, + pub px: i32, + pub py: i32, + pub vx: i32, + pub vy: i32, + pub hostile: bool, + pub age: u32, + pub legacy: Option, + pub legacy_enemy: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Pickup { + pub entity: u64, + pub item: ContentId, + pub x: i32, + pub y: i32, + pub legacy: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LegacyPickup { + pub x: i32, + pub y: i32, + pub position: usize, + pub frame: u32, + pub art_frame: u32, + pub countdown: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Effect { + pub x: i32, + pub y: i32, + pub age: u32, +} +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +pub enum Outcome { + Playing, + Complete, + Failed, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SoundEvent { + pub asset: u32, + pub pan: i32, + pub pitch: i32, + pub volume: i32, + pub priority: i32, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TerrainDelay { + pub position: usize, + pub frames: i32, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct World { + pub tick: u64, + pub mission: ContentId, + pub player: Player, + pub enemies: Vec, + pub projectiles: Vec, + pub pickups: Vec, + pub effects: Vec, + pub terrain_health: Vec, + pub terrain_dead: Vec, + pub terrain_settled: Vec, + pub terrain_delays: Vec, + pub rng: LegacyRng, + pub difficulty: u32, + pub outcome: Outcome, + pub end_timer: Option, + pub scroll: i32, + pub objectives: BTreeMap, + pub sounds: Vec, + pub sound_events: Vec, + pub mod_sounds: Vec, + pub cooldowns: BTreeMap, + pub next_entity: u64, + pub spawn_cursor: usize, + pub cycle_held: bool, + pub bomb_held: bool, + pub palette_blue: bool, + pub special_held: bool, + pub player_flash: bool, + #[serde(skip)] + pub events: Vec, +} +#[derive(Debug, Clone)] +pub struct HookEvent { + pub content: ContentId, + pub hook: &'static str, + pub event: serde_json::Value, +} +impl World { + pub fn new(mission: &ContentId, pilot: &Pilot, registry: &Registry) -> Result { + let m = registry.missions.get(mission).context("unknown mission")?; + let energy = pilot + .inventory + .get(&ContentId::from("base:energy")) + .copied() + .unwrap_or(100) as i32; + let wave = mission + .0 + .rsplit('_') + .next() + .and_then(|s| s.parse::().ok()) + .unwrap_or(1) + - 1; + let mut out = Self { + tick: 0, + mission: mission.clone(), + player: Player { + x: 144, + y: 160, + px: 144, + py: 160, + bank: 3, + shield: energy.clamp(1, 100), + super_shield: pilot + .inventory + .get(&ContentId::from("base:super_shield")) + .copied() + .unwrap_or(0) + .min(100) as i32, + credits: pilot.credits, + inventory: pilot.inventory.clone(), + selected: pilot.selected.clone(), + vx: 0, + vy: 0, + }, + enemies: vec![], + projectiles: vec![], + pickups: vec![], + effects: vec![], + terrain_health: m.layout.iter().map(|i| m.tiles[*i].health).collect(), + terrain_dead: vec![false; m.layout.len()], + terrain_settled: vec![false; m.layout.len()], + terrain_delays: vec![], + rng: LegacyRng::new(wave << 10), + difficulty: pilot.difficulty, + outcome: Outcome::Playing, + end_timer: None, + scroll: 0, + objectives: BTreeMap::new(), + sounds: vec![], + sound_events: vec![], + mod_sounds: vec![], + cooldowns: BTreeMap::new(), + next_entity: 1, + spawn_cursor: 0, + cycle_held: false, + bomb_held: false, + palette_blue: false, + special_held: false, + player_flash: false, + events: vec![], + }; + out.event( + mission.clone(), + "on_mission_start", + serde_json::json!({"tick":0}), + ); + Ok(out) + } + pub fn pilot(&self, prior: &Pilot) -> Pilot { + let mut p = prior.clone(); + p.credits = self.player.credits; + p.inventory = self.player.inventory.clone(); + p.inventory + .insert("base:energy".into(), self.player.shield.max(1) as u32); + if p.inventory + .contains_key(&ContentId::from("base:super_shield")) + { + p.inventory.insert( + "base:super_shield".into(), + self.player.super_shield.max(0) as u32, + ); + } + p.selected = self.player.selected.clone(); + p.mission = self.mission.clone(); + p + } + fn entity(&mut self) -> u64 { + let n = self.next_entity; + self.next_entity += 1; + n + } + fn event(&mut self, content: ContentId, hook: &'static str, event: serde_json::Value) { + self.events.push(HookEvent { + content, + hook, + event, + }); + } + pub fn spawn(&mut self, id: &ContentId, x: i32, y: i32, registry: &Registry) -> Result { + let e = registry.enemies.get(id).context("unknown enemy")?; + ensure!(self.enemies.len() < 4096, "enemy capacity exceeded"); + let entity = self.entity(); + let (w, h) = e + .art + .as_ref() + .map(|a| (a.logical_width as i32, a.logical_height as i32)) + .unwrap_or((32, 32)); + let f = e.legacy.as_ref().map(|l| &l.fields); + let x = match f.map(|f| f[21]) { + Some(4) => x + w, + Some(5) => x - w, + _ => x, + }; + let sx = x; + let sy = if f.is_some() { 100 - h / 2 } else { y }; + let first = e.path.first().copied().unwrap_or([0, 300]); + let mut movement = LineMove::new(x, y, sx + first[0], sy + first[1]); + if f.is_some() && !e.ground { + movement.initial(); + } + let health = if e.boss && self.difficulty <= 1 { + e.health - (e.health >> 1) + } else { + e.health + }; + self.enemies.push(Enemy { + entity, + definition: id.clone(), + x, + y, + px: x, + py: y, + sx, + sy, + width: w, + height: h, + health, + age: 0, + cooldown: 0, + path_index: 1, + reversed: false, + movement, + frame: 0, + art_frame: 0, + animation_on: f.is_none_or(|f| f[10] != 1), + animation_frames: f.map_or(1, |f| if f[10] == 2 { f[9] } else { f[7] }.max(1) as u32), + multi: 0, + frame_timer: f.map_or(0, |f| f[6]), + countdown: f.map_or(0, |f| f[8] - y), + shoot_on: false, + shootagain: -1, + shootcount: f.map_or(1, |f| { + if e.boss && self.difficulty <= 1 { + f[16] - (f[16] >> 2) + } else { + f[16] + } + }), + shootflag: f.map_or(0, |f| f[15]), + kami: 0, + vx: 0, + vy: 0, + }); + self.event( + id.clone(), + "on_spawn", + serde_json::json!({"entity":entity,"x":x,"y":y}), + ); + Ok(entity) + } + fn projectile( + &mut self, + id: &ContentId, + x: i32, + y: i32, + vx: i32, + vy: i32, + hostile: bool, + ) -> Result<()> { + ensure!( + self.projectiles.len() < 8192, + "projectile capacity exceeded" + ); + let entity = self.entity(); + self.projectiles.push(Projectile { + entity, + weapon: id.clone(), + x, + y, + px: x, + py: y, + vx, + vy, + hostile, + age: 0, + legacy: None, + legacy_enemy: None, + }); + Ok(()) + } + pub fn step( + &mut self, + input: Input, + registry: &Registry, + scripts: &mut ScriptRuntime, + ) -> Result<()> { + if self.outcome != Outcome::Playing { + return Ok(()); + } + scripts.begin_tick(); + let checkpoint = self.clone(); + let script_checkpoint = scripts.checkpoints(); + let result = self + .advance(input, registry) + .and_then(|_| self.dispatch(registry, scripts)); + if let Err(err) = result { + *self = checkpoint; + scripts.restore(script_checkpoint); + return Err(err); + } + Ok(()) + } + fn advance(&mut self, input: Input, registry: &Registry) -> Result<()> { + self.sounds.clear(); + self.sound_events.clear(); + self.mod_sounds.clear(); + self.player_flash = false; + self.player.px = self.player.x; + self.player.py = self.player.y; + if let Some([x, y]) = input.absolute { + self.player.x = x.clamp(5, 282); + self.player.y = y.clamp(0, 160); + } else { + self.player.vx = accelerate(self.player.vx, input.dx, 10); + self.player.vy = accelerate(self.player.vy, input.dy, 8); + self.player.x = (self.player.x + self.player.vx).clamp(5, 282); + self.player.y = (self.player.y + self.player.vy).clamp(0, 160); + } + let delta = ((self.player.x - self.player.px).abs() >> 2).min(3); + if let Some(bank) = input.demo_bank { + self.player.bank = bank.clamp(0, 6); + } else if self.player.x < self.player.px { + if self.player.bank < 3 + delta { + self.player.bank += 1; + } + } else if self.player.x > self.player.px { + if self.player.bank > 3 - delta { + self.player.bank -= 1; + } + } else { + self.player.bank += (3 - self.player.bank).signum(); + } + if input.fire { + let mut weapons: Vec<_> = self + .player + .inventory + .iter() + .filter_map(|(id, n)| { + if *n > 0 { + registry + .items + .get(id) + .filter(|i| !i.special && i.legacy != Some(11)) + .and_then(|i| i.weapon.clone()) + } else { + None + } + }) + .chain( + self.player + .selected + .as_ref() + .and_then(|id| registry.items.get(id)) + .and_then(|i| i.weapon.clone()), + ) + .collect(); + weapons.sort_by_key(|id| (registry.weapons[id].legacy.unwrap_or(u32::MAX), id.clone())); + // Original primary weapons fire in numeric order, followed by the selected special. + if let Some(selected) = self + .player + .selected + .as_ref() + .and_then(|id| registry.items.get(id)) + .and_then(|i| i.weapon.as_ref()) + { + weapons.retain(|id| id != selected); + weapons.push(selected.clone()); + } + for id in weapons { + self.fire(&id, registry)?; + } + } + if input.special { + if let Some(id) = self.player.selected.clone() { + if let Some(item) = registry.items.get(&id) { + if let Some(weapon) = item.weapon.as_ref() { + self.fire(weapon, registry)?; + } else if !self.special_held + && self.player.inventory.get(&id).copied().unwrap_or(0) > 0 + { + if item.consumable { + *self.player.inventory.get_mut(&id).unwrap() -= 1; + if self.player.inventory[&id] == 0 { + self.player.selected = None; + } + } + self.player.shield = (self.player.shield + item.shield).clamp(0, 100); + self.player.credits = self.player.credits.saturating_add(item.credits); + self.event(id,"on_use",serde_json::json!({"entity":0,"x":self.player.x,"y":self.player.y,"tick":self.tick})); + } + } + } + } + self.special_held = input.special; + if input.cycle && !self.cycle_held { + let mut specials: Vec<_> = self + .player + .inventory + .keys() + .filter(|id| registry.items.get(*id).is_some_and(|i| i.special)) + .cloned() + .collect(); + specials.sort_by_key(|id| (registry.items[id].legacy.unwrap_or(u32::MAX), id.clone())); + if !specials.is_empty() { + let next = self + .player + .selected + .as_ref() + .and_then(|id| specials.iter().position(|s| s == id)) + .map_or(0, |i| (i + 1) % specials.len()); + self.player.selected = Some(specials[next].clone()); + } + } + self.cycle_held = input.cycle; + if input.bomb && !self.bomb_held { + let id = ContentId::from("base:mega_bomb"); + if self.player.inventory.get(&id).copied().unwrap_or(0) > 0 { + if let Some(weapon) = registry.items.get(&id).and_then(|i| i.weapon.clone()) { + let before = self.projectiles.len(); + self.fire(&weapon, registry)?; + if self.projectiles.len() > before { + *self.player.inventory.get_mut(&id).unwrap() -= 1; + } + } + } + } + self.bomb_held = input.bomb; + self.scroll += 1; + self.think_legacy_terrain(registry); + let mission = ®istry.missions[&self.mission]; + while self.spawn_cursor < mission.spawns.len() + && mission.spawns[self.spawn_cursor].tick <= self.tick + { + let spawn = &mission.spawns[self.spawn_cursor]; + let enabled = if mission.legacy_map.is_some() { + match spawn.difficulty { + 3 => true, + 4 => self.difficulty >= 2, + 5 => self.difficulty >= 3, + _ => false, + } + } else { + self.difficulty >= spawn.difficulty + }; + if enabled { + let (x, y) = if mission.legacy_map.is_some() { + let art = registry.enemies[&spawn.enemy].art.as_ref().unwrap(); + ( + spawn.x + 16 - art.logical_width as i32 / 2, + spawn.y - art.logical_height as i32 / 2, + ) + } else { + (spawn.x, spawn.y) + }; + self.spawn(&spawn.enemy, x, y, registry)?; + } + self.spawn_cursor += 1; + } + // Ground/air enemy updates precede hostile shots, bonuses and player shots. + let mut shots = Vec::new(); + let mut retired = Vec::new(); + let mut events = Vec::new(); + for enemy in &mut self.enemies { + let def = ®istry.enemies[&enemy.definition]; + enemy.px = enemy.x; + enemy.py = enemy.y; + enemy.age += 1; + if enemy.vx != 0 || enemy.vy != 0 { + enemy.x += enemy.vx; + enemy.y += enemy.vy; + } else if def.ground { + enemy.y += 1; + if let Some(l) = &def.legacy { + match l.fields[21] { + 4 if enemy.y >= 0 => enemy.x -= def.speed, + 5 if enemy.y >= 0 => enemy.x += def.speed, + _ => {} + } + } + } else { + enemy.x = enemy.movement.x; + enemy.y = enemy.movement.y; + let left = enemy.movement.advance(def.speed); + if enemy.movement.done && !def.path.is_empty() { + let count = def.path.len(); + if enemy.path_index >= count { + if def.repeat { + enemy.reversed = true; + enemy.path_index = count.saturating_sub(1); + } else if def.legacy.as_ref().is_some_and(|l| l.fields[21] == 2) + && enemy.kami < 2 + { + enemy.kami += 1; + } else { + retired.push(enemy.entity); + } + } + let target = if enemy.kami == 2 { + [self.player.x + 16 - enemy.sx, self.player.y + 16 - enemy.sy] + } else { + def.path[enemy.path_index.min(count - 1)] + }; + enemy.movement = LineMove::new( + enemy.movement.tx, + enemy.movement.ty, + enemy.sx + target[0], + enemy.sy + target[1], + ); + if def.legacy.is_some() { + enemy.movement.initial(); + } + enemy.movement.advance(left); + if enemy.reversed { + enemy.path_index = enemy.path_index.saturating_sub(1); + let min = def + .legacy + .as_ref() + .map_or(0, |l| l.fields[20].max(0) as usize); + if enemy.path_index <= min { + enemy.reversed = false; + } + } else { + enemy.path_index += 1; + } + } else if def.path.is_empty() { + enemy.y += def.speed; + } + } + if let Some(l) = &def.legacy { + update_legacy_animation(enemy, l); + } else { + enemy.frame = enemy.age / 3; + enemy.art_frame = enemy.frame; + enemy.shoot_on = true; + } + if enemy.shoot_on + && (def.legacy.is_some() + || (enemy.health > 0 && enemy.y > -enemy.height && enemy.y < 200)) + { + if let Some(weapon) = &def.weapon { + if let Some(l) = &def.legacy { + match enemy.shootagain { + -1 => { + enemy.shootflag -= 1; + if enemy.shootflag < 0 { + enemy.shootflag = l.fields[3]; + for gun in 0..l.fields[22].max(0) as usize { + shots.push(( + weapon.clone(), + enemy.x + l.gun_x[gun] as i32, + enemy.y + l.gun_y[gun] as i32, + Some((l.shoot_type[gun], enemy.entity, def.speed, gun)), + )); + let sx = enemy.x + l.gun_x[gun] as i32; + let sy = enemy.y + l.gun_y[gun] as i32; + if (0..320).contains(&sx) && (0..200).contains(&sy) { + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + match l.shoot_type[gun] { + 4 => "FX_ENEMYMISSLE", + 5 => "FX_ENEMYLASER", + 7 => "FX_ENEMYPLASMA", + _ => "FX_ENEMYSHOT", + }, + ); + position_sound( + &mut self.sound_events, + sx, + sy, + self.player.x + 16, + self.player.y + 16, + ); + } + } + enemy.shootcount -= 1; + if enemy.shootcount < 1 { + enemy.shootagain = l.fields[17]; + } + } + } + 0 => { + enemy.shootagain = -1; + enemy.shootcount = l.fields[16]; + enemy.shootflag = l.fields[3]; + } + _ => enemy.shootagain -= 1, + } + } else if enemy.cooldown == 0 { + shots.push(( + weapon.clone(), + enemy.x + enemy.width / 2, + enemy.y + enemy.height, + Some((-1, enemy.entity, def.speed, 0)), + )); + enemy.cooldown = def.cooldown; + } else { + enemy.cooldown -= 1; + } + } + } + if def.ground + && def.legacy.as_ref().is_some_and(|l| { + enemy.y > 211 + || (l.fields[21] == 4 && enemy.x < -enemy.width / 2) + || (l.fields[21] == 5 && enemy.x > 335) + }) + { + retired.push(enemy.entity); + continue; + } + if def.boss && enemy.health < 50 && (self.tick + 1) & 2 != 0 && def.legacy.is_some() { + self.rng.next_value(); + self.rng.next_value(); + } + if !def.ground && contains(enemy, self.player.x + 16, self.player.y + 16) { + enemy.health -= 16; + damage_player( + &mut self.player, + enemy.width.max(enemy.height) >> 2, + self.difficulty, + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + ); + if def.legacy.is_some() { + self.rng.next_value(); + self.rng.next_value(); + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_CRASH", + ); + } + } + if enemy.health <= 0 { + if let Some(legacy) = &def.legacy { + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_AIREXPLO", + ); + position_sound( + &mut self.sound_events, + enemy.x + enemy.width / 2, + enemy.x + enemy.width / 2, + self.player.x + 16, + self.player.y + 16, + ); + let random_count = match legacy.fields[2] { + 2 | 6 => 2 * (enemy.width >> 4) * (enemy.height >> 4), + 4 => 3, + 5 => 3 * (enemy.width >> 4) * (enemy.height >> 4), + _ => 0, + }; + for _ in 0..random_count { + self.rng.next_value(); + } + } + self.player.credits = self.player.credits.saturating_add(def.reward); + self.effects.push(Effect { + x: enemy.x + enemy.width / 2, + y: enemy.y + enemy.height / 2, + age: 0, + }); + events.push(HookEvent { + content: enemy.definition.clone(), + hook: "on_death", + event: serde_json::json!({"entity":enemy.entity,"x":enemy.x,"y":enemy.y}), + }); + let mut drops: Vec<_> = def.drop.iter().cloned().collect(); + if def.legacy.as_ref().is_some_and(|l| l.fields[2] == 8) { + drops.insert(0, ContentId::from("base:itembuy6")); + } + for drop in drops { + let legacy = if def.legacy.is_some() { + if self.pickups.len() >= 12 + || (drop == ContentId::from("base:itembuy6") + && self.pickups.iter().filter(|p| p.item == drop).count() > 9) + { + continue; + } + let position = self.rng.next_value() as usize % 16; + Some(LegacyPickup { + x: enemy.x + 16, + y: enemy.y, + position, + frame: 0, + art_frame: 0, + countdown: None, + }) + } else { + None + }; + let id = self.next_entity; + self.next_entity += 1; + self.pickups.push(Pickup { + entity: id, + item: drop, + x: enemy.x, + y: enemy.y, + legacy, + }); + } + retired.push(enemy.entity); + } else if enemy.y > 240 || enemy.x < -enemy.width - 40 || enemy.x > 360 { + retired.push(enemy.entity); + } + if !retired.contains(&enemy.entity) { + events.push(HookEvent{content:enemy.definition.clone(),hook:"on_tick",event:serde_json::json!({"entity":enemy.entity,"x":enemy.x,"y":enemy.y,"health":enemy.health,"tick":self.tick,"player_x":self.player.x,"player_y":self.player.y})}); + } + } + self.events.extend(events); + self.enemies.retain(|e| !retired.contains(&e.entity)); + for (id, x, y, legacy) in shots { + if legacy.is_none_or(|(kind, _, _, _)| kind < 0) + || ((0..320).contains(&x) && (0..200).contains(&y)) + { + let entity = legacy.map_or(0, |(_, entity, _, _)| entity); + self.event(id.clone(),"on_fire",serde_json::json!({"entity":entity,"x":x,"y":y,"hostile":true,"tick":self.tick})); + if let Some(enemy) = self.enemies.iter().find(|e| e.entity == entity) { + let definition = enemy.definition.clone(); + self.event(definition,"on_fire",serde_json::json!({"entity":entity,"weapon":id,"x":x,"y":y,"hostile":true,"tick":self.tick})); + } + } + if let Some((kind, entity, speed, gun)) = legacy.filter(|(kind, _, _, _)| *kind >= 0) { + self.enemy_projectile(&id, x, y, kind, entity, speed, gun)?; + continue; + } + let speed = registry.weapons[&id].speed; + let dx = self.player.x + 16 - x; + let dy = self.player.y + 16 - y; + let norm = dx.abs().max(dy.abs()).max(1); + self.projectile(&id, x, y, dx * speed / norm, dy * speed / norm, true)?; + } + for cooldown in self.cooldowns.values_mut() { + *cooldown = cooldown.saturating_sub(1); + } + let mut dead_shots = Vec::new(); + let mut hit_events = Vec::new(); + self.think_enemy_projectiles(registry)?; + for p in self + .projectiles + .iter_mut() + .filter(|p| p.hostile && p.legacy_enemy.is_none()) + { + p.px = p.x; + p.py = p.y; + p.x += p.vx; + p.y += p.vy; + p.age += 1; + if (p.x - (self.player.x + 16)).abs() < 10 && (p.y - (self.player.y + 16)).abs() < 10 { + damage_player( + &mut self.player, + registry.weapons[&p.weapon].damage, + self.difficulty, + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + ); + dead_shots.push(p.entity); + } + } + let mut picked = Vec::new(); + for pickup in &mut self.pickups { + let collision = if let Some(legacy) = &mut pickup.legacy { + const X: [i32; 16] = [-1, 0, 1, 2, 3, 3, 3, 2, 1, 0, -1, -2, -3, -3, -3, -2]; + const Y: [i32; 16] = [-3, -3, -3, -2, -1, 0, 1, 2, 3, 3, 3, 2, 1, 0, -1, -2]; + legacy.art_frame = legacy.frame; + pickup.x = legacy.x - 8 + X[legacy.position]; + pickup.y = legacy.y - 8 + Y[legacy.position]; + legacy.y += 1; + if self.tick & 1 != 0 { + legacy.position = (legacy.position + 1) % 16; + legacy.frame = (legacy.frame + 1) + % registry.items[&pickup.item] + .art + .as_ref() + .map_or(1, |a| a.frames.max(1)); + } + legacy.countdown.is_none() + && self.player.shield > 0 + && legacy.x > self.player.x + && legacy.x < self.player.x + 32 + && legacy.y > self.player.y + && legacy.y < self.player.y + 32 + } else { + pickup.y += 1; + (pickup.x - self.player.x).abs() < 24 && (pickup.y - self.player.y).abs() < 24 + }; + if collision { + let item = ®istry.items[&pickup.item]; + if item.credits == 0 + && (self.player.inventory.contains_key(&pickup.item) + || self.player.inventory.len() < 20) + { + let amount = self + .player + .inventory + .entry(pickup.item.clone()) + .or_default(); + *amount = amount + .saturating_add(item.initial_count) + .min(item.max_count); + if item.special && self.player.selected.is_none() { + self.player.selected = Some(pickup.item.clone()); + } + } + if item.legacy == Some(15) { + self.player.super_shield = 100; + } else { + self.player.shield = (self.player.shield + item.shield).min(100); + } + self.player.credits = self.player.credits.saturating_add(item.credits); + if pickup.legacy.is_some() { + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_BONUS", + ); + } + if item.credits > 0 && pickup.legacy.is_some() { + pickup.legacy.as_mut().unwrap().countdown = Some(50); + } else { + picked.push(pickup.entity); + } + hit_events.push(HookEvent { + content: pickup.item.clone(), + hook: "on_pickup", + event: serde_json::json!({"entity":pickup.entity}), + }); + } + if let Some(legacy) = &mut pickup.legacy { + if let Some(countdown) = &mut legacy.countdown { + *countdown = countdown.saturating_sub(1); + if *countdown == 0 { + picked.push(pickup.entity); + } + } + if legacy.y - 8 > 200 { + picked.push(pickup.entity); + } + } + } + self.pickups + .retain(|p| p.y < 220 && !picked.contains(&p.entity)); + self.think_legacy_projectiles(registry)?; + for p in self + .projectiles + .iter_mut() + .filter(|p| !p.hostile && p.legacy.is_none()) + { + p.px = p.x; + p.py = p.y; + p.age += 1; + let weapon = ®istry.weapons[&p.weapon]; + if matches!(weapon.behavior, WeaponBehavior::Homing) { + if let Some(target) = self.enemies.iter().find(|e| { + e.health > 0 + && target_matches(&weapon.target, registry.enemies[&e.definition].ground) + }) { + p.vx = (target.x + target.width / 2 - p.x) + .clamp(-weapon.speed.abs(), weapon.speed.abs()); + } + } + p.x += p.vx; + p.y += p.vy; + if matches!(weapon.behavior, WeaponBehavior::Beam) { + p.x = self.player.x + 16; + for e in &mut self.enemies { + if target_matches(&weapon.target, registry.enemies[&e.definition].ground) + && p.x > e.x + && p.x < e.x + e.width + && e.y < self.player.y + { + e.health -= weapon.damage; + hit_events.push(HookEvent{content:e.definition.clone(),hook:"on_hit",event:serde_json::json!({"entity":e.entity,"projectile":p.entity,"weapon":p.weapon,"damage":weapon.damage,"x":p.x,"y":e.y,"health":e.health})}); + hit_events.push(HookEvent{content:p.weapon.clone(),hook:"on_hit",event:serde_json::json!({"entity":e.entity,"projectile":p.entity,"damage":weapon.damage,"x":p.x,"y":e.y})}); + } + } + if p.age > 1 { + dead_shots.push(p.entity); + } + } else if let Some(e) = self.enemies.iter_mut().find(|e| { + e.health > 0 + && target_matches(&weapon.target, registry.enemies[&e.definition].ground) + && contains(e, p.x, p.y) + }) { + e.health -= weapon.damage; + hit_events.push(HookEvent{content:e.definition.clone(),hook:"on_hit",event:serde_json::json!({"entity":e.entity,"projectile":p.entity,"weapon":p.weapon,"damage":weapon.damage,"x":p.x,"y":p.y,"health":e.health})}); + hit_events.push(HookEvent{content:p.weapon.clone(),hook:"on_hit",event:serde_json::json!({"entity":e.entity,"projectile":p.entity,"damage":weapon.damage,"x":p.x,"y":p.y})}); + dead_shots.push(p.entity); + } else if !matches!(weapon.target, Target::Air) { + let col = (p.x - 16) / 32; + let row = (p.y + mission.layout.len() as i32 / mission.columns.max(1) as i32 * 32 + - 200 + - self.scroll) + / 32; + if col >= 0 && col < mission.columns as i32 && row >= 0 { + let pos = row as usize * mission.columns as usize + col as usize; + if pos < self.terrain_health.len() + && self.terrain_health[pos] > 0 + && !self.terrain_dead[pos] + { + self.terrain_health[pos] -= weapon.damage; + dead_shots.push(p.entity); + if self.terrain_health[pos] <= 0 { + self.terrain_dead[pos] = true; + self.player.credits = self + .player + .credits + .saturating_add(mission.tiles[mission.layout[pos]].reward); + self.effects.push(Effect { + x: p.x, + y: p.y, + age: 0, + }); + } + } + } + } + } + self.events.extend(hit_events); + self.projectiles.retain(|p| { + !dead_shots.contains(&p.entity) + && (p.legacy.is_some() + || (p.x >= -32 && p.x <= 352 && p.y >= -64 && p.y <= 240 && p.age < 300)) + }); + for e in &mut self.effects { + e.age += 1; + } + self.effects.retain(|e| e.age < 20); + self.tick += 1; + if self.player.shield <= 0 { + self.outcome = Outcome::Failed; + } else if mission.auto_complete { + if mission.legacy_map.is_some() { + // ENEMY_Remove starts the original 60-tick departure only + // after the final spawn has been visited and all ships left. + if self.spawn_cursor == mission.spawns.len() && self.enemies.is_empty() { + match self.end_timer { + None => self.end_timer = Some(60), + Some(0) => self.outcome = Outcome::Complete, + Some(n) => self.end_timer = Some(n - 1), + } + } + } else if self.tick >= mission.duration + && self.spawn_cursor == mission.spawns.len() + && self + .enemies + .iter() + .all(|e| !registry.enemies[&e.definition].boss) + { + self.outcome = Outcome::Complete; + } + } + self.event(self.mission.clone(),"on_tick",serde_json::json!({"tick":self.tick,"player_x":self.player.x,"player_y":self.player.y,"enemies":self.enemies.len()})); + if self.outcome != Outcome::Playing { + self.event( + self.mission.clone(), + "on_mission_end", + serde_json::json!({"success":self.outcome==Outcome::Complete,"tick":self.tick}), + ); + } + if mission.legacy_map.is_some() && self.tick >= 3 && self.tick % 2 == 1 { + // Palette index 254 consumes the original shared RNG, even when no frame is rendered. + self.palette_blue = self.rng.next_value() % 3 == 0; + } + Ok(()) + } + fn fire(&mut self, id: &ContentId, registry: &Registry) -> Result<()> { + let Some(w) = registry.weapons.get(id) else { + return Ok(()); + }; + if self.cooldowns.get(id).copied().unwrap_or(0) > 0 { + return Ok(()); + } + self.cooldowns.insert(id.clone(), w.cooldown); + if let Some(index) = w.legacy { + if let Some(legacy) = crate::legacy_tables::weapons() + .into_iter() + .find(|w| w.index == index) + { + self.fire_legacy(id, &legacy, registry)?; + return Ok(()); + } + } + let offsets = if w.offsets.is_empty() { + vec![[0, 0]] + } else { + w.offsets.clone() + }; + for [x, y] in offsets { + self.projectile( + id, + self.player.x + 16 + x, + self.player.y + y, + 0, + -w.speed.max(1), + false, + )?; + } + self.event( + id.clone(), + "on_fire", + serde_json::json!({"entity":0,"hostile":false,"x":self.player.x+16,"y":self.player.y,"tick":self.tick}), + ); + Ok(()) + } + fn enemy_projectile( + &mut self, + id: &ContentId, + x: i32, + y: i32, + kind: i16, + enemy: u64, + enemy_speed: i32, + gun: usize, + ) -> Result<()> { + if !(0..320).contains(&x) + || !(0..200).contains(&y) + || self + .projectiles + .iter() + .filter(|p| p.legacy_enemy.is_some()) + .count() + >= 80 + { + return Ok(()); + } + let (asset, frames, maximum_speed, damage, offset_y) = match kind { + 0 => (0x101d6, 2, 6, 1, 4), + 1..=3 => (0x101d6, 2, 6, 2, 4), + 4 => (0x101d4, 2, 10, 4, 0), + 5 => (0x10241, 4, 6, 12, 0), + 6 => (0x101d1, 2, 0, 16, 0), + 7 => (0x10251, 1, 10, 15, 0), + 8 => (0x1024d, 4, 6, 1, 4), + _ => { + return Err(anyhow::anyhow!( + "unknown original enemy projectile type {kind}" + )); + } + }; + let start = [x - if kind == 6 { 0 } else { 4 }, y - offset_y]; + let mut target = [start[0], 200]; + let speed = match kind { + 0 | 8 => 1, + 1..=3 => 3, + 4 => enemy_speed + 1, + 5 => enemy_speed, + 6 => 150, + 7 => 8, + _ => 1, + }; + match kind { + 0 | 8 => target = [self.player.x + 16, self.player.y + 16], + 2 => target = [start[0] - 32, start[1] + 32], + 3 => target = [start[0] + 32, start[1] + 32], + 6 => target = [320, 200], + _ => {} + } + let mut movement = LineMove::new(start[0], start[1], target[0], target[1]); + movement.advance_shot(1); + if !(0..320).contains(&movement.x) || !(0..200).contains(&movement.y) { + return Ok(()); + } + self.projectile(id, movement.x, movement.y, 0, 0, true)?; + self.projectiles.last_mut().unwrap().legacy_enemy = Some(EnemyProjectile { + movement, + kind, + asset, + frames, + frame: 0, + art_frame: 0, + speed, + maximum_speed, + damage, + position: if kind == 6 { + self.rng.next_value() as usize % 16 + } else { + 0 + }, + enemy, + gun, + }); + Ok(()) + } + fn think_enemy_projectiles(&mut self, registry: &Registry) -> Result<()> { + const X: [i32; 16] = [-1, 0, 1, 2, 3, 3, 3, 2, 1, 0, -1, -2, -3, -3, -3, -2]; + const Y: [i32; 16] = [-3, -3, -3, -2, -1, 0, 1, 2, 3, 3, 3, 2, 1, 0, -1, -2]; + let mut retired = Vec::new(); + for p in &mut self.projectiles { + let Some(state) = p.legacy_enemy.as_mut() else { + continue; + }; + p.px = p.x; + p.py = p.y; + p.age += 1; + state.art_frame = state.frame; + state.frame += 1; + if state.kind == 5 { + if let Some(enemy) = self + .enemies + .iter() + .find(|e| e.entity == state.enemy) + .filter(|_| state.frame < state.frames) + { + let legacy = registry.enemies[&enemy.definition].legacy.as_ref().unwrap(); + p.x = enemy.x + legacy.gun_x[state.gun] as i32 - 4; + p.y = enemy.y + legacy.gun_y[state.gun] as i32; + state.movement.ty = 200; + if (p.x - self.player.x - 16).abs() < 16 && p.y < self.player.y + 16 { + state.movement.ty = self.player.y + 16 + self.rng.next_value() % 4 - 2; + damage_player( + &mut self.player, + state.damage, + self.difficulty, + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + ); + } + } else { + retired.push(p.entity); + } + } else { + state.frame %= state.frames; + if state.maximum_speed != 0 { + p.x = state.movement.x; + p.y = state.movement.y; + state.movement.advance_shot(state.speed); + if state.speed < state.maximum_speed { + state.speed += 1; + } + } else { + state.speed -= 1; + if state.speed > 0 { + p.x = state.movement.x + X[state.position]; + p.y = state.movement.y + Y[state.position]; + state.movement.y += 1; + state.position = (state.position + 1) % 16; + } else { + retired.push(p.entity); + } + } + if !(0..320).contains(&p.x) || !(0..200).contains(&p.y) { + retired.push(p.entity); + } + if (p.x - self.player.x - 16).abs() < 16 && (p.y - self.player.y - 16).abs() < 16 { + damage_player( + &mut self.player, + state.damage, + self.difficulty, + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + ); + retired.push(p.entity); + } + } + } + self.projectiles.retain(|p| !retired.contains(&p.entity)); + Ok(()) + } + fn terrain_window(&self, registry: &Registry) -> (usize, i32) { + let mission = ®istry.missions[&self.mission]; + let rows = mission.layout.len() / mission.columns.max(1) as usize; + let initial = rows.saturating_sub(8); + let wraps = if self.scroll <= 56 { + 0 + } else { + 1 + (self.scroll - 57) / 32 + }; + ( + initial.saturating_sub(wraps as usize), + -56 + self.scroll - wraps * 32, + ) + } + fn terrain_damage_neighbors(&mut self, position: usize, damage: i32, registry: &Registry) { + let mission = ®istry.missions[&self.mission]; + let columns = mission.columns.max(1) as usize; + let column = position % columns; + let neighbors = [ + if column > 0 { + position.checked_sub(1) + } else { + None + }, + position.checked_sub(columns), + if column + 1 < columns { + Some(position + 1) + } else { + None + }, + ]; + for position in neighbors.into_iter().flatten() { + if position < mission.layout.len() + && mission.tiles[mission.layout[position]].destroyed.is_some() + && !self.terrain_dead[position] + { + self.terrain_health[position] -= damage; + } + } + } + fn think_legacy_terrain(&mut self, registry: &Registry) { + let mission = ®istry.missions[&self.mission]; + if mission.legacy_map.is_none() || mission.layout.is_empty() { + return; + } + let columns = mission.columns.max(1) as usize; + let (row, y) = self.terrain_window(registry); + let start = row * columns; + let end = (start + 8 * columns).min(mission.layout.len()); + for position in start..end { + if self.terrain_health[position] < 0 && !self.terrain_dead[position] { + let x = 16 + (position % columns) as i32 * 32; + let y = y + ((position - start) / columns) as i32 * 32; + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_GEXPLO", + ); + position_sound( + &mut self.sound_events, + x + 16, + y + 16, + self.player.x + 16, + self.player.y + 16, + ); + self.terrain_damage_neighbors(position, 5, registry); + self.player.credits = self + .player + .credits + .saturating_add(mission.tiles[mission.layout[position]].reward); + self.terrain_delays.push(TerrainDelay { + position, + frames: 10, + }); + self.effects.push(Effect { + x: x + 16, + y: y + 16, + age: 0, + }); + // TILE_Explode changes its collision item immediately. Artwork waits + // for the delayed explosion and its second chain-damage pass. + self.terrain_dead[position] = true; + } + } + let delays = std::mem::take(&mut self.terrain_delays); + for mut delay in delays { + if delay.position.saturating_sub(start) > 8 * columns { + continue; + } + if delay.frames < 0 { + self.rng.next_value(); // Ground sparkle horizontal offset. + self.terrain_damage_neighbors(delay.position, 20, registry); + self.terrain_settled[delay.position] = true; + } else { + delay.frames -= 1; + self.terrain_delays.push(delay); + } + } + } + fn think_legacy_projectiles(&mut self, registry: &Registry) -> Result<()> { + let mut retired = Vec::new(); + let libs = crate::legacy_tables::weapons(); + for n in 0..self.projectiles.len() { + let mut p = self.projectiles[n].clone(); + let Some(mut state) = p.legacy.take() else { + continue; + }; + if p.hostile { + continue; + } + let weapon = ®istry.weapons[&p.weapon]; + let Some(lib) = libs.iter().find(|l| Some(l.index) == weapon.legacy) else { + continue; + }; + p.px = p.x; + p.py = p.y; + p.age += 1; + state.art_frame = state.frame; + if lib.beam == 1 && p.age > 1 { + retired.push(p.entity); + continue; + } + let (half_width, half_height) = weapon + .art + .as_ref() + .map(|a| (a.logical_width as i32 / 2, a.logical_height as i32 / 2)) + .unwrap_or((0, 0)); + p.x = state.movement.x - if lib.beam == 1 { 0 } else { half_width }; + p.y = state.movement.y + - if lib.beam == 0 && lib.moving { + half_height + } else { + 0 + }; + // The original S_BEAM damage pass tests the uncorrected launch + // column, then applies player-follow offsets to presentation. + if lib.beam == 2 { + for enemy in &mut self.enemies { + if p.x > enemy.x + && p.x < enemy.x + enemy.width - 1 + && enemy.y < self.player.y + 16 + && enemy.y > -30 + { + enemy.health -= weapon.damage; + if enemy.health != -1 { + state.movement.ty = enemy.y + enemy.height / 2; + break; + } + } + } + } + if lib.follow_x { + p.x += self.player.x + 16 - state.start[0]; + } + if lib.follow_y { + p.y += self.player.y + 16 - state.start[1]; + } + let mut skip_collision = false; + if lib.moving && (p.y + 16 < 0 || p.x < 0 || p.x > 320 || p.y > 200) { + state.movement.done = true; + skip_collision = true; + } + if !skip_collision && !state.delay { + if state.speed < lib.maxspeed { + state.speed += 1; + } + state.frame += 1; + if state.frame >= lib.frames { + if lib.moving { + state.frame = lib.startframe; + } else { + state.movement.done = true; + skip_collision = true; + } + } + } + if state.hit { + state.movement.done = true; + skip_collision = true; + } + // A plotted shot tests its endpoint before retiring, even if MoveSobj + // marked it done in the preceding step. + if !skip_collision && !lib.effect { + let enemy = self + .enemies + .iter_mut() + .filter(|e| visible(e)) + .take(30) + .find(|e| { + let ground = registry.enemies[&e.definition].ground; + contains(e, p.x, p.y) + && match lib.target { + 1 => !ground, + 2 | 4 => ground, + _ => true, + } + }); + if let Some(enemy) = enemy { + let damage = if lib.target == 4 { 5 } else { weapon.damage }; + enemy.health -= damage; + if self.difficulty == 0 && matches!(lib.target, 1 | 2) { + enemy.health -= damage; + } + state.hit = true; + if matches!(lib.target, 0 | 1 | 3) { + self.rng.next_value(); + } + let entity = enemy.entity; + let enemy_id = enemy.definition.clone(); + let health = enemy.health; + self.event(enemy_id,"on_hit",serde_json::json!({"entity":entity,"projectile":p.entity,"weapon":p.weapon,"damage":damage,"x":p.x,"y":p.y,"health":health})); + self.event(p.weapon.clone(),"on_hit",serde_json::json!({"entity":entity,"projectile":p.entity,"damage":damage,"x":p.x,"y":p.y})); + } else if matches!(lib.target, 0 | 2 | 4) { + let mission = ®istry.missions[&self.mission]; + let col = (p.x - 16).div_euclid(32); + let row = (p.y + + mission.layout.len() as i32 / mission.columns.max(1) as i32 * 32 + - 200 + - self.scroll) + .div_euclid(32); + if col >= 0 && col < mission.columns as i32 && row >= 0 { + let pos = row as usize * mission.columns as usize + col as usize; + if pos < self.terrain_health.len() + && mission.tiles[mission.layout[pos]].destroyed.is_some() + && !self.terrain_dead[pos] + { + self.terrain_health[pos] -= weapon.damage; + if lib.target != 4 { + self.rng.next_value(); + } + state.movement.done = true; + } + } + } + } + if state.movement.done { + if state.delay { + state.delay = false; + state.movement = LineMove::new( + state.movement.x, + state.movement.y, + state.movement.x + self.rng.next_value() % 32 - 16, + 0, + ); + } else if lib.index == 11 { + for enemy in &mut self.enemies { + enemy.health -= weapon.damage; + } + for (health, dead) in self.terrain_health.iter_mut().zip(&self.terrain_dead) { + if !dead { + *health -= weapon.damage; + } + } + retired.extend( + self.projectiles + .iter() + .filter(|p| p.hostile) + .map(|p| p.entity), + ); + retired.push(p.entity); + continue; + } else if lib.index != 5 { + retired.push(p.entity); + continue; + } + } + if lib.moving { + if lib.plot { + state.movement.advance_shot(state.speed); + } else { + state.movement.y -= state.speed; + if state.movement.y < 0 { + state.movement.done = true; + state.hit = true; + } + } + } + p.legacy = Some(state); + self.projectiles[n] = p; + } + self.projectiles.retain(|p| !retired.contains(&p.entity)); + Ok(()) + } + fn fire_legacy( + &mut self, + id: &ContentId, + lib: &crate::legacy_tables::LegacyWeapon, + registry: &Registry, + ) -> Result<()> { + use crate::legacy_tables::{O_GUN1, O_GUN2, O_GUN3}; + if self + .projectiles + .iter() + .filter(|p| !p.hostile && p.legacy.is_some()) + .count() + >= 70 + { + return Ok(()); + } + let center = [self.player.x + 16, self.player.y + 16]; + let bank = self.player.bank.clamp(0, 6) as usize; + let mut start = center; + let mut offsets = vec![0]; + let mut target = [center[0], 0]; + let mut initial_frame = None; + match lib.index { + 0 => { + self.player_flash = true; + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_GUN", + ); + offsets = vec![O_GUN1[bank], -O_GUN1[bank] - 1]; + } + 1 => play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_GUN", + ), + 2 => { + self.player_flash = true; + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_GUN", + ); + offsets = vec![O_GUN3[bank], -O_GUN3[bank]]; + } + 3 => { + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_MISSLE", + ); + offsets = vec![0, 0]; + } + 4 | 5 => { + let candidates: Vec<_> = self + .enemies + .iter() + .enumerate() + .filter(|(_, e)| { + visible(e) && (lib.index == 4 || !registry.enemies[&e.definition].ground) + }) + .map(|(n, _)| n) + .collect(); + if candidates.is_empty() { + if lib.index == 5 { + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_NOSHOOT", + ); + } + return Ok(()); + } + let pos = candidates[self.rng.next_value() as usize % candidates.len()]; + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + if lib.index == 5 { + "FX_TURRET" + } else { + "FX_GUN" + }, + ); + if lib.index == 4 { + initial_frame = Some(self.rng.next_value() as u32 % lib.frames); + } + let enemy = &mut self.enemies[pos]; + if lib.index == 4 { + target = [ + self.rng.next_value() % enemy.width + enemy.x - 1, + self.rng.next_value() % enemy.height + enemy.height / 2 + enemy.y - 1, + ]; + } else { + enemy.health -= lib.damage; + start = [ + self.rng.next_value() % enemy.width + enemy.movement.x - 1, + self.rng.next_value() % enemy.height + enemy.movement.y - 1, + ]; + target = center; + } + } + 6..=8 => { + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + if lib.index == 6 { + "FX_GUN" + } else { + "FX_MISSLE" + }, + ); + offsets = vec![O_GUN2[bank], -O_GUN2[bank]]; + } + 9 => play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_MISSLE", + ), + 10 => { + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_GUN", + ); + start[0] -= 4; + } + 11 => { + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_GUN", + ); + target = [160, 75]; + } + 12 => play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_PULSE", + ), + 13 => { + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_LASER", + ); + offsets = vec![O_GUN3[bank], -O_GUN3[bank]]; + target[1] = -24; + } + 14 => { + play_legacy_sound( + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + "FX_LASER", + ); + start[1] -= 24; + target[1] = -24; + } + _ => {} + } + for (shot_number, offset) in offsets.into_iter().enumerate() { + if self + .projectiles + .iter() + .filter(|p| !p.hostile && p.legacy.is_some()) + .count() + >= 70 + { + break; + } + let x = start[0] + offset; + let y = start[1]; + let frame = if lib.index <= 1 { + self.rng.next_value() as u32 % lib.frames.max(1) + } else { + initial_frame.unwrap_or(0) + }; + let mut target = target; + if lib.index == 3 { + target = [ + x + if shot_number == 0 { + self.rng.next_value() % 16 + 10 + } else { + -self.rng.next_value() % 16 - 10 + }, + y + 5, + ]; + } else if lib.index != 4 && lib.index != 5 && lib.index != 11 { + target[0] = x; + } + self.projectile(id, x, y, 0, -lib.speed, false)?; + self.projectiles.last_mut().unwrap().legacy = Some(LegacyProjectile { + movement: LineMove::new(x, y, target[0], target[1]), + speed: lib.speed, + frame, + art_frame: frame, + delay: lib.delay, + hit: false, + start: center, + }); + } + self.event( + id.clone(), + "on_fire", + serde_json::json!({"entity":0,"hostile":false,"x":center[0],"y":center[1],"tick":self.tick}), + ); + Ok(()) + } + fn dispatch(&mut self, registry: &Registry, scripts: &mut ScriptRuntime) -> Result<()> { + let mut processed = 0usize; + while !self.events.is_empty() { + let events = std::mem::take(&mut self.events); + processed += events.len(); + ensure!( + processed <= 8192, + "too many cascading script events in one tick" + ); + for event in events { + let script = if matches!(event.hook, "on_use" | "on_pickup") { + registry + .items + .get(&event.content) + .and_then(|v| v.script.as_ref()) + } else { + registry + .weapons + .get(&event.content) + .and_then(|v| v.script.as_ref()) + .or_else(|| { + registry + .enemies + .get(&event.content) + .and_then(|v| v.script.as_ref()) + }) + .or_else(|| { + registry + .missions + .get(&event.content) + .and_then(|v| v.script.as_ref()) + }) + .or_else(|| { + registry + .items + .get(&event.content) + .and_then(|v| v.script.as_ref()) + }) + }; + if let Some(path) = script { + let owner = ®istry.owners[&event.content]; + let mut e = event.event; + e["entities"] = serde_json::to_value(&self.enemies)?; + e["player"] = serde_json::to_value(&self.player)?; + e["objectives"] = serde_json::to_value(&self.objectives)?; + e["projectiles"] = serde_json::to_value(&self.projectiles)?; + e["pickups"] = serde_json::to_value(&self.pickups)?; + if e.get("tick").is_none() { + e["tick"] = self.tick.into(); + } + let commands = scripts.invoke(owner, path, event.hook, &e, self.rng.seed)?; + self.apply_commands(&commands, registry)?; + } + } + } + Ok(()) + } + pub fn apply_commands(&mut self, commands: &[Command], registry: &Registry) -> Result<()> { + let mut candidate = self.clone(); + for command in commands { + candidate.command(command, registry)?; + } + *self = candidate; + Ok(()) + } + fn command(&mut self, c: &Command, registry: &Registry) -> Result<()> { + match c { + Command::Spawn { enemy, x, y } => { + ensure!( + x.unsigned_abs() <= 32768 && y.unsigned_abs() <= 32768, + "spawn position exceeds world bounds" + ); + self.spawn(&ContentId::new(enemy)?, *x, *y, registry)?; + } + Command::Projectile { + weapon, + x, + y, + vx, + vy, + hostile, + } => { + let id = ContentId::new(weapon)?; + ensure!( + registry.weapons.contains_key(&id) + && vx.unsigned_abs() <= 128 + && vy.unsigned_abs() <= 128 + && x.unsigned_abs() <= 32768 + && y.unsigned_abs() <= 32768, + "invalid projectile command" + ); + self.projectile(&id, *x, *y, *vx, *vy, *hostile)?; + } + Command::Damage { entity, amount } => { + ensure!((0..=100000).contains(amount), "invalid damage"); + if *entity == 0 { + damage_player( + &mut self.player, + *amount, + self.difficulty, + &mut self.rng, + &mut self.sounds, + &mut self.sound_events, + ); + } else { + let e = self + .enemies + .iter_mut() + .find(|e| e.entity == *entity) + .context("damage target does not exist")?; + e.health -= amount; + let definition = e.definition.clone(); + let health = e.health; + self.event(definition,"on_hit",serde_json::json!({"entity":entity,"damage":amount,"health":health,"scripted":true,"tick":self.tick})); + } + } + Command::Despawn { entity } => { + ensure!( + self.enemies.iter().any(|e| e.entity == *entity) + || self.projectiles.iter().any(|e| e.entity == *entity), + "despawn target does not exist" + ); + self.enemies.retain(|e| e.entity != *entity); + self.projectiles.retain(|e| e.entity != *entity); + } + Command::Move { entity, x, y } => { + ensure!( + x.unsigned_abs() <= 32768 && y.unsigned_abs() <= 32768, + "invalid position" + ); + let e = self + .enemies + .iter_mut() + .find(|e| e.entity == *entity) + .context("move target does not exist")?; + let dx = *x - e.x; + let dy = *y - e.y; + e.x = *x; + e.y = *y; + e.sx += dx; + e.sy += dy; + e.movement = LineMove::new(*x, *y, e.movement.tx + dx, e.movement.ty + dy); + } + Command::Velocity { entity, vx, vy } => { + ensure!( + vx.unsigned_abs() <= 128 && vy.unsigned_abs() <= 128, + "invalid velocity" + ); + let e = self + .enemies + .iter_mut() + .find(|e| e.entity == *entity) + .context("velocity target does not exist")?; + e.vx = *vx; + e.vy = *vy; + } + Command::GiveItem { item, count } => { + let id = ContentId::new(item)?; + let def = registry.items.get(&id).context("unknown item")?; + ensure!( + self.player.inventory.contains_key(&id) || self.player.inventory.len() < 20, + "inventory capacity exceeded" + ); + let amount = self.player.inventory.entry(id).or_default(); + *amount = amount.saturating_add(*count).min(def.max_count); + } + Command::ConsumeItem { item, count } => { + let amount = self + .player + .inventory + .get_mut(&ContentId::new(item)?) + .context("item is not owned")?; + ensure!(*amount >= *count, "insufficient item quantity"); + *amount -= count; + } + Command::Credits { amount } => { + self.player.credits = self.player.credits.saturating_add_signed(*amount); + } + Command::Shield { amount } => { + ensure!(amount.unsigned_abs() <= 100000, "invalid shield adjustment"); + self.player.shield = (self.player.shield + amount).clamp(0, 100); + } + Command::Effect { x, y } => { + ensure!(self.effects.len() < 4096, "too many effects"); + self.effects.push(Effect { + x: *x, + y: *y, + age: 0, + }); + } + Command::Sound { asset } => { + self.sounds.push(*asset); + self.sound_events.push(SoundEvent { + asset: *asset, + pan: 127, + pitch: 128, + volume: 127, + priority: 1, + }); + } + Command::Objective { key, value } => { + ensure!( + key.len() <= 128 + && (self.objectives.contains_key(key) || self.objectives.len() < 1024), + "invalid objective key" + ); + self.objectives.insert(key.clone(), *value); + } + Command::PlaySound { sound } => { + let id = ContentId::new(sound)?; + ensure!( + registry.sounds.contains_key(&id), + "sound {id} is unavailable" + ); + ensure!(self.mod_sounds.len() < 1024, "too many sounds in one tick"); + self.mod_sounds.push(id); + } + Command::Complete => { + if self.outcome == Outcome::Playing { + self.outcome = Outcome::Complete; + self.event( + self.mission.clone(), + "on_mission_end", + serde_json::json!({"success":true,"tick":self.tick}), + ); + } + } + Command::Fail => { + if self.outcome == Outcome::Playing { + self.outcome = Outcome::Failed; + self.event( + self.mission.clone(), + "on_mission_end", + serde_json::json!({"success":false,"tick":self.tick}), + ); + } + } + } + Ok(()) + } + pub fn digest(&self) -> String { + use sha2::{Digest, Sha256}; + format!( + "{:x}", + Sha256::digest(serde_json::to_vec(self).expect("world serialization")) + ) + } + pub fn projectile_asset(p: &Projectile, registry: &Registry) -> Option { + p.legacy_enemy.as_ref().map(|s| s.asset).or_else(|| { + registry.weapons[&p.weapon] + .art + .as_ref() + .and_then(|a| a.asset) + }) + } + pub fn reference_state(&self, registry: &Registry) -> serde_json::Value { + serde_json::json!({"tick":self.tick,"rng":self.rng.seed,"player":[self.player.x,self.player.y,self.player.bank,self.player.shield,self.player.super_shield,self.player.credits],"enemies":self.enemies.iter().map(|e|serde_json::json!([registry.enemies[&e.definition].art.as_ref().and_then(|a|a.asset).unwrap_or(0),e.x,e.y,e.health,e.frame,e.movement.x,e.movement.y])).collect::>(),"projectiles":self.projectiles.iter().filter(|p|p.hostile).chain(self.projectiles.iter().filter(|p|!p.hostile)).map(|p|serde_json::json!([Self::projectile_asset(p,registry).map(i64::from).unwrap_or(-1),p.x,p.y,p.hostile as u32])).collect::>()}) + } +} +fn update_legacy_animation(enemy: &mut Enemy, lib: &crate::assets::LegacyEnemy) { + let f = &lib.fields; + enemy.art_frame = enemy.frame; + if f[7] > 1 { + if enemy.frame_timer < 1 { + enemy.frame_timer = f[6]; + if enemy.animation_on { + enemy.frame += 1; + if enemy.frame >= enemy.animation_frames { + enemy.frame = enemy.frame.saturating_sub(f[9].max(0) as u32); + match f[10] { + 1 => { + enemy.animation_on = false; + enemy.shoot_on = true; + } + 2 => match enemy.multi { + 1 => { + enemy.animation_frames = f[7].max(1) as u32; + enemy.multi = 2; + } + 2 => enemy.shoot_on = true, + _ => {} + }, + _ => {} + } + } + } + } else { + enemy.frame_timer -= 1; + } + if enemy.countdown < 1 { + match f[10] { + 0 => enemy.shoot_on = true, + 1 => enemy.animation_on = true, + 2 if enemy.multi == 0 => enemy.multi = 1, + _ => {} + } + } else { + enemy.countdown -= f[18]; + } + } else if enemy.countdown < 1 { + enemy.countdown = -1; + enemy.shoot_on = true; + } else { + enemy.countdown -= f[18]; + } +} +fn visible(e: &Enemy) -> bool { + e.y + e.height > 0 && e.y < 200 && e.x + e.width > 0 && e.x < 320 +} +fn play_legacy_sound( + rng: &mut LegacyRng, + sounds: &mut Vec, + events: &mut Vec, + name: &str, +) { + if let Some(sound) = crate::legacy_tables::sounds() + .into_iter() + .find(|s| s.name == name) + { + let pitch = sound.pitch + + if sound.random { + rng.next_value() % 40 - 20 + } else { + 0 + }; + sounds.push(sound.asset); + events.push(SoundEvent { + asset: sound.asset, + pan: 127, + pitch, + volume: sound.volume, + priority: sound.priority, + }); + } +} +fn position_sound(events: &mut [SoundEvent], x: i32, y: i32, player_x: i32, player_y: i32) { + if let Some(event) = events.last_mut() { + let dx = x - player_x; + let dy = y - player_y; + event.pan = (dx + 127).clamp(1, 255); + let dx = dx.abs(); + let dy = dy.abs(); + let distance = dx + dy - dx.min(dy) / 2; + let volume = if distance < 40 { + 127 + } else if distance > 500 { + 1 + } else { + 127 - (distance - 40) * 127 / 460 + }; + event.volume = event.volume * volume / 127; + } +} +fn accelerate(v: i32, direction: i32, cap: i32) -> i32 { + match direction.signum() { + -1 => (if v >= 0 { -1 } else { v } - 1).max(-cap), + 1 => (if v <= 0 { 1 } else { v } + 1).min(cap), + _ => v / 2, + } +} +fn damage_player( + p: &mut Player, + damage: i32, + difficulty: u32, + rng: &mut LegacyRng, + sounds: &mut Vec, + events: &mut Vec, +) { + let damage = if difficulty == 0 && damage > 1 { + damage >> 1 + } else { + damage + }; + let super_id = ContentId::from("base:super_shield"); + if p.inventory.contains_key(&super_id) { + // Original super shields absorb the whole hit, even when it exhausts them. + // A zero-charge shield remains equipped until another hit removes it. + p.super_shield -= damage; + play_legacy_sound(rng, sounds, events, "FX_SHIT"); + if p.super_shield < 0 { + p.super_shield = 0; + p.inventory.remove(&super_id); + } + } else { + p.shield = (p.shield - damage).max(0); + play_legacy_sound(rng, sounds, events, "FX_HIT"); + } +} +fn target_matches(t: &Target, ground: bool) -> bool { + match t { + Target::All => true, + Target::Air => !ground, + Target::Ground => ground, + } +} +fn contains(e: &Enemy, x: i32, y: i32) -> bool { + x > e.x && x < e.x + e.width - 1 && y > e.y && y < e.y + e.height - 1 +} +/// Accumulate exact rational time without rounding the original 3/70-second tick. +#[derive(Default)] +pub struct Clock { + units: u128, +} +impl Clock { + pub fn advance(&mut self, nanos: u64) -> usize { + self.units += nanos as u128 * 70; + let steps = self.units / 3_000_000_000; + self.units %= 3_000_000_000; + steps as usize + } + pub fn alpha(&self) -> f32 { + self.units as f32 / 3_000_000_000.0 + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn rng_wraps_like_legacy() { + let mut r = LegacyRng::new(1); + assert_eq!( + (0..5).map(|_| r.next_value()).collect::>(), + vec![16838, 5758, 10113, 17515, 31051] + ); + } + #[test] + fn clock_is_independent_of_frame_rate() { + for hz in [30, 60, 144] { + let mut c = Clock::default(); + let mut ticks = 0; + let mut previous = 0; + for frame in 1..=hz * 3 { + let now = frame as u64 * 1_000_000_000 / hz as u64; + ticks += c.advance(now - previous); + previous = now; + } + assert_eq!(ticks, 70); + } + } + #[test] + fn line_reaches_target() { + let mut m = LineMove::new(0, 0, 10, 7); + for _ in 0..20 { + m.advance(1); + } + assert_eq!((m.x, m.y), (10, 7)); + } +} diff --git a/src/sound.rs b/src/sound.rs new file mode 100644 index 00000000..4c4c0719 --- /dev/null +++ b/src/sound.rs @@ -0,0 +1,96 @@ +//! Checked package-local PCM WAV loading, independent of SDL2. +//! RIFF chunks are little-endian and padded to a two-byte boundary. +use crate::audio::DigitalSample; +use anyhow::{Context, Result, ensure}; + +pub fn decode(bytes: &[u8]) -> Result { + ensure!(bytes.len() <= 8 * 1024 * 1024, "sound exceeds 8 MiB"); + if !bytes.starts_with(b"RIFF") { + return DigitalSample::decode(bytes); + } + let u32_at = |offset| -> Result { + Ok(u32::from_le_bytes( + bytes + .get(offset..offset + 4) + .context("truncated WAV field")? + .try_into()?, + )) + }; + ensure!( + bytes.get(8..12) == Some(b"WAVE") && u32_at(4)? as usize == bytes.len().saturating_sub(8), + "invalid RIFF/WAVE length" + ); + let mut format = None; + let mut audio = None; + let mut offset = 12; + while offset < bytes.len() { + let tag = bytes + .get(offset..offset + 4) + .context("truncated WAV chunk")?; + let length = u32_at(offset + 4)? as usize; + let start = offset + 8; + let end = start + .checked_add(length) + .context("WAV chunk size overflow")?; + let chunk = bytes + .get(start..end) + .context("truncated WAV chunk payload")?; + match tag { + b"fmt " => { + ensure!( + format.is_none() && chunk.len() >= 16, + "duplicate/truncated WAV format" + ); + let u16_at = |n| u16::from_le_bytes([chunk[n], chunk[n + 1]]); + let rate = u32::from_le_bytes(chunk[4..8].try_into()?); + let channels = u16_at(2) as usize; + let bits = u16_at(14) as usize; + ensure!( + u16_at(0) == 1 + && matches!(channels, 1 | 2) + && matches!(bits, 8 | 16) + && (8000..=48000).contains(&rate), + "sound must be 8/16-bit PCM WAV, mono/stereo, 8–48 kHz" + ); + let align = channels * bits / 8; + ensure!( + u16_at(12) as usize == align + && u32::from_le_bytes(chunk[8..12].try_into()?) == rate * align as u32, + "invalid WAV block/byte rate" + ); + format = Some((rate, channels, bits, align)); + } + b"data" => { + ensure!(audio.is_none(), "duplicate WAV data"); + audio = Some(chunk); + } + _ => {} + } + offset = end + .checked_add(length & 1) + .context("WAV padding overflow")?; + ensure!(offset <= bytes.len(), "truncated WAV padding"); + } + let (rate, channels, bits, align) = format.context("WAV has no format")?; + let audio = audio.context("WAV has no audio data")?; + ensure!( + !audio.is_empty() && audio.len() % align == 0 && audio.len() / align <= rate as usize * 30, + "invalid WAV sample count (maximum 30 seconds)" + ); + let data = audio + .chunks_exact(align) + .map(|frame| { + let total: i32 = (0..channels) + .map(|channel| { + if bits == 8 { + (frame[channel] as i32 - 128) * 256 + } else { + i16::from_le_bytes([frame[channel * 2], frame[channel * 2 + 1]]) as i32 + } + }) + .sum(); + ((total / channels as i32) / 256 + 128).clamp(0, 255) as u8 + }) + .collect(); + Ok(DigitalSample { rate, data }) +} diff --git a/tests/audio.rs b/tests/audio.rs new file mode 100644 index 00000000..1724c1ae --- /dev/null +++ b/tests/audio.rs @@ -0,0 +1,390 @@ +use raptor_replica::audio::{DigitalSample, Mixer, MusScore}; +use std::{fs, path::Path, process::Command}; + +fn instruments(double: bool) -> Vec { + let mut bytes = b"#OPL_II#".to_vec(); + for n in 0..175 { + let mut instrument = [0u8; 36]; + instrument[0] = if n == 1 { + 1 + } else if double { + 4 + } else { + 0 + }; + instrument[2] = 128; + instrument[3] = 48; + for part in 0..2 { + let start = 4 + part * 16; + instrument[start..start + 6].copy_from_slice(&[0x21, 0xf2, 0x52, 0, 0, 32]); + instrument[start + 6] = 0; + instrument[start + 7..start + 13].copy_from_slice(&[0x21, 0xf2, 0x52, 0, 0, 0]); + } + bytes.extend(instrument); + } + bytes +} +fn mus(body: &[u8], channels: u16) -> Vec { + let mut bytes = b"MUS\x1a".to_vec(); + bytes.extend((body.len() as u16).to_le_bytes()); + bytes.extend(16u16.to_le_bytes()); + bytes.extend(channels.to_le_bytes()); + bytes.extend([0; 6]); + bytes.extend(body); + bytes +} +fn score() -> Vec { + mus( + &[ + 0x40, 0, 0, 0x90, 188, 100, 10, 0xa0, 144, 5, 0xc0, 3, 90, 5, 0x80, 60, 10, 0x60, + ], + 1, + ) +} +fn sample(data: Vec) -> DigitalSample { + DigitalSample { rate: 11025, data } +} +fn patch(data: &[u8]) -> Vec { + let mut bytes = vec![3, 0]; + bytes.extend(11025u16.to_le_bytes()); + bytes.extend(((data.len() + 32) as u32).to_le_bytes()); + bytes.extend([0xff; 16]); + bytes.extend(data); + bytes.extend([0; 16]); + bytes +} +fn mixer() -> Mixer { + Mixer::new(44100, &instruments(false)).unwrap() +} + +#[test] +fn digital_decoder_excludes_both_padding_regions() { + let decoded = DigitalSample::decode(&patch(&[0, 64, 128, 192, 255])).unwrap(); + assert_eq!(decoded.rate, 11025); + assert_eq!(decoded.data, vec![0, 64, 128, 192, 255]); + assert!(DigitalSample::decode(&patch(&[])).is_err()); +} + +#[test] +fn music_events_start_on_the_first_seventy_hertz_service_tick() { + let mut mixer = mixer(); + mixer.music_volume = 127; + mixer.play(MusScore::decode(&score()).unwrap(), false); + let mut prefix = vec![1; 630 * 2]; + mixer.mix(&mut prefix); + assert!(prefix.iter().all(|n| *n == 0)); + let mut following = vec![0; 3000 * 2]; + mixer.mix(&mut following); + assert!(following.iter().any(|n| *n != 0)); +} + +#[test] +fn fm_and_digital_output_do_not_depend_on_audio_callback_size() { + let table = instruments(true); + let mut whole = Mixer::new(44117, &table).unwrap(); + let mut chunked = Mixer::new(44117, &table).unwrap(); + for m in [&mut whole, &mut chunked] { + m.play_with_fade(MusScore::decode(&score()).unwrap(), true, true); + m.sample( + sample((0..255).cycle().take(5000).collect()), + 37, + 192, + 100, + 1, + ); + } + let mut expected = vec![0; 44117 * 2]; + whole.mix(&mut expected); + let mut actual = vec![0; expected.len()]; + let mut frame = 0; + for count in [1usize, 3, 17, 512, 127].into_iter().cycle() { + let count = count.min(actual.len() / 2 - frame); + chunked.mix(&mut actual[frame * 2..(frame + count) * 2]); + frame += count; + if frame == actual.len() / 2 { + break; + } + } + assert_eq!(actual, expected); +} + +#[test] +fn digital_mixing_uses_the_original_11025_hertz_sample_hold() { + let mut mixer = mixer(); + mixer.fx_volume = 127; + mixer.sample(sample(vec![255, 255]), 128, 128, 127, 1); + let mut out = [0; 24]; + mixer.mix(&mut out); + assert_eq!(&out[..6], &[0; 6]); + assert!(out[6] > 0 && out[7] > 0); + assert_eq!(&out[6..8], &out[8..10]); + assert_eq!(&out[6..8], &out[10..12]); + assert_eq!(&out[6..8], &out[12..14]); + assert_eq!(&out[22..24], &[0, 0]); +} + +#[test] +fn pitch_zero_is_a_valid_quarter_speed_pitch() { + let mut normal = mixer(); + let mut slow = mixer(); + normal.fx_volume = 127; + slow.fx_volume = 127; + normal.sample(sample(vec![255; 8]), 128, 128, 127, 1); + slow.sample(sample(vec![255; 8]), 128, 0, 127, 1); + let mut fast = [0; 100]; + let mut quarter = [0; 100]; + normal.mix(&mut fast); + slow.mix(&mut quarter); + assert!(fast[80..].iter().all(|v| *v == 0)); + assert!(quarter[80..].iter().any(|v| *v > 0)); +} + +#[test] +fn lower_numeric_digital_priority_wins() { + let mut mixer = mixer(); + mixer.fx_volume = 127; + mixer.set_fx_channels(1); + mixer.sample(sample(vec![255; 1000]), 128, 128, 127, 1); + mixer.sample(sample(vec![0; 1000]), 128, 128, 127, 8); + let mut protected = [0; 64]; + mixer.mix(&mut protected); + assert!(protected[8..].iter().all(|v| *v > 0)); + mixer.sample(sample(vec![0; 1000]), 128, 128, 127, 0); + let mut replaced = [0; 64]; + mixer.mix(&mut replaced); + assert!(replaced[8..].iter().all(|v| *v < 0)); +} + +#[test] +fn digital_voices_clip_together_before_being_added_to_fm() { + let mut mixer = mixer(); + mixer.fx_volume = 127; + mixer.set_fx_channels(8); + for _ in 0..8 { + mixer.sample(sample(vec![255; 100]), 128, 128, 127, 1); + } + let mut out = [0; 64]; + mixer.mix(&mut out); + assert_eq!(out[20], 127 * 128); + assert_eq!(out[21], 127 * 128); +} + +#[test] +fn malformed_scores_controller_values_and_missing_end_events_are_rejected() { + for body in [ + vec![0x90, 188], + vec![0x90, 188, 200, 1, 0x60], + vec![0xc0, 3, 255, 1, 0x60], + vec![0x30, 9, 0x60], + vec![0x90, 188, 127, 1], + ] { + assert!(MusScore::decode(&mus(&body, 1)).is_err()); + } + assert!(MusScore::decode(&mus(&[0x60], 16)).is_err()); +} + +#[test] +fn a_zero_duration_loop_and_an_odd_output_slice_terminate_cleanly() { + let mut mixer = mixer(); + mixer.play(MusScore::decode(&mus(&[0x60], 1)).unwrap(), true); + let mut out = [99; 2001]; + mixer.mix(&mut out); + assert_eq!(out[2000], 0); +} + +#[test] +#[ignore = "requires the original untracked catalog"] +fn original_music_and_sound_assets_decode_locally() { + use raptor_replica::assets::Catalog; + let root = std::env::var_os("RAPTOR_TEST_DATA") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("data")); + let catalog = Catalog::open(root).unwrap(); + let mut music = 0; + let mut sounds = 0; + for entry in catalog.entries.values() { + let bytes = catalog.read(entry.id).unwrap(); + if bytes.starts_with(b"MUS\x1a") { + MusScore::decode(&bytes).unwrap(); + music += 1; + } + if bytes.get(..4) == Some(&[3, 0, 0x11, 0x2b]) { + DigitalSample::decode(&bytes).unwrap(); + sounds += 1; + } + } + assert_eq!(music, 16); + assert_eq!(sounds, 26, "digital samples"); + Mixer::new(44100, &catalog.named("GENMIDI_OP2").unwrap()).unwrap(); +} + +const NATIVE_REFERENCE: &str = r#" +#include +#include +#include +#include +#include +#include +#include "SDL.h" +#include "musapi.h" +#include "i_oplmusic.h" +#include "dspapi.h" +#include "cards.h" +int fx_freq=44100, gsshack=0, gssrate=0, sys_midi=0; +musdevice_t mus_device_alsa={}, mus_device_tsf={}; +void SND_Lock(){} void SND_Unlock(){} void GSS_Service(){} void GSS_Poll(){} +extern "C" Uint32 SDL_GetTicks(){return 0;} +std::vector read(const char *path){std::ifstream in(path,std::ios::binary);return {std::istreambuf_iterator(in),{}};} +int main(int argc,char **argv){ + if(argc!=9)return 2; + auto gen=read(argv[1]),score=read(argv[2]),patch=read(argv[3]); + int frames=std::atoi(argv[4]),mode=std::atoi(argv[5]),fade=std::atoi(argv[6]),loop=std::atoi(argv[7]); + std::vector out(frames*2,0); + if(mode!=1){LoadInstrumentTable(gen.data());MUS_Init(M_ADLIB,0);MUS_SetVolume(127);MUS_PlaySong(score.data(),loop,fade);} + if(mode!=0){DSP_Init(8,11025);DSP_StartPatch((dsp_t*)patch.data(),37,192,85,1);} + if(mode!=1)MUS_Mix(out.data(),frames); + if(mode!=0)DSP_Mix(out.data(),frames); + FILE *file=fopen(argv[8],"wb");if(!file)return 3; + fwrite(out.data(),sizeof(int16_t),out.size(),file);fclose(file);return 0; +} +"#; + +#[test] +#[ignore = "requires g++ and SDL2 development headers; synthetic assets only"] +fn rust_fm_mus_and_digital_pcm_match_the_retained_native_reference() { + let temp = tempfile::tempdir().unwrap(); + let binary = compile_reference(temp.path()); + let patch_data: Vec<_> = (0..255).cycle().take(2000).collect(); + let patch_path = temp.path().join("patch.bin"); + fs::write(&patch_path, patch(&patch_data)).unwrap(); + for (double, mode, fade, looping) in [ + (false, 0, false, false), + (true, 0, false, false), + (false, 1, false, false), + (true, 2, true, true), + ] { + let bank = instruments(double); + let song = score(); + let frames = 44100; + let gen_path = temp.path().join("genmidi.bin"); + fs::write(&gen_path, &bank).unwrap(); + let score_path = temp.path().join("score.bin"); + fs::write(&score_path, &song).unwrap(); + let output = temp.path().join("reference.pcm"); + let status = Command::new(&binary) + .arg(&gen_path) + .arg(&score_path) + .arg(&patch_path) + .arg(frames.to_string()) + .arg(mode.to_string()) + .arg(i32::from(fade).to_string()) + .arg(i32::from(looping).to_string()) + .arg(&output) + .status() + .unwrap(); + assert!(status.success()); + let expected = fs::read(output).unwrap(); + let mut mixer = Mixer::new(44100, &bank).unwrap(); + mixer.music_volume = 127; + mixer.fx_volume = 127; + mixer.set_fx_channels(8); + if mode != 1 { + mixer.play_with_fade(MusScore::decode(&song).unwrap(), looping, fade); + } + if mode != 0 { + mixer.sample(sample(patch_data.clone()), 37, 192, 85, 1); + } + let mut out = vec![0; frames * 2]; + mixer.mix(&mut out); + let actual: Vec<_> = out.iter().flat_map(|v| v.to_le_bytes()).collect(); + if let Some(index) = actual + .chunks_exact(2) + .zip(expected.chunks_exact(2)) + .position(|(a, b)| a != b) + { + let want = i16::from_le_bytes(expected[index * 2..index * 2 + 2].try_into().unwrap()); + panic!( + "PCM mismatch double={double} mode={mode} fade={fade} loop={looping}: frame={} channel={} got={} expected={want}", + index / 2, + index % 2, + out[index] + ); + } + assert_eq!(actual.len(), expected.len()); + } +} + +fn compile_reference(directory: &Path) -> std::path::PathBuf { + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let source = directory.join("reference.cpp"); + fs::write(&source, NATIVE_REFERENCE).unwrap(); + let binary = directory.join("reference"); + let mut compile = Command::new("g++"); + compile + .args(["-std=c++17", "-O2"]) + .arg("-I") + .arg(root.join("raptor/src")); + compile.arg("-I").arg("/usr/include/SDL2"); + if let Some(home) = std::env::var_os("HOME") { + compile + .arg("-I") + .arg(Path::new(&home).join(".local/include/SDL2")); + } + compile.arg(&source); + for path in ["i_oplmusic.cpp", "opl3.cpp", "musapi.cpp", "dspapi.cpp"] { + compile.arg(root.join("raptor/src").join(path)); + } + let result = compile.arg("-o").arg(&binary).output().unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + binary +} + +#[test] +#[ignore = "requires original untracked music assets, g++ and SDL2 headers"] +fn original_intro_pcm_matches_the_retained_native_reference() { + use raptor_replica::assets::Catalog; + let temp = tempfile::tempdir().unwrap(); + let root = std::env::var_os("RAPTOR_TEST_DATA") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("data")); + let catalog = Catalog::open(root).unwrap(); + let bank = catalog.named("GENMIDI_OP2").unwrap(); + let song = catalog.named("RINTRO_MUS").unwrap(); + let binary = compile_reference(temp.path()); + fs::write(temp.path().join("genmidi.bin"), &bank).unwrap(); + fs::write(temp.path().join("score.bin"), &song).unwrap(); + fs::write(temp.path().join("patch.bin"), patch(&[128; 33])).unwrap(); + let frames = 44100 * 4; + let output = temp.path().join("reference.pcm"); + let status = Command::new(binary) + .arg(temp.path().join("genmidi.bin")) + .arg(temp.path().join("score.bin")) + .arg(temp.path().join("patch.bin")) + .arg(frames.to_string()) + .args(["0", "1", "1"]) + .arg(&output) + .status() + .unwrap(); + assert!(status.success()); + let expected = fs::read(output).unwrap(); + let mut mixer = Mixer::new(44100, &bank).unwrap(); + mixer.music_volume = 127; + mixer.play_with_fade(MusScore::decode(&song).unwrap(), true, true); + let mut actual = vec![0i16; frames * 2]; + mixer.mix(&mut actual); + for (index, (got, bytes)) in actual.iter().zip(expected.chunks_exact(2)).enumerate() { + let want = i16::from_le_bytes(bytes.try_into().unwrap()); + assert_eq!( + *got, + want, + "original intro frame {} channel {}", + index / 2, + index % 2 + ); + } + assert_eq!(actual.len() * 2, expected.len()); +} diff --git a/tests/core.rs b/tests/core.rs new file mode 100644 index 00000000..c1861b03 --- /dev/null +++ b/tests/core.rs @@ -0,0 +1,269 @@ +use raptor_replica::{ + assets::{Catalog, Sprite, TRANSPARENT, contained, i16_at, i32_at}, + audio::{DigitalSample, Mixer, MusScore}, + content::{ContentPack, Registry}, + persistence::{Config, Pilot}, + render::upscale, +}; + +fn pilot_registry() -> Registry { + let missions: Vec<_> = (1..=3).flat_map(|s| (1..=9).map(move |w| serde_json::json!({ + "id":format!("base:sector_{s}_wave_{w}"),"name":"Synthetic wave","duration":100,"legacy_map":100+s*9+w + }))).collect(); + let pack: ContentPack = serde_json::from_value(serde_json::json!({ + "items":[ + {"id":"base:forward_guns","name":"Forward Guns","price":12000,"legacy":0}, + {"id":"base:energy","name":"Energy","price":10000,"max_count":100,"initial_count":25,"legacy":16} + ],"missions":missions + })).unwrap(); + let mut registry = Registry::default(); + registry.apply(pack, "base").unwrap(); + registry.validate().unwrap(); + registry +} + +#[test] +fn training_graduation_and_sector_cycles_preserve_original_progression() { + let registry = pilot_registry(); + let mut pilot = Pilot { + difficulty: 0, + credits: 900000, + mission: "base:sector_2_wave_4".into(), + ..Pilot::default() + }; + pilot.complete_mission(®istry).unwrap(); + assert_eq!(pilot.mission.0, "base:sector_1_wave_1"); + assert_eq!(pilot.difficulty, 1); + assert_eq!(pilot.credits, 10000); + assert_eq!(pilot.inventory[&"base:energy".into()], 75); + assert!(pilot.legacy_progress.as_ref().unwrap().training_completed); + pilot.mission = "base:sector_3_wave_9".into(); + pilot.difficulty = 2; + pilot.complete_mission(®istry).unwrap(); + assert_eq!(pilot.mission.0, "base:sector_1_wave_1"); + assert_eq!(pilot.legacy_progress.as_ref().unwrap().difficulties[2], 3); + assert_eq!(pilot.difficulty, 1); + pilot.mission = "base:sector_1_wave_2".into(); + pilot.complete_mission(®istry).unwrap(); + assert_eq!(pilot.mission.0, "base:sector_1_wave_3"); +} + +#[test] +fn legacy_save_import_retains_metadata_without_modifying_source() { + fn encrypt(bytes: &[u8]) -> Vec { + let key = b"CASTLE"; + let mut index = 25 % key.len(); + let mut previous = key[index]; + bytes + .iter() + .map(|clear| { + let byte = clear.wrapping_add(key[index]).wrapping_add(previous); + previous = byte; + index = (index + 1) % key.len(); + byte + }) + .collect() + } + let mut header = vec![0u8; 88]; + header[..9].copy_from_slice(b"Synthetic"); + header[20..24].copy_from_slice(b"TEST"); + for (offset, value) in [ + (32, 65814i32), + (36, 98765), + (40, -1), + (44, 1), + (48, 3), + (52, 8), + (56, 1), + (60, 2), + (64, 0), + (68, 2), + (72, 1), + (76, 3), + (80, 0), + (84, 1), + ] { + header[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + } + let mut body = vec![0u8; 48]; + for (offset, value) in [(8, 1i32), (12, 0), (32, 71), (36, 16)] { + body[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + } + let bytes = [encrypt(&header), encrypt(&body)].concat(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("CHAR0000.FIL"); + std::fs::write(&path, &bytes).unwrap(); + let registry = pilot_registry(); + let pilot = Pilot::import_legacy(&path, ®istry).unwrap(); + assert_eq!(pilot.callsign, "TEST"); + assert_eq!(pilot.credits, 98765); + assert_eq!(pilot.mission.0, "base:sector_2_wave_9"); + assert_eq!(pilot.inventory[&"base:energy".into()], 71); + assert_eq!(pilot.completed.len(), 12); + let progress = pilot.legacy_progress.as_ref().unwrap(); + assert_eq!(progress.portrait, 65814); + assert_eq!(progress.difficulties, [0, 2, 1, 3]); + assert!(progress.training_completed); + let output = dir.path().join("pilot.json"); + pilot.save(&output).unwrap(); + assert_eq!(Pilot::load(&output, ®istry, &[]).unwrap().credits, 98765); + assert_eq!(std::fs::read(path).unwrap(), bytes); +} + +fn header(kind: i32, width: i32, height: i32) -> Vec { + [kind, 0, 0, width, height] + .into_iter() + .flat_map(i32::to_le_bytes) + .collect() +} + +#[test] +fn raw_pictures_keep_zero_opaque_and_spans_keep_empty_pixels_transparent() { + let mut raw = header(1, 2, 1); + raw.extend([0, 255]); + assert_eq!(Sprite::decode(&raw).unwrap().pixels, [0, 255]); + let mut span = header(0, 3, 2); + span.extend([1i32, 1, 4, 2].into_iter().flat_map(i32::to_le_bytes)); + span.extend([0, 17]); + span.extend([0i32, 0, -1, 0].into_iter().flat_map(i32::to_le_bytes)); + assert_eq!( + Sprite::decode(&span).unwrap().pixels, + [TRANSPARENT, TRANSPARENT, TRANSPARENT, TRANSPARENT, 0, 17] + ); + for n in 0..span.len() { + assert!(Sprite::decode(&span[..n]).is_err()); + } +} + +#[test] +fn malformed_fields_and_spans_fail_without_panicking() { + assert!(i16_at(&[], usize::MAX).is_err()); + assert!(i32_at(&[], usize::MAX).is_err()); + let mut span = header(0, 2, 2); + span.extend([i32::MAX, 0, 0, 2].into_iter().flat_map(i32::to_le_bytes)); + span.extend([1, 2]); + assert!(Sprite::decode(&span).is_err()); + assert!(Sprite::decode(&header(1, 4096, 4096)).is_err()); +} + +#[test] +fn scale_kernels_have_published_corner_results() { + let input = Sprite { + width: 3, + height: 3, + pixels: vec![9, 1, 8, 1, 2, 3, 7, 4, 6], + }; + let two = upscale(&input, 2).unwrap(); + let four = upscale(&input, 4).unwrap(); + assert_eq!( + [ + two.pixels[2 * 6 + 2], + two.pixels[2 * 6 + 3], + two.pixels[3 * 6 + 2], + two.pixels[3 * 6 + 3] + ], + [1, 2, 2, 2] + ); + let three = upscale(&input, 3).unwrap(); + let center: Vec<_> = (3..6) + .flat_map(|y| (3..6).map(move |x| y * 9 + x)) + .map(|n| three.pixels[n]) + .collect(); + assert_eq!(center, [1, 1, 2, 1, 2, 2, 2, 2, 2]); + assert_eq!(four, upscale(&two, 2).unwrap()); + assert!(upscale(&input, 5).is_err()); +} + +#[test] +fn catalog_paths_cannot_escape_or_follow_an_external_symlink() { + let root = tempfile::tempdir().unwrap(); + let other = tempfile::tempdir().unwrap(); + std::fs::write(other.path().join("outside"), b"outside").unwrap(); + assert!(contained(root.path(), std::path::Path::new("../outside")).is_err()); + #[cfg(unix)] + { + std::os::unix::fs::symlink(other.path().join("outside"), root.path().join("link")).unwrap(); + assert!(contained(root.path(), std::path::Path::new("link")).is_err()); + } +} + +#[test] +fn importing_settings_preserves_source_and_uses_sdl_key_names() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("SETUP.INI"); + let original = b"[Keyboard]\nFire=29\nFireSp=56\nMegaFire=54\n[Video]\nupscaler=3\n"; + std::fs::write(&path, original).unwrap(); + let config = Config::import_ini(&path).unwrap(); + assert_eq!(config.scale, 3); + assert_eq!(config.bindings["fire"], "Left Ctrl"); + assert_eq!(config.bindings["special"], "Left Alt"); + assert_eq!(std::fs::read(path).unwrap(), original); + #[cfg(feature = "desktop")] + for key in config.bindings.values() { + assert!( + sdl2::keyboard::Scancode::from_name(key).is_some(), + "unknown SDL key {key}" + ); + } +} + +// Original pixels never enter the test fixtures or version control. Set this +// variable only on a machine with the licensed extracted asset catalog. +#[test] +fn original_data_decoders_and_all_campaigns_when_available() { + let Some(data) = std::env::var_os("RAPTOR_TEST_DATA") else { + return; + }; + let catalog = Catalog::open(data).unwrap(); + let registry = Registry::base(&catalog).unwrap(); + registry.validate().unwrap(); + assert_eq!(registry.missions.len(), 27); + assert_eq!(registry.campaigns.len(), 3); + let mut sprites = 0; + for entry in catalog.entries.values() { + let bytes = catalog.read(entry.id).unwrap(); + if bytes.len() >= 20 + && (i32_at(&bytes, 0).ok() == Some(0) + || (i32_at(&bytes, 0).ok() == Some(1) + && i32_at(&bytes, 4).ok() == Some(1) + && i32_at(&bytes, 8).ok() == Some(0))) + && matches!(i32_at(&bytes, 12).ok(), Some(1..=4096)) + && matches!(i32_at(&bytes, 16).ok(), Some(1..=4096)) + { + Sprite::decode(&bytes).unwrap_or_else(|e| panic!("asset {:x}: {e}", entry.id)); + sprites += 1; + } + if bytes.starts_with(b"MUS\x1a") { + MusScore::decode(&bytes).unwrap(); + } + } + assert!( + sprites > 1000, + "format discovery must include unnamed graphics" + ); + for sector in 0..3 { + let pilot = Pilot::demo(sector, ®istry).unwrap(); + pilot.validate(®istry, &[]).unwrap(); + let selected = ®istry.items[pilot.selected.as_ref().unwrap()]; + assert_eq!(selected.legacy, Some([5, 8, 8][sector])); + } + let mut mixer = Mixer::new(44100, &catalog.named("GENMIDI_OP2").unwrap()).unwrap(); + mixer.play( + MusScore::decode(&catalog.named("RAP1_MUS").unwrap()).unwrap(), + false, + ); + let mut output = vec![0i16; 44100 * 2]; + mixer.mix(&mut output); + assert!( + output.iter().any(|v| *v != 0), + "FM playback must produce sound" + ); + let sample = catalog + .entries + .values() + .find_map(|e| DigitalSample::decode(&catalog.read(e.id).ok()?).ok()) + .unwrap(); + mixer.sample(sample, 128, 128, 127, 1); + mixer.mix(&mut output); + assert!(output.iter().any(|v| *v != 0)); +} diff --git a/tests/gameplay.rs b/tests/gameplay.rs new file mode 100644 index 00000000..af262df1 --- /dev/null +++ b/tests/gameplay.rs @@ -0,0 +1,186 @@ +use raptor_replica::{ + content::{ContentId, ContentPack, Registry}, + modding::{Command, ScriptRuntime}, + persistence::Pilot, + simulation::{Input, LineMove, World}, +}; +use serde_json::json; + +fn fixture() -> Registry { + let pack: ContentPack = serde_json::from_value(json!({ + "weapons": [{"id":"base:projectile_forward_guns", "name":"Guns", "damage":1,"speed":8,"cooldown":2,"behavior":"straight","target":"all","legacy":0,"art":{"asset":42,"logical_width":4,"logical_height":8,"frames":4}}], + "items":[ + {"id":"base:forward_guns","name":"Guns","price":0,"weapon":"base:projectile_forward_guns","legacy":0}, + {"id":"base:energy","name":"Shield","price":0,"max_count":100,"legacy":16}, + {"id":"base:super_shield","name":"Super Shield","price":0,"max_count":100,"legacy":15}, + {"id":"base:medkit","name":"Medkit","price":0,"max_count":5,"special":true,"consumable":true,"shield":25,"script":"medkit.rhai"} + ], + "enemies":[{"id":"base:drone","name":"Drone","speed":1,"health":20,"path":[[0,200]]}], + "missions":[{"id":"base:sector_1_wave_1","name":"Synthetic Mission","duration":1000}] + })).unwrap(); + let mut reg = Registry::default(); + reg.apply(pack, "base").unwrap(); + reg.validate().unwrap(); + reg +} + +#[test] +fn original_guns_use_banked_muzzles_and_accelerate_after_position_snapshot() { + let reg = fixture(); + let mut world = World::new(&"base:sector_1_wave_1".into(), &Pilot::default(), ®).unwrap(); + let mut scripts = ScriptRuntime::new(); + world + .step( + Input { + fire: true, + demo_bank: Some(3), + ..Input::default() + }, + ®, + &mut scripts, + ) + .unwrap(); + // Center (160,176), gun offsets +6/-7, sprite half-size (2,4). + assert_eq!( + world + .projectiles + .iter() + .map(|p| (p.x, p.y)) + .collect::>(), + [(164, 172), (151, 172)] + ); + world + .step( + Input { + fire: true, + ..Input::default() + }, + ®, + &mut scripts, + ) + .unwrap(); + assert_eq!(world.projectiles.len(), 2); + assert_eq!(world.projectiles[0].y, 163); // Speed rose from 8 to 9 after the first position. + world + .step( + Input { + fire: true, + ..Input::default() + }, + ®, + &mut scripts, + ) + .unwrap(); + assert_eq!(world.projectiles.len(), 4); + assert_eq!(world.projectiles[0].y, 153); +} + +#[test] +fn enemy_paths_stop_at_endpoint_but_shots_cross_it() { + let mut enemy = LineMove::new(0, 0, 2, 1); + enemy.advance(5); + assert_eq!((enemy.x, enemy.y), (2, 1)); + let mut shot = LineMove::new(0, 0, 2, 1); + shot.advance_shot(5); + assert_eq!((shot.x, shot.y), (5, 3)); + assert!(shot.done); +} + +#[test] +fn mission_transition_preserves_remaining_super_shield() { + let reg = fixture(); + let mut pilot = Pilot::default(); + pilot.inventory.insert("base:super_shield".into(), 31); + let mut world = World::new(&pilot.mission, &pilot, ®).unwrap(); + assert_eq!(world.player.super_shield, 31); + world + .apply_commands( + &[Command::Damage { + entity: 0, + amount: 12, + }], + ®, + ) + .unwrap(); + let saved = world.pilot(&pilot); + assert_eq!(saved.inventory[&ContentId::from("base:super_shield")], 19); + assert_eq!( + World::new(&pilot.mission, &saved, ®) + .unwrap() + .player + .super_shield, + 19 + ); +} + +#[test] +fn moving_an_entity_rebases_its_path() { + let reg = fixture(); + let mut world = World::new(&"base:sector_1_wave_1".into(), &Pilot::default(), ®).unwrap(); + let entity = world.spawn(&"base:drone".into(), 100, 0, ®).unwrap(); + world + .apply_commands( + &[Command::Move { + entity, + x: 20, + y: 20, + }], + ®, + ) + .unwrap(); + let mut scripts = ScriptRuntime::new(); + world.step(Input::default(), ®, &mut scripts).unwrap(); + assert_eq!((world.enemies[0].x, world.enemies[0].y), (20, 20)); + world.step(Input::default(), ®, &mut scripts).unwrap(); + assert_eq!((world.enemies[0].x, world.enemies[0].y), (20, 21)); +} + +#[test] +fn consumable_use_has_snapshot_and_only_fires_on_press() { + let reg = fixture(); + let mut pilot = Pilot::default(); + pilot.inventory.insert("base:medkit".into(), 2); + pilot.inventory.insert("base:energy".into(), 50); + pilot.selected = Some("base:medkit".into()); + let mut world = World::new(&pilot.mission, &pilot, ®).unwrap(); + let mut scripts = ScriptRuntime::new(); + scripts.add("base","medkit.rhai",r#"fn on_use(event,state,rng) {#{commands:[#{op:"credits",amount:7}], state:#{shield:event.player.shield,quantity:event.player.inventory["base:medkit"]}}}"#).unwrap(); + world + .step( + Input { + special: true, + ..Input::default() + }, + ®, + &mut scripts, + ) + .unwrap(); + assert_eq!(world.player.shield, 75); + assert_eq!(world.player.credits, 7); + assert_eq!(world.player.inventory[&ContentId::from("base:medkit")], 1); + world + .step( + Input { + special: true, + ..Input::default() + }, + ®, + &mut scripts, + ) + .unwrap(); + assert_eq!(world.player.credits, 7); + world.step(Input::default(), ®, &mut scripts).unwrap(); + world + .step( + Input { + special: true, + ..Input::default() + }, + ®, + &mut scripts, + ) + .unwrap(); + assert_eq!(world.player.shield, 100); + assert_eq!(world.player.credits, 14); + assert_eq!(world.player.selected, None); +} diff --git a/tests/modding.rs b/tests/modding.rs new file mode 100644 index 00000000..cb82a7e0 --- /dev/null +++ b/tests/modding.rs @@ -0,0 +1,949 @@ +use raptor_replica::{ + content::{ContentId, ContentPack, Registry}, + modding::{self, ActiveMods, Command, Manifest, ScriptRuntime}, + persistence::Pilot, + simulation::{Input, World}, +}; +use serde_json::{Value, json}; +use std::{collections::BTreeMap, fs, path::Path}; + +fn pack(value: Value) -> ContentPack { + serde_json::from_value(value).unwrap() +} +fn item(id: &str, price: u32) -> Value { + json!({"id": id, "name": id, "price": price, "max_count": 100}) +} +fn base() -> Registry { + let mut reg = Registry::default(); + reg.apply(pack(json!({ + "weapons": [{"id":"base:projectile_forward_guns", "name":"Forward Guns", "damage":1,"speed":8,"cooldown":2,"behavior":"straight","target":"all"}], + "items": [ + {"id":"base:forward_guns","name":"Forward Guns","price":0,"weapon":"base:projectile_forward_guns"}, + {"id":"base:energy","name":"Shield","price":0,"max_count":100} + ], + "missions":[{"id":"base:sector_1_wave_1","name":"Test Mission","duration":1000}] + })), "base").unwrap(); + reg.validate().unwrap(); + reg +} +fn install(root: &Path, folder: &str, id: &str, content: Value) -> Manifest { + let dir = root.join(folder); + fs::create_dir_all(&dir).unwrap(); + let manifest = Manifest { + id: id.into(), + name: id.into(), + version: "1.0.0".into(), + api_version: 1, + description: String::new(), + dependencies: BTreeMap::new(), + conflicts: vec![], + content: "content.json".into(), + scripts: vec![], + }; + write_manifest(&dir, &manifest); + fs::write( + dir.join("content.json"), + serde_json::to_vec_pretty(&content).unwrap(), + ) + .unwrap(); + manifest +} +fn write_manifest(dir: &Path, manifest: &Manifest) { + fs::write(dir.join("mod.toml"), toml::to_string(manifest).unwrap()).unwrap(); +} +fn ids(values: &[&str]) -> Vec { + values.iter().map(|v| (*v).into()).collect() +} +fn error(result: anyhow::Result) -> String { + match result { + Ok(_) => panic!("expected failure"), + Err(e) => format!("{e:#}"), + } +} + +#[test] +fn dependencies_load_before_dependents_and_keep_independent_priority() { + let temp = tempfile::tempdir().unwrap(); + install(temp.path(), "alpha", "alpha", json!({})); + let mut beta = install(temp.path(), "beta", "beta", json!({})); + beta.dependencies.insert("alpha".into(), "^1.0".into()); + write_manifest(&temp.path().join("beta"), &beta); + install(temp.path(), "gamma", "gamma", json!({})); + let d = modding::discover(temp.path()); + assert!(d.errors.is_empty()); + assert_eq!( + modding::order(&d, &ids(&["gamma", "beta", "alpha"])).unwrap(), + ids(&["gamma", "alpha", "beta"]) + ); +} + +#[test] +fn missing_disabled_wrong_version_and_cyclic_dependencies_are_actionable() { + let temp = tempfile::tempdir().unwrap(); + let mut alpha = install(temp.path(), "alpha", "alpha", json!({})); + let mut beta = install(temp.path(), "beta", "beta", json!({})); + beta.dependencies.insert("alpha".into(), "^2".into()); + write_manifest(&temp.path().join("beta"), &beta); + let d = modding::discover(temp.path()); + assert!(error(modding::order(&d, &ids(&["beta"]))).contains("requires enabled mod alpha")); + assert!(error(modding::order(&d, &ids(&["alpha", "beta"]))).contains("installed 1.0.0")); + beta.dependencies.insert("alpha".into(), "^1".into()); + alpha.dependencies.insert("beta".into(), "^1".into()); + write_manifest(&temp.path().join("beta"), &beta); + write_manifest(&temp.path().join("alpha"), &alpha); + assert!( + error(modding::order( + &modding::discover(temp.path()), + &ids(&["alpha", "beta"]) + )) + .contains("cyclic") + ); +} + +#[test] +fn api_conflicts_and_duplicate_selected_ids_reject_activation() { + let temp = tempfile::tempdir().unwrap(); + let mut alpha = install(temp.path(), "alpha", "alpha", json!({})); + install(temp.path(), "beta", "beta", json!({})); + alpha.api_version = 99; + write_manifest(&temp.path().join("alpha"), &alpha); + assert!( + error(modding::order( + &modding::discover(temp.path()), + &ids(&["alpha"]) + )) + .contains("requires API 99") + ); + alpha.api_version = 1; + alpha.conflicts.push("beta".into()); + write_manifest(&temp.path().join("alpha"), &alpha); + let d = modding::discover(temp.path()); + assert!(error(modding::order(&d, &ids(&["alpha", "beta"]))).contains("conflicts with beta")); + assert!(error(modding::order(&d, &ids(&["beta", "beta"]))).contains("duplicate mod")); +} + +#[test] +fn every_duplicate_installed_namespace_is_unusable() { + let temp = tempfile::tempdir().unwrap(); + for folder in ["first", "second", "third"] { + install(temp.path(), folder, "collision", json!({})); + } + let d = modding::discover(temp.path()); + assert!(!d.mods.contains_key("collision")); + assert_eq!(d.errors.len(), 2); + assert!( + error(ActiveMods::build(&base(), &d, &ids(&["collision"]), None)).contains("not installed") + ); +} + +#[test] +fn adding_a_duplicate_after_discovery_requires_rescanning() { + let temp = tempfile::tempdir().unwrap(); + install(temp.path(), "first", "alpha", json!({})); + let original = modding::discover(temp.path()); + install(temp.path(), "second", "alpha", json!({})); + let message = error(ActiveMods::build( + &base(), + &original, + &ids(&["alpha"]), + None, + )); + assert!(message.contains("duplicated since discovery") && message.contains("rescan")); +} + +#[test] +fn changed_files_require_a_new_discovery_snapshot() { + let temp = tempfile::tempdir().unwrap(); + install( + temp.path(), + "alpha", + "alpha", + json!({"items":[item("alpha:cell", 10)]}), + ); + let original = modding::discover(temp.path()); + let before = ActiveMods::build(&base(), &original, &ids(&["alpha"]), None).unwrap(); + fs::write( + temp.path().join("alpha/content.json"), + serde_json::to_vec(&json!({"items":[item("alpha:cell", 12)]})).unwrap(), + ) + .unwrap(); + assert!( + error(ActiveMods::build( + &base(), + &original, + &ids(&["alpha"]), + None + )) + .contains("rescan") + ); + let after = ActiveMods::build( + &base(), + &modding::discover(temp.path()), + &ids(&["alpha"]), + None, + ) + .unwrap(); + assert_ne!(before.pins[0].hash, after.pins[0].hash); + assert_eq!( + after.registry.items[&ContentId::from("alpha:cell")].price, + 12 + ); +} + +#[test] +fn package_hash_covers_added_assets_and_manifest_changes() { + let temp = tempfile::tempdir().unwrap(); + let mut manifest = install(temp.path(), "alpha", "alpha", json!({})); + let d = modding::discover(temp.path()); + fs::write(temp.path().join("alpha/readme.txt"), "Extra package file").unwrap(); + assert!(error(ActiveMods::build(&base(), &d, &ids(&["alpha"]), None)).contains("rescan")); + let d = modding::discover(temp.path()); + manifest.version = "1.0.1".into(); + write_manifest(&temp.path().join("alpha"), &manifest); + assert!(error(ActiveMods::build(&base(), &d, &ids(&["alpha"]), None)).contains("rescan")); +} + +#[test] +fn package_paths_depth_and_size_are_bounded() { + let temp = tempfile::tempdir().unwrap(); + let mut m = install(temp.path(), "traversal", "traversal", json!({})); + m.content = "../outside.json".into(); + write_manifest(&temp.path().join("traversal"), &m); + install(temp.path(), "deep", "deep", json!({})); + let mut nested = temp.path().join("deep"); + for _ in 0..17 { + nested = nested.join("nested"); + } + fs::create_dir_all(nested).unwrap(); + install(temp.path(), "large", "large", json!({})); + fs::File::create(temp.path().join("large/huge.bin")) + .unwrap() + .set_len(64 * 1024 * 1024 + 1) + .unwrap(); + let d = modding::discover(temp.path()); + assert!(d.mods.is_empty()); + assert!(d.errors.iter().any(|e| e.contains("parent traversal"))); + assert!(d.errors.iter().any(|e| e.contains("depth exceeds"))); + assert!(d.errors.iter().any(|e| e.contains("64 MiB"))); +} + +#[cfg(unix)] +#[test] +fn symlink_folders_and_files_are_rejected() { + use std::os::unix::fs::symlink; + let temp = tempfile::tempdir().unwrap(); + install(temp.path(), "alpha", "alpha", json!({})); + symlink("/etc/passwd", temp.path().join("alpha/link")).unwrap(); + symlink(temp.path().join("alpha"), temp.path().join("alias")).unwrap(); + let d = modding::discover(temp.path()); + assert!(d.mods.is_empty()); + assert_eq!(d.errors.len(), 2); + assert!(d.errors.iter().all(|e| e.contains("symlink"))); +} + +#[test] +fn invalid_manifest_versions_and_duplicate_sources_fail_discovery() { + let temp = tempfile::tempdir().unwrap(); + let mut m = install(temp.path(), "alpha", "alpha", json!({})); + m.dependencies + .insert("beta".into(), "obviously invalid".into()); + write_manifest(&temp.path().join("alpha"), &m); + assert!(modding::discover(temp.path()).mods.is_empty()); + m.dependencies.clear(); + m.scripts = ids(&["script.rhai", "script.rhai"]); + fs::write(temp.path().join("alpha/script.rhai"), "").unwrap(); + write_manifest(&temp.path().join("alpha"), &m); + assert!(modding::discover(temp.path()).errors[0].contains("duplicate script")); +} + +#[test] +fn later_explicit_overrides_win_and_report_the_previous_owner() { + let temp = tempfile::tempdir().unwrap(); + install( + temp.path(), + "alpha", + "alpha", + json!({"items":[item("base:energy", 10)], "overrides":["base:energy"]}), + ); + install( + temp.path(), + "beta", + "beta", + json!({"items":[item("base:energy", 20)], "overrides":["base:energy"]}), + ); + let d = modding::discover(temp.path()); + let active = ActiveMods::build(&base(), &d, &ids(&["alpha", "beta"]), None).unwrap(); + assert_eq!( + active.registry.items[&ContentId::from("base:energy")].price, + 20 + ); + assert_eq!( + active.registry.owners[&ContentId::from("base:energy")], + "beta" + ); + assert_eq!( + active.registry.overrides, + ids(&["base:energy: base -> alpha", "base:energy: alpha -> beta"]) + ); + let reversed = ActiveMods::build(&base(), &d, &ids(&["beta", "alpha"]), None).unwrap(); + assert_eq!( + reversed.registry.items[&ContentId::from("base:energy")].price, + 10 + ); +} + +#[test] +fn accidental_duplicates_type_changes_and_failed_packs_leave_registry_intact() { + let mut registry = base(); + let previous = registry.items.len(); + assert!( + registry + .apply( + pack(json!({"items":[item("alpha:valid", 1), item("base:energy", 2)]})), + "alpha" + ) + .is_err() + ); + assert_eq!(registry.items.len(), previous); + assert!( + !registry + .owners + .contains_key(&ContentId::from("alpha:valid")) + ); + assert!( + registry + .apply( + pack(json!({"items":[item("alpha:twice", 1), item("alpha:twice", 2)]})), + "alpha" + ) + .is_err() + ); + assert!(registry.apply(pack(json!({"enemies":[{"id":"base:energy","name":"Wrong type"}],"overrides":["base:energy"]})), "alpha").is_err()); + assert!( + registry + .apply(pack(json!({"items":[item("foreign:cell", 1)]})), "alpha") + .is_err() + ); + assert!( + registry + .apply( + pack(json!({"items":[item("alpha:new", 1)],"overrides":["alpha:new"]})), + "alpha" + ) + .is_err() + ); +} + +#[test] +fn content_references_and_undeclared_scripts_reject_the_whole_mod() { + let temp = tempfile::tempdir().unwrap(); + install( + temp.path(), + "alpha", + "alpha", + json!({"items":[{"id":"alpha:cell","name":"Cell","price":1,"weapon":"alpha:missing"}]}), + ); + assert!( + error(ActiveMods::build( + &base(), + &modding::discover(temp.path()), + &ids(&["alpha"]), + None + )) + .contains("missing weapon") + ); + fs::write(temp.path().join("alpha/content.json"), serde_json::to_vec(&json!({"items":[{"id":"alpha:cell","name":"Cell","price":1,"script":"undeclared.rhai"}]})).unwrap()).unwrap(); + assert!( + error(ActiveMods::build( + &base(), + &modding::discover(temp.path()), + &ids(&["alpha"]), + None + )) + .contains("manifest.scripts") + ); +} + +#[test] +fn script_failure_rolls_back_world_state_and_deterministic_rng() { + let mut registry = base(); + registry + .missions + .get_mut(&ContentId::from("base:sector_1_wave_1")) + .unwrap() + .script = Some("mission.rhai".into()); + let mut runtime = ScriptRuntime::new(); + runtime + .add( + "base", + "mission.rhai", + r#"fn on_mission_start(e,s,r) { + #{commands:[#{op:"credits",amount:7}, #{op:"move",entity:999,x:0,y:0}],state:#{random:r[0]}} + }"#, + ) + .unwrap(); + let pilot = Pilot::default(); + let mut world = World::new(&pilot.mission, &pilot, ®istry).unwrap(); + let before = world.digest(); + assert!( + world + .step(Input::default(), ®istry, &mut runtime) + .is_err() + ); + assert_eq!(world.digest(), before); + assert!(runtime.states.is_empty()); + assert!(runtime.rng.is_empty()); + let source = r#"fn on_mission_start(e,s,r) { #{commands:[#{op:"credits",amount:r[0]}],state:#{random:r[0]}} }"#; + runtime.add("base", "mission.rhai", source).unwrap(); + world + .step(Input::default(), ®istry, &mut runtime) + .unwrap(); + let mut fresh_runtime = ScriptRuntime::new(); + fresh_runtime.add("base", "mission.rhai", source).unwrap(); + let mut fresh_world = World::new(&pilot.mission, &pilot, ®istry).unwrap(); + fresh_world + .step(Input::default(), ®istry, &mut fresh_runtime) + .unwrap(); + assert_eq!(world.digest(), fresh_world.digest()); + assert_eq!(runtime.states, fresh_runtime.states); + assert_eq!(runtime.rng, fresh_runtime.rng); +} + +#[test] +fn command_batches_are_atomic_even_after_an_earlier_valid_command() { + let registry = base(); + let pilot = Pilot::default(); + let mut world = World::new(&pilot.mission, &pilot, ®istry).unwrap(); + let before = world.digest(); + let commands = [ + Command::Credits { amount: 100 }, + Command::Spawn { + enemy: "missing:enemy".into(), + x: 0, + y: 0, + }, + ]; + assert!(world.apply_commands(&commands, ®istry).is_err()); + assert_eq!(world.digest(), before); +} + +#[test] +fn malformed_result_excessive_commands_and_oversized_state_are_rejected() { + let mut runtime = ScriptRuntime::new(); + for (source, expected) in [ + ( + r#"fn on_tick(e,s,r) { #{commands:[#{op:"unknown"}],state:#{}} }"#, + "invalid result", + ), + ( + r#"fn on_tick(e,s,r) { let a=[]; for i in 0..257 { a.push(#{op:"complete"}); } #{commands:a,state:#{}} }"#, + "too many commands", + ), + ( + r#"fn on_tick(e,s,r) { let a=[]; for i in 0..4000 { a.push(999999999999999999); } #{commands:[],state:a} }"#, + "state exceeds", + ), + ] { + runtime.begin_tick(); + runtime.add("test", "limits.rhai", source).unwrap(); + let message = error(runtime.invoke("test", "limits.rhai", "on_tick", &json!({}), 17)); + assert!( + message.contains(expected), + "expected {expected}, got {message}" + ); + assert!(runtime.states.is_empty()); + assert!(runtime.rng.is_empty()); + } +} + +#[test] +fn execution_budget_is_shared_across_callbacks_and_resets_per_tick() { + let mut runtime = ScriptRuntime::new(); + runtime.add("test", "budget.rhai", r#"fn on_tick(e,s,r) { let x=0; for n in 0..2500 { x+=1; } #{commands:[],state:#{iterations:x}} }"#).unwrap(); + runtime.begin_tick(); + let mut success = 0; + for _ in 0..100 { + if runtime + .invoke("test", "budget.rhai", "on_tick", &json!({}), 1) + .is_err() + { + break; + } + success += 1; + } + assert!( + success > 1 && success < 100, + "successful callbacks: {success}" + ); + runtime.begin_tick(); + runtime + .invoke("test", "budget.rhai", "on_tick", &json!({}), 1) + .unwrap(); +} + +#[test] +fn missing_hook_does_not_advance_rng_or_state() { + let mut runtime = ScriptRuntime::new(); + runtime + .add( + "test", + "empty.rhai", + "fn other(e,s,r) { #{commands:[],state:s} }", + ) + .unwrap(); + assert!( + runtime + .invoke("test", "empty.rhai", "on_tick", &json!({}), 1) + .unwrap() + .is_empty() + ); + assert!(runtime.states.is_empty()); + assert!(runtime.rng.is_empty()); +} + +#[test] +fn incompatible_save_pins_and_disabled_equipment_do_not_modify_the_save() { + let temp = tempfile::tempdir().unwrap(); + install( + temp.path(), + "alpha", + "alpha", + json!({"items":[item("alpha:cell", 1)]}), + ); + let active = ActiveMods::build( + &base(), + &modding::discover(temp.path()), + &ids(&["alpha"]), + None, + ) + .unwrap(); + let mut pilot = Pilot::default(); + pilot.mods = active.pins.clone(); + pilot.inventory.insert("alpha:cell".into(), 1); + let path = temp.path().join("pilot.json"); + pilot.save(&path).unwrap(); + let before = fs::read(&path).unwrap(); + Pilot::load(&path, &active.registry, &active.pins).unwrap(); + assert!(error(Pilot::load(&path, &base(), &[])).contains("enable the matching mods")); + let mut changed = active.pins.clone(); + changed[0].hash = "different-content-hash".into(); + assert!(Pilot::load(&path, &active.registry, &changed).is_err()); + assert!( + error(Pilot::load(&path, &base(), &active.pins)) + .contains("saved item alpha:cell is unavailable") + ); + assert_eq!(fs::read(path).unwrap(), before); +} + +#[test] +fn saved_script_state_and_rng_resume_the_same_callback_sequence() { + let mut runtime = ScriptRuntime::new(); + let source = r#"fn on_tick(e,s,r) { let n=if s.contains("n") {s.n+1} else {1}; #{commands:[#{op:"credits",amount:r[0]}],state:#{n:n,last:r[0]}} }"#; + runtime.add("test", "state.rhai", source).unwrap(); + runtime + .invoke("test", "state.rhai", "on_tick", &json!({}), 42) + .unwrap(); + let mut pilot = Pilot::default(); + pilot.script_state = runtime.states.clone(); + pilot.script_rng = runtime.rng.clone(); + let restored_pilot: Pilot = + serde_json::from_slice(&serde_json::to_vec(&pilot).unwrap()).unwrap(); + let mut restored = ScriptRuntime::new(); + restored.add("test", "state.rhai", source).unwrap(); + restored.states = restored_pilot.script_state; + restored.rng = restored_pilot.script_rng; + let a = runtime + .invoke("test", "state.rhai", "on_tick", &json!({}), 42) + .unwrap(); + let b = restored + .invoke("test", "state.rhai", "on_tick", &json!({}), 42) + .unwrap(); + assert_eq!( + serde_json::to_value(a).unwrap(), + serde_json::to_value(b).unwrap() + ); + assert_eq!(runtime.states, restored.states); + assert_eq!(runtime.rng, restored.rng); +} + +#[test] +fn example_mod_compiles_and_its_weapon_enemy_item_and_mission_hooks_execute() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/mods"); + let mut active = + ActiveMods::build(&base(), &modding::discover(&dir), &ids(&["aurora"]), None).unwrap(); + assert!( + active + .registry + .weapons + .contains_key(&ContentId::from("aurora:pulse_projectile")) + ); + assert!( + active + .registry + .items + .contains_key(&ContentId::from("aurora:pulse_cannon")) + ); + assert!( + active + .registry + .enemies + .contains_key(&ContentId::from("aurora:weaver")) + ); + assert!( + active + .registry + .campaigns + .contains_key(&ContentId::from("aurora:trials")) + ); + let mission = ContentId::from("aurora:field_trials"); + let pilot = Pilot::default(); + let mut world = World::new(&mission, &pilot, &active.registry).unwrap(); + world + .step(Input::default(), &active.registry, &mut active.scripts) + .unwrap(); + assert_eq!( + world + .player + .inventory + .get(&ContentId::from("aurora:pulse_cannon")), + Some(&1) + ); + world + .step( + Input { + fire: true, + ..Input::default() + }, + &active.registry, + &mut active.scripts, + ) + .unwrap(); + assert_eq!( + active.scripts.states["aurora/scripts/weapon.rhai"]["shots"], + 1 + ); + assert!( + world + .projectiles + .iter() + .filter(|p| p.weapon.0 == "aurora:pulse_projectile") + .count() + >= 3 + ); + let entity = world + .spawn(&ContentId::from("aurora:weaver"), 60, 30, &active.registry) + .unwrap(); + world + .step(Input::default(), &active.registry, &mut active.scripts) + .unwrap(); + assert_eq!( + world + .enemies + .iter() + .find(|e| e.entity == entity) + .unwrap() + .vx, + 1 + ); + let commands = active + .scripts + .invoke( + "aurora", + "scripts/cell.rhai", + "on_pickup", + &json!({"entity":1}), + 0, + ) + .unwrap(); + world.apply_commands(&commands, &active.registry).unwrap(); + assert_eq!(world.player.credits, 25); +} + +#[test] +fn png_strips_are_validated_without_the_original_catalog() { + let temp = tempfile::tempdir().unwrap(); + let art = json!({"png":"cell.png","logical_width":1,"logical_height":1,"frames":2}); + install( + temp.path(), + "alpha", + "alpha", + json!({"items":[{"id":"alpha:cell","name":"Cell","price":1,"art":art}]}), + ); + image::RgbaImage::from_pixel(3, 1, image::Rgba([20, 40, 60, 255])) + .save(temp.path().join("alpha/cell.png")) + .unwrap(); + let message = error(ActiveMods::build( + &base(), + &modding::discover(temp.path()), + &ids(&["alpha"]), + None, + )); + assert!(message.contains("strip width")); + image::RgbaImage::from_pixel(4, 2, image::Rgba([20, 40, 60, 255])) + .save(temp.path().join("alpha/cell.png")) + .unwrap(); + ActiveMods::build( + &base(), + &modding::discover(temp.path()), + &ids(&["alpha"]), + None, + ) + .unwrap(); +} + +#[test] +fn callback_arity_and_source_size_are_checked_before_activation() { + let mut runtime = ScriptRuntime::new(); + assert!( + error(runtime.add("test", "bad.rhai", "fn on_fire(event,state) { state }")) + .contains("callbacks require") + ); + assert!( + error(runtime.add("test", "huge.rhai", &" ".repeat(1024 * 1024 + 1))) + .contains("source exceeds 1 MiB") + ); +} + +#[test] +fn callbacks_can_query_player_entities_projectiles_pickups_and_objectives() { + let mut registry = base(); + registry + .missions + .get_mut(&ContentId::from("base:sector_1_wave_1")) + .unwrap() + .script = Some("queries.rhai".into()); + let mut runtime = ScriptRuntime::new(); + runtime.add("base", "queries.rhai", r#"fn on_mission_start(e,s,r) { + #{commands:[],state:#{shield:e.player.shield,inventory:e.player.inventory, + enemies:e.entities.len,shots:e.projectiles.len,pickups:e.pickups.len,objectives:e.objectives}} + }"#).unwrap(); + let pilot = Pilot::default(); + let mut world = World::new(&pilot.mission, &pilot, ®istry).unwrap(); + world + .step(Input::default(), ®istry, &mut runtime) + .unwrap(); + let state = &runtime.states["base/queries.rhai"]; + assert_eq!(state["shield"], 100); + assert_eq!(state["inventory"]["base:forward_guns"], 1); + assert_eq!(state["enemies"], 0); + assert_eq!(state["shots"], 0); + assert_eq!(state["pickups"], 0); + assert_eq!(state["objectives"], json!({})); +} + +#[test] +fn consumable_special_items_run_on_use_once_per_button_press() { + let mut registry = base(); + registry + .apply( + pack(json!({"items":[{ + "id":"test:repair","name":"Repair","price":5,"max_count":10,"shield":7, + "special":true,"consumable":true,"script":"repair.rhai" + }]})), + "test", + ) + .unwrap(); + let mut runtime = ScriptRuntime::new(); + runtime + .add( + "test", + "repair.rhai", + r#"fn on_use(e,s,r) { + let n=if s.contains("n") {s.n+1} else {1}; + #{commands:[#{op:"credits",amount:5}],state:#{n:n}} + }"#, + ) + .unwrap(); + let mut pilot = Pilot::default(); + pilot.inventory.insert("base:energy".into(), 50); + pilot.inventory.insert("test:repair".into(), 2); + pilot.selected = Some("test:repair".into()); + let mut world = World::new(&pilot.mission, &pilot, ®istry).unwrap(); + let input = Input { + special: true, + ..Input::default() + }; + world.step(input, ®istry, &mut runtime).unwrap(); + world.step(input, ®istry, &mut runtime).unwrap(); + assert_eq!(world.player.shield, 57); + assert_eq!(world.player.inventory[&ContentId::from("test:repair")], 1); + assert_eq!(runtime.states["test/repair.rhai"]["n"], 1); + world + .step(Input::default(), ®istry, &mut runtime) + .unwrap(); + world.step(input, ®istry, &mut runtime).unwrap(); + assert_eq!(world.player.shield, 64); + assert_eq!(world.player.credits, 10); + assert_eq!(runtime.states["test/repair.rhai"]["n"], 2); +} + +#[test] +fn wall_clock_sleep_and_indirect_native_calls_are_not_exposed() { + let mut runtime = ScriptRuntime::new(); + for source in [ + "fn on_tick(e,s,r) { timestamp(); #{commands:[],state:s} }", + "fn on_tick(e,s,r) { sleep(0); #{commands:[],state:s} }", + "fn on_tick(e,s,r) { let f=Fn(\"sleep\"); f.call(0); #{commands:[],state:s} }", + "fn on_tick(e,s,r) { let f=Fn(\"timestamp\"); f.call(); #{commands:[],state:s} }", + ] { + runtime.begin_tick(); + runtime.add("test", "unsafe.rhai", source).unwrap(); + let message = error(runtime.invoke("test", "unsafe.rhai", "on_tick", &json!({}), 1)); + assert!(message.contains("Function not found"), "{message}"); + } + assert!(runtime.states.is_empty()); + assert!(runtime.rng.is_empty()); +} + +#[test] +fn dynamic_eval_and_imports_cannot_be_reintroduced_by_function_pointers() { + let mut runtime = ScriptRuntime::new(); + assert!( + runtime + .add("test", "eval.rhai", "fn on_tick(e,s,r) { eval(\"42\"); }") + .is_err() + ); + assert!( + runtime + .add("test", "imports.rhai", "import \"external\" as x;") + .is_err() + ); + runtime + .add( + "test", + "indirect.rhai", + "fn on_tick(e,s,r) { let f=Fn(\"eval\"); f.call(\"42\"); #{commands:[],state:s} }", + ) + .unwrap(); + assert!( + runtime + .invoke("test", "indirect.rhai", "on_tick", &json!({}), 1) + .is_err() + ); +} + +#[test] +fn script_inventory_commands_preserve_the_twenty_item_capacity() { + let mut registry = base(); + let extra: Vec<_> = (0..19) + .map(|n| item(&format!("test:item_{n}"), 1)) + .collect(); + registry + .apply(pack(json!({"items":extra})), "test") + .unwrap(); + let pilot = Pilot::default(); + let mut world = World::new(&pilot.mission, &pilot, ®istry).unwrap(); + for n in 0..18 { + world + .apply_commands( + &[Command::GiveItem { + item: format!("test:item_{n}"), + count: 1, + }], + ®istry, + ) + .unwrap(); + } + assert_eq!(world.player.inventory.len(), 20); + let before = world.digest(); + assert!( + world + .apply_commands( + &[Command::GiveItem { + item: "test:item_18".into(), + count: 1 + }], + ®istry + ) + .is_err() + ); + assert_eq!(before, world.digest()); + world + .apply_commands( + &[Command::GiveItem { + item: "test:item_0".into(), + count: 1, + }], + ®istry, + ) + .unwrap(); + assert_eq!(world.player.inventory[&ContentId::from("test:item_0")], 2); +} + +#[test] +fn existing_objectives_remain_updatable_at_the_capacity_limit() { + let registry = base(); + let pilot = Pilot::default(); + let mut world = World::new(&pilot.mission, &pilot, ®istry).unwrap(); + for n in 0..1024 { + world.objectives.insert(format!("test:{n}"), 0); + } + world + .apply_commands( + &[Command::Objective { + key: "test:0".into(), + value: 10, + }], + ®istry, + ) + .unwrap(); + assert_eq!(world.objectives["test:0"], 10); + assert!( + world + .apply_commands( + &[Command::Objective { + key: "test:new".into(), + value: 1 + }], + ®istry + ) + .is_err() + ); + assert_eq!(world.objectives.len(), 1024); +} + +#[test] +fn enemy_weapons_and_enemies_receive_fire_and_damage_hooks() { + let mut registry = base(); + registry.apply(pack(json!({ + "weapons":[{"id":"test:bolt","name":"Bolt","damage":1,"speed":1,"cooldown":2,"behavior":"straight","target":"all","script":"weapon.rhai"}], + "enemies":[{"id":"test:fighter","name":"Fighter","health":100,"speed":1,"cooldown":2,"weapon":"test:bolt","script":"enemy.rhai"}] + })), "test").unwrap(); + let mut runtime = ScriptRuntime::new(); + runtime + .add( + "test", + "weapon.rhai", + r#"fn on_fire(e,s,r) { + #{commands:[],state:#{hostile:e.hostile,entity:e.entity}} + }"#, + ) + .unwrap(); + runtime + .add( + "test", + "enemy.rhai", + r#"fn on_fire(e,s,r) { #{commands:[],state:#{fired:true}} } + fn on_hit(e,s,r) { s.hit=e.damage; s.scripted=e.scripted; #{commands:[],state:s} }"#, + ) + .unwrap(); + let pilot = Pilot::default(); + let mut world = World::new(&pilot.mission, &pilot, ®istry).unwrap(); + let entity = world + .spawn(&ContentId::from("test:fighter"), 30, 30, ®istry) + .unwrap(); + world + .step(Input::default(), ®istry, &mut runtime) + .unwrap(); + assert_eq!(runtime.states["test/weapon.rhai"]["hostile"], true); + assert_eq!(runtime.states["test/weapon.rhai"]["entity"], entity); + assert_eq!(runtime.states["test/enemy.rhai"]["fired"], true); + world + .apply_commands(&[Command::Damage { entity, amount: 7 }], ®istry) + .unwrap(); + world + .step(Input::default(), ®istry, &mut runtime) + .unwrap(); + assert_eq!(runtime.states["test/enemy.rhai"]["hit"], 7); + assert_eq!(runtime.states["test/enemy.rhai"]["scripted"], true); +} diff --git a/tests/sound.rs b/tests/sound.rs new file mode 100644 index 00000000..cf88a9e5 --- /dev/null +++ b/tests/sound.rs @@ -0,0 +1,119 @@ +use raptor_replica::{ + content::{ContentPack, Registry}, + modding::{self, ActiveMods, Command, ScriptRuntime}, + persistence::Pilot, + simulation::{Input, Outcome, World}, + sound, +}; +use serde_json::json; + +fn wav(channels: u16, bits: u16, data: &[u8]) -> Vec { + let align = channels * bits / 8; + let mut bytes = b"RIFF".to_vec(); + bytes.extend((36u32 + data.len() as u32 + (data.len() as u32 % 2)).to_le_bytes()); + bytes.extend(b"WAVEfmt "); + bytes.extend(16u32.to_le_bytes()); + bytes.extend(1u16.to_le_bytes()); + bytes.extend(channels.to_le_bytes()); + bytes.extend(11025u32.to_le_bytes()); + bytes.extend((11025u32 * align as u32).to_le_bytes()); + bytes.extend(align.to_le_bytes()); + bytes.extend(bits.to_le_bytes()); + bytes.extend(b"data"); + bytes.extend((data.len() as u32).to_le_bytes()); + bytes.extend(data); + if data.len() % 2 == 1 { + bytes.push(0); + } + bytes +} +fn registry() -> Registry { + let mut registry = Registry::default(); + let pack: ContentPack=serde_json::from_value(json!({ + "items":[{"id":"base:energy","name":"Shield","price":0,"max_count":100}, + {"id":"base:forward_guns","name":"Guns","price":0}], + "missions":[{"id":"base:sector_1_wave_1","name":"Test","duration":1,"auto_complete":false,"script":"mission.rhai"}], + "sounds":[{"id":"base:test","name":"Test","file":"test.wav"}] + })).unwrap(); + registry.apply(pack, "base").unwrap(); + registry.validate().unwrap(); + registry +} +#[test] +fn wav_handles_padding_unsigned_eight_bit_and_stereo_sixteen_bit() { + let decoded = sound::decode(&wav(1, 8, &[0, 128, 255])).unwrap(); + assert_eq!(decoded.data, [0, 128, 255]); + assert_eq!(decoded.rate, 11025); + let samples: Vec<_> = [-32768i16, 32767, -32768, -32768, 32767, 32767] + .into_iter() + .flat_map(i16::to_le_bytes) + .collect(); + assert_eq!( + sound::decode(&wav(2, 16, &samples)).unwrap().data, + [128, 0, 255] + ); +} +#[test] +fn malformed_wave_ranges_formats_and_padding_fail() { + let bytes = wav(1, 8, &[128, 200, 0]); + for end in 0..bytes.len() { + assert!(sound::decode(&bytes[..end]).is_err()); + } + assert!(sound::decode(&wav(3, 8, &[0, 0, 0])).is_err()); + assert!(sound::decode(&wav(1, 32, &[0, 0, 0, 0])).is_err()); + let mut huge = bytes.clone(); + huge[40..44].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(sound::decode(&huge).is_err()); +} +#[test] +fn scripted_completion_emits_end_hook_once_and_sound_ids_are_checked() { + let registry = registry(); + let mut world = World::new(&Pilot::default().mission, &Pilot::default(), ®istry).unwrap(); + let mut scripts = ScriptRuntime::new(); + scripts.add("base","mission.rhai",r#" + fn on_tick(event,state,random) { #{commands:[#{op:"complete"}],state:state} } + fn on_mission_end(event,state,random) { #{commands:[#{op:"play_sound",sound:"base:test"}],state:#{ended:1}} } + "#).unwrap(); + world + .step(Input::default(), ®istry, &mut scripts) + .unwrap(); + assert_eq!(world.outcome, Outcome::Complete); + assert_eq!(world.mod_sounds.len(), 1); + world + .step(Input::default(), ®istry, &mut scripts) + .unwrap(); + assert_eq!(world.mod_sounds.len(), 1); + assert!( + world + .apply_commands( + &[Command::PlaySound { + sound: "base:missing".into() + }], + ®istry + ) + .is_err() + ); +} +#[test] +fn package_local_sounds_validate_and_missing_files_reject_activation() { + let dir = tempfile::tempdir().unwrap(); + let package = dir.path().join("tone"); + std::fs::create_dir_all(&package).unwrap(); + std::fs::write( + package.join("mod.toml"), + "id='tone'\nname='Tone'\nversion='1.0.0'\napi_version=1\ncontent='content.json'\n", + ) + .unwrap(); + std::fs::write( + package.join("content.json"), + serde_json::to_vec(&json!({"sounds":[{"id":"tone:shot","name":"Shot","file":"shot.wav"}]})) + .unwrap(), + ) + .unwrap(); + std::fs::write(package.join("shot.wav"), wav(1, 8, &[128, 200, 50])).unwrap(); + let found = modding::discover(dir.path()); + assert!(ActiveMods::build(&Registry::default(), &found, &["tone".into()], None).is_ok()); + std::fs::remove_file(package.join("shot.wav")).unwrap(); + let found = modding::discover(dir.path()); + assert!(ActiveMods::build(&Registry::default(), &found, &["tone".into()], None).is_err()); +} diff --git a/tools/compare_replays.py b/tools/compare_replays.py new file mode 100644 index 00000000..987711b3 --- /dev/null +++ b/tools/compare_replays.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Compare complete JSONL gameplay snapshots, reporting the first state difference. + +Both files must be recorded after the same complete simulation update. Property +order is ignored; entity and projectile list order is part of the contract. +Original data and generated traces belong in the ignored .reference directory. +""" +import argparse +import json +from pathlib import Path + + +def first_difference(left, right, path="state"): + if type(left) is not type(right): + return path, left, right + if isinstance(left, dict): + if left.keys() != right.keys(): + return path + ".keys", sorted(left), sorted(right) + for key in sorted(left): + difference = first_difference(left[key], right[key], f"{path}.{key}") + if difference: + return difference + elif isinstance(left, list): + if len(left) != len(right): + return path + ".length", len(left), len(right) + for index, (a, b) in enumerate(zip(left, right)): + difference = first_difference(a, b, f"{path}[{index}]") + if difference: + return difference + elif left != right: + return path, left, right + return None + + +def read_trace(path): + records = [] + with Path(path).open(encoding="utf-8") as file: + for line_number, line in enumerate(file, 1): + if not line.strip(): + continue + record = json.loads(line) + if not isinstance(record, dict) or record.get("tick") != len(records) + 1: + raise ValueError(f"{path}:{line_number}: expected consecutive tick {len(records) + 1}") + records.append(record) + if not records: + raise ValueError(f"{path}: no snapshots") + return records + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("reference") + parser.add_argument("candidate") + args = parser.parse_args() + reference = read_trace(args.reference) + candidate = read_trace(args.candidate) + for tick, (left, right) in enumerate(zip(reference, candidate), 1): + difference = first_difference(left, right) + if difference: + path, a, b = difference + print(f"Divergence at tick {tick}: {path}") + print(f" reference: {a!r}") + print(f" candidate: {b!r}") + return 1 + if len(reference) != len(candidate): + print(f"Trace length differs: {len(reference)} reference steps, {len(candidate)} candidate steps") + return 1 + print(f"Identical gameplay snapshots across {len(reference)} simulation steps.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/generate_legacy_tables.py b/tools/generate_legacy_tables.py new file mode 100644 index 00000000..9faea908 --- /dev/null +++ b/tools/generate_legacy_tables.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Regenerate reviewable Rust constants from the preserved GPL engine source. +This development tool is not used by the Rust game at build or runtime. +""" +from pathlib import Path +import re +ROOT=Path(__file__).resolve().parents[1] +ids={k:int(v,16) for k,v in re.findall(r'#define\s+(FILE\w+)\s+(0x[0-9a-fA-F]+)',(ROOT/'raptor/src/fileids.h').read_text())} +enum=(ROOT/'raptor/src/objects.h').read_text().split('S_FORWARD_GUNS',1)[1].split('}OBJ_TYPE')[0] +names=['S_FORWARD_GUNS']+re.findall(r'^\s*(S_\w+)\s*[,\n]',enum,re.M) +names=[n for n in names if n!='S_LAST_OBJECT'] +values={**ids,**{n:i for i,n in enumerate(names)},'S_ALL':0,'S_AIR':1,'S_GROUND':2,'S_GRALL':3,'S_GTILE':4,'S_SUCK':5,'S_SHOOT':0,'S_LINE':1,'S_BEAM':2,'MAX_SHIELD':100} +def number(s,default=0): + s=s.strip() + if s in values:return values[s] + if re.fullmatch(r'-?\d+',s):return int(s) + if re.fullmatch(r'0x[0-9a-fA-F]+',s):return int(s,16) + if '/' in s: + a,b=s.split('/') + return number(a)//number(b) + raise ValueError(f'Unsupported numeric expression: {s}') +def blocks(file,var,start_pattern): + text=(ROOT/file).read_text(); starts=list(re.finditer(start_pattern,text));result={} + for i,m in enumerate(starts): + block=text[m.end():starts[i+1].start() if i+1(\w+)\s*=\s*([^;]+);',block): + if k in wanted: + f[k]=f.get(v.strip().removeprefix(var+'->')) if v.strip().startswith(var+'->') else number(v) + result[m[1]]=f + return result +objects=blocks('raptor/src/objects.cpp','lib',r'lib\s*=\s*&obj_lib\[(S_\w+)\];') +weapons=blocks('raptor/src/shots.cpp','slib',r'slib\s*=\s*&shot_lib\[(S_\w+)\];') +id_of=lambda n:'base:'+n[2:].lower().replace('missle','missile') +name_of=lambda n:n[2:].replace('_',' ').title().replace('Missle','Missile') +out=['// Generated by tools/generate_legacy_tables.py; source is GPL-2.0-or-later.','pub struct LegacyObject{pub index:u32,pub id:&\'static str,pub name:&\'static str,pub asset:u32,pub frames:u32,pub cost:u32,pub max_count:u32,pub initial_count:u32,pub special:bool}','pub struct LegacyWeapon{pub index:u32,pub id:&\'static str,pub name:&\'static str,pub asset:u32,pub frames:u32,pub damage:i32,pub speed:i32,pub cooldown:u32,pub target:u32,pub maxspeed:i32,pub startframe:u32,pub delay:bool,pub plot:bool,pub moving:bool,pub follow_x:bool,pub follow_y:bool,pub effect:bool,pub beam:u32}','pub fn objects()->Vec{vec!['] +for n in names: + f=objects.get(n,{}) + out.append(f'LegacyObject{{index:{values[n]},id:"{id_of(n)}",name:"{name_of(n)}",asset:{max(0,f.get("item",0))},frames:{f.get("numframes",1)},cost:{max(0,f.get("cost",0))*(f.get("start_cnt",1) if f.get("onlyflag") else 1)},max_count:{max(1,f.get("max_cnt",1))},initial_count:{max(1,f.get("start_cnt",1))},special:{str(bool(f.get("specialw",0))).lower()}}},') +out+= [']}','pub fn weapons()->Vec{vec!['] +for n,f in weapons.items(): + out.append(f'LegacyWeapon{{index:{values[n]},id:"{id_of(n)}",name:"{name_of(n)}",asset:{max(0,f.get("lumpnum",0))},frames:{f.get("numframes",1)},damage:{f.get("hits",1)},speed:{f.get("speed",0)},cooldown:{f.get("shoot_rate",1)},target:{f.get("ht",0)},maxspeed:{f.get("maxspeed",0)},startframe:{f.get("startframe",0)},delay:{str(bool(f.get("delayflag",0))).lower()},plot:{str(bool(f.get("use_plot",0))).lower()},moving:{str(bool(f.get("move_flag",0))).lower()},follow_x:{str(bool(f.get("fplrx",0))).lower()},follow_y:{str(bool(f.get("fplry",0))).lower()},effect:{str(bool(f.get("meffect",0))).lower()},beam:{f.get("beam",0)}}},') +out +=[']}'] +rap=(ROOT/'raptor/src/rap.cpp').read_text() +for name in ['o_gun1','o_gun2','o_gun3']: + block=re.search(rf'{name}\[8\]\s*=\s*\{{(.*?)\}};',rap,re.S)[1] + nums=[int(x.strip(),0) for x in block.split(',') if x.strip()] + out.append(f'pub const {name.upper()}: [i32; 8] = ['+', '.join(map(str,nums))+'];') +fx=(ROOT/'raptor/src/fx.cpp').read_text() +starts=list(re.finditer(r'lib\s*=\s*&fx_items\[(FX_\w+)\];',fx)) +out.append("pub struct LegacySound {pub name: &'static str,pub asset:u32,pub pitch:i32,pub random:bool,pub volume:i32,pub priority:i32}") +out.append('pub fn sounds()->Vec{vec![') +for i,m in enumerate(starts): + block=fx[m.end():starts[i+1].start() if i+1item\s*=\s*GLB_GetItemID\("(\w+)"\)',block) + if not item: continue + matches=[v for k,v in ids.items() if k.endswith('_'+item[1])] + if len(matches)!=1: raise ValueError(f'Ambiguous sound {item[1]}: {matches}') + pitch=int(re.search(r'lib->pitch\s*=\s*(-?\d+)',block)[1]) + random=int(re.search(r'lib->rpflag\s*=\s*(\d+)',block)[1]) + volume=int(re.search(r'lib->vol\s*=\s*(-?\d+)',block)[1]) + priority=int(re.search(r'lib->pri\s*=\s*(-?\d+)',block)[1]) + out.append(f'LegacySound{{name:"{m[1]}",asset:{matches[0]},pitch:{pitch},random:{str(bool(random)).lower()},volume:{volume},priority:{priority}}},') +out.append(']}') +audio=(ROOT/'raptor/src/i_oplmusic.cpp').read_text() +for name,rust in [('frequency_curve','FREQUENCY_CURVE'),('volume_mapping_table','VOLUME_CURVE')]: + block=re.search(rf'{name}\[\]\s*=\s*\{{(.*?)\}};',audio,re.S)[1] + block=re.sub(r'//[^\n]*','',block) + nums=[int(x.strip(),0) for x in block.split(',') if x.strip()] + out.append(f'pub const {rust}: [u16; {len(nums)}] = ['+', '.join(map(str,nums))+'];') +(ROOT/'src/legacy_tables.rs').write_text('\n'.join(out)+'\n') +print(f'Generated {len(names)} items and {len(weapons)} weapons') diff --git a/tools/hd_art_source.py b/tools/hd_art_source.py new file mode 100644 index 00000000..fb795649 --- /dev/null +++ b/tools/hd_art_source.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Decode a catalog picture into transparent PNG source references; never redraw art.""" +import argparse +import struct +from pathlib import Path +from PIL import Image + +def decode(path, palette): + data = path.read_bytes() + kind, _, _, width, height = struct.unpack_from('>4) for c in pal[i:i+3]) for i in range(0,768,3)] + size, relative = entries[args.asset] + source = (args.data / relative).resolve() + if not source.is_relative_to(args.data.resolve()) or source.stat().st_size != size: + raise ValueError('invalid catalog entry') + image = decode(source, palette) + if args.preview_scale < 1 or args.preview_scale > 32: + raise ValueError('preview scale must be 1..32') + if args.preview_scale != 1: + image = image.resize((image.width * args.preview_scale, image.height * args.preview_scale), Image.Resampling.NEAREST) + args.output.parent.mkdir(parents=True, exist_ok=True) + image.save(args.output) + print(f'{args.asset:05x}: {image.width}x{image.height} -> {args.output}') +if __name__ == '__main__': + main()