From 93075ab1fd1eed4b45007c1dc230a46d15470d79 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Mon, 16 Nov 2026 23:34:05 +0100 Subject: [PATCH] Add design persistence, world rendering, metrics overlay and logs M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans. --- .gitignore | 3 +- Cargo.lock | 2919 +++++++++++++++++++ Cargo.toml | 4 + TODO.md | 69 +- crates/app/Cargo.toml | 4 + crates/app/src/main.rs | 4 +- crates/app/src/runtime/application/mod.rs | 320 ++ crates/app/src/runtime/camera/input.rs | 95 + crates/app/src/runtime/camera/mod.rs | 137 + crates/app/src/runtime/camera/tests.rs | 103 + crates/app/src/runtime/config/mod.rs | 193 ++ crates/app/src/runtime/config/tests.rs | 155 + crates/app/src/runtime/devlog/mod.rs | 153 + crates/app/src/runtime/devlog/startup.rs | 66 + crates/app/src/runtime/devlog/tests.rs | 120 + crates/app/src/runtime/error.rs | 62 + crates/app/src/runtime/gpu.rs | 148 + crates/app/src/runtime/metrics/csv.rs | 141 + crates/app/src/runtime/metrics/mod.rs | 237 ++ crates/app/src/runtime/metrics/panel.rs | 153 + crates/app/src/runtime/metrics/proc.rs | 63 + crates/app/src/runtime/metrics/tests.rs | 247 ++ crates/app/src/runtime/mod.rs | 102 +- crates/app/src/runtime/scene.rs | 52 + crates/app/src/runtime/sim/mod.rs | 162 + crates/app/src/runtime/sim/pacing.rs | 102 + crates/app/src/runtime/sim/tests.rs | 41 + crates/core/src/units/mod.rs | 11 + crates/core/src/units/tests.rs | 7 + crates/materials/src/db/mod.rs | 90 +- crates/materials/src/db/tests.rs | 56 + crates/materials/src/massprops/mod.rs | 145 +- crates/materials/src/massprops/tests.rs | 222 ++ crates/materials/src/strength/mod.rs | 51 +- crates/materials/src/strength/tests.rs | 43 + crates/modes/Cargo.toml | 3 + crates/modes/tests/box_drops.rs | 129 + crates/modes/tests/joint_control.rs | 150 + crates/modes/tests/terrain_rest.rs | 129 + crates/physics/Cargo.toml | 1 + crates/physics/src/backend/mod.rs | 150 +- crates/physics/src/joints/mod.rs | 50 +- crates/physics/src/lib.rs | 4 + crates/physics/src/rapier/mod.rs | 269 +- crates/physics/src/rapier/tests.rs | 285 ++ crates/render/Cargo.toml | 3 + crates/render/src/camera.rs | 128 + crates/render/src/ctx/mod.rs | 1 - crates/render/src/error.rs | 37 + crates/render/src/gpu/mod.rs | 100 + crates/render/src/instancing/mod.rs | 1 - crates/render/src/lib.rs | 27 +- crates/render/src/overlay/atlas.rs | 193 ++ crates/render/src/overlay/mod.rs | 123 + crates/render/src/overlay/pass/geometry.rs | 106 + crates/render/src/overlay/pass/mod.rs | 327 +++ crates/render/src/overlay/pass/overlay.wgsl | 29 + crates/render/src/overlay/tests.rs | 156 + crates/render/src/overlay/text.rs | 136 + crates/render/src/renderer/mod.rs | 306 ++ crates/render/src/renderer/pipeline.rs | 274 ++ crates/render/src/renderer/shader.wgsl | 48 + crates/render/src/renderer/target.rs | 149 + crates/render/src/renderer/tests.rs | 135 + crates/render/src/scene.rs | 80 + crates/render/src/terrain/mod.rs | 1 - crates/render/src/views/mod.rs | 1 - crates/scene/Cargo.toml | 2 + crates/scene/src/import/mesh.rs | 275 ++ crates/scene/src/import/mod.rs | 19 +- crates/scene/src/import/obj.rs | 134 + crates/scene/src/import/stl.rs | 256 ++ crates/scene/src/import/tests.rs | 283 ++ crates/scene/src/model/mass.rs | 114 + crates/scene/src/model/mesh.rs | 84 + crates/scene/src/model/mod.rs | 194 +- crates/scene/src/model/persist.rs | 76 + crates/scene/src/model/tests.rs | 223 ++ crates/scene/tests/mesh_mass.rs | 87 + crates/scene/tests/persistence.rs | 229 ++ crates/sensors/src/delay.rs | 35 + crates/sensors/src/encoder/mod.rs | 140 +- crates/sensors/src/encoder/tests.rs | 176 ++ crates/sensors/src/imu/mod.rs | 138 +- crates/sensors/src/imu/tests.rs | 139 + crates/sensors/src/lib.rs | 1 + crates/sensors/src/noise/mod.rs | 70 +- crates/sensors/src/noise/tests.rs | 74 + crates/storage/Cargo.toml | 2 + crates/storage/src/blob/mod.rs | 144 +- crates/storage/src/blob/tests.rs | 99 + crates/storage/src/format/mod.rs | 124 +- crates/storage/src/format/tests.rs | 90 + crates/storage/src/migrate/mod.rs | 102 +- crates/storage/src/migrate/tests.rs | 94 + crates/storage/src/project/mod.rs | 105 +- crates/storage/src/project/tests.rs | 94 + crates/worldgen/src/noise/mod.rs | 122 +- crates/worldgen/src/noise/tests.rs | 96 + crates/worldgen/src/terrain/mod.rs | 350 ++- crates/worldgen/src/terrain/tests.rs | 330 +++ docs/CLI.md | 116 + docs/CODE_RULES.md | 35 + docs/DECISIONS.md | 4 + docs/LOGGING.md | 93 + docs/NETWORK.md | 68 + docs/README.md | 3 + 107 files changed, 14785 insertions(+), 46 deletions(-) create mode 100644 crates/app/src/runtime/application/mod.rs create mode 100644 crates/app/src/runtime/camera/input.rs create mode 100644 crates/app/src/runtime/camera/mod.rs create mode 100644 crates/app/src/runtime/camera/tests.rs create mode 100644 crates/app/src/runtime/config/mod.rs create mode 100644 crates/app/src/runtime/config/tests.rs create mode 100644 crates/app/src/runtime/devlog/mod.rs create mode 100644 crates/app/src/runtime/devlog/startup.rs create mode 100644 crates/app/src/runtime/devlog/tests.rs create mode 100644 crates/app/src/runtime/error.rs create mode 100644 crates/app/src/runtime/gpu.rs create mode 100644 crates/app/src/runtime/metrics/csv.rs create mode 100644 crates/app/src/runtime/metrics/mod.rs create mode 100644 crates/app/src/runtime/metrics/panel.rs create mode 100644 crates/app/src/runtime/metrics/proc.rs create mode 100644 crates/app/src/runtime/metrics/tests.rs create mode 100644 crates/app/src/runtime/scene.rs create mode 100644 crates/app/src/runtime/sim/mod.rs create mode 100644 crates/app/src/runtime/sim/pacing.rs create mode 100644 crates/app/src/runtime/sim/tests.rs create mode 100644 crates/materials/src/db/tests.rs create mode 100644 crates/materials/src/massprops/tests.rs create mode 100644 crates/materials/src/strength/tests.rs create mode 100644 crates/modes/tests/box_drops.rs create mode 100644 crates/modes/tests/joint_control.rs create mode 100644 crates/modes/tests/terrain_rest.rs create mode 100644 crates/physics/src/rapier/tests.rs create mode 100644 crates/render/src/camera.rs delete mode 100644 crates/render/src/ctx/mod.rs create mode 100644 crates/render/src/error.rs create mode 100644 crates/render/src/gpu/mod.rs delete mode 100644 crates/render/src/instancing/mod.rs create mode 100644 crates/render/src/overlay/atlas.rs create mode 100644 crates/render/src/overlay/mod.rs create mode 100644 crates/render/src/overlay/pass/geometry.rs create mode 100644 crates/render/src/overlay/pass/mod.rs create mode 100644 crates/render/src/overlay/pass/overlay.wgsl create mode 100644 crates/render/src/overlay/tests.rs create mode 100644 crates/render/src/overlay/text.rs create mode 100644 crates/render/src/renderer/mod.rs create mode 100644 crates/render/src/renderer/pipeline.rs create mode 100644 crates/render/src/renderer/shader.wgsl create mode 100644 crates/render/src/renderer/target.rs create mode 100644 crates/render/src/renderer/tests.rs create mode 100644 crates/render/src/scene.rs delete mode 100644 crates/render/src/terrain/mod.rs delete mode 100644 crates/render/src/views/mod.rs create mode 100644 crates/scene/src/import/mesh.rs create mode 100644 crates/scene/src/import/obj.rs create mode 100644 crates/scene/src/import/stl.rs create mode 100644 crates/scene/src/import/tests.rs create mode 100644 crates/scene/src/model/mass.rs create mode 100644 crates/scene/src/model/mesh.rs create mode 100644 crates/scene/src/model/persist.rs create mode 100644 crates/scene/src/model/tests.rs create mode 100644 crates/scene/tests/mesh_mass.rs create mode 100644 crates/scene/tests/persistence.rs create mode 100644 crates/sensors/src/delay.rs create mode 100644 crates/sensors/src/encoder/tests.rs create mode 100644 crates/sensors/src/imu/tests.rs create mode 100644 crates/sensors/src/noise/tests.rs create mode 100644 crates/storage/src/blob/tests.rs create mode 100644 crates/storage/src/format/tests.rs create mode 100644 crates/storage/src/migrate/tests.rs create mode 100644 crates/storage/src/project/tests.rs create mode 100644 crates/worldgen/src/noise/tests.rs create mode 100644 crates/worldgen/src/terrain/tests.rs create mode 100644 docs/CLI.md create mode 100644 docs/LOGGING.md create mode 100644 docs/NETWORK.md diff --git a/.gitignore b/.gitignore index 8e0d778..bbed154 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ target/ *.snap.tmp ref/ -fabrilis-docs.zip +fabrilis-metrics.csv +fabrilis-dev.log diff --git a/Cargo.lock b/Cargo.lock index 0d88b63..1c04b03 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,439 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[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" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "downcast-rs" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "ena" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabffdaee24bd1bf95c5ef7cec31260444317e72ea56c4c91750e8b7ee58d5f1" +dependencies = [ + "log", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "fabrilis-actuators" version = "0.0.1" @@ -41,10 +474,14 @@ dependencies = [ "fabrilis-core", "fabrilis-limits", "fabrilis-modes", + "fabrilis-physics", "fabrilis-platform", "fabrilis-render", "fabrilis-storage", "fabrilis-ui", + "fabrilis-worldgen", + "pollster", + "winit", ] [[package]] @@ -103,6 +540,7 @@ dependencies = [ "fabrilis-platform", "fabrilis-scene", "fabrilis-scripting", + "fabrilis-sensors", "fabrilis-soc", "fabrilis-storage", "fabrilis-structure", @@ -127,6 +565,7 @@ version = "0.0.1" dependencies = [ "fabrilis-core", "fabrilis-limits", + "rapier3d-f64", ] [[package]] @@ -141,8 +580,11 @@ dependencies = [ name = "fabrilis-render" version = "0.0.1" dependencies = [ + "bytemuck", "fabrilis-core", "fabrilis-limits", + "fontdue", + "wgpu", ] [[package]] @@ -153,6 +595,8 @@ dependencies = [ "fabrilis-limits", "fabrilis-materials", "fabrilis-storage", + "ron", + "serde", ] [[package]] @@ -186,6 +630,8 @@ version = "0.0.1" dependencies = [ "fabrilis-core", "fabrilis-limits", + "ron", + "serde", ] [[package]] @@ -233,8 +679,2481 @@ dependencies = [ "fabrilis-limits", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "fontdue" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e796cb6894e6418daacea84b28dd4f98d3b32c74d5bb452ba1ecfbf5ad8e84ca" +dependencies = [ + "hashbrown 0.15.5", + "ttf-parser", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[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 = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.6", + "windows-link", +] + +[[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 = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glam" +version = "0.30.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9" + +[[package]] +name = "glam" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556f6b2ea90b8d15a74e0e7bb41671c9bdf38cd9f78c284d750b9ce58a2b5be7" + +[[package]] +name = "glam" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0" + +[[package]] +name = "glam" +version = "0.33.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37bfe73dc8ec21f54d181e5a60554327ec3f1c600c455a75ccbfc65d2106a6c4" +dependencies = [ + "approx", + "libm", +] + +[[package]] +name = "glamx" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d74079318e3a077bd3d15faa90fde24fa37bb9f157f92f853e6019a15fd413" +dependencies = [ + "approx", + "glam 0.33.12", + "nalgebra", + "num-traits", + "simba", +] + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32", + "stable_deref_trait", +] + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + [[package]] name = "libm" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matrixmultiply" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" +dependencies = [ + "autocfg", + "rawpointer", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "naga" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd0dd362bf26c0ffdd143df6da66a25d287e196eff482f117771010b207ad163" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14474170feb673cfb18b3565111a9869797cc1d290fb9ec969c53f5e1e231c6d" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash", + "thiserror 2.0.21", +] + +[[package]] +name = "nalgebra" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adc43a60c217b0c6ff46e47f26911015ad8d2e5a8be1af668c67e370d99a4346" +dependencies = [ + "approx", + "glam 0.30.10", + "glam 0.31.1", + "glam 0.32.1", + "glam 0.33.12", + "matrixmultiply", + "nalgebra-macros", + "num-complex", + "num-rational", + "num-traits", + "simba", + "typenum", +] + +[[package]] +name = "nalgebra-macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "973e7178a678cfd059ccec50887658d482ce16b0aa9da3888ddeab5cd5eb4889" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-derive" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e98dc3b890f6c23a0f9d3d491a2823d0dea0fa656302a13dd225fa924112a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +dependencies = [ + "num-traits", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "parry3d-f64" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb9e04261f1783d8f66f36767b2b73132a63c9b30b12a5ed47e1faa240f7591" +dependencies = [ + "approx", + "arrayvec", + "bitflags 2.13.2", + "downcast-rs 2.0.2", + "either", + "ena", + "foldhash 0.2.0", + "glamx", + "hashbrown 0.17.1", + "indexmap", + "log", + "num-derive", + "num-traits", + "ordered-float", + "rstar", + "simba", + "slab", + "smallvec", + "spade", + "thiserror 2.0.21", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[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 = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[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 = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "rapier3d-f64" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4588855e9c5451702147b5c6ddff4d93887f1e59c9504b6ac3571818f6ec3d2" +dependencies = [ + "approx", + "arrayvec", + "bitflags 2.13.2", + "glamx", + "log", + "nalgebra", + "num-traits", + "parry3d-f64", + "profiling", + "serde", + "simba", + "static_assertions", + "thiserror 2.0.21", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "robust" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839" + +[[package]] +name = "ron" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97b3fe97c18ff24299ea56f802c5693eb34266fb0bc8317f4e101debc8a3ceaf" +dependencies = [ + "bitflags 2.13.2", + "serde", + "serde_derive", + "typeid", + "unicode-ident", +] + +[[package]] +name = "rstar" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90e7279515baf3838062fa9c495a408bc2f3abbf9cd2ac8c2d4108b90fa29b89" +dependencies = [ + "heapless", + "num-traits", + "smallvec", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "safe_arch" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit", + "tiny-skia", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.10", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simba" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a7200d82ff1c7b4235efd12f11e2537a402c91cf83a5cb97ce80eef787fde7" +dependencies = [ + "approx", + "libm", + "num-complex", + "num-traits", + "wide", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop", + "calloop-wayland-source", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "spade" +version = "2.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9699399fd9349b00b184f5635b074f9ec93afffef30c853f8c875b32c0f8c7fa" +dependencies = [ + "hashbrown 0.16.1", + "num-traits", + "robust", + "smallvec", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" + +[[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.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[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.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[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.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs 1.2.1", + "rustix 1.1.6", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.6", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.6", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[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 = "wgpu" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146fc3d654250e6207921a66c87534c621bc886c70df83dcf466c1d66813810e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "naga", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad661da2ee99f208c30090b585284b2ab5b8bf2358ddf2d2215592808ec62f1a" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d3f2f24aee039ffe9ef527300daf6b7428c58edeefdaa1700f4fa0fd754df16" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ccf093bd215ae9dc4f96df293e675513ac1f2569f8293a2911cc34ca3505d1" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1331b08fa2362c5d454eccc4448e6e4f01eccfea569a00e310adbfc4415f2bdc" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a57452fe453658e141aafdb09de1028afa498805fab518238ddf372a518813ff" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44a62ead68aad7cd40ac9e2cd2b8ec64f32dfbad2765f429b9fb74b8b735869f" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9f6ee0bd50f5ab79fb8c25e3f33afb27126f034af4ba5909c7a0967058659e6" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "wide" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d920ac99c3c8edce110cb8d07dbb324d6d026011dce85b1e9355b70f0adacc4f" +dependencies = [ + "bytemuck", + "safe_arch", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[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 = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2 0.5.1", + "bytemuck", + "calloop", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit", + "objc2-foundation 0.2.2", + "objc2-ui-kit", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "smithay-client-toolkit", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.6", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] diff --git a/Cargo.toml b/Cargo.toml index e829198..c63e9b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,3 +24,7 @@ too_many_lines = "warn" too_many_arguments = "warn" cognitive_complexity = "warn" allow_attributes_without_reason = "warn" + +# Dependencies stay optimized in dev: Rapier and wgpu are unusable at opt-level 0. +[profile.dev.package."*"] +opt-level = 3 diff --git a/TODO.md b/TODO.md index 0136cbc..a8dd923 100644 --- a/TODO.md +++ b/TODO.md @@ -10,35 +10,41 @@ `core::math` поверх `libm`, `core::sched` (эпохи, точки синхронизации), `core::fidelity`, `core::snapshot`, `core::id`, golden-тест детерминизма. -## M2 — Один шарнир +## M2 — Один шарнир (готово) Цель: замкнутый контур «сценарий → мотор → шарнир → датчик → регулятор» без мира, рендера и электроники. Это проверка того, что ядро, физика и мост данных стыкуются. - [x] `core::vec`: `Vec3`, `Mat3`, `Quat`, `Transform` (f64, через `core::math`) - [x] `core::units`: `Radians`; `RadiansPerSecond` и `NewtonMeters` — вместе с шарниром - [x] `core::rng`: seeded генератор (xoshiro256** через SplitMix64) для тестов и Monte Carlo -- [ ] `physics`: трейт `PhysicsBackend` + Rapier, один шарнир с мотором -- [ ] `sensors`: энкодер и IMU (минимум: шум, задержка, дискретизация) -- [ ] сценарий на Rust (Rhai позже): PD-регулятор по энкодеру -- **DoD:** headless-тест поднимает звено в заданный угол, ошибка < 2 %, golden-хеш - состояния; работает без окна и GPU. +- [x] `physics`: трейт `PhysicsBackend` + Rapier, один шарнир с мотором +- [x] `sensors`: энкодер и IMU (шум, смещение, задержка, квантование); IMU пока + одноосный по Z, три оси — когда понадобится сценарию +- [x] сценарий на Rust (Rhai позже): PD-регулятор по энкодеру +- **DoD выполнен:** headless-тест поднимает звено из 60° в 0°, ошибка 0.013 рад + (0.7 %), золотой хеш закреплён; без окна и GPU. -## M3 — Деталь и конструкция +## M3 — Деталь и конструкция (DoD выполнен) Цель: собрать конструкцию из настоящих мешей и сохранить её. -- [ ] импорт STL и OBJ, проверка меша (замкнутость, ориентация, единицы) -- [ ] масса, COM, тензор инерции по мешу (+ property-тесты на сферах и кубах) -- [ ] материалы (плотность, прочность, теплопроводность) -- [ ] формат сцены и конструкции (RON), `storage` с миграциями +- [x] импорт STL и OBJ, проверка меша (замкнутость, ориентация, единицы) +- [x] масса, COM, тензор инерции по мешу (+ property-тесты на сферах и кубах) +- [x] материалы: плотность, модуль Юнга, предел текучести, база сталь/алюминий/PLA +- [x] формат сцены и конструкции (RON), `storage`: blob по хешу, версии, миграции - [ ] `parts`: библиотека деталей, минимальный BOM -- **DoD:** тележка из трёх STL-деталей собирается, сохраняется и загружается; - масса сходится с аналитикой в пределах 1 %. +- **DoD выполнен:** три STL-детали собираются, сохраняются в папку проекта и + загружаются; масса 68.2 кг сходится с аналитикой в пределах 1 %, миграция v0→v1 + проверена тестом. Осталась библиотека деталей и BOM — это уходит в M10. ## M4 — Мир и картинка Цель: та же конструкция едет по террейну в окне. -- [ ] `worldgen`: высотная карта, чанки, коллайдеры -- [ ] `render`: wgpu, clipmap, инстансинг +- [x] `worldgen`: высотная карта, коллайдеры (trimesh), golden-хеш; чанки — вместе с рендером +- [x] `render`: wgpu, окно, глубина, меш рельефа, инстансинг кубов, offscreen-тесты; + clipmap LOD — позже, отдельным шагом - [ ] `ui`: список команд рисования, glyph atlas, event-driven redraw, оверлей отладки (текст через `fontdue`, прямоугольники, линии, клип) -- [ ] `app`: winit, главный цикл, режим World +- [x] `app`: winit, окно 1280×720, событийный цикл, World-сцена с рельефом и кубом + (физика в окне — следующий шаг) +- [ ] профилировать простой: почему иногда подпрыгивает нагрузка при стоящих кубах + (сон тел, островки контактов, оверлей); писать пики в лог (LOGGING.md) - **DoD:** тележка едет по склону; RTF ≥ 1 на эталонной сцене (см. бюджет в ARCHITECTURE.md); картинка не влияет на результат симуляции. @@ -95,3 +101,34 @@ ## Открытые вопросы См. docs/DECISIONS.md. + +## Позже — сетевой режим +Подробности: [docs/NETWORK.md](docs/NETWORK.md). Сервер ведёт авторитетную +симуляцию, клиенты смотрят и управляют по сети. + +- [ ] S1: headless-сервер, мир тикает без окна +- [ ] S2: снапшоты по сети, один клиент рисует состояние сервера +- [ ] S3: несколько клиентов с разными камерами +- [ ] S4: ввод одного клиента, подтверждение и отказ при разрыве +- [ ] S5: интернет, дельты, переподключение, токен + +## Диагностика и логи (сразу после M4d) +- [ ] `core::log`: уровни, приёмник, макросы; выключенный уровень не форматирует строку +- [x] приложение: CSV метрик и dev-лог по флагам (`--metrics-log`, `--log`, `--dev`, `--append`) +- [ ] `core::log`-фасад и приёмник: перевести приложение, затем добавлять логи в crate'ах +- [ ] логи в ключевых точках: старт и конфиг, деградации, ошибки, сводки раз в секунду, пики +- [ ] тест: golden-хеш симуляции не зависит от включённых логов +- **DoD:** в библиотеках нет `println!`, `--dev` даёт debug/trace, обычный запуск — warn/info; + выключенный уровень не строит строку + +## Headless CLI и обучение контроллеров (после M4d) +Подробности: [docs/CLI.md](docs/CLI.md). Отдельный бинарник без окна и GPU; общий +код прогонов — в `modes`. + +- [ ] C1: `fabrilis-cli` + `simulate`, CSV на выходе, golden-хеш +- [ ] C2: `validate` и коды возврата (1 — провал допуска) +- [ ] C3: `sweep` и Monte Carlo по процессам +- [ ] C4: протокол команд JSON-RPC (stdio/Unix-сокет) + `repl` для внешнего управления +- [ ] C5: `serve` — headless-сервер (стыкуется с NETWORK.md S1) +- [ ] C6: MCP-адаптер поверх команд (агент/нейросеть рулит движком) +- **DoD C1:** тот же мир без окна, результат совпадает с GUI-прогоном по seed. diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index e8cfe18..505095f 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -14,8 +14,12 @@ fabrilis-core = { path = "../core" } fabrilis-platform = { path = "../platform" } fabrilis-storage = { path = "../storage" } fabrilis-modes = { path = "../modes" } +fabrilis-physics = { path = "../physics" } fabrilis-render = { path = "../render" } fabrilis-ui = { path = "../ui" } +fabrilis-worldgen = { path = "../worldgen" } +winit = "0.30" +pollster = "0.4" [build-dependencies] fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index a32e8ae..3cf010a 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -1,3 +1,3 @@ -fn main() { - println!("fabrilis: скелет проекта, см. TODO.md"); +fn main() -> Result<(), fabrilis_app::runtime::AppError> { + fabrilis_app::runtime::run() } diff --git a/crates/app/src/runtime/application/mod.rs b/crates/app/src/runtime/application/mod.rs new file mode 100644 index 0000000..c2b3f10 --- /dev/null +++ b/crates/app/src/runtime/application/mod.rs @@ -0,0 +1,320 @@ +//! The application handler: window installation, resize, redraw and logging. + +use std::sync::Arc; +use std::time::Duration; + +use fabrilis_render::Overlay; +use winit::application::ApplicationHandler; +use winit::dpi::PhysicalSize; +use winit::event::{ElementState, KeyEvent, MouseButton, WindowEvent}; +use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; +use winit::keyboard::{KeyCode, PhysicalKey}; +use winit::window::{Window, WindowId}; + +use super::camera::Controls; +use super::config::Config; +use super::devlog::{self, DevLog, Level}; +use super::gpu::WindowRenderer; +use super::metrics::{CsvLog, FrameWork, Metrics, Row, Stopwatch, spike_reason, unix_now}; +use super::scene::View; +use super::sim::Simulation; +use super::{AppError, aspect, log_startup}; + +/// Runs the window loop until the user closes the window or presses Escape. +pub(super) fn run() -> Result<(), AppError> { + let config = super::parse_config(); + let csv = super::open_csv(&config)?; + let level = if config.dev { + Level::Debug + } else { + Level::Info + }; + let dev = match &config.log { + Some(path) => Some( + DevLog::open(path, level, config.append) + .map_err(|error| AppError::Log(format!("{}: {error}", path.display())))?, + ), + None => None, + }; + let event_loop = EventLoop::new().map_err(|error| AppError::EventLoop(error.to_string()))?; + event_loop.set_control_flow(ControlFlow::Poll); + let mut application = Fabrilis::new(config, csv, dev); + let result = event_loop.run_app(&mut application); + if let Err(error) = &result { + application.report("event loop", &error.to_string()); + } + application.finish(); + result.map_err(|error| AppError::EventLoop(error.to_string())) +} + +/// The window state plus the diagnostics that observe it. +struct Fabrilis { + config: Config, + csv: Option, + dev: Option, + frame: u64, + window: Option>, + renderer: Option, + view: Option, + simulation: Option, + controls: Controls, + metrics: Metrics, + overlay: Overlay, +} + +impl Fabrilis { + fn new(config: Config, csv: Option, dev: Option) -> Self { + Self { + config, + csv, + dev, + frame: 0, + window: None, + renderer: None, + view: None, + simulation: None, + controls: Controls::default(), + metrics: Metrics::default(), + overlay: Overlay::new(), + } + } + + fn install(&mut self, event_loop: &ActiveEventLoop) -> Result<(), AppError> { + let attributes = Window::default_attributes() + .with_title("Fabrilis — RTF ...") + .with_inner_size(PhysicalSize::new(1280, 720)); + let window = Arc::new( + event_loop + .create_window(attributes) + .map_err(|error| AppError::Window(error.to_string()))?, + ); + let mut view = super::scene::build(aspect(window.inner_size()))?; + let simulation = Simulation::new(&view.terrain, &view.heightmap, &mut view.scene)?; + let renderer = WindowRenderer::new(window.clone())?; + log_startup(self.dev.as_mut(), &self.config, &view, &renderer, &window); + self.window = Some(window); + self.renderer = Some(renderer); + self.view = Some(view); + self.simulation = Some(simulation); + Ok(()) + } + + fn resize(&mut self, size: PhysicalSize) { + let result = match &mut self.renderer { + Some(renderer) => renderer.resize(size.width, size.height), + None => return, + }; + if let Err(error) = result { + eprintln!("fabrilis: resize failed: {error}"); + self.report("resize", &error.to_string()); + return; + } + if let Some(view) = &mut self.view { + view.camera.set_aspect(aspect(size)); + } + if let Some(window) = &self.window { + window.request_redraw(); + } + } + + fn redraw(&mut self) { + let Some(view) = self.view.as_mut() else { + return; + }; + let Some(simulation) = self.simulation.as_mut() else { + return; + }; + let unix_s = if self.csv.is_some() { + Some(unix_now()) + } else { + None + }; + let frame_time = self.metrics.frame_time(); + let physics_start = Stopwatch::start(); + let frame = simulation.advance(&mut view.scene); + let physics = physics_start.elapsed(); + let slowest_step_ms = simulation.slowest_step().as_secs_f32() * 1000.0; + let sim_seconds = simulation.sim_seconds(); + let motion = self.controls.motion(frame.elapsed_seconds); + view.camera.apply(motion); + if let (Some(rtf), Some(window)) = (frame.rtf, &self.window) { + window.set_title(&format!("Fabrilis — RTF {rtf:.2}")); + } + self.metrics.set_rtf(frame.rtf); + let camera = view.camera.view(); + let size = self + .renderer + .as_ref() + .map_or((0, 0), |renderer| renderer.size()); + self.overlay.clear(); + if size.0 > 0 && size.1 > 0 { + self.metrics.draw_panel(&mut self.overlay); + } + let Some(renderer) = self.renderer.as_mut() else { + return; + }; + let render_start = Stopwatch::start(); + let draw = renderer.draw(&view.scene, &camera, &self.overlay); + let render = render_start.elapsed(); + if let Err(error) = draw { + eprintln!("fabrilis: draw failed: {error}"); + write_dev(&mut self.dev, Level::Error, "render", &error.to_string()); + } + let recorded = self.metrics.record( + frame_time, + FrameWork { + physics, + render, + steps: frame.steps, + }, + ); + if !recorded { + return; + } + self.frame = self.frame.saturating_add(1); + self.log_frame(frame_time, slowest_step_ms, sim_seconds, unix_s); + } + + /// Writes the CSV row and the dev-log summary and spike lines for one frame. + /// + /// Both observers run after the frame was drawn and only read the metrics + /// that the overlay already computed. + fn log_frame( + &mut self, + frame_time: Duration, + slowest_step_ms: f32, + sim_seconds: f64, + unix_s: Option, + ) { + let stats = self.metrics.stats(); + let frame_ms = frame_time.as_secs_f32() * 1000.0; + let spike = spike_reason(frame_ms, slowest_step_ms); + if let Some(unix_s) = unix_s { + let row = Row { + unix_s, + t_s: sim_seconds, + frame: self.frame, + stats: &stats, + spike: spike.is_some(), + }; + if let Some(csv) = self.csv.as_mut() + && let Err(error) = csv.record(&row) + { + eprintln!("fabrilis: metrics log write failed: {error}"); + write_dev(&mut self.dev, Level::Error, "metrics", &error.to_string()); + } + } + if let Some(dev) = self.dev.as_mut() { + if dev.summary_due() { + write_line(dev, Level::Info, "metrics", &devlog::summary(&stats)); + } + if let Some(trigger) = spike { + let line = devlog::spike(self.frame, frame_ms, slowest_step_ms, trigger); + write_line(dev, Level::Warn, "spike", &line); + } + } + } + + /// Logs a failure with its context before the loop gives up on the step. + fn report(&mut self, context: &str, detail: &str) { + write_dev( + &mut self.dev, + Level::Error, + "app", + &format!("{context}: {detail}"), + ); + } + + /// Flushes the CSV and closes the dev session. + fn finish(&mut self) { + if let Some(csv) = self.csv.as_mut() + && let Err(error) = csv.flush() + { + eprintln!("fabrilis: metrics log flush failed: {error}"); + } + write_dev(&mut self.dev, Level::Info, "app", "session end"); + } + + fn is_escape(event: &KeyEvent) -> bool { + event.state == ElementState::Pressed + && event.physical_key == PhysicalKey::Code(KeyCode::Escape) + } + + fn key(&mut self, event: &KeyEvent) { + if let PhysicalKey::Code(code) = event.physical_key { + self.controls + .key(code, event.state == ElementState::Pressed); + } + } +} + +/// Writes one dev-log line and reports a write failure on stderr. +fn write_line(dev: &mut DevLog, level: Level, target: &str, message: &str) { + if let Err(error) = dev.write(level, target, message) { + eprintln!("fabrilis: dev log write failed: {error}"); + } +} + +/// Writes one dev-log line when the log is enabled. +fn write_dev(dev: &mut Option, level: Level, target: &str, message: &str) { + if let Some(dev) = dev { + write_line(dev, level, target, message); + } +} + +impl ApplicationHandler for Fabrilis { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.window.is_some() { + return; + } + if let Err(error) = self.install(event_loop) { + eprintln!("fabrilis: startup failed: {error}"); + self.report("startup", &error.to_string()); + event_loop.exit(); + return; + } + if let Some(window) = &self.window { + window.request_redraw(); + } + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + _window_id: WindowId, + event: WindowEvent, + ) { + match event { + WindowEvent::CloseRequested => event_loop.exit(), + WindowEvent::KeyboardInput { event, .. } if Self::is_escape(&event) => { + event_loop.exit(); + } + WindowEvent::KeyboardInput { event, .. } => self.key(&event), + WindowEvent::MouseInput { + state, + button: MouseButton::Left, + .. + } => self.controls.mouse(state), + WindowEvent::CursorMoved { position, .. } => { + self.controls.cursor_moved(position.x, position.y); + } + WindowEvent::Focused(false) => self.controls.release_all(), + WindowEvent::Resized(size) => self.resize(size), + WindowEvent::ScaleFactorChanged { .. } => { + let size = self + .window + .as_ref() + .map_or(PhysicalSize::new(0, 0), |window| window.inner_size()); + self.resize(size); + } + WindowEvent::RedrawRequested => self.redraw(), + _ => {} + } + } + + fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) { + if let Some(window) = &self.window { + window.request_redraw(); + } + } +} diff --git a/crates/app/src/runtime/camera/input.rs b/crates/app/src/runtime/camera/input.rs new file mode 100644 index 0000000..13bb2e2 --- /dev/null +++ b/crates/app/src/runtime/camera/input.rs @@ -0,0 +1,95 @@ +//! Keyboard and mouse state mapped to camera motion. + +use winit::event::ElementState; +use winit::keyboard::KeyCode; + +use super::Motion; + +/// Radians of rotation per pixel of mouse drag. +const LOOK_SENSITIVITY: f32 = 0.0035; + +/// Which movement keys are held and how far the mouse was dragged. +#[derive(Default)] +pub(crate) struct Controls { + forward: bool, + back: bool, + left: bool, + right: bool, + up: bool, + down: bool, + fast: bool, + dragging: bool, + cursor: Option<[f64; 2]>, + turn: [f32; 2], +} + +impl Controls { + /// Tracks a movement or modifier key. + pub(crate) fn key(&mut self, code: KeyCode, pressed: bool) { + match code { + KeyCode::KeyW | KeyCode::ArrowUp => self.forward = pressed, + KeyCode::KeyS | KeyCode::ArrowDown => self.back = pressed, + KeyCode::KeyA | KeyCode::ArrowLeft => self.left = pressed, + KeyCode::KeyD | KeyCode::ArrowRight => self.right = pressed, + KeyCode::KeyE => self.up = pressed, + KeyCode::KeyQ => self.down = pressed, + KeyCode::ShiftLeft | KeyCode::ShiftRight => self.fast = pressed, + _ => {} + } + } + + /// Starts or stops a left-button drag. + pub(crate) fn mouse(&mut self, state: ElementState) { + self.dragging = state == ElementState::Pressed; + if !self.dragging { + self.cursor = None; + } + } + + /// Accumulates a drag delta while the left button is held. + pub(crate) fn cursor_moved(&mut self, x: f64, y: f64) { + if self.dragging + && let Some([last_x, last_y]) = self.cursor + { + self.turn[0] += (x - last_x) as f32 * LOOK_SENSITIVITY; + self.turn[1] -= (y - last_y) as f32 * LOOK_SENSITIVITY; + } + self.cursor = Some([x, y]); + } + + /// Drops held keys and drags when the window loses focus. + pub(crate) fn release_all(&mut self) { + self.forward = false; + self.back = false; + self.left = false; + self.right = false; + self.up = false; + self.down = false; + self.fast = false; + self.dragging = false; + self.cursor = None; + self.turn = [0.0, 0.0]; + } + + /// Builds this frame's motion and consumes the accumulated look deltas. + pub(crate) fn motion(&mut self, seconds: f32) -> Motion { + let [yaw, pitch] = self.turn; + self.turn = [0.0, 0.0]; + Motion { + forward: axis(self.forward, self.back), + strafe: axis(self.right, self.left), + lift: axis(self.up, self.down), + yaw, + pitch, + seconds, + fast: self.fast, + } + } +} + +/// `+1` when the positive key is held, `-1` when the negative one is. +fn axis(positive: bool, negative: bool) -> f32 { + let positive = if positive { 1.0 } else { 0.0 }; + let negative = if negative { 1.0 } else { 0.0 }; + positive - negative +} diff --git a/crates/app/src/runtime/camera/mod.rs b/crates/app/src/runtime/camera/mod.rs new file mode 100644 index 0000000..1f83736 --- /dev/null +++ b/crates/app/src/runtime/camera/mod.rs @@ -0,0 +1,137 @@ +//! Fly camera with yaw/pitch controls for the window. + +mod input; + +#[cfg(test)] +mod tests; + +pub(crate) use input::Controls; + +use fabrilis_core::math; +use fabrilis_render::Camera; + +/// Horizontal movement speed, metres per second. +const MOVE_SPEED: f32 = 8.0; + +/// Shift multiplier for faster movement. +const FAST_FACTOR: f32 = 3.0; + +/// Pitch limit, radians, just below a straight-down or straight-up look. +const PITCH_LIMIT: f32 = 1.45; + +const FOV_Y: f32 = 0.9; +const NEAR: f32 = 0.1; +const FAR: f32 = 500.0; + +/// Movement and look deltas for one frame. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub(crate) struct Motion { + pub forward: f32, + pub strafe: f32, + pub lift: f32, + pub yaw: f32, + pub pitch: f32, + pub seconds: f32, + pub fast: bool, +} + +/// A camera placed by an eye position and yaw/pitch angles. +pub(crate) struct FlyCamera { + position: [f32; 3], + yaw: f32, + pitch: f32, + aspect: f32, +} + +impl FlyCamera { + /// Places the camera at `eye` looking towards `target`. + pub(crate) fn look_at(eye: [f32; 3], target: [f32; 3], aspect: f32) -> Self { + let delta = [ + f64::from(target[0] - eye[0]), + f64::from(target[1] - eye[1]), + f64::from(target[2] - eye[2]), + ]; + let horizontal = math::sqrt(delta[0] * delta[0] + delta[1] * delta[1]); + let length = math::sqrt(horizontal * horizontal + delta[2] * delta[2]); + let yaw = if horizontal > 1.0e-6 { + math::atan2(delta[1], delta[0]) + } else { + 0.0 + }; + let pitch = if length > 1.0e-6 { + math::asin(delta[2] / length) + } else { + 0.0 + }; + Self { + position: eye, + yaw: yaw as f32, + pitch: (pitch as f32).clamp(-PITCH_LIMIT, PITCH_LIMIT), + aspect: aspect.max(0.0001), + } + } + + /// Updates the aspect ratio after a surface resize. + pub(crate) fn set_aspect(&mut self, aspect: f32) { + self.aspect = aspect.max(0.0001); + } + + /// Applies look deltas first, then moves in the horizontal plane and along Z. + pub(crate) fn apply(&mut self, motion: Motion) { + self.yaw += motion.yaw; + self.pitch = (self.pitch + motion.pitch).clamp(-PITCH_LIMIT, PITCH_LIMIT); + let (sin_yaw, cos_yaw) = math::sin_cos(f64::from(self.yaw)); + let (sin_yaw, cos_yaw) = (sin_yaw as f32, cos_yaw as f32); + let seconds = motion.seconds.max(0.0); + let speed = MOVE_SPEED * if motion.fast { FAST_FACTOR } else { 1.0 } * seconds; + let forward = motion.forward * speed; + let strafe = motion.strafe * speed; + self.position[0] += cos_yaw * forward + sin_yaw * strafe; + self.position[1] += sin_yaw * forward - cos_yaw * strafe; + self.position[2] += motion.lift * speed; + } + + /// The unit direction the camera looks along. + pub(crate) fn direction(&self) -> [f32; 3] { + let (sin_yaw, cos_yaw) = math::sin_cos(f64::from(self.yaw)); + let (sin_pitch, cos_pitch) = math::sin_cos(f64::from(self.pitch)); + [ + (cos_pitch * cos_yaw) as f32, + (cos_pitch * sin_yaw) as f32, + sin_pitch as f32, + ] + } + + /// The eye position, for diagnostics. + #[must_use] + pub(crate) fn eye(&self) -> [f32; 3] { + self.position + } + + /// The point one metre ahead of the eye, for diagnostics. + #[must_use] + pub(crate) fn target(&self) -> [f32; 3] { + let direction = self.direction(); + [ + self.position[0] + direction[0], + self.position[1] + direction[1], + self.position[2] + direction[2], + ] + } + + /// The renderer camera for the current pose. + pub(crate) fn view(&self) -> Camera { + let direction = self.direction(); + let target = [ + self.position[0] + direction[0], + self.position[1] + direction[1], + self.position[2] + direction[2], + ]; + Camera::look_at(self.position, target, [0.0, 0.0, 1.0]).with_projection( + FOV_Y, + self.aspect, + NEAR, + FAR, + ) + } +} diff --git a/crates/app/src/runtime/camera/tests.rs b/crates/app/src/runtime/camera/tests.rs new file mode 100644 index 0000000..235faeb --- /dev/null +++ b/crates/app/src/runtime/camera/tests.rs @@ -0,0 +1,103 @@ +//! Tests for camera movement and rotation math. + +use core::f32::consts::FRAC_PI_2; + +use fabrilis_core::math; + +use super::{FlyCamera, MOVE_SPEED, Motion, PITCH_LIMIT}; + +fn close(actual: f32, expected: f32) -> bool { + (actual - expected).abs() < 1.0e-4 +} + +fn level_camera() -> FlyCamera { + FlyCamera::look_at([0.0, 0.0, 2.0], [1.0, 0.0, 2.0], 1.0) +} + +#[test] +fn look_at_starts_level_along_x() { + let direction = level_camera().direction(); + assert!(close(direction[0], 1.0)); + assert!(close(direction[1], 0.0)); + assert!(close(direction[2], 0.0)); +} + +#[test] +fn yaw_rotation_turns_the_look_direction() { + let mut camera = level_camera(); + camera.apply(Motion { + yaw: FRAC_PI_2, + ..Motion::default() + }); + let direction = camera.direction(); + assert!(close(direction[0], 0.0)); + assert!(close(direction[1], 1.0)); + assert!(close(direction[2], 0.0)); +} + +#[test] +fn pitch_is_clamped() { + let mut camera = level_camera(); + camera.apply(Motion { + pitch: 10.0, + ..Motion::default() + }); + let direction = camera.direction(); + let expected = math::sin(f64::from(PITCH_LIMIT)) as f32; + assert!(close(direction[2], expected)); +} + +#[test] +fn forward_moves_horizontally_relative_to_yaw() { + let mut camera = level_camera(); + camera.apply(Motion { + yaw: FRAC_PI_2, + ..Motion::default() + }); + let before = camera.view().eye(); + camera.apply(Motion { + forward: 1.0, + seconds: 0.5, + ..Motion::default() + }); + let after = camera.view().eye(); + assert!(close(after[0], before[0])); + assert!(close(after[1] - before[1], MOVE_SPEED * 0.5)); + assert!(close(after[2], before[2])); +} + +#[test] +fn lift_moves_only_vertically() { + let mut camera = level_camera(); + let before = camera.view().eye(); + camera.apply(Motion { + lift: -1.0, + seconds: 0.5, + ..Motion::default() + }); + let after = camera.view().eye(); + assert!(close(after[0], before[0])); + assert!(close(after[1], before[1])); + assert!(close(after[2] - before[2], -MOVE_SPEED * 0.5)); +} + +#[test] +fn shift_multiplies_movement_speed() { + let mut slow = level_camera(); + let mut fast = level_camera(); + let start = slow.view().eye(); + slow.apply(Motion { + forward: 1.0, + seconds: 0.1, + ..Motion::default() + }); + fast.apply(Motion { + forward: 1.0, + seconds: 0.1, + fast: true, + ..Motion::default() + }); + let slow_distance = slow.view().eye()[0] - start[0]; + let fast_distance = fast.view().eye()[0] - start[0]; + assert!(close(fast_distance, slow_distance * 3.0)); +} diff --git a/crates/app/src/runtime/config/mod.rs b/crates/app/src/runtime/config/mod.rs new file mode 100644 index 0000000..1bfef4c --- /dev/null +++ b/crates/app/src/runtime/config/mod.rs @@ -0,0 +1,193 @@ +//! Command-line and environment configuration for diagnostics. +//! +//! The parser is pure: arguments and environment values are passed in, so the +//! precedence rules are unit-tested without touching the process. +//! +//! Precedence for each path is command line, then environment, then the +//! `--dev` default. Logs are off unless a path or dev mode asks for them. + +#[cfg(test)] +mod tests; + +use std::path::PathBuf; + +/// Default metrics CSV written by `--dev` when no path is given. +pub(crate) const DEFAULT_METRICS: &str = "fabrilis-metrics.csv"; + +/// Default dev log written by `--dev` when no path is given. +pub(crate) const DEFAULT_LOG: &str = "fabrilis-dev.log"; + +/// Environment variable with the metrics CSV path. +const ENV_METRICS: &str = "FABRILIS_METRICS_LOG"; + +/// Environment variable with the dev log path. +const ENV_LOG: &str = "FABRILIS_LOG"; + +/// Environment variable that enables dev mode when set to `1`. +const ENV_DEV: &str = "FABRILIS_DEV"; + +/// Usage text printed for `--help` and after a parse error. +pub(crate) const USAGE: &str = "\ +Usage: fabrilis-app [options] + +Options: + --metrics-log Write one metrics CSV row per rendered frame + --log Write the dev log to + --dev Verbose mode: default log paths and debug level + --append Append to existing logs instead of truncating + -h, --help Print this help and exit + +Environment: + FABRILIS_METRICS_LOG Metrics CSV path (command line wins) + FABRILIS_LOG Dev log path (command line wins) + FABRILIS_DEV=1 Same as --dev +"; + +/// Resolved diagnostics configuration. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Config { + /// Metrics CSV path; `None` keeps the CSV off. + pub(crate) metrics_log: Option, + /// Dev log path; `None` keeps the text log off. + pub(crate) log: Option, + /// Verbose mode: enables the dev log and the debug level. + pub(crate) dev: bool, + /// Append to existing files instead of truncating them at start. + pub(crate) append: bool, +} + +/// What the command line asked for. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Outcome { + /// Run the application with this configuration. + Run(Config), + /// Print the usage text and exit successfully. + Help, +} + +/// A configuration the parser rejected. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum ConfigError { + /// An argument is not one of the documented flags. + Unknown(String), + /// A flag that takes a path was the last argument. + MissingValue(&'static str), +} + +impl core::fmt::Display for ConfigError { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Unknown(argument) => write!(formatter, "unknown argument: {argument}"), + Self::MissingValue(flag) => write!(formatter, "missing value for {flag}"), + } + } +} + +impl std::error::Error for ConfigError {} + +/// Environment values that fill in paths the command line did not set. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Environment { + pub(crate) metrics_log: Option, + pub(crate) log: Option, + pub(crate) dev: bool, +} + +impl Environment { + /// Reads the documented `FABRILIS_*` variables, ignoring unset ones. + pub(crate) fn from_process() -> Self { + Self { + metrics_log: path_variable(ENV_METRICS), + log: path_variable(ENV_LOG), + dev: std::env::var_os(ENV_DEV).is_some_and(|value| value.to_str() == Some("1")), + } + } +} + +impl Config { + /// Parses the process arguments and environment. + pub(crate) fn from_process() -> Result { + let args: Vec = std::env::args_os() + .skip(1) + .map(|argument| argument.to_string_lossy().into_owned()) + .collect(); + parse(&args, &Environment::from_process()) + } +} + +/// Parses arguments and resolves them against the environment. +pub(crate) fn parse(args: &[String], env: &Environment) -> Result { + let mut cli = Cli::default(); + let mut arguments = args.iter(); + while let Some(argument) = arguments.next() { + match argument.as_str() { + "--help" | "-h" => return Ok(Outcome::Help), + "--dev" => cli.dev = true, + "--append" => cli.append = true, + "--metrics-log" => cli.metrics_log = Some(path_value(&mut arguments, "--metrics-log")?), + "--log" => cli.log = Some(path_value(&mut arguments, "--log")?), + argument => inline(&mut cli, argument)?, + } + } + Ok(Outcome::Run(resolve(cli, env))) +} + +/// Flags exactly as the command line gave them. +#[derive(Debug, Clone, Default)] +struct Cli { + metrics_log: Option, + log: Option, + dev: bool, + append: bool, +} + +/// Handles the `--flag=value` spelling of a path flag. +fn inline(cli: &mut Cli, argument: &str) -> Result<(), ConfigError> { + if let Some(value) = argument.strip_prefix("--metrics-log=") { + cli.metrics_log = Some(PathBuf::from(value)); + return Ok(()); + } + if let Some(value) = argument.strip_prefix("--log=") { + cli.log = Some(PathBuf::from(value)); + return Ok(()); + } + Err(ConfigError::Unknown(argument.to_owned())) +} + +/// The value after a path flag. +fn path_value( + arguments: &mut std::slice::Iter<'_, String>, + flag: &'static str, +) -> Result { + arguments + .next() + .filter(|value| !value.is_empty()) + .map(PathBuf::from) + .ok_or(ConfigError::MissingValue(flag)) +} + +/// Folds command line and environment into the final configuration. +fn resolve(cli: Cli, env: &Environment) -> Config { + let dev = cli.dev || env.dev; + let metrics_log = cli + .metrics_log + .or_else(|| env.metrics_log.clone()) + .or_else(|| dev.then(|| PathBuf::from(DEFAULT_METRICS))); + let log = cli + .log + .or_else(|| env.log.clone()) + .or_else(|| dev.then(|| PathBuf::from(DEFAULT_LOG))); + Config { + metrics_log, + log, + dev, + append: cli.append, + } +} + +/// A path environment variable, treating an empty value as unset. +fn path_variable(name: &str) -> Option { + std::env::var_os(name) + .map(PathBuf::from) + .filter(|path| !path.as_os_str().is_empty()) +} diff --git a/crates/app/src/runtime/config/tests.rs b/crates/app/src/runtime/config/tests.rs new file mode 100644 index 0000000..eccf682 --- /dev/null +++ b/crates/app/src/runtime/config/tests.rs @@ -0,0 +1,155 @@ +//! Tests for the argument and environment parser. + +use std::path::PathBuf; + +use super::*; + +fn args(items: &[&str]) -> Vec { + items.iter().map(|item| (*item).to_owned()).collect() +} + +fn run(arguments: &[&str], env: &Environment) -> Config { + match parse(&args(arguments), env) { + Ok(Outcome::Run(config)) => config, + other => panic!("expected a config, got {other:?}"), + } +} + +fn path(value: &str) -> Option { + Some(PathBuf::from(value)) +} + +#[test] +fn no_flags_leave_both_logs_off() { + let config = run(&[], &Environment::default()); + assert_eq!(config, Config::default()); + assert_eq!(config.metrics_log, None); + assert_eq!(config.log, None); +} + +#[test] +fn flags_set_paths_dev_and_append() { + let config = run( + &[ + "--metrics-log", + "run/m.csv", + "--log", + "run/dev.log", + "--dev", + "--append", + ], + &Environment::default(), + ); + assert_eq!(config.metrics_log, path("run/m.csv")); + assert_eq!(config.log, path("run/dev.log")); + assert!(config.dev); + assert!(config.append); +} + +#[test] +fn inline_values_are_accepted() { + let config = run( + &["--metrics-log=a.csv", "--log=b.log"], + &Environment::default(), + ); + assert_eq!(config.metrics_log, path("a.csv")); + assert_eq!(config.log, path("b.log")); +} + +#[test] +fn an_unknown_flag_is_an_error() { + let error = parse(&args(&["--frobnicate"]), &Environment::default()); + assert_eq!(error, Err(ConfigError::Unknown("--frobnicate".to_owned()))); +} + +#[test] +fn a_path_flag_without_a_value_is_an_error() { + assert_eq!( + parse(&args(&["--metrics-log"]), &Environment::default()), + Err(ConfigError::MissingValue("--metrics-log")) + ); + assert_eq!( + parse(&args(&["--log", "", "--dev"]), &Environment::default()), + Err(ConfigError::MissingValue("--log")) + ); +} + +#[test] +fn help_is_reported_before_any_work() { + assert_eq!( + parse(&args(&["--help"]), &Environment::default()), + Ok(Outcome::Help) + ); + assert_eq!( + parse(&args(&["-h", "--dev"]), &Environment::default()), + Ok(Outcome::Help) + ); +} + +#[test] +fn dev_mode_fills_in_the_default_paths() { + let config = run(&["--dev"], &Environment::default()); + assert_eq!(config.metrics_log, path(DEFAULT_METRICS)); + assert_eq!(config.log, path(DEFAULT_LOG)); + assert!(config.dev); +} + +#[test] +fn dev_keeps_an_explicit_path_and_fills_the_other_default() { + let metrics = run( + &["--dev", "--metrics-log", "m.csv"], + &Environment::default(), + ); + assert_eq!(metrics.metrics_log, path("m.csv")); + assert_eq!(metrics.log, path(DEFAULT_LOG)); + + let log = run(&["--dev", "--log", "d.log"], &Environment::default()); + assert_eq!(log.metrics_log, path(DEFAULT_METRICS)); + assert_eq!(log.log, path("d.log")); +} + +#[test] +fn environment_paths_are_used_without_flags() { + let env = Environment { + metrics_log: path("env/metrics.csv"), + log: path("env/dev.log"), + dev: false, + }; + let config = run(&[], &env); + assert_eq!(config.metrics_log, path("env/metrics.csv")); + assert_eq!(config.log, path("env/dev.log")); + assert!(!config.dev); +} + +#[test] +fn command_line_overrides_environment_too() { + let env = Environment { + metrics_log: path("env/metrics.csv"), + log: path("env/dev.log"), + dev: false, + }; + let config = run(&["--metrics-log", "cli/m.csv", "--log", "cli/l.log"], &env); + assert_eq!(config.metrics_log, path("cli/m.csv")); + assert_eq!(config.log, path("cli/l.log")); +} + +#[test] +fn environment_dev_keeps_explicit_paths() { + let env = Environment { + metrics_log: path("env/metrics.csv"), + log: None, + dev: true, + }; + let config = run(&[], &env); + assert!(config.dev); + assert_eq!( + config.metrics_log, + path("env/metrics.csv"), + "the environment path wins over the dev default" + ); + assert_eq!( + config.log, + path(DEFAULT_LOG), + "the missing path gets the default" + ); +} diff --git a/crates/app/src/runtime/devlog/mod.rs b/crates/app/src/runtime/devlog/mod.rs new file mode 100644 index 0000000..5b76ee2 --- /dev/null +++ b/crates/app/src/runtime/devlog/mod.rs @@ -0,0 +1,153 @@ +//! Dev text log: wall-clock stamped lines with a level, a target and a message. +//! +//! The logger is a diagnostic observer. It is off unless `--dev`, `--log` or a +//! matching environment variable asks for it, and it never feeds data back into +//! the simulation. +//! +//! Line shape: `unix_s level target message`. + +pub(crate) mod startup; + +#[cfg(test)] +mod tests; + +use std::fs::{File, OpenOptions}; +use std::io::{self, Write}; +use std::path::Path; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; + +use crate::runtime::metrics::Stats; + +/// How much detail the log records. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Level { + Error, + Warn, + Info, + Debug, + #[allow( + dead_code, + reason = "trace belongs to the documented level set; --dev stops at debug" + )] + Trace, +} + +impl Level { + /// Lower bounds `self`, so `self.rank() <= limit.rank()` means "log it". + fn rank(self) -> u8 { + match self { + Self::Error => 0, + Self::Warn => 1, + Self::Info => 2, + Self::Debug => 3, + Self::Trace => 4, + } + } +} + +impl core::fmt::Display for Level { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let name = match self { + Self::Error => "error", + Self::Warn => "warn", + Self::Info => "info", + Self::Debug => "debug", + Self::Trace => "trace", + }; + formatter.write_str(name) + } +} + +/// How often a metrics summary line is written, seconds. +const SUMMARY_INTERVAL_SECONDS: u64 = 1; + +/// A dev log file, truncated or created when opened. +pub(crate) struct DevLog { + file: File, + level: Level, + last_summary: Instant, +} + +impl DevLog { + /// Creates or opens the file, truncating it unless `append` is set, and + /// records `level` as the most detailed level to write. + #[allow( + clippy::disallowed_methods, + reason = "the dev log is a wall-clock observer of the app loop" + )] + pub(crate) fn open(path: &Path, level: Level, append: bool) -> io::Result { + let file = OpenOptions::new() + .create(true) + .write(true) + .append(append) + .truncate(!append) + .open(path)?; + Ok(Self { + file, + level, + last_summary: Instant::now(), + }) + } + + /// Writes one line and flushes it, so the log survives a crash. + pub(crate) fn write(&mut self, level: Level, target: &str, message: &str) -> io::Result<()> { + if level.rank() > self.level.rank() { + return Ok(()); + } + let line = format_line(unix_now(), level, target, message); + writeln!(self.file, "{line}")?; + self.file.flush() + } + + /// Whether the once-per-second metrics summary is due. + #[allow( + clippy::disallowed_methods, + reason = "the dev log is a wall-clock observer of the app loop" + )] + pub(crate) fn summary_due(&mut self) -> bool { + if self.last_summary.elapsed().as_secs() < SUMMARY_INTERVAL_SECONDS { + return false; + } + self.last_summary = Instant::now(); + true + } +} + +/// Formats one log line without the trailing newline. +pub(crate) fn format_line(unix_s: f64, level: Level, target: &str, message: &str) -> String { + format!("{unix_s:.3} {level} {target} {message}") +} + +/// One-line metrics summary written about once per second. +pub(crate) fn summary(stats: &Stats) -> String { + format!( + "fps={:.1} tps={:.1} frame={:.2}/{:.2} ms physics={:.2}/{:.2} ms render={:.2} ms rtf={:.2} cpu={:.1}% load1={:.2} rss={:.1} MB", + stats.fps, + stats.tps, + stats.frame_avg_ms, + stats.frame_max_ms, + stats.physics_avg_ms, + stats.physics_max_ms, + stats.render_avg_ms, + stats.rtf, + stats.cpu_percent, + stats.load_1m, + stats.rss_mb, + ) +} + +/// One-line description of a frame that exceeded its budget. +pub(crate) fn spike(frame: u64, frame_ms: f32, step_ms: f32, trigger: &str) -> String { + format!("frame={frame} frame_ms={frame_ms:.2} physics_step_ms={step_ms:.3} trigger={trigger}") +} + +/// Wall-clock seconds since the Unix epoch, as a float. +#[allow( + clippy::disallowed_methods, + reason = "the dev log is a wall-clock observer of the app loop" +)] +fn unix_now() -> f64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0.0, |elapsed| elapsed.as_secs_f64()) +} diff --git a/crates/app/src/runtime/devlog/startup.rs b/crates/app/src/runtime/devlog/startup.rs new file mode 100644 index 0000000..7705fc3 --- /dev/null +++ b/crates/app/src/runtime/devlog/startup.rs @@ -0,0 +1,66 @@ +//! Startup banner for the dev log: versions, window, world, bodies and GPU. + +use std::io; + +use fabrilis_worldgen::terrain::TerrainConfig; + +use super::{DevLog, Level}; + +/// Everything the startup lines report, gathered before the loop starts. +pub(crate) struct StartupInfo<'a> { + pub(crate) window: (u32, u32), + pub(crate) scale: f64, + pub(crate) terrain: TerrainConfig, + pub(crate) boxes: usize, + pub(crate) box_mass_kg: f64, + pub(crate) box_size_m: f64, + pub(crate) eye: [f32; 3], + pub(crate) target: [f32; 3], + pub(crate) adapter: &'a str, + pub(crate) driver: &'a str, + pub(crate) surface: &'a str, + pub(crate) metrics_path: Option<&'a str>, + pub(crate) log_path: Option<&'a str>, + pub(crate) dev: bool, + pub(crate) append: bool, +} + +/// Writes the startup banner, one line per fact. +pub(crate) fn write(log: &mut DevLog, info: &StartupInfo<'_>) -> io::Result<()> { + let terrain = info.terrain; + let [width, height] = [info.window.0, info.window.1]; + let [x, y, z] = info.eye; + let [tx, ty, tz] = info.target; + let lines = [ + format!( + "fabrilis-app {} {} {}", + env!("CARGO_PKG_VERSION"), + std::env::consts::OS, + std::env::consts::ARCH + ), + format!("window {width}x{height} scale {:.2}", info.scale), + format!( + "terrain seed={} size={} extent={:.1} height_scale={:.1}", + terrain.seed, terrain.size, terrain.extent, terrain.height_scale + ), + format!( + "boxes={} mass={:.1} kg size={:.2} m", + info.boxes, info.box_mass_kg, info.box_size_m + ), + format!("camera eye=[{x:.2}, {y:.2}, {z:.2}] target=[{tx:.2}, {ty:.2}, {tz:.2}]"), + format!("gpu adapter {}", info.adapter), + format!("gpu driver {}", info.driver), + format!("gpu surface {}", info.surface), + format!( + "metrics_log {} append={} dev={}", + info.metrics_path.unwrap_or("off"), + info.append, + info.dev + ), + format!("log {}", info.log_path.unwrap_or("off")), + ]; + for line in &lines { + log.write(Level::Info, "startup", line)?; + } + Ok(()) +} diff --git a/crates/app/src/runtime/devlog/tests.rs b/crates/app/src/runtime/devlog/tests.rs new file mode 100644 index 0000000..e2915b3 --- /dev/null +++ b/crates/app/src/runtime/devlog/tests.rs @@ -0,0 +1,120 @@ +//! Tests for the dev log line format and its file lifecycle. + +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::*; + +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(name: &str) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "fabrilis-devlog-{name}-{}-{id}", + std::process::id() + )); + std::fs::create_dir_all(&path).expect("temp directory"); + Self { path } + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +#[test] +fn a_line_has_a_stable_timestamp_level_target_and_message() { + assert_eq!( + format_line(1_700_000_000.125, Level::Info, "app", "hello"), + "1700000000.125 info app hello" + ); + assert_eq!( + format_line(0.0, Level::Warn, "spike", "frame=7"), + "0.000 warn spike frame=7" + ); +} + +#[test] +fn the_summary_and_spike_lines_are_stable() { + let stats = Stats { + fps: 60.0, + tps: 999.5, + frame_avg_ms: 16.25, + frame_max_ms: 20.5, + physics_avg_ms: 0.5, + physics_max_ms: 1.25, + render_avg_ms: 2.0, + rtf: 1.0, + cpu_percent: 12.5, + load_1m: 0.75, + rss_mb: 312.5, + }; + assert_eq!( + summary(&stats), + "fps=60.0 tps=999.5 frame=16.25/20.50 ms physics=0.50/1.25 ms render=2.00 ms rtf=1.00 cpu=12.5% load1=0.75 rss=312.5 MB" + ); + assert_eq!( + spike(42, 25.1, 1.25, "frame+physics"), + "frame=42 frame_ms=25.10 physics_step_ms=1.250 trigger=frame+physics" + ); +} + +#[test] +fn writing_creates_then_truncates_the_file() { + let dir = TempDir::new("create"); + let path = dir.path.join("fabrilis-dev.log"); + { + let mut log = DevLog::open(&path, Level::Debug, false).expect("create the log"); + log.write(Level::Info, "app", "first run").expect("write"); + } + assert!(path.is_file(), "the log file exists"); + let first = std::fs::read_to_string(&path).expect("read"); + assert_eq!(first.lines().count(), 1); + assert!(first.ends_with(" info app first run\n")); + { + let mut log = DevLog::open(&path, Level::Debug, false).expect("truncate the log"); + log.write(Level::Warn, "app", "second run").expect("write"); + } + let second = std::fs::read_to_string(&path).expect("read"); + assert_eq!(second.lines().count(), 1, "the old contents are gone"); + assert!(second.ends_with(" warn app second run\n")); +} + +#[test] +fn append_keeps_the_previous_lines() { + let dir = TempDir::new("append"); + let path = dir.path.join("fabrilis-dev.log"); + { + let mut log = DevLog::open(&path, Level::Debug, false).expect("create the log"); + log.write(Level::Info, "app", "first").expect("write"); + } + { + let mut log = DevLog::open(&path, Level::Debug, true).expect("append the log"); + log.write(Level::Info, "app", "second").expect("write"); + } + let text = std::fs::read_to_string(&path).expect("read"); + assert_eq!(text.lines().count(), 2, "both sessions are kept"); + assert!(text.contains("first") && text.contains("second")); +} + +#[test] +fn levels_above_the_limit_are_dropped() { + let dir = TempDir::new("levels"); + let path = dir.path.join("fabrilis-dev.log"); + { + let mut log = DevLog::open(&path, Level::Info, false).expect("create the log"); + log.write(Level::Debug, "app", "too detailed") + .expect("write"); + log.write(Level::Info, "app", "kept").expect("write"); + } + let text = std::fs::read_to_string(&path).expect("read"); + assert_eq!(text.lines().count(), 1); + assert!(text.contains("kept")); + assert!(!text.contains("too detailed")); +} diff --git a/crates/app/src/runtime/error.rs b/crates/app/src/runtime/error.rs new file mode 100644 index 0000000..bb41f0a --- /dev/null +++ b/crates/app/src/runtime/error.rs @@ -0,0 +1,62 @@ +//! Application errors. + +use core::fmt; + +use fabrilis_render::RenderError; +use fabrilis_worldgen::terrain::TerrainError; + +/// A failure that stops the window loop. +#[derive(Debug)] +pub enum AppError { + /// The renderer rejected a device, texture or buffer operation. + Render(RenderError), + /// Terrain generation rejected its configuration. + Terrain(TerrainError), + /// The physics world rejected a body or collider. + Physics(String), + /// The window could not be created. + Window(String), + /// The swap chain could not be acquired or configured. + Surface(String), + /// The event loop itself failed. + EventLoop(String), + /// A diagnostics log file could not be opened or written. + Log(String), +} + +impl fmt::Display for AppError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Render(error) => write!(formatter, "{error}"), + Self::Terrain(error) => write!(formatter, "terrain generation failed: {error}"), + Self::Physics(detail) => write!(formatter, "physics failure: {detail}"), + Self::Window(detail) => write!(formatter, "window failure: {detail}"), + Self::Surface(detail) => write!(formatter, "surface failure: {detail}"), + Self::EventLoop(detail) => write!(formatter, "event loop failure: {detail}"), + Self::Log(detail) => write!(formatter, "log failure: {detail}"), + } + } +} + +impl std::error::Error for AppError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Render(error) => Some(error), + Self::Terrain(error) => Some(error), + Self::Physics(_) | Self::Window(_) | Self::Surface(_) | Self::EventLoop(_) => None, + Self::Log(_) => None, + } + } +} + +impl From for AppError { + fn from(error: RenderError) -> Self { + Self::Render(error) + } +} + +impl From for AppError { + fn from(error: TerrainError) -> Self { + Self::Terrain(error) + } +} diff --git a/crates/app/src/runtime/gpu.rs b/crates/app/src/runtime/gpu.rs new file mode 100644 index 0000000..90833cb --- /dev/null +++ b/crates/app/src/runtime/gpu.rs @@ -0,0 +1,148 @@ +//! Window surface, device and swap chain owned by the application. + +use std::sync::Arc; + +use fabrilis_render::{Camera, Overlay, RenderError, Renderer, Scene, wgpu}; +use winit::window::Window; + +use super::AppError; + +/// Everything needed to present frames into the winit window. +pub(crate) struct WindowRenderer { + surface: wgpu::Surface<'static>, + device: wgpu::Device, + queue: wgpu::Queue, + config: wgpu::SurfaceConfiguration, + renderer: Renderer, + size: (u32, u32), + gpu: GpuInfo, +} + +/// Adapter and surface facts reported to the dev log. +pub(crate) struct GpuInfo { + pub(crate) adapter: String, + pub(crate) driver: String, + pub(crate) surface: String, +} + +impl WindowRenderer { + /// Creates the instance, surface, adapter, device and swap chain. + pub(crate) fn new(window: Arc) -> Result { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let surface = instance + .create_surface(window.clone()) + .map_err(|error| AppError::Surface(error.to_string()))?; + let adapter = request_adapter(&instance, &surface)?; + let (device, queue) = + pollster::block_on(adapter.request_device(&fabrilis_render::gpu::device_descriptor())) + .map_err(|error| RenderError::Device(error.to_string()))?; + let size = window.inner_size(); + let width = size.width.max(1); + let height = size.height.max(1); + let capabilities = surface.get_capabilities(&adapter); + let format = capabilities + .formats + .iter() + .copied() + .find(wgpu::TextureFormat::is_srgb) + .or_else(|| capabilities.formats.first().copied()) + .ok_or_else(|| AppError::Surface("surface reports no texture formats".to_string()))?; + let mut config = surface + .get_default_config(&adapter, width, height) + .ok_or_else(|| AppError::Surface("surface has no default configuration".to_string()))?; + config.format = format; + config.present_mode = wgpu::PresentMode::AutoVsync; + surface.configure(&device, &config); + let renderer = Renderer::for_surface(&device, &queue, format, (width, height))?; + let info = adapter.get_info(); + let driver = if info.driver_info.is_empty() { + format!("{} ({:?})", info.driver, info.backend) + } else { + format!("{} {} ({:?})", info.driver, info.driver_info, info.backend) + }; + let gpu = GpuInfo { + adapter: info.name, + driver, + surface: format!("{format:?}"), + }; + Ok(Self { + surface, + device, + queue, + config, + renderer, + size: (size.width, size.height), + gpu, + }) + } + + /// Adapter and surface facts for the startup banner. + pub(crate) fn info(&self) -> &GpuInfo { + &self.gpu + } + + /// Reconfigures the swap chain and renderer targets after a window resize. + pub(crate) fn resize(&mut self, width: u32, height: u32) -> Result<(), AppError> { + self.size = (width, height); + self.renderer.resize((width, height))?; + if width == 0 || height == 0 { + return Ok(()); + } + self.config.width = width; + self.config.height = height; + self.surface.configure(&self.device, &self.config); + Ok(()) + } + + /// The current target size in pixels. + pub(crate) fn size(&self) -> (u32, u32) { + self.size + } + + /// Acquires a surface frame, draws the scene and the overlay, then presents. + pub(crate) fn draw( + &mut self, + scene: &Scene, + camera: &Camera, + overlay: &Overlay, + ) -> Result<(), AppError> { + if self.size.0 == 0 || self.size.1 == 0 { + return Ok(()); + } + match self.surface.get_current_texture() { + wgpu::CurrentSurfaceTexture::Success(frame) + | wgpu::CurrentSurfaceTexture::Suboptimal(frame) => { + let view = frame + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); + self.renderer.draw_to(&view, scene, camera)?; + self.renderer.draw_overlay(&view, overlay)?; + self.queue.present(frame); + Ok(()) + } + wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => Ok(()), + wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => { + self.surface.configure(&self.device, &self.config); + Ok(()) + } + wgpu::CurrentSurfaceTexture::Validation => { + Err(AppError::Surface("surface validation error".to_string())) + } + } + } +} + +fn request_adapter( + instance: &wgpu::Instance, + surface: &wgpu::Surface<'_>, +) -> Result { + let options = wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::HighPerformance, + compatible_surface: Some(surface), + force_fallback_adapter: false, + ..Default::default() + }; + let adapter = pollster::block_on(instance.request_adapter(&options)) + .map_err(|error| RenderError::Adapter(error.to_string()))?; + Ok(adapter) +} diff --git a/crates/app/src/runtime/metrics/csv.rs b/crates/app/src/runtime/metrics/csv.rs new file mode 100644 index 0000000..06c4832 --- /dev/null +++ b/crates/app/src/runtime/metrics/csv.rs @@ -0,0 +1,141 @@ +//! Per-frame metrics CSV writer and the spike rule shared with the dev log. +//! +//! The writer is a passive observer: it reads values that the overlay already +//! computed and never calls into physics or the renderer. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Write}; +use std::path::Path; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; + +use super::Stats; + +/// The one header line, in the documented column order. +pub(crate) const HEADER: &str = "unix_s,t_s,frame,fps,tps,frame_ms,frame_max_ms,physics_ms,physics_max_ms,render_ms,rtf,cpu_pct,load1,rss_mb,spike"; + +/// A frame longer than this is a spike, milliseconds. +const FRAME_BUDGET_MS: f32 = 20.0; + +/// A single physics step longer than this is a spike, milliseconds. +const STEP_BUDGET_MS: f32 = 1.0; + +/// At most one flush per this interval while logging, seconds. +const FLUSH_INTERVAL_SECONDS: u64 = 1; + +/// One row of the metrics CSV. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Row<'a> { + /// Wall-clock seconds at the start of the frame. + pub(crate) unix_s: f64, + /// Simulated seconds before this frame was drawn. + pub(crate) t_s: f64, + /// Number of the rendered frame, starting at one. + pub(crate) frame: u64, + /// The same rolling values the overlay shows. + pub(crate) stats: &'a Stats, + /// Whether the frame or one of its physics steps blew its budget. + pub(crate) spike: bool, +} + +/// Formats a row exactly as the header orders it. +pub(crate) fn format_row(row: &Row<'_>) -> String { + let stats = row.stats; + format!( + "{:.3},{:.3},{},{:.1},{:.1},{:.2},{:.2},{:.2},{:.2},{:.2},{:.2},{:.1},{:.2},{:.1},{}", + row.unix_s, + row.t_s, + row.frame, + stats.fps, + stats.tps, + stats.frame_avg_ms, + stats.frame_max_ms, + stats.physics_avg_ms, + stats.physics_max_ms, + stats.render_avg_ms, + stats.rtf, + stats.cpu_percent, + stats.load_1m, + stats.rss_mb, + u8::from(row.spike), + ) +} + +/// Why a frame counts as a spike, or `None` when it fits the budget. +pub(crate) fn spike_reason(frame_ms: f32, slowest_step_ms: f32) -> Option<&'static str> { + match (frame_ms > FRAME_BUDGET_MS, slowest_step_ms > STEP_BUDGET_MS) { + (true, true) => Some("frame+physics"), + (true, false) => Some("frame"), + (false, true) => Some("physics"), + (false, false) => None, + } +} + +/// Wall-clock seconds since the Unix epoch. +#[allow( + clippy::disallowed_methods, + reason = "the metrics CSV stamps the frame start with wall-clock time" +)] +pub(crate) fn unix_now() -> f64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0.0, |elapsed| elapsed.as_secs_f64()) +} + +/// An open metrics CSV file. +pub(crate) struct CsvLog { + file: File, + last_flush: Instant, +} + +impl CsvLog { + /// Opens the file, truncating it unless `append` is set. The header is + /// written when the file starts empty, so an appended file keeps one. + #[allow( + clippy::disallowed_methods, + reason = "the metrics writer throttles flushes with wall-clock time" + )] + pub(crate) fn open(path: &Path, append: bool) -> io::Result { + let has_rows = append && fs::metadata(path).is_ok_and(|meta| meta.len() > 0); + let mut file = OpenOptions::new() + .create(true) + .write(true) + .append(append) + .truncate(!append) + .open(path)?; + if !has_rows { + file.write_all(HEADER.as_bytes())?; + file.write_all(b"\n")?; + } + Ok(Self { + file, + last_flush: Instant::now(), + }) + } + + /// Writes one row and flushes at most once per second. + pub(crate) fn record(&mut self, row: &Row<'_>) -> io::Result<()> { + writeln!(self.file, "{}", format_row(row))?; + if self.last_flush.elapsed().as_secs() >= FLUSH_INTERVAL_SECONDS { + self.flush()?; + } + Ok(()) + } + + /// Pushes buffered rows to disk and restarts the flush interval. + #[allow( + clippy::disallowed_methods, + reason = "the metrics writer throttles flushes with wall-clock time" + )] + pub(crate) fn flush(&mut self) -> io::Result<()> { + self.file.flush()?; + self.last_flush = Instant::now(); + Ok(()) + } +} + +impl Drop for CsvLog { + fn drop(&mut self) { + // The final flush is best effort: dropping must not abort the process. + let _ = self.file.flush(); + } +} diff --git a/crates/app/src/runtime/metrics/mod.rs b/crates/app/src/runtime/metrics/mod.rs new file mode 100644 index 0000000..937ce6a --- /dev/null +++ b/crates/app/src/runtime/metrics/mod.rs @@ -0,0 +1,237 @@ +//! Rolling frame, physics, render and process metrics for the debug overlay. +//! +//! Wall-clock reads live here: the rest of the application only measures phases +//! through [`Stopwatch`] and never looks at the system clock itself. + +mod csv; +mod panel; +mod proc; + +#[cfg(test)] +mod tests; + +use std::collections::VecDeque; +use std::time::{Duration, Instant}; + +use self::proc::ProcSample; + +pub(crate) use csv::{CsvLog, Row, spike_reason, unix_now}; + +/// Length of the rolling statistics window, seconds. +const WINDOW_SECONDS: f32 = 1.0; + +/// Frames kept for the graph. +const HISTORY: usize = 180; +/// Linux `USER_HZ`: `/proc` CPU ticks per second. +const TICKS_PER_SECOND: f32 = 100.0; +/// Physics and render work of one frame, as measured by the caller. +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct FrameWork { + pub(crate) physics: Duration, + pub(crate) render: Duration, + pub(crate) steps: u32, +} + +/// One frame in the rolling statistics window. +#[derive(Debug, Clone, Copy)] +struct Sample { + at: f32, + frame_ms: f32, + physics_ms: f32, + render_ms: f32, + steps: u32, + cpu_ticks: u32, +} + +/// Aggregates over the last second, rebuilt after every frame. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub(crate) struct Stats { + pub(crate) fps: f32, + pub(crate) tps: f32, + pub(crate) frame_avg_ms: f32, + pub(crate) frame_max_ms: f32, + pub(crate) physics_avg_ms: f32, + pub(crate) physics_max_ms: f32, + pub(crate) render_avg_ms: f32, + pub(crate) cpu_percent: f32, + pub(crate) load_1m: f32, + pub(crate) rss_mb: f32, + pub(crate) rtf: f32, +} + +/// Wall-clock measurement of one phase of a frame. +pub(crate) struct Stopwatch { + start: Instant, +} + +impl Stopwatch { + /// Starts a phase measurement. + #[allow( + clippy::disallowed_methods, + reason = "the diagnostics overlay is the one place that measures wall time" + )] + pub(crate) fn start() -> Self { + Self { + start: Instant::now(), + } + } + + /// The time spent since [`Stopwatch::start`]. + pub(crate) fn elapsed(self) -> Duration { + self.start.elapsed() + } +} + +/// The rolling window behind the diagnostics panel. +pub(crate) struct Metrics { + last: Instant, + clock: f32, + window: VecDeque, + history: VecDeque<[f32; 2]>, + last_ticks: Option, + rtf: Option, + primed: bool, + stats: Stats, +} + +impl Default for Metrics { + fn default() -> Self { + Self::new() + } +} + +impl Metrics { + /// Starts the frame clock. + #[allow( + clippy::disallowed_methods, + reason = "the diagnostics overlay is the one place that measures wall time" + )] + pub(crate) fn new() -> Self { + Self { + last: Instant::now(), + clock: 0.0, + window: VecDeque::with_capacity(HISTORY), + history: VecDeque::with_capacity(HISTORY), + last_ticks: None, + rtf: None, + primed: false, + stats: Stats::default(), + } + } + + /// Wall time since the previous call, that is the previous frame's duration. + #[allow( + clippy::disallowed_methods, + reason = "the diagnostics overlay is the one place that measures wall time" + )] + pub(crate) fn frame_time(&mut self) -> Duration { + let now = Instant::now(); + let elapsed = now.duration_since(self.last); + self.last = now; + elapsed + } + + /// Keeps the latest simulation-to-wall ratio reported by the pacer. + pub(crate) fn set_rtf(&mut self, rtf: Option) { + if rtf.is_some() { + self.rtf = rtf; + } + } + + /// Adds one frame to the rolling window and refreshes the aggregates. + /// + /// The first frame is warm-up: it measures window setup and pipeline + /// compilation, not a steady-state frame, and would dominate the graph. + /// Returns `false` for that frame, so observers can skip it as well. + pub(crate) fn record(&mut self, frame: Duration, work: FrameWork) -> bool { + if !self.primed { + self.primed = true; + return false; + } + let frame_ms = frame.as_secs_f32() * 1000.0; + let physics_ms = work.physics.as_secs_f32() * 1000.0; + let render_ms = work.render.as_secs_f32() * 1000.0; + self.clock += frame.as_secs_f32(); + let sample: ProcSample = proc::sample(); + let cpu_ticks = match (sample.ticks, self.last_ticks) { + (Some(now), Some(before)) => u32::try_from(now.saturating_sub(before)).unwrap_or(0), + _ => 0, + }; + self.last_ticks = sample.ticks.or(self.last_ticks); + self.window.push_back(Sample { + at: self.clock, + frame_ms, + physics_ms, + render_ms, + steps: work.steps, + cpu_ticks, + }); + self.trim(); + self.stats = self.aggregate(sample); + self.history.push_back([frame_ms, physics_ms]); + if self.history.len() > HISTORY { + self.history.pop_front(); + } + true + } + + /// The latest rolling values, as shown in the overlay. + pub(crate) fn stats(&self) -> Stats { + self.stats + } + + /// Drops samples that fell out of the statistics window. + fn trim(&mut self) { + while self.window.len() > 1 { + let span = self + .window + .front() + .map_or(0.0, |sample| self.clock - sample.at); + if span <= WINDOW_SECONDS { + break; + } + self.window.pop_front(); + } + } + + /// Folds the window into one-shot averages and maxima. + fn aggregate(&self, sample: ProcSample) -> Stats { + let mut stats = Stats { + load_1m: sample.load_1m, + rss_mb: sample.rss_mb, + rtf: self.rtf.unwrap_or(0.0), + ..Stats::default() + }; + let Some(first) = self.window.front() else { + return stats; + }; + let span = (self.clock - first.at).max(0.0); + let count = self.window.len().saturating_sub(1) as f32; + let mut frame_sum = 0.0; + let mut physics_sum = 0.0; + let mut render_sum = 0.0; + let mut steps = 0; + let mut ticks = 0_u32; + for sample in &self.window { + frame_sum += sample.frame_ms; + physics_sum += sample.physics_ms; + render_sum += sample.render_ms; + steps += sample.steps; + ticks = ticks.saturating_add(sample.cpu_ticks); + stats.frame_max_ms = stats.frame_max_ms.max(sample.frame_ms); + stats.physics_max_ms = stats.physics_max_ms.max(sample.physics_ms); + } + let frames = self.window.len() as f32; + if span > 0.0 { + stats.fps = count / span; + stats.tps = steps as f32 / span; + stats.cpu_percent = ticks as f32 / span / TICKS_PER_SECOND * 100.0; + } + if frames > 0.0 { + stats.frame_avg_ms = frame_sum / frames; + stats.physics_avg_ms = physics_sum / frames; + stats.render_avg_ms = render_sum / frames; + } + stats + } +} diff --git a/crates/app/src/runtime/metrics/panel.rs b/crates/app/src/runtime/metrics/panel.rs new file mode 100644 index 0000000..cb02f02 --- /dev/null +++ b/crates/app/src/runtime/metrics/panel.rs @@ -0,0 +1,153 @@ +//! Panel layout for the diagnostics overlay: one text line per metric and a +//! scrolling frame-time graph. + +use fabrilis_render::{Overlay, OverlayLine, OverlayRect, OverlayText}; + +use super::{HISTORY, Metrics}; + +const PANEL_X: f32 = 12.0; +const PANEL_Y: f32 = 12.0; +const PANEL_WIDTH: f32 = 300.0; +const PADDING: f32 = 10.0; +const FONT_SIZE: f32 = 14.0; +const LABEL_SIZE: f32 = 11.0; +const LINE_HEIGHT: f32 = 17.0; +const GRAPH_WIDTH: f32 = 280.0; +const GRAPH_HEIGHT: f32 = 90.0; +const GRAPH_LABEL_SPACE: f32 = 14.0; +const PANEL_COLOR: [f32; 4] = [0.03, 0.04, 0.05, 0.82]; +const GRAPH_COLOR: [f32; 4] = [0.0, 0.0, 0.0, 0.45]; +const TEXT_COLOR: [f32; 4] = [0.90, 0.93, 0.96, 1.0]; +const DIM_COLOR: [f32; 4] = [0.55, 0.60, 0.66, 1.0]; +const GRID_COLOR: [f32; 4] = [1.0, 1.0, 1.0, 0.14]; +const FRAME_COLOR: [f32; 4] = [0.35, 0.95, 0.55, 1.0]; +const FRAME_FILL: [f32; 4] = [0.35, 0.95, 0.55, 0.18]; +const PHYSICS_COLOR: [f32; 4] = [1.0, 0.70, 0.25, 1.0]; + +impl Metrics { + /// Draws the diagnostics panel and its graph into `overlay`. + pub(crate) fn draw_panel(&self, overlay: &mut Overlay) { + let lines = self.lines(); + let graph_top = PANEL_Y + PADDING + LINE_HEIGHT * lines.len() as f32 + GRAPH_LABEL_SPACE; + let height = graph_top - PANEL_Y + GRAPH_LABEL_SPACE + GRAPH_HEIGHT + PADDING; + overlay.push_rect(OverlayRect::new( + PANEL_X, + PANEL_Y, + PANEL_WIDTH, + height, + PANEL_COLOR, + )); + let mut y = PANEL_Y + PADDING; + for line in &lines { + overlay.push_text(OverlayText::new( + PANEL_X + PADDING, + y, + FONT_SIZE, + TEXT_COLOR, + line.as_str(), + )); + y += LINE_HEIGHT; + } + self.draw_graph(overlay, [PANEL_X + PADDING, graph_top]); + } + + /// One text line per metric. + fn lines(&self) -> Vec { + let stats = self.stats; + vec![ + format!("FPS {:>6.1}", stats.fps), + format!("TPS {:>6.1}", stats.tps), + format!( + "frame {:>6.2} avg {:>6.2} max", + stats.frame_avg_ms, stats.frame_max_ms + ), + format!( + "phys {:>6.2} avg {:>6.2} max", + stats.physics_avg_ms, stats.physics_max_ms + ), + format!("render {:>6.2} avg", stats.render_avg_ms), + format!("rtf {:>5.2}", stats.rtf), + format!("cpu {:>5.1} %", stats.cpu_percent), + format!("load {:>5.2}", stats.load_1m), + format!("rss {:>6.1} MB", stats.rss_mb), + ] + } + + /// Frame and physics series with a shared auto-scaled axis. + fn draw_graph(&self, overlay: &mut Overlay, origin: [f32; 2]) { + let [x, y] = origin; + let max = self + .history + .iter() + .map(|point| point[0].max(point[1])) + .fold(1.0_f32, f32::max); + overlay.push_rect(OverlayRect::new( + x, + y, + GRAPH_WIDTH, + GRAPH_HEIGHT, + GRAPH_COLOR, + )); + overlay.push_text(OverlayText::new( + x, + y - GRAPH_LABEL_SPACE + 3.0, + LABEL_SIZE, + DIM_COLOR, + format!("{max:.1} ms max"), + )); + overlay.push_text(OverlayText::new( + x + GRAPH_WIDTH - 30.0, + y + GRAPH_HEIGHT - LABEL_SIZE - 2.0, + LABEL_SIZE, + DIM_COLOR, + "0 ms", + )); + for step in 0..=4 { + let line_y = y + GRAPH_HEIGHT * step as f32 / 4.0; + overlay.push_line(OverlayLine::new( + [x, line_y], + [x + GRAPH_WIDTH, line_y], + 1.0, + GRID_COLOR, + )); + } + self.draw_series(overlay, origin, max); + } + + /// Area fill and polyline for both series, newest point on the right edge. + fn draw_series(&self, overlay: &mut Overlay, origin: [f32; 2], max: f32) { + let [x, y] = origin; + let count = self.history.len(); + if count == 0 { + return; + } + let step = GRAPH_WIDTH / (HISTORY - 1) as f32; + let mut previous_frame: Option<[f32; 2]> = None; + let mut previous_physics: Option<[f32; 2]> = None; + for (index, point) in self.history.iter().enumerate() { + let px = x + GRAPH_WIDTH - step * (count - 1 - index) as f32; + let frame = y + GRAPH_HEIGHT - travel(point[0], max); + let physics = y + GRAPH_HEIGHT - travel(point[1], max); + overlay.push_rect(OverlayRect::new( + px, + frame, + step.max(1.0), + (y + GRAPH_HEIGHT - frame).max(0.0), + FRAME_FILL, + )); + if let Some(last) = previous_frame { + overlay.push_line(OverlayLine::new(last, [px, frame], 1.5, FRAME_COLOR)); + } + if let Some(last) = previous_physics { + overlay.push_line(OverlayLine::new(last, [px, physics], 1.2, PHYSICS_COLOR)); + } + previous_frame = Some([px, frame]); + previous_physics = Some([px, physics]); + } + } +} + +/// A non-negative value scaled into graph pixels against the axis maximum. +fn travel(value: f32, max: f32) -> f32 { + (value / max).clamp(0.0, 1.0) * GRAPH_HEIGHT +} diff --git a/crates/app/src/runtime/metrics/proc.rs b/crates/app/src/runtime/metrics/proc.rs new file mode 100644 index 0000000..987e428 --- /dev/null +++ b/crates/app/src/runtime/metrics/proc.rs @@ -0,0 +1,63 @@ +//! Process counters read from `/proc`, with neutral fallbacks elsewhere. +//! +//! Every parser is pure: it takes the text of a `/proc` file and returns +//! `None` for malformed input instead of panicking. + +/// One read of the process-wide counters. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub(crate) struct ProcSample { + /// User plus system CPU time of the process, in clock ticks. + pub(crate) ticks: Option, + /// One-minute load average, or zero when unavailable. + pub(crate) load_1m: f32, + /// Resident set size in mebibytes, or zero when unavailable. + pub(crate) rss_mb: f32, +} + +/// Reads the counters once; a missing `/proc` leaves the fields at zero. +pub(crate) fn sample() -> ProcSample { + ProcSample { + ticks: read("/proc/self/stat").and_then(|text| parse_stat(&text)), + load_1m: read("/proc/loadavg") + .and_then(|text| parse_loadavg(&text)) + .unwrap_or(0.0), + rss_mb: read("/proc/self/status") + .and_then(|text| parse_rss_mb(&text)) + .unwrap_or(0.0), + } +} + +fn read(path: &str) -> Option { + std::fs::read_to_string(path).ok() +} + +/// `utime + stime` from a `/proc//stat` line. +/// +/// The command name is in parentheses and may contain spaces, so parsing starts +/// after the last closing parenthesis. +pub(crate) fn parse_stat(text: &str) -> Option { + let close = text.rfind(')')?; + let rest = text.get(close + 1..)?; + // `rest` starts at field 3 (state); utime and stime are fields 14 and 15. + let mut fields = rest.split_whitespace(); + let utime = fields.nth(11)?; + let stime = fields.next()?; + let user = utime.parse::().ok()?; + let system = stime.parse::().ok()?; + Some(user.saturating_add(system)) +} + +/// The one-minute load average from a `/proc/loadavg` line. +pub(crate) fn parse_loadavg(text: &str) -> Option { + let value = text.split_whitespace().next()?.parse::().ok()?; + (value.is_finite() && value >= 0.0).then_some(value) +} + +/// `VmRSS` from a `/proc//status` file, converted from kB to MiB. +pub(crate) fn parse_rss_mb(text: &str) -> Option { + let line = text + .lines() + .find(|line| line.trim_start().starts_with("VmRSS:"))?; + let kilobytes = line.split_whitespace().nth(1)?.parse::().ok()?; + (kilobytes.is_finite() && kilobytes >= 0.0).then_some(kilobytes / 1024.0) +} diff --git a/crates/app/src/runtime/metrics/tests.rs b/crates/app/src/runtime/metrics/tests.rs new file mode 100644 index 0000000..ecccb78 --- /dev/null +++ b/crates/app/src/runtime/metrics/tests.rs @@ -0,0 +1,247 @@ +//! Tests for the `/proc` parsers, the rolling metrics window and the CSV log. + +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +use fabrilis_render::Overlay; + +use super::*; + +/// A temp directory that removes itself when the test ends. +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(name: &str) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "fabrilis-metrics-{name}-{}-{id}", + std::process::id() + )); + std::fs::create_dir_all(&path).expect("temp directory"); + Self { path } + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +const STAT: &str = "1234 (a) b c) S 1 2 3 4 5 6 7 8 9 10 120 34 0 0 20 0 1 0 1000 0 0"; + +#[test] +fn stat_ticks_sum_user_and_system_time() { + assert_eq!(proc::parse_stat(STAT), Some(154)); +} + +#[test] +fn stat_tolerates_parentheses_in_the_command() { + assert_eq!( + proc::parse_stat("9 (x)y) R 1 2 3 4 5 6 7 8 9 10 5 7 0"), + Some(12) + ); +} + +#[test] +fn malformed_stat_returns_none() { + assert_eq!(proc::parse_stat(""), None); + assert_eq!(proc::parse_stat("1234 (bash"), None); + assert_eq!(proc::parse_stat("1234 (bash) S 1 2 3"), None); + assert_eq!( + proc::parse_stat("1234 (bash) S a b c d e f g h i j x y"), + None + ); +} + +#[test] +fn loadavg_reads_the_first_field() { + assert_eq!( + proc::parse_loadavg("0.52 0.48 0.45 2/512 12345"), + Some(0.52) + ); + assert_eq!(proc::parse_loadavg(""), None); + assert_eq!(proc::parse_loadavg("not a number"), None); + assert_eq!(proc::parse_loadavg("-1.0 0.0 0.0"), None); +} + +#[test] +fn status_reads_vmrss_in_mebibytes() { + let text = "Name:\tcat\nState:\tR (running)\nVmRSS:\t 15360 kB\nThreads:\t4\n"; + assert_eq!(proc::parse_rss_mb(text), Some(15.0)); + assert_eq!(proc::parse_rss_mb("Name:\tcat\n"), None); + assert_eq!(proc::parse_rss_mb("VmRSS:\tgarbage kB\n"), None); +} + +#[test] +fn a_spike_becomes_the_window_maximum() { + let mut metrics = Metrics::default(); + metrics.record(Duration::from_millis(500), FrameWork::default()); + metrics.record( + Duration::from_millis(16), + FrameWork { + physics: Duration::from_millis(1), + render: Duration::from_millis(2), + steps: 16, + }, + ); + metrics.record( + Duration::from_millis(90), + FrameWork { + physics: Duration::from_millis(12), + render: Duration::from_millis(2), + steps: 18, + }, + ); + let stats = metrics.stats; + assert!( + (stats.frame_max_ms - 90.0).abs() < 0.5, + "frame max {}", + stats.frame_max_ms + ); + assert!( + (stats.physics_max_ms - 12.0).abs() < 0.5, + "physics max {}", + stats.physics_max_ms + ); + assert!( + (stats.frame_avg_ms - 53.0).abs() < 0.5, + "frame average {}", + stats.frame_avg_ms + ); + assert!(stats.tps > 0.0); +} + +#[test] +fn the_panel_draws_text_rectangles_and_lines() { + let mut metrics = Metrics::default(); + for _ in 0..4 { + metrics.record(Duration::from_millis(16), FrameWork::default()); + } + let mut overlay = Overlay::new(); + metrics.draw_panel(&mut overlay); + assert!(overlay.texts.len() >= 9, "one line per metric plus labels"); + assert!(!overlay.rects.is_empty(), "panel and graph background"); + assert!(!overlay.lines.is_empty(), "grid and series"); + assert!( + overlay + .texts + .iter() + .any(|text| text.text.starts_with("FPS")), + "the panel starts with the frame rate" + ); + assert!( + overlay.texts.iter().any(|text| text.text.contains("max")), + "the graph labels its maximum" + ); +} + +#[test] +fn the_graph_keeps_only_the_recent_frames() { + let mut metrics = Metrics::default(); + for _ in 0..(HISTORY + 25) { + metrics.record(Duration::from_millis(5), FrameWork::default()); + } + assert_eq!(metrics.history.len(), HISTORY); +} + +#[test] +fn the_window_holds_about_one_second() { + let mut metrics = Metrics::default(); + for _ in 0..200 { + metrics.record(Duration::from_millis(10), FrameWork::default()); + } + assert!( + metrics.window.len() <= 101, + "the window keeps {} samples", + metrics.window.len() + ); + assert!(metrics.window.len() > 10, "the window is not empty"); +} + +fn sample_stats() -> Stats { + Stats { + fps: 60.0, + tps: 999.5, + frame_avg_ms: 16.25, + frame_max_ms: 20.5, + physics_avg_ms: 0.5, + physics_max_ms: 1.25, + render_avg_ms: 2.0, + rtf: 1.0, + cpu_percent: 12.5, + load_1m: 0.75, + rss_mb: 312.5, + } +} + +fn sample_row(stats: &Stats, frame: u64, spike: bool) -> Row<'_> { + Row { + unix_s: 1_700_000_000.125, + t_s: 4.25, + frame, + stats, + spike, + } +} + +#[test] +fn the_csv_header_and_one_row_match_the_documented_columns() { + let stats = sample_stats(); + let row = sample_row(&stats, 42, true); + assert_eq!( + csv::HEADER, + "unix_s,t_s,frame,fps,tps,frame_ms,frame_max_ms,physics_ms,physics_max_ms,render_ms,rtf,cpu_pct,load1,rss_mb,spike" + ); + assert_eq!( + csv::format_row(&row), + "1700000000.125,4.250,42,60.0,999.5,16.25,20.50,0.50,1.25,2.00,1.00,12.5,0.75,312.5,1" + ); +} + +#[test] +fn a_spike_needs_a_slow_frame_or_a_slow_step() { + assert_eq!(spike_reason(20.0, 1.0), None); + assert_eq!(spike_reason(20.01, 1.0), Some("frame")); + assert_eq!(spike_reason(10.0, 1.01), Some("physics")); + assert_eq!(spike_reason(30.0, 2.0), Some("frame+physics")); +} + +#[test] +fn the_csv_truncates_unless_append_is_set() { + let dir = TempDir::new("csv"); + let path = dir.path.join("metrics.csv"); + let stats = sample_stats(); + { + let mut log = CsvLog::open(&path, false).expect("create the CSV"); + log.record(&sample_row(&stats, 1, false)) + .expect("first row"); + log.flush().expect("flush"); + } + { + let mut log = CsvLog::open(&path, true).expect("append to the CSV"); + log.record(&sample_row(&stats, 2, true)) + .expect("second row"); + log.flush().expect("flush"); + } + let text = std::fs::read_to_string(&path).expect("read the CSV"); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 3, "one header and two rows"); + assert_eq!(lines[0], csv::HEADER, "the header is written once"); + assert!(lines[1].starts_with("1700000000.125,4.250,1,")); + assert!(lines[1].ends_with(",0")); + assert!(lines[2].ends_with(",1")); + { + let mut log = CsvLog::open(&path, false).expect("truncate the CSV"); + log.record(&sample_row(&stats, 3, false)) + .expect("fresh row"); + log.flush().expect("flush"); + } + let text = std::fs::read_to_string(&path).expect("read the CSV"); + assert_eq!(text.lines().count(), 2, "header and one fresh row"); + assert!(text.lines().nth(1).is_some_and(|line| line.contains(",3,"))); +} diff --git a/crates/app/src/runtime/mod.rs b/crates/app/src/runtime/mod.rs index f76b54a..a894081 100644 --- a/crates/app/src/runtime/mod.rs +++ b/crates/app/src/runtime/mod.rs @@ -1 +1,101 @@ -//! fabrilis-app :: runtime - stub (see docs/ARCHITECTURE.md) +//! winit application loop for the M4c vertical slice. + +mod application; +mod camera; +mod config; +mod devlog; +mod error; +mod gpu; +mod metrics; +mod scene; +mod sim; + +pub use error::AppError; + +use devlog::DevLog; +use devlog::startup::StartupInfo; +use gpu::WindowRenderer; +use scene::View; +use winit::window::Window; + +use config::Config; +use metrics::CsvLog; + +/// Runs the window loop until the user closes the window or presses Escape. +pub fn run() -> Result<(), AppError> { + application::run() +} + +/// Parses the flags and environment, printing usage or the error. +fn parse_config() -> Config { + match Config::from_process() { + Ok(config::Outcome::Run(config)) => config, + Ok(config::Outcome::Help) => { + print!("{}", config::USAGE); + std::process::exit(0); + } + Err(error) => { + eprintln!("fabrilis: {error}"); + eprintln!("{}", config::USAGE); + std::process::exit(2); + } + } +} + +/// Opens the metrics CSV when a path was configured. +fn open_csv(config: &Config) -> Result, AppError> { + let Some(path) = &config.metrics_log else { + return Ok(None); + }; + CsvLog::open(path, config.append) + .map(Some) + .map_err(|error| AppError::Log(format!("{}: {error}", path.display()))) +} + +/// Writes the startup banner, reporting a write failure without stopping the app. +fn log_startup( + dev: Option<&mut DevLog>, + config: &Config, + view: &View, + renderer: &WindowRenderer, + window: &Window, +) { + let Some(dev) = dev else { + return; + }; + let gpu = renderer.info(); + let size = window.inner_size(); + let metrics_path = config + .metrics_log + .as_ref() + .map(|path| path.display().to_string()); + let log_path = config.log.as_ref().map(|path| path.display().to_string()); + let info = StartupInfo { + window: (size.width, size.height), + scale: window.scale_factor(), + terrain: view.terrain_config, + boxes: sim::DROPS.len(), + box_mass_kg: sim::BOX_MASS, + box_size_m: sim::BOX_SIZE, + eye: view.camera.eye(), + target: view.camera.target(), + adapter: &gpu.adapter, + driver: &gpu.driver, + surface: &gpu.surface, + metrics_path: metrics_path.as_deref(), + log_path: log_path.as_deref(), + dev: config.dev, + append: config.append, + }; + if let Err(error) = devlog::startup::write(dev, &info) { + eprintln!("fabrilis: dev log write failed: {error}"); + } +} + +fn aspect(size: winit::dpi::PhysicalSize) -> f32 { + if size.height == 0 { + 1.0 + } else { + size.width as f32 / size.height as f32 + } +} diff --git a/crates/app/src/runtime/scene.rs b/crates/app/src/runtime/scene.rs new file mode 100644 index 0000000..9c75445 --- /dev/null +++ b/crates/app/src/runtime/scene.rs @@ -0,0 +1,52 @@ +//! The seeded world shown by the window: terrain, camera and collider mesh. + +use fabrilis_render::{MeshData, Scene}; +use fabrilis_worldgen::terrain::{Heightmap, TerrainConfig, TerrainMesh}; + +use super::AppError; +use super::camera::FlyCamera; + +/// Render scene plus the geometry and camera state shared with physics. +pub(crate) struct View { + pub scene: Scene, + pub camera: FlyCamera, + pub heightmap: Heightmap, + pub terrain: TerrainMesh, + /// The parameters the heightmap was generated from. + pub terrain_config: TerrainConfig, +} + +/// Builds the M4c slice: seeded heightmap terrain and a fly camera. +pub(crate) fn build(aspect: f32) -> Result { + let config = TerrainConfig { + seed: 42, + size: 65, + extent: 100.0, + height_scale: 4.0, + ..Default::default() + }; + let heightmap = Heightmap::generate(config)?; + let terrain = heightmap.mesh(); + let mesh = MeshData { + vertices: terrain + .vertices + .iter() + .map(|vertex| [vertex.x as f32, vertex.y as f32, vertex.z as f32]) + .collect(), + indices: terrain + .indices + .iter() + .flat_map(|triangle| triangle.iter().copied()) + .collect(), + }; + let scene = Scene::new(mesh); + let target = heightmap.height_at(0.0, 0.0) as f32; + let camera = FlyCamera::look_at([10.0, -16.0, 7.5], [0.0, 0.0, target], aspect); + Ok(View { + scene, + camera, + heightmap, + terrain, + terrain_config: config, + }) +} diff --git a/crates/app/src/runtime/sim/mod.rs b/crates/app/src/runtime/sim/mod.rs new file mode 100644 index 0000000..74e6e0d --- /dev/null +++ b/crates/app/src/runtime/sim/mod.rs @@ -0,0 +1,162 @@ +//! Fixed-step physics for the boxes shown in the window. + +mod pacing; + +#[cfg(test)] +mod tests; + +use std::time::Duration; + +use fabrilis_core::time::SimDelta; +use fabrilis_core::units::Kilograms; +use fabrilis_core::vec::{Quat, Transform, Vec3}; +use fabrilis_physics::{BodyDesc, BodyId, PhysicsBackend, RapierBackend, ShapeDesc, TrimeshDesc}; +use fabrilis_render::{Instance, Scene}; +use fabrilis_worldgen::terrain::{Heightmap, TerrainMesh}; + +use crate::runtime::AppError; +use crate::runtime::metrics::Stopwatch; +use pacing::{MAX_STEPS, Pacer}; + +/// Physics rate; the step never changes with the frame time. +const HZ: u64 = 1_000; + +/// Edge length of each dropped box, metres. +pub(crate) const BOX_SIZE: f64 = 0.6; + +/// Mass of each dropped box, kilograms. +pub(crate) const BOX_MASS: f64 = 4.0; + +/// Horizontal offset and drop height above the terrain for each box. +pub(crate) const DROPS: [(f64, f64, f64); 3] = + [(-1.5, 0.4, 2.0), (1.2, -0.8, 3.6), (0.2, 1.8, 5.2)]; + +/// One colour per box, linear RGBA. +const COLORS: [[f32; 4]; 3] = [ + [0.85, 0.35, 0.15, 1.0], + [0.20, 0.55, 0.85, 1.0], + [0.85, 0.75, 0.20, 1.0], +]; + +struct BoxBody { + id: BodyId, + color: [f32; 4], +} + +/// The Rapier world and the boxes it drives. +pub(crate) struct Simulation { + backend: RapierBackend, + boxes: Vec, + step: SimDelta, + pacer: Pacer, + total_steps: u64, + slowest_step: Duration, +} + +impl Simulation { + /// Builds the terrain collider and drops the boxes into the scene. + pub(crate) fn new( + terrain: &TerrainMesh, + heightmap: &Heightmap, + scene: &mut Scene, + ) -> Result { + let step = SimDelta::from_hz(HZ).ok_or_else(|| { + AppError::Physics("physics step is not a whole nanosecond".to_owned()) + })?; + let mut backend = RapierBackend::new(); + let collider = TrimeshDesc { + vertices: terrain.vertices.clone(), + indices: terrain.indices.clone(), + position: Vec3::ZERO, + rotation: Quat::IDENTITY, + }; + backend + .add_trimesh(collider) + .ok_or_else(|| AppError::Physics("terrain collider was rejected".to_owned()))?; + scene.instances.clear(); + let mut boxes = Vec::with_capacity(DROPS.len()); + for (offset, color) in DROPS.iter().zip(COLORS) { + let (x, y, drop) = *offset; + let center = Vec3::new(x, y, heightmap.height_at(x, y) + drop + BOX_SIZE * 0.5); + let id = backend.add_body(BodyDesc::dynamic( + ShapeDesc::Cuboid { + half_extents: Vec3::new(BOX_SIZE * 0.5, BOX_SIZE * 0.5, BOX_SIZE * 0.5), + }, + Kilograms::new(BOX_MASS), + center, + )); + let size = BOX_SIZE as f32; + scene.instances.push(Instance::box_at( + [center.x as f32, center.y as f32, center.z as f32], + [size, size, size], + color, + )); + boxes.push(BoxBody { id, color }); + } + Ok(Self { + backend, + boxes, + step, + pacer: Pacer::new(), + total_steps: 0, + slowest_step: Duration::ZERO, + }) + } + + /// Runs the fixed steps owed for this frame and copies transforms to the scene. + /// + /// Diagnostics time each step individually, but only observe it: the number + /// of steps, their order and the Rapier calls stay exactly the same, so the + /// resulting state hash does not depend on logging being enabled. + pub(crate) fn advance(&mut self, scene: &mut Scene) -> pacing::Frame { + let frame = self.pacer.advance(self.step.nanos(), MAX_STEPS); + self.slowest_step = Duration::ZERO; + self.total_steps = self.total_steps.saturating_add(u64::from(frame.steps)); + for _ in 0..frame.steps { + let step_start = Stopwatch::start(); + self.backend.step(self.step); + self.slowest_step = self.slowest_step.max(step_start.elapsed()); + } + self.sync(scene); + frame + } + + /// Simulated seconds represented by the steps that have actually run. + #[must_use] + pub(crate) fn sim_seconds(&self) -> f64 { + self.total_steps as f64 * self.step.nanos() as f64 / 1_000_000_000.0 + } + + /// The slowest single physics step of the latest frame. + #[must_use] + pub(crate) fn slowest_step(&self) -> Duration { + self.slowest_step + } + + /// Copies every body transform into its rendered instance. + fn sync(&self, scene: &mut Scene) { + for (instance, body) in scene.instances.iter_mut().zip(&self.boxes) { + let Some(transform) = self.backend.body_transform(body.id) else { + continue; + }; + instance.model = model(transform, BOX_SIZE as f32); + instance.color = body.color; + } + } +} + +/// A column-major model matrix for a rotated, translated box. +fn model(transform: Transform, size: f32) -> [[f32; 4]; 4] { + let [x, y, z] = transform.rotation.to_mat3().cols(); + let [px, py, pz] = [ + transform.position.x as f32, + transform.position.y as f32, + transform.position.z as f32, + ]; + [ + [x.x as f32 * size, x.y as f32 * size, x.z as f32 * size, 0.0], + [y.x as f32 * size, y.y as f32 * size, y.z as f32 * size, 0.0], + [z.x as f32 * size, z.y as f32 * size, z.z as f32 * size, 0.0], + [px, py, pz, 1.0], + ] +} diff --git a/crates/app/src/runtime/sim/pacing.rs b/crates/app/src/runtime/sim/pacing.rs new file mode 100644 index 0000000..595ea70 --- /dev/null +++ b/crates/app/src/runtime/sim/pacing.rs @@ -0,0 +1,102 @@ +//! Wall-clock pacing for the fixed-step simulation. +//! +//! The physics step never changes: the wall clock only decides how many whole +//! steps to run for the frame and how far behind the simulation has fallen. + +use std::time::{Duration, Instant}; + +/// Largest number of physics steps run for one rendered frame. +pub(crate) const MAX_STEPS: u32 = 50; + +const NS_PER_S: u64 = 1_000_000_000; + +/// Wall time beyond this is treated as a stall and not caught up in full. +const MAX_FRAME_NS: u64 = 250_000_000; + +/// The RTF measurement window, roughly one second. +const WINDOW_NS: u64 = NS_PER_S; + +/// What one frame of wall time asks the simulation to do. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) struct Frame { + /// Whole fixed steps to run before drawing. + pub steps: u32, + /// Paced wall time of the frame, seconds, capped after a stall. + pub elapsed_seconds: f32, + /// Simulated-to-wall ratio for the latest window, once one has filled. + pub rtf: Option, +} + +/// Whole steps that fit into `elapsed_ns`, capped at `max_steps`. +#[must_use] +pub(crate) fn steps_for(elapsed_ns: u64, step_ns: u64, max_steps: u32) -> u32 { + if step_ns == 0 { + return 0; + } + u32::try_from(elapsed_ns / step_ns) + .unwrap_or(max_steps) + .min(max_steps) +} + +/// Converts a wall-clock duration to whole nanoseconds without overflowing. +fn nanos(duration: Duration) -> u64 { + u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX) +} + +/// An accumulator that turns irregular frame time into fixed steps. +pub(crate) struct Pacer { + last: Instant, + accumulator_ns: u64, + window_wall_ns: u64, + window_sim_ns: u64, +} + +impl Pacer { + #[allow( + clippy::disallowed_methods, + reason = "wall clock only paces the app loop" + )] + pub(crate) fn new() -> Self { + Self { + last: Instant::now(), + accumulator_ns: 0, + window_wall_ns: 0, + window_sim_ns: 0, + } + } + + /// Consumes the time since the previous call and returns the steps to run. + #[allow( + clippy::disallowed_methods, + reason = "wall clock only paces the app loop" + )] + pub(crate) fn advance(&mut self, step_ns: u64, max_steps: u32) -> Frame { + let now = Instant::now(); + let elapsed_ns = nanos(self.last.elapsed()); + self.last = now; + let paced_ns = elapsed_ns.min(MAX_FRAME_NS); + self.accumulator_ns = self.accumulator_ns.saturating_add(paced_ns); + let steps = steps_for(self.accumulator_ns, step_ns, max_steps); + let consumed_ns = u64::from(steps).saturating_mul(step_ns); + self.accumulator_ns = self.accumulator_ns.saturating_sub(consumed_ns); + if steps == max_steps && self.accumulator_ns >= step_ns { + // Drop the backlog instead of spiralling into ever longer frames. + self.accumulator_ns = 0; + } + self.window_wall_ns = self.window_wall_ns.saturating_add(elapsed_ns); + self.window_sim_ns = self.window_sim_ns.saturating_add(consumed_ns); + let rtf = if self.window_wall_ns >= WINDOW_NS { + let ratio = self.window_sim_ns as f32 / self.window_wall_ns as f32; + self.window_wall_ns = 0; + self.window_sim_ns = 0; + Some(ratio) + } else { + None + }; + Frame { + steps, + elapsed_seconds: paced_ns as f32 / NS_PER_S as f32, + rtf, + } + } +} diff --git a/crates/app/src/runtime/sim/tests.rs b/crates/app/src/runtime/sim/tests.rs new file mode 100644 index 0000000..291a66d --- /dev/null +++ b/crates/app/src/runtime/sim/tests.rs @@ -0,0 +1,41 @@ +//! Tests for the fixed-step accumulator. + +use super::pacing::{MAX_STEPS, steps_for}; + +const STEP_NS: u64 = 1_000_000; + +#[test] +fn no_time_means_no_steps() { + assert_eq!(steps_for(0, STEP_NS, MAX_STEPS), 0); +} + +#[test] +fn one_millisecond_is_one_step() { + assert_eq!(steps_for(STEP_NS, STEP_NS, MAX_STEPS), 1); +} + +#[test] +fn sixteen_milliseconds_are_sixteen_steps() { + assert_eq!(steps_for(16_000_000, STEP_NS, MAX_STEPS), 16); +} + +#[test] +fn partial_step_waits_for_the_next_frame() { + assert_eq!(steps_for(999_999, STEP_NS, MAX_STEPS), 0); + assert_eq!(steps_for(1_999_999, STEP_NS, MAX_STEPS), 1); +} + +#[test] +fn a_huge_gap_is_capped() { + assert_eq!(steps_for(5_000_000_000, STEP_NS, MAX_STEPS), MAX_STEPS); +} + +#[test] +fn a_zero_step_cannot_run() { + assert_eq!(steps_for(16_000_000, 0, MAX_STEPS), 0); +} + +#[test] +fn a_zero_cap_runs_nothing() { + assert_eq!(steps_for(16_000_000, STEP_NS, 0), 0); +} diff --git a/crates/core/src/units/mod.rs b/crates/core/src/units/mod.rs index c6116c4..91eadf7 100644 --- a/crates/core/src/units/mod.rs +++ b/crates/core/src/units/mod.rs @@ -123,6 +123,10 @@ quantity!(/// Acceleration, m/s². MetersPerSecondSquared); quantity!(/// Torque, N·m. NewtonMeters); +quantity!(/// Volume, m³. + CubicMeters); +quantity!(/// Density, kg/m³. + KilogramsPerCubicMeter); impl Radians { /// Converts degrees to radians; degrees exist only at the UI and import boundary. @@ -189,6 +193,13 @@ impl Mul for RadiansPerSecond { Radians(self.0 * rhs.0) } } +impl Mul for KilogramsPerCubicMeter { + type Output = Kilograms; + #[inline] + fn mul(self, rhs: CubicMeters) -> Kilograms { + Kilograms(self.0 * rhs.0) + } +} #[cfg(test)] mod tests; diff --git a/crates/core/src/units/tests.rs b/crates/core/src/units/tests.rs index fe9499e..3a3bc4f 100644 --- a/crates/core/src/units/tests.rs +++ b/crates/core/src/units/tests.rs @@ -39,3 +39,10 @@ fn derived_motion_units() { let rate = RadiansPerSecond(3.0); assert_eq!(rate * Seconds(2.0), Radians(6.0)); } + +#[test] +fn volume_and_density_give_mass() { + let volume = CubicMeters(0.002); + let steel = KilogramsPerCubicMeter(7_850.0); + assert!(((steel * volume).get() - 15.7).abs() < 1e-9); +} diff --git a/crates/materials/src/db/mod.rs b/crates/materials/src/db/mod.rs index 91d76ce..a326098 100644 --- a/crates/materials/src/db/mod.rs +++ b/crates/materials/src/db/mod.rs @@ -1 +1,89 @@ -//! fabrilis-materials :: db - stub (see docs/ARCHITECTURE.md) +//! A small material database keyed by a lowercase ASCII name. +//! +//! `BTreeMap` keeps iteration order deterministic (docs/DETERMINISM.md). + +use std::collections::BTreeMap; + +use fabrilis_core::units::{KilogramsPerCubicMeter, Pascals}; + +/// Mechanical properties of a homogeneous material, in SI units. +#[derive(Debug, Clone, PartialEq)] +pub struct Material { + /// Lowercase ASCII identifier, unique within a database. + pub name: String, + /// Density, kg/m³. + pub density: KilogramsPerCubicMeter, + /// Young's modulus, Pa. + pub youngs_modulus: Pascals, + /// Yield strength, Pa. + pub yield_strength: Pascals, +} + +/// Materials addressed by name. +#[derive(Debug, Clone, Default)] +pub struct MaterialDb { + materials: BTreeMap, +} + +impl MaterialDb { + /// An empty database. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// A database with the built-in materials: `steel`, `aluminium`, `pla`. + #[must_use] + pub fn with_builtins() -> Self { + let mut db = Self::new(); + for material in builtins() { + let _replaced = db.insert(material); + } + db + } + + /// Inserts or replaces a material and returns the previous entry. + pub fn insert(&mut self, material: Material) -> Option { + self.materials.insert(material.name.clone(), material) + } + + /// Looks up a material by name. + #[must_use] + pub fn get(&self, name: &str) -> Option<&Material> { + self.materials.get(name) + } + + /// Iterates over materials in name order. + pub fn iter(&self) -> impl Iterator + '_ { + self.materials + .iter() + .map(|(name, material)| (name.as_str(), material)) + } +} + +/// The three built-in materials, in name order. +fn builtins() -> [Material; 3] { + [ + Material { + name: String::from("aluminium"), + density: KilogramsPerCubicMeter(2700.0), + youngs_modulus: Pascals(69.0e9), + yield_strength: Pascals(200.0e6), + }, + Material { + name: String::from("pla"), + density: KilogramsPerCubicMeter(1240.0), + youngs_modulus: Pascals(3.5e9), + yield_strength: Pascals(50.0e6), + }, + Material { + name: String::from("steel"), + density: KilogramsPerCubicMeter(7850.0), + youngs_modulus: Pascals(210.0e9), + yield_strength: Pascals(250.0e6), + }, + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/materials/src/db/tests.rs b/crates/materials/src/db/tests.rs new file mode 100644 index 0000000..f367154 --- /dev/null +++ b/crates/materials/src/db/tests.rs @@ -0,0 +1,56 @@ +use fabrilis_core::units::{KilogramsPerCubicMeter, Pascals}; + +use super::*; + +#[test] +fn builtins_are_present() { + let db = MaterialDb::with_builtins(); + let steel = db.get("steel").unwrap(); + assert_eq!(steel.density, KilogramsPerCubicMeter(7850.0)); + assert_eq!(steel.youngs_modulus, Pascals(210.0e9)); + assert_eq!(steel.yield_strength, Pascals(250.0e6)); + + let aluminium = db.get("aluminium").unwrap(); + assert_eq!(aluminium.density, KilogramsPerCubicMeter(2700.0)); + assert_eq!(aluminium.youngs_modulus, Pascals(69.0e9)); + assert_eq!(aluminium.yield_strength, Pascals(200.0e6)); + + let pla = db.get("pla").unwrap(); + assert_eq!(pla.density, KilogramsPerCubicMeter(1240.0)); + assert_eq!(pla.youngs_modulus, Pascals(3.5e9)); + assert_eq!(pla.yield_strength, Pascals(50.0e6)); + + assert!(db.get("unobtainium").is_none()); +} + +#[test] +fn iter_is_sorted_and_empty_by_default() { + let db = MaterialDb::with_builtins(); + let names: Vec<&str> = db.iter().map(|(name, _)| name).collect(); + assert_eq!(names, ["aluminium", "pla", "steel"]); + + let empty = MaterialDb::new(); + assert_eq!(empty.iter().count(), 0); + assert!(empty.get("steel").is_none()); +} + +#[test] +fn insert_replaces_and_returns_old() { + let mut db = MaterialDb::new(); + let custom = Material { + name: String::from("steel"), + density: KilogramsPerCubicMeter(8000.0), + youngs_modulus: Pascals(200.0e9), + yield_strength: Pascals(300.0e6), + }; + assert!(db.insert(custom.clone()).is_none()); + assert_eq!(db.get("steel"), Some(&custom)); + + let replacement = Material { + density: KilogramsPerCubicMeter(8100.0), + ..custom.clone() + }; + let old = db.insert(replacement.clone()).unwrap(); + assert_eq!(old, custom); + assert_eq!(db.get("steel"), Some(&replacement)); +} diff --git a/crates/materials/src/massprops/mod.rs b/crates/materials/src/massprops/mod.rs index 1980fb0..40b554c 100644 --- a/crates/materials/src/massprops/mod.rs +++ b/crates/materials/src/massprops/mod.rs @@ -1 +1,144 @@ -//! fabrilis-materials :: massprops - stub (see docs/ARCHITECTURE.md) +//! Mass, centre of mass and inertia tensor of a closed triangle mesh. +//! +//! The mesh is decomposed into signed tetrahedra from the origin: +//! `V = a · (b × c) / 6` per triangle `(a, b, c)`. Summing the signed +//! contributions over a watertight surface gives the volume, the first moment and +//! the second moment directly, without any absolute-value branch. +//! +//! The caller must validate that the mesh is watertight and consistently oriented +//! outwards (signed volume positive). A closed mesh with inverted winding yields a +//! negative signed volume and is rejected here; an open mesh yields a wrong volume +//! and cannot be detected from the triangle soup alone. + +use fabrilis_core::units::{CubicMeters, Kilograms, KilogramsPerCubicMeter}; +use fabrilis_core::vec::{Mat3, Vec3}; + +/// Volumes at or below this bound (m³) are treated as degenerate. +const MIN_VOLUME: f64 = 1e-12; + +/// Mass properties of a solid, in SI units. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MassProperties { + /// Enclosed volume, m³. + pub volume: CubicMeters, + /// Mass, kg. + pub mass: Kilograms, + /// Centre of mass, m, in the mesh's axes. + pub center_of_mass: Vec3, + /// Inertia tensor about the centre of mass, kg·m², in world axes. + pub inertia: Mat3, +} + +/// The signed volume enclosed by a triangle soup, m³. +/// +/// Positive for a closed mesh wound outwards. No validation is performed here; +/// [`from_triangles`] is the checked entry point. +#[must_use] +pub fn signed_volume(triangles: &[[Vec3; 3]]) -> f64 { + triangles + .iter() + .map(|&[a, b, c]| a.dot(b.cross(c)) / 6.0) + .sum() +} + +/// Mass properties of a closed, outward-oriented triangle mesh. +/// +/// Returns `None` for empty or degenerate meshes (|volume| at or below +/// `MIN_VOLUME`), for a signed volume that is not positive (inverted or +/// inconsistent winding), for non-finite vertices or density, and for a +/// zero/negative density. Watertightness itself must be validated by the caller. +#[must_use] +pub fn from_triangles( + triangles: &[[Vec3; 3]], + density: KilogramsPerCubicMeter, +) -> Option { + let density = density.get(); + if !density.is_finite() || density <= 0.0 { + return None; + } + let mut accumulator = MomentAccumulator::default(); + for &[a, b, c] in triangles { + if !a.is_finite() || !b.is_finite() || !c.is_finite() { + return None; + } + accumulator.add(a, b, c); + } + accumulator.finish(density) +} + +/// Second moment about the origin, stored as `(xx, yy, zz, xy, xz, yz)`. +#[derive(Default)] +struct MomentAccumulator { + volume: f64, + first: Vec3, + second: [f64; 6], +} + +impl MomentAccumulator { + /// Adds the tetrahedron `(0, a, b, c)` with its signed volume. + fn add(&mut self, a: Vec3, b: Vec3, c: Vec3) { + let s = a + b + c; + let tetra_volume = a.dot(b.cross(c)) / 6.0; + self.volume += tetra_volume; + // Centroid of the tetrahedron is `s / 4`. + self.first += s * (tetra_volume * 0.25); + let scale = tetra_volume / 20.0; + let [xx, yy, zz, xy, xz, yz] = &mut self.second; + *xx += scale * (a.x * a.x + b.x * b.x + c.x * c.x + s.x * s.x); + *yy += scale * (a.y * a.y + b.y * b.y + c.y * c.y + s.y * s.y); + *zz += scale * (a.z * a.z + b.z * b.z + c.z * c.z + s.z * s.z); + *xy += scale * (a.x * a.y + b.x * b.y + c.x * c.y + s.x * s.y); + *xz += scale * (a.x * a.z + b.x * b.z + c.x * c.z + s.x * s.z); + *yz += scale * (a.y * a.z + b.y * b.z + c.y * c.z + s.y * s.z); + } + + /// Applies the parallel-axis theorem and builds the result. + fn finish(&self, density: f64) -> Option { + if !self.volume.is_finite() || self.volume <= MIN_VOLUME { + return None; + } + let mass = density * self.volume; + let center = self.first / self.volume; + if !mass.is_finite() || !center.is_finite() { + return None; + } + let inertia = self.inertia_about(center, mass); + if !inertia_is_finite(inertia) { + return None; + } + Some(MassProperties { + volume: CubicMeters(self.volume), + mass: Kilograms(mass), + center_of_mass: center, + inertia, + }) + } + + /// Inertia about the given point: `tr(C) I - C` shifted by the parallel axis. + fn inertia_about(&self, center: Vec3, mass: f64) -> Mat3 { + let [xx, yy, zz, xy, xz, yz] = self.second; + let (dx, dy, dz) = (center.x, center.y, center.z); + // Covariance is geometric (units of m⁵); density turns it into kg·m². + let density = mass / self.volume; + // `|d|² I - d dᵀ` moves the origin of the moments to `center`. + let i_xx = density * (yy + zz) - mass * (dy * dy + dz * dz); + let i_yy = density * (xx + zz) - mass * (dx * dx + dz * dz); + let i_zz = density * (xx + yy) - mass * (dx * dx + dy * dy); + let i_xy = mass * dx * dy - density * xy; + let i_xz = mass * dx * dz - density * xz; + let i_yz = mass * dy * dz - density * yz; + Mat3::from_cols( + Vec3::new(i_xx, i_xy, i_xz), + Vec3::new(i_xy, i_yy, i_yz), + Vec3::new(i_xz, i_yz, i_zz), + ) + } +} + +/// True when every entry of the matrix is finite. +fn inertia_is_finite(inertia: Mat3) -> bool { + inertia.cols().iter().all(|column| column.is_finite()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/materials/src/massprops/tests.rs b/crates/materials/src/massprops/tests.rs new file mode 100644 index 0000000..f8fa497 --- /dev/null +++ b/crates/materials/src/massprops/tests.rs @@ -0,0 +1,222 @@ +use fabrilis_core::math::{PI, TAU, sin_cos}; +use fabrilis_core::units::KilogramsPerCubicMeter; +use fabrilis_core::vec::Vec3; + +use super::*; + +const DENSITY: KilogramsPerCubicMeter = KilogramsPerCubicMeter(1000.0); + +/// Closed cube with outward winding; `faces` index the eight corners. +fn cube_triangles(center: Vec3, side: f64) -> Vec<[Vec3; 3]> { + let h = side * 0.5; + let corners = [ + Vec3::new(-h, -h, -h), + Vec3::new(h, -h, -h), + Vec3::new(h, h, -h), + Vec3::new(-h, h, -h), + Vec3::new(-h, -h, h), + Vec3::new(h, -h, h), + Vec3::new(h, h, h), + Vec3::new(-h, h, h), + ] + .map(|corner| center + corner); + let faces = [ + [0, 2, 1], + [0, 3, 2], + [4, 5, 6], + [4, 6, 7], + [1, 2, 6], + [1, 6, 5], + [0, 4, 7], + [0, 7, 3], + [3, 7, 6], + [3, 6, 2], + [0, 1, 5], + [0, 5, 4], + ]; + faces + .iter() + .map(|&[a, b, c]| [corners[a], corners[b], corners[c]]) + .collect() +} + +/// Latitude-longitude sphere with outward winding; poles are duplicated. +fn sphere_triangles(radius: f64, stacks: usize, slices: usize) -> Vec<[Vec3; 3]> { + let mut rings = Vec::with_capacity((stacks + 1) * slices); + for stack in 0..=stacks { + let theta = -PI / 2.0 + PI * stack as f64 / stacks as f64; + let (sin_theta, cos_theta) = sin_cos(theta); + for slice in 0..slices { + let phi = TAU * slice as f64 / slices as f64; + let (sin_phi, cos_phi) = sin_cos(phi); + rings.push(Vec3::new( + radius * cos_theta * cos_phi, + radius * cos_theta * sin_phi, + radius * sin_theta, + )); + } + } + let mut triangles = Vec::with_capacity(stacks * slices * 2); + for stack in 0..stacks { + let lower = stack * slices; + let upper = lower + slices; + for slice in 0..slices { + let next = (slice + 1) % slices; + triangles.push([ + rings[lower + slice], + rings[lower + next], + rings[upper + next], + ]); + triangles.push([ + rings[lower + slice], + rings[upper + next], + rings[upper + slice], + ]); + } + } + triangles +} + +/// Closed cylinder about Z with outward winding, caps fan-triangulated. +fn cylinder_triangles(radius: f64, height: f64, slices: usize) -> Vec<[Vec3; 3]> { + let half = height * 0.5; + let mut bottom = Vec::with_capacity(slices); + let mut top = Vec::with_capacity(slices); + for slice in 0..slices { + let angle = TAU * slice as f64 / slices as f64; + let (sin, cos) = sin_cos(angle); + bottom.push(Vec3::new(radius * cos, radius * sin, -half)); + top.push(Vec3::new(radius * cos, radius * sin, half)); + } + let mut triangles = Vec::with_capacity(slices * 4); + for slice in 0..slices { + let next = (slice + 1) % slices; + triangles.push([bottom[slice], bottom[next], top[next]]); + triangles.push([bottom[slice], top[next], top[slice]]); + triangles.push([Vec3::new(0.0, 0.0, half), top[slice], top[next]]); + triangles.push([Vec3::new(0.0, 0.0, -half), bottom[next], bottom[slice]]); + } + triangles +} + +/// Diagonal of an inertia tensor, kg·m². +fn inertia_diagonal(inertia: Mat3) -> [f64; 3] { + let columns = inertia.cols(); + [columns[0].x, columns[1].y, columns[2].z] +} + +fn close(actual: f64, expected: f64, tolerance: f64) -> bool { + (actual - expected).abs() <= tolerance +} + +fn assert_close(actual: f64, expected: f64, tolerance: f64) { + assert!( + (actual - expected).abs() <= tolerance, + "expected {expected}, got {actual}" + ); +} + +#[test] +fn cube_centred_at_origin() { + let mesh = cube_triangles(Vec3::ZERO, 1.0); + assert_close(signed_volume(&mesh), 1.0, 1e-12); + let props = from_triangles(&mesh, DENSITY).unwrap(); + assert!(close(props.volume.get(), 1.0, 1e-12)); + assert!(close(props.mass.get(), 1000.0, 1e-12)); + assert!(close(props.center_of_mass.x, 0.0, 1e-12)); + assert!(close(props.center_of_mass.y, 0.0, 1e-12)); + assert!(close(props.center_of_mass.z, 0.0, 1e-12)); + let expected = 1000.0 / 6.0; + for diagonal in inertia_diagonal(props.inertia) { + assert_close(diagonal, expected, 1e-12); + } + let columns = props.inertia.cols(); + assert_close(columns[0].y, 0.0, 1e-12); + assert_close(columns[0].z, 0.0, 1e-12); + assert_close(columns[1].x, 0.0, 1e-12); + assert_close(columns[1].z, 0.0, 1e-12); + assert_close(columns[2].x, 0.0, 1e-12); + assert_close(columns[2].y, 0.0, 1e-12); +} + +#[test] +fn cube_translated_keeps_inertia() { + let offset = Vec3::new(2.0, -1.0, 0.5); + let mesh = cube_triangles(offset, 1.0); + let props = from_triangles(&mesh, DENSITY).unwrap(); + assert_close(props.volume.get(), 1.0, 1e-12); + assert_close(props.center_of_mass.x, offset.x, 1e-12); + assert_close(props.center_of_mass.y, offset.y, 1e-12); + assert_close(props.center_of_mass.z, offset.z, 1e-12); + // The origin moments are large, so the parallel-axis subtraction loses a few + // digits: 1e-9 absolute on values around 167 kg·m². + let expected = props.mass.get() / 6.0; + for diagonal in inertia_diagonal(props.inertia) { + assert!(close(diagonal, expected, 1e-9)); + } +} + +#[test] +fn sphere_volume_and_inertia() { + let radius = 0.5; + let mesh = sphere_triangles(radius, 32, 64); + let props = from_triangles(&mesh, DENSITY).unwrap(); + let expected_volume = 4.0 / 3.0 * PI * radius * radius * radius; + assert!(close( + props.volume.get(), + expected_volume, + expected_volume * 0.01 + )); + let expected_inertia = 0.4 * props.mass.get() * radius * radius; + for diagonal in inertia_diagonal(props.inertia) { + assert!(close(diagonal, expected_inertia, expected_inertia * 0.02)); + } +} + +#[test] +fn cylinder_inertia_about_its_axis() { + let (radius, height) = (0.4, 1.2); + let mesh = cylinder_triangles(radius, height, 64); + let props = from_triangles(&mesh, KilogramsPerCubicMeter(2700.0)).unwrap(); + let expected_volume = PI * radius * radius * height; + assert!(close( + props.volume.get(), + expected_volume, + expected_volume * 0.01 + )); + let expected = 0.5 * props.mass.get() * radius * radius; + assert!(close(props.inertia.cols()[2].z, expected, expected * 0.02)); + // The cylinder is centred on the origin. + assert_close(props.center_of_mass.z, 0.0, 1e-12); +} + +#[test] +fn rejects_open_or_inverted_soup() { + assert!(from_triangles(&[], DENSITY).is_none()); + // Inverted winding: volume is negative, so the orientation is wrong. + let mut inverted = cube_triangles(Vec3::ZERO, 1.0); + for triangle in &mut inverted { + triangle.swap(1, 2); + } + assert_close(signed_volume(&inverted), -1.0, 1e-12); + assert!(from_triangles(&inverted, DENSITY).is_none()); + // A single triangle through the origin encloses no volume. + let flat = [[Vec3::ZERO, Vec3::X, Vec3::Y]]; + assert_eq!(signed_volume(&flat), 0.0); + assert!(from_triangles(&flat, DENSITY).is_none()); +} + +#[test] +fn rejects_bad_density() { + let mesh = cube_triangles(Vec3::ZERO, 1.0); + assert!(from_triangles(&mesh, KilogramsPerCubicMeter(0.0)).is_none()); + assert!(from_triangles(&mesh, KilogramsPerCubicMeter(-100.0)).is_none()); + assert!(from_triangles(&mesh, KilogramsPerCubicMeter(f64::INFINITY)).is_none()); +} + +#[test] +fn rejects_non_finite_vertices() { + let mut mesh = cube_triangles(Vec3::ZERO, 1.0); + mesh[0][0].x = f64::NAN; + assert!(from_triangles(&mesh, DENSITY).is_none()); +} diff --git a/crates/materials/src/strength/mod.rs b/crates/materials/src/strength/mod.rs index 49b68b3..da7de9a 100644 --- a/crates/materials/src/strength/mod.rs +++ b/crates/materials/src/strength/mod.rs @@ -1 +1,50 @@ -//! fabrilis-materials :: strength - stub (see docs/ARCHITECTURE.md) +//! A minimal static strength check at a single stress value. +//! +//! The load path and stress distribution are the caller's business; this module +//! only compares a stress with the material's yield strength. + +use fabrilis_core::units::Pascals; + +/// Yield data used for a static check. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Strength { + /// Yield strength of the material, Pa. + pub yield_strength: Pascals, +} + +impl Strength { + /// Yield strength divided by the applied stress. + /// + /// `None` for a non-positive or non-finite stress, and when the resulting + /// factor is not finite. + #[must_use] + pub fn factor_of_safety(self, stress: Pascals) -> Option { + let stress = stress.get(); + if !stress.is_finite() || stress <= 0.0 { + return None; + } + let factor = self.yield_strength.get() / stress; + if factor.is_finite() { + Some(factor) + } else { + None + } + } + + /// True when the factor of safety reaches `required`. + /// + /// `required` must be finite and positive; any invalid input is unsafe. + #[must_use] + pub fn is_safe(self, stress: Pascals, required: f64) -> bool { + if !required.is_finite() || required <= 0.0 { + return false; + } + match self.factor_of_safety(stress) { + Some(factor) => factor >= required, + None => false, + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/materials/src/strength/tests.rs b/crates/materials/src/strength/tests.rs new file mode 100644 index 0000000..6c95ce2 --- /dev/null +++ b/crates/materials/src/strength/tests.rs @@ -0,0 +1,43 @@ +use fabrilis_core::units::Pascals; + +use super::*; + +fn steel() -> Strength { + Strength { + yield_strength: Pascals(250.0e6), + } +} + +#[test] +fn factor_of_safety_is_yield_over_stress() { + let factor = steel().factor_of_safety(Pascals(100.0e6)).unwrap(); + assert!((factor - 2.5).abs() < 1e-12); + let factor = steel().factor_of_safety(Pascals(250.0e6)).unwrap(); + assert!((factor - 1.0).abs() < 1e-12); + assert!(steel().factor_of_safety(Pascals(500.0e6)).unwrap() < 1.0); +} + +#[test] +fn factor_of_safety_rejects_bad_stress() { + assert!(steel().factor_of_safety(Pascals(0.0)).is_none()); + assert!(steel().factor_of_safety(Pascals(-1.0)).is_none()); + assert!(steel().factor_of_safety(Pascals(f64::NAN)).is_none()); + assert!(steel().factor_of_safety(Pascals(f64::INFINITY)).is_none()); +} + +#[test] +fn is_safe_compares_with_required_factor() { + assert!(steel().is_safe(Pascals(100.0e6), 2.5)); + assert!(!steel().is_safe(Pascals(100.0e6), 2.6)); + assert!(steel().is_safe(Pascals(250.0e6), 1.0)); + assert!(!steel().is_safe(Pascals(250.0e6), 1.1)); +} + +#[test] +fn is_safe_rejects_invalid_input() { + assert!(!steel().is_safe(Pascals(0.0), 1.0)); + assert!(!steel().is_safe(Pascals(-10.0), 1.0)); + assert!(!steel().is_safe(Pascals(100.0e6), 0.0)); + assert!(!steel().is_safe(Pascals(100.0e6), -1.0)); + assert!(!steel().is_safe(Pascals(100.0e6), f64::NAN)); +} diff --git a/crates/modes/Cargo.toml b/crates/modes/Cargo.toml index 6a0487c..1c48adc 100644 --- a/crates/modes/Cargo.toml +++ b/crates/modes/Cargo.toml @@ -28,5 +28,8 @@ fabrilis-bridge = { path = "../bridge" } fabrilis-worldgen = { path = "../worldgen" } fabrilis-scripting = { path = "../scripting" } +[dev-dependencies] +fabrilis-sensors = { path = "../sensors" } + [build-dependencies] fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/modes/tests/box_drops.rs b/crates/modes/tests/box_drops.rs new file mode 100644 index 0000000..34b1bed --- /dev/null +++ b/crates/modes/tests/box_drops.rs @@ -0,0 +1,129 @@ +//! M4c regression: the three dropped boxes settle upright and stay put. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + reason = "test helper: a failure should abort the test" +)] + +use fabrilis_core::time::SimDelta; +use fabrilis_core::units::Kilograms; +use fabrilis_core::vec::{Quat, Vec3}; +use fabrilis_physics::RapierBackend; +use fabrilis_physics::backend::{BodyDesc, PhysicsBackend, ShapeDesc, TrimeshDesc}; +use fabrilis_worldgen::terrain::{Heightmap, TerrainConfig}; + +const BOX: f64 = 0.6; +const DROPS: [(f64, f64, f64); 3] = [(-1.5, 0.4, 2.0), (1.2, -0.8, 3.6), (0.2, 1.8, 5.2)]; + +#[test] +fn dropped_boxes_settle_and_stop() { + let mut config = TerrainConfig { + seed: 42, + size: 65, + extent: 100.0, + height_scale: 4.0, + ..TerrainConfig::default() + }; + config.frequency = 2.0; + let map = Heightmap::generate(config).expect("terrain"); + let mesh = map.mesh(); + let mut world = RapierBackend::new(); + world + .add_trimesh(TrimeshDesc { + vertices: mesh.vertices, + indices: mesh.indices, + position: Vec3::ZERO, + rotation: Quat::IDENTITY, + }) + .expect("terrain collider"); + let mut bodies = Vec::new(); + for (x, y, drop) in DROPS { + let center = Vec3::new(x, y, map.height_at(x, y) + drop + BOX * 0.5); + bodies.push(world.add_body(BodyDesc::dynamic( + ShapeDesc::Cuboid { + half_extents: Vec3::new(BOX * 0.5, BOX * 0.5, BOX * 0.5), + }, + Kilograms::new(4.0), + center, + ))); + } + let dt = SimDelta::from_hz(1_000).expect("1 kHz"); + let mut before = Vec::new(); + for step in 0..5_000 { + world.step(dt); + if step == 3_999 { + before = bodies + .iter() + .map(|&body| world.body_transform(body).expect("body").position) + .collect(); + } + } + for (index, &body) in bodies.iter().enumerate() { + let transform = world.body_transform(body).expect("body"); + let ground = map.height_at(transform.position.x, transform.position.y); + println!( + "box {index}: pos {:?} ground {ground:.3}", + transform.position + ); + assert!( + transform.position.z >= ground - 0.05, + "box {index} sank through the terrain" + ); + let moved = (transform.position - before[index]).length(); + assert!(moved < 1e-3, "box {index} still moves: {moved}"); + } +} + +/// Diagnostic: `cargo test -p fabrilis-modes --test box_drops -- --ignored --nocapture`. +#[test] +#[ignore = "diagnostic timing, not a pass/fail test"] +#[allow( + clippy::disallowed_methods, + reason = "diagnostic timing uses the wall clock on purpose" +)] +fn physics_step_time_spikes() { + let config = TerrainConfig { + seed: 42, + size: 65, + extent: 100.0, + height_scale: 4.0, + frequency: 2.0, + ..TerrainConfig::default() + }; + let map = Heightmap::generate(config).expect("terrain"); + let mesh = map.mesh(); + let mut world = RapierBackend::new(); + world + .add_trimesh(TrimeshDesc { + vertices: mesh.vertices, + indices: mesh.indices, + position: Vec3::ZERO, + rotation: Quat::IDENTITY, + }) + .expect("terrain collider"); + for (x, y, drop) in DROPS { + let center = Vec3::new(x, y, map.height_at(x, y) + drop + BOX * 0.5); + world.add_body(BodyDesc::dynamic( + ShapeDesc::Cuboid { + half_extents: Vec3::new(BOX * 0.5, BOX * 0.5, BOX * 0.5), + }, + Kilograms::new(4.0), + center, + )); + } + let dt = SimDelta::from_hz(1_000).expect("1 kHz"); + let mut times = Vec::with_capacity(5_000); + for _ in 0..5_000 { + let start = std::time::Instant::now(); + world.step(dt); + times.push((start.elapsed().as_secs_f64() * 1_000.0, times.len())); + } + let total: f64 = times.iter().map(|&(ms, _)| ms).sum(); + let mut sorted = times.clone(); + sorted.sort_by(|a, b| b.0.total_cmp(&a.0)); + println!("mean step {:.3} ms, total {:.1} ms", total / 5_000.0, total); + for &(ms, index) in sorted.iter().take(10) { + println!("slow step {index}: {ms:.3} ms"); + } +} diff --git a/crates/modes/tests/joint_control.rs b/crates/modes/tests/joint_control.rs new file mode 100644 index 0000000..3a1934c --- /dev/null +++ b/crates/modes/tests/joint_control.rs @@ -0,0 +1,150 @@ +//! M2 closed loop: a link on a revolute joint is lifted by a PD controller that reads +//! a delayed encoder instead of the ground-truth state. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + reason = "test helper: a failure should abort the test" +)] + +use fabrilis_core::snapshot::hash::StateHasher; +use fabrilis_core::time::SimDelta; +use fabrilis_core::units::{Kilograms, Radians}; +use fabrilis_core::vec::{Quat, Vec3}; +use fabrilis_physics::backend::{BodyDesc, PhysicsBackend, ShapeDesc}; +use fabrilis_physics::joints::RevoluteDesc; +use fabrilis_physics::{BodyId, JointId, RapierBackend}; +use fabrilis_sensors::encoder::{Encoder, EncoderConfig}; + +const KP: f64 = 400.0; +const KD: f64 = 25.0; +const TARGET: f64 = 0.0; +const STEPS: usize = 3_000; +const GOLDEN: u64 = 0x014e_e966_1ea1_d0ce; + +struct Rig { + world: RapierBackend, + encoder: Encoder, + link: BodyId, + joint: JointId, + dt: SimDelta, + previous_raw: f64, + continuous: f64, +} + +impl Rig { + fn new(start_degrees: f64) -> Self { + let mut world = RapierBackend::new(); + let base = world.add_body(BodyDesc::fixed( + ShapeDesc::Cuboid { + half_extents: Vec3::new(0.05, 0.05, 0.05), + }, + Vec3::ZERO, + )); + let start = Quat::from_axis_angle(Vec3::Y, Radians::from_degrees(start_degrees)) + .expect("the Y axis is non-zero"); + let mut link_desc = BodyDesc::dynamic( + ShapeDesc::Cuboid { + half_extents: Vec3::new(0.5, 0.05, 0.05), + }, + Kilograms::new(1.0), + start.rotate(Vec3::new(0.5, 0.0, 0.0)), + ); + link_desc.rotation = start; + let link = world.add_body(link_desc); + let joint = world.add_revolute(RevoluteDesc::new( + base, + link, + Vec3::Y, + Vec3::ZERO, + Vec3::new(-0.5, 0.0, 0.0), + )); + let mut encoder = Encoder::new( + EncoderConfig { + resolution_bits: 16, + noise_sigma: 0.0, + bias: 0.0, + delay_steps: 1, + }, + 1, + ) + .expect("the encoder configuration is valid"); + let dt = SimDelta::from_hz(1_000).expect("1 kHz divides a second"); + let first_truth = world.joint_angle(joint).expect("the joint exists"); + let _primed = encoder.sample(first_truth); + let previous_raw = encoder.sample(first_truth).get(); + Self { + world, + encoder, + link, + joint, + dt, + previous_raw, + continuous: wrap_to_pi(previous_raw), + } + } + + fn control_step(&mut self) -> Radians { + let truth = self + .world + .joint_angle(self.joint) + .expect("the joint exists"); + let raw = self.encoder.sample(truth).get(); + let delta = wrap_to_pi(raw - self.previous_raw); + self.continuous += delta; + self.previous_raw = raw; + let rate = delta / self.dt.as_seconds().get(); + let torque = KP * (TARGET - self.continuous) - KD * rate; + self.world.apply_torque(self.link, Vec3::Y * torque); + self.world.step(self.dt); + self.world + .joint_angle(self.joint) + .expect("the joint exists") + } + + fn state(&self) -> (f64, f64) { + let transform = self + .world + .body_transform(self.link) + .expect("the link exists"); + (transform.position.z, transform.rotation.y) + } +} + +fn run() -> (f64, f64, u64) { + let mut rig = Rig::new(60.0); + let mut hasher = StateHasher::new(); + let mut final_angle = 0.0; + let mut tail_max: f64 = 0.0; + for step in 0..STEPS { + let angle = rig.control_step(); + let (z, qy) = rig.state(); + hasher.write_u64(step as u64); + hasher.write_f64(angle.get()); + hasher.write_f64(z); + hasher.write_f64(qy); + final_angle = angle.get(); + if step > 1_000 { + tail_max = tail_max.max((angle.get() - TARGET).abs()); + } + } + (final_angle, tail_max, hasher.finish()) +} + +#[test] +fn pd_controller_lifts_the_link_to_the_target_angle() { + let (final_angle, tail_max, _) = run(); + assert!(final_angle.abs() < 0.02, "final angle = {final_angle}"); + assert!(tail_max < 0.02, "tail maximum error = {tail_max}"); +} + +#[test] +fn the_closed_loop_is_deterministic() { + let (_, _, hash) = run(); + assert_eq!(hash, GOLDEN, "new hash: {hash:#018x}"); +} + +fn wrap_to_pi(angle: f64) -> f64 { + let two_pi = fabrilis_core::math::TAU; + (angle + core::f64::consts::PI).rem_euclid(two_pi) - core::f64::consts::PI +} diff --git a/crates/modes/tests/terrain_rest.rs b/crates/modes/tests/terrain_rest.rs new file mode 100644 index 0000000..fd0a30e --- /dev/null +++ b/crates/modes/tests/terrain_rest.rs @@ -0,0 +1,129 @@ +//! M4a: terrain generated from a seed carries a body without falling through. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + reason = "test helper: a failure should abort the test" +)] + +use fabrilis_core::snapshot::hash::StateHasher; +use fabrilis_core::time::SimDelta; +use fabrilis_core::units::Kilograms; +use fabrilis_core::vec::{Quat, Vec3}; +use fabrilis_physics::RapierBackend; +use fabrilis_physics::backend::{BodyDesc, PhysicsBackend, ShapeDesc, TrimeshDesc}; +use fabrilis_worldgen::terrain::{Heightmap, TerrainConfig}; + +const STEPS: usize = 3_000; + +fn terrain(seed: u64, height_scale: f64, size: usize) -> (RapierBackend, Heightmap) { + let config = TerrainConfig { + seed, + size, + extent: 100.0, + height_scale, + frequency: 2.0, + octaves: 4, + ..TerrainConfig::default() + }; + let map = Heightmap::generate(config).expect("the terrain configuration is valid"); + let mesh = map.mesh(); + let mut world = RapierBackend::new(); + let terrain = world + .add_trimesh(TrimeshDesc { + vertices: mesh.vertices, + indices: mesh.indices, + position: Vec3::ZERO, + rotation: Quat::IDENTITY, + }) + .expect("the terrain mesh is valid"); + assert!(world.body_transform(terrain).is_some()); + (world, map) +} + +#[test] +fn a_ball_rests_on_flat_terrain() { + let (mut world, _map) = terrain(1, 0.0, 33); + let radius = 0.25; + let ball = world.add_body(BodyDesc::dynamic( + ShapeDesc::Ball { radius }, + Kilograms::new(1.0), + Vec3::new(0.0, 0.0, 3.0), + )); + let dt = SimDelta::from_hz(1_000).expect("1 kHz divides a second"); + for _ in 0..STEPS { + world.step(dt); + } + let z = world + .body_transform(ball) + .expect("the ball exists") + .position + .z; + assert!((z - radius).abs() < 0.02, "ball z = {z}"); +} + +#[test] +fn a_box_stays_above_a_seeded_relief() { + let (world, map) = terrain(42, 4.0, 65); + let mut world = world; + let start = map.height_at(0.0, 0.0) + 3.0; + let body = world.add_body(BodyDesc::dynamic( + ShapeDesc::Cuboid { + half_extents: Vec3::new(0.25, 0.25, 0.1), + }, + Kilograms::new(5.0), + Vec3::new(0.0, 0.0, start), + )); + let dt = SimDelta::from_hz(1_000).expect("1 kHz divides a second"); + for _ in 0..STEPS { + world.step(dt); + } + let position = world.body_transform(body).expect("the box exists").position; + assert!(position.is_finite()); + let ground = map.height_at(position.x, position.y); + assert!( + position.z >= ground - 0.05, + "box at {position:?} below terrain {ground}" + ); +} + +#[test] +fn the_terrain_scene_is_deterministic() { + let (first, second) = (run_scene(), run_scene()); + assert_eq!(first.0.x.to_bits(), second.0.x.to_bits()); + assert_eq!(first.0.y.to_bits(), second.0.y.to_bits()); + assert_eq!(first.0.z.to_bits(), second.0.z.to_bits()); + assert_eq!(first.1, second.1); +} + +#[test] +fn the_terrain_trajectory_matches_golden() { + let (_, hash) = run_scene(); + assert_eq!(hash, GOLDEN, "new hash: {hash:#018x}"); +} + +const GOLDEN: u64 = 0xbb09_e470_43d3_1f2e; + +fn run_scene() -> (Vec3, u64) { + let (mut world, map) = terrain(42, 4.0, 65); + let start = map.height_at(0.0, 0.0) + 3.0; + let body = world.add_body(BodyDesc::dynamic( + ShapeDesc::Cuboid { + half_extents: Vec3::new(0.25, 0.25, 0.1), + }, + Kilograms::new(5.0), + Vec3::new(0.0, 0.0, start), + )); + let dt = SimDelta::from_hz(1_000).expect("1 kHz divides a second"); + let mut hasher = StateHasher::new(); + let mut last = Vec3::ZERO; + for step in 0..1_000 { + world.step(dt); + last = world.body_transform(body).expect("the box exists").position; + hasher.write_u64(step as u64); + hasher.write_f64(last.x); + hasher.write_f64(last.y); + hasher.write_f64(last.z); + } + (last, hasher.finish()) +} diff --git a/crates/physics/Cargo.toml b/crates/physics/Cargo.toml index cad52a3..9cceabf 100644 --- a/crates/physics/Cargo.toml +++ b/crates/physics/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] fabrilis-core = { path = "../core" } +rapier3d-f64 = { version = "0.36", features = ["enhanced-determinism"] } [build-dependencies] fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/physics/src/backend/mod.rs b/crates/physics/src/backend/mod.rs index d626421..12d7962 100644 --- a/crates/physics/src/backend/mod.rs +++ b/crates/physics/src/backend/mod.rs @@ -1 +1,149 @@ -//! fabrilis-physics :: backend - stub (see docs/ARCHITECTURE.md) +//! The engine-agnostic physics contract. +//! +//! Subsystems above physics talk to this trait, never to Rapier directly. All +//! values cross the boundary in SI units and the project's Z-up world frame +//! (docs/COORDINATES.md). + +use fabrilis_core::time::SimDelta; +use fabrilis_core::units::{Kilograms, Radians}; +use fabrilis_core::vec::{Quat, Transform, Vec3}; + +use crate::joints::{JointId, RevoluteDesc}; + +/// A handle to a body owned by a [`PhysicsBackend`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct BodyId(pub(crate) u32); + +impl BodyId { + /// The dense index behind the handle, for snapshots and diagnostics. + #[must_use] + pub const fn index(self) -> u32 { + self.0 + } +} + +/// Whether a body is immovable or integrated by the solver. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BodyKind { + /// Static geometry: infinite mass, never moves. + Fixed, + /// Simulated body: moves under gravity, contacts and joint reactions. + Dynamic, +} + +/// The collision shape of a body. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum ShapeDesc { + /// A box aligned with the body frame, given by its half extents. + Cuboid { + /// Half the box size along each local axis, metres. + half_extents: Vec3, + }, + /// A sphere centred on the body frame. + Ball { + /// Radius, metres. + radius: f64, + }, +} + +/// A static triangle mesh, used for terrain. +/// +/// The mesh owns its vertex buffers, so unlike [`ShapeDesc`] it is not `Copy`; +/// it is passed to [`PhysicsBackend::add_trimesh`] by value. Dynamic trimesh +/// bodies are out of scope for now: the created body is always fixed. +#[derive(Debug, Clone, PartialEq)] +pub struct TrimeshDesc { + /// Mesh vertices in the local frame of the body, metres. + pub vertices: Vec, + /// Zero-based triangles indexing `vertices`, one triangle per entry. + pub indices: Vec<[u32; 3]>, + /// World position of the local frame, metres. + pub position: Vec3, + /// World orientation of the local frame. + pub rotation: Quat, +} + +/// Everything needed to create a body. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BodyDesc { + /// Fixed or dynamic. + pub kind: BodyKind, + /// Total mass, kilograms; ignored for fixed bodies. + pub mass: Kilograms, + /// Collision shape. + pub shape: ShapeDesc, + /// Initial world position, metres. + pub position: Vec3, + /// Initial orientation. + pub rotation: Quat, +} + +impl BodyDesc { + /// A dynamic body at rest with no rotation. + #[must_use] + pub fn dynamic(shape: ShapeDesc, mass: Kilograms, position: Vec3) -> Self { + Self { + kind: BodyKind::Dynamic, + mass, + shape, + position, + rotation: Quat::IDENTITY, + } + } + + /// A fixed body at rest with no rotation. + #[must_use] + pub fn fixed(shape: ShapeDesc, position: Vec3) -> Self { + Self { + kind: BodyKind::Fixed, + mass: Kilograms::ZERO, + shape, + position, + rotation: Quat::IDENTITY, + } + } +} + +/// The simulation operations available to the rest of the engine. +pub trait PhysicsBackend { + /// Adds a body and returns its handle. + fn add_body(&mut self, desc: BodyDesc) -> BodyId; + + /// Adds a static triangle mesh (terrain) and returns its handle. + /// + /// The mesh is fixed terrain: it never moves and is not integrated by the + /// solver. `vertices` are in the local frame; `position` and `rotation` + /// place that frame in the Z-up world. Indices are zero-based triangles; + /// winding follows the right-hand rule (counter-clockwise seen from the + /// front), while terrain contacts themselves are two-sided. + /// + /// Returns `None` for an empty mesh, an empty index list, out-of-range + /// indices, non-finite vertices or placement, or a degenerate/zero-area + /// mesh that Rapier rejects. Invalid input never panics and leaves the + /// backend usable. Dynamic trimesh bodies are out of scope for now. + fn add_trimesh(&mut self, desc: TrimeshDesc) -> Option; + + /// Adds a revolute joint between two existing bodies and returns its handle. + fn add_revolute(&mut self, desc: RevoluteDesc) -> JointId; + + /// Drives a joint towards `target` with a spring-like position motor. + /// + /// `stiffness` and `damping` use the backend's motor units; unknown joints are + /// ignored. See [`RapierBackend`](crate::rapier::RapierBackend) for the model. + fn set_motor_position(&mut self, joint: JointId, target: Radians, stiffness: f64, damping: f64); + + /// Sets the world-frame torque for the next step, N·m; replaces the previous one. + /// + /// A controller calls this every step; unknown bodies are ignored. + fn apply_torque(&mut self, body: BodyId, torque: Vec3); + + /// Advances the simulation by `dt`. + fn step(&mut self, dt: SimDelta); + + /// The current world transform of a body, or `None` for an unknown handle. + fn body_transform(&self, id: BodyId) -> Option; + + /// The current angle of a revolute joint in `[-π, π]`, or `None` for an + /// unknown handle. + fn joint_angle(&self, id: JointId) -> Option; +} diff --git a/crates/physics/src/joints/mod.rs b/crates/physics/src/joints/mod.rs index cc00154..6cc2908 100644 --- a/crates/physics/src/joints/mod.rs +++ b/crates/physics/src/joints/mod.rs @@ -1 +1,49 @@ -//! fabrilis-physics :: joints - stub (see docs/ARCHITECTURE.md) +//! Joint descriptions shared by every backend. + +use fabrilis_core::vec::Vec3; + +use crate::backend::BodyId; + +/// A handle to a joint owned by a [`PhysicsBackend`](crate::backend::PhysicsBackend). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct JointId(pub(crate) u32); + +impl JointId { + /// The dense index behind the handle, for snapshots and diagnostics. + #[must_use] + pub const fn index(self) -> u32 { + self.0 + } +} + +/// A hinge that allows only relative rotation around `axis`. +/// +/// `anchor_a` and `anchor_b` are the same physical point expressed in each +/// body's local frame, so a correct joint starts with the anchors coincident. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RevoluteDesc { + /// The body the joint frame is measured from. + pub body_a: BodyId, + /// The body that rotates relative to `body_a`. + pub body_b: BodyId, + /// Hinge axis in the local frames of both bodies; normalized by the backend. + pub axis: Vec3, + /// Hinge point in the local frame of `body_a`, metres. + pub anchor_a: Vec3, + /// Hinge point in the local frame of `body_b`, metres. + pub anchor_b: Vec3, +} + +impl RevoluteDesc { + /// A hinge with the given bodies, axis and local anchors. + #[must_use] + pub fn new(body_a: BodyId, body_b: BodyId, axis: Vec3, anchor_a: Vec3, anchor_b: Vec3) -> Self { + Self { + body_a, + body_b, + axis, + anchor_a, + anchor_b, + } + } +} diff --git a/crates/physics/src/lib.rs b/crates/physics/src/lib.rs index 37d91ff..275a677 100644 --- a/crates/physics/src/lib.rs +++ b/crates/physics/src/lib.rs @@ -3,3 +3,7 @@ pub mod backend; pub mod contact; pub mod joints; pub mod rapier; + +pub use backend::{BodyDesc, BodyId, BodyKind, PhysicsBackend, ShapeDesc, TrimeshDesc}; +pub use joints::{JointId, RevoluteDesc}; +pub use rapier::RapierBackend; diff --git a/crates/physics/src/rapier/mod.rs b/crates/physics/src/rapier/mod.rs index 1201585..cdd93ce 100644 --- a/crates/physics/src/rapier/mod.rs +++ b/crates/physics/src/rapier/mod.rs @@ -1 +1,268 @@ -//! fabrilis-physics :: rapier - stub (see docs/ARCHITECTURE.md) +//! Rapier adapter: translates the project's SI/Z-up descriptions into Rapier +//! handles and copies state back. See docs/DETERMINISM.md for the Rapier +//! determinism caveats. + +use fabrilis_core::time::SimDelta; +use fabrilis_core::units::{Kilograms, Radians}; +use fabrilis_core::vec::{Quat, Transform, Vec3}; +use rapier3d_f64::dynamics::{ + CCDSolver, ImpulseJointHandle, ImpulseJointSet, IntegrationParameters, IslandManager, + JointAxis, MultibodyJointSet, RevoluteJoint, RevoluteJointBuilder, RigidBodyBuilder, + RigidBodyHandle, RigidBodySet, SoftBodySet, +}; +use rapier3d_f64::geometry::{ColliderBuilder, ColliderSet, DefaultBroadPhase, NarrowPhase}; +use rapier3d_f64::math::{Pose, Rotation, Vector}; +use rapier3d_f64::pipeline::PhysicsPipeline; + +use crate::backend::{BodyDesc, BodyId, BodyKind, PhysicsBackend, ShapeDesc, TrimeshDesc}; +use crate::joints::{JointId, RevoluteDesc}; + +/// Standard gravity in the project's Z-up world frame, m/s². +pub const EARTH_GRAVITY: Vec3 = Vec3::new(0.0, 0.0, -9.81); + +/// A Rapier world behind the [`PhysicsBackend`] trait. +pub struct RapierBackend { + gravity: Vector, + integration: IntegrationParameters, + pipeline: PhysicsPipeline, + islands: IslandManager, + broad_phase: DefaultBroadPhase, + narrow_phase: NarrowPhase, + bodies: RigidBodySet, + colliders: ColliderSet, + joints: ImpulseJointSet, + multibody_joints: MultibodyJointSet, + soft_bodies: SoftBodySet, + ccd_solver: CCDSolver, + body_handles: Vec, + joint_handles: Vec>, +} + +impl RapierBackend { + /// A world with standard gravity, Z down 9.81 m/s². + #[must_use] + pub fn new() -> Self { + Self::with_gravity(EARTH_GRAVITY) + } + + /// A world with an explicit gravity vector, m/s². + #[must_use] + pub fn with_gravity(gravity: Vec3) -> Self { + Self { + gravity: vector(gravity), + integration: IntegrationParameters::default(), + pipeline: PhysicsPipeline::new(), + islands: IslandManager::new(), + broad_phase: DefaultBroadPhase::default(), + narrow_phase: NarrowPhase::new(), + bodies: RigidBodySet::new(), + colliders: ColliderSet::new(), + joints: ImpulseJointSet::new(), + multibody_joints: MultibodyJointSet::new(), + soft_bodies: SoftBodySet::new(), + ccd_solver: CCDSolver::new(), + body_handles: Vec::new(), + joint_handles: Vec::new(), + } + } + + fn body_handle(&self, id: BodyId) -> Option { + self.body_handles.get(id.0 as usize).copied() + } + + fn joint_handle(&self, id: JointId) -> Option { + self.joint_handles.get(id.0 as usize).copied().flatten() + } +} + +impl Default for RapierBackend { + fn default() -> Self { + Self::new() + } +} + +impl PhysicsBackend for RapierBackend { + fn add_body(&mut self, desc: BodyDesc) -> BodyId { + let builder = match desc.kind { + BodyKind::Fixed => RigidBodyBuilder::fixed(), + BodyKind::Dynamic => RigidBodyBuilder::dynamic(), + }; + let pose = Pose::from_parts(vector(desc.position), rotation(desc.rotation)); + let handle = self.bodies.insert(builder.pose(pose).build()); + let collider = collider(desc.shape, desc.mass); + self.colliders + .insert_with_parent(collider, handle, &mut self.bodies); + let id = BodyId(self.body_handles.len() as u32); + self.body_handles.push(handle); + id + } + + fn add_trimesh(&mut self, desc: TrimeshDesc) -> Option { + // Frame placement first: a non-finite pose must be rejected before any + // Rapier data exists. Rapier normalizes the quaternion itself; a zero + // quaternion falls back to the identity. + if !desc.position.is_finite() || !quat_is_finite(desc.rotation) { + return None; + } + let (vertices, indices) = trimesh_buffers(desc.vertices, desc.indices)?; + // Rapier rejects an empty index list; other degenerate meshes are + // reported through the error result instead of panicking. + let collider = ColliderBuilder::trimesh(vertices, indices).ok()?; + let pose = Pose::from_parts(vector(desc.position), rotation(desc.rotation)); + let handle = self + .bodies + .insert(RigidBodyBuilder::fixed().pose(pose).build()); + self.colliders + .insert_with_parent(collider, handle, &mut self.bodies); + let id = BodyId(self.body_handles.len() as u32); + self.body_handles.push(handle); + Some(id) + } + + fn add_revolute(&mut self, desc: RevoluteDesc) -> JointId { + let id = JointId(self.joint_handles.len() as u32); + let Some(body_a) = self.body_handle(desc.body_a) else { + self.joint_handles.push(None); + return id; + }; + let Some(body_b) = self.body_handle(desc.body_b) else { + self.joint_handles.push(None); + return id; + }; + let axis = desc.axis.normalized().unwrap_or(Vec3::Z); + // Linked bodies often overlap around a hinge, so contacts between the pair + // are disabled; both still collide with the rest of the world. + let joint = RevoluteJointBuilder::new(vector(axis)) + .local_anchor1(vector(desc.anchor_a)) + .local_anchor2(vector(desc.anchor_b)) + .contacts_enabled(false); + let handle = self.joints.insert(body_a, body_b, joint, true); + self.joint_handles.push(Some(handle)); + id + } + + fn set_motor_position( + &mut self, + joint: JointId, + target: Radians, + stiffness: f64, + damping: f64, + ) { + let Some(handle) = self.joint_handle(joint) else { + return; + }; + let Some(entry) = self.joints.get_mut(handle, true) else { + return; + }; + entry + .data + .set_motor_position(JointAxis::AngX, target.get(), stiffness, damping); + } + + fn apply_torque(&mut self, body: BodyId, torque: Vec3) { + let Some(handle) = self.body_handle(body) else { + return; + }; + if let Some(entry) = self.bodies.get_mut(handle) { + // Rapier keeps user torques until they are cleared, so this sets the torque + // for the coming step instead of accumulating it every step. + entry.reset_torques(true); + entry.add_torque(vector(torque), true); + } + } + + fn step(&mut self, dt: SimDelta) { + let seconds = dt.as_seconds().get(); + if seconds <= 0.0 { + return; + } + self.integration.dt = seconds; + self.pipeline.step( + self.gravity, + &self.integration, + &mut self.islands, + &mut self.broad_phase, + &mut self.narrow_phase, + &mut self.bodies, + &mut self.colliders, + &mut self.joints, + &mut self.multibody_joints, + &mut self.soft_bodies, + &mut self.ccd_solver, + &(), + &(), + ); + } + + fn body_transform(&self, id: BodyId) -> Option { + let body = self.bodies.get(self.body_handle(id)?)?; + let translation = body.translation(); + let rotation = body.rotation(); + Some(Transform::new( + Vec3::new(translation.x, translation.y, translation.z), + Quat::new(rotation.w, rotation.x, rotation.y, rotation.z), + )) + } + + fn joint_angle(&self, id: JointId) -> Option { + let joint = self.joints.get(self.joint_handle(id)?)?; + let body_a = self.bodies.get(joint.body1())?; + let body_b = self.bodies.get(joint.body2())?; + let revolute = RevoluteJoint { data: joint.data }; + Some(Radians::new( + revolute.angle(body_a.rotation(), body_b.rotation()), + )) + } +} + +fn vector(v: Vec3) -> Vector { + Vector::new(v.x, v.y, v.z) +} + +fn rotation(q: Quat) -> Rotation { + let unit = q.normalize().unwrap_or(Quat::IDENTITY); + Rotation::from_xyzw(unit.x, unit.y, unit.z, unit.w) +} + +fn collider(shape: ShapeDesc, mass: Kilograms) -> ColliderBuilder { + let builder = match shape { + ShapeDesc::Cuboid { half_extents } => { + ColliderBuilder::cuboid(half_extents.x, half_extents.y, half_extents.z) + } + ShapeDesc::Ball { radius } => ColliderBuilder::ball(radius), + }; + builder.mass(mass.get()) +} + +fn quat_is_finite(q: Quat) -> bool { + q.w.is_finite() && q.x.is_finite() && q.y.is_finite() && q.z.is_finite() +} + +/// Validates a trimesh and converts it to Rapier's point type. +/// +/// Rapier does not check index bounds while building its BVH and would panic or +/// read garbage on a bad index, so every index is validated here first. A mesh +/// needs at least one triangle, hence at least three vertices. +fn trimesh_buffers( + vertices: Vec, + indices: Vec<[u32; 3]>, +) -> Option<(Vec, Vec<[u32; 3]>)> { + if indices.is_empty() || vertices.len() < 3 { + return None; + } + let vertex_count = u32::try_from(vertices.len()).ok()?; + if indices.iter().flatten().any(|&index| index >= vertex_count) { + return None; + } + let mut points = Vec::with_capacity(vertices.len()); + for vertex in vertices { + if !vertex.is_finite() { + return None; + } + points.push(vector(vertex)); + } + Some((points, indices)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/physics/src/rapier/tests.rs b/crates/physics/src/rapier/tests.rs new file mode 100644 index 0000000..81576b3 --- /dev/null +++ b/crates/physics/src/rapier/tests.rs @@ -0,0 +1,285 @@ +use super::*; +use crate::backend::{BodyDesc, BodyId, PhysicsBackend, ShapeDesc, TrimeshDesc}; +use crate::joints::{JointId, RevoluteDesc}; +use fabrilis_core::time::SimDelta; +use fabrilis_core::units::{Kilograms, Radians}; +use fabrilis_core::vec::{Quat, Vec3}; + +fn step_at(hz: u64) -> SimDelta { + SimDelta::from_hz(hz).expect("1 kHz divides a second evenly") +} + +fn build_motor_world() -> (RapierBackend, BodyId, JointId) { + let mut world = RapierBackend::new(); + let base = world.add_body(BodyDesc::fixed( + ShapeDesc::Cuboid { + half_extents: Vec3::new(0.05, 0.05, 0.05), + }, + Vec3::ZERO, + )); + let link = world.add_body(BodyDesc::dynamic( + ShapeDesc::Cuboid { + half_extents: Vec3::new(0.5, 0.05, 0.05), + }, + Kilograms::new(1.0), + Vec3::new(0.5, 0.0, 0.0), + )); + let joint = world.add_revolute(RevoluteDesc::new( + base, + link, + Vec3::Z, + Vec3::ZERO, + Vec3::new(-0.5, 0.0, 0.0), + )); + world.set_motor_position(joint, Radians::new(1.0), 100.0, 20.0); + (world, link, joint) +} + +#[test] +fn free_body_falls_under_gravity() { + let mut world = RapierBackend::new(); + let body = world.add_body(BodyDesc::dynamic( + ShapeDesc::Ball { radius: 0.2 }, + Kilograms::new(1.0), + Vec3::new(0.0, 0.0, 10.0), + )); + let dt = step_at(1_000); + let steps = 100; + for _ in 0..steps { + world.step(dt); + } + let z = world + .body_transform(body) + .expect("the body exists") + .position + .z; + let t = (steps as f64) * dt.as_seconds().get(); + let expected = 10.0 - 0.5 * EARTH_GRAVITY.z.abs() * t * t; + assert!(z < 10.0); + assert!( + (z - expected).abs() < 1e-3, + "z = {z}, expected = {expected}" + ); +} + +#[test] +fn motor_reaches_target_angle() { + let (mut world, _link, joint) = build_motor_world(); + let dt = step_at(1_000); + for _ in 0..2_000 { + world.step(dt); + } + let angle = world.joint_angle(joint).expect("the joint exists"); + assert!((angle.get() - 1.0).abs() <= 0.02, "angle = {}", angle.get()); + for _ in 0..200 { + world.step(dt); + let settled = world.joint_angle(joint).expect("the joint exists"); + assert!( + (settled.get() - 1.0).abs() <= 0.02, + "settled angle = {}", + settled.get() + ); + } +} + +#[test] +fn identical_worlds_match_bitwise() { + let (mut first, first_body, first_joint) = build_motor_world(); + let (mut second, second_body, second_joint) = build_motor_world(); + let dt = step_at(1_000); + for _ in 0..500 { + first.step(dt); + second.step(dt); + } + let a = first.body_transform(first_body).expect("the body exists"); + let b = second.body_transform(second_body).expect("the body exists"); + assert_eq!(a.position.x.to_bits(), b.position.x.to_bits()); + assert_eq!(a.position.y.to_bits(), b.position.y.to_bits()); + assert_eq!(a.position.z.to_bits(), b.position.z.to_bits()); + assert_eq!(a.rotation.w.to_bits(), b.rotation.w.to_bits()); + assert_eq!(a.rotation.x.to_bits(), b.rotation.x.to_bits()); + assert_eq!(a.rotation.y.to_bits(), b.rotation.y.to_bits()); + assert_eq!(a.rotation.z.to_bits(), b.rotation.z.to_bits()); + let angle_a = first.joint_angle(first_joint).expect("the joint exists"); + let angle_b = second.joint_angle(second_joint).expect("the joint exists"); + assert_eq!(angle_a.get().to_bits(), angle_b.get().to_bits()); +} + +#[test] +fn unknown_ids_return_none() { + let mut world = RapierBackend::new(); + assert!(world.body_transform(BodyId(u32::MAX)).is_none()); + assert!(world.joint_angle(JointId(u32::MAX)).is_none()); + world.set_motor_position(JointId(7), Radians::new(1.0), 1.0, 1.0); + assert!(world.body_transform(BodyId(7)).is_none()); + assert!(world.joint_angle(JointId(7)).is_none()); +} + +fn flat_terrain() -> TrimeshDesc { + TrimeshDesc { + vertices: vec![ + Vec3::new(-5.0, -5.0, 0.0), + Vec3::new(5.0, -5.0, 0.0), + Vec3::new(5.0, 5.0, 0.0), + Vec3::new(-5.0, 5.0, 0.0), + ], + indices: vec![[0, 1, 2], [0, 2, 3]], + position: Vec3::ZERO, + rotation: Quat::IDENTITY, + } +} + +fn dropped_ball(world: &mut RapierBackend, radius: f64, position: Vec3) -> BodyId { + world.add_body(BodyDesc::dynamic( + ShapeDesc::Ball { radius }, + Kilograms::new(1.0), + position, + )) +} + +#[test] +fn ball_settles_on_flat_trimesh() { + let mut world = RapierBackend::new(); + let terrain = world + .add_trimesh(flat_terrain()) + .expect("flat terrain is valid"); + assert!(world.body_transform(terrain).is_some()); + let radius = 0.25; + let ball = dropped_ball(&mut world, radius, Vec3::new(0.75, -0.5, 5.0)); + let dt = step_at(1_000); + for _ in 0..2_000 { + world.step(dt); + } + let resting = world + .body_transform(ball) + .expect("the ball exists") + .position; + assert!( + (resting.z - radius).abs() <= 0.05, + "resting z = {}, radius = {radius}", + resting.z + ); + for _ in 0..500 { + world.step(dt); + let z = world + .body_transform(ball) + .expect("the ball exists") + .position + .z; + assert!((z - radius).abs() <= 0.05, "drifted z = {z}"); + } +} + +#[test] +fn trimesh_worlds_match_bitwise() { + let mut first = RapierBackend::new(); + let mut second = RapierBackend::new(); + assert!(first.add_trimesh(flat_terrain()).is_some()); + assert!(second.add_trimesh(flat_terrain()).is_some()); + let first_ball = dropped_ball(&mut first, 0.25, Vec3::new(0.75, -0.5, 5.0)); + let second_ball = dropped_ball(&mut second, 0.25, Vec3::new(0.75, -0.5, 5.0)); + let dt = step_at(1_000); + for _ in 0..500 { + first.step(dt); + second.step(dt); + } + let a = first.body_transform(first_ball).expect("the ball exists"); + let b = second.body_transform(second_ball).expect("the ball exists"); + assert_eq!(a.position.x.to_bits(), b.position.x.to_bits()); + assert_eq!(a.position.y.to_bits(), b.position.y.to_bits()); + assert_eq!(a.position.z.to_bits(), b.position.z.to_bits()); +} + +#[test] +fn invalid_trimesh_is_rejected_and_backend_stays_usable() { + let mut world = RapierBackend::new(); + let empty_vertices = TrimeshDesc { + vertices: Vec::new(), + indices: vec![[0, 1, 2]], + position: Vec3::ZERO, + rotation: Quat::IDENTITY, + }; + let empty_indices = TrimeshDesc { + vertices: flat_terrain().vertices, + indices: Vec::new(), + position: Vec3::ZERO, + rotation: Quat::IDENTITY, + }; + let out_of_range = TrimeshDesc { + vertices: flat_terrain().vertices, + indices: vec![[0, 1, 4]], + position: Vec3::ZERO, + rotation: Quat::IDENTITY, + }; + let mut non_finite_vertices = flat_terrain().vertices; + non_finite_vertices[0] = Vec3::new(f64::NAN, 0.0, 0.0); + let non_finite = TrimeshDesc { + vertices: non_finite_vertices, + indices: vec![[0, 1, 2]], + position: Vec3::ZERO, + rotation: Quat::IDENTITY, + }; + for desc in [empty_vertices, empty_indices, out_of_range, non_finite] { + assert!(world.add_trimesh(desc).is_none()); + } + let ball = dropped_ball(&mut world, 0.2, Vec3::new(0.0, 0.0, 1.0)); + let dt = step_at(1_000); + world.step(dt); + let z = world + .body_transform(ball) + .expect("the ball exists") + .position + .z; + assert!(z < 1.0, "the ball did not fall, z = {z}"); +} + +/// Height of the plane through the origin with `normal` at `x`, `y`. +fn plane_z(normal: Vec3, x: f64, y: f64) -> f64 { + -(normal.x * x + normal.y * y) / normal.z +} + +#[test] +fn ball_stays_above_inclined_trimesh() { + let rotation = + Quat::from_axis_angle(Vec3::Y, Radians::new(0.3)).expect("the Y axis is nonzero"); + let terrain = TrimeshDesc { + vertices: vec![ + Vec3::new(-50.0, -50.0, 0.0), + Vec3::new(50.0, -50.0, 0.0), + Vec3::new(50.0, 50.0, 0.0), + Vec3::new(-50.0, 50.0, 0.0), + ], + indices: vec![[0, 1, 2], [0, 2, 3]], + position: Vec3::ZERO, + rotation, + }; + let normal = rotation.rotate(Vec3::Z); + let mut world = RapierBackend::new(); + assert!(world.add_trimesh(terrain).is_some()); + let radius = 0.25; + let ball = dropped_ball(&mut world, radius, Vec3::new(0.0, 0.0, 3.0)); + let dt = step_at(1_000); + for step in 0..2_000 { + world.step(dt); + let position = world + .body_transform(ball) + .expect("the ball exists") + .position; + let surface = plane_z(normal, position.x, position.y); + assert!( + position.z > surface, + "step {step}: z = {} under surface {surface}", + position.z + ); + } + let position = world + .body_transform(ball) + .expect("the ball exists") + .position; + let surface = plane_z(normal, position.x, position.y); + assert!( + (position.z - surface - radius / normal.z).abs() <= 0.1, + "ball left the slope: z = {}, surface = {surface}", + position.z + ); +} diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 0ad6dd2..f6eafa1 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -11,6 +11,9 @@ workspace = true [dependencies] fabrilis-core = { path = "../core" } +bytemuck = { version = "1", features = ["derive"] } +fontdue = "0.9" +wgpu = "30" [build-dependencies] fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/render/src/camera.rs b/crates/render/src/camera.rs new file mode 100644 index 0000000..e5bf700 --- /dev/null +++ b/crates/render/src/camera.rs @@ -0,0 +1,128 @@ +//! Renderer-local perspective camera. +//! +//! The camera works in the world frame: Z is up and the projection targets the +//! WebGPU depth range `0..=1`. All arithmetic is `f32` because the camera only +//! feeds the renderer and never the authoritative simulation. + +use fabrilis_core::math; + +type Mat4 = [[f32; 4]; 4]; +type Vec3 = [f32; 3]; + +/// A right-handed perspective camera with an explicit look-at pose. +#[derive(Debug, Clone, Copy)] +pub struct Camera { + eye: Vec3, + target: Vec3, + up: Vec3, + fov_y: f32, + aspect: f32, + near: f32, + far: f32, +} + +impl Camera { + /// A camera at `eye` looking at `target`, with sensible projection defaults. + #[must_use] + pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self { + Self { + eye, + target, + up, + fov_y: 0.9, + aspect: 1.0, + near: 0.1, + far: 500.0, + } + } + + /// Replaces the projection parameters, clamping them to usable values. + #[must_use] + pub fn with_projection(mut self, fov_y: f32, aspect: f32, near: f32, far: f32) -> Self { + self.fov_y = fov_y.clamp(0.01, 3.0); + self.aspect = aspect.max(0.0001); + self.near = near.max(0.0001); + self.far = far.max(self.near + 0.0001); + self + } + + /// Updates the aspect ratio after a surface resize. + pub fn set_aspect(&mut self, aspect: f32) { + self.aspect = aspect.max(0.0001); + } + + /// The eye position in world space. + #[must_use] + pub fn eye(&self) -> Vec3 { + self.eye + } + + /// The combined view-projection matrix in column-major order. + #[must_use] + pub fn view_projection(&self) -> Mat4 { + multiply(&self.projection(), &self.view()) + } + + fn view(&self) -> Mat4 { + let forward = normalize(sub(self.target, self.eye), [0.0, 1.0, 0.0]); + let side = normalize(cross(forward, self.up), [1.0, 0.0, 0.0]); + let up = cross(side, forward); + [ + [side[0], up[0], -forward[0], 0.0], + [side[1], up[1], -forward[1], 0.0], + [side[2], up[2], -forward[2], 0.0], + [ + -dot(side, self.eye), + -dot(up, self.eye), + dot(forward, self.eye), + 1.0, + ], + ] + } + + fn projection(&self) -> Mat4 { + let scale = 1.0 / math::tan(f64::from(self.fov_y) * 0.5) as f32; + let depth = self.far / (self.near - self.far); + [ + [scale / self.aspect, 0.0, 0.0, 0.0], + [0.0, scale, 0.0, 0.0], + [0.0, 0.0, depth, -1.0], + [0.0, 0.0, depth * self.near, 0.0], + ] + } +} + +fn sub(left: Vec3, right: Vec3) -> Vec3 { + [left[0] - right[0], left[1] - right[1], left[2] - right[2]] +} + +fn dot(left: Vec3, right: Vec3) -> f32 { + left[0] * right[0] + left[1] * right[1] + left[2] * right[2] +} + +fn cross(left: Vec3, right: Vec3) -> Vec3 { + [ + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ] +} + +fn normalize(vector: Vec3, fallback: Vec3) -> Vec3 { + let length = dot(vector, vector).sqrt(); + if length > 1.0e-6 { + [vector[0] / length, vector[1] / length, vector[2] / length] + } else { + fallback + } +} + +fn multiply(left: &Mat4, right: &Mat4) -> Mat4 { + let mut product = [[0.0; 4]; 4]; + for (column, output) in product.iter_mut().enumerate() { + for (row, value) in output.iter_mut().enumerate() { + *value = (0..4).map(|k| left[k][row] * right[column][k]).sum(); + } + } + product +} diff --git a/crates/render/src/ctx/mod.rs b/crates/render/src/ctx/mod.rs deleted file mode 100644 index 5a52856..0000000 --- a/crates/render/src/ctx/mod.rs +++ /dev/null @@ -1 +0,0 @@ -//! fabrilis-render :: ctx - stub (see docs/ARCHITECTURE.md) diff --git a/crates/render/src/error.rs b/crates/render/src/error.rs new file mode 100644 index 0000000..c98e2da --- /dev/null +++ b/crates/render/src/error.rs @@ -0,0 +1,37 @@ +//! Renderer errors. + +use core::fmt; + +/// Why a renderer resource could not be created or used. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RenderError { + /// No suitable GPU adapter was found. + Adapter(String), + /// The logical device could not be created. + Device(String), + /// A window surface operation failed. + Surface(String), + /// A texture could not be allocated or read back. + Texture(String), + /// A buffer could not be allocated or mapped. + Buffer(String), + /// The requested pixel format is not supported by the readback path. + UnsupportedFormat(String), +} + +impl fmt::Display for RenderError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Adapter(detail) => write!(formatter, "GPU adapter unavailable: {detail}"), + Self::Device(detail) => write!(formatter, "GPU device unavailable: {detail}"), + Self::Surface(detail) => write!(formatter, "surface failure: {detail}"), + Self::Texture(detail) => write!(formatter, "texture failure: {detail}"), + Self::Buffer(detail) => write!(formatter, "buffer failure: {detail}"), + Self::UnsupportedFormat(detail) => { + write!(formatter, "unsupported pixel format: {detail}") + } + } + } +} + +impl std::error::Error for RenderError {} diff --git a/crates/render/src/gpu/mod.rs b/crates/render/src/gpu/mod.rs new file mode 100644 index 0000000..c832982 --- /dev/null +++ b/crates/render/src/gpu/mod.rs @@ -0,0 +1,100 @@ +//! Headless GPU device creation. +//! +//! The window path lives in the application: it owns the surface and passes the +//! device and queue to [`crate::Renderer`]. + +use std::future::Future; +use std::sync::Arc; +use std::task::{Context, Poll, Wake, Waker}; +use std::thread::{self, Thread}; + +use crate::RenderError; + +/// A logical device and its queue, created without a window surface. +#[derive(Debug, Clone)] +pub struct Gpu { + device: wgpu::Device, + queue: wgpu::Queue, +} + +impl Gpu { + /// Requests a high-performance adapter, retrying with a fallback adapter. + pub fn headless() -> Result { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = request_adapter(&instance)?; + let (device, queue) = block_on(adapter.request_device(&device_descriptor())) + .map_err(|error| RenderError::Device(error.to_string()))?; + Ok(Self { device, queue }) + } + + /// The device that owns renderer resources. + #[must_use] + pub fn device(&self) -> &wgpu::Device { + &self.device + } + + /// The queue used to upload data and submit commands. + #[must_use] + pub fn queue(&self) -> &wgpu::Queue { + &self.queue + } +} + +/// Device limits and features used by both the app and headless tests. +#[must_use] +pub fn device_descriptor() -> wgpu::DeviceDescriptor<'static> { + wgpu::DeviceDescriptor { + label: Some("fabrilis device"), + required_features: wgpu::Features::empty(), + required_limits: wgpu::Limits::default(), + experimental_features: wgpu::ExperimentalFeatures::default(), + memory_hints: wgpu::MemoryHints::default(), + trace: wgpu::Trace::Off, + } +} + +fn request_adapter(instance: &wgpu::Instance) -> Result { + let options = wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::HighPerformance, + compatible_surface: None, + force_fallback_adapter: false, + ..Default::default() + }; + match block_on(instance.request_adapter(&options)) { + Ok(adapter) => Ok(adapter), + Err(primary) => { + let fallback = wgpu::RequestAdapterOptions { + force_fallback_adapter: true, + ..options + }; + block_on(instance.request_adapter(&fallback)).map_err(|secondary| { + RenderError::Adapter(format!("{primary}; fallback adapter: {secondary}")) + }) + } + } +} + +struct ThreadWake(Thread); + +impl Wake for ThreadWake { + fn wake(self: Arc) { + self.0.unpark(); + } + + fn wake_by_ref(self: &Arc) { + self.0.unpark(); + } +} + +/// Blocks on a future without pulling in an async runtime. +fn block_on(future: F) -> F::Output { + let waker = Waker::from(Arc::new(ThreadWake(thread::current()))); + let mut context = Context::from_waker(&waker); + let mut future = std::pin::pin!(future); + loop { + match future.as_mut().poll(&mut context) { + Poll::Ready(value) => return value, + Poll::Pending => thread::park(), + } + } +} diff --git a/crates/render/src/instancing/mod.rs b/crates/render/src/instancing/mod.rs deleted file mode 100644 index 4c00e93..0000000 --- a/crates/render/src/instancing/mod.rs +++ /dev/null @@ -1 +0,0 @@ -//! fabrilis-render :: instancing - stub (see docs/ARCHITECTURE.md) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1c50bfa..914a1d5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -1,5 +1,22 @@ -//! Custom wgpu renderer: clipmap terrain, instancing, compute culling, view modes (stress, temperature) -pub mod ctx; -pub mod instancing; -pub mod terrain; -pub mod views; +//! Custom wgpu renderer: depth-tested terrain meshes, instanced boxes, one +//! directional light. +//! +//! The renderer is not part of the authoritative simulation: it may use `f32` +//! and never reads wall-clock time. Headless use builds a [`Gpu`] and renders +//! into an offscreen texture; the app owns its surface and calls +//! [`Renderer::draw_to`]. + +pub mod camera; +pub mod error; +pub mod gpu; +pub mod overlay; +pub mod renderer; +pub mod scene; + +pub use camera::Camera; +pub use error::RenderError; +pub use gpu::Gpu; +pub use overlay::{Overlay, OverlayLine, OverlayRect, OverlayText}; +pub use renderer::Renderer; +pub use scene::{Instance, MeshData, Scene}; +pub use wgpu; diff --git a/crates/render/src/overlay/atlas.rs b/crates/render/src/overlay/atlas.rs new file mode 100644 index 0000000..d6de68f --- /dev/null +++ b/crates/render/src/overlay/atlas.rs @@ -0,0 +1,193 @@ +//! CPU-side glyph packing for the overlay text atlas. +//! +//! The atlas is a single `R8` image: one byte of coverage per texel. Glyphs are +//! packed shelf by shelf and cached by `(char, pixel size)`, so a glyph is +//! rasterized and uploaded once per size. + +/// Edge length of the square atlas texture, texels. +pub(super) const SIZE: u32 = 1024; + +/// Empty texels kept between glyphs so linear filtering cannot bleed. +const PADDING: u32 = 1; + +/// UV of a texel that is always opaque white, shared by solid rectangles and +/// lines so they can use the text pipeline. +pub(super) const WHITE_UV: [f32; 2] = [1.0 / 1024.0, 1.0 / 1024.0]; + +/// A rectangle of the atlas that has to be uploaded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Region { + pub(super) x: u32, + pub(super) y: u32, + pub(super) w: u32, + pub(super) h: u32, +} + +/// A rasterized glyph placed in the atlas. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(super) struct Glyph { + pub(super) uv: [f32; 2], + pub(super) uv_size: [f32; 2], + pub(super) xmin: i32, + pub(super) ymin: i32, + pub(super) width: u32, + pub(super) height: u32, + pub(super) advance: f32, +} + +/// One rasterized bitmap handed to the atlas. +pub(super) struct Raster<'a> { + pub(super) bitmap: &'a [u8], + pub(super) width: u32, + pub(super) height: u32, + pub(super) xmin: i32, + pub(super) ymin: i32, + pub(super) advance: f32, +} + +struct Entry { + ch: char, + size_bits: u32, + glyph: Glyph, +} + +/// Packed glyph coverage plus the cache that maps characters onto it. +pub(super) struct GlyphAtlas { + pixels: Vec, + entries: Vec, + cursor_x: u32, + cursor_y: u32, + shelf: u32, + dirty: Vec, +} + +impl GlyphAtlas { + /// An empty atlas with a small white block at the origin. + pub(super) fn new() -> Self { + let mut pixels = vec![0; (SIZE * SIZE) as usize]; + // A two by two white block at the origin; sampling its centre stays white + // even when filtering drifts by half a texel. + pixels[0..2].fill(255); + let second_row = SIZE as usize; + pixels[second_row..second_row + 2].fill(255); + Self { + pixels, + entries: Vec::new(), + cursor_x: 2 + PADDING, + cursor_y: 0, + shelf: 2, + dirty: vec![Region { + x: 0, + y: 0, + w: 2, + h: 2, + }], + } + } + + /// The raw coverage buffer, `SIZE * SIZE` bytes. + pub(super) fn pixels(&self) -> &[u8] { + &self.pixels + } + + /// The number of cached glyphs. + #[allow(dead_code, reason = "read by the overlay atlas test")] + pub(super) fn len(&self) -> usize { + self.entries.len() + } + + /// A region that still has to be uploaded to the GPU. + pub(super) fn take_dirty(&mut self) -> Vec { + std::mem::take(&mut self.dirty) + } + + /// The cached glyph for `ch` at a pixel size, if any. + pub(super) fn get(&self, ch: char, size_bits: u32) -> Option<&Glyph> { + self.entries + .iter() + .find(|entry| entry.ch == ch && entry.size_bits == size_bits) + .map(|entry| &entry.glyph) + } + + /// Packs a rasterized glyph and returns its placement. + /// + /// Returns `None` when the glyph is already cached or the atlas has no room + /// left for it. + pub(super) fn insert( + &mut self, + ch: char, + size_bits: u32, + raster: &Raster<'_>, + ) -> Option { + if self.get(ch, size_bits).is_some() { + return None; + } + let (x, y) = self.reserve(raster.width, raster.height)?; + let glyph = Glyph { + uv: [x as f32 / SIZE as f32, y as f32 / SIZE as f32], + uv_size: [ + raster.width as f32 / SIZE as f32, + raster.height as f32 / SIZE as f32, + ], + xmin: raster.xmin, + ymin: raster.ymin, + width: raster.width, + height: raster.height, + advance: raster.advance, + }; + self.write(x, y, raster); + self.entries.push(Entry { + ch, + size_bits, + glyph, + }); + Some(glyph) + } + + /// Finds a free shelf slot for a `width` by `height` bitmap. + fn reserve(&mut self, width: u32, height: u32) -> Option<(u32, u32)> { + if width == 0 || height == 0 { + // Invisible glyphs (spaces) still need a cache entry, not texels. + return Some((0, 0)); + } + if width + 2 * PADDING > SIZE || height + PADDING > SIZE { + return None; + } + if self.cursor_x + width + PADDING > SIZE { + self.cursor_y += self.shelf + PADDING; + self.cursor_x = 0; + self.shelf = 0; + } + if self.cursor_y + height + PADDING > SIZE { + return None; + } + let spot = (self.cursor_x, self.cursor_y); + self.cursor_x += width + PADDING; + self.shelf = self.shelf.max(height); + Some(spot) + } + + /// Copies a bitmap into the coverage buffer and marks the region dirty. + fn write(&mut self, x: u32, y: u32, raster: &Raster<'_>) { + if raster.width == 0 || raster.height == 0 { + return; + } + for row in 0..raster.height { + let source = (row * raster.width) as usize; + let target = ((y + row) * SIZE + x) as usize; + let length = raster.width as usize; + if let (Some(from), Some(to)) = ( + raster.bitmap.get(source..source + length), + self.pixels.get_mut(target..target + length), + ) { + to.copy_from_slice(from); + } + } + self.dirty.push(Region { + x, + y, + w: raster.width, + h: raster.height, + }); + } +} diff --git a/crates/render/src/overlay/mod.rs b/crates/render/src/overlay/mod.rs new file mode 100644 index 0000000..9ae6b2d --- /dev/null +++ b/crates/render/src/overlay/mod.rs @@ -0,0 +1,123 @@ +//! Screen-space 2D overlay drawn after the 3D scene. +//! +//! The overlay is a list of rectangles, lines and text in target pixels with the +//! origin at the top-left. One triangle batch draws all of it with depth testing +//! disabled and alpha blending: solid shapes sample a white texel of the glyph +//! atlas, text samples glyph coverage. + +mod atlas; +mod pass; +mod text; + +#[cfg(test)] +mod tests; + +pub(crate) use pass::{OverlayRenderer, Target}; + +/// A filled rectangle in target pixels. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct OverlayRect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, + pub color: [f32; 4], +} + +impl OverlayRect { + /// A rectangle at `(x, y)` with a size and a linear RGBA colour. + #[must_use] + pub fn new(x: f32, y: f32, w: f32, h: f32, color: [f32; 4]) -> Self { + Self { x, y, w, h, color } + } +} + +/// A straight line of a given width in target pixels. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct OverlayLine { + pub from: [f32; 2], + pub to: [f32; 2], + pub width: f32, + pub color: [f32; 4], +} + +impl OverlayLine { + /// A line from `from` to `to` with a width and a linear RGBA colour. + #[must_use] + pub fn new(from: [f32; 2], to: [f32; 2], width: f32, color: [f32; 4]) -> Self { + Self { + from, + to, + width, + color, + } + } +} + +/// One line of ASCII text, anchored at its top-left corner. +#[derive(Debug, Clone, PartialEq)] +pub struct OverlayText { + pub x: f32, + pub y: f32, + pub size: f32, + pub color: [f32; 4], + pub text: String, +} + +impl OverlayText { + /// Text at `(x, y)` in pixels with a font size and a linear RGBA colour. + #[must_use] + pub fn new(x: f32, y: f32, size: f32, color: [f32; 4], text: impl Into) -> Self { + Self { + x, + y, + size, + color, + text: text.into(), + } + } +} + +/// Everything the overlay pass draws in one frame. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Overlay { + pub rects: Vec, + pub lines: Vec, + pub texts: Vec, +} + +impl Overlay { + /// An empty overlay. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Drops all shapes but keeps the allocated buffers. + pub fn clear(&mut self) { + self.rects.clear(); + self.lines.clear(); + self.texts.clear(); + } + + /// Whether the overlay would draw nothing. + #[must_use] + pub fn is_empty(&self) -> bool { + self.rects.is_empty() && self.lines.is_empty() && self.texts.is_empty() + } + + /// Queues a filled rectangle. + pub fn push_rect(&mut self, rect: OverlayRect) { + self.rects.push(rect); + } + + /// Queues a line. + pub fn push_line(&mut self, line: OverlayLine) { + self.lines.push(line); + } + + /// Queues a text line. + pub fn push_text(&mut self, text: OverlayText) { + self.texts.push(text); + } +} diff --git a/crates/render/src/overlay/pass/geometry.rs b/crates/render/src/overlay/pass/geometry.rs new file mode 100644 index 0000000..16be5b6 --- /dev/null +++ b/crates/render/src/overlay/pass/geometry.rs @@ -0,0 +1,106 @@ +//! Vertex layout and quad assembly for the overlay batch. + +use bytemuck::{Pod, Zeroable}; + +use super::super::OverlayLine; +use super::super::atlas::WHITE_UV; + +/// A single overlay vertex: clip-space position, atlas UV and colour. +#[repr(C)] +#[derive(Debug, Clone, Copy, Pod, Zeroable)] +pub(super) struct Vertex { + pub(super) position: [f32; 2], + pub(super) uv: [f32; 2], + pub(super) color: [f32; 4], +} + +pub(super) const ATTRIBUTES: [wgpu::VertexAttribute; 3] = [ + wgpu::VertexAttribute { + format: wgpu::VertexFormat::Float32x2, + offset: 0, + shader_location: 0, + }, + wgpu::VertexAttribute { + format: wgpu::VertexFormat::Float32x2, + offset: 8, + shader_location: 1, + }, + wgpu::VertexAttribute { + format: wgpu::VertexFormat::Float32x4, + offset: 16, + shader_location: 2, + }, +]; + +/// UV rectangle of the always-white atlas texel. +pub(super) fn solid_uv() -> [f32; 4] { + [WHITE_UV[0], WHITE_UV[1], WHITE_UV[0], WHITE_UV[1]] +} + +/// Pixels to normalized device coordinates; the overlay's y axis points down. +fn ndc(x: f32, y: f32, size: (u32, u32)) -> [f32; 2] { + let width = size.0.max(1) as f32; + let height = size.1.max(1) as f32; + [x / width * 2.0 - 1.0, 1.0 - y / height * 2.0] +} + +/// Appends an axis-aligned quad as two triangles. +pub(super) fn push_quad( + vertices: &mut Vec, + size: (u32, u32), + rect: [f32; 4], + uv: [f32; 4], + color: [f32; 4], +) { + let [x, y, w, h] = rect; + if w <= 0.0 || h <= 0.0 { + return; + } + let top_left = ndc(x, y, size); + let bottom_right = ndc(x + w, y + h, size); + let corners = [ + ([top_left[0], top_left[1]], [uv[0], uv[1]]), + ([bottom_right[0], top_left[1]], [uv[2], uv[1]]), + ([bottom_right[0], bottom_right[1]], [uv[2], uv[3]]), + ([top_left[0], bottom_right[1]], [uv[0], uv[3]]), + ]; + push_corners(vertices, corners, color); +} + +/// Appends a line as a quad expanded along its normal. +pub(super) fn push_segment(vertices: &mut Vec, size: (u32, u32), line: &OverlayLine) { + let [x0, y0] = line.from; + let [x1, y1] = line.to; + let dx = x1 - x0; + let dy = y1 - y0; + let length = (dx * dx + dy * dy).sqrt(); + if length <= f32::EPSILON || line.width <= 0.0 { + return; + } + let half = line.width * 0.5; + let nx = -dy / length * half; + let ny = dx / length * half; + let uv = WHITE_UV; + let corners = [ + (ndc(x0 + nx, y0 + ny, size), uv), + (ndc(x1 + nx, y1 + ny, size), uv), + (ndc(x1 - nx, y1 - ny, size), uv), + (ndc(x0 - nx, y0 - ny, size), uv), + ]; + push_corners(vertices, corners, line.color); +} + +/// Appends two triangles for four pixel-space corners. +fn push_corners(vertices: &mut Vec, corners: [([f32; 2], [f32; 2]); 4], color: [f32; 4]) { + const INDICES: [usize; 6] = [0, 1, 2, 0, 2, 3]; + for index in INDICES { + let Some((position, uv)) = corners.get(index) else { + continue; + }; + vertices.push(Vertex { + position: *position, + uv: *uv, + color, + }); + } +} diff --git a/crates/render/src/overlay/pass/mod.rs b/crates/render/src/overlay/pass/mod.rs new file mode 100644 index 0000000..4eccb22 --- /dev/null +++ b/crates/render/src/overlay/pass/mod.rs @@ -0,0 +1,327 @@ +//! The overlay render pass: one triangle batch with alpha blending, no depth. + +mod geometry; + +use std::sync::Mutex; + +use wgpu::util::DeviceExt; + +use self::geometry::{ATTRIBUTES, Vertex, push_quad, push_segment, solid_uv}; +use super::Overlay; +use super::atlas::{GlyphAtlas, Region, SIZE}; +use super::text::TextRasterizer; + +/// GPU state of the overlay pass. +/// +/// The glyph atlas grows while drawing, so it sits behind a mutex: that keeps +/// [`crate::Renderer::draw_overlay`] callable through a shared reference. +pub(crate) struct OverlayRenderer { + state: Mutex, +} + +struct State { + pipeline: wgpu::RenderPipeline, + bind_group: wgpu::BindGroup, + texture: wgpu::Texture, + rasterizer: TextRasterizer, +} + +/// The colour view and pixel size the overlay draws into. +#[derive(Clone, Copy)] +pub(crate) struct Target<'a> { + pub(crate) view: &'a wgpu::TextureView, + pub(crate) size: (u32, u32), +} + +/// A recorded vertex batch: pipeline, atlas binding and geometry. +struct Batch<'a> { + pipeline: &'a wgpu::RenderPipeline, + bind_group: &'a wgpu::BindGroup, + vertices: &'a [Vertex], +} + +impl OverlayRenderer { + /// Creates the atlas texture, sampler, bind group and pipeline. + pub(crate) fn new( + device: &wgpu::Device, + queue: &wgpu::Queue, + format: wgpu::TextureFormat, + ) -> Self { + let texture = create_atlas_texture(device); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("fabrilis atlas sampler"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + address_mode_w: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let layout = create_layout(device); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("fabrilis atlas"), + layout: &layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }); + let pipeline = create_pipeline(device, format, &layout); + let mut rasterizer = TextRasterizer::new(); + upload_atlas(queue, &texture, &mut rasterizer); + Self { + state: Mutex::new(State { + pipeline, + bind_group, + texture, + rasterizer, + }), + } + } + + /// Draws the overlay over whatever is already in the target. + pub(crate) fn draw( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + target: Target<'_>, + overlay: &Overlay, + ) { + if target.size.0 == 0 || target.size.1 == 0 || overlay.is_empty() { + return; + } + let Ok(mut guard) = self.state.lock() else { + return; + }; + let State { + pipeline, + bind_group, + texture, + rasterizer, + } = &mut *guard; + let mut vertices = Vec::with_capacity( + overlay.rects.len() * 6 + overlay.lines.len() * 6 + overlay.texts.len() * 24, + ); + for rect in &overlay.rects { + push_quad( + &mut vertices, + target.size, + [rect.x, rect.y, rect.w, rect.h], + solid_uv(), + rect.color, + ); + } + for line in &overlay.lines { + push_segment(&mut vertices, target.size, line); + } + for item in &overlay.texts { + for quad in rasterizer.layout(item) { + push_quad(&mut vertices, target.size, quad.rect, quad.uv, item.color); + } + } + // Layout may have rasterized new glyphs, so upload after it. + upload_atlas(queue, texture, rasterizer); + submit( + device, + queue, + target, + Batch { + pipeline, + bind_group, + vertices: &vertices, + }, + ); + } +} + +/// Uploads the vertex batch and records the overlay pass. +fn submit(device: &wgpu::Device, queue: &wgpu::Queue, target: Target<'_>, batch: Batch<'_>) { + let vertices = batch.vertices; + if vertices.is_empty() { + return; + } + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("fabrilis overlay vertices"), + contents: bytemuck::cast_slice(vertices), + usage: wgpu::BufferUsages::VERTEX, + }); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("fabrilis overlay frame"), + }); + { + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: target.view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("fabrilis overlay pass"), + color_attachments: &attachments, + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(batch.pipeline); + pass.set_bind_group(0, batch.bind_group, &[]); + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..vertices.len() as u32, 0..1); + } + queue.submit([encoder.finish()]); +} + +fn create_atlas_texture(device: &wgpu::Device) -> wgpu::Texture { + device.create_texture(&wgpu::TextureDescriptor { + label: Some("fabrilis glyph atlas"), + size: wgpu::Extent3d { + width: SIZE, + height: SIZE, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }) +} + +fn create_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("fabrilis overlay layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }) +} + +fn create_pipeline( + device: &wgpu::Device, + format: wgpu::TextureFormat, + layout: &wgpu::BindGroupLayout, +) -> wgpu::RenderPipeline { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("fabrilis overlay shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("overlay.wgsl"))), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("fabrilis overlay pipeline layout"), + bind_group_layouts: &[Some(layout)], + immediate_size: 0, + }); + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("fabrilis overlay pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + buffers: &[Some(wgpu::VertexBufferLayout { + array_stride: 32, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &ATTRIBUTES, + })], + }, + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + cull_mode: None, + ..Default::default() + }, + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState::ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) +} + +/// Uploads every atlas region written since the previous frame. +fn upload_atlas(queue: &wgpu::Queue, texture: &wgpu::Texture, rasterizer: &mut TextRasterizer) { + let regions = rasterizer.take_dirty(); + if regions.is_empty() { + return; + } + let atlas = rasterizer.atlas(); + for region in regions { + let (data, row) = padded_region(atlas, region); + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: 0, + origin: wgpu::Origin3d { + x: region.x, + y: region.y, + z: 0, + }, + aspect: wgpu::TextureAspect::All, + }, + &data, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(row), + rows_per_image: Some(region.h), + }, + wgpu::Extent3d { + width: region.w, + height: region.h, + depth_or_array_layers: 1, + }, + ); + } +} + +/// Copies one atlas region into a row-padded staging buffer. +fn padded_region(atlas: &GlyphAtlas, region: Region) -> (Vec, u32) { + let row = + region.w.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let mut data = vec![0; (row * region.h) as usize]; + let pixels = atlas.pixels(); + let length = region.w as usize; + for line in 0..region.h { + let source = ((region.y + line) * SIZE + region.x) as usize; + let target = (line * row) as usize; + if let (Some(from), Some(to)) = ( + pixels.get(source..source + length), + data.get_mut(target..target + length), + ) { + to.copy_from_slice(from); + } + } + (data, row) +} diff --git a/crates/render/src/overlay/pass/overlay.wgsl b/crates/render/src/overlay/pass/overlay.wgsl new file mode 100644 index 0000000..240aced --- /dev/null +++ b/crates/render/src/overlay/pass/overlay.wgsl @@ -0,0 +1,29 @@ +struct VertexInput { + @location(0) position: vec2, + @location(1) uv: vec2, + @location(2) color: vec4, +}; + +struct VertexOutput { + @builtin(position) clip_position: vec4, + @location(0) uv: vec2, + @location(1) color: vec4, +}; + +@vertex +fn vs_main(input: VertexInput) -> VertexOutput { + var output: VertexOutput; + output.clip_position = vec4(input.position, 0.0, 1.0); + output.uv = input.uv; + output.color = input.color; + return output; +} + +@group(0) @binding(0) var atlas: texture_2d; +@group(0) @binding(1) var atlas_sampler: sampler; + +@fragment +fn fs_main(input: VertexOutput) -> @location(0) vec4 { + let coverage = textureSample(atlas, atlas_sampler, input.uv).r; + return vec4(input.color.rgb, input.color.a * coverage); +} diff --git a/crates/render/src/overlay/tests.rs b/crates/render/src/overlay/tests.rs new file mode 100644 index 0000000..0d15e2e --- /dev/null +++ b/crates/render/src/overlay/tests.rs @@ -0,0 +1,156 @@ +//! Headless tests for the screen-space overlay. + +use super::atlas::{GlyphAtlas, Raster}; +use super::text::font_path; +use super::{Overlay, OverlayLine, OverlayRect, OverlayText}; +use crate::{Camera, Gpu, MeshData, Renderer, Scene}; +use wgpu::TextureFormat; + +const SIZE: u32 = 64; +const FORMAT: TextureFormat = TextureFormat::Rgba8UnormSrgb; + +fn setup() -> (Gpu, Renderer) { + let gpu = Gpu::headless().expect("headless adapter"); + let renderer = + Renderer::new(gpu.device(), gpu.queue(), FORMAT, (SIZE, SIZE)).expect("renderer"); + (gpu, renderer) +} + +fn empty_scene() -> Scene { + Scene::new(MeshData::default()) +} + +fn camera() -> Camera { + Camera::look_at([0.0, 0.0, 5.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]) +} + +fn pixel_at(pixels: &[u8], x: u32, y: u32) -> [u8; 4] { + let index = ((y * SIZE + x) * 4) as usize; + [ + pixels[index], + pixels[index + 1], + pixels[index + 2], + pixels[index + 3], + ] +} + +#[test] +fn red_rect_changes_pixels() { + let (_gpu, mut renderer) = setup(); + let mut overlay = Overlay::new(); + overlay.push_rect(OverlayRect::new( + 16.0, + 16.0, + 32.0, + 32.0, + [1.0, 0.0, 0.0, 1.0], + )); + renderer + .draw_with_overlay(&empty_scene(), &camera(), &overlay) + .expect("draw"); + let pixels = renderer.pixels().expect("pixels"); + assert_eq!(pixels.len(), (SIZE * SIZE * 4) as usize); + + let inside = pixel_at(&pixels, 32, 32); + assert!( + inside[0] > 200 && inside[1] < 40 && inside[2] < 40, + "the rect must be red: {inside:?}" + ); + let outside = pixel_at(&pixels, 2, 2); + assert!( + outside[0] < 120, + "the corner must keep the clear colour: {outside:?}" + ); +} + +#[test] +fn white_line_changes_pixels() { + let (_gpu, mut renderer) = setup(); + let mut overlay = Overlay::new(); + overlay.push_line(OverlayLine::new( + [4.0, 32.0], + [60.0, 32.0], + 3.0, + [1.0, 1.0, 1.0, 1.0], + )); + renderer + .draw_with_overlay(&empty_scene(), &camera(), &overlay) + .expect("draw"); + let pixels = renderer.pixels().expect("pixels"); + let on_line = pixel_at(&pixels, 32, 32); + assert!( + on_line.iter().take(3).all(|channel| *channel > 200), + "the line must be white: {on_line:?}" + ); + let off_line = pixel_at(&pixels, 32, 4); + assert!( + off_line[0] < 120, + "away from the line the background stays: {off_line:?}" + ); +} + +#[test] +fn text_draws_pixels_when_a_font_exists() { + if font_path().is_none() { + return; + } + let (_gpu, mut renderer) = setup(); + let mut overlay = Overlay::new(); + overlay.push_text(OverlayText::new( + 4.0, + 4.0, + 20.0, + [1.0, 1.0, 1.0, 1.0], + "FPS 60", + )); + renderer + .draw_with_overlay(&empty_scene(), &camera(), &overlay) + .expect("draw"); + let pixels = renderer.pixels().expect("pixels"); + let covered = (4..60) + .flat_map(|x| (4..28).map(move |y| (x, y))) + .filter(|(x, y)| pixel_at(&pixels, *x, *y)[0] > 150) + .count(); + assert!(covered > 0, "the text must cover at least one pixel"); +} + +#[test] +fn atlas_does_not_duplicate_glyphs() { + let mut atlas = GlyphAtlas::new(); + let _ = atlas.take_dirty(); + let bitmap = [255u8; 16]; + let raster = Raster { + bitmap: &bitmap, + width: 4, + height: 4, + xmin: 0, + ymin: 0, + advance: 5.0, + }; + let size = 14.0f32.to_bits(); + let first = atlas.insert('A', size, &raster).expect("first insert"); + assert_eq!(atlas.take_dirty().len(), 1, "one upload per new glyph"); + assert!( + atlas.insert('A', size, &raster).is_none(), + "the same glyph is not packed twice" + ); + assert!( + atlas.take_dirty().is_empty(), + "no upload for a cached glyph" + ); + assert_eq!(atlas.len(), 1); + let cached = atlas.get('A', size).expect("cached glyph"); + assert_eq!(cached.uv, first.uv); +} + +#[test] +fn zero_size_target_is_skipped() { + let (_gpu, mut renderer) = setup(); + renderer.resize((0, 0)).expect("resize to zero"); + let mut overlay = Overlay::new(); + overlay.push_rect(OverlayRect::new(0.0, 0.0, 8.0, 8.0, [1.0; 4])); + renderer + .draw_with_overlay(&empty_scene(), &camera(), &overlay) + .expect("skipped draw"); + assert!(renderer.pixels().expect("pixels").is_empty()); +} diff --git a/crates/render/src/overlay/text.rs b/crates/render/src/overlay/text.rs new file mode 100644 index 0000000..c85f064 --- /dev/null +++ b/crates/render/src/overlay/text.rs @@ -0,0 +1,136 @@ +//! Font loading and glyph layout for the overlay text. + +use std::path::Path; + +use fontdue::{Font, FontSettings}; + +use super::OverlayText; +use super::atlas::{Glyph, GlyphAtlas, Raster, Region}; + +/// Font files tried in order; the first one that exists is loaded. +const FONT_PATHS: [&str; 5] = [ + "/usr/share/fonts/noto/NotoSans-Regular.ttf", + "/usr/share/fonts/TTF/DejaVuSans.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/System/Library/Fonts/Helvetica.ttc", + "C:\\Windows\\Fonts\\segoeui.ttf", +]; + +/// One textured glyph quad in overlay pixels, origin top-left. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(super) struct GlyphQuad { + pub(super) rect: [f32; 4], + pub(super) uv: [f32; 4], +} + +/// The first font file that exists on this machine, if any. +pub(super) fn font_path() -> Option<&'static str> { + FONT_PATHS + .iter() + .copied() + .find(|path| Path::new(path).is_file()) +} + +/// Rasterizes text and caches glyph coverage in the atlas. +pub(super) struct TextRasterizer { + font: Option, + atlas: GlyphAtlas, +} + +impl TextRasterizer { + /// Loads the first available font; without one, text is skipped. + pub(super) fn new() -> Self { + Self { + font: load_font(), + atlas: GlyphAtlas::new(), + } + } + + /// Regions of the atlas that were written since the last call. + pub(super) fn take_dirty(&mut self) -> Vec { + self.atlas.take_dirty() + } + + /// The packed coverage that backs the glyph quads. + pub(super) fn atlas(&self) -> &GlyphAtlas { + &self.atlas + } + + /// Lays one line of ASCII text out into covered quads. + pub(super) fn layout(&mut self, text: &OverlayText) -> Vec { + let mut quads = Vec::new(); + if self.font.is_none() { + return quads; + } + let size = text.size.max(1.0); + let bits = size.to_bits(); + let baseline = text.y + self.ascent(size); + let mut pen = text.x; + for ch in text.text.chars() { + if !ch.is_ascii() { + continue; + } + let Some(glyph) = self.glyph(ch, size, bits) else { + continue; + }; + if glyph.width > 0 && glyph.height > 0 { + let x = pen + glyph.xmin as f32; + let y = baseline - glyph.ymin as f32 - glyph.height as f32; + quads.push(GlyphQuad { + rect: [x, y, glyph.width as f32, glyph.height as f32], + uv: [ + glyph.uv[0], + glyph.uv[1], + glyph.uv[0] + glyph.uv_size[0], + glyph.uv[1] + glyph.uv_size[1], + ], + }); + } + pen += glyph.advance; + } + quads + } + + /// Distance from the top of the text box down to the baseline. + fn ascent(&self, size: f32) -> f32 { + self.font + .as_ref() + .and_then(|font| font.horizontal_line_metrics(size)) + .map_or(size * 0.8, |line| line.ascent) + } + + /// The cached glyph for `ch`, rasterizing and packing it on first use. + fn glyph(&mut self, ch: char, size: f32, bits: u32) -> Option { + if let Some(cached) = self.atlas.get(ch, bits) { + return Some(*cached); + } + let font = self.font.as_ref()?; + let (metrics, bitmap) = font.rasterize(ch, size); + let raster = Raster { + bitmap: &bitmap, + width: metrics.width as u32, + height: metrics.height as u32, + xmin: metrics.xmin, + ymin: metrics.ymin, + advance: metrics.advance_width, + }; + if let Some(packed) = self.atlas.insert(ch, bits, &raster) { + return Some(packed); + } + // The atlas is full: keep the pen moving but draw nothing. + Some(Glyph { + uv: [0.0, 0.0], + uv_size: [0.0, 0.0], + xmin: 0, + ymin: 0, + width: 0, + height: 0, + advance: metrics.advance_width, + }) + } +} + +fn load_font() -> Option { + let data = std::fs::read(font_path()?).ok()?; + Font::from_bytes(data, FontSettings::default()).ok() +} diff --git a/crates/render/src/renderer/mod.rs b/crates/render/src/renderer/mod.rs new file mode 100644 index 0000000..3ebcc44 --- /dev/null +++ b/crates/render/src/renderer/mod.rs @@ -0,0 +1,306 @@ +//! Depth-tested scene renderer with an optional offscreen colour target. + +mod pipeline; +mod target; + +#[cfg(test)] +mod tests; + +use pipeline::Pipelines; + +use crate::overlay::{Overlay, OverlayRenderer, Target}; +use crate::{Camera, RenderError, Scene}; + +/// A renderer that owns its pipelines, depth buffer and optional colour target. +pub struct Renderer { + device: wgpu::Device, + queue: wgpu::Queue, + format: wgpu::TextureFormat, + size: (u32, u32), + offscreen: bool, + pipelines: Pipelines, + overlay: OverlayRenderer, + depth: Option<(wgpu::Texture, wgpu::TextureView)>, + color: Option<(wgpu::Texture, wgpu::TextureView)>, +} + +impl Renderer { + /// Builds a renderer with an offscreen colour target for pixel readback. + pub fn new( + device: &wgpu::Device, + queue: &wgpu::Queue, + format: wgpu::TextureFormat, + size: (u32, u32), + ) -> Result { + Self::create(device, queue, format, size, true) + } + + /// Builds a renderer that draws directly into a caller-provided view. + pub fn for_surface( + device: &wgpu::Device, + queue: &wgpu::Queue, + format: wgpu::TextureFormat, + size: (u32, u32), + ) -> Result { + Self::create(device, queue, format, size, false) + } + + fn create( + device: &wgpu::Device, + queue: &wgpu::Queue, + format: wgpu::TextureFormat, + size: (u32, u32), + offscreen: bool, + ) -> Result { + let pipelines = pipeline::build(device, format); + let overlay = OverlayRenderer::new(device, queue, format); + let mut renderer = Self { + device: device.clone(), + queue: queue.clone(), + format, + size, + offscreen, + pipelines, + overlay, + depth: None, + color: None, + }; + renderer.allocate_targets()?; + Ok(renderer) + } + + /// Replaces the depth and colour targets after a resize. + pub fn resize(&mut self, size: (u32, u32)) -> Result<(), RenderError> { + if size == self.size { + return Ok(()); + } + self.size = size; + self.depth = None; + self.color = None; + self.allocate_targets() + } + + /// The current target size in pixels. + #[must_use] + pub fn size(&self) -> (u32, u32) { + self.size + } + + /// Draws the scene into the offscreen colour target. + pub fn draw(&mut self, scene: &Scene, camera: &Camera) -> Result<(), RenderError> { + if self.size.0 == 0 || self.size.1 == 0 { + return Ok(()); + } + let (_, view) = self.color.as_ref().ok_or_else(|| { + RenderError::Texture("renderer has no offscreen colour target".to_string()) + })?; + self.render(view, scene, camera); + Ok(()) + } + + /// Draws the scene into a surface texture view owned by the caller. + pub fn draw_to( + &self, + view: &wgpu::TextureView, + scene: &Scene, + camera: &Camera, + ) -> Result<(), RenderError> { + if self.size.0 == 0 || self.size.1 == 0 { + return Ok(()); + } + self.render(view, scene, camera); + Ok(()) + } + + /// Draws the 2D overlay into a target view, on top of what is already there. + pub fn draw_overlay( + &self, + view: &wgpu::TextureView, + overlay: &Overlay, + ) -> Result<(), RenderError> { + if self.size.0 == 0 || self.size.1 == 0 { + return Ok(()); + } + self.overlay.draw( + &self.device, + &self.queue, + Target { + view, + size: self.size, + }, + overlay, + ); + Ok(()) + } + + /// Draws the scene and then the overlay into the offscreen colour target. + pub fn draw_with_overlay( + &mut self, + scene: &Scene, + camera: &Camera, + overlay: &Overlay, + ) -> Result<(), RenderError> { + if self.size.0 == 0 || self.size.1 == 0 { + return Ok(()); + } + self.draw(scene, camera)?; + let (_, view) = self.color.as_ref().ok_or_else(|| { + RenderError::Texture("renderer has no offscreen colour target".to_string()) + })?; + self.draw_overlay(view, overlay) + } + + /// Reads the offscreen target back as tightly packed RGBA8 pixels. + pub fn pixels(&self) -> Result, RenderError> { + if self.size.0 == 0 || self.size.1 == 0 { + return Ok(Vec::new()); + } + let (texture, _) = self.color.as_ref().ok_or_else(|| { + RenderError::Texture("renderer has no offscreen colour target".to_string()) + })?; + self.read_texture(texture) + } + + fn render(&self, view: &wgpu::TextureView, scene: &Scene, camera: &Camera) { + let Some((_, depth)) = &self.depth else { + return; + }; + self.write_globals(camera); + let geometry = self.prepare_geometry(scene); + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("fabrilis frame"), + }); + { + let attachments = [Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(pipeline::CLEAR_COLOR), + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("fabrilis scene pass"), + color_attachments: &attachments, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.pipelines.pipeline); + pass.set_bind_group(0, &self.pipelines.bind_group, &[]); + geometry.draw_mesh(&mut pass, &self.pipelines); + geometry.draw_boxes(&mut pass, &self.pipelines); + } + self.queue.submit([encoder.finish()]); + } + + fn write_globals(&self, camera: &Camera) { + let globals = pipeline::Globals::new(camera.view_projection(), camera.eye()); + self.queue + .write_buffer(&self.pipelines.globals, 0, bytemuck::bytes_of(&globals)); + } + + fn prepare_geometry(&self, scene: &Scene) -> Geometry { + let terrain = pipeline::RawInstance { + model: crate::Instance::IDENTITY, + color: scene.mesh_color, + }; + self.queue.write_buffer( + &self.pipelines.terrain_instance, + 0, + bytemuck::bytes_of(&terrain), + ); + Geometry { + mesh_vertices: upload_vertices(&self.device, scene), + mesh_indices: upload_indices(&self.device, scene), + mesh_index_count: scene.mesh.indices.len() as u32, + boxes: upload_instances(&self.device, scene), + instance_count: scene.instances.len() as u32, + } + } +} + +struct Geometry { + mesh_vertices: Option, + mesh_indices: Option, + mesh_index_count: u32, + boxes: Option, + instance_count: u32, +} + +impl Geometry { + fn draw_mesh(&self, pass: &mut wgpu::RenderPass<'_>, pipelines: &Pipelines) { + let (Some(vertices), Some(indices)) = (&self.mesh_vertices, &self.mesh_indices) else { + return; + }; + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.set_vertex_buffer(1, pipelines.terrain_instance.slice(..)); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..self.mesh_index_count, 0, 0..1); + } + + fn draw_boxes(&self, pass: &mut wgpu::RenderPass<'_>, pipelines: &Pipelines) { + let Some(instances) = &self.boxes else { + return; + }; + pass.set_vertex_buffer(0, pipelines.cube_vertices.slice(..)); + pass.set_vertex_buffer(1, instances.slice(..)); + pass.set_index_buffer(pipelines.cube_indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..pipelines.cube_index_count, 0, 0..self.instance_count); + } +} + +fn upload_vertices(device: &wgpu::Device, scene: &Scene) -> Option { + if scene.mesh.vertices.is_empty() { + return None; + } + Some(pipeline::upload( + device, + "fabrilis mesh vertices", + bytemuck::cast_slice(&scene.mesh.vertices), + wgpu::BufferUsages::VERTEX, + )) +} + +fn upload_indices(device: &wgpu::Device, scene: &Scene) -> Option { + if scene.mesh.indices.is_empty() { + return None; + } + Some(pipeline::upload( + device, + "fabrilis mesh indices", + bytemuck::cast_slice(&scene.mesh.indices), + wgpu::BufferUsages::INDEX, + )) +} + +fn upload_instances(device: &wgpu::Device, scene: &Scene) -> Option { + if scene.instances.is_empty() { + return None; + } + let instances: Vec = scene + .instances + .iter() + .map(|instance| pipeline::RawInstance { + model: instance.model, + color: instance.color, + }) + .collect(); + Some(pipeline::upload( + device, + "fabrilis box instances", + bytemuck::cast_slice(&instances), + wgpu::BufferUsages::VERTEX, + )) +} diff --git a/crates/render/src/renderer/pipeline.rs b/crates/render/src/renderer/pipeline.rs new file mode 100644 index 0000000..f95878e --- /dev/null +++ b/crates/render/src/renderer/pipeline.rs @@ -0,0 +1,274 @@ +//! Pipeline, bind group, uniform block and static geometry shared by all frames. + +use bytemuck::{Pod, Zeroable}; +use wgpu::util::DeviceExt; + +/// Depth format used by the depth buffer. +pub(crate) const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float; + +/// Background colour cleared before every pass. +pub(crate) const CLEAR_COLOR: wgpu::Color = wgpu::Color { + r: 0.05, + g: 0.06, + b: 0.08, + a: 1.0, +}; + +/// Per-frame uniform block; must match `Globals` in the WGSL shader. +#[repr(C)] +#[derive(Debug, Clone, Copy, Pod, Zeroable)] +pub(crate) struct Globals { + pub view_proj: [[f32; 4]; 4], + pub light_dir: [f32; 4], + pub camera_pos: [f32; 4], +} + +impl Globals { + pub(crate) fn new(view_proj: [[f32; 4]; 4], camera_pos: [f32; 3]) -> Self { + Self { + view_proj, + light_dir: [0.35, -0.55, 0.75, 0.0], + camera_pos: [camera_pos[0], camera_pos[1], camera_pos[2], 1.0], + } + } +} + +/// One GPU instance: a column-major model matrix and a colour. +#[repr(C)] +#[derive(Debug, Clone, Copy, Pod, Zeroable)] +pub(crate) struct RawInstance { + pub model: [[f32; 4]; 4], + pub color: [f32; 4], +} + +const MESH_ATTRIBUTES: [wgpu::VertexAttribute; 1] = [wgpu::VertexAttribute { + format: wgpu::VertexFormat::Float32x3, + offset: 0, + shader_location: 0, +}]; + +const INSTANCE_ATTRIBUTES: [wgpu::VertexAttribute; 5] = [ + wgpu::VertexAttribute { + format: wgpu::VertexFormat::Float32x4, + offset: 0, + shader_location: 1, + }, + wgpu::VertexAttribute { + format: wgpu::VertexFormat::Float32x4, + offset: 16, + shader_location: 2, + }, + wgpu::VertexAttribute { + format: wgpu::VertexFormat::Float32x4, + offset: 32, + shader_location: 3, + }, + wgpu::VertexAttribute { + format: wgpu::VertexFormat::Float32x4, + offset: 48, + shader_location: 4, + }, + wgpu::VertexAttribute { + format: wgpu::VertexFormat::Float32x4, + offset: 64, + shader_location: 5, + }, +]; + +/// Resource set built once per surface format. +pub(crate) struct Pipelines { + pub pipeline: wgpu::RenderPipeline, + pub bind_group: wgpu::BindGroup, + pub globals: wgpu::Buffer, + pub cube_vertices: wgpu::Buffer, + pub cube_indices: wgpu::Buffer, + pub cube_index_count: u32, + pub terrain_instance: wgpu::Buffer, +} + +/// Builds the render pipeline, uniform binding and the unit-cube geometry. +pub(crate) fn build(device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipelines { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("fabrilis mesh shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("shader.wgsl"))), + }); + let layout = create_bind_group_layout(device); + let (globals, bind_group) = create_globals(device, &layout); + let pipeline = create_pipeline(device, format, &shader, &layout); + let (cube_vertices, cube_indices, cube_index_count) = cube_geometry(device); + let terrain_instance = upload( + device, + "fabrilis terrain instance", + bytemuck::bytes_of(&identity_instance()), + wgpu::BufferUsages::VERTEX, + ); + Pipelines { + pipeline, + bind_group, + globals, + cube_vertices, + cube_indices, + cube_index_count, + terrain_instance, + } +} + +/// Uploads data into a fresh buffer with `usage | COPY_DST`. +pub(crate) fn upload( + device: &wgpu::Device, + label: &str, + data: &[u8], + usage: wgpu::BufferUsages, +) -> wgpu::Buffer { + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some(label), + contents: data, + usage: usage | wgpu::BufferUsages::COPY_DST, + }) +} + +fn identity_instance() -> RawInstance { + RawInstance { + model: [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + color: [1.0; 4], + } +} + +const CUBE_FACES: [([f32; 3], [f32; 3], [f32; 3]); 6] = [ + ([-0.5, -0.5, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), + ([-0.5, -0.5, -0.5], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]), + ([0.5, -0.5, -0.5], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]), + ([-0.5, -0.5, -0.5], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]), + ([-0.5, 0.5, -0.5], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]), + ([-0.5, -0.5, -0.5], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]), +]; + +fn cube_geometry(device: &wgpu::Device) -> (wgpu::Buffer, wgpu::Buffer, u32) { + let mut vertices = Vec::with_capacity(24); + let mut indices = Vec::with_capacity(36); + for (origin, axis_u, axis_v) in CUBE_FACES { + let base = vertices.len() as u32; + for (u, v) in [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] { + vertices.push([ + origin[0] + axis_u[0] * u + axis_v[0] * v, + origin[1] + axis_u[1] * u + axis_v[1] * v, + origin[2] + axis_u[2] * u + axis_v[2] * v, + ]); + } + indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); + } + let vertex_buffer = upload( + device, + "fabrilis cube vertices", + bytemuck::cast_slice(&vertices), + wgpu::BufferUsages::VERTEX, + ); + let index_buffer = upload( + device, + "fabrilis cube indices", + bytemuck::cast_slice(&indices), + wgpu::BufferUsages::INDEX, + ); + (vertex_buffer, index_buffer, indices.len() as u32) +} + +fn create_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("fabrilis globals layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }) +} + +fn create_globals( + device: &wgpu::Device, + layout: &wgpu::BindGroupLayout, +) -> (wgpu::Buffer, wgpu::BindGroup) { + let globals = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("fabrilis globals"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("fabrilis globals"), + layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: globals.as_entire_binding(), + }], + }); + (globals, bind_group) +} + +fn create_pipeline( + device: &wgpu::Device, + format: wgpu::TextureFormat, + shader: &wgpu::ShaderModule, + layout: &wgpu::BindGroupLayout, +) -> wgpu::RenderPipeline { + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("fabrilis pipeline layout"), + bind_group_layouts: &[Some(layout)], + immediate_size: 0, + }); + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("fabrilis scene pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: shader, + entry_point: Some("vs_main"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + buffers: &[ + Some(wgpu::VertexBufferLayout { + array_stride: 12, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &MESH_ATTRIBUTES, + }), + Some(wgpu::VertexBufferLayout { + array_stride: 80, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &INSTANCE_ATTRIBUTES, + }), + ], + }, + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: DEPTH_FORMAT, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::Less), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: shader, + entry_point: Some("fs_main"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState::REPLACE), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) +} diff --git a/crates/render/src/renderer/shader.wgsl b/crates/render/src/renderer/shader.wgsl new file mode 100644 index 0000000..3893003 --- /dev/null +++ b/crates/render/src/renderer/shader.wgsl @@ -0,0 +1,48 @@ +struct Globals { + view_proj: mat4x4, + light_dir: vec4, + camera_pos: vec4, +}; + +@group(0) @binding(0) var globals: Globals; + +struct VertexInput { + @location(0) position: vec3, + @location(1) model_0: vec4, + @location(2) model_1: vec4, + @location(3) model_2: vec4, + @location(4) model_3: vec4, + @location(5) color: vec4, +}; + +struct VertexOutput { + @builtin(position) clip_position: vec4, + @location(0) world_position: vec3, + @location(1) color: vec4, +}; + +@vertex +fn vs_main(input: VertexInput) -> VertexOutput { + let model = mat4x4( + input.model_0, + input.model_1, + input.model_2, + input.model_3, + ); + let world = model * vec4(input.position, 1.0); + var output: VertexOutput; + output.clip_position = globals.view_proj * world; + output.world_position = world.xyz; + output.color = input.color; + return output; +} + +@fragment +fn fs_main(input: VertexOutput) -> @location(0) vec4 { + // Flat face normal from screen-space derivatives; this keeps the mesh data + // to positions only, and two-sided shading tolerates either triangle winding. + let normal = normalize(cross(dpdx(input.world_position), dpdy(input.world_position))); + let light = normalize(globals.light_dir.xyz); + let diffuse = 0.25 + 0.75 * abs(dot(normal, light)); + return vec4(input.color.rgb * diffuse, input.color.a); +} diff --git a/crates/render/src/renderer/target.rs b/crates/render/src/renderer/target.rs new file mode 100644 index 0000000..cc1c1b4 --- /dev/null +++ b/crates/render/src/renderer/target.rs @@ -0,0 +1,149 @@ +//! Offscreen targets and pixel readback. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use super::Renderer; +use super::pipeline; +use crate::RenderError; + +impl Renderer { + pub(super) fn allocate_targets(&mut self) -> Result<(), RenderError> { + if self.size.0 == 0 || self.size.1 == 0 { + return Ok(()); + } + let depth = create_texture( + &self.device, + "fabrilis depth", + pipeline::DEPTH_FORMAT, + self.size, + wgpu::TextureUsages::RENDER_ATTACHMENT, + ); + self.depth = Some(depth); + if self.offscreen { + let color = create_texture( + &self.device, + "fabrilis colour", + self.format, + self.size, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + ); + self.color = Some(color); + } + Ok(()) + } + + pub(super) fn read_texture(&self, texture: &wgpu::Texture) -> Result, RenderError> { + let bgra = match self.format { + wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba8UnormSrgb => false, + wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb => true, + other => { + return Err(RenderError::UnsupportedFormat(format!("{other:?}"))); + } + }; + let (width, height) = self.size; + let row_bytes = width * 4; + let padded_row = row_bytes.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) + * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let output = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("fabrilis readback"), + size: u64::from(padded_row) * u64::from(height), + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("fabrilis readback"), + }); + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyBufferInfo { + buffer: &output, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_row), + rows_per_image: Some(height), + }, + }, + wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + ); + self.queue.submit([encoder.finish()]); + let mut pixels = map_and_copy(&self.device, &output, padded_row, row_bytes, height)?; + if bgra { + for pixel in pixels.as_chunks_mut::<4>().0 { + pixel.swap(0, 2); + } + } + Ok(pixels) + } +} + +fn create_texture( + device: &wgpu::Device, + label: &str, + format: wgpu::TextureFormat, + size: (u32, u32), + usage: wgpu::TextureUsages, +) -> (wgpu::Texture, wgpu::TextureView) { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { + width: size.0, + height: size.1, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + (texture, view) +} + +fn map_and_copy( + device: &wgpu::Device, + buffer: &wgpu::Buffer, + padded_row: u32, + row_bytes: u32, + height: u32, +) -> Result, RenderError> { + let failed = Arc::new(AtomicBool::new(false)); + let flag = Arc::clone(&failed); + buffer + .slice(..) + .map_async(wgpu::MapMode::Read, move |result| { + if result.is_err() { + flag.store(true, Ordering::SeqCst); + } + }); + device + .poll(wgpu::PollType::wait_indefinitely()) + .map_err(|error| RenderError::Buffer(error.to_string()))?; + if failed.load(Ordering::SeqCst) { + return Err(RenderError::Buffer("readback mapping failed".to_string())); + } + let view = buffer + .slice(..) + .get_mapped_range() + .map_err(|error| RenderError::Buffer(error.to_string()))?; + let mut pixels = Vec::with_capacity((row_bytes * height) as usize); + for row in view.chunks(padded_row as usize) { + pixels.extend(row.iter().take(row_bytes as usize).copied()); + } + drop(view); + buffer.unmap(); + Ok(pixels) +} diff --git a/crates/render/src/renderer/tests.rs b/crates/render/src/renderer/tests.rs new file mode 100644 index 0000000..4a425fe --- /dev/null +++ b/crates/render/src/renderer/tests.rs @@ -0,0 +1,135 @@ +//! Headless rendering tests. + +use super::*; +use crate::{Camera, Gpu, Instance, MeshData, Scene}; + +const SIZE: u32 = 256; +const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb; + +fn setup(size: (u32, u32)) -> (Gpu, Renderer) { + let gpu = Gpu::headless().expect("headless adapter"); + let renderer = Renderer::new(gpu.device(), gpu.queue(), FORMAT, size).expect("renderer"); + (gpu, renderer) +} + +fn sloped_terrain() -> Scene { + let mesh = MeshData { + vertices: vec![ + [-2.0, -2.0, -0.6], + [2.0, -2.0, 0.6], + [2.0, 2.0, 0.6], + [-2.0, 2.0, -0.6], + ], + indices: vec![0, 1, 2, 0, 2, 3], + }; + let mut scene = Scene::new(mesh); + scene.instances.push(Instance::box_at( + [0.0, 0.0, 1.2], + [1.0, 1.0, 1.0], + [0.9, 0.4, 0.2, 1.0], + )); + scene +} + +fn orbit_camera() -> Camera { + Camera::look_at([4.0, -6.0, 5.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]) + .with_projection(0.9, 1.0, 0.1, 100.0) +} + +fn pixel_at(pixels: &[u8], size: (u32, u32), x: u32, y: u32) -> [u8; 4] { + let index = (y * size.0 + x) as usize * 4; + [ + pixels[index], + pixels[index + 1], + pixels[index + 2], + pixels[index + 3], + ] +} + +#[test] +fn renders_terrain_and_box() { + let (_gpu, mut renderer) = setup((SIZE, SIZE)); + let scene = sloped_terrain(); + renderer.draw(&scene, &orbit_camera()).expect("draw"); + let pixels = renderer.pixels().expect("pixels"); + assert_eq!(pixels.len(), (SIZE * SIZE * 4) as usize); + + let corner = pixel_at(&pixels, (SIZE, SIZE), 2, 2); + let centre = pixel_at(&pixels, (SIZE, SIZE), SIZE / 2, SIZE / 2); + assert_ne!( + corner, centre, + "the scene must cover the centre of the frame" + ); + + let covered = pixels + .as_chunks::<4>() + .0 + .iter() + .filter(|pixel| { + pixel + .iter() + .zip(corner.iter()) + .any(|(channel, reference)| channel.abs_diff(*reference) > 8) + }) + .count(); + assert!( + covered > (SIZE * SIZE / 10) as usize, + "only {covered} pixels differ from the corner" + ); +} + +#[test] +fn resize_reallocates_the_pixel_buffer() { + let (_gpu, mut renderer) = setup((SIZE, SIZE)); + let scene = sloped_terrain(); + renderer.draw(&scene, &orbit_camera()).expect("first draw"); + renderer.resize((64, 96)).expect("resize"); + assert_eq!(renderer.size(), (64, 96)); + renderer.draw(&scene, &orbit_camera()).expect("second draw"); + let pixels = renderer.pixels().expect("pixels"); + assert_eq!(pixels.len(), (64 * 96 * 4) as usize); +} + +#[test] +fn zero_size_target_is_skipped() { + let (_gpu, mut renderer) = setup((SIZE, SIZE)); + let scene = sloped_terrain(); + renderer.resize((0, 0)).expect("resize to zero"); + renderer + .draw(&scene, &orbit_camera()) + .expect("skipped draw"); + assert!(renderer.pixels().expect("pixels").is_empty()); + renderer.resize((32, 32)).expect("resize back"); + renderer + .draw(&scene, &orbit_camera()) + .expect("draw after resize"); + assert_eq!( + renderer.pixels().expect("pixels").len(), + (32 * 32 * 4) as usize + ); +} + +#[test] +fn near_box_covers_far_box() { + let (_gpu, mut renderer) = setup((SIZE, SIZE)); + let mut scene = Scene::new(MeshData::default()); + scene.instances.push(Instance::box_at( + [0.0, 0.0, 0.0], + [2.0, 2.0, 2.0], + [1.0, 0.0, 0.0, 1.0], + )); + scene.instances.push(Instance::box_at( + [0.0, 4.0, 0.0], + [2.0, 2.0, 2.0], + [0.0, 0.0, 1.0, 1.0], + )); + let camera = Camera::look_at([0.0, -8.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]) + .with_projection(0.9, 1.0, 0.1, 100.0); + renderer.draw(&scene, &camera).expect("draw"); + let pixels = renderer.pixels().expect("pixels"); + let centre = pixel_at(&pixels, (SIZE, SIZE), SIZE / 2, SIZE / 2); + assert!( + centre[0] > centre[2], + "near red box should cover the far blue one: {centre:?}" + ); +} diff --git a/crates/render/src/scene.rs b/crates/render/src/scene.rs new file mode 100644 index 0000000..ef50aaa --- /dev/null +++ b/crates/render/src/scene.rs @@ -0,0 +1,80 @@ +//! Scene data handed to the renderer: one triangle mesh plus instanced boxes. + +type Mat4 = [[f32; 4]; 4]; + +/// A triangle mesh with positions in metres and `u32` triangle indices. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct MeshData { + /// Vertex positions in world space. + pub vertices: Vec<[f32; 3]>, + /// Triples of vertex indices. + pub indices: Vec, +} + +impl MeshData { + /// The number of complete triangles in the mesh. + #[must_use] + pub fn triangle_count(&self) -> usize { + self.indices.len() / 3 + } +} + +/// One drawable box: a model matrix and a flat colour. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Instance { + /// Column-major model matrix. + pub model: Mat4, + /// Linear RGBA colour. + pub color: [f32; 4], +} + +impl Instance { + /// The identity model matrix. + pub const IDENTITY: Mat4 = [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ]; + + /// Builds an instance from a model matrix and a colour. + #[must_use] + pub fn new(model: Mat4, color: [f32; 4]) -> Self { + Self { model, color } + } + + /// A box centred at `center` with the given size along each axis. + #[must_use] + pub fn box_at(center: [f32; 3], size: [f32; 3], color: [f32; 4]) -> Self { + let model = [ + [size[0], 0.0, 0.0, 0.0], + [0.0, size[1], 0.0, 0.0], + [0.0, 0.0, size[2], 0.0], + [center[0], center[1], center[2], 1.0], + ]; + Self::new(model, color) + } +} + +/// Everything the renderer draws in one frame. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Scene { + /// The terrain surface. + pub mesh: MeshData, + /// Colour multiplied into the terrain vertices. + pub mesh_color: [f32; 4], + /// Boxes drawn with instancing. + pub instances: Vec, +} + +impl Scene { + /// A scene with one terrain mesh and the default terrain colour. + #[must_use] + pub fn new(mesh: MeshData) -> Self { + Self { + mesh, + mesh_color: [0.34, 0.46, 0.29, 1.0], + instances: Vec::new(), + } + } +} diff --git a/crates/render/src/terrain/mod.rs b/crates/render/src/terrain/mod.rs deleted file mode 100644 index 625ba52..0000000 --- a/crates/render/src/terrain/mod.rs +++ /dev/null @@ -1 +0,0 @@ -//! fabrilis-render :: terrain - stub (see docs/ARCHITECTURE.md) diff --git a/crates/render/src/views/mod.rs b/crates/render/src/views/mod.rs deleted file mode 100644 index b5d60d5..0000000 --- a/crates/render/src/views/mod.rs +++ /dev/null @@ -1 +0,0 @@ -//! fabrilis-render :: views - stub (see docs/ARCHITECTURE.md) diff --git a/crates/scene/Cargo.toml b/crates/scene/Cargo.toml index 0bd0453..f5d33cd 100644 --- a/crates/scene/Cargo.toml +++ b/crates/scene/Cargo.toml @@ -13,6 +13,8 @@ workspace = true fabrilis-core = { path = "../core" } fabrilis-materials = { path = "../materials" } fabrilis-storage = { path = "../storage" } +serde = { version = "1", features = ["derive"] } +ron = "0.12" [build-dependencies] fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/scene/src/import/mesh.rs b/crates/scene/src/import/mesh.rs new file mode 100644 index 0000000..a81fb48 --- /dev/null +++ b/crates/scene/src/import/mesh.rs @@ -0,0 +1,275 @@ +//! Indexed triangle mesh and its validation rules. +//! +//! The mesh is the common result of the STL and OBJ importers. Neither format +//! stores units, so positions are in metres only after the caller applies +//! [`Mesh::scaled`] with the source unit factor (see docs/COORDINATES.md). + +use core::fmt; +use fabrilis_core::units::CubicMeters; +use fabrilis_core::vec::Vec3; +use std::collections::BTreeMap; + +/// A closed, indexed triangle mesh in metres. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Mesh { + /// Vertex positions, metres. + pub positions: Vec, + /// Triangles as three indices into [`Self::positions`]. + pub indices: Vec<[u32; 3]>, +} + +impl Mesh { + /// Builds a mesh, rejecting triangles that reference a missing vertex. + pub fn new(positions: Vec, indices: Vec<[u32; 3]>) -> Result { + let mesh = Self { positions, indices }; + mesh.check_indices()?; + Ok(mesh) + } + + /// Every triangle as a position triple. + /// + /// Triangles whose indices point outside the position list are skipped; a + /// mesh built through [`Self::new`] never has any. + pub fn triangles(&self) -> impl Iterator + '_ { + self.indices + .iter() + .filter_map(|triangle| self.triangle(*triangle)) + } + + /// Scales every position by `factor`. + /// + /// Use `0.001` for millimetres, `0.01` for centimetres and `1.0` for metres + /// (see docs/COORDINATES.md). + #[must_use] + pub fn scaled(self, factor: f64) -> Self { + Self { + positions: self + .positions + .into_iter() + .map(|point| point * factor) + .collect(), + indices: self.indices, + } + } + + /// Signed volume, m³, from the divergence theorem: `Σ a·(b×c)/6`. + /// + /// `None` for an empty mesh, a triangle with a missing vertex or a non-finite + /// sum. A positive value means outward winding; see [`Self::validate`]. + #[must_use] + pub fn signed_volume(&self) -> Option { + if self.indices.is_empty() { + return None; + } + let mut six_volume = 0.0; + for triangle in &self.indices { + let [a, b, c] = self.triangle(*triangle)?; + six_volume += a.dot(b.cross(c)); + } + let volume = six_volume / 6.0; + volume.is_finite().then_some(volume) + } + + /// Total surface area, m². + #[must_use] + pub fn area(&self) -> f64 { + self.triangles() + .map(|[a, b, c]| (b - a).cross(c - a).length() * 0.5) + .sum() + } + + /// Checks that the mesh is a closed surface with outward winding. + /// + /// Every coordinate must be finite, every triangle must have area, every + /// undirected edge must be shared by exactly two triangles and traversed in + /// opposite directions, and the signed volume must be positive. This is the + /// check docs/TESTING.md requires before mass and inertia are computed. + pub fn validate(&self) -> Result { + if self.indices.is_empty() { + return Err(MeshError::Empty); + } + self.check_indices()?; + self.check_triangles()?; + self.check_edges()?; + let volume = self + .signed_volume() + .ok_or(MeshError::NonFinite { triangle: 0 })?; + if volume <= 0.0 { + return Err(MeshError::Inverted { volume }); + } + Ok(MeshReport { + vertices: self.positions.len(), + triangles: self.indices.len(), + volume: CubicMeters::new(volume), + degenerate: 0, + }) + } + + /// The three positions of a triangle, or `None` when an index is missing. + fn triangle(&self, [a, b, c]: [u32; 3]) -> Option<[Vec3; 3]> { + let a = *self.positions.get(a as usize)?; + let b = *self.positions.get(b as usize)?; + let c = *self.positions.get(c as usize)?; + Some([a, b, c]) + } + + fn check_indices(&self) -> Result<(), MeshError> { + for (triangle, corners) in self.indices.iter().enumerate() { + for &corner in corners { + if corner as usize >= self.positions.len() { + return Err(MeshError::BadIndex { triangle }); + } + } + } + Ok(()) + } + + fn check_triangles(&self) -> Result<(), MeshError> { + for (index, triangle) in self.indices.iter().enumerate() { + let [a, b, c] = self + .triangle(*triangle) + .ok_or(MeshError::BadIndex { triangle: index })?; + if [a, b, c].iter().any(|point| !point.is_finite()) { + return Err(MeshError::NonFinite { triangle: index }); + } + if (b - a).cross(c - a).length_squared() == 0.0 { + return Err(MeshError::Degenerate { triangle: index }); + } + } + Ok(()) + } + + fn check_edges(&self) -> Result<(), MeshError> { + let mut edges: BTreeMap<(u32, u32), EdgeUse> = BTreeMap::new(); + for triangle in &self.indices { + let [a, b, c] = *triangle; + for (start, end) in [(a, b), (b, c), (c, a)] { + let key = if start < end { + (start, end) + } else { + (end, start) + }; + let edge = edges.entry(key).or_default(); + if start < end { + edge.forward += 1; + } else { + edge.backward += 1; + } + } + } + let broken = edges + .values() + .filter(|edge| edge.forward + edge.backward != 2) + .count(); + if broken > 0 { + return Err(MeshError::NotWatertight { + undirected_edges: broken, + }); + } + if let Some((edge, _)) = edges.iter().find(|(_, edge)| edge.forward != 1) { + return Err(MeshError::InconsistentWinding { edge: *edge }); + } + Ok(()) + } +} + +/// How many triangles traverse an undirected edge in each direction. +#[derive(Default)] +struct EdgeUse { + /// Triangles going from the smaller index to the larger one. + forward: usize, + /// Triangles going from the larger index to the smaller one. + backward: usize, +} + +/// What [`Mesh::validate`] measured on a valid mesh. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MeshReport { + /// Number of vertices, including unused ones. + pub vertices: usize, + /// Number of triangles. + pub triangles: usize, + /// Enclosed volume, m³. + pub volume: CubicMeters, + /// Degenerate triangles found; always zero for a valid mesh. + pub degenerate: usize, +} + +/// Why a mesh or an imported file was rejected. +#[derive(Debug, Clone, PartialEq)] +pub enum MeshError { + /// The input has no triangles. + Empty, + /// A triangle references a vertex outside the position list. + BadIndex { + /// Zero-based triangle number. + triangle: usize, + }, + /// A triangle has a non-finite coordinate. + NonFinite { + /// Zero-based triangle number. + triangle: usize, + }, + /// A triangle has zero area. + Degenerate { + /// Zero-based triangle number. + triangle: usize, + }, + /// Edges are not shared by exactly two triangles. + NotWatertight { + /// Number of undirected edges with the wrong number of uses. + undirected_edges: usize, + }, + /// An edge is traversed twice in the same direction. + InconsistentWinding { + /// The undirected edge, smaller index first. + edge: (u32, u32), + }, + /// The signed volume is not positive, so the winding points inward. + Inverted { + /// The measured signed volume, m³. + volume: f64, + }, + /// A line of the source file could not be parsed. + /// + /// For binary STL `line` is the one-based triangle number. + Malformed { + /// One-based line number in the text, or triangle number in binary STL. + line: usize, + /// What went wrong. + reason: String, + }, +} + +impl fmt::Display for MeshError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Empty => write!(formatter, "mesh has no triangles"), + Self::BadIndex { triangle } => { + write!(formatter, "triangle {triangle} references a missing vertex") + } + Self::NonFinite { triangle } => { + write!(formatter, "triangle {triangle} has a non-finite coordinate") + } + Self::Degenerate { triangle } => { + write!(formatter, "triangle {triangle} has zero area") + } + Self::NotWatertight { undirected_edges } => write!( + formatter, + "mesh is not watertight: {undirected_edges} undirected edges are not shared by exactly two triangles" + ), + Self::InconsistentWinding { edge } => write!( + formatter, + "edge ({}, {}) is traversed twice in the same direction", + edge.0, edge.1 + ), + Self::Inverted { volume } => write!( + formatter, + "signed volume {volume} is not positive; the winding points inward" + ), + Self::Malformed { line, reason } => write!(formatter, "line {line}: {reason}"), + } + } +} + +impl std::error::Error for MeshError {} diff --git a/crates/scene/src/import/mod.rs b/crates/scene/src/import/mod.rs index d87435f..ffb949b 100644 --- a/crates/scene/src/import/mod.rs +++ b/crates/scene/src/import/mod.rs @@ -1 +1,18 @@ -//! fabrilis-scene :: import - stub (see docs/ARCHITECTURE.md) +//! Mesh import and validation: STL (binary and ASCII) and OBJ. +//! +//! Both formats store triangles without units or axes, so the caller records the +//! source units and converts with [`Mesh::scaled`] (docs/COORDINATES.md). +//! Validation is separate from parsing: an importer returns a mesh, and +//! [`Mesh::validate`] proves it is closed, has outward winding and a positive +//! volume before mass and inertia are computed (docs/TESTING.md). + +pub mod mesh; +pub mod obj; +pub mod stl; + +pub use mesh::{Mesh, MeshError, MeshReport}; +pub use obj::from_obj; +pub use stl::from_stl; + +#[cfg(test)] +mod tests; diff --git a/crates/scene/src/import/obj.rs b/crates/scene/src/import/obj.rs new file mode 100644 index 0000000..dff66fa --- /dev/null +++ b/crates/scene/src/import/obj.rs @@ -0,0 +1,134 @@ +//! OBJ import: the `v` and `f` subset needed for rigid parts. +//! +//! Supported statements: +//! +//! - `v x y z` — vertex position; extra components such as `w` are ignored; +//! - `f ...` — a polygon with three or more corners, fan-triangulated; a corner +//! may be written as `v`, `v/vt`, `v//vn` or `v/vt/vn`, and the vertex index +//! may be positive (one-based) or negative (relative to the vertices seen so +//! far). +//! +//! Comments and the `vt`, `vn`, `o`, `g`, `s`, `usemtl` and `mtllib` statements +//! are ignored. Any other statement is rejected as unsupported: this is a +//! documented subset, not a full OBJ reader. Units and axes are not stored in +//! OBJ; apply [`Mesh::scaled`] with the project factor (docs/COORDINATES.md). + +use core::str::SplitWhitespace; +use fabrilis_core::vec::Vec3; + +use super::mesh::{Mesh, MeshError}; + +/// Imports the vertex and face subset of a Wavefront OBJ file. +pub fn from_obj(text: &str) -> Result { + let mut positions = Vec::new(); + let mut indices = Vec::new(); + for (index, line) in text.lines().enumerate() { + parse_line(line, index + 1, &mut positions, &mut indices)?; + } + if indices.is_empty() { + return Err(MeshError::Empty); + } + Mesh::new(positions, indices) +} + +fn parse_line( + line: &str, + number: usize, + positions: &mut Vec, + indices: &mut Vec<[u32; 3]>, +) -> Result<(), MeshError> { + let content = line.split('#').next().unwrap_or_default(); + let mut words = content.split_whitespace(); + let Some(keyword) = words.next() else { + return Ok(()); + }; + match keyword { + "v" => parse_vertex(words, number, positions), + "f" => parse_face(words, number, positions.len(), indices), + "vt" | "vn" | "o" | "g" | "s" | "usemtl" | "mtllib" => Ok(()), + other => Err(malformed( + number, + format!("unsupported OBJ statement `{other}`"), + )), + } +} + +fn parse_vertex( + mut words: SplitWhitespace<'_>, + number: usize, + positions: &mut Vec, +) -> Result<(), MeshError> { + let x = coordinate(&mut words, number)?; + let y = coordinate(&mut words, number)?; + let z = coordinate(&mut words, number)?; + positions.push(Vec3::new(x, y, z)); + Ok(()) +} + +fn parse_face( + words: SplitWhitespace<'_>, + number: usize, + vertex_count: usize, + indices: &mut Vec<[u32; 3]>, +) -> Result<(), MeshError> { + let mut corners = Vec::new(); + for word in words { + corners.push(parse_corner(word, number, vertex_count)?); + } + let Some((&first, rest)) = corners.split_first() else { + return Err(short_face(number)); + }; + if rest.len() < 2 { + return Err(short_face(number)); + } + for pair in rest.windows(2) { + if let [a, b] = pair { + indices.push([first, *a, *b]); + } + } + Ok(()) +} + +/// Resolves one face corner such as `7`, `7/2`, `7//3` or `7/2/3`. +fn parse_corner(word: &str, number: usize, vertex_count: usize) -> Result { + let mut parts = word.split('/'); + let vertex = parts.next().unwrap_or_default(); + if vertex.is_empty() || parts.count() > 2 { + return Err(bad_corner(word, number)); + } + let Ok(raw) = vertex.parse::() else { + return Err(bad_corner(word, number)); + }; + let resolved = match raw { + 0 => return Err(malformed(number, "OBJ vertex indices are one-based")), + relative if relative < 0 => vertex_count as i64 + relative, + absolute => absolute - 1, + }; + if resolved < 0 { + return Err(bad_corner(word, number)); + } + u32::try_from(resolved).map_err(|_| bad_corner(word, number)) +} + +fn coordinate(words: &mut SplitWhitespace<'_>, line: usize) -> Result { + let Some(word) = words.next() else { + return Err(malformed(line, "missing vertex coordinate")); + }; + word.parse() + .map_err(|_| malformed(line, format!("`{word}` is not a valid coordinate"))) +} + +fn short_face(line: usize) -> MeshError { + malformed(line, "face needs at least three vertices".to_string()) +} + +fn bad_corner(word: &str, line: usize) -> MeshError { + malformed(line, format!("`{word}` is not a valid face corner")) +} + +fn malformed(line: usize, reason: impl Into) -> MeshError { + MeshError::Malformed { + line, + reason: reason.into(), + } +} diff --git a/crates/scene/src/import/stl.rs b/crates/scene/src/import/stl.rs new file mode 100644 index 0000000..9d097ed --- /dev/null +++ b/crates/scene/src/import/stl.rs @@ -0,0 +1,256 @@ +//! STL import for binary and ASCII files. +//! +//! STL stores a triangle soup without shared vertices and without units. Import +//! welds vertices whose coordinates are bitwise equal after the `f32` → `f64` +//! conversion, so a well-formed file becomes a watertight indexed mesh. Welding +//! uses the bit pattern, so `-0.0` and `0.0` stay distinct: a file that mixes +//! signed zero can keep a seam and fail [`Mesh::validate`]. Normals are ignored; +//! the winding of the `vertex` lines is authoritative and validation checks it. +//! +//! Units are not stored either, so apply [`Mesh::scaled`] with the project unit +//! factor (millimetres by default, see docs/COORDINATES.md). + +use core::str::SplitWhitespace; +use fabrilis_core::vec::Vec3; +use std::collections::BTreeMap; + +use super::mesh::{Mesh, MeshError}; + +/// Bytes before the triangle count in a binary STL file. +const HEADER: usize = 80; +/// Bytes in one binary STL triangle record: one normal and three vertices. +const RECORD: usize = 50; +/// Bytes occupied by the normal at the start of a record; the normal is ignored. +const NORMAL: usize = 12; + +/// Imports a binary or ASCII STL file. +/// +/// Binary detection requires at least 84 bytes and an exact match between the +/// file length and `84 + 50 × triangle count`; anything else is parsed as ASCII. +pub fn from_stl(bytes: &[u8]) -> Result { + if let Some(count) = binary_triangles(bytes) { + return from_binary(bytes, count); + } + from_ascii(bytes) +} + +/// The declared triangle count when `bytes` is a binary STL file. +fn binary_triangles(bytes: &[u8]) -> Option { + let count = u32::from_le_bytes(four_bytes(bytes, HEADER)?) as usize; + let expected = (HEADER + 4).checked_add(RECORD.checked_mul(count)?)?; + (expected == bytes.len()).then_some(count) +} + +fn from_binary(bytes: &[u8], count: usize) -> Result { + if count == 0 { + return Err(MeshError::Empty); + } + let mut welder = Welder::default(); + let mut indices = Vec::with_capacity(count); + for triangle in 0..count { + let start = HEADER + 4 + triangle * RECORD; + let points = binary_triangle(bytes, start).ok_or_else(|| truncated(triangle + 1))?; + indices.push(points.map(|point| welder.index(point))); + } + Mesh::new(welder.positions, indices) +} + +/// Three vertices of one binary record; the normal at `start` is skipped. +fn binary_triangle(bytes: &[u8], start: usize) -> Option<[Vec3; 3]> { + let mut points = [Vec3::ZERO; 3]; + for (index, slot) in points.iter_mut().enumerate() { + let base = start + NORMAL + index * 12; + let x = f32::from_le_bytes(four_bytes(bytes, base)?); + let y = f32::from_le_bytes(four_bytes(bytes, base + 4)?); + let z = f32::from_le_bytes(four_bytes(bytes, base + 8)?); + *slot = Vec3::new(f64::from(x), f64::from(y), f64::from(z)); + } + Some(points) +} + +fn four_bytes(bytes: &[u8], offset: usize) -> Option<[u8; 4]> { + let end = offset.checked_add(4)?; + bytes.get(offset..end)?.try_into().ok() +} + +fn truncated(line: usize) -> MeshError { + MeshError::Malformed { + line, + reason: "truncated binary STL triangle".to_string(), + } +} + +fn from_ascii(bytes: &[u8]) -> Result { + let text = core::str::from_utf8(bytes).map_err(|error| MeshError::Malformed { + line: line_at(bytes, error.valid_up_to()), + reason: "STL text is not valid UTF-8".to_string(), + })?; + let mut parser = Ascii::default(); + for (index, line) in text.lines().enumerate() { + parser.line(line, index + 1)?; + } + parser.finish() +} + +fn line_at(bytes: &[u8], offset: usize) -> usize { + bytes.get(..offset).map_or(1, |prefix| { + 1 + prefix.iter().filter(|byte| **byte == b'\n').count() + }) +} + +/// State of the ASCII facet grammar. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +enum Stage { + /// Between facets. + #[default] + Idle, + /// After `facet normal`, before `outer loop`. + Facet, + /// Inside `outer loop`. + Loop, + /// After `endloop`, before `endfacet`. + Closed, +} + +/// A small state machine over ASCII STL keywords. +#[derive(Default)] +struct Ascii { + welder: Welder, + indices: Vec<[u32; 3]>, + stage: Stage, + loop_vertices: Vec, + last_line: usize, +} + +impl Ascii { + fn line(&mut self, text: &str, number: usize) -> Result<(), MeshError> { + self.last_line = number; + let mut words = text.split_whitespace(); + let Some(keyword) = words.next() else { + return Ok(()); + }; + match keyword.to_ascii_lowercase().as_str() { + "solid" | "endsolid" => Ok(()), + "facet" => self.facet(words, number), + "outer" => self.outer(words, number), + "vertex" => self.vertex(words, number), + "endloop" => self.end_loop(number), + "endfacet" => self.end_facet(number), + other => Err(malformed( + number, + format!("unexpected STL keyword `{other}`"), + )), + } + } + + fn facet(&mut self, mut words: SplitWhitespace<'_>, number: usize) -> Result<(), MeshError> { + if self.stage != Stage::Idle { + return Err(malformed(number, "`facet` without `endfacet`")); + } + let kind = words.next().unwrap_or_default(); + if !kind.eq_ignore_ascii_case("normal") { + return Err(malformed(number, "expected `facet normal`")); + } + for _ in 0..3 { + number_value(&mut words, number, "normal component")?; + } + self.stage = Stage::Facet; + Ok(()) + } + + fn outer(&mut self, mut words: SplitWhitespace<'_>, number: usize) -> Result<(), MeshError> { + let kind = words.next().unwrap_or_default(); + if self.stage != Stage::Facet || !kind.eq_ignore_ascii_case("loop") { + return Err(malformed(number, "expected `outer loop` after `facet`")); + } + self.loop_vertices.clear(); + self.stage = Stage::Loop; + Ok(()) + } + + fn vertex(&mut self, mut words: SplitWhitespace<'_>, number: usize) -> Result<(), MeshError> { + if self.stage != Stage::Loop { + return Err(malformed(number, "`vertex` outside `outer loop`")); + } + let x = number_value(&mut words, number, "vertex coordinate")?; + let y = number_value(&mut words, number, "vertex coordinate")?; + let z = number_value(&mut words, number, "vertex coordinate")?; + let index = self.welder.index(Vec3::new(x, y, z)); + self.loop_vertices.push(index); + Ok(()) + } + + fn end_loop(&mut self, number: usize) -> Result<(), MeshError> { + if self.stage != Stage::Loop { + return Err(malformed(number, "`endloop` outside a loop")); + } + let corners: [u32; 3] = self.loop_vertices.as_slice().try_into().map_err(|_| { + malformed( + number, + "an STL facet must have exactly three vertices".to_string(), + ) + })?; + self.indices.push(corners); + self.loop_vertices.clear(); + self.stage = Stage::Closed; + Ok(()) + } + + fn end_facet(&mut self, number: usize) -> Result<(), MeshError> { + if self.stage != Stage::Closed { + return Err(malformed(number, "`endfacet` without a complete facet")); + } + self.stage = Stage::Idle; + Ok(()) + } + + fn finish(self) -> Result { + if self.stage != Stage::Idle { + return Err(malformed(self.last_line, "unterminated STL facet")); + } + if self.indices.is_empty() { + return Err(MeshError::Empty); + } + Mesh::new(self.welder.positions, self.indices) + } +} + +/// One floating-point token, with a line number for the error. +fn number_value( + words: &mut SplitWhitespace<'_>, + line: usize, + what: &str, +) -> Result { + let Some(word) = words.next() else { + return Err(malformed(line, format!("missing {what}"))); + }; + word.parse() + .map_err(|_| malformed(line, format!("`{word}` is not a valid {what}"))) +} + +fn malformed(line: usize, reason: impl Into) -> MeshError { + MeshError::Malformed { + line, + reason: reason.into(), + } +} + +/// Interns vertices by the bit pattern of their coordinates. +#[derive(Default)] +struct Welder { + positions: Vec, + lookup: BTreeMap<(u64, u64, u64), u32>, +} + +impl Welder { + fn index(&mut self, point: Vec3) -> u32 { + let key = (point.x.to_bits(), point.y.to_bits(), point.z.to_bits()); + if let Some(&index) = self.lookup.get(&key) { + return index; + } + let index = self.positions.len() as u32; + self.positions.push(point); + self.lookup.insert(key, index); + index + } +} diff --git a/crates/scene/src/import/tests.rs b/crates/scene/src/import/tests.rs new file mode 100644 index 0000000..1a675a2 --- /dev/null +++ b/crates/scene/src/import/tests.rs @@ -0,0 +1,283 @@ +use super::*; +use fabrilis_core::vec::Vec3; + +fn close(actual: f64, expected: f64) -> bool { + (actual - expected).abs() <= 1e-9 * expected.abs().max(1.0) +} + +fn cube_positions() -> Vec { + vec![ + Vec3::new(0.0, 0.0, 0.0), + Vec3::new(1.0, 0.0, 0.0), + Vec3::new(1.0, 1.0, 0.0), + Vec3::new(0.0, 1.0, 0.0), + Vec3::new(0.0, 0.0, 1.0), + Vec3::new(1.0, 0.0, 1.0), + Vec3::new(1.0, 1.0, 1.0), + Vec3::new(0.0, 1.0, 1.0), + ] +} + +/// The unit cube with outward winding, two triangles per side. +const UNIT_CUBE: [[u32; 3]; 12] = [ + [0, 2, 1], + [0, 3, 2], + [4, 5, 6], + [4, 6, 7], + [0, 1, 5], + [0, 5, 4], + [2, 3, 7], + [2, 7, 6], + [0, 4, 7], + [0, 7, 3], + [1, 2, 6], + [1, 6, 5], +]; + +fn cube_mesh() -> Mesh { + Mesh::new(cube_positions(), UNIT_CUBE.to_vec()).expect("the unit cube has in-range indices") +} + +fn cube_triangles() -> Vec<[Vec3; 3]> { + cube_mesh().triangles().collect() +} + +fn ascii_stl(triangles: &[[Vec3; 3]]) -> String { + let mut text = String::from("solid cube\n"); + for [a, b, c] in triangles { + text.push_str(" facet normal 0 0 0\n outer loop\n"); + for point in [a, b, c] { + text.push_str(&format!( + " vertex {} {} {}\n", + point.x, point.y, point.z + )); + } + text.push_str(" endloop\n endfacet\n"); + } + text.push_str("endsolid cube\n"); + text +} + +fn binary_stl(triangles: &[[Vec3; 3]]) -> Vec { + let mut bytes = vec![0u8; 80]; + bytes.extend_from_slice(&(triangles.len() as u32).to_le_bytes()); + for [a, b, c] in triangles { + for _ in 0..3 { + bytes.extend_from_slice(&0f32.to_le_bytes()); + } + for point in [a, b, c] { + for value in [point.x, point.y, point.z] { + bytes.extend_from_slice(&(value as f32).to_le_bytes()); + } + } + bytes.extend_from_slice(&0u16.to_le_bytes()); + } + bytes +} + +const OBJ_CUBE: &str = "\ +v 0 0 0 +v 1 0 0 +v 1 1 0 +v 0 1 0 +v 0 0 1 +v 1 0 1 +v 1 1 1 +v 0 1 1 +f 1 4 3 2 +f 5 6 7 8 +f 1 2 6 5 +f 3 4 8 7 +f 1 5 8 4 +f 2 3 7 6 +"; + +const OBJ_TETRA_RELATIVE: &str = "\ +v 0 0 0 +v 1 0 0 +v 0 1 0 +v 0 0 1 +f -4 -2 -3 +f -4 -3 -1 +f -3 -2 -1 +f -4 -1 -2 +"; + +#[test] +fn ascii_stl_cube_validates_and_welds_vertices() { + let text = ascii_stl(&cube_triangles()); + let mesh = from_stl(text.as_bytes()).expect("the ASCII cube imports"); + assert_eq!(mesh.positions.len(), 8, "36 facet vertices weld into 8"); + assert_eq!(mesh.triangles().count(), 12); + + let report = mesh.validate().expect("the cube is watertight"); + assert_eq!(report.vertices, 8); + assert_eq!(report.triangles, 12); + assert_eq!(report.degenerate, 0); + assert!(close(report.volume.get(), 1.0), "volume {report:?}"); + assert!(close(mesh.area(), 6.0), "area {}", mesh.area()); +} + +#[test] +fn binary_stl_cube_matches_the_ascii_result() { + let bytes = binary_stl(&cube_triangles()); + assert_eq!(bytes.len(), 84 + 50 * 12); + let mesh = from_stl(&bytes).expect("the binary cube imports"); + assert_eq!(mesh.positions.len(), 8); + assert_eq!(mesh.triangles().count(), 12); + + let report = mesh.validate().expect("the cube is watertight"); + assert!(close(report.volume.get(), 1.0), "volume {report:?}"); + assert!(close(mesh.area(), 6.0), "area {}", mesh.area()); +} + +#[test] +fn obj_quad_faces_are_fan_triangulated() { + let mesh = from_obj(OBJ_CUBE).expect("the OBJ cube imports"); + assert_eq!(mesh.positions.len(), 8); + assert_eq!( + mesh.triangles().count(), + 12, + "six quads become 12 triangles" + ); + + let report = mesh.validate().expect("the cube is watertight"); + assert_eq!(report.vertices, 8); + assert_eq!(report.triangles, 12); + assert!(close(report.volume.get(), 1.0), "volume {report:?}"); + assert!(close(mesh.area(), 6.0), "area {}", mesh.area()); +} + +#[test] +fn obj_negative_indices_resolve_relative_to_the_end() { + let mesh = from_obj(OBJ_TETRA_RELATIVE).expect("relative indices resolve"); + assert_eq!(mesh.positions.len(), 4); + assert_eq!(mesh.triangles().count(), 4); + + let report = mesh.validate().expect("the tetrahedron is watertight"); + assert!(close(report.volume.get(), 1.0 / 6.0), "volume {report:?}"); +} + +#[test] +fn open_mesh_is_not_watertight() { + let indices = UNIT_CUBE.iter().take(11).copied().collect(); + let mesh = Mesh::new(cube_positions(), indices).expect("indices are in range"); + let error = mesh + .validate() + .expect_err("a missing triangle opens the surface"); + assert!( + matches!( + error, + MeshError::NotWatertight { + undirected_edges: 3 + } + ), + "unexpected error {error:?}" + ); +} + +#[test] +fn reversed_triangle_breaks_the_winding() { + let mut indices = UNIT_CUBE.to_vec(); + if let Some(last) = indices.last_mut() { + *last = [1, 5, 6]; + } + let mesh = Mesh::new(cube_positions(), indices).expect("indices are in range"); + let error = mesh + .validate() + .expect_err("one reversed triangle breaks winding"); + assert!( + matches!(error, MeshError::InconsistentWinding { .. }), + "unexpected error {error:?}" + ); +} + +#[test] +fn fully_reversed_cube_is_inverted() { + let indices = UNIT_CUBE.iter().map(|&[a, b, c]| [a, c, b]).collect(); + let mesh = Mesh::new(cube_positions(), indices).expect("indices are in range"); + match mesh + .validate() + .expect_err("inward winding has negative volume") + { + MeshError::Inverted { volume } => assert!(close(volume, -1.0), "volume {volume}"), + other => panic!("expected Inverted, got {other:?}"), + } +} + +#[test] +fn out_of_range_index_is_rejected() { + let error = Mesh::new(vec![Vec3::ZERO], vec![[0, 1, 2]]).expect_err("one vertex is not enough"); + assert_eq!(error, MeshError::BadIndex { triangle: 0 }); + + let text = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 4\n"; + let error = from_obj(text).expect_err("the face names a missing vertex"); + assert_eq!(error, MeshError::BadIndex { triangle: 0 }); +} + +#[test] +fn empty_input_is_rejected() { + assert!(matches!(from_obj(""), Err(MeshError::Empty))); + assert!(matches!( + from_obj("# only a comment\n"), + Err(MeshError::Empty) + )); + assert!(matches!(from_stl(b""), Err(MeshError::Empty))); +} + +#[test] +fn scaled_converts_millimetres_to_metres() { + let millimetres = cube_mesh().scaled(1000.0); + let triangles: Vec<_> = millimetres.triangles().collect(); + let imported = from_stl(&binary_stl(&triangles)).expect("the millimetre cube imports"); + let cubic_millimetres = imported.signed_volume().expect("closed mesh"); + assert!( + close(cubic_millimetres, 1.0e9), + "volume {cubic_millimetres}" + ); + + let metres = imported.scaled(0.001); + assert_eq!(metres.indices.len(), 12); + let report = metres.validate().expect("the metre cube is valid"); + assert!(close(report.volume.get(), 1.0), "volume {report:?}"); +} + +#[test] +fn degenerate_triangle_is_rejected() { + let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y]; + let mesh = Mesh::new(positions, vec![[0, 0, 1]]).expect("indices are in range"); + assert_eq!( + mesh.validate().expect_err("a repeated corner has no area"), + MeshError::Degenerate { triangle: 0 } + ); +} + +#[test] +fn non_finite_vertex_is_rejected() { + let positions = vec![Vec3::new(f64::NAN, 0.0, 0.0), Vec3::Y, Vec3::Z]; + let mesh = Mesh::new(positions, vec![[0, 1, 2]]).expect("indices are in range"); + assert_eq!( + mesh.validate().expect_err("NaN is not a coordinate"), + MeshError::NonFinite { triangle: 0 } + ); +} + +#[test] +fn malformed_obj_face_reports_its_line() { + let text = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 nope\n"; + let error = from_obj(text).expect_err("the face corner is not a number"); + assert!( + matches!(error, MeshError::Malformed { line: 4, .. }), + "unexpected error {error:?}" + ); +} + +#[test] +fn malformed_stl_line_reports_its_line() { + let text = "solid cube\n nonsense here\nendsolid cube\n"; + let error = from_stl(text.as_bytes()).expect_err("the keyword is unknown"); + assert!( + matches!(error, MeshError::Malformed { line: 2, .. }), + "unexpected error {error:?}" + ); +} diff --git a/crates/scene/src/model/mass.rs b/crates/scene/src/model/mass.rs new file mode 100644 index 0000000..0627f2d --- /dev/null +++ b/crates/scene/src/model/mass.rs @@ -0,0 +1,114 @@ +//! Mass properties of a part and of a whole design. +//! +//! A part's result already has its centre of mass and inertia in the design frame: +//! the mesh is measured in its own axes and then moved by the pose. Aggregating +//! parts therefore needs only the parallel-axis theorem, with `d` measured from +//! the assembly centre of mass. + +use fabrilis_core::units::{CubicMeters, Kilograms}; +use fabrilis_core::vec::{Mat3, Vec3}; +use fabrilis_materials::db::MaterialDb; +use fabrilis_materials::massprops::{MassProperties, from_triangles}; +use fabrilis_storage::blob::BlobStore; + +use super::{Design, Part, SceneError, load_mesh}; + +impl Part { + /// Mass, centre of mass and inertia of this part in the design frame. + /// + /// The centre of mass is moved by the pose, and the inertia about the part's + /// centre of mass is rotated into design axes (`R I Rᵀ`). + pub fn mass( + &self, + materials: &MaterialDb, + store: &BlobStore, + ) -> Result { + let transform = self.pose.to_transform().ok_or(SceneError::BadPose)?; + let mesh = load_mesh(store, self.mesh)?; + let material = materials + .get(&self.material) + .ok_or_else(|| SceneError::UnknownMaterial(self.material.clone()))?; + let triangles: Vec<[Vec3; 3]> = mesh.triangles().collect(); + let local = from_triangles(&triangles, material.density).ok_or(SceneError::BadMass)?; + let rotation = transform.rotation.to_mat3(); + Ok(MassProperties { + volume: local.volume, + mass: local.mass, + center_of_mass: transform.transform_point(local.center_of_mass), + inertia: rotation * local.inertia * rotation.transpose(), + }) + } +} + +impl Design { + /// Mass, centre of mass and inertia of the assembly. + /// + /// Total mass is the sum of the parts, the centre of mass is mass-weighted, + /// and each part's inertia is shifted to the assembly centre with the + /// parallel-axis theorem. An empty design is an error, not a zero mass. + pub fn mass_properties( + &self, + materials: &MaterialDb, + store: &BlobStore, + ) -> Result { + let parts: Vec = self + .parts + .iter() + .map(|part| part.mass(materials, store)) + .collect::>()?; + if parts.is_empty() { + return Err(SceneError::EmptyDesign); + } + let total_mass: f64 = parts.iter().map(|part| part.mass.get()).sum(); + let weighted = parts.iter().fold(Vec3::ZERO, |sum, part| { + sum + part.center_of_mass * part.mass.get() + }); + let center_of_mass = weighted / total_mass; + if !total_mass.is_finite() || total_mass <= 0.0 || !center_of_mass.is_finite() { + return Err(SceneError::BadMass); + } + let mut inertia = Mat3::from_diagonal(Vec3::ZERO); + for part in &parts { + let offset = part.center_of_mass - center_of_mass; + inertia = sum_matrices( + inertia, + parallel_axis(part.inertia, part.mass.get(), offset), + ); + } + let volume: f64 = parts.iter().map(|part| part.volume.get()).sum(); + if !inertia_is_finite(inertia) || !volume.is_finite() { + return Err(SceneError::BadMass); + } + Ok(MassProperties { + volume: CubicMeters::new(volume), + mass: Kilograms::new(total_mass), + center_of_mass, + inertia, + }) + } +} + +/// Adds `m (|d|² I − d dᵀ)` to `inertia`. +fn parallel_axis(inertia: Mat3, mass: f64, offset: Vec3) -> Mat3 { + let (x, y, z) = (offset.x, offset.y, offset.z); + let square = offset.length_squared(); + let shift = Mat3::from_cols( + Vec3::new(mass * (square - x * x), -mass * x * y, -mass * x * z), + Vec3::new(-mass * y * x, mass * (square - y * y), -mass * y * z), + Vec3::new(-mass * z * x, -mass * z * y, mass * (square - z * z)), + ); + sum_matrices(inertia, shift) +} + +fn sum_matrices(left: Mat3, right: Mat3) -> Mat3 { + let [lx, ly, lz] = left.cols(); + let [rx, ry, rz] = right.cols(); + Mat3::from_cols(lx + rx, ly + ry, lz + rz) +} + +fn inertia_is_finite(inertia: Mat3) -> bool { + inertia + .cols() + .iter() + .all(|column| column.x.is_finite() && column.y.is_finite() && column.z.is_finite()) +} diff --git a/crates/scene/src/model/mesh.rs b/crates/scene/src/model/mesh.rs new file mode 100644 index 0000000..95afc37 --- /dev/null +++ b/crates/scene/src/model/mesh.rs @@ -0,0 +1,84 @@ +//! Mesh blobs: the RON form stored in a content-addressed blob store. +//! +//! The mesh is stored once per distinct geometry; parts reference it by +//! [`BlobHash`](fabrilis_storage::blob::BlobHash) (docs/STORAGE.md). + +use fabrilis_core::vec::Vec3; +use fabrilis_storage::blob::{BlobHash, BlobStore}; +use serde::{Deserialize, Serialize}; + +use crate::import::{Mesh, from_stl}; + +use super::{Part, Pose, SceneError}; + +/// The on-disk mesh form: arrays instead of core math types, which have no serde. +#[derive(Debug, Clone, Serialize, Deserialize)] +struct StoredMesh { + positions: Vec<[f64; 3]>, + indices: Vec<[u32; 3]>, +} + +/// Serialises the mesh as RON and stores it, returning its content hash. +/// +/// Storing identical geometry twice is a no-op: the hash, and therefore the file, +/// is the same. +pub fn store_mesh(store: &mut BlobStore, mesh: &Mesh) -> Result { + let stored = StoredMesh { + positions: mesh + .positions + .iter() + .map(|point| [point.x, point.y, point.z]) + .collect(), + indices: mesh.indices.clone(), + }; + let text = ron::ser::to_string_pretty(&stored, ron::ser::PrettyConfig::default()) + .map_err(|error| SceneError::MeshBlob(error.to_string()))?; + Ok(store.put(text.as_bytes())?) +} + +/// Reads a stored mesh and validates it as a closed, outward-wound surface. +pub fn load_mesh(store: &BlobStore, hash: BlobHash) -> Result { + let bytes = store.get(hash)?; + let text = + core::str::from_utf8(&bytes).map_err(|error| SceneError::MeshBlob(error.to_string()))?; + let stored: StoredMesh = + ron::from_str(text).map_err(|error| SceneError::MeshBlob(error.to_string()))?; + let positions = stored + .positions + .iter() + .map(|&[x, y, z]| Vec3::new(x, y, z)) + .collect(); + let mesh = Mesh::new(positions, stored.indices)?; + mesh.validate()?; + Ok(mesh) +} + +/// Imports an STL part: parse, scale to metres, validate, then store the mesh. +/// +/// STL carries neither units nor axes, so `unit_scale` is the source unit factor +/// (`0.001` for millimetres, `1.0` for metres); see docs/COORDINATES.md. +#[allow( + clippy::too_many_arguments, + reason = "the STL import inputs are independent scalars; a group struct would obscure the call site" +)] +pub fn add_part_from_stl( + store: &mut BlobStore, + name: &str, + stl: &[u8], + unit_scale: f64, + material: &str, + pose: Pose, +) -> Result { + if !unit_scale.is_finite() || unit_scale <= 0.0 { + return Err(SceneError::BadScale(unit_scale)); + } + let mesh = from_stl(stl)?.scaled(unit_scale); + mesh.validate()?; + let hash = store_mesh(store, &mesh)?; + Ok(Part { + name: name.to_string(), + mesh: hash, + material: material.to_string(), + pose, + }) +} diff --git a/crates/scene/src/model/mod.rs b/crates/scene/src/model/mod.rs index 0023c6a..5504abb 100644 --- a/crates/scene/src/model/mod.rs +++ b/crates/scene/src/model/mod.rs @@ -1 +1,193 @@ -//! fabrilis-scene :: model - stub (see docs/ARCHITECTURE.md) +//! Design model: named rigid parts and their mass properties. +//! +//! A part references its mesh by content hash, so one copy of a mesh serves every +//! part that uses it (docs/STORAGE.md). Poses are plain arrays because the core +//! math types intentionally do not depend on serde; conversion to [`Transform`] +//! normalises the quaternion and rejects degenerate input. + +mod mass; +mod mesh; +mod persist; + +use core::fmt; +use std::io; + +use fabrilis_core::vec::{Quat, Transform, Vec3}; +use fabrilis_storage::blob::BlobHash; +use fabrilis_storage::format::FormatError; +use serde::{Deserialize, Serialize}; + +use crate::import::MeshError; + +pub use mesh::{add_part_from_stl, load_mesh, store_mesh}; +pub use persist::DESIGN_FILE; + +/// A serialisable rigid pose: position in metres and a `wxyz` quaternion. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct Pose { + /// Position, m. + pub position: [f64; 3], + /// Rotation as a `wxyz` quaternion; not necessarily unit length. + pub rotation: [f64; 4], +} + +impl Default for Pose { + fn default() -> Self { + Self { + position: [0.0; 3], + rotation: [1.0, 0.0, 0.0, 0.0], + } + } +} + +impl Pose { + /// The corresponding [`Transform`], or `None` for a non-finite position or a + /// zero/non-finite quaternion. + #[must_use] + pub fn to_transform(self) -> Option { + let position = Vec3::new(self.position[0], self.position[1], self.position[2]); + if !position.is_finite() { + return None; + } + let rotation = Quat::new( + self.rotation[0], + self.rotation[1], + self.rotation[2], + self.rotation[3], + ) + .normalize()?; + Some(Transform::new(position, rotation)) + } + + /// The pose that places a transform, keeping its quaternion as given. + #[must_use] + pub fn from_transform(transform: Transform) -> Self { + Self { + position: [ + transform.position.x, + transform.position.y, + transform.position.z, + ], + rotation: [ + transform.rotation.w, + transform.rotation.x, + transform.rotation.y, + transform.rotation.z, + ], + } + } +} + +/// One rigid part: a mesh, a material and a pose in the design's frame. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Part { + /// Name, unique within the design by convention. + pub name: String, + /// Content hash of the stored mesh. + pub mesh: BlobHash, + /// Material name in a [`fabrilis_materials::db::MaterialDb`]. + pub material: String, + /// Placement of the part's mesh in the design frame. + pub pose: Pose, +} + +/// A named collection of parts. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Design { + /// Design name. + pub name: String, + /// Parts in insertion order. + pub parts: Vec, +} + +impl Design { + /// An empty design. + #[must_use] + pub fn new(name: impl Into) -> Self { + Self { + name: name.into(), + parts: Vec::new(), + } + } + + /// Appends a part. + pub fn push(&mut self, part: Part) { + self.parts.push(part); + } +} + +/// Why a design, a mesh blob or a mass computation failed. +#[derive(Debug)] +pub enum SceneError { + /// Reading or writing a project file failed. + Io(io::Error), + /// The versioned scene envelope is invalid. + Format(FormatError), + /// The mesh itself is invalid before it is stored. + Mesh(MeshError), + /// A stored mesh blob cannot be decoded. + MeshBlob(String), + /// The material name is not in the database. + UnknownMaterial(String), + /// The pose has a non-finite position or a zero/non-finite rotation. + BadPose, + /// The unit scale must be finite and positive. + BadScale(f64), + /// There is nothing to aggregate. + EmptyDesign, + /// Aggregated mass properties are not finite. + BadMass, +} + +impl fmt::Display for SceneError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Io(error) => write!(formatter, "project I/O failed: {error}"), + Self::Format(error) => write!(formatter, "scene format error: {error}"), + Self::Mesh(error) => write!(formatter, "mesh error: {error}"), + Self::MeshBlob(reason) => write!(formatter, "stored mesh is invalid: {reason}"), + Self::UnknownMaterial(name) => write!(formatter, "unknown material `{name}`"), + Self::BadPose => write!( + formatter, + "pose has a non-finite position or a zero/non-finite rotation" + ), + Self::BadScale(scale) => { + write!(formatter, "unit scale {scale} must be finite and positive") + } + Self::EmptyDesign => write!(formatter, "design has no parts"), + Self::BadMass => write!(formatter, "aggregated mass properties are not finite"), + } + } +} + +impl std::error::Error for SceneError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + Self::Format(error) => Some(error), + Self::Mesh(error) => Some(error), + _ => None, + } + } +} + +impl From for SceneError { + fn from(error: io::Error) -> Self { + Self::Io(error) + } +} + +impl From for SceneError { + fn from(error: FormatError) -> Self { + Self::Format(error) + } +} + +impl From for SceneError { + fn from(error: MeshError) -> Self { + Self::Mesh(error) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/scene/src/model/persist.rs b/crates/scene/src/model/persist.rs new file mode 100644 index 0000000..c34edf8 --- /dev/null +++ b/crates/scene/src/model/persist.rs @@ -0,0 +1,76 @@ +//! Reading and writing `scene.ron` in a project folder. +//! +//! Version 0 of the scene format had no per-part `pose`; the migration below fills +//! in the identity pose, so an old cart opens without edits. + +use std::collections::BTreeMap; + +use fabrilis_storage::format::{from_ron_with_migrations, to_ron}; +use fabrilis_storage::migrate::{MigrateError, Migration}; +use fabrilis_storage::project::Project; + +use super::{Design, Pose, SceneError}; + +/// File name of the design inside a project. +pub const DESIGN_FILE: &str = "scene.ron"; + +impl Design { + /// Writes the design as a versioned RON envelope in the project. + pub fn save(&self, project: &Project) -> Result<(), SceneError> { + let text = to_ron(self)?; + project.write_text(DESIGN_FILE, &text)?; + Ok(()) + } + + /// Reads the design, migrating older scene versions forward. + pub fn load(project: &Project) -> Result { + let text = project.read_text(DESIGN_FILE)?; + Ok(from_ron_with_migrations(&text, &migrations())?) + } +} + +fn migrations() -> BTreeMap { + let mut steps = BTreeMap::new(); + let _previous = steps.insert(0, add_identity_pose as Migration); + steps +} + +/// Version 0 → 1: every part gains the identity pose. +fn add_identity_pose(mut value: ron::Value) -> Result { + let ron::Value::Map(ref mut design) = value else { + return Err(MigrateError::step(0, "scene payload is not a map")); + }; + let Some(parts) = design.get_mut(&ron::Value::from("parts")) else { + return Err(MigrateError::step(0, "scene payload has no parts")); + }; + let ron::Value::Seq(parts) = parts else { + return Err(MigrateError::step(0, "scene parts are not a list")); + }; + for part in parts.iter_mut() { + let ron::Value::Map(part) = part else { + return Err(MigrateError::step(0, "a scene part is not a map")); + }; + if part.get(&ron::Value::from("pose")).is_none() { + let _previous = part.insert("pose", pose_value(Pose::default())); + } + } + Ok(value) +} + +/// The RON form of a pose, for migrations over [`ron::Value`]. +fn pose_value(pose: Pose) -> ron::Value { + let position = pose + .position + .iter() + .map(|&value| ron::Value::from(value)) + .collect(); + let rotation = pose + .rotation + .iter() + .map(|&value| ron::Value::from(value)) + .collect(); + let mut map = ron::Map::new(); + let _previous = map.insert("position", ron::Value::Seq(position)); + let _previous = map.insert("rotation", ron::Value::Seq(rotation)); + ron::Value::Map(map) +} diff --git a/crates/scene/src/model/tests.rs b/crates/scene/src/model/tests.rs new file mode 100644 index 0000000..659ec6f --- /dev/null +++ b/crates/scene/src/model/tests.rs @@ -0,0 +1,223 @@ +//! Pose conversion, mesh blobs and per-part mass properties. + +#![allow( + clippy::unwrap_used, + reason = "a test aborts on failure, which is the intent" +)] + +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use fabrilis_core::vec::{Transform, Vec3}; +use fabrilis_materials::db::MaterialDb; +use fabrilis_storage::blob::BlobStore; + +use super::{Design, Pose, SceneError, add_part_from_stl, load_mesh, store_mesh}; +use crate::import::from_stl; + +/// A directory removed on drop. +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(label: &str) -> Self { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let counter = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "fabrilis-scene-{label}-{}-{counter}", + std::process::id() + )); + std::fs::create_dir_all(&path).unwrap(); + Self { path } + } + + fn blobs(&self) -> BlobStore { + BlobStore::new(self.path.join("blobs")) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +/// A box with the given full extents, centred at the origin, as an ASCII STL. +fn box_stl(x: f64, y: f64, z: f64) -> String { + let (hx, hy, hz) = (x * 0.5, y * 0.5, z * 0.5); + let vertices = [ + (-hx, -hy, -hz), + (hx, -hy, -hz), + (hx, hy, -hz), + (-hx, hy, -hz), + (-hx, -hy, hz), + (hx, -hy, hz), + (hx, hy, hz), + (-hx, hy, hz), + ]; + let triangles = [ + [0, 2, 1], + [0, 3, 2], + [4, 5, 6], + [4, 6, 7], + [0, 1, 5], + [0, 5, 4], + [3, 7, 6], + [3, 6, 2], + [0, 4, 7], + [0, 7, 3], + [1, 2, 6], + [1, 6, 5], + ]; + let mut text = String::from("solid box\n"); + for triangle in triangles { + text.push_str("facet normal 0 0 0\nouter loop\n"); + for index in triangle { + let (vx, vy, vz) = vertices[index]; + text.push_str(&format!("vertex {vx} {vy} {vz}\n")); + } + text.push_str("endloop\nendfacet\n"); + } + text.push_str("endsolid box\n"); + text +} + +#[test] +fn pose_identity_round_trips() { + let pose = Pose::default(); + let transform = pose.to_transform().unwrap(); + assert_eq!(transform, Transform::IDENTITY); + assert_eq!(Pose::from_transform(transform), pose); +} + +#[test] +fn pose_normalises_the_quaternion() { + let pose = Pose { + position: [1.0, 2.0, 3.0], + rotation: [2.0, 0.0, 0.0, 0.0], + }; + let transform = pose.to_transform().unwrap(); + assert_eq!(transform.position, Vec3::new(1.0, 2.0, 3.0)); + assert!((transform.rotation.norm_squared() - 1.0).abs() < 1e-12); + assert!((transform.rotation.w - 1.0).abs() < 1e-12); +} + +#[test] +fn pose_rejects_degenerate_values() { + let zero_rotation = Pose { + position: [0.0; 3], + rotation: [0.0; 4], + }; + assert!(zero_rotation.to_transform().is_none()); + + let non_finite = Pose { + position: [f64::NAN, 0.0, 0.0], + rotation: [1.0, 0.0, 0.0, 0.0], + }; + assert!(non_finite.to_transform().is_none()); +} + +#[test] +fn cube_mass_matches_the_density() { + let temp = TempDir::new("cube-mass"); + let mut store = temp.blobs(); + let side = 0.1; + let stl = box_stl(side, side, side); + let part = add_part_from_stl( + &mut store, + "cube", + stl.as_bytes(), + 1.0, + "steel", + Pose::default(), + ) + .unwrap(); + + let properties = part.mass(&MaterialDb::with_builtins(), &store).unwrap(); + let expected = 7_850.0 * side * side * side; + assert!((properties.mass.get() - expected).abs() / expected < 1e-5); + assert!(properties.center_of_mass.length() < 1e-12); + let diagonal = expected * side * side / 6.0; + assert!((properties.inertia.cols()[0].x - diagonal).abs() / diagonal < 1e-5); +} + +#[test] +fn pose_translation_moves_the_center_of_mass() { + let temp = TempDir::new("pose-mass"); + let mut store = temp.blobs(); + let stl = box_stl(0.1, 0.1, 0.1); + let pose = Pose { + position: [1.0, -2.0, 3.5], + rotation: [1.0, 0.0, 0.0, 0.0], + }; + let part = add_part_from_stl(&mut store, "cube", stl.as_bytes(), 1.0, "steel", pose).unwrap(); + + let properties = part.mass(&MaterialDb::with_builtins(), &store).unwrap(); + assert!((properties.center_of_mass.x - 1.0).abs() < 1e-12); + assert!((properties.center_of_mass.y + 2.0).abs() < 1e-12); + assert!((properties.center_of_mass.z - 3.5).abs() < 1e-12); +} + +#[test] +fn stored_meshes_are_content_addressed() { + let temp = TempDir::new("mesh-blob"); + let mut store = temp.blobs(); + let mesh = from_stl(box_stl(0.2, 0.3, 0.4).as_bytes()).unwrap(); + + let first = store_mesh(&mut store, &mesh).unwrap(); + let second = store_mesh(&mut store, &mesh).unwrap(); + assert_eq!(first, second); + let files = std::fs::read_dir(store.root()).unwrap().count(); + assert_eq!(files, 1); + assert_eq!(load_mesh(&store, first).unwrap(), mesh); +} + +#[test] +fn an_unknown_material_is_reported() { + let temp = TempDir::new("material"); + let mut store = temp.blobs(); + let stl = box_stl(0.1, 0.1, 0.1); + let part = add_part_from_stl( + &mut store, + "cube", + stl.as_bytes(), + 1.0, + "unobtainium", + Pose::default(), + ) + .unwrap(); + + let error = part.mass(&MaterialDb::new(), &store).unwrap_err(); + assert!(matches!(error, SceneError::UnknownMaterial(name) if name == "unobtainium")); +} + +#[test] +fn two_cubes_aggregate_by_the_parallel_axis_theorem() { + let temp = TempDir::new("aggregate"); + let mut store = temp.blobs(); + let side = 0.1; + let mass = 7_850.0 * side * side * side; + let stl = box_stl(side, side, side); + let offset = 0.2; + let mut design = Design::new("pair"); + for (name, x) in [("left", -offset), ("right", offset)] { + let pose = Pose { + position: [x, 0.0, 0.0], + rotation: [1.0, 0.0, 0.0, 0.0], + }; + design + .push(add_part_from_stl(&mut store, name, stl.as_bytes(), 1.0, "steel", pose).unwrap()); + } + + let properties = design + .mass_properties(&MaterialDb::with_builtins(), &store) + .unwrap(); + let expected_mass = 2.0 * mass; + assert!((properties.mass.get() - expected_mass).abs() / expected_mass < 1e-5); + assert!(properties.center_of_mass.length() < 1e-12); + let own = mass * side * side / 6.0; + let expected_yy = 2.0 * (own + mass * offset * offset); + assert!((properties.inertia.cols()[0].x - 2.0 * own).abs() / (2.0 * own) < 1e-5); + assert!((properties.inertia.cols()[1].y - expected_yy).abs() / expected_yy < 1e-5); +} diff --git a/crates/scene/tests/mesh_mass.rs b/crates/scene/tests/mesh_mass.rs new file mode 100644 index 0000000..9457d9e --- /dev/null +++ b/crates/scene/tests/mesh_mass.rs @@ -0,0 +1,87 @@ +//! M3 seam: an STL part is validated as a closed mesh and its mass is computed from +//! the material density. + +#![allow( + clippy::unwrap_used, + reason = "test helper: a failure should abort the test" +)] + +use fabrilis_core::units::KilogramsPerCubicMeter; +use fabrilis_materials::db::MaterialDb; +use fabrilis_materials::massprops::from_triangles; +use fabrilis_scene::import::{Mesh, from_stl}; + +/// A cube of the given side, centred at the origin, as an ASCII STL. +fn cube_stl(side: f64) -> String { + let h = side * 0.5; + let vertices = [ + (-h, -h, -h), + (h, -h, -h), + (h, h, -h), + (-h, h, -h), + (-h, -h, h), + (h, -h, h), + (h, h, h), + (-h, h, h), + ]; + let triangles = [ + [0, 2, 1], + [0, 3, 2], + [4, 5, 6], + [4, 6, 7], + [0, 1, 5], + [0, 5, 4], + [3, 7, 6], + [3, 6, 2], + [0, 4, 7], + [0, 7, 3], + [1, 2, 6], + [1, 6, 5], + ]; + let mut text = String::from("solid cube\n"); + for triangle in triangles { + text.push_str(" facet normal 0 0 0\n outer loop\n"); + for index in triangle { + let (x, y, z) = vertices[index]; + text.push_str(&format!(" vertex {x} {y} {z}\n")); + } + text.push_str(" endloop\n endfacet\n"); + } + text.push_str("endsolid cube\n"); + text +} + +#[test] +fn stl_cube_mass_matches_the_analytic_value() { + let mesh = from_stl(cube_stl(1.0).as_bytes()).expect("the cube parses"); + let report = mesh.validate().expect("the cube is closed"); + assert!((report.volume.get() - 1.0).abs() < 1e-12); + let steel = MaterialDb::with_builtins(); + let density = steel.get("steel").expect("steel is built in").density; + let mass = from_triangles(&mesh.triangles().collect::>(), density) + .expect("a closed cube has mass properties"); + assert!((mass.mass.get() - 7_850.0).abs() < 1.0); + assert!(mass.center_of_mass.length() < 1e-12); + let inertia = mass.mass.get() / 6.0; + assert!((mass.inertia.cols()[0].x - inertia).abs() < 1e-6); +} + +#[test] +fn millimetre_stl_scaled_to_metres_keeps_the_mass() { + let mesh = from_stl(cube_stl(1_000.0).as_bytes()) + .expect("the cube parses") + .scaled(0.001); + let report = mesh.validate().expect("the cube is closed"); + assert!((report.volume.get() - 1.0).abs() < 1e-9); + let density = KilogramsPerCubicMeter::new(2_700.0); + let mass = from_triangles(&mesh.triangles().collect::>(), density) + .expect("a closed cube has mass properties"); + assert!((mass.mass.get() - 2_700.0).abs() < 1.0); +} + +#[test] +fn an_open_mesh_is_rejected_before_mass_is_computed() { + let mut mesh: Mesh = from_stl(cube_stl(1.0).as_bytes()).expect("the cube parses"); + mesh.indices.pop(); + assert!(mesh.validate().is_err()); +} diff --git a/crates/scene/tests/persistence.rs b/crates/scene/tests/persistence.rs new file mode 100644 index 0000000..3cbf0fe --- /dev/null +++ b/crates/scene/tests/persistence.rs @@ -0,0 +1,229 @@ +//! M3 seam: an STL cart is saved, loaded back and its mass is compared with the +//! analytic value. + +#![allow( + clippy::unwrap_used, + reason = "a test aborts on failure, which is the intent" +)] + +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use fabrilis_materials::db::MaterialDb; +use fabrilis_scene::model::{DESIGN_FILE, Design, Pose, add_part_from_stl}; +use fabrilis_storage::project::Project; + +/// A directory removed on drop. +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(label: &str) -> Self { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let counter = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "fabrilis-persistence-{label}-{}-{counter}", + std::process::id() + )); + std::fs::create_dir_all(&path).unwrap(); + Self { path } + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +/// A box with the given full extents, centred at the origin, as an ASCII STL. +fn box_stl(x: f64, y: f64, z: f64) -> String { + let (hx, hy, hz) = (x * 0.5, y * 0.5, z * 0.5); + let vertices = [ + (-hx, -hy, -hz), + (hx, -hy, -hz), + (hx, hy, -hz), + (-hx, hy, -hz), + (-hx, -hy, hz), + (hx, -hy, hz), + (hx, hy, hz), + (-hx, hy, hz), + ]; + let triangles = [ + [0, 2, 1], + [0, 3, 2], + [4, 5, 6], + [4, 6, 7], + [0, 1, 5], + [0, 5, 4], + [3, 7, 6], + [3, 6, 2], + [0, 4, 7], + [0, 7, 3], + [1, 2, 6], + [1, 6, 5], + ]; + let mut text = String::from("solid box\n"); + for triangle in triangles { + text.push_str("facet normal 0 0 0\nouter loop\n"); + for index in triangle { + let (vx, vy, vz) = vertices[index]; + text.push_str(&format!("vertex {vx} {vy} {vz}\n")); + } + text.push_str("endloop\nendfacet\n"); + } + text.push_str("endsolid box\n"); + text +} + +fn pose_at(x: f64, y: f64, z: f64) -> Pose { + Pose { + position: [x, y, z], + rotation: [1.0, 0.0, 0.0, 0.0], + } +} + +#[test] +fn a_cart_round_trips_and_its_mass_matches_the_analytic_value() { + let temp = TempDir::new("cart"); + let project = Project::create(&temp.path).unwrap(); + let mut blobs = project.blobs(); + let mut design = Design::new("cart"); + + let body = box_stl(0.4, 0.2, 0.1); + design.push( + add_part_from_stl( + &mut blobs, + "body", + body.as_bytes(), + 1.0, + "steel", + pose_at(0.0, 0.0, 0.0), + ) + .unwrap(), + ); + let wheel = box_stl(0.1, 0.1, 0.1); + for (name, y) in [("left", 0.15), ("right", -0.15)] { + design.push( + add_part_from_stl( + &mut blobs, + name, + wheel.as_bytes(), + 1.0, + "aluminium", + pose_at(0.0, y, -0.05), + ) + .unwrap(), + ); + } + + design.save(&project).unwrap(); + let text = project.read_text(DESIGN_FILE).unwrap(); + assert!(text.contains("format_version: 1")); + assert!(text.contains("payload:")); + assert!(project.path(DESIGN_FILE).is_file()); + + let loaded = Design::load(&project).unwrap(); + assert_eq!(loaded.name, design.name); + assert_eq!(loaded.parts, design.parts); + + let materials = MaterialDb::with_builtins(); + let properties = loaded.mass_properties(&materials, &blobs).unwrap(); + let expected = 7_850.0 * 0.4 * 0.2 * 0.1 + 2.0 * 2_700.0 * 0.1 * 0.1 * 0.1; + let error = (properties.mass.get() - expected).abs() / expected; + assert!(error < 0.01, "mass error {error} exceeds 1 %"); + assert!(properties.center_of_mass.is_finite()); + assert!( + properties + .inertia + .cols() + .iter() + .all(|column| column.is_finite()) + ); + assert!(properties.inertia.determinant() > 0.0); +} + +#[test] +fn identical_meshes_share_one_blob_and_one_table_entry() { + let temp = TempDir::new("dedup"); + let project = Project::create(&temp.path).unwrap(); + let mut blobs = project.blobs(); + let wheel = box_stl(0.1, 0.1, 0.1); + + let first = add_part_from_stl( + &mut blobs, + "left", + wheel.as_bytes(), + 1.0, + "aluminium", + Pose::default(), + ) + .unwrap(); + let second = add_part_from_stl( + &mut blobs, + "right", + wheel.as_bytes(), + 1.0, + "aluminium", + Pose::default(), + ) + .unwrap(); + + assert_eq!(first.mesh, second.mesh); + let files = std::fs::read_dir(project.path("blobs")).unwrap().count(); + assert_eq!(files, 1); +} + +#[test] +fn a_version_zero_scene_is_migrated_to_identity_poses() { + let temp = TempDir::new("migrate"); + let project = Project::create(&temp.path).unwrap(); + let version_zero = "\ +( + format_version: 0, + payload: ( + name: \"cart\", + parts: [ + ( + name: \"body\", + mesh: \"0123456789abcdef\", + material: \"steel\", + ), + ], + ), +) +"; + project.write_text(DESIGN_FILE, version_zero).unwrap(); + + let design = Design::load(&project).unwrap(); + assert_eq!(design.parts.len(), 1); + assert_eq!(design.parts[0].pose, Pose::default()); + + design.save(&project).unwrap(); + let upgraded = project.read_text(DESIGN_FILE).unwrap(); + assert!(upgraded.contains("format_version: 1")); + assert_eq!(Design::load(&project).unwrap().parts, design.parts); +} + +#[test] +fn a_newer_scene_version_is_rejected() { + let temp = TempDir::new("future"); + let project = Project::create(&temp.path).unwrap(); + let version_two = "(format_version: 2, payload: (name: \"cart\", parts: []))"; + project.write_text(DESIGN_FILE, version_two).unwrap(); + + assert!(Design::load(&project).is_err()); +} + +#[test] +fn a_missing_scene_file_is_a_not_found_error() { + let temp = TempDir::new("missing"); + let project = Project::create(&temp.path).unwrap(); + let error = Design::load(&project).unwrap_err(); + let message = error.to_string(); + assert!( + message.contains("No such file") || message.contains("os error 2"), + "{message}" + ); +} diff --git a/crates/sensors/src/delay.rs b/crates/sensors/src/delay.rs new file mode 100644 index 0000000..5bb89c0 --- /dev/null +++ b/crates/sensors/src/delay.rs @@ -0,0 +1,35 @@ +//! A fixed-length FIFO that models the transport delay of a sensor bus. + +use std::collections::VecDeque; + +/// A FIFO of `steps` samples. +/// +/// The queue starts filled with `initial`, so the first `steps` calls to +/// [`Delay::push`] report that value while the queue drains. +#[derive(Debug, Clone, PartialEq)] +pub struct Delay { + initial: T, + queue: VecDeque, +} + +impl Delay { + /// A delay of `steps` samples, reporting `initial` until the queue fills. + pub fn new(steps: usize, initial: T) -> Self { + Self { + initial: initial.clone(), + queue: core::iter::repeat_n(initial, steps).collect(), + } + } + + /// Pushes a new sample and returns the one measured `steps` samples ago, or the + /// new sample itself when the delay is zero. + pub fn push(&mut self, value: T) -> T { + if self.queue.is_empty() { + return value; + } + self.queue.push_back(value); + self.queue + .pop_front() + .unwrap_or_else(|| self.initial.clone()) + } +} diff --git a/crates/sensors/src/encoder/mod.rs b/crates/sensors/src/encoder/mod.rs index 8bcad06..506086a 100644 --- a/crates/sensors/src/encoder/mod.rs +++ b/crates/sensors/src/encoder/mod.rs @@ -1 +1,139 @@ -//! fabrilis-sensors :: encoder - stub (see docs/ARCHITECTURE.md) +//! Quadrature encoder model: quantization, bias, noise and transport delay. +//! +//! A full revolution is split into `2^resolution_bits` counts. The sensor quantizes +//! the true angle, adds a constant bias and Gaussian noise, and reports the result +//! through a FIFO delay, so a controller sees the past, not the present. + +use fabrilis_core::math; +use fabrilis_core::rng::Rng; +use fabrilis_core::units::Radians; + +use crate::delay::Delay; +use crate::noise::Noise; + +/// One full revolution, rad. +const FULL_TURN: f64 = math::TAU; + +/// Smallest accepted `resolution_bits`; one bit still gives two counts per revolution. +const MIN_BITS: u8 = 1; + +/// Largest accepted `resolution_bits`; `2^31` counts per revolution fits `u32` and `i64`. +const MAX_BITS: u8 = 31; + +/// Encoder parameters. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct EncoderConfig { + /// Counts per revolution is `2^resolution_bits`; must be in `1..=31`. + pub resolution_bits: u8, + /// Standard deviation of the Gaussian noise, rad. + pub noise_sigma: f64, + /// Constant measurement offset, rad. + pub bias: f64, + /// Transport delay in samples. + pub delay_steps: usize, +} + +impl Default for EncoderConfig { + /// A 12-bit encoder without noise, bias or delay. + fn default() -> Self { + Self { + resolution_bits: 12, + noise_sigma: 0.0, + bias: 0.0, + delay_steps: 0, + } + } +} + +/// Why an [`Encoder`] could not be created. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EncoderError { + /// The bit count is outside `1..=31`, so the count grid is unusable. + ResolutionOutOfRange(u8), +} + +impl core::fmt::Display for EncoderError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::ResolutionOutOfRange(bits) => write!( + f, + "encoder resolution of {bits} bits is outside {MIN_BITS}..={MAX_BITS}" + ), + } + } +} + +impl std::error::Error for EncoderError {} + +/// An angle encoder with quantization, noise, bias and delay. +#[derive(Debug, Clone)] +pub struct Encoder { + resolution_bits: u8, + counts: u64, + noise: Noise, + bias: f64, + delay: Delay, + rng: Rng, +} + +impl Encoder { + /// Creates an encoder, or reports an unusable resolution. + pub fn new(config: EncoderConfig, seed: u64) -> Result { + let bits = config.resolution_bits; + if !(MIN_BITS..=MAX_BITS).contains(&bits) { + return Err(EncoderError::ResolutionOutOfRange(bits)); + } + Ok(Self { + resolution_bits: bits, + counts: 1u64 << bits, + noise: Noise::new(config.noise_sigma), + bias: config.bias, + delay: Delay::new(config.delay_steps, Radians::ZERO), + rng: Rng::new(seed), + }) + } + + /// Declared resolution in bits. + #[inline] + #[must_use] + pub fn resolution_bits(&self) -> u8 { + self.resolution_bits + } + + /// Counts per full revolution, `2^resolution_bits`. + #[inline] + #[must_use] + pub fn counts_per_revolution(&self) -> u64 { + self.counts + } + + /// Measures `true_angle`. + /// + /// The angle is quantized to the nearest count, ties round up (towards `+∞`), and + /// the count is wrapped modulo `2^resolution_bits`, so the quantized angle always + /// lies in `[0, TAU)`. Bias and noise are added after quantization, then the value + /// goes through the delay FIFO. Non-finite input is measured as `0` rad. + /// + /// Until the FIFO fills, the reported value is the initial `0` rad. + pub fn sample(&mut self, true_angle: Radians) -> Radians { + let quantized = self.quantize(true_angle); + let biased = quantized.get() + self.bias; + let measured = Radians(self.noise.apply(biased, &mut self.rng)); + self.delay.push(measured) + } + + fn quantize(&self, angle: Radians) -> Radians { + let counts = self.counts as f64; + let step = FULL_TURN / counts; + let scaled = angle.get() / step; + if !scaled.is_finite() { + return Radians::ZERO; + } + // Ties round up; `floor` and `rem_euclid` are exact IEEE operations. + let count = (scaled + 0.5).floor().rem_euclid(counts); + Radians(count * step) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/sensors/src/encoder/tests.rs b/crates/sensors/src/encoder/tests.rs new file mode 100644 index 0000000..51a0bd2 --- /dev/null +++ b/crates/sensors/src/encoder/tests.rs @@ -0,0 +1,176 @@ +use fabrilis_core::math; +use fabrilis_core::units::Radians; + +use super::*; + +/// Counts per revolution for the small test encoder. +const COUNTS: f64 = 1024.0; + +/// One count of the test encoder, rad. +const STEP: f64 = math::TAU / COUNTS; + +fn quiet() -> EncoderConfig { + EncoderConfig { + resolution_bits: 10, + noise_sigma: 0.0, + bias: 0.0, + delay_steps: 0, + } +} + +fn build(config: EncoderConfig) -> Encoder { + Encoder::new(config, 42).expect("test resolution is valid") +} + +/// An angle that sits exactly on the count grid. +fn grid(count: f64) -> Radians { + Radians::new(count * STEP) +} + +#[test] +fn rejects_an_unusable_resolution() { + let zero = Encoder::new( + EncoderConfig { + resolution_bits: 0, + ..quiet() + }, + 1, + ); + assert_eq!(zero.err(), Some(EncoderError::ResolutionOutOfRange(0))); + let wide = Encoder::new( + EncoderConfig { + resolution_bits: 32, + ..quiet() + }, + 1, + ); + assert_eq!(wide.err(), Some(EncoderError::ResolutionOutOfRange(32))); + for bits in [1, 12, 31] { + let encoder = Encoder::new( + EncoderConfig { + resolution_bits: bits, + ..quiet() + }, + 1, + ); + assert!(encoder.is_ok(), "bits {bits}"); + } + assert_eq!(build(quiet()).counts_per_revolution(), 1024); + assert_eq!(build(quiet()).resolution_bits(), 10); +} + +#[test] +fn a_quiet_encoder_passes_grid_angles_through_bitwise() { + let mut encoder = build(quiet()); + for count in [0.0, 1.0, 3.0, 512.0, 1023.0] { + let angle = grid(count); + assert_eq!( + encoder.sample(angle).get().to_bits(), + angle.get().to_bits(), + "count {count}" + ); + } +} + +#[test] +fn quantization_snaps_to_the_nearest_count() { + let mut encoder = build(quiet()); + let cases = [ + (3.4, 3.0), + (3.49, 3.0), + (3.5, 4.0), + (3.6, 4.0), + (-0.4, 0.0), + (-0.5, 0.0), + (-0.6, 1023.0), + ]; + for (input, expected) in cases { + let measured = encoder.sample(Radians::new(input * STEP)); + assert_eq!( + measured.get().to_bits(), + grid(expected).get().to_bits(), + "input {input} count" + ); + } +} + +#[test] +fn a_full_turn_wraps_to_zero() { + let mut encoder = build(quiet()); + let measured = encoder.sample(Radians::new(math::TAU)); + assert_eq!(measured.get().to_bits(), 0.0_f64.to_bits()); +} + +#[test] +fn a_non_finite_angle_is_measured_as_zero() { + let mut encoder = build(quiet()); + assert_eq!( + encoder.sample(Radians::new(f64::INFINITY)).get().to_bits(), + 0.0_f64.to_bits() + ); + assert_eq!( + encoder.sample(Radians::new(f64::NAN)).get().to_bits(), + 0.0_f64.to_bits() + ); +} + +#[test] +fn bias_shifts_the_quantized_angle() { + let mut encoder = build(EncoderConfig { + bias: STEP, + ..quiet() + }); + assert_eq!( + encoder.sample(Radians::ZERO).get().to_bits(), + STEP.to_bits() + ); +} + +#[test] +fn delay_reports_the_sample_from_n_steps_ago() { + let mut encoder = build(EncoderConfig { + delay_steps: 3, + ..quiet() + }); + let mut measured = Vec::new(); + for count in [10.0, 20.0, 30.0, 40.0, 50.0] { + measured.push(encoder.sample(grid(count))); + } + let expected = [grid(0.0), grid(0.0), grid(0.0), grid(10.0), grid(20.0)]; + for (value, want) in measured.iter().zip(expected) { + assert_eq!(value.get().to_bits(), want.get().to_bits()); + } +} + +#[test] +fn the_same_seed_repeats_and_different_seeds_differ() { + let noisy = EncoderConfig { + noise_sigma: 0.01, + delay_steps: 2, + ..quiet() + }; + let mut a = Encoder::new(noisy, 7).expect("test resolution is valid"); + let mut b = Encoder::new(noisy, 7).expect("test resolution is valid"); + let mut c = Encoder::new(noisy, 8).expect("test resolution is valid"); + let mut differs = false; + for step in 0..50 { + let angle = grid(f64::from(step) * 7.0); + let (first, repeated, other) = (a.sample(angle), b.sample(angle), c.sample(angle)); + assert_eq!(first.get().to_bits(), repeated.get().to_bits()); + differs |= first.get().to_bits() != other.get().to_bits(); + } + assert!(differs); +} + +#[test] +fn noise_stays_finite_over_many_samples() { + let mut encoder = build(EncoderConfig { + noise_sigma: 10.0, + delay_steps: 4, + ..quiet() + }); + for step in 0..10_000 { + let measured = encoder.sample(Radians::new(f64::from(step) * 1e-3)); + assert!(measured.get().is_finite(), "step {step}"); + } +} diff --git a/crates/sensors/src/imu/mod.rs b/crates/sensors/src/imu/mod.rs index 45b779c..c482d6a 100644 --- a/crates/sensors/src/imu/mod.rs +++ b/crates/sensors/src/imu/mod.rs @@ -1 +1,137 @@ -//! fabrilis-sensors :: imu - stub (see docs/ARCHITECTURE.md) +//! Inertial measurement unit: a gyro and an accelerometer with noise, bias and delay. +//! +//! The model is deliberately minimal: no magnetometer and no sensor fusion, so the +//! caller supplies the true orientation and receives a perturbed measurement of it. +//! Noise applies to every output component, bias to the measured vectors, and the +//! whole sample goes through a FIFO. + +use fabrilis_core::rng::Rng; +use fabrilis_core::units::RadiansPerSecond; +use fabrilis_core::vec::{Quat, Vec3}; + +use crate::delay::Delay; +use crate::noise::Noise; + +/// IMU parameters. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ImuConfig { + /// Standard deviation of the Gaussian noise, applied to every output component. + /// + /// Orientation components are dimensionless, angular velocity is in rad/s and + /// acceleration in m/s², so one sigma serves all three at modest accuracy. + pub noise_sigma: f64, + /// Constant additive offset of angular velocity and acceleration, per component. + /// + /// Orientation carries no bias: a constant quaternion offset is not a rotation. + pub bias: f64, + /// Transport delay in samples. + pub delay_steps: usize, +} + +impl Default for ImuConfig { + /// An IMU without noise, bias or delay. + fn default() -> Self { + Self { + noise_sigma: 0.0, + bias: 0.0, + delay_steps: 0, + } + } +} + +/// One IMU measurement, expressed in the body frame. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ImuSample { + /// Measured orientation of the body in the world frame. + pub orientation: Quat, + /// Measured angular velocity, rad/s. + pub angular_velocity: Vec3, + /// Measured proper acceleration, m/s². + pub acceleration: Vec3, +} + +impl ImuSample { + /// The value reported until the delay FIFO fills. + pub const AT_REST: Self = Self { + orientation: Quat::IDENTITY, + angular_velocity: Vec3::ZERO, + acceleration: Vec3::ZERO, + }; +} + +/// A gyro and an accelerometer with noise, bias and delay. +#[derive(Debug, Clone)] +pub struct Imu { + noise: Noise, + bias: f64, + delay: Delay, + rng: Rng, +} + +impl Imu { + /// Creates an IMU; every configuration is valid. + #[must_use] + pub fn new(config: ImuConfig, seed: u64) -> Self { + Self { + noise: Noise::new(config.noise_sigma), + bias: config.bias, + delay: Delay::new(config.delay_steps, ImuSample::AT_REST), + rng: Rng::new(seed), + } + } + + /// Measures one instant of the true state. + /// + /// The gyro models a single body axis: the scalar `angular_velocity` is the rate + /// about body Z, and X and Y measure only noise and bias. Orientation components + /// are perturbed independently and renormalized, but only when noise is enabled, + /// so a noise-free IMU reproduces the input bit for bit. + /// + /// Until the FIFO fills, the reported sample is [`ImuSample::AT_REST`]. + pub fn sample( + &mut self, + true_orientation: Quat, + angular_velocity: RadiansPerSecond, + acceleration: Vec3, + ) -> ImuSample { + let noise = self.noise; + let bias = self.bias; + let rng = &mut self.rng; + let orientation = measured_orientation(true_orientation, noise, rng); + let rate = Vec3::new(0.0, 0.0, angular_velocity.get()); + let measured = ImuSample { + orientation, + angular_velocity: measured_vec3(rate, noise, bias, rng), + acceleration: measured_vec3(acceleration, noise, bias, rng), + }; + self.delay.push(measured) + } +} + +fn measured_orientation(true_orientation: Quat, noise: Noise, rng: &mut Rng) -> Quat { + if noise.is_zero() { + return true_orientation; + } + let q = Quat::new( + true_orientation.w + noise.sample(rng), + true_orientation.x + noise.sample(rng), + true_orientation.y + noise.sample(rng), + true_orientation.z + noise.sample(rng), + ); + q.normalize().unwrap_or(true_orientation) +} + +fn measured_vec3(true_value: Vec3, noise: Noise, bias: f64, rng: &mut Rng) -> Vec3 { + Vec3::new( + measured_component(true_value.x, noise, bias, rng), + measured_component(true_value.y, noise, bias, rng), + measured_component(true_value.z, noise, bias, rng), + ) +} + +fn measured_component(true_value: f64, noise: Noise, bias: f64, rng: &mut Rng) -> f64 { + bias + noise.apply(true_value, rng) +} + +#[cfg(test)] +mod tests; diff --git a/crates/sensors/src/imu/tests.rs b/crates/sensors/src/imu/tests.rs new file mode 100644 index 0000000..7d64231 --- /dev/null +++ b/crates/sensors/src/imu/tests.rs @@ -0,0 +1,139 @@ +use fabrilis_core::units::RadiansPerSecond; +use fabrilis_core::vec::{Quat, Vec3}; + +use super::*; + +fn quiet() -> ImuConfig { + ImuConfig { + noise_sigma: 0.0, + bias: 0.0, + delay_steps: 0, + } +} + +fn truth() -> (Quat, RadiansPerSecond, Vec3) { + ( + Quat::IDENTITY, + RadiansPerSecond::new(0.75), + Vec3::new(1.5, -2.25, 9.81), + ) +} + +#[test] +fn a_quiet_imu_reproduces_the_true_state_bitwise() { + let mut imu = Imu::new(quiet(), 21); + let (orientation, rate, acceleration) = truth(); + let sample = imu.sample(orientation, rate, acceleration); + assert_eq!(sample.orientation, orientation); + assert_eq!(sample.angular_velocity.x, 0.0); + assert_eq!(sample.angular_velocity.y, 0.0); + assert_eq!(sample.angular_velocity.z.to_bits(), rate.get().to_bits()); + assert_eq!(sample.acceleration.x.to_bits(), acceleration.x.to_bits()); + assert_eq!(sample.acceleration.y.to_bits(), acceleration.y.to_bits()); + assert_eq!(sample.acceleration.z.to_bits(), acceleration.z.to_bits()); +} + +#[test] +fn delay_reports_the_rest_sample_until_the_queue_fills() { + let mut imu = Imu::new( + ImuConfig { + delay_steps: 2, + ..quiet() + }, + 3, + ); + let (orientation, rate, acceleration) = truth(); + assert_eq!( + imu.sample(orientation, rate, acceleration), + ImuSample::AT_REST + ); + assert_eq!( + imu.sample(orientation, rate, acceleration), + ImuSample::AT_REST + ); + let delayed = imu.sample(orientation, rate, acceleration); + assert_eq!(delayed.orientation, orientation); + assert_eq!(delayed.angular_velocity.z.to_bits(), rate.get().to_bits()); + assert_eq!(delayed.acceleration.z.to_bits(), acceleration.z.to_bits()); +} + +#[test] +fn bias_offsets_angular_velocity_and_acceleration() { + let mut imu = Imu::new( + ImuConfig { + bias: 0.5, + ..quiet() + }, + 4, + ); + let (orientation, rate, acceleration) = truth(); + let sample = imu.sample(orientation, rate, acceleration); + assert_eq!(sample.angular_velocity.x, 0.5); + assert_eq!( + sample.angular_velocity.z.to_bits(), + (0.5 + rate.get()).to_bits() + ); + assert_eq!( + sample.acceleration.x.to_bits(), + (0.5 + acceleration.x).to_bits() + ); + assert_eq!(sample.orientation, orientation); +} + +#[test] +fn a_non_zero_rate_lands_on_the_z_axis_only() { + let mut imu = Imu::new(quiet(), 5); + let (_, rate, acceleration) = truth(); + let sample = imu.sample(Quat::IDENTITY, rate, acceleration); + assert_eq!(sample.angular_velocity, Vec3::new(0.0, 0.0, rate.get())); +} + +#[test] +fn the_same_seed_repeats_and_different_seeds_differ() { + let noisy = ImuConfig { + noise_sigma: 0.01, + bias: 0.001, + delay_steps: 1, + }; + let mut a = Imu::new(noisy, 6); + let mut b = Imu::new(noisy, 6); + let mut c = Imu::new(noisy, 7); + let (orientation, rate, acceleration) = truth(); + let mut differs = false; + for _ in 0..50 { + let first = a.sample(orientation, rate, acceleration); + let repeated = b.sample(orientation, rate, acceleration); + let other = c.sample(orientation, rate, acceleration); + assert_eq!( + first.acceleration.z.to_bits(), + repeated.acceleration.z.to_bits() + ); + assert_eq!( + first.orientation.w.to_bits(), + repeated.orientation.w.to_bits() + ); + differs |= first.acceleration.z.to_bits() != other.acceleration.z.to_bits(); + } + assert!(differs); +} + +#[test] +fn noise_stays_finite_and_the_orientation_stays_normalized() { + let mut imu = Imu::new( + ImuConfig { + noise_sigma: 0.05, + bias: 0.1, + delay_steps: 3, + }, + 8, + ); + let (orientation, rate, acceleration) = truth(); + for step in 0..10_000 { + let sample = imu.sample(orientation, rate, acceleration); + let norm = sample.orientation.norm_squared(); + assert!((norm - 1.0).abs() < 1e-12, "step {step}: norm {norm}"); + assert!(sample.orientation.w.is_finite(), "step {step}"); + assert!(sample.angular_velocity.is_finite(), "step {step}"); + assert!(sample.acceleration.is_finite(), "step {step}"); + } +} diff --git a/crates/sensors/src/lib.rs b/crates/sensors/src/lib.rs index 8862326..f26f9c0 100644 --- a/crates/sensors/src/lib.rs +++ b/crates/sensors/src/lib.rs @@ -1,4 +1,5 @@ //! IMU, encoders, current sensors: noise, bias, delay, sampling +mod delay; pub mod encoder; pub mod imu; pub mod noise; diff --git a/crates/sensors/src/noise/mod.rs b/crates/sensors/src/noise/mod.rs index 653ae21..08532e6 100644 --- a/crates/sensors/src/noise/mod.rs +++ b/crates/sensors/src/noise/mod.rs @@ -1 +1,69 @@ -//! fabrilis-sensors :: noise - stub (see docs/ARCHITECTURE.md) +//! Additive white Gaussian noise for sensor models. +//! +//! Sampling uses the Box-Muller transform over the seeded [`Rng`], so a sequence is +//! identical on every platform (docs/DETERMINISM.md). A zero sigma returns exactly +//! `0.0` and does not touch the generator, which lets a noise-free sensor reproduce +//! its input bit for bit. + +use fabrilis_core::math; +use fabrilis_core::rng::Rng; + +/// Gaussian noise with standard deviation `sigma`, in the units of the measured value. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Noise { + sigma: f64, +} + +impl Noise { + /// Creates a noise source with standard deviation `sigma`. + /// + /// A negative, zero or non-finite `sigma` disables the noise; the sign of `sigma` + /// carries no meaning here. + #[inline] + #[must_use] + pub fn new(sigma: f64) -> Self { + let sigma = if sigma.is_finite() && sigma > 0.0 { + sigma + } else { + 0.0 + }; + Self { sigma } + } + + /// The standard deviation in the units of the measured value. + #[inline] + #[must_use] + pub fn sigma(self) -> f64 { + self.sigma + } + + /// True when this source adds nothing and leaves the generator untouched. + #[inline] + #[must_use] + pub fn is_zero(self) -> bool { + self.sigma == 0.0 + } + + /// One sample from a normal distribution with mean `0.0` and standard deviation + /// `sigma`. + /// + /// A zero sigma returns exactly `0.0` and does not advance `rng`. + pub fn sample(self, rng: &mut Rng) -> f64 { + if self.sigma == 0.0 { + return 0.0; + } + // `u1` lies in `(0, 1]`, so the logarithm stays finite, and `u2` in `[0, 1)`. + let u1 = 1.0 - rng.next_f64(); + let u2 = rng.next_f64(); + let radius = math::sqrt(-2.0 * math::ln(u1)); + self.sigma * radius * math::cos(math::TAU * u2) + } + + /// `value` with one noise sample added. + pub fn apply(self, value: f64, rng: &mut Rng) -> f64 { + value + self.sample(rng) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/sensors/src/noise/tests.rs b/crates/sensors/src/noise/tests.rs new file mode 100644 index 0000000..e5c28c4 --- /dev/null +++ b/crates/sensors/src/noise/tests.rs @@ -0,0 +1,74 @@ +use fabrilis_core::rng::Rng; + +use super::*; + +#[test] +fn zero_sigma_returns_zero_and_keeps_the_generator_untouched() { + let mut rng = Rng::new(5); + assert_eq!(Noise::new(0.0).sample(&mut rng), 0.0); + let mut reference = Rng::new(5); + assert_eq!(rng.next_u64(), reference.next_u64()); +} + +#[test] +fn zero_sigma_passes_the_value_through_bitwise() { + let mut rng = Rng::new(6); + let value = -1.234_567_890_123e-7; + let measured = Noise::new(0.0).apply(value, &mut rng); + assert_eq!(measured.to_bits(), value.to_bits()); +} + +#[test] +fn negative_and_non_finite_sigma_disable_the_noise() { + assert_eq!(Noise::new(-1.0).sigma(), 0.0); + assert_eq!(Noise::new(f64::NAN).sigma(), 0.0); + assert_eq!(Noise::new(f64::INFINITY).sigma(), 0.0); + assert!(Noise::new(-1.0).is_zero()); + assert_eq!(Noise::new(0.5).sigma(), 0.5); +} + +#[test] +fn samples_are_finite_and_match_the_sigma() { + let sigma = 0.25; + let noise = Noise::new(sigma); + let mut rng = Rng::new(17); + let count = 100_000_u32; + let mut sum = 0.0; + let mut sum_squared = 0.0; + for _ in 0..count { + let value = noise.sample(&mut rng); + assert!(value.is_finite(), "{value}"); + sum += value; + sum_squared += value * value; + } + let n = f64::from(count); + let mean = sum / n; + let variance = sum_squared / n - mean * mean; + assert!(mean.abs() < 0.01, "mean {mean}"); + assert!( + (variance - sigma * sigma).abs() < 0.005, + "variance {variance}" + ); +} + +#[test] +fn the_same_seed_repeats_the_sequence() { + let noise = Noise::new(0.5); + let mut a = Rng::new(3); + let mut b = Rng::new(3); + for _ in 0..100 { + assert_eq!( + noise.sample(&mut a).to_bits(), + noise.sample(&mut b).to_bits() + ); + } +} + +#[test] +fn different_seeds_differ() { + let noise = Noise::new(1.0); + let mut a = Rng::new(1); + let mut b = Rng::new(2); + let differs = (0..8).any(|_| noise.sample(&mut a).to_bits() != noise.sample(&mut b).to_bits()); + assert!(differs); +} diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml index 0e101f6..b8279e5 100644 --- a/crates/storage/Cargo.toml +++ b/crates/storage/Cargo.toml @@ -11,6 +11,8 @@ workspace = true [dependencies] fabrilis-core = { path = "../core" } +serde = { version = "1", features = ["derive"] } +ron = "0.12" [build-dependencies] fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/storage/src/blob/mod.rs b/crates/storage/src/blob/mod.rs index 474ebe2..ffbcbcd 100644 --- a/crates/storage/src/blob/mod.rs +++ b/crates/storage/src/blob/mod.rs @@ -1 +1,143 @@ -//! fabrilis-storage :: blob - stub (see docs/ARCHITECTURE.md) +//! Content-addressed blob storage. +//! +//! A blob is named by an FNV-1a 64-bit hash of its bytes, so equal contents are +//! stored once and a file can be checked against its name (docs/STORAGE.md). The +//! hash detects accidental corruption and deduplicates saves; it is not a +//! cryptographic digest and does not resist a deliberate collision. + +use core::fmt; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use serde::de::Error as DeError; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +/// FNV-1a 64-bit offset basis. +const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; +/// FNV-1a 64-bit prime. +const PRIME: u64 = 0x0000_0100_0000_01b3; +/// Hex digits in a serialised hash. +const HEX_DIGITS: usize = 16; + +/// Distinguishes temporary files written by concurrent saves in one process. +static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0); + +/// The content hash of a blob. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct BlobHash(u64); + +impl BlobHash { + /// Hashes the bytes with FNV-1a 64. + #[must_use] + pub fn hash(bytes: &[u8]) -> Self { + let mut value = OFFSET_BASIS; + for &byte in bytes { + value ^= u64::from(byte); + value = value.wrapping_mul(PRIME); + } + Self(value) + } + + /// The hash as 16 lowercase hex digits, the blob's file name. + #[must_use] + pub fn to_hex(self) -> String { + format!("{:016x}", self.0) + } + + /// Parses 16 hex digits, uppercase or lowercase. + #[must_use] + pub fn from_hex(text: &str) -> Option { + if text.len() != HEX_DIGITS || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return None; + } + u64::from_str_radix(text, 16).ok().map(Self) + } +} + +impl fmt::Display for BlobHash { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{:016x}", self.0) + } +} + +impl Serialize for BlobHash { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.to_hex()) + } +} + +impl<'de> Deserialize<'de> for BlobHash { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Self::from_hex(&text).ok_or_else(|| DeError::custom("blob hash must be 16 hex digits")) + } +} + +/// A directory of blobs named by their content hash. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BlobStore { + root: PathBuf, +} + +impl BlobStore { + /// Uses `root` as the directory that holds the blob files. + #[must_use] + pub fn new(root: impl Into) -> Self { + Self { root: root.into() } + } + + /// The directory holding the blobs. + #[must_use] + pub fn root(&self) -> &Path { + &self.root + } + + /// Writes `bytes` unless the same contents are already stored. + /// + /// The file is written under a temporary name and renamed into place, so a + /// reader never sees a partial blob even if the process stops mid-write. + pub fn put(&self, bytes: &[u8]) -> io::Result { + let hash = BlobHash::hash(bytes); + let path = self.path(hash); + if path.is_file() { + return Ok(hash); + } + fs::create_dir_all(&self.root)?; + let temp = temp_path(&self.root); + fs::write(&temp, bytes)?; + if let Err(error) = fs::rename(&temp, &path) { + let _ = fs::remove_file(&temp); + return Err(error); + } + Ok(hash) + } + + /// Reads the blob back; a missing file is an [`io::ErrorKind::NotFound`]. + pub fn get(&self, hash: BlobHash) -> io::Result> { + fs::read(self.path(hash)) + } + + /// The file that holds `hash`, whether or not it exists yet. + #[must_use] + pub fn path(&self, hash: BlobHash) -> PathBuf { + self.root.join(hash.to_hex()) + } + + /// True when the blob is stored. + #[must_use] + pub fn contains(&self, hash: BlobHash) -> bool { + self.path(hash).is_file() + } +} + +/// A temporary file name that cannot collide with a hash file. +fn temp_path(root: &Path) -> PathBuf { + let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed); + let pid = std::process::id(); + root.join(format!(".{pid}-{counter}.blob-tmp")) +} + +#[cfg(test)] +mod tests; diff --git a/crates/storage/src/blob/tests.rs b/crates/storage/src/blob/tests.rs new file mode 100644 index 0000000..bbf5e9f --- /dev/null +++ b/crates/storage/src/blob/tests.rs @@ -0,0 +1,99 @@ +//! Blob hashing, hex round trips and content-addressed storage. + +#![allow( + clippy::unwrap_used, + reason = "a test aborts on failure, which is the intent" +)] + +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::{BlobHash, BlobStore}; + +/// A directory removed on drop. +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(label: &str) -> Self { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let counter = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "fabrilis-blob-{label}-{}-{counter}", + std::process::id() + )); + std::fs::create_dir_all(&path).unwrap(); + Self { path } + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +#[test] +fn fnv1a_matches_the_reference_vectors() { + assert_eq!(BlobHash::hash(b"").to_hex(), "cbf29ce484222325"); + assert_eq!(BlobHash::hash(b"a").to_hex(), "af63dc4c8601ec8c"); + assert_eq!(BlobHash::hash(b"foobar").to_hex(), "85944171f73967e8"); +} + +#[test] +fn hex_round_trips_and_rejects_bad_input() { + let hash = BlobHash::hash(b"payload"); + let hex = hash.to_hex(); + assert_eq!(hex.len(), 16); + assert_eq!(BlobHash::from_hex(&hex), Some(hash)); + assert_eq!(BlobHash::from_hex(&hex.to_uppercase()), Some(hash)); + assert_eq!(BlobHash::from_hex(""), None); + assert_eq!(BlobHash::from_hex("xyz"), None); + assert_eq!(BlobHash::from_hex("0123456789abcde"), None); + assert_eq!(BlobHash::from_hex("0123456789abcdeg"), None); +} + +#[test] +fn serde_uses_the_hex_string_form() { + let hash = BlobHash::hash(b"scene"); + let text = ron::to_string(&hash).unwrap(); + assert_eq!(text, format!("\"{}\"", hash.to_hex())); + assert_eq!(ron::from_str::(&text).unwrap(), hash); + assert!(ron::from_str::("\"not-a-hash\"").is_err()); +} + +#[test] +fn put_get_and_contains_round_trip() { + let temp = TempDir::new("round-trip"); + let store = BlobStore::new(&temp.path); + let hash = store.put(b"hello blob").unwrap(); + + assert!(store.contains(hash)); + assert_eq!(store.get(hash).unwrap(), b"hello blob"); + assert_eq!(store.path(hash), temp.path.join(hash.to_hex())); + assert!(store.path(hash).is_file()); +} + +#[test] +fn storing_the_same_bytes_twice_keeps_one_file() { + let temp = TempDir::new("dedup"); + let store = BlobStore::new(&temp.path); + let first = store.put(b"same").unwrap(); + let second = store.put(b"same").unwrap(); + + assert_eq!(first, second); + let files = std::fs::read_dir(&temp.path).unwrap().count(); + assert_eq!(files, 1); +} + +#[test] +fn a_missing_blob_is_not_found() { + let temp = TempDir::new("missing"); + let store = BlobStore::new(&temp.path); + let hash = BlobHash::hash(b"never stored"); + + assert!(!store.contains(hash)); + let error = store.get(hash).unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::NotFound); +} diff --git a/crates/storage/src/format/mod.rs b/crates/storage/src/format/mod.rs index 2f8480a..3c935db 100644 --- a/crates/storage/src/format/mod.rs +++ b/crates/storage/src/format/mod.rs @@ -1 +1,123 @@ -//! fabrilis-storage :: format - stub (see docs/ARCHITECTURE.md) +//! Versioned RON files. +//! +//! Every saved file is an [`Envelope`] with a `format_version` field, so a newer +//! build can reject data it does not understand and an older one can migrate it +//! forward through the chain in [`crate::migrate`]. + +use core::fmt; +use std::collections::BTreeMap; + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +use crate::migrate::{self, MigrateError, Migration}; + +/// The format version written by this build. +pub const CURRENT_VERSION: u32 = 1; + +/// A payload with the version of the schema it follows. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Envelope { + /// Schema version of `payload`. + pub format_version: u32, + /// The document itself. + pub payload: T, +} + +/// Serialises `payload` as a pretty RON envelope at [`CURRENT_VERSION`]. +pub fn to_ron(payload: &T) -> Result { + let envelope = Envelope { + format_version: CURRENT_VERSION, + payload, + }; + ron::ser::to_string_pretty(&envelope, ron::ser::PrettyConfig::default()) + .map_err(|error| FormatError::Encode(error.to_string())) +} + +/// Reads an envelope written at [`CURRENT_VERSION`]. +/// +/// Older documents are rejected because no migration steps are known here; use +/// [`from_ron_with_migrations`] to supply them. +pub fn from_ron(text: &str) -> Result { + from_ron_with_migrations(text, &BTreeMap::new()) +} + +/// Reads an envelope, migrates an older payload forward, then decodes it. +/// +/// A version newer than [`CURRENT_VERSION`] is always rejected: a newer file may +/// contain fields this build would silently drop. +pub fn from_ron_with_migrations( + text: &str, + steps: &BTreeMap, +) -> Result { + let envelope: Envelope = + ron::from_str(text).map_err(|error| FormatError::Parse(error.to_string()))?; + if envelope.format_version > CURRENT_VERSION { + return Err(FormatError::TooNew { + found: envelope.format_version, + current: CURRENT_VERSION, + }); + } + let payload = migrate::migrate_value( + envelope.payload, + envelope.format_version, + CURRENT_VERSION, + steps, + )?; + payload + .into_rust() + .map_err(|error| FormatError::Decode(error.to_string())) +} + +/// Why a file could not be read or written. +#[derive(Debug)] +pub enum FormatError { + /// The text is not a RON envelope. + Parse(String), + /// The payload could not be serialised. + Encode(String), + /// The payload does not match the requested type after migration. + Decode(String), + /// The file was written by a newer build. + TooNew { + /// Version found in the file. + found: u32, + /// Version this build understands. + current: u32, + }, + /// A migration step failed. + Migration(MigrateError), +} + +impl From for FormatError { + fn from(error: MigrateError) -> Self { + Self::Migration(error) + } +} + +impl fmt::Display for FormatError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Parse(reason) => write!(formatter, "cannot parse the RON envelope: {reason}"), + Self::Encode(reason) => write!(formatter, "cannot encode the RON payload: {reason}"), + Self::Decode(reason) => write!(formatter, "cannot decode the RON payload: {reason}"), + Self::TooNew { found, current } => write!( + formatter, + "format version {found} is newer than the supported version {current}" + ), + Self::Migration(error) => write!(formatter, "migration failed: {error}"), + } + } +} + +impl std::error::Error for FormatError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Migration(error) => Some(error), + _ => None, + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/storage/src/format/tests.rs b/crates/storage/src/format/tests.rs new file mode 100644 index 0000000..e71bf2a --- /dev/null +++ b/crates/storage/src/format/tests.rs @@ -0,0 +1,90 @@ +//! Envelope versioning and guarded decoding. + +#![allow( + clippy::unwrap_used, + reason = "a test aborts on failure, which is the intent" +)] + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use super::{CURRENT_VERSION, FormatError, from_ron, from_ron_with_migrations, to_ron}; +use crate::migrate::{MigrateError, Migration}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +struct Document { + answer: f64, +} + +/// A step from version 0 to version 1: add one to `answer`. +fn add_one(mut value: ron::Value) -> Result { + let ron::Value::Map(ref mut document) = value else { + return Err(MigrateError::step(0, "document is not a map")); + }; + let Some(answer) = document.get_mut(&ron::Value::from("answer")) else { + return Err(MigrateError::step(0, "document has no answer")); + }; + let ron::Value::Number(number) = answer else { + return Err(MigrateError::step(0, "answer is not a number")); + }; + let incremented = (*number).into_f64() + 1.0; + *answer = ron::Value::from(incremented); + Ok(value) +} + +fn steps() -> BTreeMap { + let mut steps = BTreeMap::new(); + let _previous = steps.insert(0, add_one as Migration); + steps +} + +#[test] +fn a_payload_round_trips_at_the_current_version() { + let text = to_ron(&Document { answer: 42.0 }).unwrap(); + assert!(text.contains("format_version: 1")); + assert!(text.contains("payload:")); + + let document: Document = from_ron(&text).unwrap(); + assert_eq!(document, Document { answer: 42.0 }); +} + +#[test] +fn a_newer_version_is_rejected() { + let text = format!( + "(format_version: {}, payload: (answer: 1.0))", + CURRENT_VERSION + 1 + ); + let error = from_ron::(&text).unwrap_err(); + assert!(matches!(error, FormatError::TooNew { .. })); +} + +#[test] +fn an_older_version_needs_a_registered_step() { + let text = "(format_version: 0, payload: (answer: 41.0))"; + let error = from_ron::(text).unwrap_err(); + assert!(matches!( + error, + FormatError::Migration(MigrateError::MissingStep { version: 0, .. }) + )); +} + +#[test] +fn an_older_version_is_migrated_before_decoding() { + let text = "(format_version: 0, payload: (answer: 41.0))"; + let document: Document = from_ron_with_migrations(text, &steps()).unwrap(); + assert_eq!(document, Document { answer: 42.0 }); +} + +#[test] +fn a_payload_of_the_wrong_shape_is_a_decode_error() { + let text = "(format_version: 1, payload: 7.0)"; + let error = from_ron::(text).unwrap_err(); + assert!(matches!(error, FormatError::Decode(_))); +} + +#[test] +fn malformed_text_is_a_parse_error() { + let error = from_ron::("this is not RON").unwrap_err(); + assert!(matches!(error, FormatError::Parse(_))); +} diff --git a/crates/storage/src/migrate/mod.rs b/crates/storage/src/migrate/mod.rs index 5774e27..1f3eb54 100644 --- a/crates/storage/src/migrate/mod.rs +++ b/crates/storage/src/migrate/mod.rs @@ -1 +1,101 @@ -//! fabrilis-storage :: migrate - stub (see docs/ARCHITECTURE.md) +//! Forward-only schema migrations over RON values. +//! +//! A migration upgrades the payload of one format version to the next. Steps are +//! kept in a [`BTreeMap`] so the chain is explicit and missing links are reported +//! instead of silently skipped (docs/STORAGE.md). + +use core::fmt; +use std::collections::BTreeMap; + +/// A step from version `version` to `version + 1` over the payload. +pub type Migration = fn(ron::Value) -> Result; + +/// Why a migration chain could not be applied. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MigrateError { + /// The caller asked to go backwards; saved data is never downgraded. + Downgrade { + /// Version of the loaded value. + from: u32, + /// Requested version, lower than `from`. + to: u32, + }, + /// No step is registered for the version that needs upgrading. + MissingStep { + /// Version without a step. + version: u32, + /// Version the chain was asked to reach. + to: u32, + }, + /// A step rejected the value it was given. + Step { + /// Version the failing step reads. + version: u32, + /// What was wrong with the value. + reason: String, + }, +} + +impl MigrateError { + /// Builds [`Self::Step`] for a step that rejects its input. + #[must_use] + pub fn step(version: u32, reason: impl Into) -> Self { + Self::Step { + version, + reason: reason.into(), + } + } +} + +impl fmt::Display for MigrateError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Downgrade { from, to } => { + write!( + formatter, + "cannot migrate version {from} back to version {to}" + ) + } + Self::MissingStep { version, to } => write!( + formatter, + "no migration from version {version} while migrating to version {to}" + ), + Self::Step { version, reason } => { + write!( + formatter, + "migration from version {version} failed: {reason}" + ) + } + } + } +} + +impl std::error::Error for MigrateError {} + +/// Applies the steps from `from` up to `to`, one version at a time. +/// +/// `steps[version]` must upgrade version `version` to `version + 1`. `from == to` +/// is a no-op. A downgrade, a missing step or a rejecting step is an error; the +/// value is left untouched on failure. +pub fn migrate_value( + mut value: ron::Value, + from: u32, + to: u32, + steps: &BTreeMap, +) -> Result { + if to < from { + return Err(MigrateError::Downgrade { from, to }); + } + let mut version = from; + while version < to { + let step = steps + .get(&version) + .ok_or(MigrateError::MissingStep { version, to })?; + value = step(value)?; + version += 1; + } + Ok(value) +} + +#[cfg(test)] +mod tests; diff --git a/crates/storage/src/migrate/tests.rs b/crates/storage/src/migrate/tests.rs new file mode 100644 index 0000000..d68cdd1 --- /dev/null +++ b/crates/storage/src/migrate/tests.rs @@ -0,0 +1,94 @@ +//! Migration chains: ordering, missing links and downgrades. + +#![allow( + clippy::unwrap_used, + reason = "a test aborts on failure, which is the intent" +)] + +use std::collections::BTreeMap; + +use super::{MigrateError, Migration, migrate_value}; + +/// Version 0 → 1: adds the field `a`. +fn insert_a(mut value: ron::Value) -> Result { + let ron::Value::Map(ref mut document) = value else { + return Err(MigrateError::step(0, "document is not a map")); + }; + let _previous = document.insert("a", 1); + Ok(value) +} + +/// Version 1 → 2: adds the field `b`. +fn insert_b(mut value: ron::Value) -> Result { + let ron::Value::Map(ref mut document) = value else { + return Err(MigrateError::step(1, "document is not a map")); + }; + let _previous = document.insert("b", 2); + Ok(value) +} + +fn empty_document() -> ron::Value { + ron::Value::Map(ron::Map::new()) +} + +#[test] +fn a_two_step_chain_applies_in_order() { + let mut steps = BTreeMap::new(); + let _previous = steps.insert(0, insert_a as Migration); + let _previous = steps.insert(1, insert_b as Migration); + + let migrated = migrate_value(empty_document(), 0, 2, &steps).unwrap(); + let ron::Value::Map(document) = migrated else { + panic!("a migration must return a map"); + }; + assert_eq!( + document.get(&ron::Value::from("a")), + Some(&ron::Value::from(1)) + ); + assert_eq!( + document.get(&ron::Value::from("b")), + Some(&ron::Value::from(2)) + ); +} + +#[test] +fn a_missing_step_stops_the_chain() { + let mut steps = BTreeMap::new(); + let _previous = steps.insert(0, insert_a as Migration); + + let error = migrate_value(empty_document(), 0, 2, &steps).unwrap_err(); + assert_eq!(error, MigrateError::MissingStep { version: 1, to: 2 }); +} + +#[test] +fn a_downgrade_is_rejected_before_any_step_runs() { + let error = migrate_value(empty_document(), 2, 0, &BTreeMap::new()).unwrap_err(); + assert_eq!(error, MigrateError::Downgrade { from: 2, to: 0 }); +} + +#[test] +fn equal_versions_are_a_no_op() { + let value = empty_document(); + let migrated = migrate_value(value.clone(), 3, 3, &BTreeMap::new()).unwrap(); + assert_eq!(migrated, value); +} + +#[test] +fn a_rejecting_step_reports_its_version() { + fn reject(value: ron::Value) -> Result { + let _ignored = value; + Err(MigrateError::step(0, "malformed payload")) + } + + let mut steps = BTreeMap::new(); + let _previous = steps.insert(0, reject as Migration); + + let error = migrate_value(empty_document(), 0, 1, &steps).unwrap_err(); + assert!(matches!( + error, + MigrateError::Step { + version: 0, + ref reason + } if reason == "malformed payload" + )); +} diff --git a/crates/storage/src/project/mod.rs b/crates/storage/src/project/mod.rs index 0236937..e3fcb36 100644 --- a/crates/storage/src/project/mod.rs +++ b/crates/storage/src/project/mod.rs @@ -1 +1,104 @@ -//! fabrilis-storage :: project - stub (see docs/ARCHITECTURE.md) +//! A project folder: the save format described in docs/STORAGE.md. +//! +//! A project is a directory with a `blobs/` subdirectory for content-addressed +//! files and small RON documents at its root. Text files are written through a +//! temporary file and renamed into place, so an interrupted save cannot leave a +//! half-written document behind. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::blob::BlobStore; + +/// Subdirectory holding the blobs. +const BLOB_DIRECTORY: &str = "blobs"; + +/// Distinguishes temporary files written by concurrent saves in one process. +static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0); + +/// An existing project directory. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Project { + root: PathBuf, +} + +impl Project { + /// Creates the directory, its parents and the blob store. + pub fn create(root: impl Into) -> io::Result { + let root = root.into(); + fs::create_dir_all(&root)?; + fs::create_dir_all(root.join(BLOB_DIRECTORY))?; + Ok(Self { root }) + } + + /// Opens an existing directory; a missing path is [`io::ErrorKind::NotFound`]. + pub fn open(root: impl Into) -> io::Result { + let root = root.into(); + if root.is_dir() { + Ok(Self { root }) + } else { + Err(io::Error::new( + io::ErrorKind::NotFound, + format!("project directory {} does not exist", root.display()), + )) + } + } + + /// The project directory. + #[must_use] + pub fn root(&self) -> &Path { + &self.root + } + + /// The blob store under `root/blobs`. + #[must_use] + pub fn blobs(&self) -> BlobStore { + BlobStore::new(self.root.join(BLOB_DIRECTORY)) + } + + /// A file path inside the project; the file need not exist. + #[must_use] + pub fn path(&self, name: &str) -> PathBuf { + self.root.join(name) + } + + /// Writes a text document atomically. + pub fn write_text(&self, name: &str, text: &str) -> io::Result<()> { + write_atomic(&self.path(name), text) + } + + /// Reads a text document written with [`Self::write_text`]. + pub fn read_text(&self, name: &str) -> io::Result { + fs::read_to_string(self.path(name)) + } +} + +/// Writes through a temporary file in the same directory, then renames. +fn write_atomic(path: &Path, text: &str) -> io::Result<()> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let temp = temp_path(path); + fs::write(&temp, text)?; + if let Err(error) = fs::rename(&temp, path) { + let _ = fs::remove_file(&temp); + return Err(error); + } + Ok(()) +} + +/// A temporary sibling of `path` that cannot collide with the target name. +fn temp_path(path: &Path) -> PathBuf { + let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed); + let pid = std::process::id(); + let name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("file"); + path.with_file_name(format!(".{name}.{pid}-{counter}.tmp")) +} + +#[cfg(test)] +mod tests; diff --git a/crates/storage/src/project/tests.rs b/crates/storage/src/project/tests.rs new file mode 100644 index 0000000..52e9e3d --- /dev/null +++ b/crates/storage/src/project/tests.rs @@ -0,0 +1,94 @@ +//! Project folders: creation, atomic text files and the blob directory. + +#![allow( + clippy::unwrap_used, + reason = "a test aborts on failure, which is the intent" +)] + +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::Project; + +/// A directory removed on drop. +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(label: &str) -> Self { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let counter = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "fabrilis-project-{label}-{}-{counter}", + std::process::id() + )); + std::fs::create_dir_all(&path).unwrap(); + Self { path } + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +#[test] +fn create_makes_the_root_and_the_blob_directory() { + let temp = TempDir::new("create"); + let root = temp.path.join("new-project"); + let project = Project::create(&root).unwrap(); + + assert_eq!(project.root(), root); + assert!(root.is_dir()); + assert!(root.join("blobs").is_dir()); +} + +#[test] +fn open_requires_an_existing_directory() { + let temp = TempDir::new("open"); + let missing = temp.path.join("absent"); + let error = Project::open(&missing).unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::NotFound); + + let project = Project::create(&temp.path).unwrap(); + assert_eq!(Project::open(project.root()).unwrap().root(), temp.path); +} + +#[test] +fn text_round_trips_and_replaces_atomically() { + let temp = TempDir::new("text"); + let project = Project::create(&temp.path).unwrap(); + + project.write_text("scene.ron", "first").unwrap(); + assert_eq!(project.read_text("scene.ron").unwrap(), "first"); + project.write_text("scene.ron", "second").unwrap(); + assert_eq!(project.read_text("scene.ron").unwrap(), "second"); + + let leftovers: Vec = std::fs::read_dir(project.root()) + .unwrap() + .filter_map(|entry| entry.ok()) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .filter(|name| name.starts_with('.')) + .collect(); + assert!(leftovers.is_empty(), "temporary files left: {leftovers:?}"); +} + +#[test] +fn paths_are_rooted_in_the_project() { + let temp = TempDir::new("path"); + let project = Project::create(&temp.path).unwrap(); + assert_eq!(project.path("scene.ron"), temp.path.join("scene.ron")); +} + +#[test] +fn blobs_live_in_the_blobs_subdirectory() { + let temp = TempDir::new("blobs"); + let project = Project::create(&temp.path).unwrap(); + let store = project.blobs(); + let hash = store.put(b"mesh").unwrap(); + + assert!(store.contains(hash)); + assert!(project.path("blobs").join(hash.to_hex()).is_file()); +} diff --git a/crates/worldgen/src/noise/mod.rs b/crates/worldgen/src/noise/mod.rs index f7af303..68d0568 100644 --- a/crates/worldgen/src/noise/mod.rs +++ b/crates/worldgen/src/noise/mod.rs @@ -1 +1,121 @@ -//! fabrilis-worldgen :: noise - stub (see docs/ARCHITECTURE.md) +//! Deterministic 2D value noise. +//! +//! Values sit on an integer lattice and are interpolated with a smoothstep curve. +//! The lattice value comes from SplitMix64 mixing of the seed and both lattice +//! coordinates, so the result uses integer arithmetic only: no floating-point +//! hashing, no `std` transcendental functions, the same output on every platform. +//! See docs/DETERMINISM.md. + +/// SplitMix64 increment; mixing a seed with it keeps seed `0` from being special. +const GAMMA: u64 = 0x9E37_79B9_7F4A_7C15; + +/// Odd multipliers that spread the two lattice axes before the finaliser runs. +const X_PRIME: u64 = 0xD6E8_FEB8_6659_FD93; +const Y_PRIME: u64 = 0xA076_1D64_78BD_642F; + +/// Scale that turns the top 53 bits of a hash into `[0, 1)`. +const UNIT: f64 = 1.0 / (1u64 << 53) as f64; + +/// The SplitMix64 finaliser: a bijective avalanche on 64 bits. +#[inline] +fn mix(mut z: u64) -> u64 { + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// Hashes one lattice point; pure integer arithmetic, so it is portable. +#[inline] +fn lattice_hash(seed: u64, ix: i64, iy: i64) -> u64 { + let horizontal = mix(seed.wrapping_add(GAMMA) ^ (ix as u64).wrapping_mul(X_PRIME)); + mix(horizontal ^ (iy as u64).wrapping_mul(Y_PRIME)) +} + +/// Maps a hash to a lattice value in `[-1, 1)`; the 53-bit mantissa is exact. +#[inline] +fn lattice_value(hash: u64) -> f64 { + ((hash >> 11) as f64 * UNIT).mul_add(2.0, -1.0) +} + +/// Smoothstep: `3t² - 2t³`, with zero first derivative at both ends. +#[inline] +fn smoothstep(t: f64) -> f64 { + t * t * (3.0 - 2.0 * t) +} + +/// A seeded 2D value-noise field. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Noise { + seed: u64, +} + +impl Noise { + /// Creates a field from a seed; every seed is valid. + #[inline] + #[must_use] + pub const fn new(seed: u64) -> Self { + Self { seed } + } + + /// Samples the field at `(x, y)`, returning a value in `[-1, 1]`. + /// + /// Non-finite coordinates sample as `0`, so callers never see NaN. + #[must_use] + pub fn sample(&self, x: f64, y: f64) -> f64 { + if !x.is_finite() || !y.is_finite() { + return 0.0; + } + // `as i64` saturates for coordinates beyond the lattice range, which keeps + // the result finite and deterministic instead of wrapping. + let base_x = x.floor(); + let base_y = y.floor(); + let ix = base_x as i64; + let iy = base_y as i64; + let tx = smoothstep(x - base_x); + let ty = smoothstep(y - base_y); + + let bottom_left = lattice_value(lattice_hash(self.seed, ix, iy)); + let bottom_right = lattice_value(lattice_hash(self.seed, ix.wrapping_add(1), iy)); + let top_left = lattice_value(lattice_hash(self.seed, ix, iy.wrapping_add(1))); + let top_right = lattice_value(lattice_hash( + self.seed, + ix.wrapping_add(1), + iy.wrapping_add(1), + )); + + let bottom = bottom_left + (bottom_right - bottom_left) * tx; + let top = top_left + (top_right - top_left) * tx; + bottom + (top - bottom) * ty + } +} + +/// Fractal Brownian motion: octaves summed low to high, each one `lacunarity` +/// times denser and `gain` times weaker. +/// +/// The sum is divided by the total amplitude, so the result stays in `[-1, 1]` +/// for every gain and octave count. Octaves are added in a fixed order, which +/// makes the result bit-reproducible. +/// +/// Six arguments are the natural shape of the call; bundling octaves and both +/// multipliers into a struct would only add a type at every call site. +#[allow( + clippy::too_many_arguments, + reason = "noise coordinates plus three independent fBm parameters; a params struct adds no clarity" +)] +#[must_use] +pub fn fbm(noise: &Noise, x: f64, y: f64, octaves: u8, lacunarity: f64, gain: f64) -> f64 { + let mut frequency = 1.0; + let mut amplitude = 1.0; + let mut total = 0.0; + let mut weight = 0.0; + for _ in 0..octaves { + total += amplitude * noise.sample(x * frequency, y * frequency); + weight += amplitude; + frequency *= lacunarity; + amplitude *= gain; + } + if weight > 0.0 { total / weight } else { 0.0 } +} + +#[cfg(test)] +mod tests; diff --git a/crates/worldgen/src/noise/tests.rs b/crates/worldgen/src/noise/tests.rs new file mode 100644 index 0000000..03a55ef --- /dev/null +++ b/crates/worldgen/src/noise/tests.rs @@ -0,0 +1,96 @@ +use super::*; + +#[test] +fn sample_stays_in_range() { + let noise = Noise::new(7); + for j in -32..=32 { + for i in -32..=32 { + let x = f64::from(i) * 0.37; + let y = f64::from(j) * 0.41; + let value = noise.sample(x, y); + assert!((-1.0..=1.0).contains(&value), "value {value} at ({x}, {y})"); + } + } +} + +#[test] +fn same_seed_repeats_exactly() { + let a = Noise::new(1234); + let b = Noise::new(1234); + for step in 0..100 { + let x = f64::from(step) * 0.13; + let y = f64::from(step) * 0.29; + assert_eq!(a.sample(x, y).to_bits(), b.sample(x, y).to_bits()); + } +} + +#[test] +fn different_seeds_differ() { + let a = Noise::new(1); + let b = Noise::new(2); + assert_ne!(a.sample(0.5, 0.5), b.sample(0.5, 0.5)); +} + +#[test] +fn lattice_points_are_reproducible_by_hash() { + let noise = Noise::new(99); + assert_eq!( + noise.sample(0.0, 0.0), + lattice_value(lattice_hash(99, 0, 0)) + ); + assert_eq!( + noise.sample(-3.0, 5.0), + lattice_value(lattice_hash(99, -3, 5)) + ); +} + +#[test] +fn interpolation_is_continuous_across_cells() { + // A value-noise field is continuous, so stepping over a lattice boundary + // changes the sample only slightly. + let noise = Noise::new(5); + let left = noise.sample(0.999, 0.25); + let right = noise.sample(1.001, 0.25); + assert!((left - right).abs() < 1e-2); +} + +#[test] +fn non_finite_coordinates_sample_as_zero() { + let noise = Noise::new(3); + assert_eq!(noise.sample(f64::NAN, 0.5), 0.0); + assert_eq!(noise.sample(0.5, f64::INFINITY), 0.0); + assert_eq!(noise.sample(f64::NEG_INFINITY, f64::NAN), 0.0); +} + +#[test] +fn huge_coordinates_do_not_overflow() { + let noise = Noise::new(3); + for value in [1e300, -1e300, f64::MAX, f64::MIN] { + let sampled = noise.sample(value, value); + assert!((-1.0..=1.0).contains(&sampled)); + } +} + +#[test] +fn fbm_single_octave_equals_the_field() { + let noise = Noise::new(11); + assert_eq!(fbm(&noise, 0.7, -1.3, 1, 2.0, 0.5), noise.sample(0.7, -1.3)); +} + +#[test] +fn fbm_stays_in_range_for_many_octaves() { + let noise = Noise::new(21); + for j in 0..16 { + for i in 0..16 { + let x = f64::from(i) * 0.31; + let y = f64::from(j) * 0.17; + let value = fbm(&noise, x, y, 8, 2.0, 0.5); + assert!((-1.0..=1.0).contains(&value)); + } + } +} + +#[test] +fn fbm_with_zero_octaves_is_zero() { + assert_eq!(fbm(&Noise::new(1), 0.3, 0.4, 0, 2.0, 0.5), 0.0); +} diff --git a/crates/worldgen/src/terrain/mod.rs b/crates/worldgen/src/terrain/mod.rs index 5f1da69..6b04469 100644 --- a/crates/worldgen/src/terrain/mod.rs +++ b/crates/worldgen/src/terrain/mod.rs @@ -1 +1,349 @@ -//! fabrilis-worldgen :: terrain - stub (see docs/ARCHITECTURE.md) +//! Terrain heightmap and its render/collider mesh. +//! +//! The world is Z-up, so terrain is a height field `z = f(x, y)` sampled on a +//! square grid centred at the origin: `x` and `y` cover `[-extent/2, extent/2]` +//! and `z` covers `[0, height_scale]`. Row-major storage keeps `i` along X and +//! `j` along Y. One map feeds both the renderer and the colliders (D14). +//! See docs/COORDINATES.md. + +use fabrilis_core::vec::Vec3; + +use crate::noise::{Noise, fbm}; + +/// Smallest accepted grid resolution; two nodes still form one cell. +const MIN_SIZE: usize = 2; + +/// Largest accepted grid resolution; `size²` vertices still fit `u32` indices. +const MAX_SIZE: usize = 4096; + +/// Octave bounds; more octaves cost more and add little below one sample per cell. +const MIN_OCTAVES: u8 = 1; +const MAX_OCTAVES: u8 = 8; + +/// Terrain generation parameters. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct TerrainConfig { + /// Seed of the noise field; the same seed gives the same heights. + pub seed: u64, + /// Nodes per axis, in `2..=4096`. + pub size: usize, + /// Side length of the map, m. + pub extent: f64, + /// Vertical span, m; `0` makes a flat map. + pub height_scale: f64, + /// Noise cycles across the map; larger values mean smaller features. + pub frequency: f64, + /// Octaves of fractal noise, in `1..=8`. + pub octaves: u8, + /// Frequency multiplier between octaves; must be greater than one. + pub lacunarity: f64, + /// Amplitude multiplier between octaves, in `[0, 1]`. + pub gain: f64, +} + +impl Default for TerrainConfig { + /// A 64 x 64 grid over 100 m, up to 10 m tall. + fn default() -> Self { + Self { + seed: 0, + size: 64, + extent: 100.0, + height_scale: 10.0, + frequency: 2.0, + octaves: 4, + lacunarity: 2.0, + gain: 0.5, + } + } +} + +impl TerrainConfig { + /// Distance between neighbouring nodes, m. + #[must_use] + fn spacing(&self) -> f64 { + self.extent / (self.size - 1) as f64 + } +} + +/// Why a [`Heightmap`] could not be generated. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum TerrainError { + /// The grid resolution is outside `2..=4096`. + SizeOutOfRange(usize), + /// The map side is not finite and positive. + InvalidExtent(f64), + /// The height scale is not finite and non-negative. + InvalidHeightScale(f64), + /// The noise frequency is not finite and positive. + InvalidFrequency(f64), + /// The octave count is outside `1..=8`. + OctavesOutOfRange(u8), + /// The octave frequency multiplier is not finite and greater than one. + InvalidLacunarity(f64), + /// The octave amplitude multiplier is outside `[0, 1]`. + InvalidGain(f64), +} + +impl core::fmt::Display for TerrainError { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::SizeOutOfRange(size) => write!( + formatter, + "terrain size {size} is outside {MIN_SIZE}..={MAX_SIZE}" + ), + Self::InvalidExtent(extent) => { + write!( + formatter, + "terrain extent {extent} is not finite and positive" + ) + } + Self::InvalidHeightScale(scale) => write!( + formatter, + "terrain height scale {scale} is not finite and non-negative" + ), + Self::InvalidFrequency(frequency) => write!( + formatter, + "terrain frequency {frequency} is not finite and positive" + ), + Self::OctavesOutOfRange(octaves) => write!( + formatter, + "terrain octaves {octaves} is outside {MIN_OCTAVES}..={MAX_OCTAVES}" + ), + Self::InvalidLacunarity(value) => write!( + formatter, + "terrain lacunarity {value} is not finite and greater than one" + ), + Self::InvalidGain(value) => { + write!(formatter, "terrain gain {value} is not in [0, 1]") + } + } + } +} + +impl std::error::Error for TerrainError {} + +/// Rejects parameters that would panic or produce a meaningless map. +fn validate(config: &TerrainConfig) -> Result<(), TerrainError> { + if !(MIN_SIZE..=MAX_SIZE).contains(&config.size) { + return Err(TerrainError::SizeOutOfRange(config.size)); + } + if !positive_finite(config.extent) { + return Err(TerrainError::InvalidExtent(config.extent)); + } + if !(config.height_scale.is_finite() && config.height_scale >= 0.0) { + return Err(TerrainError::InvalidHeightScale(config.height_scale)); + } + if !positive_finite(config.frequency) { + return Err(TerrainError::InvalidFrequency(config.frequency)); + } + if !(MIN_OCTAVES..=MAX_OCTAVES).contains(&config.octaves) { + return Err(TerrainError::OctavesOutOfRange(config.octaves)); + } + if !(config.lacunarity.is_finite() && config.lacunarity > 1.0) { + return Err(TerrainError::InvalidLacunarity(config.lacunarity)); + } + if !(config.gain.is_finite() && (0.0..=1.0).contains(&config.gain)) { + return Err(TerrainError::InvalidGain(config.gain)); + } + Ok(()) +} + +#[inline] +fn positive_finite(value: f64) -> bool { + value.is_finite() && value > 0.0 +} + +/// A generated heightmap with bilinear sampling and a triangle mesh. +#[derive(Debug, Clone)] +pub struct Heightmap { + config: TerrainConfig, + heights: Vec, +} + +impl Heightmap { + /// Generates the map, or reports the first invalid parameter. + pub fn generate(config: TerrainConfig) -> Result { + validate(&config)?; + let noise = Noise::new(config.seed); + let half = config.extent * 0.5; + let spacing = config.spacing(); + let noise_scale = config.frequency / config.extent; + let mut heights = Vec::with_capacity(config.size * config.size); + for j in 0..config.size { + let y = j as f64 * spacing - half; + for i in 0..config.size { + let x = i as f64 * spacing - half; + let value = fbm( + &noise, + x * noise_scale, + y * noise_scale, + config.octaves, + config.lacunarity, + config.gain, + ); + heights.push((value * 0.5 + 0.5).clamp(0.0, 1.0) * config.height_scale); + } + } + Ok(Self { config, heights }) + } + + /// Nodes per axis. + #[inline] + #[must_use] + pub fn size(&self) -> usize { + self.config.size + } + + /// Side length of the map, m. + #[inline] + #[must_use] + pub fn extent(&self) -> f64 { + self.config.extent + } + + /// Distance between neighbouring nodes, m. + #[inline] + #[must_use] + pub fn spacing(&self) -> f64 { + self.config.spacing() + } + + /// Heights in row-major order, `size × size`, `i` along X and `j` along Y. + #[inline] + #[must_use] + pub fn heights(&self) -> &[f64] { + &self.heights + } + + /// Bilinearly interpolates the height at world `(x, y)`. + /// + /// Coordinates outside the map clamp to its border; non-finite coordinates + /// clamp to the nearest edge (`NaN` to the low edge) instead of panicking. + #[must_use] + pub fn height_at(&self, x: f64, y: f64) -> f64 { + self.height_at_grid(self.grid_coordinate(x), self.grid_coordinate(y)) + } + + /// The surface normal at world `(x, y)`, pointing up. + /// + /// Uses central differences, one-sided at the border, and returns `+Z` when + /// the gradient is degenerate. + #[must_use] + pub fn normal_at(&self, x: f64, y: f64) -> Vec3 { + let gx = self.grid_coordinate(x); + let gy = self.grid_coordinate(y); + let last = (self.config.size - 1) as f64; + let (xm, xp) = neighbours(gx, last); + let (ym, yp) = neighbours(gy, last); + let dx = (xp - xm) * self.spacing(); + let dy = (yp - ym) * self.spacing(); + let slope_x = (self.height_at_grid(xp, gy) - self.height_at_grid(xm, gy)) / dx; + let slope_y = (self.height_at_grid(gx, yp) - self.height_at_grid(gx, ym)) / dy; + Vec3::new(-slope_x, -slope_y, 1.0) + .normalized() + .unwrap_or(Vec3::Z) + } + + /// A triangle mesh at full resolution; see [`Self::mesh_with_step`]. + #[must_use] + pub fn mesh(&self) -> TerrainMesh { + self.mesh_with_step(1) + } + + /// A triangle mesh that keeps every `step`-th node, for cheap colliders. + /// + /// `step` is clamped to at least one; the grid keeps the first and last node, + /// so a step of two on an odd-sized map halves the node count. + #[must_use] + pub fn mesh_with_step(&self, step: usize) -> TerrainMesh { + let step = step.max(1); + let nodes = (self.config.size - 1) / step + 1; + let vertices = self.build_vertices(nodes, step); + let indices = build_indices(nodes); + TerrainMesh { vertices, indices } + } + + fn build_vertices(&self, nodes: usize, step: usize) -> Vec { + let half = self.config.extent * 0.5; + let spacing = self.spacing(); + let mut vertices = Vec::with_capacity(nodes * nodes); + for j in 0..nodes { + let grid_j = j * step; + let y = grid_j as f64 * spacing - half; + for i in 0..nodes { + let grid_i = i * step; + let x = grid_i as f64 * spacing - half; + vertices.push(Vec3::new(x, y, self.node(grid_i, grid_j))); + } + } + vertices + } + + /// The stored height at a grid node; both indices are below `size`. + #[inline] + fn node(&self, i: usize, j: usize) -> f64 { + self.heights[j * self.config.size + i] + } + + /// World coordinate to a fractional grid coordinate in `[0, size - 1]`. + fn grid_coordinate(&self, value: f64) -> f64 { + let last = (self.config.size - 1) as f64; + if value.is_nan() { + return 0.0; + } + let offset = value + self.config.extent * 0.5; + (offset / self.spacing()).clamp(0.0, last) + } + + /// Bilinear interpolation in grid coordinates, which must be clamped. + fn height_at_grid(&self, gx: f64, gy: f64) -> f64 { + let last = self.config.size - 1; + let i0 = (gx.floor() as usize).min(last - 1); + let j0 = (gy.floor() as usize).min(last - 1); + let tx = gx - i0 as f64; + let ty = gy - j0 as f64; + let bottom_left = self.node(i0, j0); + let bottom_right = self.node(i0 + 1, j0); + let top_left = self.node(i0, j0 + 1); + let top_right = self.node(i0 + 1, j0 + 1); + // Exact at `t = 0` and `t = 1`, so node samples match the stored heights. + let bottom = bottom_left * (1.0 - tx) + bottom_right * tx; + let top = top_left * (1.0 - tx) + top_right * tx; + bottom * (1.0 - ty) + top * ty + } +} + +/// The grid positions used for a difference at `position`, clamped to the map. +fn neighbours(position: f64, last: f64) -> (f64, f64) { + ((position - 1.0).max(0.0), (position + 1.0).min(last)) +} + +/// Two counter-clockwise triangles per cell, joined into `u32` indices. +fn build_indices(nodes: usize) -> Vec<[u32; 3]> { + let cells = nodes.saturating_sub(1); + let mut indices = Vec::with_capacity(2 * cells * cells); + let row = nodes as u32; + for j in 0..cells { + for i in 0..cells { + let bottom_left = (j * nodes + i) as u32; + let bottom_right = bottom_left + 1; + let top_left = bottom_left + row; + let top_right = top_left + 1; + indices.push([bottom_left, bottom_right, top_right]); + indices.push([bottom_left, top_right, top_left]); + } + } + indices +} + +/// A triangle mesh of the terrain surface, ready for a renderer or a collider. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct TerrainMesh { + /// Vertex positions in world space, metres. + pub vertices: Vec, + /// Triangles, wound counter-clockwise when viewed from above (`+Z`). + pub indices: Vec<[u32; 3]>, +} + +#[cfg(test)] +mod tests; diff --git a/crates/worldgen/src/terrain/tests.rs b/crates/worldgen/src/terrain/tests.rs new file mode 100644 index 0000000..1f82774 --- /dev/null +++ b/crates/worldgen/src/terrain/tests.rs @@ -0,0 +1,330 @@ +use fabrilis_core::vec::Vec3; + +use super::*; + +/// FNV-1a over the little-endian bit patterns of the heights. +/// +/// The bit patterns are used so the hash does not depend on the host endianness +/// or on formatting, only on the exact `f64` values (docs/DETERMINISM.md). +fn hash_heights(heights: &[f64]) -> u64 { + let mut hash: u64 = 0xCBF2_9CE4_8422_2325; + for height in heights { + for byte in height.to_bits().to_le_bytes() { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(0x0000_0100_0000_01B3); + } + } + hash +} + +/// The reference map used by the sampling and mesh tests; its spacing (3.125 m) +/// and half extent (50 m) are exact binary values, so grid nodes land exactly. +fn reference_map() -> Heightmap { + let config = TerrainConfig { + seed: 42, + size: 33, + extent: 100.0, + height_scale: 10.0, + frequency: 2.0, + octaves: 4, + ..TerrainConfig::default() + }; + Heightmap::generate(config).expect("the reference config is valid") +} + +fn flat_map() -> Heightmap { + let config = TerrainConfig { + height_scale: 0.0, + ..TerrainConfig::default() + }; + Heightmap::generate(config).expect("a zero height scale is valid") +} + +#[test] +fn flat_terrain_has_zero_height_and_up_normals() { + let map = flat_map(); + assert_eq!(map.heights().len(), map.size() * map.size()); + for height in map.heights() { + assert_eq!(*height, 0.0); + } + for j in -5..=5 { + for i in -5..=5 { + let x = f64::from(i) * 12.5; + let y = f64::from(j) * 7.25; + assert_eq!(map.height_at(x, y), 0.0); + assert_eq!(map.normal_at(x, y), Vec3::Z); + } + } +} + +#[test] +fn default_config_has_the_documented_values() { + let config = TerrainConfig::default(); + assert_eq!(config.size, 64); + assert_eq!(config.extent, 100.0); + assert_eq!(config.height_scale, 10.0); + assert_eq!(config.frequency, 2.0); + assert_eq!(config.octaves, 4); + assert_eq!(config.lacunarity, 2.0); + assert_eq!(config.gain, 0.5); + assert_eq!(config.spacing(), 100.0 / 63.0); +} + +#[test] +fn same_seed_reproduces_heights_bitwise() { + let first = reference_map(); + let second = reference_map(); + let left: Vec = first.heights().iter().map(|h| h.to_bits()).collect(); + let right: Vec = second.heights().iter().map(|h| h.to_bits()).collect(); + assert_eq!(left, right); +} + +#[test] +fn different_seed_changes_heights() { + let other = Heightmap::generate(TerrainConfig { + seed: 43, + ..reference_map().config + }) + .expect("the config is valid"); + assert_ne!(reference_map().heights(), other.heights()); +} + +#[test] +fn golden_height_hash_is_pinned() { + // This hash covers every height of the reference map. If it changes, the + // generator changed: regenerate the whole terrain, not just this constant. + // A deliberate algorithm change requires updating this value in the same + // commit and noting why in the commit message. + const GOLDEN: u64 = 0x9C4F_677D_8BE3_CCB8; + let actual = hash_heights(reference_map().heights()); + assert_eq!( + actual, GOLDEN, + "golden height hash changed to {actual:#018x}" + ); +} + +#[test] +fn height_at_grid_nodes_returns_stored_heights_exactly() { + let map = reference_map(); + let spacing = map.spacing(); + let half = map.extent() * 0.5; + for j in 0..map.size() { + for i in 0..map.size() { + let x = i as f64 * spacing - half; + let y = j as f64 * spacing - half; + assert_eq!(map.height_at(x, y), map.heights()[j * map.size() + i]); + } + } +} + +#[test] +fn midpoints_interpolate_bilinearly() { + let map = reference_map(); + let spacing = map.spacing(); + let half = map.extent() * 0.5; + let size = map.size(); + for j in [0, 1, 15, size - 2] { + for i in [0, 1, 15, size - 2] { + let x = (i as f64 + 0.5) * spacing - half; + let y = (j as f64 + 0.5) * spacing - half; + let corners = map.heights()[j * size + i] + + map.heights()[j * size + i + 1] + + map.heights()[(j + 1) * size + i] + + map.heights()[(j + 1) * size + i + 1]; + let expected = corners * 0.25; + let actual = map.height_at(x, y); + assert!((actual - expected).abs() < 1e-12, "{actual} != {expected}"); + } + } +} + +#[test] +fn sampling_clamps_borders_and_non_finite_coordinates() { + let map = reference_map(); + let last = map.size() - 1; + let low = map.height_at(-1e9, -1e9); + let high = map.height_at(1e9, 1e9); + assert_eq!(low, map.heights()[0]); + assert_eq!(high, map.heights()[last * map.size() + last]); + assert_eq!(map.height_at(f64::NAN, f64::NAN), low); + assert_eq!(map.height_at(f64::INFINITY, 0.0), map.height_at(1e9, 0.0)); + assert_eq!(map.normal_at(f64::NAN, f64::NAN), map.normal_at(-1e9, -1e9)); +} + +#[test] +fn normal_points_against_the_gradient_and_is_a_unit_vector() { + let map = reference_map(); + let spacing = map.spacing(); + let half = map.extent() * 0.5; + let size = map.size(); + // Find an interior node with a clear slope; flat spots have a zero gradient + // and would not exercise the direction check. + let (i, j) = (1..size - 1) + .flat_map(|j| (1..size - 1).map(move |i| (i, j))) + .find(|&(i, j)| { + let dx = map.heights()[j * size + i + 1] - map.heights()[j * size + i - 1]; + let dy = map.heights()[(j + 1) * size + i] - map.heights()[(j - 1) * size + i]; + dx.abs() + dy.abs() > 0.5 + }) + .expect("the reference map has a slope somewhere"); + let x = i as f64 * spacing - half; + let y = j as f64 * spacing - half; + let slope_x = + (map.heights()[j * size + i + 1] - map.heights()[j * size + i - 1]) / (2.0 * spacing); + let slope_y = + (map.heights()[(j + 1) * size + i] - map.heights()[(j - 1) * size + i]) / (2.0 * spacing); + let normal = map.normal_at(x, y); + assert!((normal.length() - 1.0).abs() < 1e-12); + assert!(normal.z > 0.0); + assert!( + (normal.x + slope_x / (1.0 + slope_x * slope_x + slope_y * slope_y).sqrt()).abs() < 1e-12 + ); + assert!( + (normal.y + slope_y / (1.0 + slope_x * slope_x + slope_y * slope_y).sqrt()).abs() < 1e-12 + ); + assert!(normal.x * slope_x <= 0.0); + assert!(normal.y * slope_y <= 0.0); +} + +fn triangle_z(vertices: &[Vec3], indices: &[u32; 3]) -> f64 { + let a = vertices[indices[0] as usize]; + let b = vertices[indices[1] as usize]; + let c = vertices[indices[2] as usize]; + (b - a).cross(c - a).z +} + +#[test] +fn mesh_has_grid_vertices_and_upward_triangles() { + let map = Heightmap::generate(TerrainConfig { + size: 9, + height_scale: 2.0, + ..TerrainConfig::default() + }) + .expect("the config is valid"); + let mesh = map.mesh(); + assert_eq!(mesh.vertices.len(), map.size() * map.size()); + assert_eq!(mesh.indices.len(), 2 * (map.size() - 1) * (map.size() - 1)); + for triangle in &mesh.indices { + assert!(triangle_z(&mesh.vertices, triangle) > 0.0); + } + for (index, vertex) in mesh.vertices.iter().enumerate() { + let i = index % map.size(); + let j = index / map.size(); + assert_eq!(vertex.z, map.heights()[j * map.size() + i]); + } +} + +#[test] +fn mesh_with_step_halves_the_grid_and_keeps_winding() { + let map = reference_map(); + let mesh = map.mesh_with_step(2); + let nodes = 17; + assert_eq!(mesh.vertices.len(), nodes * nodes); + assert_eq!(mesh.indices.len(), 2 * (nodes - 1) * (nodes - 1)); + for triangle in &mesh.indices { + assert!(triangle_z(&mesh.vertices, triangle) > 0.0); + } + assert_eq!(map.mesh_with_step(0), map.mesh()); +} + +fn config_with(mutate: impl FnOnce(&mut TerrainConfig)) -> TerrainConfig { + let mut config = TerrainConfig::default(); + mutate(&mut config); + config +} + +#[test] +fn grid_extent_and_scale_errors_are_rejected() { + let cases = [ + ( + config_with(|config| config.size = 1), + TerrainError::SizeOutOfRange(1), + ), + ( + config_with(|config| config.size = MAX_SIZE + 1), + TerrainError::SizeOutOfRange(MAX_SIZE + 1), + ), + ( + config_with(|config| config.extent = 0.0), + TerrainError::InvalidExtent(0.0), + ), + ( + config_with(|config| config.extent = -5.0), + TerrainError::InvalidExtent(-5.0), + ), + ( + config_with(|config| config.height_scale = -1.0), + TerrainError::InvalidHeightScale(-1.0), + ), + ]; + for (config, expected) in cases { + assert_eq!(Heightmap::generate(config).unwrap_err(), expected); + } +} + +#[test] +fn noise_parameter_errors_are_rejected() { + let cases = [ + ( + config_with(|config| config.frequency = 0.0), + TerrainError::InvalidFrequency(0.0), + ), + ( + config_with(|config| config.frequency = f64::INFINITY), + TerrainError::InvalidFrequency(f64::INFINITY), + ), + ( + config_with(|config| config.octaves = 0), + TerrainError::OctavesOutOfRange(0), + ), + ( + config_with(|config| config.octaves = 9), + TerrainError::OctavesOutOfRange(9), + ), + ( + config_with(|config| config.lacunarity = 1.0), + TerrainError::InvalidLacunarity(1.0), + ), + ( + config_with(|config| config.gain = -0.5), + TerrainError::InvalidGain(-0.5), + ), + ( + config_with(|config| config.gain = 1.5), + TerrainError::InvalidGain(1.5), + ), + ]; + for (config, expected) in cases { + assert_eq!(Heightmap::generate(config).unwrap_err(), expected); + } +} + +#[test] +fn non_finite_parameter_payloads_are_rejected() { + // `NaN` is never equal to itself, so its payload is checked separately. + let nan_extent = Heightmap::generate(config_with(|config| config.extent = f64::NAN)); + assert!(matches!( + nan_extent, + Err(TerrainError::InvalidExtent(value)) if value.is_nan() + )); + let nan_gain = Heightmap::generate(config_with(|config| config.gain = f64::NAN)); + assert!(matches!( + nan_gain, + Err(TerrainError::InvalidGain(value)) if value.is_nan() + )); + let infinite_lacunarity = + Heightmap::generate(config_with(|config| config.lacunarity = f64::INFINITY)); + assert!(matches!( + infinite_lacunarity, + Err(TerrainError::InvalidLacunarity(value)) if value.is_infinite() + )); +} + +#[test] +fn errors_implement_display_and_error() { + let error = TerrainError::SizeOutOfRange(0); + let text = error.to_string(); + assert!(text.contains('0')); + let dynamic: &dyn std::error::Error = &error; + assert_eq!(dynamic.to_string(), text); +} diff --git a/docs/CLI.md b/docs/CLI.md new file mode 100644 index 0000000..2113ecd --- /dev/null +++ b/docs/CLI.md @@ -0,0 +1,116 @@ +# Headless CLI + +CLI — это пульт управления движком и расчётный инструмент: пакетные прогоны и +живая консоль. Внешняя программа — скрипт, агент, нейросеть — управляет движком +командами, как инструментами через MCP. Окно и GPU не нужны. + +Отдельный бинарник, который не зависит от `render`, `ui` и `winit`; общий код мира +и прогонов живёт в `modes`, чтобы GUI и CLI считали одно и то же. + +## Зачем + +- прогнать сценарий на сервере и получить CSV/отчёт; +- проверить регрессии в CI без дисплея; +- считать развёртки и Monte Carlo; +- держать один сервер физики и подключать клиентов (NETWORK.md); +- дать внешнему коду команды `open/run/step/set_actuator/read_sensor`, не встраивая + чужую логику в движок; +- позволить агенту или нейросети вести эксперимент по шагам и читать только датчики. + +## Команды (план) + +| Команда | Что делает | +|---|---| +| `fabrilis simulate <проект> --scenario --seed N --until T --out result.csv` | один детерминированный прогон | +| `fabrilis validate` | проверки из VALIDATION.md; код возврата 1 при провале допуска | +| `fabrilis sweep <проект> --params sweep.ron --out dir/` | сетка/Монте-Карло, по процессу на прогон | +| `fabrilis control --stdio` | протокол команд по stdin/stdout для скрипта/агента | +| `fabrilis serve --bind 0.0.0.0:9000` | headless-сервер физики (S1 из NETWORK.md) | +| `fabrilis repl --connect <сокет>` | живая консоль: команды в запущенный движок | +| `fabrilis info` | версии, возможности, доступные сценарии | + +Коды возврата: `0` — успех, `1` — провал проверки, `2` — ошибка аргументов, +`3` — ошибка выполнения. + +## Гарантии + +- Без GPU и окна; шаг физики фиксированный, как в мире. +- Один seed и одни входы дают один результат; golden-хеш проверяется в CI. +- Параллельные прогоны — отдельные процессы, результат не зависит от их числа. +- Логи по LOGGING.md: обычный уровень `info`, `--dev` — `debug/trace`. +- Метрики-лог CSV и dev-лог те же, что у GUI (LOGGING.md). + +## Пульт управления (протокол команд) + +Один и тот же набор команд доступен из CLI, из Unix-сокета/TCP и (позже) как +MCP-инструменты. Это не «обучение в движке»: внешний код решает, что делать, а +движок исполняет команды и возвращает состояние. + +Транспорт v1 — JSON-RPC 2.0, по сообщению на строку: stdio для `fabrilis control`, +Unix-сокет для локального агента, TCP с токеном для удалённого сервера. + +```text +-> {"jsonrpc":"2.0","id":1,"method":"engine.open","params":{"project":"cart","seed":42}} +<- {"jsonrpc":"2.0","id":1,"result":{"t":0.0,"bodies":3}} +-> {"jsonrpc":"2.0","id":2,"method":"engine.step","params":{"steps":10}} +<- {"jsonrpc":"2.0","id":2,"result":{"t":0.01,"events":[]}} +-> {"jsonrpc":"2.0","id":3,"method":"engine.set_actuator","params":{"joint":0,"torque":4.9}} +-> {"jsonrpc":"2.0","id":4,"method":"engine.read_sensor","params":{"sensor":"encoder0"}} +<- {"jsonrpc":"2.0","id":4,"result":{"angle":0.31,"t":0.01}} +``` + +| Команда | Смысл | +|---|---| +| `engine.open` / `engine.close` | открыть проект/сценарий, освободить | +| `engine.run` / `engine.pause` | идти по часам или стоять | +| `engine.step` | ровно N шагов, без ожидания реального времени | +| `engine.reset` | вернуть сцену к seed/снимку | +| `engine.set_actuator` | момент/цель/скорость привода | +| `engine.set_input` | GPIO/PWM/вход схемы | +| `engine.read_sensor` | энкодер, IMU, ток, температура | +| `engine.query_state` | позы, метрики, флаги (только разрешённое) | +| `engine.snapshot` / `engine.restore` | снимок и откат | +| `engine.save` | сохранить проект/результат | + +Правила: + +- команды применяются на границе шага, а не посреди решателя; ответ подтверждает, + на каком времени они применены; +- наблюдение для внешнего управления — только датчики (`sensors`), без ground truth; + `query_state` — для отладки и разрешён явно; +- шаг фиксированный; `engine.step` не зависит от реального времени; +- один процесс — одна сцена; несколько внешних клиентов подключаются к `serve` + (NETWORK.md); +- одинаковые seed и последовательность команд дают одинаковую траекторию; +- MCP-адаптер (позже) выставляет те же команды как инструменты с явным allowlist, + без доступа к файлам и сети за пределами проекта. + +## Внешние контроллеры + +Для обучения или скриптового управления используется тот же протокол: `reset`, +`step`, `set_actuator`, `read_sensor`. Reward и условие `done` задаёт сценарий, а +не ядро; один процесс — одна среда, вектор сред делает внешний код. Позже, если +JSON-RPC не хватит по скорости, добавим бинарный протокол или PyO3-биндинги. + +## Разрез работ + +- **C1** — бинарник `fabrilis-cli` и `simulate`: тот же мир без окна, CSV на выходе; + DoD: прогон тестовой сцены, golden-хеш, нет зависимости от `render`/`ui`. +- **C2** — `validate` и коды возврата; DoD: специально сломанный кейс даёт код 1. +- **C3** — `sweep` и Monte Carlo по процессам; DoD: N прогонов, результат не зависит + от числа процессов. +- **C4** — протокол команд (JSON-RPC, stdio/Unix-сокет) и `repl`; DoD: внешний + скрипт делает open/reset/step/set_actuator/read_sensor и получает детерминированную + траекторию. +- **C5** — `serve`; DoD: headless-сервер и клиент из NETWORK.md S1–S2. +- **C6** — MCP-адаптер поверх тех же команд; DoD: агент открывает сцену, шагает, + читает датчики и снимок, не имея доступа к файлам вне проекта. + +## Открыто + +- Один бинарник с подкомандами или отдельные `fabrilis-cli`/`fabrilis-server`. +- JSON-RPC по строкам достаточно или нужен бинарный протокол/shared memory. +- MCP: отдельный процесс-адаптер или встроенный режим `fabrilis mcp`. +- Права: что именно можно менять внешнему клиенту, а что только читать. +- Частота управления по умолчанию и шаг децимации наблюдений. +- Формат отчёта: CSV, JSON, RON или всё сразу. diff --git a/docs/CODE_RULES.md b/docs/CODE_RULES.md index fce9d8c..1196115 100644 --- a/docs/CODE_RULES.md +++ b/docs/CODE_RULES.md @@ -90,6 +90,41 @@ crate `tools/limits` (`fabrilis-limits`). У каждого crate'а есть `b где это разумно). - Архитектурное изменение сопровождается записью в `DECISIONS.md`. +## Логирование (обязательно с первого дня) + +Код пишет диагностику сразу, а не «потом добавим». Единая точка — фасад +`fabrilis_core::log` с уровнями; приложение ставит приёмник (stderr, файл, dev-лог). +`println!`/`eprintln!` в библиотечном коде запрещены: только `main` для `--help` и +ошибок запуска. + +| Уровень | Когда | Пример | +|---|---|---| +| `error` | работать дальше нельзя | не создался GPU-девайс, не загрузился проект | +| `warn` | работаем, но деградация | шейдер не поддержан, шаг не сошёлся, поле не распознано | +| `info` | жизненный цикл, один раз на событие | старт, seed и размер мира, загружено N деталей, режим | +| `debug` | сводки и важные изменения | раз в секунду FPS/TPS/RTF, смена камеры, решение сходимости | +| `trace` | покадрово/пошагово, только для разбора | входные события, каждый шаг решателя, пики контактов | + +Правила: + +- Уровень выбирается по смыслу события, а не по желанию. Горячий цикл логирует + только `trace` и только после проверки уровня: строка не должна строиться, если + уровень выключен. +- Логи не влияют на симуляцию: логгер не меняет порядок, состояние и время. + В crate'ах симуляции по-прежнему нет `Instant::now`/`SystemTime::now`; время для + логов ставит приёмник в `app`. +- Пишем факты в виде `key=value`, а не склейку предложений: `frame=120 + frame_ms=18.4 physics_max_ms=0.6 trigger=contact`. +- Ошибки и деградации логируются там, где возникли, а не только наверху. +- Не логировать секреты и личные пути; большие буферы и меши не дампить. +- Сообщения на английском (как комментарии), уровни и поля — стабильные. +- Тесты: формат строки, парсеры, поведение выключенного уровня (строка не + форматируется), неизменность golden-хеша при включённых логах. + +`log`/`tracing` сейчас не берём: нужен свой минимальный фасад без зависимостей и с +контролем детерминизма (D35). Если понадобится экосистема, заменим фасад, не меняя +места вызовов. + ## Идеи на потом (пока не включены) Каждый пункт можно включить отдельным шагом, когда проект дорастёт. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 42c001a..1248040 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -36,6 +36,8 @@ | D32 | Очередь событий с метками в нс в планировщике: событие делит шаг подсистемы | фронты PWM и прерывания нельзя привязывать к эпохам | | D33 | Версия компилятора зафиксирована `rust-toolchain.toml`; CI собирает базовую и `native` сборки и сверяет хеши | разные LLVM могут разойтись в последних битах | | D34 | UI — свой immediate-mode слой на нашем `wgpu`-рендере с event-driven redraw; retained-дерево только по профилировке. ShapeUI blueprint — источник контрактов, не фундамент | редактору нужны панели, дерево и графики, а не окна произвольной формы; UI-фреймворк на годы остановил бы проект | +| D35 | Логи — собственный фасад `core::log` с уровнями error/warn/info/debug/trace; приложение ставит приёмник, `--dev` включает debug/trace; логи не влияют на симуляцию | единый способ писать диагностику с первого дня, без внешних зависимостей и без влияния на детерминизм; `log`/`tracing` можно подключить позже | +| D36 | Headless CLI — пульт управления движком и расчётный инструмент, отдельным бинарником без `render`/`ui`/`winit`; общий прогон мира живёт в `modes`. Внешние скрипты, агенты и нейросети управляют командами (JSON-RPC, позже MCP), логика остаётся снаружи | один протокол для CI, сервера и агентов; движок остаётся симулятором, а не чужим рантаймом | ## Открытые вопросы - FEM: тетраэдры для всей детали или балки + локальные тетраэдры в узлах. @@ -46,6 +48,8 @@ - Коллизии: `parry` оставляем навсегда или пишем свой узкий слой после своего физического backend'а. - Когда переходить с `wgpu` на `ash` (D24): после M4 по времени сборки и RTF. +- Сетевой режим: транспорт (TCP или сразу QUIC), частота снапшотов, нужен ли + предсказанный ввод; см. NETWORK.md. - Shaping и IME для текстовых полей: `cosmic-text` или `Parley`; решаем на M10. - Нужен ли retained-слой UI: решаем по профилировке M10. - Конкретная целевая плата и список реальных компонентов. diff --git a/docs/LOGGING.md b/docs/LOGGING.md new file mode 100644 index 0000000..9534d9b --- /dev/null +++ b/docs/LOGGING.md @@ -0,0 +1,93 @@ +# Логи и настройки + +Диагностика не должна мешать симуляции: оверлей и логи — наблюдатели. Их включение +не меняет шаг, порядок подсистем и результат (DETERMINISM.md). Время смотрят только +`app` и логи; в симуляции по-прежнему `SimTime`. + +Правила для кода — в [CODE_RULES.md](CODE_RULES.md), раздел «Логирование». + +## Оверлей + +Поверх кадра показывается панель (левый верхний угол выбран для M4d): + +| Поле | Смысл | +|---|---| +| FPS | кадров в секунду за окно ~1 с | +| TPS | шагов физики в секунду, реально выполненных | +| frame ms | среднее и максимум времени кадра за окно | +| physics ms | среднее и максимум времени шага/пачки шагов физики | +| render ms | среднее время отрисовки | +| RTF | simulated / wall, как в заголовке окна | +| CPU | загрузка процесса, % одного ядра | +| load1 | средняя нагрузка системы за 1 мин | +| RSS | резидентная память процесса, МБ | + +Под панелью — график времени кадра за последние ~180 кадров: линия кадра и линия +физики, авто-масштаб по максимуму, сетка и подписи 0 / max мс. Пики контактов +(переворот куба, удар) должны быть видны как узкие высокие всплески. + +## Флаги запуска + +| Флаг | Что делает | +|---|---| +| `--metrics-log <файл>` | писать метрики в CSV, по строке на кадр | +| `--log <файл>` | писать dev-лог в указанный файл | +| `--dev` | подробный режим: почти всё в dev-лог; включает метрики-лог, если путь не задан | +| `--append` | дописывать в конец вместо перезаписи | + +По умолчанию логи выключены. Файлы **перезаписываются при старте**; `--append` +нужен только для накопления между запусками. Флаги командной строки важнее +переменных окружения. + +Переменные окружения: `FABRILIS_METRICS_LOG`, `FABRILIS_LOG`, `FABRILIS_DEV=1`. + +## Метрики-лог (CSV) + +Заголовок один раз, строка на кадр, сброс на диск раз в секунду: + +```text +unix_s,t_s,frame,fps,tps,frame_ms,frame_max_ms,physics_ms,physics_max_ms,render_ms,rtf,cpu_pct,load1,rss_mb,spike +``` + +- `unix_s` — wall-clock начала кадра, секунды; +- `t_s` — время симуляции, секунды; +- `spike` — `1`, если кадр превысил бюджет (например, 20 мс) или шаг физики был + дольше 1 мс; +- остальные поля — как в оверлее. + +CSV открывается таблицей, pandas и gnuplot. Приватных данных, кроме путей и имени +GPU в dev-логе, нет. + +## Dev-режим + +`--dev` включает уровень `debug/trace` и пишет в текстовый лог: + +- версии Rust/движка, ОС, адаптер GPU, драйвер, формат поверхности; +- параметры окна, масштаб, размер буфера; +- seed, конфигурацию и хеш рельефа; +- созданные тела, коллайдеры, массы, стартовые позы; +- параметры камеры и изменения управления (без покадрового шума); +- раз в секунду — сводку метрик; +- каждый пик: номер кадра, время кадра, время физики, причина (`contact`/`resize`/`render`); +- ошибки wgpu/Rapier с контекстом. + +Пик логируется отдельной строкой, поэтому «лаг в момент переворота» можно найти в +логе, а не только на графике. + +## Настройки (XDG, позже) + +Постоянные личные настройки планируются отдельно от проекта (STORAGE.md): + +```text +~/.config/fabrilis/settings.ron +``` + +Поля: `overlay`, `metrics_log`, `log`, `level`, `dev`. Пока достаточно флагов и +переменных окружения; файл настроек добавим, когда появится UI настроек. + +## Проверка + +- Golden-хеш симуляции совпадает при включённом и выключенном оверлее/логе. +- Парсеры `/proc/self/stat`, `/proc/loadavg`, `/proc/self/status` — чистые функции + с тестами на битые строки (возвращают 0/None, не паникуют). +- Метрики-лог не пишется, пока флаг не задан. diff --git a/docs/NETWORK.md b/docs/NETWORK.md new file mode 100644 index 0000000..639ab9c --- /dev/null +++ b/docs/NETWORK.md @@ -0,0 +1,68 @@ +# Сетевой режим (план) + +Цель: физика может считаться не на машине зрителя. Один авторитетный сервер ведёт +симуляцию, к нему подключаются клиенты: смотреть с разных углов, управлять, позже — +редактировать. Текущая модульность это допускает: `core` уже даёт снимки и +планировщик, `render` рисует по состоянию, `app` — точка сборки. + +## Роли + +| Роль | Что делает | +|---|---| +| **Server** | headless, авторитетная симуляция 1 кГц, снапшоты, приём ввода | +| **Client** | окно, рендер, камера, отправка ввода, интерполяция между снапшотами | +| **Observer** | клиент только на чтение: смотрит, не управляет | +| **Editor** | позже: правки конструкции как команды серверу, не прямой доступ к состоянию | + +## Модель + +1. Сервер тикает фиксированным шагом и остаётся единственным источником истины. +2. Клиенты **не симулируют авторитетное состояние**. Они получают снапшоты и + интерполируют между двумя последними; рендер не влияет на сервер. +3. Ввод идёт с номером последовательности; сервер применяет его на ближайшем шаге + и подтверждает. Один клиент — владелец управления, остальные наблюдатели. +4. Снапшот — уже существующий набор подснимков (COUPLING.md), сжатый и, позже, + дельтами от базового. Частота снапшотов 20–60 Гц; шаг физики от неё не зависит. +5. Для своего управления позже возможны предсказание и откат: только если + детерминизм D1/D2 подтверждён, иначе клиент показывает подтверждённое состояние. + +## Транспорт + +Начинаем с TCP + собственный фрейминг (длина, версия, тип сообщения) на localhost и +в LAN. QUIC/WebTransport — отдельное решение, когда понадобится интернет и +мобильные клиенты. Формат сообщений версионируется как файлы (STORAGE.md); +несовпадение версий — понятная ошибка, а не тихое расхождение. + +## Что уже есть и чего не хватает + +Есть: `Snapshot`/подснимки, `SimTime`, `Fidelity`, детерминированный планировщик, +`render` по состоянию, слои crate'ов. +Не хватает: сериализация снапшотов в сетевой формат, серверный бинарник без окна, +клиентский цикл интерполяции, канал ввода, интерес-менеджмент по камере, +аутентификация и права. + +Серверная часть пересекается с [CLI.md](CLI.md): C5 — тот же headless-бинарник. + +## Разрез работ + +1. **S1 — headless-сервер.** Тот же мир без окна, тикает по часам, пишет метрики. +2. **S2 — снапшоты по сети.** Один клиент подключается на localhost и рисует мир, + полученный от сервера, без локальной физики. +3. **S3 — несколько клиентов.** Два-три наблюдателя с разными камерами, сервер + рассылает одно состояние; проверка, что картинки согласованы. +4. **S4 — ввод.** Один клиент управляет телом, остальные видят результат; + подтверждение ввода и отказ при разрыве. +5. **S5 — интернет и устойчивость.** Сжатие, дельты, переподключение, лимиты, + аутентификация по токену. + +**DoD S3:** headless-сервер, два клиента на разных машинах/окнах, камеры независимы, +состояние совпадает, разрыв одного клиента не роняет остальных. + +## Открытые вопросы + +- Транспорт: TCP сейчас или сразу QUIC. +- Частота снапшотов и бюджет полосы на эталонной сцене. +- Нужен ли предсказанный ввод или достаточно 50–100 мс задержки для наблюдения. +- Кто владеет управлением: один клиент, очередь, или серверный сценарий. +- Интерес-менеджмент: весь мир или только область вокруг камеры. +- Где живёт сервер: отдельный бинарник `fabrilis-server` или подкоманда `app`. diff --git a/docs/README.md b/docs/README.md index 026be98..db6e0d9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,6 +14,9 @@ | [DECISIONS.md](DECISIONS.md) | принятые решения и открытые вопросы | | [MODES.md](MODES.md) | режимы Bench / Lab / World, Fidelity, время, события | | [UI.md](UI.md) | свой UI: модель, текст, event-driven redraw, что берём из ShapeUI | +| [LOGGING.md](LOGGING.md) | оверлей метрик, CSV-лог, dev-режим, настройки | +| [NETWORK.md](NETWORK.md) | сетевой режим: сервер физики, клиенты-наблюдатели | +| [CLI.md](CLI.md) | headless CLI: прогоны, развёртки, сервер, среда для обучения | | [PHYSICS_SCOPE.md](PHYSICS_SCOPE.md) | механика, FEM, трение, тепло, вентиляция, проводка, виды | | [SCENARIOS.md](SCENARIOS.md) | сценарии, стабилизация, отказы, развёртки, метрики | | [ELECTRONICS.md](ELECTRONICS.md) | эмуляция CPU/SoC, аналоговая схема, мост |