@lingfan-engine/ui 0.1.5 → 0.3.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.
@@ -0,0 +1,61 @@
1
+ /**
2
+ * 挂载选择:把「可见集合」和「名字 → 组件」表合成一份可直接渲染的清单。
3
+ *
4
+ * 三种宿主形态的模板各写一遍「按名字取组件、取不到就跳过」的后果不是代码重复,
5
+ * 而是同一份存档在三种宿主上挂出不同的组件集合——取不到时一种静默跳过、另一种抛错,
6
+ * 排查起来就是三套现象。选择逻辑收在这里,模板只负责把清单铺到自己的渲染树上。
7
+ *
8
+ * 取不到组件一律 fail-closed:**不渲染**那一条,并**逐条上报**名字。
9
+ * 静默跳过是这里最坏的选项——作者写了 `mount hub true` 却没看见组件,无从下手;
10
+ * 抛错则会让一个笔误黑掉整屏。上报走注入的回调,宿主决定写错误条还是打控制台。
11
+ */
12
+ import { isMountTable } from "@lingfan-engine/core";
13
+ import { mountProps, visibleMounts } from "./projection.ts";
14
+
15
+ /** 一条可渲染的挂载:名字、组件本身、完整入参 */
16
+ export interface MountSelection {
17
+ /** UI 名(= `src/ui/` 下的目录名,也是 `SYS.mounts` 的键) */
18
+ readonly name: string;
19
+ /** 组件:Vue / React 形态是组件对象,原生形态是工厂函数;本域不解释它 */
20
+ readonly component: unknown;
21
+ /** 该 UI 这一帧的完整入参(不可见时不会有这一条) */
22
+ readonly props: Readonly<Record<string, unknown>>;
23
+ }
24
+
25
+ /**
26
+ * 算出这一帧该渲染哪些 UI。
27
+ *
28
+ * @param raw `SYS.mounts` 的原始值(脏值按空表,不抛)
29
+ * @param table 「名字 → 组件」表(生成物 `uis`)
30
+ * @param onMissing 取不到组件时的上报口;缺省只静默跳过(不建议——见文件头)
31
+ */
32
+ export function selectMounts(
33
+ raw: unknown,
34
+ table: Readonly<Record<string, unknown>>,
35
+ onMissing?: (name: string) => void,
36
+ ): readonly MountSelection[] {
37
+ const out: MountSelection[] = [];
38
+ for (const name of visibleMounts(raw)) {
39
+ const component = table[name];
40
+ if (component === undefined) {
41
+ onMissing?.(name);
42
+ continue;
43
+ }
44
+ out.push({ name, component, props: mountProps(raw, name) ?? {} });
45
+ }
46
+ return out;
47
+ }
48
+
49
+ /**
50
+ * 表里没有这个名字的可见 UI 名单(宿主用它做一次性诊断,避免每帧重复上报)。
51
+ *
52
+ * `selectMounts` 的 `onMissing` 是逐帧回调,命令式宿主适合直接接;
53
+ * 声明式宿主按帧重渲染,重复上报会刷屏——用它算「稳定差集」再自己决定上报时机。
54
+ */
55
+ export function missingMounts(
56
+ raw: unknown,
57
+ table: Readonly<Record<string, unknown>>,
58
+ ): readonly string[] {
59
+ if (!isMountTable(raw)) return [];
60
+ return visibleMounts(raw).filter((name) => table[name] === undefined);
61
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * 挂载表订阅:把 `SYS.mounts` 的变化做成一个**宿主无关**的可订阅值。
3
+ *
4
+ * 三种宿主形态要的是同一件事——「现在该挂谁、各自带什么入参」,但拿值的方式不同:
5
+ * 命令式宿主(原生 DOM)要一个回调去算差量,声明式宿主(Vue / React)要一个能进各自
6
+ * 响应式系统的快照 + 订阅对。这里只提供最小面:`snapshot()` 读当前值、`subscribe()`
7
+ * 订阅变化、`set()` 由装配处把引擎状态推进来。
8
+ *
9
+ * 为什么不让各形态自己订阅引擎:订阅与退订就成了三份实现,任何一份漏掉退订都会在
10
+ * 页面拆掉之后继续往已销毁的渲染树里写。值在这里只有一条通路。
11
+ *
12
+ * 本文件不碰 DOM、不认识框架、没有模块级可变状态——一个 store 的全部状态都在闭包里。
13
+ */
14
+
15
+ /** 只读视图:声明式宿主拿它渲染,命令式宿主拿它算差量 */
16
+ export interface MountSource {
17
+ /** 当前 `SYS.mounts` 原始值;引擎还没写过时是 `undefined` */
18
+ snapshot(): unknown;
19
+ /** 订阅变化,返回退订函数。订阅时**不**立刻回调——调用方先自己读一次快照 */
20
+ subscribe(listener: (raw: unknown) => void): () => void;
21
+ }
22
+
23
+ /** 可写视图:只有装配处拿得到,写入口不在渲染器手里 */
24
+ export interface MountStore extends MountSource {
25
+ /** 写入新值;与当前值是同一个引用时不通知(引擎写侧本就是整表新建) */
26
+ set(raw: unknown): void;
27
+ }
28
+
29
+ /**
30
+ * 造一个挂载表 store。
31
+ *
32
+ * @param initial 初始值;缺省 `undefined` 即「引擎还没报过」,投影按空表处理
33
+ */
34
+ export function createMountStore(initial?: unknown): MountStore {
35
+ let current: unknown = initial;
36
+ const listeners = new Set<(raw: unknown) => void>();
37
+ return {
38
+ snapshot(): unknown {
39
+ return current;
40
+ },
41
+ set(raw: unknown): void {
42
+ if (Object.is(raw, current)) return;
43
+ current = raw;
44
+ // 复制一份再遍历:监听器里退订自己是常见写法,直接遍历 Set 会跳过后一个
45
+ for (const listener of [...listeners]) listener(current);
46
+ },
47
+ subscribe(listener: (raw: unknown) => void): () => void {
48
+ listeners.add(listener);
49
+ return (): void => {
50
+ listeners.delete(listener);
51
+ };
52
+ },
53
+ };
54
+ }
@@ -15,6 +15,8 @@ export interface ChoicesRenderInput {
15
15
  menuPrompt: string;
16
16
  menuOptions: readonly { text: string; target: string }[];
17
17
  inputPrompt: string;
18
+ /** 输入候选(缺省空数组 = 只有输入框) */
19
+ inputCandidates?: readonly { text: string; value: string }[];
18
20
  }
19
21
 
20
22
  /** 选择层文案(宿主可覆盖;缺省实现即内建文案) */
@@ -50,11 +52,20 @@ export function choicesLayerView(
50
52
  ): ChoicesLayerView | null {
51
53
  if (input.waiting === "input") {
52
54
  const texts: ChoicesTexts = { ...DEFAULT_CHOICES_TEXTS, ...deps.texts };
55
+ // 候选与输入框并存:玩家可以点候选,也可以自己打字(两者走同一个提交出口)
56
+ const candidates = (input.inputCandidates ?? []).map((item) => ({
57
+ label: item.text,
58
+ value: item.value,
59
+ }));
53
60
  return {
54
61
  rootClass: "",
55
62
  promptHtml: "",
56
63
  options: [],
57
- input: { prompt: input.inputPrompt, submitText: texts.inputSubmit },
64
+ input: {
65
+ prompt: input.inputPrompt,
66
+ submitText: texts.inputSubmit,
67
+ candidates,
68
+ },
58
69
  };
59
70
  }
60
71
  if (input.waiting !== "menu") return null;
@@ -29,7 +29,7 @@ import { isGameInputTarget } from "../input/scope";
29
29
  import { createElementRegistry } from "../element/registry";
30
30
  import type { ElementRegistry } from "../element/registry";
31
31
  import { registerBuiltinElementRenderers } from "../element";
32
- import { DEFAULT_NOTIFY_MS } from "../host/duration";
32
+ import { DEFAULT_NOTIFY_MS, DEFAULT_TEXT_CPS } from "../host/duration";
33
33
  import { choicesLayerView } from "./choices-view";
34
34
  import type { ChoicesViewDeps } from "./choices-view";
35
35
  import { dialogueLayerView } from "./dialogue-view";
@@ -72,7 +72,7 @@ export function createNarrativeOverlay(
72
72
  const reader = createStateReader(engine);
73
73
 
74
74
  const elements = options.elementRegistry ?? createBuiltinElementRegistry();
75
- const textSpeed = options.textSpeed ?? 30;
75
+ const textSpeed = options.textSpeed ?? DEFAULT_TEXT_CPS;
76
76
 
77
77
  const layerZController = createLayerZController(surface, layerZ);
78
78
  // 表面可能由宿主先建(那时还不知道本实例的层默认表):构造末尾统一下发一次,
@@ -138,6 +138,7 @@ export function createNarrativeOverlay(
138
138
  menuPrompt: s.menuPrompt,
139
139
  menuOptions: s.menuOptions,
140
140
  inputPrompt: s.inputPrompt,
141
+ inputCandidates: s.inputCandidates,
141
142
  },
142
143
  choicesDeps,
143
144
  ),
@@ -43,6 +43,8 @@ export interface RenderState {
43
43
  menuPrompt: string;
44
44
  menuOptions: Array<{ text: string; target: string }>;
45
45
  inputPrompt: string;
46
+ /** 输入候选(显示文本与要填的值成对;空数组 = 只有输入框) */
47
+ inputCandidates: Array<{ text: string; value: string }>;
46
48
  nvlMode: string;
47
49
  nvlBuffer: string[];
48
50
  elementList: ElementInstance[];
@@ -103,6 +105,7 @@ export function createProjector(deps: {
103
105
  menuPrompt: "",
104
106
  menuOptions: [],
105
107
  inputPrompt: "",
108
+ inputCandidates: [],
106
109
  nvlMode: "none",
107
110
  nvlBuffer: [],
108
111
  elementList: [],
@@ -190,6 +193,10 @@ export function createProjector(deps: {
190
193
  state.inputPrompt = reader.inputPrompt();
191
194
  return { kind: "render", targets: ["choices"] };
192
195
  }
196
+ if (key === SYS.inputOptions) {
197
+ state.inputCandidates = reader.inputCandidates();
198
+ return { kind: "render", targets: ["choices"] };
199
+ }
193
200
  if (key === SYS.nvlMode) {
194
201
  const next = reader.nvlMode();
195
202
  state.nvlMode = next === "" ? "none" : next;
@@ -218,6 +225,7 @@ export function createProjector(deps: {
218
225
  state.menuPrompt = reader.menuPrompt();
219
226
  readMenuOptions();
220
227
  state.inputPrompt = reader.inputPrompt();
228
+ state.inputCandidates = reader.inputCandidates();
221
229
  const mode = reader.nvlMode();
222
230
  state.nvlMode = mode === "" ? "none" : mode;
223
231
  state.nvlBuffer = reader.nvlLines();
@@ -62,6 +62,19 @@ export interface ChoicesLayerInput {
62
62
  prompt: string;
63
63
  /** 提交按钮显示文本 */
64
64
  submitText: string;
65
+ /**
66
+ * 候选快捷值(缺省空数组 = 只有输入框):点一项即把该项 `value` 当输入值提交,
67
+ * 输入框仍可用。`label` 是显示文本(可能已翻译),`value` 是要写进变量的原样值。
68
+ */
69
+ candidates: readonly ChoicesLayerCandidate[];
70
+ }
71
+
72
+ /** 输入候选(显示文本与要填的值成对;与菜单选项不同——它不跳列,只替玩家填值) */
73
+ export interface ChoicesLayerCandidate {
74
+ /** 显示文本(已走翻译;也用作按钮的可访问名) */
75
+ label: string;
76
+ /** 要填进变量的原样值(不进翻译表) */
77
+ value: string;
65
78
  }
66
79
 
67
80
  /**
@@ -0,0 +1,55 @@
1
+ /**
2
+ * 「继续」该读哪一个槽:从存档摘要里挑出最近写入的那一槽。
3
+ *
4
+ * 为什么需要这一层:槽位清单由工程配置决定(`shell.saves.slots` → `slot_1..slot_N`),
5
+ * 而「哪个槽最近存过」只有存档端口知道(`SavePort.list()`)。宿主入口要的是**一个槽名**
6
+ * 或**没有槽**这两件事,中间的挑选规则归这里,各形态共用。
7
+ *
8
+ * 三条口径:
9
+ * - **只认配置内的槽**:`list()` 可能返回历史遗留的槽名(改过槽位数的工程),
10
+ * 不在当前清单里的一律不选——跳到一个界面上根本看不见的槽是没法解释的行为。
11
+ * - **按写入时间取最大**:`timestamp` 是毫秒时间戳;相同时间取清单里靠前的那个,
12
+ * 保证同一份摘要集必得同一结果(否则「继续」会随机跳两个槽)。
13
+ * - **没有可用摘要 = 不可点**:空数组是合法返回值(不是错误),
14
+ * 调用方据此置 `disabled` 并显示一行提示,不静默。
15
+ */
16
+ import type { SlotSummary } from "@lingfan-engine/core";
17
+
18
+ /**
19
+ * 挑出「继续」该读的槽。
20
+ *
21
+ * @param summaries 存档端口的摘要表(`SavePort.list()` 的结果,可能是空数组)。
22
+ * @param slots 当前工程的槽名清单(`slotIds(resolveSavesConfig(manifest).slots)`)。
23
+ * @returns 最近写入且在当前清单内的那条摘要;没有则 `undefined`。
24
+ * @example
25
+ * latestSave([{ slot: "slot_1", saveCount: 2, timestamp: 100, mode: "portable" }], ["slot_1", "slot_2"]);
26
+ * // → slot_1 那条
27
+ */
28
+ export function latestSave(
29
+ summaries: readonly SlotSummary[],
30
+ slots: readonly string[],
31
+ ): SlotSummary | undefined {
32
+ const allowed = new Set(slots);
33
+ let best: SlotSummary | undefined;
34
+ for (const summary of summaries) {
35
+ if (!allowed.has(summary.slot)) continue;
36
+ if (best === undefined || summary.timestamp > best.timestamp)
37
+ best = summary;
38
+ }
39
+ return best;
40
+ }
41
+
42
+ /**
43
+ * 「继续」的可用状态:可读的槽名 + 要不要置灰。
44
+ *
45
+ * @param summaries 存档端口的摘要表。
46
+ * @param slots 当前工程的槽名清单。
47
+ * @returns `slot` 为 `undefined` 时按钮必须 `disabled`。
48
+ */
49
+ export function continueSlot(
50
+ summaries: readonly SlotSummary[],
51
+ slots: readonly string[],
52
+ ): { readonly slot: string | undefined } {
53
+ const found = latestSave(summaries, slots);
54
+ return { slot: found?.slot };
55
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * 存档域出口:只放「读存档摘要之后怎么用」的纯逻辑,不碰 `SavePort` 实现。
3
+ *
4
+ * 端口实现(localStorage / Rust 命令 / 别的)在各平台适配器里;这里回答的是
5
+ * 与平台无关的问题——「哪一槽是最近写入的、宿主入口该不该可点」。
6
+ */
7
+ export { continueSlot, latestSave } from "./continue.ts";
@@ -6,6 +6,7 @@
6
6
  * 性能:sync 仅由 `__video` 事件与显式调用触发(回溯/读档后对齐),非逐帧。
7
7
  */
8
8
  import type {
9
+ PlayerPreferences,
9
10
  ResourcePort,
10
11
  VideoCommand,
11
12
  VideoPort,
@@ -23,6 +24,11 @@ export interface VideoRendererOptions {
23
24
  onError?: (message: string) => void;
24
25
  /** cutscene 自然播放结束(引擎据此解除 video 等待) */
25
26
  onVideoFinished?: () => void;
27
+ /**
28
+ * 玩家偏好:视频音轨按 `bgm` 通道的偏好音量衰减(视频没有独立通道,
29
+ * 且音轨语义属「背景音」)。不传 = 不衰减,行为与未接偏好时一致。
30
+ */
31
+ preferences?: PlayerPreferences;
26
32
  }
27
33
 
28
34
  /**
@@ -63,6 +69,13 @@ export function createVideoRenderer(
63
69
  }
64
70
  }
65
71
 
72
+ /** 播放命令的生效音量:op 音量 × `bgm` 通道偏好(静音由 effectiveVolume 归零) */
73
+ function effectiveVolume(volume: number): number {
74
+ const pref = options.preferences?.effectiveVolume("bgm");
75
+ if (pref === undefined || pref === 1) return volume;
76
+ return Math.min(1, Math.max(0, volume * pref));
77
+ }
78
+
66
79
  function execute(command: VideoCommand): void {
67
80
  generation += 1;
68
81
  const gen = generation;
@@ -71,7 +84,7 @@ export function createVideoRenderer(
71
84
  if (url === null || generation !== gen) return; // 已被更新命令取代
72
85
  port.play(
73
86
  url,
74
- { volume: command.volume, loop: command.loop },
87
+ { volume: effectiveVolume(command.volume), loop: command.loop },
75
88
  command.cutscene ? () => options.onVideoFinished?.() : undefined,
76
89
  );
77
90
  });
@@ -109,12 +122,20 @@ export function createVideoRenderer(
109
122
  const off = engine.onStateChanged((change) => {
110
123
  if (change.key === SYS.video) sync();
111
124
  });
125
+ // 偏好变化:只调音量不重播(过场正在放时重播会把玩家看到的画面打断)
126
+ const offPrefs =
127
+ options.preferences?.onChange(() => {
128
+ const command = reader.videoCommand();
129
+ if (command === null || command.kind !== "play") return;
130
+ port.setVolume?.(effectiveVolume(command.volume));
131
+ }) ?? null;
112
132
  sync();
113
133
 
114
134
  return {
115
135
  sync,
116
136
  dispose(): void {
117
137
  off();
138
+ offPrefs?.();
118
139
  for (const url of urls.values()) resources.release(url);
119
140
  urls.clear();
120
141
  },
@@ -1,331 +0,0 @@
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
- }