Skip to main content

three_rs/nodes/
node.rs

1//! Port of `three.js/src/nodes/core/` — the node graph itself.
2//!
3//! Three's nodes are mutable JS objects that grow builder state as they are
4//! visited. Here a node is an immutable `Rc<Node>`; `Rc::as_ptr` gives it a
5//! stable identity, and every piece of per-build state the builder would have
6//! hung off the node (usage count, property name, varying slot, uniform slot)
7//! lives in the builder keyed by that identity. See `docs/nodes.md` §1.
8
9use std::cell::{Cell, RefCell};
10use std::hash::Hash;
11use std::rc::Rc;
12
13use crate::math::{Color, Matrix4, Vector2, Vector3};
14use crate::textures::{
15    CubeDepthTexture, CubeTexture, Data3DTexture, DataArrayTexture, DataTexture, DepthTexture,
16    Texture,
17};
18
19/// A WGSL value type. Three carries these as strings (`'vec3'`); the closed set
20/// is the part of `NodeBuilder`'s type vocabulary the ladder has reached.
21#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
22pub enum Type {
23    /// No value — a statement's type, or a `fn` with no return.
24    Void,
25    /// `bool`.
26    Bool,
27    /// `f32`.
28    F32,
29    /// `i32`.
30    I32,
31    /// `u32`.
32    U32,
33    /// `vec2<f32>`.
34    Vec2,
35    /// `vec3<f32>`.
36    Vec3,
37    /// `vec4<f32>`.
38    Vec4,
39    /// `vec2<u32>`.
40    UVec2,
41    /// `vec2<i32>`.
42    IVec2,
43    /// `vec3<u32>` — MaterialX's `mx_hash_vec3` packs its three byte hashes
44    /// into one.
45    UVec3,
46    /// `vec4<u32>` — the `skinIndex` attribute, which three.js declares
47    /// `attribute( 'skinIndex', 'uvec4' )` and uploads as a `Uint32Array`.
48    UVec4,
49    /// `vec3<i32>` / `vec4<i32>` — TSL's `ivec3()` / `ivec4()`.
50    IVec3,
51    /// `vec4<i32>` — TSL's `ivec4()`.
52    IVec4,
53    /// `vec2<bool>` / `vec3<bool>` / `vec4<bool>` — TSL's `bvec2()` … `bvec4()`,
54    /// and what a component-wise comparison of two vectors is.
55    BVec2,
56    /// `vec3<bool>`.
57    BVec3,
58    /// `vec4<bool>`.
59    BVec4,
60    /// `mat2` — `RotateNode`'s vec2 path emits `mat2x2<f32>( cos, sin, -sin, cos )`.
61    Mat2,
62    /// `mat3x3<f32>`.
63    Mat3,
64    /// `mat4x4<f32>`.
65    Mat4,
66}
67
68impl Type {
69    /// `NodeBuilder.getTypeLength()`.
70    pub fn components(self) -> usize {
71        match self {
72            Type::Void => 0,
73            Type::Bool | Type::F32 | Type::I32 | Type::U32 => 1,
74            Type::Vec2 | Type::UVec2 | Type::IVec2 | Type::BVec2 => 2,
75            Type::Vec3 | Type::UVec3 | Type::IVec3 | Type::BVec3 => 3,
76            Type::Vec4 | Type::UVec4 | Type::IVec4 | Type::BVec4 => 4,
77            Type::Mat2 => 4,
78            Type::Mat3 => 9,
79            Type::Mat4 => 16,
80        }
81    }
82
83    /// `NodeBuilder.getComponentType()`.
84    pub fn component_type(self) -> Type {
85        match self {
86            Type::UVec2 | Type::UVec3 | Type::UVec4 => Type::U32,
87            Type::IVec2 | Type::IVec3 | Type::IVec4 => Type::I32,
88            Type::BVec2 | Type::BVec3 | Type::BVec4 => Type::Bool,
89            Type::Vec2 | Type::Vec3 | Type::Vec4 | Type::Mat2 | Type::Mat3 | Type::Mat4 => {
90                Type::F32
91            }
92            other => other,
93        }
94    }
95
96    /// The vector type with `self`'s component type and `n` components.
97    pub fn vector_of(component: Type, n: usize) -> Type {
98        match (component, n) {
99            (_, 1) => component,
100            (Type::U32, 2) => Type::UVec2,
101            (Type::I32, 2) => Type::IVec2,
102            (Type::U32, 3) => Type::UVec3,
103            (Type::I32, 3) => Type::IVec3,
104            (Type::I32, 4) => Type::IVec4,
105            (Type::Bool, 2) => Type::BVec2,
106            (Type::Bool, 3) => Type::BVec3,
107            (Type::Bool, 4) => Type::BVec4,
108            (Type::F32, 2) => Type::Vec2,
109            (Type::F32, 3) => Type::Vec3,
110            (Type::F32, 4) => Type::Vec4,
111            (Type::U32, 4) => Type::UVec4,
112            other => panic!("three-rs: the node builder only makes vectors of {other:?}"),
113        }
114    }
115
116    /// Whether this is one of the matrix types.
117    pub fn is_matrix(self) -> bool {
118        matches!(self, Type::Mat2 | Type::Mat3 | Type::Mat4)
119    }
120}
121
122/// Which of the generated shader's uniform blocks a uniform lives in.
123///
124/// Three has a `UniformGroupNode` per uniform; the ladder uses `renderGroup`
125/// (per render call — camera, time, viewport), `objectGroup` (per render
126/// object — model matrices, material values) and, under an `ArrayCamera`,
127/// `sharedUniformGroup( 'cameraIndex' )` — the one `u32` the backend swaps
128/// per sub-camera (`docs/nodes.md` §40).
129#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
130pub enum UniformGroup {
131    /// `renderGroup` — per render call: camera, time, viewport.
132    Render,
133    /// `cameraIndex`'s group, which three sorts between the two others
134    /// (`@group( 1 )` in `webgpu_camera_array`'s dump).
135    CameraIndex,
136    /// `objectGroup` — per render object: model matrices, material values.
137    Object,
138}
139
140impl UniformGroup {
141    /// The order the groups take their `@group( n )` indices in, each one
142    /// only when it has a binding.
143    pub(crate) const ORDER: [UniformGroup; 3] = [
144        UniformGroup::Render,
145        UniformGroup::CameraIndex,
146        UniformGroup::Object,
147    ];
148
149    pub(crate) fn struct_name(self) -> &'static str {
150        match self {
151            UniformGroup::Render => "render",
152            UniformGroup::CameraIndex => "cameraIndex",
153            UniformGroup::Object => "object",
154        }
155    }
156}
157
158/// How often a uniform block has to be rewritten — `Node.updateType`.
159#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
160pub enum UpdateType {
161    /// Written once per render call.
162    Render,
163    /// Written once per render object.
164    Object,
165}
166
167/// Where a uniform's bytes come from. The renderer owns the values; the node
168/// graph only names them. This is the whole of `NodeUpdateType` /
169/// `UniformNode.update()` for the ladder so far.
170#[derive(Clone, Debug, PartialEq)]
171#[non_exhaustive]
172pub enum UniformSource {
173    /// `cameraProjectionMatrix` — `camera.projectionMatrix`.
174    CameraProjectionMatrix,
175    /// `cameraViewMatrix` — `camera.matrixWorldInverse`.
176    CameraViewMatrix,
177    /// `cameraIndex` — `uniform( 0, 'uint' ).setName( 'u_cameraIndex' )`, the
178    /// sub-camera an `ArrayCamera` draw is for. The backend binds one group
179    /// per sub-camera rather than rewriting it, so the value written here is
180    /// never read; see `Draw::sub_cameras` in the renderer.
181    CameraIndex,
182    /// `cameraWorldMatrix` — `camera.matrixWorld`.
183    CameraWorldMatrix,
184    /// `cameraPosition` — `camera.matrixWorld`'s translation, which
185    /// `getIBLVolumeRefraction` takes the world-space view vector from.
186    CameraPosition,
187    /// `modelWorldMatrix` — `object.matrixWorld`.
188    ModelWorldMatrix,
189    /// `modelNormalMatrix` — `object.normalMatrix`.
190    ModelNormalMatrix,
191    /// `cameraProjectionMatrixInverse` — `camera.projectionMatrixInverse`.
192    /// `Line2NodeMaterial.setupPosition()` needs it to push a clip-space
193    /// position back through the camera.
194    CameraProjectionMatrixInverse,
195    /// `modelWorldMatrixInverse` — `uniform( new Matrix4() ).onObjectUpdate( (
196    /// { object }, self ) => self.value.copy( object.matrixWorld ).invert() )`.
197    ModelWorldMatrixInverse,
198    /// `materialColor` — `MeshBasicMaterial.color` in the working space.
199    MaterialColor,
200    /// `materialOpacity` — `Material.opacity`.
201    MaterialOpacity,
202    /// `materialAlphaTest` — `Material.alphaTest`.
203    MaterialAlphaTest,
204    /// `materialReflectivity` — `MeshLambertMaterial.reflectivity` and
205    /// friends.
206    MaterialReflectivity,
207    /// `materialEnvIntensity` — `MeshStandardMaterial.envMapIntensity`, the
208    /// scale `EnvironmentNode` puts on both IBL terms.
209    MaterialEnvIntensity,
210    /// `materialRotation` — `SpriteMaterial.rotation`.
211    MaterialRotation,
212    /// `MeshPhongMaterial.shininess` / `.specular` / `.emissive` /
213    /// `.emissiveIntensity`.
214    MaterialShininess,
215    /// `MeshPhongMaterial.specular`.
216    MaterialSpecular,
217    /// `MeshPhongMaterial.emissive` / `MeshStandardMaterial.emissive`.
218    MaterialEmissive,
219    /// `emissiveIntensity` — the scale on [`UniformSource::MaterialEmissive`].
220    MaterialEmissiveIntensity,
221    /// `materialAnisotropyVector` — `MeshPhysicalMaterial.anisotropy` and
222    /// `.anisotropyRotation` as one `vec2( a * cos( r ), a * sin( r ) )`.
223    MaterialAnisotropyVector,
224    /// `MeshPhysicalMaterial.clearcoat` / `.clearcoatRoughness` /
225    /// `.clearcoatNormalScale`.
226    MaterialClearcoat,
227    /// `MeshPhysicalMaterial.clearcoatRoughness`.
228    MaterialClearcoatRoughness,
229    /// `MeshPhysicalMaterial.clearcoatNormalScale`.
230    MaterialClearcoatNormalScale,
231    /// `MeshPhysicalMaterial.transmission` / `.thickness` /
232    /// `.attenuationDistance` / `.attenuationColor` — `KHR_materials_transmission`
233    /// and `KHR_materials_volume`.
234    MaterialTransmission,
235    /// `MeshPhysicalMaterial.thickness`.
236    MaterialThickness,
237    /// `MeshPhysicalMaterial.attenuationDistance`.
238    MaterialAttenuationDistance,
239    /// `MeshPhysicalMaterial.attenuationColor`, in the working space.
240    MaterialAttenuationColor,
241    /// `materialEnvRotation` — the env map's rotation matrix.
242    EnvRotationMatrix,
243    /// `backgroundRotation` — `scene.backgroundRotation`.
244    BackgroundRotation,
245    /// `backgroundBlurriness` — `scene.backgroundBlurriness`.
246    BackgroundBlurriness,
247    /// `backgroundIntensity` — `scene.backgroundIntensity`.
248    BackgroundIntensity,
249    /// `reference( 'color' | 'near' | 'far' | 'density', …, scene.fog )
250    /// .setGroup( renderGroup )` — the classic `scene.fog`'s parameters, which
251    /// `NodeManager.updateFog()` binds as render-group uniforms so that a fog
252    /// whose values change never rebuilds a program. The colour is in the
253    /// working space.
254    FogColor,
255    /// `scene.fog.near` — `Fog`'s linear near distance.
256    FogNear,
257    /// `scene.fog.far` — `Fog`'s linear far distance.
258    FogFar,
259    /// `scene.fog.density` — `FogExp2`'s density.
260    FogDensity,
261    /// `time` — `TimerNode.GLOBAL`, seconds since the renderer started.
262    Time,
263    /// `deltaTime` — `TimerNode.DELTA`, `frame.deltaTime`: the seconds since
264    /// the previous `NodeFrame.update()`.
265    DeltaTime,
266    /// `frameId` — `TimerNode.FRAME`, `uniform( 0, 'uint' )` updated from
267    /// `frame.frameId`: the count of `NodeFrame.update()` calls.
268    FrameId,
269    /// `viewportSize` — the render target's pixel dimensions.
270    ViewportSize,
271    /// `viewport` — `ScreenNode.VIEWPORT`, the whole rectangle as
272    /// `( x, y, width, height )` in physical pixels. `ScreenNode.update()`
273    /// takes it from the bound render target, or from
274    /// `renderer.getViewport()` times the pixel ratio.
275    Viewport,
276    /// `screenDPR` — `uniform( 1 ).onRenderUpdate( ( { renderer } ) =>
277    /// renderer.getPixelRatio() )`.
278    ScreenDpr,
279    /// `cameraNear` — `uniform( 'float' ).setName( 'cameraNear' )
280    /// .setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near )`.
281    CameraNear,
282    /// `cameraFar` — as [`UniformSource::CameraNear`], from `camera.far`.
283    CameraFar,
284    /// `LightsNode`'s per-light members, by index into the renderer's light
285    /// list for the pass. The dumps put all four in the **render** group:
286    /// `light.color * light.intensity` (linear), the cutoff distance, the decay
287    /// exponent, and the light's position through the camera view matrix.
288    LightColorIntensity(usize),
289    /// The cutoff distance — see [`UniformSource::LightColorIntensity`].
290    LightCutoffDistance(usize),
291    /// The decay exponent — see [`UniformSource::LightColorIntensity`].
292    LightDecay(usize),
293    /// The light's position through the camera view matrix — see
294    /// [`UniformSource::LightColorIntensity`].
295    LightViewPosition(usize),
296    /// `Morph.js`' `base = uniform( 1 )`, updated per object to
297    /// `1 - Σ morphTargetInfluences` (or 1 when the targets are relative).
298    MorphBase,
299    /// `lightPosition( light )` / `lightTargetPosition( light )` — the world
300    /// positions `lightTargetDirection` differences.
301    LightWorldPosition(usize),
302    /// `lightTargetPosition( light )` — see [`UniformSource::LightWorldPosition`].
303    LightTargetPosition(usize),
304    /// `HemisphereLightNode`: `light.groundColor * light.intensity` (linear).
305    LightGroundColor(usize),
306    /// `SpotLightNode`'s `coneCosNode` / `penumbraCosNode`.
307    LightConeCos(usize),
308    /// `SpotLightNode.penumbraCosNode` — see [`UniformSource::LightConeCos`].
309    LightPenumbraCos(usize),
310    /// `ShadowNode`'s per-shadow references: `lightShadowMatrix( light )`, the
311    /// shadow camera's near and far planes (`PointShadowNode`) and
312    /// `reference( …, shadow )` for the five scalars.
313    ShadowMatrix(usize),
314    /// The shadow camera's near plane — see [`UniformSource::ShadowMatrix`].
315    ShadowCameraNear(usize),
316    /// The shadow camera's far plane — see [`UniformSource::ShadowMatrix`].
317    ShadowCameraFar(usize),
318    /// `reference( 'bias', 'float', shadow )`.
319    ShadowBias(usize),
320    /// `reference( 'normalBias', 'float', shadow )`.
321    ShadowNormalBias(usize),
322    /// `reference( 'radius', 'float', shadow )` — the blur radius.
323    ShadowRadius(usize),
324    /// `reference( 'blurSamples', 'float', shadow )` — the VSM blur passes'
325    /// tap count.
326    ShadowBlurSamples(usize),
327    /// `reference( 'mapSize', 'vec2', shadow )` — the shadow map's resolution.
328    ShadowMapSize(usize),
329    /// `reference( 'intensity', 'float', shadow )`.
330    ShadowIntensity(usize),
331    /// `materialLineWidth` — `MaterialNode.LINE_WIDTH`, i.e.
332    /// `material.linewidth`. Only a fat-line material reads it; a hairline
333    /// `Line` ignores it, as WebGL and WebGPU both do.
334    MaterialLineWidth,
335    /// `materialMetalness` / `materialRoughness` / `materialBumpScale`.
336    MaterialMetalness,
337    /// `MeshStandardMaterial.roughness`.
338    MaterialRoughness,
339    /// `MeshStandardMaterial.bumpScale`.
340    MaterialBumpScale,
341    /// `MeshPhysicalMaterial`'s `ior` / `specularIntensity` / `specularColor`,
342    /// and `MeshStandardMaterial.normalScale`.
343    MaterialIor,
344    /// `MeshPhysicalMaterial.specularIntensity`.
345    MaterialSpecularIntensity,
346    /// `MeshPhysicalMaterial.specularColor`, in the working space.
347    MaterialSpecularColor,
348    /// `MeshPhysicalMaterial.sheen` / `.sheenColor` / `.sheenRoughness`.
349    MaterialSheen,
350    /// `MeshPhysicalMaterial.sheenColor`, in the working space.
351    MaterialSheenColor,
352    /// `MeshPhysicalMaterial.sheenRoughness`.
353    MaterialSheenRoughness,
354    /// `MeshPhysicalMaterial.diffuseRoughness`.
355    MaterialDiffuseRoughness,
356    /// `MeshPhysicalMaterial.iridescence` — `KHR_materials_iridescence`.
357    MaterialIridescence,
358    /// `MeshPhysicalMaterial.iridescenceIOR`.
359    MaterialIridescenceIor,
360    /// `iridescenceThicknessRange[ 1 ]` — three reaches the range through
361    /// `reference( '1', 'float', material.iridescenceThicknessRange )` and
362    /// `reference( '0', … )`, two separate float uniforms, the maximum built
363    /// first.
364    MaterialIridescenceThicknessMax,
365    /// `iridescenceThicknessRange[ 0 ]`.
366    MaterialIridescenceThicknessMin,
367    /// `MeshStandardMaterial.normalScale`.
368    MaterialNormalScale,
369    /// `MeshStandardMaterial.aoMapIntensity` — the scale in `materialAO`'s
370    /// `tex.r.sub( 1 ).mul( aoMapIntensity ).add( 1 )`.
371    MaterialAoMapIntensity,
372    /// `material.lightMapIntensity` (`MeshBasicMaterial`, `MeshLambertMaterial`,
373    /// `MeshPhongMaterial`, `MeshStandardMaterial`, `MeshToonMaterial`) — the
374    /// scale in `materialLightMap`'s `tex.rgb.mul( lightMapIntensity )`.
375    MaterialLightMapIntensity,
376    /// `PointsMaterial.size` — `materialPointSize`.
377    MaterialPointSize,
378    /// `toneMappingExposure` — `renderer.toneMappingExposure`.
379    ToneMappingExposure,
380    /// `reference( 'bindMatrix', 'mat4' )` / `reference( 'bindMatrixInverse',
381    /// 'mat4' )` — `SkinnedMesh`'s two bind matrices, in the object group.
382    BindMatrix,
383    /// `bindMatrixInverse` — see [`UniformSource::BindMatrix`].
384    BindMatrixInverse,
385    /// `reference( 'center', 'vec2', object )` — `Sprite.center`, read by
386    /// `SpriteNodeMaterial.setupPositionView()`, in the object group.
387    ObjectCenter,
388    /// `VelocityNode.previousModelWorldMatrix` — the object's `matrixWorld`
389    /// as the last velocity draw of it left it (`getPreviousMatrix( object
390    /// )`), in the object group. See [`crate::nodes::velocity`].
391    PreviousModelWorldMatrix,
392    /// `VelocityNode.currentProjectionMatrix` — the camera's projection, or
393    /// the unjittered one `setProjectionMatrix()` handed the node, in the
394    /// render group.
395    VelocityProjectionMatrix,
396    /// `VelocityNode.previousProjectionMatrix` — last frame's
397    /// `currentProjectionMatrix` for this camera.
398    PreviousProjectionMatrix,
399    /// `VelocityNode.previousCameraViewMatrix` — last frame's
400    /// `camera.matrixWorldInverse` for this camera.
401    PreviousCameraViewMatrix,
402    /// A plain `uniform( value )` the example supplies.
403    Value(Vec<f64>),
404    /// `uniform( value )` whose `.value` is written between draws — three.js'
405    /// `UniformNode` is always this; [`UniformSource::Value`] is the special
406    /// case of one that never moves. `SSAAPassNode.sampleWeight` is the port's
407    /// first: one node, one program, eight different values across the eight
408    /// accumulation draws of a frame.
409    Settable(SettableValue),
410    /// A `uniform()` inside a node whose `updateType` is
411    /// `NodeUpdateType.OBJECT`: three calls `node.update( frame )` with
412    /// `frame.object` set to the render object about to be drawn, and the
413    /// callback writes `uniformNode.value` before that object's bindings are
414    /// built. `webgpu_instance_uniform`'s `InstanceUniformNode` is the ladder's
415    /// first — twelve meshes share one material, one program and one pipeline,
416    /// and differ only in the three floats this uniform resolves to.
417    ///
418    /// The port has no place to hang a `mesh.color` the way the page does, so
419    /// the callback receives the object itself and answers from whatever the
420    /// application keyed to it. See `docs/nodes.md` §18.
421    ObjectUpdate(ObjectUpdate),
422    /// A uniform that holds a *reference* to an application object and reads
423    /// it when the buffer is written: three's `uniform( skinnedMesh.bindMatrix
424    /// )` (the `Matrix4` itself, not a copy of its elements) and
425    /// `objectWorldMatrix( object3d )` (`Object3DNode` with an explicit object,
426    /// whose `OBJECT` update reads `object3d.matrixWorld`). Unlike
427    /// [`UniformSource::ObjectUpdate`] it does not need a render object, so a
428    /// compute kernel can read it: `computeSkinning()` and
429    /// `webgpu_skinning_points` are the first. See `docs/nodes.md` §44.
430    Live(LiveValue),
431    /// `cameraNormalMatrix` — `uniform( camera.normalMatrix )`. Nothing in
432    /// `WebGPURenderer` ever writes a camera's `normalMatrix` (only
433    /// `WebGLRenderer` updates it, and only for the objects it draws), so
434    /// three uploads the identity it was constructed with, and so does this.
435    CameraNormalMatrix,
436    /// `materialRefractionRatio` — `uniform( 0 ).onObjectUpdate( ( { material
437    /// } ) => material.refractionRatio )`.
438    MaterialRefractionRatio,
439    /// `highpModelViewMatrix` — `uniform( 'mat4' ).onObjectUpdate( … )`:
440    /// `camera.matrixWorldInverse * object.matrixWorld`, multiplied on the CPU
441    /// in double precision.
442    HighpModelViewMatrix,
443    /// `highpModelNormalViewMatrix` — the normal matrix of
444    /// [`UniformSource::HighpModelViewMatrix`]'s product, per object.
445    HighpModelNormalViewMatrix,
446    /// `Object3DNode`'s vector and scalar scopes: [`Object3DScope`] of the
447    /// object drawn (`ModelNode`, `object` `None`) or of an explicit one
448    /// (`objectPosition( object3d )` and friends), whose `matrixWorld` the
449    /// [`LiveValue`] reads when the buffer is written.
450    Object3D {
451        /// Which value of the object.
452        scope: Object3DScope,
453        /// The explicit object's `matrixWorld`, or `None` for the object the
454        /// draw is for. For [`Object3DScope::Direction`] it is instead the
455        /// world direction itself, three components, since
456        /// `getWorldDirection()` refreshes the object's world matrix and
457        /// negates for a camera, which only the object can tell.
458        object: Option<LiveValue>,
459    },
460}
461
462/// `Object3DNode`'s scopes other than `WORLD_MATRIX`, which has a uniform
463/// source of its own ([`UniformSource::ModelWorldMatrix`], or
464/// [`UniformSource::Live`] for an explicit object).
465#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
466#[non_exhaustive]
467pub enum Object3DScope {
468    /// `POSITION` — `setFromMatrixPosition( matrixWorld )`, a `vec3`.
469    Position,
470    /// `SCALE` — `setFromMatrixScale( matrixWorld )`, a `vec3`.
471    Scale,
472    /// `DIRECTION` — `getWorldDirection()`, the normalised `+z` column of
473    /// `matrixWorld`, a `vec3`.
474    Direction,
475    /// `VIEW_POSITION` — the world position through the rendering camera's
476    /// `matrixWorldInverse`, a `vec3`.
477    ViewPosition,
478    /// `RADIUS` — the bounding sphere of the *drawn* object's geometry,
479    /// through the scoped object's `matrixWorld`, a `float`. three reads
480    /// `frame.object.geometry` even for an explicit object, and so does this.
481    Radius,
482}
483
484/// The reader behind [`UniformSource::Live`]. Compares and hashes by
485/// identity, like [`SettableValue`]: the value moves, the program does not.
486#[derive(Clone)]
487pub struct LiveValue(Rc<dyn Fn() -> Vec<f64>>);
488
489impl LiveValue {
490    pub(crate) fn new(read: impl Fn() -> Vec<f64> + 'static) -> Self {
491        Self(Rc::new(read))
492    }
493
494    /// The value now.
495    pub(crate) fn get(&self) -> Vec<f64> {
496        (self.0)()
497    }
498}
499
500impl std::fmt::Debug for LiveValue {
501    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
502        f.debug_tuple("LiveValue")
503            .field(&Rc::as_ptr(&self.0).cast::<u8>())
504            .finish()
505    }
506}
507
508impl PartialEq for LiveValue {
509    fn eq(&self, other: &Self) -> bool {
510        Rc::ptr_eq(&self.0, &other.0)
511    }
512}
513
514impl std::hash::Hash for LiveValue {
515    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
516        (Rc::as_ptr(&self.0).cast::<u8>() as usize).hash(state);
517    }
518}
519
520/// The callback behind [`UniformSource::ObjectUpdate`] — `Node.update( frame )`
521/// narrowed to what an `OBJECT` update can read: `frame.object`, and the one
522/// question a node on the ladder asks `frame.renderer`, `isOccluded()`.
523///
524/// Two callbacks with the same behaviour are still two uniforms, so, like
525/// [`SettableValue`], this compares by identity: the program cache must not
526/// merge two per-object uniforms that happen to be spelled alike.
527#[derive(Clone)]
528pub struct ObjectUpdate(Rc<ObjectUpdateFn>);
529
530/// The body of an [`ObjectUpdate`]: three's `update( frame )`.
531pub(crate) type ObjectUpdateFn = dyn Fn(&NodeFrame) -> Vec<f64>;
532
533/// `NodeFrame` as a node's `update( frame )` sees it, narrowed to what the
534/// port's object-update uniforms read.
535///
536/// three hands the node the whole frame, renderer included; the port hands it
537/// the render object and the renderer's occlusion results for the render
538/// context being drawn, which is all `frame.renderer.isOccluded( object )`
539/// reads (`webgpu_occlusion`, `docs/nodes.md` §39).
540///
541/// This is the per-object view of the frame. The frame itself — `frameId`,
542/// `renderId`, the clock and the update maps — is
543/// [`NodeFrameState`](crate::nodes::NodeFrameState), which the renderer owns
544/// (`docs/nodes.md` §57).
545#[derive(Clone, Copy)]
546pub struct NodeFrame<'a> {
547    /// `frame.object` — the render object about to be drawn.
548    pub object: &'a crate::core::Object3D,
549    /// `renderContextData.occluded` for the current render context: the ids of
550    /// the objects whose last resolved occlusion query drew no samples. `None`
551    /// until a query has resolved, as three's is `undefined`.
552    pub(crate) occluded: Option<&'a std::collections::HashSet<u32>>,
553}
554
555impl<'a> NodeFrame<'a> {
556    /// `frame.renderer.isOccluded( object )`: whether the last occlusion query
557    /// the current render context resolved for `object` drew no samples.
558    /// Results arrive asynchronously, a frame or more after the draw, so this
559    /// is `false` until then, as it is in three.
560    pub fn is_occluded(&self, object: &crate::core::Object3D) -> bool {
561        self.occluded.is_some_and(|set| set.contains(&object.id))
562    }
563}
564
565impl ObjectUpdate {
566    pub(crate) fn new(update: impl Fn(&crate::core::Object3D) -> Vec<f64> + 'static) -> Self {
567        Self(Rc::new(move |frame: &NodeFrame| update(frame.object)))
568    }
569
570    /// An update that reads more of the frame than its object — see
571    /// [`NodeFrame`].
572    pub(crate) fn with_frame(update: impl Fn(&NodeFrame) -> Vec<f64> + 'static) -> Self {
573        Self(Rc::new(update))
574    }
575
576    /// `node.update( frame )` — the value for one render object.
577    pub(crate) fn value(&self, frame: &NodeFrame) -> Vec<f64> {
578        (self.0)(frame)
579    }
580}
581
582impl std::fmt::Debug for ObjectUpdate {
583    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
584        f.debug_tuple("ObjectUpdate")
585            .field(&Rc::as_ptr(&self.0).cast::<u8>())
586            .finish()
587    }
588}
589
590impl PartialEq for ObjectUpdate {
591    fn eq(&self, other: &Self) -> bool {
592        Rc::ptr_eq(&self.0, &other.0)
593    }
594}
595
596impl std::hash::Hash for ObjectUpdate {
597    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
598        (Rc::as_ptr(&self.0).cast::<u8>() as usize).hash(state);
599    }
600}
601
602/// The cell behind [`UniformSource::Settable`]. Two cells with equal contents
603/// are still two uniforms, so this compares and hashes by identity — a value
604/// that changes must not be part of any cache key.
605#[derive(Clone, Debug)]
606pub struct SettableValue(Rc<RefCell<Vec<f64>>>);
607
608impl SettableValue {
609    /// Wraps a starting value.
610    pub fn new(values: Vec<f64>) -> Self {
611        Self(Rc::new(RefCell::new(values)))
612    }
613
614    /// `uniformNode.value = …`.
615    pub fn set(&self, values: Vec<f64>) {
616        *self.0.borrow_mut() = values;
617    }
618
619    /// `uniformNode.value`.
620    pub fn get(&self) -> Vec<f64> {
621        self.0.borrow().clone()
622    }
623}
624
625impl PartialEq for SettableValue {
626    fn eq(&self, other: &Self) -> bool {
627        Rc::ptr_eq(&self.0, &other.0)
628    }
629}
630
631impl std::hash::Hash for SettableValue {
632    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
633        (Rc::as_ptr(&self.0) as *const u8 as usize).hash(state);
634    }
635}
636
637impl UniformSource {
638    pub(crate) fn update_type(&self) -> UpdateType {
639        match self {
640            UniformSource::ModelWorldMatrix
641            | UniformSource::ModelNormalMatrix
642            | UniformSource::MaterialColor
643            | UniformSource::MaterialOpacity
644            | UniformSource::MaterialAlphaTest
645            | UniformSource::MaterialReflectivity
646            | UniformSource::MaterialEnvIntensity
647            | UniformSource::MaterialShininess
648            | UniformSource::MaterialSpecular
649            | UniformSource::MaterialEmissive
650            | UniformSource::MaterialEmissiveIntensity
651            | UniformSource::ModelWorldMatrixInverse
652            | UniformSource::MaterialLineWidth
653            | UniformSource::MaterialMetalness
654            | UniformSource::MaterialRoughness
655            | UniformSource::MaterialBumpScale
656            | UniformSource::MaterialIor
657            | UniformSource::MaterialSpecularIntensity
658            | UniformSource::MaterialSpecularColor
659            | UniformSource::MaterialSheen
660            | UniformSource::MaterialSheenColor
661            | UniformSource::MaterialSheenRoughness
662            | UniformSource::MaterialDiffuseRoughness
663            | UniformSource::MaterialIridescence
664            | UniformSource::MaterialIridescenceIor
665            | UniformSource::MaterialIridescenceThicknessMax
666            | UniformSource::MaterialIridescenceThicknessMin
667            | UniformSource::MaterialNormalScale
668            | UniformSource::MaterialAoMapIntensity
669            | UniformSource::MaterialLightMapIntensity
670            | UniformSource::MaterialPointSize
671            | UniformSource::EnvRotationMatrix
672            | UniformSource::MorphBase
673            | UniformSource::BindMatrix
674            | UniformSource::BindMatrixInverse
675            | UniformSource::ObjectCenter
676            | UniformSource::PreviousModelWorldMatrix
677            | UniformSource::Value(_)
678            | UniformSource::Settable(_)
679            | UniformSource::ObjectUpdate(_)
680            | UniformSource::Live(_) => UpdateType::Object,
681            _ => UpdateType::Render,
682        }
683    }
684}
685
686/// `UniformNode`.
687#[derive(Debug)]
688pub struct UniformNode {
689    /// Where the uniform's bytes come from.
690    pub source: UniformSource,
691    /// The uniform's WGSL type.
692    pub ty: Type,
693    /// Which uniform block the uniform is bound in.
694    pub group: UniformGroup,
695    /// Three names camera uniforms explicitly and numbers the rest
696    /// `nodeUniformN`. A `Cell` because three's `UniformNode.setName()`
697    /// renames the node in place, so every reference to it sees the new name
698    /// ([`NodeRef::set_name`] on a uniform).
699    pub name: std::cell::Cell<Option<&'static str>>,
700}
701
702/// Where an array-typed uniform buffer's contents come from — `BufferNode`.
703#[derive(Clone, PartialEq)]
704#[non_exhaustive]
705pub enum BufferSource {
706    /// `InstancedMesh.instanceMatrix`.
707    InstanceMatrix,
708    /// `InstancedMesh.instanceColor` — `setColorAt()`'s three floats per
709    /// instance, always a `stepMode: 'instance'` vertex buffer (three.js wraps
710    /// it in a fresh `InstancedBufferAttribute( colors.array, 3 )` and never
711    /// takes the uniform branch for it).
712    InstanceColor,
713    /// `RangeNode` resolved per instance:
714    /// `lerp( min[c], max[c], Math.random() )`. `min`/`max` are the `Vector4`s
715    /// `RangeNode.setup()` builds out of the min/max values: a scalar splats
716    /// into all four components, a `Color` fills `xyz` and leaves `w` at 1, and
717    /// any other vector takes `x`, `y`, `z || 0`, `w || 0` — so a `vec3` range
718    /// has `w` **0** at both ends, not 1.
719    Range {
720        /// The low end of the range, one component per channel.
721        min: [f64; 4],
722        /// The high end of the range, one component per channel.
723        max: [f64; 4],
724    },
725    /// `Morph.js`' `uniformArray( mesh.morphTargetInfluences, 'float' )` — one
726    /// `vec4` per morph target with the influence in `.x`.
727    MorphInfluences,
728    /// `uniformArray( values )` — a constant array the application supplies,
729    /// already padded to one `vec4` per element the way
730    /// `UniformArrayNode.updateBuffer()` pads it. `BloomNode.bloomTintColors`
731    /// is the ladder's first; `GodraysNode`, `SSAONode`, `GTAONode` and
732    /// `SSRNode` want the same node.
733    ///
734    /// The values travel in an `Rc` so the buffer can be cached on the node's
735    /// identity and uploaded once, like [`BufferSource::Attribute`].
736    UniformArray(Rc<Vec<f32>>),
737    /// `Camera.js`' `uniformArray( matrices ).setGroup( renderGroup )
738    /// .setName( 'cameraViewMatrices' )` — every `ArrayCamera` sub-camera's
739    /// `matrixWorldInverse`, rewritten per render. A render-group buffer, the
740    /// only one.
741    CameraViewMatrices,
742    /// The same for `cameraProjectionMatrices` — the sub-cameras'
743    /// `projectionMatrix`.
744    CameraProjectionMatrices,
745    /// `ClippingNode`'s `uniformArray( intersectionPlanes ).setGroup(
746    /// renderGroup )` — the clipping context's intersection planes in view
747    /// space, one `vec4` each, written per draw from the draw's context.
748    ClippingIntersection,
749    /// The same for the context's `unionPlanes`.
750    ClippingUnion,
751    /// `buffer( previousBoneMatrices, 'mat4', bones )` — `Skinning.js`'
752    /// `getPreviousSkinnedPosition()`: the skeleton's bone matrices as they
753    /// were before this frame's `skeleton.update()`, for the
754    /// `positionPrevious` of a draw into a `velocity` MRT.
755    PreviousBoneMatrices,
756    /// `referenceBuffer( 'skeleton.boneMatrices', 'mat4', bones )` — the
757    /// skeleton's bone matrices as one `array< mat4x4<f32>, N >`. Three falls
758    /// back to a bone *texture* when `bones * 64` passes the uniform buffer
759    /// limit; the ladder's skeletons fit (Michelle is 65 bones, 4160 bytes).
760    BoneMatrices,
761    /// A per-instance attribute the caller fills itself — three.js'
762    /// `new InstancedBufferAttribute( array, itemSize )` on the geometry, e.g.
763    /// `BatchedText`'s `aGlyphUV` / `aGlyphBounds` / `aColor` / `aOpacity`.
764    /// Only ever a vertex buffer: the uniform path has no equivalent.
765    Attribute(Rc<Vec<f32>>),
766    /// `instancedArray( count, type )` — a GPU-only *storage* buffer
767    /// (`StorageBufferNode`, `StorageInstancedBufferAttribute` with no array
768    /// behind it). Zero-filled once by the renderer and never re-uploaded: the
769    /// only thing that ever writes it is a compute pass.
770    ///
771    /// Declared `array< T >` with **no** element count, because
772    /// `WGSLNodeBuilder.getStorageAccess()` emits a runtime-sized array; the
773    /// `count` on the [`BufferNode`] is only what the renderer allocates.
774    Storage,
775    /// `instancedArray( count, 'uint' ).toAtomic()` — [`BufferSource::Storage`]
776    /// whose elements are declared `atomic< T >`
777    /// (`WGSLNodeBuilder.getUniforms()`'s `bufferNode.isAtomic` arm), so the
778    /// only way to touch one is an [`atomic function`](Node::Atomic).
779    AtomicStorage,
780    /// `storage( indirectAttribute, struct( … ), count )` — an
781    /// `IndirectStorageBufferAttribute` read and written through a named WGSL
782    /// struct (`StructTypeNode`). Declared as the struct itself rather than
783    /// wrapped in `{ value : array< … > }`, which is
784    /// `WGSLNodeBuilder.isCustomStruct()`'s single-struct case. `init` is the
785    /// attribute's `Uint32Array`, uploaded once when the GPU buffer is made;
786    /// see [`crate::core::IndirectStorageBufferAttribute`].
787    Struct {
788        /// The struct's name and member list.
789        layout: Rc<StructLayout>,
790        /// The attribute's initial contents, uploaded once.
791        init: Rc<Vec<u32>>,
792    },
793    /// `storage( attribute, type, count )` over an attribute that *has* a CPU
794    /// array — `computeSkinning()`'s `storage( new InstancedBufferAttribute(
795    /// position.array, 3 ), 'vec3' )`, or a `StorageInstancedBufferAttribute(
796    /// array, itemSize )`. Uploaded once, when the GPU buffer is made, then
797    /// left to the kernels. `init` is the array's bits already laid out at the
798    /// storage stride (a `vec3` padded to 16 bytes, as
799    /// `WebGPUAttributeUtils.createAttribute()` pads it).
800    ///
801    /// `read_only` is `.toReadOnly()`: `var<storage, read>` in a kernel too.
802    StorageData {
803        /// The array's bits, already laid out at the storage stride.
804        init: Rc<Vec<u32>>,
805        /// `.toReadOnly()` — `var<storage, read>` rather than `read_write`.
806        read_only: bool,
807    },
808    /// `buffer( skeleton.boneMatrices, 'mat4', bones )` — `computeSkinning()`'s
809    /// bone matrices: a plain uniform `BufferNode` over the skeleton's own
810    /// array rather than `SkinningNode`'s `referenceBuffer`, so it is resolved
811    /// from the skeleton it names and not from a render object. The
812    /// skeleton's `OnObjectUpdate` (`skeleton.update()`, once per frame) runs
813    /// when the buffer is written.
814    SkeletonBoneMatrices(SkeletonRef),
815    /// `LightProbeNode.lightProbe` — `uniformArray( 9 × Vector3 )` holding the
816    /// probe at this index of the renderer's light list, each coefficient
817    /// already multiplied by `light.intensity` (`LightProbeNode.update()`).
818    /// One `vec4` per coefficient, rewritten per draw like
819    /// [`BufferSource::MorphInfluences`], because the probe can change between
820    /// frames while the program does not.
821    LightProbe(usize),
822    /// `uniformArray( values )` over an array the application keeps changing
823    /// — `LightProbeHelper`'s `uniformArray( lightProbe.sh.coefficients )`,
824    /// which shares the probe's own `Vector3`s. The reader returns the
825    /// elements already padded to four floats each; the buffer is rewritten
826    /// per draw. Compares by identity, as [`UniformSource::Live`] does.
827    Live(LiveValue),
828}
829
830impl BufferSource {
831    /// A `var<storage>` binding rather than a `var<uniform>` one — every
832    /// `StorageBufferNode` shape the port has.
833    pub(crate) fn is_storage(&self) -> bool {
834        matches!(
835            self,
836            BufferSource::Storage
837                | BufferSource::AtomicStorage
838                | BufferSource::Struct { .. }
839                | BufferSource::StorageData { .. }
840        )
841    }
842
843    /// The group the binding joins and the name three gives it: the two
844    /// camera arrays are `renderGroup` buffers named by `setName()`, the
845    /// clipping planes are unnamed `renderGroup` buffers, and everything else
846    /// is an object-group `NodeBuffer_N` (`None`).
847    pub(crate) fn group_and_name(&self) -> (UniformGroup, Option<&'static str>) {
848        match self {
849            BufferSource::CameraViewMatrices => (UniformGroup::Render, Some("cameraViewMatrices")),
850            BufferSource::CameraProjectionMatrices => {
851                (UniformGroup::Render, Some("cameraProjectionMatrices"))
852            }
853            // `setGroup( renderGroup )` without a name: `NodeBuffer_N`.
854            BufferSource::ClippingIntersection | BufferSource::ClippingUnion => {
855                (UniformGroup::Render, None)
856            }
857            _ => (UniformGroup::Object, None),
858        }
859    }
860}
861
862/// The skeleton behind [`BufferSource::SkeletonBoneMatrices`], compared by
863/// identity: one skeleton is one buffer however many kernels read it.
864#[derive(Clone)]
865pub struct SkeletonRef(pub(crate) Rc<RefCell<crate::objects::Skeleton>>);
866
867impl PartialEq for SkeletonRef {
868    fn eq(&self, other: &Self) -> bool {
869        Rc::ptr_eq(&self.0, &other.0)
870    }
871}
872
873/// One member of a [`StructLayout`] — an entry of `struct( { … } )`'s object.
874#[derive(Clone, Debug, PartialEq)]
875pub struct StructMember {
876    /// The member's name in WGSL.
877    pub name: &'static str,
878    /// The member's WGSL type.
879    pub ty: Type,
880    /// `{ type: 'uint', atomic: true }` — declared `atomic< u32 >`.
881    pub atomic: bool,
882}
883
884/// `struct( members, name )` — `StructTypeNode`: a named WGSL struct whose
885/// members keep their declaration order.
886#[derive(Clone, Debug, PartialEq)]
887pub struct StructLayout {
888    /// The struct's name in WGSL.
889    pub name: &'static str,
890    /// The struct's members, in declaration order.
891    pub members: Vec<StructMember>,
892}
893
894impl StructLayout {
895    /// `struct DrawBuffer {\n\tvertexCount : u32,\n … };` —
896    /// `WGSLNodeBuilder.getStructMembers()`'s spelling, `atomic< u32 >` with
897    /// the spaces three puts inside it.
898    pub(crate) fn wgsl(&self) -> String {
899        let members: Vec<String> = self
900            .members
901            .iter()
902            .map(|m| {
903                let ty = crate::nodes::wgsl::type_name(m.ty);
904                if m.atomic {
905                    format!("\t{} : atomic< {ty} >", m.name)
906                } else {
907                    format!("\t{} : {ty}", m.name)
908                }
909            })
910            .collect();
911        format!("struct {} {{\n{}\n}};", self.name, members.join(",\n"))
912    }
913
914    /// The member's index, by name — `.get( name )`.
915    pub(crate) fn member(&self, name: &str) -> usize {
916        self.members
917            .iter()
918            .position(|m| m.name == name)
919            .unwrap_or_else(|| panic!("three-rs: struct {} has no member {name}", self.name))
920    }
921}
922
923/// `workgroupArray( type, count )` — `WorkgroupInfoNode`: a `var<workgroup>`
924/// array every invocation of one workgroup shares.
925///
926/// Its identity is the array: two `workgroupArray()` calls are two arrays,
927/// each named `WorkgroupArray_N` by the builder in first-use order.
928#[derive(Debug)]
929pub struct WorkgroupArrayDef {
930    /// The array's element type.
931    pub element_ty: Type,
932    /// The number of elements.
933    pub count: usize,
934    /// `.toAtomic()`.
935    pub atomic: bool,
936}
937
938/// The identity of one `BufferNode` / `InstanceBuffer`, from a never-reused
939/// counter — the same shape as `BufferGeometry.id` and `Material.id`.
940///
941/// The renderer caches a `range()` buffer's one-and-only random fill under
942/// this. It used to be `Rc::as_ptr( &buffer )`, which a *later* buffer
943/// inherits the moment this one's material is dropped, and which would then be
944/// served the dead buffer's fill: the same freed-address bug as issue #58's
945/// geometry cache, silent rather than loud because the contents are random
946/// either way.
947#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
948pub struct BufferId(usize);
949
950impl BufferId {
951    pub(crate) fn next() -> Self {
952        thread_local! {
953            static BUFFER_ID: Cell<usize> = const { Cell::new(0) };
954        }
955        BUFFER_ID.with(|id| {
956            let next = id.get();
957            id.set(next + 1);
958            BufferId(next)
959        })
960    }
961
962    /// The number itself, for keying on.
963    pub fn get(&self) -> usize {
964        self.0
965    }
966}
967
968/// The CPU-side buffer behind one or more *instanced vertex attributes* —
969/// three.js' `InstancedBufferAttribute` / `InstancedInterleavedBuffer`.
970///
971/// `RangeNode.setup()` and `createInstanceMatrixNode()` both branch on
972/// `uniformBufferSize <= builder.getUniformBufferLimit()`: under the limit the
973/// data is a uniform buffer indexed by `instanceIndex` ([`BufferNode`]), over it
974/// an instanced attribute, which is what lifts the ~1024-instance cap the
975/// 64 KiB uniform binding imposes. `Rc` identity is the buffer's identity, so
976/// two `range( 0, 1 )` calls are two buffers with two different random fills,
977/// exactly as two `RangeNode`s are in three.js.
978#[derive(Debug)]
979pub struct InstanceBuffer {
980    /// This buffer's identity — see [`BufferId`].
981    pub id: BufferId,
982    /// Where the buffer's contents come from.
983    pub source: BufferSource,
984    /// The instance count — `InstancedBufferAttribute.count`.
985    pub count: usize,
986    /// Floats per instance, i.e. the attribute stride in components: 16 for the
987    /// interleaved instance matrix (`new InstancedInterleavedBuffer( array, 16,
988    /// 1 )`), 4 for a `range()`.
989    pub item_size: usize,
990    /// The buffer steps once per *vertex*: `attributeArray()`'s
991    /// `StorageBufferAttribute` read through `.toAttribute()`, which is not an
992    /// `InstancedBufferAttribute`. `false` for everything else here.
993    pub per_vertex: bool,
994}
995
996/// `BufferNode` — `buffer( array, type, count )`.
997#[derive(Debug)]
998pub struct BufferNode {
999    /// This buffer's identity — see [`BufferId`].
1000    pub id: BufferId,
1001    /// Where the buffer's contents come from.
1002    pub source: BufferSource,
1003    /// The type of one element.
1004    pub element_ty: Type,
1005    /// The number of elements.
1006    pub count: usize,
1007}
1008
1009/// The texture a `TextureNode` / `CubeTextureNode` samples.
1010#[derive(Clone, Debug)]
1011#[non_exhaustive]
1012pub enum TextureSource {
1013    /// `texture( Texture )` — a sampled `texture_2d<f32>`.
1014    Texture2D(Texture),
1015    /// `texture( DepthTexture )` — a sampled `texture_depth_2d`.
1016    Depth(DepthTexture),
1017    /// A `DepthTexture` with `compareFunction` set, bound as
1018    /// `texture_depth_2d` + `sampler_comparison` and read with
1019    /// `textureSampleCompare` — `ShadowNode`'s shadow map.
1020    ShadowMap(DepthTexture),
1021    /// `cubeTexture( CubeTexture )` — a sampled `texture_cube<f32>`.
1022    Cube(CubeTexture),
1023    /// `DataArrayTexture` — the morph-target data texture.
1024    DataArray(DataArrayTexture),
1025    /// `DataTexture` — `BatchedMesh`' matrices / colours / indirect tables.
1026    Data(DataTexture),
1027    /// A point light's shadow map — `cubeTexture( CubeDepthTexture )`.
1028    CubeDepth(CubeDepthTexture),
1029    /// `texture3D( Data3DTexture | Storage3DTexture )` — a sampled
1030    /// `texture_3d<f32>`.
1031    Texture3D(Data3DTexture),
1032    /// `storageTexture( StorageTexture )` — a `texture_storage_2d<format,
1033    /// access>`, what `textureStore()` writes and `.load()` reads.
1034    Storage(Texture, StorageAccess),
1035    /// `storageTexture( Storage3DTexture )` — `texture_storage_3d`.
1036    Storage3D(Data3DTexture, StorageAccess),
1037}
1038
1039impl TextureSource {
1040    /// The texture's id — `Texture.id`, whichever class it is.
1041    pub(crate) fn id(&self) -> usize {
1042        match self {
1043            TextureSource::Texture2D(t) | TextureSource::Storage(t, _) => t.id(),
1044            TextureSource::Depth(t) | TextureSource::ShadowMap(t) => t.id(),
1045            TextureSource::Cube(t) => t.id(),
1046            TextureSource::DataArray(t) => t.id(),
1047            TextureSource::Data(t) => t.id(),
1048            TextureSource::CubeDepth(t) => t.id(),
1049            TextureSource::Texture3D(t) | TextureSource::Storage3D(t, _) => t.id(),
1050        }
1051    }
1052
1053    /// Bound as a storage texture rather than a sampled one. A texture a
1054    /// kernel stores into and a material samples is two bindings of one
1055    /// texture, so the builder keys its binding names on this as well as on
1056    /// [`id`](Self::id).
1057    pub(crate) fn is_storage_binding(&self) -> bool {
1058        matches!(
1059            self,
1060            TextureSource::Storage(..) | TextureSource::Storage3D(..)
1061        )
1062    }
1063}
1064
1065/// `NodeAccess` for a `StorageTextureNode` — the `access` of its
1066/// `texture_storage_*` declaration.
1067///
1068/// `StorageTextureNode`'s default is `WRITE_ONLY`; `WGSLNodeBuilder
1069/// .getStorageAccess()` forces `READ_ONLY` outside the compute stage, which the
1070/// builder applies when it declares the binding.
1071#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1072pub enum StorageAccess {
1073    /// `texture_storage_2d<format, write>` — `StorageTextureNode`'s default.
1074    #[default]
1075    WriteOnly,
1076    /// `texture_storage_2d<format, read>` — forced outside the compute stage.
1077    ReadOnly,
1078    /// `texture_storage_2d<format, read_write>`.
1079    ReadWrite,
1080}
1081
1082impl StorageAccess {
1083    /// `WGSLNodeBuilder`'s `accessNames`.
1084    pub(crate) fn wgsl(self) -> &'static str {
1085        match self {
1086            StorageAccess::WriteOnly => "write",
1087            StorageAccess::ReadOnly => "read",
1088            StorageAccess::ReadWrite => "read_write",
1089        }
1090    }
1091
1092    /// The `wgpu` spelling, for the bind group layout.
1093    pub(crate) fn wgpu(self) -> wgpu::StorageTextureAccess {
1094        match self {
1095            StorageAccess::WriteOnly => wgpu::StorageTextureAccess::WriteOnly,
1096            StorageAccess::ReadOnly => wgpu::StorageTextureAccess::ReadOnly,
1097            StorageAccess::ReadWrite => wgpu::StorageTextureAccess::ReadWrite,
1098        }
1099    }
1100}
1101
1102impl TextureSource {
1103    /// The texture's liveness, for the renderer's view cache to sweep on; see
1104    /// [`TextureOwner`](crate::textures::TextureOwner).
1105    pub(crate) fn owner(&self) -> crate::textures::TextureOwner {
1106        match self {
1107            TextureSource::Texture2D(texture) => texture.owner(),
1108            TextureSource::Depth(depth) | TextureSource::ShadowMap(depth) => depth.owner(),
1109            TextureSource::Cube(cube) => cube.owner(),
1110            TextureSource::DataArray(data) => data.owner(),
1111            TextureSource::Data(data) => data.owner(),
1112            TextureSource::CubeDepth(cube) => cube.owner(),
1113            TextureSource::Texture3D(data) | TextureSource::Storage3D(data, _) => data.owner(),
1114            TextureSource::Storage(texture, _) => texture.owner(),
1115        }
1116    }
1117}
1118
1119/// How a `TextureNode` reads its texture — `WGSLNodeBuilder.generateTexture*`.
1120#[derive(Clone, Debug)]
1121pub enum SampleMode {
1122    /// `textureSample( t, t_sampler, uv )`.
1123    Sample,
1124    /// `textureSampleLevel( t, t_sampler, uv, level )`.
1125    Level(NodeRef),
1126    /// `textureSampleBias( t, t_sampler, uv, bias )` — `textureNode.bias(
1127    /// value )`. `FXAANode` samples its input at a bias of `-100`, pinning
1128    /// every tap to the top mip.
1129    Bias(NodeRef),
1130    /// `textureSampleGrad( t, t_sampler, uv, gradX, gradY )` —
1131    /// `textureNode.grad( gradX, gradY )` (`generateTextureGrad()`), each
1132    /// gradient built as a `vec2`.
1133    Grad(NodeRef, NodeRef),
1134    /// `textureGather( component, t, t_sampler, uv[, offset] )` —
1135    /// `textureNode.gather( component )`, optionally `.offset( ivec2 )`
1136    /// (`WGSLNodeBuilder.generateTextureGather()`): one channel of the four
1137    /// texels a bilinear tap would read, from mip level 0.
1138    Gather {
1139        /// Which channel to gather (0–3).
1140        component: NodeRef,
1141        /// An optional texel offset — `.offset( ivec2 )`.
1142        offset: Option<NodeRef>,
1143    },
1144    /// `textureGatherCompare( t, t_sampler, uv, depth[, offset] )` —
1145    /// `depthNode.gather().compare( depth )` on a depth texture with a
1146    /// comparison sampler (`generateTextureGatherCompare()`): the four
1147    /// texels' comparison results.
1148    GatherCompare {
1149        /// The depth value each of the four texels is compared against.
1150        compare: NodeRef,
1151        /// An optional texel offset — `.offset( ivec2 )`.
1152        offset: Option<NodeRef>,
1153    },
1154    /// The non-filterable path: `textureLoad` against `textureDimensions`,
1155    /// with no sampler binding at all. What Three emits for a depth texture.
1156    Load,
1157    /// `textureLoad( t, coord, layer, u32( 0u ) )` on a 2-D-array texture —
1158    /// `textureLoad( … ).depth( layer )`, with no clamping and no sampler.
1159    LoadLayer(NodeRef),
1160    /// `textureSample( t, t_sampler, uv, i32( layer ) )` on a 2-D-array
1161    /// texture — `texture( map, uv ).depth( layer )`. Three builds the depth
1162    /// node as `'int'`, so a float layer arrives truncated by `i32()`.
1163    SampleLayer(NodeRef),
1164    /// `textureSampleCompare( t, t_sampler, uv, depth )` — the depth-compare
1165    /// read `ShadowFilterNode`'s `depthCompare` lowers to.
1166    Compare(NodeRef),
1167    /// `textureLoad( t, coord, u32( 0u ) )` — an unclamped texel fetch at an
1168    /// integer coordinate, what `Batch.js` reads its data textures with. When
1169    /// the node's type is a scalar the snippet is swizzled (`.x`), which is
1170    /// how Three's `textureLoad( … ).x` on the `r32uint` indirect table lands
1171    /// in one `u32` property.
1172    LoadTexel,
1173    /// `storageTexture( t ).load( coord )` — `textureLoad( t, coord )` on a
1174    /// `texture_storage_*`, which takes no level argument
1175    /// (`WGSLNodeBuilder.generateStorageTextureLoad()`).
1176    StorageLoad,
1177}
1178
1179/// A WGSL builtin input.
1180#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1181#[non_exhaustive]
1182pub enum Builtin {
1183    /// `@builtin( vertex_index )`.
1184    VertexIndex,
1185    /// `@builtin( instance_index )`.
1186    InstanceIndex,
1187    /// `@builtin( position )` in the fragment stage.
1188    FragCoord,
1189    /// `@builtin( front_facing )` — `FrontFacingNode`.
1190    FrontFacing,
1191    /// `invocationLocalIndex` — `@builtin( local_invocation_index )`, which
1192    /// `WGSLNodeBuilder.getInvocationLocalIndex()` adds to the compute entry
1193    /// point's parameters only when a kernel reads it.
1194    InvocationLocalIndex,
1195    /// `workgroupId` / `localId` / `globalId` / `numWorkgroups` —
1196    /// `ComputeBuiltinNode`. The compute entry point always declares these four
1197    /// (`WGSLNodeBuilder.getAttributes( 'compute' )`), so reading one only names
1198    /// the parameter.
1199    WorkgroupId,
1200    /// `@builtin( local_invocation_id )` — see [`Builtin::WorkgroupId`].
1201    LocalId,
1202    /// `@builtin( global_invocation_id )` — see [`Builtin::WorkgroupId`].
1203    GlobalId,
1204    /// `@builtin( num_workgroups )` — see [`Builtin::WorkgroupId`].
1205    NumWorkgroups,
1206    /// `subgroupSize` — `@builtin( subgroup_size )`. Three's
1207    /// `computeBuiltin( 'subgroupSize', 'uint' )` only writes the name: the
1208    /// parameter is the one `WGSLNodeBuilder.getAttributes( 'compute' )`
1209    /// appends after the four above when the device has `subgroups`. The port
1210    /// declares it, and `enable subgroups;`, when a kernel reads it or calls a
1211    /// subgroup function (`docs/nodes.md` §84).
1212    SubgroupSize,
1213    /// `invocationSubgroupIndex` — `@builtin( subgroup_invocation_id )`,
1214    /// registered by `WGSLNodeBuilder.getInvocationSubgroupIndex()` when the
1215    /// flow reads it, so it comes before the four fixed parameters, like
1216    /// [`Builtin::InvocationLocalIndex`].
1217    InvocationSubgroupIndex,
1218    /// `subgroupIndex` — `@builtin( subgroup_id )`, registered by
1219    /// `WGSLNodeBuilder.getSubgroupIndex()`; see
1220    /// [`Builtin::InvocationSubgroupIndex`].
1221    SubgroupIndex,
1222}
1223
1224impl Builtin {
1225    pub(crate) fn name(self) -> &'static str {
1226        match self {
1227            Builtin::VertexIndex => "vertexIndex",
1228            Builtin::InstanceIndex => "instanceIndex",
1229            Builtin::FragCoord => "fragCoord",
1230            Builtin::FrontFacing => "isFront",
1231            Builtin::InvocationLocalIndex => "invocationLocalIndex",
1232            Builtin::WorkgroupId => "workgroupId",
1233            Builtin::LocalId => "localId",
1234            Builtin::GlobalId => "globalId",
1235            Builtin::NumWorkgroups => "numWorkgroups",
1236            Builtin::SubgroupSize => "subgroupSize",
1237            Builtin::InvocationSubgroupIndex => "invocationSubgroupIndex",
1238            Builtin::SubgroupIndex => "subgroupIndex",
1239        }
1240    }
1241
1242    pub(crate) fn ty(self) -> Type {
1243        match self {
1244            Builtin::VertexIndex
1245            | Builtin::InstanceIndex
1246            | Builtin::InvocationLocalIndex
1247            | Builtin::SubgroupSize
1248            | Builtin::InvocationSubgroupIndex
1249            | Builtin::SubgroupIndex => Type::U32,
1250            Builtin::WorkgroupId
1251            | Builtin::LocalId
1252            | Builtin::GlobalId
1253            | Builtin::NumWorkgroups => Type::UVec3,
1254            Builtin::FragCoord => Type::Vec4,
1255            Builtin::FrontFacing => Type::Bool,
1256        }
1257    }
1258}
1259
1260/// `SubgroupFunctionNode.getInputType()`: the longer of the two inputs'
1261/// types, a matrix counting as length 0, and `b`'s on a tie.
1262pub(crate) fn subgroup_input_type(a: Option<&NodeRef>, b: Option<&NodeRef>) -> Type {
1263    let length = |node: Option<&NodeRef>| match node.map(NodeRef::ty) {
1264        Some(ty) if ty.is_matrix() => 0,
1265        Some(ty) => ty.components(),
1266        None => 0,
1267    };
1268    if length(a) > length(b) {
1269        a.map(NodeRef::ty)
1270    } else {
1271        b.map(NodeRef::ty)
1272    }
1273    // Three returns `bType`, `null` for a one-input function whose input is a
1274    // matrix; the port's `Type` has no null, and a matrix is its own type.
1275    .or_else(|| a.map(NodeRef::ty))
1276    .unwrap_or(Type::Void)
1277}
1278
1279/// `SubgroupFunctionNode.generateNodeType()`: `subgroupElect` is a `bool`,
1280/// `subgroupBallot` a `uvec4`, everything else its input type.
1281fn subgroup_type(method: &str, a: Option<&NodeRef>, b: Option<&NodeRef>) -> Type {
1282    match method {
1283        "subgroupElect" => Type::Bool,
1284        "subgroupBallot" => Type::UVec4,
1285        _ => subgroup_input_type(a, b),
1286    }
1287}
1288
1289/// `VarNode` — a `var<private>` that caches its value's first use.
1290#[derive(Debug)]
1291pub struct VarDef {
1292    /// `toVar( 'name' )`; `None` numbers it `nodeVarN`. A `String` because a
1293    /// sub-build layer prefixes the name with its own (`NORMAL_normalView`) —
1294    /// see `docs/nodes.md` §7.
1295    pub name: Option<String>,
1296    /// The node whose value is cached.
1297    pub value: NodeRef,
1298    /// The variable's WGSL type.
1299    pub ty: Type,
1300}
1301
1302/// `VaryingNode` — a value computed in the vertex stage and interpolated.
1303#[derive(Debug)]
1304pub struct VaryingDef {
1305    /// `toVarying( 'name' )`; `None` numbers it `nodeVaryingN`.
1306    pub name: Option<&'static str>,
1307    /// The node whose value is carried across stages.
1308    pub value: NodeRef,
1309    /// The varying's WGSL type.
1310    pub ty: Type,
1311    /// u32 varyings need `@interpolate(flat, either)`.
1312    pub flat: bool,
1313}
1314
1315/// `ShaderNode` / `Fn()`. With `layout` set, a real WGSL `fn` is emitted and
1316/// called; without it the body is inlined at every call site — which is what
1317/// Three does for `saturation`/`hue`, and why their expressions appear
1318/// expanded three times in the dumped shader.
1319pub struct FnDef {
1320    /// The `fn`'s name in WGSL when `layout` is set; `None` numbers it.
1321    pub name: Option<&'static str>,
1322    /// The parameters' names and types, in declaration order.
1323    pub params: Vec<(&'static str, Type)>,
1324    /// The return type.
1325    pub ret: Type,
1326    /// Whether a real WGSL `fn` is emitted, rather than inlining the body.
1327    pub layout: bool,
1328    /// Builds the call's result node from the argument nodes.
1329    #[allow(clippy::type_complexity)]
1330    pub body: Box<dyn Fn(&[NodeRef]) -> NodeRef>,
1331}
1332
1333impl std::fmt::Debug for FnDef {
1334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1335        f.debug_struct("FnDef").field("name", &self.name).finish()
1336    }
1337}
1338
1339/// A node type defined outside the crate: the port of `class MyNode extends
1340/// Node` with a `setup( builder )` override, the shape every addon in
1341/// `examples/jsm/tsl/` has.
1342///
1343/// **`setup` composes; it never emits.** It returns a graph of the existing
1344/// [`Node`] variants, and the builder builds that graph in its place. It
1345/// cannot write a WGSL statement of its own, declare a binding, or change how
1346/// a variant is generated. Three's addons never override `generate` either:
1347/// they override `setup` (and `updateBefore`, which is #162). A node that needs
1348/// a statement shape nothing can compose into belongs in the crate as a
1349/// variant, where the exhaustive `match` in the builder and the dump gates see
1350/// it (#155 decision 2).
1351///
1352/// The builder calls `setup` once per build, the first time it reaches the
1353/// node, and keeps the result as three keeps `nodeProperties.outputNode`: in
1354/// the builder's per-build data, keyed on the node's identity and scoped by
1355/// [`isolate`](crate::nodes::tsl::isolate). Two reaches of one
1356/// `Node::Custom` share one expansion; two `Node::Custom`s over equal structs
1357/// are two nodes. See `docs/nodes.md` §45.
1358///
1359/// ```ignore
1360/// struct Double(NodeRef);
1361///
1362/// impl CustomNode for Double {
1363///     fn type_name(&self) -> &'static str { "DoubleNode" }
1364///     fn node_type(&self) -> Type { self.0.ty() }
1365///     fn setup(&self, _: &NodeBuilder) -> NodeRef { self.0.clone().mul(2.0) }
1366/// }
1367///
1368/// let doubled = custom(Double(uv().x()));
1369/// ```
1370pub trait CustomNode {
1371    /// three's `static get type()`: the class name, `'RGBShiftNode'`. Only
1372    /// `Debug` output and panic messages read it.
1373    fn type_name(&self) -> &'static str;
1374
1375    /// `Node.getNodeType( builder )`: the WGSL type of the value `setup`
1376    /// returns. The port needs it before the build, because the TSL methods
1377    /// that wrap this node (`.mul()`, `.x()`, …) type their result eagerly.
1378    fn node_type(&self) -> Type;
1379
1380    /// `Node.isCacheable( builder )`: whether a node reached more than once
1381    /// is built into a var once and read from there. r187dev's `Node.build()`
1382    /// does that for every cacheable node with a value (`cacheResult`), not
1383    /// only for `TempNode`s, so the default is `true`, as three's is.
1384    /// `false` builds the output again at every reach.
1385    fn is_cacheable(&self) -> bool {
1386        true
1387    }
1388
1389    /// `Node.setup( builder )`: the graph this node stands for.
1390    ///
1391    /// `builder` is shared, not mutable: the only thing to ask it is
1392    /// [`context`](crate::nodes::NodeBuilder::context), three's
1393    /// `builder.context`, as installed by an enclosing
1394    /// [`context`](crate::nodes::tsl::context) node. The TSL functions called
1395    /// here see the same context through the crate's own accessors.
1396    fn setup(&self, builder: &crate::nodes::NodeBuilder) -> NodeRef;
1397
1398    /// `updateBeforeType`. Anything but `None` puts the node in the
1399    /// material's update-before list; see `docs/nodes.md` §57.
1400    fn update_before_type(&self) -> crate::nodes::NodeUpdateType {
1401        crate::nodes::NodeUpdateType::None
1402    }
1403    /// `updateType`.
1404    fn update_type(&self) -> crate::nodes::NodeUpdateType {
1405        crate::nodes::NodeUpdateType::None
1406    }
1407    /// `updateAfterType`.
1408    fn update_after_type(&self) -> crate::nodes::NodeUpdateType {
1409        crate::nodes::NodeUpdateType::None
1410    }
1411    /// `updateBefore( frame )`. `false` leaves the guard untouched, as
1412    /// three's `=== false` does. See [`NodeUpdate`](crate::nodes::NodeUpdate).
1413    fn update_before(&self, _renderer: &mut crate::renderer::Renderer) -> bool {
1414        true
1415    }
1416    /// `update( frame )`.
1417    fn update(&self, _renderer: &mut crate::renderer::Renderer) -> bool {
1418        true
1419    }
1420    /// `updateAfter( frame )`.
1421    fn update_after(&self, _renderer: &mut crate::renderer::Renderer) -> bool {
1422        true
1423    }
1424}
1425
1426/// A [`CustomNode`] seen through [`NodeUpdate`](crate::nodes::NodeUpdate), so
1427/// the renderer drives it like any other updating node.
1428pub(crate) struct CustomUpdate(pub(crate) Rc<dyn CustomNode>);
1429
1430impl crate::nodes::NodeUpdate for CustomUpdate {
1431    fn update_before_type(&self) -> crate::nodes::NodeUpdateType {
1432        self.0.update_before_type()
1433    }
1434    fn update_type(&self) -> crate::nodes::NodeUpdateType {
1435        self.0.update_type()
1436    }
1437    fn update_after_type(&self) -> crate::nodes::NodeUpdateType {
1438        self.0.update_after_type()
1439    }
1440    fn update_before(&self, renderer: &mut crate::renderer::Renderer) -> bool {
1441        self.0.update_before(renderer)
1442    }
1443    fn update(&self, renderer: &mut crate::renderer::Renderer) -> bool {
1444        self.0.update(renderer)
1445    }
1446    fn update_after(&self, renderer: &mut crate::renderer::Renderer) -> bool {
1447        self.0.update_after(renderer)
1448    }
1449}
1450
1451impl std::fmt::Debug for dyn CustomNode {
1452    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1453        write!(f, "{}", self.type_name())
1454    }
1455}
1456
1457/// `context( node, { … } )`'s value: the `builder.context` keys a
1458/// [`Node::Context`] installs for its subgraph, merged over the ones already
1459/// in force (`builder.addContext()`).
1460///
1461/// Three's values are arbitrary JS; the port's are nodes (`getViewZ: () =>
1462/// scenePassViewZ` is `.set( "getViewZ", scene_pass_view_z )`), held in
1463/// `BuildContext`'s string-keyed `extra` map, which is where #155 decision 6
1464/// put addon keys. The typed core keys (`setupNormal`, the material side, …)
1465/// are installed by the material's own setup and cannot be set from here.
1466#[derive(Clone, Debug, Default)]
1467pub struct ContextValue {
1468    pub(crate) entries: Vec<(&'static str, NodeRef)>,
1469    /// `{ uniformFlow: … }`, which is not a node: see
1470    /// [`uniform_flow`](Self::uniform_flow).
1471    pub(crate) uniform_flow: Option<bool>,
1472    /// `{ nodeName: … }`, which is not a node: see
1473    /// [`node_name`](Self::node_name).
1474    pub(crate) node_name: Option<&'static str>,
1475}
1476
1477impl ContextValue {
1478    /// An empty set of context entries.
1479    pub fn new() -> Self {
1480        Self::default()
1481    }
1482
1483    /// `{ …, key: value }`. A later `set` of the same key wins, as the later
1484    /// of two properties does in a JS object literal.
1485    pub fn set(mut self, key: &'static str, value: impl Into<NodeRef>) -> Self {
1486        self.entries.retain(|(k, _)| *k != key);
1487        self.entries.push((key, value.into()));
1488        self
1489    }
1490
1491    /// `{ …, uniformFlow: on }` — what [`uniform_flow`] installs. Under it a
1492    /// `select()` with both branches is WGSL's `select( f, t, cond )` rather
1493    /// than an `if`/`else` over a var (`ConditionalNode.generate()`), so it
1494    /// stays in uniform control flow.
1495    ///
1496    /// [`uniform_flow`]: crate::nodes::tsl::uniform_flow
1497    pub fn uniform_flow(mut self, on: bool) -> Self {
1498        self.uniform_flow = Some(on);
1499        self
1500    }
1501
1502    /// `{ …, nodeName: name }` — what [`set_name`] installs. The first
1503    /// `uniform()` built inside clears it, and takes the name unless it has
1504    /// one of its own.
1505    ///
1506    /// [`set_name`]: crate::nodes::tsl::set_name
1507    pub fn node_name(mut self, name: &'static str) -> Self {
1508        self.node_name = Some(name);
1509        self
1510    }
1511}
1512
1513/// What [`debug`](crate::nodes::tsl::debug)'s callback is handed: three's
1514/// `callback( builder, snippet )`, with the two things of the builder a
1515/// debugging callback reads.
1516#[derive(Clone, Copy, Debug)]
1517pub struct DebugInfo<'a> {
1518    /// `builder.shaderStage`: `"vertex"`, `"fragment"` or `"compute"`.
1519    pub stage: &'static str,
1520    /// `builder.flow.code`: the statements emitted so far in the current
1521    /// scope (the stage's `main`, or the `Fn()` being built), one per line,
1522    /// with one level of indentation removed.
1523    pub flow: &'a str,
1524    /// The debugged node's snippet, which is also the debug node's own.
1525    pub snippet: &'a str,
1526}
1527
1528/// A [`debug`](crate::nodes::tsl::debug) callback.
1529#[derive(Clone)]
1530pub struct DebugCallback(pub(crate) Rc<dyn Fn(&DebugInfo<'_>)>);
1531
1532impl DebugCallback {
1533    /// Wrap `callback`.
1534    pub fn new(callback: impl Fn(&DebugInfo<'_>) + 'static) -> Self {
1535        Self(Rc::new(callback))
1536    }
1537}
1538
1539impl std::fmt::Debug for DebugCallback {
1540    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1541        f.write_str("DebugCallback")
1542    }
1543}
1544
1545/// The node set. Closed on purpose: an exhaustive `match` in the builder is
1546/// what tells the next rung it has added something the generator cannot emit.
1547/// [`Node::Custom`] is the one opening, and it can only compose the others.
1548#[derive(Debug)]
1549#[non_exhaustive]
1550pub enum Node {
1551    /// A literal. `values` holds one entry per component.
1552    Const {
1553        /// The literal's WGSL type.
1554        ty: Type,
1555        /// One entry per component.
1556        values: Vec<f64>,
1557    },
1558    /// `array< f32, N >( … )` — `QuadMesh`'s `vertexNode`.
1559    ConstArray {
1560        /// The array's element type.
1561        element_ty: Type,
1562        /// The array's contents, one entry per component of each element.
1563        values: Vec<f64>,
1564    },
1565    /// The same literal array held in a `var<private> nodeVarN : array< T, N >`
1566    /// rather than written out at each use — three.js' `TempNode` promotion of
1567    /// an `array()` that the flow reads more than once, which `BloomNode`'s
1568    /// composite does five times (`dump/m11`).
1569    ArrayVar {
1570        /// The array's element type.
1571        element_ty: Type,
1572        /// The array's contents, one entry per component of each element.
1573        values: Vec<f64>,
1574    },
1575    /// `UniformNode`.
1576    Uniform(Rc<UniformNode>),
1577    /// `BufferNode` element access: `NodeBuffer_N.value[ index ]`.
1578    BufferElement {
1579        /// The buffer being indexed.
1580        buffer: Rc<BufferNode>,
1581        /// The element index.
1582        index: NodeRef,
1583    },
1584    /// A geometry attribute.
1585    Attribute {
1586        /// The attribute's name in WGSL.
1587        name: &'static str,
1588        /// The attribute's WGSL type.
1589        ty: Type,
1590    },
1591    /// `instancedBufferAttribute( buffer, type, stride, offset )`: a vertex
1592    /// attribute whose buffer steps once per instance. `offset` is in floats
1593    /// from the start of the instance; the stride is the buffer's `item_size`,
1594    /// which is all three.js' own call sites use.
1595    InstancedAttribute {
1596        /// The per-instance buffer.
1597        buffer: Rc<InstanceBuffer>,
1598        /// The offset into one instance's data, in floats.
1599        offset: usize,
1600        /// The attribute's WGSL type.
1601        ty: Type,
1602    },
1603    /// A WGSL builtin input.
1604    Builtin(Builtin),
1605    /// `ComputeNode` used as a value — `Fn( () => { …; return x } )().compute(
1606    /// count )` set as a material's `positionNode`. Outside the compute stage
1607    /// it generates `output` (`properties.outputComputeNode`); the kernel
1608    /// itself runs from `updateBefore()` (`NodeUpdateType.FRAME`), which the
1609    /// builder records in
1610    /// [`NodeProgram::update_before`](crate::nodes::NodeProgram) for the
1611    /// renderer to dispatch. See `docs/nodes.md` §44 and §57.
1612    Compute {
1613        /// The compute kernel's statements and dispatch size.
1614        flow: Rc<crate::nodes::ComputeFlow>,
1615        /// The value read outside the compute stage.
1616        output: NodeRef,
1617    },
1618    /// `VarNode` — a cached `var<private>`.
1619    Var(Rc<VarDef>),
1620    /// `VarNode` with `intent` set, as it ends up when something assigns to
1621    /// it — see [`to_var_intent`](crate::nodes::tsl::to_var_intent). A WGSL
1622    /// function-scope `var`, declared with its value where it is first
1623    /// built (`var nodeVar0 : vec3<f32> = …;`) instead of hoisted into the
1624    /// `// vars` block.
1625    VarIntent(Rc<VarDef>),
1626    /// `VarNode` with `readOnly` set — `node.toConst()`. A WGSL `let`, so it is
1627    /// declared where it is assigned and, unlike a `var<private>`, cannot be
1628    /// written again.
1629    Let(Rc<VarDef>),
1630    /// `VaryingNode`.
1631    Varying(Rc<VaryingDef>),
1632    /// A `var<private>` with a fixed name that the setup code assigns
1633    /// explicitly — `PropertyNode` (`DiffuseColor`, `Output`, …).
1634    Property {
1635        /// The property's name in WGSL.
1636        name: &'static str,
1637        /// The property's WGSL type.
1638        ty: Type,
1639    },
1640    /// A parameter of an emitted `fn` — a name that is already in scope.
1641    Param {
1642        /// The parameter's name in WGSL.
1643        name: &'static str,
1644        /// The parameter's WGSL type.
1645        ty: Type,
1646    },
1647    /// A statement: `target = value`.
1648    Assign {
1649        /// The assignment's left-hand side.
1650        target: NodeRef,
1651        /// The assignment's right-hand side.
1652        value: NodeRef,
1653    },
1654    /// `OperatorNode`.
1655    Op {
1656        /// The WGSL operator, e.g. `"+"`.
1657        op: &'static str,
1658        /// The left operand.
1659        a: NodeRef,
1660        /// The right operand.
1661        b: NodeRef,
1662        /// The result's WGSL type.
1663        ty: Type,
1664    },
1665    /// `MathNode` — a WGSL builtin call.
1666    Math {
1667        /// The WGSL builtin's name, e.g. `"sin"`.
1668        name: &'static str,
1669        /// The call's arguments.
1670        args: Vec<NodeRef>,
1671        /// The result's WGSL type.
1672        ty: Type,
1673    },
1674    /// `SplitNode`.
1675    Swizzle {
1676        /// The node being swizzled.
1677        node: NodeRef,
1678        /// The swizzle mask, e.g. `"xyz"`.
1679        components: &'static str,
1680        /// The result's WGSL type.
1681        ty: Type,
1682    },
1683    /// `ConvertNode` / a single-argument constructor: `vec4<f32>( x )`.
1684    Cast {
1685        /// The node being converted.
1686        node: NodeRef,
1687        /// The target WGSL type.
1688        ty: Type,
1689    },
1690    /// `OperatorNode` with one operand: `( - x )`.
1691    Neg {
1692        /// The negated node.
1693        node: NodeRef,
1694        /// The result's WGSL type.
1695        ty: Type,
1696    },
1697    /// `JoinNode` — `vec4<f32>( a, b, c, d )`.
1698    Join {
1699        /// The joined components.
1700        args: Vec<NodeRef>,
1701        /// The result's WGSL type.
1702        ty: Type,
1703    },
1704    /// `ArrayElementNode`: `m[ 3u ]`, `array< f32, 3 >( … )[ vertexIndex ]`.
1705    Element {
1706        /// The array or vector being indexed.
1707        node: NodeRef,
1708        /// The element index.
1709        index: NodeRef,
1710        /// The element's WGSL type.
1711        ty: Type,
1712    },
1713    /// `TextureNode` — a texture sample.
1714    Texture {
1715        /// The texture being sampled.
1716        texture: Rc<TextureSource>,
1717        /// The sample coordinate.
1718        uv: NodeRef,
1719        /// How the texture is read.
1720        mode: SampleMode,
1721        /// The result's WGSL type.
1722        ty: Type,
1723    },
1724    /// `TextureSizeNode` — `textureDimensions( t, level )`, a `vec2<u32>`.
1725    TextureSize {
1726        /// The texture being measured.
1727        texture: Rc<TextureSource>,
1728        /// The mip level.
1729        level: NodeRef,
1730    },
1731    /// `varyingProperty( type, name )` — a *named* varying assigned to by
1732    /// statement rather than built from a value. Unlike [`Node::Varying`] it
1733    /// is declared as soon as either stage mentions it, so a varying the
1734    /// fragment stage never reads still appears in `VaryingsStruct`, exactly
1735    /// as `vBatchIndirectId` does in Three's dump.
1736    VaryingProperty {
1737        /// The varying's name in WGSL.
1738        name: &'static str,
1739        /// The varying's WGSL type.
1740        ty: Type,
1741        /// Whether the varying needs `@interpolate(flat, either)`.
1742        flat: bool,
1743    },
1744    /// A call into a [`Node::Code`] / inlined `Fn()`.
1745    Call {
1746        /// The function being called.
1747        def: Rc<FnDef>,
1748        /// The call's arguments.
1749        args: Vec<NodeRef>,
1750    },
1751    /// `CodeNode` itself — a `wgslFn()` as a node rather than as a call, which
1752    /// is the shape another `wgslFn`'s `includes` list needs it in. Building
1753    /// one emits its declaration into `// codes` and nothing else; it has no
1754    /// value, so nothing but an `includes` list may hold one.
1755    Code(Rc<crate::nodes::code::CodeDef>),
1756    /// `FunctionCallNode` over a `wgslFn()` — a call into hand-written WGSL
1757    /// the node system copies through verbatim. See [`crate::nodes::code`].
1758    CodeCall {
1759        /// The hand-written WGSL function being called.
1760        def: Rc<crate::nodes::code::CodeDef>,
1761        /// The call's arguments.
1762        args: Vec<NodeRef>,
1763    },
1764    /// A sequence of statements followed by the value they produce — the shape
1765    /// an inlined `Fn()` body with `toVar()` statements has. Three has no node
1766    /// for it: its `ShaderNode` call simply flows its body's statements into the
1767    /// current stage and returns the last expression, which is what this does.
1768    Block {
1769        /// The statements built ahead of `result`.
1770        statements: Vec<NodeRef>,
1771        /// The block's value.
1772        result: NodeRef,
1773    },
1774    /// `Loop( count, ( { i } ) => { … } )` — `for ( var i : i32 = 0; i < n; i ++ )`.
1775    Loop {
1776        /// `Loop( { start, end }, … )`'s `start`. `None` is three.js'
1777        /// `Loop( count, … )` shorthand, whose start is the literal `0`; a
1778        /// node start is written out as it stands, so
1779        /// `webgpu_postprocessing_anamorphic`'s negated half-sample count
1780        /// reaches the loop header as `i32( ( - nodeVar1 ) )`.
1781        start: Option<NodeRef>,
1782        /// `Loop( { start, end }, … )`'s `end`, or `Loop( count, … )`'s
1783        /// count — the loop's exclusive upper bound.
1784        count: NodeRef,
1785        /// The loop index, as it appears inside `body` (`Node::Param`). Its
1786        /// type is `Loop( { type } )`: `i32`, or `f32` for `hashBlur`'s
1787        /// `type: 'float'`, which also changes the step to `i += 1.`.
1788        index: NodeRef,
1789        /// `Loop( { condition } )` — `"<"` unless the caller asked for
1790        /// another comparison (`boxBlur`'s `"<="`).
1791        condition: &'static str,
1792        /// `Loop( { update } )` — `i += update` in place of the default step.
1793        update: Option<NodeRef>,
1794        /// The loop body's statements.
1795        body: Vec<NodeRef>,
1796    },
1797    /// `Break()` — a bare `break;` out of the innermost `Loop`.
1798    Break,
1799    /// `Continue()` — a bare `continue;` to the next iteration of the
1800    /// innermost `Loop`.
1801    Continue,
1802    /// `textureStore( storageTexture, coord, value )` — a statement.
1803    ///
1804    /// `StorageTextureNode.generateStore()` writes the coordinate as
1805    /// `vec2<u32>( … )` (`vec3<u32>` for a 3D texture) around whatever the
1806    /// caller passed, so a `uvec2` coordinate is wrapped once more, exactly as
1807    /// three's dump shows.
1808    TextureStore {
1809        /// The storage texture being written.
1810        texture: Rc<TextureSource>,
1811        /// The texel coordinate.
1812        coord: NodeRef,
1813        /// The value stored.
1814        value: NodeRef,
1815    },
1816    /// `If( cond, () => { … } )` as a bare statement (`setupDiscard`),
1817    /// optionally with the `.Else( … )` / `.ElseIf( … )` arm `StackNode` adds.
1818    ///
1819    /// `ElseIf` is not a shape of its own: `StackNode.ElseIf()` puts a whole
1820    /// nested `If` inside the else block, so `If( a ).ElseIf( b )` is
1821    /// `else_body: vec![ if_then( b, … ) ]` and generates as a nested
1822    /// `if`/`else`, which is exactly what three emits.
1823    If {
1824        /// The branch condition.
1825        cond: NodeRef,
1826        /// The `if` block's statements.
1827        body: Vec<NodeRef>,
1828        /// Empty for a one-armed `If`, in which case no `else` is emitted and
1829        /// the generated text is byte-identical to what it was before the arm
1830        /// existed.
1831        else_body: Vec<NodeRef>,
1832    },
1833    /// `If( cond, () => { … } )` — a one-armed conditional over a result var
1834    /// that was initialised before it. `pre` holds the statements three.js
1835    /// emits ahead of the result var (its `toConst` lines), `result` is the var
1836    /// itself and `body` the statements inside the block, the last of which
1837    /// assigns `result`. The node's value is the result var.
1838    IfVar {
1839        /// The statements built ahead of `result`.
1840        pre: Vec<NodeRef>,
1841        /// The initialised result variable.
1842        result: NodeRef,
1843        /// The branch condition.
1844        cond: NodeRef,
1845        /// The block's statements, the last of which assigns `result`.
1846        body: Vec<NodeRef>,
1847    },
1848    /// `Discard()` — a bare `discard;`.
1849    Discard,
1850    /// `return value;` inside an emitted `fn` — what an `If( cond, () => {
1851    /// return x; } )` in a `Fn()` body compiles to (`neutralToneMapping`'s
1852    /// early out).
1853    Return {
1854        /// The returned value.
1855        value: NodeRef,
1856    },
1857    /// `x.not()` — `( ! x )`. A `bool`, or a `bvecN` for an `N`-vector
1858    /// operand (`OperatorNode.getNodeType()`'s `'!'` arm).
1859    Not {
1860        /// The negated node.
1861        node: NodeRef,
1862    },
1863    /// `x.bitNot()` — `( ~ x )`, typed `getIntegerType( typeA )`.
1864    BitNot {
1865        /// The negated node.
1866        node: NodeRef,
1867        /// The result's WGSL type.
1868        ty: Type,
1869    },
1870    /// `cond.select( a, b )` — lowered to an `if`/`else` writing a result var,
1871    /// exactly as Three does.
1872    Select {
1873        /// The branch condition.
1874        cond: NodeRef,
1875        /// The value when `cond` is true.
1876        a: NodeRef,
1877        /// The value when `cond` is false.
1878        b: NodeRef,
1879        /// The result's WGSL type.
1880        ty: Type,
1881    },
1882    /// `storageStruct.get( 'member' )` — `MemberNode` on a
1883    /// [`BufferSource::Struct`] storage buffer: `NodeBuffer_N.member`.
1884    StructMember {
1885        /// The struct buffer.
1886        buffer: Rc<BufferNode>,
1887        /// The member's index in the struct's layout.
1888        member: usize,
1889    },
1890    /// `AtomicFunctionNode` — `atomicStore( &pointer, value )` and the rest of
1891    /// the family. `pointer` is a struct member or buffer element declared
1892    /// `atomic< T >`. As a bare statement it is one `atomicX( … );` line; read
1893    /// as a value as well, its result is held in a `let` first.
1894    Atomic {
1895        /// The WGSL atomic function's name, e.g. `"atomicAdd"`.
1896        method: &'static str,
1897        /// The atomic value being operated on.
1898        pointer: NodeRef,
1899        /// The operand, when the method takes one.
1900        value: Option<NodeRef>,
1901    },
1902    /// `WorkgroupInfoNode` — the array itself. Read through
1903    /// [`Node::Element`], which is how `.element( i )` reaches it.
1904    Workgroup(Rc<WorkgroupArrayDef>),
1905    /// `BarrierNode` — `workgroupBarrier()` / `storageBarrier()` /
1906    /// `textureBarrier()`, `scope` being the prefix.
1907    Barrier {
1908        /// The barrier's WGSL prefix, e.g. `"workgroup"`.
1909        scope: &'static str,
1910    },
1911    /// `SubgroupFunctionNode` — `subgroupAdd( e )`, `subgroupShuffle( e, id )`,
1912    /// `quadSwapX( e )` and the rest of the family
1913    /// (`src/nodes/gpgpu/SubgroupFunctionNode.js`). Reaching one enables
1914    /// `subgroups` in the stage that builds it.
1915    Subgroup {
1916        /// The WGSL builtin's name, e.g. `"subgroupAdd"` — three's
1917        /// `SubgroupFunctionNode.SUBGROUP_ADD` and friends.
1918        method: &'static str,
1919        /// `aNode`; `None` only for `subgroupElect()`.
1920        a: Option<NodeRef>,
1921        /// `bNode`: the lane id, shuffle mask or delta of the two-input forms.
1922        b: Option<NodeRef>,
1923    },
1924    /// A node type defined outside the crate; see [`CustomNode`]. Built by
1925    /// building what its `setup` returns.
1926    Custom(Rc<dyn CustomNode>),
1927    /// `ContextNode` — `node.context( { … } )`. Builds `node` with `value`'s
1928    /// keys merged into `builder.context`, and restores the previous context
1929    /// afterwards.
1930    Context {
1931        /// The node built under the merged context.
1932        node: NodeRef,
1933        /// The context entries merged in.
1934        value: Rc<ContextValue>,
1935    },
1936    /// `IsolateNode` — `isolate( node )`. Builds `node` in a `NodeCache` of
1937    /// its own, whose parent is the cache in force where the isolate is
1938    /// built: what `node`'s subgraph sets up, counts or declares for the first
1939    /// time stays inside it.
1940    Isolate {
1941        /// The node built in its own cache.
1942        node: NodeRef,
1943    },
1944    /// `ExpressionNode` — `expression( snippet, type )`: raw WGSL. A value
1945    /// type prints `snippet` where the node is read; `void` writes it to the
1946    /// flow as a statement. Not cacheable: each read prints it again.
1947    Expression {
1948        /// The WGSL, verbatim.
1949        snippet: Rc<str>,
1950        /// Its type, `Void` for a statement.
1951        ty: Type,
1952    },
1953    /// `DebugNode` — `debug( node, callback )`: `node`'s snippet, passed
1954    /// through after `callback` (or a log of the flow so far) has seen it.
1955    Debug {
1956        /// The node debugged.
1957        node: NodeRef,
1958        /// `null` logs the stage's flow code to stderr, as three's `log()`
1959        /// does to the console.
1960        callback: Option<DebugCallback>,
1961    },
1962    /// `structType( values )` — `StructNode`: a value of a [`struct_type`]
1963    /// (`StructTypeNode`) built from one value per member, in member order.
1964    /// Always held in a var of the struct's type, which is where three's
1965    /// `StructNode` lands too (`nodeVar31 = StructType0( … )` in the TRAA
1966    /// dump); its [`ty`](NodeRef::ty) is [`Type::Void`] because the port's
1967    /// `Type` has no struct case, and only [`Node::StructGet`] reads it.
1968    ///
1969    /// [`struct_type`]: crate::nodes::tsl::struct_type
1970    StructNew {
1971        /// The struct's layout.
1972        layout: Rc<StructLayout>,
1973        /// One value per member.
1974        values: Vec<NodeRef>,
1975    },
1976    /// `outputStruct( ...members )` — `OutputStructNode`, a fragment stage's
1977    /// whole result as one `@location( i )` member per value, each of its own
1978    /// type. It is only ever a material's `outputNode`
1979    /// (`DepthOfFieldNode`'s CoC pass writes its near and far fields this
1980    /// way); the builder turns it into the `OutputType` struct and its
1981    /// `output.mN = …` lines, as it does an [`MrtNode`]'s members, and it
1982    /// has no value of its own.
1983    ///
1984    /// [`MrtNode`]: crate::nodes::MrtNode
1985    OutputStruct {
1986        /// The members, by location.
1987        members: Vec<NodeRef>,
1988    },
1989    /// `structNode.get( name )` — `MemberNode` over a [`Node::StructNew`]
1990    /// (or over a block or `Fn()` whose result is one): `{ var }.{ member }`.
1991    StructGet {
1992        /// The struct value read.
1993        value: NodeRef,
1994        /// Its layout.
1995        layout: Rc<StructLayout>,
1996        /// The member's index in the layout.
1997        member: usize,
1998    },
1999}
2000
2001/// A handle on a node. Fluent TSL methods hang off this; see `tsl.rs`.
2002#[derive(Clone, Debug)]
2003pub struct NodeRef(Rc<Node>);
2004
2005impl NodeRef {
2006    /// Wraps a node in a new handle.
2007    pub fn new(node: Node) -> Self {
2008        NodeRef(Rc::new(node))
2009    }
2010
2011    /// The `Rc<Node>` this handle wraps.
2012    pub fn as_rc(&self) -> &Rc<Node> {
2013        &self.0
2014    }
2015
2016    /// The `Node` this handle wraps.
2017    pub fn node(&self) -> &Node {
2018        &self.0
2019    }
2020
2021    /// The identity the builder keys its per-node state on.
2022    pub fn key(&self) -> usize {
2023        Rc::as_ptr(&self.0) as *const u8 as usize
2024    }
2025
2026    /// `Node.getNodeType( builder )`.
2027    pub fn ty(&self) -> Type {
2028        match &*self.0 {
2029            Node::Const { ty, .. } => *ty,
2030            Node::ConstArray { element_ty, .. } => *element_ty,
2031            Node::ArrayVar { element_ty, .. } => *element_ty,
2032            Node::Uniform(u) => u.ty,
2033            Node::BufferElement { buffer, .. } => buffer.element_ty,
2034            Node::Attribute { ty, .. } => *ty,
2035            Node::InstancedAttribute { ty, .. } => *ty,
2036            Node::Builtin(b) => b.ty(),
2037            Node::Var(v) => v.ty,
2038            Node::VarIntent(v) => v.ty,
2039            Node::Let(v) => v.ty,
2040            Node::Varying(v) => v.ty,
2041            Node::TextureSize { .. } => Type::UVec2,
2042            Node::VaryingProperty { ty, .. } => *ty,
2043            Node::Property { ty, .. } => *ty,
2044            Node::Param { ty, .. } => *ty,
2045            Node::Assign { target, .. } => target.ty(),
2046            Node::Op { ty, .. } => *ty,
2047            Node::Math { ty, .. } => *ty,
2048            Node::Swizzle { ty, .. } => *ty,
2049            Node::Cast { ty, .. } => *ty,
2050            Node::Neg { ty, .. } => *ty,
2051            Node::Join { ty, .. } => *ty,
2052            Node::Element { ty, .. } => *ty,
2053            Node::Texture { ty, .. } => *ty,
2054            Node::Call { def, .. } => def.ret,
2055            Node::Code(_) => Type::Void,
2056            Node::CodeCall { def, .. } => def.ret,
2057            Node::IfVar { result, .. } => result.ty(),
2058            Node::Select { ty, .. } => *ty,
2059            Node::Block { result, .. } => result.ty(),
2060            Node::Loop { .. }
2061            | Node::If { .. }
2062            | Node::Discard
2063            | Node::Break
2064            | Node::Continue
2065            | Node::TextureStore { .. }
2066            | Node::Return { .. } => Type::Void,
2067            Node::Not { node } => Type::vector_of(Type::Bool, node.ty().components().max(1)),
2068            Node::BitNot { ty, .. } => *ty,
2069            Node::StructMember { buffer, member } => match &buffer.source {
2070                BufferSource::Struct { layout, .. } => layout.members[*member].ty,
2071                _ => unreachable!("three-rs: a struct member is only built on a struct buffer"),
2072            },
2073            // `AtomicFunctionNode.getNodeType()` is the pointer's type.
2074            Node::Atomic { pointer, .. } => pointer.ty(),
2075            Node::Workgroup(def) => def.element_ty,
2076            Node::Barrier { .. } => Type::Void,
2077            Node::Subgroup { method, a, b } => subgroup_type(method, a.as_ref(), b.as_ref()),
2078            Node::Compute { output, .. } => output.ty(),
2079            Node::Custom(custom) => custom.node_type(),
2080            Node::Context { node, .. } | Node::Isolate { node } | Node::Debug { node, .. } => {
2081                node.ty()
2082            }
2083            Node::Expression { ty, .. } => *ty,
2084            Node::StructNew { .. } | Node::OutputStruct { .. } => Type::Void,
2085            Node::StructGet { layout, member, .. } => layout.members[*member].ty,
2086        }
2087    }
2088}
2089
2090impl From<&NodeRef> for NodeRef {
2091    fn from(n: &NodeRef) -> Self {
2092        n.clone()
2093    }
2094}
2095
2096/// `float( x )` from a Rust number — the `From` impls are what let TSL methods
2097/// take `impl Into<NodeRef>` and read like the JS.
2098macro_rules! const_from {
2099    ($t:ty, $ty:expr) => {
2100        impl From<$t> for NodeRef {
2101            fn from(v: $t) -> Self {
2102                NodeRef::new(Node::Const {
2103                    ty: $ty,
2104                    values: vec![v as f64],
2105                })
2106            }
2107        }
2108    };
2109}
2110
2111const_from!(f64, Type::F32);
2112const_from!(f32, Type::F32);
2113const_from!(i32, Type::I32);
2114const_from!(u32, Type::U32);
2115
2116impl From<bool> for NodeRef {
2117    fn from(v: bool) -> Self {
2118        NodeRef::new(Node::Const {
2119            ty: Type::Bool,
2120            values: vec![if v { 1.0 } else { 0.0 }],
2121        })
2122    }
2123}
2124
2125impl From<Color> for NodeRef {
2126    fn from(c: Color) -> Self {
2127        NodeRef::new(Node::Const {
2128            ty: Type::Vec3,
2129            values: vec![c.r, c.g, c.b],
2130        })
2131    }
2132}
2133
2134impl From<Vector2> for NodeRef {
2135    fn from(v: Vector2) -> Self {
2136        NodeRef::new(Node::Const {
2137            ty: Type::Vec2,
2138            values: vec![v.x, v.y],
2139        })
2140    }
2141}
2142
2143impl From<Vector3> for NodeRef {
2144    fn from(v: Vector3) -> Self {
2145        NodeRef::new(Node::Const {
2146            ty: Type::Vec3,
2147            values: vec![v.x, v.y, v.z],
2148        })
2149    }
2150}
2151
2152impl From<Matrix4> for NodeRef {
2153    fn from(m: Matrix4) -> Self {
2154        NodeRef::new(Node::Const {
2155            ty: Type::Mat4,
2156            values: m.elements.to_vec(),
2157        })
2158    }
2159}
2160
2161/// A lazily-initialised accessor singleton. Three's `positionLocal` etc. are
2162/// module-level node objects, and their object identity is what makes the
2163/// builder emit one `var` shared by every reference; `thread_local!` + `Rc`
2164/// clone reproduces that.
2165pub(crate) struct Lazy<T: 'static> {
2166    cell: RefCell<Option<T>>,
2167}
2168
2169impl<T: Clone + 'static> Default for Lazy<T> {
2170    fn default() -> Self {
2171        Self::new()
2172    }
2173}
2174
2175impl<T: Clone + 'static> Lazy<T> {
2176    pub const fn new() -> Self {
2177        Lazy {
2178            cell: RefCell::new(None),
2179        }
2180    }
2181
2182    pub fn get(&self, init: impl FnOnce() -> T) -> T {
2183        let mut slot = self.cell.borrow_mut();
2184        if slot.is_none() {
2185            *slot = Some(init());
2186        }
2187        slot.as_ref()
2188            .expect("three-rs: the lazy slot was filled in just above")
2189            .clone()
2190    }
2191}
2192
2193// The program cache key hashes the binding descriptions, which bottom out in
2194// these three types. Their `Hash` impls are written by hand rather than derived
2195// so that they reach every field the *generated program* depends on and no
2196// field that is only a value: a texture's pixels, an instanced attribute's
2197// array. Three.js draws the same line in `Node.getCacheKey()`, where a texture
2198// contributes its uuid and never its image.
2199
2200impl std::hash::Hash for UniformSource {
2201    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2202        std::mem::discriminant(self).hash(state);
2203        match self {
2204            UniformSource::LightColorIntensity(i)
2205            | UniformSource::LightCutoffDistance(i)
2206            | UniformSource::LightDecay(i)
2207            | UniformSource::LightViewPosition(i)
2208            | UniformSource::LightWorldPosition(i)
2209            | UniformSource::LightTargetPosition(i)
2210            | UniformSource::LightGroundColor(i)
2211            | UniformSource::LightConeCos(i)
2212            | UniformSource::LightPenumbraCos(i)
2213            | UniformSource::ShadowMatrix(i)
2214            | UniformSource::ShadowCameraNear(i)
2215            | UniformSource::ShadowCameraFar(i)
2216            | UniformSource::ShadowBias(i)
2217            | UniformSource::ShadowNormalBias(i)
2218            | UniformSource::ShadowRadius(i)
2219            | UniformSource::ShadowBlurSamples(i)
2220            | UniformSource::ShadowMapSize(i)
2221            | UniformSource::ShadowIntensity(i) => i.hash(state),
2222            // A baked `uniform( value )`: two materials can generate identical
2223            // WGSL and differ only here (a texture's uv matrix, say), so the
2224            // bits are part of the key.
2225            UniformSource::Value(values) => {
2226                values.len().hash(state);
2227                for value in values {
2228                    value.to_bits().hash(state);
2229                }
2230            }
2231            // Identity, never contents: the whole point is that the value
2232            // moves between draws while the program stays one program.
2233            UniformSource::Settable(cell) => cell.hash(state),
2234            UniformSource::Live(value) => value.hash(state),
2235            _ => {}
2236        }
2237    }
2238}
2239
2240impl std::hash::Hash for BufferSource {
2241    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2242        std::mem::discriminant(self).hash(state);
2243        match self {
2244            BufferSource::Range { min, max } => {
2245                for value in min.iter().chain(max.iter()) {
2246                    value.to_bits().hash(state);
2247                }
2248            }
2249            // Identity, never contents — the array behind an instanced
2250            // attribute is megabytes and is resolved per draw anyway.
2251            BufferSource::Attribute(data) | BufferSource::UniformArray(data) => {
2252                (Rc::as_ptr(data) as *const u8 as usize).hash(state)
2253            }
2254            // The layout is spelled into the WGSL, which the key already
2255            // hashes; the initial contents are a value and stay out.
2256            BufferSource::Struct { layout, .. } => {
2257                layout.name.hash(state);
2258                for member in &layout.members {
2259                    member.name.hash(state);
2260                    member.ty.hash(state);
2261                    member.atomic.hash(state);
2262                }
2263            }
2264            // The array is a value; `.toReadOnly()` is spelt into the WGSL.
2265            BufferSource::StorageData { read_only, .. } => read_only.hash(state),
2266            BufferSource::SkeletonBoneMatrices(skeleton) => {
2267                (Rc::as_ptr(&skeleton.0) as *const u8 as usize).hash(state)
2268            }
2269            BufferSource::LightProbe(index) => index.hash(state),
2270            BufferSource::Live(value) => value.hash(state),
2271            BufferSource::InstanceMatrix
2272            | BufferSource::InstanceColor
2273            | BufferSource::MorphInfluences
2274            | BufferSource::BoneMatrices
2275            | BufferSource::PreviousBoneMatrices
2276            | BufferSource::CameraViewMatrices
2277            | BufferSource::CameraProjectionMatrices
2278            | BufferSource::ClippingIntersection
2279            | BufferSource::ClippingUnion
2280            | BufferSource::Storage
2281            | BufferSource::AtomicStorage => {}
2282        }
2283    }
2284}
2285
2286impl std::hash::Hash for TextureSource {
2287    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2288        std::mem::discriminant(self).hash(state);
2289        match self {
2290            // Identity only, as `Node.getCacheKey()` takes a texture's uuid.
2291            // The format, colour space, filters, wrapping and anisotropy are
2292            // *not* here: the compiled program's layout reads only the
2293            // binding's `kind` and `visibility` (`programs::layout_entry`),
2294            // and the view and sampler built from those fields are resolved
2295            // per draw. Neither the image data nor the `gpu` handle either —
2296            // the key must not move when the texture is uploaded.
2297            TextureSource::Texture2D(texture) => texture.id().hash(state),
2298            TextureSource::Depth(texture) | TextureSource::ShadowMap(texture) => {
2299                texture.id().hash(state)
2300            }
2301            TextureSource::Cube(texture) => texture.id().hash(state),
2302            TextureSource::DataArray(texture) => texture.id().hash(state),
2303            TextureSource::Data(texture) => texture.id().hash(state),
2304            TextureSource::CubeDepth(texture) => texture.id().hash(state),
2305            TextureSource::Texture3D(texture) => texture.id().hash(state),
2306            // The access is part of the declaration, so it is part of the key.
2307            TextureSource::Storage(texture, access) => {
2308                texture.id().hash(state);
2309                access.hash(state);
2310            }
2311            TextureSource::Storage3D(texture, access) => {
2312                texture.id().hash(state);
2313                access.hash(state);
2314            }
2315        }
2316    }
2317}
2318
2319/// Derived but for `Attribute`, whose `Rc<Vec<f32>>` is the caller's whole
2320/// per-instance array — `BatchedText` hands it four floats per glyph.
2321impl std::fmt::Debug for BufferSource {
2322    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2323        match self {
2324            BufferSource::InstanceMatrix => f.write_str("InstanceMatrix"),
2325            BufferSource::InstanceColor => f.write_str("InstanceColor"),
2326            BufferSource::Storage => f.write_str("Storage"),
2327            BufferSource::AtomicStorage => f.write_str("AtomicStorage"),
2328            BufferSource::Struct { layout, init } => f
2329                .debug_struct("Struct")
2330                .field("layout", &layout.name)
2331                .field("init", &format_args!("{} words", init.len()))
2332                .finish(),
2333            BufferSource::Range { min, max } => f
2334                .debug_struct("Range")
2335                .field("min", min)
2336                .field("max", max)
2337                .finish(),
2338            BufferSource::MorphInfluences => f.write_str("MorphInfluences"),
2339            BufferSource::BoneMatrices => f.write_str("BoneMatrices"),
2340            BufferSource::PreviousBoneMatrices => f.write_str("PreviousBoneMatrices"),
2341            BufferSource::CameraViewMatrices => f.write_str("CameraViewMatrices"),
2342            BufferSource::CameraProjectionMatrices => f.write_str("CameraProjectionMatrices"),
2343            BufferSource::ClippingIntersection => f.write_str("ClippingIntersection"),
2344            BufferSource::ClippingUnion => f.write_str("ClippingUnion"),
2345            BufferSource::Attribute(data) => f
2346                .debug_tuple("Attribute")
2347                .field(&format_args!("{} floats", data.len()))
2348                .finish(),
2349            BufferSource::UniformArray(data) => f
2350                .debug_tuple("UniformArray")
2351                .field(&format_args!("{} floats", data.len()))
2352                .finish(),
2353            BufferSource::StorageData { init, read_only } => f
2354                .debug_struct("StorageData")
2355                .field("init", &format_args!("{} words", init.len()))
2356                .field("read_only", read_only)
2357                .finish(),
2358            BufferSource::SkeletonBoneMatrices(skeleton) => f
2359                .debug_tuple("SkeletonBoneMatrices")
2360                .field(&format_args!("{} bones", skeleton.0.borrow().bones.len()))
2361                .finish(),
2362            BufferSource::LightProbe(index) => f.debug_tuple("LightProbe").field(index).finish(),
2363            BufferSource::Live(value) => f.debug_tuple("Live").field(value).finish(),
2364        }
2365    }
2366}