Skip to main content

three_rs/nodes/
builder.rs

1//! Port of `three.js/src/nodes/core/NodeBuilder.js` — the frontend half of the
2//! builder: build stages, slot allocation, flow emission and the cache key.
3//!
4//! Three runs `setup` → `analyze` → `generate` over `defaultShaderStages =
5//! [ 'fragment', 'vertex' ]`, fragment first. So does this: the material's
6//! setup pushes statements onto the two stage flows, `analyze()` counts how
7//! often each node is reached (visiting a node's children only the first time
8//! it is seen — which is exactly why `saturation`'s expression appears inlined
9//! three times inside `hue` in three.js' own output), and `generate()` walks
10//! the statements left to right, letting each node emit the lines it needs
11//! before the line that uses it.
12
13use std::collections::{HashMap, HashSet};
14use std::hash::{Hash, Hasher};
15use std::rc::Rc;
16
17use crate::core::{AttributeDesc, AttributeLayout};
18
19use super::frame::{NodeUpdate, NodeUpdateType, UpdateNode};
20use super::node::{
21    BufferNode, BufferSource, Builtin, ContextValue, CustomNode, FnDef, InstanceBuffer, Node,
22    NodeRef, SampleMode, TextureSource, Type, UniformGroup, UniformNode, UniformSource, UpdateType,
23    VaryingDef,
24};
25use super::wgsl::{self, TextureKind};
26
27/// `WebGPUCapabilities.getUniformBufferLimit()` —
28/// `device.limits.maxUniformBufferBindingSize`. A thread-local because the
29/// nodes that branch on it (`RangeNode`, `InstanceNode`, later `SkinningNode`)
30/// are built by free TSL functions with no builder in hand; `Renderer::new()`
31/// sets it from the device it opened. The default is WebGPU's guaranteed
32/// minimum, 64 KiB — the value Chrome reports on the grader's adapter, and the
33/// one three.js' own dumps were taken with.
34pub(crate) const DEFAULT_UNIFORM_BUFFER_LIMIT: usize = 65536;
35
36std::thread_local! {
37    static UNIFORM_BUFFER_LIMIT: std::cell::Cell<usize> =
38        const { std::cell::Cell::new(DEFAULT_UNIFORM_BUFFER_LIMIT) };
39}
40
41/// `builder.getUniformBufferLimit()`.
42pub(crate) fn uniform_buffer_limit() -> usize {
43    UNIFORM_BUFFER_LIMIT.with(|l| l.get())
44}
45
46/// Set by `Renderer::new()` from `device.limits().max_uniform_buffer_binding_size`.
47pub(crate) fn set_uniform_buffer_limit(bytes: usize) {
48    UNIFORM_BUFFER_LIMIT.with(|l| l.set(bytes));
49}
50
51#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
52pub(crate) enum Stage {
53    Fragment,
54    Vertex,
55    /// `'compute'`. Not one of `defaultShaderStages`: a compute shader is built
56    /// on its own by `WGSLNodeBuilder` with `shaderStage = 'compute'`, so the
57    /// vertex and fragment slots of a compute build stay empty.
58    Compute,
59}
60
61impl Stage {
62    fn index(self) -> usize {
63        match self {
64            Stage::Fragment => 0,
65            Stage::Vertex => 1,
66            Stage::Compute => 2,
67        }
68    }
69}
70
71/// Which shader stages a binding has to be visible in.
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
73pub struct Visibility {
74    /// Visible to the vertex stage.
75    pub vertex: bool,
76    /// Visible to the fragment stage.
77    pub fragment: bool,
78    /// Visible to a compute stage.
79    pub compute: bool,
80}
81
82impl Visibility {
83    fn add(&mut self, stage: Stage) {
84        match stage {
85            Stage::Vertex => self.vertex = true,
86            Stage::Fragment => self.fragment = true,
87            Stage::Compute => self.compute = true,
88        }
89    }
90
91    pub(crate) fn stages(self) -> wgpu::ShaderStages {
92        let mut s = wgpu::ShaderStages::NONE;
93        if self.vertex {
94            s |= wgpu::ShaderStages::VERTEX;
95        }
96        if self.fragment {
97            s |= wgpu::ShaderStages::FRAGMENT;
98        }
99        if self.compute {
100            s |= wgpu::ShaderStages::COMPUTE;
101        }
102        s
103    }
104}
105
106/// One member of a generated uniform struct.
107#[derive(Clone, Debug, Hash)]
108pub struct UniformMember {
109    /// The member's name in the generated struct.
110    pub name: String,
111    /// Where the value comes from.
112    pub source: UniformSource,
113    /// The member's WGSL type.
114    pub ty: Type,
115    /// Byte offset within the struct.
116    pub offset: u32,
117}
118
119/// One entry of a generated bind-group layout.
120///
121/// `Hash` is what the program cache key is built from, so it has to cover
122/// every field the generated program depends on — and, through the hand-written
123/// impls on [`TextureSource`] and [`BufferSource`], none of the bulk data a
124/// binding merely points at.
125#[derive(Clone, Debug, Hash)]
126pub enum BindingDesc {
127    /// A uniform struct binding.
128    Uniforms {
129        /// Which group this uniform block belongs to (render or object).
130        group: UniformGroup,
131        /// The struct's members, in declaration order.
132        members: Vec<UniformMember>,
133        /// The struct's total size in bytes, rounded up to 16.
134        size: u32,
135        /// How often the renderer refreshes this block's bytes.
136        update: UpdateType,
137        /// Which shader stages read this binding.
138        visibility: Visibility,
139    },
140    /// A texture binding.
141    Texture {
142        /// Where the texture's data comes from.
143        source: TextureSource,
144        /// The texture's dimension, sample type and filterability.
145        kind: TextureKind,
146        /// Which shader stages read this binding.
147        visibility: Visibility,
148    },
149    /// A sampler binding.
150    Sampler {
151        /// The texture this sampler was created for.
152        source: TextureSource,
153        /// The texture's dimension, sample type and filterability.
154        kind: TextureKind,
155        /// Which shader stages read this binding.
156        visibility: Visibility,
157    },
158    /// A storage buffer binding — `BufferNode` (`range()`, `storage()`, …).
159    Buffer {
160        /// The binding's name in the shader.
161        name: String,
162        /// The `BufferNode`'s own identity ([`BufferId`](crate::nodes::node::BufferId), a never-reused
163        /// counter), which is what the renderer keys its GPU buffer on. Two
164        /// `range( 0, 1 )` nodes have equal `source`s but must stay two
165        /// buffers with two random fills, so dedup is by identity and never by
166        /// value — and the identity outlives the node, so the renderer's cache
167        /// cannot hand a new buffer a dead one's fill.
168        id: usize,
169        /// Where the buffer's contents come from.
170        source: BufferSource,
171        /// The type of one element.
172        element_ty: Type,
173        /// The number of elements.
174        count: usize,
175        /// Which shader stages read this binding.
176        visibility: Visibility,
177    },
178}
179
180/// One vertex attribute of a built program: where its `@location` comes from.
181#[derive(Clone, Debug)]
182pub struct AttributeSlot {
183    /// The name in the shader — a geometry attribute's own name, or
184    /// `nodeAttributeN` for a generated one.
185    pub name: String,
186    /// The attribute's WGSL type — the input's declared type, which for a
187    /// geometry attribute is `getTypeFromAttribute()` of the attribute itself,
188    /// not the type the node graph reads it as.
189    pub ty: Type,
190    /// The `GPUVertexFormat` the pipeline reads the attribute's bytes as.
191    pub format: wgpu::VertexFormat,
192    /// Where the attribute's data comes from.
193    pub source: AttributeSource,
194}
195
196/// A geometry attribute's place in its vertex buffer —
197/// `createShaderVertexBuffers()`'s per-attribute layout, from the
198/// [`AttributeDesc`] the renderer handed over.
199#[derive(Clone, Debug, PartialEq, Eq, Hash)]
200#[doc(hidden)]
201pub struct GeometrySlot {
202    /// The attribute's name on the geometry.
203    pub name: &'static str,
204    /// `arrayStride` of its buffer, in bytes.
205    pub array_stride: u64,
206    /// Its offset within one stride, in bytes.
207    pub offset: u64,
208    /// `stepMode: 'instance'`.
209    pub instanced: bool,
210    /// Attributes with the same `Some( group )` are views of one
211    /// `InterleavedBuffer` and share a vertex buffer; `None` is a buffer of
212    /// its own.
213    pub group: Option<usize>,
214}
215
216/// Where one [`AttributeSlot`]'s data comes from.
217#[derive(Clone, Debug)]
218pub enum AttributeSource {
219    /// A named `BufferGeometry` attribute.
220    Geometry(GeometrySlot),
221    /// An `InstancedBufferAttribute` view: the shared per-instance buffer plus
222    /// this attribute's offset within one instance, in floats.
223    Instance {
224        /// The shared per-instance buffer.
225        buffer: Rc<InstanceBuffer>,
226        /// This attribute's offset within one instance, in floats.
227        offset: usize,
228    },
229}
230
231/// Where one `GPUVertexBufferLayout` gets its bytes.
232#[derive(Clone, Debug)]
233pub enum VertexBufferSource {
234    /// A `BufferGeometry` attribute — for an interleaved buffer, the first
235    /// of its views the program reads; every view resolves to the same
236    /// buffer.
237    Geometry(GeometrySlot),
238    /// A shared per-instance buffer.
239    Instance(Rc<InstanceBuffer>),
240}
241
242/// One entry of `WebGPUAttributeUtils.createShaderVertexBuffers()`: a buffer,
243/// its stride and step mode, and the attributes that read from it. Geometry
244/// attributes get one buffer each (three.js' non-interleaved case); every
245/// attribute sharing an `InstanceBuffer` shares one `stepMode: 'instance'`
246/// buffer, which is how the instance matrix arrives as four `vec4`s at offsets
247/// 0/16/32/48 of a 64-byte stride.
248#[derive(Clone, Debug)]
249pub struct VertexBufferDesc {
250    /// Where this buffer's bytes come from.
251    pub source: VertexBufferSource,
252    /// `arrayStride`, in bytes.
253    pub array_stride: u64,
254    /// `stepMode: 'instance'`.
255    pub instanced: bool,
256    /// `( shaderLocation, type, offset in bytes, format )`.
257    pub attributes: Vec<(u32, Type, u64, wgpu::VertexFormat)>,
258}
259
260/// One `ComputeNode` — `Fn( () => { … } )().compute( count, workgroupSize )`.
261///
262/// Built with [`ComputeFlow::new`], which takes the two things three's
263/// `.compute()` cannot default; the rest are fields to set afterwards
264/// (`docs/api.md` decision 3).
265#[derive(Clone)]
266#[non_exhaustive]
267pub struct ComputeFlow {
268    /// The kernel body's statements, in order.
269    pub statements: Vec<NodeRef>,
270    /// `.compute( count )` — the number of invocations the kernel is *for*, and
271    /// the bound the generated early-return checks `instanceIndex` against,
272    /// unless the kernel has a barrier (`docs/nodes.md` §84.6).
273    pub count: usize,
274    /// `ComputeNode`'s `workgroupSize`, padded to three components exactly as
275    /// `computeKernel( node, workgroupSize = [ 64 ] )` pads it.
276    pub workgroup_size: [u32; 3],
277    /// `computeNode.setName( … )`.
278    pub name: Option<String>,
279    /// `computeNode.onInit` — a second kernel the renderer runs **once**,
280    /// before the first dispatch of this one, in its own command encoder and
281    /// its own submit.
282    pub on_init: Option<Box<ComputeFlow>>,
283}
284
285impl ComputeFlow {
286    /// `Fn( () => { statements } )().compute( count )`: the kernel body and
287    /// the invocation count, with three's default `workgroupSize` of
288    /// `[ 64 ]`, no name and no `onInit`.
289    pub fn new(statements: Vec<NodeRef>, count: usize) -> Self {
290        Self {
291            statements,
292            count,
293            workgroup_size: [64, 1, 1],
294            name: None,
295            on_init: None,
296        }
297    }
298}
299
300impl std::fmt::Debug for ComputeFlow {
301    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
302        f.debug_struct("ComputeFlow")
303            .field("statements", &self.statements.len())
304            .field("count", &self.count)
305            .field("workgroup_size", &self.workgroup_size)
306            .field("name", &self.name)
307            .field("on_init", &self.on_init.is_some())
308            .finish()
309    }
310}
311
312/// `ComputeNode.updateBefore( frame )`: `frame.renderer.compute( this )`,
313/// with `updateBeforeType = NodeUpdateType.FRAME` — a kernel a material reads
314/// as a value runs once a frame, before the first draw that reads it.
315impl NodeUpdate for ComputeFlow {
316    fn update_before_type(&self) -> NodeUpdateType {
317        NodeUpdateType::Frame
318    }
319
320    fn update_before(&self, renderer: &mut crate::renderer::Renderer) -> bool {
321        renderer
322            .compute(self)
323            .expect("three-rs: a material's ComputeNode dispatches");
324        true
325    }
326}
327
328/// The built compute shader and everything its pipeline and dispatch need.
329pub struct ComputeProgram {
330    /// The generated `@compute` entry point's WGSL source.
331    pub wgsl: String,
332    /// Bind groups in `@group` order.
333    pub groups: Vec<Vec<BindingDesc>>,
334    /// `@workgroup_size`, padded to three components.
335    pub workgroup_size: [u32; 3],
336    /// The `dispatchWorkgroups` arguments.
337    pub dispatch: [u32; 3],
338    /// The kernel reads a subgroup builtin or calls a subgroup function, so
339    /// its WGSL has `enable subgroups;` and it needs a device with
340    /// `wgpu::Features::SUBGROUP` (`WGSLNodeBuilder.enableSubGroups()`).
341    pub subgroups: bool,
342    pub(crate) cache_key: u64,
343}
344
345/// The built vertex and fragment shaders and everything their pipeline needs.
346pub struct NodeProgram {
347    /// The generated `@vertex` entry point's WGSL source.
348    pub vertex_wgsl: String,
349    /// The generated `@fragment` entry point's WGSL source.
350    pub fragment_wgsl: String,
351    /// Vertex attributes in `@location` order.
352    pub attributes: Vec<AttributeSlot>,
353    /// Bind groups in `@group` order.
354    pub groups: Vec<Vec<BindingDesc>>,
355    /// A stage — in practice the fragment stage, since a subgroup function
356    /// in the vertex stage is an error — reads a subgroup builtin or calls a
357    /// subgroup function, so its WGSL has `enable subgroups;` and the material needs a device with `wgpu::Features::SUBGROUP`
358    /// (`WGSLNodeBuilder.enableSubGroups()`). See `docs/nodes.md` §84.3.
359    pub subgroups: bool,
360    pub(crate) cache_key: u64,
361    /// `nodeBuilderState.updateBeforeNodes`: every node the material reaches
362    /// that has an `updateBefore()`, in the order the build met them. A
363    /// `ComputeNode` read as a value (`renderer.compute( this )`, once per
364    /// frame), a pass or `rtt()` whose texture is bound (it renders into
365    /// it), a [`CustomNode`] with an update type.
366    /// Kept with the program, so a steady frame reads the list and walks no
367    /// graph. See `docs/nodes.md` §57.
368    pub(crate) update_before: Vec<UpdateNode>,
369    /// `nodeBuilderState.updateNodes`.
370    pub(crate) update: Vec<UpdateNode>,
371    /// `nodeBuilderState.updateAfterNodes`.
372    pub(crate) update_after: Vec<UpdateNode>,
373    /// Whether the program binds any of `VelocityNode`'s uniforms or the
374    /// previous bone matrices — three's `velocity` being among the
375    /// `updateNodes` / `updateAfterNodes`. The renderer moves the velocity
376    /// history only for such a draw, so a frame with no `velocity` output does
377    /// no previous-frame bookkeeping at all.
378    pub(crate) reads_velocity: bool,
379}
380
381impl NodeProgram {
382    /// `WebGPUAttributeUtils.createShaderVertexBuffers( renderObject )`: the
383    /// attributes grouped into vertex buffers, in first-use order — geometry
384    /// attributes one per buffer except views of one `InterleavedBuffer`,
385    /// which share one, and instanced attributes one buffer per
386    /// `InstanceBuffer`.
387    #[doc(hidden)]
388    pub fn vertex_buffers(&self) -> Vec<VertexBufferDesc> {
389        let mut out: Vec<VertexBufferDesc> = Vec::new();
390
391        for (location, slot) in self.attributes.iter().enumerate() {
392            let location = location as u32;
393            match &slot.source {
394                AttributeSource::Geometry(geometry) => {
395                    let entry = (location, slot.ty, geometry.offset, slot.format);
396                    let existing = geometry.group.and_then(|group| {
397                        out.iter_mut().find(|desc| match &desc.source {
398                            VertexBufferSource::Geometry(other) => other.group == Some(group),
399                            VertexBufferSource::Instance(_) => false,
400                        })
401                    });
402                    match existing {
403                        Some(desc) => desc.attributes.push(entry),
404                        None => out.push(VertexBufferDesc {
405                            source: VertexBufferSource::Geometry(geometry.clone()),
406                            array_stride: geometry.array_stride,
407                            instanced: geometry.instanced,
408                            attributes: vec![entry],
409                        }),
410                    }
411                }
412                AttributeSource::Instance { buffer, offset } => {
413                    let id = Rc::as_ptr(buffer) as *const u8 as usize;
414                    let existing = out.iter_mut().find(|desc| match &desc.source {
415                        VertexBufferSource::Instance(other) => {
416                            Rc::as_ptr(other) as *const u8 as usize == id
417                        }
418                        VertexBufferSource::Geometry(_) => false,
419                    });
420                    let entry = (location, slot.ty, (*offset * 4) as u64, slot.format);
421                    match existing {
422                        Some(desc) => desc.attributes.push(entry),
423                        None => out.push(VertexBufferDesc {
424                            source: VertexBufferSource::Instance(buffer.clone()),
425                            array_stride: (buffer.item_size * 4) as u64,
426                            instanced: !buffer.per_vertex,
427                            attributes: vec![entry],
428                        }),
429                    }
430                }
431            }
432        }
433
434        out
435    }
436}
437
438// ---------------------------------------------------------------------------
439
440/// What [`NodeCache`] keys its data on: what three.js' `getDataFromNode()`
441/// is handed.
442#[derive(Clone, PartialEq, Eq, Hash)]
443enum CacheKey {
444    /// A node's generated snippet: the var, `let` or result it left
445    /// (`nodeData.snippet` / `nodeData.propertyName`), keyed by identity.
446    Node(usize),
447    /// `WGSLNodeBuilder.generateTextureDimension()`'s
448    /// `textureData.dimensionsSnippet`: the `textureDimensions` var of one
449    /// texture, keyed by its binding name (one name per texture, see
450    /// `NodeBuilder::texture_names`) and the level snippet, as three keys it
451    /// on the texture object and `levelSnippet`: `"0"` for a plain tap, the
452    /// level node's snippet for `texture( map, uv ).level( n )`.
453    TextureDimensions(String, String),
454}
455
456impl CacheKey {
457    fn node(node: &NodeRef) -> Self {
458        CacheKey::Node(node.key())
459    }
460}
461
462/// `NodeCache`: per-build data with a parent chain. A lookup falls through
463/// to the parent when this cache has no entry; a write lands here only.
464///
465/// three.js' builder holds one (`builder.cache`) and swaps in a child for a
466/// subgraph (`IsolateNode`, via `getCacheFromNode( node, parent )`). The port
467/// opens a child for every block scope it emits — an `If` arm, a loop body,
468/// a `select`'s two arms — which is where three's per-scope data comes from
469/// in practice: a var declared inside an arm is visible to the rest of that
470/// arm and to nothing after it, and a snippet built before the arm is
471/// visible inside it. A layout `fn`'s body gets a cache with no parent (its
472/// own locals, its own numbering). See `docs/nodes.md` §36.
473#[derive(Default)]
474struct NodeCache {
475    data: HashMap<CacheKey, String>,
476    parent: Option<Box<NodeCache>>,
477}
478
479impl NodeCache {
480    /// `NodeCache.getData()`: this cache's entry, else the nearest parent's.
481    fn get(&self, key: &CacheKey) -> Option<&String> {
482        let mut cache = self;
483        loop {
484            if let Some(value) = cache.data.get(key) {
485                return Some(value);
486            }
487            cache = cache.parent.as_deref()?;
488        }
489    }
490
491    /// `NodeCache.setData()`.
492    fn set(&mut self, key: CacheKey, value: String) {
493        self.data.insert(key, value);
494    }
495
496    /// Make this cache a fresh child of what it was: `new NodeCache(
497    /// builder.getCache() )` followed by `builder.setCache()`.
498    fn push_child(&mut self) {
499        let parent = std::mem::take(self);
500        self.parent = Some(Box::new(parent));
501    }
502
503    /// Drop this cache's entries and restore its parent: `builder.setCache(
504    /// previousCache )`.
505    fn pop_child(&mut self) {
506        let parent = self
507            .parent
508            .take()
509            .expect("three-rs: a NodeCache child is popped only after it was pushed");
510        *self = *parent;
511    }
512}
513
514// ---------------------------------------------------------------------------
515
516/// `builder.context`: the keys a node reads while its graph is being set up,
517/// and the only build-scoped state the TSL constructors in `tsl.rs` consult.
518///
519/// three.js keeps a plain object on the builder and `ContextNode` merges keys
520/// into it for one subgraph, restoring the previous object afterwards. The
521/// port does the same with a stack of these: [`push_context`] copies the top
522/// entry, lets the caller change the keys it installs, and the returned
523/// [`ContextGuard`] pops it again. Core keys are typed fields; `extra` holds
524/// the string-keyed ones addons add (#155 decision 6).
525///
526/// The stack is one `thread_local!` beside [`NodeBuilder`] rather than a field
527/// of it, because the port's `NodeMaterial.setup()` builds the flow *before*
528/// the builder exists (three calls it from inside `builder.build()`). It is
529/// empty between material setups; outside any push, reads see the default.
530/// See `docs/nodes.md` §38.
531#[derive(Clone)]
532pub(crate) struct BuildContext {
533    /// `NodeBuilder.subBuildLayers`, one layer deep: `NORMAL` is the only name
534    /// the ladder needs. Three keeps it on the builder beside `context`.
535    pub(crate) sub_build: Option<&'static str>,
536    /// `overrideNodes`: what `material.contextNode = overrideNodes( … )`
537    /// installs for the whole of one material's setup (§27).
538    pub(crate) override_nodes: Option<super::tsl::OverrideNodes>,
539    /// `setupNormal`: `NodeMaterial.setupNormal()`'s result, the material's
540    /// `normalNode`. `normalView` takes it as its value outside the `NORMAL`
541    /// layer and `normalViewGeometry` inside it.
542    pub(crate) setup_normal: Option<NodeRef>,
543    /// `builder.isFlatShading()`: `material.flatShading && material.wireframe
544    /// === false`. `normalViewGeometry` reads it. A builder method in three,
545    /// kept here because it lives exactly as long as `setup_normal`.
546    pub(crate) flat_shading: bool,
547    /// `builder.material.side`: what `negateOnBackSide()` branches on, and so
548    /// part of every cache key that reaches `normalView` or the tangent frame.
549    pub(crate) material_side: crate::materials::Side,
550    /// `builder.geometry.hasAttribute( 'tangent' )`: what `Tangent.js` and
551    /// `Bitangent.js` branch on. With the attribute the frame comes from the
552    /// `tangent` vec4 through `modelViewMatrix`; without it, from the screen
553    /// derivatives of `TangentUtils.js`.
554    pub(crate) has_tangent: bool,
555    /// `builder.camera.isOrthographicCamera`: what `positionViewDirection`
556    /// branches on. The renderer keys the program on it through
557    /// `SetupContext::orthographic`.
558    pub(crate) orthographic_camera: bool,
559    /// `setupPositionView`: `NodeMaterial.setupPositionView()`'s result, which
560    /// `SpriteNodeMaterial` and `PointsNodeMaterial` override. `None` is the
561    /// base class' `modelViewMatrix.mul( positionLocal ).xyz`.
562    pub(crate) setup_position_view: Option<NodeRef>,
563    /// `setupClearcoatNormal`: `MeshPhysicalNodeMaterial.setup()`'s clearcoat
564    /// lobe normal, the clearcoat twin of `setup_normal`.
565    pub(crate) setup_clearcoat_normal: Option<NodeRef>,
566    /// `materialMetalness` / `materialRoughness` as `MaterialNode.setup()`
567    /// resolves them against `builder.material`: the uniform times the map's
568    /// channel when the material has one. One node per material setup, so
569    /// every reader shares the map's texture read, as three's node cache
570    /// shares it.
571    pub(crate) material_metalness: Option<NodeRef>,
572    /// See `material_metalness`.
573    pub(crate) material_roughness: Option<NodeRef>,
574    /// `material.alphaToCoverage && renderer.currentSamples > 0`: what
575    /// `shapeCircle()` branches on. Three reads both inside the `Fn` body at
576    /// build time; the renderer pushes their conjunction around the build and
577    /// keys the program on it.
578    pub(crate) alpha_to_coverage_samples: bool,
579    /// Addon keys (`getViewZ`, `getUV`, `TRAANode`'s, the light-data
580    /// nodes'): what `context( node, { … } )` installs, and what a
581    /// [`CustomNode`] reads through [`NodeBuilder::context`].
582    pub(crate) extra: HashMap<&'static str, NodeRef>,
583    /// `uniformFlow`: [`uniform_flow`](super::tsl::uniform_flow)'s key. A
584    /// two-branch `select()` built under it is WGSL's `select()`.
585    pub(crate) uniform_flow: bool,
586    /// `nodeName`: [`set_name`](super::tsl::set_name)'s key. The first
587    /// uniform built under it clears it, and takes the name unless it has
588    /// one of its own.
589    pub(crate) node_name: Option<&'static str>,
590}
591
592impl Default for BuildContext {
593    fn default() -> Self {
594        Self {
595            sub_build: None,
596            override_nodes: None,
597            setup_normal: None,
598            flat_shading: false,
599            material_side: crate::materials::Side::Front,
600            has_tangent: false,
601            orthographic_camera: false,
602            setup_position_view: None,
603            setup_clearcoat_normal: None,
604            material_metalness: None,
605            material_roughness: None,
606            alpha_to_coverage_samples: false,
607            extra: HashMap::new(),
608            uniform_flow: false,
609            node_name: None,
610        }
611    }
612}
613
614thread_local! {
615    static BUILD_CONTEXT: std::cell::RefCell<Vec<BuildContext>> =
616        const { std::cell::RefCell::new(Vec::new()) };
617}
618
619/// Pops the [`BuildContext`] [`push_context`] pushed when it goes out of
620/// scope, so an early return or a panic cannot leak one material's context
621/// into the next build.
622#[must_use = "the context is popped as soon as the guard is dropped"]
623pub(crate) struct ContextGuard {
624    depth: usize,
625}
626
627impl Drop for ContextGuard {
628    fn drop(&mut self) {
629        BUILD_CONTEXT.with(|stack| {
630            let mut stack = stack.borrow_mut();
631            debug_assert_eq!(
632                stack.len(),
633                self.depth,
634                "three-rs: BuildContext guards dropped out of order"
635            );
636            stack.pop();
637        });
638    }
639}
640
641/// `ContextNode`'s setup: a copy of the current context with `edit` applied,
642/// in force until the returned guard is dropped.
643pub(crate) fn push_context(edit: impl FnOnce(&mut BuildContext)) -> ContextGuard {
644    let mut cx = current_context(BuildContext::clone);
645    edit(&mut cx);
646    BUILD_CONTEXT.with(|stack| {
647        let mut stack = stack.borrow_mut();
648        stack.push(cx);
649        ContextGuard { depth: stack.len() }
650    })
651}
652
653/// `ContextNode`'s `builder.addContext( value )`: [`push_context`] with
654/// `value`'s keys merged over the current ones.
655pub(crate) fn push_context_value(value: &ContextValue) -> ContextGuard {
656    push_context(|cx| {
657        for (key, node) in &value.entries {
658            cx.extra.insert(key, node.clone());
659        }
660        if let Some(on) = value.uniform_flow {
661            cx.uniform_flow = on;
662        }
663        if let Some(name) = value.node_name {
664            cx.node_name = Some(name);
665        }
666    })
667}
668
669/// `builder.context.uniformFlow`. Out of line: `current_context`'s empty
670/// fallback would otherwise put a whole [`BuildContext`] in
671/// `generate_inner`'s frame.
672#[inline(never)]
673fn in_uniform_flow() -> bool {
674    current_context(|cx| cx.uniform_flow)
675}
676
677/// `UniformNode.generate()`'s `delete builder.context.nodeName`: the name an
678/// enclosing [`set_name`](super::tsl::set_name) installed, cleared from the
679/// context in force so the next uniform under it is unnamed again. An outer
680/// context keeps its own copy, as three's does once the `ContextNode`
681/// restores it.
682fn take_context_node_name() -> Option<&'static str> {
683    BUILD_CONTEXT.with(|stack| stack.borrow_mut().last_mut()?.node_name.take())
684}
685
686/// Run `f` with `alphaToCoverage` on a multisampled target (`on`) as the
687/// context the renderer installs around a material's setup and build —
688/// what `shapeCircle()` and `NodeMaterial.setupClipping()` branch on. For a
689/// test that drives [`materials::setup`](crate::materials::setup) and
690/// [`NodeBuilder::build`] without a renderer.
691#[doc(hidden)]
692pub fn with_alpha_to_coverage_samples<R>(on: bool, f: impl FnOnce() -> R) -> R {
693    let _guard = push_context(|cx| cx.alpha_to_coverage_samples = on);
694    f()
695}
696
697/// Read the current context: the top of the stack, or the default one
698/// outside any push.
699pub(crate) fn current_context<R>(read: impl FnOnce(&BuildContext) -> R) -> R {
700    thread_local! {
701        static EMPTY: BuildContext = BuildContext::default();
702    }
703    BUILD_CONTEXT.with(|stack| match stack.borrow().last() {
704        Some(cx) => read(cx),
705        None => EMPTY.with(read),
706    })
707}
708
709#[derive(Default)]
710struct StageState {
711    lines: Vec<String>,
712    indent: usize,
713    decls: Vec<(String, String)>,
714    declared: HashSet<String>,
715    attributes: Vec<AttributeSlot>,
716    builtins: Vec<Builtin>,
717    /// `WGSLNodeBuilder.enableSubGroups()` has run for this stage: its
718    /// `// directives` block holds `enable subgroups;`, and a compute entry
719    /// point takes `@builtin( subgroup_size )`.
720    subgroups: bool,
721    /// `BarrierNode.setup()` has run for this stage: it sets the builder's
722    /// `allowEarlyReturns` and `allowGlobalVariables` to `false`, so a
723    /// compute kernel with a barrier has no bounds check and declares its
724    /// vars inside `main` rather than as module-scope `var<private>`s.
725    barrier: bool,
726    codes: Vec<String>,
727    code_names: HashSet<String>,
728    /// The stage's [`NodeCache`], a child per open block.
729    cache: NodeCache,
730}
731
732struct FnScope {
733    lines: Vec<String>,
734    indent: usize,
735    locals: Vec<(String, String)>,
736    var_counter: usize,
737    const_counter: usize,
738    /// The body's [`NodeCache`]: no parent, since a `fn` sees nothing of
739    /// the stage that calls it.
740    cache: NodeCache,
741}
742
743#[derive(Default)]
744struct GroupState {
745    bindings: Vec<BindingDesc>,
746    uniform_slot: Option<usize>,
747}
748
749/// `NodeBuilder` / `WGSLNodeBuilder`: builds a material's node graph into WGSL,
750/// tracking the two shader stages, slot allocation and the flow. See
751/// `docs/nodes.md` §3.
752pub struct NodeBuilder {
753    stage: Stage,
754    stages: [StageState; 3],
755    fn_scopes: Vec<FnScope>,
756    groups: HashMap<UniformGroup, GroupState>,
757    /// `nodeUniformN` / `nodeVarN` / `nodeVaryingN` / `NodeBuffer_N` counters.
758    uniform_counter: usize,
759    var_counter: usize,
760    /// `nodeConstN` — `toConst()`'s counter, separate from `nodeVarN`'s.
761    const_counter: usize,
762    varying_counter: usize,
763    buffer_counter: usize,
764    /// `WorkgroupArray_N` — one name per `workgroupArray()`, by identity, and
765    /// the `var<workgroup>` lines `WGSLNodeBuilder.getScopedArrays()` puts
766    /// under `// locals`, in first-use order.
767    workgroup_names: HashMap<usize, String>,
768    workgroup_locals: Vec<String>,
769    /// The key of the statement [`generate_statement`](Self::generate_statement)
770    /// is generating.
771    statement: Option<usize>,
772    /// `nodeAttributeN` counter and the names already handed out, keyed by
773    /// `( instance buffer identity, offset )`.
774    attribute_counter: usize,
775    attribute_names: HashMap<(usize, usize), String>,
776    /// `varying( this )` per attribute node read in the fragment stage, so
777    /// repeated reads share one varying.
778    attribute_varyings: HashMap<usize, NodeRef>,
779    uniform_names: HashMap<usize, String>,
780    /// texture key -> (name, kind, binding slots in the object group)
781    /// Keyed on the texture id *and* whether the binding is a storage one:
782    /// a `StorageTexture` stored to by a kernel and sampled by a material is
783    /// two bindings of one texture, with two names.
784    texture_names: HashMap<(usize, bool), (String, TextureKind, Vec<usize>)>,
785    /// Varyings the fragment stage asked for, in allocation order.
786    varyings: Vec<(String, Type, bool)>,
787    varying_slots: HashMap<usize, String>,
788    /// Varyings the vertex stage has assigned to (`positionLocal.assign( …
789    /// )`) before the fragment stage asked for them; see `Node::Varying`.
790    reassigned_varyings: std::collections::HashSet<usize>,
791    /// `nodeProperties.outputNode`: inlined `Fn()` bodies and
792    /// [`CustomNode::setup`] results, expanded once per node per data cache
793    /// (see `data_cache`). The entry holds the node too: the key is its
794    /// address, and a node dropped once its `fn` body was emitted would
795    /// otherwise hand its expansion to whichever node the allocator next puts
796    /// there.
797    outputs: HashMap<(usize, usize), (NodeRef, NodeRef)>,
798    /// The half of three's `NodeCache` that `analyze` and `setup` write: the
799    /// cache a node's usage count and output live in. `0` is the build's own
800    /// cache; each [`Node::Isolate`] gets one more, whose parent is whichever
801    /// was current where the isolate was first built. A lookup walks the
802    /// parents; a first write lands in the current one. The generated
803    /// snippets are the other half, in [`NodeCache`]. See `docs/nodes.md` §45.
804    data_cache: usize,
805    data_parents: Vec<Option<usize>>,
806    /// `getCacheFromNode( isolateNode )`: each isolate's data cache, and the
807    /// node itself, held for the reason `outputs` holds its nodes.
808    isolate_caches: HashMap<usize, (NodeRef, usize)>,
809    /// The snippets an isolate's subgraph generated, per isolate, stage and
810    /// `fn` depth, so a second build of the same isolate finds them again as
811    /// three's persistent child cache does.
812    isolate_snippets: HashMap<(usize, usize, usize), HashMap<CacheKey, String>>,
813    /// Three's `updateBeforeNodes` / `updateNodes` / `updateAfterNodes`, in
814    /// first-use order. See [`NodeProgram::update_before`].
815    update_nodes: [Vec<UpdateNode>; 3],
816    /// Emitted `fn` names for `Fn()`s with a layout.
817    fn_names: HashMap<(usize, usize), String>,
818    fn_counter: usize,
819    /// `usageCount`, keyed on `(data cache, node)`.
820    usage: HashMap<(usize, usize), u32>,
821    /// `NodeBuilder.getOutputType()` — the fragment entry point's
822    /// `@location( 0 )` type. Three reads it off the render target's colour
823    /// texture: `vec2` for an `RGFormat` target (the VSM blur passes'
824    /// `VSMVertical` / `VSMHorizontal`), `vec4` for everything else.
825    output_type: Type,
826    /// `builder.camera.isArrayCamera`: the `cameraViewMatrix` and
827    /// `cameraProjectionMatrix` element nodes `Camera.js` returns for an
828    /// `ArrayCamera`, which stand in for the plain uniforms wherever the
829    /// graph reaches them. See [`with_array_cameras`](Self::with_array_cameras).
830    array_cameras: Option<ArrayCameraNodes>,
831    /// [`MaterialFlow::geometry_has_tangent`] for the flow being built.
832    geometry_has_tangent: bool,
833    /// [`MaterialFlow::geometry_attributes`] for the flow being built.
834    geometry_attributes: Vec<AttributeDesc>,
835    /// [`MaterialFlow::clip_distances`] for the flow being built.
836    clip_distances: usize,
837}
838
839/// `Camera.js`' `ArrayCamera` arm: `uniformArray( matrices ).element(
840/// cameraIndex )` for the view and the projection matrix.
841struct ArrayCameraNodes {
842    view: NodeRef,
843    projection: NodeRef,
844}
845
846impl Default for NodeBuilder {
847    fn default() -> Self {
848        Self::new()
849    }
850}
851
852/// The struct a value of no [`Type`] carries — a [`Node::StructNew`], seen
853/// through the blocks and vars that pass it on — for declaring a var of it.
854fn struct_layout_of(node: &NodeRef) -> Option<Rc<super::node::StructLayout>> {
855    match node.node() {
856        Node::StructNew { layout, .. } => Some(layout.clone()),
857        Node::Block { result, .. } => struct_layout_of(result),
858        Node::Var(v) => struct_layout_of(&v.value),
859        _ => None,
860    }
861}
862
863/// `WGSLNodeBuilder.getDirectives( shaderStage )`: one `enable X;` line per
864/// directive the stage enabled. `subgroups` is the only one the port has.
865fn directives(s: &StageState) -> &'static str {
866    if s.subgroups {
867        "enable subgroups;"
868    } else {
869        ""
870    }
871}
872
873/// The vertex stage's directives: [`directives`], plus `WGSLNodeBuilder.
874/// enableClipDistances()`'s `enable clip_distances;` when the flow writes
875/// hardware clip distances.
876#[inline(never)]
877fn vertex_directives(s: &StageState, clip_distances: usize) -> String {
878    match (directives(s), clip_distances) {
879        (d, 0) => d.to_string(),
880        ("", _) => "enable clip_distances;".to_string(),
881        (d, _) => format!("{d}\nenable clip_distances;"),
882    }
883}
884
885/// `WGSLNodeBuilder.enableHardwareClipping( planeCount )`'s
886/// `getBuiltin( 'clip_distances', 'hw_clip_distances', 'array<f32, N >',
887/// 'vertex' )` — the varyings struct member just above `builtinClipSpace`.
888#[inline(never)]
889fn clip_distances_member(clip_distances: usize) -> String {
890    if clip_distances == 0 {
891        String::new()
892    } else {
893        format!("\t@builtin( clip_distances ) hw_clip_distances : array<f32, {clip_distances} >,\n")
894    }
895}
896
897impl NodeBuilder {
898    /// A fresh builder, empty of any material's flow.
899    pub fn new() -> Self {
900        let mut b = NodeBuilder {
901            stage: Stage::Fragment,
902            stages: Default::default(),
903            fn_scopes: Vec::new(),
904            groups: HashMap::new(),
905            uniform_counter: 0,
906            var_counter: 0,
907            const_counter: 0,
908            varying_counter: 0,
909            buffer_counter: 0,
910            workgroup_names: HashMap::new(),
911            workgroup_locals: Vec::new(),
912            statement: None,
913            attribute_counter: 0,
914            attribute_names: HashMap::new(),
915            attribute_varyings: HashMap::new(),
916            uniform_names: HashMap::new(),
917            texture_names: HashMap::new(),
918            varyings: Vec::new(),
919            varying_slots: HashMap::new(),
920            reassigned_varyings: std::collections::HashSet::new(),
921            outputs: HashMap::new(),
922            data_cache: 0,
923            data_parents: vec![None],
924            isolate_caches: HashMap::new(),
925            isolate_snippets: HashMap::new(),
926            update_nodes: Default::default(),
927            fn_names: HashMap::new(),
928            fn_counter: 0,
929            usage: HashMap::new(),
930            output_type: Type::Vec4,
931            array_cameras: None,
932            geometry_has_tangent: true,
933            geometry_attributes: Vec::new(),
934            clip_distances: 0,
935        };
936        for s in &mut b.stages {
937            // Statements in `fn main` sit one tab in.
938            s.indent = 1;
939        }
940        b
941    }
942
943    // -- analyze ---------------------------------------------------------
944
945    /// `Node.analyze()`: count reaches, recursing only the first time a node is
946    /// seen. The `usageCount > 1` test is what promotes a `TempNode` to a var.
947    pub(crate) fn analyze(&mut self, node: &NodeRef) {
948        if let Some(element) = self.array_camera_element(node) {
949            self.analyze(&element);
950            return;
951        }
952        // A `ComputeNode` outside the compute stage is its output and nothing
953        // else, so it neither counts nor is counted.
954        if let Node::Compute { flow, output } = node.node() {
955            self.add_update_node(UpdateNode::new(flow.clone()));
956            let output = output.clone();
957            self.analyze(&output);
958            return;
959        }
960        // `ShaderCallNodeInternal.build()` in the analyze stage is
961        // `outputNode.build( builder, output )` and nothing else: an inlined
962        // `Fn()` call neither counts itself nor stops the walk, so two call
963        // sites that share one memoised body count *the body* twice and it
964        // becomes a var. `saturation()` read as a vec3 and again for its `.w`
965        // by `renderOutput()` is that case
966        // (`webgpu_postprocessing_difference`).
967        match node.node() {
968            Node::Call { def, args } if !def.layout => {
969                let (def, args) = (def.clone(), args.clone());
970                let body = self.call_body(node, &def, &args);
971                self.analyze(&body);
972                return;
973            }
974            // `IsolateNode.build()`: not cacheable, so it is never counted
975            // itself; its node is built in its own cache.
976            Node::Isolate { node: inner } => {
977                let inner = inner.clone();
978                let outer = self.enter_isolate(node);
979                self.analyze(&inner);
980                self.data_cache = outer;
981                return;
982            }
983            _ => {}
984        }
985        if self.increase_usage(node) > 1 {
986            // A block is an inline `Fn()` call. In three's analyze stage
987            // `StackNode.build()` runs at every reach and builds every
988            // statement and then the `outputNode` each time, so all of them
989            // are counted again. The port re-counts only `result`: a block
990            // read twice counts its result twice, and a computed result
991            // becomes a var instead of being spelled out at each read
992            // (`depthAwareBlend()` under `renderOutput()`, which reads its
993            // colour's `.xyz` and `.w`). Re-counting the statements as well
994            // would change no WGSL: they are void statements and vars, whose
995            // promotion does not depend on a second count.
996            if let Node::Block { result, .. } = node.node() {
997                let result = result.clone();
998                self.analyze(&result);
999            }
1000            return;
1001        }
1002        // `ContextNode.analyze()`: counted like any node, and its node built
1003        // under its context the first time only.
1004        let _context = match node.node() {
1005            Node::Context { value, .. } => Some(push_context_value(value)),
1006            _ => None,
1007        };
1008        for child in self.children(node) {
1009            self.analyze(&child);
1010        }
1011    }
1012
1013    /// `builder.increaseUsage( node )`: the count lives in the first data
1014    /// cache up the chain that has one for `node`, else in the current one.
1015    fn increase_usage(&mut self, node: &NodeRef) -> u32 {
1016        let key = node.key();
1017        let cache = self
1018            .data_owner(|b, id| b.usage.contains_key(&(id, key)))
1019            .unwrap_or(self.data_cache);
1020        let count = self.usage.entry((cache, key)).or_insert(0);
1021        *count += 1;
1022        *count
1023    }
1024
1025    /// `NodeCache.getData()`'s walk: the nearest data cache, from the current
1026    /// one up, for which `has` holds.
1027    fn data_owner(&self, has: impl Fn(&Self, usize) -> bool) -> Option<usize> {
1028        let mut cache = Some(self.data_cache);
1029        while let Some(id) = cache {
1030            if has(self, id) {
1031                return Some(id);
1032            }
1033            cache = self.data_parents[id];
1034        }
1035        None
1036    }
1037
1038    /// Make `isolate`'s data cache current, creating it as a child of the
1039    /// current one the first time (`getCacheFromNode( node, true )`), and
1040    /// return the one it replaced.
1041    fn enter_isolate(&mut self, isolate: &NodeRef) -> usize {
1042        let id = match self.isolate_caches.get(&isolate.key()) {
1043            Some((_, id)) => *id,
1044            None => {
1045                let id = self.data_parents.len();
1046                self.data_parents.push(Some(self.data_cache));
1047                self.isolate_caches
1048                    .insert(isolate.key(), (isolate.clone(), id));
1049                id
1050            }
1051        };
1052        std::mem::replace(&mut self.data_cache, id)
1053    }
1054
1055    /// `builder.context`: the value installed for `key` by the nearest
1056    /// enclosing [`context`](crate::nodes::tsl::context) node, if any. What a
1057    /// [`CustomNode::setup`] reads where three's reads
1058    /// `builder.context.getViewZ`.
1059    pub fn context(&self, key: &str) -> Option<NodeRef> {
1060        current_context(|cx| cx.extra.get(key).cloned())
1061    }
1062
1063    /// `builder.shaderStage === 'fragment'`.
1064    pub(crate) fn is_fragment_stage(&self) -> bool {
1065        self.stage == Stage::Fragment
1066    }
1067
1068    fn children(&mut self, node: &NodeRef) -> Vec<NodeRef> {
1069        match node.node() {
1070            Node::Const { .. }
1071            | Node::ConstArray { .. }
1072            | Node::ArrayVar { .. }
1073            | Node::Uniform(_)
1074            | Node::Attribute { .. }
1075            | Node::InstancedAttribute { .. }
1076            | Node::Builtin(_)
1077            | Node::Property { .. }
1078            | Node::Param { .. } => vec![],
1079            Node::Compute { output, .. } => vec![output.clone()],
1080            Node::BufferElement { index, .. } => vec![index.clone()],
1081            Node::Var(v) => vec![v.value.clone()],
1082            Node::VarIntent(v) => vec![v.value.clone()],
1083            Node::Let(v) => vec![v.value.clone()],
1084            Node::Varying(v) => vec![v.value.clone()],
1085            Node::Assign { target, value } => vec![value.clone(), target.clone()],
1086            Node::Op { a, b, .. } => vec![a.clone(), b.clone()],
1087            Node::Math { args, .. } => args.clone(),
1088            Node::Swizzle { node, .. } => vec![node.clone()],
1089            Node::Cast { node, .. } => vec![node.clone()],
1090            Node::Neg { node, .. } => vec![node.clone()],
1091            Node::Join { args, .. } => args.clone(),
1092            Node::Element { node, index, .. } => vec![node.clone(), index.clone()],
1093            Node::Texture { uv, mode, .. } => {
1094                let mut v = vec![uv.clone()];
1095                match mode {
1096                    SampleMode::Level(l)
1097                    | SampleMode::Bias(l)
1098                    | SampleMode::LoadLayer(l)
1099                    | SampleMode::SampleLayer(l)
1100                    | SampleMode::Compare(l) => v.push(l.clone()),
1101                    SampleMode::Grad(x, y) => {
1102                        v.push(x.clone());
1103                        v.push(y.clone());
1104                    }
1105                    SampleMode::Gather { component, offset } => {
1106                        v.push(component.clone());
1107                        v.extend(offset.clone());
1108                    }
1109                    SampleMode::GatherCompare { compare, offset } => {
1110                        v.push(compare.clone());
1111                        v.extend(offset.clone());
1112                    }
1113                    _ => {}
1114                }
1115                v
1116            }
1117            Node::Call { def, args } => {
1118                if def.layout {
1119                    // A real `fn`: its body is its own scope, analysed when it
1120                    // is emitted. Only the arguments are part of this graph.
1121                    args.clone()
1122                } else {
1123                    // Three reaches an inlined call's arguments only through the
1124                    // body it returns (`getNodeProperties` exposes `outputNode`,
1125                    // not `inputNodes`), so the arguments must not be counted
1126                    // here as well — that would promote them to vars.
1127                    vec![self.call_body(node, def, args)]
1128                }
1129            }
1130            // A `wgslFn`'s texture and sampler arguments are *bindings*, not
1131            // values: three never builds them, so they are not part of this
1132            // graph and must not be counted — counting one would promote it to
1133            // a var and emit a `textureSample` nothing reads.
1134            // A `CodeNode` in an `includes` list is a declaration, not a
1135            // value: it has no inputs of its own to count.
1136            Node::Code(_) => vec![],
1137            Node::CodeCall { def, args } => def
1138                .params
1139                .iter()
1140                .zip(args)
1141                .filter(|((_, kind), _)| matches!(kind, crate::nodes::code::ParamKind::Value(_)))
1142                .map(|(_, arg)| arg.clone())
1143                .collect(),
1144            Node::Select { cond, a, b, .. } => vec![cond.clone(), a.clone(), b.clone()],
1145            Node::Block { statements, result } => {
1146                let mut v = statements.clone();
1147                v.push(result.clone());
1148                v
1149            }
1150            Node::Loop {
1151                start,
1152                count,
1153                update,
1154                body,
1155                ..
1156            } => {
1157                let mut v = Vec::new();
1158                v.extend(start.iter().cloned());
1159                v.push(count.clone());
1160                v.extend(update.iter().cloned());
1161                v.extend(body.iter().cloned());
1162                v
1163            }
1164            Node::If {
1165                cond,
1166                body,
1167                else_body,
1168            } => {
1169                let mut v = vec![cond.clone()];
1170                v.extend(body.iter().cloned());
1171                v.extend(else_body.iter().cloned());
1172                v
1173            }
1174            Node::IfVar {
1175                pre,
1176                result,
1177                cond,
1178                body,
1179            } => {
1180                let mut v = pre.clone();
1181                v.push(result.clone());
1182                v.push(cond.clone());
1183                v.extend(body.iter().cloned());
1184                v
1185            }
1186            Node::Discard | Node::Break | Node::Continue => vec![],
1187            Node::TextureStore { coord, value, .. } => vec![coord.clone(), value.clone()],
1188            Node::TextureSize { level, .. } => vec![level.clone()],
1189            Node::VaryingProperty { .. } => vec![],
1190            Node::Return { value } => vec![value.clone()],
1191            Node::Not { node } | Node::BitNot { node, .. } => vec![node.clone()],
1192            Node::StructMember { .. } | Node::Workgroup(_) | Node::Barrier { .. } => vec![],
1193            // `Node.analyze()` over `nodeProperties`: what `setup` returned.
1194            Node::Custom(custom) => {
1195                let custom = custom.clone();
1196                vec![self.custom_output(node, &custom)]
1197            }
1198            Node::Context { node, .. } | Node::Isolate { node } | Node::Debug { node, .. } => {
1199                vec![node.clone()]
1200            }
1201            Node::Expression { .. } => vec![],
1202            Node::StructNew { values, .. } => values.clone(),
1203            Node::OutputStruct { members } => members.clone(),
1204            Node::StructGet { value, .. } => vec![value.clone()],
1205            Node::Atomic { pointer, value, .. } => {
1206                let mut v = vec![pointer.clone()];
1207                v.extend(value.iter().cloned());
1208                v
1209            }
1210            Node::Subgroup { a, b, .. } => a.iter().chain(b.iter()).cloned().collect(),
1211        }
1212    }
1213
1214    fn call_body(&mut self, node: &NodeRef, def: &Rc<FnDef>, args: &[NodeRef]) -> NodeRef {
1215        let def = def.clone();
1216        self.output_of(node, |_| (def.body)(args))
1217    }
1218
1219    /// [`CustomNode::setup`], once per node per data cache.
1220    fn custom_output(&mut self, node: &NodeRef, custom: &Rc<dyn CustomNode>) -> NodeRef {
1221        let custom = custom.clone();
1222        self.add_update_node(UpdateNode::with_reference(
1223            Rc::as_ptr(&custom) as *const u8 as usize,
1224            Rc::new(crate::nodes::node::CustomUpdate(custom.clone())),
1225        ));
1226        self.output_of(node, |builder| custom.setup(builder))
1227    }
1228
1229    /// `NodeBuilder.addNode()`'s update half: `node` joins each list whose
1230    /// type is not `NONE`, once.
1231    fn add_update_node(&mut self, entry: UpdateNode) {
1232        let types = [
1233            entry.node.update_before_type(),
1234            entry.node.update_type(),
1235            entry.node.update_after_type(),
1236        ];
1237        for (list, ty) in self.update_nodes.iter_mut().zip(types) {
1238            if ty != NodeUpdateType::None && !list.iter().any(|e| e.reference == entry.reference) {
1239                list.push(entry.clone());
1240            }
1241        }
1242    }
1243
1244    /// `nodeProperties.outputNode`: the one found up the data-cache chain,
1245    /// else `setup`'s, stored in the current cache.
1246    fn output_of(&mut self, node: &NodeRef, setup: impl FnOnce(&Self) -> NodeRef) -> NodeRef {
1247        let key = node.key();
1248        if let Some(cache) = self.data_owner(|b, id| b.outputs.contains_key(&(id, key))) {
1249            return self.outputs[&(cache, key)].1.clone();
1250        }
1251        let output = setup(self);
1252        self.outputs
1253            .insert((self.data_cache, key), (node.clone(), output.clone()));
1254        output
1255    }
1256
1257    // -- flow ------------------------------------------------------------
1258
1259    fn emit(&mut self, line: String) {
1260        // three.js' `addLineFlowCode()` indents nothing when there is nothing to
1261        // indent, so a blank separator line in its output is empty, not a tab.
1262        if line.is_empty() {
1263            if let Some(scope) = self.fn_scopes.last_mut() {
1264                scope.lines.push(String::new());
1265            } else {
1266                self.stages[self.stage.index()].lines.push(String::new());
1267            }
1268            return;
1269        }
1270        if let Some(scope) = self.fn_scopes.last_mut() {
1271            let tab = "\t".repeat(scope.indent);
1272            scope.lines.push(format!("{tab}{line}"));
1273        } else {
1274            let s = &mut self.stages[self.stage.index()];
1275            let tab = "\t".repeat(s.indent);
1276            s.lines.push(format!("{tab}{line}"));
1277        }
1278    }
1279
1280    /// Open a block scope: one tab deeper, and a child [`NodeCache`].
1281    fn push_scope(&mut self) {
1282        if let Some(scope) = self.fn_scopes.last_mut() {
1283            scope.cache.push_child();
1284            scope.indent += 1;
1285        } else {
1286            let s = &mut self.stages[self.stage.index()];
1287            s.cache.push_child();
1288            s.indent += 1;
1289        }
1290    }
1291
1292    fn pop_scope(&mut self) {
1293        if let Some(scope) = self.fn_scopes.last_mut() {
1294            scope.cache.pop_child();
1295            scope.indent -= 1;
1296        } else {
1297            let s = &mut self.stages[self.stage.index()];
1298            s.cache.pop_child();
1299            s.indent -= 1;
1300        }
1301    }
1302
1303    /// `builder.cache` — the open `fn` body's, else the current stage's.
1304    fn cache(&self) -> &NodeCache {
1305        match self.fn_scopes.last() {
1306            Some(scope) => &scope.cache,
1307            None => &self.stages[self.stage.index()].cache,
1308        }
1309    }
1310
1311    fn cache_mut(&mut self) -> &mut NodeCache {
1312        match self.fn_scopes.last_mut() {
1313            Some(scope) => &mut scope.cache,
1314            None => &mut self.stages[self.stage.index()].cache,
1315        }
1316    }
1317
1318    fn cache_get(&self, key: CacheKey) -> Option<String> {
1319        self.cache().get(&key).cloned()
1320    }
1321
1322    fn cache_put(&mut self, key: CacheKey, snippet: String) {
1323        self.cache_mut().set(key, snippet);
1324    }
1325
1326    /// `NodeBuilder.getVarFromNode()` — declare a `var` and return its name.
1327    fn declare_var(&mut self, name: Option<&str>, ty: Type) -> String {
1328        self.declare_var_typed(name, wgsl::type_name(ty).to_string())
1329    }
1330
1331    /// [`declare_var`](Self::declare_var) for a var whose WGSL type is not one
1332    /// of [`Type`]'s — an `array< T, N >`, which only a literal array var is.
1333    fn declare_var_typed(&mut self, name: Option<&str>, ty: String) -> String {
1334        if let Some(scope) = self.fn_scopes.last_mut() {
1335            let name = match name {
1336                Some(n) => n.to_string(),
1337                None => {
1338                    let n = format!("nodeVar{}", scope.var_counter);
1339                    scope.var_counter += 1;
1340                    n
1341                }
1342            };
1343            scope.locals.push((name.clone(), ty));
1344            return name;
1345        }
1346        let name = match name {
1347            Some(n) => n.to_string(),
1348            None => {
1349                let n = format!("nodeVar{}", self.var_counter);
1350                self.var_counter += 1;
1351                n
1352            }
1353        };
1354        let s = &mut self.stages[self.stage.index()];
1355        if s.declared.insert(name.clone()) {
1356            s.decls.push((name.clone(), ty));
1357        }
1358        name
1359    }
1360
1361    /// The name of a [`Node::VarIntent`]: a `nodeVarN` like
1362    /// [`declare_var`](Self::declare_var)'s, but declared by the statement that
1363    /// assigns it, so neither the stage's `// vars` block nor a function's
1364    /// locals list gets an entry.
1365    fn local_var_name(&mut self, name: Option<&str>) -> String {
1366        if let Some(n) = name {
1367            return n.to_string();
1368        }
1369        let counter = match self.fn_scopes.last_mut() {
1370            Some(scope) => &mut scope.var_counter,
1371            None => &mut self.var_counter,
1372        };
1373        let n = format!("nodeVar{counter}");
1374        *counter += 1;
1375        n
1376    }
1377
1378    /// `NodeBuilder.getVarFromNode()`'s `readOnly` half — the `nodeConstN`
1379    /// counter, which three.js keeps separate from `nodeVarN`.
1380    fn declare_const(&mut self, name: Option<&str>) -> String {
1381        if let Some(n) = name {
1382            return n.to_string();
1383        }
1384        if let Some(scope) = self.fn_scopes.last_mut() {
1385            let n = format!("nodeConst{}", scope.const_counter);
1386            scope.const_counter += 1;
1387            return n;
1388        }
1389        let n = format!("nodeConst{}", self.const_counter);
1390        self.const_counter += 1;
1391        n
1392    }
1393
1394    fn add_code(&mut self, name: &str, src: &str) {
1395        let s = &mut self.stages[self.stage.index()];
1396        if s.code_names.insert(name.to_string()) {
1397            s.codes.push(src.to_string());
1398        }
1399    }
1400
1401    // -- slots -----------------------------------------------------------
1402
1403    #[allow(dead_code)]
1404    fn group(&mut self, group: UniformGroup) -> &mut GroupState {
1405        self.groups.entry(group).or_default()
1406    }
1407
1408    fn uniform_snippet(&mut self, u: &Rc<UniformNode>, key: usize) -> String {
1409        let stage = self.stage;
1410        // `this.name || builder.context.nodeName`, and the context's name is
1411        // consumed whether or not this uniform was new.
1412        let context_name = take_context_node_name();
1413        if let Some(name) = self.uniform_names.get(&key).cloned() {
1414            self.touch_uniform_group(u.group, stage);
1415            return format!("{}.{}", u.group.struct_name(), name);
1416        }
1417
1418        let name = match u.name.get().or(context_name) {
1419            Some(n) => n.to_string(),
1420            None => {
1421                let n = format!("nodeUniform{}", self.uniform_counter);
1422                self.uniform_counter += 1;
1423                n
1424            }
1425        };
1426        self.uniform_names.insert(key, name.clone());
1427
1428        let update = u.source.update_type();
1429        let g = self.groups.entry(u.group).or_default();
1430        if g.uniform_slot.is_none() {
1431            g.uniform_slot = Some(g.bindings.len());
1432            g.bindings.push(BindingDesc::Uniforms {
1433                group: u.group,
1434                members: Vec::new(),
1435                size: 0,
1436                update,
1437                visibility: Visibility::default(),
1438            });
1439        }
1440        let slot = g
1441            .uniform_slot
1442            .expect("three-rs: the uniform slot was filled in just above");
1443        if let BindingDesc::Uniforms {
1444            members,
1445            size,
1446            visibility,
1447            ..
1448        } = &mut g.bindings[slot]
1449        {
1450            // A `bool` has no host-shareable layout, so three declares the
1451            // member with the shared node's input type, `u32`.
1452            let member_ty = if u.ty == Type::Bool { Type::U32 } else { u.ty };
1453            let align = wgsl::align_of(member_ty);
1454            let offset = size.div_ceil(align) * align;
1455            members.push(UniformMember {
1456                name: name.clone(),
1457                source: u.source.clone(),
1458                ty: member_ty,
1459                offset,
1460            });
1461            *size = offset + wgsl::size_of(member_ty);
1462            visibility.add(stage);
1463        }
1464
1465        format!("{}.{}", u.group.struct_name(), name)
1466    }
1467
1468    fn touch_uniform_group(&mut self, group: UniformGroup, stage: Stage) {
1469        let g = self.groups.entry(group).or_default();
1470        if let Some(slot) = g.uniform_slot {
1471            if let BindingDesc::Uniforms { visibility, .. } = &mut g.bindings[slot] {
1472                visibility.add(stage);
1473            }
1474        }
1475    }
1476
1477    fn texture_slots(&mut self, source: &Rc<TextureSource>) -> (String, TextureKind) {
1478        let stage = self.stage;
1479        let (key, kind) = match &**source {
1480            TextureSource::Texture2D(t) => (
1481                t.id(),
1482                // `WGSLNodeBuilder.isUnfilterable()`: a `NearestFilter` /
1483                // `NearestFilter` colour texture is bound `non-filtering`,
1484                // with no sampler, and read with `textureLoad`.
1485                if t.is_array() {
1486                    // `CompressedArrayTexture` — `getTextureType()`'s
1487                    // `texture_2d_array`, sampled. An unfilterable array
1488                    // (three's `textureLoad` on it) has no page yet.
1489                    assert!(
1490                        !t.is_unfilterable(),
1491                        "three-rs: a NearestFilter array texture is not supported yet"
1492                    );
1493                    TextureKind::Sampled2DArray
1494                } else if t.is_unfilterable() {
1495                    TextureKind::FloatData2D
1496                } else {
1497                    TextureKind::Float2D
1498                },
1499            ),
1500            TextureSource::Depth(t) => (
1501                t.id(),
1502                if t.is_multisample() {
1503                    TextureKind::DepthMultisampled2D
1504                } else {
1505                    TextureKind::Depth2D
1506                },
1507            ),
1508            TextureSource::ShadowMap(t) => (t.id(), TextureKind::DepthCompare2D),
1509            TextureSource::Cube(t) => (t.id(), TextureKind::Cube),
1510            TextureSource::DataArray(t) => (t.id(), TextureKind::Float2DArray),
1511            TextureSource::Data(t) => (
1512                t.id(),
1513                if t.is_uint() {
1514                    TextureKind::Uint2D
1515                } else {
1516                    TextureKind::FloatData2D
1517                },
1518            ),
1519            TextureSource::CubeDepth(t) => (t.id(), TextureKind::DepthCube),
1520            TextureSource::Texture3D(t) => {
1521                // The unfilterable 3D path (`textureLoad` against
1522                // `textureDimensions`) is not ported: no page on the ladder
1523                // samples a `NearestFilter` volume, and a sampler-less
1524                // `textureSampleLevel` would be a compile error, not pixels.
1525                assert!(
1526                    !t.is_unfilterable(),
1527                    "three-rs: texture3D() of an unfilterable (NearestFilter) \
1528                     Data3DTexture is not ported; set LinearFilter on both filters"
1529                );
1530                (t.id(), TextureKind::Float3D)
1531            }
1532            TextureSource::Storage(t, access) => (
1533                t.id(),
1534                TextureKind::Storage {
1535                    format: t.format(),
1536                    access: *access,
1537                    dim3: false,
1538                },
1539            ),
1540            TextureSource::Storage3D(t, access) => (
1541                t.id(),
1542                TextureKind::Storage {
1543                    format: t.format(),
1544                    access: *access,
1545                    dim3: true,
1546                },
1547            ),
1548        };
1549        let key = (key, source.is_storage_binding());
1550
1551        if let Some((name, kind, slots)) = self.texture_names.get(&key).cloned() {
1552            let g = self.groups.entry(UniformGroup::Object).or_default();
1553            for slot in slots {
1554                match &mut g.bindings[slot] {
1555                    BindingDesc::Texture { visibility, .. }
1556                    | BindingDesc::Sampler { visibility, .. } => visibility.add(stage),
1557                    _ => {}
1558                }
1559            }
1560            return (name, kind);
1561        }
1562
1563        let name = format!("nodeUniform{}", self.uniform_counter);
1564        self.uniform_counter += 1;
1565
1566        let mut visibility = Visibility::default();
1567        visibility.add(stage);
1568        let g = self.groups.entry(UniformGroup::Object).or_default();
1569        let mut slots = Vec::new();
1570        if kind.has_sampler() {
1571            slots.push(g.bindings.len());
1572            g.bindings.push(BindingDesc::Sampler {
1573                source: (**source).clone(),
1574                kind,
1575                visibility,
1576            });
1577        }
1578        slots.push(g.bindings.len());
1579        g.bindings.push(BindingDesc::Texture {
1580            source: (**source).clone(),
1581            kind,
1582            visibility,
1583        });
1584        self.texture_names.insert(key, (name.clone(), kind, slots));
1585        (name, kind)
1586    }
1587
1588    /// A depth texture is bound without a sampler (`isUnfilterable()`, read
1589    /// with `textureLoad`), but `textureGather` on it needs one —
1590    /// three's `generateTextureGather()` binds a `non-filtering` sampler
1591    /// next to it. Adds that sampler the first time the texture is
1592    /// gathered, whether or not it was already bound sampler-less.
1593    fn ensure_depth_sampler(&mut self, source: &Rc<TextureSource>) {
1594        let TextureSource::Depth(t) = &**source else {
1595            return;
1596        };
1597        let key = (t.id(), source.is_storage_binding());
1598        let Some((name, kind, mut slots)) = self.texture_names.get(&key).cloned() else {
1599            return;
1600        };
1601        let g = self.groups.entry(UniformGroup::Object).or_default();
1602        if slots
1603            .iter()
1604            .any(|slot| matches!(g.bindings[*slot], BindingDesc::Sampler { .. }))
1605        {
1606            return;
1607        }
1608        let mut visibility = Visibility::default();
1609        visibility.add(self.stage);
1610        slots.push(g.bindings.len());
1611        g.bindings.push(BindingDesc::Sampler {
1612            source: (**source).clone(),
1613            kind,
1614            visibility,
1615        });
1616        self.texture_names.insert(key, (name, kind, slots));
1617    }
1618
1619    /// `generateWrapFunction( texture )`: adds the `tsl_coord_<S>S_<T>T_2d`
1620    /// function for the texture's wrapping pair, and the per-axis polyfill
1621    /// each half of it calls, and returns its name. A depth texture is
1622    /// clamped on both axes, as is every colour texture the `Texture` default
1623    /// leaves alone.
1624    ///
1625    /// Out of line: `generate()`'s frame is what bounds the node depth a
1626    /// debug build can walk (`tests/nodes_mx_library.rs` sits near it).
1627    #[inline(never)]
1628    fn wrap_function(&mut self, texture: &TextureSource) -> String {
1629        let (wrap_s, wrap_t) = match texture {
1630            TextureSource::Texture2D(t) => t.wrapping(),
1631            _ => (
1632                crate::textures::Wrapping::ClampToEdge,
1633                crate::textures::Wrapping::ClampToEdge,
1634            ),
1635        };
1636        let (wrap_fn, includes, code) = wgsl::wrap_function_2d(wrap_s, wrap_t);
1637        for (include, include_code) in includes {
1638            self.add_code(include, include_code);
1639        }
1640        self.add_code(&wrap_fn, &code);
1641        wrap_fn
1642    }
1643
1644    /// `generateTextureGather()` on a depth texture: `textureGather` with
1645    /// the texture's non-filtering sampler, no component, and three's
1646    /// `UnsignedIntType` cast around it. Out of line for the same reason as
1647    /// [`Self::wrap_function`].
1648    #[inline(never)]
1649    fn depth_gather(&mut self, texture: &Rc<TextureSource>, name: &str, suv: &str) -> String {
1650        let int_typed = match &**texture {
1651            TextureSource::Depth(t) => {
1652                t.texture_type() == crate::textures::TextureType::UnsignedInt
1653            }
1654            _ => false,
1655        };
1656        self.ensure_depth_sampler(texture);
1657        let gather = format!("textureGather( {name}, {name}_sampler, {suv})");
1658        if int_typed {
1659            format!("vec4<f32>( {gather} )")
1660        } else {
1661            gather
1662        }
1663    }
1664
1665    fn buffer_snippet(&mut self, buffer: &Rc<BufferNode>) -> String {
1666        let stage = self.stage;
1667        let buffer_id = buffer.id.get();
1668        let (group, fixed_name) = buffer.source.group_and_name();
1669        let g = self.groups.entry(group).or_default();
1670        for b in g.bindings.iter_mut() {
1671            if let BindingDesc::Buffer {
1672                name,
1673                id,
1674                visibility,
1675                ..
1676            } = b
1677            {
1678                if *id == buffer_id {
1679                    visibility.add(stage);
1680                    return name.clone();
1681                }
1682            }
1683        }
1684        let name = match fixed_name {
1685            Some(name) => name.to_string(),
1686            None => {
1687                let name = format!("NodeBuffer_{}", self.buffer_counter);
1688                self.buffer_counter += 1;
1689                name
1690            }
1691        };
1692        let g = self.groups.entry(group).or_default();
1693        let mut visibility = Visibility::default();
1694        visibility.add(stage);
1695        g.bindings.push(BindingDesc::Buffer {
1696            name: name.clone(),
1697            id: buffer_id,
1698            source: buffer.source.clone(),
1699            element_ty: buffer.element_ty,
1700            count: buffer.count,
1701            visibility,
1702        });
1703        name
1704    }
1705
1706    /// `AttributeNode.generate()`'s `hasGeometryAttribute()` miss: three warns
1707    /// `Vertex attribute "name" not found on geometry.` and returns
1708    /// `builder.generateConst( nodeType )` — a typed zero (`vec4` is
1709    /// `( 0, 0, 0, 1 )`, `Vector4`'s default), in either stage, and no slot.
1710    ///
1711    /// The geometry is known when the renderer handed its attributes over
1712    /// (`geometry_attributes` non-empty); a flow built with none — a
1713    /// hand-built program — declares whatever it reads, as before typed
1714    /// attributes (see [`geometry_attribute`](Self::geometry_attribute)).
1715    /// `tangent` also has its own flag, [`MaterialFlow::geometry_has_tangent`].
1716    /// The crate has no logger, so the warning goes to stderr like its others.
1717    /// A helper so the `format!` stays out of `generate`'s frame.
1718    #[inline(never)]
1719    fn missing_attribute(&self, name: &str, ty: Type) -> Option<String> {
1720        let known = !self.geometry_attributes.is_empty();
1721        let missing = (name == "tangent" && !self.geometry_has_tangent)
1722            || (known
1723                && !self
1724                    .geometry_attributes
1725                    .iter()
1726                    .any(|desc| desc.name == name));
1727        if !missing {
1728            return None;
1729        }
1730        eprintln!("three-rs: AttributeNode: Vertex attribute \"{name}\" not found on geometry.");
1731        Some(wgsl::default_constant(ty))
1732    }
1733
1734    /// `AttributeNode.generate()` in the vertex stage: declare the input in
1735    /// the attribute's own type (`getTypeFromAttribute()`) and convert it to
1736    /// the node's with `builder.format()`. An attribute the renderer described
1737    /// no geometry entry for (a hand-built program, whose flow carries no
1738    /// geometry attributes at all — a geometry that lacks the name is
1739    /// [`missing_attribute`](Self::missing_attribute)'s) is declared in the
1740    /// node's type over a 32-bit format of its own, as before typed
1741    /// attributes. A helper rather than inline in `generate`'s match, to keep
1742    /// that frame small (the `nodes_mx_library` stack canary).
1743    #[inline(never)]
1744    fn geometry_attribute(&mut self, name: &'static str, ty: Type) -> String {
1745        let desc = self
1746            .geometry_attributes
1747            .iter()
1748            .find(|desc| desc.name == name);
1749        let (slot_ty, format, geometry) = match desc {
1750            Some(desc) => {
1751                let group = match desc.layout {
1752                    AttributeLayout::Interleaved { buffer, .. } => Some(buffer),
1753                    _ => None,
1754                };
1755                (
1756                    desc.shader_type(),
1757                    desc.vertex_format(),
1758                    GeometrySlot {
1759                        name,
1760                        array_stride: desc.array_stride(),
1761                        offset: desc.offset(),
1762                        instanced: desc.instanced,
1763                        group,
1764                    },
1765                )
1766            }
1767            None => (
1768                ty,
1769                float_vertex_format(ty),
1770                GeometrySlot {
1771                    name,
1772                    array_stride: (ty.components() * 4) as u64,
1773                    offset: 0,
1774                    instanced: false,
1775                    group: None,
1776                },
1777            ),
1778        };
1779        let s = &mut self.stages[Stage::Vertex.index()];
1780        if !s.attributes.iter().any(|slot| slot.name == name) {
1781            s.attributes.push(AttributeSlot {
1782                name: name.to_string(),
1783                ty: slot_ty,
1784                format,
1785                source: AttributeSource::Geometry(geometry),
1786            });
1787        }
1788        wgsl::convert(name, slot_ty, ty)
1789    }
1790
1791    /// `AttributeNode.generate()`: an attribute read in the fragment stage is
1792    /// not an attribute there at all — three.js wraps it in `varying( this )`
1793    /// and the vertex stage writes it through. This is what carries a whole
1794    /// instanced `vec4` into the fragment flow (`varyings.nodeVaryingN =
1795    /// nodeAttributeN`) instead of passing the instance index down and indexing
1796    /// a uniform buffer.
1797    fn attribute_varying(&mut self, node: &NodeRef) -> String {
1798        let varying = match self.attribute_varyings.get(&node.key()) {
1799            Some(varying) => varying.clone(),
1800            None => {
1801                let varying = NodeRef::new(Node::Varying(Rc::new(VaryingDef {
1802                    name: None,
1803                    value: node.clone(),
1804                    ty: node.ty(),
1805                    flat: matches!(node.ty(), Type::U32 | Type::I32),
1806                })));
1807                self.attribute_varyings.insert(node.key(), varying.clone());
1808                varying
1809            }
1810        };
1811        self.generate(&varying)
1812    }
1813
1814    // -- generate --------------------------------------------------------
1815
1816    /// Generate one statement of a flow or a block. `StackNode` is the
1817    /// parent the flow's statements share; [`Node::Atomic`] asks whether it is
1818    /// one, which is `AtomicFunctionNode`'s `parents[ 0 ].isStackNode`.
1819    fn generate_statement(&mut self, stmt: &NodeRef) -> String {
1820        self.statement = Some(stmt.key());
1821        self.generate(stmt)
1822    }
1823
1824    fn usage_of(&self, node: &NodeRef) -> u32 {
1825        let key = node.key();
1826        self.data_owner(|b, id| b.usage.contains_key(&(id, key)))
1827            .map_or(1, |cache| self.usage[&(cache, key)])
1828    }
1829
1830    /// `TempNode.hasDependencies()` — a computed node used more than once gets
1831    /// a var. A texture read always does.
1832    fn needs_var(&self, node: &NodeRef) -> bool {
1833        match node.node() {
1834            Node::Texture { .. } => true,
1835            // `UniformNode.generate()`: a `bool` uniform is a `u32` in the
1836            // buffer, converted once into a var — "cache to variable".
1837            Node::Uniform(u) => u.ty == Type::Bool,
1838            // `negate()` is `MathNode.NEGATE`, so it is shared like any
1839            // other math node (`GodraysNode`'s ray-plane `t`, read three
1840            // times).
1841            Node::Op { .. } | Node::Math { .. } | Node::Neg { .. } | Node::Join { .. } => {
1842                self.usage_of(node) > 1
1843            }
1844            // A call to an `Fn()` with a layout is a real function call, and
1845            // `FunctionCallNode` is a `TempNode`: cached once when shared.
1846            Node::Call { def, .. } if def.layout => self.usage_of(node) > 1,
1847            // `FunctionCallNode` is a `TempNode` whatever it calls.
1848            Node::CodeCall { .. } => self.usage_of(node) > 1,
1849            // `Node.build()`'s `cacheResult`: a cacheable node with a value,
1850            // reached more than once.
1851            Node::Custom(custom) => {
1852                custom.is_cacheable() && custom.node_type() != Type::Void && self.usage_of(node) > 1
1853            }
1854            _ => false,
1855        }
1856    }
1857
1858    pub(crate) fn generate(&mut self, node: &NodeRef) -> String {
1859        if let Some(element) = self.array_camera_element(node) {
1860            return self.generate(&element);
1861        }
1862        // `ComputeNode.generate()` outside the compute stage:
1863        // `outputComputeNode.build( builder, output )`.
1864        if let Node::Compute { output, .. } = node.node() {
1865            let output = output.clone();
1866            return self.generate(&output);
1867        }
1868        if let Some(name) = self.cache_get(CacheKey::node(node)) {
1869            return name;
1870        }
1871
1872        if self.needs_var(node) {
1873            let snippet = self.generate_inner(node);
1874            let name = self.declare_var(None, node.ty());
1875            self.emit(format!("{name} = {snippet};"));
1876            self.cache_put(CacheKey::node(node), name.clone());
1877            return name;
1878        }
1879
1880        self.generate_inner(node)
1881    }
1882
1883    fn format(&mut self, node: &NodeRef, want: Type) -> String {
1884        // `ConstNode.generate()`: a scalar number constant asked for as
1885        // another scalar number type is regenerated as that type's literal
1886        // (`_regNum = /float|u?int/`), so `state.mul( 747796405 )` on a `u32`
1887        // is `747796405u`, not a conversion.
1888        if let Node::Const { ty, values } = node.node() {
1889            let numeric = |t: Type| matches!(t, Type::F32 | Type::I32 | Type::U32);
1890            if numeric(*ty) && numeric(want) {
1891                return wgsl::constant(want, values);
1892            }
1893        }
1894        let snippet = self.generate(node);
1895        wgsl::convert(&snippet, node.ty(), want)
1896    }
1897
1898    /// `AssignNode.needsSplitAssign( builder )`: the root vector and the
1899    /// components, when assigning to this target needs one statement per
1900    /// component rather than a swizzle assign.
1901    ///
1902    /// three.js' test is `targetNode.isSplitNode && components.length > 1 &&
1903    /// 'xyzw'.slice( 0, targetLength ) !== components`; the port's
1904    /// [`swizzle`](crate::nodes::tsl) already collapses a whole-vector swizzle
1905    /// into the node itself, so a surviving multi-component `Swizzle` *is* the
1906    /// different-vector case.
1907    fn split_assign_target(&self, target: &NodeRef) -> Option<(NodeRef, &'static str)> {
1908        match target.node() {
1909            Node::Swizzle {
1910                node, components, ..
1911            } if components.len() > 1 => Some((node.clone(), components)),
1912            _ => None,
1913        }
1914    }
1915
1916    /// `ConditionalNode.generate()` under `builder.context.uniformFlow`, kept
1917    /// out of [`Self::generate_inner`]'s frame (it bounds node depth in debug
1918    /// builds).
1919    ///
1920    /// Three allocates the result property before it reads the context, so
1921    /// the var is declared and never assigned; the condition is built, then
1922    /// both branches, and the value is `getTernary()`: `select( else, if,
1923    /// cond )`, unconditionally evaluating both. Three leaves a second read to
1924    /// `Node.build()`'s `cacheResult`, a `let` holding the `select`; the port
1925    /// holds it in a var (`docs/nodes.md` §8).
1926    #[inline(never)]
1927    fn generate_uniform_flow_select(&mut self, node: &NodeRef) -> String {
1928        let Node::Select { cond, a, b, ty } = node.node() else {
1929            unreachable!()
1930        };
1931        let (cond, a, b, ty) = (cond.clone(), a.clone(), b.clone(), *ty);
1932        self.declare_var(None, ty);
1933        let scond = self.generate(&cond);
1934        let sa = self.format(&a, ty);
1935        let sb = self.format(&b, ty);
1936        let select = format!("select( {sb}, {sa}, {scond} )");
1937        if self.usage_of(node) > 1 {
1938            let name = self.declare_var(None, ty);
1939            self.emit(format!("{name} = {select};"));
1940            self.cache_put(CacheKey::node(node), name.clone());
1941            return name;
1942        }
1943        select
1944    }
1945
1946    /// `ExpressionNode.generate()`: a value is the snippet itself; `void` is
1947    /// `addLineFlowCode( snippet )`, which ends the line with a `;` unless it
1948    /// already has one.
1949    #[inline(never)]
1950    fn generate_expression(&mut self, node: &NodeRef) -> String {
1951        let Node::Expression { snippet, ty } = node.node() else {
1952            unreachable!()
1953        };
1954        let (snippet, ty) = (snippet.clone(), *ty);
1955        if ty != Type::Void {
1956            return snippet.to_string();
1957        }
1958        // `addLineFlowCode( '' )` adds nothing.
1959        if snippet.is_empty() {
1960            return String::new();
1961        }
1962        let line = if snippet.trim_end().ends_with(';') {
1963            snippet.to_string()
1964        } else {
1965            format!("{snippet};")
1966        };
1967        self.emit(line);
1968        String::new()
1969    }
1970
1971    /// `DebugNode.generate()`: `node`'s snippet, handed to the callback, or
1972    /// with no callback logged after the flow so far in three's format. The
1973    /// snippet is kept like any generate-once node's, so a second read in the
1974    /// same scope neither calls the callback nor logs again.
1975    #[inline(never)]
1976    fn generate_debug(&mut self, node: &NodeRef) -> String {
1977        let Node::Debug {
1978            node: inner,
1979            callback,
1980        } = node.node()
1981        else {
1982            unreachable!()
1983        };
1984        let (inner, callback) = (inner.clone(), callback.clone());
1985        let snippet = self.generate(&inner);
1986        let stage = match self.stage {
1987            Stage::Vertex => "vertex",
1988            Stage::Fragment => "fragment",
1989            Stage::Compute => "compute",
1990        };
1991        let lines = match self.fn_scopes.last() {
1992            Some(scope) => &scope.lines,
1993            None => &self.stages[self.stage.index()].lines,
1994        };
1995        let flow = lines
1996            .iter()
1997            .map(|l| l.strip_prefix('\t').unwrap_or(l))
1998            .collect::<Vec<_>>()
1999            .join("\n");
2000        let info = crate::nodes::node::DebugInfo {
2001            stage,
2002            flow: &flow,
2003            snippet: &snippet,
2004        };
2005        match callback {
2006            Some(callback) => (callback.0)(&info),
2007            None => {
2008                let title = format!("--- TSL debug - {stage} shader ---");
2009                let border = "-".repeat(title.len());
2010                eprintln!("// #{title}#\n{flow}\n/* ... */ {snippet} /* ... */\n// #{border}#");
2011            }
2012        }
2013        self.cache_put(CacheKey::node(node), snippet.clone());
2014        snippet
2015    }
2016
2017    /// The packing builtins, kept out of [`Self::generate_inner`]'s frame (it
2018    /// bounds node depth in debug builds).
2019    ///
2020    /// - `PackFloatNode` / `UnpackFloatNode`: `` `${ method }(${ snippet })` ``,
2021    ///   the operand at its own type and no padding inside the parentheses.
2022    /// - `Packed4x8IntegerNode`: `` `${ method }( ${ params } )` ``, each
2023    ///   operand built at `getInputType()` — `ivec4` for `pack4xI8[Clamp]`,
2024    ///   `uvec4` for `pack4xU8[Clamp]`, `uint` for the rest.
2025    #[inline(never)]
2026    fn generate_packing(&mut self, name: &str, args: &[NodeRef]) -> Option<String> {
2027        let input = match name {
2028            "pack2x16snorm" | "pack2x16unorm" | "pack2x16float" | "pack4x8snorm"
2029            | "pack4x8unorm" | "unpack2x16snorm" | "unpack2x16unorm" | "unpack2x16float"
2030            | "unpack4x8snorm" | "unpack4x8unorm" => {
2031                let snippet = self.generate(&args[0]);
2032                return Some(format!("{name}({snippet})"));
2033            }
2034            "pack4xI8" | "pack4xI8Clamp" => Type::IVec4,
2035            "pack4xU8" | "pack4xU8Clamp" => Type::UVec4,
2036            "unpack4xI8" | "unpack4xU8" | "dot4U8Packed" | "dot4I8Packed" => Type::U32,
2037            _ => return None,
2038        };
2039        let parts: Vec<String> = args.iter().map(|a| self.format(a, input)).collect();
2040        Some(format!("{name}( {} )", parts.join(", ")))
2041    }
2042
2043    /// A builtin read in a compute kernel, kept out of
2044    /// [`Self::generate_inner`]'s frame.
2045    ///
2046    /// `instanceIndex` is the module-scope `var<private>` the entry point
2047    /// fills from `globalId`, not a parameter — `WGSLNodeBuilder.getBuiltins(
2048    /// 'compute' )` never lists it. `invocationLocalIndex`,
2049    /// `invocationSubgroupIndex` and `subgroupIndex` are `IndexNode`s, whose
2050    /// `getBuiltin()` registers the parameter when the flow reads them, so
2051    /// they are declared in that order before the four fixed ones.
2052    /// `subgroupSize` is a `ComputeBuiltinNode` that only writes its name; the
2053    /// parameter is the one `getAttributes( 'compute' )` appends last.
2054    #[inline(never)]
2055    fn generate_compute_builtin(&mut self, b: Builtin) -> String {
2056        let s = &mut self.stages[Stage::Compute.index()];
2057        if matches!(
2058            b,
2059            Builtin::InvocationLocalIndex
2060                | Builtin::InvocationSubgroupIndex
2061                | Builtin::SubgroupIndex
2062        ) && !s.builtins.contains(&b)
2063        {
2064            s.builtins.push(b);
2065        }
2066        // `getSubgroupIndex()` / `getInvocationSubgroupIndex()` call
2067        // `enableSubGroups()`; three's `subgroupSize` relies on
2068        // `getAttributes()` having enabled them for every kernel.
2069        if matches!(
2070            b,
2071            Builtin::SubgroupSize | Builtin::InvocationSubgroupIndex | Builtin::SubgroupIndex
2072        ) {
2073            s.subgroups = true;
2074        }
2075        b.name().to_string()
2076    }
2077
2078    /// `SubgroupFunctionNode.setup()` and `.generate()`
2079    /// (`src/nodes/gpgpu/SubgroupFunctionNode.js`).
2080    ///
2081    /// `setup()` enables `subgroups` in the stage that builds the node. The
2082    /// parameters are built as three builds them: `subgroupBroadcast`,
2083    /// `subgroupShuffle` and `quadBroadcast` take `a` at the node's type and
2084    /// `b` as an `int` when it is a `float` (a lane id given as a JS number)
2085    /// and at the node's type otherwise; the shuffles by mask or delta take `b`
2086    /// as a `uint`; the rest take both at `getInputType()`. The call is
2087    /// `` `${ method }( ${ params } )` ``, or `subgroupElect()`.
2088    #[inline(never)]
2089    fn generate_subgroup(&mut self, node: &NodeRef) -> String {
2090        let Node::Subgroup { method, a, b } = node.node() else {
2091            unreachable!()
2092        };
2093        let (method, a, b) = (*method, a.clone(), b.clone());
2094        assert_ne!(
2095            self.stage,
2096            Stage::Vertex,
2097            "three-rs: TSL: \"{method}\" is not supported in the vertex shader stage."
2098        );
2099        self.stages[self.stage.index()].subgroups = true;
2100        let ty = node.ty();
2101        let input = crate::nodes::node::subgroup_input_type(a.as_ref(), b.as_ref());
2102        let mut params: Vec<String> = Vec::new();
2103        match method {
2104            "subgroupBroadcast" | "subgroupShuffle" | "quadBroadcast" => {
2105                let (a, b) = (
2106                    a.expect("three-rs: a subgroup function's first input"),
2107                    b.unwrap_or_else(|| panic!("three-rs: {method}() takes a lane id")),
2108                );
2109                params.push(self.format(&a, ty));
2110                let b_ty = if b.ty() == Type::F32 { Type::I32 } else { ty };
2111                params.push(self.format(&b, b_ty));
2112            }
2113            "subgroupShuffleXor" | "subgroupShuffleDown" | "subgroupShuffleUp" => {
2114                let (a, b) = (
2115                    a.expect("three-rs: a subgroup function's first input"),
2116                    b.unwrap_or_else(|| panic!("three-rs: {method}() takes a mask or delta")),
2117                );
2118                params.push(self.format(&a, ty));
2119                params.push(self.format(&b, Type::U32));
2120            }
2121            _ => {
2122                if let Some(a) = &a {
2123                    params.push(self.format(a, input));
2124                }
2125                if let Some(b) = &b {
2126                    params.push(self.format(b, input));
2127                }
2128            }
2129        }
2130        if params.is_empty() {
2131            format!("{method}()")
2132        } else {
2133            format!("{method}( {} )", params.join(", "))
2134        }
2135    }
2136
2137    #[inline(never)]
2138    fn generate_texture(&mut self, node: &NodeRef) -> String {
2139        let Node::Texture {
2140            texture, uv, mode, ..
2141        } = node.node()
2142        else {
2143            unreachable!()
2144        };
2145        let (texture, uv, mode) = (texture.clone(), uv.clone(), mode.clone());
2146        let mode_is_color = matches!(
2147            mode,
2148            SampleMode::Sample
2149                | SampleMode::Grad(..)
2150                | SampleMode::Level(_)
2151                | SampleMode::Bias(_)
2152                | SampleMode::Load
2153        ) && matches!(*texture, TextureSource::Texture2D(_));
2154        let (name, kind) = self.texture_slots(&texture);
2155        let suv = self.generate(&uv);
2156        // `TextureNode.generate()` builds the snippet as a `vec4` and
2157        // `format()`s it to the node type: an RG map's `vec2` node
2158        // gets `.xy` on the fetch itself, a red map's `float` `.x`.
2159        let narrow = |s: String| match node.ty() {
2160            Type::Vec2 => format!("{s}.xy"),
2161            Type::F32 => format!("{s}.x"),
2162            _ => s,
2163        };
2164        let snippet = match mode {
2165            // `_generateTextureSample()`: outside the fragment stage
2166            // there are no implicit derivatives, so a plain sample is
2167            // `generateTextureSampleLevel()` at a literal level `0`.
2168            SampleMode::Sample if self.stage != Stage::Fragment => {
2169                format!("textureSampleLevel( {name}, {name}_sampler, {suv}, 0 )")
2170            }
2171            SampleMode::Sample => {
2172                format!("textureSample( {name}, {name}_sampler, {suv} )")
2173            }
2174            SampleMode::Grad(grad_x, grad_y) => {
2175                let sx = self.format(&grad_x, Type::Vec2);
2176                let sy = self.format(&grad_y, Type::Vec2);
2177                format!("textureSampleGrad( {name}, {name}_sampler, {suv}, {sx}, {sy} )")
2178            }
2179            // `generateTextureGather()`, with three's spacing: no
2180            // space before the closing parenthesis without an offset.
2181            // A depth texture has one channel, so WGSL's
2182            // `textureGather` takes no component, and three's
2183            // `UnsignedIntType` cast wraps it (see `GatherCompare`).
2184            SampleMode::Gather { .. } if matches!(*texture, TextureSource::Depth(_)) => {
2185                self.depth_gather(&texture, &name, &suv)
2186            }
2187            SampleMode::Gather { component, offset } => {
2188                let scomponent = self.format(&component, Type::I32);
2189                match offset {
2190                    Some(offset) => {
2191                        let soffset = self.format(&offset, Type::IVec2);
2192                        format!(
2193                            "textureGather( {scomponent}, {name}, {name}_sampler, {suv}, {soffset} )"
2194                        )
2195                    }
2196                    None => format!("textureGather( {scomponent}, {name}, {name}_sampler, {suv})"),
2197                }
2198            }
2199            // `generateTextureGatherCompare()`, the same spacing.
2200            //
2201            // Quirk kept: `TextureNode.generate()` types a gather's
2202            // snippet from `texture.type`, and a `DepthTexture` is
2203            // `UnsignedIntType` by default, so three takes the result
2204            // for a `uvec4` and formats it to the node's `vec4` —
2205            // `vec4<f32>( textureGatherCompare( … ) )`, a no-op cast
2206            // in WGSL (`docs/nodes.md` §44).
2207            SampleMode::GatherCompare { compare, offset } => {
2208                let int_typed = match &*texture {
2209                    TextureSource::Depth(t) | TextureSource::ShadowMap(t) => {
2210                        t.texture_type() == crate::textures::TextureType::UnsignedInt
2211                    }
2212                    _ => false,
2213                };
2214                let scompare = self.format(&compare, Type::F32);
2215                let gather = match offset {
2216                    Some(offset) => {
2217                        let soffset = self.format(&offset, Type::IVec2);
2218                        format!(
2219                            "textureGatherCompare( {name}, {name}_sampler, {suv}, {scompare}, {soffset} )"
2220                        )
2221                    }
2222                    None => {
2223                        format!("textureGatherCompare( {name}, {name}_sampler, {suv}, {scompare})")
2224                    }
2225                };
2226                if int_typed {
2227                    format!("vec4<f32>( {gather} )")
2228                } else {
2229                    gather
2230                }
2231            }
2232            // `texture3D( … ).sample( uv ).r`: the texture node is
2233            // built as a `float`, so the fetch itself is narrowed and
2234            // the node's var is an `f32` — three's
2235            // `nodeVar7 = textureSampleLevel( … ).x`.
2236            // `generateTextureLevel()` on an unfilterable map is
2237            // `generateTextureLod()`: a `textureLoad` at the level, not a
2238            // `textureSampleLevel` through a sampler the map has none of.
2239            SampleMode::Level(level)
2240                if kind == TextureKind::FloatData2D
2241                    && matches!(*texture, TextureSource::Texture2D(_)) =>
2242            {
2243                self.generate_texture_lod(&texture, &name, kind, &suv, &level)
2244            }
2245            SampleMode::Level(level) if node.ty().components() == 1 => {
2246                let slevel = self.generate(&level);
2247                format!("textureSampleLevel( {name}, {name}_sampler, {suv}, {slevel} ).x")
2248            }
2249            SampleMode::Level(level) => {
2250                let slevel = self.generate(&level);
2251                format!("textureSampleLevel( {name}, {name}_sampler, {suv}, {slevel} )")
2252            }
2253            SampleMode::Bias(bias) => {
2254                let sbias = self.generate(&bias);
2255                format!("textureSampleBias( {name}, {name}_sampler, {suv}, {sbias} )")
2256            }
2257            SampleMode::LoadLayer(layer) => {
2258                let slayer = self.generate(&layer);
2259                wgsl::texture_load_layer(&name, &suv, &slayer)
2260            }
2261            SampleMode::SampleLayer(layer) => {
2262                let slayer = self.generate(&layer);
2263                // `depthNode.build( builder, 'int' )`: a float layer
2264                // is cast, an int one passes through.
2265                let slayer = if layer.ty() == Type::I32 {
2266                    slayer
2267                } else {
2268                    format!("i32( {slayer} )")
2269                };
2270                format!("textureSample( {name}, {name}_sampler, {suv}, {slayer} )")
2271            }
2272            SampleMode::Compare(depth) => {
2273                let sdepth = self.generate(&depth);
2274                format!("textureSampleCompare( {name}, {name}_sampler, {suv}, {sdepth} )")
2275            }
2276            // A depth texture's `textureLoad` is already the `f32`:
2277            // `TAAUtils.sampleCurrentDepth()`'s `depthNode.load(
2278            // neighbor ).r` is three's bare
2279            // `textureLoad( depth, vec2<i32>( n ), u32( 0u ) )`.
2280            SampleMode::LoadTexel if matches!(*texture, TextureSource::Depth(_)) => {
2281                wgsl::texture_load_texel(&name, &suv)
2282            }
2283            SampleMode::LoadTexel => {
2284                let snippet = wgsl::texture_load_texel(&name, &suv);
2285                // `textureLoad( t, coord ).x` on the `r32uint`
2286                // indirect table: Three splits the `uvec4` and caches
2287                // the scalar, so the swizzle rides along with the
2288                // fetch rather than becoming a second property.
2289                if node.ty().components() == 1 {
2290                    format!("{snippet}.x")
2291                } else {
2292                    snippet
2293                }
2294            }
2295            SampleMode::Load => {
2296                // `generateWrapFunction( texture )`: one
2297                // `tsl_coord_<S>S_<T>T_2d` per wrapping pair, each
2298                // built from a per-axis polyfill. A depth texture is
2299                // clamped on both axes, as is every colour texture
2300                // the `Texture` default leaves alone.
2301                let wrap_fn = self.wrap_function(&texture);
2302                // `WGSLNodeBuilder.generateTextureDimension()` keeps
2303                // one dimensions var per texture in `builder.cache`,
2304                // so a second tap in the same scope (or one nested in
2305                // it) reuses it, and a sibling `if` declares its own.
2306                let dims_key = CacheKey::TextureDimensions(name.clone(), "0".to_string());
2307                let dims = match self.cache_get(dims_key.clone()) {
2308                    Some(dims) => dims,
2309                    None => {
2310                        let dims = self.declare_var(None, Type::UVec2);
2311                        let dims_expr = wgsl::texture_dimensions(&name, kind);
2312                        self.emit(format!("{dims} = {dims_expr};"));
2313                        self.cache_put(dims_key, dims.clone());
2314                        dims
2315                    }
2316                };
2317                wgsl::texture_load(&name, &wrap_fn, &suv, &dims)
2318            }
2319            // `generateStorageTextureLoad()`: no level argument.
2320            SampleMode::StorageLoad => {
2321                let snippet = format!("textureLoad( {name}, {suv} )");
2322                if node.ty().components() == 1 {
2323                    format!("{snippet}.x")
2324                } else {
2325                    snippet
2326                }
2327            }
2328        };
2329        if mode_is_color {
2330            narrow(snippet)
2331        } else {
2332            snippet
2333        }
2334    }
2335
2336    /// `WGSLNodeBuilder.generateTextureLod()` with a level snippet — a
2337    /// `.level( n )` tap of an unfilterable 2-D map: the wrapped, clamped
2338    /// texel fetch [`SampleMode::Load`] emits, but with `u32( level )` in
2339    /// both the `textureDimensions` (cached per texture *and* level, as
2340    /// three's `dimensionsSnippet[ levelSnippet ]` is) and the `textureLoad`.
2341    /// `ImportanceSampledEnvironment`'s `texture( map, uv ).level( 0 )` on a
2342    /// `NearestFilter` `DataTexture` is the caller.
2343    #[inline(never)]
2344    fn generate_texture_lod(
2345        &mut self,
2346        texture: &Rc<TextureSource>,
2347        name: &str,
2348        kind: TextureKind,
2349        suv: &str,
2350        level: &NodeRef,
2351    ) -> String {
2352        let slevel = self.generate(level);
2353        let wrap_fn = self.wrap_function(texture);
2354        let dims_key = CacheKey::TextureDimensions(name.to_string(), slevel.clone());
2355        let dims = match self.cache_get(dims_key.clone()) {
2356            Some(dims) => dims,
2357            None => {
2358                let dims = self.declare_var(None, Type::UVec2);
2359                let dims_expr = wgsl::texture_dimensions_level(name, kind, &slevel);
2360                self.emit(format!("{dims} = {dims_expr};"));
2361                self.cache_put(dims_key, dims.clone());
2362                dims
2363            }
2364        };
2365        wgsl::texture_load_level(name, &wrap_fn, suv, &dims, &slevel)
2366    }
2367
2368    #[inline(never)]
2369    fn generate_varying(&mut self, node: &NodeRef) -> String {
2370        let Node::Varying(v) = node.node() else {
2371            unreachable!()
2372        };
2373        let v = v.clone();
2374        if let Some(name) = self.varying_slots.get(&node.key()).cloned() {
2375            // A varying is read through the `varyings` struct in the
2376            // vertex stage and as a `main` parameter in the fragment
2377            // stage — `NodeBuilder.getPropertyName()`'s two cases.
2378            return match self.stage {
2379                Stage::Vertex => format!("varyings.{name}"),
2380                Stage::Fragment => name,
2381                Stage::Compute => unreachable!("three-rs: compute has no varyings"),
2382            };
2383        }
2384        match self.stage {
2385            Stage::Compute => unreachable!("three-rs: compute has no varyings"),
2386            Stage::Vertex => {
2387                // Not requested by the fragment stage: a plain private
2388                // var in the vertex shader, which is exactly what
2389                // three.js emits for `v_normalViewGeometry` on the
2390                // background material.
2391                let snippet = self.generate(&v.value);
2392                let name = self.declare_var(v.name, v.ty);
2393                self.emit(format!("{name} = {snippet};"));
2394                self.cache_put(CacheKey::node(node), name.clone());
2395                name
2396            }
2397            Stage::Fragment => {
2398                let name = match v.name {
2399                    Some(n) => n.to_string(),
2400                    None => {
2401                        let n = format!("nodeVarying{}", self.varying_counter);
2402                        self.varying_counter += 1;
2403                        n
2404                    }
2405                };
2406                self.varyings.push((name.clone(), v.ty, v.flat));
2407                self.varying_slots.insert(node.key(), name.clone());
2408                // The vertex-side chain is flowed into the vertex stage
2409                // at the point the fragment stage asks for it.
2410                //
2411                // When the vertex stage already holds it as a private
2412                // var — `positionLocal` read, and reassigned, by the
2413                // `context.position` statements flowed before either
2414                // stage (`material.positionNode`, instancing,
2415                // skinning) — the varying carries that var's current
2416                // value. In three.js the varying *is* the variable
2417                // (`varyings.positionLocal = ( varyings.positionLocal
2418                // + … )`), so the fragment stage sees the reassigned
2419                // value, not the attribute; see `docs/nodes.md` §8.
2420                self.stage = Stage::Vertex;
2421                // Three's vertex stage writes every assignment to a
2422                // varying straight into `varyings.name`, so what
2423                // reaches the fragment stage is the last value
2424                // assigned (`webgpu_particles`' `positionLocal`, moved
2425                // by its `positionNode`). The port's vertex stage
2426                // holds that value in the private var until now.
2427                let reassigned = self.reassigned_varyings.contains(&node.key());
2428                let snippet = match self.cache_get(CacheKey::node(node)) {
2429                    Some(var) if reassigned => var,
2430                    _ => self.generate(&v.value),
2431                };
2432                self.emit(format!("varyings.{name} = {snippet};"));
2433                self.stage = Stage::Fragment;
2434                name
2435            }
2436        }
2437    }
2438
2439    #[inline(never)]
2440    fn generate_loop(&mut self, node: &NodeRef) -> String {
2441        let Node::Loop {
2442            start,
2443            count,
2444            index,
2445            condition,
2446            update,
2447            body,
2448        } = node.node()
2449        else {
2450            unreachable!()
2451        };
2452        let (start, count, index, condition, update, body) = (
2453            start.clone(),
2454            count.clone(),
2455            index.clone(),
2456            *condition,
2457            update.clone(),
2458            body.clone(),
2459        );
2460        // The start is generated before the end, which is the order
2461        // three.js' `LoopNode` builds them in and so the order their
2462        // vars and uniforms are numbered in.
2463        let index_ty = index.ty();
2464        let sstart = match &start {
2465            Some(start) => self.loop_bound(start, index_ty),
2466            None => wgsl::constant(index_ty, &[0.0]),
2467        };
2468        let scount = self.loop_bound(&count, index_ty);
2469        let name = match index.node() {
2470            Node::Param { name, .. } => *name,
2471            _ => "i",
2472        };
2473        let ty = wgsl::type_name(index_ty);
2474        // `LoopNode.generate()`'s default update: `++` / `--` for an
2475        // integer index, `+= 1.` / `-= 1.` for anything else.
2476        let rising = condition.contains('<');
2477        let default_update = match (index_ty, rising) {
2478            (Type::I32 | Type::U32, true) => "++",
2479            (Type::I32 | Type::U32, false) => "--",
2480            (_, true) => "+= 1.",
2481            (_, false) => "-= 1.",
2482        };
2483        // `Loop( { update } )` — `i += update` in place of the
2484        // default, `RaymarchingBox`'s float march.
2485        let step = match &update {
2486            Some(update) => format!("{name} += {}", self.generate(update)),
2487            None => format!("{name} {default_update}"),
2488        };
2489        self.emit(String::new());
2490        self.emit(format!(
2491            "for ( var {name} : {ty} = {sstart}; {name} {condition} {scount}; {step} ) {{"
2492        ));
2493        self.emit(String::new());
2494        self.push_scope();
2495        for stmt in &body {
2496            self.generate_statement(stmt);
2497        }
2498        self.pop_scope();
2499        self.emit(String::new());
2500        self.emit("}".to_string());
2501        self.emit(String::new());
2502        String::new()
2503    }
2504
2505    #[inline(never)]
2506    fn generate_math(&mut self, node: &NodeRef) -> String {
2507        let Node::Math { name, args, ty } = node.node() else {
2508            unreachable!()
2509        };
2510        if let Some(snippet) = self.generate_packing(name, args) {
2511            return snippet;
2512        }
2513        let (name, args, ty) = (*name, args.clone(), *ty);
2514        // `WGSLNodeBuilder`'s `wgslPolyfill` table: a method that
2515        // lowers to a `tsl_*` helper brings the helper's code with it.
2516        if let Some(snippet) = wgsl::polyfill(name) {
2517            self.add_code(name, snippet);
2518        }
2519        // `mix`'s interpolant and `cross`/`reflect`'s operands keep
2520        // their own types; everything else is widened to the result
2521        // type, as `MathNode.generate()` does.
2522        // `MathNode.getInputType()`: a method whose result is narrower
2523        // than its operands widens its operands to the wider *operand*,
2524        // not to the result type. `distance` returns an `f32` from two
2525        // vectors, so `format( a, ty )` would swizzle them down; `dot`
2526        // is the same, and `luminance( vec4 )` is the case that makes
2527        // it load-bearing (`webgpu_postprocessing_difference`): three
2528        // widens the `vec3` coefficients to `vec4( vec3( … ), 1.0 )`,
2529        // so the alpha difference is weighted 1.0 and not dropped.
2530        let input_ty = args
2531            .iter()
2532            .map(|a| a.ty())
2533            .max_by_key(|t| t.components())
2534            .unwrap_or(ty);
2535        let parts: Vec<String> = args
2536            .iter()
2537            .enumerate()
2538            .map(|(i, a)| match name {
2539                "distance" => self.format(a, input_ty),
2540                "mix" if i == 2 => self.generate(a),
2541                // `MathNode.REFRACT`: I and N take the input type, eta
2542                // is built as a `float`.
2543                "refract" if i == 2 => self.format(a, Type::F32),
2544                "refract" => self.format(a, input_ty),
2545                "dot" => self.format(a, input_ty),
2546                "cross" | "reflect" | "normalize" | "transpose" | "tsl_inverse_mat2"
2547                | "tsl_inverse_mat3" | "tsl_inverse_mat4" | "determinant" | "length" | "dpdx"
2548                | "- dpdy" | "inverseSqrt" | "all" | "any" => self.generate(a),
2549                // `select( f, t, cond )`'s condition is a bool, and the
2550                // MaterialX helpers pass their own already-typed
2551                // operands; nothing here is widened.
2552                "select" | "fract" | "sqrt" | "abs" => self.generate(a),
2553                // `MathNode.generate()` builds both of `step`'s
2554                // operands at the input type, so a scalar edge
2555                // widens: `step( vec3<f32>( 0.5 ), base )` in
2556                // `blendOverlay` — WGSL has no mixed overload.
2557                "step" => self.format(a, input_ty),
2558                // `BitcastNode` builds its operand as it stands; the
2559                // result type is the cast's, not the input's.
2560                n if n.starts_with("bitcast<") => self.generate(a),
2561                _ => self.format(a, ty),
2562            })
2563            .collect();
2564        format!("{name}( {} )", parts.join(", "))
2565    }
2566
2567    #[inline(never)]
2568    fn generate_op(&mut self, node: &NodeRef) -> String {
2569        let Node::Op { op, a, b, ty } = node.node() else {
2570            unreachable!()
2571        };
2572        let (op, a, b, ty) = (*op, a.clone(), b.clone(), *ty);
2573        // A comparison's operands are formatted to the wider
2574        // *operand* type (`OperatorNode.getNodeType()`'s
2575        // `typeA`/`typeB`), not to its `bool` result; the component
2576        // type is the operand's, so a `u32` comparison stays `u32`.
2577        let want = if ty.component_type() == Type::Bool {
2578            let (ta, tb) = (a.ty(), b.ty());
2579            if ta.components() > 1 {
2580                ta
2581            } else if tb.components() > 1 {
2582                tb
2583            } else if ta != tb {
2584                Type::F32
2585            } else {
2586                ta
2587            }
2588        } else {
2589            ty
2590        };
2591        // `OperatorNode.generate()`'s two matrix-and-scalar arms
2592        // (`OperatorNode.js:360`). A matrix times a float is emitted
2593        // with the *float first* — `( skinWeight.x * boneMat )`, not
2594        // `( boneMat * skinWeight.x )` — and a float times a matrix is
2595        // emitted with no enclosing parens at all. Neither operand is
2596        // widened to the result type in either case. Both quirks are
2597        // visible in Three's skinning dump, which multiplies the same
2598        // pair both ways round in the two statements it emits.
2599        if a.ty().is_matrix() && b.ty() == Type::F32 {
2600            let sa = self.generate(&a);
2601            let sb = self.generate(&b);
2602            format!("( {sb} {op} {sa} )")
2603        } else if a.ty() == Type::F32 && b.ty().is_matrix() {
2604            let sa = self.generate(&a);
2605            let sb = self.generate(&b);
2606            format!("{sa} {op} {sb}")
2607        } else if op == ">>" || op == "<<" {
2608            // `OperatorNode`: a shift's amount is `changeComponentType(
2609            // typeB, 'uint' )`, the value is the result type.
2610            let sa = self.format(&a, want);
2611            let amount = Type::vector_of(Type::U32, b.ty().components().max(1));
2612            let sb = self.format(&b, amount);
2613            format!("( {sa} {op} {sb} )")
2614        } else {
2615            let sa = if a.ty().is_matrix() {
2616                self.generate(&a)
2617            } else {
2618                self.format(&a, want)
2619            };
2620            let sb = if b.ty().is_matrix() {
2621                self.generate(&b)
2622            } else {
2623                self.format(&b, want)
2624            };
2625            format!("( {sa} {op} {sb} )")
2626        }
2627    }
2628
2629    #[inline(never)]
2630    fn generate_builtin(&mut self, node: &NodeRef) -> String {
2631        let Node::Builtin(b) = node.node() else {
2632            unreachable!()
2633        };
2634        // `FrontFacingNode.generate()`: outside the fragment stage
2635        // there is no face, and three writes the literal `true`. The
2636        // vertex stage reaches it when a double-sided material with a
2637        // `tangent` attribute builds `bitangentView` there, whose
2638        // `negateOnBackSide()` then multiplies by `f32( true ) * 2 - 1`.
2639        if *b == Builtin::FrontFacing && self.stage != Stage::Fragment {
2640            return "true".to_string();
2641        }
2642        if self.stage == Stage::Compute {
2643            return self.generate_compute_builtin(*b);
2644        }
2645        // `ComputeBuiltinNode.generate()` outside the compute stage:
2646        // a warning and `generateConst( 'uint' )`.
2647        if *b == Builtin::SubgroupSize {
2648            eprintln!(
2649                "three-rs: TSL: Compute built-in value \"subgroupSize\" can not be accessed in the {} stage",
2650                if self.stage == Stage::Vertex { "vertex" } else { "fragment" }
2651            );
2652            return wgsl::constant(Type::U32, &[0.0]);
2653        }
2654        assert!(
2655            !matches!(
2656                b,
2657                Builtin::InvocationLocalIndex
2658                    | Builtin::WorkgroupId
2659                    | Builtin::LocalId
2660                    | Builtin::GlobalId
2661                    | Builtin::NumWorkgroups
2662                    | Builtin::InvocationSubgroupIndex
2663                    | Builtin::SubgroupIndex
2664            ),
2665            "three-rs: the compute builtin {} is only readable in a compute kernel",
2666            b.name()
2667        );
2668        // `IndexNode.generate()`
2669        // (`src/nodes/core/IndexNode.js:96-112`): the vertex and
2670        // instance indices are the raw builtin in the vertex and
2671        // compute stages and `varying( this )` anywhere else. WGSL has
2672        // no `instance_index` in a fragment entry point at all, so this
2673        // is not cosmetic — reading `instanceIndex` in a fragment flow
2674        // without it does not compile.
2675        if self.stage == Stage::Fragment
2676            && matches!(b, Builtin::InstanceIndex | Builtin::VertexIndex)
2677        {
2678            return self.attribute_varying(node);
2679        }
2680        let s = &mut self.stages[self.stage.index()];
2681        if !s.builtins.contains(b) {
2682            s.builtins.push(*b);
2683        }
2684        b.name().to_string()
2685    }
2686
2687    #[inline(never)]
2688    fn generate_select(&mut self, node: &NodeRef) -> String {
2689        let Node::Select { cond, a, b, ty } = node.node() else {
2690            unreachable!()
2691        };
2692        let (cond, a, b, ty) = (cond.clone(), a.clone(), b.clone(), *ty);
2693        // `ConditionalNode.generate()` builds its result property
2694        // *before* the condition, so the result takes the lower
2695        // `nodeVarN` number when the condition itself needs vars.
2696        let result = self.declare_var(None, ty);
2697        let scond = self.generate(&cond);
2698        self.emit(String::new());
2699        self.emit(format!("if ( {scond} ) {{"));
2700        self.emit(String::new());
2701        self.push_scope();
2702        let sa = self.format(&a, ty);
2703        self.emit(format!("{result} = {sa};"));
2704        self.pop_scope();
2705        self.emit(String::new());
2706        self.emit("} else {".to_string());
2707        self.emit(String::new());
2708        self.push_scope();
2709        let sb = self.format(&b, ty);
2710        self.emit(format!("{result} = {sb};"));
2711        self.pop_scope();
2712        self.emit(String::new());
2713        self.emit("}".to_string());
2714        self.emit(String::new());
2715        // `ConditionalNode.generate()` remembers its result property in
2716        // `nodeData`, so a second reference reuses the branch rather
2717        // than emitting the whole if/else again.
2718        self.cache_put(CacheKey::node(node), result.clone());
2719        result
2720    }
2721
2722    #[inline(never)]
2723    fn generate_swizzle(&mut self, node: &NodeRef) -> String {
2724        let Node::Swizzle {
2725            node: inner,
2726            components,
2727            ..
2728        } = node.node()
2729        else {
2730            unreachable!()
2731        };
2732        let (inner, components) = (inner.clone(), *components);
2733        // `SplitNode.generate()`: `if ( componentsLength >=
2734        // nodeTypeLength ) … node.build( builder, type )` — a
2735        // component past the end of the source *expands* the source
2736        // rather than swizzling out of bounds. `renderOutput()` asking
2737        // a vec3 `outputNode` for its alpha is that case, and it is
2738        // not cosmetic: `vec3.w` is not WGSL
2739        // (`webgpu_postprocessing_difference`).
2740        // `SplitNode.getVectorLength()`.
2741        let reach = components
2742            .bytes()
2743            .map(|c| "xyzw".find(c as char).unwrap_or(0) + 1)
2744            .chain(std::iter::once(components.len()))
2745            .max()
2746            .unwrap_or(1);
2747        let from = inner.ty();
2748        let snippet = if reach > from.components() {
2749            let wider = Type::vector_of(from.component_type(), reach);
2750            self.format(&inner, wider)
2751        } else {
2752            self.generate(&inner)
2753        };
2754        // "unnecessary swizzle": only `saturation()`'s cached `.rgb` of a
2755        // `vec3` survives construction with the whole vector's components.
2756        if components.len() == from.components() && "xyzw".starts_with(components) {
2757            return snippet;
2758        }
2759        format!("{snippet}.{components}")
2760    }
2761
2762    #[inline(never)]
2763    fn generate_if(&mut self, node: &NodeRef) -> String {
2764        let Node::If {
2765            cond,
2766            body,
2767            else_body,
2768        } = node.node()
2769        else {
2770            unreachable!()
2771        };
2772        let (cond, body, else_body) = (cond.clone(), body.clone(), else_body.clone());
2773        let scond = self.generate(&cond);
2774        self.emit(String::new());
2775        self.emit(format!("if ( {scond} ) {{"));
2776        self.emit(String::new());
2777        self.push_scope();
2778        for statement in &body {
2779            self.generate_statement(statement);
2780        }
2781        self.if_arm_tail(&body);
2782        self.pop_scope();
2783        self.emit(String::new());
2784        // A one-armed `If` emits exactly what it always did; the
2785        // `else` is additive, and takes `Node::Select`'s spacing,
2786        // which is the same `StackNode` text.
2787        if !else_body.is_empty() {
2788            self.emit("} else {".to_string());
2789            self.emit(String::new());
2790            self.push_scope();
2791            for statement in &else_body {
2792                self.generate_statement(statement);
2793            }
2794            self.if_arm_tail(&else_body);
2795            self.pop_scope();
2796            self.emit(String::new());
2797        }
2798        self.emit("}".to_string());
2799        self.emit(String::new());
2800        String::new()
2801    }
2802
2803    #[inline(never)]
2804    fn generate_atomic(&mut self, node: &NodeRef) -> String {
2805        let Node::Atomic {
2806            method,
2807            pointer,
2808            value,
2809        } = node.node()
2810        else {
2811            unreachable!()
2812        };
2813        let (method, pointer, value) = (*method, pointer.clone(), value.clone());
2814        let is_statement = self.statement == Some(node.key());
2815        assert_ne!(
2816            self.stage,
2817            Stage::Vertex,
2818            "three-rs: {method} is not supported in the vertex stage"
2819        );
2820        let ty = pointer.ty();
2821        let mut params = vec![format!("&{}", self.generate(&pointer))];
2822        if let Some(value) = &value {
2823            // `b.build( builder, inputType )` — a float into a `u32`
2824            // atomic is `u32( x )`, the same-width conversion
2825            // `wgsl::convert` writes out.
2826            params.push(self.format(value, ty));
2827        }
2828        let call = format!("{method}( {} )", params.join(", "));
2829        if is_statement && self.usage_of(node) <= 1 {
2830            self.emit(format!("{call};"));
2831            return String::new();
2832        }
2833        let name = self.declare_const(None);
2834        // `generateLetStatement()` is `let ${ name }` in WGSL — no type.
2835        self.emit(format!("let {name} = {call};"));
2836        self.cache_put(CacheKey::node(node), name.clone());
2837        name
2838    }
2839
2840    #[inline(never)]
2841    fn generate_assign(&mut self, node: &NodeRef) -> String {
2842        let Node::Assign { target, value } = node.node() else {
2843            unreachable!()
2844        };
2845        let (target, value) = (target.clone(), value.clone());
2846        let want = target.ty();
2847        // `AssignNode.generate()` generates the target first: a var's
2848        // lazy initialiser therefore lands above the statement that
2849        // first assigns to it, and the temps the value needs are
2850        // numbered after it.
2851        let lhs = self.generate(&target);
2852        if self.stage == Stage::Vertex && matches!(target.node(), Node::Varying(_)) {
2853            self.reassigned_varyings.insert(target.key());
2854        }
2855        let snippet = self.format(&value, want);
2856        // `AssignNode.needsSplitAssign()`: WGSL has no swizzle assign
2857        // (`builder.isAvailable( 'swizzleAssign' )` is false), so a
2858        // multi-component swizzle target that is not the whole vector
2859        // goes through a temp and one statement per component —
2860        // `diffuseColor.rgb.mulAssign( … )` on a `vec4` is
2861        // `nodeVarN = ( DiffuseColor.xyz * … ); DiffuseColor.x =
2862        // nodeVarN[ 0 ]; …`. A target that *is* the whole vector
2863        // (`positionLocal.xyz` on a `vec3`) keeps the plain form.
2864        if let Some((root, components)) = self.split_assign_target(&target) {
2865            let temp = self.declare_var(None, want);
2866            self.emit(format!("{temp} = {snippet};"));
2867            let root = self.generate(&root);
2868            for (i, component) in components.chars().enumerate() {
2869                self.emit(format!("{root}.{component} = {temp}[ {i} ];"));
2870            }
2871            return lhs;
2872        }
2873        self.emit(format!("{lhs} = {snippet};"));
2874        lhs
2875    }
2876
2877    #[inline(never)]
2878    fn generate_ifvar(&mut self, node: &NodeRef) -> String {
2879        let Node::IfVar {
2880            pre,
2881            result,
2882            cond,
2883            body,
2884        } = node.node()
2885        else {
2886            unreachable!()
2887        };
2888        let (pre, result, cond, body) = (pre.clone(), result.clone(), cond.clone(), body.clone());
2889        // `If()` is a statement list, not an expression: three.js emits
2890        // everything ahead of the result var first, then the var's own
2891        // initialiser, then the condition, then the block.
2892        for stmt in &pre {
2893            self.generate_statement(stmt);
2894        }
2895        let name = self.generate(&result);
2896        let scond = self.generate(&cond);
2897        self.emit(String::new());
2898        self.emit(format!("if ( {scond} ) {{"));
2899        self.emit(String::new());
2900        self.push_scope();
2901        for stmt in &body {
2902            self.generate_statement(stmt);
2903        }
2904        self.emit(String::new());
2905        self.pop_scope();
2906        self.emit(String::new());
2907        self.emit("}".to_string());
2908        self.emit(String::new());
2909        self.cache_put(CacheKey::node(node), name.clone());
2910        name
2911    }
2912
2913    #[inline(never)]
2914    fn generate_cast(&mut self, node: &NodeRef) -> String {
2915        let Node::Cast { node: inner, ty } = node.node() else {
2916            unreachable!()
2917        };
2918        let (inner, ty) = (inner.clone(), *ty);
2919        let from = inner.ty();
2920        let snippet = self.generate(&inner);
2921        if ty == from {
2922            // `ConvertNode` to the type it already has — see
2923            // `materialx::mx_nodes::convert`. `format()` returns the
2924            // snippet untouched.
2925            return snippet;
2926        }
2927        // `NodeBuilder.format()`'s two matrix narrowings.
2928        if from == Type::Mat4 && ty == Type::Mat3 {
2929            return format!(
2930                "{}( {snippet}[ 0 ].xyz, {snippet}[ 1 ].xyz, {snippet}[ 2 ].xyz )",
2931                wgsl::type_name(ty)
2932            );
2933        }
2934        if from == Type::Mat3 && ty == Type::Mat2 {
2935            return format!(
2936                "{}( {snippet}[ 0 ].xy, {snippet}[ 1 ].xy )",
2937                wgsl::type_name(ty)
2938            );
2939        }
2940        if ty.components() == from.components() {
2941            format!("{}( {snippet} )", wgsl::type_name(ty))
2942        } else {
2943            wgsl::convert(&snippet, from, ty)
2944        }
2945    }
2946
2947    #[inline(never)]
2948    fn generate_workgroup(&mut self, node: &NodeRef) -> String {
2949        let Node::Workgroup(def) = node.node() else {
2950            unreachable!()
2951        };
2952        let def = def.clone();
2953        assert_eq!(
2954            self.stage,
2955            Stage::Compute,
2956            "three-rs: workgroupArray() can only be used in a compute kernel"
2957        );
2958        let key = Rc::as_ptr(&def) as *const u8 as usize;
2959        if let Some(name) = self.workgroup_names.get(&key) {
2960            return name.clone();
2961        }
2962        let name = format!("WorkgroupArray_{}", self.workgroup_names.len());
2963        let ty = wgsl::type_name(def.element_ty);
2964        let ty = if def.atomic {
2965            format!("atomic<{ty}>")
2966        } else {
2967            ty.to_string()
2968        };
2969        self.workgroup_locals.push(format!(
2970            "var<workgroup> {name}: array< {ty}, {} >;",
2971            def.count
2972        ));
2973        self.workgroup_names.insert(key, name.clone());
2974        name
2975    }
2976
2977    #[inline(never)]
2978    fn generate_texturestore(&mut self, node: &NodeRef) -> String {
2979        let Node::TextureStore {
2980            texture,
2981            coord,
2982            value,
2983        } = node.node()
2984        else {
2985            unreachable!()
2986        };
2987        let (texture, coord, value) = (texture.clone(), coord.clone(), value.clone());
2988        let (name, kind) = self.texture_slots(&texture);
2989        let dim3 = matches!(kind, TextureKind::Storage { dim3: true, .. });
2990        let scoord = self.generate(&coord);
2991        let svalue = self.format(&value, Type::Vec4);
2992        // `uvNode.build( builder, 'uvec2' | 'uvec3' )`, whatever the
2993        // coordinate's own type: `textureStore( t, vec2<u32>( a, b ),
2994        // … )` for a `uvec2( a, b )`, `vec2<u32>( c )` for an `ivec2`
2995        // held in `c`.
2996        let coord_ty = if dim3 { "vec3<u32>" } else { "vec2<u32>" };
2997        let scoord = match coord.node() {
2998            Node::Join { args, .. } => {
2999                let parts: Vec<String> = args.iter().map(|a| self.generate(a)).collect();
3000                format!("{coord_ty}( {} )", parts.join(", "))
3001            }
3002            _ => format!("{coord_ty}( {scoord} )"),
3003        };
3004        self.emit(format!("textureStore( {name}, {scoord}, {svalue} );"));
3005        String::new()
3006    }
3007
3008    fn generate_inner(&mut self, node: &NodeRef) -> String {
3009        match node.node() {
3010            Node::Const { ty, values } => wgsl::constant(*ty, values),
3011
3012            Node::ConstArray { element_ty, values } => {
3013                // A vector element is one `vec2<f32>( x, y )` per
3014                // `components()` entries: `depthAwareBlend`'s Poisson disk,
3015                // `array< vec2<f32>, 8 >( vec2<f32>( 0.493393, … ), … )`.
3016                let width = element_ty.components().max(1);
3017                let parts: Vec<String> = if width == 1 {
3018                    values.iter().map(|v| wgsl::number(*v)).collect()
3019                } else {
3020                    values
3021                        .chunks(width)
3022                        .map(|chunk| wgsl::constant(*element_ty, chunk))
3023                        .collect()
3024                };
3025                format!(
3026                    "array< {}, {} >( {} )",
3027                    wgsl::type_name(*element_ty),
3028                    parts.len(),
3029                    parts.join(", ")
3030                )
3031            }
3032
3033            // `array( … )` the flow reads more than once: three.js gives it a
3034            // `var<private>` of array type and assigns the literal once
3035            // (`dump/m11`'s `nodeVar0 = array< f32, 5 >( 1.0, … )`).
3036            Node::ArrayVar { element_ty, values } => {
3037                let (element_ty, values) = (*element_ty, values.clone());
3038                let parts: Vec<String> = values.iter().map(|v| wgsl::number(*v)).collect();
3039                let literal = format!(
3040                    "array< {}, {} >( {} )",
3041                    wgsl::type_name(element_ty),
3042                    values.len(),
3043                    parts.join(", ")
3044                );
3045                let name = self.declare_var_typed(
3046                    None,
3047                    format!("array< {}, {} >", wgsl::type_name(element_ty), values.len()),
3048                );
3049                self.emit(format!("{name} = {literal};"));
3050                self.cache_put(CacheKey::node(node), name.clone());
3051                name
3052            }
3053
3054            Node::Uniform(u) => {
3055                let u = u.clone();
3056                let snippet = self.uniform_snippet(&u, node.key());
3057                if u.ty == Type::Bool {
3058                    // `builder.format( uniformName, 'uint', 'bool' )`, into
3059                    // the var `needs_var` gives it.
3060                    return format!("bool( {snippet} )");
3061                }
3062                snippet
3063            }
3064
3065            Node::BufferElement { buffer, index } => {
3066                let buffer = buffer.clone();
3067                let index = index.clone();
3068                let name = self.buffer_snippet(&buffer);
3069                let idx = self.generate(&index);
3070                format!("{name}.value[ {idx} ]")
3071            }
3072
3073            Node::Attribute { name, ty } => {
3074                if let Some(constant) = self.missing_attribute(name, *ty) {
3075                    return constant;
3076                }
3077                if self.stage == Stage::Fragment {
3078                    return self.attribute_varying(node);
3079                }
3080                self.geometry_attribute(name, *ty)
3081            }
3082
3083            Node::InstancedAttribute { buffer, offset, ty } => {
3084                if self.stage == Stage::Fragment {
3085                    return self.attribute_varying(node);
3086                }
3087                let key = (Rc::as_ptr(buffer) as *const u8 as usize, *offset);
3088                if let Some(name) = self.attribute_names.get(&key) {
3089                    return name.clone();
3090                }
3091                let name = format!("nodeAttribute{}", self.attribute_counter);
3092                self.attribute_counter += 1;
3093                self.attribute_names.insert(key, name.clone());
3094                self.stages[Stage::Vertex.index()]
3095                    .attributes
3096                    .push(AttributeSlot {
3097                        name: name.clone(),
3098                        ty: *ty,
3099                        format: float_vertex_format(*ty),
3100                        source: AttributeSource::Instance {
3101                            buffer: buffer.clone(),
3102                            offset: *offset,
3103                        },
3104                    });
3105                name
3106            }
3107
3108            Node::Builtin(_) => self.generate_builtin(node),
3109
3110            Node::Property { name, ty } => {
3111                let ty = *ty;
3112                let name = *name;
3113                self.declare_var(Some(name), ty)
3114            }
3115
3116            Node::Param { name, .. } => name.to_string(),
3117
3118            Node::Var(v) => {
3119                let v = v.clone();
3120                let snippet = self.generate(&v.value);
3121                // A struct value's var is declared as the struct:
3122                // `ggxReflectionSample( … ).toVar()` is `nodeVar66 =
3123                // nodeVar65;` with `var nodeVar66 : StructType0;`.
3124                let name = match struct_layout_of(&v.value) {
3125                    Some(layout) if v.ty == Type::Void => {
3126                        self.declare_var_typed(v.name.as_deref(), layout.name.to_string())
3127                    }
3128                    _ => self.declare_var(v.name.as_deref(), v.ty),
3129                };
3130                self.emit(format!("{name} = {snippet};"));
3131                self.cache_put(CacheKey::node(node), name.clone());
3132                name
3133            }
3134
3135            // `VarNode.generate()`'s `nodeVar.local` branch:
3136            // `generateVarStatement()` in front of the first assignment, and no
3137            // entry in `vars`. Counted on the same `nodeVarN` counter as a
3138            // hoisted var, as three's `_var` counter is.
3139            Node::VarIntent(v) => {
3140                let v = v.clone();
3141                let snippet = self.generate(&v.value);
3142                let name = self.local_var_name(v.name.as_deref());
3143                // A struct value's var is declared as the struct, as a hoisted
3144                // var is: `TemporalReprojectNode`'s specular neighbourhood is
3145                // `var nodeVar39 : StructType2 = nodeVar37;`.
3146                let ty = match struct_layout_of(&v.value) {
3147                    Some(layout) if v.ty == Type::Void => layout.name.to_string(),
3148                    _ => wgsl::type_name(v.ty).to_string(),
3149                };
3150                self.emit(format!("var {name} : {ty} = {snippet};"));
3151                self.cache_put(CacheKey::node(node), name.clone());
3152                name
3153            }
3154
3155            // `NodeBuilder.getVarFromNode( node, name, type, readOnly )` with
3156            // `readOnly`: a WGSL `let`, declared at the point it is assigned
3157            // rather than hoisted into the `// vars` block.
3158            Node::Let(v) => {
3159                let v = v.clone();
3160                let snippet = self.generate(&v.value);
3161                let name = self.declare_const(v.name.as_deref());
3162                self.emit(format!("let {name} = {snippet};"));
3163                self.cache_put(CacheKey::node(node), name.clone());
3164                name
3165            }
3166
3167            Node::Varying(_) => self.generate_varying(node),
3168
3169            Node::Assign { .. } => self.generate_assign(node),
3170
3171            Node::Op { .. } => self.generate_op(node),
3172
3173            Node::Math { .. } => self.generate_math(node),
3174
3175            Node::Swizzle { .. } => self.generate_swizzle(node),
3176
3177            // `ConvertNode.generate()` is `builder.format( snippet, from, to )`.
3178            // Widening goes through the shared ladder, so `vec3( vec2 )` is
3179            // `vec3<f32>( v, 0.0 )` and not a splat; narrowing is the swizzle
3180            // arm, which is where `vec3( materialEnvRotation.mul( … ) )` gets
3181            // its `.xyz` in `PMREMUtils.bilinearCubeUV`. A same-width cast
3182            // keeps the explicit constructor the port has always emitted (see
3183            // `wgsl::convert`).
3184            Node::Cast { .. } => self.generate_cast(node),
3185
3186            Node::Neg { node: inner, .. } => {
3187                let inner = inner.clone();
3188                let snippet = self.generate(&inner);
3189                format!("( - {snippet} )")
3190            }
3191
3192            Node::Join { args, ty } => {
3193                let (args, ty) = (args.clone(), *ty);
3194                // `JoinNode.generate()` converts a component whose *primitive*
3195                // type is not the join's — and only then, which is why this is
3196                // here rather than in `wgsl::convert`'s equal-length arm (see
3197                // `docs/nodes.md` §8). `vec3( ind.equal( 0 ), … )` is the one
3198                // the ladder needs: three bools into `vec3<f32>( f32( a ),
3199                // f32( b ), f32( c ) )`.
3200                let want = ty.component_type();
3201                let parts: Vec<String> = args
3202                    .iter()
3203                    .map(|a| {
3204                        let snippet = self.generate(a);
3205                        if a.ty().component_type() == want {
3206                            snippet
3207                        } else {
3208                            format!("{}( {snippet} )", wgsl::type_name(want))
3209                        }
3210                    })
3211                    .collect();
3212                format!("{}( {} )", wgsl::type_name(ty), parts.join(", "))
3213            }
3214
3215            Node::Element {
3216                node: inner, index, ..
3217            } => {
3218                let (inner, index) = (inner.clone(), index.clone());
3219                let snippet = self.generate(&inner);
3220                // `ArrayElementNode.generate()` builds a non-integer index as
3221                // `'uint'`, so a float index comes out as `u32( … )`.
3222                let idx = if index.ty() == Type::F32 {
3223                    self.format(&index, Type::U32)
3224                } else {
3225                    self.generate(&index)
3226                };
3227                format!("{snippet}[ {idx} ]")
3228            }
3229
3230            Node::Texture { .. } => self.generate_texture(node),
3231
3232            // `StorageTextureNode.generateStore()` →
3233            // `WGSLNodeBuilder.generateTextureStore()`.
3234            Node::TextureStore { .. } => self.generate_texturestore(node),
3235
3236            Node::Break => {
3237                self.emit("break;".to_string());
3238                String::new()
3239            }
3240
3241            Node::Continue => {
3242                self.emit("continue;".to_string());
3243                String::new()
3244            }
3245
3246            Node::TextureSize { texture, level } => {
3247                let (texture, level) = (texture.clone(), level.clone());
3248                let (name, _kind) = self.texture_slots(&texture);
3249                let slevel = self.generate(&level);
3250                wgsl::texture_size(&name, &slevel)
3251            }
3252
3253            Node::VaryingProperty { name, ty, flat } => {
3254                let (name, ty, flat) = (*name, *ty, *flat);
3255                if !self.varyings.iter().any(|(n, _, _)| n == name) {
3256                    self.varyings.push((name.to_string(), ty, flat));
3257                }
3258                // `NodeBuilder.getPropertyName()`: `varyings.x` while building
3259                // the vertex stage, the bare `main` parameter in the fragment
3260                // stage.
3261                match self.stage {
3262                    Stage::Vertex => format!("varyings.{name}"),
3263                    Stage::Fragment => name.to_string(),
3264                    Stage::Compute => unreachable!("three-rs: compute has no varyings"),
3265                }
3266            }
3267
3268            Node::Call { def, args } => {
3269                let (def, args) = (def.clone(), args.clone());
3270                if !def.layout {
3271                    let body = self.call_body(node, &def, &args);
3272                    return self.generate(&body);
3273                }
3274                let name = self.emit_function(&def);
3275                let parts: Vec<String> = args
3276                    .iter()
3277                    .enumerate()
3278                    .map(|(i, a)| {
3279                        let want = def.params[i].1;
3280                        self.format(a, want)
3281                    })
3282                    .collect();
3283                format!("{name}( {} )", parts.join(", "))
3284            }
3285
3286            Node::Code(def) => {
3287                let def = def.clone();
3288                self.emit_code_fn(&def);
3289                String::new()
3290            }
3291
3292            Node::CodeCall { def, args } => {
3293                let (def, args) = (def.clone(), args.clone());
3294                self.emit_code_fn(&def);
3295                let parts: Vec<String> = def
3296                    .params
3297                    .iter()
3298                    .zip(&args)
3299                    .map(|((_, kind), arg)| match kind {
3300                        crate::nodes::code::ParamKind::Value(ty) => self.format(arg, *ty),
3301                        crate::nodes::code::ParamKind::Texture => self.code_texture(arg).0,
3302                        crate::nodes::code::ParamKind::Sampler => {
3303                            format!("{}_sampler", self.code_texture(arg).0)
3304                        }
3305                    })
3306                    .collect();
3307                format!("{}( {} )", def.name, parts.join(", "))
3308            }
3309
3310            Node::IfVar { .. } => self.generate_ifvar(node),
3311
3312            Node::Select { .. } if in_uniform_flow() => self.generate_uniform_flow_select(node),
3313
3314            Node::Select { .. } => self.generate_select(node),
3315
3316            // A block is an inline `Fn()` call. Three builds its stack once
3317            // and leaves the result snippet in `builder.cache`, so a block
3318            // reached a second time in the same scope (or one nested in it)
3319            // is that snippet, not a second run of its statements. The two
3320            // readers that found this: `renderOutput()` reading its colour's
3321            // `.xyz` and `.w` (the display nodes), and the raging sea's
3322            // `elevation`, one call site read by `emissiveNode` and by
3323            // `normalNode`. See `docs/nodes.md` §36.
3324            Node::Block { statements, result } => {
3325                let (statements, result) = (statements.clone(), result.clone());
3326                for stmt in &statements {
3327                    self.generate_statement(stmt);
3328                }
3329                let snippet = self.generate(&result);
3330                self.cache_put(CacheKey::node(node), snippet.clone());
3331                snippet
3332            }
3333
3334            Node::Loop { .. } => self.generate_loop(node),
3335
3336            // `If( cond, … )` as a statement: no result property, unlike
3337            // `Node::Select`.
3338            Node::If { .. } => self.generate_if(node),
3339
3340            Node::Discard => {
3341                self.emit("discard;".to_string());
3342                String::new()
3343            }
3344
3345            // `return value;` — only legal inside an emitted `fn`, which is
3346            // the only place Three's `Fn()` bodies put one.
3347            Node::Return { value } => {
3348                let value = value.clone();
3349                let snippet = self.generate(&value);
3350                self.emit(format!("return {snippet};"));
3351                String::new()
3352            }
3353
3354            Node::Not { node: inner } => {
3355                let inner = inner.clone();
3356                let snippet = self.generate(&inner);
3357                format!("( ! {snippet} )")
3358            }
3359
3360            // `StructNode.generate()`: the struct's declaration, then its
3361            // value in a var of the struct's type — three's
3362            // `nodeVar31 = StructType0( closest, texel, farthest );`.
3363            // `materials::setup()` unpacks a material's `outputStruct()` into
3364            // the flow's MRT members; there is no other place it can stand.
3365            Node::OutputStruct { .. } => {
3366                panic!("three-rs: outputStruct() is only a material's outputNode")
3367            }
3368
3369            Node::StructNew { layout, values } => {
3370                let (layout, values) = (layout.clone(), values.clone());
3371                self.add_code(layout.name, &layout.wgsl());
3372                let args: Vec<String> = values
3373                    .iter()
3374                    .zip(&layout.members)
3375                    .map(|(value, member)| self.format(value, member.ty))
3376                    .collect();
3377                let name = self.declare_var_typed(None, layout.name.to_string());
3378                self.emit(format!("{name} = {}( {} );", layout.name, args.join(", ")));
3379                self.cache_put(CacheKey::node(node), name.clone());
3380                name
3381            }
3382
3383            // `MemberNode` over a `StructNode`.
3384            Node::StructGet {
3385                value,
3386                layout,
3387                member,
3388            } => {
3389                let (value, field) = (value.clone(), layout.members[*member].name);
3390                let snippet = self.generate(&value);
3391                format!("{snippet}.{field}")
3392            }
3393
3394            // `MemberNode` over a custom-struct storage buffer:
3395            // `WGSLNodeBuilder.getPropertyName()` returns the bare buffer name
3396            // for `isCustomStruct()`, with no `.value`.
3397            Node::StructMember { buffer, member } => {
3398                let (buffer, member) = (buffer.clone(), *member);
3399                assert_eq!(
3400                    self.stage,
3401                    Stage::Compute,
3402                    "three-rs: a struct storage buffer is only ported for compute kernels"
3403                );
3404                let name = self.buffer_snippet(&buffer);
3405                let BufferSource::Struct { layout, .. } = &buffer.source else {
3406                    unreachable!("three-rs: a struct member is only built on a struct buffer")
3407                };
3408                format!("{name}.{}", layout.members[member].name)
3409            }
3410
3411            // `AtomicFunctionNode.generate()`. `parents.length === 1 &&
3412            // parents[ 0 ].isStackNode` — nothing but the flow reads it — is a
3413            // bare call; anything else also reads the old value, which three
3414            // holds in a `let` declared where the call is made.
3415            Node::Atomic { .. } => self.generate_atomic(node),
3416
3417            // `WorkgroupInfoNode.generate()` → `builder.getScopedArray()`.
3418            Node::Workgroup(_) => self.generate_workgroup(node),
3419
3420            // Resolved in `generate()` before it gets here.
3421            Node::Compute { .. } => unreachable!("three-rs: a ComputeNode generates its output"),
3422
3423            // `BarrierNode.generate()`: `addLineFlowCode( `${ scope }Barrier()` )`.
3424            // `Node.generate()` with an `outputNode`: build what `setup`
3425            // returned, in this node's place.
3426            Node::Custom(custom) => {
3427                let custom = custom.clone();
3428                let output = self.custom_output(node, &custom);
3429                self.generate(&output)
3430            }
3431
3432            Node::Expression { .. } => self.generate_expression(node),
3433
3434            Node::Debug { .. } => self.generate_debug(node),
3435
3436            // `ContextNode.generate()`.
3437            Node::Context { node: inner, value } => {
3438                let (inner, value) = (inner.clone(), value.clone());
3439                let _context = push_context_value(&value);
3440                self.generate(&inner)
3441            }
3442
3443            // `IsolateNode.build()`: `inner` against the isolate's own cache,
3444            // which falls through to the one in force here. Its snippets are
3445            // kept for the next build of the same isolate and dropped from
3446            // view outside it.
3447            Node::Isolate { node: inner } => {
3448                let inner = inner.clone();
3449                let outer = self.enter_isolate(node);
3450                let slot = (node.key(), self.stage.index(), self.fn_scopes.len());
3451                self.cache_mut().push_child();
3452                if let Some(data) = self.isolate_snippets.remove(&slot) {
3453                    self.cache_mut().data = data;
3454                }
3455                let snippet = self.generate(&inner);
3456                let data = std::mem::take(&mut self.cache_mut().data);
3457                self.isolate_snippets.insert(slot, data);
3458                self.cache_mut().pop_child();
3459                self.data_cache = outer;
3460                snippet
3461            }
3462
3463            Node::Subgroup { .. } => self.generate_subgroup(node),
3464
3465            Node::Barrier { scope } => {
3466                let scope = *scope;
3467                assert_eq!(
3468                    self.stage,
3469                    Stage::Compute,
3470                    "three-rs: {scope}Barrier() can only be used in a compute kernel"
3471                );
3472                self.stages[Stage::Compute.index()].barrier = true;
3473                self.emit(format!("{scope}Barrier();"));
3474                String::new()
3475            }
3476            // `OperatorNode.generate()`'s `'~'` arm: the operand is built as
3477            // its own type, `( ~ a )`.
3478            Node::BitNot { node: inner, .. } => {
3479                let inner = inner.clone();
3480                let snippet = self.generate(&inner);
3481                format!("( ~ {snippet} )")
3482            }
3483        }
3484    }
3485
3486    /// A `Loop` bound, which `LoopNode.generate()` builds as the loop's own
3487    /// `type` (`int` unless `Loop( { type } )` says otherwise): a constant
3488    /// is regenerated as a literal of that type (`float( 1 )` is `1` in an
3489    /// `int` loop, `45` is `45.0` in a `float` one), anything else is
3490    /// converted (`i32( … )`, `f32( … )`).
3491    fn loop_bound(&mut self, bound: &NodeRef, ty: Type) -> String {
3492        match bound.node() {
3493            Node::Const { values, .. } if values.len() == 1 => wgsl::constant(ty, values),
3494            // `LoopNode.generate()` builds a non-constant bound with
3495            // `.build( builder, type )`, whose same-length arm is `i32( … )`
3496            // (or `f32( … )` for a `type: 'float'` loop) — which
3497            // `wgsl::convert` leaves out (see its doc), so it is written
3498            // here: `i < i32( ( nodeUniform4 + 1.0 ) )`.
3499            _ if bound.ty() != ty && bound.ty().components() == 1 => {
3500                format!("{}( {} )", wgsl::type_name(ty), self.generate(bound))
3501            }
3502            _ => self.format(bound, ty),
3503        }
3504    }
3505
3506    /// The end of an `If` / `Else` arm. `ConditionalNode.generate()` closes
3507    /// an arm with `tab + '\t' + snippet + '\n\n'`, where `snippet` is what
3508    /// the arm's callback returned: `return x;` when it returned a value (the
3509    /// port's trailing [`Node::Return`]) and nothing at all when it returned
3510    /// nothing — which still leaves that tab-indented line, empty.
3511    fn if_arm_tail(&mut self, arm: &[NodeRef]) {
3512        if !matches!(arm.last().map(|n| n.node()), Some(Node::Return { .. })) {
3513            self.emit_blank_tab();
3514        }
3515    }
3516
3517    /// An indented line with nothing on it. [`emit`](Self::emit) writes a
3518    /// blank separator as a truly empty line, which is what three's own
3519    /// separators are; this one is three's `tab + ''`.
3520    fn emit_blank_tab(&mut self) {
3521        if let Some(scope) = self.fn_scopes.last_mut() {
3522            let tab = "\t".repeat(scope.indent);
3523            scope.lines.push(tab);
3524        } else {
3525            let s = &mut self.stages[self.stage.index()];
3526            let tab = "\t".repeat(s.indent);
3527            s.lines.push(tab);
3528        }
3529    }
3530
3531    /// `FunctionNode` — emit a real WGSL `fn` once and return its name.
3532    fn emit_function(&mut self, def: &Rc<FnDef>) -> String {
3533        let key = Rc::as_ptr(def) as *const u8 as usize;
3534        // Emitted once per *stage*: each stage is its own WGSL module, so a
3535        // `Fn()` both stages call — the raging sea's `mx_noise_float`, read by
3536        // `positionNode` and again by `emissiveNode` — is written into both,
3537        // as three.js' per-stage `codes` has it. The name is shared.
3538        let stage_key = (self.stage.index(), key);
3539        if let Some(name) = self.fn_names.get(&stage_key).cloned() {
3540            return name;
3541        }
3542        let name = match self.fn_names.iter().find(|((_, k), _)| *k == key) {
3543            Some((_, name)) => name.clone(),
3544            None => match def.name {
3545                Some(n) => n.to_string(),
3546                None => {
3547                    let n = format!("fn{}", self.fn_counter);
3548                    self.fn_counter += 1;
3549                    n
3550                }
3551            },
3552        };
3553        self.fn_names.insert(stage_key, name.clone());
3554
3555        let params: Vec<NodeRef> = def
3556            .params
3557            .iter()
3558            .map(|(n, t)| NodeRef::new(Node::Param { name: n, ty: *t }))
3559            .collect();
3560
3561        // The body is analysed and generated in its own scope: its own var
3562        // numbering and its own local declarations.
3563        let saved_usage = std::mem::take(&mut self.usage);
3564        let body = (def.body)(&params);
3565        self.analyze(&body);
3566
3567        self.fn_scopes.push(FnScope {
3568            lines: Vec::new(),
3569            indent: 1,
3570            locals: Vec::new(),
3571            var_counter: 0,
3572            const_counter: 0,
3573            cache: NodeCache::default(),
3574        });
3575        let result = self.format(&body, def.ret);
3576        let scope = self
3577            .fn_scopes
3578            .pop()
3579            .expect("three-rs: the fn scope pushed above is still on the stack");
3580        self.usage = saved_usage;
3581
3582        let mut src = String::new();
3583        let sig: Vec<String> = def
3584            .params
3585            .iter()
3586            .map(|(n, t)| format!("{n} : {}", wgsl::type_name(*t)))
3587            .collect();
3588        src.push_str(&format!(
3589            "fn {name} ( {} ) -> {} {{\n\n",
3590            sig.join(", "),
3591            wgsl::type_name(def.ret)
3592        ));
3593        for (n, t) in &scope.locals {
3594            src.push_str(&format!("\tvar {n} : {t};\n"));
3595        }
3596        // `WGSLNodeBuilder._getWGSLMethod()`'s template is `\t${ vars }` on a
3597        // line of its own, so a `fn` with no locals still has that tab line.
3598        if scope.locals.is_empty() {
3599            src.push_str("\t\n");
3600        }
3601        src.push('\n');
3602        for line in &scope.lines {
3603            src.push_str(line);
3604            src.push('\n');
3605        }
3606        src.push_str(&format!("\n\treturn {result};\n\n}}\n"));
3607
3608        self.add_code(&name, &src);
3609        name
3610    }
3611
3612    /// `FunctionNode.generate()` — `includes` are built first, so a `wgslFn`
3613    /// that calls another lands *after* it in `// codes`. The source goes in
3614    /// verbatim with one newline appended, the way `getCodeFromNode()` stores
3615    /// `code + '\n'`.
3616    fn emit_code_fn(&mut self, def: &Rc<crate::nodes::code::CodeDef>) {
3617        // `CodeNode.generate()` builds every include before its own code. A
3618        // nested `wgslFn` lands in `// codes` that way; a `varyingProperty()`
3619        // include declares its varying and generates nothing.
3620        for include in def.includes.clone() {
3621            self.generate(&include);
3622        }
3623        let (name, code) = (def.name.clone(), format!("{}\n", def.code));
3624        self.add_code(&name, &code);
3625    }
3626
3627    /// The texture binding behind a `wgslFn` argument declared `texture_2d<f32>`
3628    /// or `sampler`. Three passes a `TextureNode` for both and
3629    /// `WGSLNodeBuilder.getPropertyName()` hands back the binding's name, plus
3630    /// `_sampler` for the sampler half.
3631    fn code_texture(&mut self, arg: &NodeRef) -> (String, crate::nodes::builder::TextureKind) {
3632        match arg.node() {
3633            Node::Texture { texture, .. } => {
3634                let texture = texture.clone();
3635                self.texture_slots(&texture)
3636            }
3637            _ => panic!("three-rs: a wgslFn texture parameter needs a texture node"),
3638        }
3639    }
3640}
3641
3642// ---------------------------------------------------------------------------
3643// assembly
3644// ---------------------------------------------------------------------------
3645
3646/// What a material's setup produced: the statements of each stage and the node
3647/// each stage returns.
3648///
3649/// `materials::setup` builds one for every material. A test that drives
3650/// [`NodeBuilder::build`] with a hand-made graph starts from
3651/// [`MaterialFlow::new`] and sets the stages it needs.
3652#[non_exhaustive]
3653pub struct MaterialFlow {
3654    /// `context.position` — statements flowed into the vertex stage before
3655    /// either stage's own flow, which is where instancing, morphing and
3656    /// skinning reassign `positionLocal`.
3657    pub pre_vertex_statements: Vec<NodeRef>,
3658    /// `NodeMaterial.setupDepth()`'s value: `depth.assign( depthNode )`, the
3659    /// **first** fragment statement three emits (it runs before
3660    /// `setupDiffuseColor()`), written to the fragment stage's
3661    /// `@builtin( frag_depth )` output. `Some` widens the single-attachment
3662    /// output struct to `{ @location( 0 ) color, @builtin( frag_depth )
3663    /// depth }`. See `docs/nodes.md` §27.
3664    pub depth: Option<NodeRef>,
3665    /// Fragment-stage statements, run before the output node.
3666    pub fragment_statements: Vec<NodeRef>,
3667    /// Whether to emit the `Output = …` property assignment. A material with a
3668    /// `fragmentNode` writes `output.color` straight from the result.
3669    pub emit_output_property: bool,
3670    /// The `vec4` the fragment stage writes to `output.color`, and — when
3671    /// `emit_output_property` is set — to the `Output` property.
3672    pub output: NodeRef,
3673    /// `context.getOutput`'s own `output.assign( materialOutputNode )` — a
3674    /// second write to the `Output` property, emitted immediately after
3675    /// `NodeMaterial.setup()`'s own and before the node the hook returned.
3676    /// Only `DirectRenderPipeline` sets it; see
3677    /// [`OutputContext`](crate::materials::OutputContext).
3678    pub output_assign: Option<NodeRef>,
3679    /// `material.outputNode`. `NodeMaterial.setup()` assigns the *basic*
3680    /// output to the `Output` property and then hands `output.color` to this
3681    /// node instead, so a custom output can read `Output` (or, as
3682    /// `webgpu_mesh_batch` does, `DiffuseColor` and `normalView`) after the
3683    /// standard flow has run.
3684    pub output_node: Option<NodeRef>,
3685    /// `MRTNode.members` — the values written to the fragment stage's several
3686    /// colour attachments, already laid out by attachment index (see
3687    /// `MrtNode::members`).
3688    ///
3689    /// `None` is the single-attachment shape every rung before
3690    /// `webgpu_postprocessing_bloom_selective` has: `struct OutputStruct {
3691    /// @location( 0 ) color }` and one `output.color = …`. `Some` switches the
3692    /// fragment stage to `OutputStructNode`'s `struct OutputType { @location(
3693    /// i ) mi }` and one `output.mi = …` per member, in the flow rather than in
3694    /// the result section — which is what three.js's own dump shows.
3695    ///
3696    /// Each member carries the WGSL type its `@location( i )` slot is
3697    /// declared as. For an `MRTNode` that is the type `MRTNode.setup()`
3698    /// converts it to (`builder.getOutputType( index )`): `vec4` for an
3699    /// `RGBAFormat` attachment, `f32` for `OITPassNode`'s `RedFormat`
3700    /// revealage. A bare `outputStruct()` declares each member as its own
3701    /// type — `DepthOfFieldNode`'s CoC pass writes two `f32`s.
3702    pub mrt: Option<Vec<(NodeRef, Type)>>,
3703    /// Vertex-stage statements, run before the position node.
3704    pub vertex_statements: Vec<NodeRef>,
3705    /// The clip-space position the vertex stage writes.
3706    pub position: NodeRef,
3707    /// `builder.geometry.hasAttribute( 'tangent' )`, at build time.
3708    /// `AttributeNode.generate()` checks the geometry for every attribute and,
3709    /// when it is missing, warns and writes `builder.generateConst( type )` in
3710    /// its place. The port knows only this one ahead of the draw, and the
3711    /// vertex layer of [`tangent_world`](crate::nodes::tsl::tangent_world)
3712    /// reads `tangent` whatever the geometry has, so it is the one checked.
3713    /// `true` in [`MaterialFlow::new`]: a hand-made flow keeps the slot.
3714    pub geometry_has_tangent: bool,
3715    /// The geometry's attributes as
3716    /// [`BufferGeometry::attribute_descs`](crate::core::BufferGeometry::attribute_descs)
3717    /// lists them — `builder.geometry.getAttribute( name )`, which
3718    /// `AttributeNode` reads its input's type, format and buffer layout from.
3719    /// Empty in [`MaterialFlow::new`]: every attribute is then a 32-bit
3720    /// buffer of its own in the node's type.
3721    pub geometry_attributes: Vec<AttributeDesc>,
3722    /// `builder.hardwareClipping`: the number of union clipping planes the
3723    /// vertex stage writes to `@builtin( clip_distances )`, 0 for none. A
3724    /// non-zero count enables the `clip_distances` directive and declares the
3725    /// `hw_clip_distances` varyings member; the statements that write it are
3726    /// in [`vertex_statements`](Self::vertex_statements). See
3727    /// [`hardware_clipping`](crate::nodes::clipping::hardware_clipping).
3728    pub(crate) clip_distances: usize,
3729}
3730
3731/// The 32-bit `GPUVertexFormat` for an attribute declared as `ty` with no
3732/// typed array behind it to say otherwise: an `InstanceBuffer` view (always
3733/// `f32` data) or a geometry attribute the renderer described no entry for.
3734#[inline(never)]
3735fn float_vertex_format(ty: Type) -> wgpu::VertexFormat {
3736    use wgpu::VertexFormat as F;
3737    match ty {
3738        Type::F32 => F::Float32,
3739        Type::Vec2 => F::Float32x2,
3740        Type::Vec3 => F::Float32x3,
3741        Type::Vec4 => F::Float32x4,
3742        Type::U32 => F::Uint32,
3743        Type::UVec2 => F::Uint32x2,
3744        Type::UVec3 => F::Uint32x3,
3745        Type::UVec4 => F::Uint32x4,
3746        Type::I32 => F::Sint32,
3747        Type::IVec2 => F::Sint32x2,
3748        Type::IVec3 => F::Sint32x3,
3749        Type::IVec4 => F::Sint32x4,
3750        other => panic!("three-rs: {other:?} is not a vertex attribute type"),
3751    }
3752}
3753
3754impl MaterialFlow {
3755    /// A flow that writes `output` from the fragment stage and `position`
3756    /// from the vertex stage, with no statements of its own, no depth, MRT or
3757    /// output node, and the `Output` property assigned.
3758    pub fn new(output: NodeRef, position: NodeRef) -> Self {
3759        Self {
3760            pre_vertex_statements: Vec::new(),
3761            depth: None,
3762            fragment_statements: Vec::new(),
3763            emit_output_property: true,
3764            output,
3765            output_assign: None,
3766            output_node: None,
3767            mrt: None,
3768            vertex_statements: Vec::new(),
3769            position,
3770            geometry_has_tangent: true,
3771            geometry_attributes: Vec::new(),
3772            clip_distances: 0,
3773        }
3774    }
3775}
3776
3777impl NodeBuilder {
3778    /// `NodeBuilder.build()`: analyse both stages, generate fragment then
3779    /// vertex, and assemble the two shader strings.
3780    /// `ComputeNode` — one `Fn( ... )().compute( count, workgroupSize )`.
3781    pub fn build_compute(mut self, flow: &ComputeFlow) -> ComputeProgram {
3782        self.stage = Stage::Compute;
3783        for stmt in &flow.statements {
3784            self.analyze(stmt);
3785        }
3786        for stmt in &flow.statements {
3787            self.generate_statement(stmt);
3788        }
3789
3790        // `ComputeNode.setup()` builds its bounds check *after* the kernel body
3791        // (`src/nodes/gpgpu/ComputeNode.js`), so the `uniform( count, 'uint' )`
3792        // it needs takes the **last** `nodeUniformN` number — while the line it
3793        // generates is the **first** in the flow. Both halves of that are
3794        // visible in three's dump and both are reproduced here.
3795        //
3796        // A barrier turns `allowEarlyReturns` off (`BarrierNode.setup()`): the
3797        // check would leave the barrier in non-uniform control flow, so three
3798        // builds neither the line nor its uniform.
3799        let guard = if self.stages[Stage::Compute.index()].barrier {
3800            None
3801        } else {
3802            let count = super::tsl::uniform_value(Type::U32, vec![flow.count as f64]);
3803            let cond = super::tsl::instance_index().greater_than_equal(count);
3804            let snippet = self.generate(&cond);
3805            Some(format!("\tif {snippet} {{ return; }}"))
3806        };
3807
3808        let mut prefix = Vec::new();
3809        if let Some(name) = &flow.name {
3810            // `computeNode.setName()`, which three writes into the flow as a
3811            // comment before the kernel's first line.
3812            prefix.push(String::new());
3813            prefix.push(format!("\t// flow -> {name}"));
3814        }
3815        if let Some(guard) = guard {
3816            prefix.push(guard);
3817            prefix.push(String::new());
3818        }
3819        let state = &mut self.stages[Stage::Compute.index()];
3820        prefix.append(&mut state.lines);
3821        state.lines = prefix;
3822
3823        let wgsl = self.assemble_compute(flow.workgroup_size);
3824
3825        let mut groups: Vec<Vec<BindingDesc>> = Vec::new();
3826        for group in UniformGroup::ORDER {
3827            if let Some(g) = self.groups.get(&group) {
3828                if !g.bindings.is_empty() {
3829                    groups.push(g.bindings.clone());
3830                }
3831            }
3832        }
3833        for bindings in groups.iter_mut() {
3834            for desc in bindings.iter_mut() {
3835                if let BindingDesc::Uniforms { size, .. } = desc {
3836                    *size = size.div_ceil(16) * 16;
3837                }
3838            }
3839        }
3840
3841        let mut hasher = std::collections::hash_map::DefaultHasher::new();
3842        wgsl.hash(&mut hasher);
3843        groups.hash(&mut hasher);
3844        let cache_key = hasher.finish();
3845
3846        // `WebGPUBackend.compute()`: one workgroup per `workgroupSize` elements,
3847        // rounded up — the tail invocations are what the bounds check is for.
3848        // Three's split across `y` once `x` would pass
3849        // `maxComputeWorkgroupsPerDimension` is not ported; no dispatch this
3850        // rung comes near 65 535.
3851        let per_group =
3852            (flow.workgroup_size[0] * flow.workgroup_size[1] * flow.workgroup_size[2]) as usize;
3853        let dispatch = [flow.count.div_ceil(per_group) as u32, 1, 1];
3854
3855        ComputeProgram {
3856            wgsl,
3857            groups,
3858            workgroup_size: flow.workgroup_size,
3859            dispatch,
3860            subgroups: self.stages[Stage::Compute.index()].subgroups,
3861            cache_key,
3862        }
3863    }
3864
3865    /// The fragment output type for a render target whose colour attachment
3866    /// has `components` channels — `NodeBuilder.getOutputType()`, which maps
3867    /// the target texture's format to a vector length. Only the two-channel
3868    /// case differs from the default `vec4`.
3869    /// Build for an `ArrayCamera` of `count` sub-cameras (0: an ordinary
3870    /// camera, and nothing changes).
3871    ///
3872    /// three.js' `cameraViewMatrix` and `cameraProjectionMatrix` are
3873    /// `Fn( ( { camera } ) => … ).once()`, so which node they are is decided
3874    /// per build from `builder.camera`. The port's accessors are process-wide
3875    /// singletons that every cached node (`normalWorld`, `positionView`, a
3876    /// light's direction) already holds, so the decision is made here
3877    /// instead: wherever the build reaches one of the two uniforms it builds
3878    /// the array element in its place. The element's index is `cameraIndex`
3879    /// — `uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup(
3880    /// sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' )`,
3881    /// which is flat because it is a `u32`. `docs/nodes.md` §40.
3882    #[doc(hidden)]
3883    pub fn with_array_cameras(mut self, count: usize) -> Self {
3884        if count == 0 {
3885            return self;
3886        }
3887        let camera_index = NodeRef::new(Node::Varying(Rc::new(super::node::VaryingDef {
3888            name: Some("v_cameraIndex"),
3889            value: NodeRef::new(Node::Uniform(Rc::new(UniformNode {
3890                source: UniformSource::CameraIndex,
3891                ty: Type::U32,
3892                group: UniformGroup::CameraIndex,
3893                name: std::cell::Cell::new(Some("u_cameraIndex")),
3894            }))),
3895            ty: Type::U32,
3896            flat: true,
3897        })));
3898        let element = |source| {
3899            NodeRef::new(Node::BufferElement {
3900                buffer: Rc::new(super::node::BufferNode {
3901                    id: super::node::BufferId::next(),
3902                    source,
3903                    element_ty: Type::Mat4,
3904                    count,
3905                }),
3906                index: camera_index.clone(),
3907            })
3908        };
3909        self.array_cameras = Some(ArrayCameraNodes {
3910            view: element(BufferSource::CameraViewMatrices),
3911            projection: element(BufferSource::CameraProjectionMatrices),
3912        });
3913        self
3914    }
3915
3916    /// The array element that stands in for `node` under an `ArrayCamera`,
3917    /// when `node` is the camera's view or projection uniform.
3918    fn array_camera_element(&self, node: &NodeRef) -> Option<NodeRef> {
3919        let nodes = self.array_cameras.as_ref()?;
3920        match node.node() {
3921            Node::Uniform(u) => match u.source {
3922                UniformSource::CameraViewMatrix => Some(nodes.view.clone()),
3923                UniformSource::CameraProjectionMatrix => Some(nodes.projection.clone()),
3924                _ => None,
3925            },
3926            _ => None,
3927        }
3928    }
3929
3930    #[doc(hidden)]
3931    pub fn with_output_components(mut self, components: u32) -> Self {
3932        self.output_type = match components {
3933            1 => Type::F32,
3934            2 => Type::Vec2,
3935            _ => Type::Vec4,
3936        };
3937        self
3938    }
3939
3940    /// `NodeBuilder.build()`: analyse both stages, generate fragment then
3941    /// vertex, and assemble the vertex and fragment shader strings.
3942    pub fn build(mut self, flow: &MaterialFlow) -> NodeProgram {
3943        // `builder.context.clipSpace = vertexNode` — what `clipSpace` reads.
3944        let _clip_space = push_context(|cx| {
3945            cx.extra.insert("clipSpace", flow.position.clone());
3946        });
3947        self.geometry_has_tangent = flow.geometry_has_tangent;
3948        self.geometry_attributes
3949            .clone_from(&flow.geometry_attributes);
3950        self.clip_distances = flow.clip_distances;
3951        // Each stage's flow is analysed in that stage, as three's
3952        // `build()` sets the shader stage before every stage's pass: a
3953        // [`CustomNode`] that branches on the stage (`clip_space`) is set up
3954        // in the stage that first reaches it.
3955        self.stage = Stage::Vertex;
3956        for stmt in &flow.pre_vertex_statements {
3957            self.analyze(stmt);
3958        }
3959        self.stage = Stage::Fragment;
3960        if let Some(node) = &flow.depth {
3961            self.analyze(node);
3962        }
3963        for stmt in &flow.fragment_statements {
3964            self.analyze(stmt);
3965        }
3966        // The output node is reached twice — once by the `Output` property and
3967        // once by `output.color` — which is what gives it its own var.
3968        self.analyze(&flow.output);
3969        // The basic output is reached twice — once by the `Output` property and
3970        // once by `output.color` — which is what gives it its own var. With a
3971        // custom `outputNode` it is reached only by `Output`.
3972        // With MRT the basic output is reached only by `Output`, exactly as
3973        // with a custom `outputNode`: `NodeMaterial.setup()` assigns it to the
3974        // property and then hands the *MRT node* to the result, and the MRT's
3975        // `output` member reads the property back rather than the node.
3976        if flow.emit_output_property && flow.output_node.is_none() && flow.mrt.is_none() {
3977            self.analyze(&flow.output);
3978        }
3979        if let Some(node) = &flow.output_assign {
3980            self.analyze(node);
3981        }
3982        if let Some(node) = &flow.output_node {
3983            self.analyze(node);
3984        }
3985        for (member, _) in flow.mrt.iter().flatten() {
3986            self.analyze(member);
3987        }
3988        self.stage = Stage::Vertex;
3989        for stmt in &flow.vertex_statements {
3990            self.analyze(stmt);
3991        }
3992        self.analyze(&flow.position);
3993        self.analyze(&flow.position);
3994
3995        self.stage = Stage::Vertex;
3996        for stmt in &flow.pre_vertex_statements {
3997            self.generate_statement(stmt);
3998        }
3999
4000        self.stage = Stage::Fragment;
4001        // `setupDepth()` runs before `setupDiffuseColor()`, so `output.depth`
4002        // is the first line of the fragment flow, above the discard the
4003        // colour node may add.
4004        if let Some(node) = &flow.depth {
4005            let node = node.clone();
4006            let snippet = self.format(&node, Type::F32);
4007            self.emit(format!("output.depth = {snippet};"));
4008        }
4009        for stmt in &flow.fragment_statements {
4010            self.generate_statement(stmt);
4011        }
4012        // `NodeMaterial.setup()` registers the `Output` property *before* the
4013        // output node's own flow runs, so `Output` is declared above the temps
4014        // that flow needs — the order three's own dumps show.
4015        // A red target's `Output` is the `f32` the program writes.
4016        let output_prop_ty = match self.output_type {
4017            Type::F32 => Type::F32,
4018            _ => Type::Vec4,
4019        };
4020        let output_prop = flow
4021            .emit_output_property
4022            .then(|| self.declare_var(Some("Output"), output_prop_ty));
4023        // The entry point writes a `vec4`: three builds the output node with
4024        // `vec4` as its output type, so a `fragmentNode` that returns a
4025        // `vec3` — `webgpu_tsl_interoperability`'s `crtFragment` — is widened
4026        // here rather than assigned as it is.
4027        let output_type = self.output_type;
4028        let mut color = self.format(&flow.output, output_type);
4029        if let Some(output_prop) = &output_prop {
4030            self.emit(format!("{output_prop} = {color};"));
4031        }
4032        // The hook's own assign, which is why a direct-pipeline fragment has
4033        // `Output = nodeVarN;` twice.
4034        if let (Some(output_prop), Some(node)) = (&output_prop, &flow.output_assign) {
4035            let node = node.clone();
4036            let snippet = self.generate(&node);
4037            self.emit(format!("{output_prop} = {snippet};"));
4038        }
4039        if let Some(node) = &flow.output_node {
4040            let node = node.clone();
4041            color = self.format(&node, output_type);
4042        }
4043        // `OutputStructNode.generate()`: one `output.mN = <member>` line per
4044        // member, pushed onto the *flow* — the entry point's result section is
4045        // then empty and only `return output;` is left.
4046        if let Some(members) = &flow.mrt {
4047            for (index, (member, ty)) in members.iter().enumerate() {
4048                let snippet = self.format(member, *ty);
4049                self.emit(format!("output.m{index} = {snippet};"));
4050            }
4051        }
4052
4053        self.stage = Stage::Vertex;
4054        for stmt in &flow.vertex_statements {
4055            self.generate_statement(stmt);
4056        }
4057        let position = self.generate(&flow.position);
4058
4059        let fragment_wgsl = self.assemble_with_mrt(
4060            Stage::Fragment,
4061            &color,
4062            flow.mrt
4063                .as_ref()
4064                .map(|members| members.iter().map(|(_, ty)| *ty).collect::<Vec<_>>())
4065                .as_deref(),
4066            flow.depth.is_some(),
4067        );
4068        let vertex_wgsl = self.assemble(Stage::Vertex, &position);
4069
4070        let attributes = self.stages[Stage::Vertex.index()].attributes.clone();
4071
4072        let mut groups: Vec<Vec<BindingDesc>> = Vec::new();
4073        for group in UniformGroup::ORDER {
4074            if let Some(g) = self.groups.get(&group) {
4075                if !g.bindings.is_empty() {
4076                    groups.push(g.bindings.clone());
4077                }
4078            }
4079        }
4080        // A uniform-address-space struct is padded out to a multiple of 16.
4081        for bindings in groups.iter_mut() {
4082            for desc in bindings.iter_mut() {
4083                if let BindingDesc::Uniforms { size, .. } = desc {
4084                    *size = size.div_ceil(16) * 16;
4085                }
4086            }
4087        }
4088
4089        let mut hasher = std::collections::hash_map::DefaultHasher::new();
4090        vertex_wgsl.hash(&mut hasher);
4091        fragment_wgsl.hash(&mut hasher);
4092        // The vertex buffer layouts are baked into the pipeline but do not all
4093        // show in the WGSL: an attribute's stride and offset come from its
4094        // `InstanceBuffer`. Buffer *identity* is deliberately not hashed — it
4095        // changes every frame for the instance matrix, and the per-draw program
4096        // (not the cached one) is what resolves resources.
4097        for slot in &attributes {
4098            slot.name.hash(&mut hasher);
4099            slot.ty.hash(&mut hasher);
4100            slot.format.hash(&mut hasher);
4101            match &slot.source {
4102                AttributeSource::Geometry(geometry) => geometry.hash(&mut hasher),
4103                AttributeSource::Instance { buffer, offset } => {
4104                    buffer.item_size.hash(&mut hasher);
4105                    buffer.per_vertex.hash(&mut hasher);
4106                    offset.hash(&mut hasher);
4107                }
4108            }
4109        }
4110        // Two materials can generate identical WGSL and still need different
4111        // bindings — two copies of the same shader with different baked uniform
4112        // values (a texture's uv matrix, say). The binding descriptions are part
4113        // of the program, so they are part of its key. `BindingDesc`'s `Hash`
4114        // walks the description itself: a texture goes in by identity and by the
4115        // fields its binding and sampler are built from, never by its pixels,
4116        // and never by whether it has been uploaded yet.
4117        groups.hash(&mut hasher);
4118        let cache_key = hasher.finish();
4119
4120        // `PassTextureNode.setup()` builds its `passNode`, and an `RTTNode`
4121        // is its own texture node, so a material that samples a pass has the
4122        // pass among its update-before nodes. The port's texture node is a
4123        // bare texture, so the link is looked up by the texture bound.
4124        for binding in groups.iter().flatten() {
4125            if let BindingDesc::Texture { source, .. } = binding {
4126                if let Some(entry) = crate::nodes::frame::texture_update(source.id()) {
4127                    self.add_update_node(entry);
4128                }
4129            }
4130        }
4131        let [update_before, update, update_after] = std::mem::take(&mut self.update_nodes);
4132        let reads_velocity = groups.iter().flatten().any(|binding| match binding {
4133            BindingDesc::Uniforms { members, .. } => members.iter().any(|member| {
4134                matches!(
4135                    member.source,
4136                    UniformSource::PreviousModelWorldMatrix
4137                        | UniformSource::VelocityProjectionMatrix
4138                        | UniformSource::PreviousProjectionMatrix
4139                        | UniformSource::PreviousCameraViewMatrix
4140                )
4141            }),
4142            BindingDesc::Buffer { source, .. } => {
4143                matches!(source, BufferSource::PreviousBoneMatrices)
4144            }
4145            _ => false,
4146        });
4147
4148        NodeProgram {
4149            vertex_wgsl,
4150            fragment_wgsl,
4151            attributes,
4152            groups,
4153            subgroups: self.stages[Stage::Vertex.index()].subgroups
4154                || self.stages[Stage::Fragment.index()].subgroups,
4155            cache_key,
4156            update_before,
4157            update,
4158            update_after,
4159            reads_velocity,
4160        }
4161    }
4162
4163    /// The group index a uniform group ended up at: the groups take their
4164    /// indices in [`UniformGroup::ORDER`], each only when it is used at all —
4165    /// render, then `cameraIndex`, then object.
4166    fn group_index(&self, group: UniformGroup) -> u32 {
4167        UniformGroup::ORDER
4168            .iter()
4169            .take_while(|g| **g != group)
4170            .filter(|g| self.groups.get(g).is_some_and(|g| !g.bindings.is_empty()))
4171            .count() as u32
4172    }
4173
4174    fn uniform_declarations(&self, stage: Stage) -> String {
4175        let mut out = String::new();
4176
4177        // Textures and samplers first, then array buffers, then the two
4178        // structs — declaration order is free in WGSL; binding numbers are not.
4179        for group in [UniformGroup::Object, UniformGroup::Render] {
4180            let Some(g) = self.groups.get(&group) else {
4181                continue;
4182            };
4183            let gi = self.group_index(group);
4184            for (binding, desc) in g.bindings.iter().enumerate() {
4185                match desc {
4186                    BindingDesc::Sampler {
4187                        source,
4188                        kind,
4189                        visibility,
4190                    } => {
4191                        if !Self::visible(*visibility, stage) {
4192                            continue;
4193                        }
4194                        let name = self.texture_name(source);
4195                        // A shadow map is read with `textureSampleCompare`, so
4196                        // its sampler is declared `sampler_comparison`.
4197                        out.push_str(&format!(
4198                            "@binding( {binding} ) @group( {gi} ) var {name}_sampler : {};\n",
4199                            kind.sampler_wgsl()
4200                        ));
4201                    }
4202                    BindingDesc::Texture {
4203                        source,
4204                        kind,
4205                        visibility,
4206                    } => {
4207                        if !Self::visible(*visibility, stage) {
4208                            continue;
4209                        }
4210                        let name = self.texture_name(source);
4211                        out.push_str(&format!(
4212                            "@binding( {binding} ) @group( {gi} ) var {name} : {};\n",
4213                            kind.declaration(stage == Stage::Compute)
4214                        ));
4215                    }
4216                    _ => {}
4217                }
4218            }
4219        }
4220
4221        // `WGSLNodeBuilder.getUniforms()` collects `bufferSnippets` and
4222        // `structSnippets` separately and writes every buffer before any
4223        // uniform struct, whichever group each is in.
4224        for group in UniformGroup::ORDER {
4225            let Some(g) = self.groups.get(&group) else {
4226                continue;
4227            };
4228            let gi = self.group_index(group);
4229            for (binding, desc) in g.bindings.iter().enumerate() {
4230                let BindingDesc::Buffer {
4231                    name,
4232                    element_ty,
4233                    count,
4234                    visibility,
4235                    source,
4236                    ..
4237                } = desc
4238                else {
4239                    continue;
4240                };
4241                if !Self::visible(*visibility, stage) {
4242                    continue;
4243                }
4244                // `WGSLNodeBuilder.getStorageAccess()`: `read_write` in the
4245                // compute stage and forced to `read` everywhere else.
4246                let read_only = matches!(
4247                    source,
4248                    BufferSource::StorageData {
4249                        read_only: true,
4250                        ..
4251                    }
4252                );
4253                let access = if visibility.compute && !read_only {
4254                    "read_write"
4255                } else {
4256                    "read"
4257                };
4258                let element = wgsl::type_name(*element_ty);
4259                match source {
4260                    // `isCustomStruct()`: the struct itself, on one line.
4261                    BufferSource::Struct { layout, .. } => out.push_str(&format!(
4262                        "@binding( {binding} ) @group( {gi} ) var<storage, {access}> {name} : {};\n",
4263                        layout.name
4264                    )),
4265                    // A runtime-sized array — no element count.
4266                    BufferSource::Storage | BufferSource::StorageData { .. } => out.push_str(&format!(
4267                        "\nstruct {name}Struct {{\n\tvalue : array< {element} >\n}};\n@binding( {binding} ) @group( {gi} )\nvar<storage, {access}> {name} : {name}Struct;\n"
4268                    )),
4269                    // `bufferNode.isAtomic ? `atomic<${ bufferType }>``.
4270                    BufferSource::AtomicStorage => out.push_str(&format!(
4271                        "\nstruct {name}Struct {{\n\tvalue : array< atomic<{element}> >\n}};\n@binding( {binding} ) @group( {gi} )\nvar<storage, {access}> {name} : {name}Struct;\n"
4272                    )),
4273                    _ => out.push_str(&format!(
4274                        "\nstruct {name}Struct {{\n\tvalue : array< {element}, {count} >\n}};\n@binding( {binding} ) @group( {gi} )\nvar<uniform> {name} : {name}Struct;\n"
4275                    )),
4276                }
4277            }
4278        }
4279
4280        for group in UniformGroup::ORDER {
4281            let Some(g) = self.groups.get(&group) else {
4282                continue;
4283            };
4284            let gi = self.group_index(group);
4285            for (binding, desc) in g.bindings.iter().enumerate() {
4286                let BindingDesc::Uniforms {
4287                    members,
4288                    visibility,
4289                    ..
4290                } = desc
4291                else {
4292                    continue;
4293                };
4294                if !Self::visible(*visibility, stage) || members.is_empty() {
4295                    continue;
4296                }
4297                let name = group.struct_name();
4298                out.push_str(&format!("\nstruct {name}Struct {{\n"));
4299                let decls: Vec<String> = members
4300                    .iter()
4301                    .map(|m| format!("\t{} : {}", m.name, wgsl::type_name(m.ty)))
4302                    .collect();
4303                out.push_str(&decls.join(",\n"));
4304                out.push_str(&format!(
4305                    "\n}};\n@binding( {binding} ) @group( {gi} )\nvar<uniform> {name} : {name}Struct;\n"
4306                ));
4307            }
4308        }
4309
4310        out
4311    }
4312
4313    fn visible(v: Visibility, stage: Stage) -> bool {
4314        match stage {
4315            Stage::Vertex => v.vertex,
4316            Stage::Fragment => v.fragment,
4317            Stage::Compute => v.compute,
4318        }
4319    }
4320
4321    fn texture_name(&self, source: &TextureSource) -> String {
4322        let key = (source.id(), source.is_storage_binding());
4323        self.texture_names[&key].0.clone()
4324    }
4325
4326    /// `WGSLNodeBuilder`'s compute template
4327    /// (`src/renderers/webgpu/nodes/WGSLNodeBuilder.js` `_getWGSLComputeCode`).
4328    ///
4329    /// One deliberate divergence, listed in `docs/nodes.md` §8: three emits
4330    /// `enable subgroups;` under `// directives` and a
4331    /// `@builtin( subgroup_size ) subgroupSize : u32` parameter in every
4332    /// kernel when the device has `subgroups`; the port emits both only for a
4333    /// kernel that reads a subgroup builtin or calls a subgroup function
4334    /// (`docs/nodes.md` §84), so a kernel without them runs on any adapter.
4335    fn assemble_compute(&self, workgroup_size: [u32; 3]) -> String {
4336        let s = &self.stages[Stage::Compute.index()];
4337        let mut out = String::from("// three-rs - Node System\n\n");
4338        // Three's `// directives\n${ directives }\n\n`, less the line it
4339        // spends on `enable subgroups;` in a kernel that has none.
4340        if s.subgroups {
4341            out.push_str(&format!("// directives\n{}\n\n", directives(s)));
4342        } else {
4343            out.push_str("// directives\n\n");
4344        }
4345        out.push_str("// system\nvar<private> instanceIndex : u32;\n\n");
4346        // `// locals\n${ scopedArrays }\n\n` and `// structs\n${ structs }\n\n`,
4347        // `getStructs()` being `\n` + the structs + `\n` when there are any.
4348        out.push_str(&format!(
4349            "// locals\n{}\n\n",
4350            self.workgroup_locals.join("\n")
4351        ));
4352        let mut structs: Vec<String> = Vec::new();
4353        for group in UniformGroup::ORDER {
4354            let Some(g) = self.groups.get(&group) else {
4355                continue;
4356            };
4357            for desc in &g.bindings {
4358                if let BindingDesc::Buffer {
4359                    source: BufferSource::Struct { layout, .. },
4360                    ..
4361                } = desc
4362                {
4363                    let text = layout.wgsl();
4364                    if !structs.contains(&text) {
4365                        structs.push(text);
4366                    }
4367                }
4368            }
4369        }
4370        let structs = if structs.is_empty() {
4371            String::new()
4372        } else {
4373            format!("\n{}\n", structs.join("\n\n"))
4374        };
4375        out.push_str(&format!("// structs\n{structs}\n\n"));
4376
4377        out.push_str("// uniforms\n");
4378        out.push_str(&self.uniform_declarations(Stage::Compute));
4379        out.push('\n');
4380
4381        // `// vars\n${ vars }\n\n`, the declarations joined by `\n` — so a
4382        // kernel with none still has the blank line. With
4383        // `allowGlobalVariables` off (a barrier) the module-scope block is
4384        // empty and `getVars( 'compute', false )` writes them under
4385        // `// local vars` instead: `\n\t` + `var name : T;` joined by `\n\t`
4386        // + `\n`.
4387        let local_vars = if s.barrier {
4388            let vars: Vec<String> = s
4389                .decls
4390                .iter()
4391                .map(|(name, ty)| format!("var {name} : {ty};"))
4392                .collect();
4393            out.push_str("// vars\n\n\n");
4394            format!("\n\t{}\n", vars.join("\n\t"))
4395        } else {
4396            let vars: Vec<String> = s
4397                .decls
4398                .iter()
4399                .map(|(name, ty)| format!("var<private> {name} : {ty};"))
4400                .collect();
4401            out.push_str(&format!("// vars\n{}\n\n", vars.join("\n")));
4402            String::new()
4403        };
4404
4405        out.push_str("// codes\n");
4406        for code in &s.codes {
4407            out.push_str(code);
4408            out.push('\n');
4409        }
4410        out.push_str("\n\n");
4411
4412        let [wx, wy, wz] = workgroup_size;
4413        // `getBuiltin( 'local_invocation_index', … )` and the two subgroup
4414        // indices register their parameter while the flow is generated, i.e.
4415        // before `getAttributes()` adds the four fixed ones — so they come
4416        // first, in the order the flow read them. `subgroup_size` is the one
4417        // `getAttributes()` appends after those four.
4418        let mut leading = String::new();
4419        for b in &s.builtins {
4420            let builtin = match b {
4421                Builtin::InvocationLocalIndex => "local_invocation_index",
4422                Builtin::InvocationSubgroupIndex => "subgroup_invocation_id",
4423                Builtin::SubgroupIndex => "subgroup_id",
4424                _ => unreachable!("three-rs: only the index builtins are registered by the flow"),
4425            };
4426            leading.push_str(&format!("@builtin( {builtin} ) {} : u32,\n\t", b.name()));
4427        }
4428        let subgroup_size = if s.subgroups {
4429            ",\n\t@builtin( subgroup_size ) subgroupSize : u32"
4430        } else {
4431            ""
4432        };
4433        out.push_str(&format!(
4434            "@compute @workgroup_size( {wx}, {wy}, {wz} )\n\
4435             fn main( {leading}@builtin( global_invocation_id ) globalId : vec3<u32>,\n\
4436             \t@builtin( workgroup_id ) workgroupId : vec3<u32>,\n\
4437             \t@builtin( local_invocation_id ) localId : vec3<u32>,\n\
4438             \t@builtin( num_workgroups ) numWorkgroups : vec3<u32>{subgroup_size} ) {{\n\n\
4439             \t// local vars\n\t{local_vars}\n\n\
4440             \t// system\n\
4441             \tinstanceIndex = globalId.x\n\
4442             \t\t+ globalId.y * ( {wx} * numWorkgroups.x )\n\
4443             \t\t+ globalId.z * ( {wx} * numWorkgroups.x ) * ( {wy} * numWorkgroups.y );\n\n\
4444             \t// flow\n\t// code\n\n"
4445        ));
4446        for line in &s.lines {
4447            out.push_str(line);
4448            out.push('\n');
4449        }
4450        out.push_str("\n\t\n\n}\n");
4451        out
4452    }
4453
4454    fn assemble(&self, stage: Stage, result: &str) -> String {
4455        self.assemble_with_mrt(stage, result, None, false)
4456    }
4457
4458    /// `mrt_members` is `Some(types)` for a fragment stage with an
4459    /// `OutputStructNode` result: the struct is `OutputType` with one
4460    /// `@location( i ) mi : <type>` member per entry, and the entry point's
4461    /// result section is empty because `generate()` already wrote the
4462    /// assignments into the flow.
4463    fn assemble_with_mrt(
4464        &self,
4465        stage: Stage,
4466        result: &str,
4467        mrt_members: Option<&[Type]>,
4468        depth: bool,
4469    ) -> String {
4470        let s = &self.stages[stage.index()];
4471        let mut out = String::from("// three-rs - Node System\n\n");
4472
4473        if stage == Stage::Fragment {
4474            out.push_str("// global\ndiagnostic( off, derivative_uniformity );\n\n\n");
4475            // Three's `// directives` block, which the port writes only when
4476            // it has something in it.
4477            if s.subgroups {
4478                out.push_str(&format!("// directives\n{}\n\n", directives(s)));
4479            }
4480            match mrt_members {
4481                Some(types) => {
4482                    out.push_str("// structs\n\nstruct OutputType {\n");
4483                    for (index, ty) in types.iter().enumerate() {
4484                        let ty = wgsl::type_name(*ty);
4485                        out.push_str(&format!("\t@location( {index} ) m{index} : {ty},\n"));
4486                    }
4487                    out.push_str("\t\n};\nvar<private> output : OutputType;\n\n");
4488                }
4489                // `NodeBuilder.getOutputStructName()`'s depth member:
4490                // `@builtin( frag_depth )`, with the comma and the spacing
4491                // three's template puts around it.
4492                None if depth => out.push_str(&format!("// structs\n\nstruct OutputStruct {{\n\t@location( 0 ) color: {},\n\t@builtin( frag_depth ) depth : f32\n}};\nvar<private> output : OutputStruct;\n\n", wgsl::type_name(self.output_type))),
4493                None => out.push_str(&format!("// structs\n\nstruct OutputStruct {{\n\t@location( 0 ) color: {}\n}};\nvar<private> output : OutputStruct;\n\n", wgsl::type_name(self.output_type))),
4494            }
4495        } else {
4496            let directives = match stage {
4497                Stage::Vertex => vertex_directives(s, self.clip_distances),
4498                _ => directives(s).to_string(),
4499            };
4500            out.push_str(&format!("// directives\n{directives}\n\n// structs\n\n\n"));
4501        }
4502
4503        out.push_str("// uniforms\n");
4504        out.push_str(&self.uniform_declarations(stage));
4505        out.push('\n');
4506
4507        if stage == Stage::Vertex {
4508            out.push_str("// varyings\n\nstruct VaryingsStruct {\n");
4509            for (name, ty, flat) in &self.varyings {
4510                let interp = if *flat {
4511                    "@interpolate(flat, either) "
4512                } else {
4513                    ""
4514                };
4515                let loc = self
4516                    .varyings
4517                    .iter()
4518                    .position(|(n, _, _)| n == name)
4519                    .expect("three-rs: the varying was read out of this same list");
4520                out.push_str(&format!(
4521                    "\t@location( {loc} ) {interp}{name} : {},\n",
4522                    wgsl::type_name(*ty)
4523                ));
4524            }
4525            out.push_str(&clip_distances_member(self.clip_distances));
4526            out.push_str("\t@builtin( position ) builtinClipSpace : vec4<f32>\n};\nvar<private> varyings : VaryingsStruct;\n\n");
4527        }
4528
4529        // `// vars\n${ vars }\n\n`, the declarations joined by `\n` — so a
4530        // kernel with none still has the blank line.
4531        let vars: Vec<String> = s
4532            .decls
4533            .iter()
4534            .map(|(name, ty)| format!("var<private> {name} : {ty};"))
4535            .collect();
4536        out.push_str(&format!("// vars\n{}\n\n", vars.join("\n")));
4537
4538        out.push_str("// codes\n");
4539        for code in &s.codes {
4540            out.push_str(code);
4541            out.push('\n');
4542        }
4543        // Three's template is `// codes\n${ codes }\n\n${ entry }`, so an empty
4544        // `codes` section is followed by two blank lines, not one.
4545        out.push_str("\n\n");
4546
4547        let mut params: Vec<String> = Vec::new();
4548        for b in &s.builtins {
4549            let builtin = match b {
4550                Builtin::VertexIndex => "vertex_index",
4551                Builtin::InstanceIndex => "instance_index",
4552                Builtin::FragCoord => "position",
4553                Builtin::FrontFacing => "front_facing",
4554                Builtin::InvocationLocalIndex
4555                | Builtin::WorkgroupId
4556                | Builtin::LocalId
4557                | Builtin::GlobalId
4558                | Builtin::NumWorkgroups
4559                | Builtin::SubgroupSize
4560                | Builtin::InvocationSubgroupIndex
4561                | Builtin::SubgroupIndex => {
4562                    unreachable!("three-rs: compute builtins never reach a render stage")
4563                }
4564            };
4565            params.push(format!(
4566                "@builtin( {builtin} ) {} : {}",
4567                b.name(),
4568                wgsl::type_name(b.ty())
4569            ));
4570        }
4571        if stage == Stage::Vertex {
4572            for (i, slot) in s.attributes.iter().enumerate() {
4573                params.push(format!(
4574                    "@location( {i} ) {} : {}",
4575                    slot.name,
4576                    wgsl::type_name(slot.ty)
4577                ));
4578            }
4579        } else {
4580            for (i, (name, ty, flat)) in self.varyings.iter().enumerate() {
4581                let interp = if *flat {
4582                    "@interpolate(flat, either) "
4583                } else {
4584                    ""
4585                };
4586                params.push(format!(
4587                    "@location( {i} ) {interp}{name} : {}",
4588                    wgsl::type_name(*ty)
4589                ));
4590            }
4591        }
4592
4593        let (attr, ret) = match stage {
4594            Stage::Vertex => ("@vertex", "VaryingsStruct"),
4595            Stage::Fragment => (
4596                "@fragment",
4597                match mrt_members {
4598                    Some(_) => "OutputType",
4599                    None => "OutputStruct",
4600                },
4601            ),
4602            Stage::Compute => unreachable!("three-rs: assemble_compute writes the compute entry"),
4603        };
4604        out.push_str(&format!(
4605            "{attr}\nfn main( {} ) -> {ret} {{\n\n\t// flow\n\t// code\n\n",
4606            params.join(",\n\t")
4607        ));
4608        for line in &s.lines {
4609            out.push_str(line);
4610            out.push('\n');
4611        }
4612        out.push_str("\n\t// result\n\n");
4613        match stage {
4614            Stage::Vertex => {
4615                out.push_str(&format!(
4616                    "\tvaryings.builtinClipSpace = {result};\n\n\treturn varyings;\n\n}}\n"
4617                ));
4618            }
4619            Stage::Fragment => match mrt_members {
4620                // `OutputStructNode.generate()` returns the struct's property
4621                // name and leaves the assignments in the flow, so there is
4622                // nothing left to write here.
4623                Some(_) => out.push_str("\treturn output;\n\n}\n"),
4624                None => out.push_str(&format!(
4625                    "\toutput.color = {result};\n\n\treturn output;\n\n}}\n"
4626                )),
4627            },
4628            Stage::Compute => unreachable!("three-rs: assemble_compute writes the compute entry"),
4629        }
4630        out
4631    }
4632}
4633
4634#[cfg(test)]
4635mod tests {
4636    use super::{current_context, push_context};
4637
4638    #[test]
4639    fn build_context_nests_and_restores() {
4640        assert_eq!(current_context(|cx| cx.sub_build), None);
4641        {
4642            let _outer = push_context(|cx| cx.sub_build = Some("NORMAL"));
4643            assert_eq!(current_context(|cx| cx.sub_build), Some("NORMAL"));
4644            {
4645                let _inner = push_context(|cx| cx.sub_build = Some("VERTEX"));
4646                assert_eq!(current_context(|cx| cx.sub_build), Some("VERTEX"));
4647            }
4648            assert_eq!(current_context(|cx| cx.sub_build), Some("NORMAL"));
4649        }
4650        assert_eq!(current_context(|cx| cx.sub_build), None);
4651    }
4652}