phi-engine 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +60 -2
  2. package/audio/Audio.ts +3 -0
  3. package/audio/AudioService.ts +15 -0
  4. package/audio/SoundName.ts +1 -0
  5. package/audio/index.ts +3 -0
  6. package/game/Game.ts +3 -0
  7. package/game/GameService.ts +57 -0
  8. package/game/PauseReason.ts +6 -0
  9. package/game/Time.ts +3 -0
  10. package/game/TimeService.ts +17 -0
  11. package/game/index.ts +5 -0
  12. package/input/Input.ts +3 -0
  13. package/input/InputDevice.ts +2 -0
  14. package/input/InputService.ts +71 -0
  15. package/input/index.ts +3 -0
  16. package/math/Color.ts +46 -0
  17. package/math/Vector2.ts +59 -0
  18. package/math/Vector3.ts +63 -0
  19. package/math/index.ts +3 -0
  20. package/package.json +23 -4
  21. package/render/Camera.ts +3 -0
  22. package/render/CameraService.ts +19 -0
  23. package/render/PostProcess.ts +3 -0
  24. package/render/PostProcessService.ts +14 -0
  25. package/render/index.ts +4 -0
  26. package/runtime/EngineOutputBus.ts +17 -0
  27. package/runtime/EntityValues.ts +103 -0
  28. package/runtime/PhiRuntime.ts +517 -0
  29. package/runtime/UiBridge.ts +178 -0
  30. package/runtime/UiCommand.ts +14 -0
  31. package/runtime/UiEventWire.ts +6 -0
  32. package/runtime/ViewportWire.ts +6 -0
  33. package/runtime/interfaceBridge.ts +3 -0
  34. package/runtime/protocol.ts +5 -0
  35. package/runtime/runtime.ts +9 -0
  36. package/scene/Component.ts +108 -0
  37. package/scene/Entity.ts +118 -0
  38. package/scene/Mesh3D.ts +37 -0
  39. package/scene/PointLight.ts +15 -0
  40. package/scene/Scene.ts +3 -0
  41. package/scene/SceneAccessor.ts +45 -0
  42. package/scene/SceneService.ts +21 -0
  43. package/scene/Sprite2D.ts +20 -0
  44. package/scene/Transform2D.ts +43 -0
  45. package/scene/Transform3D.ts +56 -0
  46. package/scene/index.ts +16 -0
  47. package/scene/registerComponents.ts +6 -0
  48. package/ui/Align.ts +2 -0
  49. package/ui/Anchor.ts +11 -0
  50. package/ui/Bar.ts +100 -0
  51. package/ui/Button.ts +93 -0
  52. package/ui/Choice.ts +80 -0
  53. package/ui/Column.ts +10 -0
  54. package/ui/ComponentUi.ts +70 -0
  55. package/ui/Container.ts +39 -0
  56. package/ui/ContainerOptions.ts +18 -0
  57. package/ui/Control.ts +94 -0
  58. package/ui/Element.ts +64 -0
  59. package/ui/ElementKind.ts +12 -0
  60. package/ui/Group.ts +110 -0
  61. package/ui/Icon.ts +63 -0
  62. package/ui/IconShape.ts +1 -0
  63. package/ui/Layer.ts +105 -0
  64. package/ui/Row.ts +10 -0
  65. package/ui/Settings.ts +3 -0
  66. package/ui/SettingsService.ts +48 -0
  67. package/ui/Slider.ts +158 -0
  68. package/ui/Spacer.ts +46 -0
  69. package/ui/Text.ts +62 -0
  70. package/ui/TextSize.ts +5 -0
  71. package/ui/Theme.ts +3 -0
  72. package/ui/ThemeValues.ts +58 -0
  73. package/ui/Toggle.ts +46 -0
  74. package/ui/Viewport.ts +11 -0
  75. package/ui/WireValue.ts +5 -0
  76. package/ui/finiteColor.ts +11 -0
  77. package/ui/finiteNumber.ts +10 -0
  78. package/ui/index.ts +26 -0
  79. package/ui/wholeNumber.ts +12 -0
@@ -0,0 +1,517 @@
1
+ import { Mesh3D } from '../scene/Mesh3D';
2
+ import { PointLight } from '../scene/PointLight';
3
+ import { Sprite2D } from '../scene/Sprite2D';
4
+ import { Transform2D } from '../scene/Transform2D';
5
+ import { Transform3D } from '../scene/Transform3D';
6
+ import type { Component, ComponentClass, ComponentConstructor } from '../scene/Component';
7
+ import { Entity } from '../scene/Entity';
8
+ import type { EntityBlueprint, SceneAccessor } from '../scene/SceneAccessor';
9
+ import { EntityValues } from './EntityValues';
10
+ import { Color } from '../math/Color';
11
+ import type { EngineOutputBus } from './EngineOutputBus';
12
+ import type { SoundName } from '../audio/SoundName';
13
+ import type { InputSnapshotWire } from '../input/InputService';
14
+ import { Audio } from '../audio/Audio';
15
+ import { Camera } from '../render/Camera';
16
+ import { Input } from '../input/Input';
17
+ import { PostProcess } from '../render/PostProcess';
18
+ import { Game } from '../game/Game';
19
+ import { Scene } from '../scene/Scene';
20
+ import type { PauseReason } from '../game/PauseReason';
21
+ import { Time } from '../game/Time';
22
+ import { interfaceBridge } from './interfaceBridge';
23
+ import { Settings } from '../ui/Settings';
24
+ import type { ViewportWire } from './ViewportWire';
25
+ import type { UiEventWire } from './UiEventWire';
26
+
27
+ interface WireEntity {
28
+ id: number;
29
+ name: string | null;
30
+ tag: string | null;
31
+ transform2d?: {
32
+ x: number;
33
+ y: number;
34
+ rotation: number;
35
+ scale_x: number;
36
+ scale_y: number;
37
+ z: number;
38
+ };
39
+ sprite2d?: {
40
+ color: [number, number, number, number];
41
+ emissive: number;
42
+ shape: string;
43
+ visible: boolean;
44
+ };
45
+ transform3d?: {
46
+ x: number;
47
+ y: number;
48
+ z: number;
49
+ rot_x: number;
50
+ rot_y: number;
51
+ rot_z: number;
52
+ scale_x: number;
53
+ scale_y: number;
54
+ scale_z: number;
55
+ };
56
+ mesh3d?: {
57
+ shape: string;
58
+ albedo: [number, number, number, number];
59
+ metallic: number;
60
+ roughness: number;
61
+ emissive: [number, number, number, number];
62
+ emissive_strength: number;
63
+ visible: boolean;
64
+ };
65
+ point_light?: { color: [number, number, number, number]; intensity: number; radius: number };
66
+ scripts?: { component: string; props: Record<string, unknown> }[];
67
+ }
68
+
69
+ interface StepInputWire {
70
+ phase: 'fixed_update' | 'update' | 'end_scene';
71
+ dt: number;
72
+ fixed_dt: number;
73
+ elapsed: number;
74
+ frame: number;
75
+ paused: boolean;
76
+ pause_reason: PauseReason | null;
77
+ input: InputSnapshotWire;
78
+ viewport: ViewportWire;
79
+ /** The element events of this frame, in the update phase only. */
80
+ ui_events: UiEventWire[];
81
+ can_quit: boolean;
82
+ /** The current data of the entities that the scripts have not accepted, in ID order. */
83
+ new_entities: WireEntity[];
84
+ /** All the entities in the world. */
85
+ live_ids: number[];
86
+ last_step_failed: boolean;
87
+ }
88
+
89
+ interface OutCommand {
90
+ op: string;
91
+ [key: string]: unknown;
92
+ }
93
+
94
+ function serializeEntity(e: Entity): Record<string, unknown> {
95
+ const data: Record<string, unknown> = {};
96
+ if (e.hasTransform2d) {
97
+ data.transform2d = {
98
+ x: e.transform2d.x,
99
+ y: e.transform2d.y,
100
+ rotation: e.transform2d.rotation,
101
+ scale_x: e.transform2d.scaleX,
102
+ scale_y: e.transform2d.scaleY,
103
+ z: e.transform2d.z,
104
+ };
105
+ }
106
+ if (e.sprite2d) {
107
+ data.sprite2d = {
108
+ color: e.sprite2d.color.toArray(),
109
+ emissive: e.sprite2d.emissive,
110
+ shape: e.sprite2d.shape,
111
+ visible: e.sprite2d.visible,
112
+ };
113
+ }
114
+ if (e.hasTransform3d) {
115
+ data.transform3d = {
116
+ x: e.transform3d.x,
117
+ y: e.transform3d.y,
118
+ z: e.transform3d.z,
119
+ rot_x: e.transform3d.rotX,
120
+ rot_y: e.transform3d.rotY,
121
+ rot_z: e.transform3d.rotZ,
122
+ scale_x: e.transform3d.scaleX,
123
+ scale_y: e.transform3d.scaleY,
124
+ scale_z: e.transform3d.scaleZ,
125
+ };
126
+ }
127
+ if (e.mesh3d) {
128
+ data.mesh3d = {
129
+ shape: e.mesh3d.shape,
130
+ albedo: e.mesh3d.albedo.toArray(),
131
+ metallic: e.mesh3d.metallic,
132
+ roughness: e.mesh3d.roughness,
133
+ emissive: e.mesh3d.emissive.toArray(),
134
+ emissive_strength: e.mesh3d.emissiveStrength,
135
+ visible: e.mesh3d.visible,
136
+ };
137
+ }
138
+ if (e.pointLight) {
139
+ data.point_light = {
140
+ color: e.pointLight.color.toArray(),
141
+ intensity: e.pointLight.intensity,
142
+ radius: e.pointLight.radius,
143
+ };
144
+ }
145
+ return data;
146
+ }
147
+
148
+ function serializeSpawn(e: Entity): OutCommand {
149
+ return {
150
+ op: 'spawn',
151
+ local_id: e.id,
152
+ name: e.name || null,
153
+ tag: e.tag || null,
154
+ ...serializeEntity(e),
155
+ };
156
+ }
157
+
158
+ export class PhiRuntime implements SceneAccessor, EngineOutputBus {
159
+ private readonly registry = new Map<string, ComponentConstructor>();
160
+
161
+ private readonly entities = new Map<number, Entity>();
162
+
163
+ /** Rust sends entities again if a step fails. This prevents the scripts from adding one twice. */
164
+ private lastAddedWorldId = 0;
165
+
166
+ private readonly sharedValues = new Map<number, EntityValues>();
167
+
168
+ private lastSentIds: number[] = [];
169
+
170
+ private pendingCommands: OutCommand[] = [];
171
+
172
+ private nextLocalId = -1;
173
+
174
+ /** The components whose onStart() has run. It is weak, so removed components do not stay. */
175
+ private readonly startedComponents = new WeakSet<Component>();
176
+
177
+ constructor() {
178
+ Audio.attach(this);
179
+ Camera.attach(this);
180
+ Game.attach(this);
181
+ PostProcess.attach(this);
182
+ Scene.attach(this);
183
+ Settings.attach(this);
184
+ }
185
+
186
+ register(components: Record<string, ComponentConstructor>): void {
187
+ for (const [name, ctor] of Object.entries(components)) {
188
+ this.registry.set(name, ctor);
189
+ }
190
+ }
191
+
192
+ // --- SceneAccessor ---
193
+
194
+ spawn<const C extends readonly Component[]>(blueprint: EntityBlueprint<C>): Entity {
195
+ const id = this.nextLocalId;
196
+ this.nextLocalId -= 1;
197
+ const entity = new Entity(id, blueprint.name ?? '', blueprint.tag ?? '', this, (m) =>
198
+ this.log(m),
199
+ );
200
+
201
+ if (blueprint.transform2d || blueprint.sprite2d) {
202
+ entity.transform2d = new Transform2D(blueprint.transform2d);
203
+ entity.hasTransform2d = true;
204
+ }
205
+ if (blueprint.sprite2d) {
206
+ entity.sprite2d = new Sprite2D(blueprint.sprite2d);
207
+ }
208
+ if (blueprint.transform3d || blueprint.mesh3d || blueprint.pointLight) {
209
+ entity.transform3d = new Transform3D(blueprint.transform3d);
210
+ entity.hasTransform3d = true;
211
+ }
212
+ if (blueprint.mesh3d) {
213
+ entity.mesh3d = new Mesh3D(blueprint.mesh3d);
214
+ }
215
+ if (blueprint.pointLight) {
216
+ entity.pointLight = new PointLight(
217
+ blueprint.pointLight.color,
218
+ blueprint.pointLight.intensity,
219
+ blueprint.pointLight.radius,
220
+ );
221
+ }
222
+
223
+ if (blueprint.components) {
224
+ for (const spec of blueprint.components) {
225
+ entity.addComponent(spec.type, spec.props);
226
+ }
227
+ }
228
+
229
+ this.entities.set(id, entity);
230
+ this.pendingCommands.push(serializeSpawn(entity));
231
+ return entity;
232
+ }
233
+
234
+ destroy(entity: Entity): void {
235
+ if (!entity.isAlive) return;
236
+ entity.markDestroyed();
237
+ this.entities.delete(entity.id);
238
+ this.sharedValues.delete(entity.id);
239
+ this.pendingCommands.push({ op: 'despawn', id: entity.id });
240
+ }
241
+
242
+ findByName(name: string): Entity | null {
243
+ for (const e of this.entities.values()) {
244
+ if (e.isAlive && e.name === name) return e;
245
+ }
246
+ return null;
247
+ }
248
+
249
+ findByTag(tag: string): Entity[] {
250
+ const out: Entity[] = [];
251
+ for (const e of this.entities.values()) {
252
+ if (e.isAlive && e.tag === tag) out.push(e);
253
+ }
254
+ return out;
255
+ }
256
+
257
+ findAllWith<T extends Component>(ctor: ComponentClass<T>): T[] {
258
+ const out: T[] = [];
259
+ for (const e of this.entities.values()) {
260
+ const comp = e.isAlive ? e.getComponent(ctor) : null;
261
+ if (comp) out.push(comp);
262
+ }
263
+ return out;
264
+ }
265
+
266
+ entityCount(): number {
267
+ return this.entities.size;
268
+ }
269
+
270
+ // --- EngineOutputBus ---
271
+
272
+ playSound(sound: SoundName): void {
273
+ this.pendingCommands.push({ op: 'play_sound', sound });
274
+ }
275
+
276
+ setCamera2D(x: number, y: number, halfHeight?: number): void {
277
+ this.pendingCommands.push({ op: 'set_camera_2d', x, y, half_height: halfHeight ?? null });
278
+ }
279
+
280
+ setCamera3D(
281
+ pos: [number, number, number],
282
+ target: [number, number, number],
283
+ fovDegrees?: number,
284
+ ): void {
285
+ this.pendingCommands.push({
286
+ op: 'set_camera_3d',
287
+ position: pos,
288
+ target,
289
+ fov_y_degrees: fovDegrees ?? null,
290
+ });
291
+ }
292
+
293
+ setPostProcess(patch: { bloomIntensity?: number; saturation?: number; exposure?: number }): void {
294
+ this.pendingCommands.push({
295
+ op: 'set_post_process',
296
+ bloom_intensity: patch.bloomIntensity ?? null,
297
+ saturation: patch.saturation ?? null,
298
+ exposure: patch.exposure ?? null,
299
+ });
300
+ }
301
+
302
+ setPaused(paused: boolean): void {
303
+ this.pendingCommands.push({ op: 'set_paused', paused });
304
+ }
305
+
306
+ setTextScale(scale: number): void {
307
+ this.pendingCommands.push({ op: 'set_text_scale', scale });
308
+ }
309
+
310
+ quit(): void {
311
+ this.pendingCommands.push({ op: 'quit' });
312
+ }
313
+
314
+ changeScene(path: string): void {
315
+ this.pendingCommands.push({ op: 'change_scene', path });
316
+ }
317
+
318
+ log(message: string): void {
319
+ this.pendingCommands.push({ op: 'log', message: String(message) });
320
+ }
321
+
322
+ // --- Host Bridge Execution ---
323
+
324
+ private addNewEntities(newEntities: WireEntity[]): void {
325
+ for (const entity of newEntities) {
326
+ if (entity.id > this.lastAddedWorldId) {
327
+ this.addWorldEntity(entity);
328
+ this.lastAddedWorldId = entity.id;
329
+ }
330
+ }
331
+ }
332
+
333
+ private addWorldEntity(we: WireEntity): void {
334
+ const entity = new Entity(we.id, we.name ?? '', we.tag ?? '', this, (m) => this.log(m));
335
+ if (we.transform2d) {
336
+ entity.transform2d = new Transform2D({
337
+ x: we.transform2d.x,
338
+ y: we.transform2d.y,
339
+ rotation: we.transform2d.rotation,
340
+ scaleX: we.transform2d.scale_x,
341
+ scaleY: we.transform2d.scale_y,
342
+ z: we.transform2d.z,
343
+ });
344
+ entity.hasTransform2d = true;
345
+ }
346
+ if (we.sprite2d) {
347
+ const c = we.sprite2d.color;
348
+ entity.sprite2d = new Sprite2D({
349
+ color: new Color(c[0], c[1], c[2], c[3]),
350
+ emissive: we.sprite2d.emissive,
351
+ shape: we.sprite2d.shape as Sprite2D['shape'],
352
+ visible: we.sprite2d.visible,
353
+ });
354
+ }
355
+ if (we.transform3d) {
356
+ entity.transform3d = new Transform3D({
357
+ x: we.transform3d.x,
358
+ y: we.transform3d.y,
359
+ z: we.transform3d.z,
360
+ rotX: we.transform3d.rot_x,
361
+ rotY: we.transform3d.rot_y,
362
+ rotZ: we.transform3d.rot_z,
363
+ scaleX: we.transform3d.scale_x,
364
+ scaleY: we.transform3d.scale_y,
365
+ scaleZ: we.transform3d.scale_z,
366
+ });
367
+ entity.hasTransform3d = true;
368
+ }
369
+ if (we.mesh3d) {
370
+ const a = we.mesh3d.albedo;
371
+ const em = we.mesh3d.emissive;
372
+ entity.mesh3d = new Mesh3D({
373
+ shape: we.mesh3d.shape as Mesh3D['shape'],
374
+ albedo: new Color(a[0], a[1], a[2], a[3]),
375
+ metallic: we.mesh3d.metallic,
376
+ roughness: we.mesh3d.roughness,
377
+ emissive: new Color(em[0], em[1], em[2], em[3]),
378
+ emissiveStrength: we.mesh3d.emissive_strength,
379
+ visible: we.mesh3d.visible,
380
+ });
381
+ }
382
+ if (we.point_light) {
383
+ const pc = we.point_light.color;
384
+ entity.pointLight = new PointLight(
385
+ new Color(pc[0], pc[1], pc[2], pc[3]),
386
+ we.point_light.intensity,
387
+ we.point_light.radius,
388
+ );
389
+ }
390
+ // Store the values from Rust now, because component properties can change them.
391
+ const values = new EntityValues();
392
+ values.update(entity);
393
+ if (we.scripts) {
394
+ for (const s of we.scripts) {
395
+ const ctor = this.registry.get(s.component);
396
+ if (ctor) {
397
+ entity.addComponent(ctor, s.props);
398
+ } else {
399
+ this.log(`Warning: component '${s.component}' is not registered`);
400
+ }
401
+ }
402
+ }
403
+ this.entities.set(we.id, entity);
404
+ this.sharedValues.set(we.id, values);
405
+ }
406
+
407
+ /** Removes the entities that another tool removed from the world. */
408
+ private removeMissingEntities(liveIds: Set<number>): void {
409
+ for (const [id, ent] of Array.from(this.entities.entries())) {
410
+ if (id > 0 && !liveIds.has(id)) {
411
+ ent.markDestroyed();
412
+ this.entities.delete(id);
413
+ this.sharedValues.delete(id);
414
+ }
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Gives onDestroy() to each entity of the scene. An error in one entity does not stop the
420
+ * other entities, and the step then gives the first error. An entity that an onDestroy()
421
+ * spawns now never starts. Rust removes all entities and elements after this step.
422
+ */
423
+ private endScene(): void {
424
+ const errors: unknown[] = [];
425
+ Array.from(this.entities.values()).forEach((entity) => {
426
+ // An earlier onDestroy() can destroy an entity of this list.
427
+ if (!entity.isAlive) return;
428
+ try {
429
+ entity.markDestroyed();
430
+ } catch (error) {
431
+ errors.push(error);
432
+ }
433
+ });
434
+ this.entities.clear();
435
+ this.sharedValues.clear();
436
+ interfaceBridge.clear();
437
+ if (errors.length > 0) throw errors[0];
438
+ }
439
+
440
+ /** Sends each entity that a script changed. */
441
+ private flushEntityStateUpdates(): void {
442
+ for (const e of this.entities.values()) {
443
+ if (e.isAlive && this.hasChanged(e)) {
444
+ this.lastSentIds.push(e.id);
445
+ this.pendingCommands.push({ op: 'sync_entity', id: e.id, ...serializeEntity(e) });
446
+ }
447
+ }
448
+ }
449
+
450
+ /** Makes the scripts send the changes from the last step again. */
451
+ private forgetLastSentValues(): void {
452
+ this.lastSentIds.forEach((id) => this.sharedValues.delete(id));
453
+ }
454
+
455
+ /** Finds out if an entity changed since the last call, and stores its current values. */
456
+ private hasChanged(e: Entity): boolean {
457
+ let values = this.sharedValues.get(e.id);
458
+ if (!values) {
459
+ values = new EntityValues();
460
+ this.sharedValues.set(e.id, values);
461
+ }
462
+ return values.update(e);
463
+ }
464
+
465
+ /** Called by `phi_script` on `Stage::FixedUpdate` and `Stage::Update`. */
466
+ step(payloadJson: string): string {
467
+ const payload = JSON.parse(payloadJson) as StepInputWire;
468
+ this.pendingCommands = [];
469
+ Time.sync(payload.elapsed, payload.dt, payload.fixed_dt, payload.frame);
470
+ Game.sync(payload.pause_reason, payload.can_quit);
471
+ Input.sync(payload.input);
472
+ interfaceBridge.sync(payload.viewport);
473
+ Settings.sync(payload.viewport.text_scale);
474
+ interfaceBridge.begin(payload.last_step_failed);
475
+ if (payload.last_step_failed) this.forgetLastSentValues();
476
+ // A script error can end this step before the flush, so clear the list here.
477
+ this.lastSentIds = [];
478
+ if (payload.phase === 'end_scene') {
479
+ this.endScene();
480
+ return JSON.stringify(this.pendingCommands);
481
+ }
482
+ this.addNewEntities(payload.new_entities);
483
+ this.removeMissingEntities(new Set(payload.live_ids));
484
+
485
+ // 1. Run onStart() for all newly attached components
486
+ for (const ent of Array.from(this.entities.values())) {
487
+ if (ent.isAlive) {
488
+ for (const comp of ent.components) {
489
+ if (!this.startedComponents.has(comp)) {
490
+ this.startedComponents.add(comp);
491
+ comp.onStart?.();
492
+ }
493
+ }
494
+ }
495
+ }
496
+
497
+ // The callbacks of the interface run also while the game is paused, as a pause menu needs.
498
+ interfaceBridge.dispatch(payload.ui_events);
499
+
500
+ // 2. Execute phase lifecycle hook on all active components
501
+ for (const ent of Array.from(this.entities.values())) {
502
+ for (const comp of ent.components) {
503
+ if (!ent.isAlive) break;
504
+ if (payload.phase === 'fixed_update') {
505
+ comp.onFixedUpdate?.(payload.fixed_dt);
506
+ } else if (!Game.paused || (comp.constructor as typeof Component).runsWhenPaused) {
507
+ comp.onUpdate?.(payload.dt);
508
+ }
509
+ }
510
+ }
511
+
512
+ // 3. Emit synchronized entity component state back to Rust ECS World
513
+ this.flushEntityStateUpdates();
514
+ this.pendingCommands.push(...interfaceBridge.flush());
515
+ return JSON.stringify(this.pendingCommands);
516
+ }
517
+ }
@@ -0,0 +1,178 @@
1
+ import { Button } from '../ui/Button';
2
+ import { Control } from '../ui/Control';
3
+ import type { Element } from '../ui/Element';
4
+ import type { UiEventWire } from './UiEventWire';
5
+ import type { WireValue } from '../ui/WireValue';
6
+ import type { UiCommand } from './UiCommand';
7
+ import type { Viewport } from '../ui/Viewport';
8
+ import type { ViewportWire } from './ViewportWire';
9
+
10
+ function sameValue(a: WireValue | undefined, b: WireValue | undefined): boolean {
11
+ if (Array.isArray(a) && Array.isArray(b)) {
12
+ return a.length === b.length && a.every((item, index) => item === b[index]);
13
+ }
14
+ return a === b;
15
+ }
16
+
17
+ /**
18
+ * The interface side of each step. It keeps the viewport that Rust gives, and collects the
19
+ * changes to the elements in one step, and makes the fewest commands for them.
20
+ * It compares each element with the properties that Rust has, so a value that changes and
21
+ * then changes back sends nothing.
22
+ */
23
+ export class UiBridge {
24
+ private nextOwnerId = 1;
25
+
26
+ private currentViewport: Viewport = { width: 1920, height: 1080, scale: 1, textScale: 1 };
27
+
28
+ /** The elements that came on the screen in this step, in order. */
29
+ private created: Element[] = [];
30
+
31
+ private readonly changedElements = new Set<Element>();
32
+
33
+ /** The IDs that Rust has and must remove. */
34
+ private removedIds: number[] = [];
35
+
36
+ /** The properties that Rust has for each element. */
37
+ private readonly sent = new Map<Element, Record<string, WireValue>>();
38
+
39
+ /**
40
+ * The elements that the last flush sent, with the properties that Rust had before it, or
41
+ * undefined for a new element.
42
+ */
43
+ private lastFlush = new Map<Element, Record<string, WireValue> | undefined>();
44
+
45
+ private lastRemovedIds: number[] = [];
46
+
47
+ get viewport(): Viewport {
48
+ return this.currentViewport;
49
+ }
50
+
51
+ sync(viewport: ViewportWire): void {
52
+ this.currentViewport = {
53
+ width: viewport.width,
54
+ height: viewport.height,
55
+ scale: viewport.scale,
56
+ textScale: viewport.text_scale,
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Starts a step. If Rust could not read the commands of the last step, the next flush sends
62
+ * them again.
63
+ */
64
+ begin(lastStepFailed: boolean): void {
65
+ if (lastStepFailed) {
66
+ this.removedIds = [...this.lastRemovedIds, ...this.removedIds];
67
+ this.lastFlush.forEach((previous, element) => {
68
+ if (previous === undefined) {
69
+ this.sent.delete(element);
70
+ this.created.push(element);
71
+ } else {
72
+ this.sent.set(element, previous);
73
+ this.changedElements.add(element);
74
+ }
75
+ });
76
+ }
77
+ // A script error can end this step before the flush, so forget the last flush here.
78
+ this.lastFlush = new Map();
79
+ this.lastRemovedIds = [];
80
+ }
81
+
82
+ newOwnerId(): number {
83
+ const id = this.nextOwnerId;
84
+ this.nextOwnerId += 1;
85
+ return id;
86
+ }
87
+
88
+ added(element: Element): void {
89
+ this.created.push(element);
90
+ }
91
+
92
+ changed(element: Element): void {
93
+ this.changedElements.add(element);
94
+ }
95
+
96
+ removed(element: Element): void {
97
+ if (this.sent.has(element)) {
98
+ this.removedIds.push(element.id);
99
+ }
100
+ this.forget(element);
101
+ }
102
+
103
+ /**
104
+ * Gives each event to its element. An element that left the screen after Rust made the
105
+ * event gets nothing.
106
+ */
107
+ dispatch(events: readonly UiEventWire[]): void {
108
+ events.forEach((event) => {
109
+ const element = [...this.sent.keys()].find((candidate) => candidate.id === event.id);
110
+ if (element instanceof Button && event.kind === 'press') {
111
+ element.press();
112
+ } else if (element instanceof Control && event.kind === 'change') {
113
+ element.change(event.value);
114
+ }
115
+ });
116
+ }
117
+
118
+ /** Forgets all elements, because Rust removes all of them at the end of the scene. */
119
+ clear(): void {
120
+ this.created = [];
121
+ this.changedElements.clear();
122
+ this.removedIds = [];
123
+ this.sent.clear();
124
+ this.lastFlush = new Map();
125
+ this.lastRemovedIds = [];
126
+ }
127
+
128
+ /** Gives the commands for the changes since the last call. Removes come first, so an ID can come back. */
129
+ flush(): UiCommand[] {
130
+ const commands: UiCommand[] = this.removedIds.map((id) => ({ op: 'ui_remove', id }));
131
+ this.created.forEach((element) => this.create(element, commands));
132
+ this.changedElements.forEach((element) => this.update(element, commands));
133
+ this.lastRemovedIds = this.removedIds;
134
+ this.created = [];
135
+ this.changedElements.clear();
136
+ this.removedIds = [];
137
+ return commands;
138
+ }
139
+
140
+ private create(element: Element, commands: UiCommand[]): void {
141
+ // A tree that left the screen in the same step has no owner.
142
+ if (element.owner === null || this.sent.has(element)) return;
143
+ // The create of the parent also creates its children, after the parent.
144
+ if (element.parent !== null && !this.sent.has(element.parent)) return;
145
+ const props = element.wireProps();
146
+ commands.push({
147
+ op: 'ui_create',
148
+ id: element.id,
149
+ parent: element.parent?.id ?? null,
150
+ owner: element.owner.id,
151
+ kind: element.kind,
152
+ props,
153
+ });
154
+ this.lastFlush.set(element, undefined);
155
+ this.sent.set(element, props);
156
+ element.children.forEach((child) => this.create(child, commands));
157
+ }
158
+
159
+ private update(element: Element, commands: UiCommand[]): void {
160
+ const last = this.sent.get(element);
161
+ // Rust does not have the element yet, so its create command has the new values.
162
+ if (!last) return;
163
+ const props = element.wireProps();
164
+ const changes = Object.fromEntries(
165
+ Object.entries(props).filter(([key, value]) => !sameValue(value, last[key])),
166
+ );
167
+ if (Object.keys(changes).length === 0) return;
168
+ commands.push({ op: 'ui_update', id: element.id, props: changes });
169
+ this.lastFlush.set(element, last);
170
+ this.sent.set(element, props);
171
+ }
172
+
173
+ private forget(element: Element): void {
174
+ this.sent.delete(element);
175
+ this.changedElements.delete(element);
176
+ element.children.forEach((child) => this.forget(child));
177
+ }
178
+ }
@@ -0,0 +1,14 @@
1
+ import type { ElementKind } from '../ui/ElementKind';
2
+ import type { WireValue } from '../ui/WireValue';
3
+
4
+ export type UiCommand =
5
+ | {
6
+ op: 'ui_create';
7
+ id: number;
8
+ parent: number | null;
9
+ owner: number;
10
+ kind: ElementKind;
11
+ props: Record<string, WireValue>;
12
+ }
13
+ | { op: 'ui_update'; id: number; props: Record<string, WireValue> }
14
+ | { op: 'ui_remove'; id: number };