three-rs 0.2.0

A port of three.js core and its WebGPURenderer to Rust on wgpu, graded against three.js's own end-to-end pixel comparison.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Port of `three.js/src/nodes/display/PassNode.js`.
//!
//! `pass( scene, camera )` is a `TempNode` that owns a `RenderTarget`, renders
//! the given scene into it once per frame from `updateBefore()`, and evaluates
//! to the target's colour texture. Its `setup()` returns a `PassTextureNode`,
//! which is itself a `TempNode`, so a pass **used as a value** contributes two
//! vars to the generated shader — `nodeVarN = textureSample( … ); nodeVarN+1 =
//! nodeVarN;` — and `.a` is taken on the outer one. `to_var( texture_uv( … ) )`
//! reproduces that exactly ([`PassNode::node`]).
//!
//! `passNode.getTextureNode()` is the *inner* node on its own, so it emits one
//! var and no copy ([`PassNode::texture_node`]). `webgpu_postprocessing_masking`
//! takes the first form and `webgpu_postprocessing_difference` the second; both
//! dumps show the difference.
//!
//! `PassTextureNode` also calls `setUpdateMatrix( false )`, so a pass samples
//! the raw `uv()` varying with no texture matrix — unlike `texture( map )`,
//! which carries a `mat3x3` in the object uniform block.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

use crate::cameras::RenderCamera;
use crate::core::Layers;
use crate::nodes::node::SettableValue;
use crate::nodes::tsl::{
    pass_depth_texture, perspective_depth_to_view_z, texture_uv, to_var, uniform_settable, uv,
};
use crate::nodes::{MrtNode, NodeRef, NodeUpdate, NodeUpdateType, Type};
use crate::objects::Scene;
use crate::textures::{DepthTexture, TextureFilter, TextureType};

/// `PassNode`'s depth output name.
pub const DEPTH_ATTACHMENT: &str = "depth";

use super::render_target::{RenderTarget, RenderTargetOptions, OUTPUT_ATTACHMENT};
use super::Renderer;

/// `pass( scene, camera )`.
///
/// A handle: clones share one pass. The pass renders its scene from
/// `updateBefore()` (`NodeUpdateType.FRAME`), which the renderer fires the
/// first time in a frame that a draw samples one of the pass's textures, as
/// three's does (`docs/nodes.md` §57). The nested render is its own submit,
/// so the GPU runs it before the pass that samples it.
///
/// The scene and camera are shared handles, given by [`pass`] or
/// [`PassNode::set_scene`]: the node holds them across frames, as three's
/// `this.scene` / `this.camera` do. A pass without them never renders; the
/// explicit `render()` that used to cover that case was removed in 0.2.0
/// (`docs/api.md` decision 10).
#[derive(Clone)]
pub struct PassNode(Rc<PassState>);

/// The handle reads through to what it shares, so the accessors below read
/// the pass's fields as they did before it was a handle.
impl std::ops::Deref for PassNode {
    type Target = PassState;

    fn deref(&self) -> &PassState {
        &self.0
    }
}

/// A shared scene, as a pass holds it.
pub type SceneRef = Rc<RefCell<Scene>>;
/// A shared camera, as a pass holds it.
pub type CameraRef = Rc<RefCell<dyn RenderCamera>>;

/// What a [`PassNode`] handle shares.
pub struct PassState {
    render_target: RenderTarget,
    node: NodeRef,
    /// `PassNode._previousTextureNodes` — the node for the *other* texture
    /// behind an output name, memoised like `_textureNodes` so that two asks
    /// compose one node.
    previous_texture_nodes: RefCell<HashMap<String, NodeRef>>,
    /// `PassNode._mrt` — the MRT the renderer is given for the duration of this
    /// pass's own render.
    mrt: RefCell<Option<MrtNode>>,
    /// `PassNode._textureNodes` — one node per named attachment, memoised so
    /// that two `getTextureNode( name )` calls compose the *same* node and the
    /// builder sees one texture, not two.
    texture_nodes: RefCell<HashMap<String, NodeRef>>,
    /// `PassNode._viewZNodes` — memoised like the texture nodes, so two asks
    /// compose one graph.
    view_z_nodes: RefCell<HashMap<String, NodeRef>>,
    /// `PassNode._cameraNear` / `_cameraFar`: `uniform( 0 )` a piece, written
    /// from the pass's camera in `updateBefore()`. They are object-group
    /// uniforms of whatever material samples the pass, which is why the fog
    /// composite's shader reads `object.nodeUniform1` / `object.nodeUniform2`.
    camera_near: (NodeRef, SettableValue),
    camera_far: (NodeRef, SettableValue),
    /// `PassNode.autoClearDepth`.
    auto_clear_depth: bool,
    /// Whether the depth attachment is this pass's own. A pass handed another
    /// pass's depth texture must not resize it — the owner already did, and
    /// `set_size` on a shared handle would drop the contents this pass exists
    /// to read.
    owns_depth_texture: bool,
    /// `PassNode._layers`.
    layers: RefCell<Option<Layers>>,
    /// `PixelationPassNode.pixelSize` — the target is the drawing buffer's
    /// size divided by this, floored. 1 for every other pass.
    size_divisor: std::cell::Cell<u32>,
    /// `PassNode.opaque` / `.transparent` / `lighting.enabled`.
    opaque: Cell<bool>,
    transparent: Cell<bool>,
    lighting_enabled: Cell<bool>,
    /// `this.scene` / `this.camera`.
    scene: RefCell<Option<(SceneRef, CameraRef)>>,
}

/// `pass( scene, camera )`: a pass that renders `scene` through `camera`
/// whenever a draw samples it.
pub fn pass(scene: SceneRef, camera: CameraRef) -> PassNode {
    let node = PassNode::new();
    node.set_scene(scene, camera);
    node
}

/// `pass( scene, camera, options )`'s options object, as far as the ported
/// pages use it.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct PassOptions {
    /// `options.minFilter` — the pass's colour texture's minification filter.
    pub min_filter: TextureFilter,
    /// `options.magFilter` — the pass's colour texture's magnification filter.
    pub mag_filter: TextureFilter,
    /// `options.depthTexture` — `depthTexture = options.depthTexture || new
    /// DepthTexture()`. A pass given another pass's depth attachment renders
    /// *into* it, which is how `webgpu_deferred`'s transparent pass depth-tests
    /// against the opaque G-buffer it never drew.
    pub depth_texture: Option<DepthTexture>,
    /// `options.autoClearDepth`, copied onto `renderer.autoClearDepth` for the
    /// duration of the pass. `false` keeps the shared depth attachment's
    /// contents (`loadOp: "load"`).
    pub auto_clear_depth: bool,
}

impl Default for PassOptions {
    /// `RenderTarget`'s own defaults: `LinearFilter` on both sides, a fresh
    /// `DepthTexture`, and `autoClearDepth` on.
    fn default() -> Self {
        Self {
            min_filter: TextureFilter::Linear,
            mag_filter: TextureFilter::Linear,
            depth_texture: None,
            auto_clear_depth: true,
        }
    }
}

impl Default for PassNode {
    fn default() -> Self {
        Self::new()
    }
}

impl PassNode {
    /// `new PassNode( PassNode.COLOR, scene, camera )`: a 1×1 `RenderTarget`
    /// with `{ type: HalfFloatType }` plus a `DepthTexture` named `depth`,
    /// resized to the drawing buffer on the first frame.
    pub fn new() -> Self {
        Self::new_with_options(PassOptions::default())
    }

    /// `pass( scene, camera, options )` — the third argument, which three
    /// spreads over `renderTarget.texture` and so over every attachment
    /// `getTexture( name )` clones from it.
    ///
    /// The filter pair is not cosmetic: `webgpu_mrt` passes `NearestFilter` on
    /// both sides, which makes all four attachments unfilterable, and the
    /// composite shader that samples them is generated with `textureLoad` and
    /// no samplers at all (`docs/nodes.md` §23).
    pub fn new_with_options(options: PassOptions) -> Self {
        let render_target = RenderTarget::new_with_options(
            1,
            1,
            RenderTargetOptions {
                // `PassNode.setup()` then overwrites this with
                // `renderer.getOutputBufferType()`, which is `HalfFloatType`.
                texture_type: TextureType::HalfFloat,
                samples: 0,
                depth_buffer: true,
                min_filter: options.min_filter,
                mag_filter: options.mag_filter,
            },
        )
        .expect("three-rs: PassNode's render target is a HalfFloat colour type");
        render_target.set_depth_texture(options.depth_texture.clone().unwrap_or_default());

        // `getTextureNode()`'s node — the `PassTextureNode` — and the
        // `PassNode` that wraps it. Both are `TempNode`s, which is why a pass
        // *used as a value* contributes two vars and `getTextureNode()` one;
        // sharing the inner node keeps them one texture to the builder.
        let texture_node = texture_uv(&render_target.texture(), uv());
        let node = to_var(None, texture_node.clone());

        let texture_nodes = HashMap::from([(OUTPUT_ATTACHMENT.to_string(), texture_node)]);

        let camera_near = uniform_settable(Type::F32, vec![0.0]);
        let camera_far = uniform_settable(Type::F32, vec![0.0]);

        let pass = Self(Rc::new(PassState {
            render_target,
            node,
            previous_texture_nodes: RefCell::new(HashMap::new()),
            mrt: RefCell::new(None),
            texture_nodes: RefCell::new(texture_nodes),
            view_z_nodes: RefCell::new(HashMap::new()),
            camera_near,
            camera_far,
            auto_clear_depth: options.auto_clear_depth,
            owns_depth_texture: options.depth_texture.is_none(),
            layers: RefCell::new(None),
            size_divisor: std::cell::Cell::new(1),
            opaque: Cell::new(true),
            transparent: Cell::new(true),
            lighting_enabled: Cell::new(true),
            scene: RefCell::new(None),
        }));
        // `PassTextureNode.passNode`: a draw that binds one of the pass's
        // textures has the pass among its update-before nodes. The depth
        // attachment only when it is this pass's own: a pass rendering into
        // another's depth must not be taken for its producer.
        pass.link(pass.0.render_target.texture().id());
        if pass.0.owns_depth_texture {
            pass.link(pass.depth_texture().id());
        }
        pass
    }

    /// Register `texture_id` as filled by this pass's `updateBefore()`.
    fn link(&self, texture_id: usize) {
        crate::nodes::frame::register_texture_update(texture_id, &self.0);
    }

    /// `passNode.scene = scene; passNode.camera = camera` — what the pass
    /// renders from `updateBefore()`.
    pub fn set_scene(&self, scene: SceneRef, camera: CameraRef) {
        *self.0.scene.borrow_mut() = Some((scene, camera));
    }

    /// `PixelationPassNode.pixelSize = n` — the render target becomes
    /// `floor( drawingBuffer / n )` on the next render. Crate-private: only
    /// [`PixelationPassNode`](crate::nodes::display::PixelationPassNode)
    /// overrides `setSize()` in three.js.
    pub(crate) fn set_size_divisor(&self, divisor: u32) {
        self.size_divisor.set(divisor);
    }

    /// The pass's depth attachment, sampled at `coord` — the tap
    /// `getTextureNode( 'depth' ).sample( coord )` makes.
    pub(crate) fn depth_texture_node_at(&self, coord: NodeRef) -> NodeRef {
        crate::nodes::tsl::pass_depth_texture_uv(&self.depth_texture(), coord)
    }

    /// `passNode.setLayers( layers )` — the camera layer mask this pass renders
    /// with. `Layers::default()` (layer 0 only) is what `webgpu_deferred`'s
    /// opaque and transparent passes set, to keep the resolve quad on layer 2
    /// out of them.
    pub fn set_layers(&self, layers: Layers) {
        *self.layers.borrow_mut() = Some(layers);
    }

    /// `passNode.opaque` — `false` skips the opaque half of the render list,
    /// and with it the skybox.
    pub fn set_opaque(&mut self, opaque: bool) {
        self.0.opaque.set(opaque);
    }

    /// `passNode.transparent`.
    pub fn set_transparent(&mut self, transparent: bool) {
        self.0.transparent.set(transparent);
    }

    /// `passNode.lighting = new Lighting(); passNode.lighting.enabled = false`
    /// — the pass renders every material with an empty light list.
    pub fn set_lighting_enabled(&mut self, enabled: bool) {
        self.0.lighting_enabled.set(enabled);
    }

    /// `passNode.getTexture( 'depth' )` — the pass's own depth attachment.
    ///
    /// Three seeds `_textures[ 'depth' ]` in the constructor when the target
    /// has a depth buffer and throws from `getTexture()` for any other pass;
    /// here the target always has one, so this is infallible.
    pub fn depth_texture(&self) -> DepthTexture {
        self.render_target
            .depth_texture()
            .expect("three-rs: a PassNode's render target always carries a DepthTexture")
    }

    /// `passNode.getViewZNode( name )` — the depth attachment read back as a
    /// view-space z.
    ///
    /// `perspectiveDepthToViewZ( getTextureNode( name ), cameraNear,
    /// cameraFar )`. Only `'depth'` exists as a name here: a custom depth
    /// output would be an extra colour attachment, which no ported page asks
    /// for.
    pub fn view_z_node(&self, name: &str) -> NodeRef {
        if let Some(node) = self.view_z_nodes.borrow().get(name) {
            return node.clone();
        }
        assert_eq!(
            name, DEPTH_ATTACHMENT,
            "three-rs: PassNode::view_z_node only knows the 'depth' output"
        );
        let node = perspective_depth_to_view_z(
            pass_depth_texture(&self.depth_texture()),
            self.camera_near.0.clone(),
            self.camera_far.0.clone(),
        );
        self.view_z_nodes
            .borrow_mut()
            .insert(name.to_string(), node.clone());
        node
    }

    /// `passNode.setMRT( mrt )`.
    ///
    /// The names the MRT writes are *not* what creates the attachments —
    /// `getTextureNode( name )` is, exactly as in three.js, where
    /// `MRTNode.setup()` silently drops an output whose name is not among
    /// `renderTarget.textures`. `webgpu_postprocessing_bloom_selective` asks
    /// for `getTextureNode( 'bloomIntensity' )` and so gets the second
    /// attachment; a page that set the MRT and never sampled the extra output
    /// would render single-attachment, in three.js too.
    pub fn set_mrt(&self, mrt: MrtNode) {
        *self.mrt.borrow_mut() = Some(mrt);
    }

    /// `passNode.getMRT()`.
    pub fn mrt(&self) -> Option<MrtNode> {
        self.mrt.borrow().clone()
    }

    /// `passNode.getTextureNode( name )` — the node for one named colour
    /// attachment, creating the attachment on first ask
    /// (`PassNode.getTexture()`).
    ///
    /// Unlike [`PassNode::node`] this is **one** var, not two: a
    /// `PassTextureNode` is what the graph holds, and the `PassNode` it builds
    /// from its own `setup()` is then built only that once — `hasDependencies`
    /// is false, so `TempNode` gives it no var of its own. `pass( scene, camera )`
    /// used directly is the case with two, because there the graph holds the
    /// `PassNode` as well and its usage count reaches two.
    ///
    /// `getTextureNode()` with no argument is that direct use,
    /// [`PassNode::node`]; `getTextureNode( 'output' )` is this, on the same
    /// `renderTarget.textures[ 0 ]`.
    pub fn texture_node(&self, name: &str) -> NodeRef {
        if let Some(node) = self.texture_nodes.borrow().get(name) {
            return node.clone();
        }
        // `PassNode`'s constructor seeds `_textures.depth` with the depth
        // attachment, so `getTextureNode( 'depth' )` is a tap on *that* and
        // not a new colour attachment. `webgpu_deferred`'s resolve material
        // reads it for both its `discard` and its `depthNode`.
        if name == DEPTH_ATTACHMENT {
            let node = pass_depth_texture(&self.depth_texture());
            self.texture_nodes
                .borrow_mut()
                .insert(name.to_string(), node.clone());
            return node;
        }
        let texture = if name == crate::renderer::OUTPUT_ATTACHMENT {
            self.render_target.texture()
        } else {
            self.render_target.add_texture(name)
        };
        self.link(texture.id());
        let node = texture_uv(&texture, uv());
        self.texture_nodes
            .borrow_mut()
            .insert(name.to_string(), node.clone());
        node
    }

    /// `passNode.getPreviousTextureNode( name )` — the node for the frame
    /// *before* this one on that output.
    ///
    /// `PassNode.updateBefore()` calls `toggleTexture()` for every name that
    /// has one **before** it renders, so on the very first frame the scene is
    /// drawn into one of the pair and the node named "previous" points at the
    /// other, which nothing has ever rendered into: a zero-initialised
    /// texture. `webgpu_postprocessing_difference` grades exactly that frame,
    /// so its `|previous − current|` is `|0 − current|` and the whole image is
    /// a saturated version of the box. Rendering the previous buffer, or
    /// swapping in the other order, is a different picture.
    pub fn previous_texture_node(&self, name: &str) -> NodeRef {
        if let Some(node) = self.previous_texture_nodes.borrow().get(name) {
            return node.clone();
        }
        // `if ( this._textureNodes[ name ] === undefined ) this.getTextureNode(
        // name );` — the attachment has to exist before its shadow does.
        let _ = self.texture_node(name);
        let texture = self.render_target.add_previous_texture(name);
        self.link(texture.id());
        let node = texture_uv(&texture, uv());
        self.previous_texture_nodes
            .borrow_mut()
            .insert(name.to_string(), node.clone());
        node
    }

    /// `passNode.getTexture( name )`.
    pub fn texture_named(&self, name: &str) -> crate::textures::Texture {
        self.render_target.add_texture(name)
    }

    /// `passNode.getTextureNode()` — the node to compose with.
    pub fn node(&self) -> NodeRef {
        self.node.clone()
    }

    /// `pass( … ).a`.
    pub fn a(&self) -> NodeRef {
        self.node.a()
    }

    /// `renderTarget.texture`.
    pub fn texture(&self) -> crate::textures::Texture {
        self.render_target.texture()
    }

    /// `passNode.renderTarget` — the accumulator an `SSAAPassNode` clones and
    /// then draws into. `pub(crate)` because a `RenderTarget` is a handle and
    /// handing one out would let an application render into a pass's target
    /// behind its back.
    pub(crate) fn render_target(&self) -> &RenderTarget {
        &self.render_target
    }

    /// The render a pass's explicit `render()` used to do, before it was
    /// removed in 0.2.0 (`docs/api.md` decision 10): for the passes that
    /// wrap a `PassNode` and render it themselves (`SsaaPassNode`'s samples,
    /// the toon outline).
    pub(crate) fn render_scene(
        &self,
        renderer: &mut Renderer,
        scene: &mut Scene,
        camera: &mut dyn RenderCamera,
    ) {
        let (near, far) = (camera.near(), camera.far());
        self.0.render_with(renderer, near, far, |renderer| {
            renderer.render(scene, camera)
        });
    }
}

impl PassState {
    /// `PassNode.updateBefore( frame )`: size the target to the drawing buffer,
    /// then `renderer.setRenderTarget( this.renderTarget ); renderer.render(
    /// this.scene, this.camera )` with the previous target restored after.
    ///
    /// `render` is the `renderer.render( this.scene, this.camera )` call, so
    /// that a pass holding its scene in a `RefCell` can render it through a
    /// shared borrow (see [`update_before`](NodeUpdate::update_before)).
    fn render_with(
        &self,
        renderer: &mut Renderer,
        near: f64,
        far: f64,
        render: impl FnOnce(&mut Renderer),
    ) {
        let (width, height) = renderer.drawing_buffer_size();
        // `PixelationPassNode.setSize()`: `Math.floor( size / pixelSize )`
        // before `PassNode.setSize()` — a divisor of 1 is `PassNode`'s own.
        let divisor = self.size_divisor.get().max(1);
        let (width, height) = (width / divisor, height / divisor);
        self.render_target
            .set_size_keeping_depth(width, height, !self.owns_depth_texture);
        // `PassNode.setup()`: `renderTarget.samples = renderer.samples`.
        self.render_target.set_samples(renderer.samples());

        // `for ( const name in this._previousTextures ) this.toggleTexture(
        // name );` — before the render, not after.
        for name in self.previous_texture_nodes.borrow().keys() {
            self.render_target.toggle_texture(name);
        }

        // `this._cameraNear.value = camera.near; this._cameraFar.value =
        // camera.far;`
        self.camera_near.1.set(vec![near]);
        self.camera_far.1.set(vec![far]);

        let previous = renderer.render_target();
        let previous_mrt = renderer.mrt();
        let previous_auto_clear_depth = renderer.auto_clear_depth;
        let previous_opaque = renderer.opaque;
        let previous_transparent = renderer.transparent;
        let previous_lighting = renderer.lighting_enabled;
        let previous_layers = renderer.camera_layers;

        renderer.set_render_target(Some(self.render_target.clone()));
        renderer.set_mrt(self.mrt.borrow().clone());
        renderer.auto_clear_depth = self.auto_clear_depth;
        renderer.opaque = self.opaque.get();
        renderer.transparent = self.transparent.get();
        renderer.lighting_enabled = self.lighting_enabled.get();
        renderer.camera_layers = *self.layers.borrow();

        render(renderer);

        renderer.set_render_target(previous);
        renderer.set_mrt(previous_mrt);
        renderer.auto_clear_depth = previous_auto_clear_depth;
        renderer.opaque = previous_opaque;
        renderer.transparent = previous_transparent;
        renderer.lighting_enabled = previous_lighting;
        renderer.camera_layers = previous_layers;
    }
}

impl NodeUpdate for PassState {
    /// `this.updateBeforeType = NodeUpdateType.FRAME`.
    fn update_before_type(&self) -> NodeUpdateType {
        NodeUpdateType::Frame
    }

    /// `PassNode.updateBefore( frame )`. A pass with no scene has nothing to
    /// render, and does not count, so it is tried again at the next draw.
    ///
    /// The scene and camera are borrowed shared, not mutably: a pass's scene
    /// can draw a material that samples another pass over the same scene
    /// (the deferred page's resolve quad reads the opaque pass), and that
    /// nested render borrows them again while the outer one holds them.
    fn update_before(&self, renderer: &mut Renderer) -> bool {
        let Some((scene, camera)) = self.scene.borrow().clone() else {
            return false;
        };
        let (near, far) = {
            let camera = camera.borrow();
            (camera.near(), camera.far())
        };
        self.render_with(renderer, near, far, |renderer| {
            renderer.render_shared(&scene.borrow(), &camera)
        });
        true
    }

    /// `PassNode.setup()`: `renderTarget.samples = renderer.samples`, ahead
    /// of the pass's own render. A material that binds this pass's depth
    /// texture (`getViewZNode()`) is built on the same call that discovers
    /// the binding (`docs/nodes.md` §57.5), so the multisample flag the
    /// builder reads has to be right before `updateBefore()` ever runs, not
    /// after — this is what three's `setup()` does during graph analysis
    /// and `render_with` alone cannot reproduce.
    fn sync_before_build(&self, samples: u32) {
        self.render_target.set_samples(samples);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `dump-difference/dump.json` has two quad bind groups: 63, built with
    /// the previous node on texture 4, and 64 — the one pass 0 actually binds
    /// — with the current node on texture 4 (the rendered target) and the
    /// previous node on texture 59, which no pass ever writes. So the two
    /// nodes name two different textures, and only one of them is an
    /// attachment.
    ///
    /// No GPU: this is the target's own bookkeeping, before any render.
    #[test]
    fn the_previous_texture_is_never_a_colour_attachment() {
        let pass = PassNode::new();
        let current = pass.texture_node(OUTPUT_ATTACHMENT);
        let previous = pass.previous_texture_node(OUTPUT_ATTACHMENT);

        assert_ne!(current.key(), previous.key());

        let attachments: Vec<usize> = pass
            .render_target()
            .textures()
            .iter()
            .map(|texture| texture.id())
            .collect();
        assert_eq!(attachments.len(), 1);
        assert_eq!(attachments[0], pass.render_target().texture().id());

        let shadow = pass.render_target().add_previous_texture(OUTPUT_ATTACHMENT);
        assert!(!attachments.contains(&shadow.id()));
    }

    /// Both accessors are memoised, so a page that asks twice composes one
    /// node and the builder sees one texture — `_textureNodes` /
    /// `_previousTextureNodes`.
    #[test]
    fn the_texture_nodes_are_memoised() {
        let pass = PassNode::new();
        assert_eq!(
            pass.texture_node(OUTPUT_ATTACHMENT).key(),
            pass.texture_node(OUTPUT_ATTACHMENT).key()
        );
        assert_eq!(
            pass.previous_texture_node(OUTPUT_ATTACHMENT).key(),
            pass.previous_texture_node(OUTPUT_ATTACHMENT).key()
        );
    }
}