perf(wire): switch wire pipeline to instanced rendering

Step 3 of the wire pipeline cold-open optimization plan — the biggest
single lever.

Each segment used to upload as 6 vertices × 96 B = 576 B with the segment
payload (pos_a/pos_b/color/half_width/distance/pattern_length/pat0/pat1)
duplicated across all six corners of the quad. Wire pipeline now uploads
one INSTANCE per segment (88 B) and the vertex shader derives `which_end`
and `side` from `@builtin(vertex_index)` against a 6-entry corner table.

Net effect on cold open: ~6.5× less wire vertex memory and PCIe upload,
plus a smaller Vec to allocate and copy on the CPU side.

Wire instance attributes also collapse distance_a / distance_b into a
single mix() inside the vertex shader, so per-segment distance still
interpolates correctly for the GPU-side linetype dash test.

Touches the wire, wire_xray, and face3d-edges draw passes.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
This commit is contained in:
HakanandClaude Opus 4.7 committed 2026-05-23 09:52:23 +03:00
1 parent 0ad7af7742
commit 4b4f5c94cd
3 files changed
+126 -136

No files matched your search

+11 -11
View File
@@ -158,7 +158,7 @@ impl Pipeline {
vertex: wgpu::VertexState {
module: &wire_shader,
entry_point: Some("vs_main"),
buffers: &[wire_gpu::WireVertex::layout()],
buffers: &[wire_gpu::WireInstance::layout()],
compilation_options: wgpu::PipelineCompilationOptions::default(),
},
primitive: wgpu::PrimitiveState {
@@ -201,7 +201,7 @@ impl Pipeline {
vertex: wgpu::VertexState {
module: &wire_shader,
entry_point: Some("vs_main"),
buffers: &[wire_gpu::WireVertex::layout()],
buffers: &[wire_gpu::WireInstance::layout()],
compilation_options: wgpu::PipelineCompilationOptions::default(),
},
primitive: wgpu::PrimitiveState {
@@ -1073,9 +1073,9 @@ impl Pipeline {
pass.set_pipeline(&self.wire_pipeline);
pass.set_bind_group(0, &self.uniform_bind_group, &[]);
for edges in &self.gpu_face3d_edges {
if edges.vertex_count >= 6 {
pass.set_vertex_buffer(0, edges.vertex_buffer.slice(..));
pass.draw(0..edges.vertex_count, 0..1);
if edges.instance_count > 0 {
pass.set_vertex_buffer(0, edges.instance_buffer.slice(..));
pass.draw(0..6, 0..edges.instance_count);
}
}
}
@@ -1109,7 +1109,7 @@ impl Pipeline {
pass.set_bind_group(0, &self.uniform_bind_group, &[]);
let mut scissor_active = false;
for (i, wire) in self.gpu_wires.iter().enumerate() {
if wire.vertex_count < 6 {
if wire.instance_count == 0 {
continue;
}
match self.wire_pixel_scissors.get(i) {
@@ -1123,8 +1123,8 @@ impl Pipeline {
}
_ => {}
}
pass.set_vertex_buffer(0, wire.vertex_buffer.slice(..));
pass.draw(0..wire.vertex_count, 0..1);
pass.set_vertex_buffer(0, wire.instance_buffer.slice(..));
pass.draw(0..6, 0..wire.instance_count);
}
if scissor_active {
pass.set_scissor_rect(0, 0, vp.width, vp.height);
@@ -1213,9 +1213,9 @@ impl Pipeline {
pass.set_pipeline(&self.wire_xray_pipeline);
pass.set_bind_group(0, &self.uniform_bind_group, &[]);
for wire in &self.gpu_selected_wires {
if wire.vertex_count >= 6 {
pass.set_vertex_buffer(0, wire.vertex_buffer.slice(..));
pass.draw(0..wire.vertex_count, 0..1);
if wire.instance_count > 0 {
pass.set_vertex_buffer(0, wire.instance_buffer.slice(..));
pass.draw(0..6, 0..wire.instance_count);
}
}
}
+84 -104
View File
@@ -1,27 +1,26 @@
// Wire GPU buffers — quad (TriangleList) rendering for thick lines.
// Wire GPU buffers — instanced quad rendering for thick lines.
//
// Each segment [A→B] emits 6 vertices (2 triangles). Every vertex carries
// both endpoints so the vertex shader can compute the screen-space
// perpendicular direction and expand the quad to the correct pixel width.
// Each segment [A→B] is one INSTANCE; the vertex shader expands a 6-vertex
// unit quad whose corners are derived from `@builtin(vertex_index)`. This
// cuts upload bandwidth by ~6.5× versus the old layout (which duplicated
// the segment payload across six vertex records).
//
// NaN sentinel: text glyphs pack multiple disconnected strokes into one
// WireModel, separated by [NaN, NaN, NaN] points. Segments where either
// endpoint contains NaN are silently skipped during upload.
// endpoint contains NaN are silently skipped during emission.
//
// Vertex layout (96 bytes, stride = 96):
// Instance layout (88 bytes, stride = 88, step_mode = Instance):
// pos_a [f32; 3] offset 0 12 B — segment start (world)
// pos_b [f32; 3] offset 12 12 B — segment end (world)
// which_end f32 offset 24 4 B — 0.0 = A end, 1.0 = B end
// side f32 offset 28 4 B — ±1.0 perpendicular side
// color [f32; 4] offset 32 16 B — RGBA [0,1]
// distance f32 offset 48 4 B — arc-length from wire start
// half_width f32 offset 52 4 B — half line width in pixels
// pattern_length f32 offset 56 4 B — dash pattern total length
// _pad f32 offset 60 4 B
// pat0 [f32; 4] offset 64 16 B — pattern elements 0-3
// pat1 [f32; 4] offset 80 16 B — pattern elements 4-7
// ------
// 96 B / vertex
// color [f32; 4] offset 24 16 B — RGBA [0,1]
// distance_a f32 offset 40 4 B — arc-length at endpoint A
// distance_b f32 offset 44 4 B — arc-length at endpoint B
// half_width f32 offset 48 4 B — half line width in pixels
// pattern_length f32 offset 52 4 B — dash pattern total length
// pat0 [f32; 4] offset 56 16 B — pattern elements 0-3
// pat1 [f32; 4] offset 72 16 B — pattern elements 4-7
// ------
// 88 B / instance
use crate::scene::wire_model::WireModel;
use iced::wgpu;
@@ -32,15 +31,15 @@ use rayon::prelude::*;
/// `create_buffer_init` performs and avoids holding a second `Vec` worth of
/// memory during upload — meaningful on cold open where wire buffers can run
/// into the hundreds of MB.
fn vertex_buffer_mapped(
fn instance_buffer_mapped(
device: &wgpu::Device,
label: &str,
data: &[WireVertex],
data: &[WireInstance],
) -> wgpu::Buffer {
let bytes: &[u8] = bytemuck::cast_slice(data);
// wgpu rejects size-0 buffers; the renderer already guards `vertex_count`
// wgpu rejects size-0 buffers; the renderer already guards `instance_count`
// before issuing a draw, so a placeholder allocation is fine here.
let size = bytes.len().max(std::mem::size_of::<WireVertex>()) as u64;
let size = bytes.len().max(std::mem::size_of::<WireInstance>()) as u64;
let buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size,
@@ -55,29 +54,27 @@ fn vertex_buffer_mapped(
buf
}
// ── Vertex layout ─────────────────────────────────────────────────────────
// ── Instance layout ───────────────────────────────────────────────────────
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct WireVertex {
pub struct WireInstance {
pub pos_a: [f32; 3],
pub pos_b: [f32; 3],
pub which_end: f32,
pub side: f32,
pub color: [f32; 4],
pub distance: f32,
pub distance_a: f32,
pub distance_b: f32,
pub half_width: f32,
pub pattern_length: f32,
pub _pad: f32,
pub pat0: [f32; 4],
pub pat1: [f32; 4],
}
impl WireVertex {
impl WireInstance {
pub fn layout<'a>() -> wgpu::VertexBufferLayout<'a> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<WireVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
array_stride: std::mem::size_of::<WireInstance>() as u64,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
@@ -92,41 +89,36 @@ impl WireVertex {
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32,
}, // which_end
wgpu::VertexAttribute {
offset: 28,
shader_location: 3,
format: wgpu::VertexFormat::Float32,
}, // side
wgpu::VertexAttribute {
offset: 32,
shader_location: 4,
format: wgpu::VertexFormat::Float32x4,
}, // color
wgpu::VertexAttribute {
offset: 40,
shader_location: 3,
format: wgpu::VertexFormat::Float32,
}, // distance_a
wgpu::VertexAttribute {
offset: 44,
shader_location: 4,
format: wgpu::VertexFormat::Float32,
}, // distance_b
wgpu::VertexAttribute {
offset: 48,
shader_location: 5,
format: wgpu::VertexFormat::Float32,
}, // distance
}, // half_width
wgpu::VertexAttribute {
offset: 52,
shader_location: 6,
format: wgpu::VertexFormat::Float32,
}, // half_width
}, // pattern_length
wgpu::VertexAttribute {
offset: 56,
shader_location: 7,
format: wgpu::VertexFormat::Float32,
}, // pattern_length
wgpu::VertexAttribute {
offset: 64,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
}, // pat0
wgpu::VertexAttribute {
offset: 80,
shader_location: 9,
offset: 72,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
}, // pat1
],
@@ -137,18 +129,18 @@ impl WireVertex {
// ── GPU handle ────────────────────────────────────────────────────────────
pub struct WireGpu {
pub vertex_buffer: wgpu::Buffer,
pub vertex_count: u32,
pub instance_buffer: wgpu::Buffer,
pub instance_count: u32,
/// Paper-space bbox [x0, y0, x1, y1] for GPU scissor clipping.
/// Set only for viewport-projected wires; None for regular wires.
pub vp_scissor: Option<[f32; 4]>,
}
/// Expand one `WireModel` into its flat vertex stream (6 verts per finite
/// segment). Pulled out so both the single-wire and batched paths share the
/// same emission logic, and so the batched path can `par_iter().flat_map`
/// across wires on cold open.
fn emit_wire_vertices(wire: &WireModel, color: [f32; 4]) -> Vec<WireVertex> {
/// Expand one `WireModel` into its per-segment instance stream (1 instance per
/// finite segment). Pulled out so both the single-wire and batched paths share
/// the same emission logic, and so the batched path can `par_iter` across
/// wires on cold open.
fn emit_wire_instances(wire: &WireModel, color: [f32; 4]) -> Vec<WireInstance> {
let pat0 = [
wire.pattern[0],
wire.pattern[1],
@@ -188,7 +180,7 @@ fn emit_wire_vertices(wire: &WireModel, color: [f32; 4]) -> Vec<WireVertex> {
}
}
let mut vertices: Vec<WireVertex> = Vec::with_capacity(seg_count * 6);
let mut instances: Vec<WireInstance> = Vec::with_capacity(seg_count);
for i in 0..seg_count {
let a = wire.points[i];
let b = wire.points[i + 1];
@@ -201,32 +193,19 @@ fn emit_wire_vertices(wire: &WireModel, color: [f32; 4]) -> Vec<WireVertex> {
{
continue;
}
let dist_a = dists[i];
let dist_b = dists[i + 1];
let make = |which_end: f32, side: f32| -> WireVertex {
let dist = if which_end < 0.5 { dist_a } else { dist_b };
WireVertex {
pos_a: a,
pos_b: b,
which_end,
side,
color,
distance: dist,
half_width,
pattern_length: wire.pattern_length,
_pad: 0.0,
pat0,
pat1,
}
};
vertices.push(make(0.0, -1.0));
vertices.push(make(1.0, -1.0));
vertices.push(make(1.0, 1.0));
vertices.push(make(0.0, -1.0));
vertices.push(make(1.0, 1.0));
vertices.push(make(0.0, 1.0));
instances.push(WireInstance {
pos_a: a,
pos_b: b,
color,
distance_a: dists[i],
distance_b: dists[i + 1],
half_width,
pattern_length: wire.pattern_length,
pat0,
pat1,
});
}
vertices
instances
}
impl WireGpu {
@@ -236,21 +215,23 @@ impl WireGpu {
g
}
/// Merge multiple WireModels into GPU buffers chunked to fit the 256 MB GPU limit.
/// Each wire keeps its own color and pattern — they're stored per-vertex.
/// Returns an empty Vec if the combined vertex list is empty.
/// Merge multiple WireModels into GPU instance buffers, chunked to fit the
/// 256 MB GPU limit. Each wire keeps its own color and pattern — they live
/// per-instance.
pub fn from_batch(device: &wgpu::Device, wires: &[WireModel]) -> Vec<Self> {
let total_segs: usize = wires.iter().map(|w| w.points.len().saturating_sub(1)).sum();
if total_segs == 0 {
return vec![];
}
// Parallel per-wire vertex emission. `flat_map_iter` keeps memory peak
// sane (one Vec<WireVertex> per wire, then concatenated) while letting
// rayon spread CPU work across cores. Ordering is preserved.
let vertices: Vec<WireVertex> = wires
// Parallel per-wire instance emission. Each wire's stream is
// independent — `block_cache` groups wires by style upstream, so order
// within a batch does not affect correctness. `reduce` concatenates the
// per-wire Vec<WireInstance> chunks while letting rayon spread work
// across cores.
let instances: Vec<WireInstance> = wires
.par_iter()
.map(|wire| emit_wire_vertices(wire, wire.color))
.map(|wire| emit_wire_instances(wire, wire.color))
.reduce(Vec::new, |mut acc, mut chunk| {
if acc.is_empty() {
chunk
@@ -262,22 +243,22 @@ impl WireGpu {
}
});
if vertices.is_empty() {
if instances.is_empty() {
return vec![];
}
// GPU max buffer size is 256 MB; chunk to stay within the limit.
const MAX_VERTS: usize = 268_435_456 / std::mem::size_of::<WireVertex>();
const MAX_INSTANCES: usize = 268_435_456 / std::mem::size_of::<WireInstance>();
vertices
.chunks(MAX_VERTS)
instances
.chunks(MAX_INSTANCES)
.enumerate()
.map(|(i, chunk)| {
let label = format!("wire.batch.vbuf.{i}");
let vertex_buffer = vertex_buffer_mapped(device, &label, chunk);
let label = format!("wire.batch.ibuf.{i}");
let instance_buffer = instance_buffer_mapped(device, &label, chunk);
Self {
vertex_buffer,
vertex_count: chunk.len() as u32,
instance_buffer,
instance_count: chunk.len() as u32,
vp_scissor: None,
}
})
@@ -285,15 +266,14 @@ impl WireGpu {
}
fn build(device: &wgpu::Device, wire: &WireModel, color: [f32; 4]) -> Self {
let vertices = emit_wire_vertices(wire, color);
let label = format!("wire.vbuf.{}", wire.name);
let vertex_buffer = vertex_buffer_mapped(device, &label, &vertices);
let instances = emit_wire_instances(wire, color);
let label = format!("wire.ibuf.{}", wire.name);
let instance_buffer = instance_buffer_mapped(device, &label, &instances);
Self {
vertex_buffer,
vertex_count: vertices.len() as u32,
instance_buffer,
instance_count: instances.len() as u32,
vp_scissor: None,
}
}
}
+31 -21
View File
@@ -1,12 +1,15 @@
// Wire shader — renders 1-D CAD entities as screen-aligned quads.
// Topology: TriangleList (6 vertices per segment).
// Topology: TriangleList, 6 vertices drawn per INSTANCE.
//
// Each vertex carries both segment endpoints (pos_a, pos_b) plus which_end
// (0=A, 1=B) and side (±1). The vertex shader expands the quad by half_width
// pixels perpendicular to the segment direction in screen space.
// One instance = one segment. The six vertex IDs map to the corners of a
// two-triangle quad; the vertex shader derives `which_end` (0=A end, 1=B end)
// and `side` (±1 perpendicular) from `@builtin(vertex_index)` and expands the
// quad by `half_width` pixels perpendicular to the segment direction in
// screen space.
//
// Linetype is applied entirely on the GPU:
// • distance = cumulative arc-length from wire start (interpolated by GPU).
// • distance = cumulative arc-length, linearly interpolated from
// (distance_a, distance_b) by `which_end`.
// • pattern_length > 0 enables the dash test; 0 = solid (no discard).
// • pat0/pat1 encode up to 8 elements: positive=dash, negative=gap.
@@ -15,24 +18,23 @@ struct Uniforms {
camera_pos: vec4<f32>,
viewport_size: vec2<f32>,
world_per_pixel: f32,
// LWDISPLAY toggle: 0.0 = force 1 px (half_width 0.5), 1.0 = use per-vertex
// baked half_width. Lets the LWT button switch without retessellating.
// LWDISPLAY toggle: 0.0 = force 1 px (half_width 0.5), 1.0 = use the
// per-instance baked half_width. Lets the LWT button switch without
// retessellating.
lwdisplay_enable: f32,
}
@group(0) @binding(0) var<uniform> u: Uniforms;
struct VertexIn {
struct InstanceIn {
@location(0) pos_a: vec3<f32>,
@location(1) pos_b: vec3<f32>,
@location(2) which_end: f32,
@location(3) side: f32,
@location(4) color: vec4<f32>,
@location(5) distance: f32,
@location(6) half_width: f32,
@location(7) pattern_length: f32,
// location 8 = _pad (not needed in shader)
@location(8) pat0: vec4<f32>,
@location(9) pat1: vec4<f32>,
@location(2) color: vec4<f32>,
@location(3) distance_a: f32,
@location(4) distance_b: f32,
@location(5) half_width: f32,
@location(6) pattern_length: f32,
@location(7) pat0: vec4<f32>,
@location(8) pat1: vec4<f32>,
}
struct VertexOut {
@@ -44,7 +46,15 @@ struct VertexOut {
@location(4) pat1: vec4<f32>,
}
@vertex fn vs_main(in: VertexIn) -> VertexOut {
@vertex fn vs_main(@builtin(vertex_index) vid: u32, in: InstanceIn) -> VertexOut {
// Two-triangle quad corner table:
// vid 0,1,2 = (A,-1) (B,-1) (B,+1)
// vid 3,4,5 = (A,-1) (B,+1) (A,+1)
let which_end_arr = array<f32, 6>(0.0, 1.0, 1.0, 0.0, 1.0, 0.0);
let side_arr = array<f32, 6>(-1.0, -1.0, 1.0, -1.0, 1.0, 1.0);
let which_end = which_end_arr[vid];
let side = side_arr[vid];
let clip_a = u.view_proj * vec4<f32>(in.pos_a, 1.0);
let clip_b = u.view_proj * vec4<f32>(in.pos_b, 1.0);
@@ -71,19 +81,19 @@ struct VertexOut {
let perp_ndc = perp / (u.viewport_size * 0.5);
// Select the clip-space position for this vertex's endpoint.
let clip_pos = mix(clip_a, clip_b, in.which_end);
let clip_pos = mix(clip_a, clip_b, which_end);
// LWDISPLAY off → collapse to a 1-pixel-wide line (half_width = 0.5).
let hw = select(0.5, in.half_width, u.lwdisplay_enable > 0.5);
// Offset in clip space (multiply by w to un-apply perspective division).
let ndc_offset = perp_ndc * hw * in.side;
let ndc_offset = perp_ndc * hw * side;
let final_clip = clip_pos + vec4<f32>(ndc_offset * clip_pos.w, 0.0, 0.0);
var out: VertexOut;
out.clip_pos = final_clip;
out.color = in.color;
out.distance = in.distance;
out.distance = mix(in.distance_a, in.distance_b, which_end);
out.pattern_length = in.pattern_length;
out.pat0 = in.pat0;
out.pat1 = in.pat1;