three_rs/objects/scene.rs
1//! Port of `three.js/src/scenes/Scene.js` (rung 2 subset).
2
3use crate::core::{Object3D, ObjectRef, SceneRenderHook};
4use crate::materials::MeshBasicNodeMaterial;
5use crate::math::{Color, Matrix4};
6use crate::nodes::tsl::FogNode;
7use crate::textures::CubeTexture;
8
9/// `Scene.background`. three.js accepts a `Color`, a `Texture` or a
10/// `CubeTexture`; `Background.update()` branches on which one it is — a colour
11/// becomes the clear value, anything else becomes the skybox mesh.
12#[derive(Clone, Debug)]
13#[non_exhaustive]
14pub enum Background {
15 /// A flat clear colour.
16 Color(Color),
17 /// A skybox drawn from a cube texture.
18 CubeTexture(CubeTexture),
19 /// `scene.backgroundNode = …` — `Background.update()`'s
20 /// `background.isNode` branch, which draws the skybox sphere with
21 /// `vec4( node ).mul( backgroundIntensity )` instead of clearing. Held in
22 /// the same slot because `nodes.getBackgroundNode( scene ) ||
23 /// scene.background` makes the node win over a plain background.
24 ///
25 /// Any node, not just a `color()`: `webgpu_skinning` uses
26 /// `screenUV.y.mix( color( 0x66bbff ), color( 0x4466ff ) )`.
27 Node(crate::nodes::NodeRef),
28 /// `scene.background = <the texture of a generated PMREM>`.
29 ///
30 /// Upstream this is the PMREM cube render target's texture, flagged
31 /// `isPMREMTexture`; `NodeManager.getBackgroundNode()` turns it into
32 /// `pmremTexture( background )` and `Background.update()` wraps that in
33 /// the node branch's context — `getUV` is `backgroundRotation.mul(
34 /// normalWorldGeometry )` and `getTextureLevel` is `backgroundBlurriness`.
35 /// The port carries the handle rather than the texture, because the
36 /// `maxLod` uniform the read needs travels with it; the renderer builds the
37 /// node, so an application writes the one line the page does.
38 Pmrem(crate::materials::environment::PmremHandle),
39 /// `scene.backgroundNode = <a graph of pmremTexture()s>` —
40 /// `webgpu_cubemap_mix`'s `mix( pmremTexture( cube2 ), pmremTexture(
41 /// cube1 ), … )`. `Background.update()` builds it under the same context
42 /// as [`Background::Pmrem`].
43 EnvironmentNode(crate::materials::environment::EnvironmentNode),
44}
45
46impl From<Color> for Background {
47 fn from(color: Color) -> Self {
48 Background::Color(color)
49 }
50}
51
52impl From<CubeTexture> for Background {
53 fn from(texture: CubeTexture) -> Self {
54 Background::CubeTexture(texture)
55 }
56}
57
58/// `Scene extends Object3D`.
59///
60/// The `Object3D` half is a real scene-graph [`ObjectRef`], so the tree under a scene
61/// is the tree the renderer walks: `Group`s, lights and their children all
62/// nest, and `Renderer::render` collects drawables with
63/// `crate::renderer::project_object`. The fields below are what `Scene` adds
64/// to `Object3D`; they are not a `Payload` variant because nothing in the
65/// renderer's traversal branches on them.
66pub struct Scene {
67 /// The scene root. `node.borrow().is_scene` is true.
68 pub node: ObjectRef,
69 /// `scene.background`.
70 pub background: Option<Background>,
71 /// `scene.backgroundBlurriness` — the roughness the background's PMREM is
72 /// read at, in `[ 0, 1 ]`. Three reads it through `backgroundBlurriness`,
73 /// the render-group uniform `BackgroundNode` puts on `getTextureLevel`, so
74 /// changing it is a uniform write and not a new program.
75 pub background_blurriness: f64,
76 /// `scene.backgroundIntensity` — the factor `BackgroundNode` multiplies
77 /// the background colour by. Like [`Scene::background_blurriness`] it is
78 /// a render-group uniform, so changing it is a uniform write.
79 pub background_intensity: f64,
80 /// `scene.environmentIntensity` — the factor `EnvironmentNode` scales the
81 /// radiance and irradiance of [`Scene::environment`] (or
82 /// [`Scene::environment_node`]) by, on every material that takes the
83 /// scene's environment instead of carrying its own. A material with its
84 /// own `pmrem_env` reads `envMapIntensity` instead, which the port keeps
85 /// at 1.
86 pub environment_intensity: f64,
87 /// `scene.environment` — the default environment map for every material in
88 /// the scene that does not carry one of its own.
89 ///
90 /// Upstream this is a plain `Texture` and
91 /// `NodeManager.updateEnvironment( scene )` turns it into a
92 /// `scene.environmentNode`, which `NodeMaterial.setupEnvironment()` falls
93 /// back to when neither `builder.context.environment` nor the material's
94 /// own `envNode` is set. The port carries the generated PMREM's handle for
95 /// the reason [`Background::Pmrem`] does: the `maxLod` uniform the read needs
96 /// travels with the texture.
97 ///
98 /// Assigning it after a material has drawn once needs
99 /// [`MeshBasicNodeMaterial::set_needs_update`] on that material, exactly as
100 /// three.js needs `material.needsUpdate = true`: it changes the program,
101 /// not a uniform.
102 ///
103 /// [`MeshBasicNodeMaterial::set_needs_update`]: crate::materials::MeshBasicNodeMaterial::set_needs_update
104 pub environment: Option<crate::materials::environment::PmremHandle>,
105 /// `scene.environmentRotation` — the rotation `materialEnvRotation` applies
106 /// to [`Scene::environment`] (or [`Scene::environment_node`]) on every
107 /// material that has no `envMap` of its own. Three's uniform is
108 /// `makeRotationFromEuler( rotation ).transpose()`, an object-group `mat4`,
109 /// so changing it is a uniform write, not a new program.
110 pub environment_rotation: crate::math::Euler,
111 /// `scene.environmentNode` set by hand to a graph of `pmremTexture()`s.
112 /// `NodeManager.getEnvironmentNode()` returns it ahead of the node it would
113 /// make from [`Scene::environment`], so it wins when both are set. The same
114 /// rule about [`MeshBasicNodeMaterial::set_needs_update`] applies.
115 ///
116 /// [`MeshBasicNodeMaterial::set_needs_update`]: crate::materials::MeshBasicNodeMaterial::set_needs_update
117 pub environment_node: Option<crate::materials::environment::EnvironmentNode>,
118 /// `scene.fog` — a classic [`Fog`](super::Fog) or
119 /// [`FogExp2`](super::FogExp2). The renderer turns it into a fog node
120 /// whose parameters are render-group uniforms (`NodeManager.updateFog()`),
121 /// so changing a value is a uniform write; changing the *kind* is a new
122 /// program. [`Scene::fog_node`] wins when both are set, as in three.js.
123 pub fog: Option<super::SceneFog>,
124 /// `scene.fogNode`. Read by `NodeMaterial`'s output flow on every material
125 /// in the scene (rung 5).
126 pub fog_node: Option<FogNode>,
127 /// `scene.overrideMaterial` — used to draw every object in the scene with
128 /// this material instead of its own.
129 pub override_material: Option<MeshBasicNodeMaterial>,
130 /// `scene.onBeforeRender( renderer, scene, camera, renderTarget )` —
131 /// called at the start of every render of this scene, after its matrices
132 /// and the camera's are updated and before the scene is projected. Not the
133 /// `on_before_render` of [`Scene::node`]'s `Object3D`: three calls an
134 /// object's hook per draw, and the scene root is not drawn, so the
135 /// renderer never calls that one. See [`SceneRenderHook`].
136 pub on_before_render: Option<SceneRenderHook>,
137 /// `scene.onAfterRender( renderer, scene, camera, renderTarget )` —
138 /// called at the end of every render of this scene, after its pass (and
139 /// its output pass, if any) has been recorded and every object's
140 /// `on_after_render` has run.
141 pub on_after_render: Option<SceneRenderHook>,
142}
143
144impl Default for Scene {
145 fn default() -> Self {
146 let object = Object3D {
147 object_type: "Scene",
148 is_scene: true,
149 ..Default::default()
150 };
151
152 Self {
153 node: object.into_node(),
154 background: None,
155 background_blurriness: 0.0,
156 background_intensity: 1.0,
157 environment_intensity: 1.0,
158 environment: None,
159 environment_rotation: crate::math::Euler::default(),
160 environment_node: None,
161 fog: None,
162 fog_node: None,
163 override_material: None,
164 on_before_render: None,
165 on_after_render: None,
166 }
167 }
168}
169
170impl Scene {
171 /// `new Scene()`.
172 pub fn new() -> Self {
173 Self::default()
174 }
175
176 /// `Scene.matrixWorld`.
177 pub fn matrix_world(&self) -> Matrix4 {
178 self.node.borrow().matrix_world
179 }
180
181 /// `scene.onBeforeRender = function ( renderer, scene, camera,
182 /// renderTarget ) { ... }` — sets [`Scene::on_before_render`]. Assigning
183 /// the field works too; this spares spelling out the closure's argument
184 /// types.
185 pub fn set_on_before_render(
186 &mut self,
187 hook: impl Fn(
188 &crate::renderer::Renderer,
189 &Scene,
190 &dyn crate::cameras::RenderCamera,
191 Option<&crate::renderer::RenderTarget>,
192 ) + 'static,
193 ) {
194 self.on_before_render = Some(Box::new(hook));
195 }
196
197 /// `scene.onAfterRender = function ( ... ) { ... }` — sets
198 /// [`Scene::on_after_render`], as
199 /// [`set_on_before_render`](Self::set_on_before_render) does.
200 pub fn set_on_after_render(
201 &mut self,
202 hook: impl Fn(
203 &crate::renderer::Renderer,
204 &Scene,
205 &dyn crate::cameras::RenderCamera,
206 Option<&crate::renderer::RenderTarget>,
207 ) + 'static,
208 ) {
209 self.on_after_render = Some(Box::new(hook));
210 }
211
212 /// `scene.background = value`.
213 pub fn set_background(&mut self, background: impl Into<Background>) {
214 self.background = Some(background.into());
215 }
216
217 /// `scene.add( object )`.
218 pub fn add(&self, object: &ObjectRef) -> &Self {
219 self.node.add(object);
220 self
221 }
222
223 /// `scene.remove( object )`.
224 pub fn remove(&self, object: &ObjectRef) -> &Self {
225 self.node.remove(object);
226 self
227 }
228
229 /// `scene.children`, cloned — the direct children only. The renderer does
230 /// not use this; it walks the whole tree.
231 pub fn children(&self) -> Vec<ObjectRef> {
232 self.node.children()
233 }
234
235 /// `Object3D.updateMatrixWorld()` on the scene root, which is what
236 /// `Renderer.render()` calls before projecting the scene.
237 pub fn update_matrix_world(&self) {
238 self.node.update_matrix_world(false);
239 }
240}