@haiyue/animation-spec 0.1.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 (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +190 -0
  3. package/SPECIFICATION.md +108 -0
  4. package/bin/hya-convert.mjs +31 -0
  5. package/dist/binary.d.ts +7 -0
  6. package/dist/chunks/types-l6nBVYwx.js +8 -0
  7. package/dist/chunks/types-l6nBVYwx.js.map +1 -0
  8. package/dist/errors.d.ts +7 -0
  9. package/dist/extensions.d.ts +19 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +2927 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/lottie-merge-path.d.ts +11 -0
  14. package/dist/lottie.d.ts +62 -0
  15. package/dist/lottie.js +2642 -0
  16. package/dist/lottie.js.map +1 -0
  17. package/dist/native3d/Animation3DError.d.ts +8 -0
  18. package/dist/native3d/Animation3DParser.d.ts +7 -0
  19. package/dist/native3d/Animation3DTypes.d.ts +285 -0
  20. package/dist/native3d/index.d.ts +5 -0
  21. package/dist/native3d.d.ts +2 -0
  22. package/dist/native3d.js +907 -0
  23. package/dist/native3d.js.map +1 -0
  24. package/dist/parser.d.ts +2 -0
  25. package/dist/state-machine.d.ts +130 -0
  26. package/dist/text-selector.d.ts +2 -0
  27. package/dist/types.d.ts +419 -0
  28. package/dist/validation.d.ts +32 -0
  29. package/package.json +69 -0
  30. package/schema/animation-3d-carrier.schema.json +73 -0
  31. package/schema/animation-3d-extension.schema.json +573 -0
  32. package/schema/animation-3d.contract.json +130 -0
  33. package/schema/animation.schema.json +611 -0
  34. package/schema/fixtures/native-3d-mixed-invalid.hya.json +50 -0
  35. package/schema/fixtures/native-3d-valid.hya.json +284 -0
  36. package/src/binary.ts +1441 -0
  37. package/src/errors.ts +18 -0
  38. package/src/extensions.ts +55 -0
  39. package/src/index.ts +90 -0
  40. package/src/lottie-merge-path.ts +204 -0
  41. package/src/lottie.ts +3073 -0
  42. package/src/native3d/Animation3DError.ts +20 -0
  43. package/src/native3d/Animation3DParser.ts +964 -0
  44. package/src/native3d/Animation3DTypes.ts +322 -0
  45. package/src/native3d/index.ts +14 -0
  46. package/src/native3d.ts +2 -0
  47. package/src/parser.ts +41 -0
  48. package/src/state-machine.ts +645 -0
  49. package/src/text-selector.ts +7 -0
  50. package/src/types.ts +483 -0
  51. package/src/validation.ts +1286 -0
  52. package/test/fixtures/basic-lottie.json +31 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Haiyue Engine contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,190 @@
1
+ # `@haiyue/animation-spec`
2
+
3
+ Haiyue Animation(`.hya`)是面向网页加载、校验和播放的中间动效格式。它不是另一套创作工具文件:Lottie、Galacean Effects 等来源应在构建或导入阶段转换为 `.hya`,播放器只依赖稳定、受限的运行时数据。
4
+
5
+ ## 要求与安装
6
+
7
+ - Node.js `>=22` 用于 CLI、构建和测试;schema/parser/codec 本身不要求 WebGPU。
8
+ - TypeScript 5.2+,`module: "ESNext"`、`moduleResolution: "Bundler"`、`skipLibCheck: false`。
9
+ - 只有 Engine runtime preview 需要 release matrix 中的原生 WebGPU 浏览器;本包没有 DOM 或 Engine 依赖。
10
+
11
+ ```sh
12
+ npm install @haiyue/animation-spec
13
+ ```
14
+
15
+ ## 入口选择与最小解析
16
+
17
+ - `@haiyue/animation-spec`:HYA 类型、严格 parser、binary codec 和状态机数据。
18
+ - `@haiyue/animation-spec/lottie`:离线/导入期 Lottie 转换和字体清单。
19
+ - `@haiyue/animation-spec/native3d`:`org.haiyue.animation-3d@1` source-neutral 格式 parser/types。
20
+ - `hya-convert`:Node.js 22+ CLI。
21
+
22
+ ```ts
23
+ import { parseAnimation } from '@haiyue/animation-spec';
24
+
25
+ const bytes = await fetch('/motion.hya').then(response => {
26
+ if (!response.ok) throw new Error(`HYA request failed: ${response.status}`);
27
+ return response.arrayBuffer();
28
+ });
29
+ const animation = parseAnimation(bytes);
30
+ console.log(animation.duration, animation.nodes.length);
31
+ ```
32
+
33
+ `parseAnimation()` 和 codec 不持有 Worker、DOM 或 GPU 资源,不需要 `dispose()`;丢弃返回对象即可。Engine runtime 中创建的 asset handle、animation instance、media/Worker 和 scene owner 由对应宿主显式释放。格式错误使用 `AnimationFormatError` 的稳定 code/path;Lottie fidelity 问题读取 converter diagnostics,并在交付流水线使用 `strict: true`。
34
+
35
+ ## 能力样例浏览器
36
+
37
+ 仓库内置 `animation-spec/index.html` 能力浏览器,并保留
38
+ `animation-spec/viewer.html` 作为可直接运行的稳定入口。manifest 与二进制 fixture
39
+ 位于 `animation-spec/samples`,每个文件只声明一个唯一的主能力。页面支持
40
+ 内置样例切换、远程 HYA/JSON URL、本地文件与拖放导入、时间轴、JSON 查看,
41
+ 以及运行时和 WebGPU diagnostic。
42
+
43
+ ```sh
44
+ npm run samples:generate -w ./animation-spec
45
+ EXAMPLE_FILTER=hya-samples npm run build -w ./examples
46
+ npm run serve:examples:lan
47
+ ```
48
+
49
+ 然后访问本地示例服务的 `/animation-spec/`。
50
+
51
+ ## 包边界
52
+
53
+ - `@haiyue/animation-spec`:零引擎依赖的类型、严格 parser、`.hya` codec 和扩展注册表。
54
+ - `@haiyue/animation-spec/lottie`:可选 Lottie 转换器;不会进入基础 parser bundle。
55
+ - `@haiyue/extensions/animation`:Haiyue 运行时组件和系统。
56
+ - `hya-convert`:离线转换 CLI。
57
+
58
+ `@haiyue/extensions` 是首发仓库应用使用的 private workspace,不是 `@haiyue/animation-spec` 的公共 npm 依赖,也不属于 0.1 的公共 npm package 集。公共 consumer 可以独立完成 schema、parse、codec 和转换;播放宿主需自行实现或随 Haiyue 静态应用消费 runtime。
59
+
60
+ ```ts
61
+ import { encodeAnimationBinary, parseAnimation } from '@haiyue/animation-spec';
62
+ import { convertLottieDocument } from '@haiyue/animation-spec/lottie';
63
+
64
+ const document = convertLottieDocument(lottieJson);
65
+ const deliveryBuffer = encodeAnimationBinary(document);
66
+ const animation = parseAnimation(deliveryBuffer); // keyframe tracks are zero-copy Float32Array views
67
+ ```
68
+
69
+ ```ts
70
+ import { createAnimationAssetLoader } from '@haiyue/extensions/animation';
71
+
72
+ engine.assetManager!.registerLoader(createAnimationAssetLoader());
73
+ const handle = await engine.assetManager!.loadUrl('motion.hya');
74
+ // handle.value is ParsedAnimation; release the handle with the scene/resource owner.
75
+ ```
76
+
77
+ ```ts
78
+ import { Animation2DRenderSystem, Animation2DSystem } from '@haiyue/extensions/animation';
79
+ import { Particle2DRenderSystem, Particle2DSystem } from '@haiyue/engine';
80
+
81
+ scene.addSystem(new Animation2DSystem({ assetManager: engine.assetManager! }), false);
82
+ scene.addSystem(new Particle2DSystem(), false);
83
+ scene.addSystem(new Animation2DRenderSystem(engine, cameraEntity, {
84
+ loadOp: 'clear',
85
+ maxMaskTargets: 16,
86
+ }));
87
+ scene.addSystem(new Particle2DRenderSystem(engine, cameraEntity, { loadOp: 'load' }));
88
+ ```
89
+
90
+ ```sh
91
+ npm run build -w ./animation-spec
92
+ node animation-spec/bin/hya-convert.mjs input-lottie.json output.hya
93
+ ```
94
+
95
+ JSON 用于调试和工具交换,`.hya` 用于网页交付。完整约束见 [SPECIFICATION.md](./SPECIFICATION.md),机器可读约束见 [schema/animation.schema.json](./schema/animation.schema.json)。运行时 parser 仍是安全边界的最终校验器。
96
+
97
+ 仓库中的 [`examples/animation-spec`](../examples/animation-spec/) 是可交互转换工作台:可以读取允许 CORS 的 Lottie URL 或直接粘贴 JSON,查看 diagnostics/HYA JSON、下载 `.hya`,并在 WebGPU 预览中播放、逐帧移动和拖动时间轴。
98
+
99
+ 真实素材质量与性能基线见 [`corpus/`](./corpus/) 和 [`examples/hya-corpus-dashboard`](../examples/hya-corpus-dashboard/):固定许可明确的 Lottie/AE 参考帧,统一采集 fidelity、raw/gzip size、source-to-runtime parse、warm-adapter first-frame,以及按源 JSON path 建立的 feature 失败归因。运行 `npm run hya:dashboard` 会验证素材哈希、重新转换并通过 Chrome WebGPU 更新两处同源报告。
100
+
101
+ ## v1 能力
102
+
103
+ | 能力 | 规范 | 首版 Haiyue runtime | Lottie converter |
104
+ | --- | --- | --- | --- |
105
+ | 节点树 / 2D transform / opacity | 是 | 是 | 是 |
106
+ | rect / ellipse | 是 | 是 | 是 |
107
+ | image sprite / UV rect / sRGB | 是 | 是,复用 AssetManager | 是 |
108
+ | M/L/Q/C vector path / fill rule | 是 | 是,自适应细分与 geometry cache | 静态 path;动画统一 cubic topology、方向与起点,顶点变化用无损曲线细分归一 |
109
+ | vector paint / stroke | 内建 `org.haiyue.vector-shape@1` | solid/linear/radial gradient、动态 color/opacity/width、dash | 保留同一 shape stack 的多 paint、fill rule、gradient 与 dash |
110
+ | ordered mask stack | 单节点最多 8 层,可嵌套 | add/subtract/intersect/difference、alpha/luma/inverted、feather/animated expansion | 是;超 8 层分解为有序 coverage node,动画 feather 仍精确诊断 |
111
+ | track matte | 是 | 支持嵌套 composite graph | alpha/luma 及 inverted,可与 mask stack 组合 |
112
+ | canvas text | 是 | 动态 document、web font、tracking、确定性 grapheme shaping、字符 animator/range selector | 静态与动画 text document;character/排除空格/word/line、easing、smoothness、确定性 random selector;expression 精确诊断 |
113
+ | ordered visual effects | 是,最多 8 项 | tint/fill/opacity/color-matrix/blur/drop-shadow,单视图复用一对 ping-pong target | 静态与动画参数;未知 AE effect/plugin 不静默近似 |
114
+ | deterministic particle2d | 是 | 是,引擎原生 SoA simulation + WebGPU instancing | 不适用 |
115
+ | timeline audio | 是 | 是,HTML media 与 composition time 同步 | audio layer |
116
+ | step / linear / cubic easing | 是 | 是 | 是 |
117
+ | spatial Bézier motion | position track `spatialTangents` | 普通 timeline 与状态机 mixer 共用 | 保留 Lottie `to/ti` 与 temporal easing |
118
+ | path modifiers | `vector-shape@1` ordered modifiers | animated trim-path、round-corners | simultaneous/individual trim 与 group scope |
119
+ | nested precomp / time stretch | 节点树与普通 track | 是 | 是;precomp 与普通 layer 共用局部 timeline,保留父级 transform、opacity、in/out/start/stretch |
120
+ | precomp time remap | 烘焙为普通 track 时间 | 无来源格式分支 | 单调 scalar keyframe 支持;静态/非单调形式精确诊断 |
121
+
122
+ 转换器必须返回结构化 diagnostics。默认模式允许能力降级,`strict` 模式用于流水线阻止任何有损转换。
123
+
124
+ 转换器同时识别新版 Lottie 的显式 `a: 1` 和旧 Bodymovin 仅以 `k[].t/s/e` 表达的关键帧。后者不再被误判为静态数组。position 的空间 Bézier `to/ti` 与 temporal easing 分开编码;trim-path、round-corners 以有序、来源无关的 path modifier 执行。path morph 会统一为 cubic command topology,并在顶点数变化时用 de Casteljau 曲线细分保持关键帧几何;Merge Paths mode 1 的多个动画 operand 会按素材帧率 bake 为同一 compound morph。文字 document、font mapping、tracking,以及包含 character/排除空格/word/line、easing、smoothness、稳定随机种子的 range selector 都保存在 HYA ABI 中。type 15 data layer 作为 `binary` resource 和非视觉 `org.haiyue.data-layer@1` 节点扩展保留。动画 mask feather、动画 boolean Merge Paths、非 normal layer blend、skew、radial highlight、repeater、expression selector、text expression 与未知 effect/plugin 仍返回带精确 JSON path 的 diagnostics,不会静默丢失或执行源脚本。
125
+
126
+ `org.haiyue.vector-shape@1` 是来源无关的内建视觉组件,不是 Lottie 私有运行时分支。它把 path topology、可选 morph track、solid/gradient fill 或 stroke paint,以及按数组顺序执行的 trim/round modifier 编进 HYA Float32 pool;paint opacity 独立于颜色 alpha,避免动画 opacity 被重复相乘。Lottie animated path 坐标会量化到 1/64 canvas unit,最大源误差为 1/128 unit;转换器同时设置 `morphRelative`,让 morph track 保存相对初始 values 的 delta,运行时采样后再还原绝对坐标,从而避免重复坐标破坏 gzip 交付效率。旧 HYA v1/v2 容器和既有普通 `path2d`、`org.haiyue.vector-stroke@1`、`org.haiyue.vector-path-morph@1` 数据继续可读。
127
+
128
+ `convertLottie()` 的 `fonts` 字段和独立的 `inspectLottieFonts()` 会列出每个 authored font 的使用次数、替代 family、WOFF2 URI、integrity hash 与可选实测 metrics。缺少映射仍输出 `W_LOTTIE_FONT_SUBSTITUTION`;工具不能猜测或静默使用平台字体。动画转换工作台会把这份清单与普通 diagnostics 一起展示。
129
+
130
+ 扩展分为两个相互独立的安装点:`AnimationExtensionRegistry` 校验不可信格式数据,`Animation2DExtensionRegistry` 创建和释放引擎视觉实例。两者使用同一个 versioned id,但工具链无需依赖 WebGPU runtime,runtime 也无需依赖来源格式转换器。
131
+
132
+ Haiyue 运行时由 `Animation2DSystem` 负责时间轴、文字 atlas/web font、音频同步和异步资源生命周期,由独立的 `Animation2DRenderSystem` 负责有序 sprite/path/text 绘制、mask/matte 与效果栈。效果管线在单个 view 内只复用一对全视口 RGBA ping-pong target,并在覆盖下一项前提交当前结果,显存不会随 effect entity 数增长;若 renderer 被错误安装到共享外部 pass,效果会计入 `droppedEffectCount` 而不会尝试嵌套 pass。粒子仿真与绘制属于引擎通用能力,分别安装 `Particle2DSystem` 和 `Particle2DRenderSystem`;格式 runtime 只负责实例化 emitter、时间轴 seek 和资源句柄。
133
+
134
+ ## 单素材状态机
135
+
136
+ 内建扩展 `org.haiyue.animation-state-machine@1` 可以在一个 `.hya` 内声明多个命名时间区间以及状态机。区间引用同一 composition 的 track/node/resource 表,不复制素材或 GPU 资源;运行时把区间适配为 2D clip,再通过共享 mixer 将最终 pose 写回同一棵 HYA 节点树。
137
+
138
+ ```json
139
+ {
140
+ "extensionsUsed": ["org.haiyue.animation-state-machine@1"],
141
+ "extensionsRequired": ["org.haiyue.animation-state-machine@1"],
142
+ "extensions": {
143
+ "org.haiyue.animation-state-machine@1": {
144
+ "clips": [
145
+ { "id": "idle", "start": 0, "duration": 1 },
146
+ { "id": "run", "start": 1, "duration": 0.8 }
147
+ ],
148
+ "stateMachine": {
149
+ "format": "haiyue-animation-state-machine@1",
150
+ "id": "character",
151
+ "name": "Character",
152
+ "parameters": [{ "name": "moving", "type": "boolean", "defaultValue": false }],
153
+ "layers": [{
154
+ "id": "base", "name": "Base", "initialStateId": "idle",
155
+ "states": [
156
+ { "id": "idle", "name": "Idle", "motion": { "kind": "clip", "clipId": "idle" }, "loop": "repeat" },
157
+ { "id": "run", "name": "Run", "motion": { "kind": "clip", "clipId": "run" }, "loop": "repeat" }
158
+ ],
159
+ "transitions": [{
160
+ "id": "move", "from": "idle", "to": "run", "duration": 0.2,
161
+ "conditions": [{ "parameter": "moving", "operator": "is-true" }]
162
+ }]
163
+ }]
164
+ }
165
+ }
166
+ }
167
+ }
168
+ ```
169
+
170
+ ```ts
171
+ import {
172
+ Animation2DStateMachineComponent,
173
+ Animation2DStateMachineSystem,
174
+ } from '@haiyue/extensions/hya-state-machine';
175
+
176
+ scene.addSystem(new Animation2DStateMachineSystem({ assetManager: engine.assetManager! }), false);
177
+ const character = new Animation2DStateMachineComponent(hya, { autoplay: true });
178
+ entity.addComponent(character);
179
+ character.setBoolean('moving', true); // Idle -> Run,按 transition.duration cross-fade
180
+ ```
181
+
182
+ 参数支持 float、integer、boolean 和一次性 trigger;state 支持 clip、1D/2D Blend Tree,layer 支持 weight、override/additive 和 binding mask。区间裁剪会保留 step/linear/cubic-bezier 曲线。当前 pose mixer 不会静默丢弃 timeline audio、particle、animated path morph 或自定义带时间副作用的组件;这些内容用于状态 clip 时会在实例化前给出精确诊断。
183
+
184
+ 当前 `particle2d` 使用独立 render pass,因此不参与动画视觉的精确层间排序和 mask/matte;需要这种语义时应在后续引入统一的 2D render graph item 协议。浏览器音频受 autoplay policy 约束,用户手势前的 `play()` 失败会保持可重试,不会中断动画帧。
185
+
186
+ ## License
187
+
188
+ [MIT](./LICENSE)
189
+
190
+ Repository:[HypnosNova/HaiYue / animation-spec](https://github.com/HypnosNova/HaiYue/tree/main/animation-spec)。规范见 [SPECIFICATION.md](./SPECIFICATION.md),首发支持边界见 [known limitations](https://github.com/HypnosNova/HaiYue/blob/main/docs/engine-guide/known-limitations.md)。
@@ -0,0 +1,108 @@
1
+ # Haiyue Animation 1.0
2
+
3
+ ## 1. 目标
4
+
5
+ Haiyue Animation 是动效的运行时中间表示(IR)。规范优先保证:浏览器低分配解析、可预测的能力集合、未知可选能力可跳过、必需能力明确失败,以及来源格式不进入播放器依赖图。
6
+
7
+ `format` 固定为 `haiyue-animation`,规范版本固定为 `1.0`。容器扩展名为 `.hya`,MIME 为 `application/vnd.haiyue.animation`。
8
+
9
+ ## 2. 时间与坐标
10
+
11
+ - 所有持久化时间单位都是秒;`frameRate` 仅保留创作信息,不参与运行时寻址。
12
+ - `duration` 必须大于零,track 时间严格递增并位于 `[0, duration]`。
13
+ - v1 坐标系固定为 `screen-y-down`:原点位于画布左上,x 向右,y 向下;旋转使用弧度。
14
+ - transform 的 `position`、`rotation`、`scale`、`anchor`、`opacity` 默认分别为 `[0,0]`、`0`、`[1,1]`、`[0,0]`、`1`。
15
+
16
+ ## 3. 文档模型
17
+
18
+ 文档由定宽画布、资源表、扁平节点表和 SoA 友好的 track 表组成。节点通过稳定字符串 id 与 parent id 建树;格式禁止重复 id、悬空 parent 和循环。组件是节点的视觉或行为能力。
19
+
20
+ v1 核心组件包括:
21
+
22
+ - `shape2d`:`rect` 或 `ellipse`、局部位置、尺寸和线性 RGBA fill;
23
+ - `sprite2d`:image 资源 id、局部位置、尺寸、可选 tint 和归一化 `uvRect`;可用 `uvRectTrack` 的 STEP 关键帧在同一 atlas 内切换来源区域,`valueSize` 固定为 4,每个矩形都必须完整位于 `[0,1]`;
24
+ - `path2d`:紧凑的 `M/L/Q/C/Z` command stream、连续 float values、fill、fill rule 和细分容差。
25
+ - `text2d`:UTF-16 text、布局尺寸、字体样式、对齐、颜色与栅格化倍率;可包含 step-keyed text document、binary font resource、tracking,以及最多 16 个按顺序执行的字符 animator/range selector;
26
+ - `particle2d`:固定最大容量、发射率/首帧 burst、确定性 seed、生命周期/速度/尺寸范围、重力、形状、颜色和混合模式;可引用一个 image;
27
+ - `audio`:引用 audio resource,并声明 volume、loop、start offset 与 playback rate。
28
+
29
+ image 资源默认按 sRGB 采样,可用 `colorSpace: "linear"` 显式覆盖。sprite 与 particle texture 必须引用 image,audio component 必须引用 audio resource,均不能引用任意 binary 资源。
30
+
31
+ text document 可以切换 text、font family/size/weight/style、font resource、line height、tracking、alignment 和 color。runtime 使用确定性的 grapheme 边界与 Canvas shaping;映射到 web font 的资源必须是 binary,加载完成后重建文字 atlas。字符 animator 支持 position、scale、rotation、opacity、fill color 与 tracking;selector 支持 percent/index、square/ramp/triangle/round/smooth、动画 start/end/offset/amount、characters/characters-excluding-spaces/words/lines 分组、shape easing、smoothness,以及基于 uint32 seed 的确定性随机排列。Lottie `rn` 不得在播放时调用 `Math.random()`;转换器从稳定 source path 派生 seed。expression selector 与 text document expression 不在 Web runtime 执行,必须保留静态 fallback、精确 diagnostic 和离线 bake 路径。
32
+
33
+ 节点的 `effects` 是最多 8 项的有序、来源无关效果栈。v1 支持 tint、fill、opacity、4×5 color matrix、二维 blur 和 drop shadow;静态值与普通 step/linear/cubic-bezier value track 使用相同 Float32 pool。运行时按数组顺序执行,颜色效果、模糊和投影不得在导入阶段静默烘焙进某个特定组件。未覆盖的 AE effect、plugin 或 expression 保持离线 bake/no-go,并指向原始 effect/parameter path。
34
+
35
+ Lottie type 15 data layer 是非视觉数据依赖:引用的 payload 以 `binary` resource 保存,节点通过 `org.haiyue.data-layer@1` 记录 resource 与 media type。该扩展只保留来源和依赖关系,不解释或执行引用它的 JavaScript expression;因此数据层可完整转换,而表达式能力必须单独归因。
36
+
37
+ 节点可用 `composite` 引用另一个稳定 node id 作为 `mask` 或 `matte`。单层对象保持早期格式兼容;`{ layers: [...] }` 表示最多 8 层的有序复合栈。每层模式可为 `alpha`、`alpha-inverted`、`luma`、`luma-inverted`,操作可为 `add`、`subtract`、`intersect`、`difference`,并可携带非负 feather、有符号 expansion 和可选 scalar `expansionTrack`。source 节点及其子树只参与离屏来源输出,不再进入主颜色输出;source 自身可以引用更早的 composite source,从而表达嵌套 matte,以及在不扩宽单 Pass texture ABI 的情况下分解大型有序 mask 栈。自引用、环和悬空引用在 JSON 与 compact binary 两条路径上都必须失败。
38
+
39
+ `org.haiyue.vector-shape@1` 是内建、来源无关的 vector visual component。它包含一条稳定 `M/L/Q/C/Z` topology、初始 values、可选 morph track,以及 fill 或 stroke paint。`morphRelative: true` 表示 morph 每个 sample 是相对初始 values 的逐分量 delta;缺省或 false 继续表示绝对坐标。fill 支持 solid、linear-gradient 与 radial-gradient;stroke 支持 width/cap/join/miter、dash、gradient。颜色、paint opacity、gradient geometry/stops、width 和 dash offset 可以携带普通 step/linear/cubic-bezier value track。`modifiers` 是最多 8 项的有序数组,当前包含 animated `trim-path`(simultaneous/individual)与 `round-corners`;运行时严格按数组顺序在 geometry tessellation 前执行。Lottie converter 对 animated path 坐标使用 1/64 canvas-unit 网格,最大转换误差为 1/128 unit,同时避免不可压缩的任意 Float32 mantissa。gradient stops 限制为 2–8 个有序 `offset,r,g,b,a` 元组,paint opacity 与颜色 alpha 分开存储。所有内嵌 track 时间必须落在 composition duration 内。
40
+
41
+ v1 track 属性是 `position`、`rotation`、`scale`、`opacity`。`times` 与 `values` 紧密排列;position/scale 每帧两个 float,其余属性每帧一个 float。cubic-bezier 每个相邻关键帧段保存一个 temporal `x1,y1,x2,y2`,两个 x 必须位于 `[0,1]`。position 可额外保存每段 4 个 `spatialTangents`,依次为相对起点的 outgoing xy 和相对终点的 incoming xy;temporal easing 决定曲线进度,spatial cubic 决定二维轨迹,二者不得混用。
42
+
43
+ JSON Schema 描述 authoring JSON 的结构;parser 还会检查跨表引用、层级、数值有限性、计数和输入字节预算。实现必须在创建字符串纹理或粒子 SoA 前检查 `maxTextCharacters` 与 `maxParticleCapacity` 的全 composition 预算。
44
+
45
+ ## 4. 二进制容器 HYA1
46
+
47
+ 所有整数和 float 都是 little-endian。24 字节 header 依次为:
48
+
49
+ | Offset | 类型 | 内容 |
50
+ | ---: | --- | --- |
51
+ | 0 | `u32` | magic `HYA1` |
52
+ | 4 | `u16` | container major = 1 |
53
+ | 6 | `u16` | container minor = 0 |
54
+ | 8 | `u32` | metadata byte offset |
55
+ | 12 | `u32` | metadata byte length |
56
+ | 16 | `u32` | 4-byte aligned float pool offset |
57
+ | 20 | `u32` | float count |
58
+
59
+ metadata 是 UTF-8 JSON,但 track 数组、`path2d.values`、文字 animator track 和 effect track 以 `{offset,length}` 引用一个连续 `Float32` pool。解码器在原始 `ArrayBuffer` 上创建 view,不逐 track/path 分配或复制。text document、particle 配置和 audio/font 引用保留在 metadata;资源 payload 不嵌入 HYA1,通过 URI、MIME 和可选 integrity 独立缓存。新增 compact node/effect/text 字段是可选尾部字段,旧 v1/v2 binary 继续可读。
60
+
61
+ ## 5. 扩展
62
+
63
+ 扩展 id 必须是带 major 的命名空间,例如 `org.example.particle@1`。文档在 `extensionsUsed` 声明全部扩展;不能降级的扩展同时放入 `extensionsRequired`。
64
+
65
+ - 未注册的 optional 扩展组件可被 runtime 跳过。
66
+ - 未注册的 required 扩展必须在创建运行时对象前失败。
67
+ - 扩展 major 不兼容时使用新 id,不在同一 id 下改变语义。
68
+ - 注册表按 handler 身份 token 化注销,旧插件不能移除后注册的实现。
69
+
70
+ 新增通用能力应先以扩展验证数据模型和性能;只有多个独立生产用例都需要且有跨 runtime 一致语义时,才进入下一个 core version。
71
+
72
+ 具体播放器可以提供同 id 的 runtime handler。Haiyue 2D handler 获得 anchor-adjusted parent,并返回支持确定性 `apply(compositionTime, opacity)` 与 `destroy()` 的实例;实现必须能处理 seek、循环回绕和重复释放,不能假设时间只单调前进。
73
+
74
+ ### 5.1 内建动画状态机扩展
75
+
76
+ `org.haiyue.animation-state-machine@1` 是内建的 versioned document extension,因此作为 required extension 时不要求外部格式 registry。基础 `parseAnimation()` 负责不可信输入的容器、metadata 和总量预算;`parseHyaStateMachineExtension()` 负责下列严格语义校验,状态机 runtime 会在创建任何 Entity、视觉或 GPU 资源前调用它。payload 包含:
77
+
78
+ - `clips`:唯一 id、可选 name、composition 内的 `start`/`duration`;所有区间必须完整落在文档 duration 内;
79
+ - `stateMachine`:固定 format `haiyue-animation-state-machine@1`,以及 parameters、layers、states、transitions;
80
+ - state motion 可以直接引用 clip,或用 float/integer 参数构成递归但有深度预算的 1D/2D Blend Tree;
81
+ - transition condition 必须与参数类型匹配;声明顺序决定同一帧内的优先级;trigger 只由成功选中的 transition 消费;
82
+ - layer 可以声明 override/additive、weight 以及稳定 binding id 的 include/exclude mask。
83
+
84
+ 状态机描述不烘焙进每条 track。JSON 和 HYA binary 都通过现有 document extension metadata 保存该 payload,keyframe float pool 和旧 container 解码路径不变。播放实现必须让多个 clip 共享一份解析结果、资源句柄和节点实例;cross-fade 只混合 pose,不能通过并行创建两个完整素材实例来伪装状态切换。
85
+
86
+ Haiyue 2D runtime 将 position、rotation、scale、opacity 和 node visibility 作为 pose binding。step、linear 与裁剪后的 cubic-bezier 必须保持原采样语义。audio、particle、animated path morph 或未知时间副作用尚未具有混合协议时,adapter 必须在创建场景节点前失败并指出源组件路径,不能静默丢弃或退回两份素材播放。
87
+
88
+ ### 5.2 原生 3D 必需扩展
89
+
90
+ 原生 3D 不改变 HYA core 1.0 的 2D transform 语义。它使用 required document extension `org.haiyue.animation-3d@1`,payload format 为 `haiyue-animation-3d@1`;标识必须同时出现在 `extensionsUsed` 和 `extensionsRequired`。
91
+
92
+ 3D carrier 的 core `canvas` 只表示输出 viewport,core `nodes` 和 `tracks` 必须为空。任何 2D core 内容与 native-3D payload 同时出现都以 `E_ANIMATION_3D_MIXED_DIMENSIONS` 拒绝。3D 坐标固定为右手、`+Y` up、`-Z` forward、米、秒、弧度和 normalized XYZW quaternion;Euler 只属于 authoring UI。
93
+
94
+ Payload 包含 canonical Transform3D、perspective/orthographic camera、primitive/model、基础 PBR material、Particle3D descriptor、`haiyue-animation3d-clip@1` clip,以及可选 `haiyue-animation3d-state-machine@1` controller。Joint 使用稳定 node id/path 的 transform binding,Morph 使用 `morph.weights`,material/camera 使用有限集合的 property binding。glTF/GLB 仍是来源 adapter 责任,不进入格式 parser。
95
+
96
+ 不支持 3D 的宿主必须在创建 ECS/GPU/runtime owner 前拒绝 required extension。完整字段、预算、diagnostic 和 fixture 由 `schema/animation-3d-extension.schema.json`、`schema/animation-3d.contract.json` 与 `@haiyue/animation-spec/native3d` 构建声明定义;本规范不复制整份 declaration 或 schema。
97
+
98
+ ## 6. 转换器契约
99
+
100
+ 转换发生在编辑器导入或构建阶段。转换器输出 document、已转换/跳过计数以及带 code、path、severity 的 diagnostics。来源单位、坐标和 easing 必须在转换时归一化;播放器不得保留按来源格式分支。
101
+
102
+ 有损转换在普通模式产生 warning,在 strict 模式失败。未知内容不能被悄悄解释成近似但语义不同的核心组件。
103
+
104
+ ## 7. 安全与版本
105
+
106
+ 输入是不可信数据。实现必须在分配前限制输入、metadata、node、component、track、keyframe、resource、文本字符和粒子总容量,并拒绝 NaN、Infinity、越界引用和非法 binary range。
107
+
108
+ 当前项目没有历史项目兼容负担:不兼容的核心格式变更提升版本并同步迁移仓库数据,不在 parser 内累积永久 fallback。对外发布后的迁移窗口需另立 ADR。
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFile, writeFile } from 'node:fs/promises';
4
+ import { extname, resolve } from 'node:path';
5
+ import { encodeAnimationBinary } from '../dist/index.js';
6
+ import { convertLottie } from '../dist/lottie.js';
7
+
8
+ const args = process.argv.slice(2);
9
+ if (args.includes('--help') || args.length < 2) {
10
+ console.log('Usage: hya-convert <input.json> <output.hya|output.json> [--strict]');
11
+ process.exit(args.includes('--help') ? 0 : 1);
12
+ }
13
+
14
+ const [inputName, outputName] = args;
15
+ if (!inputName || !outputName) process.exit(1);
16
+
17
+ const inputPath = resolve(inputName);
18
+ const outputPath = resolve(outputName);
19
+ const input = await readFile(inputPath, 'utf8');
20
+ const result = convertLottie(input, { strict: args.includes('--strict') });
21
+
22
+ if (extname(outputPath).toLowerCase() === '.json') {
23
+ await writeFile(outputPath, `${JSON.stringify(result.document, null, 2)}\n`);
24
+ } else {
25
+ await writeFile(outputPath, new Uint8Array(encodeAnimationBinary(result.document)));
26
+ }
27
+
28
+ for (const diagnostic of result.diagnostics) {
29
+ console.error(`${diagnostic.severity}: ${diagnostic.code} ${diagnostic.path} - ${diagnostic.message}`);
30
+ }
31
+ console.log(`Converted ${result.convertedLayerCount} layer(s), skipped ${result.skippedLayerCount}; wrote ${outputPath}.`);
@@ -0,0 +1,7 @@
1
+ import type { AnimationDocument, AnimationParseOptions, ParsedAnimation } from './types';
2
+ export declare function isAnimationBinary(buffer: ArrayBuffer): boolean;
3
+ /** Encodes compact indexed metadata plus one contiguous zero-copy Float32 track/path pool. */
4
+ export declare function encodeAnimationBinary(document: AnimationDocument | ParsedAnimation, options?: AnimationParseOptions): ArrayBuffer;
5
+ export declare function decodeAnimationBinary(buffer: ArrayBuffer, options?: AnimationParseOptions): ParsedAnimation;
6
+ /** @internal Parser entry point that checks and consumes the magic with one DataView. */
7
+ export declare function tryDecodeAnimationBinary(buffer: ArrayBuffer, options: AnimationParseOptions): ParsedAnimation | undefined;
@@ -0,0 +1,8 @@
1
+ const ANIMATION_FORMAT = 'haiyue-animation';
2
+ const ANIMATION_VERSION = '1.0';
3
+ const ANIMATION_MIME_TYPE = 'application/vnd.haiyue.animation';
4
+ const ANIMATION_FILE_EXTENSION = '.hya';
5
+ const ANIMATION_VECTOR_SHAPE_EXTENSION_ID = 'org.haiyue.vector-shape@1';
6
+
7
+ export { ANIMATION_VERSION as A, ANIMATION_FORMAT as a, ANIMATION_VECTOR_SHAPE_EXTENSION_ID as b, ANIMATION_FILE_EXTENSION as c, ANIMATION_MIME_TYPE as d };
8
+ //# sourceMappingURL=types-l6nBVYwx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-l6nBVYwx.js","sources":["../../src/types.ts"],"sourcesContent":[null],"names":[],"mappings":"AAAO,MAAM,gBAAgB,GAAG;AACzB,MAAM,iBAAiB,GAAG;AAC1B,MAAM,mBAAmB,GAAG;AAC5B,MAAM,wBAAwB,GAAG;AAgLjC,MAAM,mCAAmC,GAAG;;;;"}
@@ -0,0 +1,7 @@
1
+ export type AnimationFormatErrorCode = 'E_ANIMATION_INVALID_FORMAT' | 'E_ANIMATION_UNSUPPORTED_VERSION' | 'E_ANIMATION_LIMIT_EXCEEDED' | 'E_ANIMATION_MISSING_EXTENSION' | 'E_ANIMATION_INVALID_BINARY';
2
+ export declare class AnimationFormatError extends Error {
3
+ readonly code: AnimationFormatErrorCode;
4
+ readonly path: string;
5
+ readonly name = "AnimationFormatError";
6
+ constructor(code: AnimationFormatErrorCode, message: string, path?: string);
7
+ }
@@ -0,0 +1,19 @@
1
+ export interface AnimationExtensionValidationContext {
2
+ readonly extension: string;
3
+ readonly path: string;
4
+ fail(message: string, path?: string): never;
5
+ }
6
+ export interface AnimationExtensionHandler {
7
+ /** Versioned identifier such as `org.example.particle@1`. */
8
+ readonly id: string;
9
+ validateComponent?(component: Readonly<Record<string, unknown>>, context: AnimationExtensionValidationContext): void;
10
+ validateDocument?(data: unknown, context: AnimationExtensionValidationContext): void;
11
+ }
12
+ export declare class AnimationExtensionRegistry {
13
+ private readonly _handlers;
14
+ register(handler: AnimationExtensionHandler): () => void;
15
+ get(id: string): AnimationExtensionHandler | undefined;
16
+ has(id: string): boolean;
17
+ }
18
+ export declare function extensionIdFromComponentType(type: string): string | null;
19
+ export declare function validateExtensionId(value: string): void;
@@ -0,0 +1,10 @@
1
+ export { ANIMATION_FILE_EXTENSION, ANIMATION_FORMAT, ANIMATION_MIME_TYPE, ANIMATION_VERSION, ANIMATION_VECTOR_SHAPE_EXTENSION_ID, } from './types';
2
+ export type { AnimationBinaryResource, AnimationAudioComponent, AnimationAudioResource, AnimationCanvas, AnimationComponent, AnimationCoordinateSystem, AnimationComposite, AnimationCompositeKind, AnimationCompositeLayer, AnimationCompositeMode, AnimationCompositeOperation, AnimationCompositeStack, AnimationDocument, AnimationEndBehavior, AnimationExtensionComponent, AnimationImageResource, AnimationInterpolation, AnimationLayerEffect, AnimationTintEffect, AnimationFillEffect, AnimationOpacityEffect, AnimationColorMatrixEffect, AnimationBlurEffect, AnimationDropShadowEffect, AnimationFillRule, AnimationNode, AnimationParseLimits, AnimationParseOptions, AnimationPath2DComponent, AnimationPathCommand, AnimationParticle2DComponent, AnimationResource, AnimationShape2DComponent, AnimationSource, AnimationSprite2DComponent, AnimationText2DComponent, AnimationTextAnimator, AnimationTextDocumentKeyframe, AnimationTextRangeSelector, AnimationTextSelectorShape, AnimationTextSelectorUnits, AnimationTrack, AnimationTrackProperty, AnimationTransform2D, AnimationVectorGradientPaint, AnimationVectorShapeComponent, AnimationVectorSolidPaint, AnimationVectorStrokePaint, AnimationVectorValueTrack, ParsedAnimation, ParsedAnimationTrack, } from './types';
3
+ export { AnimationFormatError } from './errors';
4
+ export type { AnimationFormatErrorCode } from './errors';
5
+ export { AnimationExtensionRegistry, extensionIdFromComponentType, validateExtensionId } from './extensions';
6
+ export type { AnimationExtensionHandler, AnimationExtensionValidationContext } from './extensions';
7
+ export { parseAnimation } from './parser';
8
+ export { decodeAnimationBinary, encodeAnimationBinary, isAnimationBinary } from './binary';
9
+ export { HYA_STATE_MACHINE_CHANNEL_REGISTRY, HYA_STATE_MACHINE_EXTENSION_ID, hyaStateMachineChannelCapability, parseHyaStateMachineExtension, } from './state-machine';
10
+ export type { HyaAnimationClipRange, HyaStateMachineBindingMask, HyaStateMachineBlendMode, HyaStateMachineChannelCapability, HyaStateMachineChannelId, HyaStateMachineChannelKind, HyaStateMachineChannelSupport, HyaStateMachineCondition, HyaStateMachineDefinition, HyaStateMachineExtension, HyaStateMachineLayer, HyaStateMachineLoopMode, HyaStateMachineMotion, HyaStateMachineParameter, HyaStateMachineState, HyaStateMachineTransition, } from './state-machine';