diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7299842..b13e8f7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,6 +71,10 @@ jobs: env: ANIMATHIO_CLI: ${{ steps.host-2-3-0.outputs.cli }} run: python3 community/network/smoke.py "$ANIMATHIO_CLI" target/plugins + - name: Test Physics Play on released 2.3.0 + env: + ANIMATHIO_CLI: ${{ steps.host-2-3-0.outputs.cli }} + run: python3 community/physics/smoke.py "$ANIMATHIO_CLI" target/plugins - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: plugins diff --git a/README.md b/README.md index 35f14d7..6a18ee4 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ MIT licensed, like AniMathIO. Plugins are sandboxed WebAssembly components. | [Code Snippets](https://github.com/AniMathIO/plugins/tree/HEAD/community/code-snippets) | AniMathIO | Syntax-highlighted code with type-on reveal and token morph animations | MIT AND OFL-1.1 | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/code-snippets) | | [Molecule Studio](https://github.com/AniMathIO/plugins/tree/HEAD/community/molecule) | AniMathIO | Self-drawing 2D molecular structures and reactions from SMILES, with CPK colors and wedge/dash stereo | MIT | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/molecule) | | [Net Lab](https://github.com/AniMathIO/plugins/tree/HEAD/community/network) | AniMathIO | Animate ARP, ICMP ping, TCP, DHCP, DNS and traceroute over teaching topologies | MIT | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/network) | +| [Physics Play](https://github.com/AniMathIO/plugins/tree/HEAD/community/physics) | AniMathIO | Deterministic 2D mechanics demos: projectile, pendulum, spring, collisions and falling stacks | MIT | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/physics) | | [Ray Optics](https://github.com/AniMathIO/plugins/tree/HEAD/community/optics) | AniMathIO | Animated lens and mirror rays, Snell refraction, total internal reflection and prism dispersion | MIT | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/optics) | diff --git a/community-plugins.json b/community-plugins.json index 51a8cf3..4b8df76 100644 --- a/community-plugins.json +++ b/community-plugins.json @@ -22,6 +22,16 @@ "license": "MIT", "min_abi": "1.1.0" }, + { + "id": "io.github.animathio.physics", + "name": "Physics Play", + "author": "AniMathIO", + "description": "Deterministic 2D mechanics demos: projectile, pendulum, spring, collisions and falling stacks", + "repo": "AniMathIO/plugins", + "path": "community/physics", + "license": "MIT", + "min_abi": "1.1.0" + }, { "id": "io.github.animathio.optics", "name": "Ray Optics", diff --git a/community/physics/Cargo.lock b/community/physics/Cargo.lock new file mode 100644 index 0000000..c4e765f --- /dev/null +++ b/community/physics/Cargo.lock @@ -0,0 +1,834 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "auditable-serde" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7bf8143dfc3c0258df908843e169b5cc5fcf76c7718bd66135ef4a9cd558c5" +dependencies = [ + "semver", + "serde", + "serde_json", + "topological-sort", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[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-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "physics" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[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 = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[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 = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "topological-sort" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea68304e134ecd095ac6c3574494fc62b909f416c4fca77e440530221e549d3d" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "wasm-encoder" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bb72f02e7fbf07183443b27b0f3d4144abf8c114189f2e088ed95b696a7822" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce1ef0faabbbba6674e97a56bee857ccddf942785a336c8b47b42373c922a91d" +dependencies = [ + "anyhow", + "auditable-serde", + "flate2", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "url", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f51cad774fb3c9461ab9bccc9c62dfb7388397b5deda31bf40e8108ccd678b2" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e7091ed6c9abfa4e0a2ef3b39d0539da992d841fcf32c255f64fb98764ffee5" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "398c650cec1278cfb72e214ba26ef3440ab726e66401bd39c04f465ee3979e6b" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68faed92ae696b93ea9a7b67ba6c37bf09d72c6d9a70fa824a743c3020212f11" +dependencies = [ + "bitflags", + "futures", + "once_cell", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83903c8dcd8084a8a67ae08190122cf0e25dc37bdc239070a00f47e22d3f0aae" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7bf7f20495bcc7dc9f24c5fbcac9e919ca5ebdb7a1b1841d74447d3c8dd0c60" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "635c3adc595422cbf2341a17fb73a319669cc8d33deed3a48368a841df86b676" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddf445ed5157046e4baf56f9138c124a0824d4d1657e7204d71886ad8ce2fc11" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/community/physics/Cargo.toml b/community/physics/Cargo.toml new file mode 100644 index 0000000..ed19102 --- /dev/null +++ b/community/physics/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "physics" +version = "0.1.0" +edition = "2021" +license = "MIT" +publish = false + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +wit-bindgen = "=0.40.0" + +[profile.release] +opt-level = 3 +lto = true +strip = "debuginfo" + +[workspace] diff --git a/community/physics/NOTICE b/community/physics/NOTICE new file mode 100644 index 0000000..726808a --- /dev/null +++ b/community/physics/NOTICE @@ -0,0 +1,23 @@ +Physics Play for AniMathIO +Copyright (c) 2026 AniMathIO contributors. MIT (see ../../LICENSE). + +Scene inspiration +manim-physics, Matheart and contributors +https://github.com/Matheart/manim-physics/tree/d37580e07ac67d06c8dfbb78804b8a0256d1502b +Copyright (c) 2021 Matheart and manim-physics contributors. +MIT License, reproduced in assets/manim-physics-LICENSE. + +Studied the rigid mechanics examples and pendulum demo for the scene ideas. +Physics Play implements its vector drawings, projectile and spring formulas, +nonlinear pendulum, and disk and domino contact models in Rust. No manim-physics +source, artwork, Python, Manim or pymunk is incorporated. + +WASM feasibility spike +Rapier (rapier2d 0.36.1, commit 3406750a38286a0d3c7d0f4be2f9d53153e81d90) +https://github.com/dimforge/rapier/tree/v0.36.1 +Apache License 2.0. + +Evaluated Rapier with enhanced-determinism for disk and domino contacts in the +AniMathIO WASM sandbox. The prototype built and rendered short scenes, but +trapped when replaying its largest 30-second scenes. The released component +uses an original bounded solver and neither bundles nor links Rapier or Parry. diff --git a/community/physics/README.md b/community/physics/README.md new file mode 100644 index 0000000..a959d94 --- /dev/null +++ b/community/physics/README.md @@ -0,0 +1,107 @@ +# Physics Play + +Physics Play adds five keyframeable mechanics demos to AniMathIO. Draw a family of +projectile trajectories, compare pendulum and spring periods, measure momentum +in elastic and inelastic collisions, or watch a row of dominoes topple. + +Plugin ID `io.github.animathio.physics` · ABI 1.1.0 · MIT + +| Projectile | Pendulum | Spring | +| --- | --- | --- | +| ![Projectile paths with velocity arrows](screenshots/projectile-050.png) | ![Pendulum with a trail and period readout](screenshots/pendulum-050.png) | ![Spring with an equilibrium marker](screenshots/spring-050.png) | + +| Default collision | Elastic collision | Fully inelastic collision | Dominoes | +| --- | --- | --- | --- | +| ![Six disks in motion at two seconds](screenshots/collision-050.png) | ![Elastic collision transfers the launch velocity](screenshots/collision-elastic.png) | ![Inelastic collision shares the launch velocity](screenshots/collision-inelastic.png) | ![Dominoes partway through the chain reaction](screenshots/stack-chain.png) | + +![The launcher and domino row at 2.4 seconds with restitution set to 0.1](screenshots/stack-soft.png) + +## Use in AniMathIO + +Add **Physics Play** from the Library and choose a **Scene** in the inspector. +Keyframe **Progress** from 0 at the start of the clip to 1 at the end. **Duration** +sets the simulated seconds covered by that interval. Linear keyframes give a +constant simulation rate. Adjust the keyframes to slow down an impact or play +a scene in reverse. + +Each frame starts with the parameters sampled at that frame. For example, a +gravity keyframe changes the entire computed trajectory for that frame. + +| Scene | Motion and readouts | +| --- | --- | +| `projectile` | Highlights the selected launch angle and shows that body's height or landing range. With multiple bodies, secondary paths fan out by up to 9° on each side. Velocity arrows shorten or disappear near the floor or another ball. | +| `pendulum` | A bob released from rest. Shows the current angle and the full-amplitude period from the elliptic-integral formula. | +| `spring` | A vertical Hooke oscillator released from rest at 30% beyond equilibrium. The spring is tuned so its static extension equals **Length**. Shows its period and extension. | +| `collision` | Equal-mass disks in a 12 × 5 m arena. Shows their total momentum and translational kinetic energy. The momentum readout flags exchanges with the arena and the effect of gravity. | +| `stack` | A rolling ball tips the first domino. At low restitution the ball can keep rolling and make contact again. Contacts trigger the remaining dominoes, and the readout counts how many have tipped past 0.6 radians. | + +To compare collision types, set **Bodies** to 2, **Speed** to 5 m/s, +**Gravity** and **Friction** to 0, **Duration** to 1 s and **Progress** to 0.85. +At 0.85 s the first collision is over and the walls have yet to act. +With 1 kg disks, momentum is 5 kg·m/s in both cases. +**Restitution** 1 transfers the launch velocity to the second disk while +preserving 12.5 J of kinetic energy. **Restitution** 0 leaves both disks moving +at 2.5 m/s with 6.25 J in total. + +## Parameters + +| ID | Default | Meaning | +| --- | --- | --- | +| `scene` | `projectile` | `projectile`, `pendulum`, `spring`, `collision`, or `stack` | +| `progress` | 1 | 0–1, fraction of the simulated duration | +| `duration_s` | 4 | 0.5–30 simulated seconds | +| `gravity` | 9.81 | 0–30 m/s² downward acceleration | +| `bodies` | 6 | 1–12 projectiles, collision disks or dominoes. Rounded to an integer. | +| `mass` | 1 | 0.1–10 kg per disk for collision momentum and energy. Changing all disk masses together leaves the equal-mass trajectories unchanged. | +| `speed` | 15 | 0–40 m/s initial speed for projectiles, the first disk, or the domino launcher | +| `angle_deg` | 45 | 0–90° launch angle or pendulum release angle | +| `length_m` | 1.5 | 0.2–10 m pendulum length or spring equilibrium extension | +| `restitution` | 0.8 | 0–1 coefficient of restitution for disk contacts, the launcher’s contact with the first domino and impact transfer in the domino row | +| `friction` | 0 | 0–1 tangential friction for disk contacts and rolling resistance in the domino launcher | +| `show_vectors` | true | Show velocity arrows | +| `show_trail` | true | Show motion traces | +| `show_ground` | true | Show the metre scale for projectile, collision and stack | +| `accent` | Amber | Color for the main body and its velocity arrow | + +With zero gravity, projectiles travel in straight lines and the pendulum and +spring stay at their release positions. The pendulum and spring are undamped. +The domino scene uses floor pivots and a simplified impulse transfer. The disk +solver models translational contact impulses and friction. + +## Build and verify + +```sh +rustup target add wasm32-wasip2 +bash community/physics/build.sh +# Output: community/physics/target/physics.amplugin +``` + +Set `ANIMATHIO_PLUGIN_DIR` to the absolute directory containing the bundle. +When using this override, include the other plugins needed by your projects. + +```sh +CARGO_BUILD_JOBS=2 CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 19 ionice -c3 cargo test --manifest-path community/physics/Cargo.toml --locked +python3 community/physics/smoke.py /path/to/animathio-cli community/physics/target +``` + +The native tests check analytic motion, scene readouts, collision momentum and energy, +domino propagation and separation, deterministic replay and operation counts. The smoke test uses the +released 2.3.0 CLI and checks every scene at five progress values, including a +host-sampled keyframe and repeated 30-second renders with 12 bodies. It checks +the background and body colors so an error placeholder fails the test. Add +`--screenshots` to regenerate the PNGs in [screenshots](screenshots/). The +stress summary measures elapsed CLI time, including startup and PNG encoding. + +## Simulation and credits + +Projectile and spring positions use closed-form equations. The pendulum uses a +fourth-order Runge–Kutta stepper on at most one quarter period, then applies +symmetry. The disk and domino scenes replay from zero on a fixed grid of up to +3,600 steps. Disk work is bounded by 66 pair checks per step, and traces and ruler +graduations have explicit bounds. With the same parameters and canvas, seek order +and prior calls have no effect. Labels use the host's vector text command. + +The scene selection draws on [manim-physics](https://github.com/Matheart/manim-physics). +The Rapier WASM spike exceeded the sandbox budget in the heaviest 30-second cases, +so the component uses a small purpose-built solver. Credits and details of what +was studied are in [NOTICE](NOTICE). diff --git a/community/physics/assets/manim-physics-LICENSE b/community/physics/assets/manim-physics-LICENSE new file mode 100644 index 0000000..22ce4a7 --- /dev/null +++ b/community/physics/assets/manim-physics-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Matheart and manim-physics contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/community/physics/build.sh b/community/physics/build.sh new file mode 100644 index 0000000..8d67fae --- /dev/null +++ b/community/physics/build.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +export CARGO_BUILD_JOBS=2 CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0 +runner=(cargo) +if [[ "$OSTYPE" == linux* ]]; then runner=(nice -n 19 ionice -c3 cargo); fi +"${runner[@]}" build --target wasm32-wasip2 --release --locked +python3 - <<'PACKAGE' +import os, pathlib, tomllib, zipfile +root = pathlib.Path('.') +name = tomllib.loads((root / 'Cargo.toml').read_text())['package']['name'] +out = root / 'target' / (name + '.amplugin') +out.parent.mkdir(exist_ok=True) +with zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) as z: + z.write('plugin.toml', 'plugin.toml') + z.write('NOTICE', 'NOTICE') + z.write('../../LICENSE', 'LICENSE') + z.write('assets/manim-physics-LICENSE', 'licenses/manim-physics-LICENSE') + build_dir = pathlib.Path(os.environ.get("CARGO_TARGET_DIR") or "target") + z.write(build_dir / "wasm32-wasip2" / "release" / f"{name.replace('-', '_')}.wasm", "plugin.wasm") +print(out) +PACKAGE diff --git a/community/physics/plugin.toml b/community/physics/plugin.toml new file mode 100644 index 0000000..b9eb831 --- /dev/null +++ b/community/physics/plugin.toml @@ -0,0 +1,7 @@ +api_version = "1.1.0" +id = "io.github.animathio.physics" +name = "Physics Play" +version = "0.1.0" +description = "Deterministic 2D mechanics demos: projectile, pendulum, spring, collisions and falling stacks" +kinds = ["clip-source"] +capabilities = [] diff --git a/community/physics/screenshots/collision-000.png b/community/physics/screenshots/collision-000.png new file mode 100644 index 0000000..28c16a1 Binary files /dev/null and b/community/physics/screenshots/collision-000.png differ diff --git a/community/physics/screenshots/collision-050.png b/community/physics/screenshots/collision-050.png new file mode 100644 index 0000000..7cc7e0f Binary files /dev/null and b/community/physics/screenshots/collision-050.png differ diff --git a/community/physics/screenshots/collision-100.png b/community/physics/screenshots/collision-100.png new file mode 100644 index 0000000..5effb04 Binary files /dev/null and b/community/physics/screenshots/collision-100.png differ diff --git a/community/physics/screenshots/collision-elastic.png b/community/physics/screenshots/collision-elastic.png new file mode 100644 index 0000000..6bcefce Binary files /dev/null and b/community/physics/screenshots/collision-elastic.png differ diff --git a/community/physics/screenshots/collision-inelastic.png b/community/physics/screenshots/collision-inelastic.png new file mode 100644 index 0000000..62beb0e Binary files /dev/null and b/community/physics/screenshots/collision-inelastic.png differ diff --git a/community/physics/screenshots/pendulum-000.png b/community/physics/screenshots/pendulum-000.png new file mode 100644 index 0000000..62a8bc7 Binary files /dev/null and b/community/physics/screenshots/pendulum-000.png differ diff --git a/community/physics/screenshots/pendulum-050.png b/community/physics/screenshots/pendulum-050.png new file mode 100644 index 0000000..b4c87db Binary files /dev/null and b/community/physics/screenshots/pendulum-050.png differ diff --git a/community/physics/screenshots/pendulum-100.png b/community/physics/screenshots/pendulum-100.png new file mode 100644 index 0000000..455b191 Binary files /dev/null and b/community/physics/screenshots/pendulum-100.png differ diff --git a/community/physics/screenshots/projectile-000.png b/community/physics/screenshots/projectile-000.png new file mode 100644 index 0000000..be94e75 Binary files /dev/null and b/community/physics/screenshots/projectile-000.png differ diff --git a/community/physics/screenshots/projectile-050.png b/community/physics/screenshots/projectile-050.png new file mode 100644 index 0000000..d90da6f Binary files /dev/null and b/community/physics/screenshots/projectile-050.png differ diff --git a/community/physics/screenshots/projectile-100.png b/community/physics/screenshots/projectile-100.png new file mode 100644 index 0000000..e49864c Binary files /dev/null and b/community/physics/screenshots/projectile-100.png differ diff --git a/community/physics/screenshots/spring-000.png b/community/physics/screenshots/spring-000.png new file mode 100644 index 0000000..01b0c88 Binary files /dev/null and b/community/physics/screenshots/spring-000.png differ diff --git a/community/physics/screenshots/spring-050.png b/community/physics/screenshots/spring-050.png new file mode 100644 index 0000000..2a358cf Binary files /dev/null and b/community/physics/screenshots/spring-050.png differ diff --git a/community/physics/screenshots/spring-100.png b/community/physics/screenshots/spring-100.png new file mode 100644 index 0000000..9c43ea3 Binary files /dev/null and b/community/physics/screenshots/spring-100.png differ diff --git a/community/physics/screenshots/stack-000.png b/community/physics/screenshots/stack-000.png new file mode 100644 index 0000000..bcdb2f3 Binary files /dev/null and b/community/physics/screenshots/stack-000.png differ diff --git a/community/physics/screenshots/stack-050.png b/community/physics/screenshots/stack-050.png new file mode 100644 index 0000000..7a8475e Binary files /dev/null and b/community/physics/screenshots/stack-050.png differ diff --git a/community/physics/screenshots/stack-100.png b/community/physics/screenshots/stack-100.png new file mode 100644 index 0000000..ae197d7 Binary files /dev/null and b/community/physics/screenshots/stack-100.png differ diff --git a/community/physics/screenshots/stack-chain.png b/community/physics/screenshots/stack-chain.png new file mode 100644 index 0000000..0631f67 Binary files /dev/null and b/community/physics/screenshots/stack-chain.png differ diff --git a/community/physics/screenshots/stack-soft.png b/community/physics/screenshots/stack-soft.png new file mode 100644 index 0000000..e91afeb Binary files /dev/null and b/community/physics/screenshots/stack-soft.png differ diff --git a/community/physics/smoke.py b/community/physics/smoke.py new file mode 100644 index 0000000..2748825 --- /dev/null +++ b/community/physics/smoke.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Render Physics Play in a released AniMathIO sandbox and check the resulting pixels.""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import time +import zipfile + +from PIL import Image + +ROOT = Path(__file__).resolve().parent +WORK = ROOT / 'target' / 'smoke' +PLUGIN_ID = 'io.github.animathio.physics' +BACKGROUND = (17, 20, 28) +AMBER = (240, 150, 40) +FOREGROUND = (226, 229, 235) +SCENES = ('projectile', 'pendulum', 'spring', 'collision', 'stack') +TICKS_PER_SECOND = 705_600_000 + + +def check_pixels(image, name, accent, require_launcher): + colors = dict((rgb, count) for count, rgb in image.getcolors(image.width * image.height)) + # Host render can return success for a checkerboard with error text. Require + # the actual project background and a solid patch of the plugin's body color. + assert colors.get(BACKGROUND, 0) > image.width * image.height // 2, ( + f'{name}: expected the project background around the scene' + ) + if accent is not None: + assert colors.get(accent, 0) > 30, f'{name}: no physics body colored {accent}' + if require_launcher: + assert colors.get(AMBER, 0) > 30, f'{name}: launcher is out of frame' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('cli', type=Path) + parser.add_argument('plugin_dir', type=Path, help='directory containing physics.amplugin') + parser.add_argument('--screenshots', action='store_true') + args = parser.parse_args() + cli = args.cli.resolve() + plugins = args.plugin_dir.resolve() + if not any(plugins.glob('*.amplugin')): + parser.error(f'no .amplugin in {plugins}') + + WORK.mkdir(parents=True, exist_ok=True) + env = dict( + os.environ, + ANIMATHIO_PLUGIN_DIR=str(plugins), + ANIMATHIO_PLUGIN_SETTINGS=str(WORK / 'community-plugins.json'), + ANIMATHIO_USER_PLUGIN_DIR=str(WORK / 'user-plugins'), + XDG_CONFIG_HOME=str(WORK / 'config'), + XDG_CACHE_HOME=str(WORK / 'cache'), + XDG_DATA_HOME=str(WORK / 'data'), + ANIMATHIO_AUDIO='none', + ) + + def run(*cmd): + start = time.perf_counter() + result = subprocess.run([cli, *map(str, cmd)], env=env, text=True, + capture_output=True, timeout=30) + if result.returncode or 'warning:' in result.stderr.lower(): + raise RuntimeError(f'{cmd}\n{result.stdout}{result.stderr}') + return time.perf_counter() - start + + sample = WORK / 'sample.amio' + sample.unlink(missing_ok=True) + run('new-sample', '-o', sample) + with zipfile.ZipFile(sample) as bundle: + project = json.loads(bundle.read('project.json')) + project.update(assets={}, width=1280, height=720, background=[*BACKGROUND, 255]) + project['tracks'] = project['tracks'][:1] + clip = project['tracks'][0]['clips']['1'] + clip.update(animations=[], effects=[]) + clip['range']['end'] = 30 * TICKS_PER_SECOND + + worst_stress = (0.0, '') + + def render(name, *, frame=0, expected_accent=AMBER, require_launcher=False, **params): + nonlocal worst_stress + clip['kind'] = {'Plugin': {'plugin_id': PLUGIN_ID, 'params': params}} + path = WORK / f'{name}.amio' + with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) as bundle: + bundle.writestr('project.json', json.dumps(project)) + png = WORK / f'{name}.png' + png.unlink(missing_ok=True) + elapsed = run('render', path, '--frame', frame, '-o', png) + if params.get('duration_s') == 30: + worst_stress = max(worst_stress, (elapsed, name)) + with Image.open(png) as result: + image = result.convert('RGB') + # The launcher can roll out of frame after impact. Require a domino + # for stack frames and the highlighted body color for other scenes. + body_color = FOREGROUND if params.get('scene') == 'stack' else expected_accent + check_pixels(image, name, body_color, require_launcher) + print('PASS', name) + return image.tobytes() + + frames = {} + screenshots = [] + for scene in SCENES: + for progress in (0, 25, 50, 75, 100): + name = f'{scene}-{progress:03}' + frames[name] = render(name, scene=scene, progress=progress / 100) + if progress in (0, 50, 100): + screenshots.append(name) + assert len({frames[f'{scene}-{p:03}'] for p in (0, 25, 50, 75, 100)}) == 5, scene + + midpoint = dict(scene='projectile', progress=0.5) + for key in ('show_vectors', 'show_trail', 'show_ground'): + assert frames['projectile-050'] != render(key, **midpoint, **{key: False}) + assert frames['projectile-050'] != render('moon', **midpoint, gravity=1.62) + green = (61, 199, 120) + render('custom-accent', **midpoint, accent=[*green, 255], expected_accent=green) + assert frames['pendulum-050'] != render('long-pendulum', scene='pendulum', progress=0.5, length_m=4) + assert frames['spring-050'] != render('fast-spring', scene='spring', progress=0.5, gravity=20) + + isolated = dict(scene='collision', bodies=2, duration_s=1, progress=0.85, + gravity=0, friction=0, speed=5) + elastic = render('collision-elastic', **isolated, restitution=1) + inelastic = render('collision-inelastic', **isolated, restitution=0) + assert elastic != inelastic + assert elastic != render('double-mass', **isolated, restitution=1, mass=2) + render('stack-chain', scene='stack', progress=0.1, bodies=8) + render('stack-soft', scene='stack', progress=0.6, restitution=0.1, require_launcher=True) + screenshots += ['collision-elastic', 'collision-inelastic', 'stack-chain', 'stack-soft'] + + # Force maximum-size worlds to run inside the released host's 50M fuel, + # 64 MiB and epoch limits. Exercise busy contacts as well as default material. + for scene in SCENES: + render(f'max-{scene}', scene=scene, duration_s=30, progress=1, bodies=12) + for scene in ('collision', 'stack'): + for gravity, restitution, friction in ((0, 1, 0), (30, 1, 0), (30, 0, 1)): + name = f'{scene}-stress-{gravity}-{restitution}-{friction}' + params = dict(scene=scene, duration_s=30, progress=1, bodies=12, speed=40, + gravity=gravity, restitution=restitution, friction=friction) + original = render(name, **params) + assert original == render(f'{name}-repeat', **params) + # Largest projectile extent has subpixel bodies. The project background + # still distinguishes the vector render from a sandbox placeholder. + render('wide-trajectory', scene='projectile', duration_s=30, progress=1, + speed=40, bodies=12, gravity=0, expected_accent=None) + render('no-gravity', scene='pendulum', gravity=0) + render('flat-angle', scene='projectile', angle_deg=0, bodies=1, progress=0.5) + render('stationary-projectile', scene='projectile', speed=0, progress=0.5) + render('single-body', scene='collision', bodies=1) + + clip['animations'] = [{'target': {'Param': 'progress'}, 'keys': { + '0': {'value': {'Number': 0.0}, 'interpolation': 'Linear'}, + str(TICKS_PER_SECOND): {'value': {'Number': 1.0}, 'interpolation': 'Hold'}, + }}] + assert frames['stack-050'] == render('keyframed', frame=15, scene='stack', progress=0) + clip['animations'] = [] + assert frames['projectile-100'] == render('defaults') + + if args.screenshots: + out = ROOT / 'screenshots' + out.mkdir(exist_ok=True) + for name in screenshots: + with Image.open(WORK / f'{name}.png') as image: + image.save(out / f'{name}.png', optimize=True) + elapsed, name = worst_stress + print(f'Slowest 30-second scene: {elapsed:.3f} s ({name}, including CLI startup and PNG encoding)') + print('All released-host checks passed') + + +if __name__ == '__main__': + main() diff --git a/community/physics/src/analytic.rs b/community/physics/src/analytic.rs new file mode 100644 index 0000000..e1b1c81 --- /dev/null +++ b/community/physics/src/analytic.rs @@ -0,0 +1,137 @@ +//! Closed-form and fixed-step deterministic motion. Everything here is a pure +//! function of its arguments: the same parameters and time always produce the +//! same state, which is what makes `render_clip` deterministic. + +const PENDULUM_HZ: f64 = 240.0; + +/// Position of a projectile launched from the origin (metres; ground at y = 0) +/// with speed `v` at `angle_deg` under gravity `g`, at time `t` seconds. +pub fn projectile_position(v: f64, angle_deg: f64, g: f64, t: f64) -> (f64, f64) { + let a = angle_deg.to_radians(); + (v * a.cos() * t, v * a.sin() * t - 0.5 * g * t * t) +} + +/// Velocity of the same projectile at time `t` (metres per second). +pub fn projectile_velocity(v: f64, angle_deg: f64, g: f64, t: f64) -> (f64, f64) { + let a = angle_deg.to_radians(); + (v * a.cos(), v * a.sin() - g * t) +} + +/// Total flight time until the projectile returns to its launch height, or `None` +/// without gravity. Launching horizontally from the ground lands immediately. +pub fn flight_time(v: f64, angle_deg: f64, g: f64) -> Option { + if g <= 0.0 { + return None; + } + let upward = v * angle_deg.to_radians().sin(); + Some(2.0 * upward.max(0.0) / g) +} + +/// Complete elliptic integral of the first kind K(m) (m = k²), computed with the +/// arithmetic-geometric mean, which converges quadratically. Deterministic and +/// accurate to double precision in well under 24 iterations. +pub fn elliptic_k(m: f64) -> f64 { + let m = m.clamp(0.0, 0.999_999); + let (mut a, mut b) = (1.0_f64, (1.0 - m).sqrt()); + for _ in 0..24 { + let next = 0.5 * (a + b); + b = (a * b).sqrt(); + a = next; + } + std::f64::consts::FRAC_PI_2 / a +} + +/// Exact pendulum period for a release from rest at `theta0_deg`: +/// T = 4·K(sin²(θ₀/2))·√(L/g). Reduces to the small-angle 2π√(L/g) as θ₀ → 0. +pub fn pendulum_period(length_m: f64, g: f64, theta0_deg: f64) -> f64 { + if g <= 0.0 || length_m <= 0.0 { + return f64::INFINITY; + } + let m = (0.5 * theta0_deg.to_radians()).sin().powi(2); + 4.0 * elliptic_k(m) * (length_m / g).sqrt() +} + +/// One classic RK4 step of θ'' = −(g/L)·sinθ over `h` seconds. +fn pendulum_rk4(theta: f64, omega: f64, g_over_l: f64, h: f64) -> (f64, f64) { + let acc = |th: f64| -g_over_l * th.sin(); + let k1t = omega; + let k1w = acc(theta); + let k2t = omega + 0.5 * h * k1w; + let k2w = acc(theta + 0.5 * h * k1t); + let k3t = omega + 0.5 * h * k2w; + let k3w = acc(theta + 0.5 * h * k2t); + let k4t = omega + h * k3w; + let k4w = acc(theta + h * k3t); + ( + theta + h / 6.0 * (k1t + 2.0 * k2t + 2.0 * k3t + k4t), + omega + h / 6.0 * (k1w + 2.0 * k2w + 2.0 * k3w + k4w), + ) +} + +/// Use the period and symmetry to integrate at most one quarter swing. RK4 +/// resolves the nonlinear motion and the last step reaches the requested time. +pub fn pendulum_state(theta0: f64, g_over_l: f64, period: f64, time: f64) -> (f64, f64) { + if !period.is_finite() || theta0 == 0.0 { + return (theta0, 0.0); + } + let phase = time % period; + let half = period * 0.5; + let quarter = period * 0.25; + let (elapsed, angle_sign, speed_sign) = if phase < quarter { + (phase, 1.0, 1.0) + } else if phase < half { + (half - phase, -1.0, 1.0) + } else if phase < half + quarter { + (phase - half, -1.0, -1.0) + } else { + (period - phase, 1.0, -1.0) + }; + let steps = (elapsed * PENDULUM_HZ).ceil() as usize; + let dt = elapsed / steps.max(1) as f64; + let (mut theta, mut omega) = (theta0, 0.0); + for _ in 0..steps { + (theta, omega) = pendulum_rk4(theta, omega, g_over_l, dt); + } + (angle_sign * theta, speed_sign * omega) +} + +/// Bob position for a pivot at the origin (metres; y up, down is negative). +pub fn pendulum_bob(length_m: f64, theta: f64) -> (f64, f64) { + (length_m * theta.sin(), -length_m * theta.cos()) +} + +/// Bob velocity for angular state (θ, ω): the tangential vector ω·L. +pub fn pendulum_velocity(length_m: f64, theta: f64, omega: f64) -> (f64, f64) { + ( + omega * length_m * theta.cos(), + omega * length_m * theta.sin(), + ) +} + +/// Mechanical energy per unit mass of the pendulum (J/kg): ½(L·ω)² + g·L·(1−cos θ). +/// Test helper for the RK4 energy-conservation check. +#[cfg(test)] +pub fn pendulum_energy(length_m: f64, g: f64, theta: f64, omega: f64) -> f64 { + 0.5 * (length_m * omega).powi(2) + g * length_m * (1.0 - theta.cos()) +} + +/// Undamped spring-mass offset from equilibrium, released from rest `amplitude` +/// metres below equilibrium: A·cos(ωt) (positive = further down). +pub fn spring_offset(amplitude: f64, omega: f64, t: f64) -> f64 { + amplitude * (omega * t).cos() +} + +/// Spring-mass velocity at time `t` (metres per second, positive = down). +pub fn spring_velocity(amplitude: f64, omega: f64, t: f64) -> f64 { + -amplitude * omega * (omega * t).sin() +} + +/// Undamped spring angular frequency for the tuned spring: ω = √(g/L). The spring +/// constant is chosen so the static stretch equals `length_m`, which makes the +/// spring period equal the small-angle pendulum period of the same length. +pub fn spring_omega(length_m: f64, g: f64) -> f64 { + if g <= 0.0 || length_m <= 0.0 { + return 0.0; + } + (g / length_m).sqrt() +} diff --git a/community/physics/src/draw.rs b/community/physics/src/draw.rs new file mode 100644 index 0000000..53289c3 --- /dev/null +++ b/community/physics/src/draw.rs @@ -0,0 +1,370 @@ +//! Scene emission: world-to-canvas fitting and the drawing primitives every scene +//! shares (bodies, arrows, dashed trails, tick-marked ground, readout text). + +use super::{ + Color, DrawCommand, PathVerb, Point, Size, StrokeCap, StrokeJoin, StrokeStyle, TextAlignment, + TextElement, +}; + +/// Axis-aligned bounding box in world coordinates (metres, y up). +#[derive(Clone, Copy, Debug)] +pub struct Extent { + pub min_x: f64, + pub min_y: f64, + pub max_x: f64, + pub max_y: f64, +} + +impl Extent { + pub fn new() -> Self { + Extent { + min_x: f64::INFINITY, + min_y: f64::INFINITY, + max_x: f64::NEG_INFINITY, + max_y: f64::NEG_INFINITY, + } + } + pub fn add(&mut self, x: f64, y: f64) { + self.min_x = self.min_x.min(x); + self.min_y = self.min_y.min(y); + self.max_x = self.max_x.max(x); + self.max_y = self.max_y.max(y); + } + pub fn pad(&mut self, m: f64) { + self.min_x -= m; + self.min_y -= m; + self.max_x += m; + self.max_y += m; + } + /// Degenerate boxes become small finite squares so fitting stays finite. + pub fn sanitized(mut self) -> Self { + let min_side = 0.5; + if self.max_x - self.min_x < min_side { + let c = (self.min_x + self.max_x) * 0.5; + self.min_x = c - min_side * 0.5; + self.max_x = c + min_side * 0.5; + } + if self.max_y - self.min_y < min_side { + let c = (self.min_y + self.max_y) * 0.5; + self.min_y = c - min_side * 0.5; + self.max_y = c + min_side * 0.5; + } + self + } +} + +impl Default for Extent { + fn default() -> Self { + Self::new() + } +} + +/// Maps world metres (y up) to canvas pixels (y down) with a uniform scale, so the +/// scene is resolution-independent: the same metres-per-canvas-height at any size. +#[derive(Clone, Copy, Debug)] +pub struct View { + scale: f64, + tx: f64, + ty: f64, +} + +impl View { + /// Fit `extent` into the canvas leaving `margin` of each edge free (fraction of + /// the corresponding canvas dimension). + pub fn fit(extent: &Extent, size: Size, margin: f64) -> Self { + let w = (extent.max_x - extent.min_x).max(1e-6); + let h = (extent.max_y - extent.min_y).max(1e-6); + let scale = ((size.width as f64 * (1.0 - 2.0 * margin)) / w) + .min(size.height as f64 * (1.0 - 2.0 * margin) / h) + .max(1e-6); + let center_x = (extent.min_x + extent.max_x) * 0.5; + let center_y = (extent.min_y + extent.max_y) * 0.5; + View { + scale, + tx: size.width as f64 * 0.5 - center_x * scale, + ty: size.height as f64 * 0.5 + center_y * scale, + } + } + pub fn point(&self, x: f64, y: f64) -> Point { + Point { + x: (self.tx + x * self.scale) as f32, + y: (self.ty - y * self.scale) as f32, + } + } + /// Canvas length of a world distance. + pub fn dist(&self, meters: f64) -> f32 { + (meters * self.scale) as f32 + } +} + +const KAPPA: f32 = 0.552_284_8; + +/// A circle as four cubic Béziers, canvas pixels. +pub fn circle_path(cx: f32, cy: f32, r: f32) -> Vec { + let k = KAPPA * r; + let p = |x: f32, y: f32| Point { x, y }; + vec![ + PathVerb::MoveTo(p(cx + r, cy)), + PathVerb::CubicTo((p(cx + r, cy + k), p(cx + k, cy + r), p(cx, cy + r))), + PathVerb::CubicTo((p(cx - k, cy + r), p(cx - r, cy + k), p(cx - r, cy))), + PathVerb::CubicTo((p(cx - r, cy - k), p(cx - k, cy - r), p(cx, cy - r))), + PathVerb::CubicTo((p(cx + k, cy - r), p(cx + r, cy - k), p(cx + r, cy))), + PathVerb::Close, + ] +} + +/// An open polyline (or closed polygon) through canvas points. +pub fn polyline(points: &[Point], closed: bool) -> Vec { + let mut path = Vec::with_capacity(points.len() + 1); + for (index, point) in points.iter().enumerate() { + if index == 0 { + path.push(PathVerb::MoveTo(*point)); + } else { + path.push(PathVerb::LineTo(*point)); + } + } + if closed && points.len() > 2 { + path.push(PathVerb::Close); + } + path +} + +/// The four corners of a rotated box, canvas pixels. +pub fn box_corners(cx: f64, cy: f64, hx: f64, hy: f64, angle: f64, view: &View) -> Vec { + let (sin, cos) = angle.sin_cos(); + let local = [(hx, hy), (-hx, hy), (-hx, -hy), (hx, -hy)]; + local + .iter() + .map(|(dx, dy)| view.point(cx + dx * cos - dy * sin, cy + dx * sin + dy * cos)) + .collect() +} + +#[cfg(test)] +pub fn rgb(r: u8, g: u8, b: u8, a: u8) -> Color { + Color { r, g, b, a } +} + +pub fn with_alpha(mut c: Color, a: u8) -> Color { + c.a = a; + c +} + +pub fn arrow_head(width: f32) -> (f32, f32) { + let length = width * 3.0 + 7.0; + (length, length * 0.42) +} + +pub const FOREGROUND: Color = Color { + r: 226, + g: 229, + b: 235, + a: 255, +}; +pub const MUTED: Color = Color { + r: 124, + g: 132, + b: 143, + a: 255, +}; +pub const TRAIL: Color = Color { + r: 126, + g: 158, + b: 196, + a: 255, +}; + +pub struct Painter { + pub elements: Vec, +} + +impl Painter { + pub fn new() -> Self { + Painter { + elements: Vec::new(), + } + } + pub fn fill(&mut self, path: Vec, color: Color) { + if path.len() > 1 { + self.elements.push(DrawCommand::FillPath((path, color))); + } + } + pub fn stroke(&mut self, path: Vec, width: f32, color: Color) { + if path.len() > 1 && width > 0.0 { + self.elements.push(DrawCommand::StrokePath(( + path, + StrokeStyle { + width, + color, + cap: StrokeCap::Round, + join: StrokeJoin::Round, + }, + ))); + } + } + pub fn line(&mut self, from: Point, to: Point, width: f32, color: Color) { + self.stroke(polyline(&[from, to], false), width, color); + } + /// An arrow from `from` to `to` (canvas pixels): round-cap shaft plus a filled + /// triangular head sized to the shaft width. + pub fn arrow(&mut self, from: Point, to: Point, width: f32, color: Color) { + let dx = to.x - from.x; + let dy = to.y - from.y; + let len = (dx * dx + dy * dy).sqrt(); + let (head, half) = arrow_head(width); + if len < head * 1.4 { + return; // too short to read as an arrow + } + let (ux, uy) = (dx / len, dy / len); + let shaft_end = Point { + x: to.x - ux * head * 0.9, + y: to.y - uy * head * 0.9, + }; + self.line(from, shaft_end, width, color); + let tip_a = Point { + x: to.x - ux * head - uy * half, + y: to.y - uy * head + ux * half, + }; + let tip_b = Point { + x: to.x - ux * head + uy * half, + y: to.y - uy * head - ux * half, + }; + self.fill(polyline(&[to, tip_a, tip_b], true), color); + } + /// A dashed polyline in canvas pixels, fixed pixel dash lengths so the rhythm + /// does not change with zoom. + pub fn dashed(&mut self, points: &[Point], width: f32, color: Color, on: f32, off: f32) { + if points.len() < 2 { + return; + } + // Scale the dashes on long paths to bound the number of emitted paths. + let length: f32 = points + .windows(2) + .map(|pair| (pair[1].x - pair[0].x).hypot(pair[1].y - pair[0].y)) + .sum(); + let factor = (length / ((on + off) * 96.0)).max(1.0); + let (on, off) = (on * factor, off * factor); + let mut segment: Vec = Vec::new(); + let mut drawing = true; + let mut remaining = on; + for pair in points.windows(2) { + let (ax, ay) = (pair[0].x, pair[0].y); + let (bx, by) = (pair[1].x, pair[1].y); + let mut seg_len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt(); + let (ux, uy) = ((bx - ax) / seg_len.max(1e-6), (by - ay) / seg_len.max(1e-6)); + let mut cursor = Point { x: ax, y: ay }; + while seg_len > 1e-3 { + let piece = seg_len.min(remaining); + let next = Point { + x: cursor.x + ux * piece, + y: cursor.y + uy * piece, + }; + if drawing { + if segment.is_empty() { + segment.push(cursor); + } + segment.push(next); + } + cursor = next; + seg_len -= piece; + remaining -= piece; + if remaining <= 1e-3 { + if drawing && segment.len() > 1 { + self.stroke(polyline(&segment, false), width, color); + } + segment.clear(); + drawing = !drawing; + remaining = if drawing { on } else { off }; + } + } + } + if drawing && segment.len() > 1 { + self.stroke(polyline(&segment, false), width, color); + } + } + /// Host-shaped text at canvas pixels; (`x`, `y`) is the top-left of the line box + /// after the alignment layout across the canvas width. + pub fn text( + &mut self, + text: &str, + align: TextAlignment, + x: f32, + y: f32, + size: f32, + color: Color, + ) { + if text.is_empty() { + return; + } + self.elements.push(DrawCommand::TextRun(TextElement { + align, + text: text.into(), + font_size: size.max(4.0), + x, + y, + color, + })); + } +} + +impl Default for Painter { + fn default() -> Self { + Self::new() + } +} + +/// A ground ruler with graduations in metres. Large ranges use coarser ticks. +pub fn draw_ground( + painter: &mut Painter, + view: &View, + x0: f64, + x1: f64, + label_every: u32, + canvas: Size, + tick_font: f32, +) { + let a = view.point(x0, 0.0); + let b = view.point(x1, 0.0); + painter.line(a, b, 3.0, MUTED); + let raw_step = ((x1 - x0) / 64.0).max(1.0); + let order = 10_f64.powf(raw_step.log10().floor()); + let ratio = raw_step / order; + let step = order + * if ratio <= 1.0 { + 1.0 + } else if ratio <= 2.0 { + 2.0 + } else if ratio <= 5.0 { + 5.0 + } else { + 10.0 + }; + let first = (x0 / step).ceil() as i64; + let last = (x1 / step).floor() as i64; + for index in first..=last { + let m = index * step as i64; + let tick = view.point(m as f64, 0.0); + let labeled = index % i64::from(label_every) == 0; + let height = if labeled { 12.0 } else { 6.0 }; + painter.line( + tick, + Point { + x: tick.x, + y: tick.y + height, + }, + 1.5, + with_alpha(MUTED, 200), + ); + if labeled { + // Center the label on the tick: offset from the canvas-centred layout. + let offset = tick.x - canvas.width as f32 * 0.5; + painter.text( + &m.to_string(), + TextAlignment::Center, + offset, + tick.y + 18.0, + tick_font, + with_alpha(MUTED, 220), + ); + } + } +} diff --git a/community/physics/src/lib.rs b/community/physics/src/lib.rs new file mode 100644 index 0000000..e418abf --- /dev/null +++ b/community/physics/src/lib.rs @@ -0,0 +1,726 @@ +//! Deterministic vector scenes for teaching 2D mechanics. +wit_bindgen::generate!({ path: "wit", world: "source-plugin" }); + +use animathio::plugin::types::*; + +mod analytic; +mod draw; +mod params; +mod sim; + +use draw::{ + box_corners, circle_path, polyline, with_alpha, Extent, Painter, View, FOREGROUND, MUTED, TRAIL, +}; +use params::*; + +pub const ACCENT_DEFAULT: Color = Color { + r: 240, + g: 150, + b: 40, + a: 255, +}; + +#[derive(Clone, Copy)] +enum Demo { + Projectile, + Pendulum, + Spring, + Collision, + Stack, +} + +struct Params { + scene: Demo, + progress: f64, + duration: f64, + gravity: f64, + bodies: usize, + mass: f64, + speed: f64, + angle_deg: f64, + length_m: f64, + restitution: f64, + friction: f64, + show_vectors: bool, + show_trail: bool, + show_ground: bool, + accent: Color, +} + +const SCENES: [(&str, Demo); 5] = [ + ("projectile", Demo::Projectile), + ("pendulum", Demo::Pendulum), + ("spring", Demo::Spring), + ("collision", Demo::Collision), + ("stack", Demo::Stack), +]; + +const DEFAULT_RESTITUTION: f64 = 0.8; +const DEFAULT_FRICTION: f64 = 0.0; +const VELOCITY_WIDTH: f32 = 2.5; + +fn read_params(list: &[ParamEntry]) -> Result { + let name = string(list, "scene", "projectile"); + let scene = SCENES + .iter() + .find(|(id, _)| *id == name) + .map(|(_, scene)| *scene) + .ok_or_else(|| error("Unsupported scene"))?; + Ok(Params { + scene, + progress: number(list, "progress", 1.0, 0.0, 1.0)?, + duration: number(list, "duration_s", 4.0, 0.5, 30.0)?, + gravity: number(list, "gravity", 9.81, 0.0, 30.0)?, + bodies: number(list, "bodies", 6.0, 1.0, sim::MAX_BODIES as f64)?.round() as usize, + mass: number(list, "mass", 1.0, 0.1, 10.0)?, + speed: number(list, "speed", 15.0, 0.0, 40.0)?, + angle_deg: number(list, "angle_deg", 45.0, 0.0, 90.0)?, + length_m: number(list, "length_m", 1.5, 0.2, 10.0)?, + restitution: number(list, "restitution", DEFAULT_RESTITUTION, 0.0, 1.0)?, + friction: number(list, "friction", DEFAULT_FRICTION, 0.0, 1.0)?, + show_vectors: boolean(list, "show_vectors", true), + show_trail: boolean(list, "show_trail", true), + show_ground: boolean(list, "show_ground", true), + accent: color(list, "accent", ACCENT_DEFAULT), + }) +} + +struct PhysicsPlay; + +impl Guest for PhysicsPlay { + fn describe() -> Manifest { + Manifest { + name: "Physics Play".into(), + version: "0.1.0".into(), + description: "Deterministic 2D mechanics demos: projectile, pendulum, spring, collisions and falling stacks".into(), + kinds: vec!["clip-source".into()], + metadata: vec![ + ("param.duration_s.unit".into(), "s".into()), + ("param.gravity.unit".into(), "m/s^2".into()), + ("param.mass.unit".into(), "kg".into()), + ("param.speed.unit".into(), "m/s".into()), + ("param.angle_deg.unit".into(), "degrees".into()), + ("param.length_m.unit".into(), "m".into()), + ], + params: vec![ + enum_param("scene", "Scene", &SCENES.map(|(name, _)| name), "projectile"), + num_param("progress", "Progress", 0.0, 1.0, 1.0, 0.01), + num_param("duration_s", "Duration (s)", 0.5, 30.0, 4.0, 0.1), + num_param("gravity", "Gravity (m/s^2)", 0.0, 30.0, 9.81, 0.01), + num_param("bodies", "Bodies", 1.0, sim::MAX_BODIES as f64, 6.0, 1.0), + num_param("mass", "Mass (kg)", 0.1, 10.0, 1.0, 0.1), + num_param("speed", "Speed (m/s)", 0.0, 40.0, 15.0, 0.1), + num_param("angle_deg", "Angle (deg)", 0.0, 90.0, 45.0, 1.0), + num_param("length_m", "Length (m)", 0.2, 10.0, 1.5, 0.1), + num_param("restitution", "Restitution", 0.0, 1.0, DEFAULT_RESTITUTION, 0.05), + num_param("friction", "Friction", 0.0, 1.0, DEFAULT_FRICTION, 0.05), + bool_param("show_vectors", "Velocity vectors", true), + bool_param("show_trail", "Trail", true), + bool_param("show_ground", "Ground scale", true), + color_param("accent", "Accent", ACCENT_DEFAULT), + ], + } + } + + fn render_clip( + params: Vec, + _time_ticks: i64, + size: Size, + ) -> Result { + render(¶ms, size) + } +} + +/// Space the secondary launches on either side of the selected angle, which +/// comes last so its body is on top when the paths overlap. +fn launch_angles(p: &Params) -> impl Iterator { + let angle = p.angle_deg; + let low = (angle - 9.0).max(0.0); + let high = (angle + 9.0).min(90.0); + let others = if p.speed == 0.0 { 0 } else { p.bodies - 1 }; + let right = if low == angle { + others + } else if high == angle { + 0 + } else { + others.div_ceil(2) + }; + let left = others - right; + (0..left) + .map(move |i| low + (angle - low) * i as f64 / left as f64) + .chain((1..=right).map(move |i| angle + (high - angle) * i as f64 / right as f64)) + .chain(std::iter::once(angle)) +} + +fn render(list: &[ParamEntry], size: Size) -> Result { + if size.width == 0 || size.height == 0 { + return Err(error("Canvas dimensions must be positive")); + } + let p = read_params(list)?; + let extent = extent_for(&p).sanitized(); + let view = View::fit(&extent, size, 0.07); + let sim_time = p.progress * p.duration; + let mut painter = Painter::new(); + match p.scene { + Demo::Projectile => draw_projectile(&mut painter, &view, &extent, &p, sim_time, size), + Demo::Pendulum => draw_pendulum(&mut painter, &view, &p, sim_time, size), + Demo::Spring => draw_spring(&mut painter, &view, &p, sim_time, size), + Demo::Collision => draw_collision(&mut painter, &view, &p, size), + Demo::Stack => draw_stack(&mut painter, &view, &extent, &p, size), + } + Ok(Scene { + coordinate_space: CoordinateSpace::Canvas, + elements: painter.elements, + }) +} + +/// Progress-independent framing: derived from parameters only, so the camera never +/// moves while progress scrubs. +fn extent_for(p: &Params) -> Extent { + match p.scene { + Demo::Projectile => { + let mut extent = Extent::new(); + let radius = projectile_radius(p.speed); + extent.add(0.0, 0.0); + for angle in launch_angles(p) { + let flight = analytic::flight_time(p.speed, angle, p.gravity) + .unwrap_or(p.duration) + .min(p.duration); + let apex = if p.gravity > 0.0 { + (p.speed * angle.to_radians().sin() / p.gravity).min(flight) + } else { + flight + }; + for time in [apex, flight] { + let (x, y) = analytic::projectile_position(p.speed, angle, p.gravity, time); + extent.add(x, y + radius); + } + } + extent.pad(radius + 0.4); + // Retain a metre scale even for a stationary ball or a ground launch. + extent.add(-1.5, -0.75); + extent.add(1.5, 1.5); + extent + } + Demo::Pendulum => { + let l = p.length_m; + let bob = (0.16 * l).clamp(0.06, 0.5); + let reach = (l * p.angle_deg.to_radians().sin()).abs().max(0.3 * l); + let mut extent = Extent::new(); + extent.add(-reach - bob, -l - bob); + extent.add(reach + bob, 0.12 * l); + extent + } + Demo::Spring => { + let l = p.length_m; + let amplitude = 0.3 * l; + let half = 0.12 * l; + let mut extent = Extent::new(); + extent.add(-0.55 * l, -l - amplitude - half - 0.15 * l); + extent.add(0.55 * l, 0.1 * l); + extent + } + Demo::Collision => { + let mut extent = Extent::new(); + extent.add(0.0, 0.0); + extent.add(sim::ARENA_W, sim::ARENA_H); + extent + } + Demo::Stack => { + let mut extent = Extent::new(); + extent.add(-2.4, -0.1); + extent.add(1.6 + sim::DOMINO_SPACING * p.bodies as f64, 2.0); + extent + } + } +} + +/// Canvas-space font sizes that follow the canvas short edge. +fn fonts(size: Size) -> (f32, f32) { + let short = size.width.min(size.height) as f32; + ( + (short * 0.034).clamp(11.0, 40.0), + (short * 0.021).clamp(9.0, 24.0), + ) +} + +fn readout_lines(painter: &mut Painter, lines: &[String], font: f32) { + for (index, line) in lines.iter().enumerate() { + painter.text( + line, + TextAlignment::Left, + 16.0, + 14.0 + index as f32 * font * 1.45, + font, + with_alpha(FOREGROUND, 235), + ); + } +} + +fn time_readout(painter: &mut Painter, size: Size, sim_time: f64, duration: f64, font: f32) { + painter.text( + &format!("t = {:.2} s / {:.2} s", sim_time, duration), + TextAlignment::Left, + 16.0, + size.height as f32 - font * 1.6, + font, + with_alpha(FOREGROUND, 235), + ); +} + +fn velocity_arrow( + painter: &mut Painter, + view: &View, + size: Size, + (x, y): (f64, f64), + (vx, vy): (f64, f64), + body_radius_m: f64, + accent: Color, +) { + if let Some((from, to)) = velocity_segment(view, size, (x, y), (vx, vy), body_radius_m) { + painter.arrow(from, to, VELOCITY_WIDTH, with_alpha(accent, 220)); + } +} + +fn velocity_segment( + view: &View, + size: Size, + (x, y): (f64, f64), + (vx, vy): (f64, f64), + body_radius_m: f64, +) -> Option<(Point, Point)> { + let speed = (vx * vx + vy * vy).sqrt(); + if speed < 2e-2 { + return None; + } + let short = size.width.min(size.height) as f64; + let radius_px = view.dist(body_radius_m) as f64; + let px_per_unit = short * 0.018; + // Long enough to leave the body: slow arrows must stay readable. + let min_len = radius_px + 16.0; + let len = (speed * px_per_unit).max(min_len).min(short * 0.45); + let (ux, uy) = (vx / speed, vy / speed); + let center = view.point(x, y); + let from = Point { + x: center.x + (ux * (radius_px + 2.0)) as f32, + y: center.y - (uy * (radius_px + 2.0)) as f32, + }; + // The shaft starts at the body edge; keep it long enough to read as an arrow. + let shaft = (len - radius_px).max(26.0); + let to = Point { + x: from.x + (ux * shaft) as f32, + y: from.y - (uy * shaft) as f32, + }; + Some((from, to)) +} + +/// Clip the vector along its original direction, allowing room for the head +/// and shaft. The painter omits vectors that become too short to read. +fn clip_projectile_vector( + from: Point, + to: Point, + ground_y: f32, + radius: f32, + other_balls: impl Iterator, +) -> Option { + let (dx, dy) = (to.x - from.x, to.y - from.y); + let mut length = dx.hypot(dy); + let (ux, uy) = (dx / length, dy / length); + let (head, half_head) = draw::arrow_head(VELOCITY_WIDTH); + let ground = ground_y - 1.5; + if from.y + VELOCITY_WIDTH / 2.0 > ground { + return None; + } + let tip_clearance = (ux.abs() * half_head - uy * head) + .max(VELOCITY_WIDTH / 2.0 - uy * head * 0.9) + .max(0.0); + let room = ground - from.y - tip_clearance; + if uy > 0.0 { + length = length.min(room / uy); + } + + // Enclose the arrow in a swept disk to clear each other ball at the head + // as well as along the shaft. + let clearance = radius + half_head.max(VELOCITY_WIDTH / 2.0) + 1.0; + for center in other_balls { + let (x, y) = (center.x - from.x, center.y - from.y); + let along = x * ux + y * uy; + let across = x * uy - y * ux; + let intersection = clearance * clearance - across * across; + if intersection > 0.0 { + let half_chord = intersection.sqrt(); + if along + half_chord >= 0.0 { + length = length.min(along - half_chord); + } + } + } + (length > 0.0 && length * uy <= room + 1e-3).then_some(Point { + x: from.x + ux * length, + y: from.y + uy * length, + }) +} + +fn trail_stroke(painter: &mut Painter, view: &View, points: &[(f64, f64)], color: Color) { + let canvas_points: Vec = points.iter().map(|(x, y)| view.point(*x, *y)).collect(); + painter.dashed(&canvas_points, 1.8, with_alpha(color, 165), 8.0, 6.5); +} + +fn projectile_radius(speed: f64) -> f64 { + (0.12 * speed.sqrt()).clamp(0.15, 0.6) +} + +fn draw_projectile( + painter: &mut Painter, + view: &View, + extent: &Extent, + p: &Params, + sim_time: f64, + size: Size, +) { + let (font, tick) = fonts(size); + if p.show_ground { + draw::draw_ground(painter, view, extent.min_x, extent.max_x, 5, size, tick); + } + let radius = projectile_radius(p.speed); + let radius_px = view.dist(radius); + let launches: Vec<_> = launch_angles(p) + .map(|angle| { + let (t, landed) = projectile_time(p, angle, sim_time); + let (x, y) = analytic::projectile_position(p.speed, angle, p.gravity, t); + (angle, t, landed, x, y.max(0.0)) + }) + .collect(); + let centers: Vec<_> = launches + .iter() + .map(|&(_, _, _, x, y)| view.point(x, y + radius)) + .collect(); + for (index, &(angle, t, _, _, _)) in launches.iter().enumerate() { + if p.show_trail && t > 0.0 { + let trace: Vec<_> = (0..=120) + .map(|step| { + let (x, y) = analytic::projectile_position( + p.speed, + angle, + p.gravity, + t * f64::from(step) / 120.0, + ); + (x, y + radius) + }) + .collect(); + let color = if index + 1 == launches.len() { + p.accent + } else { + TRAIL + }; + trail_stroke(painter, view, &trace, color); + } + } + let ground = view.point(0.0, 0.0).y; + for (index, &(angle, t, landed, x, y)) in launches.iter().enumerate() { + let highlight = index + 1 == launches.len(); + let color = if highlight { p.accent } else { FOREGROUND }; + let center = centers[index]; + let outline = circle_path(center.x, center.y, radius_px); + painter.fill(outline.clone(), color); + painter.stroke(outline, 1.5, with_alpha(FOREGROUND, 200)); + if p.show_vectors && !landed { + let velocity = analytic::projectile_velocity(p.speed, angle, p.gravity, t); + let others = centers + .iter() + .enumerate() + .filter_map(|(i, &point)| (i != index).then_some(point)); + if let Some((from, to)) = + velocity_segment(view, size, (x, y + radius), velocity, radius) + { + if let Some(tip) = clip_projectile_vector(from, to, ground, radius_px, others) { + painter.arrow(from, tip, VELOCITY_WIDTH, with_alpha(color, 220)); + } + } + } + } + let &(angle, _, landed, x, y) = launches + .last() + .expect("the selected launch is always present"); + let result = if landed { + format!("Range = {x:.1} m") + } else { + format!("Height = {y:.1} m") + }; + readout_lines(painter, &[format!("{angle:.1}° launch | {result}")], font); + time_readout(painter, size, sim_time, p.duration, font); +} + +fn projectile_time(p: &Params, angle: f64, time: f64) -> (f64, bool) { + if p.speed == 0.0 { + return (0.0, true); + } + match analytic::flight_time(p.speed, angle, p.gravity) { + Some(flight) if time >= flight => (flight, true), + _ => (time, false), + } +} + +fn ceiling_mount(painter: &mut Painter, view: &View, x: f64, half_width: f64, y: f64) { + let a = view.point(x - half_width, y); + let b = view.point(x + half_width, y); + painter.line(a, b, 3.0, with_alpha(MUTED, 230)); + for k in 0..5 { + let t = (a.x + (b.x - a.x) * k as f32 / 4.0, a.y); + painter.line( + Point { x: t.0, y: t.1 }, + Point { + x: t.0 + 7.0, + y: t.1 + 7.0, + }, + 1.5, + with_alpha(MUTED, 160), + ); + } + let pivot = view.point(x, y); + painter.fill(circle_path(pivot.x, pivot.y, 4.5), MUTED); +} + +fn draw_pendulum(painter: &mut Painter, view: &View, p: &Params, sim_time: f64, size: Size) { + let (font, _tick) = fonts(size); + let l = p.length_m; + let theta0 = p.angle_deg.to_radians(); + let bob_r = (0.16 * l).clamp(0.06, 0.5); + let period = analytic::pendulum_period(l, p.gravity, p.angle_deg); + let (theta, omega) = analytic::pendulum_state(theta0, p.gravity / l, period, sim_time); + let (bx, by) = analytic::pendulum_bob(l, theta); + if p.show_trail { + let end = if sim_time >= period / 2.0 { + -theta0 + } else { + theta + }; + let trace: Vec<_> = (0..=80) + .map(|step| analytic::pendulum_bob(l, theta0 + (end - theta0) * f64::from(step) / 80.0)) + .collect(); + trail_stroke(painter, view, &trace, TRAIL); + } + ceiling_mount(painter, view, 0.0, 0.35 * l, 0.0); + let pivot = view.point(0.0, 0.0); + let bob = view.point(bx, by); + painter.line(pivot, bob, 3.0, with_alpha(FOREGROUND, 230)); + painter.fill(circle_path(bob.x, bob.y, view.dist(bob_r)), p.accent); + painter.stroke( + circle_path(bob.x, bob.y, view.dist(bob_r)), + 1.5, + with_alpha(FOREGROUND, 200), + ); + if p.show_vectors { + let (vx, vy) = analytic::pendulum_velocity(l, theta, omega); + velocity_arrow(painter, view, size, (bx, by), (vx, vy), bob_r, p.accent); + } + let mut lines = Vec::new(); + if period.is_finite() { + lines.push(format!("T = {:.2} s", period)); + lines.push(format!("angle = {:.1} deg", theta.to_degrees())); + } else { + lines.push("no gravity: at rest".to_string()); + } + readout_lines(painter, &lines, font); + time_readout(painter, size, sim_time, p.duration, font); +} + +fn draw_spring(painter: &mut Painter, view: &View, p: &Params, sim_time: f64, size: Size) { + let (font, _tick) = fonts(size); + let l = p.length_m; + let amplitude = 0.3 * l; + let half = (0.12 * l).clamp(0.05, 0.6); + let omega = analytic::spring_omega(l, p.gravity); + let offset = analytic::spring_offset(amplitude, omega, sim_time); + let velocity = analytic::spring_velocity(amplitude, omega, sim_time); + let y_mass = -l - offset; + // Equilibrium marker. + let eq_a = view.point(-0.45 * l, -l); + let eq_b = view.point(0.45 * l, -l); + painter.dashed(&[eq_a, eq_b], 1.5, with_alpha(MUTED, 180), 7.0, 6.0); + if p.show_trail && omega > 0.0 { + let first_half = sim_time.min(std::f64::consts::PI / omega); + let end = -l - analytic::spring_offset(amplitude, omega, first_half); + trail_stroke(painter, view, &[(0.0, -l - amplitude), (0.0, end)], TRAIL); + } + ceiling_mount(painter, view, 0.0, 0.3 * l, 0.0); + // Coil: zigzag between the anchor and the top of the mass. + let anchor = view.point(0.0, 0.0); + let top = view.point(0.0, y_mass + half); + let coil_points = 15; + let width = view.dist(0.14 * l).max(6.0); + let mut zig: Vec = Vec::with_capacity(coil_points + 2); + zig.push(anchor); + for k in 1..=coil_points { + let t = k as f32 / (coil_points + 1) as f32; + let side = if k % 2 == 0 { 1.0 } else { -1.0 }; + zig.push(Point { + x: anchor.x + side * width * 0.5, + y: anchor.y + (top.y - anchor.y) * t, + }); + } + zig.push(top); + painter.stroke(polyline(&zig, false), 2.2, with_alpha(FOREGROUND, 230)); + let corners = box_corners(0.0, y_mass, half, half, 0.0, view); + painter.fill(polyline(&corners, true), p.accent); + painter.stroke(polyline(&corners, true), 1.5, with_alpha(FOREGROUND, 200)); + if p.show_vectors { + velocity_arrow( + painter, + view, + size, + (0.0, y_mass), + (0.0, -velocity), + half, + p.accent, + ); + } + let mut lines = Vec::new(); + if omega > 0.0 { + let period = std::f64::consts::TAU / omega; + lines.push(format!("T = {:.2} s", period)); + lines.push(format!("Extension = {:.2} m", l + offset)); + } else { + lines.push("no gravity: at rest".to_string()); + } + readout_lines(painter, &lines, font); + time_readout(painter, size, sim_time, p.duration, font); +} + +impl Params { + fn material(&self) -> sim::Material { + sim::Material { + gravity: self.gravity, + restitution: self.restitution, + friction: self.friction, + } + } +} + +fn draw_collision(painter: &mut Painter, view: &View, p: &Params, size: Size) { + let (font, tick) = fonts(size); + let left = view.point(0.0, 0.0); + let right = view.point(sim::ARENA_W, 0.0); + painter.stroke( + polyline( + &[ + left, + view.point(0.0, sim::ARENA_H), + view.point(sim::ARENA_W, sim::ARENA_H), + right, + ], + false, + ), + 2.0, + MUTED, + ); + if p.show_ground { + draw::draw_ground(painter, view, 0.0, sim::ARENA_W, 2, size, tick); + } else { + painter.line(left, right, 2.0, MUTED); + } + + let plan = sim::Plan::new(p.progress, p.duration); + let state = sim::collision(p.bodies, p.speed, p.material(), plan, p.show_trail); + trail_stroke(painter, view, &state.motion.trail, TRAIL); + let mut px = 0.0; + let mut py = 0.0; + let mut ke = 0.0; + for (index, body) in state.motion.bodies.into_iter().enumerate() { + px += p.mass * body.vx; + py += p.mass * body.vy; + ke += 0.5 * p.mass * (body.vx * body.vx + body.vy * body.vy); + let center = view.point(body.x, body.y); + let fill = if index == 0 { p.accent } else { FOREGROUND }; + let outline = circle_path(center.x, center.y, view.dist(sim::BALL_RADIUS)); + painter.fill(outline.clone(), fill); + painter.stroke(outline, 1.2, MUTED); + if p.show_vectors { + velocity_arrow( + painter, + view, + size, + (body.x, body.y), + (body.vx, body.vy), + sim::BALL_RADIUS, + fill, + ); + } + } + let momentum = if state.boundary_impulse || (plan.steps > 0 && p.gravity > 0.0) { + "Momentum (not conserved)" + } else { + "Momentum" + }; + let lines = [ + format!("{momentum} = ({px:.1}, {py:.1}) kg m/s"), + format!("Kinetic energy = {ke:.2} J"), + ]; + readout_lines(painter, &lines, font); + time_readout(painter, size, plan.time(), p.duration, font); +} + +fn draw_stack(painter: &mut Painter, view: &View, extent: &Extent, p: &Params, size: Size) { + let (font, tick) = fonts(size); + if p.show_ground { + draw::draw_ground(painter, view, extent.min_x, extent.max_x, 2, size, tick); + } + let plan = sim::Plan::new(p.progress, p.duration); + let mut state = sim::stack(p.bodies, p.speed, p.material(), plan, p.show_trail); + for (x, _) in &mut state.trail { + *x = x.max(extent.min_x); + } + state.trail.dedup(); + trail_stroke(painter, view, &state.trail, TRAIL); + + let ball = state.bodies[0]; + let center = view.point(ball.x, ball.y); + let outline = circle_path(center.x, center.y, view.dist(sim::STACK_BALL_R)); + painter.fill(outline.clone(), p.accent); + painter.stroke(outline, 1.2, FOREGROUND); + let (sin, cos) = ball.angle.sin_cos(); + painter.line( + center, + view.point( + ball.x + cos * sim::STACK_BALL_R * 0.7, + ball.y + sin * sim::STACK_BALL_R * 0.7, + ), + 1.5, + FOREGROUND, + ); + if p.show_vectors { + velocity_arrow( + painter, + view, + size, + (ball.x, ball.y), + (ball.vx, ball.vy), + sim::STACK_BALL_R, + p.accent, + ); + } + + let mut fallen = 0; + for block in &state.bodies[1..] { + if block.angle.abs() > 0.6 { + fallen += 1; + } + let corners = box_corners( + block.x, + block.y, + sim::DOMINO_HX, + sim::DOMINO_HY, + block.angle, + view, + ); + let outline = polyline(&corners, true); + painter.fill(outline.clone(), FOREGROUND); + painter.stroke(outline, 1.2, MUTED); + } + readout_lines(painter, &[format!("Toppled = {fallen}/{}", p.bodies)], font); + time_readout(painter, size, plan.time(), p.duration, font); +} + +export!(PhysicsPlay); + +#[cfg(test)] +mod tests; diff --git a/community/physics/src/params.rs b/community/physics/src/params.rs new file mode 100644 index 0000000..41439b6 --- /dev/null +++ b/community/physics/src/params.rs @@ -0,0 +1,110 @@ +//! Parameter readers and schema builders. Every numeric read is finite-checked and +//! clamped to its declared range, so rendering can trust the values (pattern shared +//! with `community/code-snippets`). + +use super::{ + BoolParam, Color, ColorParam, Diagnostic, EnumParam, NumberRange, ParamEntry, ParamKind, + ParamSpec, ParamValue, +}; + +pub fn error(message: &str) -> Diagnostic { + Diagnostic { + code: "invalid-input".into(), + message: message.into(), + metadata: vec![], + } +} + +pub fn string<'a>(params: &'a [ParamEntry], id: &str, default: &'a str) -> &'a str { + params + .iter() + .find(|p| p.id == id) + .and_then(|p| match &p.value { + ParamValue::String(s) | ParamValue::EnumChoice(s) => Some(s.as_str()), + _ => None, + }) + .unwrap_or(default) +} + +pub fn number( + params: &[ParamEntry], + id: &str, + default: f64, + min: f64, + max: f64, +) -> Result { + let n = params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Number(n) => Some(n), + _ => None, + }) + .unwrap_or(default); + if !n.is_finite() { + return Err(error("Numeric parameters must be finite")); + } + Ok(n.clamp(min, max)) +} + +pub fn boolean(params: &[ParamEntry], id: &str, default: bool) -> bool { + params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Bool(b) => Some(b), + _ => None, + }) + .unwrap_or(default) +} + +pub fn color(params: &[ParamEntry], id: &str, default: Color) -> Color { + params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Color(c) => Some(c), + _ => None, + }) + .unwrap_or(default) +} + +pub fn enum_param(id: &str, label: &str, options: &[&str], default: &str) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::EnumChoice(EnumParam { + options: options.iter().map(|s| (*s).into()).collect(), + default: default.into(), + }), + } +} + +pub fn num_param(id: &str, label: &str, min: f64, max: f64, default: f64, step: f64) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Number(NumberRange { + min, + max, + default, + step, + }), + } +} + +pub fn bool_param(id: &str, label: &str, default: bool) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Bool(BoolParam { default }), + } +} + +pub fn color_param(id: &str, label: &str, default: Color) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Color(ColorParam { default }), + } +} diff --git a/community/physics/src/sim.rs b/community/physics/src/sim.rs new file mode 100644 index 0000000..f031854 --- /dev/null +++ b/community/physics/src/sim.rs @@ -0,0 +1,416 @@ +//! Small fixed-step solver for the two contact demos. Each call starts at t = 0. + +pub const ARENA_W: f64 = 12.0; +pub const ARENA_H: f64 = 5.0; +pub const BALL_RADIUS: f64 = 0.35; +pub const DOMINO_HX: f64 = 0.09; +pub const DOMINO_HY: f64 = 0.45; +pub const DOMINO_SPACING: f64 = 0.55; +pub const STACK_BALL_R: f64 = 0.28; + +pub const HZ: f64 = 120.0; +pub const MAX_STEPS: usize = 3600; +pub const MAX_BODIES: usize = 12; +const TRAIL_INTERVAL: usize = 16; + +#[derive(Clone, Copy, Debug)] +pub struct Plan { + pub dt: f64, + pub steps: usize, +} + +impl Plan { + pub fn new(progress: f64, duration: f64) -> Self { + // Derive dt from duration alone to trace the same trajectory when scrubbing. + let total = ((duration * HZ).ceil() as usize).clamp(1, MAX_STEPS); + Self { + dt: duration / total as f64, + steps: (progress * total as f64).round() as usize, + } + } + + pub fn time(self) -> f64 { + self.dt * self.steps as f64 + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Snapshot { + pub x: f64, + pub y: f64, + pub angle: f64, + pub vx: f64, + pub vy: f64, +} + +#[derive(Clone, Copy)] +pub struct Material { + pub gravity: f64, + pub restitution: f64, + pub friction: f64, +} + +/// Solver work counted per render, so tests can bound the fuel a scene needs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Work { + /// Visits of the disk-contact loop and of the domino transfer/support loops. + pub pair_checks: u32, + /// Wall/containment checks on disks. + pub wall_checks: u32, +} + +pub struct Simulation { + pub bodies: Vec, + pub trail: Vec<(f64, f64)>, + /// Only the tests read this; the render ignores how much work it took. + #[cfg_attr(not(test), allow(dead_code))] + pub work: Work, +} + +pub struct Collision { + pub motion: Simulation, + pub boundary_impulse: bool, +} + +fn record(trail: &mut Vec<(f64, f64)>, body: Snapshot, step: usize, plan: Plan, enabled: bool) { + if enabled && (step == plan.steps || step.is_multiple_of(TRAIL_INTERVAL)) { + trail.push((body.x, body.y)); + } +} + +/// Advance the equal-mass disks, resolving walls and then all disk pairs in +/// a fixed order. The first row starts on the floor along the launch line. +pub fn collision( + count: usize, + speed: f64, + material: Material, + plan: Plan, + trace: bool, +) -> Collision { + let mut bodies = Vec::with_capacity(count); + bodies.push(Snapshot { + x: 1.4, + y: BALL_RADIUS, + vx: speed, + ..Snapshot::default() + }); + for i in 0..count - 1 { + bodies.push(Snapshot { + x: 5.4 + 0.85 * (i % 6) as f64, + y: BALL_RADIUS + 1.15 * (i / 6) as f64, + ..Snapshot::default() + }); + } + + let mut trail = Vec::new(); + let mut work = Work::default(); + let mut boundary_impulse = false; + record(&mut trail, bodies[0], 0, plan, trace); + for step in 1..=plan.steps { + for body in &mut bodies { + body.x += body.vx * plan.dt; + body.y += (body.vy - 0.5 * material.gravity * plan.dt) * plan.dt; + body.vy -= material.gravity * plan.dt; + boundary_impulse |= contain(body, material); + work.wall_checks += 1; + } + for i in 1..bodies.len() { + let (earlier, later) = bodies.split_at_mut(i); + for a in earlier { + contact(a, &mut later[0], material); + work.pair_checks += 1; + } + } + // A pair's penetration correction can move a disk across a wall. + for body in &mut bodies { + boundary_impulse |= contain(body, material); + work.wall_checks += 1; + } + record(&mut trail, bodies[0], step, plan, trace); + } + Collision { + motion: Simulation { + bodies, + trail, + work, + }, + boundary_impulse, + } +} + +fn contain(body: &mut Snapshot, material: Material) -> bool { + let side = bound_axis( + &mut body.x, + &mut body.vx, + &mut body.vy, + ARENA_W, + material, + 0.0, + ); + // Treat very slow vertical bounces as resting contact to suppress chatter. + let vertical = bound_axis( + &mut body.y, + &mut body.vy, + &mut body.vx, + ARENA_H, + material, + 0.5, + ); + side || vertical +} + +fn bound_axis( + position: &mut f64, + normal_speed: &mut f64, + tangent_speed: &mut f64, + length: f64, + material: Material, + rest_speed: f64, +) -> bool { + let min = BALL_RADIUS; + let max = length - BALL_RADIUS; + if (*position >= min || *normal_speed >= 0.0) && (*position <= max || *normal_speed <= 0.0) { + *position = position.clamp(min, max); + return false; + } + *position = position.clamp(min, max); + let before = *normal_speed; + *normal_speed = if before.abs() < rest_speed { + 0.0 + } else { + -material.restitution * before + }; + let friction = material.friction * (*normal_speed - before).abs(); + *tangent_speed -= tangent_speed.clamp(-friction, friction); + true +} + +fn contact(a: &mut Snapshot, b: &mut Snapshot, material: Material) { + let dx = b.x - a.x; + let dy = b.y - a.y; + let distance_sq = dx * dx + dy * dy; + let diameter = 2.0 * BALL_RADIUS; + if distance_sq >= diameter * diameter { + return; + } + let distance = distance_sq.sqrt(); + let (nx, ny) = if distance > 1e-9 { + (dx / distance, dy / distance) + } else { + (1.0, 0.0) + }; + let correction = 0.5 * (diameter - distance); + a.x -= correction * nx; + a.y -= correction * ny; + b.x += correction * nx; + b.y += correction * ny; + + let vx = b.vx - a.vx; + let vy = b.vy - a.vy; + let closing = vx * nx + vy * ny; + if closing >= 0.0 { + return; + } + let normal = -0.5 * (1.0 + material.restitution) * closing; + let friction = material.friction * normal; + let tangent = (0.5 * (vx * ny - vy * nx)).clamp(-friction, friction); + let impulse_x = normal * nx - tangent * ny; + let impulse_y = normal * ny + tangent * nx; + a.vx -= impulse_x; + a.vy -= impulse_y; + b.vx += impulse_x; + b.vy += impulse_y; +} + +const FIRST_DOMINO: f64 = 0.7; +const BALL_START: f64 = -1.6; +const BLOCK_WIDTH: f64 = 2.0 * DOMINO_HX; +const BLOCK_HEIGHT: f64 = 2.0 * DOMINO_HY; + +#[derive(Clone, Copy, Default)] +struct Domino { + angle: f64, + omega: f64, + hit_next: bool, + next_angle: f64, + support_angle: f64, +} + +impl Domino { + fn snapshot(self, index: usize) -> Snapshot { + let (sin, cos) = self.angle.sin_cos(); + let pivot = FIRST_DOMINO + DOMINO_SPACING * index as f64 + DOMINO_HX; + Snapshot { + x: pivot - DOMINO_HX * cos + DOMINO_HY * sin, + y: DOMINO_HX * sin + DOMINO_HY * cos, + angle: -self.angle, + ..Snapshot::default() + } + } +} + +/// The rolling ball hits the first block; each block rotates about its floor +/// corner and transfers an angular impulse at first contact with the next block. +pub fn stack(count: usize, speed: f64, material: Material, plan: Plan, trace: bool) -> Simulation { + let mut ball = Snapshot { + x: BALL_START, + y: STACK_BALL_R, + vx: speed, + ..Snapshot::default() + }; + let ball_contact = FIRST_DOMINO - DOMINO_HX - STACK_BALL_R; + let hit_angle = ((DOMINO_SPACING - BLOCK_WIDTH) / BLOCK_HEIGHT).asin(); + let mut blocks = vec![ + Domino { + support_angle: hit_angle, + ..Domino::default() + }; + count + ]; + let mut trail = Vec::new(); + let transfer = 0.5 * (1.0 + material.restitution); + // Moment of inertia about a corner, divided by mass. + let inertia = (BLOCK_WIDTH * BLOCK_WIDTH + BLOCK_HEIGHT * BLOCK_HEIGHT) / 3.0; + // Below this restitution the first impulse can leave the launcher rolling forward. + let can_recontact = material.restitution < STACK_BALL_R * STACK_BALL_R / inertia; + let flat = std::f64::consts::FRAC_PI_2; + let slowdown = 0.05 * material.friction * material.gravity * plan.dt; + let mut launched = false; + record(&mut trail, ball, 0, plan, trace); + let mut work = Work::default(); + for step in 1..=plan.steps { + ball.vx -= ball.vx.clamp(-slowdown, slowdown); + ball.x += ball.vx * plan.dt; + if !launched && ball.x >= ball_contact { + // Use restitution at the point of contact with the pivoted block. + let arm = STACK_BALL_R; + let impulse = (1.0 + material.restitution) * ball.vx / (1.0 + arm * arm / inertia); + blocks[0].omega = impulse * arm / inertia; + ball.x = ball_contact; + ball.vx -= impulse; + launched = true; + } + for block in &mut blocks { + if block.angle == flat || (block.angle == 0.0 && block.omega == 0.0) { + continue; + } + let (sin, cos) = block.angle.sin_cos(); + block.omega += + material.gravity * (DOMINO_HY * sin - DOMINO_HX * cos) / inertia * plan.dt; + block.angle += block.omega * plan.dt; + if block.angle < 0.0 || block.angle >= flat { + block.angle = block.angle.clamp(0.0, flat); + block.omega = 0.0; + } + } + for i in 1..blocks.len() { + let (earlier, later) = blocks.split_at_mut(i); + let (block, next) = (&mut earlier[i - 1], &mut later[0]); + work.pair_checks += 1; + if !block.hit_next && block.angle >= hit_angle { + // Keep enough information to transfer an impact even if the + // proposed angle crossed the contact in a single step. + let incoming = block.omega; + block.angle = hit_angle; + next.omega = transfer * incoming; + block.omega -= next.omega; + block.hit_next = true; + } + } + // A leaning block rests against the next block until it tips farther. + // Walk backward so the next block is already in its supported position. + for i in (1..blocks.len()).rev() { + let next = blocks[i].angle; + let block = &mut blocks[i - 1]; + work.pair_checks += 1; + if block.angle <= hit_angle { + continue; + } + // A settled neighbor offers the same support on every step. + if next != block.next_angle { + block.next_angle = next; + // An upright block first meets our top-right corner at hit_angle. + block.support_angle = support_limit(next).max(hit_angle); + } + if block.angle > block.support_angle { + block.angle = block.support_angle; + block.omega = 0.0; + } + } + if can_recontact && launched { + launcher_contact(&mut ball, &mut blocks[0], inertia, material.restitution); + } + ball.angle = -(ball.x - BALL_START) / STACK_BALL_R; + record(&mut trail, ball, step, plan, trace); + } + + let bodies = std::iter::once(ball) + .chain( + blocks + .into_iter() + .enumerate() + .map(|(i, block)| block.snapshot(i)), + ) + .collect(); + Simulation { + bodies, + trail, + work, + } +} + +fn launcher_contact(ball: &mut Snapshot, block: &mut Domino, inertia: f64, restitution: f64) { + let (sin, cos) = block.angle.sin_cos(); + let pivot = FIRST_DOMINO + DOMINO_HX; + let radius = STACK_BALL_R; + let face_arm = radius - (radius + BLOCK_WIDTH) * sin; + // Offset the left face by the ball radius. As the block falls, the + // tangency moves below that face and onto its bottom-left corner. + let (contact_x, normal_x, arm) = if face_arm >= 0.0 { + ( + pivot + (radius * sin - BLOCK_WIDTH - radius) / cos, + cos, + face_arm / cos, + ) + } else { + let corner_x = -BLOCK_WIDTH * cos; + let corner_y = BLOCK_WIDTH * sin; + let dy = radius - corner_y; + let dx = (radius * radius - dy * dy).sqrt(); + let normal_x = dx / radius; + let arm = corner_y * normal_x + corner_x * dy / radius; + (pivot + corner_x - dx, normal_x, arm) + }; + if ball.x < contact_x { + return; + } + ball.x = contact_x; + + let closing = ball.vx * normal_x - block.omega * arm; + if closing > 0.0 { + // The floor holds the ball at a fixed height and supports a flat block. + let angular_response = if block.angle == std::f64::consts::FRAC_PI_2 { + 0.0 + } else { + arm / inertia + }; + let impulse = + (1.0 + restitution) * closing / (normal_x * normal_x + arm * angular_response); + ball.vx -= impulse * normal_x; + block.omega += impulse * angular_response; + } +} + +fn support_limit(next: f64) -> f64 { + let (sin, cos) = next.sin_cos(); + // First vertex/face contact: our top-right corner on the next left face. + let left_face = next + ((DOMINO_SPACING * cos - BLOCK_WIDTH) / BLOCK_HEIGHT).asin(); + + // Opposite contact: either end of that face can reach our right face. + // The lower endpoint becomes the near end of the top edge once flat. + let left_x = DOMINO_SPACING - BLOCK_WIDTH * cos; + let left_y = BLOCK_WIDTH * sin; + let bottom_left = left_x.atan2(left_y); + let top_left = (left_x + BLOCK_HEIGHT * sin).atan2(left_y + BLOCK_HEIGHT * cos); + left_face.min(bottom_left).min(top_left) +} diff --git a/community/physics/src/tests.rs b/community/physics/src/tests.rs new file mode 100644 index 0000000..5b42068 --- /dev/null +++ b/community/physics/src/tests.rs @@ -0,0 +1,645 @@ +//! Native unit tests: analytic correctness against textbook values, determinism of +//! the free simulation, parameter handling and bounded work. + +use super::*; +use draw::View; + +fn base_params() -> Vec { + let specs = PhysicsPlay::describe().params; + specs + .iter() + .map(|spec| ParamEntry { + id: spec.id.clone(), + value: match &spec.kind { + ParamKind::Number(range) => ParamValue::Number(range.default), + ParamKind::Color(c) => ParamValue::Color(c.default), + ParamKind::String(s) => ParamValue::String(s.default.clone()), + ParamKind::EnumChoice(e) => ParamValue::EnumChoice(e.default.clone()), + ParamKind::Bool(b) => ParamValue::Bool(b.default), + ParamKind::Point(pt) => ParamValue::Point(pt.default), + ParamKind::AssetRef(_) => ParamValue::String(String::new()), + }, + }) + .collect() +} + +fn with(list: &mut [ParamEntry], id: &str, value: ParamValue) { + list.iter_mut() + .find(|p| p.id == id) + .expect("known param") + .value = value; +} + +fn with_all(list: &mut [ParamEntry], values: &[(&str, ParamValue)]) { + for (id, value) in values { + with(list, id, value.clone()); + } +} + +fn render_snapshot(list: &[ParamEntry], size: Size) -> String { + match render(list, size) { + Ok(scene) => format!("{scene:?}"), + Err(d) => format!("ERR {} {}", d.code, d.message), + } +} + +fn readouts(list: &[ParamEntry]) -> Vec { + render(list, CANVAS) + .unwrap() + .elements + .into_iter() + .filter_map(|element| match element { + DrawCommand::TextRun(text) if text.x == 16.0 => Some(text.text), + _ => None, + }) + .collect() +} + +const CANVAS: Size = Size { + width: 1280, + height: 720, +}; + +#[test] +fn elliptic_integral_matches_known_values() { + let k = analytic::elliptic_k(0.0); + assert!((k - std::f64::consts::FRAC_PI_2).abs() < 1e-12, "{k}"); + // Abramowitz & Stegun 17.3.1 reference values. + assert!((analytic::elliptic_k(0.25) - 1.685_750_354_812_596).abs() < 1e-12); + assert!((analytic::elliptic_k(0.5) - 1.854_074_677_301_372).abs() < 1e-12); +} + +#[test] +fn pendulum_period_reduces_to_small_angle_and_grows_with_amplitude() { + let (l, g) = (1.5, 9.81); + let small = analytic::pendulum_period(l, g, 0.5); + let small_angle = std::f64::consts::TAU * (l / g).sqrt(); + assert!( + (small - small_angle).abs() / small_angle < 1e-5, + "{small} vs {small_angle}" + ); + // Exact ratio for a 60° release: T/T₀ = 2·K(0.25)/π ≈ 1.07318. + let ratio = analytic::pendulum_period(l, g, 60.0) / small_angle; + assert!((ratio - 2.0 * analytic::elliptic_k(0.25) / std::f64::consts::PI).abs() < 1e-12); + assert!((ratio - 1.073_182).abs() < 1e-5, "{ratio}"); + // No gravity: no oscillation, period infinite. + assert!(analytic::pendulum_period(l, 0.0, 45.0).is_infinite()); +} + +#[test] +fn nonlinear_pendulum_keeps_energy_and_reaches_its_turning_points() { + let (l, g, angle) = (0.2, 30.0, 90.0_f64); + let theta0 = angle.to_radians(); + let period = analytic::pendulum_period(l, g, angle); + let initial_energy = analytic::pendulum_energy(l, g, theta0, 0.0); + for step in 0..=64 { + let time = step as f64 / 64.0 * period; + let (theta, omega) = analytic::pendulum_state(theta0, g / l, period, time); + let energy = analytic::pendulum_energy(l, g, theta, omega); + assert!((energy - initial_energy).abs() / initial_energy < 1e-6); + match step { + 16 => assert!(theta.abs() < 1e-6 && omega < 0.0), + 32 => assert!((theta + theta0).abs() < 1e-12 && omega.abs() < 1e-12), + 48 => assert!(theta.abs() < 1e-6 && omega > 0.0), + 64 => assert_eq!((theta, omega), (theta0, 0.0)), + _ => {} + } + } + assert_eq!( + analytic::pendulum_state(theta0, 0.0, f64::INFINITY, 30.0), + (theta0, 0.0) + ); +} + +#[test] +fn projectile_matches_textbook_formulas() { + let (v, angle, g) = (15.0, 45.0, 9.81); + let flight = analytic::flight_time(v, angle, g).unwrap(); + let expected_range = v * v * (2.0 * angle.to_radians()).sin() / g; + let range = analytic::projectile_position(v, angle, g, flight).0; + assert!( + (range - expected_range).abs() < 1e-9, + "{range} vs {expected_range}" + ); + // Apex exactly halfway: height (v·sinα)²/(2g). + let apex = analytic::projectile_position(v, angle, g, flight * 0.5).1; + let expected_apex = (v * angle.to_radians().sin()).powi(2) / (2.0 * g); + assert!((apex - expected_apex).abs() < 1e-9); + // Horizontal motion is uniform; vertical acceleration is −g. + let (vx, vy) = analytic::projectile_velocity(v, angle, g, 0.3); + assert!((vx - v * angle.to_radians().cos()).abs() < 1e-12); + let (_, vy2) = analytic::projectile_velocity(v, angle, g, 0.8); + assert!(((vy2 - vy) / (0.8 - 0.3) + g).abs() < 1e-9); + // Ground-level horizontal launch cannot stay aloft in gravity. + assert!(analytic::flight_time(v, angle, 0.0).is_none()); + assert_eq!(analytic::flight_time(v, 0.0, g), Some(0.0)); +} + +#[test] +fn spring_is_exact_hooke_motion() { + let (l, g) = (1.5, 9.81); + let omega = analytic::spring_omega(l, g); + assert!((omega - (g / l).sqrt()).abs() < 1e-12); + let amplitude = 0.3 * l; + assert_eq!(analytic::spring_offset(amplitude, omega, 0.0), amplitude); + assert!(analytic::spring_velocity(amplitude, omega, 0.0).abs() < 1e-12); + // Half a period later: mirror position, zero velocity. + let half = std::f64::consts::PI / omega; + assert!((analytic::spring_offset(amplitude, omega, half) + amplitude).abs() < 1e-9); + assert!(analytic::spring_velocity(amplitude, omega, half).abs() < 1e-9); + // Same period as the small-angle pendulum of the same length (tuned spring). + let pendulum_small = std::f64::consts::TAU * (l / g).sqrt(); + let spring = std::f64::consts::TAU / omega; + assert!((spring - pendulum_small).abs() < 1e-12); + assert_eq!(analytic::spring_omega(l, 0.0), 0.0); +} + +#[test] +fn full_duration_uses_one_stable_step_grid() { + for duration in [0.5, 4.0, 20.1, 30.0] { + let full = sim::Plan::new(1.0, duration); + assert!((full.time() - duration).abs() < 1e-12); + assert!(full.steps <= sim::MAX_STEPS); + assert!(full.dt <= 1.0 / sim::HZ); + let mut previous = 0; + for step in 0..=64 { + let plan = sim::Plan::new(f64::from(step) / 64.0, duration); + assert!(plan.steps >= previous); + assert_eq!(plan.dt, full.dt); + previous = plan.steps; + } + } + assert_eq!(sim::Plan::new(1.0, 30.0).steps, sim::MAX_STEPS); +} + +#[test] +fn isolated_equal_mass_collision_obeys_restitution_and_conserves_momentum() { + for speed in [5.0, 40.0] { + for restitution in [0.0, 0.2, 1.0] { + let material = sim::Material { + gravity: 0.0, + friction: 0.0, + restitution, + }; + let time = if speed == 5.0 { 0.85 } else { 0.2 }; + let state = sim::collision(2, speed, material, sim::Plan::new(time, 1.0), false); + assert!(!state.boundary_impulse); + let [a, b] = state.motion.bodies.as_slice() else { + panic!("expected two disks") + }; + assert!((a.vx + b.vx - speed).abs() < 1e-12); + assert!((b.vx - a.vx - restitution * speed).abs() < 1e-12); + let energy = 0.5 * (a.vx.powi(2) + b.vx.powi(2)); + let expected = 0.25 * speed.powi(2) * (1.0 + restitution.powi(2)); + assert!((energy - expected).abs() < 1e-12); + } + } +} + +#[test] +fn default_collision_still_has_kinetic_energy_at_midpoint() { + let p = read_params(&[]).unwrap(); + let state = sim::collision( + p.bodies, + p.speed, + p.material(), + sim::Plan::new(0.5, p.duration), + false, + ); + let energy: f64 = state + .motion + .bodies + .iter() + .map(|body| 0.5 * p.mass * (body.vx.powi(2) + body.vy.powi(2))) + .sum(); + assert!(energy > 0.0); + assert!(state.boundary_impulse); +} + +fn domino_overlap(a: sim::Snapshot, b: sim::Snapshot) -> f64 { + let axes = |angle: f64| { + let (sin, cos) = angle.sin_cos(); + [(cos, sin), (-sin, cos)] + }; + let a_axes = axes(a.angle); + let b_axes = axes(b.angle); + let dot = |(x, y): (f64, f64), (u, v): (f64, f64)| x * u + y * v; + let radius = |axis, body_axes: [(f64, f64); 2]| { + sim::DOMINO_HX * dot(axis, body_axes[0]).abs() + + sim::DOMINO_HY * dot(axis, body_axes[1]).abs() + }; + a_axes + .into_iter() + .chain(b_axes) + .map(|axis| { + radius(axis, a_axes) + radius(axis, b_axes) - dot(axis, (b.x - a.x, b.y - a.y)).abs() + }) + .fold(f64::INFINITY, f64::min) +} + +#[test] +fn neighboring_dominoes_do_not_penetrate_during_replay() { + let p = read_params(&[]).unwrap(); + let plan = sim::Plan::new(1.0, p.duration); + for count in [6, 12] { + for steps in 0..=plan.steps { + let sample = sim::Plan { steps, ..plan }; + let state = sim::stack(count, p.speed, p.material(), sample, false); + for (index, pair) in state.bodies[1..].windows(2).enumerate() { + let overlap = domino_overlap(pair[0], pair[1]); + assert!( + overlap < 0.001, + "{count} dominoes, pair {index}, t = {:.4} s: {overlap:.6} m", + sample.time() + ); + } + } + } +} + +#[test] +fn soft_domino_launches_keep_the_ball_outside_the_row() { + let p = read_params(&[]).unwrap(); + for restitution in [0.0, 0.1, 0.25] { + let material = sim::Material { + restitution, + ..p.material() + }; + for hz in [60, 120, 240] { + let dt = 1.0 / f64::from(hz); + for steps in 0..=(p.duration / dt).round() as usize { + let plan = sim::Plan { dt, steps }; + let state = sim::stack(p.bodies, p.speed, material, plan, false); + let ball = state.bodies[0]; + let first = state.bodies[1]; + let (sin, cos) = first.angle.sin_cos(); + let dx = ball.x - first.x; + let dy = ball.y - first.y; + // Measure the distance to the oriented rectangle in its local axes. + let x = dx * cos + dy * sin; + let y = -dx * sin + dy * cos; + let outside_x = (x.abs() - sim::DOMINO_HX).max(0.0); + let outside_y = (y.abs() - sim::DOMINO_HY).max(0.0); + assert!( + dx < 0.0 && outside_x.hypot(outside_y) >= sim::STACK_BALL_R - 1e-9, + "launcher at restitution {restitution}, {hz} Hz, t = {:.4} s: {ball:?}, {first:?}", + plan.time() + ); + for (index, pair) in state.bodies[1..].windows(2).enumerate() { + let overlap = domino_overlap(pair[0], pair[1]); + assert!( + overlap < 1e-9, + "pair {index} at restitution {restitution}, {hz} Hz, t = {:.4} s: {overlap:.6} m", + plan.time() + ); + } + } + } + } +} + +#[test] +fn domino_launcher_contact_speed_matches_configured_restitution() { + let p = read_params(&[]).unwrap(); + let plan = sim::Plan::new(1.0, p.duration); + for restitution in [0.0, 0.1, 0.25, 0.4, 0.8, 1.0] { + let material = sim::Material { + gravity: 0.0, + friction: 0.0, + restitution, + }; + let sample = |steps| { + sim::stack( + p.bodies, + p.speed, + material, + sim::Plan { steps, ..plan }, + false, + ) + }; + let impact_step = (1..=plan.steps) + .find(|&steps| sample(steps).bodies[1].angle < 0.0) + .expect("the launcher hits the first domino"); + let incoming = sample(impact_step - 1).bodies[0].vx; + let after = sample(impact_step).bodies; + // With gravity off, the first angle increment gives the angular + // velocity from the impulse. The initial contact arm is the ball radius. + let contact_speed = -after[1].angle / plan.dt * sim::STACK_BALL_R; + let separation = contact_speed - after[0].vx; + assert!( + (separation - restitution * incoming).abs() < 1e-12, + "restitution {restitution}: separation {separation} m/s, approach {incoming} m/s" + ); + } +} + +#[test] +fn domino_contact_propagates_down_the_row() { + let material = sim::Material { + gravity: 9.81, + restitution: 0.8, + friction: 0.8, + }; + let run = + |progress, speed| sim::stack(12, speed, material, sim::Plan::new(progress, 4.0), true); + let underway = run(0.1, 15.0).bodies; + assert!(underway[1].angle < 0.0); + assert_eq!(underway[12].angle, 0.0); + let complete = run(1.0, 15.0).bodies; + assert!( + complete[1..].iter().all(|block| block.angle < -0.6), + "{complete:?}" + ); + assert!(run(1.0, 0.0).bodies.iter().all(|body| body.angle == 0.0)); +} + +#[test] +fn contact_solvers_are_deterministic_at_maximum_work() { + let material = sim::Material { + gravity: 30.0, + restitution: 1.0, + friction: 0.0, + }; + let plan = sim::Plan::new(1.0, 30.0); + let run = || { + [ + sim::collision(12, 40.0, material, plan, true).motion, + sim::stack(12, 40.0, material, plan, true), + ] + }; + for (first, second) in run().into_iter().zip(run()) { + let bits = + |body: &sim::Snapshot| [body.x, body.y, body.angle, body.vx, body.vy].map(f64::to_bits); + assert!(first + .bodies + .iter() + .map(bits) + .eq(second.bodies.iter().map(bits))); + assert_eq!(first.trail, second.trail); + assert!(first.trail.len() <= 226); + assert!(first + .bodies + .iter() + .flat_map(bits) + .all(|value| f64::from_bits(value).is_finite())); + } + let state = sim::collision(12, 40.0, material, plan, false).motion; + assert!(state.trail.is_empty()); + for body in state.bodies { + assert!((sim::BALL_RADIUS..=sim::ARENA_W - sim::BALL_RADIUS).contains(&body.x)); + assert!((sim::BALL_RADIUS..=sim::ARENA_H - sim::BALL_RADIUS).contains(&body.y)); + } +} + +#[test] +fn solver_work_stays_within_published_bounds() { + let plan = sim::Plan::new(1.0, 30.0); + let material = sim::Material { + gravity: 30.0, + restitution: 1.0, + friction: 0.0, + }; + // The README bounds disk work at 66 pair checks and two wall passes per step, + // and the domino row at two visits per pair per step. Measure both solvers + // at their heaviest settings and at the defaults. + for (bodies, speed, material) in [ + (12, 40.0, material), + (6, 15.0, read_params(&[]).unwrap().material()), + ] { + let collision = sim::collision(bodies, speed, material, plan, false).motion; + assert!(collision.work.pair_checks > 0); + assert!(collision.work.pair_checks <= 66 * plan.steps as u32); + assert!(collision.work.wall_checks <= 24 * plan.steps as u32); + let stack = sim::stack(bodies, speed, material, plan, false); + assert!(stack.work.pair_checks > 0); + assert!(stack.work.pair_checks <= 2 * 11 * plan.steps as u32); + } +} + +#[test] +fn every_scene_renders_deterministically_at_every_progress() { + for (scene_name, _) in SCENES { + for k in 0..=4 { + let mut list = base_params(); + with_all( + &mut list, + &[ + ("scene", ParamValue::EnumChoice(scene_name.to_string())), + ("progress", ParamValue::Number(k as f64 / 4.0)), + ], + ); + let first = render_snapshot(&list, CANVAS); + let second = render_snapshot(&list, CANVAS); + assert_eq!(first, second, "{scene_name} progress {k}/4"); + assert!(!first.starts_with("ERR"), "{scene_name}: {first}"); + } + } +} + +#[test] +fn progress_changes_every_scene() { + for (scene_name, _) in SCENES { + let mut list = base_params(); + with( + &mut list, + "scene", + ParamValue::EnumChoice(scene_name.to_string()), + ); + with(&mut list, "progress", ParamValue::Number(0.0)); + let start = render_snapshot(&list, CANVAS); + with(&mut list, "progress", ParamValue::Number(1.0)); + let end = render_snapshot(&list, CANVAS); + assert_ne!(start, end, "{scene_name}"); + } +} + +#[test] +fn default_scenes_report_drawn_quantities() { + let mut actual = Vec::new(); + for (name, _) in SCENES { + let list = [ + ParamEntry { + id: "scene".into(), + value: ParamValue::EnumChoice(name.into()), + }, + ParamEntry { + id: "progress".into(), + value: ParamValue::Number(0.5), + }, + ]; + actual.push(readouts(&list)); + } + assert_eq!( + actual, + [ + vec!["45.0° launch | Height = 1.6 m", "t = 2.00 s / 4.00 s"], + vec!["T = 2.56 s", "angle = 9.3 deg", "t = 2.00 s / 4.00 s"], + vec!["T = 2.46 s", "Extension = 1.68 m", "t = 2.00 s / 4.00 s"], + vec![ + "Momentum (not conserved) = (-0.9, 0.0) kg m/s", + "Kinetic energy = 7.54 J", + "t = 2.00 s / 4.00 s" + ], + vec!["Toppled = 6/6", "t = 2.00 s / 4.00 s"], + ] + ); +} + +#[test] +fn projectile_includes_the_selected_angle_and_frames_resting_bodies() { + let mut list = base_params(); + with(&mut list, "progress", ParamValue::Number(0.5)); + let p = read_params(&list).unwrap(); + let angles: Vec<_> = launch_angles(&p).collect(); + assert_eq!(angles, [36.0, 40.5, 48.0, 51.0, 54.0, 45.0]); + let radius = projectile_radius(p.speed); + let view = View::fit(&extent_for(&p).sanitized(), CANVAS, 0.07); + let (x, y) = analytic::projectile_position(p.speed, 45.0, p.gravity, 2.0); + let center = view.point(x, y + radius); + assert!(render(&list, CANVAS) + .unwrap() + .elements + .iter() + .any(|element| { + matches!(element, DrawCommand::FillPath((path, color)) + if color.r == p.accent.r && color.g == p.accent.g && color.b == p.accent.b + && color.a == p.accent.a + && matches!(path.first(), Some(PathVerb::MoveTo(start)) + if start.x == center.x + view.dist(radius) && start.y == center.y)) + })); + with(&mut list, "angle_deg", ParamValue::Number(0.0)); + assert_eq!(readouts(&list)[0], "0.0° launch | Range = 0.0 m"); + with(&mut list, "speed", ParamValue::Number(0.0)); + let p = read_params(&list).unwrap(); + assert_eq!(launch_angles(&p).collect::>(), [0.0]); + let extent = extent_for(&p); + assert!(extent.max_x - extent.min_x >= 3.0 && extent.max_y - extent.min_y >= 2.0); + assert_eq!(readouts(&list)[0], "0.0° launch | Range = 0.0 m"); +} + +#[test] +fn projectile_velocity_vectors_clear_the_ground_and_other_balls() { + let from = Point { x: 0.0, y: 30.0 }; + let to = Point { x: 100.0, y: 80.0 }; + let tip = clip_projectile_vector(from, to, 60.0, 10.0, std::iter::empty()).unwrap(); + assert!((tip.y - 58.5).abs() < 1e-3); + assert!((tip.x - 57.0).abs() < 1e-3); + let level = Point { x: 100.0, y: 30.0 }; + let ball = Point { x: 50.0, y: 30.0 }; + let tip = clip_projectile_vector(from, level, 100.0, 10.0, std::iter::once(ball)).unwrap(); + assert!(tip.x < 40.0); + let near = Point { x: 5.0, y: 30.0 }; + assert!(clip_projectile_vector(from, level, 100.0, 10.0, std::iter::once(near)).is_none()); + let shallow = Point { x: 100.0, y: 29.9 }; + assert!(clip_projectile_vector(from, shallow, 35.0, 10.0, std::iter::empty()).is_none()); +} + +#[test] +fn max_duration_max_bodies_renders_within_bounds() { + // The released host smoke test separately checks its memory and fuel limits. + for (scene_name, _) in SCENES { + let mut list = base_params(); + with_all( + &mut list, + &[ + ("scene", ParamValue::EnumChoice(scene_name.to_string())), + ("duration_s", ParamValue::Number(30.0)), + ("progress", ParamValue::Number(1.0)), + ("bodies", ParamValue::Number(12.0)), + ], + ); + let scene = + render(&list, CANVAS).unwrap_or_else(|err| panic!("{scene_name}: {}", err.message)); + assert!((3..1400).contains(&scene.elements.len())); + } +} + +#[test] +fn toggles_change_the_output() { + let mut base = base_params(); + with( + &mut base, + "scene", + ParamValue::EnumChoice("projectile".into()), + ); + with(&mut base, "progress", ParamValue::Number(0.4)); + let with_vectors = render_snapshot(&base, CANVAS); + let mut variant = base.clone(); + with(&mut variant, "show_vectors", ParamValue::Bool(false)); + let no_vectors = render_snapshot(&variant, CANVAS); + assert!( + with_vectors != no_vectors, + "velocity arrows must affect the frame" + ); + let mut variant = base.clone(); + with(&mut variant, "show_trail", ParamValue::Bool(false)); + assert_ne!(with_vectors, render_snapshot(&variant, CANVAS)); + let mut variant = base.clone(); + with(&mut variant, "show_ground", ParamValue::Bool(false)); + assert_ne!(with_vectors, render_snapshot(&variant, CANVAS)); + let mut variant = base.clone(); + with( + &mut variant, + "accent", + ParamValue::Color(draw::rgb(0, 255, 0, 255)), + ); + assert_ne!(with_vectors, render_snapshot(&variant, CANVAS)); + let mut variant = base.clone(); + with(&mut variant, "gravity", ParamValue::Number(1.62)); + assert_ne!(with_vectors, render_snapshot(&variant, CANVAS)); +} + +#[test] +fn invalid_input_is_rejected_cleanly() { + assert!(render( + &base_params(), + Size { + width: 0, + height: 720 + } + ) + .is_err()); + assert!(render( + &base_params(), + Size { + width: 1280, + height: 0 + } + ) + .is_err()); + let mut bad_scene = base_params(); + with( + &mut bad_scene, + "scene", + ParamValue::EnumChoice("orbit".into()), + ); + assert!(render(&bad_scene, CANVAS).is_err()); + let mut nan = base_params(); + with(&mut nan, "progress", ParamValue::Number(f64::NAN)); + assert!(render(&nan, CANVAS).is_err()); + // Out-of-range numbers are clamped, not rejected. + let mut high = base_params(); + with(&mut high, "bodies", ParamValue::Number(99.0)); + assert!(render(&high, CANVAS).is_ok()); +} + +#[test] +fn view_fits_and_is_uniform() { + let mut extent = Extent::new(); + extent.add(-2.0, -1.0); + extent.add(6.0, 3.0); + let view = View::fit(&extent, CANVAS, 0.07); + // Center maps to center. + let center = view.point(2.0, 1.0); + assert!((center.x - 640.0).abs() < 1e-3); + assert!((center.y - 360.0).abs() < 1e-3); + // Uniform scale; y flips. + let right = view.point(6.0, 1.0); + let top = view.point(2.0, 3.0); + assert!(right.x > center.x); + assert!(top.y < center.y); + assert!((view.dist(4.0) as f64 - (right.x - center.x) as f64).abs() < 1e-3); + // Everything lands inside the canvas with margins. + let corner = view.point(-2.0, 3.0); + assert!(corner.x >= 1280.0 * 0.06 - 1.0 && corner.x <= 1280.0 * 0.94 + 1.0); +} diff --git a/community/physics/wit/plugin.wit b/community/physics/wit/plugin.wit new file mode 100644 index 0000000..b6820d9 --- /dev/null +++ b/community/physics/wit/plugin.wit @@ -0,0 +1,582 @@ +package animathio:plugin@1.1.0; + +/// Shared data types for vector graphics, parameter schemas and plugin manifests. +interface types { + /// 2D dimensions in integer pixels. + record size { + width: u32, + height: u32, + } + + /// Finite 2D coordinates: x right, y down. Scene.coordinate-space selects units. + record point { + x: f32, + y: f32, + } + + /// Straight-alpha 8-bit RGBA color. + record color { + r: u8, + g: u8, + b: u8, + a: u8, + } + + /// Path segment command. + variant path-verb { + move-to(point), + line-to(point), + quad-to(tuple), + cubic-to(tuple), + close, + } + + /// Sequence of path commands forming one or more contours. + type path = list; + + /// Line cap style at path endpoints. + enum stroke-cap { + butt, + round, + square, + } + + /// Line join style at path vertices. + enum stroke-join { + miter, + round, + bevel, + } + + /// Outline styling parameters. + record stroke-style { + width: f32, + color: color, + cap: stroke-cap, + join: stroke-join, + } + + /// Horizontal alignment in the available canvas width. + enum text-alignment { left, center, right } + + /// Text run layout element. + record text-element { + align: text-alignment, + text: string, + font-size: f32, + x: f32, + y: f32, + color: color, + } + + /// Vector drawing command. + variant draw-command { + fill-path(tuple), + stroke-path(tuple), + text-run(text-element), + } + + /// canvas: pixels on the requested render canvas. normalized: local unit square, + /// with x scaled by width and y by height. Strokes are outlined in local + /// units then transformed with the paths (nonuniform scaling is allowed). + /// Normalized text-run font-size is a fraction of canvas height; x/y are + /// offsets from the centered text block. Values outside 0..1 are allowed. + enum coordinate-space { canvas, normalized } + + /// Evaluated vector scene composed of ordered draw commands. + record scene { + coordinate-space: coordinate-space, + elements: list, + } + + /// Axis-aligned bounding box in canvas coordinates. + record bbox { + min-x: f32, + min-y: f32, + max-x: f32, + max-y: f32, + } + + /// Result of host-side math typesetting. + record typeset-result { + paths: list, + bbox: bbox, + } + + /// Input language for host-side math typesetting. + enum math-mode { + latex, + typst, + } + + /// Finite inclusive range; min <= default <= max and step > 0 (UI hint). + record number-range { + min: f64, + max: f64, + default: f64, + step: f64, + } + + /// Color parameter declaration. + record color-param { + default: color, + } + + /// Text string parameter declaration. + record string-param { + default: string, + } + + /// Multiple-choice enum parameter declaration. + record enum-param { + options: list, + default: string, + } + + /// Boolean toggle parameter declaration. + record bool-param { + default: bool, + } + + /// 2D point parameter declaration. + record point-param { + default: point, + } + + /// Asset reference parameter declaration. + record asset-ref-param { + media-type: string, + default-asset: option, + } + + /// Supported parameter types. + variant param-kind { + %number(number-range), + %color(color-param), + %string(string-param), + enum-choice(enum-param), + %bool(bool-param), + %point(point-param), + asset-ref(asset-ref-param), + } + + /// Stable id, fallback human label and typed schema. Labels are not identifiers. + /// Translation keys and units may be supplied in manifest.metadata. + record param-spec { + id: string, + label: string, + kind: param-kind, + } + + /// Concrete value assigned to a parameter at evaluation time. + variant param-value { + %number(f64), + %color(color), + %string(string), + enum-choice(string), + %bool(bool), + %point(point), + asset-ref(string), + } + + /// Key-value parameter entry. + record param-entry { + id: string, + value: param-value, + } + + /// Map of parameter values passed to plugin invocations. + type param-map = list; + + /// Open classification: clip-source, effect, audio-effect, animation-preset + /// (1.1) or importer (1.1). The legacy animation kind has no execution world. + /// Unknown strings are metadata, never permission to invoke an unknown world. + type plugin-kind = string; + + /// Optional, namespaced advisory metadata. Unknown keys must be ignored. + /// Keys are unique; values are UTF-8, never executable content. Reserved + /// conventions: label-key, description-key, param..unit, + /// param..label-key and param..option..label-key; + /// prefix with effect.. for effect descriptors. No localization service + /// is implied: plain labels/messages remain mandatory fallbacks. + type metadata = list>; + + /// Extensible error code plus fallback diagnostic text and advisory details. + /// Known codes: invalid-input, limit-exceeded, service-failed, plugin-error. + /// Unknown codes are displayed using message; callers must not parse messages. + record diagnostic { + code: string, + message: string, + metadata: metadata, + } + + /// Plugin metadata and parameter schema. + record manifest { + name: string, + version: string, + description: string, + kinds: list, + metadata: metadata, + params: list, + } +} + +/// Host-provided services imported by plugins. +interface host { + use types.{path, math-mode, typeset-result, diagnostic}; + + /// Text shaping via host font engine. Size is pixels; positive and finite. + /// Returns glyph outline paths or an explicit diagnostic. + shape-text: func(text: string, font-size: f32) -> result, diagnostic>; + + /// Typeset math via the host typesetting engine. Returns glyph and rule + /// outline paths plus a tight bounding box. + typeset-math: func(source: string, mode: math-mode, font-size: f32) -> result; + + /// Extract double-quoted d attributes from SVG path elements, or accept raw + /// SVG path data. This is not a complete SVG renderer: transforms, styles, + /// other primitives and external resources are not interpreted. Empty input + /// succeeds with no paths; unsupported/non-path input returns a diagnostic. + svg-to-paths: func(svg-xml: string) -> result, diagnostic>; + + /// Hard limits configured for this host, as unique key/value pairs. + /// Stable keys: ticks-per-second, max-memory-bytes, max-table-elements, + /// fuel-per-call, epoch-interval-ms, epoch-deadline-ticks, max-effect-pixels, + /// effect-memory-bytes, effect-fuel-per-pixel, effect-epoch-deadline-ticks, + /// max-audio-block-frames, max-audio-state-bytes, audio-memory-bytes, + /// audio-fuel-per-sample, audio-epoch-deadline-ticks, max-audio-channels, + /// max-audio-sample-rate, max-shape-text-chars, max-shape-text-verbs, + /// max-svg-input-bytes, max-svg-verbs, max-typeset-verbs, + /// max-typeset-source-bytes, max-typeset-font-size-px, typeset-timeout-ms, + /// max-log-message-bytes, max-log-entries, max-effects-per-plugin (added in 1.0.x); since 1.1 also max-import-source-bytes, + /// import-memory-bytes, import-fuel-per-byte, import-epoch-deadline-ticks, + /// max-import-output-bytes, max-import-commands, max-sibling-file-bytes, + /// max-sibling-total-bytes, max-sibling-files, max-preset-keys. + /// Keys and units are specified in docs/plugins.md; unknown keys are ignored. + /// This reports policy, not remaining fuel or memory. Budgets reset per call. + limits: func() -> list>; + + /// Host logging for diagnostic and debug output. + log: func(message: string); +} + +/// Pixel-filter effects, added in API 0.2.1. +/// +/// A frame effect receives one straight-alpha sRGB RGBA8 frame and returns a +/// frame of the same size. The host enforces size, fuel, wall-clock and memory +/// limits on every call; see `SandboxLimits` in `plugin-host`. +interface frame-effects { + use types.{size, param-map, param-spec, diagnostic}; + + /// One filter offered by an effect plugin. + record effect-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`), stored in projects. + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Numeric parameters with range, default and step. Only `number` kinds are + /// supported; effect parameters are keyframeable numbers. + params: list, + } + + /// List the filters this plugin provides. + list-effects: func() -> list; + + /// Apply filter `effect` to `pixels`: `size.width * size.height * 4` bytes of + /// row-major straight-alpha sRGB RGBA8. Must return exactly the same number + /// of bytes. `time-ticks` is the clip-local source time. The call is a pure + /// function of its arguments. Returns a diagnostic on invalid input. + apply-frame: func(effect: string, pixels: list, size: size, params: param-map, time-ticks: s64) -> result, diagnostic>; +} + +/// Audio effects, added in API 0.2.2. +/// +/// An audio effect receives one block of interleaved f32 PCM and returns a block of +/// the same size. The host splits longer signals into contiguous blocks and carries an +/// opaque `state` blob from each call to the next, so filters, envelope followers and +/// other stateful processors work across block boundaries without the plugin keeping any +/// memory between calls. The host enforces block size, state size, fuel, wall-clock and +/// memory limits on every call; see `SandboxLimits` in `plugin-host`. +interface audio-effects { + use types.{param-map, param-spec, diagnostic}; + + /// One audio filter offered by an audio-effect plugin. + record audio-effect-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`), stored in projects. + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Numeric parameters with range, default and step; keyframeable on clip chains. + /// Only `number` kinds are supported. + params: list, + } + + /// A block of interleaved 32-bit float PCM. + record audio-block { + /// Frames per second (1..=768000). + sample-rate: u32, + /// Interleaved channel count (1..=32). + channels: u16, + /// Time of the first frame in the chain's own timeline, in ticks: clip-local for a + /// clip chain, project time for a track chain. + start-ticks: s64, + /// `frames * channels` finite samples, frame-major interleaving. Unclipped; + /// values may exceed 1.0. Preserve channel order (stereo is left, right). + /// No channel-layout negotiation or planar format is implied. + samples: list, + } + + /// Result of processing one block. + record block-output { + /// Exactly as many samples as the input block. + samples: list, + /// State to hand back with the next contiguous block, or none for stateless filters. + state: option>, + } + + /// List the audio filters this plugin provides. + list-audio-effects: func() -> list; + + /// Process one block with filter `effect`. `state` is `none` for the first block of a + /// signal; an empty blob is equivalent to none. Otherwise it is exactly the + /// nonempty blob the previous call returned. The call is a pure + /// function of its arguments. Returns a diagnostic on invalid input. + process-block: func(effect: string, block: audio-block, params: param-map, state: option>) -> result; +} + +/// Animation presets, added in API 1.1.0. +/// +/// A preset plugin turns a preset choice into ordinary keyframe curves. The host +/// converts the curves into one `Command::Batch` of keyframe edits, so rendering never +/// calls the plugin and undo restores the previous keyframes exactly. +interface animation-presets { + use types.{param-map, param-spec, diagnostic}; + + /// Where a preset sits in a clip's lifetime. The host places the window: + /// entrance at the clip start, exit at the clip end, emphasis centred on the clip. + enum preset-role { + entrance, + exit, + emphasis, + } + + /// One preset offered by an animation-preset plugin. + record preset-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`). + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Window placement. + role: preset-role, + /// Clip kinds the preset applies to; empty means every visual clip. Kind ids: + /// `video`, `image`, `vector` and `plugin:`. + applies-to: list, + /// Default window length in ticks (positive). + default-duration-ticks: s64, + /// Preset options: number, enum-choice or bool kinds only. + params: list, + } + + /// The clip a preset is generated for. + record clip-info { + /// Clip kind id, as in `applies-to`. + kind: string, + /// Visible clip length in ticks (positive). + duration-ticks: s64, + /// Length of one project frame in ticks (positive); a sampling hint. + frame-ticks: s64, + /// Current value of every animatable numeric target at the window's rest + /// point: the end of an entrance window, the start of an exit or emphasis + /// window. Keys are the curve target ids below. + rest: list>, + } + + /// Interpolation toward the next key, matching core keyframes. + enum curve-interpolation { + hold, + linear, + ease-in-out, + } + + /// One keyframe. `time-ticks` is relative to the window start, 0..=window. + record curve-key { + time-ticks: s64, + value: f64, + interpolation: curve-interpolation, + } + + /// Keyframes for one target: `opacity`, `x`, `y`, `scale-x`, `scale-y`, + /// `rotation` (radians) or `param:` for a numeric clip parameter. + record curve { + target: string, + keys: list, + } + + /// List the presets this plugin provides. + list-presets: func() -> list; + + /// Generate the curves for `preset` over a window of `window-ticks` (positive, + /// at most the clip duration). Pure in its arguments. Returns a diagnostic on + /// invalid input, e.g. a preset that does not apply to the clip kind. + generate: func(preset: string, clip: clip-info, window-ticks: s64, params: param-map) -> result, diagnostic>; +} + +/// Bounded reads of files next to an imported source, added in API 1.1.0. +/// Only importer components import this interface. +interface import-files { + use types.{diagnostic}; + + /// Read a file relative to the directory the host granted for this import. + /// `relative-path` uses `/` separators; absolute paths, `..` components and + /// paths that resolve (through symlinks) outside the directory are refused. + /// Per-file, total-byte and file-count caps apply per call; without a granted + /// directory every read fails with `invalid-input`. + read-sibling: func(relative-path: string) -> result, diagnostic>; +} + +/// Project importers, added in API 1.1.0. +/// +/// An importer turns source bytes into a versioned command document that the host +/// validates and replays onto a fresh project, plus content-addressed asset bytes. +interface importer { + use types.{param-map, param-spec, diagnostic}; + + /// One import format offered by an importer plugin. + record importer-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`). + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Lower-case file extensions without the dot, e.g. `py`. + extensions: list, + /// Import options: string, number, enum-choice or bool kinds only. + params: list, + } + + /// The source being imported. + record import-source { + /// File name hint without directories (may be empty). + file-name: string, + /// Raw source bytes. + bytes: list, + } + + /// One asset referenced by the command document. + record imported-asset { + /// Lower-case hex BLAKE3 hash of `bytes`; the host recomputes it. + id: string, + /// Human-readable filename hint. + name: string, + /// Declared media type; decoders still probe the bytes. + media-type: string, + bytes: list, + } + + /// Non-fatal message severity. + enum message-severity { + info, + warning, + } + + /// One non-fatal observation; line and column are one-based, 0 when unknown. + record import-message { + severity: message-severity, + line: u32, + column: u32, + message: string, + snippet: string, + } + + /// A successful import. + record import-output { + /// UTF-8 JSON `{"version": 1, "commands": [...]}`: AniMathIO core commands + /// in their control-protocol serialization, replayed in order on an empty + /// project. Every command is validated; any failure rejects the import. + commands: string, + assets: list, + messages: list, + } + + /// List the formats this plugin imports. + list-importers: func() -> list; + + /// Import `source` with format `importer`. Pure apart from `read-sibling`. + run-import: func(importer: string, source: import-source, params: param-map) -> result; +} + +/// World for animation-preset plugins (`kinds = ["animation-preset"]`), API 1.1.0. +world animation-preset-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The presets themselves. + export animation-presets; +} + +/// World for importer plugins (`kinds = ["importer"]`), API 1.1.0. +world importer-plugin { + import host; + import import-files; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The import formats themselves. + export importer; +} + +/// World for audio-effect plugins (`kinds = ["audio-effect"]`): describe plus audio filters. +world audio-effect-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The audio filters themselves. + export audio-effects; +} + +/// World for effect plugins (`kinds = ["effect"]`): describe plus pixel filters. +/// Components for this world need no clip-source or animation exports. +world effect-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The pixel filters themselves. + export frame-effects; +} + +/// Pure vector generators. Frame and audio effects use their own worlds. +world source-plugin { + import host; + + use types.{manifest, scene, param-map, size, diagnostic}; + + /// Describe the plugin, its kinds and its parameter schema. + export describe: func() -> manifest; + + /// Render a vector scene, pure in its arguments. time-ticks is clip-local source + /// time in integer flicks (705600000 ticks/second). size is the render canvas. + /// An empty scene is valid; invalid geometry or traps fail the call. + export render-clip: func(params: param-map, time-ticks: s64, size: size) -> result; +}