swf2js 0.1.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (416) hide show
  1. package/README.md +81 -14
  2. package/package.json +11 -7
  3. package/studio/actionscript-roundtrip.test.js +54 -0
  4. package/studio/actionscript-scripts.test.js +169 -0
  5. package/studio/animated-image.test.js +137 -0
  6. package/studio/arithmetic.test.js +16 -0
  7. package/studio/as3-import.test.js +110 -0
  8. package/studio/audio-info.test.js +44 -0
  9. package/studio/components.test.js +152 -0
  10. package/studio/document-editing.test.js +92 -0
  11. package/studio/examples/01-space-mission.json +1628 -0
  12. package/studio/examples/02-clockwork-vault.json +1079 -0
  13. package/studio/examples/03-neon-synth.json +1364 -0
  14. package/studio/examples/04-kinetic-poster.json +923 -0
  15. package/studio/examples/05-signal-relay.json +1131 -0
  16. package/studio/examples/06-calculator.json +564 -0
  17. package/studio/frame-editing.test.js +129 -0
  18. package/studio/frame-events.test.js +117 -0
  19. package/studio/groups.test.js +88 -0
  20. package/studio/index.html +962 -0
  21. package/studio/interaction-triggers.test.js +37 -0
  22. package/studio/linked-actions.test.js +48 -0
  23. package/studio/lottie.test.js +208 -0
  24. package/studio/masks.test.js +43 -0
  25. package/studio/media-assets.test.js +62 -0
  26. package/studio/paint-tools.test.js +60 -0
  27. package/studio/playback.test.js +17 -0
  28. package/studio/project-io.test.js +405 -0
  29. package/studio/project-preview.test.js +475 -0
  30. package/studio/scene-transition.test.js +32 -0
  31. package/studio/server/archive-companions.js +27 -0
  32. package/studio/server/as3-library.js +91 -0
  33. package/studio/server/assets.js +162 -0
  34. package/studio/server/audio-info.js +82 -0
  35. package/studio/server/font-files.js +332 -0
  36. package/studio/server/http.js +135 -0
  37. package/studio/server/linked-actions.js +93 -0
  38. package/studio/server/png-decode.js +1 -0
  39. package/studio/server/project-movie.js +1164 -0
  40. package/studio/server/project-preview.js +152 -0
  41. package/studio/server/projects.js +370 -0
  42. package/studio/server/report.js +29 -0
  43. package/studio/server/routes.js +93 -0
  44. package/studio/server/swf-authoring.js +90 -0
  45. package/studio/server/swf-control-runtime.as +513 -0
  46. package/studio/server/swf-controls.js +119 -0
  47. package/studio/server/swf-export.js +293 -0
  48. package/studio/server/swf-import.js +1675 -0
  49. package/studio/server/swf-morphs.js +64 -0
  50. package/studio/server/swf-routes.js +42 -0
  51. package/studio/server/swf-streams.js +80 -0
  52. package/studio/server/swf-transition-runtime.as +52 -0
  53. package/studio/server/tween-recovery.js +106 -0
  54. package/studio/server-api.test.js +283 -0
  55. package/studio/server.js +320 -0
  56. package/studio/src/animated-image.js +423 -0
  57. package/studio/src/appearance-inspector.js +63 -0
  58. package/studio/src/arithmetic.js +50 -0
  59. package/studio/src/authored-controls.js +42 -0
  60. package/studio/src/busy.js +41 -0
  61. package/studio/src/canvas.js +430 -0
  62. package/studio/src/clipper-browser.js +2 -0
  63. package/studio/src/color-transform.js +38 -0
  64. package/studio/src/component-inspector.js +126 -0
  65. package/studio/src/components.js +268 -0
  66. package/studio/src/display-frame.js +262 -0
  67. package/studio/src/document-editing.js +69 -0
  68. package/studio/src/event-editor.js +150 -0
  69. package/studio/src/frame-editing.js +150 -0
  70. package/studio/src/frame-events.js +128 -0
  71. package/studio/src/frame-image.js +28 -0
  72. package/studio/src/groups.js +125 -0
  73. package/studio/src/handler-editor.js +122 -0
  74. package/studio/src/history.js +83 -0
  75. package/studio/src/imported-paths.js +99 -0
  76. package/studio/src/index.js +3582 -0
  77. package/studio/src/interaction-triggers.js +42 -0
  78. package/studio/src/json-patch.js +77 -0
  79. package/studio/src/layer-icons.js +25 -0
  80. package/studio/src/lottie-export.js +948 -0
  81. package/studio/src/lottie-import.js +1138 -0
  82. package/studio/src/masks.js +69 -0
  83. package/studio/src/media-assets.js +188 -0
  84. package/studio/src/media-library.js +193 -0
  85. package/studio/src/model.js +431 -0
  86. package/studio/src/numeric-fields.js +46 -0
  87. package/studio/src/object-list.js +57 -0
  88. package/studio/src/paint-tools.js +76 -0
  89. package/studio/src/placement-effects.js +74 -0
  90. package/studio/src/playback.js +10 -0
  91. package/studio/src/preview-audio.js +64 -0
  92. package/studio/src/preview-interactions.js +106 -0
  93. package/studio/src/preview-recorder.js +335 -0
  94. package/studio/src/preview-surface.js +338 -0
  95. package/studio/src/project-io.js +905 -0
  96. package/studio/src/project-session.js +375 -0
  97. package/studio/src/projects-dialog.js +319 -0
  98. package/studio/src/scene-transition.js +129 -0
  99. package/studio/src/script-editor.js +175 -0
  100. package/studio/src/script-references.js +74 -0
  101. package/studio/src/scripted-controls.js +146 -0
  102. package/studio/src/scripts.js +185 -0
  103. package/studio/src/stage-guides.js +101 -0
  104. package/studio/src/svg-animation.js +416 -0
  105. package/studio/src/svg-context.js +522 -0
  106. package/studio/src/svg-frame.js +413 -0
  107. package/studio/src/svg-import.js +1208 -0
  108. package/studio/src/swf-recording.js +104 -0
  109. package/studio/src/symbol-library.js +39 -0
  110. package/studio/src/symbols.js +62 -0
  111. package/studio/src/text-fields.js +58 -0
  112. package/studio/src/theme.js +43 -0
  113. package/studio/src/timeline.js +321 -0
  114. package/studio/src/vector-cut.js +103 -0
  115. package/studio/src/vector-geometry.js +254 -0
  116. package/studio/src/vector-style.js +146 -0
  117. package/studio/src/video-encode.js +84 -0
  118. package/studio/src/video-export.js +331 -0
  119. package/studio/src/video-mux.js +339 -0
  120. package/studio/src/video-playback.js +281 -0
  121. package/studio/src/workspace.js +344 -0
  122. package/studio/stroke-style.test.js +119 -0
  123. package/studio/styles.css +1547 -0
  124. package/studio/svg-export.test.js +162 -0
  125. package/studio/svg-import.test.js +318 -0
  126. package/studio/swf-authoring.test.js +140 -0
  127. package/studio/swf-export.test.js +324 -0
  128. package/studio/swf-import.test.js +489 -0
  129. package/studio/symbols.test.js +68 -0
  130. package/studio/tests/accessibility-interactions.mjs +138 -0
  131. package/studio/tests/appearance-interactions.mjs +103 -0
  132. package/studio/tests/control-interactions.mjs +60 -0
  133. package/studio/tests/event-interactions.mjs +117 -0
  134. package/studio/tests/external-resources.mjs +174 -0
  135. package/studio/tests/frame-image.mjs +71 -0
  136. package/studio/tests/html-export.mjs +68 -0
  137. package/studio/tests/import-files.mjs +131 -0
  138. package/studio/tests/lottie.mjs +125 -0
  139. package/studio/tests/mask-interactions.mjs +148 -0
  140. package/studio/tests/media-interactions.mjs +109 -0
  141. package/studio/tests/paint-interactions.mjs +64 -0
  142. package/studio/tests/project-interactions.mjs +244 -0
  143. package/studio/tests/script-interactions.mjs +178 -0
  144. package/studio/tests/scripted-control-interactions.mjs +107 -0
  145. package/studio/tests/svg-export.mjs +149 -0
  146. package/studio/tests/text-field-interactions.mjs +64 -0
  147. package/studio/tests/theme-interactions.mjs +53 -0
  148. package/studio/tests/timeline-browser.mjs +507 -0
  149. package/studio/tests/transition-interactions.mjs +94 -0
  150. package/studio/tests/trigger-interactions.mjs +93 -0
  151. package/studio/tests/video-export.mjs +243 -0
  152. package/studio/tests/workspace-interactions.mjs +226 -0
  153. package/studio/tween-recovery.test.js +31 -0
  154. package/studio/vector-style.test.js +56 -0
  155. package/studio/video-export.test.js +326 -0
  156. package/studiospec/actionscript.md +88 -0
  157. package/studiospec/architecture.md +378 -0
  158. package/studiospec/controls.md +100 -0
  159. package/studiospec/file-support.md +268 -0
  160. package/studiospec/lottie.md +69 -0
  161. package/studiospec/requirements.md +135 -0
  162. package/studiospec/stroke-style.md +95 -0
  163. package/studiospec/svg-export.md +83 -0
  164. package/studiospec/svg-import.md +139 -0
  165. package/studiospec/swooflib-integration.md +115 -0
  166. package/studiospec/tasks.md +573 -0
  167. package/studiospec/video-export.md +127 -0
  168. package/swf2js/__tests__/actionscript.test.js +1609 -0
  169. package/swf2js/__tests__/adpcm-audio.test.js +43 -0
  170. package/swf2js/__tests__/as2-compiler.test.js +153 -0
  171. package/swf2js/__tests__/as3-mixed-depth.test.js +498 -0
  172. package/swf2js/__tests__/authored-sprite-hit.test.js +118 -0
  173. package/swf2js/__tests__/authored-sprite-sizing.test.js +164 -0
  174. package/swf2js/__tests__/avm1-action-prefix.test.js +134 -0
  175. package/swf2js/__tests__/avm1-attach-movie.test.js +1151 -0
  176. package/swf2js/__tests__/avm1-boxhead-budget.test.js +73 -0
  177. package/swf2js/__tests__/avm1-cfg-bubble-tanks.test.js +101 -0
  178. package/swf2js/__tests__/avm1-cfg-mario-kart.test.js +184 -0
  179. package/swf2js/__tests__/avm1-cfg-mario.test.js +31 -0
  180. package/swf2js/__tests__/avm1-cfg-pacman.test.js +49 -0
  181. package/swf2js/__tests__/avm1-checkers-gameplay.test.js +122 -0
  182. package/swf2js/__tests__/avm1-clip-actions.test.js +2002 -0
  183. package/swf2js/__tests__/avm1-clone-drag.test.js +626 -0
  184. package/swf2js/__tests__/avm1-decompiler.test.js +102 -0
  185. package/swf2js/__tests__/avm1-dynamic-locals.test.js +159 -0
  186. package/swf2js/__tests__/avm1-formal-parameters.test.js +71 -0
  187. package/swf2js/__tests__/avm1-key-events.test.js +52 -0
  188. package/swf2js/__tests__/avm1-load-bitmap.test.js +75 -0
  189. package/swf2js/__tests__/avm1-loading-host-actions.test.js +764 -0
  190. package/swf2js/__tests__/avm1-multibyte-strings.test.js +63 -0
  191. package/swf2js/__tests__/avm1-pacman-gameplay.test.js +115 -0
  192. package/swf2js/__tests__/avm1-shape-hittest.test.js +311 -0
  193. package/swf2js/__tests__/avm1-shared-bodies.test.js +57 -0
  194. package/swf2js/__tests__/avm1-shared-runtime.test.js +1364 -0
  195. package/swf2js/__tests__/avm1-snake-gameplay.test.js +139 -0
  196. package/swf2js/__tests__/avm1-super.test.js +70 -0
  197. package/swf2js/__tests__/avm1-target-path.test.js +325 -0
  198. package/swf2js/__tests__/avm1-try.test.js +229 -0
  199. package/swf2js/__tests__/avm2-activation-closures.test.js +65 -0
  200. package/swf2js/__tests__/avm2-applytype.test.js +180 -0
  201. package/swf2js/__tests__/avm2-call-ops.test.js +232 -0
  202. package/swf2js/__tests__/avm2-callsuperid.test.js +231 -0
  203. package/swf2js/__tests__/avm2-class-initializer.test.js +219 -0
  204. package/swf2js/__tests__/avm2-custom-namespace.test.js +139 -0
  205. package/swf2js/__tests__/avm2-describe-type.test.js +96 -0
  206. package/swf2js/__tests__/avm2-dictionary.test.js +96 -0
  207. package/swf2js/__tests__/avm2-domain-memory.test.js +332 -0
  208. package/swf2js/__tests__/avm2-e4x.test.js +326 -0
  209. package/swf2js/__tests__/avm2-exceptions.test.js +81 -0
  210. package/swf2js/__tests__/avm2-findprop.test.js +110 -0
  211. package/swf2js/__tests__/avm2-getlex.test.js +166 -0
  212. package/swf2js/__tests__/avm2-global-slot.test.js +106 -0
  213. package/swf2js/__tests__/avm2-interface.test.js +95 -0
  214. package/swf2js/__tests__/avm2-multiname-precedence.test.js +148 -0
  215. package/swf2js/__tests__/avm2-named-namespace-types.test.js +106 -0
  216. package/swf2js/__tests__/avm2-optional-args.test.js +100 -0
  217. package/swf2js/__tests__/avm2-outer-scopes.test.js +101 -0
  218. package/swf2js/__tests__/avm2-package-internal-class.test.js +106 -0
  219. package/swf2js/__tests__/avm2-protected-namespace.test.js +105 -0
  220. package/swf2js/__tests__/avm2-protected.test.js +214 -0
  221. package/swf2js/__tests__/avm2-qwop-gameplay.test.js +116 -0
  222. package/swf2js/__tests__/avm2-runtime-namespaces.test.js +159 -0
  223. package/swf2js/__tests__/avm2-script-traits.test.js +89 -0
  224. package/swf2js/__tests__/avm2-shared-runtime.test.js +52 -0
  225. package/swf2js/__tests__/avm2-slot-ops.test.js +117 -0
  226. package/swf2js/__tests__/avm2-type-ops.test.js +224 -0
  227. package/swf2js/__tests__/bevel-filter.test.js +116 -0
  228. package/swf2js/__tests__/bitmap-button-mask.test.js +106 -0
  229. package/swf2js/__tests__/bitmap-data-draw.test.js +388 -0
  230. package/swf2js/__tests__/bitmap-decoder.test.js +108 -0
  231. package/swf2js/__tests__/bitmapdata-color-bounds.test.js +70 -0
  232. package/swf2js/__tests__/bitmapdata-copy-channel.test.js +91 -0
  233. package/swf2js/__tests__/bitmapdata-copy-pixels.test.js +136 -0
  234. package/swf2js/__tests__/bitmapdata-fill-compare.test.js +241 -0
  235. package/swf2js/__tests__/bitmapdata-filter.test.js +232 -0
  236. package/swf2js/__tests__/bitmapdata-hit-test.test.js +71 -0
  237. package/swf2js/__tests__/bitmapdata-merge.test.js +84 -0
  238. package/swf2js/__tests__/bitmapdata-palette-map.test.js +92 -0
  239. package/swf2js/__tests__/bitmapdata-pixels-io.test.js +198 -0
  240. package/swf2js/__tests__/bitmapdata-threshold.test.js +97 -0
  241. package/swf2js/__tests__/bitmapdata-vector.test.js +82 -0
  242. package/swf2js/__tests__/blur-filter.test.js +48 -0
  243. package/swf2js/__tests__/bundle-emitter.test.js +394 -0
  244. package/swf2js/__tests__/button-actions.test.js +370 -0
  245. package/swf2js/__tests__/button-color-transform.test.js +48 -0
  246. package/swf2js/__tests__/button-decoder.test.js +106 -0
  247. package/swf2js/__tests__/button-hit-test.test.js +825 -0
  248. package/swf2js/__tests__/button-scaling-grid.test.js +124 -0
  249. package/swf2js/__tests__/button-sound.test.js +105 -0
  250. package/swf2js/__tests__/bytearray-coercion.test.js +23 -0
  251. package/swf2js/__tests__/bytearray-object-serialization.test.js +380 -0
  252. package/swf2js/__tests__/cfg-switch-loop.test.js +103 -0
  253. package/swf2js/__tests__/clip-depth-mask.test.js +119 -0
  254. package/swf2js/__tests__/clipped-bitmap-fill.test.js +118 -0
  255. package/swf2js/__tests__/companion-swf.test.js +638 -0
  256. package/swf2js/__tests__/context-menu.test.js +149 -0
  257. package/swf2js/__tests__/convolution-filter.test.js +74 -0
  258. package/swf2js/__tests__/definefont4.test.js +280 -0
  259. package/swf2js/__tests__/display-displacement.test.js +161 -0
  260. package/swf2js/__tests__/display-list.test.js +80 -0
  261. package/swf2js/__tests__/display-mask-render.test.js +656 -0
  262. package/swf2js/__tests__/displayobject-stage.test.js +320 -0
  263. package/swf2js/__tests__/embedded-script-audio.test.js +131 -0
  264. package/swf2js/__tests__/embedded-swf.test.js +202 -0
  265. package/swf2js/__tests__/embedded-textfield.test.js +107 -0
  266. package/swf2js/__tests__/embedded-timeline-audio.test.js +182 -0
  267. package/swf2js/__tests__/embedded-timeline-input.test.js +420 -0
  268. package/swf2js/__tests__/embedded-timer-lifecycle.test.js +145 -0
  269. package/swf2js/__tests__/event-priority-order.test.js +125 -0
  270. package/swf2js/__tests__/event-weak-listeners.test.js +53 -0
  271. package/swf2js/__tests__/event-will-trigger.test.js +43 -0
  272. package/swf2js/__tests__/flash-text-engine-content.test.js +115 -0
  273. package/swf2js/__tests__/flash-text-engine-format.test.js +95 -0
  274. package/swf2js/__tests__/flash-text-engine-line.test.js +314 -0
  275. package/swf2js/__tests__/font-encoder.test.js +95 -0
  276. package/swf2js/__tests__/font-outline-text.test.js +659 -0
  277. package/swf2js/__tests__/glow-shadow-filter.test.js +68 -0
  278. package/swf2js/__tests__/graphics-bitmap-smoothing.test.js +32 -0
  279. package/swf2js/__tests__/graphics-fill-lifetime.test.js +36 -0
  280. package/swf2js/__tests__/graphics-gradient-matrix.test.js +53 -0
  281. package/swf2js/__tests__/graphics-stroke-hit-test.test.js +457 -0
  282. package/swf2js/__tests__/hit-test-primitives.test.js +414 -0
  283. package/swf2js/__tests__/input-events.test.js +714 -0
  284. package/swf2js/__tests__/integration/corpus.test.js +41 -0
  285. package/swf2js/__tests__/loader-embedded-swf.test.js +210 -0
  286. package/swf2js/__tests__/loader-info.test.js +81 -0
  287. package/swf2js/__tests__/local-connection.test.js +122 -0
  288. package/swf2js/__tests__/morph-focal-gradient.test.js +51 -0
  289. package/swf2js/__tests__/morph-topology.test.js +267 -0
  290. package/swf2js/__tests__/movie-data-codec.test.js +128 -0
  291. package/swf2js/__tests__/nellymoser-audio.test.js +84 -0
  292. package/swf2js/__tests__/opaque-background-cache.test.js +352 -0
  293. package/swf2js/__tests__/path-stream.test.js +81 -0
  294. package/swf2js/__tests__/place-object-filters.test.js +88 -0
  295. package/swf2js/__tests__/place-object3-decoder.test.js +116 -0
  296. package/swf2js/__tests__/place-object3-image.test.js +85 -0
  297. package/swf2js/__tests__/player-version.test.js +46 -0
  298. package/swf2js/__tests__/root-textfield.test.js +287 -0
  299. package/swf2js/__tests__/scaling-grid.test.js +183 -0
  300. package/swf2js/__tests__/shape-decoder.test.js +361 -0
  301. package/swf2js/__tests__/shape-line-style2.test.js +138 -0
  302. package/swf2js/__tests__/shape-nonscaling-stroke.test.js +131 -0
  303. package/swf2js/__tests__/shape-pixel-hint.test.js +101 -0
  304. package/swf2js/__tests__/simplebutton-pointer.test.js +1477 -0
  305. package/swf2js/__tests__/socket-offline.test.js +67 -0
  306. package/swf2js/__tests__/sound-avm1-stop.test.js +99 -0
  307. package/swf2js/__tests__/sound-envelope.test.js +110 -0
  308. package/swf2js/__tests__/sound-extract.test.js +168 -0
  309. package/swf2js/__tests__/sound-id3.test.js +283 -0
  310. package/swf2js/__tests__/sound-load.test.js +259 -0
  311. package/swf2js/__tests__/sound-mixer-spectrum.test.js +261 -0
  312. package/swf2js/__tests__/sound-stream-sprite.test.js +624 -0
  313. package/swf2js/__tests__/sound-transform.test.js +104 -0
  314. package/swf2js/__tests__/speex-audio.test.js +77 -0
  315. package/swf2js/__tests__/stage-noscale.test.js +45 -0
  316. package/swf2js/__tests__/swf-encoder.test.js +134 -0
  317. package/swf2js/__tests__/swflib-assemble.test.js +20 -0
  318. package/swf2js/__tests__/textfield-html-text.test.js +368 -0
  319. package/swf2js/__tests__/textfield-line-layout.test.js +339 -0
  320. package/swf2js/__tests__/textfield-programmatic-overlay.test.js +2506 -0
  321. package/swf2js/__tests__/textfield-scroll.test.js +79 -0
  322. package/swf2js/__tests__/textfield-selection.test.js +383 -0
  323. package/swf2js/__tests__/timeline-effect-surfaces.test.js +295 -0
  324. package/swf2js/__tests__/timeline-named-anchor.test.js +139 -0
  325. package/swf2js/__tests__/timeline-scenes.test.js +1723 -0
  326. package/swf2js/__tests__/urlloader-http-status.test.js +236 -0
  327. package/{src → swf2js}/cli.js +43 -11
  328. package/swf2js/compiler/as2-classes.js +156 -0
  329. package/swf2js/compiler/as2-parser.js +598 -0
  330. package/swf2js/compiler/avm1-codegen.js +897 -0
  331. package/swf2js/compiler/index.js +28 -0
  332. package/{src → swf2js}/decoder/button-decoder.js +3 -1
  333. package/swf2js/decoder/png.js +114 -0
  334. package/{src → swf2js}/decoder/shape-decoder.js +20 -10
  335. package/{src → swf2js}/decoder/tag-decoder.js +5 -3
  336. package/{src → swf2js}/decoder/tag-types.js +4 -0
  337. package/swf2js/decompiler/avm1-decompiler.js +1138 -0
  338. package/{src → swf2js}/emitter/asset-encoder.js +66 -113
  339. package/{src → swf2js}/emitter/bundle-emitter.js +209 -78
  340. package/swf2js/emitter/external-resources.js +39 -0
  341. package/swf2js/emitter/movie-data-codec.js +91 -0
  342. package/swf2js/encoder/bit-writer.js +182 -0
  343. package/swf2js/encoder/shape-encoder.js +310 -0
  344. package/swf2js/encoder/swf-builder.js +639 -0
  345. package/swf2js/encoder/swf-writer.js +55 -0
  346. package/{src/runtime/swflib/assemble.js → swf2js/runtime/assemble-swooflib.js} +4 -3
  347. package/{src → swf2js}/runtime/avm1-runtime.js +102 -63
  348. package/{src → swf2js}/runtime/index.js +1 -1
  349. package/{src → swf2js}/runtime/movie-runtime.js +28 -2
  350. package/{src → swf2js}/transpiler/actionscript.js +82 -19
  351. package/{src → swf2js}/transpiler/avm1/avm1-opcodes.js +5 -3
  352. package/{src → swf2js}/transpiler/avm1/avm1-transpiler.js +69 -6
  353. package/{src → swf2js}/transpiler/avm2/avm2-transpiler.js +1 -1
  354. package/{src → swf2js}/transpiler/timeline/display-list.js +41 -22
  355. package/{src → swf2js}/transpiler/timeline/timeline-codegen.js +97 -36
  356. package/swooflib/README.md +569 -0
  357. package/swooflib/adpcm.js +147 -0
  358. package/{src/runtime/swflib → swooflib}/builtins.js +6 -0
  359. package/{src/runtime/swflib → swooflib}/context-menu.js +7 -1
  360. package/swooflib/control-definitions.js +42 -0
  361. package/swooflib/control-widget.js +763 -0
  362. package/swooflib/controls.js +300 -0
  363. package/{src/runtime/swflib → swooflib}/display.js +16 -10
  364. package/{src/runtime/swflib → swooflib}/events.js +11 -0
  365. package/{src/runtime/swflib → swooflib}/flash.js +6 -5
  366. package/{src/runtime/swflib → swooflib}/graphics.js +81 -19
  367. package/{src/runtime/swflib → swooflib}/input.js +12 -14
  368. package/{src/runtime/swflib → swooflib}/loader.js +52 -22
  369. package/swooflib/movie-network.js +86 -0
  370. package/swooflib/path-stream.js +169 -0
  371. package/{src/runtime/swflib → swooflib}/render.js +3 -13
  372. package/{src/runtime/swflib → swooflib}/sound.js +25 -2
  373. package/{src/runtime/swflib → swooflib}/stage.js +3 -3
  374. package/swooflib/stream-time.js +21 -0
  375. package/{src/runtime/swflib → swooflib}/system.js +88 -37
  376. package/{src/runtime/swflib → swooflib}/text-paint.js +14 -3
  377. package/{src/runtime/swflib → swooflib}/text.js +8 -0
  378. package/swooflib/xml-node.js +53 -0
  379. package/src/emitter/timeline-data-codec.js +0 -58
  380. /package/{src → swf2js}/decoder/symbol-table.js +0 -0
  381. /package/{src → swf2js}/emitter/embedded-swf.js +0 -0
  382. /package/{src → swf2js}/emitter/font-encoder.js +0 -0
  383. /package/{src → swf2js}/model/swf-document.js +0 -0
  384. /package/{src → swf2js}/model/transpile-result.js +0 -0
  385. /package/{src → swf2js}/parser/bit-reader.js +0 -0
  386. /package/{src → swf2js}/parser/decompressor.js +0 -0
  387. /package/{src → swf2js}/parser/swf-parser.js +0 -0
  388. /package/{src → swf2js}/pretty-printer/pretty-printer.js +0 -0
  389. /package/{src → swf2js}/runtime/avm2-runtime.js +0 -0
  390. /package/{src → swf2js}/runtime/embedded-movie-runtime.js +0 -0
  391. /package/{src → swf2js}/transpiler/avm1/avm1-ir.js +0 -0
  392. /package/{src → swf2js}/transpiler/avm1/avm1-rewrite.js +0 -0
  393. /package/{src → swf2js}/transpiler/avm2/abc-reader.js +0 -0
  394. /package/{src → swf2js}/transpiler/cfg-structurer.js +0 -0
  395. /package/{src → swf2js}/util/diagnostics.js +0 -0
  396. /package/{src → swf2js}/util/logger.js +0 -0
  397. /package/{src/runtime/swflib → swooflib}/bitmap-image.js +0 -0
  398. /package/{src/runtime/swflib → swooflib}/bitmap.js +0 -0
  399. /package/{src/runtime/swflib → swooflib}/bytearray.js +0 -0
  400. /package/{src/runtime/swflib → swooflib}/compiled-swf.js +0 -0
  401. /package/{src/runtime/swflib → swooflib}/cursor-flag.js +0 -0
  402. /package/{src/runtime/swflib → swooflib}/dictionary.js +0 -0
  403. /package/{src/runtime/swflib → swooflib}/filters.js +0 -0
  404. /package/{src/runtime/swflib → swooflib}/geom.js +0 -0
  405. /package/{src/runtime/swflib → swooflib}/glyph-metrics.js +0 -0
  406. /package/{src/runtime/swflib → swooflib}/host.js +0 -0
  407. /package/{src/runtime/swflib → swooflib}/inherit.js +0 -0
  408. /package/{src/runtime/swflib → swooflib}/marks.js +0 -0
  409. /package/{src/runtime/swflib → swooflib}/matrix3d.js +0 -0
  410. /package/{src/runtime/swflib → swooflib}/pointer-bridge.js +0 -0
  411. /package/{src/runtime/swflib → swooflib}/projection.js +0 -0
  412. /package/{src/runtime/swflib → swooflib}/sprite-drag.js +0 -0
  413. /package/{src/runtime/swflib → swooflib}/stage-ref.js +0 -0
  414. /package/{src/runtime/swflib → swooflib}/text-field.js +0 -0
  415. /package/{src/runtime/swflib → swooflib}/transform.js +0 -0
  416. /package/{src/runtime/swflib → swooflib}/xml.js +0 -0
@@ -0,0 +1,948 @@
1
+ // Lottie export (studiospec/lottie.md). The project is written structure for structure: each
2
+ // object is one layer, Studio's keyframes and eases are Lottie keyframes, symbols are precomps,
3
+ // and scenes are precomps placed on the main timeline in the order the movie plays them.
4
+ // Studio-only data (events, scripts, sounds, object ids) rides along under `studio`, so a file
5
+ // Studio wrote imports back exactly; players ignore it.
6
+
7
+ import { orderedSceneElements, poseAt, visibleAt } from './model.js';
8
+ import { symbolFrame, symbolPlacementFrame } from './symbols.js';
9
+ import { blendModes } from './placement-effects.js';
10
+
11
+ const EPSILON = 0.005;
12
+ // A held value changes at the next keyframe. Some players (ThorVG) still show the held value at
13
+ // that keyframe's exact time, so the new value is also keyed a thousandth of a frame before.
14
+ export const STEP = 0.001;
15
+
16
+ // ---- Values ------------------------------------------------------------------------------------
17
+
18
+ /** Lottie keyframe tangents for Studio's eases: each is the exact cubic timing curve. */
19
+ export const EASES = {
20
+ linear: { o: [0.3333, 0.3333], i: [0.6667, 0.6667] },
21
+ easeIn: { o: [0.3333, 0], i: [0.6667, 0.3333] },
22
+ easeOut: { o: [0.3333, 0.6667], i: [0.6667, 1] },
23
+ };
24
+ const round = value => Math.round(value * 1e4) / 1e4;
25
+ const roundAll = value => Array.isArray(value) ? value.map(roundAll)
26
+ : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, roundAll(v)]))
27
+ : typeof value === 'number' ? round(value) : value;
28
+
29
+ function ease(tween, t) {
30
+ if (tween === 'easeIn') return t * t;
31
+ if (tween === 'easeOut') return 1 - (1 - t) ** 2;
32
+ if (tween === 'easeInOut') return t < 0.5 ? 2 * t * t : 1 - ((-2 * t + 2) ** 2) / 2;
33
+ return t;
34
+ }
35
+
36
+ const near = (a, b, tolerance) => a.length === b.length && a.every((value, i) => Math.abs(value - b[i]) <= tolerance);
37
+
38
+ /**
39
+ * An animatable Lottie property from per-frame values. `valueAt(frame)` gives a flat list of
40
+ * numbers for a 1-based frame; `spans` are Studio's keyframes ({ frame, tween }) in order;
41
+ * `format(numbers)` gives Lottie's value. A span whose values follow its ease exactly is one
42
+ * Lottie keyframe with that ease (ease in-out: two, meeting halfway); any other span is written
43
+ * frame by frame. Lottie time is the frame minus one.
44
+ */
45
+ export function animatedProperty(valueAt, spans, format, { tolerance = EPSILON, wrap = value => value } = {}) {
46
+ const frames = spans.map(span => span.frame);
47
+ const first = frames[0] ?? 1, last = frames.at(-1) ?? 1;
48
+ const cache = new Map();
49
+ const at = frame => {
50
+ if (!cache.has(frame)) cache.set(frame, valueAt(frame));
51
+ return cache.get(frame);
52
+ };
53
+ const start = at(first);
54
+ let constant = true;
55
+ for (let frame = first + 1; frame <= last && constant; frame++) constant = near(at(frame), start, tolerance);
56
+ if (constant) return { a: 0, k: format(start) };
57
+ const keys = [];
58
+ const key = (frame, values, tween) => {
59
+ const entry = { t: round(frame - 1), s: wrap(format(values)) };
60
+ if (tween === 'hold') entry.h = 1;
61
+ else if (tween) {
62
+ const { o, i } = EASES[tween];
63
+ entry.o = { x: o[0], y: o[1] };
64
+ entry.i = { x: i[0], y: i[1] };
65
+ }
66
+ keys.push(entry);
67
+ };
68
+ for (let index = 0; index < spans.length - 1; index++) {
69
+ const a = spans[index].frame, b = spans[index + 1].frame;
70
+ if (b <= a) continue;
71
+ const tween = spans[index].tween || 'linear';
72
+ const from = at(a), to = at(b);
73
+ if (tween === 'hold') {
74
+ key(a, from, 'hold');
75
+ if (!near(from, to, tolerance)) key(b - STEP, to, 'hold');
76
+ continue;
77
+ }
78
+ let fits = true;
79
+ for (let frame = a + 1; frame < b && fits; frame++) {
80
+ const t = ease(tween, (frame - a) / (b - a));
81
+ fits = near(at(frame), from.map((value, i) => value + (to[i] - value) * t), tolerance);
82
+ }
83
+ if (fits && near(from, to, tolerance)) key(a, from, 'linear');
84
+ else if (fits && tween === 'easeInOut') {
85
+ key(a, from, 'easeIn');
86
+ key(a + (b - a) / 2, from.map((value, i) => (value + to[i]) / 2), 'easeOut');
87
+ } else if (fits) key(a, from, tween);
88
+ else for (let frame = a; frame < b; frame++) key(frame, at(frame), 'linear');
89
+ }
90
+ keys.push({ t: round(last - 1), s: wrap(format(at(last))) });
91
+ return { a: 1, k: keys };
92
+ }
93
+
94
+ /** Studio's transform as Lottie's: rotation, then skew (of the y axis), then scale. */
95
+ export function lottieTransformValues(pose, factor = [1, 1]) {
96
+ const skew = (pose.skew ?? 0) * Math.PI / 180;
97
+ const flip = pose.mirror ? -1 : 1;
98
+ return {
99
+ p: [pose.x, pose.y],
100
+ r: pose.rotation ?? 0,
101
+ s: [(pose.scaleX ?? 1) * 100 * factor[0], (pose.scaleY ?? 1) * flip * Math.cos(skew) * 100 * factor[1]],
102
+ sk: pose.skew ?? 0,
103
+ o: (pose.opacity ?? 1) * 100,
104
+ };
105
+ }
106
+
107
+ /** An affine matrix [a, b, c, d, e, f] as Lottie transform values (p, r, s, sk). */
108
+ export function decomposeMatrix([a, b, c, d, e, f]) {
109
+ const sx = Math.hypot(a, b);
110
+ if (sx < 1e-12) return { p: [e, f], r: 0, s: [0, 0], sk: 0 };
111
+ const r = Math.atan2(b, a);
112
+ const u = c * Math.cos(r) + d * Math.sin(r), v = -c * Math.sin(r) + d * Math.cos(r);
113
+ const skew = Math.abs(v) < 1e-12 ? 0 : Math.atan(-u / v);
114
+ return { p: [e, f], r: r * 180 / Math.PI, s: [sx * 100, v * 100], sk: skew * 180 / Math.PI };
115
+ }
116
+
117
+ const staticValue = k => ({ a: 0, k });
118
+
119
+ export function groupTransform(matrix = [1, 0, 0, 1, 0, 0], opacity = 1) {
120
+ const { p, r, s, sk } = decomposeMatrix(matrix);
121
+ return { ty: 'tr', p: staticValue(roundAll(p)), a: staticValue([0, 0]), s: staticValue(roundAll(s)), r: staticValue(round(r)),
122
+ o: staticValue(round(opacity * 100)), sk: staticValue(round(sk)), sa: staticValue(0) };
123
+ }
124
+
125
+ /** SVG path commands (absolute M, L, Q, C, Z) as Lottie bezier shapes, one per subpath. */
126
+ export function lottieShapes(cmds) {
127
+ const shapes = [];
128
+ let current = null, last = [0, 0], start = [0, 0];
129
+ const begin = point => {
130
+ current = { c: false, v: [point], i: [[0, 0]], o: [[0, 0]] };
131
+ shapes.push(current);
132
+ start = point;
133
+ };
134
+ const curve = (c1, c2, end) => {
135
+ if (!current) begin(last);
136
+ const index = current.v.length - 1;
137
+ current.o[index] = [c1[0] - last[0], c1[1] - last[1]];
138
+ current.v.push(end);
139
+ current.i.push([c2[0] - end[0], c2[1] - end[1]]);
140
+ current.o.push([0, 0]);
141
+ last = end;
142
+ };
143
+ for (const c of cmds) {
144
+ if (c[0] === 'M') { begin([c[1], c[2]]); last = [c[1], c[2]]; }
145
+ else if (c[0] === 'L') curve(last, [c[1], c[2]], [c[1], c[2]]);
146
+ else if (c[0] === 'Q') {
147
+ const q = [c[1], c[2]], end = [c[3], c[4]];
148
+ curve([last[0] + 2 / 3 * (q[0] - last[0]), last[1] + 2 / 3 * (q[1] - last[1])],
149
+ [end[0] + 2 / 3 * (q[0] - end[0]), end[1] + 2 / 3 * (q[1] - end[1])], end);
150
+ } else if (c[0] === 'C') curve([c[1], c[2]], [c[3], c[4]], [c[5], c[6]]);
151
+ else if (c[0] === 'Z' && current) {
152
+ current.c = true;
153
+ const n = current.v.length;
154
+ // The closing vertex is the first one again: it lends the first its incoming handle.
155
+ if (n > 1 && Math.hypot(current.v[n - 1][0] - start[0], current.v[n - 1][1] - start[1]) < 1e-6) {
156
+ current.i[0] = current.i[n - 1];
157
+ current.v.pop(); current.i.pop(); current.o.pop();
158
+ }
159
+ current = null;
160
+ last = start;
161
+ }
162
+ }
163
+ // Straight segments have zero handles, which Lottie reads as straight.
164
+ return shapes.filter(shape => shape.v.length > 1 || shape.c);
165
+ }
166
+
167
+ const flatShape = shape => [...shape.v.flat(), ...shape.i.flat(), ...shape.o.flat()];
168
+ function unflatShape(numbers, template) {
169
+ const n = template.v.length;
170
+ const pairs = offset => Array.from({ length: n }, (_, k) => [round(numbers[offset + 2 * k]), round(numbers[offset + 2 * k + 1])]);
171
+ return { c: template.c, v: pairs(0), i: pairs(2 * n), o: pairs(4 * n) };
172
+ }
173
+
174
+ export function parseMatrixAttr(text) {
175
+ const numbers = String(text ?? '').match(/-?\d*\.?\d+(?:e[-+]?\d+)?/gi)?.map(Number);
176
+ return numbers?.length === 6 ? numbers : [1, 0, 0, 1, 0, 0];
177
+ }
178
+
179
+ const mul = (m, n) => [m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1], m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3],
180
+ m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5]];
181
+
182
+ export function rgbNumbers(text) {
183
+ const match = String(text).match(/rgb\((\d+),(\d+),(\d+)\)/);
184
+ return match ? [+match[1] / 255, +match[2] / 255, +match[3] / 255] : [0, 0, 0];
185
+ }
186
+
187
+ const hexNumbers = hex => [1, 3, 5].map(i => parseInt(String(hex).slice(i, i + 2), 16) / 255 || 0);
188
+
189
+ /** Studio's colour transform (multipliers and offsets per channel) applied to a 0–1 colour. */
190
+ export function tinted(color, transform) {
191
+ if (!transform) return color;
192
+ const channels = ['red', 'green', 'blue'];
193
+ return color.map((value, i) => i > 2 ? value
194
+ : Math.max(0, Math.min(1, value * (transform[`${channels[i]}Multiplier`] ?? 1) + (transform[`${channels[i]}Offset`] ?? 0) / 255)));
195
+ }
196
+
197
+ // ---- Artwork -----------------------------------------------------------------------------------
198
+
199
+ /**
200
+ * One object's artwork (an SVG element tree from the recording context, in the object's own
201
+ * space) as a list of draws: paths with their paint, text runs and images.
202
+ */
203
+ export function artworkDraws(tree) {
204
+ const definitions = new Map();
205
+ const index = node => {
206
+ if (node.attrs?.id) definitions.set(node.attrs.id, node);
207
+ for (const child of node.children ?? []) index(child);
208
+ };
209
+ index(tree);
210
+ const draws = [];
211
+ const visit = (node, matrix, opacity, clips) => {
212
+ if (['linearGradient', 'radialGradient', 'clipPath', 'pattern', 'filter', 'defs'].includes(node.tag)) return;
213
+ const own = node.attrs?.transform ? parseMatrixAttr(node.attrs.transform) : [1, 0, 0, 1, 0, 0];
214
+ const here = mul(matrix, own);
215
+ const alpha = opacity * (node.attrs?.opacity != null ? +node.attrs.opacity : 1);
216
+ let clipChain = clips;
217
+ const clipRef = node.attrs?.['clip-path']?.match(/url\(#([^)]+)\)/)?.[1];
218
+ if (clipRef && definitions.get(clipRef)) {
219
+ const clipPath = definitions.get(clipRef).children?.[0];
220
+ if (clipPath?.attrs?.d) clipChain = [...clips, { d: clipPath.attrs.d, matrix: mul(matrix, parseMatrixAttr(clipPath.attrs.transform)) }];
221
+ }
222
+ if (node.tag === 'path') {
223
+ const draw = { kind: 'path', d: node.attrs.d, matrix: here, opacity: alpha, clips: clipChain, rule: node.attrs['fill-rule'] === 'evenodd' ? 2 : 1 };
224
+ for (const kind of ['fill', 'stroke']) {
225
+ const value = node.attrs[kind];
226
+ if (!value || value === 'none') continue;
227
+ const ref = value.match(/url\(#([^)]+)\)/)?.[1];
228
+ const gradient = ref && definitions.get(ref);
229
+ const paint = gradient && /Gradient$/.test(gradient.tag) ? { type: 'gradient', gradient }
230
+ : ref ? { type: 'pattern', pattern: definitions.get(ref) } : { type: 'solid', color: rgbNumbers(value), alpha: +(node.attrs[`${kind}-opacity`] ?? 1) };
231
+ draw[kind] = paint;
232
+ }
233
+ if (draw.stroke) {
234
+ draw.width = +node.attrs['stroke-width'] || 1;
235
+ draw.cap = { butt: 1, round: 2, square: 3 }[node.attrs['stroke-linecap']] ?? 1;
236
+ draw.join = { miter: 1, round: 2, bevel: 3 }[node.attrs['stroke-linejoin']] ?? 1;
237
+ draw.miter = +node.attrs['stroke-miterlimit'] || 4;
238
+ if (node.attrs['stroke-dasharray']) draw.dash = node.attrs['stroke-dasharray'].split(/[ ,]+/).map(Number);
239
+ }
240
+ draws.push(draw);
241
+ } else if (node.tag === 'text') {
242
+ draws.push({ kind: 'text', text: node.text ?? '', x: +node.attrs.x || 0, y: +node.attrs.y || 0, matrix: here, opacity: alpha,
243
+ font: node.font ?? '', anchor: node.attrs['text-anchor'] ?? 'start', color: rgbNumbers(node.attrs.fill), clips: clipChain,
244
+ stroked: node.attrs.fill === 'none' });
245
+ } else if (node.tag === 'use') {
246
+ draws.push({ kind: 'image', image: String(node.attrs.href ?? node.attrs['xlink:href']).slice(1), matrix: here, opacity: alpha, clips: clipChain });
247
+ }
248
+ for (const child of node.children ?? []) visit(child, here, alpha, clipChain);
249
+ };
250
+ visit(tree, [1, 0, 0, 1, 0, 0], 1, []);
251
+ return draws;
252
+ }
253
+
254
+ // Draws are cached per appearance, so what is derived from one is cached with it.
255
+ const parsedShapes = new WeakMap(), parsedBounds = new WeakMap(), signatures = new WeakMap();
256
+ function drawShapes(draw) {
257
+ if (!parsedShapes.has(draw)) parsedShapes.set(draw, lottieShapes(new PathCommands(draw.d).cmds));
258
+ return parsedShapes.get(draw);
259
+ }
260
+ function drawBounds(draw) {
261
+ if (!parsedBounds.has(draw)) parsedBounds.set(draw, boundsOf(new PathCommands(draw.d)));
262
+ return parsedBounds.get(draw);
263
+ }
264
+
265
+ /** The shape of a draw list: draws with the same structure can be animated into each other. */
266
+ function drawsSignature(draws) {
267
+ if (signatures.has(draws)) return signatures.get(draws);
268
+ const signature = draws.map(draw => {
269
+ if (draw.kind === 'path') {
270
+ const paint = kind => !draw[kind] ? '-' : draw[kind].type === 'gradient'
271
+ ? `${draw[kind].gradient.tag}${draw[kind].gradient.children.length}` : draw[kind].type;
272
+ return `p${draw.d.replace(/[^MLQCZ]/g, '')}|${paint('fill')}|${paint('stroke')}|${draw.rule}|${draw.cap}${draw.join}|${draw.dash?.length ?? 0}|${draw.clips.length}`;
273
+ }
274
+ if (draw.kind === 'text') return `t${draw.font}|${draw.anchor}|${draw.text}`;
275
+ return `i${draw.image}|${draw.clips.length}`;
276
+ }).join(';');
277
+ signatures.set(draws, signature);
278
+ return signature;
279
+ }
280
+
281
+ /** Font size, family, weight and style from a CSS font shorthand. */
282
+ export function parseFont(font) {
283
+ const match = String(font).match(/^(.*?)(\d+(?:\.\d+)?)px\s*(?:\/\s*\S+\s*)?(.*)$/);
284
+ if (!match) return { size: 12, family: 'sans-serif', bold: false, italic: false };
285
+ const family = match[3].split(',')[0].trim().replace(/^["']|["']$/g, '') || 'sans-serif';
286
+ return { size: +match[2], family, bold: /\b(bold|[6-9]00)\b/.test(match[1]), italic: /\bitalic\b/.test(match[1]) };
287
+ }
288
+
289
+ // Studio's text painter draws words; Lottie wants lines. Words on one baseline are one line,
290
+ // placed where the field's alignment puts it.
291
+ export function textLines(draws, align, measure) {
292
+ const words = draws.filter(draw => draw.kind === 'text' && !draw.stroked).map(draw => {
293
+ const width = measure(draw.font, draw.text);
294
+ const x = draw.x + draw.matrix[4], y = draw.y + draw.matrix[5];
295
+ const left = draw.anchor === 'middle' ? x - width / 2 : draw.anchor === 'end' ? x - width : x;
296
+ return { ...draw, left, right: left + width, baseline: y };
297
+ });
298
+ const lines = [];
299
+ for (const word of words.sort((a, b) => a.baseline - b.baseline || a.left - b.left)) {
300
+ const line = lines.find(item => Math.abs(item.baseline - word.baseline) < 0.5);
301
+ if (!line) { lines.push({ baseline: word.baseline, words: [word] }); continue; }
302
+ line.words.push(word);
303
+ }
304
+ for (const line of lines) {
305
+ line.words.sort((a, b) => a.left - b.left);
306
+ const size = parseFont(line.words[0].font).size;
307
+ line.text = line.words.map((word, i) => (i && word.left - line.words[i - 1].right > size * 0.15 && !/\s$/.test(line.words[i - 1].text) ? ' ' : '') + word.text).join('');
308
+ line.left = line.words[0].left;
309
+ line.right = line.words.at(-1).right;
310
+ line.x = align === 'center' ? (line.left + line.right) / 2 : align === 'right' ? line.right : line.left;
311
+ }
312
+ return lines;
313
+ }
314
+
315
+ /**
316
+ * Where Studio's renderer puts a text object's first line ({ x, baseline } in its own space),
317
+ * for import: Lottie places text by its first line. Loads the renderer; returns a function.
318
+ */
319
+ export async function studioTextLayout() {
320
+ const [{ makeArtwork }, { createSvgImages, createSvgWalker, measureText }] = await Promise.all([import('./canvas.js'), import('./svg-frame.js')]);
321
+ const walker = createSvgWalker({ images: createSvgImages() });
322
+ const measure = (font, text) => measureText(font, text).width;
323
+ return fields => {
324
+ const element = { id: 'layout', name: 'layout', type: 'text', keyframes: [], strokeWidth: 0, ...fields };
325
+ const pose = { ...fields, x: 0, y: 0, rotation: 0, skew: 0, scaleX: 1, scaleY: 1, opacity: 1 };
326
+ const tree = walker.walk(makeArtwork(element, pose, []), [1, 0, 0, 1, 0, 0], 'layout', 0);
327
+ const line = tree ? textLines(artworkDraws(tree), fields.textAlign ?? 'left', measure)[0] : null;
328
+ return line ? { x: line.x, baseline: line.baseline, lines: textLines(artworkDraws(tree), fields.textAlign ?? 'left', measure).length } : null;
329
+ };
330
+ }
331
+
332
+ // ---- Gradients ---------------------------------------------------------------------------------
333
+
334
+ function gradientValues(gradient, colorTransform) {
335
+ const stops = gradient.children.map(stop => ({ offset: +stop.attrs.offset, color: tinted(rgbNumbers(stop.attrs['stop-color']), colorTransform),
336
+ alpha: +(stop.attrs['stop-opacity'] ?? 1) }));
337
+ const a = gradient.attrs;
338
+ let geometry;
339
+ if (gradient.tag === 'linearGradient') geometry = [+a.x1, +a.y1, +a.x2, +a.y2, 0, 0];
340
+ else {
341
+ const cx = +a.cx, cy = +a.cy, r = +a.r, dx = +a.fx - cx, dy = +a.fy - cy;
342
+ const distance = r > 0 ? Math.min(0.99, Math.hypot(dx, dy) / r) : 0;
343
+ geometry = [cx, cy, cx + r, cy, distance * 100, distance ? Math.atan2(dy, dx) * 180 / Math.PI : 0];
344
+ }
345
+ return [...geometry, ...stops.flatMap(stop => [stop.offset, ...stop.color]), ...stops.flatMap(stop => [stop.offset, stop.alpha])];
346
+ }
347
+
348
+ // ---- Effects and blending ----------------------------------------------------------------------
349
+
350
+ const BLEND_CODES = { multiply: 1, screen: 2, overlay: 3, darken: 4, lighten: 5, hardlight: 8, difference: 10, add: 16 };
351
+
352
+ function sigma(blur, passes = 1) {
353
+ const radius = (Math.max(1, Math.min(255, +blur || 0)) - 1) / 2, width = 2 * radius + 1;
354
+ return passes > 0 ? Math.sqrt(passes * (width * width - 1) / 12) : 0;
355
+ }
356
+ const effectValue = (ty, nm, k) => ({ ty, nm, mn: nm, ix: 0, v: { a: 0, k } });
357
+
358
+ /** Studio's effect and imported filters as Lottie effects (gaussian blur, drop shadow). */
359
+ function lottieEffects(pose, report) {
360
+ const list = [];
361
+ const blur = (x, y, passes) => list.push({ ty: 29, nm: 'Gaussian Blur', mn: 'ADBE Gaussian Blur 2', en: 1, ef: [
362
+ effectValue(0, 'Blurriness', round((sigma(x, passes) + sigma(y, passes)) / 2 / 0.3)), effectValue(7, 'Blur Dimensions', 1), effectValue(7, 'Repeat Edge Pixels', 0)] });
363
+ const shadow = (color, alpha, angle, distance, x, y, passes) => list.push({ ty: 25, nm: 'Drop Shadow', mn: 'ADBE Drop Shadow', en: 1, ef: [
364
+ effectValue(2, 'Shadow Color', [...color, 1]), effectValue(0, 'Opacity', round(alpha * 255)), effectValue(1, 'Direction', round(angle + 90)),
365
+ effectValue(0, 'Distance', round(distance)), effectValue(0, 'Softness', round((sigma(x, passes) + sigma(y, passes)) / 2 * 4))] });
366
+ const effect = pose.effect;
367
+ if (effect?.inner) report('Inner and knockout glows and shadows (left out)');
368
+ else if (effect?.type === 'blur') blur(effect.blurX, effect.blurY, 1);
369
+ else if (effect?.type === 'shadow') shadow(hexNumbers(effect.color), effect.alpha, effect.angle, effect.distance, effect.blurX, effect.blurY, 1);
370
+ else if (effect?.type === 'glow') { report('Glows (written as an even shadow)'); shadow(hexNumbers(effect.color), effect.alpha, 0, 0, effect.blurX, effect.blurY, 1); }
371
+ for (const filter of pose.filters ?? []) {
372
+ const passes = filter.passes ?? filter.quality ?? 1;
373
+ const color = filter.color ? [filter.color.r / 255, filter.color.g / 255, filter.color.b / 255] : [0, 0, 0];
374
+ const alpha = filter.color ? filter.color.a / 255 : 1;
375
+ if (filter.inner || filter.knockout) report('Inner and knockout glows and shadows (left out)');
376
+ else if (filter.type === 'blur') blur(filter.blurX, filter.blurY, passes);
377
+ else if (filter.type === 'dropShadow') shadow(color, alpha, filter.angle ?? 45, filter.distance ?? 4, filter.blurX, filter.blurY, passes);
378
+ else if (filter.type === 'glow') { report('Glows (written as an even shadow)'); shadow(color, alpha, 0, 0, filter.blurX, filter.blurY, passes); }
379
+ else report(`The ${filter.type} filter (left out)`);
380
+ }
381
+ return list;
382
+ }
383
+
384
+ // ---- Layers ------------------------------------------------------------------------------------
385
+
386
+ /**
387
+ * Writes a project as Lottie. `playback` is the movie's playback order: a list of output frames
388
+ * ({ scene, playhead, transition, outgoing }), as video export plays it; `artwork(element, pose)`
389
+ * records an object's artwork as an SVG element tree in its own space; `images` collects bitmaps.
390
+ */
391
+ export function writeLottie(project, { playback, artwork, images, measure = (font, text) => text.length * parseFont(font).size * 0.5, ending = 'stop', repeatFrom = null, report = () => {}, studio = null }) {
392
+ const { stage } = project;
393
+ const fps = stage.frameRate;
394
+ const definitions = new Map((project.symbols ?? []).map(symbol => [symbol.id, symbol]));
395
+ const fonts = new Map();
396
+ const assets = [];
397
+ const compiled = new Map();
398
+
399
+ function fontName(font) {
400
+ const { family, bold, italic } = parseFont(font);
401
+ const style = `${bold ? 'Bold' : ''}${italic ? 'Italic' : ''}` || 'Regular';
402
+ // Named as font files are ("Georgia Bold"): players that load fonts by name (ThorVG) find them.
403
+ const name = style === 'Regular' ? family : `${family} ${style.replace('BoldItalic', 'Bold Italic')}`;
404
+ if (!fonts.has(name)) fonts.set(name, { fName: name, fFamily: family, fStyle: style, fWeight: bold ? '700' : '400', ascent: 75 });
405
+ return name;
406
+ }
407
+
408
+ function compile(timeline, id, name, width, height, origin = [0, 0]) {
409
+ if (compiled.has(id)) return id;
410
+ compiled.set(id, true);
411
+ const layers = timelineLayers(timeline);
412
+ // Lottie clips a precomp to its size; Studio does not clip symbols. The precomp is made big
413
+ // enough for all its artwork, and a null layer moves the content into it.
414
+ if (origin[0] || origin[1]) {
415
+ const shift = { ddd: 0, ind: layers.length + 1, ty: 3, nm: 'origin', sr: 1, ao: 0, ip: 0, op: timeline.durationFrames, st: 0, bm: 0,
416
+ ks: { a: staticValue([0, 0]), p: staticValue(roundAll([-origin[0], -origin[1]])), s: staticValue([100, 100]), r: staticValue(0), o: staticValue(100) } };
417
+ for (const layer of layers) if (layer.parent == null) layer.parent = shift.ind;
418
+ layers.push(shift);
419
+ }
420
+ assets.push({ id, nm: name, fr: fps, w: width, h: height, layers });
421
+ return id;
422
+ }
423
+
424
+ // A box holding everything a timeline can draw, in its own coordinates: each object's box at
425
+ // each of its keyframes, turned any way, plus room for strokes and effects.
426
+ const boxes = new Map();
427
+ function timelineBox(timeline, depth = 0) {
428
+ if (boxes.has(timeline)) return boxes.get(timeline);
429
+ let x0 = 0, y0 = 0, x1 = timeline.width ?? stage.width, y1 = timeline.height ?? stage.height;
430
+ for (const element of timeline.elements) {
431
+ const frames = [1, ...(element.keyframes ?? []).map(key => key.frame)];
432
+ for (const frame of frames) {
433
+ const pose = poseAt(element, frame);
434
+ let radius;
435
+ if (element.type === 'symbol' && definitions.get(element.symbolId) && depth < 32) {
436
+ const definition = definitions.get(element.symbolId);
437
+ const [a, b, c, d] = timelineBox(definition, depth + 1);
438
+ const kx = Math.abs(pose.width / definition.width), ky = Math.abs(pose.height / definition.height);
439
+ radius = Math.max(...[[a, b], [c, b], [a, d], [c, d]].map(([x, y]) =>
440
+ Math.hypot((x - definition.width / 2) * kx, (y - definition.height / 2) * ky)));
441
+ } else radius = Math.hypot(pose.width, pose.height) / 2;
442
+ const effect = pose.effect ? Math.max(pose.effect.blurX ?? 0, pose.effect.blurY ?? 0) * 2 + (pose.effect.distance ?? 0) : 0;
443
+ radius = radius * Math.max(Math.abs(pose.scaleX ?? 1), Math.abs(pose.scaleY ?? 1), 1) + (pose.strokeWidth ?? 0) + effect + 8;
444
+ x0 = Math.min(x0, pose.x - radius); y0 = Math.min(y0, pose.y - radius);
445
+ x1 = Math.max(x1, pose.x + radius); y1 = Math.max(y1, pose.y + radius);
446
+ }
447
+ }
448
+ const box = [Math.floor(x0), Math.floor(y0), Math.ceil(x1), Math.ceil(y1)];
449
+ boxes.set(timeline, box);
450
+ return box;
451
+ }
452
+
453
+ // Frames [first, last] an object is drawn in, as runs.
454
+ function exposures(element, duration) {
455
+ const runs = [];
456
+ let open = null;
457
+ for (let frame = 1; frame <= duration; frame++) {
458
+ if (visibleAt(element, frame)) { if (open == null) open = frame; }
459
+ else if (open != null) { runs.push([open, frame - 1]); open = null; }
460
+ }
461
+ if (open != null) runs.push([open, duration]);
462
+ return runs;
463
+ }
464
+
465
+ function timelineLayers(timeline) {
466
+ const out = [];
467
+ const duration = timeline.durationFrames;
468
+ const hiddenLayers = new Set((timeline.layers ?? []).filter(layer => layer.visible === false).map(layer => layer.id));
469
+ const sources = new Set();
470
+ for (const element of timeline.elements) if (element.maskId) sources.add(element.maskId);
471
+ const byId = new Map(timeline.elements.map(element => [element.id, element]));
472
+ let index = 1;
473
+ for (const element of orderedSceneElements(timeline)) {
474
+ if (hiddenLayers.has(element.layerId) || sources.has(element.id)) continue;
475
+ for (const run of exposures(element, duration)) {
476
+ const made = elementLayers(element, run, timeline);
477
+ const source = element.maskId && byId.get(element.maskId);
478
+ if (element.maskId && !source) report('Imported mask slots (left unmasked)');
479
+ if (source?.maskId) report('Masks of masks (only the first applies)');
480
+ for (const layer of made) {
481
+ if (source && !hiddenLayers.has(source.layerId)) {
482
+ const matte = elementLayers(source, run, timeline, true)[0];
483
+ if (matte) {
484
+ matte.td = 1;
485
+ layer.tt = 1;
486
+ out.push(layer, matte);
487
+ continue;
488
+ }
489
+ }
490
+ out.push(layer);
491
+ }
492
+ }
493
+ }
494
+ // Lottie lists layers top first.
495
+ out.reverse();
496
+ for (const layer of out) layer.ind = index++;
497
+ for (const layer of out) {
498
+ if (layer.parentLayer) { layer.parent = layer.parentLayer.ind; delete layer.parentLayer; }
499
+ }
500
+ return out;
501
+ }
502
+
503
+ function keySpans(element, run) {
504
+ const keys = [...(element.keyframes ?? [])].sort((a, b) => a.frame - b.frame).filter(key => !key.blank);
505
+ const spans = keys.map(key => ({ frame: key.frame, tween: key.tween || 'linear' }));
506
+ if (!spans.length || spans[0].frame > run[0]) spans.unshift({ frame: run[0], tween: 'hold' });
507
+ if (spans.at(-1).frame < run[1]) spans.push({ frame: run[1], tween: 'hold' });
508
+ return spans;
509
+ }
510
+
511
+ function transform(element, spans, run, { anchor = [0, 0], factor = () => [1, 1], opacity = true } = {}) {
512
+ const pose = frame => poseAt(element, frame);
513
+ const values = frame => lottieTransformValues(pose(frame), factor(pose(frame)));
514
+ const ks = {
515
+ a: staticValue(roundAll(anchor)),
516
+ p: animatedProperty(frame => values(frame).p, spans, roundAll),
517
+ r: animatedProperty(frame => [values(frame).r], spans, v => round(v[0]), { wrap: v => [v] }),
518
+ s: animatedProperty(frame => values(frame).s, spans, roundAll),
519
+ o: opacity ? animatedProperty(frame => [values(frame).o], spans, v => round(v[0]), { wrap: v => [v] }) : staticValue(100),
520
+ };
521
+ const skew = animatedProperty(frame => [values(frame).sk], spans, v => round(v[0]), { wrap: v => [v] });
522
+ if (skew.a || skew.k) { ks.sk = skew; ks.sa = staticValue(0); }
523
+ return ks;
524
+ }
525
+
526
+ function baseLayer(element, run, ty) {
527
+ const layer = { ddd: 0, ty, nm: element.name ?? element.id, cl: String(element.id).replace(/[^\w-]/g, '_'), sr: 1, ao: 0,
528
+ ip: run[0] - 1, op: run[1], st: 0, bm: 0 };
529
+ const mode = blendModes[poseAt(element, run[0]).blendMode];
530
+ if (mode && mode !== 'normal' && mode !== 'layer') {
531
+ if (BLEND_CODES[mode] != null) layer.bm = BLEND_CODES[mode];
532
+ else report(`The ${mode} blend mode (left out)`);
533
+ }
534
+ const effects = lottieEffects(poseAt(element, run[0]), report);
535
+ if (effects.length) layer.ef = effects;
536
+ return layer;
537
+ }
538
+
539
+ // Each frame's artwork for an object, recorded once per distinct appearance.
540
+ function artworkTrack(element) {
541
+ const cache = new Map();
542
+ return frame => {
543
+ const pose = poseAt(element, frame);
544
+ const { x, y, rotation, scaleX, scaleY, skew, opacity, mirror, frame: _f, ...look } = pose;
545
+ const signature = JSON.stringify(look);
546
+ if (!cache.has(signature)) {
547
+ const draws = artworkDraws(artwork(element, pose));
548
+ cache.set(signature, { pose, draws, paths: draws.filter(draw => draw.kind === 'path') });
549
+ }
550
+ return cache.get(signature);
551
+ };
552
+ }
553
+
554
+ function elementLayers(element, run, timeline, matte = false) {
555
+ const spans = keySpans(element, run);
556
+ if (element.type === 'symbol') return [symbolLayer(element, run, spans)];
557
+ const track = artworkTrack(element);
558
+ const draws = track(run[0]).draws;
559
+ if (element.type === 'bitmap') {
560
+ const image = draws.find(draw => draw.kind === 'image');
561
+ return image ? [imageLayer(element, run, spans, image)] : [];
562
+ }
563
+ if (element.type === 'text') {
564
+ const layer = textLayer(element, run, spans, track);
565
+ return layer ? [layer] : [];
566
+ }
567
+ const layers = [];
568
+ const shape = shapeLayer(element, run, spans, track, matte);
569
+ if (shape) layers.push(shape);
570
+ // A label on a shape (a button) is its own text layer, following the shape.
571
+ if (!matte && draws.some(draw => draw.kind === 'text')) {
572
+ const label = textLayer(element, run, spans, track);
573
+ if (label && shape) {
574
+ label.parentLayer = shape;
575
+ label.ks = { ...label.ks, p: staticValue([0, 0]), r: staticValue(0), s: staticValue([100, 100]) };
576
+ delete label.ks.sk;
577
+ delete label.ks.sa;
578
+ label.nm = `${label.nm} label`;
579
+ }
580
+ if (label) layers.push(label);
581
+ }
582
+ if (!matte && draws.some(draw => draw.kind === 'image')) report('Bitmap fills in shapes (left out)');
583
+ if (!matte && draws.some(draw => draw.kind === 'text' && draw.stroked)) report('Outlined text (left out)');
584
+ return layers;
585
+ }
586
+
587
+ function symbolLayer(element, run, spans) {
588
+ const definition = definitions.get(element.symbolId);
589
+ const [x0, y0, x1, y1] = timelineBox(definition);
590
+ const id = compile(definition, `symbol_${definition.id}`, definition.name ?? definition.id, x1 - x0, y1 - y0, [x0, y0]);
591
+ const layer = { ...baseLayer(element, run, 0), refId: id, w: x1 - x0, h: y1 - y0 };
592
+ layer.ks = transform(element, spans, run, { anchor: [definition.width / 2 - x0, definition.height / 2 - y0],
593
+ factor: pose => [pose.width / definition.width, pose.height / definition.height] });
594
+ if (poseAt(element, run[0]).colorTransform) report('Colour tints on symbols and bitmaps (left out)');
595
+ // The symbol's own frame for each frame of its parent: a start offset when it simply plays,
596
+ // a time remap otherwise (loops, a single frame, a later first frame).
597
+ const child = [];
598
+ for (let frame = run[0]; frame <= run[1]; frame++) child.push(symbolFrame(element, definition, frame, symbolPlacementFrame(element, frame)));
599
+ const offset = run[0] - child[0];
600
+ if (child.every((value, i) => value === child[0] + i)) layer.st = offset;
601
+ else layer.tm = timeRemap(child, run[0], fps);
602
+ return layer;
603
+ }
604
+
605
+ function imageLayer(element, run, spans, draw) {
606
+ const [a, b, c, d, e, f] = draw.matrix;
607
+ if (Math.abs(b) > 1e-9 || Math.abs(c) > 1e-9) report('Rotated bitmap placements (drawn unrotated)');
608
+ const layer = { ...baseLayer(element, run, 2), refId: draw.image };
609
+ // The image's placement inside the object is folded into the anchor and the scale.
610
+ layer.ks = transform(element, spans, run, { anchor: [-e / a, -f / d], factor: () => [a, d] });
611
+ if (draw.clips.length) {
612
+ const inverse = [1 / a, 0, 0, 1 / d, -e / a, -f / d];
613
+ layer.hasMask = true;
614
+ // Each clip's outline intersects; its further contours (holes) are subtracted after it.
615
+ layer.masksProperties = draw.clips.flatMap((clip, n) => {
616
+ const shapes = lottieShapes(transformCmds(clip.d, mul(inverse, clip.matrix)));
617
+ return (shapes.length ? shapes : [{ c: true, v: [], i: [], o: [] }]).map((shape, k) => ({
618
+ mode: k ? 's' : n ? 'i' : 'a', inv: false, o: staticValue(100), x: staticValue(0), pt: staticValue(roundAll(shape)) }));
619
+ });
620
+ }
621
+ if (poseAt(element, run[0]).colorTransform) report('Colour tints on symbols and bitmaps (left out)');
622
+ if (element.smoothed === false) report('Unsmoothed (pixelated) bitmaps (smoothed)');
623
+ return layer;
624
+ }
625
+
626
+ function textLayer(element, run, spans, track) {
627
+ const align = pose => pose.textAlign ?? element.textAlign ?? 'left';
628
+ const linesAt = frame => textLines(track(frame).draws, align(track(frame).pose), measure);
629
+ const first = linesAt(run[0]);
630
+ if (!first.length) return null;
631
+ const layer = baseLayer(element, run, 5);
632
+ layer.ks = transform(element, spans, run, { anchor: [-first[0].x, -first[0].baseline] });
633
+ const doc = frame => {
634
+ const lines = linesAt(frame);
635
+ const pose = track(frame).pose;
636
+ const word = lines[0]?.words[0] ?? first[0].words[0];
637
+ const font = parseFont(word.font);
638
+ const spacing = lines.length > 1 ? (lines.at(-1).baseline - lines[0].baseline) / (lines.length - 1) : font.size * 1.2;
639
+ return { s: round(font.size), f: fontName(word.font), t: lines.map(line => line.text).join('\r'),
640
+ j: { left: 0, right: 1, center: 2 }[align(pose)] ?? 0, tr: 0, lh: round(spacing), ls: 0,
641
+ fc: roundAll(tinted(word.color ?? [0, 0, 0], pose.colorTransform)) };
642
+ };
643
+ const keys = [];
644
+ let previous = null;
645
+ for (let frame = run[0]; frame <= run[1]; frame++) {
646
+ const value = doc(frame);
647
+ const text = JSON.stringify(value);
648
+ if (text !== previous) keys.push({ s: value, t: frame - 1 });
649
+ previous = text;
650
+ }
651
+ if (new Set(first.flatMap(line => line.words.map(word => JSON.stringify(word.color)))).size > 1) report('Text with several colours (in its first colour)');
652
+ if (first.some(line => Math.abs(line.x - first[0].x) > 0.5)) report('Text lines placed apart from each other (aligned together)');
653
+ layer.t = { d: { k: keys }, p: {}, m: { g: 1, a: staticValue([0, 0]) }, a: [] };
654
+ return layer;
655
+ }
656
+
657
+ function shapeLayer(element, run, spans, track, matte) {
658
+ const first = track(run[0]).paths;
659
+ if (!first.length) return null;
660
+ const signature = drawsSignature(first);
661
+ for (let frame = spans[0].frame; frame <= spans.at(-1).frame; frame++) {
662
+ if (drawsSignature(track(frame).paths) !== signature) {
663
+ report('Artwork whose drawing changes shape (shown as its first frame)');
664
+ break;
665
+ }
666
+ }
667
+ const drawsAt = frame => {
668
+ const { paths, pose } = track(frame);
669
+ return { paths: drawsSignature(paths) === signature ? paths : first, pose };
670
+ };
671
+ const layer = { ...baseLayer(element, run, 4) };
672
+ layer.ks = transform(element, spans, run);
673
+ const primitive = { rectangle: 'rc', roundedRectangle: 'rc', ellipse: 'el', circle: 'el' }[element.type];
674
+ const groups = first.map((draw, n) => {
675
+ const items = [];
676
+ const property = (pick, format, options) => animatedProperty(frame => pick(drawsAt(frame), frame), spans, format, options);
677
+ const bounds = drawBounds(draw);
678
+ const pose = drawsAt(run[0]).pose;
679
+ const isPrimitive = primitive && !(pose.erasures?.length) && near(bounds, [-pose.width / 2, -pose.height / 2, pose.width / 2, pose.height / 2], 0.01)
680
+ && (primitive === 'el' || !element.cornerRadius || element.type === 'roundedRectangle');
681
+ if (isPrimitive) {
682
+ const size = property(({ pose }) => [pose.width, pose.height], roundAll);
683
+ if (primitive === 'rc') items.push({ ty: 'rc', d: 1, s: size, p: staticValue([0, 0]), r: staticValue(round(pose.cornerRadius ?? 0)) });
684
+ else items.push({ ty: 'el', d: 1, s: size, p: staticValue([0, 0]) });
685
+ } else {
686
+ const shapes = drawShapes(draw);
687
+ shapes.forEach((template, k) => {
688
+ items.push({ ty: 'sh', ind: k, ks: property(({ paths }) => flatShape(drawShapes(paths[n])[k] ?? template),
689
+ numbers => unflatShape(numbers, template), { wrap: value => [value] }) });
690
+ });
691
+ }
692
+ const tint = frame => drawsAt(frame).pose.colorTransform;
693
+ const paint = (kind) => {
694
+ const value = draw[kind];
695
+ if (!value) return null;
696
+ if (matte) return kind === 'fill' ? { ty: 'fl', c: staticValue([1, 1, 1, 1]), o: staticValue(100), r: draw.rule } : null;
697
+ if (value.type === 'pattern') { report('Repeating bitmap fills (left out)'); return null; }
698
+ const stroke = kind === 'stroke' ? { w: property(({ paths }) => [paths[n].width], v => round(v[0]), { wrap: v => [v] }),
699
+ lc: draw.cap, lj: draw.join, ml: draw.miter } : {};
700
+ if (draw.dash) stroke.d = draw.dash.map((length, i) => ({ n: i % 2 ? 'g' : 'd', nm: i % 2 ? 'gap' : 'dash', v: staticValue(length) }));
701
+ if (value.type === 'solid') {
702
+ return { ty: kind === 'fill' ? 'fl' : 'st', ...(kind === 'fill' ? { r: draw.rule } : {}), ...stroke,
703
+ c: property(({ paths }, frame) => [...tinted(paths[n][kind].color, tint(frame)), 1], roundAll),
704
+ o: property(({ paths }) => [paths[n][kind].alpha * 100], v => round(v[0]), { wrap: v => [v] }) };
705
+ }
706
+ const gradient = value.gradient;
707
+ const count = gradient.children.length;
708
+ const values = (frame, paths) => gradientValues(paths[n][kind].gradient, tint(frame));
709
+ const at = (offset, length) => property(({ paths }, frame) => values(frame, paths).slice(offset, offset + length), roundAll);
710
+ const result = { ty: kind === 'fill' ? 'gf' : 'gs', ...(kind === 'fill' ? { r: draw.rule } : {}), ...stroke, o: staticValue(100),
711
+ t: gradient.tag === 'linearGradient' ? 1 : 2, s: at(0, 2), e: at(2, 2),
712
+ g: { p: count, k: property(({ paths }, frame) => values(frame, paths).slice(6), roundAll) } };
713
+ if (result.t === 2) {
714
+ result.h = property(({ paths }, frame) => [values(frame, paths)[4]], v => round(v[0]), { wrap: v => [v] });
715
+ result.a = property(({ paths }, frame) => [values(frame, paths)[5]], v => round(v[0]), { wrap: v => [v] });
716
+ }
717
+ return result;
718
+ };
719
+ const stroke = paint('stroke'), fill = paint('fill');
720
+ if (!stroke && !fill) return null;
721
+ if (draw.clips.length && !matte) report('Clipped artwork inside an object (drawn unclipped)');
722
+ // Paints apply to the shapes before them; the first item is drawn on top.
723
+ items.push(...[stroke, fill].filter(Boolean));
724
+ const opacity = draw.opacity;
725
+ items.push(groupTransform(draw.matrix, opacity));
726
+ return { ty: 'gr', nm: `${draw.fill ? 'fill' : 'stroke'} ${n + 1}`, it: items, np: items.length };
727
+ }).filter(Boolean);
728
+ if (!groups.length) return null;
729
+ layer.shapes = groups.reverse();
730
+ return layer;
731
+ }
732
+
733
+ // ---- The main timeline ----
734
+
735
+ const main = [];
736
+ const segments = [];
737
+ playback.forEach((frame, index) => {
738
+ const last = segments.at(-1);
739
+ if (last && last.scene === frame.scene) last.frames.push({ index, playhead: frame.playhead });
740
+ else segments.push({ scene: frame.scene, frames: [{ index, playhead: frame.playhead }] });
741
+ });
742
+ const sceneAsset = scene => compile(scene, `scene_${scene.id}`, scene.name ?? scene.id, stage.width, stage.height);
743
+ const markers = [];
744
+ for (const segment of segments) {
745
+ const id = sceneAsset(segment.scene);
746
+ const start = segment.frames[0].index, end = segment.frames.at(-1).index + 1;
747
+ const layer = { ddd: 0, ty: 0, nm: segment.scene.name ?? segment.scene.id, refId: id, sr: 1, ao: 0, w: stage.width, h: stage.height,
748
+ ip: start, op: end, st: 0, bm: 0, ks: { a: staticValue([0, 0]), p: staticValue([0, 0]), s: staticValue([100, 100]), r: staticValue(0), o: staticValue(100) } };
749
+ const playheads = segment.frames.map(frame => frame.playhead);
750
+ if (playheads.every((value, i) => value === playheads[0] + i)) layer.st = start - (playheads[0] - 1);
751
+ else layer.tm = timeRemap(playheads, start + 1, fps);
752
+ main.push(layer);
753
+ markers.push({ tm: start, cm: segment.scene.name ?? segment.scene.id, dr: end - start });
754
+ }
755
+ // Transitions: the outgoing scene, still, over the incoming one, fading or wiped away.
756
+ let transition = null;
757
+ playback.forEach((frame, index) => {
758
+ if (!frame.transition) { transition = null; return; }
759
+ if (!transition) {
760
+ transition = { start: index, frames: [], outgoing: frame.outgoing, type: frame.transition.type };
761
+ const id = sceneAsset(frame.outgoing.scene);
762
+ transition.layer = { ddd: 0, ty: 0, nm: `${frame.outgoing.scene.name ?? frame.outgoing.scene.id} (transition)`, refId: id, sr: 1, ao: 0,
763
+ w: stage.width, h: stage.height, ip: index, op: index + 1, st: 0, bm: 0,
764
+ tm: staticValue(round((frame.outgoing.playhead - 1) / fps)),
765
+ ks: { a: staticValue([0, 0]), p: staticValue([0, 0]), s: staticValue([100, 100]), r: staticValue(0), o: staticValue(100) } };
766
+ transition.list = [];
767
+ main.push(transition);
768
+ }
769
+ transition.layer.op = index + 1;
770
+ transition.list.push({ index, progress: frame.transition.progress });
771
+ });
772
+ const layers = [];
773
+ for (const item of main.slice().reverse()) {
774
+ if (!item.layer) { layers.push(item); continue; }
775
+ const { layer, list, type } = item;
776
+ const keys = list.map(({ index, progress }) => ({ t: index, s: [round((1 - progress) * 100)], h: 1 }));
777
+ if (type === 'crossfade') {
778
+ layer.ks.o = { a: 1, k: keys };
779
+ layers.push(layer);
780
+ } else {
781
+ // A wipe: what is left of the outgoing scene is the part right of the edge.
782
+ const edge = { ddd: 0, ty: 4, nm: 'wipe edge', sr: 1, ao: 0, ip: layer.ip, op: layer.op, st: 0, bm: 0, td: 1,
783
+ ks: { a: staticValue([0, 0]), p: staticValue([0, 0]), s: staticValue([100, 100]), r: staticValue(0), o: staticValue(100) },
784
+ shapes: [{ ty: 'gr', it: [
785
+ { ty: 'rc', d: 1, s: staticValue([stage.width * 2, stage.height]), r: staticValue(0),
786
+ p: { a: 1, k: list.map(({ index, progress }) => ({ t: index, s: [round(progress * stage.width + stage.width), stage.height / 2], h: 1 })) } },
787
+ { ty: 'fl', c: staticValue([1, 1, 1, 1]), o: staticValue(100), r: 1 }, groupTransform()] }] };
788
+ layer.tt = 1;
789
+ layers.push(edge, layer);
790
+ }
791
+ }
792
+ // Background.
793
+ layers.reverse();
794
+ layers.unshift({ ddd: 0, ty: 1, nm: 'Background', sr: 1, ao: 0, ip: 0, op: Math.max(1, playback.length), st: 0, bm: 0, sc: stage.background ?? '#ffffff',
795
+ sw: stage.width, sh: stage.height, ks: { a: staticValue([0, 0]), p: staticValue([0, 0]), s: staticValue([100, 100]), r: staticValue(0), o: staticValue(100) } });
796
+ layers.reverse();
797
+ layers.forEach((layer, i) => { layer.ind = i + 1; });
798
+ if (ending === 'repeat' && repeatFrom > 0) {
799
+ markers.push({ tm: 0, cm: 'intro', dr: repeatFrom }, { tm: repeatFrom, cm: 'loop', dr: playback.length - repeatFrom });
800
+ }
801
+
802
+ for (const [, entry] of images.entries) assets.push({ id: entry.id, w: entry.width, h: entry.height, u: '', p: entry.href ?? '', e: 1 });
803
+ const lottie = { v: '5.7.4', fr: fps, ip: 0, op: Math.max(1, playback.length), w: stage.width, h: stage.height, nm: project.name ?? 'Studio movie', ddd: 0,
804
+ assets, layers, markers, fonts: { list: [...fonts.values()] }, meta: { g: 'Swoof Studio' } };
805
+ if (studio) lottie.studio = studio(lottie);
806
+ return lottie;
807
+ }
808
+
809
+ /** A time remap (seconds) that shows `frames[i]` (1-based) at Lottie time `start - 1 + i`. */
810
+ export function timeRemap(frames, start, fps) {
811
+ const keys = [];
812
+ let runStart = 0;
813
+ for (let i = 1; i <= frames.length; i++) {
814
+ if (i < frames.length && frames[i] === frames[i - 1] + 1) continue;
815
+ const runEnd = i - 1;
816
+ if (keys.length) keys.push({ t: round(start - 1 + runStart - STEP), s: [round((frames[runStart] - 1) / fps)], h: 1 });
817
+ keys.push({ t: start - 1 + runStart, s: [round((frames[runStart] - 1) / fps)], ...(runEnd > runStart ? EASE_LINEAR : { h: 1 }) });
818
+ if (runEnd > runStart) keys.push({ t: start - 1 + runEnd, s: [round((frames[runEnd] - 1) / fps)], h: 1 });
819
+ runStart = i;
820
+ }
821
+ return keys.length === 1 ? staticValue(keys[0].s[0]) : { a: 1, k: keys };
822
+ }
823
+ const EASE_LINEAR = { o: { x: 0.3333, y: 0.3333 }, i: { x: 0.6667, y: 0.6667 } };
824
+
825
+ // Path commands from SVG path data (as the recording context writes it: absolute M L Q C Z).
826
+ class PathCommands {
827
+ constructor(d) {
828
+ this.cmds = [];
829
+ const tokens = String(d).match(/[MLQCZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi) ?? [];
830
+ let i = 0;
831
+ while (i < tokens.length) {
832
+ const op = tokens[i++];
833
+ const count = { M: 2, L: 2, Q: 4, C: 6, Z: 0 }[op];
834
+ if (count == null) continue;
835
+ this.cmds.push([op, ...tokens.slice(i, i + count).map(Number)]);
836
+ i += count;
837
+ }
838
+ }
839
+ }
840
+ function transformCmds(d, m) {
841
+ return new PathCommands(d).cmds.map(([op, ...n]) => {
842
+ const out = [op];
843
+ for (let k = 0; k < n.length; k += 2) out.push(m[0] * n[k] + m[2] * n[k + 1] + m[4], m[1] * n[k] + m[3] * n[k + 1] + m[5]);
844
+ return out;
845
+ });
846
+ }
847
+ function boundsOf(path) {
848
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
849
+ for (const [, ...n] of path.cmds) for (let k = 0; k < n.length; k += 2) {
850
+ x0 = Math.min(x0, n[k]); x1 = Math.max(x1, n[k]); y0 = Math.min(y0, n[k + 1]); y1 = Math.max(y1, n[k + 1]);
851
+ }
852
+ return [x0, y0, x1, y1];
853
+ }
854
+
855
+ // ---- Export ------------------------------------------------------------------------------------
856
+
857
+ /**
858
+ * Plays the project as video export does and writes it as Lottie JSON. options: { maxSeconds,
859
+ * signal, onProgress, studioData }. Returns { blob, frames, seconds, ending, notes, fonts }.
860
+ */
861
+ export async function exportLottie(project, { maxSeconds = 60, signal, onProgress = () => {}, studioData = true } = {}) {
862
+ const [{ playHeadless, swfPlayerReasons }, { makeArtwork, captureDisplayFrame }, { createSvgImages, createSvgWalker, measureText }, { decodeAsset }, { serializeProject }] = await Promise.all([
863
+ import('./video-playback.js'), import('./canvas.js'), import('./svg-frame.js'), import('./media-assets.js'), import('./project-io.js')]);
864
+ const notes = new Set();
865
+ const report = note => notes.add(note);
866
+ const reasons = swfPlayerReasons(project);
867
+ if (reasons.length) report(`${reasons.join(' and ')} (Lottie players do not run them; the timeline is written as authored)`);
868
+ if ((project.scenes ?? []).some(scene => scene.audioClips?.length) || (project.assets ?? []).some(asset => asset.kind === 'audio')) report('Sound (Lottie has none)');
869
+ const fps = project.stage.frameRate;
870
+ const maxFrames = Math.max(1, Math.round(maxSeconds * fps));
871
+ onProgress(0, 'Loading media…');
872
+ await Promise.all((project.assets ?? []).map(asset => decodeAsset(asset).catch(() => null)));
873
+ const images = createSvgImages();
874
+ const fonts = new Set();
875
+ const walker = createSvgWalker({ images, report, fonts });
876
+ const playback = [];
877
+ let state = null, outgoing = null, interactive = false;
878
+ const result = await playHeadless({
879
+ project, maxFrames, holdFrames: Math.round(fps),
880
+ // Frame events (scene changes, stops) fire from the timelines a frame shows.
881
+ render: ({ scene, playhead, hiddenIds, clocks }) => {
882
+ state = { scene, playhead };
883
+ if (hiddenIds.size || clocks.size) interactive = true;
884
+ return captureDisplayFrame({ scene, symbols: project.symbols ?? [], assets: project.assets ?? [], clocks, playhead, hiddenIds, onFlush: () => {} });
885
+ },
886
+ snapshot: () => { outgoing = state; },
887
+ emit: async (transition, current) => {
888
+ if (signal?.aborted) throw new DOMException('Export was cancelled', 'AbortError');
889
+ playback.push({ ...current, transition, outgoing: transition ? outgoing : null });
890
+ if (playback.length % 50 === 0) {
891
+ onProgress(playback.length / maxFrames * 0.5, `Playing frame ${playback.length}…`);
892
+ await new Promise(resolve => setTimeout(resolve, 0));
893
+ }
894
+ },
895
+ });
896
+ if (interactive) report('Objects shown or hidden, and symbols played or stopped, by actions (written as their timelines)');
897
+ onProgress(0.5, 'Writing layers…');
898
+ const artwork = (element, pose) => {
899
+ const display = makeArtwork(element, pose, project.assets ?? []);
900
+ return walker.walk(display, [1, 0, 0, 1, 0, 0], 'art', 0) ?? { tag: 'g', attrs: {}, children: [] };
901
+ };
902
+ // Studio's own project, for reimport; images are the Lottie assets, by reference.
903
+ // Studio's own project, gzipped: Lottie cannot hold events, scripts, sounds or Studio's object
904
+ // kinds, and the hash tells an untouched file from one edited elsewhere.
905
+ const studio = studioData ? async lottie => ({ format: 'swoof-studio-lottie', version: 1, hash: lottieHash(lottie),
906
+ project: await gzipBase64(serializeProject(project, 0)) }) : null;
907
+ const loopFrom = result.ending === 'repeat' ? result.repeatFrom ?? 0 : null;
908
+ // Bitmaps are embedded after the layers are written; collect them first.
909
+ const draft = writeLottie(project, { playback, artwork, images, measure: (font, text) => measureText(font, text).width, ending: result.ending, repeatFrom: loopFrom, report });
910
+ onProgress(0.9, 'Embedding images…');
911
+ await images.resolve();
912
+ for (const asset of draft.assets) {
913
+ const entry = [...images.entries.values()].find(item => item.id === asset.id);
914
+ if (entry) asset.p = entry.href;
915
+ }
916
+ if (studio) draft.studio = await studio(draft);
917
+ const text = JSON.stringify(draft);
918
+ onProgress(1, 'Done');
919
+ return { blob: new Blob([text], { type: 'application/json' }), frames: playback.length, seconds: playback.length / fps, ending: result.ending,
920
+ loopFrom, notes: [...notes], fonts: [...fonts], width: project.stage.width, height: project.stage.height };
921
+ }
922
+
923
+ export async function gzipBase64(text) {
924
+ const stream = new Blob([text]).stream().pipeThrough(new CompressionStream('gzip'));
925
+ const bytes = new Uint8Array(await new Response(stream).arrayBuffer());
926
+ let binary = '';
927
+ for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
928
+ return btoa(binary);
929
+ }
930
+
931
+ export async function gunzipBase64(text) {
932
+ const bytes = Uint8Array.from(atob(text), c => c.charCodeAt(0));
933
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'));
934
+ return new Response(stream).text();
935
+ }
936
+
937
+ /** FNV-1a of a file's text without Studio's own data: an edit elsewhere changes it. */
938
+ export function studioHash(text) {
939
+ let hash = 0x811c9dc5;
940
+ for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193);
941
+ return (hash >>> 0).toString(36);
942
+ }
943
+
944
+ /** The hash of the Lottie content without Studio's own data. */
945
+ export function lottieHash(lottie) {
946
+ const { studio, ...content } = lottie;
947
+ return studioHash(JSON.stringify(content));
948
+ }