three_rs/nodes/frame.rs
1//! Port of `three.js/src/nodes/core/NodeFrame.js` and the `NodeUpdateType`
2//! half of `constants.js`: the renderer-owned clock, and the three update
3//! phases a node can take part in. See `docs/nodes.md` §57.
4//!
5//! Three's `NodeFrame` is one object. It holds the clock (`time`,
6//! `deltaTime`, `frameId`, `renderId`), the three update maps, and, while an
7//! update runs, the render object being drawn. The port splits it along the
8//! borrow it needs:
9//!
10//! * [`NodeFrameState`] is the renderer's: the clock and the maps. The
11//! renderer owns one and reads it back through
12//! [`Renderer::node_frame`](crate::renderer::Renderer::node_frame).
13//! * [`NodeFrame`](crate::nodes::NodeFrame) is what an object-update uniform
14//! is handed: the render object and the occlusion results, borrowed for one
15//! draw, plus a copy of the clock (§39).
16//!
17//! A node takes part in the phases through [`NodeUpdate`]. The builder
18//! collects every such node a material reaches into its
19//! [`NodeProgram`](crate::nodes::NodeProgram), which is cached with the
20//! material, so a steady frame walks three short lists and no graph.
21
22use std::cell::RefCell;
23use std::collections::HashMap;
24use std::rc::{Rc, Weak};
25
26use crate::renderer::Renderer;
27
28/// `NodeUpdateType`: how often a phase runs for one node.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
30pub enum NodeUpdateType {
31 /// `NONE`: never.
32 #[default]
33 None,
34 /// `FRAME`: at most once per frame, however many draws reach the node.
35 Frame,
36 /// `RENDER`: at most once per `render()` call.
37 Render,
38 /// `OBJECT`: every time a draw that reaches the node is made.
39 Object,
40}
41
42/// The update half of three's `Node`: `updateBeforeType` / `updateType` /
43/// `updateAfterType` and the three methods they gate.
44///
45/// Three hands each method the `NodeFrame`, and the node reads
46/// `frame.renderer` off it. The port hands the renderer itself, and the clock
47/// is [`renderer.node_frame()`](Renderer::node_frame).
48///
49/// A method returns `false` for "this did not count", three's `=== false`:
50/// the guard is left as it was, so the phase runs again at the next chance.
51pub trait NodeUpdate {
52 /// `getUpdateBeforeType()`.
53 fn update_before_type(&self) -> NodeUpdateType {
54 NodeUpdateType::None
55 }
56 /// `getUpdateType()`.
57 fn update_type(&self) -> NodeUpdateType {
58 NodeUpdateType::None
59 }
60 /// `getUpdateAfterType()`.
61 fn update_after_type(&self) -> NodeUpdateType {
62 NodeUpdateType::None
63 }
64 /// `updateBefore( frame )`: before the draw that reaches the node. A pass
65 /// renders its scene here.
66 fn update_before(&self, _renderer: &mut Renderer) -> bool {
67 true
68 }
69 /// `update( frame )`: while the draw's bindings are updated.
70 fn update(&self, _renderer: &mut Renderer) -> bool {
71 true
72 }
73 /// `updateAfter( frame )`: after the draw.
74 fn update_after(&self, _renderer: &mut Renderer) -> bool {
75 true
76 }
77 /// Three's `PassNode.setup()` sets `renderTarget.samples = renderer.samples`
78 /// while the graph that reaches the pass is analyzed — before any pass
79 /// renders. That is what lets a composite bind the pass's depth texture
80 /// as `texture_depth_multisampled_2d` on the very build that discovers
81 /// it. The port has no per-node `setup()` hook (`docs/nodes.md` §57.2),
82 /// so [`sync_before_build`](Self::sync_before_build) stands in for it: it
83 /// runs on every node with a live texture registration, right before
84 /// [`Renderer`] builds a material's program,
85 /// which is the earliest point the builder can see a pass's textures.
86 /// [`PassNode`](crate::PassNode) is the only node that overrides it
87 /// (`docs/nodes.md` §57.5); the default is a no-op.
88 fn sync_before_build(&self, _samples: u32) {}
89}
90
91/// One entry of three's `updateBeforeNodes` / `updateNodes` /
92/// `updateAfterNodes`: the node, and `node.updateReference( frame )`, the
93/// identity its guard is kept under.
94#[derive(Clone)]
95pub(crate) struct UpdateNode {
96 pub(crate) reference: usize,
97 pub(crate) node: Rc<dyn NodeUpdate>,
98}
99
100impl UpdateNode {
101 /// An entry for `node`, guarded under its own address.
102 pub fn new<T: NodeUpdate + 'static>(node: Rc<T>) -> Self {
103 Self {
104 reference: Rc::as_ptr(&node) as *const u8 as usize,
105 node,
106 }
107 }
108
109 /// An entry guarded under `reference`, for a node that is a wrapper
110 /// around the thing that has the identity (a `CustomNode`, a
111 /// `ComputeFlow`).
112 pub(crate) fn with_reference(reference: usize, node: Rc<dyn NodeUpdate>) -> Self {
113 Self { reference, node }
114 }
115}
116
117impl std::fmt::Debug for UpdateNode {
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 f.debug_tuple("UpdateNode")
120 .field(&(self.reference as *const u8))
121 .finish()
122 }
123}
124
125/// Which of the three maps a guard lives in.
126#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
127pub(crate) enum UpdatePhase {
128 Before,
129 Update,
130 After,
131}
132
133/// `{ renderId, frameId }`, one per node per phase (`_getMaps()`).
134#[derive(Clone, Copy, Debug, Default)]
135struct Stamp {
136 frame_id: u64,
137 render_id: u64,
138 /// The frame the entry was last claimed in, for [`NodeFrameState::sweep`].
139 touched: u64,
140}
141
142/// A phase that [`NodeFrameState::claim`] let through. Hand it back to
143/// [`NodeFrameState::settle`] with what the method returned.
144#[must_use]
145#[derive(Debug)]
146pub(crate) struct Claim {
147 phase: UpdatePhase,
148 reference: usize,
149 ty: NodeUpdateType,
150 previous: Stamp,
151}
152
153/// Three's `NodeFrame`, the renderer's half: the clock and the update maps.
154#[derive(Debug, Default)]
155pub struct NodeFrameState {
156 /// `frameId`: incremented by [`update`](Self::update), once per frame.
157 pub frame_id: u64,
158 /// `renderId`: which `render()` call is running. Three sets it to
159 /// `info.calls` and puts the previous value back when a nested render
160 /// returns, so a pass rendered from inside a draw does not change the
161 /// outer render's id.
162 pub render_id: u64,
163 /// `time`, in seconds — what the TSL `time` node reads.
164 pub time: f64,
165 /// `deltaTime` — the last update's step.
166 pub delta_time: f64,
167 /// `lastTime` — `undefined` until the first frame, which is what makes
168 /// that frame's delta 0 whatever the clock says.
169 last_time: Option<f64>,
170 /// The count `render_id` is taken from: never reset, unlike `info.calls`.
171 renders: u64,
172 /// Whether a frame has been opened by a render and not yet closed by a
173 /// render to the screen. See [`begin_render`](Self::begin_render).
174 open: bool,
175 /// `updateBeforeMap` / `updateMap` / `updateAfterMap`, keyed on the
176 /// update reference.
177 maps: HashMap<(UpdatePhase, usize), Stamp>,
178 /// `VelocityNode`'s and `Skinning.js`' previous-frame data: each object's
179 /// last `matrixWorld`, each camera's last view and projection, each
180 /// skeleton's last bones. Empty — and never walked — until a draw binds a
181 /// velocity uniform. See [`crate::nodes::velocity`].
182 pub(crate) velocity: crate::nodes::velocity::VelocityState,
183}
184
185impl NodeFrameState {
186 /// `NodeFrame.update()`:
187 ///
188 /// ```js
189 /// this.frameId ++;
190 /// if ( this.lastTime === undefined ) this.lastTime = performance.now();
191 /// this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
192 /// this.lastTime = performance.now();
193 /// this.time += this.deltaTime;
194 /// ```
195 ///
196 /// `now` is in milliseconds, as `performance.now()` is.
197 pub fn update(&mut self, now: f64) {
198 self.frame_id += 1;
199 let last = *self.last_time.get_or_insert(now);
200 self.delta_time = (now - last) / 1000.0;
201 self.time += self.delta_time;
202 self.last_time = Some(now);
203 }
204
205 /// The start of a `render()` or `render_quad()`: open a frame if none is
206 /// open (three's animation loop calls `update()` once per display frame,
207 /// before any render of it), then take a new render id. Returns the id
208 /// to put back with [`end_render`](Self::end_render).
209 pub(crate) fn begin_render(&mut self, now: f64) -> u64 {
210 self.open(now);
211 self.renders += 1;
212 std::mem::replace(&mut self.render_id, self.renders)
213 }
214
215 /// Open a frame if none is open, as the first render of one does.
216 pub(crate) fn open(&mut self, now: f64) {
217 if !self.open {
218 self.update(now);
219 self.open = true;
220 }
221 }
222
223 /// The end of a render: put the outer render's id back, and close the
224 /// frame if this render drew to the screen. The port has no animation
225 /// loop to mark frames, and a render to the screen is the last thing a
226 /// frame does, so that is where one ends. Renders into a target — a
227 /// pass's scene, a bloom's quads — belong to the frame they are part of.
228 pub(crate) fn end_render(&mut self, previous_render_id: u64, to_screen: bool) {
229 self.render_id = previous_render_id;
230 if to_screen {
231 self.open = false;
232 }
233 }
234
235 /// The guard half of `updateBeforeNode()` / `updateNode()` /
236 /// `updateAfterNode()`: `Some` if the phase should run now.
237 ///
238 /// For `updateBefore` three writes the stamp first and puts the old one
239 /// back if the method returns `false`; for the other two it writes the
240 /// stamp only once the method has returned something else. Either way
241 /// the stamp the map ends up with is the same, except while the method
242 /// runs: a pass's nested render that reaches the same node again finds
243 /// its before-guard already taken, which is what stops a pass sampling
244 /// itself from recursing. [`settle`](Self::settle) does the rest.
245 pub(crate) fn claim(
246 &mut self,
247 phase: UpdatePhase,
248 reference: usize,
249 ty: NodeUpdateType,
250 ) -> Option<Claim> {
251 let (frame_id, render_id) = (self.frame_id, self.render_id);
252 let stamp = self.maps.entry((phase, reference)).or_default();
253 stamp.touched = frame_id;
254 let previous = *stamp;
255 match ty {
256 NodeUpdateType::None => return None,
257 NodeUpdateType::Frame if stamp.frame_id == frame_id => return None,
258 NodeUpdateType::Render if stamp.render_id == render_id => return None,
259 NodeUpdateType::Frame if phase == UpdatePhase::Before => stamp.frame_id = frame_id,
260 NodeUpdateType::Render if phase == UpdatePhase::Before => stamp.render_id = render_id,
261 _ => {}
262 }
263 Some(Claim {
264 phase,
265 reference,
266 ty,
267 previous,
268 })
269 }
270
271 /// The rest of a claimed phase, given what the method returned.
272 pub(crate) fn settle(&mut self, claim: Claim, counted: bool) {
273 let (frame_id, render_id) = (self.frame_id, self.render_id);
274 let Some(stamp) = self.maps.get_mut(&(claim.phase, claim.reference)) else {
275 return;
276 };
277 match (claim.phase, counted) {
278 (UpdatePhase::Before, false) => *stamp = claim.previous,
279 (UpdatePhase::Before, true) => {}
280 (_, false) => {}
281 (_, true) => match claim.ty {
282 NodeUpdateType::Frame => stamp.frame_id = frame_id,
283 NodeUpdateType::Render => stamp.render_id = render_id,
284 NodeUpdateType::None | NodeUpdateType::Object => {}
285 },
286 }
287 }
288
289 /// Drop the stamps no node has touched for `grace` frames, so a consumer
290 /// that makes new passes every frame does not grow the maps.
291 pub(crate) fn sweep(&mut self, grace: u64) {
292 let cutoff = self.frame_id.saturating_sub(grace);
293 self.maps.retain(|_, stamp| stamp.touched >= cutoff);
294 self.velocity.sweep(self.frame_id, grace);
295 }
296}
297
298/// A [`TEXTURE_UPDATES`] entry: the node's update reference, and the node.
299type TextureUpdate = (usize, Weak<dyn NodeUpdate>);
300
301thread_local! {
302 /// Which node fills a texture from its `updateBefore()`, by texture id:
303 /// `PassTextureNode.passNode`, and `RTTNode` being the `TextureNode` of
304 /// its own target. The port's texture node is a bare
305 /// [`Node::Texture`](crate::nodes::Node::Texture) over the texture, so the
306 /// link sits beside the texture instead of on the node. Weak: the pass
307 /// is kept alive by whoever made it, as the example's `App` does.
308 static TEXTURE_UPDATES: RefCell<HashMap<usize, TextureUpdate>> =
309 RefCell::new(HashMap::new());
310}
311
312/// Mark `texture_id` as filled by `node`'s `updateBefore()`: any material
313/// that binds the texture has `node` among its update-before nodes.
314pub(crate) fn register_texture_update<T: NodeUpdate + 'static>(texture_id: usize, node: &Rc<T>) {
315 let reference = Rc::as_ptr(node) as *const u8 as usize;
316 let node: Rc<dyn NodeUpdate> = node.clone();
317 let weak = Rc::downgrade(&node);
318 TEXTURE_UPDATES.with(|map| {
319 let mut map = map.borrow_mut();
320 map.retain(|_, (_, weak)| weak.strong_count() > 0);
321 map.insert(texture_id, (reference, weak));
322 });
323}
324
325/// The node that fills `texture_id`, if one is registered and alive.
326pub(crate) fn texture_update(texture_id: usize) -> Option<UpdateNode> {
327 TEXTURE_UPDATES.with(|map| {
328 let (reference, weak) = map.borrow().get(&texture_id)?.clone();
329 Some(UpdateNode::with_reference(reference, weak.upgrade()?))
330 })
331}
332
333/// [`NodeUpdate::sync_before_build`] on every live registered node, ahead of
334/// a material build. Cheap and idempotent (`RenderTarget::set_samples`
335/// returns early once a target is already at `samples`), so calling it on
336/// every cache miss — the only time a build runs — costs nothing on a
337/// steady frame.
338pub(crate) fn sync_before_build(samples: u32) {
339 TEXTURE_UPDATES.with(|map| {
340 for (_, weak) in map.borrow().values() {
341 if let Some(node) = weak.upgrade() {
342 node.sync_before_build(samples);
343 }
344 }
345 });
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 /// A node's guard across two frames, each of two renders, each of two
353 /// draws of the node: the phases run in three's order, `FRAME` once a
354 /// frame, `RENDER` once a render and `OBJECT` every draw.
355 #[test]
356 fn two_frames_run_the_phases_in_order_behind_their_guards() {
357 let mut frame = NodeFrameState::default();
358 let mut log: Vec<(u64, u64, &str)> = Vec::new();
359
360 // One node per update type in each phase, keyed apart.
361 let nodes = [
362 (1usize, NodeUpdateType::Frame, "frame"),
363 (2, NodeUpdateType::Render, "render"),
364 (3, NodeUpdateType::Object, "object"),
365 ];
366
367 for _frame in 0..2 {
368 for render in 0..2 {
369 let to_screen = render == 1;
370 let previous = frame.begin_render(0.0);
371 for _draw in 0..2 {
372 // `_renderObjectDirect`: updateBefore, update, draw,
373 // updateAfter.
374 for (phase, name) in [
375 (UpdatePhase::Before, "before"),
376 (UpdatePhase::Update, "update"),
377 ] {
378 for (reference, ty, kind) in nodes {
379 if let Some(claim) = frame.claim(phase, reference, ty) {
380 log.push((frame.frame_id, frame.render_id, name));
381 log.push((frame.frame_id, frame.render_id, kind));
382 frame.settle(claim, true);
383 }
384 }
385 }
386 log.push((frame.frame_id, frame.render_id, "draw"));
387 for (reference, ty, kind) in nodes {
388 if let Some(claim) = frame.claim(UpdatePhase::After, reference, ty) {
389 log.push((frame.frame_id, frame.render_id, "after"));
390 log.push((frame.frame_id, frame.render_id, kind));
391 frame.settle(claim, true);
392 }
393 }
394 }
395 frame.end_render(previous, to_screen);
396 }
397 }
398
399 let count = |f: u64, what: &str, kind: &str| {
400 log.windows(2)
401 .filter(|w| w[0].0 == f && w[0].2 == what && w[1].2 == kind)
402 .count()
403 };
404 for f in [1, 2] {
405 for what in ["before", "update", "after"] {
406 assert_eq!(count(f, what, "frame"), 1, "{what} FRAME in frame {f}");
407 assert_eq!(count(f, what, "render"), 2, "{what} RENDER in frame {f}");
408 assert_eq!(count(f, what, "object"), 4, "{what} OBJECT in frame {f}");
409 }
410 }
411 // Two frames, not four: the render into a target does not close one.
412 assert_eq!(frame.frame_id, 2);
413
414 // Order within the first draw of the first frame.
415 let first: Vec<&str> = log
416 .iter()
417 .take_while(|entry| entry.2 != "draw")
418 .map(|entry| entry.2)
419 .collect();
420 assert_eq!(
421 first,
422 [
423 "before", "frame", "before", "render", "before", "object", "update", "frame",
424 "update", "render", "update", "object"
425 ]
426 );
427 let after_draw = log.iter().position(|e| e.2 == "draw").unwrap();
428 assert_eq!(log[after_draw + 1].2, "after");
429 }
430
431 /// `=== false` leaves the guard as it was, so the phase runs again at the
432 /// next draw of the same frame; a nested claim of a before-phase that is
433 /// running is refused.
434 #[test]
435 fn a_phase_that_does_not_count_runs_again() {
436 let mut frame = NodeFrameState::default();
437 let previous = frame.begin_render(0.0);
438
439 let claim = frame
440 .claim(UpdatePhase::Before, 7, NodeUpdateType::Frame)
441 .expect("first claim");
442 // Re-entered while it runs: refused.
443 assert!(frame
444 .claim(UpdatePhase::Before, 7, NodeUpdateType::Frame)
445 .is_none());
446 frame.settle(claim, false);
447 let claim = frame
448 .claim(UpdatePhase::Before, 7, NodeUpdateType::Frame)
449 .expect("runs again after a false");
450 frame.settle(claim, true);
451 assert!(frame
452 .claim(UpdatePhase::Before, 7, NodeUpdateType::Frame)
453 .is_none());
454
455 let claim = frame
456 .claim(UpdatePhase::After, 8, NodeUpdateType::Frame)
457 .unwrap();
458 frame.settle(claim, false);
459 assert!(frame
460 .claim(UpdatePhase::After, 8, NodeUpdateType::Frame)
461 .is_some());
462 frame.end_render(previous, true);
463 }
464
465 /// A render nested inside another gets its own id and hands the outer
466 /// one back, as three's `renderId = previousRenderId` does.
467 #[test]
468 fn a_nested_render_restores_the_render_id() {
469 let mut frame = NodeFrameState::default();
470 let outer = frame.begin_render(0.0);
471 let outer_id = frame.render_id;
472 let inner = frame.begin_render(0.0);
473 assert_ne!(frame.render_id, outer_id);
474 frame.end_render(inner, false);
475 assert_eq!(frame.render_id, outer_id);
476 frame.end_render(outer, true);
477 assert_eq!(frame.frame_id, 1);
478 }
479}