Skip to main content

cadkit_gpu/
plan.rs

1//! Renderer for [`cadkit_scene::PlanFrame`] chunks.
2
3use std::collections::HashMap;
4use std::ops::Range;
5
6use cadkit_scene::ChunkDraw;
7use cadkit_scene::layout::INSTANCE_BYTES;
8
9/// A chunk buffer not drawn for this many prepared frames is released.
10const EVICT_FRAMES: u64 = 600;
11/// Per-chunk uniform: origin, scale, pixels per point and viewport as eight f32.
12const UNIFORM_BYTES: u64 = 32;
13/// Prepared frames kept per renderer; several canvases may share one renderer.
14const KEEP_PREPARED: u64 = 16;
15
16/// Where a frame is drawn, in physical pixels of the render target.
17#[derive(Debug, Clone, Copy, PartialEq)]
18#[non_exhaustive]
19pub struct PlanTarget {
20    /// Canvas center, in physical pixels (y down). Chunk offsets are added to it in f64.
21    pub center_px: [f64; 2],
22    /// Physical pixels per logical pixel; stroke widths are logical.
23    pub pixels_per_point: f32,
24    /// Viewport of the draw: left, top, width and height in physical pixels.
25    pub viewport_px: [f32; 4],
26}
27
28impl PlanTarget {
29    /// A target whose canvas fills `viewport_px` (left, top, width, height).
30    pub fn new(viewport_px: [f32; 4], pixels_per_point: f32) -> Self {
31        let [left, top, width, height] = viewport_px;
32        Self {
33            center_px: [
34                f64::from(left) + f64::from(width) / 2.,
35                f64::from(top) + f64::from(height) / 2.,
36            ],
37            pixels_per_point,
38            viewport_px,
39        }
40    }
41
42    /// Sets [`Self::center_px`].
43    #[must_use]
44    pub fn with_center_px(mut self, center_px: [f64; 2]) -> Self {
45        self.center_px = center_px;
46        self
47    }
48}
49
50struct GpuChunk {
51    generation: u64,
52    buffer: wgpu::Buffer,
53    used: u64,
54}
55
56struct Prepared {
57    bind_group: wgpu::BindGroup,
58    /// Chunk slot, dynamic uniform offset and instance ranges.
59    draws: Vec<(u64, u32, Vec<Range<u32>>)>,
60}
61
62/// Draws [`ChunkDraw`]s; see the [crate documentation](crate).
63///
64/// Uploads happen in [`Self::prepare`]; [`Self::paint`] only records draw calls, so it can
65/// run inside a render pass that a UI toolkit owns.
66pub struct PlanRenderer {
67    pipeline: wgpu::RenderPipeline,
68    layout: wgpu::BindGroupLayout,
69    stride: u64,
70    chunks: HashMap<u64, GpuChunk>,
71    frame: u64,
72    prepared: HashMap<u64, Prepared>,
73}
74
75impl PlanRenderer {
76    /// Creates the pipeline for color targets of `format`, single-sampled, blending
77    /// premultiplied alpha.
78    pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
79        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
80            label: Some("cadkit plan shader"),
81            source: wgpu::ShaderSource::Wgsl(include_str!("plan.wgsl").into()),
82        });
83        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
84            label: Some("cadkit plan chunk"),
85            entries: &[wgpu::BindGroupLayoutEntry {
86                binding: 0,
87                visibility: wgpu::ShaderStages::VERTEX,
88                ty: wgpu::BindingType::Buffer {
89                    ty: wgpu::BufferBindingType::Uniform,
90                    has_dynamic_offset: true,
91                    min_binding_size: wgpu::BufferSize::new(UNIFORM_BYTES),
92                },
93                count: None,
94            }],
95        });
96        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
97            label: Some("cadkit plan pipeline"),
98            bind_group_layouts: &[Some(&layout)],
99            immediate_size: 0,
100        });
101        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
102            label: Some("cadkit plan"),
103            layout: Some(&pipeline_layout),
104            vertex: wgpu::VertexState {
105                module: &shader,
106                entry_point: Some("vs_main"),
107                compilation_options: Default::default(),
108                buffers: &[Some(wgpu::VertexBufferLayout {
109                    array_stride: INSTANCE_BYTES as u64,
110                    step_mode: wgpu::VertexStepMode::Instance,
111                    attributes: &wgpu::vertex_attr_array![
112                        0 => Float32x2,
113                        1 => Float32x2,
114                        2 => Uint32x2,
115                        3 => Unorm8x4,
116                        4 => Float32,
117                        5 => Uint32,
118                    ],
119                })],
120            },
121            primitive: wgpu::PrimitiveState {
122                cull_mode: None,
123                ..Default::default()
124            },
125            depth_stencil: None,
126            multisample: Default::default(),
127            fragment: Some(wgpu::FragmentState {
128                module: &shader,
129                entry_point: Some("fs_main"),
130                compilation_options: Default::default(),
131                targets: &[Some(wgpu::ColorTargetState {
132                    format,
133                    blend: Some(wgpu::BlendState {
134                        color: wgpu::BlendComponent {
135                            src_factor: wgpu::BlendFactor::One,
136                            dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
137                            operation: wgpu::BlendOperation::Add,
138                        },
139                        alpha: wgpu::BlendComponent {
140                            src_factor: wgpu::BlendFactor::OneMinusDstAlpha,
141                            dst_factor: wgpu::BlendFactor::One,
142                            operation: wgpu::BlendOperation::Add,
143                        },
144                    }),
145                    write_mask: wgpu::ColorWrites::ALL,
146                })],
147            }),
148            multiview_mask: None,
149            cache: None,
150        });
151        let alignment = u64::from(device.limits().min_uniform_buffer_offset_alignment);
152        Self {
153            pipeline,
154            layout,
155            stride: UNIFORM_BYTES.div_ceil(alignment) * alignment,
156            chunks: HashMap::new(),
157            frame: 0,
158            prepared: HashMap::new(),
159        }
160    }
161
162    /// Releases every chunk buffer and prepared frame; the pipeline stays.
163    pub fn clear(&mut self) {
164        self.chunks.clear();
165        self.prepared.clear();
166    }
167
168    /// Number of chunk buffers currently held.
169    pub fn chunk_buffers(&self) -> usize {
170        self.chunks.len()
171    }
172
173    /// Uploads changed chunks and the per-chunk positions of `draws` and stores them under
174    /// `id`, which [`Self::paint`] takes. Use a new, increasing `id` per painted canvas and
175    /// frame; the last 16 are kept. Chunk buffers not drawn for 600 prepared frames are
176    /// released.
177    pub fn prepare(
178        &mut self,
179        device: &wgpu::Device,
180        queue: &wgpu::Queue,
181        id: u64,
182        draws: &[ChunkDraw],
183        target: PlanTarget,
184    ) {
185        self.frame += 1;
186        let frame = self.frame;
187        let stride = usize::try_from(self.stride).unwrap_or(usize::MAX);
188        let mut uniforms = vec![0u8; draws.len().max(1).saturating_mul(stride)];
189        let mut prepared = Vec::with_capacity(draws.len());
190        for (index, draw) in draws.iter().enumerate() {
191            let fresh = self
192                .chunks
193                .get(&draw.slot)
194                .is_some_and(|chunk| chunk.generation == draw.generation);
195            if !fresh {
196                let size = draw.bytes.len() as u64;
197                match self.chunks.get_mut(&draw.slot) {
198                    Some(chunk) if chunk.buffer.size() >= size => {
199                        queue.write_buffer(&chunk.buffer, 0, &draw.bytes);
200                        chunk.generation = draw.generation;
201                    }
202                    _ => {
203                        let buffer = device.create_buffer(&wgpu::BufferDescriptor {
204                            label: Some("cadkit plan chunk instances"),
205                            // Headroom so a growing chunk is not reallocated on every edit.
206                            size: (size + size / 4).next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT),
207                            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
208                            mapped_at_creation: false,
209                        });
210                        queue.write_buffer(&buffer, 0, &draw.bytes);
211                        self.chunks.insert(
212                            draw.slot,
213                            GpuChunk {
214                                generation: draw.generation,
215                                buffer,
216                                used: frame,
217                            },
218                        );
219                    }
220                }
221            }
222            if let Some(chunk) = self.chunks.get_mut(&draw.slot) {
223                chunk.used = frame;
224            }
225            let [left, top, width, height] = target.viewport_px;
226            let values = [
227                (draw.offset[0] + target.center_px[0]) as f32,
228                (draw.offset[1] + target.center_px[1]) as f32,
229                draw.scale as f32,
230                target.pixels_per_point,
231                left,
232                top,
233                width,
234                height,
235            ];
236            let base = index.saturating_mul(stride);
237            if let Some(slot) = uniforms.get_mut(base..base.saturating_add(32)) {
238                for (bytes, value) in slot.as_chunks_mut::<4>().0.iter_mut().zip(values) {
239                    *bytes = value.to_le_bytes();
240                }
241            }
242            prepared.push((
243                draw.slot,
244                u32::try_from(index as u64 * self.stride).unwrap_or(u32::MAX),
245                draw.ranges.clone(),
246            ));
247        }
248        self.chunks
249            .retain(|_, chunk| frame.saturating_sub(chunk.used) < EVICT_FRAMES);
250        let buffer = device.create_buffer(&wgpu::BufferDescriptor {
251            label: Some("cadkit plan chunk positions"),
252            size: uniforms.len() as u64,
253            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
254            mapped_at_creation: false,
255        });
256        queue.write_buffer(&buffer, 0, &uniforms);
257        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
258            label: Some("cadkit plan chunk positions"),
259            layout: &self.layout,
260            entries: &[wgpu::BindGroupEntry {
261                binding: 0,
262                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
263                    buffer: &buffer,
264                    offset: 0,
265                    size: wgpu::BufferSize::new(UNIFORM_BYTES),
266                }),
267            }],
268        });
269        self.prepared
270            .retain(|other, _| id.saturating_sub(*other) < KEEP_PREPARED);
271        self.prepared.insert(
272            id,
273            Prepared {
274                bind_group,
275                draws: prepared,
276            },
277        );
278    }
279
280    /// Records the draws prepared under `id`; nothing when there are none.
281    pub fn paint(&self, pass: &mut wgpu::RenderPass<'_>, id: u64) {
282        let Some(prepared) = self.prepared.get(&id) else {
283            return;
284        };
285        pass.set_pipeline(&self.pipeline);
286        for (slot, offset, ranges) in &prepared.draws {
287            let Some(chunk) = self.chunks.get(slot) else {
288                continue;
289            };
290            pass.set_bind_group(0, &prepared.bind_group, &[*offset]);
291            pass.set_vertex_buffer(0, chunk.buffer.slice(..));
292            for range in ranges {
293                pass.draw(0..6, range.clone());
294            }
295        }
296    }
297}