diff --git a/CHANGELOG.md b/CHANGELOG.md index 9411e26d..06e542b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ ## Unreleased +* **HTML canvas export** (ADR 0028). File › Export › Export HTML Canvas… writes the movie as + one web page that plays in any modern browser: open it from your disk, put it on a server or + send it as one file. Everything moves exactly as on the stage, because every frame of every + timeline is computed by AniCraft (classic, shape and motion tweens, easing, motion guides, + shape hints); shapes, gradients, strokes (variable-width ones too), text, bitmaps, masks, + symbols that fade or blend as one, alpha and tint all come across. It is interactive: movie + clips play on their own timelines, buttons show Up, Over and Down and answer in their Hit + area, and frame actions and button events (stop, play, go to a frame or label in any scene, + next/previous frame and scene, trace, set properties, instance paths like `panel.door`) + behave as in Test Movie: the page's player is a port of AniCraft's and the tests run both + side by side. Sounds play with the first click (Event, Start, Stop; Stream over its span). + The movie fits the browser window, sharp on high-density screens. The demo exports in 1 ms + to a 59 KB page (18 KB of movie data). Filters, Subtract and Invert blending, tints on + bitmaps and plug-in frame scripts are reported, not exported. Headless: + `file.export_html {path, title?, sound?, fit?}`. + * **Camera layer with layer depth** (ADR 0027). Click the camera button in the timeline header (or pick the **Camera tool**, C) to add a camera: a Camera layer on top of the timeline whose frame shows on the stage as an orange outline of what the movie will show. diff --git a/Cargo.lock b/Cargo.lock index 625b7b5e..7ec8cb1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,6 +134,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -315,6 +324,7 @@ version = "0.1.0" dependencies = [ "anicraft-doc", "anicraft-geom", + "boa_engine", "png 0.17.16", "rayon", "serde_json", @@ -641,6 +651,145 @@ dependencies = [ "piper", ] +[[package]] +name = "boa_ast" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6339a700715bda376f5ea65c76e8fe8fc880930d8b0638cea68e7f3da6538e0a" +dependencies = [ + "bitflags 2.13.2", + "boa_interner", + "boa_macros", + "boa_string", + "indexmap", + "num-bigint", + "rustc-hash 2.1.3", +] + +[[package]] +name = "boa_engine" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1521be326f8a5c8887e95d4ce7f002917a002a23f7b93b9a6a2bf50ed4157824" +dependencies = [ + "aligned-vec", + "arrayvec", + "bitflags 2.13.2", + "boa_ast", + "boa_gc", + "boa_interner", + "boa_macros", + "boa_parser", + "boa_string", + "bytemuck", + "cfg-if", + "cow-utils", + "dashmap", + "dynify", + "fast-float2", + "futures-channel", + "futures-concurrency", + "futures-lite", + "hashbrown 0.16.1", + "icu_normalizer", + "indexmap", + "intrusive-collections", + "itertools 0.14.0", + "num-bigint", + "num-integer", + "num-traits", + "num_enum", + "paste", + "portable-atomic", + "rand", + "regress", + "rustc-hash 2.1.3", + "ryu-js", + "serde", + "serde_json", + "small_btree", + "static_assertions", + "tag_ptr", + "tap", + "thin-vec", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "boa_gc" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17323a98cf2e631afacf1a6d659c1212c48a68bacfa85afab0a66ade80582e51" +dependencies = [ + "boa_macros", + "boa_string", + "hashbrown 0.16.1", + "thin-vec", +] + +[[package]] +name = "boa_interner" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20510b8b02bcde9b0a01cf34c0c308c56156503d1d91cdab4c8cfbd292b747ea" +dependencies = [ + "boa_gc", + "boa_macros", + "hashbrown 0.16.1", + "indexmap", + "once_cell", + "phf", + "rustc-hash 2.1.3", + "static_assertions", +] + +[[package]] +name = "boa_macros" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5822cb4f146d243060e588bc5a5f2e709683fdad3d7111f42c48e6b5c921d23d" +dependencies = [ + "cfg-if", + "cow-utils", + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "boa_parser" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd957fa9fa93e3a001a8aba5a5cd40c2bbfde486378be4c4b472fd304aaddb" +dependencies = [ + "bitflags 2.13.2", + "boa_ast", + "boa_interner", + "boa_macros", + "fast-float2", + "icu_properties", + "num-bigint", + "num-traits", + "regress", + "rustc-hash 2.1.3", +] + +[[package]] +name = "boa_string" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2da1d7f4a76fd9040788a122f0d807910800a7b86f5952e9244848c36511de" +dependencies = [ + "fast-float2", + "itoa", + "paste", + "rustc-hash 2.1.3", + "ryu-js", + "static_assertions", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -885,6 +1034,12 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "cow-utils" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417bef24afe1460300965a25ff4a24b8b45ad011948302ec221e8a0a81eb2c79" + [[package]] name = "cpal" version = "0.18.2" @@ -961,12 +1116,32 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + [[package]] name = "dasp_sample" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "dispatch" version = "0.2.0" @@ -985,6 +1160,17 @@ dependencies = [ "objc2 0.6.5", ] +[[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.9", +] + [[package]] name = "dlib" version = "0.5.3" @@ -1015,6 +1201,26 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "dynify" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81acb15628a3e22358bf73de5e7e62360b8a777dbcb5fc9ac7dfa9ae73723747" +dependencies = [ + "dynify-macros", +] + +[[package]] +name = "dynify-macros" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec431cd708430d5029356535259c5d645d60edd3d39c54e5eea9782d46caa7d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "ecolor" version = "0.36.2" @@ -1072,7 +1278,7 @@ dependencies = [ "bitflags 2.13.2", "emath", "epaint", - "itertools", + "itertools 0.15.0", "log", "nohash-hasher", "profiling", @@ -1209,6 +1415,26 @@ version = "0.36.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13" +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -1260,6 +1486,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fast-float2" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f" + [[package]] name = "fastrand" version = "2.5.0" @@ -1293,6 +1525,12 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + [[package]] name = "flate2" version = "1.1.10" @@ -1365,6 +1603,28 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-concurrency" +version = "7.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6" +dependencies = [ + "fixedbitset", + "futures-core", + "futures-lite", + "pin-project", + "smallvec", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -1615,6 +1875,12 @@ dependencies = [ "smallvec", ] +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + [[package]] name = "hashbrown" version = "0.15.5" @@ -1656,6 +1922,95 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "icu_collections" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" +dependencies = [ + "displaydoc", + "potential_utf", + "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", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b24a59706036ba941c9476a55cd57b82b77f38a3c667d637ee7cabbc85eaedc" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" + +[[package]] +name = "icu_properties" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5a97b8ac6235e69506e8dacfb2adf38461d2ce6d3e9bd9c94c4cbc3cd4400a4" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "potential_utf", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632" + +[[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", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + [[package]] name = "image" version = "0.25.10" @@ -1680,6 +2035,24 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "intrusive-collections" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" +dependencies = [ + "memoffset", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.15.0" @@ -1872,6 +2245,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "litrs" version = "1.0.1" @@ -2042,6 +2421,23 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", + "serde", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-derive" version = "0.4.2" @@ -2053,6 +2449,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2085,6 +2490,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + [[package]] name = "objc-sys" version = "0.3.5" @@ -2521,6 +2935,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + [[package]] name = "peniko" version = "0.6.1" @@ -2708,6 +3128,30 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "presser" version = "0.3.1" @@ -2780,6 +3224,35 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -2862,6 +3335,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regress" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2057b2325e68a893284d1538021ab90279adac1139957ca2a74426c6f118fb48" +dependencies = [ + "hashbrown 0.16.1", + "memchr", +] + [[package]] name = "renderdoc-sys" version = "1.1.0" @@ -2948,6 +3431,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu-js" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" + [[package]] name = "same-file" version = "1.0.6" @@ -3113,6 +3602,15 @@ dependencies = [ "version_check", ] +[[package]] +name = "small_btree" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba60d2df92ba73864714808ca68c059734853e6ab722b40e1cf543ebb3a057a" +dependencies = [ + "arrayvec", +] + [[package]] name = "smallvec" version = "1.16.4" @@ -3206,6 +3704,12 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "static_assertions" version = "1.1.0" @@ -3244,6 +3748,40 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[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.9", +] + +[[package]] +name = "tag_ptr" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0e973b34477b7823833469eb0f5a3a60370fef7a453e02d751b59180d0a5a05" + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + [[package]] name = "tempfile" version = "3.27.0" @@ -3266,6 +3804,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "thin-vec" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6a4b9ba8738cb4a4f399d37e266becfd475e75eb73425b87a05a2f2039ba63e" + [[package]] name = "thiserror" version = "1.0.69" @@ -3320,6 +3864,49 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + [[package]] name = "tinyvec" version = "1.13.3" @@ -3471,6 +4058,21 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "utf16_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c7de35d9d8757dbc1f5125dc8b51438c68b4430546a735c3a9b91aaaaf9a18a" +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 = "uuid" version = "1.29.0" @@ -4313,6 +4915,18 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + [[package]] name = "x11-dl" version = "2.21.0" @@ -4376,6 +4990,29 @@ version = "0.8.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" +[[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.9", + "synstructure 0.14.0", +] + [[package]] name = "zbus" version = "5.19.0" @@ -4502,6 +5139,62 @@ dependencies = [ "syn 2.0.119", ] +[[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.9", + "synstructure 0.14.0", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "serde", + "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.9", +] + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index de504cb0..2943ca0a 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -294,7 +294,7 @@ impl Ctx { /// The first frame of the unbroken run of keyframes on `layer`, up to `frame`, that hold /// element `id` as an instance of `symbol`: where a movie clip instance started playing. -pub(crate) fn instance_start(layer: &Layer, frame: u32, id: ElementId, symbol: SymbolId) -> u32 { +pub fn instance_start(layer: &Layer, frame: u32, id: ElementId, symbol: SymbolId) -> u32 { let Some(mut i) = layer.keyframe_index_at(frame) else { return frame }; let holds = |k: &crate::Keyframe| k.elements.iter().any(|e| e.id == id && matches!(e.kind, ElementKind::Symbol { symbol: s, .. } if s == symbol)); let mut start = layer.keyframes.get(i).map_or(frame, |k| k.start); @@ -309,7 +309,7 @@ pub(crate) fn instance_start(layer: &Layer, frame: u32, id: ElementId, symbol: S } /// The path a guide layer's first shape traces at `frame`, in the layer's own space. -pub(crate) fn guide_walk(guide: &Layer, frame: u32) -> Option { +pub fn guide_walk(guide: &Layer, frame: u32) -> Option { let (_, els) = evaluate_layer_elements(guide, frame)?; els.iter().find_map(|e| match &e.kind { ElementKind::Shape(s) => { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 49345092..05733ff9 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -28,7 +28,7 @@ pub use motion::{MotionTween, Property, PropertyKey, Props, Track}; pub use sound::{FrameSound, Sound, SoundFormat, SoundId, SoundSync}; pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; pub use camera::Camera; -pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera}; +pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, guide_walk, instance_start}; pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, PluginScript}; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index c49d9be3..46c6a6ea 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -83,6 +83,15 @@ pub fn specs() -> Vec { mutates: false, run: export_lottie, }, + CommandSpec { + id: "file.export_html", + label: "Export HTML Canvas…", + menu: "File/Export", + shortcut: None, + params: "{path (.html: one self-contained page), title? (default: the file name), sound? (default true: embed the movie's sounds), fit? (default true: scale to the browser window), confirm?}", + mutates: false, + run: export_html, + }, CommandSpec { id: "edit.undo", label: "Undo", menu: "Edit", shortcut: Some("Ctrl+Z"), params: "{}", mutates: false, run: |s, _| s.undo() }, CommandSpec { id: "edit.redo", label: "Redo", menu: "Edit", shortcut: Some("Ctrl+Y"), params: "{}", mutates: false, run: |s, _| s.redo() }, CommandSpec { @@ -625,6 +634,44 @@ fn export_lottie(s: &mut Session, p: &Value) -> Result { Ok(json!({"written": path.display().to_string(), "frames": to - from + 1, "layers": out.layers, "bytes": out.json.len(), "report": summary, "notes": out.report})) } +/// The movie as one web page that plays in a browser, buttons and frame actions included +/// (see `anicraft_render::html`, ADR 0028). +fn export_html(s: &mut Session, p: &Value) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + let stem: String = path.file_stem().map_or_else(|| "AniCraft movie".into(), |n| n.to_string_lossy().chars().take(128).collect()); + let title = match opt_str(p, "title")? { + Some(t) if t.chars().count() > 256 => return Err(EngineError::Param("param 'title' is at most 256 characters".into())), + Some(t) if !t.trim().is_empty() => t.to_string(), + _ => stem, + }; + let opts = anicraft_render::html::HtmlOptions { title, sound: opt_bool(p, "sound")?.unwrap_or(true), fit: opt_bool(p, "fit")?.unwrap_or(true) }; + let started = std::time::Instant::now(); + let out = anicraft_render::html::to_html(&s.doc, &opts).map_err(EngineError::Param)?; + std::fs::write(&path, out.html.as_bytes())?; + let summary = if out.report.is_empty() { + String::new() + } else { + format!("Approximated or left out: {}.", out.report.iter().map(|(k, n)| format!("{k} on {n}")).collect::>().join(", ")) + }; + let st = out.stats; + Ok(json!({ + "written": path.display().to_string(), + "bytes": out.html.len(), + "frames": s.doc.frame_count(), + "scenes": s.doc.scenes.len(), + "timelines": st.timelines, + "stored_frames": st.contents, + "paths": st.paths, + "images": st.images, + "sounds": st.sounds, + "data_bytes": st.data_bytes, + "code_bytes": st.code_bytes, + "ms": started.elapsed().as_millis() as u64, + "report": summary, + "notes": out.report, + })) +} + fn export_gif(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); // The whole movie: every scene in order. diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index da491370..2fc73a75 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -109,7 +109,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { let same = s.path.as_deref() == Some(path); (!same && path.exists()).then(|| overwrite(path, "Saving")) } - "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_audio" => { + "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_audio" => { let path = Path::new(p.get("path").and_then(Value::as_str)?); path.exists().then(|| overwrite(path, "Exporting")) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7ee16307..83d2f6b5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1765,6 +1765,33 @@ fn lottie_export_writes_the_movie_and_asks_before_replacing() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn html_export_writes_one_page_that_holds_the_interactive_movie() { + let dir = std::env::temp_dir().join(format!("anicraft-html-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("menu.html"); + let mut s = Session::new(sample::interactive()); + let v = run(&mut s, "file.export_html", json!({"path": path.display().to_string()})); + let html = std::fs::read_to_string(&path).unwrap(); + assert_eq!(v["bytes"].as_u64(), Some(html.len() as u64)); + assert!(html.starts_with("") && html.contains("menu"), "the title defaults to the file name"); + assert!(html.contains("\"op\":\"goto_and_play\"") && html.contains("new AniCraft.Player"), "actions and the player are in the page"); + assert_eq!((v["scenes"].as_u64(), v["frames"].as_u64()), (Some(1), Some(u64::from(s.doc.frame_count())))); + assert!(v["timelines"].as_u64().unwrap() >= 3, "the scene, the button and the spinner: {v}"); + assert_eq!(v["report"], ""); + // Replacing needs consent; params are checked. + let p = json!({"path": path.display().to_string(), "title": "Menu", "fit": false, "sound": false}); + assert!(s.execute("file.export_html", &p).is_err()); + let mut p = p; + p["confirm"] = json!(true); + run(&mut s, "file.export_html", p); + assert!(std::fs::read_to_string(&path).unwrap().contains("Menu")); + assert!(s.execute("file.export_html", &json!({"path": dir.join("x.html").display().to_string(), "title": "t".repeat(300)})).is_err()); + assert!(s.execute("file.export_html", &json!({"path": dir.join("x.html").display().to_string(), "fit": "yes"})).is_err()); + assert!(s.execute("file.export_html", &json!({})).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn text_lays_out_renders_edits_saves_and_breaks_apart() { if anicraft_text::Fonts::get().families().is_empty() { diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index c45c8e64..3db8e2fc 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -18,3 +18,8 @@ serde_json.workspace = true [lints] workspace = true + +[dev-dependencies] +# Runs the exported HTML player's JavaScript in tests, to compare it with the Rust player +# (pure Rust, Unlicense OR MIT; tests only, never in the app). +boa_engine = { version = "0.21", default-features = false } diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs new file mode 100644 index 00000000..266dca51 --- /dev/null +++ b/crates/render/src/html.rs @@ -0,0 +1,695 @@ +//! HTML canvas export (ADR 0028): the movie as one self-contained web page that plays in any +//! modern browser with `` 2D, buttons and frame actions included. +//! +//! The page holds three things: the movie's data as JSON, the player (`html/player.js`, a port +//! of the Rust player in `anicraft-doc`) and the page code (`html/canvas.js`: drawing, timing, +//! pointer, sound). Both scripts are our own source files, embedded at build time. +//! +//! The data is baked, not re-keyed: every timeline (each scene's and each symbol's that the +//! movie uses) is evaluated frame by frame, so classic, shape and motion tweens, easing, motion +//! guides and shape hints come out exactly as AniCraft computes them, and the browser never +//! interpolates. A frame is its layers (bottom first) and their items: shapes (a path, a paint, +//! a stroke, a colour effect) and symbol instances (which the player resolves at run time: movie +//! clips have their own playheads, buttons their pointer states). Identical paths, paints and +//! frames are stored once, so a still keyframe over many frames costs one entry. +//! +//! What doesn't carry across is counted in the report: filters, Subtract and Invert blending, +//! tints on bitmaps, and plug-in frame scripts (they need the plug-in host). + +use crate::stroke::variable_outline; +use anicraft_doc::actions::{Action, FrameRef, Seg}; +use anicraft_doc::{BlendMode, ColorEffect, Document, Element, ElementKind, FrameScript, Layer, LayerKind, Paint, Rgba, SoundFormat, SoundSync, SymbolId, SymbolKind, Timeline, base64_encode, evaluate_guided, guide_walk, instance_start}; +use anicraft_geom::{Affine, FillRule, Path, PathCmd}; +use serde_json::{Map, Value, json}; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; +use std::sync::Arc; + +/// The player core: instance tree, frame actions, button events (no page access). +pub const PLAYER_JS: &str = include_str!("html/player.js"); +/// The page: canvas drawing, timing, pointer and sound. +pub const CANVAS_JS: &str = include_str!("html/canvas.js"); +/// Version of the embedded data (`"v"`), raised when the player must change to read it. +pub const FORMAT_VERSION: u32 = 1; +/// Largest page written. +pub const MAX_HTML_BYTES: usize = 512 << 20; + +/// What to export. +#[derive(Clone, Debug)] +pub struct HtmlOptions { + /// The page title. + pub title: String, + /// Embed the movie's sounds (played with Web Audio). + pub sound: bool, + /// Scale the movie to fit the browser window (else it shows at its stage size). + pub fit: bool, +} + +impl Default for HtmlOptions { + fn default() -> Self { + HtmlOptions { title: "AniCraft movie".into(), sound: true, fit: true } + } +} + +/// Counts of what the export holds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct HtmlStats { + pub timelines: usize, + /// Frames over every timeline. + pub frames: usize, + /// Distinct frames stored. + pub contents: usize, + pub paths: usize, + pub images: usize, + pub sounds: usize, + /// Bytes of movie data and of player code in the page. + pub data_bytes: usize, + pub code_bytes: usize, +} + +/// The movie's data, as the player reads it. +pub struct Movie { + pub json: Value, + /// The exported paths, by index (the shapes' own paths; the JSON holds them rounded). + pub paths: Vec>, + /// What couldn't be carried across exactly, by kind, with how many elements (or + /// keyframes) it touched. + pub report: BTreeMap, + pub stats: HtmlStats, +} + +/// The finished page. +pub struct HtmlExport { + pub html: String, + pub report: BTreeMap, + pub stats: HtmlStats, +} + +/// Notes for the report. +const FILTERS: &str = "filters (not exported; drawn without them)"; +const BLENDS: &str = "Subtract and Invert blending (drawn normally)"; +const BITMAP_TINT: &str = "tints on bitmap fills (drawn untinted)"; +const PLUGIN_SCRIPTS: &str = "plug-in frame scripts (not exported; they need the plug-in host)"; + +/// A number rounded to `1/scale`, written as an integer when it is one. +fn num(v: f32, scale: f64) -> Value { + let r = (f64::from(v) * scale).round() / scale; + if !r.is_finite() { + json!(0) + } else if r.fract() == 0.0 && r.abs() < 9e15 { + json!(r as i64) + } else { + json!(r) + } +} + +fn coord(v: f32) -> Value { + num(v, 1000.0) +} + +fn color(c: Rgba) -> Vec { + let c = c.sanitized(); + [c.r, c.g, c.b, c.a].into_iter().map(|v| num(v, 10_000.0)).collect() +} + +/// `[a, b, c, d, e, f]`, the linear part finer than the offset; `None` for the identity. +fn matrix(m: &Affine) -> Option { + if *m == Affine::IDENTITY { + return None; + } + let [a, b, c, d, e, f] = m.m; + Some(json!([num(a, 1e5), num(b, 1e5), num(c, 1e5), num(d, 1e5), coord(e), coord(f)])) +} + +/// `[alpha, tint r, g, b, tint amount]`; `None` for no effect. +fn effect(fx: &ColorEffect) -> Option { + if *fx == ColorEffect::default() { + return None; + } + let t = fx.tint.sanitized(); + let a = if fx.alpha.is_finite() { fx.alpha } else { 1.0 }; + let k = if fx.tint_amount.is_finite() { fx.tint_amount } else { 0.0 }; + Some(json!([num(a, 1e4), num(t.r, 1e4), num(t.g, 1e4), num(t.b, 1e4), num(k, 1e4)])) +} + +/// SVG path data (what `Path2D` reads), three decimals; empty when a point isn't finite. +fn path_data(p: &Path) -> String { + use std::fmt::Write; + let mut s = String::with_capacity(p.cmds.len() * 14); + let pt = |s: &mut String, x: f32, y: f32| { + let _ = write!(s, "{} {}", coord(x), coord(y)); + }; + for c in &p.cmds { + match *c { + PathCmd::MoveTo(a) => { + s.push('M'); + pt(&mut s, a.x, a.y); + } + PathCmd::LineTo(a) => { + s.push('L'); + pt(&mut s, a.x, a.y); + } + PathCmd::QuadTo(a, b) => { + s.push('Q'); + pt(&mut s, a.x, a.y); + s.push(' '); + pt(&mut s, b.x, b.y); + } + PathCmd::CubicTo(a, b, e) => { + s.push('C'); + pt(&mut s, a.x, a.y); + s.push(' '); + pt(&mut s, b.x, b.y); + s.push(' '); + pt(&mut s, e.x, e.y); + } + PathCmd::Close => s.push('Z'), + } + } + let finite = p.cmds.iter().all(|c| match *c { + PathCmd::MoveTo(a) | PathCmd::LineTo(a) => a.x.is_finite() && a.y.is_finite(), + PathCmd::QuadTo(a, b) => [a, b].iter().all(|q| q.x.is_finite() && q.y.is_finite()), + PathCmd::CubicTo(a, b, e) => [a, b, e].iter().all(|q| q.x.is_finite() && q.y.is_finite()), + PathCmd::Close => true, + }); + if finite { s } else { String::new() } +} + +/// An action as the player reads it: `op`, the target as steps (`^` the main timeline, `..` up +/// a level, else an instance name; `e` when it isn't a valid path), and `d`, its description +/// (for messages). +fn action(a: &Action) -> Value { + let mut o = Map::new(); + o.insert("op".into(), json!(a.op())); + if let Some(t) = a.target() { + match t.segments() { + Ok(segs) => { + if !segs.is_empty() { + let steps: Vec = segs + .iter() + .map(|s| match s { + Seg::Root => json!("^"), + Seg::Parent => json!(".."), + Seg::Child(n) => json!(n), + }) + .collect(); + o.insert("t".into(), Value::Array(steps)); + } + } + Err(e) => { + o.insert("e".into(), json!(e)); + } + } + } + match a { + Action::Trace { message } => { + o.insert("msg".into(), json!(message)); + } + Action::GotoAndPlay { frame, scene, .. } | Action::GotoAndStop { frame, scene, .. } => { + o.insert("f".into(), match frame { + FrameRef::Number(n) => json!(n), + FrameRef::Label(l) => json!(l), + }); + if let Some(s) = scene { + o.insert("s".into(), json!(s)); + } + } + Action::SetProperty { property, value, .. } => { + o.insert("p".into(), json!(property.key())); + o.insert("v".into(), if value.is_finite() { json!(value) } else { json!(0) }); + o.insert("pl".into(), json!(property.label().to_lowercase())); + } + _ => {} + } + if !matches!(a, Action::Trace { .. }) { + o.insert("d".into(), json!(a.describe())); + } + Value::Object(o) +} + +fn actions(list: &[Action]) -> Value { + Value::Array(list.iter().map(action).collect()) +} + +/// Whether timeline layer `index` takes part in playback (what the player walks and draws): +/// shown, not a folder or guide, not in a hidden folder. +fn plays(tl: &Timeline, index: usize) -> bool { + tl.layers.get(index).is_some_and(|l| l.visible && !matches!(l.kind, LayerKind::Folder | LayerKind::Guide)) && !tl.hidden_by_folder(index) +} + +/// Interning tables and the report, while baking. +struct Bake<'a> { + doc: &'a Document, + sound: bool, + paths: Vec>, + path_d: Vec, + by_ptr: HashMap<*const Path, usize>, + /// Every path met, kept alive so no pointer in `by_ptr` is reused by a later path. + keep: Vec>, + by_d: HashMap, + paints: Vec, + paint_ix: HashMap, + contents: Vec, + content_ix: HashMap, + symbols: HashMap, + images: Vec, + image_ix: HashMap, + sounds: Vec, + sound_ix: HashMap, + notes: BTreeMap<&'static str, BTreeSet>, +} + +impl<'a> Bake<'a> { + fn path(&mut self, p: &Arc) -> usize { + // The table keeps every path alive, so a pointer is never reused while it is a key. + if let Some(&i) = self.by_ptr.get(&Arc::as_ptr(p)) { + return i; + } + let d = path_data(p); + let i = match self.by_d.get(&d) { + Some(&i) => i, + None => { + self.path_d.push(d.clone()); + self.paths.push(p.clone()); + self.by_d.insert(d, self.paths.len() - 1); + self.paths.len() - 1 + } + }; + self.by_ptr.insert(Arc::as_ptr(p), i); + self.keep.push(p.clone()); + i + } + + fn paint(&mut self, p: &Paint, el: &Element) -> usize { + let stops = |s: &[anicraft_doc::GradientStop]| -> Vec { + s.iter() + .map(|g| { + let o = if g.offset.is_finite() { g.offset.clamp(0.0, 1.0) } else { 0.0 }; + let mut v = vec![num(o, 1e4)]; + v.extend(color(g.color)); + Value::Array(v) + }) + .collect() + }; + let v = match p { + Paint::Solid(c) => json!({"s": color(*c)}), + Paint::Linear { start, end, stops: s } => json!({"l": [coord(start.x), coord(start.y), coord(end.x), coord(end.y)], "st": stops(s)}), + Paint::Radial { center, radius, stops: s } => json!({"r": [coord(center.x), coord(center.y), coord(radius.max(0.0))], "st": stops(s)}), + Paint::Bitmap { bitmap, repeat, matrix: m } => match self.doc.bitmap(*bitmap) { + Some(b) => { + if el.color.tint_amount > 0.0 { + self.notes.entry(BITMAP_TINT).or_default().insert(el.id.0); + } + let n = self.images.len(); + let i = *self.image_ix.entry(b.id.0).or_insert(n); + if i == n { + self.images.push(format!("data:image/png;base64,{}", base64_encode(&b.png))); + } + let mut o = json!({"b": i, "rep": repeat}); + if let Some(m) = matrix(m) { + o["m"] = m; + } + o + } + // An image that can't be found shows grey, as on the stage. + None => json!({"s": color(Rgba::hex(0x808080))}), + }, + }; + let key = v.to_string(); + let n = self.paints.len(); + let i = *self.paint_ix.entry(key).or_insert(n); + if i == n { + self.paints.push(v); + } + i + } + + /// A shape item: `p` path, `f` paint, `s` stroke `[r, g, b, a, width]`, `eo` even-odd, + /// `m` transform, `c` colour effect. + fn shape(&mut self, path: &Arc, m: &Affine, fx: &ColorEffect, fill: Option<(&Paint, &Element)>, stroke: Option<(Rgba, f32)>, rule: FillRule) -> Value { + let mut o = Map::new(); + o.insert("p".into(), json!(self.path(path))); + if let Some((p, el)) = fill { + o.insert("f".into(), json!(self.paint(p, el))); + } + if let Some((c, w)) = stroke { + let mut s = color(c); + s.push(num(w, 1e3)); + o.insert("s".into(), Value::Array(s)); + } + if rule == FillRule::EvenOdd { + o.insert("eo".into(), json!(1)); + } + if let Some(m) = matrix(m) { + o.insert("m".into(), m); + } + if let Some(c) = effect(fx) { + o.insert("c".into(), c); + } + Value::Object(o) + } + + /// The items of one element on `layer` at frame `f` (its keyframe starts at `start`). + fn element(&mut self, el: &Element, layer: &Layer, f: u32, start: u32, out: &mut Vec) { + if !el.transform.is_finite() { + return; + } + match &el.kind { + ElementKind::Shape(s) => { + let stroke = s.stroke.as_ref().filter(|st| st.width.is_finite() && st.width > 0.0); + match stroke.and_then(|st| st.profile.as_ref().map(|p| (st, p))) { + // A variable-width stroke is the filled outline the renderer fills. + Some((st, profile)) => { + if let Some(p) = &s.fill { + out.push(self.shape(&s.path, &el.transform, &el.color, Some((p, el)), None, s.fill_rule)); + } + let outline = variable_outline(&s.path, &el.transform, st.width, profile, crate::TOLERANCE); + if !outline.is_empty() { + let fill = Paint::Solid(st.color); + out.push(self.shape(&Arc::new(outline), &Affine::IDENTITY, &el.color, Some((&fill, el)), None, FillRule::NonZero)); + } + } + None => out.push(self.shape(&s.path, &el.transform, &el.color, s.fill.as_ref().map(|p| (p, el)), stroke.map(|st| (st.color, st.width)), s.fill_rule)), + } + } + // The camera is the view, not artwork (ADR 0027): it is baked into the layers. + ElementKind::Camera => {} + ElementKind::Text(t) => { + let fill = Paint::Solid(t.color); + out.push(self.shape(&t.outline, &el.transform, &el.color, Some((&fill, el)), None, FillRule::NonZero)); + } + ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events } => { + let (Some(&y), Some(sym)) = (self.symbols.get(symbol), self.doc.symbol(*symbol)) else { return }; + let len = sym.timeline.frame_count(); + let mut o = Map::new(); + o.insert("y".into(), json!(y)); + o.insert("id".into(), json!(el.id.0)); + if !el.name.is_empty() { + o.insert("n".into(), json!(el.name)); + } + if let Some(m) = matrix(&el.transform) { + o.insert("m".into(), m); + } + if let Some(c) = effect(&el.color) { + o.insert("c".into(), c); + } + match sym.kind { + SymbolKind::Graphic => { + let g = loop_mode.local_frame(f.saturating_sub(start), *first_frame, len); + if g > 0 { + o.insert("g".into(), json!(g)); + } + } + SymbolKind::MovieClip => { + // Where the clip is outside the player (inside a button's hit area). + let af = f.saturating_sub(instance_start(layer, f, el.id, *symbol)) % len.max(1); + if af > 0 { + o.insert("af".into(), json!(af)); + } + } + SymbolKind::Button => {} + } + if !blend.is_normal() { + o.insert("bl".into(), json!(blend.key())); + if matches!(blend, BlendMode::Subtract | BlendMode::Invert) { + self.notes.entry(BLENDS).or_default().insert(el.id.0); + } + } + if !filters.is_empty() { + o.insert("fx".into(), json!(1)); + self.notes.entry(FILTERS).or_default().insert(el.id.0); + } + if !events.is_empty() { + o.insert("ev".into(), Value::Array(events.iter().map(|h| json!([h.event.key(), actions(&h.actions)])).collect())); + } + out.push(Value::Object(o)); + } + } + } + + fn sound(&mut self, id: anicraft_doc::SoundId) -> Option { + if !self.sound { + return None; + } + let s = self.doc.sound(id)?; + let n = self.sounds.len(); + let i = *self.sound_ix.entry(s.id.0).or_insert(n); + if i == n { + let mime = match s.format { + SoundFormat::Wav => "audio/wav", + SoundFormat::Ogg => "audio/ogg", + SoundFormat::Mp3 => "audio/mpeg", + }; + self.sounds.push(json!({"name": s.name, "mime": mime, "data": base64_encode(&s.data)})); + } + Some(i) + } + + /// One timeline: its length `n`, frames as runs `f: [[content, count]…]`, mask layer count + /// `nm`, labels `lb`, and per frame the scripts `a` and sounds `snd` of keyframes starting + /// there (top layer first). A scene's frames seen through its camera (ADR 0027) carry the + /// camera's tint (`cc`) and each layer its view (`v`: the camera and the layer's depth). + fn timeline(&mut self, tl: &Timeline, scene: bool) -> Value { + let n = tl.frame_count(); + // One clip slot per visible mask layer, top first (as the evaluator numbers them). + let slots: HashMap = tl.layers.iter().filter(|l| l.kind == LayerKind::Mask && l.visible).enumerate().map(|(i, l)| (l.id.0, i)).collect(); + let playing: Vec = (0..tl.layers.len()).filter(|&i| plays(tl, i)).collect(); + let stage = self.doc.stage; + let mut runs: Vec<(usize, u32)> = Vec::new(); + let mut scripts = Map::new(); + let mut sounds = Map::new(); + for f in 0..n { + let camera = if scene { tl.camera_at(f, &stage) } else { None }; + let mut layers = Vec::new(); + for &index in playing.iter().rev() { + let Some(layer) = tl.layers.get(index).filter(|l| l.kind != LayerKind::Camera) else { continue }; + let mut entry = Map::new(); + if let Some(v) = camera.and_then(|c| matrix(&c.view(&stage, layer.depth))) { + entry.insert("v".into(), v); + } + if layer.kind == LayerKind::Mask { + entry.insert("mk".into(), json!(slots.get(&layer.id.0).copied().unwrap_or(0))); + } else if let Some(&slot) = layer.parent.and_then(|p| slots.get(&p.0)) { + entry.insert("c".into(), json!(slot)); + } + let walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, f)); + let mut items = Vec::new(); + if let Some((start, els)) = evaluate_guided(layer, f, walk.as_ref()) { + for el in els.iter() { + self.element(el, layer, f, start, &mut items); + } + } + if items.is_empty() && layer.kind != LayerKind::Mask { + continue; + } + entry.insert("e".into(), Value::Array(items)); + layers.push(Value::Object(entry)); + } + let mut content = json!({"l": layers}); + if let Some(cc) = camera.and_then(|c| effect(&c.color())) { + content["cc"] = cc; + } + let key = content.to_string(); + let next = self.contents.len(); + let ci = *self.content_ix.entry(key).or_insert(next); + if ci == next { + self.contents.push(content); + } + match runs.last_mut() { + Some((c, count)) if *c == ci => *count += 1, + _ => runs.push((ci, 1)), + } + // What entering this frame runs and plays. + let mut a = Vec::new(); + let mut snd = Vec::new(); + for &index in &playing { + let Some(k) = tl.layers.get(index).and_then(|l| l.keyframe_starting_at(f).and_then(|k| l.keyframes.get(k))) else { continue }; + match &k.script { + Some(FrameScript::Actions(list)) => a.push(actions(list)), + Some(FrameScript::Plugin(p)) => { + self.notes.entry(PLUGIN_SCRIPTS).or_default().insert(u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0)); + a.push(json!({"plugin": format!("{} · {}", p.id, p.entry)})); + } + None => {} + } + if let Some(fs) = k.sound + && let Some(i) = self.sound(fs.sound) + { + let sync = match fs.sync { + SoundSync::Event => "event", + SoundSync::Start => "start", + SoundSync::Stop => "stop", + SoundSync::Stream => "stream", + }; + snd.push(json!([i, sync, fs.repeat.max(1), fs.looping, k.duration.max(1)])); + } + } + if !a.is_empty() { + scripts.insert(f.to_string(), Value::Array(a)); + } + if !snd.is_empty() { + sounds.insert(f.to_string(), Value::Array(snd)); + } + } + // A label names its first frame, over every layer. + let mut labels: BTreeMap<&str, u32> = BTreeMap::new(); + for k in tl.layers.iter().flat_map(|l| l.keyframes.iter()).filter(|k| !k.label.is_empty()) { + let e = labels.entry(k.label.as_str()).or_insert(k.start); + *e = (*e).min(k.start); + } + let mut o = json!({"n": n, "f": runs.iter().map(|(c, k)| json!([c, k])).collect::>()}); + if !slots.is_empty() { + o["nm"] = json!(slots.len()); + } + if !labels.is_empty() { + o["lb"] = Value::Array(labels.into_iter().map(|(l, f)| json!([l, f])).collect()); + } + if !scripts.is_empty() { + o["a"] = Value::Object(scripts); + } + if !sounds.is_empty() { + o["snd"] = Value::Object(sounds); + } + o + } +} + +/// The symbols the movie uses, in the order first met (scenes first, then inside symbols). +fn used_symbols(doc: &Document) -> Vec { + let mut seen: BTreeSet = BTreeSet::new(); + let mut order = Vec::new(); + let mut queue: VecDeque<&Timeline> = doc.scenes.iter().map(|s| &s.timeline).collect(); + while let Some(tl) = queue.pop_front() { + for el in tl.layers.iter().flat_map(|l| l.keyframes.iter()).flat_map(|k| k.elements.iter()) { + if let ElementKind::Symbol { symbol, .. } = &el.kind + && let Some(sym) = doc.symbol(*symbol) + && seen.insert(*symbol) + { + order.push(*symbol); + queue.push_back(&sym.timeline); + } + } + } + order +} + +/// The movie's data: the stage, tables (paths, paints, images, sounds), symbols, scenes, and +/// every used timeline's baked frames (scenes' first, then symbols' in `symbols` order). +pub fn movie(doc: &Document, opts: &HtmlOptions) -> Movie { + let used = used_symbols(doc); + let mut b = Bake { + doc, + sound: opts.sound, + paths: Vec::new(), + path_d: Vec::new(), + by_ptr: HashMap::new(), + keep: Vec::new(), + by_d: HashMap::new(), + paints: Vec::new(), + paint_ix: HashMap::new(), + contents: Vec::new(), + content_ix: HashMap::new(), + symbols: used.iter().enumerate().map(|(i, s)| (*s, i)).collect(), + images: Vec::new(), + image_ix: HashMap::new(), + sounds: Vec::new(), + sound_ix: HashMap::new(), + notes: BTreeMap::new(), + }; + let scenes = doc.scenes.len(); + let mut timelines = Vec::with_capacity(scenes + used.len()); + let mut frames = 0usize; + for s in &doc.scenes { + frames += s.timeline.frame_count() as usize; + timelines.push(b.timeline(&s.timeline, true)); + } + let mut symbols = Vec::with_capacity(used.len()); + for (i, id) in used.iter().enumerate() { + let Some(sym) = doc.symbol(*id) else { continue }; + frames += sym.timeline.frame_count() as usize; + timelines.push(b.timeline(&sym.timeline, false)); + let kind = match sym.kind { + SymbolKind::Graphic => "graphic", + SymbolKind::MovieClip => "movieclip", + SymbolKind::Button => "button", + }; + symbols.push(json!({"name": sym.name, "k": kind, "tl": scenes + i})); + } + let stage = doc.stage; + let fps = if stage.fps.is_finite() && stage.fps > 0.0 { stage.fps } else { 24.0 }; + let json = json!({ + "v": FORMAT_VERSION, + "generator": format!("AniCraft {}", env!("CARGO_PKG_VERSION")), + "stage": {"w": stage.width.max(1), "h": stage.height.max(1), "fps": num(fps, 1000.0), "bg": stage.background.to_hex()}, + "fit": opts.fit, + "scenes": doc.scenes.iter().enumerate().map(|(i, s)| json!({"name": s.name, "tl": i})).collect::>(), + "symbols": symbols, + "timelines": timelines, + "contents": b.contents, + "paths": b.path_d, + "paints": b.paints, + "images": b.images, + "sounds": b.sounds, + }); + let stats = HtmlStats { + timelines: json["timelines"].as_array().map_or(0, Vec::len), + frames, + contents: json["contents"].as_array().map_or(0, Vec::len), + paths: b.paths.len(), + images: json["images"].as_array().map_or(0, Vec::len), + sounds: json["sounds"].as_array().map_or(0, Vec::len), + data_bytes: 0, + code_bytes: PLAYER_JS.len() + CANVAS_JS.len(), + }; + let report = b.notes.into_iter().map(|(k, v)| (k.to_string(), v.len())).collect(); + Movie { json, paths: b.paths, report, stats } +} + +/// Text for HTML content and attributes. +fn escape_html(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c if c.is_control() => {} + c => out.push(c), + } + } + out +} + +/// The movie as one web page: the data, the player and the page code inline, images and +/// sounds embedded, so the file plays from a disk, a server or an e-mail attachment alike. +pub fn to_html(doc: &Document, opts: &HtmlOptions) -> Result { + let mut m = movie(doc, opts); + // In a & \"knobs\"".into(), ..Default::default() }).unwrap(); + assert!(e.html.starts_with("")); + assert!(e.html.contains("Doors </script> & "knobs"")); + for js in [PLAYER_JS, CANVAS_JS] { + assert!(!js.to_ascii_lowercase().contains("").count(), 2); + let start = e.html.find("id=\"anicraft-movie\">").unwrap() + "id=\"anicraft-movie\">".len(); + let end = start + e.html[start..].find("").unwrap(); + let back: Value = serde_json::from_str(&e.html[start..end]).unwrap(); + assert_eq!(back, movie(&doc, &HtmlOptions::default()).json); + assert_eq!(back["v"], FORMAT_VERSION); + assert_eq!(back["scenes"].as_array().unwrap().len(), 2); + assert_eq!((back["stage"]["w"].as_u64(), back["stage"]["fps"].as_f64()), (Some(640), Some(24.0))); + assert_eq!(e.stats.data_bytes, end - start); + assert!(e.report.is_empty(), "nothing lost: {:?}", e.report); + // The page code needs a browser to run, but it must compile. + let mut ctx = Context::default(); + ctx.eval(Source::from_bytes(&format!("new Function({})", json!(CANVAS_JS)))).unwrap_or_else(|e| panic!("canvas.js: {e}")); +} + +#[test] +fn frames_are_baked_and_stored_once() { + let doc = sample::demo(); + let m = movie(&doc, &HtmlOptions::default()); + let frames = doc.frame_count() as usize; + assert_eq!(m.json["timelines"][0]["n"].as_u64(), Some(frames as u64)); + assert!(m.stats.frames >= frames && m.stats.contents <= m.stats.frames, "{:?}", m.stats); + // A keyframe held over many frames is one stored frame. + let mut still = Document::default(); + { + let l = Arc::make_mut(&mut still.timeline_mut(0).layers[0]); + l.keyframes = vec![kf(0, 50, vec![rect(9, 0.0, 0.0, 10.0, 10.0, 0xff0000)], vec![], "")]; + } + let s = movie(&still, &HtmlOptions::default()); + assert_eq!((s.stats.frames, s.stats.contents, s.json["timelines"][0]["f"].clone()), (50, 1, json!([[0, 50]]))); + // Runs add up to each timeline's length. + for tl in m.json["timelines"].as_array().unwrap() { + let total: u64 = tl["f"].as_array().unwrap().iter().map(|r| r[1].as_u64().unwrap()).sum(); + assert_eq!(Some(total), tl["n"].as_u64()); + } + // A still shape over many frames is one path; a tween moves its transform, not its path. + assert!(m.stats.paths < 40, "{:?}", m.stats); + // Unused library symbols stay out. + let mut d = doc.clone(); + d.library.push(Arc::new(Symbol { id: SymbolId(999_999), name: "unused".into(), kind: SymbolKind::Graphic, timeline: Timeline::default() })); + assert_eq!(movie(&d, &HtmlOptions::default()).json["symbols"], m.json["symbols"]); +} + +#[test] +fn variable_width_strokes_become_filled_outlines() { + use anicraft_doc::{ProfilePreset, Stroke}; + let mut doc = Document::default(); + let shape = Shape { path: Arc::new(Path::line(Vec2::new(10.0, 10.0), Vec2::new(200.0, 10.0))), fill: None, stroke: Some(Stroke::new(Rgba::hex(0x00ff00), 10.0).with_profile(ProfilePreset::TaperEnd.profile())), fill_rule: FillRule::NonZero }; + let el = Element { id: ElementId(77), name: String::new(), transform: Affine::translate(5.0, 0.0), color: Default::default(), kind: ElementKind::Shape(shape) }; + Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements.push(Arc::new(el)); + let m = movie(&doc, &HtmlOptions::default()); + let items = &m.json["contents"][0]["l"][0]["e"]; + assert_eq!(items.as_array().unwrap().len(), 1); + assert!(items[0]["f"].is_u64() && items[0]["s"].is_null(), "{items}"); + assert!(items[0]["m"].is_null(), "the outline is already in place"); +} + +#[test] +fn what_does_not_carry_across_is_reported() { + let mut doc = fixture(); + let tl = doc.timeline_mut(0); + let l = Arc::make_mut(&mut tl.layers[2]); + let k = l.keyframe_mut(0).unwrap(); + if let ElementKind::Symbol { filters, blend, .. } = &mut Arc::make_mut(&mut k.elements[0]).kind { + filters.push(anicraft_doc::Filter::Blur { blur_x: 4.0, blur_y: 4.0, quality: 1 }); + *blend = BlendMode::Subtract; + } + Arc::make_mut(&mut tl.layers[0]).keyframe_mut(1).unwrap().script = Some(FrameScript::Plugin(PluginScript { id: "org.example.menu".into(), entry: "main".into() })); + let m = movie(&doc, &HtmlOptions::default()); + assert_eq!(m.report.get(FILTERS), Some(&1)); + assert_eq!(m.report.get(BLENDS), Some(&1)); + assert_eq!(m.report.get(PLUGIN_SCRIPTS), Some(&1)); + // The player says so when the frame script's keyframe is entered. + let mut js = Js::new(&m); + js.eval("P.start()"); + let lines: Vec = (0..3).map(|_| js.eval("P.step([]).output")).collect(); + assert!(lines[2].to_string().contains("Frame script org.example.menu · main not run"), "{lines:?}"); +} + +#[test] +fn bitmaps_and_sounds_are_embedded_once() { + let mut doc = Document::default(); + let png = { + let mut out = Vec::new(); + let mut enc = png::Encoder::new(&mut out, 1, 1); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.write_header().unwrap().write_image_data(&[255, 0, 0, 255]).unwrap(); + out + }; + let bitmap = anicraft_doc::Bitmap::from_png(anicraft_doc::BitmapId(50), "dot", png).unwrap(); + doc.bitmaps.push(Arc::new(bitmap)); + let wav = anicraft_doc::audio::wav::encode(8000, 1, &[0.0; 80], anicraft_doc::audio::wav::Bits::Int16); + doc.sounds.push(Arc::new(anicraft_doc::Sound::from_data(anicraft_doc::SoundId(60), "beep", wav).unwrap())); + let fill = Paint::Bitmap { bitmap: anicraft_doc::BitmapId(50), repeat: true, matrix: Affine::scale(2.0, 2.0) }; + let a = Element { id: ElementId(70), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), fill.clone())) }; + let b = Element { id: ElementId(71), kind: ElementKind::Shape(Shape::filled(Path::rect(20.0, 0.0, 10.0, 10.0), fill)), ..a.clone() }; + { + let k = Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap(); + k.elements = vec![Arc::new(a), Arc::new(b)]; + k.sound = Some(anicraft_doc::FrameSound::new(anicraft_doc::SoundId(60))); + } + let m = movie(&doc, &HtmlOptions::default()); + assert_eq!(m.stats.images, 1); + assert!(m.json["images"][0].as_str().unwrap().starts_with("data:image/png;base64,iVBOR")); + assert_eq!(m.json["paints"][0], json!({"b": 0, "rep": true, "m": [2, 0, 0, 2, 0, 0]})); + assert_eq!(m.json["sounds"][0]["mime"], "audio/wav"); + assert_eq!(m.json["timelines"][0]["snd"]["0"], json!([[0, "event", 1, false, 1]])); + // The player hands the frame's sounds to the page. + let mut js = Js::new(&m); + assert_eq!(js.eval("P.start().sounds"), json!([[0, "event", 1, false, 1]])); + let silent = movie(&doc, &HtmlOptions { sound: false, ..Default::default() }); + assert_eq!((silent.stats.sounds, silent.json["timelines"][0].get("snd")), (0, None)); +} + +#[test] +fn hostile_documents_export_without_panicking() { + let mut doc = Document::default(); + let bad = Element { id: ElementId(5), name: "x".into(), transform: Affine { m: [f32::NAN, 0.0, 0.0, 1.0, f32::INFINITY, 0.0] }, color: ColorEffect { alpha: f32::NAN, tint: Rgba::new(f32::NAN, 2.0, -1.0, 1.0), tint_amount: f32::INFINITY }, kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, f32::NAN, 1.0), Paint::Radial { center: Vec2::ZERO, radius: -5.0, stops: vec![GradientStop { offset: f32::NAN, color: Rgba::BLACK }] })) }; + let fine = Element { id: ElementId(6), transform: Affine::IDENTITY, ..bad.clone() }; + let missing = inst(7, 12345, "ghost", Affine::IDENTITY, vec![]); + Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements = vec![Arc::new(bad), Arc::new(fine), missing]; + let e = to_html(&doc, &HtmlOptions::default()).unwrap(); + assert!(!e.html.contains("NaN") && !e.html.contains("inf"), "numbers stay finite"); + let m = movie(&doc, &HtmlOptions::default()); + assert_eq!(m.json["paths"][0], "", "a path with a NaN point is left empty"); + let mut js = Js::new(&m); + js.eval("P.start()"); + js.eval("P.step([{type: 'move', x: 1, y: 1}])"); + // An empty document is a one-frame movie. + let m = movie(&Document::default(), &HtmlOptions::default()); + assert_eq!(m.json["timelines"][0]["n"], 1); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b79a011c..e02083e5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -8,6 +8,7 @@ pub mod paint; pub mod raster; pub mod stroke; mod filters; +pub mod html; pub mod lottie; pub mod svg; diff --git a/docs/adr/0028-html-canvas-export.md b/docs/adr/0028-html-canvas-export.md new file mode 100644 index 00000000..a2408880 --- /dev/null +++ b/docs/adr/0028-html-canvas-export.md @@ -0,0 +1,179 @@ +# ADR 0028: HTML canvas export + +* Status: accepted (2026-11-09), first slice +* Relates to: ADR 0024 (frame actions, the action IR and the pure player), ADR 0027 (camera + layer and layer depth), ADR 0013 + (ActionScript), ADR 0010 (mask layers), ADR 0016 (motion tweens), ADR 0018 (variable-width + strokes), ADR 0020 (audio), ADR 0002 (the CPU renderer is the oracle), roadmap M6 + +## Context + +Animate's most used publish target today is HTML5 Canvas: a web page that plays the movie, +buttons and timeline scripts included. Our users expect File › Export to give them that, as a +file they can open in a browser, put on a server or send to someone. ADR 0024 gave us the +interactivity model: a typed action IR and a pure, budgeted player in `anicraft-doc`. This +ADR decides what the page contains, how the movie's data is represented, how the browser runs +the player's semantics, and how we keep the browser's behaviour equal to ours. + +## Decision + +### One self-contained `.html` file + +The page holds the movie's data as JSON (in a `