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
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
//! Standard Blinn-Phong mesh shader.

use std::borrow::Cow;

use glam::Mat4;

use crate::color::Color;
use crate::engine::Engine;
use crate::light3d::Material3D;
use crate::platform::types::TextureResource;

use super::geometry::DrawMode;
use super::mesh::Mesh3D;
use super::skinned::SkinnedMesh3D;
use super::vertex::Mesh3DVertex;

/// Resolved draw command with texture bind group
pub struct ResolvedDraw3DSkinned {
    pub mesh: SkinnedMesh3D,
    pub model: Mat4,
    pub color: Color,
    pub material: Material3D,
    pub bone_matrices: Vec<Mat4>,
    pub texture_bind_group: Option<wgpu::BindGroup>,
}

/// Uniform data for 3D mesh rendering
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable, Debug)]
struct Mesh3DUniform {
    // Matrices (16 floats each)
    mvp: [[f32; 4]; 4],
    model: [[f32; 4]; 4],
    // Camera
    camera_pos: [f32; 4], // w unused
    // Material
    diffuse: [f32; 4],
    specular: [f32; 4],
    emissive: [f32; 4],
    // Lighting
    ambient: [f32; 4],
    light_dir: [f32; 4], // direction for directional/spot lights
    light_color: [f32; 4],
    light_pos: [f32; 4], // position for point/spot, w = light type (0=dir, 1=point, 2=spot)
    light_params: [f32; 4], // x=radius, y=inner_angle, z=outer_angle, w=intensity
    // Misc
    shininess: f32,
    has_texture: f32,
    _padding: [f32; 2],
}

/// Maximum number of 3D draw calls per frame
const MAX_MESH3D_DRAWS: usize = 256;

pub struct Mesh3DShader {
    pipeline_solid: wgpu::RenderPipeline,
    pipeline_wireframe: wgpu::RenderPipeline,
    pipeline_points: wgpu::RenderPipeline,
    uniform: wgpu::Buffer,
    /// Alignment for dynamic uniform buffer offsets
    uniform_alignment: u32,
    #[allow(dead_code)]
    uniform_bind_group_layout: wgpu::BindGroupLayout,
    uniform_bind_group: wgpu::BindGroup,
    texture_bind_group_layout: wgpu::BindGroupLayout,
    /// Default white 1x1 texture used when no texture is specified
    #[allow(dead_code)]
    default_texture: TextureResource,
    default_texture_bind_group: wgpu::BindGroup,
    /// Cache for texture bind groups, keyed by texture pointer
    texture_bind_group_cache: hashbrown::HashMap<usize, wgpu::BindGroup>,
}

impl Mesh3DShader {
    /// Create a basic 3D mesh renderer targeting the surface format
    /// (works for offscreen textures created with the same format).
    pub fn new(g: &Engine) -> Self {
        let state = g.backend_state();
        let device = &state.device;
        let format = state.surface_view_format;

        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("mesh3d.shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
                "../../assets/shaders/mesh3d.wgsl"
            ))),
        });

        // Get the minimum uniform buffer offset alignment
        let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment;
        // Calculate aligned size for each uniform block
        let uniform_size = std::mem::size_of::<Mesh3DUniform>() as u32;
        let aligned_uniform_size = uniform_size.div_ceil(uniform_alignment) * uniform_alignment;

        // Create a large uniform buffer for dynamic offsets (supports up to MAX_MESH3D_DRAWS draw calls)
        let uniform = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("mesh3d.uniform"),
            size: (aligned_uniform_size as usize * MAX_MESH3D_DRAWS) as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let uniform_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("mesh3d.uniform_bgl"),
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: wgpu::BufferSize::new(uniform_size as u64),
                    },
                    count: None,
                }],
            });

        let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("mesh3d.uniform_bg"),
            layout: &uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                    buffer: &uniform,
                    offset: 0,
                    size: wgpu::BufferSize::new(uniform_size as u64),
                }),
            }],
        });

        // Texture bind group layout
        let texture_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("mesh3d.texture_bgl"),
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Texture {
                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
                            view_dimension: wgpu::TextureViewDimension::D2,
                            multisampled: false,
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                        count: None,
                    },
                ],
            });

        // Create default white 1x1 texture
        let default_texture = Self::create_default_texture(device, &state.queue);
        let default_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("mesh3d.default_texture_bg"),
            layout: &texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&default_texture.view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&default_texture.sampler),
                },
            ],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("mesh3d.pl"),
            bind_group_layouts: &[&uniform_bind_group_layout, &texture_bind_group_layout],
            push_constant_ranges: &[],
        });

        // Helper closure to create a pipeline with given settings
        let create_pipeline = |label: &str,
                               topology: wgpu::PrimitiveTopology,
                               polygon_mode: wgpu::PolygonMode,
                               cull_mode: Option<wgpu::Face>|
         -> wgpu::RenderPipeline {
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                    label: Some(label),
                    layout: Some(&pipeline_layout),
                    cache: None,
                    vertex: wgpu::VertexState {
                        module: &shader,
                        entry_point: Some("vs_main"),
                        buffers: &[wgpu::VertexBufferLayout {
                            array_stride: std::mem::size_of::<Mesh3DVertex>() as wgpu::BufferAddress,
                            step_mode: wgpu::VertexStepMode::Vertex,
                            attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x2],
                        }],
                        compilation_options: Default::default(),
                    },
                    fragment: Some(wgpu::FragmentState {
                        module: &shader,
                        entry_point: Some("fs_main"),
                        targets: &[Some(wgpu::ColorTargetState {
                            format,
                            blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                            write_mask: wgpu::ColorWrites::ALL,
                        })],
                        compilation_options: Default::default(),
                    }),
                    primitive: wgpu::PrimitiveState {
                        topology,
                        cull_mode,
                        front_face: wgpu::FrontFace::Ccw,
                        polygon_mode,
                        ..Default::default()
                    },
                    depth_stencil: Some(wgpu::DepthStencilState {
                        format: wgpu::TextureFormat::Depth32Float,
                        depth_write_enabled: true,
                        depth_compare: wgpu::CompareFunction::Greater,
                        stencil: wgpu::StencilState::default(),
                        bias: wgpu::DepthBiasState::default(),
                    }),
                    multisample: wgpu::MultisampleState::default(),
                    multiview: None,
                })
        };

        let pipeline_solid = create_pipeline(
            "mesh3d.pipeline.solid",
            wgpu::PrimitiveTopology::TriangleList,
            wgpu::PolygonMode::Fill,
            Some(wgpu::Face::Back),
        );
        // Note: True wireframe mode requires the POLYGON_MODE_LINE feature which
        // is not available on all platforms. We fall back to solid rendering.
        // TODO: Generate line indices from triangle indices for proper wireframe support
        let pipeline_wireframe = create_pipeline(
            "mesh3d.pipeline.wireframe",
            wgpu::PrimitiveTopology::TriangleList,
            wgpu::PolygonMode::Fill,
            None, // No culling for wireframe
        );
        // Points mode uses PointList topology - renders vertices as points
        let pipeline_points = create_pipeline(
            "mesh3d.pipeline.points",
            wgpu::PrimitiveTopology::PointList,
            wgpu::PolygonMode::Fill,
            None, // No culling for points
        );

        Self {
            pipeline_solid,
            pipeline_wireframe,
            pipeline_points,
            uniform,
            uniform_alignment,
            uniform_bind_group_layout,
            uniform_bind_group,
            texture_bind_group_layout,
            default_texture,
            default_texture_bind_group,
            texture_bind_group_cache: hashbrown::HashMap::new(),
        }
    }

    /// Create a default white 1x1 texture
    pub(super) fn create_default_texture(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
    ) -> TextureResource {
        let size = wgpu::Extent3d {
            width: 1,
            height: 1,
            depth_or_array_layers: 1,
        };
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("mesh3d.default_texture"),
            size,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        // White pixel
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &[255u8, 255, 255, 255],
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(4),
                rows_per_image: Some(1),
            },
            size,
        );
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });
        TextureResource {
            texture,
            view,
            sampler,
        }
    }

    /// Clear texture bind group cache at frame start
    pub fn frame_start(&mut self) {
        self.texture_bind_group_cache.clear();
    }

    /// Create a texture bind group for a given texture resource
    fn create_texture_bind_group(
        &self,
        device: &wgpu::Device,
        texture: &TextureResource,
    ) -> wgpu::BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("mesh3d.texture_bg"),
            layout: &self.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&texture.view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&texture.sampler),
                },
            ],
        })
    }

    /// Get or create a cached texture bind group
    fn get_or_create_texture_bind_group(
        &mut self,
        device: &wgpu::Device,
        texture: &TextureResource,
    ) {
        let key = std::ptr::from_ref(&texture.texture) as usize;
        if !self.texture_bind_group_cache.contains_key(&key) {
            let bg = self.create_texture_bind_group(device, texture);
            self.texture_bind_group_cache.insert(key, bg);
        }
    }

    /// Record drawing of meshes into the provided encoder.
    /// Each mesh is drawn with its own model matrix, optional texture, color, material, and draw mode.
    /// If `should_clear` is true, clears color and depth at start of pass.
    #[allow(clippy::type_complexity)]
    #[allow(clippy::too_many_arguments)]
    pub fn record_to_encoder(
        &mut self,
        g: &Engine,
        color_target: &wgpu::Texture,
        depth_view: &wgpu::TextureView,
        view_proj: Mat4,
        draws: &[(
            &Mesh3D,
            Mat4,
            Option<&TextureResource>,
            Color,
            &crate::light3d::Material3D,
            DrawMode,
        )],
        encoder: &mut wgpu::CommandEncoder,
        should_clear: bool,
    ) {
        let color_view = color_target.create_view(&wgpu::TextureViewDescriptor::default());
        let state = g.backend_state();
        let lighting = g.lighting();
        let camera = g.camera3d();

        // Get the first enabled light of any type
        let (light_dir, light_color, light_pos, light_params) = lighting
            .lights
            .iter()
            .flatten()
            .find(|l| l.enabled)
            .map(|l| {
                use crate::light3d::LightKind;
                let (light_type, radius, inner_angle, outer_angle) = match l.kind {
                    LightKind::Directional => (0.0, 0.0, 0.0, 0.0),
                    LightKind::Point { radius } => (1.0, radius, 0.0, 0.0),
                    LightKind::Spot {
                        radius,
                        inner_angle,
                        outer_angle,
                    } => (2.0, radius, inner_angle, outer_angle),
                };
                (
                    l.direction,
                    l.color,
                    [l.position.x, l.position.y, l.position.z, light_type],
                    [radius, inner_angle, outer_angle, l.intensity],
                )
            })
            .unwrap_or_else(|| {
                (
                    glam::Vec3::new(0.5, -1.0, -0.5).normalize(),
                    Color::rgb(1.0, 1.0, 1.0),
                    [0.0, 0.0, 0.0, 0.0], // Directional light by default
                    [0.0, 0.0, 0.0, 1.0], // Intensity = 1.0
                )
            });

        // Calculate aligned uniform size
        let uniform_size = std::mem::size_of::<Mesh3DUniform>() as u32;
        let aligned_uniform_size =
            uniform_size.div_ceil(self.uniform_alignment) * self.uniform_alignment;

        // Pre-compute all uniform data and cache texture bind groups BEFORE the render pass
        let draw_count = draws.len().min(MAX_MESH3D_DRAWS);
        let mut uniform_data_buffer = vec![0u8; aligned_uniform_size as usize * draw_count];

        // First pass: populate bind group cache and build uniform data
        for (i, (_, model, texture_res, color, material, _)) in
            draws.iter().take(draw_count).enumerate()
        {
            let mvp = view_proj * *model;

            // Cache texture bind group and determine has_texture flag
            let has_texture = if let Some(tex_res) = texture_res {
                // Populate cache (this is idempotent for same texture)
                self.get_or_create_texture_bind_group(&state.device, tex_res);
                1.0f32
            } else {
                0.0f32
            };

            // Combine material diffuse with color tint
            let diffuse = Color::rgba(
                material.diffuse.r * color.r,
                material.diffuse.g * color.g,
                material.diffuse.b * color.b,
                material.diffuse.a * color.a,
            );

            // Build uniform data
            let uniform_data = Mesh3DUniform {
                mvp: mvp.to_cols_array_2d(),
                model: model.to_cols_array_2d(),
                camera_pos: [camera.eye.x, camera.eye.y, camera.eye.z, 0.0],
                diffuse: [diffuse.r, diffuse.g, diffuse.b, diffuse.a],
                specular: [
                    material.specular.r,
                    material.specular.g,
                    material.specular.b,
                    material.specular.a,
                ],
                emissive: [
                    material.emissive.r,
                    material.emissive.g,
                    material.emissive.b,
                    material.emissive.a,
                ],
                ambient: [
                    lighting.ambient.r,
                    lighting.ambient.g,
                    lighting.ambient.b,
                    lighting.ambient.a,
                ],
                light_dir: [light_dir.x, light_dir.y, light_dir.z, 0.0],
                light_color: [light_color.r, light_color.g, light_color.b, light_color.a],
                light_pos,
                light_params,
                shininess: material.shininess,
                has_texture,
                _padding: [0.0; 2],
            };

            // Copy uniform data to the buffer at the correct offset
            let offset = i * aligned_uniform_size as usize;
            let uniform_bytes = bytemuck::bytes_of(&uniform_data);
            uniform_data_buffer[offset..offset + uniform_bytes.len()]
                .copy_from_slice(uniform_bytes);
        }

        // Write all uniform data to GPU at once, BEFORE the render pass
        state
            .queue
            .write_buffer(&self.uniform, 0, &uniform_data_buffer);

        // Now begin the render pass
        let (color_load, depth_load) = if should_clear {
            (
                wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                wgpu::LoadOp::Clear(0.0),
            )
        } else {
            (wgpu::LoadOp::Load, wgpu::LoadOp::Load)
        };
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("mesh3d.pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &color_view,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: color_load,
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                    view: depth_view,
                    depth_ops: Some(wgpu::Operations {
                        load: depth_load,
                        store: wgpu::StoreOp::Store,
                    }),
                    stencil_ops: None,
                }),
                occlusion_query_set: None,
                timestamp_writes: None,
            });

            // Track current pipeline to avoid redundant switches
            let mut current_mode: Option<DrawMode> = None;

            for (i, (mesh, _, texture_res, _, _, draw_mode)) in
                draws.iter().take(draw_count).enumerate()
            {
                // Set pipeline if mode changed
                if current_mode != Some(*draw_mode) {
                    current_mode = Some(*draw_mode);
                    let pipeline = match draw_mode {
                        DrawMode::Solid => &self.pipeline_solid,
                        DrawMode::Wireframe => &self.pipeline_wireframe,
                        DrawMode::Points => &self.pipeline_points,
                    };
                    pass.set_pipeline(pipeline);
                }

                // Set uniform bind group with dynamic offset for this draw call
                let dynamic_offset = (i as u32) * aligned_uniform_size;
                pass.set_bind_group(0, &self.uniform_bind_group, &[dynamic_offset]);

                // Set texture bind group from cache
                if let Some(tex_res) = texture_res {
                    let key = std::ptr::from_ref(&tex_res.texture) as usize;
                    if let Some(bg) = self.texture_bind_group_cache.get(&key) {
                        pass.set_bind_group(1, bg, &[]);
                    } else {
                        pass.set_bind_group(1, &self.default_texture_bind_group, &[]);
                    }
                } else {
                    pass.set_bind_group(1, &self.default_texture_bind_group, &[]);
                }

                pass.set_vertex_buffer(0, mesh.vertex.slice(..));
                pass.set_index_buffer(mesh.index.slice(..), wgpu::IndexFormat::Uint16);
                pass.draw_indexed(0..mesh.index_count, 0, 0..1);
            }
        }
    }
}