From fd980af82fef05edad52bee91d43eaeb32db994f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 17:26:37 +0100 Subject: [PATCH 1/2] perf: static meshes' GPU vertices are 64 bytes, not 96 (lossless) Static meshes upload StaticVertex3D (position, normal, colour, uv, tangent; the same shader locations 0-3 and 6) and the pipelines feed locations 4 and 5 (joints, weights) from one shared 32-byte zero buffer with array_stride 0, so every shader, the engine's and games', reads exactly what it read before. Skinned meshes, morph inputs, the path-tracing megabuffer and immediate geometry keep the 96-byte Vertex3D. Pipelines that draw both kinds hold a pair chosen per draw; arena-only paths (GPU-driven, visibility raster and its storage decode, VSM casters) are 64-byte. OpenGL keeps 96 (glVertexAttribPointer reads stride 0 as tightly packed). Golden suite unchanged (no image moved); game frames old vs new within the old-vs-old noise in five scenes on the Mac. Co-Authored-By: Claude --- .../shaders/visibility_buffer/geometry.wgsl | 21 +- .../shared/src/renderer/card_capture_pass.rs | 15 +- native/shared/src/renderer/geometry_arena.rs | 31 +- native/shared/src/renderer/gpu_driven.rs | 46 +- .../src/renderer/layered_pbr_refraction.rs | 95 ++-- .../shared/src/renderer/layered_pbr_scene.rs | 194 ++++---- native/shared/src/renderer/layered_pbr_ssr.rs | 104 ++-- native/shared/src/renderer/lazy_pipeline.rs | 21 +- .../src/renderer/local_light_shadows.rs | 18 +- .../shared/src/renderer/material_pipeline.rs | 64 +-- native/shared/src/renderer/material_system.rs | 73 +-- .../src/renderer/material_system_tests.rs | 3 + native/shared/src/renderer/mod.rs | 101 ++-- native/shared/src/renderer/morph_pass.rs | 10 +- native/shared/src/renderer/planar_pass.rs | 28 +- native/shared/src/renderer/pt_dynamic_skin.rs | 11 +- native/shared/src/renderer/scene_pass.rs | 88 ++-- native/shared/src/renderer/shadow_pass.rs | 89 ++-- .../src/renderer/sorted_transparency.rs | 66 ++- .../shared/src/renderer/temporal_reactive.rs | 24 +- .../src/renderer/transmitted_shadows.rs | 117 +++-- native/shared/src/renderer/types.rs | 3 + native/shared/src/renderer/vertex_formats.rs | 458 ++++++++++++++++++ .../shared/src/renderer/visibility_buffer.rs | 33 +- .../src/renderer/visibility_buffer_tests.rs | 31 +- native/shared/src/renderer/vsm_gpu_casters.rs | 5 +- .../src/renderer/weighted_transparency.rs | 8 +- native/shared/src/scene.rs | 138 +++--- native/shared/src/scene/draw_lists.rs | 91 ++-- native/shared/src/scene/node_vertices.rs | 10 +- native/shared/src/scene/shared_mesh.rs | 13 +- native/shared/src/shadows.rs | 10 +- 32 files changed, 1381 insertions(+), 638 deletions(-) create mode 100644 native/shared/src/renderer/vertex_formats.rs diff --git a/native/shared/shaders/visibility_buffer/geometry.wgsl b/native/shared/shaders/visibility_buffer/geometry.wgsl index a9c204d5..6fdcb813 100644 --- a/native/shared/shaders/visibility_buffer/geometry.wgsl +++ b/native/shared/shaders/visibility_buffer/geometry.wgsl @@ -1,19 +1,20 @@ -// Bloom shared-geometry storage ABI for visibility shading — version 1. +// Bloom shared-geometry storage ABI for visibility shading — version 2. // -// Vertex3D is a tightly packed 96-byte Rust/vertex-buffer record. WGSL -// storage structs give vec3 values 16-byte alignment, so spelling the record -// with native vec3 fields would silently read the wrong offsets. Six vec4 -// lanes preserve the exact 24-word byte layout and are decoded explicitly. +// The shared static-geometry arena holds unskinned meshes only, as the +// tightly packed 64-byte StaticVertex3D (renderer/vertex_formats.rs): +// position, normal, color, uv, tangent. WGSL storage structs give vec3 values +// 16-byte alignment, so spelling the record with native vec3 fields would +// silently read the wrong offsets. Four vec4 lanes preserve the exact +// 16-word byte layout and are decoded explicitly. Joints and weights are not +// stored: they are zero for every arena vertex, as the 96-byte record held. -const BLOOM_VERTEX3D_WORDS: u32 = 24u; +const BLOOM_VERTEX3D_WORDS: u32 = 16u; struct BloomPackedVertex3D { words_0: vec4, words_1: vec4, words_2: vec4, words_3: vec4, - words_4: vec4, - words_5: vec4, }; struct BloomVertex3D { @@ -36,9 +37,9 @@ fn bloom_decode_vertex3d(packed: BloomPackedVertex3D) -> BloomVertex3D { )), bitcast>(vec4(packed.words_1.zw, packed.words_2.xy)), bitcast>(packed.words_2.zw), + vec4(0.0), + vec4(0.0), bitcast>(packed.words_3), - bitcast>(packed.words_4), - bitcast>(packed.words_5), ); } diff --git a/native/shared/src/renderer/card_capture_pass.rs b/native/shared/src/renderer/card_capture_pass.rs index ea80928a..275e1e68 100644 --- a/native/shared/src/renderer/card_capture_pass.rs +++ b/native/shared/src/renderer/card_capture_pass.rs @@ -1,6 +1,6 @@ //! The render pass and atlas copies of one frame's mesh-card captures. -use super::{Renderer, CARD_SLOTS_PER_ROW, CARD_SLOT_SIZE}; +use super::{vertex_formats, Renderer, VertexLayout, CARD_SLOTS_PER_ROW, CARD_SLOT_SIZE}; /// One axis of one mesh: what to draw, the scratch-grid cell it draws into /// and the atlas slot that cell is copied to. @@ -8,6 +8,7 @@ pub(super) struct CardCaptureDraw { pub uniform_offset: u32, pub texture_bg: wgpu::BindGroup, pub vertex_buffer: wgpu::Buffer, + pub vertex_layout: VertexLayout, pub index_buffer: wgpu::Buffer, pub index_count: u32, pub cell_x: u32, @@ -60,8 +61,12 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); - pass.set_pipeline(&self.card_capture_pipeline); + let mut current_layout = None; for draw in draws { + if current_layout != Some(draw.vertex_layout) { + pass.set_pipeline(self.card_capture_pipeline.get(draw.vertex_layout)); + current_layout = Some(draw.vertex_layout); + } // The viewport maps the capture's clip space onto its cell; // the scissor keeps geometry outside the card bounds from // spilling into a neighbouring cell. @@ -77,6 +82,12 @@ impl Renderer { pass.set_bind_group(0, uniform_bg, &[draw.uniform_offset]); pass.set_bind_group(1, &draw.texture_bg, &[]); pass.set_vertex_buffer(0, draw.vertex_buffer.slice(..)); + vertex_formats::bind_skin_zero( + &mut pass, + draw.vertex_layout, + 1, + self.gpu_driven.skin_zero(), + ); pass.set_index_buffer(draw.index_buffer.slice(..), wgpu::IndexFormat::Uint32); pass.draw_indexed(0..draw.index_count, 0, 0..1); } diff --git a/native/shared/src/renderer/geometry_arena.rs b/native/shared/src/renderer/geometry_arena.rs index 9a074155..4cb9c2fb 100644 --- a/native/shared/src/renderer/geometry_arena.rs +++ b/native/shared/src/renderer/geometry_arena.rs @@ -2,8 +2,11 @@ //! index buffer for every static mesh, with a free list. It grows by doubling //! up to the device's buffer limit; past that an upload is refused and the //! caller keeps the mesh on buffers of its own. +//! +//! It holds only unskinned meshes, so its vertices are the 64-byte +//! `StaticVertex3D` (`VertexLayout::arena()`; 96 bytes on OpenGL). -use super::super::{material_indirection::GpuCompletionTracker, Vertex3D}; +use super::super::{material_indirection::GpuCompletionTracker, Vertex3D, VertexLayout}; use super::GeometrySlice; #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] @@ -34,6 +37,8 @@ pub(super) struct GeometryArena { /// so the storage-binding limit applies as well as the buffer limit. max_capacity: u64, full_warned: bool, + /// The format of every vertex in the arena. + pub(super) layout: VertexLayout, } impl GeometryArena { @@ -41,10 +46,13 @@ impl GeometryArena { pub(super) fn new(device: &wgpu::Device) -> Self { let limits = device.limits(); + let layout = VertexLayout::arena(); Self { + layout, max_capacity: arena_max_capacity( limits.max_buffer_size, limits.max_storage_buffer_binding_size as u64, + layout.stride(), ), full_warned: false, vertex: create_vertex_arena(device, Self::INITIAL_CAPACITY), @@ -69,7 +77,8 @@ impl GeometryArena { indices: &[u32], ) -> Option { self.collect(); - let vertex_size = std::mem::size_of_val(vertices) as u64; + let stride = self.layout.stride(); + let vertex_size = vertices.len() as u64 * stride; let index_size = std::mem::size_of_val(indices) as u64; let previous_vertex_end = self.vertex_end; let previous_index_end = self.index_end; @@ -119,7 +128,7 @@ impl GeometryArena { previous_index_end, ); if vertex_size > 0 { - queue.write_buffer(&self.vertex, vertex_offset, bytemuck::cast_slice(vertices)); + queue.write_buffer(&self.vertex, vertex_offset, &self.layout.encode(vertices)); } if index_size > 0 { queue.write_buffer(&self.index, index_offset, bytemuck::cast_slice(indices)); @@ -130,7 +139,7 @@ impl GeometryArena { index_offset, index_size, first_index: (index_offset / 4) as u32, - base_vertex: (vertex_offset / std::mem::size_of::() as u64) as i32, + base_vertex: (vertex_offset / stride) as i32, }) } @@ -264,10 +273,10 @@ fn grown_capacity(current: u64, required: u64, max: u64) -> u64 { } } -/// Both limits, rounded down to whole vertices and indices. -fn arena_max_capacity(max_buffer_size: u64, max_storage_binding_size: u64) -> u64 { +/// Both limits, rounded down to whole vertices (of `stride` bytes) and indices. +fn arena_max_capacity(max_buffer_size: u64, max_storage_binding_size: u64, stride: u64) -> u64 { let limit = max_buffer_size.min(max_storage_binding_size); - let unit = std::mem::size_of::() as u64 * 4; + let unit = stride * 4; limit / unit * unit } @@ -360,9 +369,11 @@ mod tests { assert_eq!(grown_capacity(32 * mb, 40 * mb, 1024 * mb), 64 * mb); // 390 MB would round up to 448 MB; a 400 MB device gets 400 MB. assert_eq!(grown_capacity(256 * mb, 390 * mb, 400 * mb), 400 * mb); - let unit = std::mem::size_of::() as u64 * 4; - assert_eq!(arena_max_capacity(1000 * mb, 300 * mb) % unit, 0); - assert!(arena_max_capacity(1000 * mb, 300 * mb) <= 300 * mb); + for stride in [64, 96] { + let unit = stride * 4; + assert_eq!(arena_max_capacity(1000 * mb, 300 * mb, stride) % unit, 0); + assert!(arena_max_capacity(1000 * mb, 300 * mb, stride) <= 300 * mb); + } } #[test] diff --git a/native/shared/src/renderer/gpu_driven.rs b/native/shared/src/renderer/gpu_driven.rs index eca876ab..82d0bbcf 100644 --- a/native/shared/src/renderer/gpu_driven.rs +++ b/native/shared/src/renderer/gpu_driven.rs @@ -62,10 +62,13 @@ pub struct GeometrySlice { } pub enum MeshGeometry { + /// A slice of the arena, in the arena's format (`arena_layout()`). Shared(GeometrySlice), Dedicated { vertex: wgpu::Buffer, index: wgpu::Buffer, + /// The format `vertex` holds. + layout: super::VertexLayout, }, } @@ -122,6 +125,8 @@ pub struct GpuDrivenRenderer { main_visibility_compat_pipeline: Option, main_visibility_compat_prepassed_pipeline: Option, visibility: super::visibility_buffer::VisibilityBufferRuntime, + /// Zero joints/weights for 64-byte static draws (`vertex_formats.rs`). + skin_zero: wgpu::Buffer, pub(super) draw_scratch: Vec, pub stats: SubmissionStats, } @@ -329,6 +334,7 @@ impl GpuDrivenRenderer { let renderer = Self { arena: GeometryArena::new(device), + skin_zero: super::vertex_formats::create_skin_zero_buffer(device), enabled, count_supported, draw_capacity, @@ -387,6 +393,16 @@ impl GpuDrivenRenderer { (&self.arena.vertex, &self.arena.index) } + /// The format of every vertex in the shared arena. + pub(crate) fn arena_layout(&self) -> super::VertexLayout { + self.arena.layout + } + + /// The shared zero joints/weights that static draws bind. + pub(crate) fn skin_zero(&self) -> &wgpu::Buffer { + &self.skin_zero + } + pub fn upload_static( &mut self, device: &wgpu::Device, @@ -410,9 +426,10 @@ impl GpuDrivenRenderer { match self.arena.upload(device, queue, vertices, indices) { Some(slice) => MeshGeometry::Shared(slice), None => MeshGeometry::Dedicated { + layout: self.arena.layout, vertex: device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("cached_static_model_vb"), - contents: bytemuck::cast_slice(vertices), + contents: &self.arena.layout.encode(vertices), usage: wgpu::BufferUsages::VERTEX, }), index: device.create_buffer_init(&wgpu::util::BufferInitDescriptor { @@ -444,13 +461,19 @@ impl GpuDrivenRenderer { first_index: slice.first_index, index_count, base_vertex: slice.base_vertex, + layout: self.arena.layout, }, - MeshGeometry::Dedicated { vertex, index } => MeshDrawRef { + MeshGeometry::Dedicated { + vertex, + index, + layout, + } => MeshDrawRef { vertex, index, first_index: 0, index_count, base_vertex: 0, + layout: *layout, }, } } @@ -472,17 +495,23 @@ impl GpuDrivenRenderer { first_index: 0, index_count, base_vertex: 0, + layout: self.arena.layout, }, slice.vertex_offset, slice.index_offset, ), - MeshGeometry::Dedicated { vertex, index } => ( + MeshGeometry::Dedicated { + vertex, + index, + layout, + } => ( MeshDrawRef { vertex, index, first_index: 0, index_count, base_vertex: 0, + layout: *layout, }, 0, 0, @@ -845,6 +874,7 @@ impl GpuDrivenRenderer { pass.set_bind_group(2, global_materials, &[]); pass.set_bind_group(3, joints, &[]); pass.set_vertex_buffer(0, self.arena.vertex.slice(..)); + super::bind_skin_zero(pass, self.arena.layout, 1, &self.skin_zero); pass.set_index_buffer(self.arena.index.slice(..), wgpu::IndexFormat::Uint32); let indirect = match route { IndirectRoute::All => &self.indirect_buffer, @@ -1183,6 +1213,12 @@ fn create_cull_bind_group( }) } +/// The vertex streams of a pipeline drawing the arena: its format, plus the +/// zero joints/weights at slot 1 when that is the 64-byte one. +pub(super) fn arena_buffers() -> Vec> { + super::vertex_formats::layout_buffers(super::VertexLayout::arena(), &[Vertex3D::desc()]) +} + fn create_depth_pipeline( device: &wgpu::Device, layout: &wgpu::PipelineLayout, @@ -1204,7 +1240,7 @@ fn create_depth_pipeline( vertex: wgpu::VertexState { module: shader, entry_point: Some("vs_main_scene"), - buffers: &[Vertex3D::desc()], + buffers: &arena_buffers(), compilation_options: Default::default(), }, fragment: Some(wgpu::FragmentState { @@ -1290,7 +1326,7 @@ fn create_main_pipeline( vertex: wgpu::VertexState { module: vertex_shader, entry_point: Some("vs_main_scene"), - buffers: &[Vertex3D::desc()], + buffers: &arena_buffers(), compilation_options: Default::default(), }, fragment: Some(wgpu::FragmentState { diff --git a/native/shared/src/renderer/layered_pbr_refraction.rs b/native/shared/src/renderer/layered_pbr_refraction.rs index 9276c031..85cb81ef 100644 --- a/native/shared/src/renderer/layered_pbr_refraction.rs +++ b/native/shared/src/renderer/layered_pbr_refraction.rs @@ -150,14 +150,14 @@ pub(super) fn scene_layered_refractive_shader_source( pub(super) struct SceneLayeredRefractiveResources { material_layout: wgpu::BindGroupLayout, - scalar: wgpu::RenderPipeline, - scalar_double_sided: wgpu::RenderPipeline, - uv1: Option, - uv1_double_sided: Option, - reactive: Option, - reactive_double_sided: Option, - reactive_uv1: Option, - reactive_uv1_double_sided: Option, + scalar: MeshPipelines, + scalar_double_sided: MeshPipelines, + uv1: Option, + uv1_double_sided: Option, + reactive: Option, + reactive_double_sided: Option, + reactive_uv1: Option, + reactive_uv1_double_sided: Option, } impl SceneLayeredRefractiveResources { @@ -166,8 +166,9 @@ impl SceneLayeredRefractiveResources { secondary_uv: bool, double_sided: bool, reactive: bool, + layout: VertexLayout, ) -> &wgpu::RenderPipeline { - match (reactive, secondary_uv, double_sided) { + let pipelines = match (reactive, secondary_uv, double_sided) { (false, false, false) => &self.scalar, (false, false, true) => &self.scalar_double_sided, (false, true, false) => self @@ -194,7 +195,8 @@ impl SceneLayeredRefractiveResources { .reactive_uv1_double_sided .as_ref() .expect("layered refractive reactive UV1 resources are initialized"), - } + }; + pipelines.get(layout) } } @@ -303,7 +305,7 @@ fn create_pipeline( double_sided: bool, reactive: bool, label: &'static str, -) -> wgpu::RenderPipeline { +) -> MeshPipelines { let buffers = if secondary_uv { vec![Vertex3D::desc(), secondary_uv_desc()] } else { @@ -328,41 +330,44 @@ fn create_pipeline( write_mask: wgpu::ColorWrites::RED, })); } - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(label), - layout: Some(layout), - vertex: wgpu::VertexState { - module: shader, - entry_point: Some("vs_main_scene"), - buffers: &buffers, - compilation_options: Default::default(), - }, - fragment: Some(wgpu::FragmentState { - module: shader, - entry_point: Some("fs_refractive_scene"), - targets: &targets, - compilation_options: Default::default(), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - strip_index_format: None, - front_face: wgpu::FrontFace::Ccw, - cull_mode: (!double_sided).then_some(wgpu::Face::Back), - polygon_mode: wgpu::PolygonMode::Fill, - unclipped_depth: false, - conservative: false, + MeshPipelines::lazy( + device, + &wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(layout), + vertex: wgpu::VertexState { + module: shader, + entry_point: Some("vs_main_scene"), + buffers: &buffers, + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: shader, + entry_point: Some("fs_refractive_scene"), + targets: &targets, + compilation_options: Default::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: (!double_sided).then_some(wgpu::Face::Back), + polygon_mode: wgpu::PolygonMode::Fill, + unclipped_depth: false, + conservative: false, + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: DEPTH_FORMAT, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, }, - depth_stencil: Some(wgpu::DepthStencilState { - format: DEPTH_FORMAT, - depth_write_enabled: Some(false), - depth_compare: Some(wgpu::CompareFunction::LessEqual), - stencil: wgpu::StencilState::default(), - bias: wgpu::DepthBiasState::default(), - }), - multisample: wgpu::MultisampleState::default(), - multiview_mask: None, - cache: None, - }) + ) } impl Renderer { diff --git a/native/shared/src/renderer/layered_pbr_scene.rs b/native/shared/src/renderer/layered_pbr_scene.rs index 743375af..1cf18434 100644 --- a/native/shared/src/renderer/layered_pbr_scene.rs +++ b/native/shared/src/renderer/layered_pbr_scene.rs @@ -625,22 +625,22 @@ fn apply_layered_capture_debug(source: String, mode: Option<&str>) -> String { pub(crate) struct SceneLayeredPbrResources { pub(crate) material_layout: wgpu::BindGroupLayout, - opaque: wgpu::RenderPipeline, - opaque_prepassed: wgpu::RenderPipeline, - opaque_uv1: wgpu::RenderPipeline, - opaque_prepassed_uv1: wgpu::RenderPipeline, - transparent: wgpu::RenderPipeline, - transparent_double_sided: wgpu::RenderPipeline, - transparent_uv1: wgpu::RenderPipeline, - transparent_uv1_double_sided: wgpu::RenderPipeline, - reactive: Option, - reactive_double_sided: Option, - reactive_uv1: Option, - reactive_uv1_double_sided: Option, - weighted: Option, - weighted_double_sided: Option, - weighted_uv1: Option, - weighted_uv1_double_sided: Option, + opaque: MeshPipelines, + opaque_prepassed: MeshPipelines, + opaque_uv1: MeshPipelines, + opaque_prepassed_uv1: MeshPipelines, + transparent: MeshPipelines, + transparent_double_sided: MeshPipelines, + transparent_uv1: MeshPipelines, + transparent_uv1_double_sided: MeshPipelines, + reactive: Option, + reactive_double_sided: Option, + reactive_uv1: Option, + reactive_uv1_double_sided: Option, + weighted: Option, + weighted_double_sided: Option, + weighted_uv1: Option, + weighted_uv1_double_sided: Option, } pub(crate) struct SceneSheenAlbedoLut { @@ -704,6 +704,7 @@ impl SceneLayeredPbrResources { &self, secondary_uv: bool, prepassed: bool, + layout: VertexLayout, ) -> &wgpu::RenderPipeline { match (secondary_uv, prepassed) { (false, false) => &self.opaque, @@ -711,6 +712,7 @@ impl SceneLayeredPbrResources { (true, false) => &self.opaque_uv1, (true, true) => &self.opaque_prepassed_uv1, } + .get(layout) } pub(crate) fn transparent_pipeline( @@ -719,8 +721,9 @@ impl SceneLayeredPbrResources { double_sided: bool, reactive: bool, weighted: bool, + layout: VertexLayout, ) -> &wgpu::RenderPipeline { - match (weighted, reactive, secondary_uv, double_sided) { + let pipelines = match (weighted, reactive, secondary_uv, double_sided) { (false, false, false, false) => &self.transparent, (false, false, false, true) => &self.transparent_double_sided, (false, false, true, false) => &self.transparent_uv1, @@ -757,7 +760,8 @@ impl SceneLayeredPbrResources { .weighted_uv1_double_sided .as_ref() .expect("layered weighted UV1 resources are initialized"), - } + }; + pipelines.get(layout) } } @@ -900,7 +904,7 @@ fn create_layered_opaque_pipeline( secondary_uv: bool, prepassed: bool, label: &'static str, -) -> wgpu::RenderPipeline { +) -> MeshPipelines { let shader = match (secondary_uv, prepassed) { (false, false) => modules.scalar, (false, true) => modules.scalar_prepassed, @@ -909,45 +913,48 @@ fn create_layered_opaque_pipeline( }; let buffers = scene_vertex_buffers(secondary_uv); let targets = scene_main_targets(); - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(label), - layout: Some(layout), - vertex: wgpu::VertexState { - module: shader, - entry_point: Some("vs_main_scene"), - buffers: &buffers, - compilation_options: Default::default(), - }, - fragment: Some(wgpu::FragmentState { - module: shader, - entry_point: Some("fs_main_scene"), - targets: &targets, - compilation_options: Default::default(), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - strip_index_format: None, - front_face: wgpu::FrontFace::Ccw, - cull_mode: Some(wgpu::Face::Back), - polygon_mode: wgpu::PolygonMode::Fill, - unclipped_depth: false, - conservative: false, - }, - depth_stencil: Some(wgpu::DepthStencilState { - format: DEPTH_FORMAT, - depth_write_enabled: Some(!prepassed), - depth_compare: Some(if prepassed { - wgpu::CompareFunction::Equal - } else { - wgpu::CompareFunction::Less + MeshPipelines::lazy( + device, + &wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(layout), + vertex: wgpu::VertexState { + module: shader, + entry_point: Some("vs_main_scene"), + buffers: &buffers, + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: shader, + entry_point: Some("fs_main_scene"), + targets: &targets, + compilation_options: Default::default(), }), - stencil: wgpu::StencilState::default(), - bias: wgpu::DepthBiasState::default(), - }), - multisample: wgpu::MultisampleState::default(), - multiview_mask: None, - cache: None, - }) + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: Some(wgpu::Face::Back), + polygon_mode: wgpu::PolygonMode::Fill, + unclipped_depth: false, + conservative: false, + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: DEPTH_FORMAT, + depth_write_enabled: Some(!prepassed), + depth_compare: Some(if prepassed { + wgpu::CompareFunction::Equal + } else { + wgpu::CompareFunction::Less + }), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }, + ) } #[allow(clippy::too_many_arguments)] @@ -960,43 +967,46 @@ fn create_layered_transparent_pipeline( secondary_uv: bool, double_sided: bool, label: &'static str, -) -> wgpu::RenderPipeline { +) -> MeshPipelines { let buffers = scene_vertex_buffers(secondary_uv); - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(label), - layout: Some(layout), - vertex: wgpu::VertexState { - module: shader, - entry_point: Some("vs_main_scene"), - buffers: &buffers, - compilation_options: Default::default(), - }, - fragment: Some(wgpu::FragmentState { - module: shader, - entry_point: Some(entry_point), - targets, - compilation_options: Default::default(), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - strip_index_format: None, - front_face: wgpu::FrontFace::Ccw, - cull_mode: (!double_sided).then_some(wgpu::Face::Back), - polygon_mode: wgpu::PolygonMode::Fill, - unclipped_depth: false, - conservative: false, + MeshPipelines::lazy( + device, + &wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(layout), + vertex: wgpu::VertexState { + module: shader, + entry_point: Some("vs_main_scene"), + buffers: &buffers, + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: shader, + entry_point: Some(entry_point), + targets, + compilation_options: Default::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: (!double_sided).then_some(wgpu::Face::Back), + polygon_mode: wgpu::PolygonMode::Fill, + unclipped_depth: false, + conservative: false, + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: DEPTH_FORMAT, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, }, - depth_stencil: Some(wgpu::DepthStencilState { - format: DEPTH_FORMAT, - depth_write_enabled: Some(false), - depth_compare: Some(wgpu::CompareFunction::LessEqual), - stencil: wgpu::StencilState::default(), - bias: wgpu::DepthBiasState::default(), - }), - multisample: wgpu::MultisampleState::default(), - multiview_mask: None, - cache: None, - }) + ) } impl Renderer { diff --git a/native/shared/src/renderer/layered_pbr_ssr.rs b/native/shared/src/renderer/layered_pbr_ssr.rs index 1bd49362..f7a90161 100644 --- a/native/shared/src/renderer/layered_pbr_ssr.rs +++ b/native/shared/src/renderer/layered_pbr_ssr.rs @@ -14,18 +14,18 @@ const IRIDESCENCE_SSR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Un pub(crate) struct SceneIridescenceSsrResources { _metadata_texture: wgpu::Texture, pub(crate) metadata_view: wgpu::TextureView, - scalar_metadata_pipeline: wgpu::RenderPipeline, - uv1_metadata_pipeline: wgpu::RenderPipeline, + scalar_metadata_pipeline: MeshPipelines, + uv1_metadata_pipeline: MeshPipelines, pub(crate) ssr_layout: wgpu::BindGroupLayout, pub(crate) ssr_pipeline: wgpu::RenderPipeline, } impl SceneIridescenceSsrResources { - fn metadata_pipeline(&self, secondary_uv: bool) -> &wgpu::RenderPipeline { + fn metadata_pipeline(&self, secondary_uv: bool, layout: VertexLayout) -> &wgpu::RenderPipeline { if secondary_uv { - &self.uv1_metadata_pipeline + self.uv1_metadata_pipeline.get(layout) } else { - &self.scalar_metadata_pipeline + self.scalar_metadata_pipeline.get(layout) } } } @@ -136,50 +136,53 @@ fn create_metadata_pipeline( shader: &wgpu::ShaderModule, secondary_uv: bool, label: &'static str, -) -> wgpu::RenderPipeline { +) -> MeshPipelines { let mut buffers = vec![Vertex3D::desc()]; if secondary_uv { buffers.push(secondary_uv_desc()); } - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(label), - layout: Some(layout), - vertex: wgpu::VertexState { - module: shader, - entry_point: Some("vs_main_scene"), - buffers: &buffers, - compilation_options: Default::default(), - }, - fragment: Some(wgpu::FragmentState { - module: shader, - entry_point: Some("fs_transparent_scene"), - targets: &[Some(wgpu::ColorTargetState { - format: IRIDESCENCE_SSR_FORMAT, - blend: None, - write_mask: wgpu::ColorWrites::ALL, - })], - compilation_options: Default::default(), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - strip_index_format: None, - front_face: wgpu::FrontFace::Ccw, - cull_mode: Some(wgpu::Face::Back), - polygon_mode: wgpu::PolygonMode::Fill, - unclipped_depth: false, - conservative: false, + MeshPipelines::lazy( + device, + &wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(layout), + vertex: wgpu::VertexState { + module: shader, + entry_point: Some("vs_main_scene"), + buffers: &buffers, + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: shader, + entry_point: Some("fs_transparent_scene"), + targets: &[Some(wgpu::ColorTargetState { + format: IRIDESCENCE_SSR_FORMAT, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: Default::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: Some(wgpu::Face::Back), + polygon_mode: wgpu::PolygonMode::Fill, + unclipped_depth: false, + conservative: false, + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: DEPTH_FORMAT, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::Equal), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, }, - depth_stencil: Some(wgpu::DepthStencilState { - format: DEPTH_FORMAT, - depth_write_enabled: Some(false), - depth_compare: Some(wgpu::CompareFunction::Equal), - stencil: wgpu::StencilState::default(), - bias: wgpu::DepthBiasState::default(), - }), - multisample: wgpu::MultisampleState::default(), - multiview_mask: None, - cache: None, - }) + ) } fn create_layered_ssr_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { @@ -534,9 +537,10 @@ impl Renderer { for draw in draws { self.bind_joint_page(&mut pass, 3, draw.joint_offset, &mut joint_page); let uses_uv1 = draw.secondary_uv.is_some(); - if current_uv1 != Some(uses_uv1) { - pass.set_pipeline(resources.metadata_pipeline(uses_uv1)); - current_uv1 = Some(uses_uv1); + let layout = draw.mesh.layout; + if current_uv1 != Some((uses_uv1, layout)) { + pass.set_pipeline(resources.metadata_pipeline(uses_uv1, layout)); + current_uv1 = Some((uses_uv1, layout)); } pass.set_bind_group(0, draw.uniforms, &[]); pass.set_bind_group(2, draw.material, &[]); @@ -544,6 +548,12 @@ impl Renderer { if let Some(secondary_uv) = draw.secondary_uv { pass.set_vertex_buffer(1, secondary_uv.slice(..)); } + bind_skin_zero( + &mut pass, + layout, + vertex_formats::zero_slot(u32::from(uses_uv1)), + self.gpu_driven.skin_zero(), + ); pass.set_index_buffer( draw.mesh.index.slice(draw.index_byte_offset..), wgpu::IndexFormat::Uint32, diff --git a/native/shared/src/renderer/lazy_pipeline.rs b/native/shared/src/renderer/lazy_pipeline.rs index 46c73aa1..a41b30c1 100644 --- a/native/shared/src/renderer/lazy_pipeline.rs +++ b/native/shared/src/renderer/lazy_pipeline.rs @@ -463,13 +463,18 @@ impl super::Renderer { let mut wanted: Vec = vec![self.pipeline_2d.warm_handle()]; if scene_3d { + // each mesh pipeline in both vertex formats (vertex_formats.rs) + for pipelines in [ + &self.scene_depth_pipeline, + &self.scene_depth_opaque_pipeline, + &self.scene_pipeline_prepassed, + &self.scene_node_depth_pipeline, + &self.scene_node_pipeline_prepassed, + &self.scene_pipeline, + ] { + wanted.extend(pipelines.warm_handles()); + } wanted.extend([ - self.scene_depth_pipeline.warm_handle(), - self.scene_depth_opaque_pipeline.warm_handle(), - self.scene_pipeline_prepassed.warm_handle(), - self.scene_node_depth_pipeline.warm_handle(), - self.scene_node_pipeline_prepassed.warm_handle(), - self.scene_pipeline.warm_handle(), self.scene_compose_pipeline.warm_handle(), self.composite_pipeline.warm_handle(), ]); @@ -477,7 +482,7 @@ impl super::Renderer { wanted.push(froxel.assign_pipeline.warm_handle()); } if self.shadow_map.enabled { - wanted.push(self.shadow_map.pipeline.warm_handle()); + wanted.extend(self.shadow_map.pipeline.warm_handles()); wanted.push(self.shadow_map.pipeline_skinned.warm_handle()); } if gpu_driven_draws { @@ -522,8 +527,8 @@ impl super::Renderer { self.probe_temporal_pipeline.warm_handle(), self.probe_spatial_pipeline.warm_handle(), self.probe_resolve_pipeline.warm_handle(), - self.card_capture_pipeline.warm_handle(), ]); + wanted.extend(self.card_capture_pipeline.warm_handles()); // hardware ray queries where the device has them, else the SDF tracers match &self.probe_trace_hw_pipeline { Some(hw) => wanted.push(hw.warm_handle()), diff --git a/native/shared/src/renderer/local_light_shadows.rs b/native/shared/src/renderer/local_light_shadows.rs index 5a4e2831..3f989c6a 100644 --- a/native/shared/src/renderer/local_light_shadows.rs +++ b/native/shared/src/renderer/local_light_shadows.rs @@ -524,9 +524,12 @@ pub(crate) struct PassInputs<'a> { pub vbs: &'a [&'a wgpu::Buffer], pub ibs: &'a [&'a wgpu::Buffer], pub cutout_bgs: &'a [&'a wgpu::BindGroup], - pub pipeline: &'a wgpu::RenderPipeline, - pub pipeline_cutout: &'a wgpu::RenderPipeline, + /// Opaque and cutout casters per vertex format (vertex_formats.rs). + pub pipeline: &'a super::vertex_formats::MeshPipelines, + pub pipeline_cutout: &'a super::vertex_formats::MeshPipelines, pub pipeline_skinned: &'a wgpu::RenderPipeline, + /// The zero joints/weights stream of 64-byte casters. + pub skin_zero: &'a wgpu::Buffer, pub joint_bind_group: &'a wgpu::BindGroup, pub camera_pos: [f32; 3], pub camera_planes: [[f32; 4]; 6], @@ -880,7 +883,7 @@ impl LocalLightShadows { occlusion_query_set: None, multiview_mask: None, }); - let mut current_kind = u8::MAX; + let mut current_kind = None; for (slot, &entry_index) in entries.iter().enumerate() { let entry = &inputs.nodes[entry_index]; let kind = if entry.skinned { @@ -890,13 +893,13 @@ impl LocalLightShadows { } else { 0 }; - if kind != current_kind { + if current_kind != Some((kind, entry.layout)) { pass.set_pipeline(match kind { - 1 => inputs.pipeline_cutout, + 1 => inputs.pipeline_cutout.get(entry.layout), 2 => inputs.pipeline_skinned, - _ => inputs.pipeline, + _ => inputs.pipeline.get(entry.layout), }); - current_kind = kind; + current_kind = Some((kind, entry.layout)); } pass.set_bind_group(0, &gpu.draw_bind_group, &[(base + slot * stride) as u32]); if kind == 1 { @@ -905,6 +908,7 @@ impl LocalLightShadows { pass.set_bind_group(1, inputs.joint_bind_group, &[]); } pass.set_vertex_buffer(0, inputs.vbs[entry.vb_idx].slice(..)); + super::vertex_formats::bind_skin_zero(&mut pass, entry.layout, 1, inputs.skin_zero); pass.set_index_buffer( inputs.ibs[entry.ib_idx].slice(..), wgpu::IndexFormat::Uint32, diff --git a/native/shared/src/renderer/material_pipeline.rs b/native/shared/src/renderer/material_pipeline.rs index 82fae5b7..fc956b2e 100644 --- a/native/shared/src/renderer/material_pipeline.rs +++ b/native/shared/src/renderer/material_pipeline.rs @@ -476,8 +476,10 @@ enum TranslucentReactiveSource { /// A pipeline ready to receive draws. Owns only the `RenderPipeline`; /// the layouts are borrowed from the shared `MaterialAbiLayouts`. pub struct MaterialPipeline { - pub pipeline: wgpu::RenderPipeline, - pub(crate) reactive_pipeline: Option, + /// One per vertex format (vertex_formats.rs): 64-byte static meshes and + /// 96-byte skinned ones draw through the same material. + pub pipeline: super::vertex_formats::MeshPipelinePair, + pub(crate) reactive_pipeline: Option, reactive_recipe: Option, pub profile: FragmentProfile, pub bucket: Bucket, @@ -505,7 +507,7 @@ pub struct MaterialPipeline { /// `None` for materials whose original cull mode is already /// `None` (translucent, cutout) — flipping a non-culled pipeline /// is a no-op so we don't bother compiling a duplicate. - pub reflection_pipeline: Option, + pub reflection_pipeline: Option, } impl MaterialPipeline { @@ -576,7 +578,8 @@ impl MaterialPipeline { }), Some(reactive_target), ]; - self.reactive_pipeline = Some(device.create_render_pipeline( + self.reactive_pipeline = Some(super::vertex_formats::MeshPipelinePair::new( + device, &wgpu::RenderPipelineDescriptor { label: Some(&format!("{}_reactive_compatible", recipe.label)), layout: Some(&recipe.pipeline_layout), @@ -973,32 +976,35 @@ pub fn compile_material( let make_pipeline = |cull: Option, label_suffix: &str| { let label_owned = format!("{}{}", desc.label, label_suffix); - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(&label_owned), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module: &module, - entry_point: Some("vs_main"), - buffers: vertex_buffers, - compilation_options: Default::default(), - }, - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some("fs_main"), - targets, - compilation_options: Default::default(), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - front_face: wgpu::FrontFace::Ccw, - cull_mode: cull, - ..Default::default() + super::vertex_formats::MeshPipelinePair::new( + device, + &wgpu::RenderPipelineDescriptor { + label: Some(&label_owned), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs_main"), + buffers: vertex_buffers, + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs_main"), + targets, + compilation_options: Default::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + front_face: wgpu::FrontFace::Ccw, + cull_mode: cull, + ..Default::default() + }, + depth_stencil: depth_stencil.clone(), + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, }, - depth_stencil: depth_stencil.clone(), - multisample: wgpu::MultisampleState::default(), - multiview_mask: None, - cache: None, - }) + ) }; let pipeline = make_pipeline(main_cull, ""); diff --git a/native/shared/src/renderer/material_system.rs b/native/shared/src/renderer/material_system.rs index 3ab7a3cd..faa546c6 100644 --- a/native/shared/src/renderer/material_system.rs +++ b/native/shared/src/renderer/material_system.rs @@ -249,6 +249,8 @@ pub fn map_texture_array_format(code: u32) -> wgpu::TextureFormat { pub struct MaterialSystem { pub layouts: MaterialAbiLayouts, pub(super) pipeline_creation_count: u64, + /// Zero joints/weights for 64-byte static meshes (vertex_formats.rs). + pub(super) skin_zero: wgpu::Buffer, // Compiled pipelines, indexed by MaterialHandle (1-based; 0 = invalid). pub pipelines: Vec>, @@ -825,6 +827,7 @@ impl MaterialSystem { indirection.flush(device, queue); Self { + skin_zero: super::vertex_formats::create_skin_zero_buffer(device), layouts, pipeline_creation_count: 0, pipelines: Vec::new(), @@ -2053,43 +2056,48 @@ impl MaterialSystem { return; } - let mut last_material: MaterialHandle = 0; + // The material and vertex format (vertex_formats.rs) bound last. + let mut bound: Option<(MaterialHandle, super::VertexLayout)> = None; for cmd in &self.commands { if !accept(cmd.material) { continue; } - if cmd.material != last_material { - let mat = match self.pipelines.get(cmd.material as usize - 1) { - Some(Some(m)) => m, - _ => continue, - }; - // Probe passes (use_reflection_pipeline) present the - // 4-attachment opaque G-buffer layout. Translucent- - // profile pipelines are single-target — binding one - // there is a wgpu validation panic — and reads_scene - // materials expect a group-4 bind the probe pass never - // provides. Skip both; `last_material` stays latched on - // the previously bound material, which is correct - // because no pipeline/bind state changes here. - if use_reflection_pipeline - && (matches!(mat.profile, FragmentProfile::Translucent) || mat.reads_scene) - { - continue; - } - let pipeline = if use_reflection_pipeline { - mat.reflection_pipeline.as_ref().unwrap_or(&mat.pipeline) - } else { - &mat.pipeline - }; - pass.set_pipeline(pipeline); - pass.set_bind_group(0, &self.per_frame_bg, &[]); - pass.set_bind_group(1, per_view_bg, &[]); - pass.set_bind_group(2, self.per_material_bg_for(cmd.material), &[]); - last_material = cmd.material; + let mat = match self.pipelines.get(cmd.material as usize - 1) { + Some(Some(m)) => m, + _ => continue, + }; + // Probe passes (use_reflection_pipeline) present the + // 4-attachment opaque G-buffer layout. Translucent- + // profile pipelines are single-target — binding one + // there is a wgpu validation panic — and reads_scene + // materials expect a group-4 bind the probe pass never + // provides. Skip both. + if use_reflection_pipeline + && (matches!(mat.profile, FragmentProfile::Translucent) || mat.reads_scene) + { + continue; } if let Some((mesh, lmin, lmax)) = mesh_fetch(cmd.mesh_handle, cmd.mesh_idx) { + if bound != Some((cmd.material, mesh.layout)) { + let pipeline = if use_reflection_pipeline { + mat.reflection_pipeline.as_ref().unwrap_or(&mat.pipeline) + } else { + &mat.pipeline + }; + pass.set_pipeline(pipeline.get(mesh.layout)); + pass.set_bind_group(0, &self.per_frame_bg, &[]); + pass.set_bind_group(1, per_view_bg, &[]); + pass.set_bind_group(2, self.per_material_bg_for(cmd.material), &[]); + bound = Some((cmd.material, mesh.layout)); + } pass.set_bind_group(3, &self.per_draw_bgs[cmd.draw_slot], &[]); pass.set_vertex_buffer(0, mesh.vertex.slice(..)); + super::vertex_formats::bind_skin_zero( + pass, + mesh.layout, + super::vertex_formats::zero_slot(u32::from(mat.wants_instancing)), + &self.skin_zero, + ); pass.set_index_buffer(mesh.index.slice(..), wgpu::IndexFormat::Uint32); let instance_range = self.bind_instance_buffer(pass, &cmd.instance); if instance_range.end <= instance_range.start { @@ -2255,12 +2263,13 @@ impl MaterialSystem { return; } - let mut last_material: MaterialHandle = 0; + let mut last_material = None; for cmd in &self.translucent_commands { if let Some(mesh) = mesh_fetch(cmd.mesh_handle, cmd.mesh_idx) { - let bind_material_state = cmd.material != last_material; + let key = (cmd.material, mesh.layout); + let bind_material_state = last_material != Some(key); if self.dispatch_translucent_command(pass, cmd, mesh, false, bind_material_state) { - last_material = cmd.material; + last_material = Some(key); } } } diff --git a/native/shared/src/renderer/material_system_tests.rs b/native/shared/src/renderer/material_system_tests.rs index e0c019d2..c0cd8cb4 100644 --- a/native/shared/src/renderer/material_system_tests.rs +++ b/native/shared/src/renderer/material_system_tests.rs @@ -367,6 +367,7 @@ fn fs_reactive(_in: VsOut) -> ReactiveTranslucentOut { first_index: 0, index_count: icount, base_vertex: 0, + layout: crate::renderer::VertexLayout::Full96, }) } else { None @@ -638,6 +639,7 @@ fn fs_reactive(_in: VsOut) -> ReactiveTranslucentOut { first_index: 0, index_count, base_vertex: 0, + layout: crate::renderer::VertexLayout::Full96, }, true, true, @@ -900,6 +902,7 @@ fn fs_main(_in: VsOut) -> TranslucentOut { first_index: 0, index_count: icount, base_vertex: 0, + layout: crate::renderer::VertexLayout::Full96, }) } else { None diff --git a/native/shared/src/renderer/mod.rs b/native/shared/src/renderer/mod.rs index 3c23821c..1e44257d 100644 --- a/native/shared/src/renderer/mod.rs +++ b/native/shared/src/renderer/mod.rs @@ -141,6 +141,7 @@ pub use virtual_model_api::VirtualNodeRole; mod volumetric_fog; #[cfg(feature = "models3d")] pub use virtual_geometry_integration::RendererVirtualGeometryError; +pub(crate) mod vertex_formats; pub(crate) mod visibility_buffer; mod visibility_ids; pub(crate) mod visibility_shading; @@ -220,6 +221,8 @@ use types::{ MAX_UNIFORM_SLOTS, }; pub use types::{RenderMode, SceneMaterialUniforms, Vertex2D, Vertex3D}; +use vertex_formats::{bind_skin_zero, MeshPipelines}; +pub use vertex_formats::{StaticVertex3D, VertexLayout}; // ============================================================ // Shaders @@ -339,6 +342,8 @@ pub(super) struct MeshDrawRef<'a> { pub(super) first_index: u32, pub(super) index_count: u32, pub(super) base_vertex: i32, + /// The format `vertex` holds: picks the pipeline and the zero stream. + pub(super) layout: VertexLayout, } impl MeshDrawRef<'_> { @@ -1187,7 +1192,7 @@ pub struct Renderer { /// captures land; consumed by the card-lighting pass for NdotL. pub card_slot_meta_buffer: wgpu::Buffer, - pub card_capture_pipeline: LazyRenderPipeline, + pub card_capture_pipeline: MeshPipelines, pub card_capture_uniform_layout: wgpu::BindGroupLayout, pub card_capture_texture_layout: wgpu::BindGroupLayout, pub card_capture_uniform: wgpu::Buffer, @@ -1665,15 +1670,15 @@ pub struct Renderer { // Scene pipeline (retained scene graph rendering with normal // mapping). Distinct from pipeline_3d so immediate-mode draws // don't have to carry tangent vertex data or normal-map bindings. - pub scene_pipeline: LazyRenderPipeline, + pub scene_pipeline: MeshPipelines, /// The settings the pipelines were last prewarmed for (lazy_pipeline.rs). prewarm_signature: u64, - scene_transparent_pipeline: LazyRenderPipeline, - scene_transparent_double_sided_pipeline: LazyRenderPipeline, - scene_transparent_reactive_pipeline: Option, - scene_transparent_reactive_double_sided_pipeline: Option, - scene_weighted_transparent_pipeline: Option, - scene_weighted_transparent_double_sided_pipeline: Option, + scene_transparent_pipeline: MeshPipelines, + scene_transparent_double_sided_pipeline: MeshPipelines, + scene_transparent_reactive_pipeline: Option, + scene_transparent_reactive_double_sided_pipeline: Option, + scene_weighted_transparent_pipeline: Option, + scene_weighted_transparent_double_sided_pipeline: Option, weighted_transparency_resolve_pipeline: Option, weighted_transparency_reactive_resolve_pipeline: Option, weighted_transparency_resolve_layout: Option, @@ -1686,14 +1691,14 @@ pub struct Renderer { /// route gate. Opaque-only scenes keep both at None/false. transmitted_shadow_resources: Option, transmitted_shadows_active: bool, - scene_refractive_pipeline: Option, - scene_refractive_double_sided_pipeline: Option, - scene_refractive_uv1_pipeline: Option, - scene_refractive_uv1_double_sided_pipeline: Option, - scene_refractive_reactive_pipeline: Option, - scene_refractive_reactive_double_sided_pipeline: Option, - scene_refractive_reactive_uv1_pipeline: Option, - scene_refractive_reactive_uv1_double_sided_pipeline: Option, + scene_refractive_pipeline: Option, + scene_refractive_double_sided_pipeline: Option, + scene_refractive_uv1_pipeline: Option, + scene_refractive_uv1_double_sided_pipeline: Option, + scene_refractive_reactive_pipeline: Option, + scene_refractive_reactive_double_sided_pipeline: Option, + scene_refractive_reactive_uv1_pipeline: Option, + scene_refractive_reactive_uv1_double_sided_pipeline: Option, /// Native physical-transmission group 4 specialization. Present only when /// the bounded screen-space reflection tier is startup-enabled and a /// contributing material has forced lazy pipeline creation. @@ -1705,19 +1710,19 @@ pub struct Renderer { scene_refractive_reflection_params_buffer: Option, refractive_reflections_active: bool, /// EN-044 — depth-only prepass over the same cached-model draws. - pub scene_depth_pipeline: LazyRenderPipeline, + pub scene_depth_pipeline: MeshPipelines, /// The same with a fragment stage that cannot discard, for solid meshes. - scene_depth_opaque_pipeline: LazyRenderPipeline, + scene_depth_opaque_pipeline: MeshPipelines, /// Shade-mode depth-only variant whose inert color slot makes it /// compatible with the inline packed visibility attachment. #[cfg(not(target_arch = "wasm32"))] - scene_depth_visibility_pipeline: Option, + scene_depth_visibility_pipeline: Option, /// EN-044 — cached-model pipeline for the prepassed path (no depth write, Equal). - pub scene_pipeline_prepassed: LazyRenderPipeline, + pub scene_pipeline_prepassed: MeshPipelines, /// The retained scene nodes' depth prepass and prepassed pipeline: as /// above, with scene_pipeline's back-face culling. - scene_node_depth_pipeline: LazyRenderPipeline, - scene_node_pipeline_prepassed: LazyRenderPipeline, + scene_node_depth_pipeline: MeshPipelines, + scene_node_pipeline_prepassed: MeshPipelines, pub scene_material_layout: wgpu::BindGroupLayout, scene_sheen_albedo_lut: Option, scene_layered_pbr_resources: Option, @@ -1819,7 +1824,7 @@ pub struct Renderer { /// house) into the planar probe with a mirrored VP. Single-target HDR /// pipeline + a dynamic per-draw model uniform + a sun/ambient uniform. /// `None` until the first `dispatch_planar_reflections` with a probe. - pub reflect_scene_pipeline: Option, + pub reflect_scene_pipeline: Option, pub reflect_model_buf: Option, pub reflect_model_bg: Option, pub reflect_light_buf: Option, @@ -2030,6 +2035,7 @@ impl Renderer { // when the high-tier VSM environment switch is also present. let renderer_capabilities = capabilities::RendererCapabilities::detect(device.features(), &device.limits()); + vertex_formats::configure_for_backend(device.adapter_info().backend); crate::virtual_shadows::configure_capability_tier(renderer_capabilities.selected_tier); // EN-063 — the format frames are RENDERED in, as opposed to the @@ -3880,7 +3886,7 @@ impl Renderer { ], immediate_size: 0, }); - let scene_pipeline = LazyRenderPipeline::new( + let scene_pipeline = MeshPipelines::lazy( &device, &wgpu::RenderPipelineDescriptor { label: Some("scene_pipeline"), @@ -3961,7 +3967,7 @@ impl Renderer { let create_scene_transparent_pipeline = |label: &'static str, cull_mode: Option| { - LazyRenderPipeline::new( + MeshPipelines::lazy( &device, &wgpu::RenderPipelineDescriptor { label: Some(label), @@ -4055,7 +4061,7 @@ impl Renderer { // scene_pipeline: their prepass culls the same faces. let create_scene_pipeline_prepassed = |label: &'static str, cull_mode: Option| { - LazyRenderPipeline::new( + MeshPipelines::lazy( &device, &wgpu::RenderPipelineDescriptor { label: Some(label), @@ -6716,7 +6722,7 @@ impl Renderer { ], immediate_size: 0, }); - let card_capture_pipeline = LazyRenderPipeline::new( + let card_capture_pipeline = MeshPipelines::lazy( &device, &wgpu::RenderPipelineDescriptor { label: Some("card_capture_pipeline"), @@ -9603,7 +9609,7 @@ impl Renderer { has_em, node.material.emissive, em_idx, - vb.clone(), + (vb.clone(), node.gpu_vb_layout), ib.clone(), node.gpu_index_count, ) @@ -9670,7 +9676,8 @@ impl Renderer { capture_draws.push(CardCaptureDraw { uniform_offset: uniform_offset as u32, texture_bg: texture_bg.clone(), - vertex_buffer: vb_ptr.clone(), + vertex_buffer: vb_ptr.0.clone(), + vertex_layout: vb_ptr.1, index_buffer: ib_ptr.clone(), index_count, cell_x: axis * CARD_SLOT_SIZE, @@ -10742,7 +10749,7 @@ impl Renderer { size: &size_descs[i], vertex_buffer: vb, first_vertex: 0, - vertex_stride: std::mem::size_of::() as u64, + vertex_stride: n.gpu_vb_layout.stride(), index_buffer: Some(ib), first_index: Some(0), transform_buffer: None, @@ -12042,8 +12049,9 @@ impl Renderer { }); let create_pipeline = |label: &'static str, cull_mode: Option| { - self.device - .create_render_pipeline(&wgpu::RenderPipelineDescriptor { + MeshPipelines::lazy( + &self.device, + &wgpu::RenderPipelineDescriptor { label: Some(label), layout: Some(&pipeline_layout), vertex: wgpu::VertexState { @@ -12091,7 +12099,8 @@ impl Renderer { multisample: wgpu::MultisampleState::default(), multiview_mask: None, cache: None, - }) + }, + ) }; self.scene_refractive_pipeline = Some(create_pipeline( "scene_refractive_pipeline", @@ -12182,8 +12191,9 @@ impl Renderer { }); let vertex_layouts = [Vertex3D::desc(), secondary_uv_desc()]; let create_pipeline = |label: &'static str, cull_mode: Option| { - self.device - .create_render_pipeline(&wgpu::RenderPipelineDescriptor { + MeshPipelines::lazy( + &self.device, + &wgpu::RenderPipelineDescriptor { label: Some(label), layout: Some(&layout), vertex: wgpu::VertexState { @@ -12228,7 +12238,8 @@ impl Renderer { multisample: wgpu::MultisampleState::default(), multiview_mask: None, cache: None, - }) + }, + ) }; self.scene_refractive_uv1_pipeline = Some(create_pipeline( "scene_refractive_uv1_pipeline", @@ -13023,7 +13034,6 @@ impl Renderer { // color + normal map) apply — drawModel should behave the same // as attachModelToNode for PBR purposes. if !self.model_draw_commands.is_empty() { - pass.set_pipeline(&self.scene_pipeline); pass.set_bind_group(1, &self.lighting_bind_group, &[]); pass.set_bind_group(3, &self.joint_bind_group, &[]); let mut joint_page = 0; @@ -13038,6 +13048,7 @@ impl Renderer { cmd.joint_offset, cmd.mesh_idx, ); + pass.set_pipeline(self.scene_pipeline.get(draw.layout)); self.bind_joint_page(&mut pass, 3, cmd.joint_offset, &mut joint_page); pass.set_bind_group( 0, @@ -13046,6 +13057,7 @@ impl Renderer { ); pass.set_bind_group(2, &mesh.material_bg, &[]); pass.set_vertex_buffer(0, draw.vertex.slice(..)); + bind_skin_zero(&mut pass, draw.layout, 1, self.gpu_driven.skin_zero()); pass.set_index_buffer(draw.index.slice(..), wgpu::IndexFormat::Uint32); pass.draw_indexed(draw.index_range(), draw.base_vertex, 0..1); } @@ -14240,6 +14252,7 @@ impl Renderer { // buffers because the compute pre-skin pass reads them directly. let geometry = if is_skinned { gpu_driven::MeshGeometry::Dedicated { + layout: VertexLayout::Full96, vertex: self .device .create_buffer_init(&wgpu::util::BufferInitDescriptor { @@ -14296,16 +14309,18 @@ impl Renderer { index_count: mesh.indices.len() as u32, }, ); - let (vertex_byte_offset, index_byte_offset) = match &geometry { - gpu_driven::MeshGeometry::Shared(slice) => { - (slice.vertex_offset, slice.index_offset) - } - gpu_driven::MeshGeometry::Dedicated { .. } => (0, 0), + let (vertex_byte_offset, index_byte_offset, geometry_layout) = match &geometry { + gpu_driven::MeshGeometry::Shared(slice) => ( + slice.vertex_offset, + slice.index_offset, + self.gpu_driven.arena_layout(), + ), + gpu_driven::MeshGeometry::Dedicated { layout, .. } => (0, 0, *layout), }; let vertex_buffer_view_id = self.material_system.indirection.register_buffer_view( material_indirection::ResidentBufferView { byte_offset: vertex_byte_offset, - byte_size: (mesh.vertices.len() * std::mem::size_of::()) as u64, + byte_size: mesh.vertices.len() as u64 * geometry_layout.stride(), }, ); let index_buffer_view_id = self.material_system.indirection.register_buffer_view( diff --git a/native/shared/src/renderer/morph_pass.rs b/native/shared/src/renderer/morph_pass.rs index 0149fd12..7f08ec34 100644 --- a/native/shared/src/renderer/morph_pass.rs +++ b/native/shared/src/renderer/morph_pass.rs @@ -386,6 +386,7 @@ impl MorphPass { if skinned && !self.overrides.is_empty() { if let Some(vb) = self.vertex_buffer(joint_offset, mesh_idx) { draw.vertex = vb; + draw.layout = VertexLayout::Full96; } } draw @@ -773,8 +774,13 @@ impl Renderer { .and_then(|m| m.as_ref()) .and_then(|m| m.get(mesh_idx)) .and_then(|m| match &m.geometry { - gpu_driven::MeshGeometry::Dedicated { vertex, .. } => Some(vertex), - gpu_driven::MeshGeometry::Shared(_) => None, + // Morphs read and write 96-byte vertices: skinned meshes only. + gpu_driven::MeshGeometry::Dedicated { + vertex, + layout: super::VertexLayout::Full96, + .. + } => Some(vertex), + _ => None, }) else { continue; diff --git a/native/shared/src/renderer/planar_pass.rs b/native/shared/src/renderer/planar_pass.rs index 9ebbf2b8..e06ebfc0 100644 --- a/native/shared/src/renderer/planar_pass.rs +++ b/native/shared/src/renderer/planar_pass.rs @@ -127,9 +127,9 @@ impl Renderer { ], immediate_size: 0, }); - let pipeline = self - .device - .create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let pipeline = MeshPipelines::lazy( + &self.device, + &wgpu::RenderPipelineDescriptor { label: Some("reflect_scene_pipeline"), layout: Some(&pl), vertex: wgpu::VertexState { @@ -163,7 +163,8 @@ impl Renderer { multisample: Default::default(), multiview_mask: None, cache: None, - }); + }, + ); let model_buf = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("reflect_model_buf"), size: REFLECT_STRIDE * REFLECT_MAX_DRAWS as u64, @@ -580,7 +581,9 @@ impl Renderer { staged[base + 64..base + 128].copy_from_slice(bytemuck::bytes_of(&cmd.model)); reflect_draws.push((cmd.cache_handle, cmd.mesh_idx, slot as u32)); } - for (i, (_vb, _ib, _ic, _bg, model, wmin, wmax)) in scene_draws.iter().enumerate() { + for (i, (_vb, _ib, _ic, _layout, _bg, model, wmin, wmax)) in + scene_draws.iter().enumerate() + { let slot = reflect_draws.len() + node_slots.len(); if slot >= REFLECT_MAX_DRAWS { break; @@ -740,11 +743,12 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); + let zero = self.gpu_driven.skin_zero(); if let (Some(rp), Some(rmbg), Some(rlbg)) = (refl_pipeline, refl_model_bg, refl_light_bg) { if !reflect_draws.is_empty() || !node_slots.is_empty() { - pass.set_pipeline(rp); + let mut current_layout = None; pass.set_bind_group(1, rlbg, &[]); for (handle, midx, slot) in &reflect_draws { if let Some(Some(meshes)) = cache.get(handle) { @@ -752,9 +756,14 @@ impl Renderer { let mesh = &meshes[*midx]; let draw = self.gpu_driven.mesh_draw(&mesh.geometry, mesh.index_count); + if current_layout != Some(draw.layout) { + pass.set_pipeline(rp.get(draw.layout)); + current_layout = Some(draw.layout); + } pass.set_bind_group(0, rmbg, &[*slot * REFLECT_STRIDE as u32]); pass.set_bind_group(2, &mesh.material_bg, &[]); pass.set_vertex_buffer(0, draw.vertex.slice(..)); + bind_skin_zero(&mut pass, draw.layout, 1, zero); pass.set_index_buffer( draw.index.slice(..), wgpu::IndexFormat::Uint32, @@ -767,11 +776,16 @@ impl Renderer { // Vertex3D and node material bind groups share the // scene material layout the pipeline's g2 expects. for (i, slot) in &node_slots { - let (vb, ib, index_count, mat_bg, _model, _wmin, _wmax) = + let (vb, ib, index_count, layout, mat_bg, _model, _wmin, _wmax) = &scene_draws[*i]; + if current_layout != Some(*layout) { + pass.set_pipeline(rp.get(*layout)); + current_layout = Some(*layout); + } pass.set_bind_group(0, rmbg, &[*slot * REFLECT_STRIDE as u32]); pass.set_bind_group(2, *mat_bg, &[]); pass.set_vertex_buffer(0, vb.slice(..)); + bind_skin_zero(&mut pass, *layout, 1, zero); pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32); pass.draw_indexed(0..*index_count, 0, 0..1); } diff --git a/native/shared/src/renderer/pt_dynamic_skin.rs b/native/shared/src/renderer/pt_dynamic_skin.rs index 849553fb..72f097d9 100644 --- a/native/shared/src/renderer/pt_dynamic_skin.rs +++ b/native/shared/src/renderer/pt_dynamic_skin.rs @@ -218,10 +218,15 @@ impl Renderer { let src_vb = match self.model_gpu_cache.get(&w.cache_handle) { Some(Some(meshes)) => match meshes.get(w.mesh_idx) { Some(m) => match &m.geometry { - gpu_driven::MeshGeometry::Dedicated { vertex, .. } => vertex, // Dynamic PT windows are registered only for skinned - // cached meshes, which always retain dedicated input. - gpu_driven::MeshGeometry::Shared(_) => continue, + // cached meshes, which always retain dedicated 96-byte + // input (cs_skin reads 24 words a vertex). + gpu_driven::MeshGeometry::Dedicated { + vertex, + layout: super::VertexLayout::Full96, + .. + } => vertex, + _ => continue, }, None => continue, }, diff --git a/native/shared/src/renderer/scene_pass.rs b/native/shared/src/renderer/scene_pass.rs index f683feb2..e7e1caa4 100644 --- a/native/shared/src/renderer/scene_pass.rs +++ b/native/shared/src/renderer/scene_pass.rs @@ -15,14 +15,14 @@ pub(super) fn create_scene_depth_pipeline( visibility_target: bool, cull_mode: Option, cutout: bool, -) -> super::lazy_pipeline::LazyRenderPipeline { +) -> super::vertex_formats::MeshPipelines { let targets = [visibility_target.then_some(wgpu::ColorTargetState { format: visibility_buffer::VISIBILITY_FORMAT, blend: None, // Cached-model depth draws do not own packed visibility IDs. write_mask: wgpu::ColorWrites::empty(), })]; - super::lazy_pipeline::LazyRenderPipeline::new( + super::vertex_formats::MeshPipelines::lazy( device, &wgpu::RenderPipelineDescriptor { label: Some(label), @@ -224,11 +224,12 @@ impl Renderer { let one_pipeline = self.dbg_skip("prepass_split"); // A/B diag let mut joint_page = 0; for cutout_round in [false, true] { - pass.set_pipeline(match &self.scene_depth_visibility_pipeline { + let depth_pipelines = match &self.scene_depth_visibility_pipeline { Some(visibility) => visibility, None if cutout_round || one_pipeline => &self.scene_depth_pipeline, None => &self.scene_depth_opaque_pipeline, - }); + }; + let mut current_layout = None; for cmd in &self.model_draw_commands { if let Some(Some(meshes)) = self.model_gpu_cache.get(&cmd.cache_handle) { if cmd.mesh_idx < meshes.len() { @@ -266,6 +267,10 @@ impl Renderer { cmd.joint_offset, cmd.mesh_idx, ); + if current_layout != Some(draw.layout) { + pass.set_pipeline(depth_pipelines.get(draw.layout)); + current_layout = Some(draw.layout); + } self.bind_joint_page( &mut pass, 3, @@ -279,6 +284,12 @@ impl Renderer { ); pass.set_bind_group(2, &mesh.material_bg, &[]); pass.set_vertex_buffer(0, draw.vertex.slice(..)); + bind_skin_zero( + &mut pass, + draw.layout, + 1, + self.gpu_driven.skin_zero(), + ); pass.set_index_buffer( draw.index.slice(..), wgpu::IndexFormat::Uint32, @@ -292,11 +303,12 @@ impl Renderer { // The opaque retained nodes, so the main pass shades each of // their pixels once (see Scene::render_depth_prepass). if !self.dbg_skip("scene_graph") { - pass.set_pipeline(&self.scene_node_depth_pipeline); scene.render_depth_prepass( &mut pass, self.gpu_driven.submitting(), self.imported_refraction_enabled, + &self.scene_node_depth_pipeline, + self.gpu_driven.skin_zero(), ); } #[cfg(feature = "models3d")] @@ -566,17 +578,14 @@ impl Renderer { // write, Equal test), because the depth prepass above already stored // their exact depth. That is what lets the hardware early-Z reject the // occluded leaf cards instead of shading every one of them. - #[cfg(not(target_arch = "wasm32"))] - pass.set_pipeline(&self.scene_pipeline_prepassed); // wasm: no prepass priming (see above) — classic Less + write. - #[cfg(target_arch = "wasm32")] - pass.set_pipeline(&self.scene_pipeline); #[cfg(not(target_arch = "wasm32"))] let base_cached_pipeline = &self.scene_pipeline_prepassed; #[cfg(target_arch = "wasm32")] let base_cached_pipeline = &self.scene_pipeline; let cached_prepassed = cfg!(not(target_arch = "wasm32")); - let mut current_cached_pipeline = Some((false, false)); + // (layered, uv1, vertex format); each picked per draw. + let mut current_cached_pipeline = None; pass.set_bind_group(1, &self.lighting_bind_group, &[]); pass.set_bind_group(3, &self.joint_bind_group, &[]); @@ -659,24 +668,6 @@ impl Renderer { let layered_material = mesh.layered_material_bg.as_ref(); let layered_uv1 = layered_material.is_some() && mesh.layered_uses_uv1; - if current_cached_pipeline - != Some((layered_material.is_some(), layered_uv1)) - { - if layered_material.is_some() { - let resources = self - .scene_layered_pbr_resources - .as_ref() - .expect("layered material initialized its pipelines"); - pass.set_pipeline( - resources - .opaque_pipeline(layered_uv1, cached_prepassed), - ); - } else { - pass.set_pipeline(base_cached_pipeline); - } - current_cached_pipeline = - Some((layered_material.is_some(), layered_uv1)); - } let (draw, vertex_offset, index_offset) = if layered_uv1 { let Some(secondary_uv) = mesh.layered_uv1_buffer.as_ref() else { @@ -700,6 +691,23 @@ impl Renderer { cmd.joint_offset, cmd.mesh_idx, ); + let key = (layered_material.is_some(), layered_uv1, draw.layout); + if current_cached_pipeline != Some(key) { + if layered_material.is_some() { + let resources = self + .scene_layered_pbr_resources + .as_ref() + .expect("layered material initialized its pipelines"); + pass.set_pipeline(resources.opaque_pipeline( + layered_uv1, + cached_prepassed, + draw.layout, + )); + } else { + pass.set_pipeline(base_cached_pipeline.get(draw.layout)); + } + current_cached_pipeline = Some(key); + } self.bind_joint_page( &mut pass, 3, @@ -717,6 +725,12 @@ impl Renderer { &[], ); pass.set_vertex_buffer(0, draw.vertex.slice(vertex_offset..)); + bind_skin_zero( + &mut pass, + draw.layout, + vertex_formats::zero_slot(u32::from(layered_uv1)), + self.gpu_driven.skin_zero(), + ); pass.set_index_buffer( draw.index.slice(index_offset..), wgpu::IndexFormat::Uint32, @@ -734,14 +748,14 @@ impl Renderer { // (wasm, or a diagnostic skip) they keep the depth-writing one. if !self.dbg_skip("scene_graph") { // SH-055 diag - pass.set_pipeline(&self.scene_pipeline); scene.render_with_material_specializations( &mut pass, self.gpu_driven.submitting(), self.imported_refraction_enabled, &self.scene_pipeline, self.scene_layered_pbr_resources.as_ref(), - scene_nodes_prepassed.then_some(&*self.scene_node_pipeline_prepassed), + scene_nodes_prepassed.then_some(&self.scene_node_pipeline_prepassed), + self.gpu_driven.skin_zero(), ); } // Game-compiled opaque materials share this pass (see @@ -839,7 +853,6 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); - pass.set_pipeline(&self.scene_pipeline); pass.set_bind_group(1, &self.lighting_bind_group, &[]); pass.set_bind_group(3, &self.joint_bind_group, &[]); scene.render_layer_with_material_specializations( @@ -848,6 +861,7 @@ impl Renderer { self.imported_refraction_enabled, &self.scene_pipeline, self.scene_layered_pbr_resources.as_ref(), + self.gpu_driven.skin_zero(), ); } profiler.end("main_hdr_pass"); @@ -998,13 +1012,14 @@ impl Renderer { &mut joint_page, ); let uses_uv1 = draw.secondary_uv.is_some(); - let pipeline_key = (draw.layered, draw.double_sided, uses_uv1); + let layout = draw.mesh.layout; + let pipeline_key = (draw.layered, draw.double_sided, uses_uv1, layout); if current_pipeline_key != Some(pipeline_key) { let pipeline = if draw.layered { self.scene_layered_refractive_resources .as_ref() .expect("layered refractive material initialized its pipelines") - .pipeline(uses_uv1, draw.double_sided, reactive) + .pipeline(uses_uv1, draw.double_sided, reactive, layout) } else { match (reactive, uses_uv1, draw.double_sided) { (false, false, false) => self.scene_refractive_pipeline.as_ref(), @@ -1025,6 +1040,7 @@ impl Renderer { .as_ref(), } .expect("selected imported-refraction pipeline must be initialized") + .get(layout) }; pass.set_pipeline(pipeline); current_pipeline_key = Some(pipeline_key); @@ -1035,6 +1051,12 @@ impl Renderer { if let Some(secondary_uv) = draw.secondary_uv { pass.set_vertex_buffer(1, secondary_uv.slice(..)); } + bind_skin_zero( + pass, + layout, + vertex_formats::zero_slot(u32::from(uses_uv1)), + self.gpu_driven.skin_zero(), + ); pass.set_index_buffer( draw.mesh.index.slice(draw.index_byte_offset..), wgpu::IndexFormat::Uint32, diff --git a/native/shared/src/renderer/shadow_pass.rs b/native/shared/src/renderer/shadow_pass.rs index 9a455b99..e43340af 100644 --- a/native/shared/src/renderer/shadow_pass.rs +++ b/native/shared/src/renderer/shadow_pass.rs @@ -9,6 +9,8 @@ use super::*; /// shadow pages and the local-light shadow maps. pub(crate) struct ShadowDrawEntry { pub(crate) vb_idx: usize, + /// The vertex format of `vb_idx`'s buffer: picks the pipeline variant. + pub(crate) layout: VertexLayout, pub(crate) ib_idx: usize, pub(crate) index_start: u32, pub(crate) index_count: u32, @@ -55,6 +57,20 @@ pub(crate) struct ShadowDrawEntry { } impl Renderer { + /// The shadow pipeline of a caster of `kind` (0 opaque, 1 cutout, 2 + /// skinned) whose vertex buffer holds `layout`. Skinned casters are + /// always 96-byte. + fn shadow_caster_pipeline(&self, kind: u8, layout: VertexLayout) -> &wgpu::RenderPipeline { + match kind { + 1 => self.shadow_map.pipeline_cutout.get(layout), + 2 => { + debug_assert_eq!(layout, VertexLayout::Full96); + &self.shadow_map.pipeline_skinned + } + _ => self.shadow_map.pipeline.get(layout), + } + } + pub(super) fn record_shadow_pass( &mut self, encoder: &mut wgpu::CommandEncoder, @@ -308,12 +324,12 @@ impl Renderer { // A node drawn at a simpler level of detail casts with that level too: the full // mesh of a distant tree went into every cascade at its close-up triangle count. let lod = node.active_lod_geometry(); - let (vb, ib, index_count) = match lod { - Some((vb, ib, count)) => (vb, ib, count), + let (vb, ib, index_count, vb_layout) = match lod { + Some((vb, ib, count, layout)) => (vb, ib, count, layout), None => { let Some(vb) = &node.gpu_vb else { continue }; let Some(ib) = &node.gpu_ib else { continue }; - (vb, ib, node.gpu_index_count) + (vb, ib, node.gpu_index_count, node.gpu_vb_layout) } }; let vb_idx = shadow_vbs.len(); @@ -337,6 +353,7 @@ impl Renderer { let world_transform = node.world_transform(); shadow_nodes.push(ShadowDrawEntry { vb_idx, + layout: vb_layout, ib_idx: vb_idx, index_start: 0, index_count, @@ -376,6 +393,7 @@ impl Renderer { // unbounded, always-dirty entry (pre-segmentation shape). shadow_nodes.push(ShadowDrawEntry { vb_idx, + layout: VertexLayout::Full96, ib_idx: vb_idx, index_start: 0, index_count: self.indices_3d.len() as u32, @@ -409,6 +427,7 @@ impl Renderer { } shadow_nodes.push(ShadowDrawEntry { vb_idx, + layout: VertexLayout::Full96, ib_idx: vb_idx, index_start: call.index_start, index_count: count, @@ -488,6 +507,7 @@ impl Renderer { .unwrap_or(([1.0, 1.0, 1.0], [-1.0, -1.0, -1.0])); shadow_nodes.push(ShadowDrawEntry { vb_idx, + layout: draw.layout, ib_idx: vb_idx, index_start: draw.first_index, index_count: draw.index_count, @@ -541,6 +561,7 @@ impl Renderer { transform_aabb(&cmd.model, mesh.local_min, mesh.local_max); shadow_nodes.push(ShadowDrawEntry { vb_idx, + layout: draw.layout, ib_idx: vb_idx, index_start: draw.first_index, index_count: draw.index_count, @@ -616,6 +637,7 @@ impl Renderer { transform_aabb(&cmd.model, mesh.local_min, mesh.local_max); shadow_nodes.push(ShadowDrawEntry { vb_idx, + layout: draw.layout, ib_idx: vb_idx, index_start: draw.first_index, index_count: draw.index_count, @@ -1011,8 +1033,7 @@ impl Renderer { // Pipeline kind per caster: 0 opaque, 1 cutout, 2 skinned. // Only switch when the kind changes. - let mut cur_kind: u8 = 0; - shadow_pass.set_pipeline(&self.shadow_map.pipeline); + let mut cur_kind: Option<(u8, VertexLayout)> = None; for (slot, &ei) in static_entries.iter().enumerate() { let entry = &shadow_nodes[ei]; let offset = (static_base + slot * stride) as u32; @@ -1023,13 +1044,10 @@ impl Renderer { } else { 0 }; - if kind != cur_kind { - shadow_pass.set_pipeline(match kind { - 1 => &self.shadow_map.pipeline_cutout, - 2 => &self.shadow_map.pipeline_skinned, - _ => &self.shadow_map.pipeline, - }); - cur_kind = kind; + if cur_kind != Some((kind, entry.layout)) { + shadow_pass + .set_pipeline(self.shadow_caster_pipeline(kind, entry.layout)); + cur_kind = Some((kind, entry.layout)); } shadow_pass.set_bind_group(0, static_bind_group, &[offset]); if kind == 1 { @@ -1048,6 +1066,12 @@ impl Renderer { ); } shadow_pass.set_vertex_buffer(0, shadow_vbs[entry.vb_idx].slice(..)); + bind_skin_zero( + &mut shadow_pass, + entry.layout, + 1, + self.gpu_driven.skin_zero(), + ); shadow_pass.set_index_buffer( shadow_ibs[entry.ib_idx].slice(..), wgpu::IndexFormat::Uint32, @@ -1163,8 +1187,7 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); - let mut cur_kind: u8 = 0; - shadow_pass.set_pipeline(&self.shadow_map.pipeline); + let mut cur_kind: Option<(u8, VertexLayout)> = None; for (slot, &ei) in dyn_entries.iter().enumerate() { let entry = &shadow_nodes[ei]; let offset = (dyn_base + slot * stride) as u32; @@ -1175,13 +1198,10 @@ impl Renderer { } else { 0 }; - if kind != cur_kind { - shadow_pass.set_pipeline(match kind { - 1 => &self.shadow_map.pipeline_cutout, - 2 => &self.shadow_map.pipeline_skinned, - _ => &self.shadow_map.pipeline, - }); - cur_kind = kind; + if cur_kind != Some((kind, entry.layout)) { + shadow_pass + .set_pipeline(self.shadow_caster_pipeline(kind, entry.layout)); + cur_kind = Some((kind, entry.layout)); } shadow_pass.set_bind_group( 0, @@ -1206,6 +1226,12 @@ impl Renderer { ); } shadow_pass.set_vertex_buffer(0, shadow_vbs[entry.vb_idx].slice(..)); + bind_skin_zero( + &mut shadow_pass, + entry.layout, + 1, + self.gpu_driven.skin_zero(), + ); shadow_pass.set_index_buffer( shadow_ibs[entry.ib_idx].slice(..), wgpu::IndexFormat::Uint32, @@ -1515,8 +1541,7 @@ impl Renderer { index, ); } - let mut current_kind = 0u8; - page_pass.set_pipeline(&self.shadow_map.pipeline); + let mut current_kind: Option<(u8, VertexLayout)> = None; for (slot, &entry_index) in page_entries.iter().enumerate() { let entry = &shadow_nodes[entry_index]; let offset = (page_base + slot * stride) as u32; @@ -1529,13 +1554,10 @@ impl Renderer { }; page_cutout_draws += usize::from(kind == 1); page_skinned_draws += usize::from(kind == 2); - if kind != current_kind { - page_pass.set_pipeline(match kind { - 1 => &self.shadow_map.pipeline_cutout, - 2 => &self.shadow_map.pipeline_skinned, - _ => &self.shadow_map.pipeline, - }); - current_kind = kind; + if current_kind != Some((kind, entry.layout)) { + page_pass + .set_pipeline(self.shadow_caster_pipeline(kind, entry.layout)); + current_kind = Some((kind, entry.layout)); } page_pass.set_bind_group(0, vsm_uniforms, &[offset]); if kind == 1 { @@ -1554,6 +1576,12 @@ impl Renderer { ); } page_pass.set_vertex_buffer(0, shadow_vbs[entry.vb_idx].slice(..)); + bind_skin_zero( + &mut page_pass, + entry.layout, + 1, + self.gpu_driven.skin_zero(), + ); page_pass.set_index_buffer( shadow_ibs[entry.ib_idx].slice(..), wgpu::IndexFormat::Uint32, @@ -1591,6 +1619,7 @@ impl Renderer { pipeline: &self.shadow_map.pipeline, pipeline_cutout: &self.shadow_map.pipeline_cutout, pipeline_skinned: &self.shadow_map.pipeline_skinned, + skin_zero: self.gpu_driven.skin_zero(), joint_bind_group: &self.joint_bind_group, camera_pos: self.current_camera_pos, camera_planes: crate::scene::extract_frustum_planes(&mat4_multiply( diff --git a/native/shared/src/renderer/sorted_transparency.rs b/native/shared/src/renderer/sorted_transparency.rs index 3d087767..9e8b7b58 100644 --- a/native/shared/src/renderer/sorted_transparency.rs +++ b/native/shared/src/renderer/sorted_transparency.rs @@ -28,8 +28,9 @@ enum SortedPipelineKey { double_sided: bool, layered: bool, secondary_uv: bool, + layout: VertexLayout, }, - Custom(material_system::MaterialHandle), + Custom(material_system::MaterialHandle, VertexLayout), } #[derive(Copy, Clone, Debug)] @@ -110,9 +111,9 @@ impl material_system::MaterialSystem { let Some(pipeline) = material.reactive_pipeline.as_ref() else { return false; }; - pipeline + pipeline.get(mesh.layout) } else { - &material.pipeline + material.pipeline.get(mesh.layout) }; if bind_material_state { pass.set_pipeline(pipeline); @@ -127,6 +128,12 @@ impl material_system::MaterialSystem { } pass.set_bind_group(3, &self.per_draw_bgs[command.draw_slot], &[]); pass.set_vertex_buffer(0, mesh.vertex.slice(..)); + super::vertex_formats::bind_skin_zero( + pass, + mesh.layout, + super::vertex_formats::zero_slot(u32::from(material.wants_instancing)), + &self.skin_zero, + ); pass.set_index_buffer(mesh.index.slice(..), wgpu::IndexFormat::Uint32); let instance_range = self.bind_instance_buffer(pass, &command.instance); if instance_range.end > instance_range.start { @@ -142,13 +149,14 @@ impl material_system::MaterialSystem { ) where F: FnMut(u64, usize) -> Option>, { - let mut last_material = 0; + let mut last_material = None; for command in &self.translucent_commands { if let Some(mesh) = mesh_fetch(command.mesh_handle, command.mesh_idx) { - let bind_material_state = command.material != last_material; + let key = (command.material, mesh.layout); + let bind_material_state = last_material != Some(key); if self.dispatch_translucent_command(pass, command, mesh, true, bind_material_state) { - last_material = command.material; + last_material = Some(key); } } } @@ -287,8 +295,8 @@ impl Renderer { ) } else { ( - self.scene_transparent_pipeline.get(), - self.scene_transparent_double_sided_pipeline.get(), + &self.scene_transparent_pipeline, + &self.scene_transparent_double_sided_pipeline, ) }; pass.set_bind_group(1, &self.lighting_bind_group, &[]); @@ -303,17 +311,24 @@ impl Renderer { &mut joint_page, ); let secondary_uv = draw.secondary_uv.is_some(); - let pipeline_key = (draw.layered, secondary_uv, draw.double_sided); + let layout = draw.mesh.layout; + let pipeline_key = (draw.layered, secondary_uv, draw.double_sided, layout); if current_pipeline_key != Some(pipeline_key) { let pipeline = if draw.layered { self.scene_layered_pbr_resources .as_ref() .expect("layered material initialized its pipelines") - .transparent_pipeline(secondary_uv, draw.double_sided, reactive, weighted) + .transparent_pipeline( + secondary_uv, + draw.double_sided, + reactive, + weighted, + layout, + ) } else if draw.double_sided { - double_sided + double_sided.get(layout) } else { - single_sided + single_sided.get(layout) }; pass.set_pipeline(pipeline); current_pipeline_key = Some(pipeline_key); @@ -324,6 +339,12 @@ impl Renderer { if let Some(secondary_uv) = draw.secondary_uv { pass.set_vertex_buffer(1, secondary_uv.slice(..)); } + bind_skin_zero( + pass, + layout, + vertex_formats::zero_slot(u32::from(secondary_uv)), + self.gpu_driven.skin_zero(), + ); pass.set_index_buffer( draw.mesh.index.slice(draw.index_byte_offset..), wgpu::IndexFormat::Uint32, @@ -368,8 +389,8 @@ impl Renderer { ) } else { ( - self.scene_transparent_pipeline.get(), - self.scene_transparent_double_sided_pipeline.get(), + &self.scene_transparent_pipeline, + &self.scene_transparent_double_sided_pipeline, ) }; let mut current_pipeline = None; @@ -395,10 +416,12 @@ impl Renderer { }; if take_imported { let draw = imported.next().expect("peeked imported draw"); + let layout = draw.mesh.layout; let key = SortedPipelineKey::Imported { double_sided: draw.double_sided, layered: draw.layered, secondary_uv: draw.secondary_uv.is_some(), + layout, }; if current_pipeline != Some(key) { let pipeline = if draw.layered { @@ -410,11 +433,12 @@ impl Renderer { draw.double_sided, reactive, false, + layout, ) } else if draw.double_sided { - imported_pipelines.1 + imported_pipelines.1.get(layout) } else { - imported_pipelines.0 + imported_pipelines.0.get(layout) }; pass.set_pipeline(pipeline); pass.set_bind_group(1, &self.lighting_bind_group, &[]); @@ -434,6 +458,12 @@ impl Renderer { if let Some(secondary_uv) = draw.secondary_uv { pass.set_vertex_buffer(1, secondary_uv.slice(..)); } + bind_skin_zero( + pass, + layout, + vertex_formats::zero_slot(u32::from(draw.secondary_uv.is_some())), + self.gpu_driven.skin_zero(), + ); pass.set_index_buffer( draw.mesh.index.slice(draw.index_byte_offset..), wgpu::IndexFormat::Uint32, @@ -447,9 +477,9 @@ impl Renderer { let Some(mesh) = meshes.get(command.mesh_idx) else { continue; }; - let key = SortedPipelineKey::Custom(command.material); - let bind_material_state = current_pipeline != Some(key); let mesh = self.gpu_driven.mesh_draw(&mesh.geometry, mesh.index_count); + let key = SortedPipelineKey::Custom(command.material, mesh.layout); + let bind_material_state = current_pipeline != Some(key); if self.material_system.dispatch_translucent_command( pass, command, diff --git a/native/shared/src/renderer/temporal_reactive.rs b/native/shared/src/renderer/temporal_reactive.rs index aadb5c01..f088171b 100644 --- a/native/shared/src/renderer/temporal_reactive.rs +++ b/native/shared/src/renderer/temporal_reactive.rs @@ -426,8 +426,9 @@ impl Renderer { immediate_size: 0, }); let create_pipeline = |label: &'static str, cull_mode: Option| { - self.device - .create_render_pipeline(&wgpu::RenderPipelineDescriptor { + MeshPipelines::lazy( + &self.device, + &wgpu::RenderPipelineDescriptor { label: Some(label), layout: Some(&layout), vertex: wgpu::VertexState { @@ -472,7 +473,8 @@ impl Renderer { multisample: wgpu::MultisampleState::default(), multiview_mask: None, cache: None, - }) + }, + ) }; self.scene_transparent_reactive_pipeline = Some(create_pipeline( "scene_transparent_reactive_pipeline", @@ -540,8 +542,9 @@ impl Renderer { immediate_size: 0, }); let create_pipeline = |label: &'static str, cull_mode: Option| { - self.device - .create_render_pipeline(&wgpu::RenderPipelineDescriptor { + MeshPipelines::lazy( + &self.device, + &wgpu::RenderPipelineDescriptor { label: Some(label), layout: Some(&layout), vertex: wgpu::VertexState { @@ -591,7 +594,8 @@ impl Renderer { multisample: wgpu::MultisampleState::default(), multiview_mask: None, cache: None, - }) + }, + ) }; self.scene_refractive_reactive_pipeline = Some(create_pipeline( "scene_refractive_reactive_pipeline", @@ -667,8 +671,9 @@ impl Renderer { }); let vertex_layouts = [Vertex3D::desc(), secondary_uv_desc()]; let create_pipeline = |label: &'static str, cull_mode: Option| { - self.device - .create_render_pipeline(&wgpu::RenderPipelineDescriptor { + MeshPipelines::lazy( + &self.device, + &wgpu::RenderPipelineDescriptor { label: Some(label), layout: Some(&layout), vertex: wgpu::VertexState { @@ -718,7 +723,8 @@ impl Renderer { multisample: wgpu::MultisampleState::default(), multiview_mask: None, cache: None, - }) + }, + ) }; self.scene_refractive_reactive_uv1_pipeline = Some(create_pipeline( "scene_refractive_reactive_uv1_pipeline", diff --git a/native/shared/src/renderer/transmitted_shadows.rs b/native/shared/src/renderer/transmitted_shadows.rs index 6256417b..a0a7b512 100644 --- a/native/shared/src/renderer/transmitted_shadows.rs +++ b/native/shared/src/renderer/transmitted_shadows.rs @@ -581,7 +581,7 @@ fn create_transmitted_shadow_caster_pipeline( device: &wgpu::Device, layout: &wgpu::PipelineLayout, secondary_uv: bool, -) -> wgpu::RenderPipeline { +) -> MeshPipelines { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(if secondary_uv { "transmitted_shadow_caster_uv1_shader" @@ -600,52 +600,55 @@ fn create_transmitted_shadow_caster_pipeline( } else { &base_layouts[..] }; - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(if secondary_uv { - "transmitted_shadow_caster_uv1_pipeline" - } else { - "transmitted_shadow_caster_pipeline" - }), - layout: Some(layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_main"), - buffers: vertex_layouts, - compilation_options: Default::default(), - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_main"), - targets: &[Some(wgpu::ColorTargetState { - format: TRANSMITTED_SHADOW_COLOR_FORMAT, - blend: None, - write_mask: wgpu::ColorWrites::ALL, - })], - compilation_options: Default::default(), - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - front_face: wgpu::FrontFace::Ccw, - // Nearest-layer depth removes the back surface of closed volumes - // while still accepting either orientation of a pane. - cull_mode: None, - ..Default::default() - }, - depth_stencil: Some(wgpu::DepthStencilState { - format: TRANSMITTED_SHADOW_DEPTH_FORMAT, - depth_write_enabled: Some(true), - depth_compare: Some(wgpu::CompareFunction::Less), - stencil: Default::default(), - bias: wgpu::DepthBiasState { - constant: 1, - slope_scale: 1.0, - clamp: 0.0, + MeshPipelines::lazy( + device, + &wgpu::RenderPipelineDescriptor { + label: Some(if secondary_uv { + "transmitted_shadow_caster_uv1_pipeline" + } else { + "transmitted_shadow_caster_pipeline" + }), + layout: Some(layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: vertex_layouts, + compilation_options: Default::default(), }, - }), - multisample: Default::default(), - multiview_mask: None, - cache: None, - }) + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format: TRANSMITTED_SHADOW_COLOR_FORMAT, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: Default::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + front_face: wgpu::FrontFace::Ccw, + // Nearest-layer depth removes the back surface of closed volumes + // while still accepting either orientation of a pane. + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: TRANSMITTED_SHADOW_DEPTH_FORMAT, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::Less), + stencil: Default::default(), + bias: wgpu::DepthBiasState { + constant: 1, + slope_scale: 1.0, + clamp: 0.0, + }, + }), + multisample: Default::default(), + multiview_mask: None, + cache: None, + }, + ) } pub(super) struct TransmittedShadowResources { @@ -657,8 +660,8 @@ pub(super) struct TransmittedShadowResources { draw_uniform_bind_group: wgpu::BindGroup, blocker_bind_groups: [wgpu::BindGroup; crate::shadows::NUM_CASCADES], caster_pipeline_layout: wgpu::PipelineLayout, - caster_pipeline: wgpu::RenderPipeline, - caster_uv1_pipeline: Option, + caster_pipeline: MeshPipelines, + caster_uv1_pipeline: Option, resolve_uniform_buffer: wgpu::Buffer, resolve_layout: wgpu::BindGroupLayout, resolve_pipeline: wgpu::RenderPipeline, @@ -1064,6 +1067,7 @@ impl Renderer { struct Draw<'a> { vertex: &'a wgpu::Buffer, + layout: VertexLayout, secondary_uv: Option<&'a wgpu::Buffer>, index: &'a wgpu::Buffer, material: &'a wgpu::BindGroup, @@ -1126,6 +1130,7 @@ impl Renderer { }; draws.push(Draw { vertex, + layout: node.gpu_vb_layout, secondary_uv, index: index_buffer, material, @@ -1204,6 +1209,7 @@ impl Renderer { } draws.push(Draw { vertex: geometry.vertex, + layout: geometry.layout, secondary_uv, index: geometry.index, material, @@ -1325,16 +1331,17 @@ impl Renderer { let draw = &draws[draw_index]; self.bind_joint_page(&mut pass, 3, draw.joint_offset, &mut joint_page); let uses_uv1 = draw.secondary_uv.is_some(); - if current_uses_uv1 != Some(uses_uv1) { - pass.set_pipeline(if uses_uv1 { + if current_uses_uv1 != Some((uses_uv1, draw.layout)) { + let pipelines = if uses_uv1 { resources .caster_uv1_pipeline .as_ref() .expect("UV1 transmitted-shadow pipeline initialized on material use") } else { &resources.caster_pipeline - }); - current_uses_uv1 = Some(uses_uv1); + }; + pass.set_pipeline(pipelines.get(draw.layout)); + current_uses_uv1 = Some((uses_uv1, draw.layout)); } let offset = (cascade_base + slot * stride) as u32; pass.set_bind_group(0, &resources.draw_uniform_bind_group, &[offset]); @@ -1343,6 +1350,12 @@ impl Renderer { if let Some(secondary_uv) = draw.secondary_uv { pass.set_vertex_buffer(1, secondary_uv.slice(..)); } + bind_skin_zero( + &mut pass, + draw.layout, + vertex_formats::zero_slot(u32::from(uses_uv1)), + self.gpu_driven.skin_zero(), + ); pass.set_index_buffer( draw.index.slice(draw.index_byte_offset..), wgpu::IndexFormat::Uint32, diff --git a/native/shared/src/renderer/types.rs b/native/shared/src/renderer/types.rs index f4a472b3..7f3a7c2d 100644 --- a/native/shared/src/renderer/types.rs +++ b/native/shared/src/renderer/types.rs @@ -1328,6 +1328,9 @@ mod physical_uv_tests { #[test] fn secondary_uv_keeps_established_vertex_and_uniform_abis() { assert_eq!(std::mem::size_of::(), 96); + // Static meshes upload without joints/weights (vertex_formats.rs). + assert_eq!(std::mem::size_of::(), 64); + assert_eq!(super::super::StaticVertex3D::static_desc().array_stride, 64); assert_eq!(std::mem::size_of::(), 96); assert_eq!(std::mem::size_of::(), 144); let layout = secondary_uv_desc(); diff --git a/native/shared/src/renderer/vertex_formats.rs b/native/shared/src/renderer/vertex_formats.rs new file mode 100644 index 00000000..c1b77441 --- /dev/null +++ b/native/shared/src/renderer/vertex_formats.rs @@ -0,0 +1,458 @@ +//! The two GPU vertex formats of a mesh, and the pipeline pairs that draw them. +//! +//! `Vertex3D` is 96 bytes: position, normal, colour, uv, joints, weights and +//! tangent. A static (unskinned) mesh has nothing in its joints and weights, +//! so its vertex buffer holds `StaticVertex3D` instead: the same fields at the +//! same offsets without the 32 bytes of joints and weights, 64 bytes a vertex. +//! Shaders keep declaring `@location(4) joints` and `@location(5) weights` +//! (the material ABI publishes locations 0..6): a pipeline that draws a static +//! mesh reads them from a second vertex stream with `array_stride` 0 over one +//! shared 32-byte buffer of zeros, so every vertex sees exactly the zeros its +//! 96-byte vertex held. Nothing in any shader changes. +//! +//! A skinned mesh (any vertex whose weights add up to more than 0.01, the test +//! the engine's shaders and model cache already use) keeps the 96-byte layout. +//! A pass that can draw both kinds holds a pipeline for each +//! (`ByLayout`) and picks one per draw from the mesh's `VertexLayout`, which +//! is stored next to its vertex buffer. The zero stream goes in the slot after +//! the pipeline's other vertex buffers (`zero_slot`): slot 1, or slot 2 where +//! slot 1 carries instances or the second texture coordinates. +//! +//! OpenGL keeps 96 bytes everywhere: GL reads a vertex-attribute stride of 0 +//! as "tightly packed", not "the same vertex for every vertex". + +use super::lazy_pipeline::{LazyRenderPipeline, WarmHandle}; +use super::Vertex3D; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// A static mesh's vertex: `Vertex3D` without joints and weights. +#[repr(C)] +#[derive(Copy, Clone, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] +pub struct StaticVertex3D { + pub position: [f32; 3], + pub normal: [f32; 3], + pub color: [f32; 4], + pub uv: [f32; 2], + pub tangent: [f32; 4], +} + +impl StaticVertex3D { + pub fn from_vertex(v: &Vertex3D) -> Self { + Self { + position: v.position, + normal: v.normal, + color: v.color, + uv: v.uv, + tangent: v.tangent, + } + } + + /// Locations 0, 1, 2, 3 and 6, as in `Vertex3D::desc()`. + pub fn static_desc() -> wgpu::VertexBufferLayout<'static> { + const ATTRIBUTES: [wgpu::VertexAttribute; 5] = [ + wgpu::VertexAttribute { + offset: 0, + shader_location: 0, + format: wgpu::VertexFormat::Float32x3, + }, + wgpu::VertexAttribute { + offset: 12, + shader_location: 1, + format: wgpu::VertexFormat::Float32x3, + }, + wgpu::VertexAttribute { + offset: 24, + shader_location: 2, + format: wgpu::VertexFormat::Float32x4, + }, + wgpu::VertexAttribute { + offset: 40, + shader_location: 3, + format: wgpu::VertexFormat::Float32x2, + }, + wgpu::VertexAttribute { + offset: 48, + shader_location: 6, + format: wgpu::VertexFormat::Float32x4, + }, + ]; + wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as wgpu::BufferAddress, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &ATTRIBUTES, + } + } +} + +/// Bytes of the shared zero buffer: one `vec4` of joints and one of weights. +pub(crate) const SKIN_ZERO_BYTES: u64 = 32; + +/// Locations 4 (joints) and 5 (weights) from the zero buffer, the same 32 +/// bytes for every vertex. +pub(crate) fn skin_zero_desc() -> wgpu::VertexBufferLayout<'static> { + const ATTRIBUTES: [wgpu::VertexAttribute; 2] = [ + wgpu::VertexAttribute { + offset: 0, + shader_location: 4, + format: wgpu::VertexFormat::Float32x4, + }, + wgpu::VertexAttribute { + offset: 16, + shader_location: 5, + format: wgpu::VertexFormat::Float32x4, + }, + ]; + wgpu::VertexBufferLayout { + array_stride: 0, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &ATTRIBUTES, + } +} + +/// The shared zero joints and weights every static draw binds. +pub(crate) fn create_skin_zero_buffer(device: &wgpu::Device) -> wgpu::Buffer { + use wgpu::util::DeviceExt; + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("static_vertex_skin_zero"), + contents: &[0u8; SKIN_ZERO_BYTES as usize], + usage: wgpu::BufferUsages::VERTEX, + }) +} + +/// Set once a renderer is made on a backend that cannot use the 64-byte format. +static STATIC_LAYOUT_OFF: AtomicBool = AtomicBool::new(false); + +/// Called when a renderer is made: OpenGL keeps every mesh at 96 bytes. +pub(crate) fn configure_for_backend(backend: wgpu::Backend) { + if backend == wgpu::Backend::Gl { + STATIC_LAYOUT_OFF.store(true, Ordering::Relaxed); + } +} + +fn static_layout_enabled() -> bool { + !STATIC_LAYOUT_OFF.load(Ordering::Relaxed) +} + +/// The skin test of the engine's shaders and model cache. +pub(crate) fn weights_skin(w: [f32; 4]) -> bool { + w[0] + w[1] + w[2] + w[3] > 0.01 +} + +/// Which of the two formats a mesh's vertex buffer holds. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)] +pub enum VertexLayout { + /// `Vertex3D`, 96 bytes: skinned meshes, immediate-mode geometry, OpenGL. + #[default] + Full96, + /// `StaticVertex3D`, 64 bytes, joints and weights from the zero stream. + Static64, +} + +impl VertexLayout { + pub const fn stride(self) -> u64 { + match self { + VertexLayout::Full96 => 96, + VertexLayout::Static64 => 64, + } + } + + /// 32-bit words a vertex takes (storage readers of vertex buffers). + pub const fn words(self) -> u32 { + (self.stride() / 4) as u32 + } + + /// The layout of the mesh's own vertex stream (slot 0). + pub fn primary_desc(self) -> wgpu::VertexBufferLayout<'static> { + match self { + VertexLayout::Full96 => Vertex3D::desc(), + VertexLayout::Static64 => StaticVertex3D::static_desc(), + } + } + + /// The format these vertices go to the GPU in: 96 bytes if any vertex is + /// skinned, else 64. + pub fn for_vertices(vertices: &[Vertex3D]) -> Self { + if !static_layout_enabled() || vertices.iter().any(|v| weights_skin(v.weights)) { + VertexLayout::Full96 + } else { + VertexLayout::Static64 + } + } + + /// As `for_vertices`, for a shared model primitive's compact store. + pub fn for_store(store: &crate::models::VertexStore) -> Self { + if !static_layout_enabled() || (0..store.len()).any(|i| weights_skin(store.weight(i))) { + VertexLayout::Full96 + } else { + VertexLayout::Static64 + } + } + + /// The format of the shared static-geometry arena, which holds only + /// unskinned meshes. + pub fn arena() -> Self { + if static_layout_enabled() { + VertexLayout::Static64 + } else { + VertexLayout::Full96 + } + } + + /// The bytes of `vertices` in this format. + pub fn encode(self, vertices: &[Vertex3D]) -> std::borrow::Cow<'_, [u8]> { + match self { + VertexLayout::Full96 => std::borrow::Cow::Borrowed(bytemuck::cast_slice(vertices)), + VertexLayout::Static64 => { + let mut bytes = Vec::with_capacity(vertices.len() * 64); + for v in vertices { + bytes.extend_from_slice(bytemuck::bytes_of(&StaticVertex3D::from_vertex(v))); + } + std::borrow::Cow::Owned(bytes) + } + } + } +} + +/// The vertex buffers of a pipeline drawing this layout, from the 96-byte +/// list `full` (`Vertex3D::desc()` first, then the pipeline's other +/// streams): the primary stream swapped and the zero stream appended. +pub(crate) fn layout_buffers<'a>( + layout: VertexLayout, + full: &[wgpu::VertexBufferLayout<'a>], +) -> Vec> { + debug_assert_eq!( + full.first().map(|b| b.array_stride), + Some(std::mem::size_of::() as u64) + ); + let mut buffers = full.to_vec(); + if layout == VertexLayout::Static64 { + buffers[0] = StaticVertex3D::static_desc(); + buffers.push(skin_zero_desc()); + } + buffers +} + +/// The slot of the zero stream in a pipeline with `streams` vertex buffers +/// besides the mesh's own (0, or 1 with instances or texture coordinates 1). +pub(crate) const fn zero_slot(streams: u32) -> u32 { + 1 + streams +} + +/// Binds the zero joints and weights for a static draw (nothing for a +/// 96-byte one). +pub(crate) fn bind_skin_zero<'a>( + pass: &mut wgpu::RenderPass<'a>, + layout: VertexLayout, + slot: u32, + zero: &'a wgpu::Buffer, +) { + if layout == VertexLayout::Static64 { + pass.set_vertex_buffer(slot, zero.slice(..)); + } +} + +/// One of something for each vertex layout: typically a pipeline. +pub struct ByLayout { + pub(crate) full: T, + pub(crate) compact: T, +} + +impl ByLayout { + pub(crate) fn new(mut make: impl FnMut(VertexLayout) -> T) -> Self { + Self { + full: make(VertexLayout::Full96), + compact: make(VertexLayout::Static64), + } + } + + pub fn get(&self, layout: VertexLayout) -> &T { + match layout { + VertexLayout::Full96 => &self.full, + VertexLayout::Static64 => &self.compact, + } + } +} + +impl Clone for ByLayout { + fn clone(&self) -> Self { + Self { + full: self.full.clone(), + compact: self.compact.clone(), + } + } +} + +/// A lazy pipeline for each layout of the same descriptor. +pub type MeshPipelines = ByLayout; + +impl MeshPipelines { + /// Both layouts of `desc`, whose vertex buffers are the 96-byte list + /// (see `layout_buffers`). The 64-byte one is labelled `