Skip to main content

three_rs/nodes/tsl/
utils.rs

1//! The utils family of TSL (sweep 4): the context helpers from
2//! `ContextNode.js` (`uniformFlow`, `setName`, `label`), `BypassNode`,
3//! `VaryingNode`'s `vertexStage`, the leftover `Packing.js` functions,
4//! `ExpressionNode`, `DebugNode`, `SampleNode`, `CodeNode`'s raw `wgsl()` and
5//! the `EventNode` hooks. Each item's doc comment names the JS it ports; the
6//! WGSL the shader-emitting ones produce is pinned against three's own dump in
7//! `tests/nodes_tsl_batch.rs`.
8
9use std::rc::Rc;
10use std::sync::atomic::{AtomicUsize, Ordering};
11
12use super::{block, context, custom, dot, float, pack_normal_to_rgb, sqrt, to_varying, uv};
13use crate::nodes::code::CodeDef;
14use crate::nodes::node::{ContextValue, CustomNode, DebugCallback, Node, NodeRef, Type};
15use crate::nodes::{NodeBuilder, NodeUpdateType};
16use crate::renderer::Renderer;
17
18// ---------------------------------------------------------------------------
19// context helpers (`ContextNode.js`)
20// ---------------------------------------------------------------------------
21
22/// `uniformFlow( node )` — `context( node, { uniformFlow: true } )`. Inside
23/// it a two-branch [`select`](NodeRef::select) is built as WGSL's `select( else,
24/// if, cond )`, both branches evaluated, instead of an `if`/`else` writing a
25/// var — what a derivative or texture sample needs to stay in uniform control
26/// flow. Three still declares the var the `if` form would have used and
27/// leaves it unassigned; so does the port, which keeps the numbering of every
28/// later var the same as three's.
29pub fn uniform_flow(node: impl Into<NodeRef>) -> NodeRef {
30    context(node, ContextValue::default().uniform_flow(true))
31}
32
33/// `setName( node, name )` — `context( node, { nodeName: name } )`. The first
34/// `uniform()` built inside takes `name` unless it has a name of its own
35/// (`this.name || builder.context.nodeName` in `UniformNode.generate()`).
36/// Either way the build consumes the key, as three's `delete
37/// builder.context.nodeName` does, so any later uniform in the same context
38/// is numbered as usual. Three also reads the key in
39/// `BufferAttributeNode.generate()`; the port's instanced attributes do not
40/// (`docs/nodes.md` §70.1).
41///
42/// This is the free function. The method [`NodeRef::set_name`] on a uniform is
43/// three's `UniformNode.setName()`, which renames in place instead.
44pub fn set_name(node: impl Into<NodeRef>, name: &'static str) -> NodeRef {
45    context(node, ContextValue::default().node_name(name))
46}
47
48/// `label( node, name )` — deprecated in three (r179) for [`set_name`], which
49/// it calls.
50#[deprecated(note = "three.js r179 renamed `label()` to `setName()`; use `set_name`")]
51pub fn label(node: impl Into<NodeRef>, name: &'static str) -> NodeRef {
52    set_name(node, name)
53}
54
55// ---------------------------------------------------------------------------
56// BypassNode, vertexStage
57// ---------------------------------------------------------------------------
58
59/// `bypass( outputNode, callNode )` — `BypassNode.generate()`: `callNode` is
60/// built as a statement (`build( builder, 'void' )`, its line added to the
61/// flow when it has one), and the value is `outputNode`'s. A second read in
62/// the same scope is the cached snippet, not a second run of the call.
63pub fn bypass(output: impl Into<NodeRef>, call: impl Into<NodeRef>) -> NodeRef {
64    block(vec![call.into()], output.into())
65}
66
67/// `vertexStage( node )` — `varying( node )`: `node` computed in the vertex
68/// stage and read through an unnamed varying.
69pub fn vertex_stage(node: impl Into<NodeRef>) -> NodeRef {
70    to_varying(None, node.into())
71}
72
73// ---------------------------------------------------------------------------
74// Packing.js
75// ---------------------------------------------------------------------------
76
77/// `unpackNormal( xy )` — the `z` of a unit normal whose `xy` a two-channel
78/// normal map stores: `vec3( xy, sqrt( saturate( 1 - dot( xy, xy ) ) ) )`.
79pub fn unpack_normal(xy: impl Into<NodeRef>) -> NodeRef {
80    let xy = xy.into();
81    let z = sqrt(float(1.0).sub(dot(xy.clone(), xy.clone())).saturate());
82    super::vec3_join(vec![xy, z])
83}
84
85/// `directionToColor( node )` — deprecated in three (r185) for
86/// [`pack_normal_to_rgb`], which it calls.
87#[deprecated(note = "three.js r185 renamed `directionToColor()` to `packNormalToRGB()`")]
88pub fn direction_to_color(node: impl Into<NodeRef>) -> NodeRef {
89    pack_normal_to_rgb(node.into())
90}
91
92/// `unpackRGBToNormal( node )` — `node * 2 - 1`, the inverse of
93/// [`pack_normal_to_rgb`]: a colour back to the unit direction it stores.
94pub fn unpack_rgb_to_normal(node: impl Into<NodeRef>) -> NodeRef {
95    node.into().mul(2.0).sub(1.0)
96}
97
98/// `colorToDirection( node )` — deprecated in three (r185) for
99/// [`unpack_rgb_to_normal`], which it calls.
100#[deprecated(note = "three.js r185 renamed `colorToDirection()` to `unpackRGBToNormal()`")]
101pub fn color_to_direction(node: impl Into<NodeRef>) -> NodeRef {
102    unpack_rgb_to_normal(node)
103}
104
105// ---------------------------------------------------------------------------
106// ExpressionNode, DebugNode
107// ---------------------------------------------------------------------------
108
109/// `expression( snippet, type )` — `ExpressionNode`: a value of type `ty` is
110/// `snippet` itself, verbatim; a [`Type::Void`] one is a statement, the
111/// snippet as a flow line ending in `;` (nothing for an empty snippet). Never
112/// cached: every read is the snippet again.
113pub fn expression(snippet: &str, ty: Type) -> NodeRef {
114    NodeRef::new(Node::Expression {
115        snippet: snippet.into(),
116        ty,
117    })
118}
119
120/// `debug( node, callback )` — `DebugNode`: `node`'s value, unchanged. When it
121/// is generated its snippet is handed to `callback` along with the stage and
122/// the flow emitted so far ([`DebugInfo`](crate::nodes::DebugInfo)); with no callback the same thing
123/// is written to stderr in three's `// #--- TSL debug - … shader ---#`
124/// format, where three's goes to `console.log`.
125pub fn debug(node: impl Into<NodeRef>, callback: Option<DebugCallback>) -> NodeRef {
126    NodeRef::new(Node::Debug {
127        node: node.into(),
128        callback,
129    })
130}
131
132// ---------------------------------------------------------------------------
133// SampleNode
134// ---------------------------------------------------------------------------
135
136type SampleCallback = Rc<dyn Fn(NodeRef) -> NodeRef>;
137
138/// `SampleNode` — a node that is a function of a uv: in a graph it is the
139/// callback at `uv()`, and [`sample`](Self::sample) calls it at any other.
140/// What a `NodeMaterial` hands a post-processing pass as "the thing to
141/// sample".
142///
143/// Three's `sample( callback, uv )` also takes a uv, stores it as `uvNode`
144/// and never reads it; the port leaves it out.
145#[derive(Clone)]
146pub struct SampleNode {
147    callback: SampleCallback,
148    node: NodeRef,
149}
150
151impl std::fmt::Debug for SampleNode {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.debug_struct("SampleNode").finish_non_exhaustive()
154    }
155}
156
157struct SampleSetup {
158    callback: SampleCallback,
159    ty: Type,
160}
161
162impl CustomNode for SampleSetup {
163    fn type_name(&self) -> &'static str {
164        "SampleNode"
165    }
166    fn node_type(&self) -> Type {
167        self.ty
168    }
169    fn is_cacheable(&self) -> bool {
170        false
171    }
172    fn setup(&self, _builder: &NodeBuilder) -> NodeRef {
173        (self.callback)(uv())
174    }
175}
176
177impl SampleNode {
178    /// `sampleNode.sample( uv )`: the callback at `uv`.
179    pub fn sample(&self, uv: impl Into<NodeRef>) -> NodeRef {
180        (self.callback)(uv.into())
181    }
182
183    /// The node itself: `setup()`'s `this.sample( uv() )`.
184    pub fn node(&self) -> NodeRef {
185        self.node.clone()
186    }
187}
188
189impl From<&SampleNode> for NodeRef {
190    fn from(node: &SampleNode) -> Self {
191        node.node()
192    }
193}
194
195impl From<SampleNode> for NodeRef {
196    fn from(node: SampleNode) -> Self {
197        node.node
198    }
199}
200
201/// `sample( callback )` — see [`SampleNode`].
202pub fn sample(callback: impl Fn(NodeRef) -> NodeRef + 'static) -> SampleNode {
203    let callback: SampleCallback = Rc::new(callback);
204    // The port types nodes eagerly, so the callback runs once here to learn
205    // the type of what it returns; `setup()` runs it again at each build.
206    let ty = callback(uv()).ty();
207    let node = custom(SampleSetup {
208        callback: callback.clone(),
209        ty,
210    });
211    SampleNode { callback, node }
212}
213
214// ---------------------------------------------------------------------------
215// CodeNode
216// ---------------------------------------------------------------------------
217
218/// `wgsl( code, includes )` — a raw `CodeNode`: `code` lands in `// codes`
219/// verbatim, after whatever `includes` declare, and the node itself is
220/// nothing. It is what a [`wgsl_fn`](super::wgsl_fn)'s `includes` list takes
221/// to put a helper the WGSL calls, or any other module-scope declaration, in
222/// front of it. Unlike `wgslFn`, nothing is parsed: the snippet may hold any
223/// number of declarations, and is emitted once per `wgsl()` node however
224/// often it is reached.
225pub fn wgsl(code: &str, includes: Vec<NodeRef>) -> NodeRef {
226    static NEXT: AtomicUsize = AtomicUsize::new(0);
227    // `getCodeFromNode( this )` keys the code by node; the port's `// codes`
228    // are keyed by name, so each raw snippet gets one no declaration can have.
229    let name = format!("#wgsl{}", NEXT.fetch_add(1, Ordering::Relaxed));
230    super::code(&Rc::new(CodeDef {
231        name,
232        code: code.to_string(),
233        params: Vec::new(),
234        ret: Type::Void,
235        includes,
236    }))
237}
238
239// ---------------------------------------------------------------------------
240// EventNode
241// ---------------------------------------------------------------------------
242
243/// When an [`EventNode`]'s callback runs: `EventNode.OBJECT` and the rest.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245enum EventType {
246    Object,
247    Material,
248    Frame,
249    AfterObject,
250    BeforeObject,
251    BeforeMaterial,
252    BeforeFrame,
253}
254
255/// `EventNode` — a `void` node that emits nothing and runs a callback in one
256/// of the renderer's update phases, for as long as a material that reaches
257/// it is drawn. Built by the `on_*` functions below; attached to a graph with
258/// [`NodeRef::bypass`], as three's `.toStack()` would inside a `Fn()`.
259///
260/// The callback gets the [`Renderer`], what every update hook in the port
261/// gets, where three's gets the `NodeFrame` with the object and material
262/// being drawn.
263struct EventNode {
264    event: EventType,
265    callback: Box<dyn Fn(&mut Renderer)>,
266}
267
268impl EventNode {
269    fn phase(&self, before: bool, after: bool) -> NodeUpdateType {
270        use EventType::*;
271        match (self.event, before, after) {
272            (Object, false, false) | (AfterObject, false, true) | (BeforeObject, true, false) => {
273                NodeUpdateType::Object
274            }
275            (Material, false, false) | (BeforeMaterial, true, false) => NodeUpdateType::Render,
276            (Frame, false, false) | (BeforeFrame, true, false) => NodeUpdateType::Frame,
277            _ => NodeUpdateType::None,
278        }
279    }
280}
281
282impl CustomNode for EventNode {
283    fn type_name(&self) -> &'static str {
284        "EventNode"
285    }
286    fn node_type(&self) -> Type {
287        Type::Void
288    }
289    fn is_cacheable(&self) -> bool {
290        false
291    }
292    fn setup(&self, _builder: &NodeBuilder) -> NodeRef {
293        // `Node.setup()` with no children: nothing to build.
294        expression("", Type::Void)
295    }
296    fn update_before_type(&self) -> NodeUpdateType {
297        self.phase(true, false)
298    }
299    fn update_type(&self) -> NodeUpdateType {
300        self.phase(false, false)
301    }
302    fn update_after_type(&self) -> NodeUpdateType {
303        self.phase(false, true)
304    }
305    fn update_before(&self, renderer: &mut Renderer) -> bool {
306        (self.callback)(renderer);
307        true
308    }
309    fn update(&self, renderer: &mut Renderer) -> bool {
310        (self.callback)(renderer);
311        true
312    }
313    fn update_after(&self, renderer: &mut Renderer) -> bool {
314        (self.callback)(renderer);
315        true
316    }
317}
318
319fn event(event: EventType, callback: impl Fn(&mut Renderer) + 'static) -> NodeRef {
320    custom(EventNode {
321        event,
322        callback: Box::new(callback),
323    })
324}
325
326/// `OnObjectUpdate( callback )` — `updateType = OBJECT`: once per draw of an
327/// object whose material reaches the node.
328pub fn on_object_update(callback: impl Fn(&mut Renderer) + 'static) -> NodeRef {
329    event(EventType::Object, callback)
330}
331
332/// `OnMaterialUpdate( callback )` — `updateType = RENDER`: once per
333/// `render()` call that draws the material.
334pub fn on_material_update(callback: impl Fn(&mut Renderer) + 'static) -> NodeRef {
335    event(EventType::Material, callback)
336}
337
338/// `OnFrameUpdate( callback )` — `updateType = FRAME`: once per frame.
339pub fn on_frame_update(callback: impl Fn(&mut Renderer) + 'static) -> NodeRef {
340    event(EventType::Frame, callback)
341}
342
343/// `OnAfterObjectUpdate( callback )` — `updateAfterType = OBJECT`: after each
344/// draw.
345pub fn on_after_object_update(callback: impl Fn(&mut Renderer) + 'static) -> NodeRef {
346    event(EventType::AfterObject, callback)
347}
348
349/// `OnBeforeObjectUpdate( callback )` — `updateBeforeType = OBJECT`: before
350/// each draw.
351pub fn on_before_object_update(callback: impl Fn(&mut Renderer) + 'static) -> NodeRef {
352    event(EventType::BeforeObject, callback)
353}
354
355/// `OnBeforeMaterialUpdate( callback )` — `updateBeforeType = RENDER`.
356pub fn on_before_material_update(callback: impl Fn(&mut Renderer) + 'static) -> NodeRef {
357    event(EventType::BeforeMaterial, callback)
358}
359
360/// `OnBeforeFrameUpdate( callback )` — `updateBeforeType = FRAME`.
361pub fn on_before_frame_update(callback: impl Fn(&mut Renderer) + 'static) -> NodeRef {
362    event(EventType::BeforeFrame, callback)
363}
364
365// ---------------------------------------------------------------------------
366// method chaining
367// ---------------------------------------------------------------------------
368
369/// The method form of `setName`: `UniformNode.setName()` on a uniform, the
370/// `ContextNode.js` chaining on anything else.
371fn rename_or_set_name(node: &NodeRef, name: &'static str) -> NodeRef {
372    if let Node::Uniform(u) = node.node() {
373        u.name.set(Some(name));
374        return node.clone();
375    }
376    set_name(node, name)
377}
378
379impl NodeRef {
380    /// `node.bypass( call )` — see [`bypass`].
381    pub fn bypass(&self, call: impl Into<NodeRef>) -> NodeRef {
382        bypass(self, call)
383    }
384
385    /// `node.uniformFlow()` — see [`uniform_flow`].
386    pub fn uniform_flow(&self) -> NodeRef {
387        uniform_flow(self)
388    }
389
390    /// `node.setName( name )`. Three has two: on a uniform it is
391    /// `UniformNode.setName()`, which renames the node in place and returns
392    /// it, so every reference to the uniform takes `name` and a second
393    /// `setName` wins over the first. On any other node it is the method
394    /// chaining of the free [`set_name`], a context.
395    pub fn set_name(&self, name: &'static str) -> NodeRef {
396        rename_or_set_name(self, name)
397    }
398
399    /// `node.label( name )` — deprecated in three for
400    /// [`set_name`](Self::set_name), with the same two forms.
401    #[deprecated(note = "three.js r179 renamed `label()` to `setName()`; use `set_name`")]
402    pub fn label(&self, name: &'static str) -> NodeRef {
403        rename_or_set_name(self, name)
404    }
405
406    /// `node.toVertexStage()` — see [`vertex_stage`].
407    pub fn to_vertex_stage(&self) -> NodeRef {
408        vertex_stage(self)
409    }
410
411    /// `node.debug( callback )` — see [`debug`].
412    pub fn debug(&self, callback: Option<DebugCallback>) -> NodeRef {
413        debug(self, callback)
414    }
415}