roast2d_internal 0.4.0

Roast2D internal crate
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use glam::Vec3;

use crate::color::Color;

/// Type of light source
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum LightKind {
    /// Directional light (like the sun) - direction only, no position
    #[default]
    Directional,
    /// Point light - position and radius
    Point { radius: f32 },
    /// Spot light - position, direction, and cone angles
    Spot {
        radius: f32,
        inner_angle: f32,
        outer_angle: f32,
    },
}

/// A light source in the 3D scene
#[derive(Debug, Clone, Copy)]
pub struct Light3D {
    /// Type of light
    pub kind: LightKind,
    /// Position in world space (used by Point and Spot lights)
    pub position: Vec3,
    /// Direction the light points (used by Directional and Spot lights)
    pub direction: Vec3,
    /// Light color
    pub color: Color,
    /// Light intensity multiplier
    pub intensity: f32,
    /// Whether the light is active
    pub enabled: bool,
}

impl Default for Light3D {
    fn default() -> Self {
        Self {
            kind: LightKind::Directional,
            position: Vec3::ZERO,
            direction: Vec3::new(0.0, -1.0, -1.0).normalize(),
            color: Color::rgb(1.0, 1.0, 1.0),
            intensity: 1.0,
            enabled: true,
        }
    }
}

impl Light3D {
    /// Create a directional light
    pub fn directional(direction: Vec3, color: Color) -> Self {
        Self {
            kind: LightKind::Directional,
            direction: direction.normalize(),
            color,
            ..Default::default()
        }
    }

    /// Create a point light
    pub fn point(position: Vec3, radius: f32, color: Color) -> Self {
        Self {
            kind: LightKind::Point { radius },
            position,
            color,
            ..Default::default()
        }
    }

    /// Create a spot light
    pub fn spot(
        position: Vec3,
        direction: Vec3,
        radius: f32,
        inner_angle: f32,
        outer_angle: f32,
        color: Color,
    ) -> Self {
        Self {
            kind: LightKind::Spot {
                radius,
                inner_angle,
                outer_angle,
            },
            position,
            direction: direction.normalize(),
            color,
            ..Default::default()
        }
    }
}

/// Material properties for 3D rendering (simplified Blinn-Phong)
#[derive(Debug, Clone, Copy)]
pub struct Material3D {
    /// Diffuse color (base color)
    pub diffuse: Color,
    /// Specular color (highlight color)
    pub specular: Color,
    /// Shininess exponent (higher = sharper highlights)
    pub shininess: f32,
    /// Emissive color (self-illumination)
    pub emissive: Color,
}

impl Default for Material3D {
    fn default() -> Self {
        Self {
            diffuse: Color::rgb(1.0, 1.0, 1.0),
            specular: Color::rgb(0.5, 0.5, 0.5),
            shininess: 32.0,
            emissive: Color::rgb(0.0, 0.0, 0.0),
        }
    }
}

impl Material3D {
    /// Create a material with just a diffuse color
    pub fn color(diffuse: Color) -> Self {
        Self {
            diffuse,
            ..Default::default()
        }
    }

    /// Create a shiny metallic material
    pub fn metallic(color: Color, shininess: f32) -> Self {
        Self {
            diffuse: color,
            specular: color,
            shininess,
            emissive: Color::rgb(0.0, 0.0, 0.0),
        }
    }

    /// Create an emissive (glowing) material
    pub fn emissive(color: Color) -> Self {
        Self {
            diffuse: color,
            specular: Color::rgb(0.0, 0.0, 0.0),
            shininess: 1.0,
            emissive: color,
        }
    }
}

/// PBR (Physically Based Rendering) material properties.
///
/// Uses the metallic-roughness workflow, which is the standard for
/// modern 3D engines and the glTF format.
#[derive(Debug, Clone, Copy)]
pub struct PbrMaterial {
    /// Base color (albedo) of the material
    pub albedo: Color,

    /// Metallic factor: 0.0 = dielectric (plastic, wood), 1.0 = metal
    /// Metals reflect light with their albedo color, dielectrics use a fixed F0
    pub metallic: f32,

    /// Roughness: 0.0 = smooth mirror, 1.0 = completely rough/matte
    pub roughness: f32,

    /// Ambient occlusion factor: darkens crevices (0.0 = full occlusion, 1.0 = none)
    pub ao: f32,

    /// Emissive color (self-illumination, adds to final color)
    pub emissive: Color,
}

impl Default for PbrMaterial {
    fn default() -> Self {
        Self {
            albedo: Color::rgb(1.0, 1.0, 1.0),
            metallic: 0.0,
            roughness: 0.5,
            ao: 1.0,
            emissive: Color::rgb(0.0, 0.0, 0.0),
        }
    }
}

impl PbrMaterial {
    /// Create a PBR material with the given albedo color
    pub fn new(albedo: Color) -> Self {
        Self {
            albedo,
            ..Default::default()
        }
    }

    /// Create a metallic material (gold, silver, copper, etc.)
    pub fn metal(albedo: Color, roughness: f32) -> Self {
        Self {
            albedo,
            metallic: 1.0,
            roughness,
            ..Default::default()
        }
    }

    /// Create a dielectric/non-metal material (plastic, wood, stone, etc.)
    pub fn dielectric(albedo: Color, roughness: f32) -> Self {
        Self {
            albedo,
            metallic: 0.0,
            roughness,
            ..Default::default()
        }
    }

    /// Create a smooth/shiny material
    pub fn smooth(albedo: Color, metallic: f32) -> Self {
        Self {
            albedo,
            metallic,
            roughness: 0.1,
            ..Default::default()
        }
    }

    /// Create a rough/matte material
    pub fn rough(albedo: Color, metallic: f32) -> Self {
        Self {
            albedo,
            metallic,
            roughness: 0.9,
            ..Default::default()
        }
    }

    /// Create an emissive (glowing) PBR material
    pub fn emissive(color: Color, intensity: f32) -> Self {
        Self {
            albedo: color,
            metallic: 0.0,
            roughness: 0.5,
            ao: 1.0,
            emissive: Color::rgb(
                color.r * intensity,
                color.g * intensity,
                color.b * intensity,
            ),
        }
    }

    /// Builder: set metallic value
    pub fn with_metallic(mut self, metallic: f32) -> Self {
        self.metallic = metallic.clamp(0.0, 1.0);
        self
    }

    /// Builder: set roughness value
    pub fn with_roughness(mut self, roughness: f32) -> Self {
        self.roughness = roughness.clamp(0.0, 1.0);
        self
    }

    /// Builder: set ambient occlusion
    pub fn with_ao(mut self, ao: f32) -> Self {
        self.ao = ao.clamp(0.0, 1.0);
        self
    }

    /// Builder: set emissive color
    pub fn with_emissive(mut self, emissive: Color) -> Self {
        self.emissive = emissive;
        self
    }
}

/// Maximum number of lights supported
pub const MAX_LIGHTS: usize = 4;

/// Lighting state for the 3D renderer
#[derive(Debug, Clone)]
pub struct LightingState {
    /// Ambient light color
    pub ambient: Color,
    /// Array of lights (up to MAX_LIGHTS)
    pub lights: [Option<Light3D>; MAX_LIGHTS],
}

impl Default for LightingState {
    fn default() -> Self {
        Self {
            ambient: Color::rgb(0.1, 0.1, 0.1),
            lights: [None; MAX_LIGHTS],
        }
    }
}

impl LightingState {
    /// Set the ambient light color
    pub fn set_ambient(&mut self, color: Color) {
        self.ambient = color;
    }

    /// Set a light at the given index (0-3)
    pub fn set_light(&mut self, index: usize, light: Option<Light3D>) {
        if index < MAX_LIGHTS {
            self.lights[index] = light;
        }
    }

    /// Get a light at the given index
    pub fn get_light(&self, index: usize) -> Option<&Light3D> {
        if index < MAX_LIGHTS {
            self.lights[index].as_ref()
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::color::{GOLD, GREEN, RED, WHITE};

    // ==================== Light3D Tests ====================

    #[test]
    fn test_light_directional_normalizes_direction() {
        let light = Light3D::directional(Vec3::new(10.0, 0.0, 0.0), WHITE);
        assert!((light.direction.length() - 1.0).abs() < 1e-6);
        assert_eq!(light.direction, Vec3::X);
    }

    #[test]
    fn test_light_point() {
        let light = Light3D::point(Vec3::new(1.0, 2.0, 3.0), 10.0, RED);
        assert_eq!(light.position, Vec3::new(1.0, 2.0, 3.0));
        assert!(matches!(light.kind, LightKind::Point { radius } if radius == 10.0));
        assert_eq!(light.color.r, 1.0);
    }

    #[test]
    fn test_light_spot() {
        let light = Light3D::spot(
            Vec3::new(0.0, 5.0, 0.0),
            Vec3::new(0.0, -1.0, 0.0),
            20.0,
            0.5,
            1.0,
            WHITE,
        );
        assert_eq!(light.position, Vec3::new(0.0, 5.0, 0.0));
        assert!((light.direction - Vec3::NEG_Y).length() < 1e-6);
        assert!(matches!(
            light.kind,
            LightKind::Spot { radius, inner_angle, outer_angle }
                if radius == 20.0 && inner_angle == 0.5 && outer_angle == 1.0
        ));
    }

    #[test]
    fn test_light_default() {
        let light = Light3D::default();
        assert!(matches!(light.kind, LightKind::Directional));
        assert!(light.enabled);
        assert_eq!(light.intensity, 1.0);
    }

    // ==================== Material3D Tests ====================

    #[test]
    fn test_material3d_default() {
        let mat = Material3D::default();
        assert_eq!(mat.diffuse.r, 1.0);
        assert_eq!(mat.shininess, 32.0);
    }

    #[test]
    fn test_material3d_color() {
        let mat = Material3D::color(RED);
        assert_eq!(mat.diffuse.r, 1.0);
        assert_eq!(mat.diffuse.g, 0.0);
    }

    #[test]
    fn test_material3d_metallic() {
        let mat = Material3D::metallic(GOLD, 64.0);
        assert_eq!(mat.diffuse, mat.specular); // metallic: specular = diffuse
        assert_eq!(mat.shininess, 64.0);
    }

    #[test]
    fn test_material3d_emissive() {
        let mat = Material3D::emissive(GREEN);
        assert_eq!(mat.emissive.g, mat.diffuse.g);
    }

    // ==================== PbrMaterial Tests ====================

    #[test]
    fn test_pbr_material_default() {
        let mat = PbrMaterial::default();
        assert_eq!(mat.metallic, 0.0);
        assert_eq!(mat.roughness, 0.5);
        assert_eq!(mat.ao, 1.0);
    }

    #[test]
    fn test_pbr_material_metal() {
        let mat = PbrMaterial::metal(GOLD, 0.3);
        assert_eq!(mat.metallic, 1.0);
        assert_eq!(mat.roughness, 0.3);
    }

    #[test]
    fn test_pbr_material_dielectric() {
        let mat = PbrMaterial::dielectric(WHITE, 0.7);
        assert_eq!(mat.metallic, 0.0);
        assert_eq!(mat.roughness, 0.7);
    }

    #[test]
    fn test_pbr_material_smooth() {
        let mat = PbrMaterial::smooth(WHITE, 0.5);
        assert_eq!(mat.roughness, 0.1);
    }

    #[test]
    fn test_pbr_material_rough() {
        let mat = PbrMaterial::rough(WHITE, 0.5);
        assert_eq!(mat.roughness, 0.9);
    }

    #[test]
    fn test_pbr_material_with_metallic_clamp() {
        let mat = PbrMaterial::default()
            .with_metallic(1.5) // should clamp to 1.0
            .with_metallic(-0.5); // should clamp to 0.0
        assert_eq!(mat.metallic, 0.0);

        let mat2 = PbrMaterial::default().with_metallic(1.5);
        assert_eq!(mat2.metallic, 1.0);
    }

    #[test]
    fn test_pbr_material_with_roughness_clamp() {
        let mat = PbrMaterial::default().with_roughness(2.0);
        assert_eq!(mat.roughness, 1.0);

        let mat2 = PbrMaterial::default().with_roughness(-1.0);
        assert_eq!(mat2.roughness, 0.0);
    }

    #[test]
    fn test_pbr_material_with_ao_clamp() {
        let mat = PbrMaterial::default().with_ao(1.5);
        assert_eq!(mat.ao, 1.0);

        let mat2 = PbrMaterial::default().with_ao(-0.5);
        assert_eq!(mat2.ao, 0.0);
    }

    #[test]
    fn test_pbr_material_emissive() {
        let mat = PbrMaterial::emissive(Color::rgb(1.0, 0.5, 0.0), 2.0);
        assert_eq!(mat.emissive.r, 2.0);
        assert_eq!(mat.emissive.g, 1.0);
        assert_eq!(mat.emissive.b, 0.0);
    }

    // ==================== LightingState Tests ====================

    #[test]
    fn test_lighting_state_default() {
        let state = LightingState::default();
        assert!((state.ambient.r - 0.1).abs() < 0.01);
        assert!(state.lights.iter().all(|l| l.is_none()));
    }

    #[test]
    fn test_lighting_state_set_ambient() {
        let mut state = LightingState::default();
        state.set_ambient(Color::rgb(0.5, 0.5, 0.5));
        assert_eq!(state.ambient.r, 0.5);
    }

    #[test]
    fn test_lighting_state_set_get_light() {
        let mut state = LightingState::default();
        let light = Light3D::directional(Vec3::NEG_Y, WHITE);

        state.set_light(0, Some(light));
        assert!(state.get_light(0).is_some());
        assert!(state.get_light(1).is_none());

        state.set_light(0, None);
        assert!(state.get_light(0).is_none());
    }

    #[test]
    fn test_lighting_state_bounds_check() {
        let mut state = LightingState::default();
        let light = Light3D::default();

        // Setting beyond MAX_LIGHTS should be ignored
        state.set_light(MAX_LIGHTS, Some(light));
        assert!(state.get_light(MAX_LIGHTS).is_none());

        // Valid indices
        for i in 0..MAX_LIGHTS {
            state.set_light(i, Some(Light3D::default()));
            assert!(state.get_light(i).is_some());
        }
    }
}