@threenative/core 0.3.4 → 0.3.6

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +57 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2408 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +574 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +850 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,265 @@
1
+ import { GLYPH_ADVANCE, GLYPH_HEIGHT, GLYPH_WIDTH } from "./react-glyphs.js";
2
+
3
+ /**
4
+ * The layout model behind the native React overlay: pure TypeScript, no WASM, no Yoga, no CSS
5
+ * parser. `TN_NATIVE_WASM_ON_MOBILE` refuses WebAssembly in mobile bundles, which rules out Yoga;
6
+ * writing a CSS engine here would be writing a browser, one ticket at a time.
7
+ *
8
+ * That last clause used to read "which is the thing this whole path exists to avoid", and PRD-217
9
+ * corrected it: the thing to avoid is *shipping* a browser, and every platform already provides
10
+ * one at the composition layer for free. So `ui.renderer: "web"` is now the default — the same
11
+ * React DOM, Tailwind, CSS and SVG on every target — and this renderer is the opt-in for a UI that
12
+ * is part of the rendered frame, a target with no web view, or zero extra processes. Growing this
13
+ * vocabulary toward CSS is still the wrong move; a game that needs CSS should ask for the web
14
+ * renderer instead.
15
+ *
16
+ * **The supported subset is exactly the fields on {@link IOverlayStyle} and nothing else.** A style
17
+ * key that is not on that interface is not "ignored for now" — {@link assertKnownStyle} throws
18
+ * `TN_REACT_UNKNOWN_STYLE` naming the key, because a convention discovered by failure is worse than
19
+ * one that does not exist.
20
+ *
21
+ * Units are screen pixels throughout, matching `CanvasLayer`'s orthographic camera. The origin is
22
+ * the top-left of the parent's content box, y increasing downwards, like a screen and unlike Three.
23
+ */
24
+
25
+ /** `#rrggbb`, `#rgb`, or a packed `0xrrggbb` number. Alpha is `opacity`, kept separate on purpose. */
26
+ export type OverlayColor = string | number;
27
+
28
+ export interface IOverlayStyle {
29
+ /** Distance from the parent's left content edge. Ignored when the parent lays out in flow. */
30
+ left?: number;
31
+ /** Distance from the parent's right content edge. Applied only when `left` is absent. */
32
+ right?: number;
33
+ /** Distance from the parent's top content edge. Ignored when the parent lays out in flow. */
34
+ top?: number;
35
+ /** Distance from the parent's bottom content edge. Applied only when `top` is absent. */
36
+ bottom?: number;
37
+ /** Centre horizontally in the parent's content box. Wins over `left`/`right`. */
38
+ centerX?: boolean;
39
+ /** Centre vertically in the parent's content box. Wins over `top`/`bottom`. */
40
+ centerY?: boolean;
41
+ /** Fixed width. Without one, a box shrink-wraps its children and text measures its glyphs. */
42
+ width?: number;
43
+ /** Fixed height. Without one, a box shrink-wraps its children and text is one line tall. */
44
+ height?: number;
45
+ /** Uniform inset between this box's edges and its content box. */
46
+ padding?: number;
47
+ /** Lay children out in flow along this axis. Absent means children are placed absolutely. */
48
+ direction?: "row" | "column";
49
+ /** Space between flow children, in pixels. Only meaningful with `direction`. */
50
+ gap?: number;
51
+ /** Cross-axis placement of flow children. */
52
+ align?: "start" | "center" | "end";
53
+ /** Fill colour. Absent means the box draws nothing and only positions its children. */
54
+ background?: OverlayColor;
55
+ /** Glyph colour on a `text` element. */
56
+ color?: OverlayColor;
57
+ /** 0-1, multiplied into whatever this element draws. Children carry their own. */
58
+ opacity?: number;
59
+ /** Cell height of one glyph in pixels; the 5x7 grid scales to it. Inherited by descendants. */
60
+ fontSize?: number;
61
+ /** Extra pixels between glyph cells, on top of the 5x7 grid's one-column gap. */
62
+ letterSpacing?: number;
63
+ /** Horizontal placement of the glyph run inside a `text` box that has a `width`. */
64
+ textAlign?: "left" | "center" | "right";
65
+ /** Paint order among siblings. Higher paints later. Ties fall back to tree order. */
66
+ zIndex?: number;
67
+ }
68
+
69
+ const STYLE_KEYS: ReadonlySet<string> = new Set<keyof IOverlayStyle>([
70
+ "left",
71
+ "right",
72
+ "top",
73
+ "bottom",
74
+ "centerX",
75
+ "centerY",
76
+ "width",
77
+ "height",
78
+ "padding",
79
+ "direction",
80
+ "gap",
81
+ "align",
82
+ "background",
83
+ "color",
84
+ "opacity",
85
+ "fontSize",
86
+ "letterSpacing",
87
+ "textAlign",
88
+ "zIndex",
89
+ ]);
90
+
91
+ /** Fail closed on an unsupported style key, naming it. Silently dropping it is how a HUD lies. */
92
+ export function assertKnownStyle(style: IOverlayStyle, elementType: string): void {
93
+ for (const key of Object.keys(style)) {
94
+ if (STYLE_KEYS.has(key)) continue;
95
+ throw new Error(
96
+ `TN_REACT_UNKNOWN_STYLE: <${elementType}> was given style '${key}', which the native overlay does not implement. Supported: ${[...STYLE_KEYS].join(", ")}.`,
97
+ );
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Every style key the overlay implements, for the templates' AGENTS.md and for error messages.
103
+ * @situation discover which React HUD style properties work on native
104
+ * @example supportedStyleKeys().includes("centerX")
105
+ */
106
+ export function supportedStyleKeys(): readonly string[] {
107
+ return [...STYLE_KEYS];
108
+ }
109
+
110
+ /** A resolved rectangle in screen pixels, origin top-left of the framebuffer. */
111
+ export interface IOverlayBox {
112
+ x: number;
113
+ y: number;
114
+ width: number;
115
+ height: number;
116
+ }
117
+
118
+ /** What the layout pass walks. The host config builds these; nothing else should. */
119
+ export interface ILayoutNode {
120
+ readonly kind: "view" | "text";
121
+ style: IOverlayStyle;
122
+ text: string;
123
+ children: ILayoutNode[];
124
+ /** Filled by {@link layoutTree}. */
125
+ box: IOverlayBox;
126
+ /** Font size actually used, after inheritance. Filled by {@link layoutTree}. */
127
+ resolvedFontSize: number;
128
+ }
129
+
130
+ /** Default cell height when no ancestor sets one. Small enough to be legible on a 1080p phone. */
131
+ const DEFAULT_FONT_SIZE = 14;
132
+
133
+ /**
134
+ * Width in pixels of a glyph run at a given cell height.
135
+ * @situation measure native React HUD text before laying it out
136
+ * @example const scoreWidth = measureText("SCORE 10", 24)
137
+ */
138
+ export function measureText(text: string, fontSize: number, letterSpacing = 0): number {
139
+ if (text.length === 0) return 0;
140
+ const cell = fontSize / GLYPH_HEIGHT;
141
+ const advance = GLYPH_ADVANCE * cell + letterSpacing;
142
+ return (text.length - 1) * advance + GLYPH_WIDTH * cell;
143
+ }
144
+
145
+ function intrinsicSize(node: ILayoutNode, fontSize: number): { width: number; height: number } {
146
+ const { style } = node;
147
+ if (node.kind === "text") {
148
+ return {
149
+ width: style.width ?? measureText(node.text, fontSize, style.letterSpacing ?? 0),
150
+ height: style.height ?? fontSize,
151
+ };
152
+ }
153
+ const padding = style.padding ?? 0;
154
+ const gap = style.gap ?? 0;
155
+ let contentWidth = 0;
156
+ let contentHeight = 0;
157
+ for (const [index, child] of node.children.entries()) {
158
+ const childFont = child.style.fontSize ?? fontSize;
159
+ const size = intrinsicSize(child, childFont);
160
+ if (style.direction === "row") {
161
+ contentWidth += size.width + (index > 0 ? gap : 0);
162
+ contentHeight = Math.max(contentHeight, size.height);
163
+ } else if (style.direction === "column") {
164
+ contentHeight += size.height + (index > 0 ? gap : 0);
165
+ contentWidth = Math.max(contentWidth, size.width);
166
+ } else {
167
+ // Absolute children: the box wraps whatever reaches furthest from its top-left.
168
+ contentWidth = Math.max(contentWidth, (child.style.left ?? 0) + size.width);
169
+ contentHeight = Math.max(contentHeight, (child.style.top ?? 0) + size.height);
170
+ }
171
+ }
172
+ return {
173
+ width: style.width ?? contentWidth + padding * 2,
174
+ height: style.height ?? contentHeight + padding * 2,
175
+ };
176
+ }
177
+
178
+ function crossOffset(align: IOverlayStyle["align"], available: number, size: number): number {
179
+ if (align === "center") return (available - size) / 2;
180
+ if (align === "end") return available - size;
181
+ return 0;
182
+ }
183
+
184
+ function place(node: ILayoutNode, content: IOverlayBox, size: { width: number; height: number }) {
185
+ const { style } = node;
186
+ let x: number;
187
+ if (style.centerX === true) x = content.x + (content.width - size.width) / 2;
188
+ else if (style.left !== undefined) x = content.x + style.left;
189
+ else if (style.right !== undefined) x = content.x + content.width - style.right - size.width;
190
+ else x = content.x;
191
+ let y: number;
192
+ if (style.centerY === true) y = content.y + (content.height - size.height) / 2;
193
+ else if (style.top !== undefined) y = content.y + style.top;
194
+ else if (style.bottom !== undefined) y = content.y + content.height - style.bottom - size.height;
195
+ else y = content.y;
196
+ node.box = { x, y, width: size.width, height: size.height };
197
+ }
198
+
199
+ /**
200
+ * Resolve every box in the tree against a root of `width` x `height` screen pixels.
201
+ *
202
+ * Two passes, both cheap and both non-recursive in cost terms: measure intrinsic sizes bottom-up,
203
+ * then assign positions top-down. It refuses nothing silently — a zero-sized root is a caller bug
204
+ * and throws, matching the framework's fail-closed rule.
205
+ */
206
+ export function layoutTree(root: ILayoutNode, width: number, height: number): void {
207
+ if (!(width > 0) || !(height > 0)) {
208
+ throw new Error(
209
+ `TN_REACT_LAYOUT_EMPTY_VIEWPORT: the overlay was laid out against ${width}x${height}. A zero-sized surface draws nothing and would look identical to a crash.`,
210
+ );
211
+ }
212
+ root.box = { x: 0, y: 0, width, height };
213
+ root.resolvedFontSize = root.style.fontSize ?? DEFAULT_FONT_SIZE;
214
+ arrange(root, root.resolvedFontSize);
215
+ }
216
+
217
+ function arrange(node: ILayoutNode, fontSize: number): void {
218
+ const { style } = node;
219
+ const padding = style.padding ?? 0;
220
+ const content: IOverlayBox = {
221
+ x: node.box.x + padding,
222
+ y: node.box.y + padding,
223
+ width: Math.max(0, node.box.width - padding * 2),
224
+ height: Math.max(0, node.box.height - padding * 2),
225
+ };
226
+ const gap = style.gap ?? 0;
227
+ let cursor = style.direction === "row" ? content.x : content.y;
228
+ for (const [index, child] of node.children.entries()) {
229
+ const childFont = child.style.fontSize ?? fontSize;
230
+ child.resolvedFontSize = childFont;
231
+ const size = intrinsicSize(child, childFont);
232
+ if (style.direction === "row") {
233
+ if (index > 0) cursor += gap;
234
+ child.box = {
235
+ x: cursor,
236
+ y: content.y + crossOffset(style.align, content.height, size.height),
237
+ width: size.width,
238
+ height: size.height,
239
+ };
240
+ cursor += size.width;
241
+ } else if (style.direction === "column") {
242
+ if (index > 0) cursor += gap;
243
+ child.box = {
244
+ x: content.x + crossOffset(style.align, content.width, size.width),
245
+ y: cursor,
246
+ width: size.width,
247
+ height: size.height,
248
+ };
249
+ cursor += size.height;
250
+ } else {
251
+ place(child, content, size);
252
+ }
253
+ arrange(child, childFont);
254
+ }
255
+ }
256
+
257
+ /** The x offset of a glyph run inside its own box, honouring `textAlign`. */
258
+ export function textOffset(node: ILayoutNode): number {
259
+ const runWidth = measureText(node.text, node.resolvedFontSize, node.style.letterSpacing ?? 0);
260
+ if (node.style.textAlign === "center") return (node.box.width - runWidth) / 2;
261
+ if (node.style.textAlign === "right") return node.box.width - runWidth;
262
+ return 0;
263
+ }
264
+
265
+ export { GLYPH_HEIGHT, GLYPH_WIDTH, GLYPH_ADVANCE };
package/src/react.ts ADDED
@@ -0,0 +1,60 @@
1
+ import { type ReactNode, createElement } from "react";
2
+ import { TEXT_ELEMENT, VIEW_ELEMENT } from "./react-host.js";
3
+ import type { IOverlayStyle } from "./react-layout.js";
4
+
5
+ /**
6
+ * `@threenative/core/react` — React that renders on a phone, with no DOM and no WebView.
7
+ *
8
+ * A subpath on purpose. `react` and `react-reconciler` are **optional** peers, and nothing in
9
+ * `@threenative/core`'s main entry imports either of them, so a game that never mounts a React
10
+ * overlay pays nothing and core stays consumable from React Three Fiber. Importing this module is
11
+ * the opt-in.
12
+ *
13
+ * The element vocabulary is two components, borrowed from React Native rather than invented:
14
+ * {@link View} is a rectangle, {@link Text} is a run of glyphs. They are components and not
15
+ * lowercase intrinsics because `view` and `text` are already SVG tags in `@types/react`, and a
16
+ * HUD element that silently means `<svg:text>` on one platform is exactly the kind of quiet
17
+ * divergence this path exists to end.
18
+ *
19
+ * @situation render a React HUD on Android or iOS without a WebView
20
+ * @situation show the same React component on web and on a phone
21
+ * @constraint styling is the `style` prop; Tailwind class names are CSS and cannot cross
22
+ * @constraint import `react`, never `react-dom`, from the portable native entry
23
+ * @example const overlay = createReactOverlay({ canvasLayer: ctx.canvasLayer });
24
+ */
25
+
26
+ export { createReactOverlay, TEXT_ELEMENT, VIEW_ELEMENT } from "./react-host.js";
27
+ export type { IReactOverlay, IReactOverlayOptions } from "./react-host.js";
28
+ export type { IOverlayBox, IOverlayStyle, OverlayColor } from "./react-layout.js";
29
+ export { measureText, supportedStyleKeys } from "./react-layout.js";
30
+ export { supportedGlyphs } from "./react-glyphs.js";
31
+
32
+ export interface IViewProps {
33
+ style?: IOverlayStyle;
34
+ children?: ReactNode;
35
+ }
36
+
37
+ export interface ITextProps {
38
+ style?: IOverlayStyle;
39
+ /** Strings and numbers only. Nesting an element inside `Text` has nothing to draw it with. */
40
+ children?: ReactNode;
41
+ }
42
+
43
+ /**
44
+ * A rectangle. Paints when its style has a `background`; otherwise it only positions children.
45
+ * @situation group and position native React HUD elements
46
+ * @example <View style={{ centerX: true, top: 24 }}><Text>READY</Text></View>
47
+ */
48
+ export function View(props: IViewProps): ReactNode {
49
+ return createElement(VIEW_ELEMENT, { style: props.style }, props.children);
50
+ }
51
+
52
+ /**
53
+ * A run of bitmap glyphs, drawn as one instanced quad per lit pixel.
54
+ * @situation show text in a native React HUD without a DOM
55
+ * @alias objective panel journal
56
+ * @example <Text style={{ color: "#ffffff", fontSize: 24 }}>SCORE 10</Text>
57
+ */
58
+ export function Text(props: ITextProps): ReactNode {
59
+ return createElement(TEXT_ELEMENT, { style: props.style }, props.children);
60
+ }
@@ -0,0 +1,159 @@
1
+ import type { Object3D } from "three";
2
+
3
+ /** The marker shared by alpha-antialiasing logs, playtests, and native diagnostics. */
4
+ export const ALPHA_ANTIALIASING_MARKER = "TN_ALPHA_ANTIALIASING";
5
+
6
+ export interface IAlphaAntialiasingReport {
7
+ /** True once at least one cutout material has been put on the coverage mask. */
8
+ readonly applied: boolean;
9
+ readonly marker: typeof ALPHA_ANTIALIASING_MARKER;
10
+ /** Empty when applied; otherwise why the convention did nothing, and what to change. */
11
+ readonly reason: string;
12
+ /** The sample count the decision was made against. One means there is no coverage mask. */
13
+ readonly sampleCount: number;
14
+ /** How many distinct cutout materials this renderer has converted. */
15
+ readonly materials: number;
16
+ }
17
+
18
+ /**
19
+ * The part of `THREE.Material` this reads. Structural rather than imported so a native adapter
20
+ * and a test stub are the same input as a `MeshStandardNodeMaterial`.
21
+ */
22
+ export interface IAlphaAntialiasingMaterial {
23
+ alphaHash?: boolean;
24
+ alphaTest?: number;
25
+ alphaTestNode?: unknown;
26
+ alphaToCoverage?: boolean;
27
+ transparent?: boolean;
28
+ }
29
+
30
+ /**
31
+ * A cutout is an opaque material whose silhouette is carved by an alpha test — and that is the one
32
+ * shape alpha-to-coverage is for. A transparent material is already resolved by sorting and
33
+ * blending, and taking its alpha for coverage would dither it instead; a material with no alpha
34
+ * test has no cutout edge to resolve.
35
+ */
36
+ function isCutout(material: IAlphaAntialiasingMaterial): boolean {
37
+ if (material.transparent === true || material.alphaHash === true) return false;
38
+ const threshold = material.alphaTest;
39
+ return (
40
+ (typeof threshold === "number" && threshold > 0) ||
41
+ (material.alphaTestNode !== undefined && material.alphaTestNode !== null)
42
+ );
43
+ }
44
+
45
+ function isTraversable(
46
+ value: unknown,
47
+ ): value is { traverse(callback: (child: unknown) => void): void } {
48
+ return (
49
+ typeof value === "object" &&
50
+ value !== null &&
51
+ typeof (value as { traverse?: unknown }).traverse === "function"
52
+ );
53
+ }
54
+
55
+ /**
56
+ * Alpha antialiasing: resolve alpha-tested silhouettes through the multisample coverage mask.
57
+ * Godot's `alpha_antialiasing_mode`, in Three.js's `alphaToCoverage`.
58
+ *
59
+ * MSAA antialiases triangle edges. A leaf, a fern, a chain-link fence and a hair card have no
60
+ * triangle edge to antialias — the silhouette is carved *inside* the triangle by `discard`, which
61
+ * is all-or-nothing per pixel however many samples the target holds. So a game can own a 4x
62
+ * multisampled target, pay its bandwidth every frame, and still draw a distant tree line as a
63
+ * black-and-white stipple. `alphaToCoverage` is what spends that target on cutouts: three swaps
64
+ * the binary discard for a screen-space-derivative smoothstep and hands the result to the hardware
65
+ * coverage mask, so a leaf edge can land on one, two, three or four of the samples already
66
+ * allocated. No new target, no second pass, no extra memory.
67
+ *
68
+ * Which is why the coupling is the framework's and not the game's. The flag itself is one line of
69
+ * plain Three.js, but it is a silent no-op — worse, a fattened silhouette — unless the surface
70
+ * being drawn is multisampled, and the sample count is the renderer's answer on a seam that
71
+ * differs between the browser and the native host. A game cannot portably ask. So the engine
72
+ * couples the two, ships it on, and reports it: turning the convention off does not turn its
73
+ * measurement off, and neither does refusing it.
74
+ */
75
+ export class AlphaAntialiasing {
76
+ readonly #converted = new WeakSet<object>();
77
+ readonly #enabled: boolean;
78
+ readonly #report: (line: string) => void;
79
+ readonly #sampleCount: () => number;
80
+ #announced = false;
81
+ #armed: boolean | undefined;
82
+ #materials = 0;
83
+
84
+ constructor(options: {
85
+ readonly enabled: boolean;
86
+ readonly report: (line: string) => void;
87
+ readonly sampleCount: () => number;
88
+ }) {
89
+ this.#enabled = options.enabled;
90
+ this.#report = options.report;
91
+ this.#sampleCount = options.sampleCount;
92
+ }
93
+
94
+ /**
95
+ * Convert every cutout material under a root, then announce the decision once.
96
+ *
97
+ * Called from the renderer's warm-up, which is the point that matters: three builds a pipeline
98
+ * from `alphaToCoverage` and rebuilds it when the flag moves, so a convention applied at draw
99
+ * time would throw away exactly the warm-up it was applied during. Cheap to repeat — a material
100
+ * is looked at once ever.
101
+ */
102
+ convertTree(root: unknown): void {
103
+ if (this.#active() && isTraversable(root)) {
104
+ root.traverse((child) => {
105
+ const material = (child as Object3D & Record<string, unknown>).material;
106
+ if (Array.isArray(material)) for (const one of material) this.convertMaterial(one);
107
+ else this.convertMaterial(material);
108
+ });
109
+ }
110
+ this.#announce();
111
+ }
112
+
113
+ /**
114
+ * Convert one material as the renderer is about to draw with it, which is how content that
115
+ * streams in after warm-up is caught. Its pipeline is being built for the first time either way,
116
+ * so there is nothing to rebuild. Per draw call, and a `WeakSet` hit after the first sight.
117
+ */
118
+ convertMaterial(material: unknown): void {
119
+ if (!this.#active()) return;
120
+ if (typeof material !== "object" || material === null) return;
121
+ if (this.#converted.has(material)) return;
122
+ this.#converted.add(material);
123
+ const candidate = material as IAlphaAntialiasingMaterial;
124
+ if (!isCutout(candidate) || candidate.alphaToCoverage === true) return;
125
+ candidate.alphaToCoverage = true;
126
+ this.#materials += 1;
127
+ }
128
+
129
+ report(): IAlphaAntialiasingReport {
130
+ const sampleCount = this.#sampleCount();
131
+ return {
132
+ applied: this.#materials > 0,
133
+ marker: ALPHA_ANTIALIASING_MARKER,
134
+ materials: this.#materials,
135
+ reason: this.#reason(sampleCount),
136
+ sampleCount,
137
+ };
138
+ }
139
+
140
+ #reason(sampleCount: number): string {
141
+ if (this.#materials > 0) return "";
142
+ if (!this.#enabled) return "renderer.alphaAntialiasing is false";
143
+ if (sampleCount < 2)
144
+ return "the surface is single-sampled, so there is no coverage mask for a cutout edge to resolve into; set renderer.antialias (or renderer.android.antialias) true to give it one";
145
+ return "no cutout material has been drawn; nothing in this scene carves its silhouette with an alpha test";
146
+ }
147
+
148
+ /** True while the convention can still do something. The sample count cannot move after boot. */
149
+ #active(): boolean {
150
+ this.#armed ??= this.#enabled && this.#sampleCount() > 1;
151
+ return this.#armed;
152
+ }
153
+
154
+ #announce(): void {
155
+ if (this.#announced) return;
156
+ this.#announced = true;
157
+ this.#report(`${ALPHA_ANTIALIASING_MARKER}:${JSON.stringify(this.report())}`);
158
+ }
159
+ }
@@ -0,0 +1,126 @@
1
+ import { BatchedMesh, DataTexture, type Matrix4, type Texture } from "three";
2
+
3
+ const THREE_NATIVE_BATCHED_VELOCITY_PATCH = "threeNativeBatchedVelocityPatch";
4
+
5
+ interface IBatchedMeshVelocityState {
6
+ _matricesTexture: Texture | null;
7
+ _previousMatricesTexture?: Texture;
8
+ }
9
+
10
+ interface IBatchedMatrixImage {
11
+ readonly data: Float32Array;
12
+ readonly height: number;
13
+ readonly width: number;
14
+ }
15
+
16
+ /**
17
+ * Whether the installed Three.js build contains the BatchedMesh previous-position accessor.
18
+ * Published core can be installed without this repository's pnpm root, so the projection must
19
+ * keep material batches on the exact proxy lane when a consumer has not applied the patch.
20
+ */
21
+ export function isBatchedMeshVelocityPatched(): boolean {
22
+ return Reflect.get(BatchedMesh, THREE_NATIVE_BATCHED_VELOCITY_PATCH) === true;
23
+ }
24
+
25
+ function state(mesh: BatchedMesh): IBatchedMeshVelocityState {
26
+ return mesh as BatchedMesh & IBatchedMeshVelocityState;
27
+ }
28
+
29
+ /**
30
+ * Allocates the previous-matrix texture only for a batch whose material actually needs velocity.
31
+ * The clone is deliberately separate from `_matricesTexture`: GPU uploads to the current frame
32
+ * must not race the previous-frame sample in the velocity pass.
33
+ */
34
+ export function ensureBatchedMeshVelocity(mesh: BatchedMesh): void {
35
+ const current = state(mesh)._matricesTexture;
36
+ if (current === null) throw new Error("BatchedMesh has no current matrix texture.");
37
+ if (state(mesh)._previousMatricesTexture !== undefined) return;
38
+ const image = matrixImage(current);
39
+ const previous = new DataTexture(
40
+ image.data.slice(),
41
+ image.width,
42
+ image.height,
43
+ current.format as ConstructorParameters<typeof DataTexture>[3],
44
+ current.type,
45
+ );
46
+ previous.minFilter = current.minFilter;
47
+ previous.magFilter = current.magFilter;
48
+ previous.wrapS = current.wrapS;
49
+ previous.wrapT = current.wrapT;
50
+ previous.flipY = current.flipY;
51
+ previous.unpackAlignment = current.unpackAlignment;
52
+ previous.colorSpace = current.colorSpace;
53
+ previous.needsUpdate = true;
54
+ state(mesh)._previousMatricesTexture = previous;
55
+ }
56
+
57
+ /**
58
+ * Writes one sub-draw's previous value before updating its current matrix. A new slot receives
59
+ * its current matrix as its previous value, producing zero velocity for its first visible frame.
60
+ */
61
+ export function setBatchedMeshMatrixWithVelocity(
62
+ mesh: BatchedMesh,
63
+ instanceId: number,
64
+ current: Matrix4,
65
+ previous: Matrix4,
66
+ ): void {
67
+ setBatchedMeshPreviousMatrix(mesh, instanceId, previous);
68
+ mesh.setMatrixAt(instanceId, current);
69
+ }
70
+
71
+ /**
72
+ * Advances one sub-draw's previous value for the next velocity pass without rewriting its current
73
+ * matrix. This is called for every live slot on every projected frame, including unchanged slots;
74
+ * otherwise a slot that moved once would keep reporting that move forever.
75
+ */
76
+ export function setBatchedMeshPreviousMatrix(
77
+ mesh: BatchedMesh,
78
+ instanceId: number,
79
+ previous: Matrix4,
80
+ ): void {
81
+ ensureBatchedMeshVelocity(mesh);
82
+ const previousTexture = state(mesh)._previousMatricesTexture as Texture;
83
+ previous.toArray(matrixImage(previousTexture).data, instanceId * 16);
84
+ previousTexture.needsUpdate = true;
85
+ }
86
+
87
+ /** Writes the complete per-sub-draw previous frame without touching the current matrix texture. */
88
+ export function setBatchedMeshPreviousMatrices(
89
+ mesh: BatchedMesh,
90
+ previous: ArrayLike<number>,
91
+ ): void {
92
+ ensureBatchedMeshVelocity(mesh);
93
+ const previousTexture = state(mesh)._previousMatricesTexture as Texture;
94
+ const image = matrixImage(previousTexture);
95
+ if (previous.length !== image.data.length) {
96
+ throw new Error(
97
+ `BatchedMesh previous matrix length ${String(previous.length)} does not match ${String(image.data.length)}.`,
98
+ );
99
+ }
100
+ image.data.set(previous);
101
+ previousTexture.needsUpdate = true;
102
+ }
103
+
104
+ /** Releases the extra texture owned by the material-batching lane. */
105
+ export function disposeBatchedMeshVelocity(mesh: BatchedMesh): void {
106
+ const previous = state(mesh)._previousMatricesTexture;
107
+ previous?.dispose();
108
+ state(mesh)._previousMatricesTexture = undefined;
109
+ }
110
+
111
+ /** Returns the previous texture for focused conformance tests and renderer adapters. */
112
+ export function readBatchedMeshPreviousMatrices(mesh: BatchedMesh): Texture | undefined {
113
+ return state(mesh)._previousMatricesTexture;
114
+ }
115
+
116
+ function matrixImage(texture: Texture): IBatchedMatrixImage {
117
+ const image = texture.image as Partial<IBatchedMatrixImage>;
118
+ if (
119
+ !(image.data instanceof Float32Array) ||
120
+ !Number.isInteger(image.width) ||
121
+ !Number.isInteger(image.height)
122
+ ) {
123
+ throw new Error("BatchedMesh matrix texture must contain a Float32Array image.");
124
+ }
125
+ return image as IBatchedMatrixImage;
126
+ }