soorat 1.0.0

Soorat — GPU rendering engine for AGNOS
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! 3D mesh rendering pipeline.

use crate::error::Result;
use crate::math_util::IDENTITY_MAT4;
use crate::vertex::Vertex3D;
use wgpu::util::DeviceExt;

/// Camera uniforms for the mesh shader.
#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct CameraUniforms {
    pub view_proj: [f32; 16],
    pub model: [f32; 16],
    pub camera_pos: [f32; 4],
    /// Inverse-transpose of model matrix rows for correct normals.
    /// Stored as 3 × vec4 (padded mat3) for WGSL uniform alignment.
    pub normal_matrix_0: [f32; 4],
    pub normal_matrix_1: [f32; 4],
    pub normal_matrix_2: [f32; 4],
}

impl Default for CameraUniforms {
    fn default() -> Self {
        Self {
            view_proj: IDENTITY_MAT4,
            model: IDENTITY_MAT4,
            camera_pos: [0.0, 0.0, 5.0, 0.0],
            normal_matrix_0: [1.0, 0.0, 0.0, 0.0],
            normal_matrix_1: [0.0, 1.0, 0.0, 0.0],
            normal_matrix_2: [0.0, 0.0, 1.0, 0.0],
        }
    }
}

impl CameraUniforms {
    /// Set the model matrix and auto-compute the normal matrix (inverse-transpose of upper 3x3).
    pub fn set_model(&mut self, model: [f32; 16]) {
        self.model = model;
        // Extract upper 3x3 rows, compute inverse-transpose
        // For uniform scale, transpose of upper 3x3 = inverse-transpose
        // For non-uniform scale, need proper inverse
        let (nm0, nm1, nm2) = inverse_transpose_3x3(&model);
        self.normal_matrix_0 = [nm0[0], nm0[1], nm0[2], 0.0];
        self.normal_matrix_1 = [nm1[0], nm1[1], nm1[2], 0.0];
        self.normal_matrix_2 = [nm2[0], nm2[1], nm2[2], 0.0];
    }
}

/// Compute inverse-transpose of upper-left 3x3 from a 4x4 column-major matrix.
/// Returns 3 rows of the resulting 3x3 matrix.
#[inline]
fn inverse_transpose_3x3(m: &[f32; 16]) -> ([f32; 3], [f32; 3], [f32; 3]) {
    // Extract upper-left 3x3 (column-major)
    let a = [m[0], m[1], m[2]];
    let b = [m[4], m[5], m[6]];
    let c = [m[8], m[9], m[10]];

    // For 3x3 columns [a, b, c]:
    // inv = (1/det) * [b×c, c×a, a×b]^T
    // inv^T = (1/det) * [b×c, c×a, a×b] (as rows)

    let bc = [
        b[1] * c[2] - b[2] * c[1],
        b[2] * c[0] - b[0] * c[2],
        b[0] * c[1] - b[1] * c[0],
    ];
    let ca = [
        c[1] * a[2] - c[2] * a[1],
        c[2] * a[0] - c[0] * a[2],
        c[0] * a[1] - c[1] * a[0],
    ];
    let ab = [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ];

    let det = a[0] * bc[0] + a[1] * bc[1] + a[2] * bc[2];
    let inv_det = if det.abs() > 1e-10 { 1.0 / det } else { 1.0 };

    (
        [bc[0] * inv_det, bc[1] * inv_det, bc[2] * inv_det],
        [ca[0] * inv_det, ca[1] * inv_det, ca[2] * inv_det],
        [ab[0] * inv_det, ab[1] * inv_det, ab[2] * inv_det],
    )
}

/// Light uniforms for the mesh shader.
#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct LightUniforms {
    /// RGB + intensity in alpha.
    pub ambient_color: [f32; 4],
    /// Normalized direction the light points (w unused).
    pub light_direction: [f32; 4],
    /// RGB + intensity in alpha.
    pub light_color: [f32; 4],
    /// Light view-projection matrix for shadow mapping.
    pub light_view_proj: [f32; 16],
}

impl Default for LightUniforms {
    fn default() -> Self {
        Self {
            ambient_color: [1.0, 1.0, 1.0, 0.1],
            // Normalized: (0, -1, -1) / sqrt(2)
            light_direction: [
                0.0,
                -std::f32::consts::FRAC_1_SQRT_2,
                -std::f32::consts::FRAC_1_SQRT_2,
                0.0,
            ],
            light_color: [1.0, 1.0, 1.0, 1.0],
            light_view_proj: IDENTITY_MAT4,
        }
    }
}

/// A loaded 3D mesh with GPU buffers ready for drawing.
pub struct Mesh {
    pub vertex_buffer: wgpu::Buffer,
    pub index_buffer: wgpu::Buffer,
    pub index_count: u32,
}

impl Mesh {
    /// Create a mesh from vertex and index data.
    #[must_use]
    pub fn new(device: &wgpu::Device, vertices: &[Vertex3D], indices: &[u32]) -> Self {
        tracing::debug!(
            vertex_count = vertices.len(),
            index_count = indices.len(),
            "creating mesh"
        );
        let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("mesh_vertex_buffer"),
            contents: bytemuck::cast_slice(vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });

        let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("mesh_index_buffer"),
            contents: bytemuck::cast_slice(indices),
            usage: wgpu::BufferUsages::INDEX,
        });

        let index_count = u32::try_from(indices.len()).unwrap_or_else(|_| {
            tracing::warn!(
                len = indices.len(),
                "mesh index count exceeds u32::MAX, clamping"
            );
            u32::MAX
        });

        Self {
            vertex_buffer,
            index_buffer,
            index_count,
        }
    }
}

/// Depth buffer texture for z-testing.
pub struct DepthBuffer {
    pub texture: wgpu::Texture,
    pub view: wgpu::TextureView,
}

impl DepthBuffer {
    pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;

    #[must_use]
    pub fn new(device: &wgpu::Device, width: u32, height: u32) -> Self {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("depth_buffer"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: Self::FORMAT,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });

        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());

        Self { texture, view }
    }

    pub fn resize(&mut self, device: &wgpu::Device, width: u32, height: u32) {
        *self = Self::new(device, width, height);
    }
}

/// Shadow pass uniforms for the PBR shader.
#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct ShadowPassUniforms {
    pub light_view_proj: [f32; 16],
    pub shadow_map_size: [f32; 4],
}

impl Default for ShadowPassUniforms {
    fn default() -> Self {
        Self {
            light_view_proj: IDENTITY_MAT4,
            shadow_map_size: [2048.0, 0.0, 0.0, 0.0],
        }
    }
}

/// Draw parameters for `MeshPipeline::draw`.
pub struct MeshDrawParams<'a> {
    pub color_view: &'a wgpu::TextureView,
    pub depth: &'a DepthBuffer,
    pub mesh: &'a Mesh,
    pub material_bind_group: &'a wgpu::BindGroup,
    pub shadow_bind_group: &'a wgpu::BindGroup,
    pub ibl_bind_group: &'a wgpu::BindGroup,
    pub clear_color: Option<crate::color::Color>,
}

/// 3D mesh rendering pipeline with PBR shading (Cook-Torrance/GGX/Fresnel-Schlick).
///
/// Uses [`mabda::RenderPipeline`] for pipeline management and
/// [`mabda::create_uniform_buffer`] for uniform buffer creation.
pub struct MeshPipeline {
    pipeline: mabda::RenderPipeline,
    camera_buffer: wgpu::Buffer,
    light_buffer: wgpu::Buffer,
    material_buffer: wgpu::Buffer,
    shadow_pass_buffer: wgpu::Buffer,
    uniform_bind_group: wgpu::BindGroup,
}

impl MeshPipeline {
    /// Create a new PBR mesh pipeline for the given surface format.
    pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat) -> Result<Self> {
        tracing::debug!(?surface_format, "creating mesh pipeline");
        // Group 0: camera + light_array + material + shadow uniforms
        let group0_entries = mabda::BindGroupLayoutBuilder::new()
            .uniform_buffer(wgpu::ShaderStages::VERTEX_FRAGMENT) // camera
            .uniform_buffer(wgpu::ShaderStages::FRAGMENT) // light_array
            .uniform_buffer(wgpu::ShaderStages::FRAGMENT) // material
            .uniform_buffer(wgpu::ShaderStages::VERTEX_FRAGMENT) // shadow
            .into_entries();

        // Group 1: textures (base color + sampler)
        let group1_entries = mabda::BindGroupLayoutBuilder::new()
            .texture_2d(wgpu::ShaderStages::FRAGMENT)
            .sampler(wgpu::ShaderStages::FRAGMENT)
            .into_entries();

        // Group 2: shadow map (depth texture + comparison sampler)
        let group2_entries = mabda::BindGroupLayoutBuilder::new()
            .texture_depth_2d(wgpu::ShaderStages::FRAGMENT)
            .comparison_sampler(wgpu::ShaderStages::FRAGMENT)
            .into_entries();

        // Group 3: IBL (irradiance cubemap + prefiltered cubemap + BRDF LUT)
        let group3_entries = mabda::BindGroupLayoutBuilder::new()
            .texture_cube(wgpu::ShaderStages::FRAGMENT)
            .sampler(wgpu::ShaderStages::FRAGMENT)
            .texture_cube(wgpu::ShaderStages::FRAGMENT)
            .sampler(wgpu::ShaderStages::FRAGMENT)
            .texture_2d(wgpu::ShaderStages::FRAGMENT)
            .sampler(wgpu::ShaderStages::FRAGMENT)
            .into_entries();

        let pipeline = mabda::RenderPipelineBuilder::new(
            device,
            include_str!("pbr.wgsl"),
            "vs_main",
            "fs_main",
        )
        .label("mesh_pipeline")
        .vertex_layout(Vertex3D::layout())
        .bind_group(group0_entries)
        .bind_group(group1_entries)
        .bind_group(group2_entries)
        .bind_group(group3_entries)
        .color_target(surface_format, Some(wgpu::BlendState::ALPHA_BLENDING))
        .cull_mode(Some(wgpu::Face::Back))
        .depth_stencil(wgpu::DepthStencilState {
            format: DepthBuffer::FORMAT,
            depth_write_enabled: Some(true),
            depth_compare: Some(wgpu::CompareFunction::Less),
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        })
        .build()?;

        let cam_defaults = CameraUniforms::default();
        let camera_buffer = mabda::create_uniform_buffer(
            device,
            bytemuck::bytes_of(&cam_defaults),
            "camera_uniform_buffer",
        );

        let light_defaults = crate::lights::LightArrayUniforms::default();
        let light_buffer = mabda::create_uniform_buffer(
            device,
            bytemuck::bytes_of(&light_defaults),
            "light_array_uniform_buffer",
        );

        let mat_defaults = crate::pbr_material::MaterialUniforms::default();
        let material_buffer = mabda::create_uniform_buffer(
            device,
            bytemuck::bytes_of(&mat_defaults),
            "material_uniform_buffer",
        );

        let shadow_defaults = ShadowPassUniforms::default();
        let shadow_pass_buffer = mabda::create_uniform_buffer(
            device,
            bytemuck::bytes_of(&shadow_defaults),
            "shadow_pass_uniform_buffer",
        );

        let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("pbr_uniform_bind_group"),
            layout: pipeline.bind_group_layout(0).ok_or_else(|| {
                crate::error::RenderError::Pipeline(
                    "mesh pipeline missing bind group layout 0".into(),
                )
            })?,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: camera_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: light_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: material_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: shadow_pass_buffer.as_entire_binding(),
                },
            ],
        });

        Ok(Self {
            pipeline,
            camera_buffer,
            light_buffer,
            material_buffer,
            shadow_pass_buffer,
            uniform_bind_group,
        })
    }

    /// Get the material bind group layout for creating material bind groups.
    pub fn material_bind_group_layout(&self) -> Result<&wgpu::BindGroupLayout> {
        self.pipeline.bind_group_layout(1).ok_or_else(|| {
            crate::error::RenderError::Pipeline("mesh pipeline missing bind group layout 1".into())
        })
    }

    /// Update camera uniforms (view-projection + model matrix).
    pub fn update_camera(&self, queue: &wgpu::Queue, camera: &CameraUniforms) {
        queue.write_buffer(&self.camera_buffer, 0, bytemuck::bytes_of(camera));
    }

    /// Update light uniforms (multi-light array).
    pub fn update_lights(&self, queue: &wgpu::Queue, lights: &crate::lights::LightArrayUniforms) {
        queue.write_buffer(&self.light_buffer, 0, bytemuck::bytes_of(lights));
    }

    /// Update shadow pass uniforms (light view-proj + shadow map size).
    pub fn update_shadow_pass(&self, queue: &wgpu::Queue, shadow: &ShadowPassUniforms) {
        queue.write_buffer(&self.shadow_pass_buffer, 0, bytemuck::bytes_of(shadow));
    }

    /// Update PBR material uniforms (metallic, roughness, base_color_factor).
    pub fn update_material(
        &self,
        queue: &wgpu::Queue,
        material: &crate::pbr_material::MaterialUniforms,
    ) {
        queue.write_buffer(&self.material_buffer, 0, bytemuck::bytes_of(material));
    }

    /// Get the shadow bind group layout for creating shadow bind groups.
    pub fn shadow_bind_group_layout(&self) -> Result<&wgpu::BindGroupLayout> {
        self.pipeline.bind_group_layout(2).ok_or_else(|| {
            crate::error::RenderError::Pipeline("mesh pipeline missing bind group layout 2".into())
        })
    }

    /// Get the IBL bind group layout for creating IBL bind groups.
    pub fn ibl_bind_group_layout(&self) -> Result<&wgpu::BindGroupLayout> {
        self.pipeline.bind_group_layout(3).ok_or_else(|| {
            crate::error::RenderError::Pipeline("mesh pipeline missing bind group layout 3".into())
        })
    }

    /// Create a shadow bind group from a shadow map.
    pub fn create_shadow_bind_group(
        &self,
        device: &wgpu::Device,
        shadow_map: &crate::shadow::ShadowMap,
    ) -> Result<wgpu::BindGroup> {
        Ok(device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("shadow_bind_group"),
            layout: self.shadow_bind_group_layout()?,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&shadow_map.depth_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&shadow_map.sampler),
                },
            ],
        }))
    }

    /// Draw a mesh with PBR shading, shadow mapping, and IBL.
    /// Use `EnvironmentMap::solid_color` for a black cubemap when IBL is not desired.
    pub fn draw(&self, device: &wgpu::Device, queue: &wgpu::Queue, params: &MeshDrawParams<'_>) {
        tracing::debug!(
            index_count = params.mesh.index_count,
            has_clear = params.clear_color.is_some(),
            "drawing mesh"
        );
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("mesh_encoder"),
        });

        {
            let color_load = match params.clear_color {
                Some(c) => wgpu::LoadOp::Clear(c.to_wgpu()),
                None => wgpu::LoadOp::Load,
            };

            let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("mesh_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: params.color_view,
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: color_load,
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                    view: &params.depth.view,
                    depth_ops: Some(wgpu::Operations {
                        load: wgpu::LoadOp::Clear(1.0),
                        store: wgpu::StoreOp::Store,
                    }),
                    stencil_ops: None,
                }),
                ..Default::default()
            });

            render_pass.set_pipeline(self.pipeline.raw());
            render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
            render_pass.set_bind_group(1, params.material_bind_group, &[]);
            render_pass.set_bind_group(2, params.shadow_bind_group, &[]);
            render_pass.set_bind_group(3, params.ibl_bind_group, &[]);
            render_pass.set_vertex_buffer(0, params.mesh.vertex_buffer.slice(..));
            render_pass.set_index_buffer(
                params.mesh.index_buffer.slice(..),
                wgpu::IndexFormat::Uint32,
            );
            render_pass.draw_indexed(0..params.mesh.index_count, 0, 0..1);
        }

        queue.submit(std::iter::once(encoder.finish()));
    }

    /// Draw a mesh into an existing render pass (for egui/editor integration).
    /// The caller owns the render pass and is responsible for the encoder lifecycle.
    pub fn draw_into_pass<'a>(
        &'a self,
        render_pass: &mut wgpu::RenderPass<'a>,
        mesh: &'a Mesh,
        material_bind_group: &'a wgpu::BindGroup,
        shadow_bind_group: &'a wgpu::BindGroup,
        ibl_bind_group: &'a wgpu::BindGroup,
    ) {
        render_pass.set_pipeline(self.pipeline.raw());
        render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
        render_pass.set_bind_group(1, material_bind_group, &[]);
        render_pass.set_bind_group(2, shadow_bind_group, &[]);
        render_pass.set_bind_group(3, ibl_bind_group, &[]);
        render_pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
        render_pass.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
        render_pass.draw_indexed(0..mesh.index_count, 0, 0..1);
    }
}

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

    #[test]
    fn camera_uniforms_size() {
        // 2 * mat4 + vec4 + 3 * vec4 (normal matrix) = 128 + 16 + 48 = 192
        assert_eq!(std::mem::size_of::<CameraUniforms>(), 192);
    }

    #[test]
    fn light_uniforms_size() {
        assert_eq!(std::mem::size_of::<LightUniforms>(), 112); // 3 * vec4 + mat4 = 48 + 64
    }

    #[test]
    fn shadow_pass_uniforms_size() {
        assert_eq!(std::mem::size_of::<ShadowPassUniforms>(), 80); // mat4 + vec4 = 64 + 16
    }

    #[test]
    fn camera_uniforms_default() {
        let cam = CameraUniforms::default();
        // Identity matrix: diagonal = 1
        assert_eq!(cam.view_proj[0], 1.0);
        assert_eq!(cam.view_proj[5], 1.0);
        assert_eq!(cam.view_proj[10], 1.0);
        assert_eq!(cam.view_proj[15], 1.0);
    }

    #[test]
    fn light_uniforms_default() {
        let light = LightUniforms::default();
        assert_eq!(light.ambient_color[3], 0.1); // low ambient
        assert!(light.light_direction[1] < 0.0); // pointing down
        // Direction should be normalized (length ~1.0)
        let d = light.light_direction;
        let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
        assert!((len - 1.0).abs() < 0.001);
    }

    #[test]
    fn camera_uniforms_bytemuck() {
        let cam = CameraUniforms::default();
        let bytes = bytemuck::bytes_of(&cam);
        assert_eq!(bytes.len(), 192);
    }

    #[test]
    fn camera_set_model_computes_normals() {
        let mut cam = CameraUniforms::default();
        cam.set_model(IDENTITY_MAT4);
        // Identity model → identity normal matrix
        assert!((cam.normal_matrix_0[0] - 1.0).abs() < 0.001);
        assert!((cam.normal_matrix_1[1] - 1.0).abs() < 0.001);
        assert!((cam.normal_matrix_2[2] - 1.0).abs() < 0.001);
    }

    #[test]
    fn camera_set_model_non_uniform_scale() {
        let mut cam = CameraUniforms::default();
        // Non-uniform scale: 2x in X, 1x in Y, 0.5x in Z
        let mut model = IDENTITY_MAT4;
        model[0] = 2.0; // scale X
        model[10] = 0.5; // scale Z
        cam.set_model(model);
        // Normal matrix should compensate: X normals shrink, Z normals stretch
        assert!((cam.normal_matrix_0[0] - 0.5).abs() < 0.001); // 1/2
        assert!((cam.normal_matrix_1[1] - 1.0).abs() < 0.001); // 1/1
        assert!((cam.normal_matrix_2[2] - 2.0).abs() < 0.001); // 1/0.5
    }

    #[test]
    fn shadow_pass_uniforms_default() {
        let s = ShadowPassUniforms::default();
        assert_eq!(s.shadow_map_size[0], 2048.0);
        assert_eq!(s.light_view_proj[0], 1.0); // identity
    }

    #[test]
    fn shadow_pass_uniforms_bytemuck() {
        let s = ShadowPassUniforms::default();
        let bytes = bytemuck::bytes_of(&s);
        assert_eq!(bytes.len(), 80);
    }

    #[test]
    fn light_uniforms_bytemuck() {
        let light = LightUniforms::default();
        let bytes = bytemuck::bytes_of(&light);
        assert_eq!(bytes.len(), 112);
    }

    #[test]
    fn depth_buffer_format() {
        assert_eq!(DepthBuffer::FORMAT, wgpu::TextureFormat::Depth32Float);
    }

    #[test]
    fn camera_uniforms_set_model_singular() {
        // Adversarial: zero-determinant matrix must not produce NaN in normal matrix
        let mut cam = CameraUniforms::default();
        // All-zero matrix has determinant 0
        let zero_model = [0.0_f32; 16];
        cam.set_model(zero_model);
        for &v in &cam.normal_matrix_0 {
            assert!(!v.is_nan(), "normal_matrix_0 contains NaN");
        }
        for &v in &cam.normal_matrix_1 {
            assert!(!v.is_nan(), "normal_matrix_1 contains NaN");
        }
        for &v in &cam.normal_matrix_2 {
            assert!(!v.is_nan(), "normal_matrix_2 contains NaN");
        }

        // Singular but non-zero: two identical columns
        let mut singular = IDENTITY_MAT4;
        singular[4] = singular[0]; // col1 = col0
        singular[5] = singular[1];
        singular[6] = singular[2];
        cam.set_model(singular);
        for &v in &cam.normal_matrix_0 {
            assert!(
                !v.is_nan(),
                "normal_matrix_0 contains NaN for singular matrix"
            );
        }
        for &v in &cam.normal_matrix_1 {
            assert!(
                !v.is_nan(),
                "normal_matrix_1 contains NaN for singular matrix"
            );
        }
        for &v in &cam.normal_matrix_2 {
            assert!(
                !v.is_nan(),
                "normal_matrix_2 contains NaN for singular matrix"
            );
        }
    }
}