@threenative/three-native 0.0.0-stage → 0.3.5

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,426 @@
1
+ /**
2
+ * The differential half: a native driver's answers against the pinned reference goldens.
3
+ *
4
+ * One driver process per fixture. The fixture goes in as the line protocol on stdin, one reply
5
+ * per observation comes back on stdout, and every observation is compared with the fixture's own
6
+ * tolerance. The three statuses are the whole answer:
7
+ *
8
+ * pass every observation matched inside the tolerance
9
+ * fail an observation differed; the message names the first difference in bits and decimals
10
+ * blocked the driver is missing, or it answered `unsupported` for the fixture or an observation
11
+ *
12
+ * `blocked` is never `pass`. A row nobody ran is a row nobody proved.
13
+ *
14
+ * pnpm parity -- --suite native-engine
15
+ */
16
+
17
+ import { spawnSync } from "node:child_process";
18
+ import { existsSync, readFileSync } from "node:fs";
19
+ import path from "node:path";
20
+
21
+ import {
22
+ type IFixture,
23
+ type IFixtureGolden,
24
+ type IFixtureTolerance,
25
+ type IGoldenObservation,
26
+ REPO_ROOT,
27
+ decimalOf,
28
+ numberBits,
29
+ ulpDistance,
30
+ } from "./fixture-format.js";
31
+ import { type DriverReply, decodeNumbers, encodeFixture, parseReply } from "./fixture-protocol.js";
32
+
33
+ export type FixtureStatus = "pass" | "fail" | "blocked";
34
+
35
+ /** A render fixture's reason for being blocked on this side. Named, dated, and never a pass. */
36
+ export const NATIVE_RENDER_BLOCKED = "native renderer pending (PRD-514)";
37
+
38
+ export interface IFirstDifference {
39
+ readonly index: number;
40
+ readonly id: string;
41
+ readonly source: string;
42
+ readonly expected: string;
43
+ readonly expectedDecimal: string;
44
+ readonly actual: string;
45
+ readonly actualDecimal: string;
46
+ }
47
+
48
+ export interface IFixtureResult {
49
+ readonly id: string;
50
+ readonly adaptedFrom: string;
51
+ readonly tolerance: IFixtureTolerance;
52
+ readonly status: FixtureStatus;
53
+ /** The reason a blocked row did not run, or the reason a failure is not a value difference. */
54
+ readonly reason: string;
55
+ readonly observations: number;
56
+ readonly matched: number;
57
+ readonly firstDifference: IFirstDifference | null;
58
+ }
59
+
60
+ /** One reported number, in both forms the message prints. */
61
+ function describe(value: number): { readonly bits: string; readonly decimal: string } {
62
+ return { bits: numberBits(value), decimal: decimalOf(value) };
63
+ }
64
+
65
+ /**
66
+ * Why two doubles are not equal inside this tolerance. Null when they are equal.
67
+ *
68
+ * A declared bound is a bound: `{"ulps": 4}` alone does not also demand bit equality. Two values
69
+ * pass when they are inside *any* bound the fixture declared, and fail only when they are outside
70
+ * every one of them.
71
+ */
72
+ function mismatch(expected: number, actual: number, tolerance: IFixtureTolerance): string | null {
73
+ // `Object.is` is the bit comparison: -0 differs from 0, and Infinity matches itself. A tolerance
74
+ // of zero still refuses a driver that answers +0 where the reference wrote -0.
75
+ if (Object.is(expected, actual)) return null;
76
+ // One NaN against something that is not NaN. Two NaNs never reach this line: any NaN payload is
77
+ // equal to any other, because hardware raises several for the same invalid operation and a
78
+ // payload is not part of what a driver agreed to compute.
79
+ if (Number.isNaN(expected) || Number.isNaN(actual))
80
+ return `expected ${decimalOf(expected)}, observed ${decimalOf(actual)}`;
81
+ const ulps = tolerance.ulps ?? Number.POSITIVE_INFINITY;
82
+ const distance = Math.abs(expected - actual);
83
+ if (tolerance.ulps !== undefined && ulpDistance(expected, actual) <= ulps) return null;
84
+ // `abs: 0` means bit-exact, and the `Object.is` above already refused a bit difference. Only a
85
+ // wider absolute bound can forgive anything, which is what keeps -0 from passing as 0.
86
+ if (tolerance.abs !== undefined && tolerance.abs > 0 && distance <= tolerance.abs) return null;
87
+ if (distance === 0) return "the sign of zero differs";
88
+ const bound =
89
+ tolerance.ulps === undefined
90
+ ? `absolute tolerance ${decimalOf(tolerance.abs ?? 0)}`
91
+ : tolerance.abs === undefined
92
+ ? `tolerance of ${String(tolerance.ulps)} ulps`
93
+ : `absolute tolerance ${decimalOf(tolerance.abs)} or ${String(tolerance.ulps)} ulps`;
94
+ return `${decimalOf(distance)} apart, outside ${bound}`;
95
+ }
96
+
97
+ /**
98
+ * Compares one observation against its golden.
99
+ *
100
+ * Numbers compare element by element under the tolerance; text, booleans and JSON compare as
101
+ * whole values, because a tolerance on a name or a flag would hide the difference it exists to
102
+ * expose.
103
+ */
104
+ export function compareObservation(
105
+ golden: IGoldenObservation,
106
+ actual: DriverReply & { kind: "obs" },
107
+ tolerance: IFixtureTolerance,
108
+ ): IFirstDifference | null {
109
+ const source =
110
+ golden.path ?? (golden.method === undefined ? "(returned value)" : `${golden.method}()`);
111
+ if (golden.kind === "number" || golden.kind === "numbers") {
112
+ const expectedValues = decodeNumbers(golden.value);
113
+ const actualValues = decodeNumbers(actual.value);
114
+ if (actual.observation !== golden.kind)
115
+ return difference(
116
+ golden,
117
+ source,
118
+ golden.value,
119
+ golden.decimal ?? "",
120
+ actual.value,
121
+ actual.value,
122
+ );
123
+ for (const [position, expected] of expectedValues.entries()) {
124
+ const observed = actualValues[position];
125
+ if (observed === undefined)
126
+ return difference(
127
+ golden,
128
+ source,
129
+ golden.value,
130
+ golden.decimal ?? "",
131
+ actual.value,
132
+ actual.value,
133
+ );
134
+ const reason = mismatch(expected, observed, tolerance);
135
+ if (reason !== null) {
136
+ const left = describe(expected);
137
+ const right = describe(observed);
138
+ return difference(
139
+ golden,
140
+ `${source}[${position}]`,
141
+ `n:${left.bits}`,
142
+ left.decimal,
143
+ `n:${right.bits}`,
144
+ right.decimal,
145
+ );
146
+ }
147
+ }
148
+ return null;
149
+ }
150
+ if (golden.value === actual.value) return null;
151
+ return difference(golden, source, golden.value, golden.decimal ?? "", actual.value, actual.value);
152
+ }
153
+
154
+ function difference(
155
+ golden: IGoldenObservation,
156
+ source: string,
157
+ expected: string,
158
+ expectedDecimal: string,
159
+ actual: string,
160
+ actualDecimal: string,
161
+ ): IFirstDifference {
162
+ return {
163
+ index: golden.index,
164
+ id: golden.id,
165
+ source,
166
+ expected,
167
+ expectedDecimal,
168
+ actual,
169
+ actualDecimal,
170
+ };
171
+ }
172
+
173
+ export interface IDriverRun {
174
+ readonly lines: readonly string[];
175
+ /** The driver could not run here. The row is blocked, because nothing was proved. */
176
+ readonly blocked?: string;
177
+ /** The driver ran and misbehaved. The row fails, because something was proved and it was wrong. */
178
+ readonly error?: string;
179
+ }
180
+
181
+ /** Runs one fixture against one driver. A driver that cannot run here is a block, never a pass. */
182
+ export function runFixture(
183
+ fixture: IFixture,
184
+ driver: string | null,
185
+ renderPng?: string,
186
+ ): IDriverRun {
187
+ const script = `${encodeFixture(fixture, renderPng).join("\n")}\n`;
188
+ if (driver === null)
189
+ return {
190
+ lines: [],
191
+ blocked: "no native driver: pass --driver PATH or set TN_NATIVE_FIXTURE_DRIVER",
192
+ };
193
+ if (!existsSync(driver)) return { lines: [], blocked: `native driver not found: ${driver}` };
194
+ const command = /\.[cm]?js$/u.test(driver)
195
+ ? { file: process.execPath, prefix: [driver] }
196
+ : { file: driver, prefix: [] };
197
+ const run = spawnSync(command.file, command.prefix, {
198
+ input: script,
199
+ encoding: "utf8",
200
+ maxBuffer: 32 * 1024 * 1024,
201
+ timeout: 120_000,
202
+ });
203
+ const spawnCode = (run.error as NodeJS.ErrnoException | undefined)?.code;
204
+ if (spawnCode !== undefined && ["ENOENT", "EACCES", "EPERM"].includes(spawnCode))
205
+ return { lines: [], blocked: `native driver could not start: ${run.error?.message ?? driver}` };
206
+ const lines = (run.stdout ?? "").split("\n").filter((line) => line.trim() !== "");
207
+ const error =
208
+ run.error?.message ??
209
+ (run.status === 0
210
+ ? undefined
211
+ : `driver exited ${String(run.status)}${(run.stderr ?? "") === "" ? "" : `: ${(run.stderr ?? "").trim().split("\n").slice(-3).join(" ")}`}`);
212
+ return { lines, ...(error === undefined ? {} : { error }) };
213
+ }
214
+
215
+ /** How two frames differ, as the conformance lane measures it (metrics.mjs compareCaptures). */
216
+ export interface IPixelComparison {
217
+ readonly pixelMismatchRatio: number;
218
+ readonly perceptualDeltaE: number;
219
+ }
220
+
221
+ /** What a render-capable driver needs: where to write frames, and how to compare them. */
222
+ export interface IRenderOptions {
223
+ readonly frameDir: string;
224
+ readonly goldensDir: string;
225
+ readonly compare: (golden: Uint8Array, native: Uint8Array, levels: number) => IPixelComparison;
226
+ }
227
+
228
+ export interface IRunFixturesOptions {
229
+ readonly driver: string | null;
230
+ /** Present when the driver can draw frames; a render fixture is blocked without it. */
231
+ readonly renders?: IRenderOptions;
232
+ /** Where a fixture with no golden for this reference version is reported. Default: fail. */
233
+ readonly version: string;
234
+ readonly goldens: ReadonlyMap<string, IFixtureGolden>;
235
+ }
236
+
237
+ export function runFixtures(
238
+ fixtures: readonly IFixture[],
239
+ options: IRunFixturesOptions,
240
+ ): readonly IFixtureResult[] {
241
+ return fixtures.map((fixture) => runOne(fixture, options));
242
+ }
243
+
244
+ function runOne(fixture: IFixture, options: IRunFixturesOptions): IFixtureResult {
245
+ const base = {
246
+ id: fixture.name,
247
+ adaptedFrom: fixture.adaptedFrom,
248
+ tolerance: fixture.tolerance,
249
+ observations: fixture.observe.length,
250
+ };
251
+ // A frame the reference drew in a browser is not a frame the native renderer can draw yet, so the
252
+ // row is blocked before any golden or driver is consulted: a render fixture is never a failure,
253
+ // and never a pass, until the driver can answer a `render` request.
254
+ if (fixture.render !== undefined && options.renders === undefined)
255
+ return {
256
+ ...base,
257
+ status: "blocked",
258
+ reason: NATIVE_RENDER_BLOCKED,
259
+ matched: 0,
260
+ firstDifference: null,
261
+ };
262
+ const golden = options.goldens.get(fixture.name);
263
+ if (golden === undefined)
264
+ return {
265
+ ...base,
266
+ status: "fail",
267
+ reason: `no golden for three ${options.version}: run pnpm --filter @threenative/three-native test:reference`,
268
+ matched: 0,
269
+ firstDifference: null,
270
+ };
271
+ if (golden.blocked !== null)
272
+ return {
273
+ ...base,
274
+ status: "blocked",
275
+ reason: golden.blocked,
276
+ matched: 0,
277
+ firstDifference: null,
278
+ };
279
+
280
+ const renderPng =
281
+ fixture.render !== undefined && options.renders !== undefined
282
+ ? path.join(options.renders.frameDir, `${fixture.name}.png`)
283
+ : undefined;
284
+ const run = runFixture(fixture, options.driver, renderPng);
285
+ if (run.blocked !== undefined)
286
+ return { ...base, status: "blocked", reason: run.blocked, matched: 0, firstDifference: null };
287
+
288
+ const replies: DriverReply[] = [];
289
+ let parseFailure: string | null = null;
290
+ for (const line of run.lines) {
291
+ try {
292
+ replies.push(parseReply(line));
293
+ } catch (error) {
294
+ parseFailure = error instanceof Error ? error.message : String(error);
295
+ break;
296
+ }
297
+ }
298
+ if (parseFailure !== null)
299
+ return { ...base, status: "fail", reason: parseFailure, matched: 0, firstDifference: null };
300
+
301
+ for (const reply of replies) {
302
+ if (reply.kind === "unsupported")
303
+ return {
304
+ ...base,
305
+ status: "blocked",
306
+ reason: `driver reported unsupported${reply.index === null ? "" : ` observation ${reply.index}`}: ${reply.reason}`,
307
+ matched: 0,
308
+ firstDifference: null,
309
+ };
310
+ if (reply.kind === "error")
311
+ return {
312
+ ...base,
313
+ status: "fail",
314
+ reason: `driver error: ${reply.message}`,
315
+ matched: 0,
316
+ firstDifference: null,
317
+ };
318
+ }
319
+
320
+ const values = replies.filter((reply) => reply.kind === "obs");
321
+ if (values.length !== golden.observations.length)
322
+ return {
323
+ ...base,
324
+ status: "fail",
325
+ reason: `driver answered ${values.length} observation(s), the fixture asserts ${golden.observations.length}`,
326
+ matched: 0,
327
+ firstDifference: null,
328
+ };
329
+ for (const reply of values) {
330
+ const expected = golden.observations[reply.index];
331
+ if (expected === undefined)
332
+ return {
333
+ ...base,
334
+ status: "fail",
335
+ reason: `driver answered observation ${reply.index}, which the golden does not record`,
336
+ matched: 0,
337
+ firstDifference: null,
338
+ };
339
+ if (expected.kind === "pixels") {
340
+ const failure = comparePixels(fixture, golden, reply.value, options.renders);
341
+ if (failure !== null)
342
+ return { ...base, status: "fail", reason: failure, matched: 0, firstDifference: null };
343
+ continue;
344
+ }
345
+ let found: IFirstDifference | null;
346
+ try {
347
+ found = compareObservation(expected, reply, fixture.tolerance);
348
+ } catch (error) {
349
+ // A driver that prints something this protocol does not define failed this observation. It is
350
+ // a failure of that fixture, not of the run.
351
+ return {
352
+ ...base,
353
+ status: "fail",
354
+ reason: `observation ${reply.index} (${expected.id}) is not a protocol value: ${error instanceof Error ? error.message : String(error)}`,
355
+ matched: 0,
356
+ firstDifference: null,
357
+ };
358
+ }
359
+ if (found !== null)
360
+ return {
361
+ ...base,
362
+ status: "fail",
363
+ reason: [
364
+ `observation ${found.index} (${found.id} ${found.source}) differs`,
365
+ `expected ${found.expected} = ${found.expectedDecimal}`,
366
+ `observed ${found.actual} = ${found.actualDecimal}`,
367
+ ].join("\n"),
368
+ matched: 0,
369
+ firstDifference: found,
370
+ };
371
+ }
372
+ if (run.error !== undefined)
373
+ return { ...base, status: "fail", reason: run.error, matched: 0, firstDifference: null };
374
+ return {
375
+ ...base,
376
+ status: "pass",
377
+ reason: `${golden.observations.length} observation(s) matched`,
378
+ matched: golden.observations.length,
379
+ firstDifference: null,
380
+ };
381
+ }
382
+
383
+ /**
384
+ * A `pixels` observation: the driver's frame against the golden PNG, under the fixture's metric.
385
+ * Returns the failure, or null when the frame is within bounds.
386
+ */
387
+ function comparePixels(
388
+ fixture: IFixture,
389
+ golden: IFixtureGolden,
390
+ value: string,
391
+ renders: IRenderOptions | undefined,
392
+ ): string | null {
393
+ const metric = fixture.observe.find((o) => o.kind === "pixels")?.metric;
394
+ if (renders === undefined || golden.render === undefined || metric === undefined)
395
+ return "a pixels observation needs a render-capable driver, a golden frame and a metric";
396
+ if (!value.startsWith("s:")) return `pixels observation is not a frame path: ${value}`;
397
+ const nativePng = decodeURIComponent(value.slice(2));
398
+ if (!existsSync(nativePng)) return `the driver named a frame it did not write: ${nativePng}`;
399
+ const goldenPng = path.join(renders.goldensDir, golden.render.png);
400
+ let measured: IPixelComparison;
401
+ try {
402
+ measured = renders.compare(
403
+ readFileSync(goldenPng),
404
+ readFileSync(nativePng),
405
+ metric.levels ?? 0,
406
+ );
407
+ } catch (error) {
408
+ return `frame comparison failed: ${error instanceof Error ? error.message : String(error)}`;
409
+ }
410
+ const within =
411
+ measured.pixelMismatchRatio <= metric.maxPixelMismatchRatio &&
412
+ measured.perceptualDeltaE <= metric.maxPerceptualDeltaE;
413
+ return within
414
+ ? null
415
+ : `frame differs: pixelMismatchRatio ${measured.pixelMismatchRatio} (max ${metric.maxPixelMismatchRatio}), ` +
416
+ `perceptualDeltaE ${measured.perceptualDeltaE} (max ${metric.maxPerceptualDeltaE}); native ${nativePng}`;
417
+ }
418
+
419
+ /** The driver this machine has, or null. `--driver` wins over the environment. */
420
+ export function resolveDriver(
421
+ driver: string | null,
422
+ env: NodeJS.ProcessEnv = process.env,
423
+ ): string | null {
424
+ const chosen = driver ?? env.TN_NATIVE_FIXTURE_DRIVER ?? null;
425
+ return chosen === null || chosen === "" ? null : path.resolve(REPO_ROOT, chosen);
426
+ }