scena 1.3.0

A Rust-native scene-graph renderer with typed scene state, glTF assets, and explicit prepare/render lifecycles.
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
use crate::diagnostics::LookupError;
use crate::material::Color;

use super::{Angle, LightKey, NodeKey, NodeKind, Scene, Transform};

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Light {
    Directional(DirectionalLight),
    Point(PointLight),
    Spot(SpotLight),
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DirectionalLight {
    color: Color,
    illuminance_lux: f32,
    casts_shadows: bool,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PointLight {
    color: Color,
    intensity_candela: f32,
    range: Option<f32>,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SpotLight {
    color: Color,
    intensity_candela: f32,
    range: Option<f32>,
    inner_cone_angle: Angle,
    outer_cone_angle: Angle,
}

/// Builder returned by [`Scene::directional_light`], [`Scene::point_light`], and
/// [`Scene::spot_light`].
#[must_use = "light builders do nothing until add() is called"]
pub struct LightBuilder<'scene> {
    scene: &'scene mut Scene,
    parent: NodeKey,
    transform: Transform,
    light: Light,
}

impl Scene {
    pub fn light(&self, light: LightKey) -> Option<&Light> {
        self.lights.get(light)
    }

    pub fn directional_light(&mut self, light: DirectionalLight) -> LightBuilder<'_> {
        self.light_builder(Light::Directional(light))
    }

    /// Inserts a studio-style three-point directional rig.
    ///
    /// The rig contains a key light, cool fill, and warm rim light. The
    /// returned handles are ordered as key, fill, and rim so callers can
    /// adjust or remove individual lights after insertion. Intensities are
    /// tuned for neutral glTF product/model-viewer scenes without
    /// over-exposing PBR metallic body materials.
    ///
    /// This preset uses moderate intensities (key 13,500 lux, fill 4,500 lux,
    /// rim 3,500 lux). Only the key casts shadows because the renderer
    /// supports one shadowed directional light per scene.
    ///
    /// # Errors
    ///
    /// Returns a [`LookupError`] if the scene cannot insert one of the light
    /// nodes under the root.
    pub fn add_studio_lighting(&mut self) -> Result<StudioLightingHandles, LookupError> {
        let key = self
            .directional_light(
                DirectionalLight::default()
                    .with_color(Color::WHITE)
                    .with_illuminance_lux(13_500.0)
                    .with_shadows(true),
            )
            .transform(Transform::default().rotate_x_deg(-30.0).rotate_y_deg(20.0))
            .add()?;
        let fill = self
            .directional_light(
                DirectionalLight::default()
                    .with_color(Color::from_srgb_u8(200, 215, 235))
                    .with_illuminance_lux(4_500.0),
            )
            .transform(
                Transform::default()
                    .rotate_x_deg(-10.0)
                    .rotate_y_deg(-120.0),
            )
            .add()?;
        let rim = self
            .directional_light(
                DirectionalLight::default()
                    .with_color(Color::from_srgb_u8(255, 235, 210))
                    .with_illuminance_lux(3_500.0),
            )
            .transform(Transform::default().rotate_x_deg(15.0).rotate_y_deg(170.0))
            .add()?;
        Ok(StudioLightingHandles { key, fill, rim })
    }

    pub fn point_light(&mut self, light: PointLight) -> LightBuilder<'_> {
        self.light_builder(Light::Point(light))
    }

    pub fn spot_light(&mut self, light: SpotLight) -> LightBuilder<'_> {
        self.light_builder(Light::Spot(light))
    }

    fn light_builder(&mut self, light: Light) -> LightBuilder<'_> {
        let parent = self.root;
        LightBuilder {
            scene: self,
            parent,
            transform: Transform::default(),
            light,
        }
    }

    fn insert_light(
        &mut self,
        parent: NodeKey,
        light: Light,
        transform: Transform,
    ) -> Result<NodeKey, LookupError> {
        let light = self.lights.insert(light);
        match self.insert_node(parent, NodeKind::Light(light), transform) {
            Ok(node) => Ok(node),
            Err(error) => {
                self.lights.remove(light);
                Err(error)
            }
        }
    }
}

/// Handles for the three lights inserted by [`Scene::add_studio_lighting`].
///
/// Returned so callers can later adjust an individual light, for example to
/// raise the key, tint the rim, or remove the rig.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StudioLightingHandles {
    pub key: NodeKey,
    pub fill: NodeKey,
    pub rim: NodeKey,
}

impl LightBuilder<'_> {
    /// Overrides the parent node. The parent is validated when [`Self::add`] is called.
    pub fn parent(mut self, parent: NodeKey) -> Self {
        self.parent = parent;
        self
    }

    /// Overrides the local transform. Light direction and position are derived from this
    /// node transform during render preparation.
    pub fn transform(mut self, transform: Transform) -> Self {
        self.transform = transform;
        self
    }

    /// Inserts the light node and returns its typed scene node key.
    pub fn add(self) -> Result<NodeKey, LookupError> {
        self.scene
            .insert_light(self.parent, self.light, self.transform)
    }
}

impl Default for DirectionalLight {
    fn default() -> Self {
        Self {
            color: Color::WHITE,
            illuminance_lux: 10_000.0,
            casts_shadows: false,
        }
    }
}

impl DirectionalLight {
    pub const fn color(self) -> Color {
        self.color
    }

    pub const fn illuminance_lux(self) -> f32 {
        self.illuminance_lux
    }

    pub const fn casts_shadows(self) -> bool {
        self.casts_shadows
    }

    pub const fn with_color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    pub const fn with_illuminance_lux(mut self, illuminance_lux: f32) -> Self {
        self.illuminance_lux = non_negative_or(illuminance_lux, 10_000.0);
        self
    }

    pub const fn with_shadows(mut self, enabled: bool) -> Self {
        self.casts_shadows = enabled;
        self
    }
}

impl Default for PointLight {
    fn default() -> Self {
        Self {
            color: Color::WHITE,
            intensity_candela: 100.0,
            range: None,
        }
    }
}

impl PointLight {
    pub const fn color(self) -> Color {
        self.color
    }

    pub const fn intensity_candela(self) -> f32 {
        self.intensity_candela
    }

    pub const fn range(self) -> Option<f32> {
        self.range
    }

    pub const fn with_color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    pub const fn with_intensity_candela(mut self, intensity_candela: f32) -> Self {
        self.intensity_candela = non_negative_or(intensity_candela, 100.0);
        self
    }

    pub const fn with_range(mut self, range: f32) -> Self {
        self.range = positive_range(range);
        self
    }
}

impl Default for SpotLight {
    fn default() -> Self {
        Self {
            color: Color::WHITE,
            intensity_candela: 100.0,
            range: None,
            inner_cone_angle: Angle::from_radians(0.0),
            outer_cone_angle: Angle::from_radians(std::f32::consts::FRAC_PI_4),
        }
    }
}

impl SpotLight {
    pub const fn color(self) -> Color {
        self.color
    }

    pub const fn intensity_candela(self) -> f32 {
        self.intensity_candela
    }

    pub const fn range(self) -> Option<f32> {
        self.range
    }

    pub const fn inner_cone_angle(self) -> Angle {
        self.inner_cone_angle
    }

    pub const fn outer_cone_angle(self) -> Angle {
        self.outer_cone_angle
    }

    pub const fn with_color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    pub const fn with_intensity_candela(mut self, intensity_candela: f32) -> Self {
        self.intensity_candela = non_negative_or(intensity_candela, 100.0);
        self
    }

    pub const fn with_range(mut self, range: f32) -> Self {
        self.range = positive_range(range);
        self
    }

    pub const fn with_inner_cone_angle(mut self, angle: Angle) -> Self {
        self.inner_cone_angle = clamp_angle(angle, 0.0, self.outer_cone_angle.radians());
        self
    }

    pub const fn with_outer_cone_angle(mut self, angle: Angle) -> Self {
        self.outer_cone_angle =
            clamp_angle(angle, self.inner_cone_angle.radians(), std::f32::consts::PI);
        self
    }
}

const fn non_negative_or(value: f32, fallback: f32) -> f32 {
    if value.is_nan() {
        fallback
    } else if value < 0.0 {
        0.0
    } else {
        value
    }
}

const fn positive_range(value: f32) -> Option<f32> {
    if value.is_finite() && value > 0.0 {
        Some(value)
    } else {
        None
    }
}

const fn clamp_angle(angle: Angle, min: f32, max: f32) -> Angle {
    let radians = angle.radians();
    if !radians.is_finite() || radians < min {
        Angle::from_radians(min)
    } else if radians > max {
        Angle::from_radians(max)
    } else {
        angle
    }
}

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

    #[test]
    fn add_studio_lighting_inserts_three_directional_nodes_with_distinct_keys() {
        let mut scene = Scene::new();
        let handles = scene
            .add_studio_lighting()
            .expect("studio lighting inserts");
        assert_ne!(handles.key, handles.fill);
        assert_ne!(handles.fill, handles.rim);
        assert_ne!(handles.key, handles.rim);
        // Each handle resolves to a Light::Directional in the scene.
        for node in [handles.key, handles.fill, handles.rim] {
            let node_data = scene.node(node).expect("node exists");
            match node_data.kind {
                NodeKind::Light(light_key) => {
                    let light = scene.light(light_key).expect("light exists");
                    assert!(matches!(light, Light::Directional(_)));
                }
                _ => panic!("studio lighting handle must point at a Light node"),
            }
        }
    }

    #[test]
    fn add_studio_lighting_uses_moderate_intensities_not_overdriven_3point() {
        // Keep the preset moderate so PBR material differences stay visible.
        let mut scene = Scene::new();
        let handles = scene.add_studio_lighting().expect("inserts");
        let mut illuminances = Vec::new();
        for node in [handles.key, handles.fill, handles.rim] {
            let node_data = scene.node(node).expect("node");
            let NodeKind::Light(light_key) = node_data.kind else {
                panic!("light node");
            };
            let Light::Directional(light) = scene.light(light_key).expect("light") else {
                panic!("directional");
            };
            illuminances.push(light.illuminance_lux());
        }
        for lux in &illuminances {
            assert!(
                *lux < 20_000.0,
                "studio preset must stay under 20k lux per light (got {lux})"
            );
        }
        let total: f32 = illuminances.iter().sum();
        assert_eq!(illuminances, [13_500.0, 4_500.0, 3_500.0]);
        assert!(
            total < 30_000.0,
            "combined studio preset under 30k lux total (got {total})"
        );
    }

    #[test]
    fn add_studio_lighting_shadows_only_the_key_light() {
        let mut scene = Scene::new();
        let handles = scene.add_studio_lighting().expect("inserts");

        let casts_shadows = |scene: &Scene, node| -> bool {
            let node_data = scene.node(node).expect("node");
            let NodeKind::Light(light_key) = node_data.kind else {
                panic!("light node");
            };
            let Light::Directional(light) = scene.light(light_key).expect("light") else {
                panic!("directional");
            };
            light.casts_shadows()
        };

        assert!(
            casts_shadows(&scene, handles.key),
            "studio key light should cast the single supported directional shadow"
        );
        assert!(
            !casts_shadows(&scene, handles.fill),
            "studio fill light must not cast a second directional shadow"
        );
        assert!(
            !casts_shadows(&scene, handles.rim),
            "studio rim light must not cast a second directional shadow"
        );
    }
}