@threenative/core 0.3.11 → 0.3.13

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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -23,6 +23,25 @@ interface IAssetCacheReport {
23
23
  readonly reason?: string;
24
24
  }
25
25
 
26
+ /**
27
+ * Generated content kept between runs (PRD-860): `ctx.assets.memo(key, build)` returns what `build`
28
+ * returned the last time this exact build of the game ran, read back from disk, and calls `build`
29
+ * only when nothing is stored. A seeded world, a painted sky or a baked placement list is the same
30
+ * every run of one build, so a repeat visit stops paying for it.
31
+ *
32
+ * The value is named typed arrays, the shape a generator hands to geometry, instancing and
33
+ * textures. The build identity is the hashed entry script the web build writes into the page
34
+ * (`__TN_BUILD_ID__`), so any code change regenerates and the old build's entries are deleted. With
35
+ * no build identity (the dev server) or no Cache API (a native host), `build` runs every time and
36
+ * `TN_ASSET_MEMO` says why.
37
+ */
38
+ type MemoArray = Float32Array | Float64Array | Int8Array | Int16Array | Int32Array | Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array;
39
+ /** Every field a typed array: a record or an interface, which has no index signature. */
40
+ type MemoShape<T> = {
41
+ readonly [K in keyof T]: MemoArray;
42
+ };
43
+ type AssetMemo = <T extends MemoShape<T>>(key: string, build: () => T | Promise<T>) => Promise<T>;
44
+
26
45
  interface IAssetLoaderOptions {
27
46
  readonly basePath?: string;
28
47
  /**
@@ -64,14 +83,46 @@ interface IAssetLoaderOptions {
64
83
  * `navigator.connection.saveData`.
65
84
  */
66
85
  readonly backgroundFill?: boolean;
86
+ /**
87
+ * Draw a model's coarse companion first, where the cook wrote one, and the full model when it
88
+ * lands (PRD-860). On by default; `false` is the named override, reported once as
89
+ * `TN_ASSETS_STREAM_MESHES_OFF`.
90
+ */
91
+ readonly streamMeshes?: boolean;
92
+ /**
93
+ * Draw a streamed model's KTX2 textures with their resident mips first, and the whole files when
94
+ * they land (PRD-860). On by default; `false` is the named override, reported once as
95
+ * `TN_ASSETS_STREAM_TEXTURES_OFF`. It rides on `streamMeshes`: the coarse parse is where the
96
+ * resident mips draw.
97
+ */
98
+ readonly streamTextures?: boolean;
67
99
  }
68
100
  /** What one request is worth relative to the rest of the loader's queue. */
101
+ /**
102
+ * Report marker for a file a scene asks for after the reveal that the game had not prefetched.
103
+ *
104
+ * The reveal is the first moment the player is playing, so the download such a request starts is
105
+ * time spent looking at a world without that file in it — the pop-in a streaming game exists to
106
+ * avoid. One line per file, carrying the bytes and how far into play the request landed, so a
107
+ * playtest can count the pop-ins instead of a person having to watch for them.
108
+ *
109
+ * A file the game asked `prefetch` for first is not late: that is a deliberate stream, and the
110
+ * engine's own background fill is no promise either — it lags the link by design.
111
+ */
112
+ declare const ASSET_LATE_MARKER = "TN_ASSET_LATE";
69
113
  interface IAssetRequestOptions {
70
114
  /**
71
115
  * `now` for a file the running scene awaits, `soon` for a prefetch. The loader's own direct
72
116
  * calls default to `now`.
73
117
  */
74
118
  readonly priority?: AssetPriority;
119
+ /**
120
+ * PRD-860: `true` resolves a model only once its full file has replaced the coarse companion the
121
+ * first scene draws (the same object, upgraded in place). For a caller that copies the vertices:
122
+ * a trimesh or convex-hull collider, a navmesh bake, a geometry merge. Default: the coarse model,
123
+ * so the scene plays before the download ends.
124
+ */
125
+ readonly whole?: boolean;
75
126
  }
76
127
  /** What a `prefetch` asked for and what the download produced. */
77
128
  interface IAssetPrefetchProgress {
@@ -183,8 +234,22 @@ interface IAssetLoader {
183
234
  /**
184
235
  * Start the post-reveal idle fill. The engine calls this when `ctx.startup.whenReady()` settles;
185
236
  * a game that drives a loader outside `defineGame` may call it after its own reveal.
237
+ *
238
+ * It is also where the reveal is marked for {@link ASSET_LATE_MARKER}: a whole-file load a scene
239
+ * asks for after this call, and that the game did not `prefetch`, is reported as the pop-in it is.
240
+ * A game that never calls it never gets the report.
186
241
  */
187
242
  startBackgroundFill(): Promise<void>;
243
+ /**
244
+ * Generated content kept between runs (PRD-860): returns what `build` returned the last time this
245
+ * build of the game ran, read from disk, and calls `build` only when nothing is stored. Use it for
246
+ * seeded work that is the same every run, such as placement lists, painted sky pixels or terrain
247
+ * heights. The value is named typed arrays. A new build regenerates. On the dev server and on a
248
+ * native host `build` runs every time, and `TN_ASSET_MEMO` says why.
249
+ *
250
+ * @example const { pixels } = await ctx.assets.memo("sky", () => ({ pixels: paintSky() }));
251
+ */
252
+ memo: AssetMemo;
188
253
  /**
189
254
  * How many loads this loader has been asked for and how many have settled (resolved or
190
255
  * rejected). A loading view reads the ratio; the runtime folds it into `ctx.startup.progress`
@@ -247,5 +312,17 @@ type AssetKind = "audio" | "model" | "texture";
247
312
  */
248
313
  declare function reconcileMirroredClips(root: Object3D, clips: readonly AnimationClip[]): boolean;
249
314
  declare function createAssetLoader(options?: IAssetLoaderOptions): IAssetLoader;
315
+ /**
316
+ * Fetch a data file the asset loader serves: each url `assets.resolve(path)` names, in order, until
317
+ * one answers ok. A built game serves the hashed output and a dev server the source path, so taking
318
+ * only the first url 404s on one of them. When none answers it throws `TN_ASSET_NOT_SERVED` naming
319
+ * every url tried and why, so a missing file is never a half-drawn world.
320
+ *
321
+ * @situation load a baked JSON or binary file (a heightmap, a placement buffer, a data table) that the loader has no typed method for
322
+ * @situation a data file loads in dev but 404s in the built game
323
+ * @constraint reads the response once; call `.json()` or `.arrayBuffer()` on the result
324
+ * @example const heights = new Float32Array(await (await fetchAsset(ctx.assets, "world/forest.bin")).arrayBuffer());
325
+ */
326
+ declare function fetchAsset(assets: Pick<IAssetLoader, "resolve">, path: string): Promise<Response>;
250
327
 
251
- export { type AssetPriority as A, type IAssetLoader as I, type IAssetLoaderOptions as a, type IAssetCacheReport as b, type IAssetCacheState as c, type IAssetPrefetchProgress as d, type IAssetRequestOptions as e, type ITextureOptions as f, createAssetLoader as g, reconcileMirroredClips as r };
328
+ export { ASSET_LATE_MARKER as A, type IAssetLoader as I, type IAssetLoaderOptions as a, type AssetPriority as b, type IAssetCacheReport as c, type IAssetCacheState as d, type IAssetPrefetchProgress as e, type IAssetRequestOptions as f, type ITextureOptions as g, createAssetLoader as h, fetchAsset as i, reconcileMirroredClips as r };
@@ -0,0 +1,46 @@
1
+ import { Vector3 } from 'three';
2
+
3
+ type CameraShakeCurve = (phase: number) => number;
4
+ interface ICameraShakeOptions {
5
+ /** Position amplitude in world metres, supplied by the game. */
6
+ readonly amplitude: Vector3;
7
+ /** Rotation amplitude in radians around x/y/z, supplied by the game. */
8
+ readonly rotationAmplitude: Vector3;
9
+ /** Curve cycles per second, supplied by the game. */
10
+ readonly frequency: number;
11
+ /** Exponential envelope decay per second, supplied by the game. */
12
+ readonly decay: number;
13
+ /** Game-authored waveform sampled at `elapsed * frequency * 2π`. */
14
+ readonly curve: CameraShakeCurve;
15
+ }
16
+ interface ICameraShakeOffset {
17
+ readonly position: Vector3;
18
+ readonly rotation: Vector3;
19
+ }
20
+ /**
21
+ * Produce a transient camera offset without owning or mutating a camera.
22
+ *
23
+ * The caller supplies the amplitudes, frequency, decay and waveform. {@link update} evaluates the
24
+ * waveform against the caller's fixed-step delta and returns a reusable position/rotation offset;
25
+ * a template can compose it after its own camera rig and damping.
26
+ */
27
+ declare class CameraShake {
28
+ #private;
29
+ readonly amplitude: Vector3;
30
+ readonly rotationAmplitude: Vector3;
31
+ readonly frequency: number;
32
+ readonly decay: number;
33
+ readonly curve: CameraShakeCurve;
34
+ readonly offset: ICameraShakeOffset;
35
+ constructor(options: ICameraShakeOptions);
36
+ get active(): boolean;
37
+ get elapsed(): number;
38
+ /** Start or restart the authored shake waveform. */
39
+ trigger(): this;
40
+ /** Stop the effect and clear the offset. */
41
+ stop(): this;
42
+ /** Evaluate the current offset and advance by one caller-supplied fixed-step delta. */
43
+ update(dt: number): ICameraShakeOffset;
44
+ }
45
+
46
+ export { type CameraShakeCurve as C, type ICameraShakeOffset as I, CameraShake as a, type ICameraShakeOptions as b };
@@ -1,6 +1,6 @@
1
1
  import * as three from 'three';
2
2
  import { Camera, Vector2, Vector3, Scene, OrthographicCamera } from 'three';
3
- import { I as IRendererLike } from './renderer-rZm0hVqq.js';
3
+ import { I as IRendererLike } from './renderer-BtOSseYf.js';
4
4
 
5
5
  interface IViewportSize {
6
6
  readonly aspect: number;
@@ -0,0 +1,133 @@
1
+ import { debugRequested, countDebug, measureDebug } from './chunk-GYUZJQ7U.js';
2
+ import { UI_STARTUP_MESSAGE, GAME_STATE_MESSAGE, UI_INTENT_MESSAGE, postUiState, serializeUiState } from './chunk-CFGTPFUH.js';
3
+
4
+ // src/ui-state.ts
5
+ var microtask = (flush) => {
6
+ void Promise.resolve().then(flush);
7
+ };
8
+ function publishUiState(bridge, store, options = {}) {
9
+ if (bridge.end !== "game") {
10
+ throw new Error(
11
+ `TN_UI_STATE_WRONG_END: state is published by the 'game' end, not '${bridge.end}'.`
12
+ );
13
+ }
14
+ const schedule = options.schedule ?? microtask;
15
+ const debug = debugRequested();
16
+ const serialize = debug ? (state) => {
17
+ countDebug("uiSerializations", 1, "ui", "publishUiState");
18
+ return measureDebug("uiSerialize", "ui", "publishUiState", () => serializeUiState(state));
19
+ } : serializeUiState;
20
+ const read = () => store.getPublishedState === void 0 ? store.getState() : store.getPublishedState();
21
+ let stopped = false;
22
+ let queued = false;
23
+ let lastFrame = "";
24
+ const send = (state, frame) => {
25
+ lastFrame = frame;
26
+ postUiState(bridge, state, frame);
27
+ if (debug) {
28
+ countDebug("uiMessages", 1, "ui", "publishUiState");
29
+ countDebug(
30
+ "uiMessageBytes",
31
+ new TextEncoder().encode(frame).byteLength,
32
+ "ui",
33
+ "publishUiState"
34
+ );
35
+ }
36
+ };
37
+ const publish = () => {
38
+ if (stopped) return;
39
+ const state = read();
40
+ send(state, serialize(state));
41
+ };
42
+ const flush = () => {
43
+ queued = false;
44
+ if (stopped) return;
45
+ if (!bridge.hasPeer()) return;
46
+ const state = read();
47
+ const frame = serialize(state);
48
+ if (frame === lastFrame) return;
49
+ send(state, frame);
50
+ };
51
+ const unsubscribe = store.subscribe(() => {
52
+ if (stopped || queued) return;
53
+ queued = true;
54
+ schedule(flush);
55
+ });
56
+ if (bridge.hasPeer()) publish();
57
+ return {
58
+ publish,
59
+ stop() {
60
+ stopped = true;
61
+ unsubscribe();
62
+ }
63
+ };
64
+ }
65
+ function subscribeUiState(bridge) {
66
+ if (bridge.end !== "ui") {
67
+ throw new Error(
68
+ `TN_UI_STATE_WRONG_END: state is mirrored by the 'ui' end, not '${bridge.end}'.`
69
+ );
70
+ }
71
+ const listeners = /* @__PURE__ */ new Set();
72
+ let current;
73
+ let covered = false;
74
+ const off = bridge.onMessage((message) => {
75
+ if (message.type === UI_STARTUP_MESSAGE) {
76
+ const next = message.phase !== "ready";
77
+ if (next === covered) return;
78
+ covered = next;
79
+ for (const listener of [...listeners]) listener();
80
+ return;
81
+ }
82
+ if (message.type !== GAME_STATE_MESSAGE) return;
83
+ const state = message.state;
84
+ if (typeof state !== "object" || state === null || Array.isArray(state)) {
85
+ throw new Error("TN_UI_STATE_FRAME_INVALID: a published state frame must carry an object.");
86
+ }
87
+ current = state;
88
+ for (const listener of [...listeners]) listener();
89
+ });
90
+ return {
91
+ get: () => current,
92
+ covered: () => covered,
93
+ subscribe(listener) {
94
+ listeners.add(listener);
95
+ return () => listeners.delete(listener);
96
+ },
97
+ stop() {
98
+ off();
99
+ listeners.clear();
100
+ }
101
+ };
102
+ }
103
+ function sendUiIntent(bridge, intent, payload) {
104
+ if (bridge.end !== "ui") {
105
+ throw new Error(
106
+ `TN_UI_INTENT_WRONG_END: intents are sent by the 'ui' end, not '${bridge.end}'.`
107
+ );
108
+ }
109
+ if (typeof intent !== "string" || intent.length === 0) {
110
+ throw new Error("TN_UI_INTENT_INVALID: an intent needs a non-empty name.");
111
+ }
112
+ bridge.post({
113
+ type: UI_INTENT_MESSAGE,
114
+ intent,
115
+ ...payload === void 0 ? {} : { payload }
116
+ });
117
+ }
118
+ function onUiIntent(bridge, listener) {
119
+ if (bridge.end !== "game") {
120
+ throw new Error(
121
+ `TN_UI_INTENT_WRONG_END: intents are received by the 'game' end, not '${bridge.end}'.`
122
+ );
123
+ }
124
+ return bridge.onMessage((message) => {
125
+ if (message.type !== UI_INTENT_MESSAGE) return;
126
+ if (typeof message.intent !== "string" || message.intent.length === 0) {
127
+ throw new Error("TN_UI_INTENT_INVALID: an intent frame must carry a non-empty name.");
128
+ }
129
+ listener(message.intent, message.payload);
130
+ });
131
+ }
132
+
133
+ export { onUiIntent, publishUiState, sendUiIntent, subscribeUiState };
@@ -0,0 +1,231 @@
1
+ // src/ui-bridge.ts
2
+ var HIT_REGIONS_MESSAGE = "tn:hit-regions";
3
+ var GAME_STATE_MESSAGE = "tn:state";
4
+ var UI_INTENT_MESSAGE = "tn:intent";
5
+ var UI_DEV_METRICS_MESSAGE = "tn:dev-metrics";
6
+ var UI_STARTUP_MESSAGE = "tn:startup";
7
+ var UI_READY_INTENT = "tn:ready";
8
+ var UI_BRIDGE_GLOBALS = {
9
+ /** UI end, inbound: the host calls this with one JSON string. */
10
+ uiReceive: "__tnUiReceive",
11
+ /** UI end, outbound: an injected object with `postMessage(string)`. */
12
+ uiHost: "tnHost",
13
+ /** Game end, inbound: the runtime calls this with one JSON string. */
14
+ gameReceive: "__tnUiGameReceive",
15
+ /** Game end, outbound: the runtime installs this and forwards to the web view. */
16
+ gamePost: "__tnUiPost"
17
+ };
18
+ var stateFrames = /* @__PURE__ */ new WeakMap();
19
+ function serializeUiState(state) {
20
+ return assertSendable({ type: GAME_STATE_MESSAGE, state });
21
+ }
22
+ function postUiState(bridge, state, frame) {
23
+ const message = { type: GAME_STATE_MESSAGE, state };
24
+ stateFrames.set(message, frame);
25
+ try {
26
+ bridge.post(message);
27
+ } finally {
28
+ stateFrames.delete(message);
29
+ }
30
+ }
31
+ function assertSendable(message) {
32
+ if (typeof message !== "object" || message === null || Array.isArray(message)) {
33
+ throw new Error("TN_UI_BRIDGE_MESSAGE_INVALID: a bridge message must be a JSON object.");
34
+ }
35
+ if (typeof message.type !== "string" || message.type.length === 0) {
36
+ throw new Error("TN_UI_BRIDGE_MESSAGE_INVALID: a bridge message must carry a string 'type'.");
37
+ }
38
+ let frame;
39
+ try {
40
+ frame = stateFrames.get(message) ?? JSON.stringify(message);
41
+ } catch (error) {
42
+ throw new Error(
43
+ `TN_UI_BRIDGE_MESSAGE_INVALID: '${message.type}' is not JSON-serialisable: ${error instanceof Error ? error.message : String(error)}`
44
+ );
45
+ }
46
+ if (frame === void 0) {
47
+ throw new Error(`TN_UI_BRIDGE_MESSAGE_INVALID: '${message.type}' serialised to nothing.`);
48
+ }
49
+ return frame;
50
+ }
51
+ function parseFrame(frame) {
52
+ const text = typeof frame === "string" ? frame : frame?.data;
53
+ if (typeof text !== "string") {
54
+ throw new Error("TN_UI_BRIDGE_FRAME_INVALID: expected a JSON string from the host.");
55
+ }
56
+ let parsed;
57
+ try {
58
+ parsed = JSON.parse(text);
59
+ } catch (error) {
60
+ throw new Error(
61
+ `TN_UI_BRIDGE_FRAME_INVALID: not JSON: ${error instanceof Error ? error.message : String(error)}`
62
+ );
63
+ }
64
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
65
+ throw new Error("TN_UI_BRIDGE_FRAME_INVALID: a bridge frame must be a JSON object.");
66
+ }
67
+ if (typeof parsed.type !== "string") {
68
+ throw new Error("TN_UI_BRIDGE_FRAME_INVALID: a bridge frame must carry a string 'type'.");
69
+ }
70
+ return parsed;
71
+ }
72
+ function findOutbound(scope, end) {
73
+ if (end === "game") {
74
+ const post = scope[UI_BRIDGE_GLOBALS.gamePost];
75
+ return typeof post === "function" ? (frame) => post(frame) : void 0;
76
+ }
77
+ const injected = scope[UI_BRIDGE_GLOBALS.uiHost];
78
+ if (typeof injected?.postMessage === "function") {
79
+ return (frame) => injected.postMessage(frame);
80
+ }
81
+ const webkit = scope.webkit;
82
+ const handler = webkit?.messageHandlers?.[UI_BRIDGE_GLOBALS.uiHost];
83
+ if (typeof handler?.postMessage === "function") {
84
+ return (frame) => handler.postMessage(frame);
85
+ }
86
+ const ipc = scope.ipc;
87
+ if (typeof ipc?.postMessage === "function") {
88
+ return (frame) => ipc.postMessage(frame);
89
+ }
90
+ return void 0;
91
+ }
92
+ var BROKER_KEY = "__tnUiBridgeBroker";
93
+ function broker(scope) {
94
+ const existing = scope[BROKER_KEY];
95
+ if (existing !== void 0) return existing;
96
+ const created = { game: /* @__PURE__ */ new Set(), ui: /* @__PURE__ */ new Set(), inbound: /* @__PURE__ */ new Map() };
97
+ scope[BROKER_KEY] = created;
98
+ return created;
99
+ }
100
+ function installInbound(scope, key, deliver) {
101
+ const bus = broker(scope);
102
+ let slot = bus.inbound.get(key);
103
+ if (slot === void 0) {
104
+ const receivers = /* @__PURE__ */ new Set();
105
+ slot = {
106
+ receivers,
107
+ dispatch: (frame) => {
108
+ let firstError;
109
+ let failed = false;
110
+ for (const receiver of [...receivers]) {
111
+ try {
112
+ receiver(frame);
113
+ } catch (error) {
114
+ if (!failed) {
115
+ failed = true;
116
+ firstError = error;
117
+ }
118
+ }
119
+ }
120
+ if (failed) throw firstError;
121
+ }
122
+ };
123
+ bus.inbound.set(key, slot);
124
+ }
125
+ slot.receivers.add(deliver);
126
+ scope[key] = slot.dispatch;
127
+ const installed = slot;
128
+ return () => {
129
+ installed.receivers.delete(deliver);
130
+ if (installed.receivers.size === 0 && scope[key] === installed.dispatch) scope[key] = void 0;
131
+ };
132
+ }
133
+ var LOOPBACK_KEY = "__tnUiLoopback";
134
+ function installLoopback(scope) {
135
+ const search = scope.location?.search;
136
+ if (typeof search !== "string" || new URLSearchParams(search).get("tnUiLoopback") !== "1") return;
137
+ if (scope[LOOPBACK_KEY] !== void 0) return;
138
+ const { port1: gamePort, port2: uiPort } = new MessageChannel();
139
+ const receive = (key) => (event) => scope[key]?.(event.data);
140
+ gamePort.onmessage = receive(UI_BRIDGE_GLOBALS.gameReceive);
141
+ uiPort.onmessage = receive(UI_BRIDGE_GLOBALS.uiReceive);
142
+ scope[UI_BRIDGE_GLOBALS.gamePost] = (frame) => gamePort.postMessage(frame);
143
+ scope[UI_BRIDGE_GLOBALS.uiHost] = { postMessage: (frame) => uiPort.postMessage(frame) };
144
+ scope.__tnUiOverlayAttached = () => true;
145
+ scope[LOOPBACK_KEY] = {
146
+ close() {
147
+ gamePort.close();
148
+ uiPort.close();
149
+ for (const key of [UI_BRIDGE_GLOBALS.gamePost, UI_BRIDGE_GLOBALS.uiHost, LOOPBACK_KEY])
150
+ scope[key] = void 0;
151
+ scope.__tnUiOverlayAttached = void 0;
152
+ }
153
+ };
154
+ }
155
+ function connectUiBridge(options) {
156
+ const { end } = options;
157
+ if (end !== "game" && end !== "ui") {
158
+ throw new Error(`TN_UI_BRIDGE_END_INVALID: expected 'game' or 'ui', got '${String(end)}'.`);
159
+ }
160
+ const scope = options.scope ?? globalThis;
161
+ installLoopback(scope);
162
+ const listeners = /* @__PURE__ */ new Set();
163
+ const deliver = (frame) => {
164
+ const message = parseFrame(frame);
165
+ for (const listener of [...listeners]) listener(message);
166
+ };
167
+ const outbound = findOutbound(scope, end);
168
+ const inboundKey = end === "ui" ? UI_BRIDGE_GLOBALS.uiReceive : UI_BRIDGE_GLOBALS.gameReceive;
169
+ let closed = false;
170
+ if (outbound === void 0) {
171
+ const bus = broker(scope);
172
+ const peer = end === "ui" ? "game" : "ui";
173
+ const own = (message) => {
174
+ for (const listener of [...listeners]) listener(message);
175
+ };
176
+ bus[end].add(own);
177
+ return {
178
+ end,
179
+ transport: "in-process",
180
+ hasPeer: () => bus[peer].size > 0,
181
+ post(message) {
182
+ const frame = assertSendable(message);
183
+ if (closed) throw new Error("TN_UI_BRIDGE_CLOSED: post on a closed bridge.");
184
+ const copy = JSON.parse(frame);
185
+ for (const listener of [...bus[peer]]) listener(copy);
186
+ },
187
+ onMessage(listener) {
188
+ listeners.add(listener);
189
+ return () => listeners.delete(listener);
190
+ },
191
+ close() {
192
+ closed = true;
193
+ listeners.clear();
194
+ bus[end].delete(own);
195
+ }
196
+ };
197
+ }
198
+ const uninstall = installInbound(scope, inboundKey, deliver);
199
+ const injected = scope[UI_BRIDGE_GLOBALS.uiHost];
200
+ if (end === "ui" && injected !== void 0 && typeof injected === "object") {
201
+ injected.onmessage = (event) => deliver(event);
202
+ }
203
+ return {
204
+ end,
205
+ transport: "host",
206
+ hasPeer() {
207
+ const attached = scope.__tnUiOverlayAttached;
208
+ if (end === "ui") return true;
209
+ return typeof attached === "function" ? attached() === true : false;
210
+ },
211
+ post(message) {
212
+ const frame = assertSendable(message);
213
+ if (closed) throw new Error("TN_UI_BRIDGE_CLOSED: post on a closed bridge.");
214
+ outbound(frame);
215
+ },
216
+ onMessage(listener) {
217
+ listeners.add(listener);
218
+ return () => listeners.delete(listener);
219
+ },
220
+ close() {
221
+ closed = true;
222
+ listeners.clear();
223
+ uninstall();
224
+ if (end === "ui" && injected !== void 0 && typeof injected === "object") {
225
+ injected.onmessage = void 0;
226
+ }
227
+ }
228
+ };
229
+ }
230
+
231
+ export { GAME_STATE_MESSAGE, HIT_REGIONS_MESSAGE, UI_BRIDGE_GLOBALS, UI_DEV_METRICS_MESSAGE, UI_INTENT_MESSAGE, UI_READY_INTENT, UI_STARTUP_MESSAGE, connectUiBridge, postUiState, serializeUiState };