Skip to main content

strata_render/
gpu3d.rs

1//! Hardware-Accelerated 3D GPU Render Pipeline and WGSL Shaders.
2//!
3//! Provides direct GPU vertex and fragment pipelines with depth-stencil textures (`Depth32Float`),
4//! uniform buffers for model-view-projection matrices, multi-light Blinn-Phong shading,
5//! and compositing the rendered 3D viewport into the 2D display list.
6
7use crate::camera64::DVec3;
8use crate::gpu_context::{GpuBufferHandle, GpuBufferUsage, GpuDevice, GpuRenderPassDescriptor};
9use crate::math3d::{Mat4, Vec3};
10use crate::scene3d::{Camera3D, Light3D, Material3D, Scene3D};
11use strata_layout::Rect;
12
13/// Standard WGSL shader for hardware-accelerated 3D meshes with depth testing and lighting.
14pub const WGSL_3D_STANDARD_SHADER: &str = r#"
15struct VertexInput {
16    @location(0) position: vec3<f32>,
17    @location(1) normal: vec3<f32>,
18    @location(2) uv: vec2<f32>,
19};
20
21struct VertexOutput {
22    @builtin(position) clip_position: vec4<f32>,
23    @location(0) world_pos: vec3<f32>,
24    @location(1) world_normal: vec3<f32>,
25    @location(2) uv: vec2<f32>,
26};
27
28struct Uniforms {
29    model_matrix: mat4x4<f32>,
30    view_proj_matrix: mat4x4<f32>,
31    normal_matrix: mat4x4<f32>,
32    camera_pos: vec3<f32>,
33    _pad0: f32,
34    ambient_color: vec3<f32>,
35    _pad1: f32,
36    dir_light_dir: vec3<f32>,
37    _pad2: f32,
38    dir_light_color: vec3<f32>,
39    _pad3: f32,
40    material_color: vec4<f32>,
41    roughness: f32,
42    metalness: f32,
43    _pad4: vec2<f32>,
44};
45
46@group(0) @binding(0) var<uniform> uniforms: Uniforms;
47
48@vertex
49fn vs_main(model: VertexInput) -> VertexOutput {
50    var out: VertexOutput;
51
52    let world_pos = uniforms.model_matrix * vec4<f32>(model.position, 1.0);
53    out.world_pos = world_pos.xyz;
54    out.clip_position = uniforms.view_proj_matrix * world_pos;
55    out.world_normal = normalize((uniforms.normal_matrix * vec4<f32>(model.normal, 0.0)).xyz);
56    out.uv = model.uv;
57
58    return out;
59}
60
61@fragment
62fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
63    let N = normalize(in.world_normal);
64    let V = normalize(uniforms.camera_pos - in.world_pos);
65    let L = normalize(-uniforms.dir_light_dir);
66    let H = normalize(L + V);
67
68    // Ambient
69    let ambient = uniforms.ambient_color * uniforms.material_color.rgb;
70
71    // Diffuse
72    let diff = max(dot(N, L), 0.0);
73    let diffuse = diff * uniforms.dir_light_color * uniforms.material_color.rgb;
74
75    // Specular (Blinn-Phong)
76    let spec = pow(max(dot(N, H), 0.0), max((1.0 - uniforms.roughness) * 64.0, 1.0));
77    let specular = spec * uniforms.dir_light_color * mix(vec3<f32>(0.04), uniforms.material_color.rgb, uniforms.metalness);
78
79    let final_color = ambient + diffuse + specular;
80    return vec4<f32>(final_color, uniforms.material_color.a);
81}
82"#;
83
84/// Standard WGSL shader for Relative-To-Eye (RTE) double-single 3D meshes on GPU.
85///
86/// Prevents 32-bit vertex jitter and shaking at planetary coordinates (~6.378e6 m)
87/// by evaluating relative subtraction `(pos_high - eye_high) + (pos_low - eye_low)`
88/// directly inside the GPU vertex shader.
89pub const WGSL_3D_RTE_SHADER: &str = r#"
90struct RteVertexInput {
91    @location(0) position_high: vec3<f32>,
92    @location(1) position_low: vec3<f32>,
93    @location(2) normal: vec3<f32>,
94    @location(3) uv: vec2<f32>,
95};
96
97struct RteVertexOutput {
98    @builtin(position) clip_position: vec4<f32>,
99    @location(0) view_relative_pos: vec3<f32>,
100    @location(1) world_normal: vec3<f32>,
101    @location(2) uv: vec2<f32>,
102};
103
104struct RteUniforms {
105    view_proj_relative: mat4x4<f32>,
106    normal_matrix: mat4x4<f32>,
107    eye_high: vec3<f32>,
108    _pad0: f32,
109    eye_low: vec3<f32>,
110    _pad1: f32,
111    ambient_color: vec3<f32>,
112    _pad2: f32,
113    dir_light_dir: vec3<f32>,
114    _pad3: f32,
115    dir_light_color: vec3<f32>,
116    _pad4: f32,
117    material_color: vec4<f32>,
118    roughness: f32,
119    metalness: f32,
120    _pad5: vec2<f32>,
121};
122
123@group(0) @binding(0) var<uniform> uniforms: RteUniforms;
124
125@vertex
126fn vs_rte_main(input: RteVertexInput) -> RteVertexOutput {
127    var out: RteVertexOutput;
128
129    // Double-single Relative-To-Eye (RTE) subtraction on GPU
130    let rel_high = input.position_high - uniforms.eye_high;
131    let rel_low = input.position_low - uniforms.eye_low;
132    let rel_pos = rel_high + rel_low;
133
134    out.view_relative_pos = rel_pos;
135    out.clip_position = uniforms.view_proj_relative * vec4<f32>(rel_pos, 1.0);
136    out.world_normal = normalize((uniforms.normal_matrix * vec4<f32>(input.normal, 0.0)).xyz);
137    out.uv = input.uv;
138
139    return out;
140}
141
142@fragment
143fn fs_rte_main(in: RteVertexOutput) -> @location(0) vec4<f32> {
144    let N = normalize(in.world_normal);
145    let V = normalize(-in.view_relative_pos);
146    let L = normalize(-uniforms.dir_light_dir);
147    let H = normalize(L + V);
148
149    // Ambient
150    let ambient = uniforms.ambient_color * uniforms.material_color.rgb;
151
152    // Diffuse
153    let diff = max(dot(N, L), 0.0);
154    let diffuse = diff * uniforms.dir_light_color * uniforms.material_color.rgb;
155
156    // Specular (Blinn-Phong)
157    let spec = pow(max(dot(N, H), 0.0), max((1.0 - uniforms.roughness) * 64.0, 1.0));
158    let specular = spec * uniforms.dir_light_color * mix(vec3<f32>(0.04), uniforms.material_color.rgb, uniforms.metalness);
159
160    let final_color = ambient + diffuse + specular;
161    return vec4<f32>(final_color, uniforms.material_color.a);
162}
163"#;
164
165/// 3D vertex layout for GPU vertex buffer upload.
166#[repr(C)]
167#[derive(Debug, Clone, Copy, PartialEq, Default)]
168pub struct Gpu3DVertex {
169    pub position: [f32; 3],
170    pub normal: [f32; 3],
171    pub uv: [f32; 2],
172}
173
174/// Packed uniform buffer data for 3D shaders.
175#[repr(C)]
176#[derive(Debug, Clone, Copy, PartialEq)]
177pub struct Gpu3DUniforms {
178    pub model_matrix: [[f32; 4]; 4],
179    pub view_proj_matrix: [[f32; 4]; 4],
180    pub normal_matrix: [[f32; 4]; 4],
181    pub camera_pos: [f32; 3],
182    pub _pad0: f32,
183    pub ambient_color: [f32; 3],
184    pub _pad1: f32,
185    pub dir_light_dir: [f32; 3],
186    pub _pad2: f32,
187    pub dir_light_color: [f32; 3],
188    pub _pad3: f32,
189    pub material_color: [f32; 4],
190    pub roughness: f32,
191    pub metalness: f32,
192    pub _pad4: [f32; 2],
193}
194
195#[inline]
196pub fn mat4_to_cols_2d(m: &Mat4) -> [[f32; 4]; 4] {
197    [
198        [m.m[0], m.m[1], m.m[2], m.m[3]],
199        [m.m[4], m.m[5], m.m[6], m.m[7]],
200        [m.m[8], m.m[9], m.m[10], m.m[11]],
201        [m.m[12], m.m[13], m.m[14], m.m[15]],
202    ]
203}
204
205impl Gpu3DUniforms {
206    /// Safe byte view for uploading to GPU uniform buffer.
207    pub fn as_bytes(&self) -> &[u8] {
208        unsafe {
209            std::slice::from_raw_parts(
210                self as *const Self as *const u8,
211                std::mem::size_of::<Self>(),
212            )
213        }
214    }
215}
216
217impl Default for Gpu3DUniforms {
218    fn default() -> Self {
219        let id = mat4_to_cols_2d(&Mat4::IDENTITY);
220        Self {
221            model_matrix: id,
222            view_proj_matrix: id,
223            normal_matrix: id,
224            camera_pos: [0.0, 0.0, 5.0],
225            _pad0: 0.0,
226            ambient_color: [0.2, 0.2, 0.25],
227            _pad1: 0.0,
228            dir_light_dir: [-0.5, -1.0, -0.5],
229            _pad2: 0.0,
230            dir_light_color: [0.9, 0.9, 0.85],
231            _pad3: 0.0,
232            material_color: [0.8, 0.8, 0.8, 1.0],
233            roughness: 0.4,
234            metalness: 0.1,
235            _pad4: [0.0, 0.0],
236        }
237    }
238}
239
240/// 3D vertex layout for GPU Relative-To-Eye (RTE) double-single vertex buffer upload.
241///
242/// Stores position split into high and low 32-bit floats (`vec3<f32> high`, `vec3<f32> low`),
243/// eliminating 32-bit floating point precision loss at planetary scales.
244#[repr(C)]
245#[derive(Debug, Clone, Copy, PartialEq, Default)]
246pub struct GpuRteVertex {
247    pub position_high: [f32; 3],
248    pub position_low: [f32; 3],
249    pub normal: [f32; 3],
250    pub uv: [f32; 2],
251}
252
253impl GpuRteVertex {
254    pub const STRIDE_FLOATS: usize = 11; // 11 floats = 44 bytes
255
256    pub fn new(position: DVec3, normal: [f32; 3], uv: [f32; 2]) -> Self {
257        let (high, low) = position.split_high_low();
258        Self {
259            position_high: high,
260            position_low: low,
261            normal,
262            uv,
263        }
264    }
265}
266
267/// Packed uniform buffer data for Relative-To-Eye (RTE) 3D shaders.
268#[repr(C)]
269#[derive(Debug, Clone, Copy, PartialEq)]
270pub struct GpuRteUniforms {
271    pub view_proj_relative: [[f32; 4]; 4],
272    pub normal_matrix: [[f32; 4]; 4],
273    pub eye_high: [f32; 3],
274    pub _pad0: f32,
275    pub eye_low: [f32; 3],
276    pub _pad1: f32,
277    pub ambient_color: [f32; 3],
278    pub _pad2: f32,
279    pub dir_light_dir: [f32; 3],
280    pub _pad3: f32,
281    pub dir_light_color: [f32; 3],
282    pub _pad4: f32,
283    pub material_color: [f32; 4],
284    pub roughness: f32,
285    pub metalness: f32,
286    pub _pad5: [f32; 2],
287}
288
289impl GpuRteUniforms {
290    /// Safe byte view for uploading to GPU uniform buffer.
291    pub fn as_bytes(&self) -> &[u8] {
292        unsafe {
293            std::slice::from_raw_parts(
294                self as *const Self as *const u8,
295                std::mem::size_of::<Self>(),
296            )
297        }
298    }
299}
300
301impl Default for GpuRteUniforms {
302    fn default() -> Self {
303        let id = mat4_to_cols_2d(&Mat4::IDENTITY);
304        Self {
305            view_proj_relative: id,
306            normal_matrix: id,
307            eye_high: [0.0, 0.0, 0.0],
308            _pad0: 0.0,
309            eye_low: [0.0, 0.0, 0.0],
310            _pad1: 0.0,
311            ambient_color: [0.2, 0.2, 0.25],
312            _pad2: 0.0,
313            dir_light_dir: [-0.5, -1.0, -0.5],
314            _pad3: 0.0,
315            dir_light_color: [0.9, 0.9, 0.85],
316            _pad4: 0.0,
317            material_color: [0.8, 0.8, 0.8, 1.0],
318            roughness: 0.4,
319            metalness: 0.1,
320            _pad5: [0.0, 0.0],
321        }
322    }
323}
324
325/// Hardware GPU 3D rendering pipeline managing vertex/index buffers and draw passes.
326pub struct Gpu3DPipeline {
327    pub vertex_buffer: GpuBufferHandle,
328    pub index_buffer: GpuBufferHandle,
329    pub uniform_buffer: GpuBufferHandle,
330    pub depth_stencil: crate::gpu_pipeline::GpuDepthStencilState,
331    pub viewport_width: u32,
332    pub viewport_height: u32,
333    pub early_z_culled_fragments: usize,
334    pub total_tested_fragments: usize,
335}
336
337impl Gpu3DPipeline {
338    /// Creates a new 3D GPU pipeline on the specified device.
339    pub fn new(device: &GpuDevice, width: u32, height: u32) -> Self {
340        let vb = device.create_buffer(1024 * 1024, GpuBufferUsage::Vertex);
341        let ib = device.create_buffer(512 * 1024, GpuBufferUsage::Index);
342        let ub = device.create_buffer(
343            std::mem::size_of::<Gpu3DUniforms>(),
344            GpuBufferUsage::Uniform,
345        );
346
347        Self {
348            vertex_buffer: vb,
349            index_buffer: ib,
350            uniform_buffer: ub,
351            depth_stencil: crate::gpu_pipeline::GpuDepthStencilState::default(),
352            viewport_width: width,
353            viewport_height: height,
354            early_z_culled_fragments: 0,
355            total_tested_fragments: 0,
356        }
357    }
358
359    /// Evaluates hardware early-Z fragment occlusion test, updating occlusion stats.
360    pub fn test_early_z(&mut self, current_depth: f32, new_depth: f32) -> bool {
361        self.total_tested_fragments += 1;
362        if self.depth_stencil.passes_test(current_depth, new_depth) {
363            true
364        } else {
365            self.early_z_culled_fragments += 1;
366            false
367        }
368    }
369
370    /// Renders a Scene3D directly onto the hardware GPU device target, resolving any
371    /// [`crate::texture3d::TextureStore`] attached to `scene`.
372    pub fn render_scene(
373        &mut self,
374        device: &mut GpuDevice,
375        scene: &Scene3D,
376        viewport: Rect,
377        clip: Option<Rect>,
378    ) {
379        self.render_scene_with_textures(device, scene, viewport, clip, scene.textures_deref());
380    }
381
382    /// Renders a Scene3D onto the hardware GPU device target using `textures` (or `scene.textures_deref()`).
383    pub fn render_scene_with_textures(
384        &mut self,
385        device: &mut GpuDevice,
386        scene: &Scene3D,
387        viewport: Rect,
388        clip: Option<Rect>,
389        textures: Option<&crate::texture3d::TextureStore>,
390    ) {
391        let eff_textures = textures.or_else(|| scene.textures_deref());
392        let mut encoder = device.create_command_encoder();
393
394        let pass_desc = GpuRenderPassDescriptor {
395            color_texture_id: device.swapchain_texture.id,
396            depth_texture_id: Some(device.depth_texture.id),
397            clear_color: Some([0.05, 0.05, 0.06, 1.0]),
398            clear_depth: Some(1.0),
399            scissor_rect: clip.or(Some(viewport)),
400        };
401
402        encoder.begin_render_pass(pass_desc);
403
404        // Upload uniforms
405        let mut uniforms = Gpu3DUniforms::default();
406        let aspect = viewport.width / viewport.height.max(1.0);
407        let up_vec = scene
408            .camera_up()
409            .map(|u| Vec3::new(u[0] as f32, u[1] as f32, u[2] as f32))
410            .unwrap_or(Vec3::UP);
411        let (proj_mat, view_mat, cam_pos) = match &scene.camera {
412            Camera3D::Perspective {
413                fov_horizontal_deg,
414                near,
415                far,
416                position,
417                target,
418            } => {
419                let fov_x = fov_horizontal_deg.to_radians();
420                let fov_y = 2.0 * ((fov_x * 0.5).tan() / aspect).atan();
421                let p = Mat4::perspective(fov_y, aspect, *near, *far);
422                let eye = Vec3::new(position[0], position[1], position[2]);
423                let tgt = Vec3::new(target[0], target[1], target[2]);
424                let v = Mat4::look_at(eye, tgt, up_vec);
425                (p, v, *position)
426            }
427            Camera3D::Orthographic {
428                left,
429                right,
430                top,
431                bottom,
432                near,
433                far,
434                position,
435                target,
436            } => {
437                let p = Mat4::orthographic(*left, *right, *bottom, *top, *near, *far);
438                let eye = Vec3::new(position[0], position[1], position[2]);
439                let tgt = Vec3::new(target[0], target[1], target[2]);
440                let v = Mat4::look_at(eye, tgt, up_vec);
441                (p, v, *position)
442            }
443        };
444
445        let view_proj = proj_mat.multiply(&view_mat);
446        uniforms.view_proj_matrix = mat4_to_cols_2d(&view_proj);
447        uniforms.camera_pos = cam_pos;
448
449        // Process lights
450        for light in &scene.lights {
451            match light {
452                Light3D::Ambient { color, intensity } => {
453                    let (r, g, b, _) = color.to_f32();
454                    uniforms.ambient_color = [r * intensity, g * intensity, b * intensity];
455                }
456                Light3D::Directional {
457                    position,
458                    color,
459                    intensity,
460                    ..
461                } => {
462                    let dir = Vec3::new(position[0], position[1], position[2]).normalize();
463                    uniforms.dir_light_dir = [dir.x, dir.y, dir.z];
464                    let (r, g, b, _) = color.to_f32();
465                    uniforms.dir_light_color = [r * intensity, g * intensity, b * intensity];
466                }
467                _ => {}
468            }
469        }
470
471        // Draw meshes
472        for mesh in &scene.meshes {
473            let t = Vec3::new(
474                mesh.transform.position[0],
475                mesh.transform.position[1],
476                mesh.transform.position[2],
477            );
478            let r = Vec3::new(
479                mesh.transform.rotation[0],
480                mesh.transform.rotation[1],
481                mesh.transform.rotation[2],
482            );
483            let s = Vec3::new(
484                mesh.transform.scale[0],
485                mesh.transform.scale[1],
486                mesh.transform.scale[2],
487            );
488            let model_mat = Mat4::from_trs(t, r, s);
489            let normal_mat = model_mat.inverse().unwrap_or(Mat4::IDENTITY).transpose();
490
491            uniforms.model_matrix = mat4_to_cols_2d(&model_mat);
492            uniforms.normal_matrix = mat4_to_cols_2d(&normal_mat);
493
494            let mesh_index_count: usize = match &mesh.geometry {
495                crate::scene3d::Geometry3D::Custom { indices, .. }
496                | crate::scene3d::Geometry3D::CustomTextured { indices, .. } => indices.len(),
497                _ => 36,
498            };
499
500            match &mesh.material {
501                Material3D::Standard {
502                    color,
503                    roughness,
504                    metalness,
505                    ..
506                } => {
507                    let (r, g, b, a) = color.to_f32();
508                    uniforms.material_color = [r, g, b, a];
509                    uniforms.roughness = *roughness;
510                    uniforms.metalness = *metalness;
511                    self.uniform_buffer.write_bytes(0, uniforms.as_bytes());
512                    encoder.draw_indexed(mesh_index_count.max(3), 1);
513                }
514                Material3D::Basic { color } => {
515                    let (r, g, b, a) = color.to_f32();
516                    uniforms.material_color = [r, g, b, a];
517                    uniforms.roughness = 1.0;
518                    uniforms.metalness = 0.0;
519                    self.uniform_buffer.write_bytes(0, uniforms.as_bytes());
520                    encoder.draw_indexed(mesh_index_count.max(3), 1);
521                }
522                Material3D::Textured(tex_mat) => {
523                    uniforms.material_color = sample_textured_material_color(tex_mat, eff_textures);
524                    uniforms.roughness = 0.9;
525                    uniforms.metalness = 0.0;
526                    self.uniform_buffer.write_bytes(0, uniforms.as_bytes());
527                    encoder.draw_indexed(mesh_index_count.max(3), 1);
528                }
529                Material3D::TexturedBatch(batch) => {
530                    uniforms.roughness = 0.9;
531                    uniforms.metalness = 0.0;
532                    for draw in &batch.draws {
533                        if draw.index_count == 0 {
534                            continue;
535                        }
536                        uniforms.material_color =
537                            sample_textured_material_color(&draw.material, eff_textures);
538                        self.uniform_buffer.write_bytes(0, uniforms.as_bytes());
539                        encoder.draw_indexed(draw.index_count as usize, 1);
540                    }
541                }
542                _ => {
543                    self.uniform_buffer.write_bytes(0, uniforms.as_bytes());
544                    encoder.draw_indexed(mesh_index_count.max(3), 1);
545                }
546            }
547        }
548
549        encoder.end_render_pass();
550        device.submit(encoder);
551    }
552
553    /// Renders a Relative-To-Eye (RTE) double-single mesh using GPU vertex shaders.
554    pub fn render_rte_mesh(
555        &mut self,
556        device: &mut GpuDevice,
557        uniforms: &GpuRteUniforms,
558        vertices: &[GpuRteVertex],
559        indices: &[u32],
560        viewport: Rect,
561        clip: Option<Rect>,
562    ) {
563        let mut encoder = device.create_command_encoder();
564
565        let pass_desc = GpuRenderPassDescriptor {
566            color_texture_id: device.swapchain_texture.id,
567            depth_texture_id: Some(device.depth_texture.id),
568            clear_color: None,
569            clear_depth: None,
570            scissor_rect: clip.or(Some(viewport)),
571        };
572
573        encoder.begin_render_pass(pass_desc);
574
575        // Upload RTE uniforms
576        self.uniform_buffer.write_bytes(0, uniforms.as_bytes());
577
578        // Upload vertex & index buffers if data provided
579        if !vertices.is_empty() {
580            let v_bytes = unsafe {
581                std::slice::from_raw_parts(
582                    vertices.as_ptr() as *const u8,
583                    std::mem::size_of_val(vertices),
584                )
585            };
586            self.vertex_buffer.write_bytes(0, v_bytes);
587        }
588
589        if !indices.is_empty() {
590            let i_bytes = unsafe {
591                std::slice::from_raw_parts(
592                    indices.as_ptr() as *const u8,
593                    std::mem::size_of_val(indices),
594                )
595            };
596            self.index_buffer.write_bytes(0, i_bytes);
597            encoder.draw_indexed(indices.len(), 1);
598        } else {
599            encoder.draw_indexed(36, 1);
600        }
601
602        encoder.end_render_pass();
603        device.submit(encoder);
604    }
605}
606
607fn sample_textured_material_color(
608    mat: &crate::scene3d::TexturedMaterial3D,
609    textures: Option<&crate::texture3d::TextureStore>,
610) -> [f32; 4] {
611    let (tr, tg, tb, ta) = mat.tint.to_f32();
612    let opacity = mat.opacity.clamp(0.0, 1.0);
613    if let Some(store) = textures {
614        if let Some(tex) = store.get(mat.texture) {
615            let uv = mat.uv_transform.apply((0.5, 0.5));
616            let sampled = crate::texture3d::sample_texture(tex, uv);
617            return [
618                (sampled[0] as f32 / 255.0) * tr,
619                (sampled[1] as f32 / 255.0) * tg,
620                (sampled[2] as f32 / 255.0) * tb,
621                (sampled[3] as f32 / 255.0) * ta * opacity,
622            ];
623        }
624    }
625    [tr, tg, tb, ta * opacity]
626}