@threenative/three-native 0.0.0-stage → 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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -2
  3. package/package.json +42 -3
  4. package/src/addons/buffer-geometry-utils.ts +14 -0
  5. package/src/addons/data-utils.ts +63 -0
  6. package/src/addons/decal-geometry.ts +25 -0
  7. package/src/addons/decal.ts +218 -0
  8. package/src/addons/gltf-loader-web.ts +323 -0
  9. package/src/addons/hdr-loader.ts +71 -0
  10. package/src/addons/hdr.ts +139 -0
  11. package/src/addons/lut-cube-loader-web.ts +17 -0
  12. package/src/addons/lut-cube-loader.ts +149 -0
  13. package/src/addons/merge-geometries.ts +374 -0
  14. package/src/addons/mesh-bvh-webgpu.ts +13 -0
  15. package/src/addons/mesh-bvh.ts +50 -0
  16. package/src/addons/post-effects-web.ts +22 -0
  17. package/src/addons/post-effects.ts +173 -0
  18. package/src/audio.ts +564 -0
  19. package/src/blend-mode.ts +33 -0
  20. package/src/browser-backend.ts +2156 -0
  21. package/src/browser-entry.ts +305 -0
  22. package/src/browser-math.ts +448 -0
  23. package/src/browser-renderer.ts +527 -0
  24. package/src/browser-tsl.ts +650 -0
  25. package/src/catalog.ts +497 -0
  26. package/src/fixture-format.ts +721 -0
  27. package/src/fixture-native.ts +426 -0
  28. package/src/fixture-protocol.ts +315 -0
  29. package/src/math-utils.ts +65 -0
  30. package/src/object-surface.ts +250 -0
  31. package/src/pass-node.ts +286 -0
  32. package/src/property-binding.ts +93 -0
  33. package/src/quad-mesh.ts +54 -0
  34. package/src/reflector.ts +89 -0
  35. package/src/refused.ts +27 -0
  36. package/src/render-target.ts +107 -0
  37. package/src/rtt.ts +158 -0
  38. package/src/shadow-map.ts +21 -0
  39. package/src/storage.ts +206 -0
  40. package/src/texture-sources.ts +252 -0
  41. package/src/tsl-extras.ts +51 -0
  42. package/src/tsl-struct.ts +20 -0
  43. package/src/tsl-uniforms.ts +234 -0
  44. package/src/update-ranges.ts +109 -0
  45. package/src/wgsl-fn.ts +55 -0
@@ -0,0 +1,286 @@
1
+ /**
2
+ * three's `pass(scene, camera)`, `mrt()` and the MRT slots over the engine's own scene pass, for both
3
+ * back ends (the V8 player and the Wasm engine). The engine draws one scene pass whose targets are
4
+ * the renderer's colour ("output"), depth and, with an MRT that asks for it, view normals; a pass's
5
+ * texture nodes name those targets. `normalView` is the engine's TSL node, as in three, so a graph
6
+ * reads it and `mrt({ normal: normalView })` names the normal target by that node's identity.
7
+ *
8
+ * Which pass is the frame's is fixed by how it is made, never by when: `pass(scene, camera)` (the
9
+ * call a world environment makes, and the one core re-aims at the frame's root every frame) is the
10
+ * frame pass and the only one that publishes a scene. `new PassNode(PassNode.COLOR, scene, camera)`
11
+ * is an offscreen pass: it owns a HalfFloat RenderTarget of floor(surface * resolutionScale), is
12
+ * drawn into it each frame before the frame samples it (`updateSecondaryPasses`), and never
13
+ * publishes. The two cannot be told apart by scene at construction, because a pass hands out its
14
+ * texture node before any frame has named the frame's scene.
15
+ */
16
+
17
+ const HALF_FLOAT_TYPE = 1016; // three's HalfFloatType
18
+
19
+ interface ISurface {
20
+ readonly width: number;
21
+ readonly height: number;
22
+ }
23
+
24
+ interface IPassTarget {
25
+ readonly texture: unknown;
26
+ readonly width: number;
27
+ readonly height: number;
28
+ setSize(width: number, height: number): void;
29
+ dispose(): void;
30
+ }
31
+
32
+ /** What an offscreen pass needs of a back end: its RenderTarget, and the surface before a first frame. */
33
+ export interface IPassHost {
34
+ // quality-allow: three's class name, so a back end passes its class map.
35
+ // biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
36
+ RenderTarget: new (
37
+ width: number,
38
+ height: number,
39
+ options: { type: number },
40
+ ) => IPassTarget;
41
+ surface?(): ISurface;
42
+ }
43
+
44
+ /** Draws `scene` through `camera` into `target`, at the call. */
45
+ export type PassDraw = (target: IPassTarget, scene: unknown, camera: unknown) => void;
46
+
47
+ interface IPassTsl {
48
+ texture(source: unknown, uv: unknown): unknown;
49
+ uv(): unknown;
50
+ readonly normalView: unknown;
51
+ }
52
+
53
+ interface IMRTSlot {
54
+ readonly isMRTSlot: true;
55
+ readonly name: string;
56
+ }
57
+
58
+ interface IMRTNode {
59
+ readonly isMRTNode: true;
60
+ readonly outputs: Readonly<Record<string, unknown>>;
61
+ /**
62
+ * three's per-output blend state. The engine's scene pass keeps the material's own blending on
63
+ * every target, so a mode is recorded for `getBlendMode` and not applied to the target.
64
+ */
65
+ readonly blendModes: Record<string, unknown>;
66
+ setBlendMode(name: string, blend: unknown): IMRTNode;
67
+ getBlendMode(name: string): unknown;
68
+ }
69
+
70
+ /**
71
+ * three's templates write the normal target as `vec4(normalView, 0)`: the zero alpha, with a
72
+ * `BlendMode(MaterialBlending)` on the output, keeps the opaque normal under a transparent card. The
73
+ * engine's normal target holds the view normal itself, so that spelling names the same target.
74
+ * `vec4` is the back end's own constructor; its result for `(normalView, 0)` carries the marker
75
+ * `mrt()` reads, every other call is untouched.
76
+ */
77
+ export function markNormalTarget<T extends (...args: never[]) => object>(
78
+ vec4: T,
79
+ normalView: unknown,
80
+ ): T {
81
+ return ((...args: unknown[]) => {
82
+ // quality-allow: the back end's vec4 is called with its untyped argument list, as three's own TSL does.
83
+ const node = (vec4 as unknown as (...a: unknown[]) => object)(...args);
84
+ if (args.length === 2 && args[0] === normalView && args[1] === 0)
85
+ Object.defineProperty(node, "__tnNormalView", { value: normalView });
86
+ return node;
87
+ // quality-allow: the wrapper is returned as the same call signature T it wraps.
88
+ }) as unknown as T;
89
+ }
90
+
91
+ /**
92
+ * `onTarget(scene, camera)` hears where a pass points (the V8 player draws that scene); a back end that
93
+ * draws the renderer's last scene passes none.
94
+ */
95
+ export function definePass(
96
+ tsl: IPassTsl,
97
+ onTarget?: (scene: unknown, camera: unknown) => void,
98
+ host?: IPassHost,
99
+ ) {
100
+ const slot = (name: string): IMRTSlot => Object.freeze({ isMRTSlot: true, name });
101
+ const output = slot("output");
102
+ const normalView = tsl.normalView;
103
+ const metalness = slot("metalness");
104
+ const roughness = slot("roughness");
105
+
106
+ function mrt(outputs: Record<string, unknown>): IMRTNode {
107
+ const named: Record<string, unknown> = {};
108
+ for (const [name, value] of Object.entries(outputs)) {
109
+ const normal =
110
+ name === "normal" &&
111
+ (value === normalView ||
112
+ (value as { __tnNormalView?: unknown } | null)?.__tnNormalView === normalView);
113
+ if (
114
+ !normal &&
115
+ ((value as IMRTSlot | null)?.isMRTSlot !== true || name !== (value as IMRTSlot).name)
116
+ )
117
+ throw new Error(
118
+ `TN_NATIVE_MRT_UNSUPPORTED: ${name} must be one of output, normal: normalView or vec4(normalView, 0), metalness, roughness`,
119
+ );
120
+ named[name] = normal ? normalView : value;
121
+ }
122
+ const node: IMRTNode = Object.freeze({
123
+ isMRTNode: true as const,
124
+ outputs: Object.freeze(named),
125
+ blendModes: {} as Record<string, unknown>,
126
+ setBlendMode(name: string, blend: unknown): IMRTNode {
127
+ node.blendModes[name] = blend;
128
+ return node;
129
+ },
130
+ getBlendMode: (name: string): unknown => node.blendModes[name],
131
+ });
132
+ return node;
133
+ }
134
+
135
+ const framePass = Symbol("tn.framePass");
136
+ const drawPass = Symbol("tn.drawPass");
137
+ interface IOffscreen {
138
+ [drawPass](surface: ISurface, draw: PassDraw): void;
139
+ }
140
+ const offscreen = new Set<IOffscreen>();
141
+ let lastSurface: ISurface | undefined;
142
+
143
+ class PassNode implements IOffscreen {
144
+ static readonly COLOR = "color";
145
+ static readonly DEPTH = "depth";
146
+ readonly isPassNode = true;
147
+ #mrt: IMRTNode | null = null;
148
+ #scene: unknown;
149
+ #camera: unknown;
150
+ #scale = 1;
151
+ #target: IPassTarget | null = null;
152
+ #offscreen: boolean;
153
+ #disposed = false;
154
+
155
+ constructor(scope: unknown, scene: unknown, camera: unknown) {
156
+ this.#scene = scene;
157
+ this.#camera = camera;
158
+ this.#offscreen = scope !== framePass;
159
+ if (!this.#offscreen) {
160
+ onTarget?.(scene, camera);
161
+ return;
162
+ }
163
+ if (scope !== PassNode.COLOR)
164
+ throw new Error(
165
+ `TN_NATIVE_PASS_SCOPE_UNSUPPORTED: an offscreen PassNode draws colour only, not '${String(scope)}'`,
166
+ );
167
+ if (host === undefined)
168
+ throw new Error("TN_NATIVE_PASS_HOST: this back end has no RenderTarget for a PassNode");
169
+ this.#target = new host.RenderTarget(1, 1, { type: HALF_FLOAT_TYPE });
170
+ this.#resize(lastSurface ?? host.surface?.());
171
+ offscreen.add(this);
172
+ }
173
+
174
+ get scene(): unknown {
175
+ return this.#scene;
176
+ }
177
+ set scene(value: unknown) {
178
+ this.#scene = value;
179
+ if (!this.#offscreen) onTarget?.(value, this.#camera);
180
+ }
181
+ get camera(): unknown {
182
+ return this.#camera;
183
+ }
184
+ set camera(value: unknown) {
185
+ this.#camera = value;
186
+ if (!this.#offscreen) onTarget?.(this.#scene, value);
187
+ }
188
+
189
+ /** The offscreen pass's real target, so its width and height are the allocated size. */
190
+ get renderTarget(): IPassTarget | undefined {
191
+ return this.#target ?? undefined;
192
+ }
193
+
194
+ setResolutionScale(scale: number): this {
195
+ if (!this.#offscreen)
196
+ throw new Error(
197
+ "TN_NATIVE_PASS_RESOLUTION_UNSUPPORTED: the frame pass draws at the surface size; only an offscreen PassNode scales",
198
+ );
199
+ if (!Number.isFinite(scale) || scale <= 0)
200
+ throw new Error(`TN_NATIVE_PASS_RESOLUTION_SCALE: expected a number above 0, got ${scale}`);
201
+ this.#scale = scale;
202
+ this.#resize(lastSurface ?? host?.surface?.());
203
+ return this;
204
+ }
205
+
206
+ getResolutionScale(): number {
207
+ return this.#scale;
208
+ }
209
+
210
+ #resize(surface: ISurface | undefined): void {
211
+ const target = this.#target;
212
+ if (target === null || surface === undefined) return;
213
+ const width = Math.max(1, Math.floor(surface.width * this.#scale));
214
+ const height = Math.max(1, Math.floor(surface.height * this.#scale));
215
+ if (width !== target.width || height !== target.height) target.setSize(width, height);
216
+ }
217
+
218
+ [drawPass](surface: ISurface, draw: PassDraw): void {
219
+ if (this.#target === null) return;
220
+ this.#resize(surface);
221
+ draw(this.#target, this.#scene, this.#camera);
222
+ }
223
+
224
+ setMRT(value: IMRTNode | null): this {
225
+ if (value !== null && value?.isMRTNode !== true)
226
+ throw new Error("TN_NATIVE_MRT_UNSUPPORTED: setMRT takes mrt()");
227
+ if (value !== null && this.#offscreen)
228
+ throw new Error("TN_NATIVE_MRT_UNSUPPORTED: an offscreen PassNode draws colour only");
229
+ this.#mrt = value;
230
+ return this;
231
+ }
232
+
233
+ getMRT(): IMRTNode | null {
234
+ return this.#mrt;
235
+ }
236
+
237
+ getTextureNode(name = "output"): unknown {
238
+ if (this.#offscreen) {
239
+ if (this.#target === null)
240
+ throw new Error("TN_NATIVE_PASS_DISPOSED: getTextureNode() after dispose()");
241
+ if (name !== "output")
242
+ throw new Error(
243
+ `TN_NATIVE_PASS_TEXTURE_UNSUPPORTED: an offscreen PassNode has no '${name}' target`,
244
+ );
245
+ return tsl.texture(this.#target.texture, tsl.uv());
246
+ }
247
+ if (name === "output") return tsl.texture({ name: "scene" }, tsl.uv());
248
+ if (name === "depth") return tsl.texture({ name: "depth" }, tsl.uv());
249
+ if (name === "normal" && this.#mrt?.outputs.normal === normalView)
250
+ return tsl.texture({ name: "normal" }, tsl.uv());
251
+ throw new Error(
252
+ `TN_NATIVE_PASS_TEXTURE_UNSUPPORTED: the native scene pass has no '${name}' target`,
253
+ );
254
+ }
255
+
256
+ /** Releases an offscreen pass's target and stops drawing it. The frame pass owns nothing to release. */
257
+ dispose(): void {
258
+ if (this.#disposed) return;
259
+ this.#disposed = true;
260
+ offscreen.delete(this);
261
+ this.#target?.dispose();
262
+ this.#target = null;
263
+ }
264
+ }
265
+
266
+ const pass = (scene: unknown, camera: unknown): PassNode =>
267
+ new PassNode(framePass, scene, camera);
268
+
269
+ /**
270
+ * Draws every live offscreen pass into its target, at the surface size, before the frame that
271
+ * samples them. A back end calls it once per frame with its drawing buffer and its target draw;
272
+ * with no offscreen pass it reads neither.
273
+ */
274
+ function updateSecondaryPasses(surface: () => ISurface, draw: PassDraw): void {
275
+ if (offscreen.size === 0) return;
276
+ const { width, height } = surface();
277
+ if (!(width >= 1 && height >= 1))
278
+ throw new Error(
279
+ `TN_NATIVE_PASS_SURFACE: the surface is ${width}x${height}; an offscreen PassNode needs a real size`,
280
+ );
281
+ lastSurface = { width, height };
282
+ for (const entry of [...offscreen]) entry[drawPass](lastSurface, draw);
283
+ }
284
+
285
+ return { pass, PassNode, updateSecondaryPasses, mrt, output, normalView, metalness, roughness };
286
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * three's PropertyBinding and console function over the engine's PropertyBinding, for both back ends
3
+ * (the V8 player and the Wasm engine). The engine binds; this keeps three's JS surface: the static
4
+ * `parseTrackName` and `findNode`, `targetObject` as a property, and a failed bind reported through
5
+ * `setConsoleFunction`'s function (three's utils `error()`), or `console.error` without one.
6
+ */
7
+
8
+ type ConsoleFunction = (type: string, message: string, ...params: unknown[]) => void;
9
+
10
+ interface IEngineBinding {
11
+ bind(): string;
12
+ __bind?(): [string, unknown];
13
+ unbind(): void;
14
+ targetObject(): unknown;
15
+ parseTrackName(path: string): Record<string, string | undefined>;
16
+ findNode(root: unknown, nodeName?: string): unknown;
17
+ }
18
+
19
+ type EngineClass = (new (...args: unknown[]) => object) & Record<string, unknown>;
20
+
21
+ export function definePropertyBinding(Native: EngineClass) {
22
+ let consoleFunction: ConsoleFunction | null = null;
23
+ const prototype = Native.prototype as IEngineBinding;
24
+ const bind = prototype.bind;
25
+ const bindWithTarget = prototype.__bind;
26
+ const unbind = prototype.unbind;
27
+ const target = prototype.targetObject;
28
+ // Games bind every track of every clip while they load: `__bind` answers the reason and the target
29
+ // in one engine call, and the target is kept until the next bind or unbind. A path's parse depends
30
+ // on the path alone, so each is parsed once.
31
+ const targets = new WeakMap<object, unknown>();
32
+ const parsed = new Map<string, Record<string, string | undefined>>();
33
+ // One engine object with no root answers the statics.
34
+ let helper: IEngineBinding | undefined;
35
+ const statics = (): IEngineBinding => {
36
+ // quality-allow: Native engine PropertyBinding constructor produces instance satisfying IEngineBinding interface.
37
+ helper ??= new Native() as unknown as IEngineBinding;
38
+ return helper;
39
+ };
40
+
41
+ Object.defineProperties(prototype, {
42
+ bind: {
43
+ configurable: true,
44
+ writable: true,
45
+ value(this: IEngineBinding): void {
46
+ let reason: string;
47
+ if (bindWithTarget === undefined) reason = bind.call(this);
48
+ else {
49
+ const [text, object] = bindWithTarget.call(this);
50
+ reason = text;
51
+ targets.set(this, object);
52
+ }
53
+ if (reason === "") return;
54
+ if (consoleFunction !== null) consoleFunction("error", reason);
55
+ else console.error(reason);
56
+ },
57
+ },
58
+ targetObject: {
59
+ configurable: true,
60
+ get(this: IEngineBinding): unknown {
61
+ return targets.has(this) ? targets.get(this) : target.call(this);
62
+ },
63
+ },
64
+ unbind: {
65
+ configurable: true,
66
+ writable: true,
67
+ value(this: IEngineBinding): void {
68
+ targets.delete(this);
69
+ unbind.call(this);
70
+ },
71
+ },
72
+ });
73
+ Object.assign(Native, {
74
+ parseTrackName: (path: string) => {
75
+ let known = parsed.get(path);
76
+ if (known === undefined) {
77
+ known = statics().parseTrackName(path);
78
+ parsed.set(path, known);
79
+ }
80
+ return { ...known };
81
+ },
82
+ findNode: (root: unknown, nodeName?: string) => statics().findNode(root, nodeName),
83
+ });
84
+
85
+ const PropertyBinding = Native;
86
+ return {
87
+ PropertyBinding,
88
+ getConsoleFunction: (): ConsoleFunction | null => consoleFunction,
89
+ setConsoleFunction: (fn: ConsoleFunction | null | undefined): void => {
90
+ consoleFunction = fn ?? null;
91
+ },
92
+ };
93
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * three r185's QuadMesh (src/renderers/common/QuadMesh.js) over the engine's own Mesh, shared by both
3
+ * back ends (PRD-551): a Mesh over one fullscreen triangle, drawn through a fixed orthographic camera
4
+ * by `renderer.render(quad, camera)`, so it fills whatever the renderer draws into (a render target).
5
+ */
6
+
7
+ type Constructor = new (...args: unknown[]) => object;
8
+
9
+ type EngineClasses = Readonly<
10
+ Record<"Mesh" | "BufferGeometry" | "Float32BufferAttribute" | "OrthographicCamera", Constructor>
11
+ >;
12
+
13
+ export function defineQuadMesh(classes: EngineClasses) {
14
+ // Built on first use, as three builds its module-level geometry and camera once.
15
+ let shared: { geometry: object; camera: object } | undefined;
16
+ const quad = () => {
17
+ if (shared === undefined) {
18
+ const geometry = new classes.BufferGeometry() as {
19
+ setAttribute(name: string, attribute: object): void;
20
+ };
21
+ geometry.setAttribute(
22
+ "position",
23
+ new classes.Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3),
24
+ );
25
+ geometry.setAttribute("uv", new classes.Float32BufferAttribute([0, -1, 0, 1, 2, 1], 2));
26
+ shared = { geometry, camera: new classes.OrthographicCamera(-1, 1, 1, -1, 0, 1) };
27
+ }
28
+ return shared;
29
+ };
30
+ const Mesh = classes.Mesh as new (geometry: object, material?: unknown) => object;
31
+
32
+ return class QuadMesh extends Mesh {
33
+ readonly isQuadMesh = true;
34
+ readonly camera: object;
35
+
36
+ constructor(material: unknown = null) {
37
+ // three passes `null`; the engine Mesh takes its default material until one is assigned.
38
+ super(quad().geometry, material ?? undefined);
39
+ this.camera = quad().camera;
40
+ }
41
+
42
+ render(renderer: { render(scene: unknown, camera: unknown): void }): void {
43
+ renderer.render(this, this.camera);
44
+ }
45
+
46
+ async renderAsync(renderer: {
47
+ init(): Promise<unknown>;
48
+ render(scene: unknown, camera: unknown): void;
49
+ }): Promise<void> {
50
+ await renderer.init();
51
+ this.render(renderer);
52
+ }
53
+ };
54
+ }
@@ -0,0 +1,89 @@
1
+ // Ported from three.js r185 (three@0.185.1). The MIT License, Copyright © 2010-2026 three.js authors.
2
+ /**
3
+ * three's TSL `reflector(parameters)` over an engine back end, for both: the browser-JS one and the
4
+ * V8 facade. The engine draws the mirrored pass itself, before the frame that samples it, so the
5
+ * node it returns carries upstream's parameters and `target`, but no JS `updateBefore`.
6
+ *
7
+ * Two differences are structural. The engine keeps one virtual camera per reflector, where three
8
+ * keeps one per scene camera, so `getVirtualCamera(camera)` returns it for every camera. And a
9
+ * function assigned over `getVirtualCamera` (WaterSurface3D sets the reflection's layers that way)
10
+ * runs once, at assignment, against that camera, since the engine never calls back into JS for it.
11
+ * `updateBefore` cannot be read or replaced: a game that wraps it would otherwise run no code at all.
12
+ */
13
+
14
+ /** ReflectorNode's parameters, as upstream reads them. */
15
+ export interface IReflectorParameters {
16
+ readonly target?: object;
17
+ readonly resolutionScale?: number;
18
+ /** @deprecated r180 name of resolutionScale. */
19
+ readonly resolution?: number;
20
+ readonly generateMipmaps?: boolean;
21
+ readonly bounces?: boolean;
22
+ readonly depth?: boolean;
23
+ readonly samples?: number;
24
+ }
25
+
26
+ /** The engine classes the reflector builds its target and virtual camera from. */
27
+ export interface IReflectorClasses {
28
+ // quality-allow: three's PascalCase class name passed in engine constructor map.
29
+ // biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
30
+ readonly Object3D: new () => object;
31
+ // quality-allow: three's PascalCase class name passed in engine constructor map.
32
+ // biome-ignore lint/style/useNamingConvention: see Object3D.
33
+ readonly PerspectiveCamera: new () => object;
34
+ }
35
+
36
+ type NativeReflector = (...args: unknown[]) => object;
37
+
38
+ const UPDATE_HOOK =
39
+ "TN_NATIVE_REFLECTOR_UPDATE_HOOK: the engine draws the reflection pass natively; updateBefore cannot be read or replaced";
40
+
41
+ /** Returns three's `reflector` over the engine's TSL `reflector(target, camera, ...)` call. */
42
+ export function defineReflector(native: NativeReflector, classes: IReflectorClasses) {
43
+ return function reflector(parameters: IReflectorParameters = {}): object {
44
+ const target = parameters.target ?? new classes.Object3D();
45
+ const resolutionScale = parameters.resolutionScale ?? parameters.resolution ?? 1;
46
+ const { generateMipmaps = false, bounces = true, depth = false, samples = 0 } = parameters;
47
+ const camera = new classes.PerspectiveCamera();
48
+ const node = native(
49
+ target,
50
+ camera,
51
+ resolutionScale,
52
+ bounces ? 1 : 0,
53
+ generateMipmaps ? 1 : 0,
54
+ depth ? 1 : 0,
55
+ samples,
56
+ );
57
+ let getVirtualCamera: (camera?: object) => object = () => camera;
58
+ const base = {
59
+ target,
60
+ resolutionScale,
61
+ generateMipmaps,
62
+ bounces,
63
+ depth,
64
+ samples,
65
+ // three's NodeUpdateType.NONE: no JS update runs, so a caller can tell before it wraps one.
66
+ updateBeforeType: "none",
67
+ get getVirtualCamera() {
68
+ return getVirtualCamera;
69
+ },
70
+ set getVirtualCamera(wrapper: (camera?: object) => object) {
71
+ getVirtualCamera = wrapper;
72
+ wrapper();
73
+ },
74
+ get updateBefore(): never {
75
+ throw new Error(UPDATE_HOOK);
76
+ },
77
+ set updateBefore(_hook: unknown) {
78
+ throw new Error(UPDATE_HOOK);
79
+ },
80
+ dispose() {},
81
+ };
82
+ Object.defineProperties(node, {
83
+ target: { value: target, enumerable: true },
84
+ reflector: { value: base, enumerable: true },
85
+ _reflectorBaseNode: { value: base },
86
+ });
87
+ return node;
88
+ };
89
+ }
package/src/refused.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * A three export the native engine does not provide, for both back ends: any call, construction or
3
+ * property access throws `diagnostic` naming the export. A game that only imports it (core's WebGL2
4
+ * fallback, a renderer it never builds) runs; one that uses it fails at that use, by name.
5
+ */
6
+ export function refused(name: string, diagnostic: string): unknown {
7
+ const fail = (): never => {
8
+ throw new Error(`${diagnostic}: ${name} is not available on the native engine.`);
9
+ };
10
+ return new Proxy(function refusedExport() {}, {
11
+ apply: fail,
12
+ construct: fail,
13
+ get: fail,
14
+ set: fail,
15
+ has: fail,
16
+ ownKeys: fail,
17
+ getPrototypeOf: fail,
18
+ defineProperty: fail,
19
+ deleteProperty: fail,
20
+ getOwnPropertyDescriptor: fail,
21
+ });
22
+ }
23
+
24
+ /** `refused` under the catalog's diagnostic for an unsupported export, `TN_NATIVE_UNSUPPORTED_<NAME>`. */
25
+ export function unsupportedExport(name: string): unknown {
26
+ return refused(name, `TN_NATIVE_UNSUPPORTED_${name.toUpperCase()}`);
27
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * three's render-target surface on the renderer, shared by both back ends (PRD-551): which target a
3
+ * renderer draws into, the cube-face and mip refusals, and readRenderTargetPixelsAsync's typed array.
4
+ * The engine draws a target and reads it back as RGBA16Float rows (top row first); each back end
5
+ * supplies those two calls, so the renderer facades differ only in how they reach the engine.
6
+ */
7
+
8
+ const HALF_FLOAT_TYPE = 1016; // three's HalfFloatType
9
+ const FLOAT_TYPE = 1015; // three's FloatType
10
+
11
+ interface IRenderTargetLike {
12
+ readonly texture: { readonly type: number };
13
+ }
14
+
15
+ /** IEEE binary16 bits to a number. */
16
+ function halfToFloat(bits: number): number {
17
+ const exponent = (bits >> 10) & 31;
18
+ const mantissa = bits & 1023;
19
+ const magnitude =
20
+ exponent === 0
21
+ ? mantissa * 2 ** -24
22
+ : exponent === 31
23
+ ? mantissa === 0
24
+ ? Number.POSITIVE_INFINITY
25
+ : Number.NaN
26
+ : (mantissa + 1024) * 2 ** (exponent - 25);
27
+ return bits & 0x8000 ? -magnitude : magnitude;
28
+ }
29
+
30
+ /**
31
+ * RGBA16Float rows as three's readRenderTargetPixelsAsync types them for the target's texture type:
32
+ * the half bits as a Uint16Array (HalfFloatType), floats (FloatType), or bytes (UnsignedByteType,
33
+ * each channel clamped to [0, 1] and rounded, as an RGBA8 target stores it).
34
+ */
35
+ export function pixelsOfType(
36
+ bytes: Uint8Array,
37
+ type: number,
38
+ ): Uint8Array | Uint16Array | Float32Array {
39
+ const halves = new Uint16Array(
40
+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
41
+ );
42
+ if (type === HALF_FLOAT_TYPE) return halves;
43
+ if (type === FLOAT_TYPE) return Float32Array.from(halves, halfToFloat);
44
+ return Uint8Array.from(halves, (bits) =>
45
+ Math.round(Math.min(1, Math.max(0, halfToFloat(bits))) * 255),
46
+ );
47
+ }
48
+
49
+ /** The engine's two calls for a back end's render targets. */
50
+ export interface IRenderTargetEngine {
51
+ /** Draws `root` through `camera` into `target`; throws the engine's refusal. */
52
+ draw(target: unknown, root: unknown, camera: unknown): void;
53
+ /** The region's RGBA16Float rows, top row first. */
54
+ read(target: unknown, x: number, y: number, width: number, height: number): Promise<Uint8Array>;
55
+ }
56
+
57
+ /**
58
+ * Adds three's setRenderTarget, getRenderTarget, getActiveCubeFace, getActiveMipmapLevel and
59
+ * readRenderTargetPixelsAsync to a renderer facade's prototype, and routes its render() into the
60
+ * current target. `engineOf(renderer)` reaches the engine for that renderer.
61
+ */
62
+ export function defineRenderTargets(
63
+ prototype: { render(scene: unknown, camera: unknown): void },
64
+ engineOf: (renderer: object) => IRenderTargetEngine,
65
+ ): void {
66
+ const targets = new WeakMap<object, unknown>();
67
+ const render = prototype.render;
68
+ Object.assign(prototype, {
69
+ setRenderTarget(
70
+ this: object,
71
+ target: unknown = null,
72
+ activeCubeFace = 0,
73
+ activeMipmapLevel = 0,
74
+ ): void {
75
+ if (activeCubeFace !== 0 || activeMipmapLevel !== 0)
76
+ throw new Error(
77
+ "TN_NATIVE_RENDER_TARGET_UNSUPPORTED: a cube face or mip level other than 0 is not drawn natively",
78
+ );
79
+ targets.set(this, target);
80
+ },
81
+ getRenderTarget(this: object): unknown {
82
+ return targets.get(this) ?? null;
83
+ },
84
+ getActiveCubeFace(): number {
85
+ return 0;
86
+ },
87
+ getActiveMipmapLevel(): number {
88
+ return 0;
89
+ },
90
+ render(this: object, scene: unknown, camera: unknown): void {
91
+ const target = targets.get(this);
92
+ if (target === null || target === undefined) render.call(this, scene, camera);
93
+ else engineOf(this).draw(target, scene, camera);
94
+ },
95
+ async readRenderTargetPixelsAsync(
96
+ this: object,
97
+ target: IRenderTargetLike,
98
+ x: number,
99
+ y: number,
100
+ width: number,
101
+ height: number,
102
+ ): Promise<Uint8Array | Uint16Array | Float32Array> {
103
+ const bytes = await engineOf(this).read(target, x, y, width, height);
104
+ return pixelsOfType(bytes, target.texture.type);
105
+ },
106
+ });
107
+ }