Skip to main content

three_rs/objects/
fog.rs

1//! Ports of `three.js/src/scenes/Fog.js` and `three.js/src/scenes/FogExp2.js`,
2//! and the `scene.fog` slot that holds either.
3//!
4//! three.js has two unrelated classes told apart by `isFog` / `isFogExp2`;
5//! `NodeManager.updateFog()` branches on those flags to build the fog node.
6//! The port makes the pair one enum, [`SceneFog`], so the branch is a `match`.
7//!
8//! Neither class carries any node state. The renderer turns the one in
9//! `scene.fog` into a `fog( color, factor )` node whose parameters are
10//! render-group uniforms read from the scene each frame — see
11//! [`SceneFog::node`] and `docs/nodes.md` §28 — so changing a value never
12//! rebuilds a program.
13
14use crate::math::Color;
15use crate::nodes::tsl::{density_fog_factor, fog, range_fog_factor, uniform, FogNode};
16use crate::nodes::{Type, UniformGroup, UniformSource};
17
18/// `Fog` — linear fog: none before `near`, all fog from `far` on.
19#[derive(Clone, Debug, PartialEq)]
20pub struct Fog {
21    /// `fog.name`.
22    pub name: String,
23    /// `fog.color`, in the working colour space.
24    pub color: Color,
25    /// `fog.near`.
26    pub near: f64,
27    /// `fog.far`.
28    pub far: f64,
29}
30
31impl Fog {
32    /// `new Fog( color, near, far )`.
33    pub fn new(color: Color, near: f64, far: f64) -> Self {
34        Self {
35            name: String::new(),
36            color,
37            near,
38            far,
39        }
40    }
41
42    /// `new Fog( color )` — `near = 1`, `far = 1000`.
43    pub fn with_color(color: Color) -> Self {
44        Self::new(color, 1.0, 1000.0)
45    }
46
47    /// `fog.isFog`.
48    pub fn is_fog(&self) -> bool {
49        true
50    }
51}
52
53impl Default for Fog {
54    /// `new Fog()` — `new Color( undefined )` is white.
55    fn default() -> Self {
56        Self::with_color(Color::default())
57    }
58}
59
60/// `FogExp2` — exponential squared fog of one `density`.
61#[derive(Clone, Debug, PartialEq)]
62pub struct FogExp2 {
63    /// `fog.name`.
64    pub name: String,
65    /// `fog.color`, in the working colour space.
66    pub color: Color,
67    /// `fog.density`.
68    pub density: f64,
69}
70
71impl FogExp2 {
72    /// `new FogExp2( color, density )`.
73    pub fn new(color: Color, density: f64) -> Self {
74        Self {
75            name: String::new(),
76            color,
77            density,
78        }
79    }
80
81    /// `new FogExp2( color )` — `density = 0.00025`.
82    pub fn with_color(color: Color) -> Self {
83        Self::new(color, 0.00025)
84    }
85
86    /// `fog.isFogExp2`.
87    pub fn is_fog_exp2(&self) -> bool {
88        true
89    }
90}
91
92impl Default for FogExp2 {
93    /// `new FogExp2()`.
94    fn default() -> Self {
95        Self::with_color(Color::default())
96    }
97}
98
99/// What `scene.fog` may hold: a [`Fog`] or a [`FogExp2`].
100#[derive(Clone, Debug, PartialEq)]
101pub enum SceneFog {
102    /// Linear fog, `Fog`.
103    Linear(Fog),
104    /// Exponential squared fog, `FogExp2`.
105    Exp2(FogExp2),
106}
107
108impl From<Fog> for SceneFog {
109    fn from(fog: Fog) -> Self {
110        SceneFog::Linear(fog)
111    }
112}
113
114impl From<FogExp2> for SceneFog {
115    fn from(fog: FogExp2) -> Self {
116        SceneFog::Exp2(fog)
117    }
118}
119
120impl SceneFog {
121    /// `fog.isFog`.
122    pub fn is_fog(&self) -> bool {
123        matches!(self, SceneFog::Linear(_))
124    }
125
126    /// `fog.isFogExp2`.
127    pub fn is_fog_exp2(&self) -> bool {
128        matches!(self, SceneFog::Exp2(_))
129    }
130
131    /// `fog.color`.
132    pub fn color(&self) -> Color {
133        match self {
134            SceneFog::Linear(fog) => fog.color,
135            SceneFog::Exp2(fog) => fog.color,
136        }
137    }
138
139    /// `NodeManager.updateFog( scene )`'s node for this fog:
140    ///
141    /// ```js
142    /// if ( sceneFog.isFogExp2 ) {
143    ///     const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
144    ///     const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
145    ///     return fog( color, densityFogFactor( density ) );
146    /// } else if ( sceneFog.isFog ) {
147    ///     …
148    ///     return fog( color, rangeFogFactor( near, far ) );
149    /// }
150    /// ```
151    ///
152    /// three.js caches the node per fog object (`getCacheNode( 'fog',
153    /// sceneFog, … )`) so that the program stays keyed on one node and a new
154    /// `near` is only a uniform write. The port's uniforms name *where* their
155    /// value comes from — the scene's fog, written into the render group on
156    /// every `render()` — rather than holding a reference to one object, so a
157    /// single node per kind serves every scene: it is built once per thread and
158    /// cloned, which keeps its identity (and so the program cache key) stable
159    /// across frames and across fog objects of the same kind, as three's does
160    /// across frames.
161    #[doc(hidden)]
162    pub fn node(&self) -> FogNode {
163        thread_local! {
164            static LINEAR: FogNode = fog(
165                fog_uniform(UniformSource::FogColor, Type::Vec3),
166                range_fog_factor(
167                    fog_uniform(UniformSource::FogNear, Type::F32),
168                    fog_uniform(UniformSource::FogFar, Type::F32),
169                ),
170            );
171            static EXP2: FogNode = fog(
172                fog_uniform(UniformSource::FogColor, Type::Vec3),
173                density_fog_factor(fog_uniform(UniformSource::FogDensity, Type::F32)),
174            );
175        }
176        match self {
177            SceneFog::Linear(_) => LINEAR.with(Clone::clone),
178            SceneFog::Exp2(_) => EXP2.with(Clone::clone),
179        }
180    }
181}
182
183/// `reference( name, type, sceneFog ).setGroup( renderGroup )`.
184fn fog_uniform(source: UniformSource, ty: Type) -> crate::nodes::NodeRef {
185    uniform(source, ty, UniformGroup::Render, None)
186}