rcus-render 0.1.1

wgpu renderer for rcus: solid quads, a runtime glyph atlas, and scissored text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
mod pipeline;
mod quad;
mod text;

use anyhow::{anyhow, Result};

pub use pipeline::{SolidPipeline, TextPipeline, Viewport};
pub use quad::{Frame, GlyphQuad, Scissor, TextVertex, Vertex};
pub use text::{AtlasSet, GlyphAtlas, TextMetrics};

use quad::intersect;
use rcus_layout::{Color, LayoutTree};
use wgpu::util::DeviceExt;

/// Turns a layout tree into the two vertex batches the GPU consumes. The
/// builder owns the glyph atlases so a host never touches glyph internals.
pub struct FrameBuilder {
    atlases: AtlasSet,
    font: Vec<u8>,
    viewport: Viewport,
    frame: Frame,
    default_color: Color,
}

impl FrameBuilder {
    pub fn new(font: Vec<u8>) -> Self {
        Self {
            atlases: AtlasSet::new(),
            font,
            viewport: Viewport {
                width: 1.0,
                height: 1.0,
            },
            frame: Frame::new(),
            default_color: Color::rgba(0.85, 0.87, 0.92, 1.0),
        }
    }

    pub fn with_default_color(mut self, color: Color) -> Self {
        self.default_color = color;
        self
    }

    /// Resolves the atlas layer for a pixel size, creating it on first use.
    pub fn layer(&mut self, font_size: f32) -> &mut GlyphAtlas {
        let index = self
            .atlases
            .layer(font_size, true, &self.font)
            .expect("embedded font must parse");
        self.atlases.get_mut(index)
    }

    /// Glyph atlases, so a renderer can upload them after shaping.
    pub fn atlases(&self) -> &AtlasSet {
        &self.atlases
    }

    /// True when new glyphs or layers were rasterized since the last frame.
    pub fn take_dirty_atlas(&mut self) -> bool {
        self.atlases.take_dirty()
    }

    pub fn build(&mut self, tree: &LayoutTree) {
        self.viewport = Viewport {
            width: tree.viewport.width,
            height: tree.viewport.height,
        };
        let mut frame = quad::build_quads(tree);
        self.emit_text(tree, &mut frame);
        self.frame = frame;
    }

    /// Walks the tree in paint order, shaping text and inheriting clip rects.
    fn emit_text(&mut self, tree: &LayoutTree, frame: &mut Frame) {
        self.emit_text_node(&tree.root, None, frame);
    }

    fn emit_text_node(
        &mut self,
        node: &rcus_layout::LayoutNode,
        inherited: Option<rcus_layout::Rect>,
        frame: &mut Frame,
    ) {
        let clip = if node.clip {
            let rect = match inherited {
                Some(parent) => intersect(parent, node.rect),
                None => node.rect,
            };
            if rect.width <= 0.0 || rect.height <= 0.0 {
                return;
            }
            Some(rect)
        } else {
            inherited
        };
        if let Some(text) = node.text.as_deref() {
            self.emit_text_run(node, text, clip, frame);
        }
        for child in &node.children {
            self.emit_text_node(child, clip, frame);
        }
    }

    fn emit_text_run(
        &mut self,
        node: &rcus_layout::LayoutNode,
        text: &str,
        clip: Option<rcus_layout::Rect>,
        frame: &mut Frame,
    ) {
        if node.rect.width <= 0.0 || node.rect.height <= 0.0 || text.is_empty() {
            return;
        }
        if let Some(clip) = clip {
            if clip.right() <= node.rect.x || clip.bottom() <= node.rect.y {
                return;
            }
        }
        let layer = match self.atlases.layer(node.font_size, true, &self.font) {
            Ok(index) => index,
            Err(_) => return,
        };
        let color = node.color.unwrap_or(self.default_color);
        let rgba = [color.r, color.g, color.b, color.a];
        let width_limit = match clip {
            Some(clip) => (clip.right() - node.rect.x).max(0.0),
            None => node.rect.width,
        };
        let atlas = self.atlases.get_mut(layer);
        let fitted = atlas.ellipsize(text, width_limit);
        let baseline = node.rect.y + (node.rect.height - node.font_size) / 2.0 + atlas.ascent();
        let scissor = clip.filter(|clip| {
            !(clip.x <= node.rect.x
                && clip.y <= node.rect.y
                && clip.right() >= node.rect.right()
                && clip.bottom() >= node.rect.bottom())
        });
        let scissor_index = scissor.map(|clip| {
            frame.scissors.push(Scissor {
                x: clip.x,
                y: clip.y,
                width: clip.width,
                height: clip.height,
            });
            (frame.scissors.len() - 1) as u16
        });
        let mut glyphs = Vec::with_capacity(fitted.chars().count() * 6);
        self.atlases
            .get_mut(layer)
            .shape(&mut glyphs, &fitted, node.rect.x, baseline, rgba, layer);
        let start = frame.glyphs.len();
        frame.glyphs.extend_from_slice(&glyphs);
        for _ in start..frame.glyphs.len() {
            frame.glyph_scissors.push(scissor_index);
        }
    }

    pub fn frame(&self) -> &Frame {
        &self.frame
    }

    pub fn viewport(&self) -> Viewport {
        self.viewport
    }
}

/// Draws frames with a solid pass followed by one textured text pass.
pub struct Renderer {
    device: wgpu::Device,
    queue: wgpu::Queue,
    format: wgpu::TextureFormat,
    solid: SolidPipeline,
    text: TextPipeline,
    quad_buffer: wgpu::Buffer,
    quad_capacity: usize,
    glyph_buffer: wgpu::Buffer,
    glyph_capacity: usize,
    /// Device pixels per logical pixel, used to scale scissor rectangles.
    scale_factor: f32,
    /// The window surface, attached once the window exists.
    surface: Option<wgpu::Surface<'static>>,
    config: Option<wgpu::SurfaceConfiguration>,
}

impl Renderer {
    pub fn new(
        device: wgpu::Device,
        queue: wgpu::Queue,
        format: wgpu::TextureFormat,
        atlases: &AtlasSet,
        scale_factor: f32,
    ) -> Result<Self> {
        let solid = SolidPipeline::new(&device, format)?;
        let mut text = TextPipeline::new(&device, &queue, format)?;
        text.sync_atlas(&device, &queue, atlases);
        let quad_buffer = empty_buffer(&device, 4096, "rcus-quad-buffer");
        let glyph_buffer = empty_buffer(&device, 65536, "rcus-glyph-buffer");
        Ok(Self {
            device,
            queue,
            format,
            solid,
            text,
            quad_buffer,
            quad_capacity: 4096,
            glyph_buffer,
            glyph_capacity: 65536,
            scale_factor: scale_factor.max(1.0),
            surface: None,
            config: None,
        })
    }

    /// Updates the device pixel ratio after a monitor or window change.
    pub fn set_scale_factor(&mut self, scale_factor: f32) {
        self.scale_factor = scale_factor.max(1.0);
    }

    /// Attaches a window surface and configures the swapchain for it.
    pub fn attach_surface(
        &mut self,
        surface: wgpu::Surface<'static>,
        config: wgpu::SurfaceConfiguration,
    ) {
        surface.configure(&self.device, &config);
        self.config = Some(config);
        self.surface = Some(surface);
    }

    /// Reconfigures the swapchain after a window resize.
    pub fn resize(&mut self, width: u32, height: u32) {
        if let Some(config) = self.config.as_mut() {
            config.width = width.max(1);
            config.height = height.max(1);
        }
        self.reconfigure();
    }

    /// Reconfigures the swapchain after the surface is lost or outdated.
    fn reconfigure(&mut self) {
        let Some(config) = self.config.clone() else {
            return;
        };
        if let Some(surface) = self.surface.as_ref() {
            surface.configure(&self.device, &config);
        }
    }

    pub fn format(&self) -> wgpu::TextureFormat {
        self.format
    }

    /// Re-uploads the glyph atlas after new characters were rasterized.
    pub fn upload_atlas(&mut self, atlases: &AtlasSet) {
        self.text.sync_atlas(&self.device, &self.queue, atlases);
    }

    fn write_quads(&mut self, vertices: &[Vertex]) {
        let bytes = bytemuck::cast_slice(vertices);
        if bytes.len() > self.quad_capacity {
            self.quad_capacity = bytes.len().next_power_of_two();
            self.quad_buffer = self
                .device
                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("rcus-quad-buffer"),
                    contents: bytes,
                    usage: wgpu::BufferUsages::VERTEX,
                });
            return;
        }
        self.queue.write_buffer(&self.quad_buffer, 0, bytes);
    }

    fn write_glyphs(&mut self, vertices: &[TextVertex]) {
        let bytes = bytemuck::cast_slice(vertices);
        if bytes.len() > self.glyph_capacity {
            self.glyph_capacity = bytes.len().next_power_of_two();
            self.glyph_buffer = self
                .device
                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("rcus-glyph-buffer"),
                    contents: bytes,
                    usage: wgpu::BufferUsages::VERTEX,
                });
            return;
        }
        self.queue.write_buffer(&self.glyph_buffer, 0, bytes);
    }

    /// Draws one frame to the attached surface and presents it.
    pub fn render(&mut self, frame: &Frame, viewport: Viewport) -> Result<()> {
        let acquired = match self.surface.as_ref() {
            Some(surface) => surface.get_current_texture(),
            None => return Ok(()),
        };
        let target = match acquired {
            Ok(texture) => texture,
            Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
                self.reconfigure();
                return Ok(());
            }
            Err(wgpu::SurfaceError::OutOfMemory) => return Err(anyhow!("swapchain out of memory")),
            Err(error) => return Err(anyhow!("swapchain error: {error:?}")),
        };
        let view = target
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default());
        self.draw(frame, viewport, &view)?;
        target.present();
        Ok(())
    }

    fn draw(
        &mut self,
        frame: &Frame,
        viewport: Viewport,
        target: &wgpu::TextureView,
    ) -> Result<()> {
        if frame.is_empty() {
            return Ok(());
        }
        self.text
            .set_viewport(&self.queue, viewport.width, viewport.height);
        if !frame.quads.is_empty() {
            self.write_quads(&frame.quads);
        }
        if !frame.glyphs.is_empty() {
            self.write_glyphs(&frame.glyphs);
        }
        let scale = self.scale_factor;
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("rcus-encoder"),
            });
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("rcus-pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: target,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color {
                            r: 0.02,
                            g: 0.02,
                            b: 0.03,
                            a: 1.0,
                        }),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
            });
            let width = viewport.width.max(1.0) as u32;
            let height = viewport.height.max(1.0) as u32;
            // Both passes group vertices into runs of identical clip rectangles,
            // so a clipped panel costs one extra draw instead of a scissor
            // change per rectangle.
            if !frame.quads.is_empty() {
                pass.set_pipeline(&self.solid.pipeline);
                pass.set_vertex_buffer(0, self.quad_buffer.slice(..));
                draw_runs(frame.quads.len(), &frame.quad_scissors, |run, scissor| {
                    apply_scissor(&mut pass, frame, scissor, scale, width, height);
                    pass.draw(run.0 as u32..run.1 as u32, 0..1);
                });
            }
            if !frame.glyphs.is_empty() {
                pass.set_pipeline(&self.text.pipeline);
                pass.set_bind_group(0, &self.text.bind_group, &[]);
                pass.set_vertex_buffer(0, self.glyph_buffer.slice(..));
                draw_runs(frame.glyphs.len(), &frame.glyph_scissors, |run, scissor| {
                    apply_scissor(&mut pass, frame, scissor, scale, width, height);
                    pass.draw(run.0 as u32..run.1 as u32, 0..1);
                });
            }
        }
        self.queue.submit([encoder.finish()]);
        Ok(())
    }
}

/// Calls `draw` once per run of vertices that share a clip rectangle.
fn draw_runs(
    vertices: usize,
    scissors: &[Option<u16>],
    mut draw: impl FnMut((usize, usize), Option<u16>),
) {
    let mut run_start = 0usize;
    let mut run_scissor = scissors.first().copied().flatten();
    for index in 0..=vertices {
        let scissor = scissors.get(index).copied().flatten();
        if index == vertices || scissor != run_scissor {
            if index > run_start {
                draw((run_start, index), run_scissor);
            }
            run_start = index;
            run_scissor = scissor;
        }
    }
}

fn apply_scissor(
    pass: &mut wgpu::RenderPass<'_>,
    frame: &Frame,
    index: Option<u16>,
    scale: f32,
    width: u32,
    height: u32,
) {
    let (x, y, w, h) = match index.and_then(|index| frame.scissors.get(index as usize)) {
        Some(scissor) => (
            (scissor.x * scale).floor().max(0.0) as u32,
            (scissor.y * scale).floor().max(0.0) as u32,
            (scissor.width * scale).ceil().max(0.0) as u32,
            (scissor.height * scale).ceil().max(0.0) as u32,
        ),
        None => (0, 0, width, height),
    };
    pass.set_scissor_rect(
        x.min(width.saturating_sub(1)),
        y.min(height.saturating_sub(1)),
        w.clamp(1, width),
        h.clamp(1, height),
    );
}

fn empty_buffer(device: &wgpu::Device, size: usize, label: &str) -> wgpu::Buffer {
    device.create_buffer(&wgpu::BufferDescriptor {
        label: Some(label),
        size: size as u64,
        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    })
}