Skip to main content

rcus_render/
lib.rs

1mod pipeline;
2mod quad;
3mod text;
4
5use anyhow::{anyhow, Result};
6
7pub use pipeline::{SolidPipeline, TextPipeline, Viewport};
8pub use quad::{BoxStyle, BoxVertex, Frame, GlyphQuad, Scissor, TextVertex};
9pub use text::{AtlasSet, GlyphAtlas, TextMetrics};
10
11use quad::intersect;
12use rcus_layout::{Color, LayoutTree};
13use wgpu::util::DeviceExt;
14
15/// Turns a layout tree into the two vertex batches the GPU consumes. The
16/// builder owns the glyph atlases so a host never touches glyph internals.
17pub struct FrameBuilder {
18    atlases: AtlasSet,
19    font: Vec<u8>,
20    viewport: Viewport,
21    frame: Frame,
22    default_color: Color,
23}
24
25impl FrameBuilder {
26    pub fn new(font: Vec<u8>) -> Self {
27        Self {
28            atlases: AtlasSet::new(),
29            font,
30            viewport: Viewport {
31                width: 1.0,
32                height: 1.0,
33            },
34            frame: Frame::new(),
35            default_color: Color::rgba(0.85, 0.87, 0.92, 1.0),
36        }
37    }
38
39    pub fn with_default_color(mut self, color: Color) -> Self {
40        self.default_color = color;
41        self
42    }
43
44    /// Resolves the atlas layer for a pixel size, creating it on first use.
45    pub fn layer(&mut self, font_size: f32) -> &mut GlyphAtlas {
46        let index = self
47            .atlases
48            .layer(font_size, true, &self.font)
49            .expect("embedded font must parse");
50        self.atlases.get_mut(index)
51    }
52
53    /// Glyph atlases, so a renderer can upload them after shaping.
54    pub fn atlases(&self) -> &AtlasSet {
55        &self.atlases
56    }
57
58    /// True when new glyphs or layers were rasterized since the last frame.
59    pub fn take_dirty_atlas(&mut self) -> bool {
60        self.atlases.take_dirty()
61    }
62
63    pub fn build(&mut self, tree: &LayoutTree) {
64        self.viewport = Viewport {
65            width: tree.viewport.width,
66            height: tree.viewport.height,
67        };
68        let mut frame = quad::build_quads(tree);
69        self.emit_text(tree, &mut frame);
70        self.frame = frame;
71    }
72
73    /// Walks the tree in paint order, shaping text and inheriting clip rects.
74    fn emit_text(&mut self, tree: &LayoutTree, frame: &mut Frame) {
75        self.emit_text_node(&tree.root, None, frame);
76    }
77
78    fn emit_text_node(
79        &mut self,
80        node: &rcus_layout::LayoutNode,
81        inherited: Option<rcus_layout::Rect>,
82        frame: &mut Frame,
83    ) {
84        let clip = if node.clip {
85            let rect = match inherited {
86                Some(parent) => intersect(parent, node.rect),
87                None => node.rect,
88            };
89            if rect.width <= 0.0 || rect.height <= 0.0 {
90                return;
91            }
92            Some(rect)
93        } else {
94            inherited
95        };
96        if let Some(text) = node.text.as_deref() {
97            self.emit_text_run(node, text, clip, frame);
98        }
99        for child in &node.children {
100            self.emit_text_node(child, clip, frame);
101        }
102    }
103
104    fn emit_text_run(
105        &mut self,
106        node: &rcus_layout::LayoutNode,
107        text: &str,
108        clip: Option<rcus_layout::Rect>,
109        frame: &mut Frame,
110    ) {
111        if node.rect.width <= 0.0 || node.rect.height <= 0.0 || text.is_empty() {
112            return;
113        }
114        if let Some(clip) = clip {
115            if clip.right() <= node.rect.x || clip.bottom() <= node.rect.y {
116                return;
117            }
118        }
119        let layer = match self.atlases.layer(node.font_size, true, &self.font) {
120            Ok(index) => index,
121            Err(_) => return,
122        };
123        let color = node.color.unwrap_or(self.default_color);
124        let rgba = [color.r, color.g, color.b, color.a];
125        let width_limit = match clip {
126            Some(clip) => (clip.right() - node.rect.x).max(0.0),
127            None => node.rect.width,
128        };
129        let atlas = self.atlases.get_mut(layer);
130        let fitted = atlas.ellipsize(text, width_limit);
131        let baseline = node.rect.y + (node.rect.height - node.font_size) / 2.0 + atlas.ascent();
132        let scissor = clip.filter(|clip| {
133            !(clip.x <= node.rect.x
134                && clip.y <= node.rect.y
135                && clip.right() >= node.rect.right()
136                && clip.bottom() >= node.rect.bottom())
137        });
138        let scissor_index = scissor.map(|clip| {
139            frame.scissors.push(Scissor {
140                x: clip.x,
141                y: clip.y,
142                width: clip.width,
143                height: clip.height,
144            });
145            (frame.scissors.len() - 1) as u16
146        });
147        let mut glyphs = Vec::with_capacity(fitted.chars().count() * 6);
148        self.atlases
149            .get_mut(layer)
150            .shape(&mut glyphs, &fitted, node.rect.x, baseline, rgba, layer);
151        let start = frame.glyphs.len();
152        frame.glyphs.extend_from_slice(&glyphs);
153        for _ in start..frame.glyphs.len() {
154            frame.glyph_scissors.push(scissor_index);
155        }
156    }
157
158    pub fn frame(&self) -> &Frame {
159        &self.frame
160    }
161
162    pub fn viewport(&self) -> Viewport {
163        self.viewport
164    }
165}
166
167/// Draws frames with a solid pass followed by one textured text pass.
168pub struct Renderer {
169    device: wgpu::Device,
170    queue: wgpu::Queue,
171    format: wgpu::TextureFormat,
172    solid: SolidPipeline,
173    text: TextPipeline,
174    box_buffer: wgpu::Buffer,
175    box_capacity: usize,
176    glyph_buffer: wgpu::Buffer,
177    glyph_capacity: usize,
178    /// Device pixels per logical pixel, used to scale scissor rectangles.
179    scale_factor: f32,
180    /// The window surface, attached once the window exists.
181    surface: Option<wgpu::Surface<'static>>,
182    config: Option<wgpu::SurfaceConfiguration>,
183}
184
185impl Renderer {
186    pub fn new(
187        device: wgpu::Device,
188        queue: wgpu::Queue,
189        format: wgpu::TextureFormat,
190        atlases: &AtlasSet,
191        scale_factor: f32,
192    ) -> Result<Self> {
193        let solid = SolidPipeline::new(&device, format)?;
194        let mut text = TextPipeline::new(&device, &queue, format)?;
195        text.sync_atlas(&device, &queue, atlases);
196        // A box is six vertices of 96 bytes; 256 boxes is a frame with room to spare.
197        const INITIAL_BOXES: usize = 256;
198        let box_buffer = empty_buffer(
199            &device,
200            std::mem::size_of::<BoxVertex>() * 6 * INITIAL_BOXES,
201            "rcus-box-buffer",
202        );
203        let glyph_buffer = empty_buffer(&device, 65536, "rcus-glyph-buffer");
204        Ok(Self {
205            device,
206            queue,
207            format,
208            solid,
209            text,
210            box_buffer,
211            box_capacity: std::mem::size_of::<BoxVertex>() * 6 * INITIAL_BOXES,
212            glyph_buffer,
213            glyph_capacity: 65536,
214            scale_factor: scale_factor.max(1.0),
215            surface: None,
216            config: None,
217        })
218    }
219
220    /// Updates the device pixel ratio after a monitor or window change.
221    pub fn set_scale_factor(&mut self, scale_factor: f32) {
222        self.scale_factor = scale_factor.max(1.0);
223    }
224
225    /// Attaches a window surface and configures the swapchain for it.
226    pub fn attach_surface(
227        &mut self,
228        surface: wgpu::Surface<'static>,
229        config: wgpu::SurfaceConfiguration,
230    ) {
231        surface.configure(&self.device, &config);
232        self.config = Some(config);
233        self.surface = Some(surface);
234    }
235
236    /// Reconfigures the swapchain after a window resize.
237    pub fn resize(&mut self, width: u32, height: u32) {
238        if let Some(config) = self.config.as_mut() {
239            config.width = width.max(1);
240            config.height = height.max(1);
241        }
242        self.reconfigure();
243    }
244
245    /// Reconfigures the swapchain after the surface is lost or outdated.
246    fn reconfigure(&mut self) {
247        let Some(config) = self.config.clone() else {
248            return;
249        };
250        if let Some(surface) = self.surface.as_ref() {
251            surface.configure(&self.device, &config);
252        }
253    }
254
255    pub fn format(&self) -> wgpu::TextureFormat {
256        self.format
257    }
258
259    /// Re-uploads the glyph atlas after new characters were rasterized.
260    pub fn upload_atlas(&mut self, atlases: &AtlasSet) {
261        self.text.sync_atlas(&self.device, &self.queue, atlases);
262    }
263
264    fn write_boxes(&mut self, vertices: &[BoxVertex]) {
265        let bytes = bytemuck::cast_slice(vertices);
266        let needed = bytes.len();
267        if needed > self.box_capacity {
268            self.box_capacity = needed.next_power_of_two();
269            self.box_buffer = self
270                .device
271                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
272                    label: Some("rcus-box-buffer"),
273                    contents: bytes,
274                    usage: wgpu::BufferUsages::VERTEX,
275                });
276            return;
277        }
278        self.queue.write_buffer(&self.box_buffer, 0, bytes);
279    }
280
281    fn write_glyphs(&mut self, vertices: &[TextVertex]) {
282        let bytes = bytemuck::cast_slice(vertices);
283        if bytes.len() > self.glyph_capacity {
284            self.glyph_capacity = bytes.len().next_power_of_two();
285            self.glyph_buffer = self
286                .device
287                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
288                    label: Some("rcus-glyph-buffer"),
289                    contents: bytes,
290                    usage: wgpu::BufferUsages::VERTEX,
291                });
292            return;
293        }
294        self.queue.write_buffer(&self.glyph_buffer, 0, bytes);
295    }
296
297    /// Draws one frame to the attached surface and presents it.
298    pub fn render(&mut self, frame: &Frame, viewport: Viewport) -> Result<()> {
299        let acquired = match self.surface.as_ref() {
300            Some(surface) => surface.get_current_texture(),
301            None => return Ok(()),
302        };
303        let target = match acquired {
304            Ok(texture) => texture,
305            Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
306                self.reconfigure();
307                return Ok(());
308            }
309            Err(wgpu::SurfaceError::OutOfMemory) => return Err(anyhow!("swapchain out of memory")),
310            Err(error) => return Err(anyhow!("swapchain error: {error:?}")),
311        };
312        let view = target
313            .texture
314            .create_view(&wgpu::TextureViewDescriptor::default());
315        self.draw(frame, viewport, &view)?;
316        target.present();
317        Ok(())
318    }
319
320    /// Draws one frame into a texture the caller owns, and hands back the
321    /// pixels as PNG bytes.
322    ///
323    /// A window presents a swapchain image, so `render` is all it needs. A
324    /// snapshot has nowhere to present: a doc image, a CI job, or a test on a
325    /// machine with no display. This runs the same pipelines against the same
326    /// frame, so what comes back is what the window would have shown.
327    ///
328    /// `width` and `height` are the image size in device pixels; the viewport
329    /// is in logical pixels and is scaled by the device pixel ratio the
330    /// renderer was built with.
331    pub fn snapshot_png(
332        &mut self,
333        frame: &Frame,
334        viewport: Viewport,
335        width: u32,
336        height: u32,
337    ) -> Result<Vec<u8>> {
338        let width = width.max(1);
339        let height = height.max(1);
340        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
341            label: Some("rcus-snapshot"),
342            size: wgpu::Extent3d {
343                width,
344                height,
345                depth_or_array_layers: 1,
346            },
347            mip_level_count: 1,
348            sample_count: 1,
349            dimension: wgpu::TextureDimension::D2,
350            format: wgpu::TextureFormat::Rgba8Unorm,
351            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
352            view_formats: &[],
353        });
354        let target = texture.create_view(&wgpu::TextureViewDescriptor::default());
355        self.draw(frame, viewport, &target)?;
356        let pixels = self.read_texture(&texture, width, height)?;
357        let image = image::RgbaImage::from_raw(width, height, pixels)
358            .ok_or_else(|| anyhow!("snapshot of {width}x{height} did not decode"))?;
359        // The texture is the device's orientation, top row first, which is what
360        // an image wants as well; no flip is needed.
361        let mut bytes = Vec::new();
362        image
363            .write_to(
364                &mut std::io::Cursor::new(&mut bytes),
365                image::ImageFormat::Png,
366            )
367            .map_err(|error| anyhow!("png encode: {error}"))?;
368        Ok(bytes)
369    }
370
371    /// Copies a texture back to the CPU, padding each row to the alignment
372    /// `copy_texture_to_buffer` requires and trimming it again afterwards.
373    fn read_texture(&self, texture: &wgpu::Texture, width: u32, height: u32) -> Result<Vec<u8>> {
374        const ALIGNMENT: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
375        // The alignment is in bytes, not pixels: a row is four bytes per pixel,
376        // and the copy is rejected unless the stride covers the whole row.
377        let row_bytes = width * 4;
378        let padded = row_bytes.div_ceil(ALIGNMENT) * ALIGNMENT;
379        let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
380            label: Some("rcus-snapshot-readback"),
381            size: u64::from(padded) * u64::from(height),
382            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
383            mapped_at_creation: false,
384        });
385        let mut encoder = self
386            .device
387            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
388                label: Some("rcus-snapshot-copy"),
389            });
390        encoder.copy_texture_to_buffer(
391            texture.as_image_copy(),
392            wgpu::ImageCopyBuffer {
393                buffer: &buffer,
394                layout: wgpu::ImageDataLayout {
395                    offset: 0,
396                    bytes_per_row: Some(padded),
397                    rows_per_image: Some(height),
398                },
399            },
400            wgpu::Extent3d {
401                width,
402                height,
403                depth_or_array_layers: 1,
404            },
405        );
406        self.queue.submit([encoder.finish()]);
407        let slice = buffer.slice(..);
408        let (sender, receiver) = std::sync::mpsc::channel();
409        slice.map_async(wgpu::MapMode::Read, move |result| {
410            let _ = sender.send(result);
411        });
412        // `Maintain::Wait` blocks until the copy has run and the mapping
413        // callback has fired, which is the only way to read a texture back
414        // without spinning on the queue.
415        self.device.poll(wgpu::Maintain::Wait);
416        receiver
417            .recv()
418            .map_err(|_| anyhow!("the readback channel closed"))?
419            .map_err(|error| anyhow!("mapping the readback: {error}"))?;
420        let mapped = slice.get_mapped_range();
421        let mut pixels = Vec::with_capacity((row_bytes * height) as usize);
422        for row in mapped.chunks(padded as usize) {
423            pixels.extend_from_slice(&row[..row_bytes as usize]);
424        }
425        drop(mapped);
426        buffer.unmap();
427        Ok(pixels)
428    }
429
430    fn draw(
431        &mut self,
432        frame: &Frame,
433        viewport: Viewport,
434        target: &wgpu::TextureView,
435    ) -> Result<()> {
436        if frame.is_empty() {
437            return Ok(());
438        }
439        self.text
440            .set_viewport(&self.queue, viewport.width, viewport.height);
441        if !frame.boxes.is_empty() {
442            self.write_boxes(&frame.boxes);
443        }
444        if !frame.glyphs.is_empty() {
445            self.write_glyphs(&frame.glyphs);
446        }
447        let scale = self.scale_factor;
448        let mut encoder = self
449            .device
450            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
451                label: Some("rcus-encoder"),
452            });
453        {
454            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
455                label: Some("rcus-pass"),
456                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
457                    view: target,
458                    resolve_target: None,
459                    ops: wgpu::Operations {
460                        load: wgpu::LoadOp::Clear(wgpu::Color {
461                            r: 0.02,
462                            g: 0.02,
463                            b: 0.03,
464                            a: 1.0,
465                        }),
466                        store: wgpu::StoreOp::Store,
467                    },
468                })],
469                depth_stencil_attachment: None,
470                timestamp_writes: None,
471                occlusion_query_set: None,
472            });
473            let width = viewport.width.max(1.0) as u32;
474            let height = viewport.height.max(1.0) as u32;
475            // Both passes group vertices into runs of identical clip rectangles,
476            // so a clipped panel costs one extra draw instead of a scissor
477            // change per rectangle.
478            if !frame.boxes.is_empty() {
479                pass.set_pipeline(&self.solid.pipeline);
480                pass.set_vertex_buffer(0, self.box_buffer.slice(..));
481                draw_runs(frame.boxes.len(), &frame.box_scissors, |run, scissor| {
482                    apply_scissor(&mut pass, frame, scissor, scale, width, height);
483                    pass.draw(run.0 as u32..run.1 as u32, 0..1);
484                });
485            }
486            if !frame.glyphs.is_empty() {
487                pass.set_pipeline(&self.text.pipeline);
488                pass.set_bind_group(0, &self.text.bind_group, &[]);
489                pass.set_vertex_buffer(0, self.glyph_buffer.slice(..));
490                draw_runs(frame.glyphs.len(), &frame.glyph_scissors, |run, scissor| {
491                    apply_scissor(&mut pass, frame, scissor, scale, width, height);
492                    pass.draw(run.0 as u32..run.1 as u32, 0..1);
493                });
494            }
495        }
496        self.queue.submit([encoder.finish()]);
497        Ok(())
498    }
499}
500
501/// Calls `draw` once per run of vertices that share a clip rectangle.
502fn draw_runs(
503    vertices: usize,
504    scissors: &[Option<u16>],
505    mut draw: impl FnMut((usize, usize), Option<u16>),
506) {
507    let mut run_start = 0usize;
508    let mut run_scissor = scissors.first().copied().flatten();
509    for index in 0..=vertices {
510        let scissor = scissors.get(index).copied().flatten();
511        if index == vertices || scissor != run_scissor {
512            if index > run_start {
513                draw((run_start, index), run_scissor);
514            }
515            run_start = index;
516            run_scissor = scissor;
517        }
518    }
519}
520
521fn apply_scissor(
522    pass: &mut wgpu::RenderPass<'_>,
523    frame: &Frame,
524    index: Option<u16>,
525    scale: f32,
526    width: u32,
527    height: u32,
528) {
529    let (x, y, w, h) = match index.and_then(|index| frame.scissors.get(index as usize)) {
530        Some(scissor) => (
531            (scissor.x * scale).floor().max(0.0) as u32,
532            (scissor.y * scale).floor().max(0.0) as u32,
533            (scissor.width * scale).ceil().max(0.0) as u32,
534            (scissor.height * scale).ceil().max(0.0) as u32,
535        ),
536        None => (0, 0, width, height),
537    };
538    pass.set_scissor_rect(
539        x.min(width.saturating_sub(1)),
540        y.min(height.saturating_sub(1)),
541        w.clamp(1, width),
542        h.clamp(1, height),
543    );
544}
545
546fn empty_buffer(device: &wgpu::Device, size: usize, label: &str) -> wgpu::Buffer {
547    device.create_buffer(&wgpu::BufferDescriptor {
548        label: Some(label),
549        size: size as u64,
550        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
551        mapped_at_creation: false,
552    })
553}