rayzee 5.3.8 → 5.4.1

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 (48) hide show
  1. package/dist/rayzee.es.js +2933 -2888
  2. package/dist/rayzee.es.js.map +1 -1
  3. package/dist/rayzee.umd.js +53 -53
  4. package/dist/rayzee.umd.js.map +1 -1
  5. package/package.json +2 -2
  6. package/src/Passes/AIUpscaler.js +30 -6
  7. package/src/Passes/OIDNDenoiser.js +57 -15
  8. package/src/PathTracerApp.js +154 -21
  9. package/src/Pipeline/RenderPipeline.js +10 -1
  10. package/src/Processor/AssetLoader.js +40 -18
  11. package/src/Processor/EquirectHDRInfo.js +38 -29
  12. package/src/Processor/InstanceTable.js +16 -0
  13. package/src/Processor/SceneProcessor.js +22 -33
  14. package/src/Processor/ShaderBuilder.js +67 -22
  15. package/src/Processor/TLASBuilder.js +9 -4
  16. package/src/Stages/ASVGF.js +4 -4
  17. package/src/Stages/AdaptiveSampling.js +2 -2
  18. package/src/Stages/AutoExposure.js +42 -32
  19. package/src/Stages/BilateralFilter.js +2 -2
  20. package/src/Stages/Display.js +2 -1
  21. package/src/Stages/EdgeFilter.js +6 -3
  22. package/src/Stages/MotionVector.js +2 -2
  23. package/src/Stages/NormalDepth.js +1 -1
  24. package/src/Stages/PathTracer.js +88 -46
  25. package/src/Stages/SSRC.js +4 -4
  26. package/src/Stages/Variance.js +2 -2
  27. package/src/TSL/BVHTraversal.js +15 -63
  28. package/src/TSL/Clearcoat.js +1 -1
  29. package/src/TSL/Displacement.js +1 -1
  30. package/src/TSL/EmissiveSampling.js +17 -13
  31. package/src/TSL/Environment.js +12 -9
  32. package/src/TSL/LightBVHSampling.js +3 -2
  33. package/src/TSL/LightsCore.js +1 -1
  34. package/src/TSL/LightsDirect.js +1 -1
  35. package/src/TSL/LightsIndirect.js +0 -1
  36. package/src/TSL/LightsSampling.js +2 -2
  37. package/src/TSL/MaterialTransmission.js +1 -1
  38. package/src/TSL/PathTracer.js +4 -4
  39. package/src/TSL/PathTracerCore.js +6 -6
  40. package/src/TSL/Struct.js +1 -1
  41. package/src/TSL/patches.js +145 -0
  42. package/src/index.js +1 -1
  43. package/src/managers/EnvironmentManager.js +32 -56
  44. package/src/managers/LightManager.js +20 -0
  45. package/src/managers/UniformManager.js +22 -0
  46. package/src/managers/helpers/OutlineHelper.js +3 -1
  47. package/src/TSL/storageTexturePatch.js +0 -31
  48. package/src/TSL/structProxy.js +0 -87
@@ -41,7 +41,7 @@ import {
41
41
  sampler,
42
42
  } from 'three/tsl';
43
43
 
44
- import { struct } from './structProxy.js';
44
+ import { struct } from './patches.js';
45
45
 
46
46
  import {
47
47
  PI_INV,
@@ -590,7 +590,7 @@ export const Trace = Fn( ( [
590
590
  spotLightsBuffer, numSpotLights,
591
591
  // Environment
592
592
  envTexture, environmentIntensity, envMatrix,
593
- envMarginalWeights, envConditionalWeights,
593
+ envCDFBuffer,
594
594
  envTotalSum, envResolution,
595
595
  enableEnvironmentLight, useEnvMapIS,
596
596
  // Rendering parameters
@@ -598,7 +598,7 @@ export const Trace = Fn( ( [
598
598
  backgroundIntensity, showBackground, transparentBackground,
599
599
  fireflyThreshold, globalIlluminationIntensity,
600
600
  totalTriangleCount, enableEmissiveTriangleSampling,
601
- emissiveTriangleBuffer, emissiveTriangleCount, emissiveTotalPower, emissiveBoost,
601
+ emissiveTriangleBuffer, emissiveVec4Offset, emissiveTriangleCount, emissiveTotalPower, emissiveBoost,
602
602
  lightBVHBuffer, lightBVHNodeCount,
603
603
  // Per-pixel info
604
604
  pixelCoord, resolution, frame,
@@ -1013,7 +1013,7 @@ export const Trace = Fn( ( [
1013
1013
  triangleBuffer,
1014
1014
  materialBuffer,
1015
1015
  envTexture, environmentIntensity, envMatrix,
1016
- envMarginalWeights, envConditionalWeights,
1016
+ envCDFBuffer,
1017
1017
  envTotalSum, envResolution,
1018
1018
  enableEnvironmentLight,
1019
1019
  );
@@ -1040,6 +1040,7 @@ export const Trace = Fn( ( [
1040
1040
  rngState,
1041
1041
  lightBVHBuffer,
1042
1042
  emissiveTriangleBuffer,
1043
+ emissiveVec4Offset,
1043
1044
  triangleBuffer,
1044
1045
  ) );
1045
1046
 
@@ -1091,7 +1092,7 @@ export const Trace = Fn( ( [
1091
1092
  hitInfo.hitPoint, N, V, material,
1092
1093
  totalTriangleCount, bounceIndex, rngState,
1093
1094
  emissiveBoost,
1094
- emissiveTriangleBuffer, emissiveTriangleCount, emissiveTotalPower,
1095
+ emissiveTriangleBuffer, emissiveVec4Offset, emissiveTriangleCount, emissiveTotalPower,
1095
1096
  triangleBuffer,
1096
1097
  traceShadowRayWrapped,
1097
1098
  evaluateMaterialResponse,
@@ -1132,7 +1133,6 @@ export const Trace = Fn( ( [
1132
1133
  rngState,
1133
1134
  samplingInfo,
1134
1135
  envTexture, environmentIntensity, envMatrix,
1135
- envMarginalWeights, envConditionalWeights,
1136
1136
  envTotalSum, envResolution,
1137
1137
  enableEnvironmentLight, useEnvMapIS,
1138
1138
  ) );
package/src/TSL/Struct.js CHANGED
@@ -1,4 +1,4 @@
1
- import { struct } from './structProxy.js';
1
+ import { struct } from './patches.js';
2
2
 
3
3
  export const Ray = struct( {
4
4
  origin: 'vec3',
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Rayzee patches for Three.js / TSL.
3
+ *
4
+ * Side-effect on import: installs `WebGPUBackend.createNodeBuilder` override
5
+ * (restores r183 function-scoped `var` emission for compute shaders — prevents
6
+ * a register-allocation regression in the path tracer's hot loop).
7
+ *
8
+ * Export: `struct()` — drop-in replacement for TSL's `struct()` returning
9
+ * a proxy factory that supports GLSL-style dot-notation field access.
10
+ */
11
+
12
+ import { WebGPUBackend } from 'three/webgpu';
13
+ import { struct as _struct } from 'three/tsl';
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // 1. WGSL global-variable promotion patch (compute-only)
17
+ // ---------------------------------------------------------------------------
18
+ // Three.js r184 introduced `WGSLNodeBuilder.allowGlobalVariables = true`, which
19
+ // emits `.toVar()` declarations at WGSL module scope as `var<private> name : T`
20
+ // instead of function-local `var name : T` inside `fn main()` (as r183 did).
21
+ //
22
+ // For compute shaders with hundreds of `.toVar()` calls in loops (e.g. the BVH
23
+ // traversal + BRDF path tracer), `var<private>` increases GPU register pressure
24
+ // because the Dawn/Chromium WGSL compiler cannot aggressively register-allocate
25
+ // variables with a stable per-invocation memory address. We measured a ~8% fps
26
+ // regression (120 → 110) on the path tracer after upgrading r183 → r184 that
27
+ // traced entirely to GPU execution, not CPU.
28
+ //
29
+ // `allowGlobalVariables` is ONLY consumed by the compute template
30
+ // (`_getWGSLComputeCode`). The vertex/fragment templates always emit
31
+ // `shaderData.vars` at module scope and REQUIRE `allowGlobalVariables=true`
32
+ // (emitting function-local `var` at module scope is invalid WGSL and crashes
33
+ // pipeline creation with "Invalid ShaderModule"). We install a per-instance
34
+ // accessor that returns `false` only when the builder is for a compute node
35
+ // (material === null) and `true` otherwise, so render pipelines keep r184
36
+ // behavior untouched.
37
+ //
38
+ // Relevant upstream lines:
39
+ // - `node_modules/three/src/renderers/webgpu/nodes/WGSLNodeBuilder.js:247`
40
+ // (`this.allowGlobalVariables = true`)
41
+ // - `...WGSLNodeBuilder.js:2458` (module-scope vars block)
42
+ // - `...WGSLNodeBuilder.js:2467` (function-body vars block)
43
+ //
44
+ // Revisit if upstream adds an official opt-out or fixes register pressure.
45
+
46
+ const _origCreateNodeBuilder = WebGPUBackend.prototype.createNodeBuilder;
47
+
48
+ WebGPUBackend.prototype.createNodeBuilder = function ( object, renderer ) {
49
+
50
+ const builder = _origCreateNodeBuilder.call( this, object, renderer );
51
+
52
+ Object.defineProperty( builder, 'allowGlobalVariables', {
53
+ get() {
54
+
55
+ return this.material !== null;
56
+
57
+ },
58
+ set() { /* ignore — the value is derived from material presence */ },
59
+ configurable: true,
60
+ } );
61
+
62
+ return builder;
63
+
64
+ };
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // 2. TSL struct proxy — enables GLSL-style dot-notation field access
68
+ // ---------------------------------------------------------------------------
69
+ // TSL structs require `.get('fieldName')` for member access, but GLSL-style
70
+ // dot notation (`.fieldName`) is more natural and matches ported code.
71
+ //
72
+ // This wraps TSL's `struct()` so that:
73
+ // - Direct construction: `MyStruct({...}).toVar('x')` → `.fieldName` works
74
+ // - Fn return values: `MyStruct.wrap(someFn(...))` → `.fieldName` works
75
+ //
76
+ // Property access for known struct member names is redirected to `.get('name')`.
77
+ // Swizzle properties (x, y, z, w, etc.), Node methods (.add, .assign, etc.), and
78
+ // other standard properties pass through to the underlying node unmodified.
79
+
80
+ function createStructProxy( node, memberSet ) {
81
+
82
+ return new Proxy( node, {
83
+
84
+ get( target, prop, receiver ) {
85
+
86
+ // Intercept known struct member names
87
+ if ( typeof prop === 'string' && memberSet.has( prop ) ) {
88
+
89
+ return target.get( prop );
90
+
91
+ }
92
+
93
+ const val = Reflect.get( target, prop, receiver );
94
+
95
+ // Intercept .toVar() to proxy-wrap the result
96
+ if ( prop === 'toVar' && typeof val === 'function' ) {
97
+
98
+ return ( ...args ) => createStructProxy( val.apply( target, args ), memberSet );
99
+
100
+ }
101
+
102
+ return val;
103
+
104
+ }
105
+
106
+ } );
107
+
108
+ }
109
+
110
+ /**
111
+ * Drop-in replacement for TSL's `struct()` that returns a proxy-enhanced factory.
112
+ *
113
+ * The returned factory:
114
+ * - Creates struct nodes where `.toVar()` results support dot-notation field access
115
+ * - Has `.wrap(node)` method to proxy-wrap Fn return values for field access
116
+ * - Has `.layout` and `.isStruct` matching the original TSL struct API
117
+ *
118
+ * @param {Object} members - Struct member layout (e.g., { didHit: 'bool', dst: 'float' })
119
+ * @param {string|null} name - Optional struct name
120
+ * @returns {Function} Enhanced struct factory
121
+ */
122
+ export function struct( members, name = null ) {
123
+
124
+ const factory = _struct( members, name );
125
+ const memberSet = new Set( Object.keys( members ) );
126
+
127
+ const wrappedFactory = ( ...args ) => {
128
+
129
+ const node = factory( ...args );
130
+ return createStructProxy( node, memberSet );
131
+
132
+ };
133
+
134
+ wrappedFactory.layout = factory.layout;
135
+ wrappedFactory.isStruct = true;
136
+
137
+ /**
138
+ * Wrap an existing node (e.g., Fn return value) with struct field access proxy.
139
+ * Usage: `const hit = HitInfo.wrap(traverseBVH(...).toVar('hit'));`
140
+ */
141
+ wrappedFactory.wrap = ( node ) => createStructProxy( node, memberSet );
142
+
143
+ return wrappedFactory;
144
+
145
+ }
package/src/index.js CHANGED
@@ -6,7 +6,7 @@
6
6
  */
7
7
 
8
8
  // Patches (side-effect imports — must run before any StorageTexture usage)
9
- import './TSL/storageTexturePatch.js';
9
+ import './TSL/patches.js';
10
10
 
11
11
  // Main application
12
12
  export { PathTracerApp } from './PathTracerApp.js';
@@ -43,11 +43,11 @@ export class EnvironmentManager {
43
43
  this.environmentTexture = this._envPlaceholder;
44
44
  this.envTexSize = new Vector2();
45
45
 
46
- // CDF storage buffers
47
- this.envMarginalStorageAttr = null;
48
- this.envMarginalStorageNode = null;
49
- this.envConditionalStorageAttr = null;
50
- this.envConditionalStorageNode = null;
46
+ // CDF storage buffer (marginal + conditional packed into one buffer).
47
+ // Layout: [ marginal (envResolution.y floats) | conditional (envResolution.x * envResolution.y floats) ]
48
+ // Conditional offset is the marginal length, which equals envResolution.y at runtime.
49
+ this.envCDFStorageAttr = null;
50
+ this.envCDFStorageNode = null;
51
51
  this._initCDFStorageBuffers();
52
52
 
53
53
  // Environment rotation
@@ -177,74 +177,52 @@ export class EnvironmentManager {
177
177
 
178
178
  }
179
179
 
180
- // ===== CDF STORAGE BUFFERS =====
180
+ // ===== CDF STORAGE BUFFER =====
181
181
 
182
182
  /**
183
- * Initialize CDF storage buffers with placeholder data.
184
- * Must be called before shader compilation so the nodes exist in the graph.
183
+ * Initialize the packed CDF storage buffer with placeholder data.
184
+ * Must be called before shader compilation so the node exists in the graph.
185
+ *
186
+ * Layout: [ marginal (size = envResolution.y) | conditional (size = envResolution.x * envResolution.y) ]
187
+ * Placeholder shape is a 1x2 env map: marginal=[0,1], conditional=[0,0,1,1].
185
188
  * @private
186
189
  */
187
190
  _initCDFStorageBuffers() {
188
191
 
189
- // Marginal: 1 float per entry, default placeholder
190
- const marginalPlaceholder = new Float32Array( [ 0, 1 ] );
191
- this.envMarginalStorageAttr = new StorageInstancedBufferAttribute( marginalPlaceholder, 1 );
192
- this.envMarginalStorageNode = storage( this.envMarginalStorageAttr, 'float', 2 ).toReadOnly();
193
-
194
- // Conditional: 1 float per entry, default placeholder
195
- const conditionalPlaceholder = new Float32Array( [ 0, 0, 1, 1 ] );
196
- this.envConditionalStorageAttr = new StorageInstancedBufferAttribute( conditionalPlaceholder, 1 );
197
- this.envConditionalStorageNode = storage( this.envConditionalStorageAttr, 'float', 4 ).toReadOnly();
198
-
199
- }
200
-
201
- /**
202
- * Update marginal CDF storage buffer from Float32Array.
203
- */
204
- setEnvMarginalData( floatData ) {
205
-
206
- if ( ! floatData ) return;
207
-
208
- this.envMarginalStorageAttr = new StorageInstancedBufferAttribute( floatData, 1 );
209
- this.envMarginalStorageNode.value = this.envMarginalStorageAttr;
210
- this.envMarginalStorageNode.bufferCount = floatData.length;
211
-
212
- }
213
-
214
- /**
215
- * Update conditional CDF storage buffer from Float32Array.
216
- */
217
- setEnvConditionalData( floatData ) {
218
-
219
- if ( ! floatData ) return;
220
-
221
- this.envConditionalStorageAttr = new StorageInstancedBufferAttribute( floatData, 1 );
222
- this.envConditionalStorageNode.value = this.envConditionalStorageAttr;
223
- this.envConditionalStorageNode.bufferCount = floatData.length;
192
+ const placeholder = new Float32Array( [ 0, 1, 0, 0, 1, 1 ] );
193
+ this.envCDFStorageAttr = new StorageInstancedBufferAttribute( placeholder, 1 );
194
+ this.envCDFStorageNode = storage( this.envCDFStorageAttr, 'float', placeholder.length ).toReadOnly();
224
195
 
225
196
  }
226
197
 
227
198
  /**
228
- * Update both CDF storage buffers from equirectHdrInfo.
199
+ * Update the packed CDF storage buffer from equirectHdrInfo.
200
+ * Concatenates marginal + conditional into one buffer.
229
201
  * @private
230
202
  */
231
203
  _updateCDFStorageBuffers() {
232
204
 
233
- this.setEnvMarginalData( this.equirectHdrInfo.marginalData );
234
- this.setEnvConditionalData( this.equirectHdrInfo.conditionalData );
205
+ const marginal = this.equirectHdrInfo.marginalData;
206
+ const conditional = this.equirectHdrInfo.conditionalData;
207
+ if ( ! marginal || ! conditional ) return;
208
+
209
+ const combined = new Float32Array( marginal.length + conditional.length );
210
+ combined.set( marginal, 0 );
211
+ combined.set( conditional, marginal.length );
212
+
213
+ this.envCDFStorageAttr = new StorageInstancedBufferAttribute( combined, 1 );
214
+ this.envCDFStorageNode.value = this.envCDFStorageAttr;
215
+ this.envCDFStorageNode.bufferCount = combined.length;
235
216
 
236
217
  }
237
218
 
238
219
  /**
239
- * Get CDF storage nodes for shader graph.
240
- * @returns {{ marginalNode: StorageNode, conditionalNode: StorageNode }}
220
+ * Get the packed CDF storage node for shader graph.
221
+ * @returns {{ cdfNode: StorageNode }}
241
222
  */
242
223
  getCDFStorageNodes() {
243
224
 
244
- return {
245
- marginalNode: this.envMarginalStorageNode,
246
- conditionalNode: this.envConditionalStorageNode,
247
- };
225
+ return { cdfNode: this.envCDFStorageNode };
248
226
 
249
227
  }
250
228
 
@@ -559,10 +537,8 @@ export class EnvironmentManager {
559
537
 
560
538
  this.proceduralSkyRenderer = null;
561
539
  this.simpleSkyRenderer = null;
562
- this.envMarginalStorageAttr = null;
563
- this.envMarginalStorageNode = null;
564
- this.envConditionalStorageAttr = null;
565
- this.envConditionalStorageNode = null;
540
+ this.envCDFStorageAttr = null;
541
+ this.envCDFStorageNode = null;
566
542
  this._envPlaceholder?.dispose();
567
543
  this._envPlaceholder = null;
568
544
  this.environmentTexture = null;
@@ -255,6 +255,26 @@ export class LightManager extends EventDispatcher {
255
255
 
256
256
  }
257
257
 
258
+ /**
259
+ * Releases all scene lights, helper nodes, and callback refs.
260
+ * Safe to call multiple times.
261
+ */
262
+ dispose() {
263
+
264
+ if ( this._disposed ) return;
265
+ this._disposed = true;
266
+
267
+ this.sceneHelpers?.clear();
268
+ this._removeAllLights();
269
+
270
+ // Drop external refs so GC can collect scene/pathTracer
271
+ this._onReset = null;
272
+ this.pathTracer = null;
273
+ this.sceneHelpers = null;
274
+ this.scene = null;
275
+
276
+ }
277
+
258
278
  // ── Private ───────────────────────────────────────────────────
259
279
 
260
280
  /** Syncs helpers in sceneHelpers with current scene lights. */
@@ -237,6 +237,9 @@ export class UniformManager {
237
237
  u( 'emissiveTriangleCount', 0, 'int' );
238
238
  u( 'emissiveTotalPower', 0.0, 'float' );
239
239
  u( 'lightBVHNodeCount', 0, 'int' );
240
+ // Offset (in vec4 elements) within the packed light buffer where emissive
241
+ // triangle data starts. Equals lightBVHNodeCount * LBVH_STRIDE; computed on upload.
242
+ u( 'emissiveVec4Offset', 0, 'int' );
240
243
 
241
244
  // Render mode
242
245
  u( 'renderMode', DEFAULT_STATE.renderMode, 'int' );
@@ -265,4 +268,23 @@ export class UniformManager {
265
268
 
266
269
  }
267
270
 
271
+ /**
272
+ * Releases uniform node references. Safe to call multiple times.
273
+ *
274
+ * Note: TSL uniform nodes are registered in the shader graph — once a
275
+ * compiled pipeline references them they are kept alive by the renderer
276
+ * until the pipeline is disposed. Clearing our maps here just drops the
277
+ * JS-side strong refs so UniformManager itself can be collected.
278
+ */
279
+ dispose() {
280
+
281
+ if ( this._disposed ) return;
282
+ this._disposed = true;
283
+
284
+ this._uniforms.clear();
285
+ this._booleans.clear();
286
+ this._lightBuffers = {};
287
+
288
+ }
289
+
268
290
  }
@@ -121,7 +121,9 @@ export class OutlineHelper {
121
121
  this.visible = false;
122
122
  this._outlineNode?.dispose();
123
123
  this._material?.dispose();
124
- this._quad?.dispose();
124
+ // QuadMesh extends Mesh — no dispose method on the mesh itself;
125
+ // its material is already disposed above. Just drop the ref.
126
+ this._quad = null;
125
127
 
126
128
  }
127
129
 
@@ -1,31 +0,0 @@
1
- /**
2
- * Monkey-patch for Three.js StorageTexture.setSize() bind group staleness.
3
- *
4
- * Bug: StorageTexture.setSize() calls dispose() but never sets needsUpdate = true.
5
- * The Bindings system tracks texture.version (incremented by needsUpdate setter)
6
- * to detect when bind groups need recreation. Without the version bump, the bind
7
- * group keeps referencing the destroyed GPUTextureView → writes silently fail.
8
- *
9
- * Three.js issue: https://github.com/mrdoob/three.js/issues/32969
10
- * Targeted fix: r184+ (2026-03-25)
11
- *
12
- * Import this module once at app startup (side-effect only).
13
- */
14
-
15
- import { StorageTexture } from 'three/webgpu';
16
-
17
- const _origSetSize = StorageTexture.prototype.setSize;
18
-
19
- StorageTexture.prototype.setSize = function ( width, height ) {
20
-
21
- const wasChanged = this.image.width !== width || this.image.height !== height;
22
-
23
- _origSetSize.call( this, width, height );
24
-
25
- if ( wasChanged ) {
26
-
27
- this.needsUpdate = true;
28
-
29
- }
30
-
31
- };
@@ -1,87 +0,0 @@
1
- /**
2
- * Proxy-enhanced struct factory for TSL.
3
- *
4
- * TSL structs require `.get('fieldName')` for member access, but GLSL-style
5
- * dot notation (`.fieldName`) is more natural and matches the ported code.
6
- *
7
- * This utility wraps TSL's `struct()` so that:
8
- * - Direct construction: `MyStruct({...}).toVar('x')` → `.fieldName` works automatically
9
- * - Fn return values: `MyStruct.wrap(someFn(...))` → `.fieldName` works automatically
10
- *
11
- * Internally, property access for known struct member names is redirected to `.get('name')`.
12
- * Swizzle properties (x, y, z, w, etc.), Node methods (.add, .assign, etc.), and other
13
- * standard properties pass through to the underlying node unmodified.
14
- */
15
-
16
- import { struct as _struct } from 'three/tsl';
17
-
18
- /**
19
- * Creates a Proxy around a TSL node that redirects struct member access to `.get('name')`.
20
- * Also intercepts `.toVar()` to ensure the resulting VarNode is also proxy-wrapped.
21
- */
22
- function createStructProxy( node, memberSet ) {
23
-
24
- return new Proxy( node, {
25
-
26
- get( target, prop, receiver ) {
27
-
28
- // Intercept known struct member names
29
- if ( typeof prop === 'string' && memberSet.has( prop ) ) {
30
-
31
- return target.get( prop );
32
-
33
- }
34
-
35
- const val = Reflect.get( target, prop, receiver );
36
-
37
- // Intercept .toVar() to proxy-wrap the result
38
- if ( prop === 'toVar' && typeof val === 'function' ) {
39
-
40
- return ( ...args ) => createStructProxy( val.apply( target, args ), memberSet );
41
-
42
- }
43
-
44
- return val;
45
-
46
- }
47
-
48
- } );
49
-
50
- }
51
-
52
- /**
53
- * Drop-in replacement for TSL's `struct()` that returns a proxy-enhanced factory.
54
- *
55
- * The returned factory:
56
- * - Creates struct nodes where `.toVar()` results support dot-notation field access
57
- * - Has `.wrap(node)` method to proxy-wrap Fn return values for field access
58
- * - Has `.layout` and `.isStruct` matching the original TSL struct API
59
- *
60
- * @param {Object} members - Struct member layout (e.g., { didHit: 'bool', dst: 'float' })
61
- * @param {string|null} name - Optional struct name
62
- * @returns {Function} Enhanced struct factory
63
- */
64
- export function struct( members, name = null ) {
65
-
66
- const factory = _struct( members, name );
67
- const memberSet = new Set( Object.keys( members ) );
68
-
69
- const wrappedFactory = ( ...args ) => {
70
-
71
- const node = factory( ...args );
72
- return createStructProxy( node, memberSet );
73
-
74
- };
75
-
76
- wrappedFactory.layout = factory.layout;
77
- wrappedFactory.isStruct = true;
78
-
79
- /**
80
- * Wrap an existing node (e.g., Fn return value) with struct field access proxy.
81
- * Usage: `const hit = HitInfo.wrap(traverseBVH(...).toVar('hit'));`
82
- */
83
- wrappedFactory.wrap = ( node ) => createStructProxy( node, memberSet );
84
-
85
- return wrappedFactory;
86
-
87
- }