@lingfan-engine/ui 0.0.0-stage → 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 (63) hide show
  1. package/LICENSE +201 -0
  2. package/package.json +38 -4
  3. package/src/audio/audio.ts +331 -0
  4. package/src/audio/index.ts +11 -0
  5. package/src/choices/index.ts +10 -0
  6. package/src/choices/templates.ts +74 -0
  7. package/src/commands/index.ts +6 -0
  8. package/src/commands/registry.ts +54 -0
  9. package/src/dialogue/index.ts +24 -0
  10. package/src/dialogue/inline.ts +136 -0
  11. package/src/dialogue/templates.ts +70 -0
  12. package/src/dialogue/textView.ts +35 -0
  13. package/src/dialogue/typewriter.ts +181 -0
  14. package/src/dom/index.ts +7 -0
  15. package/src/dom/materialize.ts +88 -0
  16. package/src/dom/overlay-surface.ts +278 -0
  17. package/src/element/animation.ts +141 -0
  18. package/src/element/index.ts +38 -0
  19. package/src/element/interaction.ts +123 -0
  20. package/src/element/registry.ts +69 -0
  21. package/src/element/render.ts +77 -0
  22. package/src/element/renderers/base.ts +56 -0
  23. package/src/element/renderers/bindings.ts +178 -0
  24. package/src/element/renderers/container.ts +141 -0
  25. package/src/element/renderers/controls.ts +80 -0
  26. package/src/element/renderers/decoration.ts +28 -0
  27. package/src/element/renderers/index.ts +5 -0
  28. package/src/element/renderers/media.ts +71 -0
  29. package/src/element/renderers/register.ts +77 -0
  30. package/src/element/renderers/text.ts +20 -0
  31. package/src/element/resource.ts +55 -0
  32. package/src/element/spec.ts +77 -0
  33. package/src/element/style.ts +150 -0
  34. package/src/host/duration.ts +25 -0
  35. package/src/host/effects.ts +174 -0
  36. package/src/host/frame-loop.ts +84 -0
  37. package/src/host/index.ts +47 -0
  38. package/src/host/layer-view.ts +74 -0
  39. package/src/host/state-view.ts +190 -0
  40. package/src/index.ts +161 -0
  41. package/src/input/index.ts +11 -0
  42. package/src/input/scope.ts +100 -0
  43. package/src/minigame/index.ts +2 -0
  44. package/src/minigame/registry.ts +35 -0
  45. package/src/notify/index.ts +11 -0
  46. package/src/notify/templates.ts +60 -0
  47. package/src/overlay/choices-view.ts +76 -0
  48. package/src/overlay/create.ts +254 -0
  49. package/src/overlay/dialogue-view.ts +72 -0
  50. package/src/overlay/element-tree.ts +109 -0
  51. package/src/overlay/index.ts +16 -0
  52. package/src/overlay/layer-z.ts +73 -0
  53. package/src/overlay/notify-view.ts +32 -0
  54. package/src/overlay/projector.ts +286 -0
  55. package/src/overlay/surface.ts +125 -0
  56. package/src/overlay/types.ts +124 -0
  57. package/src/resources/index.ts +10 -0
  58. package/src/resources/urlCache.ts +79 -0
  59. package/src/templates/index.ts +7 -0
  60. package/src/templates/registry.ts +79 -0
  61. package/src/video/index.ts +6 -0
  62. package/src/video/videoView.ts +122 -0
  63. package/README.md +0 -3
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2026 MoFeng-02
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@lingfan-engine/ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "灵泛叙事引擎参考展示层:框架无关的可测纯逻辑(内联标记、打字机、音频差量规划)",
6
+ "license": "Apache-2.0",
7
+ "exports": {
8
+ ".": "./src/index.ts"
9
+ },
10
+ "files": [
11
+ "src",
12
+ "!src/**/*.test.ts"
13
+ ],
14
+ "sideEffects": false,
15
+ "dependencies": {
16
+ "@lingfan-engine/core": "workspace:*"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/MoFeng-02/LingFan.Engine.git",
21
+ "directory": "packages/ui"
22
+ },
23
+ "homepage": "https://github.com/MoFeng-02/LingFan.Engine#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/MoFeng-02/LingFan.Engine/issues"
26
+ },
27
+ "keywords": [
28
+ "narrative",
29
+ "ui",
30
+ "dialogue",
31
+ "typewriter",
32
+ "framework-agnostic"
33
+ ],
34
+ "engines": {
35
+ "node": ">=22.12.0"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ }
40
+ }
@@ -0,0 +1,331 @@
1
+ /**
2
+ * 音频渲染:核心只写状态,此处把状态差量翻译成端口动作(可测纯逻辑),
3
+ * 由适配器(infra/audioPort)落地播放;资源寻址经 ResourcePort,
4
+ * 播放位置回写走帧级键。
5
+ *
6
+ * 状态经引擎的类型化读口读取(`createStateReader`):通道形状校验与降级在引擎侧
7
+ * 只有一份,本层只负责「差量 → 端口动作」。
8
+ */
9
+ import type {
10
+ AudioChannel,
11
+ AudioChannelState,
12
+ AudioPort,
13
+ PlayerPreferences,
14
+ ResourcePort,
15
+ StoryEngine,
16
+ } from "@lingfan-engine/core";
17
+ import { createStateReader, SYS } from "@lingfan-engine/core";
18
+ import { createResourceUrlCache } from "../resources";
19
+
20
+ /** 渲染视图:四通道状态 + bgm 播放位置(帧级键直读,不进事件流) */
21
+ export interface AudioView {
22
+ bgm: AudioChannelState | null;
23
+ ambient: AudioChannelState | null;
24
+ voice: AudioChannelState | null;
25
+ se: AudioChannelState | null;
26
+ bgmPosition: number;
27
+ }
28
+
29
+ /** 端口动作:play = 播放/更新/定位/重播,stop = 停止(fadeMs 淡出) */
30
+ export type AudioAction =
31
+ | {
32
+ type: "play";
33
+ channel: AudioChannel;
34
+ resource: string;
35
+ volume: number;
36
+ loop: boolean;
37
+ position: number;
38
+ fadeMs: number;
39
+ /** true = 回到 position 重播;false = 同资源无缝续播/更新 */
40
+ restart: boolean;
41
+ }
42
+ | { type: "stop"; channel: AudioChannel; fadeMs: number };
43
+
44
+ /**
45
+ * `AudioAction` 中 play 分支的别名(按 `type` 判别后的收窄形态)。
46
+ * 它不是新的动作形状,字段仍以 `AudioAction` 的 play 分支为唯一来源,只是给
47
+ * 「已经排除了 stop」的本地执行边界一个名字:`apply` 处理掉 stop 后把剩下的交给
48
+ * `playAction` 逐条落地播放,参数用它写明「这里拿到的必然是 play」。
49
+ */
50
+ type PlayAction = Extract<AudioAction, { type: "play" }>;
51
+
52
+ /** 常驻通道(se 为一次性触发,单独按 seq 判定) */
53
+ const CHANNELS = ["bgm", "ambient", "voice"] as const;
54
+
55
+ /** 位置差异阈值(秒):小于此视为播放器噪声,不打断播放(seek 抖动防护) */
56
+ const SEEK_THRESHOLD = 0.5;
57
+
58
+ /** 空视图:渲染器初始差量基准(组合根创建顺序无关,引擎已推进也能补播) */
59
+ export const EMPTY_AUDIO_VIEW: AudioView = {
60
+ bgm: null,
61
+ ambient: null,
62
+ voice: null,
63
+ se: null,
64
+ bgmPosition: 0,
65
+ };
66
+
67
+ /** 有效音量合成末端:op 音量 × 通道偏好(prefs 缺省/偏好 1 = 原样,不复制对象) */
68
+ function withPrefs(
69
+ state: AudioChannelState | null,
70
+ pref: number | undefined,
71
+ ): AudioChannelState | null {
72
+ if (state === null || state.kind !== "play") return state;
73
+ if (pref === undefined || pref === 1) return state;
74
+ return { ...state, volume: Math.min(1, Math.max(0, state.volume * pref)) };
75
+ }
76
+
77
+ /** prefs 存在时各通道合成玩家有效音量(偏好在视图层落地,planAudioActions 差量自动感知) */
78
+ export function readAudioView(
79
+ engine: StoryEngine,
80
+ prefs?: PlayerPreferences,
81
+ ): AudioView {
82
+ const reader = createStateReader(engine);
83
+ return {
84
+ bgm: withPrefs(reader.audioChannel("bgm"), prefs?.effectiveVolume("bgm")),
85
+ ambient: withPrefs(
86
+ reader.audioChannel("ambient"),
87
+ prefs?.effectiveVolume("ambient"),
88
+ ),
89
+ voice: withPrefs(
90
+ reader.audioChannel("voice"),
91
+ prefs?.effectiveVolume("voice"),
92
+ ),
93
+ se: withPrefs(reader.audioChannel("se"), prefs?.effectiveVolume("se")),
94
+ bgmPosition: reader.mediaPosition(),
95
+ };
96
+ }
97
+
98
+ /**
99
+ * 状态差量 → 端口动作:
100
+ * - 通道由 play 变 stop/null → stop(带淡出参数)
101
+ * - 换资源 → play(bgm 从目标位置起播)
102
+ * - 同资源 + 显式 restart(seq 变化)→ play 回到起点重播
103
+ * - 同资源仅音量/循环变化 → play 更新(适配器不重头播);bgm 位置差超阈值 → 定位
104
+ * - se 按单调 seq 判定:每次执行都触发一次(同一资源连续触发亦然)
105
+ */
106
+ export function planAudioActions(
107
+ prev: AudioView,
108
+ next: AudioView,
109
+ ): AudioAction[] {
110
+ const actions: AudioAction[] = [];
111
+ for (const channel of CHANNELS) {
112
+ const before = prev[channel];
113
+ const after = next[channel];
114
+ if (after === null || after.kind !== "play") {
115
+ if (before !== null && before.kind === "play") {
116
+ actions.push({
117
+ type: "stop",
118
+ channel,
119
+ fadeMs: after !== null && after.kind === "stop" ? after.fadeMs : 0,
120
+ });
121
+ }
122
+ continue;
123
+ }
124
+ const position = channel === "bgm" ? next.bgmPosition : 0;
125
+ const sameResource =
126
+ before !== null &&
127
+ before.kind === "play" &&
128
+ before.resource === after.resource;
129
+ if (!sameResource) {
130
+ actions.push({
131
+ type: "play",
132
+ channel,
133
+ resource: after.resource,
134
+ volume: after.volume,
135
+ loop: after.loop,
136
+ position,
137
+ fadeMs: after.fadeMs,
138
+ restart: true,
139
+ });
140
+ continue;
141
+ }
142
+ // 同资源:显式重播优先于增量更新(seq 变化 = 这是一次新的重播请求)
143
+ if (after.restart === true && after.seq !== before.seq) {
144
+ actions.push({
145
+ type: "play",
146
+ channel,
147
+ resource: after.resource,
148
+ volume: after.volume,
149
+ loop: after.loop,
150
+ position: 0,
151
+ fadeMs: after.fadeMs,
152
+ restart: true,
153
+ });
154
+ continue;
155
+ }
156
+ if (before.volume !== after.volume || before.loop !== after.loop) {
157
+ actions.push({
158
+ type: "play",
159
+ channel,
160
+ resource: after.resource,
161
+ volume: after.volume,
162
+ loop: after.loop,
163
+ position,
164
+ fadeMs: after.fadeMs,
165
+ restart: false,
166
+ });
167
+ continue;
168
+ }
169
+ if (
170
+ channel === "bgm" &&
171
+ Math.abs(next.bgmPosition - prev.bgmPosition) > SEEK_THRESHOLD
172
+ ) {
173
+ actions.push({
174
+ type: "play",
175
+ channel,
176
+ resource: after.resource,
177
+ volume: after.volume,
178
+ loop: after.loop,
179
+ position,
180
+ fadeMs: 0,
181
+ restart: false,
182
+ });
183
+ }
184
+ }
185
+ const beforeSe = prev.se;
186
+ const afterSe = next.se;
187
+ if (
188
+ afterSe !== null &&
189
+ afterSe.kind === "play" &&
190
+ (beforeSe === null ||
191
+ beforeSe.kind !== "play" ||
192
+ beforeSe.seq !== afterSe.seq)
193
+ ) {
194
+ actions.push({
195
+ type: "play",
196
+ channel: "se",
197
+ resource: afterSe.resource,
198
+ volume: afterSe.volume,
199
+ loop: false,
200
+ position: 0,
201
+ fadeMs: 0,
202
+ restart: true,
203
+ });
204
+ }
205
+ return actions;
206
+ }
207
+
208
+ /** 音频渲染器:订阅通道事件 → 差量应用;位置回写由帧循环驱动 */
209
+ export interface AudioRenderer {
210
+ /** 与引擎状态对齐(订阅外的显式同步,如读档/回溯完成) */
211
+ sync(): void;
212
+ /** 帧循环回写播放位置:帧级键静默写,不进事件流 */
213
+ pollPosition(): void;
214
+ dispose(): void;
215
+ }
216
+
217
+ /**
218
+ * 宿主侧回调:解析失败的诊断出口;不传则该失败被静默忽略。
219
+ * `preferences` 是唯一的可选注入——不传即无偏好,音量按引擎状态算。
220
+ */
221
+ export interface AudioRendererOptions {
222
+ /** 资源解析失败诊断(报错诊断:不静默吞错) */
223
+ onError?: (message: string) => void;
224
+ /** 玩家偏好(可选):合成通道有效音量;偏好变化即时重规划(滑块/静音即时生效) */
225
+ preferences?: PlayerPreferences;
226
+ }
227
+
228
+ /**
229
+ * 造一个音频渲染器并立即订阅四条通道的音频状态(构造末尾先自同步一次)。
230
+ *
231
+ * 它按通道分代际,迟到的旧解析结果不误播;资源 URL 经共享缓存取,`dispose` 时
232
+ * 逐个 `resources.release` 并退订。位置回写不由本层计时——宿主每帧调 `pollPosition`。
233
+ */
234
+ export function createAudioRenderer(
235
+ engine: StoryEngine,
236
+ port: AudioPort,
237
+ resources: ResourcePort,
238
+ options: AudioRendererOptions = {},
239
+ ): AudioRenderer {
240
+ const audioKeys = new Set<string>([
241
+ SYS.audioBgm,
242
+ SYS.audioSe,
243
+ SYS.audioAmbient,
244
+ SYS.audioVoice,
245
+ ]);
246
+ const reader = createStateReader(engine);
247
+ let view: AudioView = EMPTY_AUDIO_VIEW;
248
+ /**
249
+ * 已解析 URL 缓存(逻辑资源 → URL):常驻曲目复用解析结果,会话结束统一 release。
250
+ * 不做引用计数/中途回收——VN 的资源集合有界,改用 LRU + refcount 的前提是长会话大量换曲。
251
+ */
252
+ const urls = createResourceUrlCache((resource) =>
253
+ resources.resolve(resource),
254
+ );
255
+ /** 每通道动作代际:异步解析落地时若已被更新动作/停止取代,丢弃该次播放(防错播) */
256
+ const generations = new Map<AudioChannel, number>();
257
+
258
+ function invalidate(channel: AudioChannel): void {
259
+ generations.set(channel, (generations.get(channel) ?? 0) + 1);
260
+ }
261
+
262
+ async function resolveUrl(resource: string): Promise<string | null> {
263
+ try {
264
+ return await urls.resolve(resource);
265
+ } catch (e) {
266
+ options.onError?.(`资源解析失败:${resource}(${String(e)})`);
267
+ return null; // fail-closed:不播放(诊断已上报,不静默)
268
+ }
269
+ }
270
+
271
+ async function playAction(action: PlayAction): Promise<void> {
272
+ // se 为一次性触发:每次独立播放,不参与代际取消(允许叠放)
273
+ const guarded = action.channel !== "se";
274
+ if (guarded) invalidate(action.channel);
275
+ const generation = generations.get(action.channel);
276
+ const url = await resolveUrl(action.resource);
277
+ if (url === null) return;
278
+ if (guarded && generations.get(action.channel) !== generation) return;
279
+ port.play(action.channel, url, {
280
+ volume: action.volume,
281
+ loop: action.loop,
282
+ position: action.position,
283
+ fadeMs: action.fadeMs,
284
+ restart: action.restart,
285
+ });
286
+ }
287
+
288
+ function apply(actions: AudioAction[]): void {
289
+ for (const action of actions) {
290
+ if (action.type === "stop") {
291
+ invalidate(action.channel); // 停止使在途解析作废
292
+ port.stop(action.channel, action.fadeMs);
293
+ continue;
294
+ }
295
+ void playAction(action);
296
+ }
297
+ }
298
+
299
+ function sync(): void {
300
+ const next = readAudioView(engine, options.preferences);
301
+ apply(planAudioActions(view, next));
302
+ view = next;
303
+ }
304
+
305
+ const offState = engine.onStateChanged((change) => {
306
+ if (audioKeys.has(change.key)) sync();
307
+ });
308
+ // 偏好变化(滑块/静音)→ 合成音量差量 → play 更新动作(同资源不重播)
309
+ const offPrefs = options.preferences?.onChange(() => sync()) ?? null;
310
+ sync();
311
+
312
+ return {
313
+ sync,
314
+ pollPosition(): void {
315
+ const bgm = reader.audioChannel("bgm");
316
+ if (bgm === null || bgm.kind !== "play") return;
317
+ const seconds = port.position("bgm");
318
+ if (seconds <= 0) return;
319
+ engine.reportMediaPosition(seconds);
320
+ // 同步视图:避免下一帧把自身回写当成 seek 目标
321
+ view = { ...view, bgmPosition: seconds };
322
+ },
323
+ dispose(): void {
324
+ offState();
325
+ offPrefs?.();
326
+ for (const url of urls.values()) resources.release(url);
327
+ urls.clear();
328
+ generations.clear();
329
+ },
330
+ };
331
+ }
@@ -0,0 +1,11 @@
1
+ /** 音频渲染域出口:状态差量规划器 + 渲染器(可测纯逻辑,播放归适配器)。 */
2
+ export {
3
+ EMPTY_AUDIO_VIEW,
4
+ createAudioRenderer,
5
+ planAudioActions,
6
+ readAudioView,
7
+ type AudioAction,
8
+ type AudioRenderer,
9
+ type AudioRendererOptions,
10
+ type AudioView,
11
+ } from "./audio";
@@ -0,0 +1,10 @@
1
+ /** 选择层挂载点出口(模板注册制)。 */
2
+ export {
3
+ builtinChoiceTemplate,
4
+ createChoiceTemplateRegistry,
5
+ type ChoiceTemplateFn,
6
+ type ChoiceTemplateInput,
7
+ type ChoiceTemplateOption,
8
+ type ChoiceTemplateRegistry,
9
+ type ChoiceTemplateView,
10
+ } from "./templates";
@@ -0,0 +1,74 @@
1
+ /**
2
+ * 选择层模板(挂载点模板的一例:提示行 + 选项列表 + rootClass 皮肤)。
3
+ *
4
+ * 骨架挂点(宿主渲染固定结构,模板只填内容):
5
+ * - 提示行(`promptHtml`;空串 = 隐藏该行)
6
+ * - 选项列表(`options`:每项文本与可选禁用态;**点击与目标解析归宿主**,
7
+ * 模板不参与交互语义——那是核心层的 `choose(target)`)
8
+ *
9
+ * 与 Ren'Py `choice` screen 的差别:它的 `items` 里带 `action` 对象(可执行副作用),
10
+ * 本模板只给「渲染所需的数据」,动作仍由宿主 `choose(target)` 走核心语义——
11
+ * 模板无法绕过引擎改变叙事流向,破坏面因此被限制在展示层。
12
+ *
13
+ * 未知名 / null 回退默认(模板只影响展示,缺失应兜底——与元素/小游戏注册表的
14
+ * fail-closed 口径不同)。
15
+ */
16
+ import {
17
+ TemplateRegistry,
18
+ createTemplateRegistry,
19
+ } from "../templates/registry";
20
+ import { renderDialogueLine } from "../dialogue/textView";
21
+
22
+ /** 单个选项的渲染投影(宿主从 `SYS.menuOptions` 映射) */
23
+ export interface ChoiceTemplateOption {
24
+ /** 选项文本(原文;经统一接缝渲染) */
25
+ text: string;
26
+ /** 选项目标列 id(宿主点击时交核心 `choose(target)`;模板不得改写) */
27
+ target: string;
28
+ }
29
+
30
+ /** 选择层模板输入:宿主投影的渲染状态 */
31
+ export interface ChoiceTemplateInput {
32
+ /** 插值后的菜单提示(空 = 无提示行) */
33
+ prompt: string;
34
+ /** 选项列表(顺序即呈现顺序) */
35
+ options: readonly ChoiceTemplateOption[];
36
+ /** 当前所属场景(可选;模板可用于分场景换装) */
37
+ scene?: string;
38
+ }
39
+
40
+ /** 选择层模板输出:语义骨架各挂点内容 */
41
+ export interface ChoiceTemplateView {
42
+ /** 选择层根皮肤类(宿主布局类叠加) */
43
+ rootClass: string;
44
+ /** 提示行 HTML(空串 = 隐藏);经统一接缝转义 */
45
+ promptHtml: string;
46
+ /** 选项行 HTML 列表(与 `options` 等长、同序——宿主按序挂点击) */
47
+ optionHtml: readonly string[];
48
+ }
49
+
50
+ /** 选择层模板:吃投影出的选项状态,吐骨架各挂点内容。纯函数——不挂点击、不改 `target` */
51
+ export type ChoiceTemplateFn = (
52
+ input: ChoiceTemplateInput,
53
+ ) => ChoiceTemplateView;
54
+
55
+ /** 选择层模板注册表:按名存 `ChoiceTemplateFn`,按名解析,未知名回退默认 */
56
+ export type ChoiceTemplateRegistry = TemplateRegistry<
57
+ ChoiceTemplateInput,
58
+ ChoiceTemplateView
59
+ >;
60
+
61
+ /** 造一张空的选择层模板注册表;宿主在装配期向它 `register` 模板(本函数不装内建默认) */
62
+ export function createChoiceTemplateRegistry(): ChoiceTemplateRegistry {
63
+ return createTemplateRegistry<ChoiceTemplateInput, ChoiceTemplateView>();
64
+ }
65
+
66
+ /** 内置默认模板:提示行 + 逐项转义文本(与既有参考实现等价) */
67
+ export const builtinChoiceTemplate: ChoiceTemplateFn = (input) => ({
68
+ rootClass: "tpl-choice",
69
+ promptHtml:
70
+ input.prompt === "" ? "" : renderDialogueLine({ text: input.prompt }).html,
71
+ optionHtml: input.options.map(
72
+ (opt) => renderDialogueLine({ text: opt.text }).html,
73
+ ),
74
+ });
@@ -0,0 +1,6 @@
1
+ /** 宿主命名命令域出口。 */
2
+ export {
3
+ createCommandRegistry,
4
+ type CommandRegistry,
5
+ type NamedCommandHandler,
6
+ } from "./registry";