@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,315 @@
1
+ /**
2
+ * The fixture line protocol: one fixture in, one reply per observation out.
3
+ *
4
+ * A native driver is a plain process. It reads commands on stdin and writes replies on stdout,
5
+ * so it can be the C++ engine, a test binary, or the fake driver in `__tests__/fixtures/`. Tokens
6
+ * are separated by single spaces and carry no other separator: strings are percent-encoded, and
7
+ * every number travels as its binary64 bits.
8
+ *
9
+ * fixture <name>
10
+ * new <id> <Class> <arg>*
11
+ * call <id> <method> <resultId|-> <arg>*
12
+ * set <id> <path> <arg>
13
+ * observe <index> <id> <path|-> <method|-> <kind>
14
+ * end
15
+ *
16
+ * args: n:<16 hex digits> | s:<percent-encoded> | b:1 | b:0 | null | r:<id>
17
+ * obs <index> <kind> <value>
18
+ * unsupported <index|-> <percent-encoded reason>
19
+ * error <percent-encoded message>
20
+ *
21
+ * The C++ driver implements the other half of this file.
22
+ */
23
+
24
+ import {
25
+ FIXTURE_ARRAY_TYPES,
26
+ FIXTURE_NUMBER_NAMES,
27
+ type FixtureArg,
28
+ type FixtureArrayType,
29
+ type FixtureNumberName,
30
+ type IFixture,
31
+ type ObservationKind,
32
+ bitsNumber,
33
+ canonicalJson,
34
+ decimalOf,
35
+ numberBits,
36
+ } from "./fixture-format.js";
37
+
38
+ /**
39
+ * Encodes one argument. `r:` is a reference, `n:` the binary64 bits of any number, `a:<type>:` a
40
+ * typed array of such bits, comma-separated, `R:` a comma-separated list of references, and `o:`
41
+ * an options object: `key=<scalar token>` pairs joined by `;` (a string's token escapes both).
42
+ */
43
+ export function encodeArg(arg: FixtureArg): string {
44
+ if (arg === null) return "null";
45
+ if (typeof arg === "boolean") return arg ? "b:1" : "b:0";
46
+ if (typeof arg === "number") return `n:${numberBits(arg)}`;
47
+ if (typeof arg === "string") return `s:${encodeURIComponent(arg)}`;
48
+ if ("ref" in arg) return `r:${arg.ref}`;
49
+ if ("refs" in arg) return `R:${arg.refs.join(",")}`;
50
+ if ("record" in arg)
51
+ return `o:${Object.entries(arg.record)
52
+ .map(([key, value]) => `${key}=${encodeArg(value)}`)
53
+ .join(";")}`;
54
+ if ("array" in arg)
55
+ return `a:${arg.type}:${arg.array.map((value) => numberBits(value)).join(",")}`;
56
+ if (FIXTURE_NUMBER_NAMES.includes(arg.num)) return `n:${numberBits(namedNumber(arg.num))}`;
57
+ throw new Error(
58
+ `TN_PROTOCOL_ARG_INVALID: ${JSON.stringify(arg)} is not an argument this protocol encodes`,
59
+ );
60
+ }
61
+
62
+ /** The value behind `{ "num": "NaN" }` and its three siblings. */
63
+ export function namedNumber(name: FixtureNumberName): number {
64
+ if (name === "NaN") return Number.NaN;
65
+ if (name === "Infinity") return Number.POSITIVE_INFINITY;
66
+ if (name === "-Infinity") return Number.NEGATIVE_INFINITY;
67
+ return -0;
68
+ }
69
+
70
+ /** The inverse of {@link encodeArg}. Fails closed on a token this protocol does not define. */
71
+ export function decodeArg(token: string): FixtureArg {
72
+ if (token === "null") return null;
73
+ if (token === "b:1") return true;
74
+ if (token === "b:0") return false;
75
+ if (token.startsWith("r:")) {
76
+ const id = token.slice(2);
77
+ if (id === "") throw new Error(`TN_PROTOCOL_ARG_INVALID: ${token} names no id`);
78
+ return { ref: id };
79
+ }
80
+ if (token.startsWith("n:")) return bitsNumber(token.slice(2));
81
+ if (token.startsWith("R:"))
82
+ return { refs: token.slice(2) === "" ? [] : token.slice(2).split(",") };
83
+ if (token.startsWith("a:")) {
84
+ const [, type, bits = ""] = token.split(":");
85
+ if (!FIXTURE_ARRAY_TYPES.includes(type as FixtureArrayType))
86
+ throw new Error(`TN_PROTOCOL_ARG_INVALID: ${token} names no typed array`);
87
+ return {
88
+ array: bits === "" ? [] : bits.split(",").map(bitsNumber),
89
+ type: type as FixtureArrayType,
90
+ };
91
+ }
92
+ if (token.startsWith("s:")) return decodeURIComponent(token.slice(2));
93
+ if (token.startsWith("o:")) {
94
+ const fields: Record<string, number | string | boolean | null> = {};
95
+ for (const pair of token.slice(2) === "" ? [] : token.slice(2).split(";")) {
96
+ const at = pair.indexOf("=");
97
+ const value = at > 0 ? decodeArg(pair.slice(at + 1)) : undefined;
98
+ if (value === undefined || (value !== null && typeof value === "object"))
99
+ throw new Error(`TN_PROTOCOL_ARG_INVALID: ${token} holds a field that is not a scalar`);
100
+ fields[pair.slice(0, at)] = value;
101
+ }
102
+ return { record: fields };
103
+ }
104
+ throw new Error(`TN_PROTOCOL_ARG_INVALID: ${token} is not an argument this protocol decodes`);
105
+ }
106
+
107
+ const NUMBER_TOKEN = /^n:([0-9a-f]{16})$/u;
108
+
109
+ /** Every number in an observation value, in order. `-0` and NaN keep their bits. */
110
+ export function decodeNumbers(value: string): readonly number[] {
111
+ return value.split(",").map((token) => {
112
+ const bits = NUMBER_TOKEN.exec(token)?.[1];
113
+ if (bits === undefined)
114
+ throw new Error(`TN_PROTOCOL_VALUE_INVALID: ${token} is not n:<16 hex digits>`);
115
+ return bitsNumber(bits);
116
+ });
117
+ }
118
+
119
+ /** The text of a `string` or `json` value, percent-decoded. */
120
+ export function decodeText(value: string): string {
121
+ if (!value.startsWith("s:"))
122
+ throw new Error(`TN_PROTOCOL_VALUE_INVALID: ${value} is not s:<text>`);
123
+ return decodeURIComponent(value.slice(2));
124
+ }
125
+
126
+ export interface IEncodedObservation {
127
+ readonly value: string;
128
+ readonly decimal: string;
129
+ }
130
+
131
+ /**
132
+ * The wire form of an observed value, plus the decimal a human reads next to it.
133
+ *
134
+ * `json` compares as canonical JSON text. Two drivers that build the same object agree; a driver
135
+ * that formats a float differently does not, which is the honest answer for a structural check.
136
+ */
137
+ export function encodeObservation(kind: ObservationKind, value: unknown): IEncodedObservation {
138
+ if (kind === "number") return numberValue(value as number);
139
+ if (kind === "numbers") return numbersValue(value);
140
+ if (kind === "boolean") {
141
+ if (typeof value !== "boolean")
142
+ throw new Error(`TN_OBSERVATION_INVALID: boolean observed ${typeof value}`);
143
+ return { value: value ? "b:1" : "b:0", decimal: String(value) };
144
+ }
145
+ if (kind === "string") {
146
+ if (typeof value !== "string")
147
+ throw new Error(`TN_OBSERVATION_INVALID: string observed ${typeof value}`);
148
+ return { value: `s:${encodeURIComponent(value)}`, decimal: value };
149
+ }
150
+ if (kind === "pixels") {
151
+ // The frame's own hash is the observation: two runs that drew the same pixels agree byte for
152
+ // byte, and the driver that answers differently names a frame nobody compared.
153
+ if (typeof value !== "string")
154
+ throw new Error(`TN_OBSERVATION_INVALID: pixels observed ${typeof value}`);
155
+ return { value: `s:${encodeURIComponent(value)}`, decimal: value };
156
+ }
157
+ const text = canonicalJson(value);
158
+ return { value: `s:${encodeURIComponent(text)}`, decimal: text };
159
+ }
160
+
161
+ /**
162
+ * A `numbers` value. A plain array is the usual case; a typed array (`Float32Array`, `Uint16Array`)
163
+ * is what a BufferAttribute's `.array` is, and the native side reads it as the same list of doubles,
164
+ * so its elements are observed in order.
165
+ */
166
+ function numbersValue(value: unknown): IEncodedObservation {
167
+ if (
168
+ !Array.isArray(value) &&
169
+ (!ArrayBuffer.isView(value) || !("length" in value) || typeof value.length !== "number")
170
+ )
171
+ throw new Error(`TN_OBSERVATION_INVALID: numbers observed ${typeof value}`);
172
+ const entries = Array.from(value as ArrayLike<number>, numberValue);
173
+ return {
174
+ value: entries.map((entry) => entry.value).join(","),
175
+ decimal: entries.map((entry) => entry.decimal).join(", "),
176
+ };
177
+ }
178
+
179
+ function numberValue(value: number): IEncodedObservation {
180
+ if (typeof value !== "number")
181
+ throw new Error(`TN_OBSERVATION_INVALID: number observed ${typeof value}`);
182
+ return { value: `n:${numberBits(value)}`, decimal: decimalOf(value) };
183
+ }
184
+
185
+ /** The whole script for one fixture, including the `fixture` and `end` commands. */
186
+ /**
187
+ * The `render` line, emitted just before the `pixels` observation: the reference takes its numbers
188
+ * in Node, where nothing renders, and rendering switches the camera to WebGPU clip space (a new
189
+ * projectionMatrix), so every numeric observation is answered before the frame is drawn.
190
+ */
191
+ function renderLine(fixture: IFixture, renderPng: string): string {
192
+ const render = fixture.render;
193
+ if (render === undefined)
194
+ throw new Error(`TN_FIXTURE_RENDER_MISSING: ${fixture.name} has no render block`);
195
+ return [
196
+ "render",
197
+ render.scene,
198
+ render.camera,
199
+ String(render.width),
200
+ String(render.height),
201
+ render.toneMapping,
202
+ encodeArg(render.toneMappingExposure),
203
+ render.outputColorSpace,
204
+ `s:${encodeURIComponent(renderPng)}`,
205
+ // Only when on, so every frame captured before shadows keeps its exact driver line.
206
+ ...(render.shadowMap === true
207
+ ? [render.shadowMapType === "PCFSoftShadowMap" ? "shadowMapSoft" : "shadowMap"]
208
+ : []),
209
+ ].join(" ");
210
+ }
211
+
212
+ /**
213
+ * The fixture as driver lines. `renderPng`, when given, asks a render-capable driver to draw the
214
+ * fixture's frame: `render <scene> <camera> <width> <height> <toneMapping> <exposure> <srgb|linear>
215
+ * <png path> [shadowMap|shadowMapSoft]`, placed before the `pixels` observation, which the driver answers with that PNG's path.
216
+ */
217
+ export function encodeFixture(fixture: IFixture, renderPng?: string): readonly string[] {
218
+ const lines = [`fixture ${fixture.name}`];
219
+ for (const op of fixture.ops) {
220
+ if (op.op === "set") {
221
+ lines.push(["set", op.id, op.path, encodeArg(op.value)].join(" "));
222
+ continue;
223
+ }
224
+ if (op.op === "tsl") {
225
+ lines.push(["tsl", op.id, encodeArg(op.program)].join(" "));
226
+ continue;
227
+ }
228
+ if (op.op === "gltf") {
229
+ lines.push(
230
+ ["gltf", op.id, encodeArg(op.file), ...(op.clips?.length ? [op.clips.join(",")] : [])].join(
231
+ " ",
232
+ ),
233
+ );
234
+ continue;
235
+ }
236
+ const args = op.args.map((arg) => encodeArg(arg));
237
+ if (op.op === "new") lines.push(["new", op.id, op.class, ...args].join(" "));
238
+ else lines.push(["call", op.id, op.method, op.result ?? "-", ...args].join(" "));
239
+ }
240
+ fixture.observe.forEach((observation, index) => {
241
+ if (observation.kind === "pixels" && renderPng !== undefined)
242
+ lines.push(renderLine(fixture, renderPng));
243
+ lines.push(
244
+ [
245
+ "observe",
246
+ String(index),
247
+ observation.id,
248
+ observation.path ?? "-",
249
+ observation.method ?? "-",
250
+ observation.kind,
251
+ ].join(" "),
252
+ );
253
+ });
254
+ lines.push("end");
255
+ return lines;
256
+ }
257
+
258
+ export interface IValueReply {
259
+ readonly kind: "obs";
260
+ readonly index: number;
261
+ readonly observation: ObservationKind;
262
+ readonly value: string;
263
+ }
264
+
265
+ export interface IUnsupportedReply {
266
+ readonly kind: "unsupported";
267
+ /** Null when the driver refused the fixture itself rather than one observation. */
268
+ readonly index: number | null;
269
+ readonly reason: string;
270
+ }
271
+
272
+ export interface IErrorReply {
273
+ readonly kind: "error";
274
+ readonly message: string;
275
+ }
276
+
277
+ export type DriverReply = IValueReply | IUnsupportedReply | IErrorReply;
278
+
279
+ /** Parses one stdout line. An unrecognized line throws, so a wrong driver cannot read as a pass. */
280
+ export function parseReply(line: string): DriverReply {
281
+ const trimmed = line.trim();
282
+ if (trimmed.startsWith("error "))
283
+ return { kind: "error", message: decodeURIComponent(trimmed.slice(6)) };
284
+ if (trimmed.startsWith("unsupported ")) {
285
+ const [index, reason = ""] = trimmed.slice("unsupported ".length).split(" ");
286
+ return {
287
+ kind: "unsupported",
288
+ index: index === "-" || index === "" ? null : Number(index),
289
+ reason: decodeURIComponent(reason),
290
+ };
291
+ }
292
+ if (trimmed.startsWith("obs ")) {
293
+ const [index, observation, value] = trimmed.slice("obs ".length).split(" ");
294
+ if (index === undefined || observation === undefined || value === undefined)
295
+ throw new Error(`TN_PROTOCOL_REPLY_INVALID: ${JSON.stringify(trimmed)} is missing a field`);
296
+ if (!OBSERVATIONS.has(observation))
297
+ throw new Error(`TN_PROTOCOL_REPLY_INVALID: ${observation} is not an observation kind`);
298
+ return {
299
+ kind: "obs",
300
+ index: Number(index),
301
+ observation: observation as ObservationKind,
302
+ value,
303
+ };
304
+ }
305
+ throw new Error(`TN_PROTOCOL_REPLY_INVALID: ${JSON.stringify(trimmed)} is not a reply`);
306
+ }
307
+
308
+ const OBSERVATIONS: ReadonlySet<string> = new Set([
309
+ "number",
310
+ "numbers",
311
+ "boolean",
312
+ "string",
313
+ "json",
314
+ "pixels",
315
+ ]);
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The rest of three r185's number-only `MathUtils` (MIT), verbatim, for the Wasm web back end. The
3
+ * engine binds clamp, lerp, degToRad and euclideanModulo (its registry is the catalog's supported
4
+ * set), and a game written against three calls the others by name (`MathUtils.damp`), so they sit
5
+ * beside the engine class as plain JS and add no engine call.
6
+ */
7
+ let seed = 1234567;
8
+ const lerp = (x: number, y: number, t: number): number => (1 - t) * x + t * y;
9
+ const euclideanModulo = (n: number, m: number): number => ((n % m) + m) % m;
10
+
11
+ export const mathUtilsExtras = {
12
+ // quality-allow: three's MathUtils constant names.
13
+ // biome-ignore lint/style/useNamingConvention: three's constant names.
14
+ DEG2RAD: Math.PI / 180,
15
+ // quality-allow: three's MathUtils constant names.
16
+ // biome-ignore lint/style/useNamingConvention: three's constant names.
17
+ RAD2DEG: 180 / Math.PI,
18
+ mapLinear: (x: number, a1: number, a2: number, b1: number, b2: number): number =>
19
+ b1 + ((x - a1) * (b2 - b1)) / (a2 - a1),
20
+ inverseLerp: (x: number, y: number, value: number): number =>
21
+ x !== y ? (value - x) / (y - x) : 0,
22
+ damp: (x: number, y: number, lambda: number, dt: number): number =>
23
+ lerp(x, y, 1 - Math.exp(-lambda * dt)),
24
+ pingpong: (x: number, length = 1): number =>
25
+ length - Math.abs(euclideanModulo(x, length * 2) - length),
26
+ smoothstep(x: number, min: number, max: number): number {
27
+ if (x <= min) return 0;
28
+ if (x >= max) return 1;
29
+ const t = (x - min) / (max - min);
30
+ return t * t * (3 - 2 * t);
31
+ },
32
+ smootherstep(x: number, min: number, max: number): number {
33
+ if (x <= min) return 0;
34
+ if (x >= max) return 1;
35
+ const t = (x - min) / (max - min);
36
+ return t * t * t * (t * (t * 6 - 15) + 10);
37
+ },
38
+ randInt: (low: number, high: number): number =>
39
+ low + Math.floor(Math.random() * (high - low + 1)),
40
+ randFloat: (low: number, high: number): number => low + Math.random() * (high - low),
41
+ randFloatSpread: (range: number): number => range * (0.5 - Math.random()),
42
+ seededRandom(s?: number): number {
43
+ if (s !== undefined) seed = s;
44
+ // Mulberry32 generator
45
+ seed += 0x6d2b79f5;
46
+ let t = seed;
47
+ t = Math.imul(t ^ (t >>> 15), t | 1);
48
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
49
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
50
+ },
51
+ radToDeg: (radians: number): number => radians * (180 / Math.PI),
52
+ isPowerOfTwo: (value: number): boolean => (value & (value - 1)) === 0 && value !== 0,
53
+ ceilPowerOfTwo: (value: number): number => 2 ** Math.ceil(Math.log(value) / Math.LN2),
54
+ floorPowerOfTwo: (value: number): number => 2 ** Math.floor(Math.log(value) / Math.LN2),
55
+ };
56
+
57
+ /** The engine's MathUtils class with the extras on each instance, which is how three's namespace binds. */
58
+ export function withMathUtilsExtras(MathUtils: new () => object): new () => object {
59
+ return class extends MathUtils {
60
+ constructor() {
61
+ super();
62
+ Object.assign(this, mathUtilsExtras);
63
+ }
64
+ };
65
+ }
@@ -0,0 +1,250 @@
1
+ /**
2
+ * The JavaScript half of three's object surface that both engine back ends share (PRD-540; moved
3
+ * from the V8 player's core-three.mjs): `geometry.attributes` and `groups`, `shape.holes`, and the
4
+ * abstract `Material` base. The engine owns the data; these are views over its bindings.
5
+ */
6
+
7
+ type Constructor = abstract new (...args: never[]) => object;
8
+ type Prototype = Record<string, unknown> & object;
9
+
10
+ /** The engine classes the views attach to; a missing one is skipped. */
11
+ export interface ISurfaceClasses {
12
+ readonly bufferGeometry: Constructor;
13
+ readonly geometries: readonly Constructor[];
14
+ readonly shape?: Constructor;
15
+ readonly materials: readonly Constructor[];
16
+ }
17
+
18
+ // three's `geometry.attributes` map over the native named attributes: one live view per geometry,
19
+ // reading through getAttribute and writing through setAttribute/deleteAttribute.
20
+ // The engine lists names in its own (sorted) order; three's standard names come first, as three
21
+ // adds them, then the rest.
22
+ const STANDARD_ATTRIBUTES = [
23
+ "position",
24
+ "normal",
25
+ "uv",
26
+ "uv1",
27
+ "uv2",
28
+ "uv3",
29
+ "color",
30
+ "tangent",
31
+ "skinIndex",
32
+ "skinWeight",
33
+ ];
34
+
35
+ interface IGeometry {
36
+ /** Every attribute name, one per line: one engine call. */
37
+ readonly __attributeNames: string;
38
+ setAttribute(name: string, attribute: unknown): unknown;
39
+ deleteAttribute(name: string): unknown;
40
+ hasAttribute(name: string): boolean;
41
+ getAttribute(name: string): unknown;
42
+ }
43
+
44
+ function defineGeometrySurface(
45
+ BufferGeometry: Constructor,
46
+ geometries: readonly Constructor[],
47
+ ): void {
48
+ const attributeViews = new WeakMap<object, object>();
49
+ for (const geometry of [BufferGeometry, ...geometries]) {
50
+ const prototype = geometry.prototype as Prototype & IGeometry;
51
+ // three's morphAttributes is a plain object a game replaces whole (core's merge clears it with
52
+ // {}): the engine's holder takes its position and normal arrays, an absent one as none, and
53
+ // any other key is refused by name.
54
+ const morph = Object.getOwnPropertyDescriptor(prototype, "morphAttributes");
55
+ if (morph?.get !== undefined && morph.set === undefined)
56
+ Object.defineProperty(prototype, "morphAttributes", {
57
+ configurable: true,
58
+ get: morph.get,
59
+ set(this: object, value: Record<string, unknown>) {
60
+ for (const key of Object.keys(value))
61
+ if (key !== "position" && key !== "normal")
62
+ throw new TypeError(`TN_NATIVE_UNSUPPORTED morphAttributes.${key} is not ported`);
63
+ const holder = morph.get?.call(this) as Record<string, unknown>;
64
+ holder.position = value.position ?? [];
65
+ holder.normal = value.normal ?? [];
66
+ },
67
+ });
68
+ // The registry answers `groups` as canonical JSON text (the fixtures' protocol); three's is an
69
+ // array of { start, count, materialIndex } in that key order.
70
+ // ponytail: a fresh array per read, so edit groups with addGroup/clearGroups, as three advises.
71
+ const groups = Object.getOwnPropertyDescriptor(prototype, "groups");
72
+ if (groups?.get !== undefined)
73
+ Object.defineProperty(prototype, "groups", {
74
+ configurable: true,
75
+ get(this: object) {
76
+ return (
77
+ JSON.parse(groups.get?.call(this) as string) as {
78
+ start: number;
79
+ count: number;
80
+ materialIndex: number;
81
+ }[]
82
+ ).map(({ start, count, materialIndex }) => ({ start, count, materialIndex }));
83
+ },
84
+ });
85
+ // Each geometry class carries its own `attributes` accessor, so every one gets the view.
86
+ Object.defineProperty(prototype, "attributes", {
87
+ configurable: true,
88
+ get(this: IGeometry) {
89
+ const cached = attributeViews.get(this);
90
+ if (cached !== undefined) return cached;
91
+ const names = () => {
92
+ const listed = this.__attributeNames === "" ? [] : this.__attributeNames.split("\n");
93
+ return [...new Set([...STANDARD_ATTRIBUTES, ...listed])].filter((name) =>
94
+ listed.includes(name),
95
+ );
96
+ };
97
+ const view = new Proxy(
98
+ {},
99
+ {
100
+ // getAttribute answers null for a missing name: one engine call, not two.
101
+ get: (_, name) =>
102
+ typeof name === "string" ? (this.getAttribute(name) ?? undefined) : undefined,
103
+ has: (_, name) => typeof name === "string" && this.hasAttribute(name),
104
+ set: (_, name, attribute) => {
105
+ this.setAttribute(String(name), attribute);
106
+ return true;
107
+ },
108
+ deleteProperty: (_, name) => {
109
+ this.deleteAttribute(String(name));
110
+ return true;
111
+ },
112
+ ownKeys: () => names(),
113
+ // Object.keys asks for every name's descriptor: answer from the name list and read the
114
+ // attribute only if the descriptor's getter runs.
115
+ getOwnPropertyDescriptor: (_, name) =>
116
+ typeof name === "string" && names().includes(name)
117
+ ? {
118
+ get: () => this.getAttribute(name),
119
+ set: (attribute: unknown) => this.setAttribute(name, attribute),
120
+ enumerable: true,
121
+ configurable: true,
122
+ }
123
+ : undefined,
124
+ },
125
+ );
126
+ attributeViews.set(this, view);
127
+ return view;
128
+ },
129
+ });
130
+ }
131
+ }
132
+
133
+ // three's `shape.holes` is the plain array a game pushes paths into: each change writes the whole
134
+ // array through the native setter, so the geometry built from the shape sees it.
135
+ function defineShapeHoles(Shape: Constructor): void {
136
+ const holeViews = new WeakMap<object, unknown[]>();
137
+ const holes = Object.getOwnPropertyDescriptor(Shape.prototype, "holes");
138
+ if (holes?.get === undefined || holes.set === undefined)
139
+ throw new TypeError("TN_BROWSER_UNBOUND: Shape.holes needs the engine's getter and setter");
140
+ Object.defineProperty(Shape.prototype, "holes", {
141
+ configurable: true,
142
+ get(this: object) {
143
+ if (!holeViews.has(this)) {
144
+ const shape = this;
145
+ holeViews.set(
146
+ this,
147
+ new Proxy(holes.get?.call(this) as unknown[], {
148
+ set(target, key, value) {
149
+ // quality-allow: target is unknown[] accessed by PropertyKey inside Proxy handler.
150
+ (target as unknown as Record<PropertyKey, unknown>)[key] = value;
151
+ holes.set?.call(shape, [...target]);
152
+ return true;
153
+ },
154
+ }),
155
+ );
156
+ }
157
+ return holeViews.get(this);
158
+ },
159
+ set(this: object, value: unknown[]) {
160
+ holes.set?.call(this, [...value]);
161
+ holeViews.delete(this);
162
+ },
163
+ });
164
+ }
165
+
166
+ /**
167
+ * three's abstract Material: the base the native material classes share for `instanceof` and its
168
+ * default hooks. The engine compiles no WebGL program, so the hooks stay three's no-op defaults; a
169
+ * bare Material has no native class and refuses construction.
170
+ */
171
+ export class Material {
172
+ constructor() {
173
+ throw new Error("TN_NATIVE_MATERIAL_ABSTRACT: construct a concrete material class");
174
+ }
175
+
176
+ onBeforeCompile(): void {}
177
+
178
+ // No program reads this key, and a strict build keeps no function source to stringify.
179
+ customProgramCacheKey(): string {
180
+ return "";
181
+ }
182
+ }
183
+ // quality-allow: Material.prototype does not declare dynamic isMaterial property from Three.js class contract.
184
+ (Material.prototype as unknown as Prototype).isMaterial = true;
185
+
186
+ /** Attaches the shared views to a back end's engine classes. */
187
+ export function defineObjectSurface(classes: ISurfaceClasses): void {
188
+ defineGeometrySurface(classes.bufferGeometry, classes.geometries);
189
+ if (classes.shape !== undefined) defineShapeHoles(classes.shape);
190
+ for (const material of classes.materials) {
191
+ Object.setPrototypeOf(material.prototype, Material.prototype);
192
+ // The browser back end already defines the flag (read-only) from the catalog.
193
+ const flag = `is${material.name}`;
194
+ if (!Object.hasOwn(material.prototype, flag)) (material.prototype as Prototype)[flag] = true;
195
+ }
196
+ }
197
+
198
+ // three's scene classes and the `is<Class>` flag each one defines; every light is also `isLight`.
199
+ const FLAGGED_CLASSES = [
200
+ "NodeMaterial",
201
+ "MeshBasicNodeMaterial",
202
+ "MeshStandardNodeMaterial",
203
+ "SpriteNodeMaterial",
204
+ "Texture",
205
+ "DataTexture",
206
+ "CanvasTexture",
207
+ "Object3D",
208
+ "Scene",
209
+ "Group",
210
+ "Mesh",
211
+ "SkinnedMesh",
212
+ "InstancedMesh",
213
+ "BatchedMesh",
214
+ "Bone",
215
+ "LOD",
216
+ "Sprite",
217
+ "Line",
218
+ "LineSegments",
219
+ "Points",
220
+ "Camera",
221
+ "PerspectiveCamera",
222
+ "OrthographicCamera",
223
+ "AmbientLight",
224
+ "DirectionalLight",
225
+ "HemisphereLight",
226
+ "PointLight",
227
+ "SpotLight",
228
+ ] as const;
229
+
230
+ /**
231
+ * Puts three's type flags (`isMesh`, `isCamera`, `isLight`, ...) on a back end's scene classes. A
232
+ * subclass inherits its parent's through the prototype chain, as in three; a missing class is skipped.
233
+ */
234
+ export function defineTypeFlags(classes: Readonly<Record<string, unknown>>): void {
235
+ for (const name of FLAGGED_CLASSES) {
236
+ const cls = classes[name] as Constructor | undefined;
237
+ if (typeof cls !== "function") continue;
238
+ const flags = name.endsWith("Light")
239
+ ? [`is${name}`, "isLight"]
240
+ : name.endsWith("NodeMaterial")
241
+ ? [`is${name}`, "isNodeMaterial"]
242
+ : [`is${name}`];
243
+ for (const flag of flags)
244
+ Object.defineProperty(cls.prototype, flag, {
245
+ configurable: true,
246
+ writable: true,
247
+ value: true,
248
+ });
249
+ }
250
+ }