@lubomirklimes/character-runtime 0.0.0-stage → 0.1.0-preview.1

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 (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/dist/acs/acs15.d.ts +9 -0
  4. package/dist/acs/acs15.js +382 -0
  5. package/dist/acs/acs2-reader.d.ts +2 -0
  6. package/dist/acs/acs2-reader.js +277 -0
  7. package/dist/acs/binary.d.ts +1 -0
  8. package/dist/acs/binary.js +107 -0
  9. package/dist/acs/compound-file.d.ts +1 -0
  10. package/dist/acs/compound-file.js +326 -0
  11. package/dist/acs/document.d.ts +33 -0
  12. package/dist/acs/document.js +99 -0
  13. package/dist/acs/errors.d.ts +28 -0
  14. package/dist/acs/errors.js +41 -0
  15. package/dist/acs/image.d.ts +30 -0
  16. package/dist/acs/image.js +113 -0
  17. package/dist/acs/index.d.ts +11 -0
  18. package/dist/acs/index.js +10 -0
  19. package/dist/acs/lz.d.ts +7 -0
  20. package/dist/acs/lz.js +102 -0
  21. package/dist/acs/metadata.d.ts +14 -0
  22. package/dist/acs/metadata.js +126 -0
  23. package/dist/acs/model.d.ts +130 -0
  24. package/dist/acs/model.js +12 -0
  25. package/dist/acs/mouth.d.ts +37 -0
  26. package/dist/acs/mouth.js +43 -0
  27. package/dist/acs/wave.d.ts +53 -0
  28. package/dist/acs/wave.js +422 -0
  29. package/dist/browser/animation-frame-clock.d.ts +18 -0
  30. package/dist/browser/animation-frame-clock.js +42 -0
  31. package/dist/browser/canvas-renderer.d.ts +50 -0
  32. package/dist/browser/canvas-renderer.js +145 -0
  33. package/dist/browser/host.d.ts +84 -0
  34. package/dist/browser/host.js +206 -0
  35. package/dist/browser/index.d.ts +6 -0
  36. package/dist/browser/index.js +8 -0
  37. package/dist/browser/web-audio.d.ts +48 -0
  38. package/dist/browser/web-audio.js +205 -0
  39. package/dist/browser/web-speech.d.ts +131 -0
  40. package/dist/browser/web-speech.js +302 -0
  41. package/dist/core/activities.d.ts +10 -0
  42. package/dist/core/activities.js +479 -0
  43. package/dist/core/agent.d.ts +263 -0
  44. package/dist/core/agent.js +764 -0
  45. package/dist/core/audio.d.ts +17 -0
  46. package/dist/core/audio.js +174 -0
  47. package/dist/core/balloon.d.ts +43 -0
  48. package/dist/core/balloon.js +94 -0
  49. package/dist/core/clock.d.ts +32 -0
  50. package/dist/core/clock.js +51 -0
  51. package/dist/core/compositor.d.ts +22 -0
  52. package/dist/core/compositor.js +67 -0
  53. package/dist/core/events.d.ts +131 -0
  54. package/dist/core/events.js +1 -0
  55. package/dist/core/host.d.ts +29 -0
  56. package/dist/core/host.js +77 -0
  57. package/dist/core/index.d.ts +16 -0
  58. package/dist/core/index.js +13 -0
  59. package/dist/core/lipsync.d.ts +41 -0
  60. package/dist/core/lipsync.js +209 -0
  61. package/dist/core/random.d.ts +52 -0
  62. package/dist/core/random.js +105 -0
  63. package/dist/core/request.d.ts +68 -0
  64. package/dist/core/request.js +131 -0
  65. package/dist/core/resources.d.ts +70 -0
  66. package/dist/core/resources.js +243 -0
  67. package/dist/core/scheduler.d.ts +25 -0
  68. package/dist/core/scheduler.js +766 -0
  69. package/dist/core/source.d.ts +21 -0
  70. package/dist/core/source.js +54 -0
  71. package/dist/core/speech.d.ts +91 -0
  72. package/dist/core/speech.js +86 -0
  73. package/dist/core/text.d.ts +38 -0
  74. package/dist/core/text.js +97 -0
  75. package/dist/index.d.ts +2 -0
  76. package/dist/index.js +4 -0
  77. package/package.json +68 -4
@@ -0,0 +1,17 @@
1
+ import type { WaveAudio } from '../acs/wave.js';
2
+ /**
3
+ * A platform audio output (one voice): plays a clip from an offset and stops it (Runtime.md §9). Outputs are platform services; the
4
+ * runtime decides what is sent when.
5
+ */
6
+ export interface AudioOutput {
7
+ play(clip: WaveAudio, offsetMs: number): void;
8
+ stop(): void;
9
+ dispose(): void;
10
+ }
11
+ /** Sound budgets of one agent. */
12
+ export interface AudioLimits {
13
+ /** Sound clips kept, including sounds that could not be decoded (default 256). */
14
+ readonly maxSounds?: number;
15
+ /** Decoded sound bytes kept (default 64 MiB). */
16
+ readonly maxSoundBytes?: number;
17
+ }
@@ -0,0 +1,174 @@
1
+ import { CharacterRuntimeError } from '../acs/errors.js';
2
+ /** @internal An output that plays nothing (agents without audio still time their effects). */
3
+ export const NULL_OUTPUT = { play() { }, stop() { }, dispose() { } };
4
+ /** @internal One effect voice: the latest eligible cue of an advance, at most 250 ms late (Runtime.md §9). */
5
+ class EffectPlayer {
6
+ output;
7
+ soundOf;
8
+ clipOf;
9
+ owner = 0;
10
+ enabledValue = false;
11
+ silentReturn = false;
12
+ status = 'Muted';
13
+ constructor(output, soundOf, clipOf) {
14
+ this.output = output;
15
+ this.soundOf = soundOf;
16
+ this.clipOf = clipOf;
17
+ }
18
+ get enabled() {
19
+ return this.enabledValue;
20
+ }
21
+ set enabled(value) {
22
+ if (this.enabledValue === value)
23
+ return;
24
+ this.enabledValue = value;
25
+ if (!value) {
26
+ this.stop();
27
+ this.status = 'Muted';
28
+ }
29
+ else
30
+ this.status = 'Ready for sound effects.';
31
+ }
32
+ stop() {
33
+ try {
34
+ this.output.stop();
35
+ }
36
+ catch (e) {
37
+ this.status = 'Audio stop failed: ' + e.message;
38
+ }
39
+ this.owner = 0;
40
+ }
41
+ process(records, now) {
42
+ let latest = null, clip = null;
43
+ for (const e of records) {
44
+ if (e.kind === 'paused' || (e.kind === 'cancelled' && (e.requestId === this.owner || latest?.requestId === e.requestId))) {
45
+ this.stop();
46
+ latest = null;
47
+ clip = null;
48
+ }
49
+ if (e.kind === 'transition')
50
+ this.silentReturn = e.detail === 'interrupt-exit';
51
+ if (e.kind !== 'frame' || this.silentReturn)
52
+ continue;
53
+ const index = this.soundOf(e.animation, e.frame);
54
+ if (index < 0)
55
+ continue;
56
+ const sound = this.clipOf(index);
57
+ if (!sound) {
58
+ this.status = `Unsupported sound ${index}; skipped.`;
59
+ continue;
60
+ }
61
+ latest = e;
62
+ clip = sound;
63
+ }
64
+ if (!this.enabledValue || !latest || !clip)
65
+ return;
66
+ const late = Math.max(0, now - latest.timeMs);
67
+ if (late > 250 || late >= clip.durationMs) {
68
+ this.status = 'Skipped late sound cue.';
69
+ return;
70
+ }
71
+ try {
72
+ this.output.stop();
73
+ this.output.play(clip, late);
74
+ this.owner = latest.requestId;
75
+ this.status = `Effect of request #${this.owner}.`;
76
+ }
77
+ catch (e) {
78
+ this.status = 'Audio unavailable: ' + e.message;
79
+ this.owner = 0;
80
+ }
81
+ }
82
+ dispose() {
83
+ this.stop();
84
+ try {
85
+ this.output.dispose();
86
+ }
87
+ catch {
88
+ // Disposal problems of a platform output are not runtime errors.
89
+ }
90
+ }
91
+ }
92
+ /** @internal Sound effects of one agent: a bounded clip cache, nominal effect durations and one effect voice. */
93
+ export class AgentAudio {
94
+ source;
95
+ createOutput;
96
+ clips = new Map();
97
+ bytes = 0;
98
+ enabledValue;
99
+ player = null;
100
+ maxSounds;
101
+ maxSoundBytes;
102
+ constructor(source, createOutput, enabled, limits = {}) {
103
+ this.source = source;
104
+ this.createOutput = createOutput;
105
+ this.enabledValue = enabled;
106
+ this.maxSounds = limits.maxSounds ?? 256;
107
+ this.maxSoundBytes = limits.maxSoundBytes ?? 64 * 1024 * 1024;
108
+ }
109
+ get enabled() {
110
+ return this.enabledValue;
111
+ }
112
+ set enabled(value) {
113
+ this.enabledValue = value;
114
+ if (this.player)
115
+ this.player.enabled = value;
116
+ }
117
+ get status() {
118
+ return this.player?.status ?? 'Muted';
119
+ }
120
+ /** Bytes of the prepared clips. */
121
+ get cachedBytes() {
122
+ return this.bytes;
123
+ }
124
+ ensurePlayer() {
125
+ this.player ??= new EffectPlayer(this.createOutput(), (a, f) => this.source.character.animations[a]?.frames[f]?.sound ?? -1, (i) => this.clips.get(i) ?? null);
126
+ this.player.enabled = this.enabledValue;
127
+ return this.player;
128
+ }
129
+ process(records, now) {
130
+ if (this.enabledValue)
131
+ this.ensurePlayer();
132
+ this.player?.process(records, now);
133
+ }
134
+ /** Nominal duration of the effect a frame starts (0 when effects are off or the clip cannot be decoded). */
135
+ effectDuration(animation, frame) {
136
+ const index = this.source.character.animations[animation]?.frames[frame]?.sound ?? -1;
137
+ return this.enabledValue && index >= 0 ? this.clips.get(index)?.durationMs ?? 0 : 0;
138
+ }
139
+ /** Decodes the not yet prepared sounds of `animation` within the budgets (undecodable sounds are recorded as such). */
140
+ prepare(animation) {
141
+ const needed = new Set();
142
+ for (const f of this.source.character.animations[animation]?.frames ?? [])
143
+ if (f.sound >= 0)
144
+ needed.add(f.sound);
145
+ for (const index of needed) {
146
+ if (this.clips.has(index))
147
+ continue;
148
+ if (this.clips.size >= this.maxSounds)
149
+ break;
150
+ let clip = null;
151
+ try {
152
+ clip = this.source.document.readSound(index);
153
+ if (clip.byteLength + this.bytes > this.maxSoundBytes)
154
+ clip = null;
155
+ }
156
+ catch (e) {
157
+ if (!(e instanceof CharacterRuntimeError))
158
+ throw e;
159
+ }
160
+ this.clips.set(index, clip);
161
+ this.bytes += clip?.byteLength ?? 0;
162
+ }
163
+ }
164
+ /** Stops the effect voice. */
165
+ stop() {
166
+ this.player?.stop();
167
+ }
168
+ dispose() {
169
+ this.player?.dispose();
170
+ this.player = null;
171
+ this.clips.clear();
172
+ this.bytes = 0;
173
+ }
174
+ }
@@ -0,0 +1,43 @@
1
+ import type { BalloonMetadata } from '../acs/model.js';
2
+ export type BalloonKind = 'speech' | 'thought';
3
+ /** A point in logical surface units. */
4
+ export interface Point {
5
+ readonly x: number;
6
+ readonly y: number;
7
+ }
8
+ /** Presentation settings of a balloon (colors are COLORREF words 0x00BBGGRR; font height LOGFONT-style, negative = pixel height). */
9
+ export interface BalloonStyle {
10
+ readonly foreColor: number;
11
+ readonly backColor: number;
12
+ readonly borderColor: number;
13
+ readonly fontName: string;
14
+ readonly fontHeight: number;
15
+ readonly fontWeight: number;
16
+ readonly lines: number;
17
+ readonly charsPerLine: number;
18
+ readonly sizeToText: boolean;
19
+ readonly autoHide: boolean;
20
+ readonly autoPace: boolean;
21
+ }
22
+ /** The default style for characters without a balloon block: black on light yellow, Tahoma 13, 2 lines × 32 characters. */
23
+ export declare const DEFAULT_BALLOON_STYLE: BalloonStyle;
24
+ /** The balloon style of a character from its balloon block and Style bits (Runtime.md §14.2). */
25
+ export declare function balloonStyleFor(style: number, balloon: BalloonMetadata | null): BalloonStyle;
26
+ /**
27
+ * The logical state of a word balloon (no rendering). `lines` are the wrapped lines of the whole text; `visibleLines` is the window of
28
+ * at most `style.lines` lines that contains the revealed text. Hosts draw it near `anchor` (the top centre of the character).
29
+ */
30
+ export interface BalloonState {
31
+ readonly requestId: number;
32
+ readonly kind: BalloonKind;
33
+ readonly text: string;
34
+ readonly revealedLength: number;
35
+ readonly visible: boolean;
36
+ readonly complete: boolean;
37
+ readonly style: BalloonStyle;
38
+ readonly lines: readonly string[];
39
+ readonly visibleLines: readonly string[];
40
+ readonly anchor: Point;
41
+ }
42
+ /** The state of a hidden balloon. */
43
+ export declare const HIDDEN_BALLOON: BalloonState;
@@ -0,0 +1,94 @@
1
+ import { CharacterStyle } from '../acs/model.js';
2
+ import { wrapText } from './text.js';
3
+ /** The default style for characters without a balloon block: black on light yellow, Tahoma 13, 2 lines × 32 characters. */
4
+ export const DEFAULT_BALLOON_STYLE = {
5
+ foreColor: 0x000000, backColor: 0xe1ffff, borderColor: 0x000000, fontName: 'Tahoma', fontHeight: -13, fontWeight: 400, lines: 2, charsPerLine: 32,
6
+ sizeToText: false, autoHide: true, autoPace: true,
7
+ };
8
+ /** The balloon style of a character from its balloon block and Style bits (Runtime.md §14.2). */
9
+ export function balloonStyleFor(style, balloon) {
10
+ let b = DEFAULT_BALLOON_STYLE;
11
+ if (balloon) {
12
+ b = {
13
+ ...b, foreColor: balloon.foreColor & 0xffffff, backColor: balloon.backColor & 0xffffff, borderColor: balloon.borderColor & 0xffffff,
14
+ fontName: balloon.fontName.length > 0 ? balloon.fontName : b.fontName, fontHeight: balloon.fontHeight !== 0 ? balloon.fontHeight : b.fontHeight,
15
+ fontWeight: balloon.fontWeight !== 0 ? balloon.fontWeight : b.fontWeight, lines: balloon.lines > 0 ? balloon.lines : b.lines,
16
+ charsPerLine: balloon.charsPerLine > 0 ? balloon.charsPerLine : b.charsPerLine,
17
+ };
18
+ }
19
+ return { ...b, sizeToText: (style & CharacterStyle.sizeToText) !== 0, autoHide: (style & CharacterStyle.noAutoHide) === 0, autoPace: (style & CharacterStyle.noAutoPace) === 0 };
20
+ }
21
+ /** The state of a hidden balloon. */
22
+ export const HIDDEN_BALLOON = {
23
+ requestId: 0, kind: 'speech', text: '', revealedLength: 0, visible: false, complete: true, style: DEFAULT_BALLOON_STYLE, lines: [], visibleLines: [],
24
+ anchor: { x: 0, y: 0 },
25
+ };
26
+ /** @internal The balloon state machine of one agent. */
27
+ export class BalloonController {
28
+ emit;
29
+ current = HIDDEN_BALLOON;
30
+ layout = [];
31
+ hideAt = null;
32
+ constructor(emit) {
33
+ this.emit = emit;
34
+ }
35
+ get state() {
36
+ return this.current;
37
+ }
38
+ show(time, request, kind, text, style, anchor, revealAll) {
39
+ this.layout = wrapText(text, style.charsPerLine);
40
+ this.hideAt = null;
41
+ this.set(time, { requestId: request, kind, text, revealedLength: revealAll ? text.length : 0, visible: true, complete: false, style, lines: this.layout.map((l) => l.text), visibleLines: [], anchor });
42
+ }
43
+ /** Reveals the text up to `length` UTF-16 units (monotonic). */
44
+ reveal(time, request, length) {
45
+ const s = this.current;
46
+ if (!s.visible || s.requestId !== request)
47
+ return;
48
+ length = Math.min(Math.max(length, s.revealedLength), s.text.length);
49
+ if (length !== s.revealedLength)
50
+ this.set(time, { ...s, revealedLength: length });
51
+ }
52
+ finish(time, request, completed, hideDelay) {
53
+ const s = this.current;
54
+ if (!s.visible || s.requestId !== request)
55
+ return;
56
+ if (completed)
57
+ this.set(time, { ...s, revealedLength: s.text.length, complete: true });
58
+ if (!completed || this.current.style.autoHide)
59
+ this.hideAt = completed ? time + hideDelay : time;
60
+ if (this.hideAt !== null && this.hideAt <= time)
61
+ this.hide(time);
62
+ }
63
+ move(anchor) {
64
+ const s = this.current;
65
+ if (s.visible && (s.anchor.x !== anchor.x || s.anchor.y !== anchor.y))
66
+ this.current = { ...s, anchor };
67
+ }
68
+ tick(now) {
69
+ if (this.hideAt !== null && this.hideAt <= now)
70
+ this.hide(this.hideAt);
71
+ }
72
+ shift(delta) {
73
+ if (this.hideAt !== null)
74
+ this.hideAt += delta;
75
+ }
76
+ hide(time) {
77
+ this.hideAt = null;
78
+ if (this.current.visible)
79
+ this.set(time, { ...HIDDEN_BALLOON, style: this.current.style });
80
+ }
81
+ set(time, next) {
82
+ if (next.visible) {
83
+ // The visible window: the last `lines` lines that contain revealed text (the balloon scrolls with the speech).
84
+ let revealedLine = 0;
85
+ for (let i = 0; i < this.layout.length; i++)
86
+ if (this.layout[i].start < Math.max(1, next.revealedLength))
87
+ revealedLine = i;
88
+ const lines = Math.max(1, next.style.lines), first = Math.max(0, revealedLine - lines + 1);
89
+ next = { ...next, visibleLines: this.layout.slice(first, first + lines).map((l) => l.text) };
90
+ }
91
+ this.current = next;
92
+ this.emit(time, next);
93
+ }
94
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * A runtime clock: monotonic milliseconds as a finite, non-negative number (Runtime.md §2). The runtime never starts timers; a host
3
+ * reads time from a clock and advances agents with it.
4
+ */
5
+ export interface Clock {
6
+ readonly nowMs: number;
7
+ }
8
+ /** A clock that moves only when told to (tests, deterministic hosts, offline rendering). */
9
+ export declare class ManualClock implements Clock {
10
+ private now;
11
+ constructor(start?: number);
12
+ get nowMs(): number;
13
+ /** Moves the clock forward by `ms` (≥ 0) and returns the new time. */
14
+ advance(ms: number): number;
15
+ /** Sets the clock to `time`, which must not be earlier than the current time. */
16
+ set(time: number): void;
17
+ }
18
+ /**
19
+ * The platform's monotonic counter (`performance.now()`), starting at 0 when created. Each read is the difference since creation, so
20
+ * no error accumulates.
21
+ */
22
+ export declare class SystemClock implements Clock {
23
+ private readonly start;
24
+ private last;
25
+ get nowMs(): number;
26
+ }
27
+ /** A clock read through a host function, which must be monotonic. */
28
+ export declare class DelegateClock implements Clock {
29
+ private readonly read;
30
+ constructor(read: () => number);
31
+ get nowMs(): number;
32
+ }
@@ -0,0 +1,51 @@
1
+ function check(t) {
2
+ if (!Number.isFinite(t) || t < 0)
3
+ throw new RangeError('Clock times are finite and non-negative.');
4
+ return t;
5
+ }
6
+ /** A clock that moves only when told to (tests, deterministic hosts, offline rendering). */
7
+ export class ManualClock {
8
+ now;
9
+ constructor(start = 0) {
10
+ this.now = check(start);
11
+ }
12
+ get nowMs() {
13
+ return this.now;
14
+ }
15
+ /** Moves the clock forward by `ms` (≥ 0) and returns the new time. */
16
+ advance(ms) {
17
+ if (!Number.isFinite(ms) || ms < 0)
18
+ throw new RangeError('A clock advances by a finite, non-negative amount.');
19
+ return (this.now = check(this.now + ms));
20
+ }
21
+ /** Sets the clock to `time`, which must not be earlier than the current time. */
22
+ set(time) {
23
+ if (check(time) < this.now)
24
+ throw new RangeError('The clock is monotonic.');
25
+ this.now = time;
26
+ }
27
+ }
28
+ /**
29
+ * The platform's monotonic counter (`performance.now()`), starting at 0 when created. Each read is the difference since creation, so
30
+ * no error accumulates.
31
+ */
32
+ export class SystemClock {
33
+ start = performance.now();
34
+ last = 0;
35
+ get nowMs() {
36
+ const t = performance.now() - this.start;
37
+ if (t > this.last)
38
+ this.last = t;
39
+ return this.last;
40
+ }
41
+ }
42
+ /** A clock read through a host function, which must be monotonic. */
43
+ export class DelegateClock {
44
+ read;
45
+ constructor(read) {
46
+ this.read = read;
47
+ }
48
+ get nowMs() {
49
+ return this.read();
50
+ }
51
+ }
@@ -0,0 +1,22 @@
1
+ import type { IndexedImage, RgbaImage } from '../acs/image.js';
2
+ /** One indexed image placed at a frame offset. */
3
+ export interface IndexedLayer {
4
+ readonly image: IndexedImage;
5
+ readonly x: number;
6
+ readonly y: number;
7
+ }
8
+ /**
9
+ * Paints indexed layers in the given order (the first is drawn first): color-key pixels are skipped, every other pixel is written as its
10
+ * opaque palette color. Layers are clipped to the canvas.
11
+ */
12
+ export declare function composeIndexed(width: number, height: number, layers: readonly IndexedLayer[], palette: Uint32Array, transparent: number): RgbaImage;
13
+ /**
14
+ * Composes one frame (Runtime.md §8): layers are painted from the last listed to the first, so layer 0 is in front; painting stops at the
15
+ * first undecodable layer (null) met from the back.
16
+ */
17
+ export declare function composeFrame(width: number, height: number, layers: readonly (IndexedLayer | null)[], palette: Uint32Array, transparent: number): RgbaImage;
18
+ /**
19
+ * Composes a frame with a mouth overlay: frame layers in native order, Replace omits layer 0, the overlay is painted last; painting
20
+ * stops at the first undecodable entry.
21
+ */
22
+ export declare function composeMouthFrame(width: number, height: number, layers: readonly (IndexedLayer | null)[], overlay: IndexedLayer | null, replaceBody: boolean, palette: Uint32Array, transparent: number): RgbaImage;
@@ -0,0 +1,67 @@
1
+ import { InvalidArgumentError } from '../acs/errors.js';
2
+ import { MAX_BITMAP_BYTES } from '../acs/image.js';
3
+ const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
4
+ /**
5
+ * Paints indexed layers in the given order (the first is drawn first): color-key pixels are skipped, every other pixel is written as its
6
+ * opaque palette color. Layers are clipped to the canvas.
7
+ */
8
+ export function composeIndexed(width, height, layers, palette, transparent) {
9
+ if (width < 1 || height < 1 || width * height * 4 > MAX_BITMAP_BYTES)
10
+ throw new InvalidArgumentError('Canvas exceeds dimension/byte policy.');
11
+ const pixels = new Uint8ClampedArray(width * height * 4);
12
+ const colors = new Uint32Array(256);
13
+ for (let i = 0; i < 256; i++) {
14
+ const c = i < palette.length ? palette[i] : 0;
15
+ const r = (c >>> 16) & 0xff, g = (c >>> 8) & 0xff, b = c & 0xff;
16
+ colors[i] = LITTLE_ENDIAN ? ((0xff << 24) | (b << 16) | (g << 8) | r) >>> 0 : ((r << 24) | (g << 16) | (b << 8) | 0xff) >>> 0;
17
+ }
18
+ const target = new Uint32Array(pixels.buffer);
19
+ for (const layer of layers) {
20
+ const { image } = layer, source = image.indices, stride = image.stride;
21
+ const left = Math.max(0, layer.x), top = Math.max(0, layer.y);
22
+ const right = Math.min(width, layer.x + image.width), bottom = Math.min(height, layer.y + image.height);
23
+ for (let y = top; y < bottom; y++) {
24
+ const row = (image.height - 1 - (y - layer.y)) * stride - layer.x;
25
+ const d = y * width;
26
+ for (let x = left; x < right; x++) {
27
+ const index = source[row + x];
28
+ if (index !== transparent)
29
+ target[d + x] = colors[index];
30
+ }
31
+ }
32
+ }
33
+ return { width, height, pixels };
34
+ }
35
+ /**
36
+ * Composes one frame (Runtime.md §8): layers are painted from the last listed to the first, so layer 0 is in front; painting stops at the
37
+ * first undecodable layer (null) met from the back.
38
+ */
39
+ export function composeFrame(width, height, layers, palette, transparent) {
40
+ const ordered = [];
41
+ for (let i = layers.length - 1; i >= 0; i--) {
42
+ const layer = layers[i];
43
+ if (!layer)
44
+ break;
45
+ ordered.push(layer);
46
+ }
47
+ return composeIndexed(width, height, ordered, palette, transparent);
48
+ }
49
+ /**
50
+ * Composes a frame with a mouth overlay: frame layers in native order, Replace omits layer 0, the overlay is painted last; painting
51
+ * stops at the first undecodable entry.
52
+ */
53
+ export function composeMouthFrame(width, height, layers, overlay, replaceBody, palette, transparent) {
54
+ if (layers.length === 0)
55
+ throw new InvalidArgumentError('A mouth overlay needs at least one frame layer.');
56
+ const sequence = [];
57
+ for (let i = layers.length - 1; i >= (replaceBody ? 1 : 0); i--)
58
+ sequence.push(layers[i] ?? null);
59
+ sequence.push(overlay);
60
+ const ordered = [];
61
+ for (const layer of sequence) {
62
+ if (!layer)
63
+ break;
64
+ ordered.push(layer);
65
+ }
66
+ return composeIndexed(width, height, ordered, palette, transparent);
67
+ }
@@ -0,0 +1,131 @@
1
+ import type { BalloonState, Point } from './balloon.js';
2
+ import type { LipSyncSource } from './lipsync.js';
3
+ import type { RequestEndReason, RequestKind } from './scheduler.js';
4
+ /** Visibility states (Runtime.md §10). */
5
+ export type AgentVisibility = 'hidden' | 'showing' | 'visible' | 'hiding';
6
+ /** Why an animation segment begins (Runtime.md §18). */
7
+ export type AnimationCause = 'animation' | 'named-return' | 'interrupt-exit' | 'exit-return' | 'release-exit';
8
+ interface EventBase {
9
+ /** Logical time in milliseconds. */
10
+ readonly timeMs: number;
11
+ /** The id of the agent that raised the event. */
12
+ readonly agentId: number;
13
+ }
14
+ /** The typed runtime events (Runtime.md §18; canonical form Conformance.md §6.3). */
15
+ export type AgentEvent = EventBase & ({
16
+ readonly type: 'request-queued';
17
+ readonly requestId: number;
18
+ readonly kind: RequestKind;
19
+ readonly name: string;
20
+ } | {
21
+ readonly type: 'request-started';
22
+ readonly requestId: number;
23
+ readonly kind: RequestKind;
24
+ readonly name: string;
25
+ readonly animation: number;
26
+ } | {
27
+ readonly type: 'request-completed';
28
+ readonly requestId: number;
29
+ readonly kind: RequestKind;
30
+ readonly name: string;
31
+ } | {
32
+ readonly type: 'request-cancelled';
33
+ readonly requestId: number;
34
+ readonly kind: RequestKind;
35
+ readonly name: string;
36
+ readonly reason: RequestEndReason;
37
+ } | {
38
+ readonly type: 'request-failed';
39
+ readonly requestId: number;
40
+ readonly kind: RequestKind;
41
+ readonly name: string;
42
+ readonly code: string;
43
+ readonly detail: string;
44
+ } | {
45
+ readonly type: 'animation-started';
46
+ readonly requestId: number;
47
+ readonly animation: number;
48
+ readonly animationName: string;
49
+ readonly frame: number;
50
+ readonly cause: AnimationCause;
51
+ } | {
52
+ readonly type: 'frame';
53
+ readonly requestId: number;
54
+ readonly animation: number;
55
+ readonly frame: number;
56
+ readonly isReturn: boolean;
57
+ readonly resting: boolean;
58
+ } | {
59
+ readonly type: 'sound-cue';
60
+ readonly requestId: number;
61
+ readonly animation: number;
62
+ readonly frame: number;
63
+ readonly sound: number;
64
+ } | {
65
+ readonly type: 'state-requested';
66
+ readonly requestId: number;
67
+ readonly state: string;
68
+ } | {
69
+ readonly type: 'paused';
70
+ } | {
71
+ readonly type: 'resumed';
72
+ } | {
73
+ readonly type: 'visibility';
74
+ readonly visibility: AgentVisibility;
75
+ } | {
76
+ readonly type: 'idle-level';
77
+ readonly level: number;
78
+ } | {
79
+ readonly type: 'move-started';
80
+ readonly requestId: number;
81
+ readonly from: Point;
82
+ readonly to: Point;
83
+ readonly durationMs: number;
84
+ } | {
85
+ readonly type: 'move-ended';
86
+ readonly requestId: number;
87
+ readonly position: Point;
88
+ readonly completed: boolean;
89
+ } | {
90
+ readonly type: 'position';
91
+ readonly position: Point;
92
+ } | {
93
+ readonly type: 'scale';
94
+ readonly scale: number;
95
+ } | {
96
+ readonly type: 'speech-started';
97
+ readonly requestId: number;
98
+ readonly text: string;
99
+ readonly voice: string | null;
100
+ readonly lipSync: LipSyncSource;
101
+ readonly durationMs: number;
102
+ readonly note: string;
103
+ } | {
104
+ readonly type: 'speech-word';
105
+ readonly requestId: number;
106
+ readonly word: number;
107
+ readonly textStart: number;
108
+ readonly textLength: number;
109
+ } | {
110
+ readonly type: 'speech-ended';
111
+ readonly requestId: number;
112
+ readonly completed: boolean;
113
+ } | {
114
+ readonly type: 'mouth';
115
+ readonly requestId: number;
116
+ readonly shape: number | null;
117
+ } | {
118
+ readonly type: 'balloon';
119
+ readonly balloon: BalloonState;
120
+ } | {
121
+ readonly type: 'runtime-error';
122
+ readonly source: 'speech' | 'speech-audio' | 'exit-cycle' | 'return-skipped';
123
+ readonly message: string;
124
+ });
125
+ /** The event types. */
126
+ export type AgentEventType = AgentEvent['type'];
127
+ /** Distributes an event union member over its type. */
128
+ export type AgentEventOf<T extends AgentEventType> = Extract<AgentEvent, {
129
+ type: T;
130
+ }>;
131
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,29 @@
1
+ import { CharacterAgent, type AgentOptions } from './agent.js';
2
+ import { type Clock } from './clock.js';
3
+ import type { AgentEvent } from './events.js';
4
+ import { CharacterSource, type CharacterInput } from './source.js';
5
+ /**
6
+ * Several independent agents on one clock, advanced in the order they were added (Runtime.md §17). The host shares only time and the
7
+ * update order, which makes cross-agent waits deterministic.
8
+ */
9
+ export declare class AgentHost {
10
+ private readonly list;
11
+ private disposed;
12
+ readonly clock: Clock;
13
+ constructor(clock?: Clock);
14
+ get agents(): readonly CharacterAgent[];
15
+ /** Creates an agent for a source on this host's clock and adds it. */
16
+ create(source: CharacterSource, options?: Omit<AgentOptions, 'clock'>): CharacterAgent;
17
+ /** Loads a character (URL, Blob/File, ArrayBuffer or typed array) and adds an agent for it. */
18
+ load(input: CharacterInput, options?: Omit<AgentOptions, 'clock'>): Promise<CharacterAgent>;
19
+ /** Adds an agent created on this host's clock (advanced after the agents added before it). */
20
+ add(agent: CharacterAgent): CharacterAgent;
21
+ /** Removes and disposes one agent (its requests are cancelled, which releases waits of other agents on them). */
22
+ unload(agent: CharacterAgent): boolean;
23
+ /** Advances every agent to `now` (default: the clock), in the order added, and returns all their events. */
24
+ advance(now?: number): AgentEvent[];
25
+ /** With a manual clock: advances in steps until `done()` holds or `maxMs` passed. */
26
+ runUntil(done: () => boolean, stepMs?: number, maxMs?: number): void;
27
+ /** Disposes every agent; every request handle completes. */
28
+ dispose(): void;
29
+ }