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
//! Skybox rendering for 3D scenes.
//!
//! A skybox is a large cube that surrounds the entire scene and displays
//! environment textures (like sky, clouds, distant scenery) at infinity.

use image::DynamicImage;

use crate::engine::Engine;

/// Shader source for skybox
const SKYBOX_SHADER_SOURCE: &str = include_str!("../assets/shaders/skybox.wgsl");

/// Skybox uniform data
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct SkyboxUniform {
    /// View-projection matrix (without translation)
    view_proj: [[f32; 4]; 4],
}

/// Cubemap texture resource for skybox
pub struct CubemapTexture {
    pub(crate) view: wgpu::TextureView,
    pub(crate) sampler: wgpu::Sampler,
}

impl CubemapTexture {
    /// Create a cubemap from 6 face images.
    ///
    /// Face order: +X (right), -X (left), +Y (top), -Y (bottom), +Z (front), -Z (back)
    pub fn from_faces(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        faces: [&DynamicImage; 6],
    ) -> Self {
        // All faces must have the same dimensions
        let (width, height) = faces[0].to_rgba8().dimensions();
        for face in &faces[1..] {
            let (w, h) = face.to_rgba8().dimensions();
            assert_eq!(
                (width, height),
                (w, h),
                "All cubemap faces must have the same dimensions"
            );
        }

        let size = wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 6, // 6 faces
        };

        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("Cubemap 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: &[],
        });

        // Upload each face
        for (i, face) in faces.iter().enumerate() {
            let rgba = face.to_rgba8();
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d {
                        x: 0,
                        y: 0,
                        z: i as u32,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                &rgba,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(4 * width),
                    rows_per_image: Some(height),
                },
                wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
            );
        }

        let view = texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some("Cubemap View"),
            format: Some(wgpu::TextureFormat::Rgba8UnormSrgb),
            dimension: Some(wgpu::TextureViewDimension::Cube),
            usage: None,
            aspect: wgpu::TextureAspect::All,
            base_mip_level: 0,
            mip_level_count: None,
            base_array_layer: 0,
            array_layer_count: Some(6),
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("Cubemap Sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });

        Self { view, sampler }
    }

    /// Create a cubemap from 6 raw image byte arrays.
    ///
    /// Face order: +X (right), -X (left), +Y (top), -Y (bottom), +Z (front), -Z (back)
    #[allow(clippy::too_many_arguments)]
    pub fn from_face_bytes(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        right: &[u8],
        left: &[u8],
        top: &[u8],
        bottom: &[u8],
        front: &[u8],
        back: &[u8],
    ) -> Result<Self, image::ImageError> {
        let faces = [
            image::load_from_memory(right)?,
            image::load_from_memory(left)?,
            image::load_from_memory(top)?,
            image::load_from_memory(bottom)?,
            image::load_from_memory(front)?,
            image::load_from_memory(back)?,
        ];
        Ok(Self::from_faces(
            device,
            queue,
            [
                &faces[0], &faces[1], &faces[2], &faces[3], &faces[4], &faces[5],
            ],
        ))
    }

    /// Create a solid color cubemap (useful for testing or simple backgrounds)
    pub fn solid_color(device: &wgpu::Device, queue: &wgpu::Queue, color: [u8; 4]) -> Self {
        // Create a 1x1 pixel for each face
        let pixel_data = vec![color[0], color[1], color[2], color[3]];
        let img = DynamicImage::ImageRgba8(image::RgbaImage::from_raw(1, 1, pixel_data).unwrap());
        Self::from_faces(device, queue, [&img, &img, &img, &img, &img, &img])
    }
}

/// Skybox for 3D scene backgrounds.
///
/// The skybox is rendered at infinity (always behind all other objects)
/// and follows the camera's rotation but not its position.
pub struct Skybox {
    pub(crate) cubemap: CubemapTexture,
}

impl Skybox {
    /// Create a skybox from 6 face images.
    ///
    /// # Arguments
    /// * `g` - Engine reference for GPU access
    /// * `faces` - Array of 6 images in order: +X (right), -X (left), +Y (top), -Y (bottom), +Z (front), -Z (back)
    pub fn from_faces(g: &Engine, faces: [&DynamicImage; 6]) -> Self {
        let cubemap = CubemapTexture::from_faces(
            &g.render.backend_state.device,
            &g.render.backend_state.queue,
            faces,
        );
        Self { cubemap }
    }

    /// Create a skybox from 6 face image byte arrays.
    ///
    /// # Arguments
    /// * `g` - Engine reference for GPU access
    /// * `right`, `left`, `top`, `bottom`, `front`, `back` - Image data for each face
    pub fn from_face_bytes(
        g: &Engine,
        right: &[u8],
        left: &[u8],
        top: &[u8],
        bottom: &[u8],
        front: &[u8],
        back: &[u8],
    ) -> Result<Self, image::ImageError> {
        let cubemap = CubemapTexture::from_face_bytes(
            &g.render.backend_state.device,
            &g.render.backend_state.queue,
            right,
            left,
            top,
            bottom,
            front,
            back,
        )?;
        Ok(Self { cubemap })
    }

    /// Create a solid color skybox.
    pub fn solid_color(g: &Engine, r: u8, g_color: u8, b: u8) -> Self {
        let cubemap = CubemapTexture::solid_color(
            &g.render.backend_state.device,
            &g.render.backend_state.queue,
            [r, g_color, b, 255],
        );
        Self { cubemap }
    }
}

/// Skybox shader/renderer
pub struct SkyboxShader {
    pipeline: wgpu::RenderPipeline,
    uniform_buffer: wgpu::Buffer,
    uniform_bind_group: wgpu::BindGroup,
    texture_bind_group_layout: wgpu::BindGroupLayout,
}

impl SkyboxShader {
    pub fn new(g: &Engine) -> Self {
        let device = &g.render.backend_state.device;

        // Compile shader
        let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Skybox Shader"),
            source: wgpu::ShaderSource::Wgsl(SKYBOX_SHADER_SOURCE.into()),
        });

        // Uniform buffer
        let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Skybox Uniform Buffer"),
            size: std::mem::size_of::<SkyboxUniform>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        // Uniform bind group layout
        let uniform_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("Skybox Uniform Bind Group Layout"),
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
            });

        // Uniform bind group
        let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Skybox Uniform Bind Group"),
            layout: &uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

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

        // Pipeline layout
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Skybox Pipeline Layout"),
            bind_group_layouts: &[&uniform_bind_group_layout, &texture_bind_group_layout],
            push_constant_ranges: &[],
        });

        // Render pipeline
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Skybox Pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader_module,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[], // No vertex buffers - we generate vertices in shader
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader_module,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: g.render.backend_state.surface_view_format,
                    blend: None, // No blending needed for skybox
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None, // Don't cull - we're inside the cube
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            // Depth test: pass if depth <= existing (with reverse-Z, skybox at 0.0 will be behind everything)
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth32Float,
                depth_write_enabled: false, // Don't write to depth buffer
                depth_compare: wgpu::CompareFunction::LessEqual, // For reverse-Z: 0.0 is far
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview: None,
            cache: None,
        });

        Self {
            pipeline,
            uniform_buffer,
            uniform_bind_group,
            texture_bind_group_layout,
        }
    }

    /// Render the skybox.
    pub fn record(
        &self,
        g: &Engine,
        render_target: &wgpu::Texture,
        depth_view: &wgpu::TextureView,
        skybox: &Skybox,
        encoder: &mut wgpu::CommandEncoder,
        should_clear: bool,
    ) {
        let device = &g.render.backend_state.device;
        let queue = &g.render.backend_state.queue;

        // Calculate aspect ratio
        let size = render_target.size();
        let aspect = if size.height == 0 {
            1.0
        } else {
            size.width as f32 / size.height as f32
        };

        // Get camera matrices
        let camera = g.camera3d();
        let projection = camera.projection_matrix(aspect);

        // View matrix WITHOUT translation (skybox is always at infinity)
        let mut view = camera.view_matrix();
        // Remove translation by setting the last column to (0, 0, 0, 1)
        view.w_axis.x = 0.0;
        view.w_axis.y = 0.0;
        view.w_axis.z = 0.0;

        let view_proj = projection * view;

        // Update uniform buffer
        let uniform = SkyboxUniform {
            view_proj: view_proj.to_cols_array_2d(),
        };
        queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[uniform]));

        // Create texture bind group for this skybox's cubemap
        let texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Skybox Texture Bind Group"),
            layout: &self.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&skybox.cubemap.view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&skybox.cubemap.sampler),
                },
            ],
        });

        // Create render pass
        let view = render_target.create_view(&wgpu::TextureViewDescriptor::default());
        let (color_load, depth_load) = if should_clear {
            (
                wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                wgpu::LoadOp::Clear(0.0), // Reverse-Z: far plane is 0.0
            )
        } else {
            (wgpu::LoadOp::Load, wgpu::LoadOp::Load)
        };

        let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("Skybox Render Pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: &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,
        });

        render_pass.set_pipeline(&self.pipeline);
        render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
        render_pass.set_bind_group(1, &texture_bind_group, &[]);

        // Draw 36 vertices (12 triangles = 6 faces * 2 triangles each)
        render_pass.draw(0..36, 0..1);
    }
}