1mod pipeline;
2mod quad;
3mod text;
4
5use anyhow::{anyhow, Result};
6
7pub use pipeline::{SolidPipeline, TextPipeline, Viewport};
8pub use quad::{Frame, GlyphQuad, Scissor, TextVertex, Vertex};
9pub use text::{AtlasSet, GlyphAtlas, TextMetrics};
10
11use quad::intersect;
12use rcus_layout::{Color, LayoutTree};
13use wgpu::util::DeviceExt;
14
15pub 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 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 pub fn atlases(&self) -> &AtlasSet {
55 &self.atlases
56 }
57
58 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 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
167pub struct Renderer {
169 device: wgpu::Device,
170 queue: wgpu::Queue,
171 format: wgpu::TextureFormat,
172 solid: SolidPipeline,
173 text: TextPipeline,
174 quad_buffer: wgpu::Buffer,
175 quad_capacity: usize,
176 glyph_buffer: wgpu::Buffer,
177 glyph_capacity: usize,
178 scale_factor: f32,
180 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 let quad_buffer = empty_buffer(&device, 4096, "rcus-quad-buffer");
197 let glyph_buffer = empty_buffer(&device, 65536, "rcus-glyph-buffer");
198 Ok(Self {
199 device,
200 queue,
201 format,
202 solid,
203 text,
204 quad_buffer,
205 quad_capacity: 4096,
206 glyph_buffer,
207 glyph_capacity: 65536,
208 scale_factor: scale_factor.max(1.0),
209 surface: None,
210 config: None,
211 })
212 }
213
214 pub fn set_scale_factor(&mut self, scale_factor: f32) {
216 self.scale_factor = scale_factor.max(1.0);
217 }
218
219 pub fn attach_surface(
221 &mut self,
222 surface: wgpu::Surface<'static>,
223 config: wgpu::SurfaceConfiguration,
224 ) {
225 surface.configure(&self.device, &config);
226 self.config = Some(config);
227 self.surface = Some(surface);
228 }
229
230 pub fn resize(&mut self, width: u32, height: u32) {
232 if let Some(config) = self.config.as_mut() {
233 config.width = width.max(1);
234 config.height = height.max(1);
235 }
236 self.reconfigure();
237 }
238
239 fn reconfigure(&mut self) {
241 let Some(config) = self.config.clone() else {
242 return;
243 };
244 if let Some(surface) = self.surface.as_ref() {
245 surface.configure(&self.device, &config);
246 }
247 }
248
249 pub fn format(&self) -> wgpu::TextureFormat {
250 self.format
251 }
252
253 pub fn upload_atlas(&mut self, atlases: &AtlasSet) {
255 self.text.sync_atlas(&self.device, &self.queue, atlases);
256 }
257
258 fn write_quads(&mut self, vertices: &[Vertex]) {
259 let bytes = bytemuck::cast_slice(vertices);
260 if bytes.len() > self.quad_capacity {
261 self.quad_capacity = bytes.len().next_power_of_two();
262 self.quad_buffer = self
263 .device
264 .create_buffer_init(&wgpu::util::BufferInitDescriptor {
265 label: Some("rcus-quad-buffer"),
266 contents: bytes,
267 usage: wgpu::BufferUsages::VERTEX,
268 });
269 return;
270 }
271 self.queue.write_buffer(&self.quad_buffer, 0, bytes);
272 }
273
274 fn write_glyphs(&mut self, vertices: &[TextVertex]) {
275 let bytes = bytemuck::cast_slice(vertices);
276 if bytes.len() > self.glyph_capacity {
277 self.glyph_capacity = bytes.len().next_power_of_two();
278 self.glyph_buffer = self
279 .device
280 .create_buffer_init(&wgpu::util::BufferInitDescriptor {
281 label: Some("rcus-glyph-buffer"),
282 contents: bytes,
283 usage: wgpu::BufferUsages::VERTEX,
284 });
285 return;
286 }
287 self.queue.write_buffer(&self.glyph_buffer, 0, bytes);
288 }
289
290 pub fn render(&mut self, frame: &Frame, viewport: Viewport) -> Result<()> {
292 let acquired = match self.surface.as_ref() {
293 Some(surface) => surface.get_current_texture(),
294 None => return Ok(()),
295 };
296 let target = match acquired {
297 Ok(texture) => texture,
298 Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
299 self.reconfigure();
300 return Ok(());
301 }
302 Err(wgpu::SurfaceError::OutOfMemory) => return Err(anyhow!("swapchain out of memory")),
303 Err(error) => return Err(anyhow!("swapchain error: {error:?}")),
304 };
305 let view = target
306 .texture
307 .create_view(&wgpu::TextureViewDescriptor::default());
308 self.draw(frame, viewport, &view)?;
309 target.present();
310 Ok(())
311 }
312
313 pub fn snapshot_png(
325 &mut self,
326 frame: &Frame,
327 viewport: Viewport,
328 width: u32,
329 height: u32,
330 ) -> Result<Vec<u8>> {
331 let width = width.max(1);
332 let height = height.max(1);
333 let texture = self.device.create_texture(&wgpu::TextureDescriptor {
334 label: Some("rcus-snapshot"),
335 size: wgpu::Extent3d {
336 width,
337 height,
338 depth_or_array_layers: 1,
339 },
340 mip_level_count: 1,
341 sample_count: 1,
342 dimension: wgpu::TextureDimension::D2,
343 format: wgpu::TextureFormat::Rgba8Unorm,
344 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
345 view_formats: &[],
346 });
347 let target = texture.create_view(&wgpu::TextureViewDescriptor::default());
348 self.draw(frame, viewport, &target)?;
349 let pixels = self.read_texture(&texture, width, height)?;
350 let image = image::RgbaImage::from_raw(width, height, pixels)
351 .ok_or_else(|| anyhow!("snapshot of {width}x{height} did not decode"))?;
352 let mut bytes = Vec::new();
355 image
356 .write_to(
357 &mut std::io::Cursor::new(&mut bytes),
358 image::ImageFormat::Png,
359 )
360 .map_err(|error| anyhow!("png encode: {error}"))?;
361 Ok(bytes)
362 }
363
364 fn read_texture(&self, texture: &wgpu::Texture, width: u32, height: u32) -> Result<Vec<u8>> {
367 const ALIGNMENT: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
368 let padded = width.div_ceil(ALIGNMENT) * ALIGNMENT;
369 let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
370 label: Some("rcus-snapshot-readback"),
371 size: u64::from(padded) * u64::from(height),
372 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
373 mapped_at_creation: false,
374 });
375 let mut encoder = self
376 .device
377 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
378 label: Some("rcus-snapshot-copy"),
379 });
380 encoder.copy_texture_to_buffer(
381 texture.as_image_copy(),
382 wgpu::ImageCopyBuffer {
383 buffer: &buffer,
384 layout: wgpu::ImageDataLayout {
385 offset: 0,
386 bytes_per_row: Some(padded),
387 rows_per_image: Some(height),
388 },
389 },
390 wgpu::Extent3d {
391 width,
392 height,
393 depth_or_array_layers: 1,
394 },
395 );
396 self.queue.submit([encoder.finish()]);
397 let slice = buffer.slice(..);
398 let (sender, receiver) = std::sync::mpsc::channel();
399 slice.map_async(wgpu::MapMode::Read, move |result| {
400 let _ = sender.send(result);
401 });
402 self.device.poll(wgpu::Maintain::Wait);
406 receiver
407 .recv()
408 .map_err(|_| anyhow!("the readback channel closed"))?
409 .map_err(|error| anyhow!("mapping the readback: {error}"))?;
410 let mapped = slice.get_mapped_range();
411 let mut pixels = Vec::with_capacity((width * height * 4) as usize);
412 for row in mapped.chunks(padded as usize) {
413 pixels.extend_from_slice(&row[..width as usize * 4]);
414 }
415 drop(mapped);
416 buffer.unmap();
417 Ok(pixels)
418 }
419
420 fn draw(
421 &mut self,
422 frame: &Frame,
423 viewport: Viewport,
424 target: &wgpu::TextureView,
425 ) -> Result<()> {
426 if frame.is_empty() {
427 return Ok(());
428 }
429 self.text
430 .set_viewport(&self.queue, viewport.width, viewport.height);
431 if !frame.quads.is_empty() {
432 self.write_quads(&frame.quads);
433 }
434 if !frame.glyphs.is_empty() {
435 self.write_glyphs(&frame.glyphs);
436 }
437 let scale = self.scale_factor;
438 let mut encoder = self
439 .device
440 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
441 label: Some("rcus-encoder"),
442 });
443 {
444 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
445 label: Some("rcus-pass"),
446 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
447 view: target,
448 resolve_target: None,
449 ops: wgpu::Operations {
450 load: wgpu::LoadOp::Clear(wgpu::Color {
451 r: 0.02,
452 g: 0.02,
453 b: 0.03,
454 a: 1.0,
455 }),
456 store: wgpu::StoreOp::Store,
457 },
458 })],
459 depth_stencil_attachment: None,
460 timestamp_writes: None,
461 occlusion_query_set: None,
462 });
463 let width = viewport.width.max(1.0) as u32;
464 let height = viewport.height.max(1.0) as u32;
465 if !frame.quads.is_empty() {
469 pass.set_pipeline(&self.solid.pipeline);
470 pass.set_vertex_buffer(0, self.quad_buffer.slice(..));
471 draw_runs(frame.quads.len(), &frame.quad_scissors, |run, scissor| {
472 apply_scissor(&mut pass, frame, scissor, scale, width, height);
473 pass.draw(run.0 as u32..run.1 as u32, 0..1);
474 });
475 }
476 if !frame.glyphs.is_empty() {
477 pass.set_pipeline(&self.text.pipeline);
478 pass.set_bind_group(0, &self.text.bind_group, &[]);
479 pass.set_vertex_buffer(0, self.glyph_buffer.slice(..));
480 draw_runs(frame.glyphs.len(), &frame.glyph_scissors, |run, scissor| {
481 apply_scissor(&mut pass, frame, scissor, scale, width, height);
482 pass.draw(run.0 as u32..run.1 as u32, 0..1);
483 });
484 }
485 }
486 self.queue.submit([encoder.finish()]);
487 Ok(())
488 }
489}
490
491fn draw_runs(
493 vertices: usize,
494 scissors: &[Option<u16>],
495 mut draw: impl FnMut((usize, usize), Option<u16>),
496) {
497 let mut run_start = 0usize;
498 let mut run_scissor = scissors.first().copied().flatten();
499 for index in 0..=vertices {
500 let scissor = scissors.get(index).copied().flatten();
501 if index == vertices || scissor != run_scissor {
502 if index > run_start {
503 draw((run_start, index), run_scissor);
504 }
505 run_start = index;
506 run_scissor = scissor;
507 }
508 }
509}
510
511fn apply_scissor(
512 pass: &mut wgpu::RenderPass<'_>,
513 frame: &Frame,
514 index: Option<u16>,
515 scale: f32,
516 width: u32,
517 height: u32,
518) {
519 let (x, y, w, h) = match index.and_then(|index| frame.scissors.get(index as usize)) {
520 Some(scissor) => (
521 (scissor.x * scale).floor().max(0.0) as u32,
522 (scissor.y * scale).floor().max(0.0) as u32,
523 (scissor.width * scale).ceil().max(0.0) as u32,
524 (scissor.height * scale).ceil().max(0.0) as u32,
525 ),
526 None => (0, 0, width, height),
527 };
528 pass.set_scissor_rect(
529 x.min(width.saturating_sub(1)),
530 y.min(height.saturating_sub(1)),
531 w.clamp(1, width),
532 h.clamp(1, height),
533 );
534}
535
536fn empty_buffer(device: &wgpu::Device, size: usize, label: &str) -> wgpu::Buffer {
537 device.create_buffer(&wgpu::BufferDescriptor {
538 label: Some(label),
539 size: size as u64,
540 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
541 mapped_at_creation: false,
542 })
543}