Skip to main content

render2d/
lib.rs

1// render2d -- the core of the 2D renderer for CAD on lib/gpu (G6a, G6b; docs/RENDER2D.md): a retained scene of
2// entities with stable ids (lines, polylines, arcs and circles; Bézier curves, ellipses and splines flattened per zoom
3// band on the CPU, curve.rs; fills of rings, triangulated on the CPU, fill.rs; blocks inserted many times, their records
4// once on the GPU and each insert an instance with its transform, G6b2), layers and styles (transparency per layer and
5// entity, by block); strokes as quads whose
6// coverage the fragment shader computes from the geometry (no MSAA), with exact butt, square and round caps and miter,
7// bevel and round joins, dash patterns in pixels or drawing units; fills with their edge's exact coverage, every pixel
8// blended once, and hatches from the camera's place in f64; f64 coordinates, a pair of f32 per axis on the GPU with the
9// camera subtracted first; visibility in compute shaders that keep the painter's order and write the indirect draws.  Hosted
10// like render3d as the content of a ui.gpu_view (the app glues it with a GpuContent; lib/ui knows nothing of it).  The
11// same WGSL on every path: compiled ahead (shaders_spv.rs) on Vulkan, handed to the browser as text on WebGPU.
12//
13//   Renderer::new(&device, &RendererDesc) -> Result<Renderer>   the pipelines of one colour format
14//   Scene::new(&renderer) -> Result<Scene>
15//   scene.add_style(&Style) -> StyleId, set_style; add_layer(&Layer) -> LayerId, set_layer, remove_layer
16//   scene.insert(layer, style, &Shape) -> EntityId, update(id, &Shape), set_entity_style(id, style), remove(id)
17//   scene.add_block(&Block) -> BlockId, insert_in(block, style, &Shape); Shape::Insert(Insert) places a block on a
18//        layer or in another block (moved by update, arrays as DXF's MINSERT)
19//   scene.set_camera(&Camera)                                   centre (f64), scale (units per pixel), rotation
20//   dxf::load(&mut scene, &bytes, &dxf::Options) -> Loaded      (G6e2) a DXF drawing into the scene (dxf.rs, dxftext.rs;
21//        the reader is the crate jflib-dxf)
22//   a frame:
23//        scene.prepare(&mut renderer, (w, h))?;         waits for this slot's last frame, uploads what changed
24//        renderer.record(&mut encoder, &scene, color)?;
25//        let id = queue.submit([encoder.finish()?])?;   (or swapchain.present)
26//        scene.submitted(id);
27//
28// Draw order: layers by Layer::order (then by when they were added), within a layer the order of insertion (an update
29// keeps an entity's place); colours are sRGB codes with straight alpha, blended in code space as lib/gfx blends
30// (the target holds codes: a Unorm format such as ui's Bgra8Unorm, no sRGB format).  The camera's y axis points up
31// on the screen.  Errors are gpu's: Invalid for ids and values this crate can judge, the rest from the backend.
32#![no_std]
33#![forbid(unsafe_code)]
34
35extern crate alloc;
36
37use alloc::sync::Arc;
38
39use gpu::*;
40
41mod atlas;
42mod block;
43pub mod curve;
44pub mod dxf;
45mod dxftext;
46pub mod fill;
47mod geo;
48mod index;
49pub mod math;
50pub mod msdf;
51mod scene;
52pub mod text;
53
54pub use scene::{Block, BlockId, Camera, Cap, EntityId, FrameStats, HatchLine, Insert, InstanceInfo, Join, Layer, LayerId, Scene, Shape, Style, StyleId, Transparency, Unit, UploadInfo, ARC_STEP,
55                BLOCK_DEPTH, BY_BLOCK_COLOR, BY_BLOCK_DASH, BY_BLOCK_WIDTH, DASH_MAX, HATCH_DASH_MAX, HATCH_MAX, TRANSPARENCY_MAX};
56// (G6d) picking, area selection, object snaps; highlighting; the overlay
57pub use scene::{box_is_window, Grip, HighlightInfo, Hit, IndexInfo, Overlay, OverlayInfo, Region, SelectMode, Snap, SnapKind, SnapOptions, Space, Target, CROSSING_EDGE, CROSSING_FILL, GRIP_COLD, GRIP_EDGE,
58                GRIP_HOT, GRIP_HOVER, GRIP_PX, HL_ALPHA, HL_HOVER, HL_HOVER_RGB, HL_SELECTED, HL_SELECTED_RGB, MARKER_COLOR, MARKER_PX, MARKER_WIDTH, SNAP_ALL, SNAP_CEN, SNAP_END, SNAP_INS, SNAP_INT,
59                SNAP_MID, SNAP_NEA, SNAP_PER, SNAP_QUA, SNAP_TAN, WINDOW_EDGE, WINDOW_FILL};
60pub use scene::{TextInfo, TEXT_BAR_BELOW, TEXT_FILL_FROM, TEXT_LARGE_FROM};
61// (G6e1) the CPU path: Scene::new_cpu, attach, detach, draw_cpu
62pub use scene::CpuInfo;
63pub use text::{layout_mtext, layout_text, Attach, Bar as TextBar, FontId, FontMetrics, Fonts, GlyphShape, HAlign, Layout as TextLayout, Line as TextLine, MText, Placed as PlacedGlyph, Text, TextStyle, TextStyleId,
64               VAlign, FALLBACK_MAX, LINE_SPACING};
65
66/// the most frames the CPU may record ahead of the GPU
67pub const FRAMES_MAX: usize = 3;
68/// records per page: the unit of the pool's regions and of a workgroup of culling (common.wgsl PAGE)
69pub const PAGE: u32 = 256;
70/// quads per instance of a draw (stroke.wgsl BATCH): the u16 indices of one instance reach 4 * BATCH corners
71pub const BATCH: u32 = 16384;
72/// the most visible layers (stroke.wgsl: first_instance = layer << 16 on Voll)
73pub const LAYERS_MAX: u32 = 65535;
74
75pub(crate) const RECORD_WORDS: usize = 16;
76pub(crate) const RECORD_BYTES: u64 = 64;
77pub(crate) const STYLE_WORDS: usize = 32;
78pub(crate) const STYLE_BYTES: u64 = 128;
79/// a row of the scatter shader: the place, 3 words of padding, the record
80pub(crate) const CHANGE_WORDS: usize = 20;
81pub(crate) const VIEW_BYTES: u64 = 80;
82/// an instance of a block (cull.wgsl Inst, scene.rs inst_words) and its space of a frame (block.wgsl Space)
83pub(crate) const INST_WORDS: usize = 40;
84pub(crate) const INST_BYTES: u64 = 160;
85pub(crate) const SPACE_BYTES: u64 = 80;
86/// an entry of the visibility (cull.wgsl einfo): page, instance + 1, first | count << 16, epx offset
87pub(crate) const ENTRY_BYTES: u64 = 16;
88pub(crate) const WG_INST: u32 = 64;
89/// a hatched style's entry of the hatch table (fill.wgsl Hatch): 32 vec4f
90pub(crate) const HATCH_WORDS: usize = 128;
91pub(crate) const HATCH_BYTES: u64 = 512;
92pub(crate) const DRAW_BYTES: u64 = 20;
93/// timestamps per frame: start, after the uploads, after the visibility, after the draw
94pub(crate) const STAMPS: u32 = 4;
95pub(crate) const WG_SCATTER: u32 = 64;
96
97/// (G6e3) the scatter's changes in one dispatch: as many as its workgroups (of WG_SCATTER) and a storage binding reach, a
98/// piece's bytes a multiple of the binding offsets' alignment (the change buffer is bound per piece)
99fn scatter_chunk(l: &Limits) -> u32 {
100    let bytes = CHANGE_WORDS as u64 * 4;
101    let align = (l.min_storage_offset_alignment as u64).max(1);
102    let mut n = (l.max_compute_workgroups[0] as u64 * WG_SCATTER as u64).min(l.max_storage_binding as u64 / bytes).min(u32::MAX as u64 / 2).max(1);
103    while n > 1 && (n * bytes) % align != 0 {
104        n -= 1;
105    }
106    n as u32
107}
108
109/// the shaders, compiled from the *.wgsl beside this file with common.wgsl in front (render2dtest --test shaders
110/// compares them with what wgsl::compile makes of them, --gen-shaders writes them again); the browser takes the WGSL
111#[cfg(not(target_arch = "wasm32"))]
112mod spv {
113    include!("shaders_spv.rs");
114}
115
116/// the WGSL sources as the device gets them (common.wgsl in front of each, block.wgsl behind it in those that place records;
117/// stroke.wgsl with fs_full from full_body.wgsl, the same body as the function full_body, and fill.wgsl)
118pub const COMMON_WGSL: &str = include_str!("common.wgsl");
119pub const BLOCK_WGSL: &str = include_str!("block.wgsl");
120pub const CULL_WGSL: &str = concat!(include_str!("common.wgsl"), include_str!("block.wgsl"), include_str!("textc.wgsl"), include_str!("cull.wgsl"));
121pub const SCATTER_WGSL: &str = concat!(include_str!("common.wgsl"), include_str!("scatter.wgsl"));
122pub const STROKE_WGSL: &str = concat!(include_str!("common.wgsl"), include_str!("block.wgsl"), include_str!("stroke.wgsl"), "\n@fragment\nfn fs_full(i: VsOut) -> @location(0) vec4f {\n",
123                                      include_str!("full_body.wgsl"), "}\n\nfn full_body(i: VsOut) -> vec4f {\n", include_str!("full_body.wgsl"), "}\n", include_str!("fill.wgsl"));
124/// text (G6c): STROKE_WGSL with textc.wgsl and text.wgsl behind it (vs_text / fs_text for layers of text alone, vs_text_all
125/// / fs_text_all for text among anything else)
126pub const TEXT_WGSL: &str = concat!(include_str!("common.wgsl"), include_str!("block.wgsl"), include_str!("stroke.wgsl"), "\n@fragment\nfn fs_full(i: VsOut) -> @location(0) vec4f {\n",
127                                    include_str!("full_body.wgsl"), "}\n\nfn full_body(i: VsOut) -> vec4f {\n", include_str!("full_body.wgsl"), "}\n", include_str!("fill.wgsl"), include_str!("textc.wgsl"),
128                                    include_str!("text.wgsl"));
129pub const TEXTC_WGSL: &str = include_str!("textc.wgsl");
130/// (G6d) the highlight's look (behind the stroke and text shaders: hl_wgsl) and the write pass with highlights (behind
131/// CULL_WGSL: write_hl_wgsl)
132pub const HL_WGSL: &str = include_str!("hl.wgsl");
133pub const HL_WRITE_WGSL: &str = include_str!("hl_write.wgsl");
134
135/// (G6d) the vertex shaders that read the highlight: STROKE_WGSL or TEXT_WGSL with every visible list's word through
136/// hl_take, ink through hl_ink, half_width through hl_wider, and hl.wgsl behind them (the entries keep their names: vs,
137/// vs_full, vs_fill, vs_text, vs_text_all).  The plain sources and their shaders stay as they are
138pub fn hl_wgsl(base: &str) -> alloc::string::String {
139    let mut s = base.replace("item_of(visible[l.x + j], l.x + j)", "item_of(hl_take(visible[l.x + j]), l.x + j)");
140    s = s.replace("fn ink(color: u32, t: u32, layer_t: u32) -> u32 {",
141                  "fn ink(color: u32, t: u32, layer_t: u32) -> u32 {\n    return hl_ink(ink_own(color, t, layer_t));\n}\n\nfn ink_own(color: u32, t: u32, layer_t: u32) -> u32 {");
142    s = s.replace("fn half_width(st: Style, view: View) -> f32 {",
143                  "fn half_width(st: Style, view: View) -> f32 {\n    return half_width_own(st, view) + hl_wider();\n}\n\nfn half_width_own(st: Style, view: View) -> f32 {");
144    s.push_str(HL_WGSL);
145    s
146}
147
148/// (G6d) CULL_WGSL with the write pass that puts the highlight into the visible list (entry write_hl)
149pub fn write_hl_wgsl() -> alloc::string::String {
150    let mut s = alloc::string::String::from(CULL_WGSL);
151    s.push_str(HL_WRITE_WGSL);
152    s
153}
154#[cfg(not(target_arch = "wasm32"))]
155pub const COUNT_SPV: &[u32] = spv::COUNT;
156#[cfg(not(target_arch = "wasm32"))]
157pub const SCAN_SPV: &[u32] = spv::SCAN;
158#[cfg(not(target_arch = "wasm32"))]
159pub const WRITE_SPV: &[u32] = spv::WRITE;
160#[cfg(not(target_arch = "wasm32"))]
161pub const INSTANCES_SPV: &[u32] = spv::INSTANCES;
162#[cfg(not(target_arch = "wasm32"))]
163pub const SCATTER_SPV: &[u32] = spv::SCATTER;
164#[cfg(not(target_arch = "wasm32"))]
165pub const VS_SPV: &[u32] = spv::VS;
166#[cfg(not(target_arch = "wasm32"))]
167pub const VS_FULL_SPV: &[u32] = spv::VS_FULL;
168#[cfg(not(target_arch = "wasm32"))]
169pub const FS_SPV: &[u32] = spv::FS;
170#[cfg(not(target_arch = "wasm32"))]
171pub const FS_FULL_SPV: &[u32] = spv::FS_FULL;
172#[cfg(not(target_arch = "wasm32"))]
173pub const VS_FILL_SPV: &[u32] = spv::VS_FILL;
174#[cfg(not(target_arch = "wasm32"))]
175pub const FS_FILL_SPV: &[u32] = spv::FS_FILL;
176#[cfg(not(target_arch = "wasm32"))]
177pub const VS_TEXT_SPV: &[u32] = spv::VS_TEXT;
178#[cfg(not(target_arch = "wasm32"))]
179pub const FS_TEXT_SPV: &[u32] = spv::FS_TEXT;
180#[cfg(not(target_arch = "wasm32"))]
181pub const VS_TEXT_ALL_SPV: &[u32] = spv::VS_TEXT_ALL;
182#[cfg(not(target_arch = "wasm32"))]
183pub const FS_TEXT_ALL_SPV: &[u32] = spv::FS_TEXT_ALL;
184/// (G6d) the vertex shaders of hl_wgsl and write_hl
185#[cfg(not(target_arch = "wasm32"))]
186pub const VS_HL_SPV: &[u32] = spv::VS_HL;
187#[cfg(not(target_arch = "wasm32"))]
188pub const VS_FULL_HL_SPV: &[u32] = spv::VS_FULL_HL;
189#[cfg(not(target_arch = "wasm32"))]
190pub const VS_FILL_HL_SPV: &[u32] = spv::VS_FILL_HL;
191#[cfg(not(target_arch = "wasm32"))]
192pub const VS_TEXT_HL_SPV: &[u32] = spv::VS_TEXT_HL;
193#[cfg(not(target_arch = "wasm32"))]
194pub const VS_TEXT_ALL_HL_SPV: &[u32] = spv::VS_TEXT_ALL_HL;
195#[cfg(not(target_arch = "wasm32"))]
196pub const WRITE_HL_SPV: &[u32] = spv::WRITE_HL;
197
198/// Renderer::new.  Made with `new` and changed field by field (it may grow)
199#[derive(Clone, Copy, Debug)]
200#[non_exhaustive]
201pub struct RendererDesc {
202    /// the format of the colour targets: one without sRGB (the codes are blended as they are)
203    pub color: Format,
204    /// frames the CPU may record ahead of the GPU (1 ..= FRAMES_MAX)
205    pub frames_in_flight: usize,
206    /// (G6e3) a render pass of its own, after a barrier, for a run of layers whose fragment shader needs scratch memory
207    /// (fs_full, fs_fill, fs_text_all, the overlay's fs_fill) when the last such run before it took another pipeline: None
208    /// decides by the adapter (on for Intel under Vulkan: Mesa's driver gives such shaders of two draws the same scratch
209    /// memory with their own strides, on Gen9 they overwrote each other's spilled registers; docs/RENDER2D.md "Die anderen
210    /// Ziele (G6e3)"), Some forces it either way.  No pixel changes; on GPUs that draw in tiles each pass costs a store and
211    /// a load of the target
212    pub separate_scratch: Option<bool>,
213}
214
215impl RendererDesc {
216    pub const fn new(color: Format) -> RendererDesc {
217        RendererDesc { color, frames_in_flight: 2, separate_scratch: None }
218    }
219}
220
221/// who a scene belongs to
222pub(crate) struct Tag;
223
224/// the pipelines of one colour format on one device
225pub struct Renderer {
226    pub(crate) dev: Device,
227    pub(crate) desc: RendererDesc,
228    /// level Voll: one multi-draw for all visible layers; else one indirect draw per layer
229    pub(crate) multi: bool,
230    /// (G6e3) RendererDesc::separate_scratch as decided
231    pub(crate) separate: bool,
232    pub(crate) max_records: u32,
233    pub(crate) max_entries: u32,
234    /// (G6e3) the changes one dispatch of the scatter shader reaches: its workgroups and its binding (each piece's offset
235    /// aligned for a storage binding); more in one frame go up in pieces
236    pub(crate) scatter_chunk: u32,
237    pub(crate) tag: Arc<Tag>,
238    count: ComputePipeline,
239    scan: ComputePipeline,
240    write: ComputePipeline,
241    scatter: ComputePipeline,
242    /// the spaces of a frame's instances of blocks (cull.wgsl instances)
243    instances: ComputePipeline,
244    /// solid segments (stroke.wgsl fs), and everything (fs_full: arcs, dash patterns) for the layers that hold arcs or
245    /// dashed strokes; fills and hatches too (fs_fill) for the layers that hold a fill
246    stroke: RenderPipeline,
247    stroke_full: RenderPipeline,
248    /// fills, hatches and everything fs_full draws, for the layers that hold a fill
249    stroke_fill: RenderPipeline,
250    /// text (G6c): layers of text alone (fs_text), text among anything else (fs_text_all: fs_fill's work too)
251    text: RenderPipeline,
252    text_all: RenderPipeline,
253    pub(crate) text_layout: BindGroupLayout,
254    pub(crate) count_layout: BindGroupLayout,
255    pub(crate) scan_layout: BindGroupLayout,
256    pub(crate) write_layout: BindGroupLayout,
257    pub(crate) scatter_layout: BindGroupLayout,
258    pub(crate) inst_layout: BindGroupLayout,
259    pub(crate) draw_layout: BindGroupLayout,
260    /// u16, 0 1 2 2 1 3 per quad, BATCH quads (written once, with the first submission)
261    quads: Buffer,
262    /// (G6d) the pipelines that read the highlight, made with the first scene that highlights something
263    hl: Option<HlPipes>,
264}
265
266/// (G6d) the write pass with highlights and the vertex shaders that read them, with the plain fragment shaders
267struct HlPipes {
268    write: ComputePipeline,
269    pub(crate) write_layout: BindGroupLayout,
270    stroke: RenderPipeline,
271    stroke_full: RenderPipeline,
272    stroke_fill: RenderPipeline,
273    text: RenderPipeline,
274    text_all: RenderPipeline,
275}
276
277/// the highlight's shader modules: the write pass, the vertex shaders, the plain fragment shaders
278struct HlModules {
279    write: ShaderModule,
280    vs: ShaderModule,
281    vs_full: ShaderModule,
282    vs_fill: ShaderModule,
283    vs_text: ShaderModule,
284    vs_text_all: ShaderModule,
285    fs: ShaderModule,
286    fs_full: ShaderModule,
287    fs_fill: ShaderModule,
288    fs_text: ShaderModule,
289    fs_text_all: ShaderModule,
290}
291
292#[cfg(not(target_arch = "wasm32"))]
293fn hl_modules(dev: &Device) -> Result<HlModules> {
294    let m = |w: &[u32]| ShaderModule::from_spirv(dev, w);
295    Ok(HlModules { write: m(WRITE_HL_SPV)?, vs: m(VS_HL_SPV)?, vs_full: m(VS_FULL_HL_SPV)?, vs_fill: m(VS_FILL_HL_SPV)?, vs_text: m(VS_TEXT_HL_SPV)?, vs_text_all: m(VS_TEXT_ALL_HL_SPV)?, fs: m(FS_SPV)?,
296                   fs_full: m(FS_FULL_SPV)?, fs_fill: m(FS_FILL_SPV)?, fs_text: m(FS_TEXT_SPV)?, fs_text_all: m(FS_TEXT_ALL_SPV)? })
297}
298
299#[cfg(target_arch = "wasm32")]
300fn hl_modules(dev: &Device) -> Result<HlModules> {
301    let w = ShaderModule::from_wgsl(dev, &write_hl_wgsl())?;
302    let s = ShaderModule::from_wgsl(dev, &hl_wgsl(STROKE_WGSL))?;
303    let t = ShaderModule::from_wgsl(dev, &hl_wgsl(TEXT_WGSL))?;
304    let fs = ShaderModule::from_wgsl(dev, STROKE_WGSL)?;
305    let ft = ShaderModule::from_wgsl(dev, TEXT_WGSL)?;
306    Ok(HlModules { write: w, vs: s.clone(), vs_full: s.clone(), vs_fill: s, vs_text: t.clone(), vs_text_all: t, fs: fs.clone(), fs_full: fs.clone(), fs_fill: fs, fs_text: ft.clone(), fs_text_all: ft })
307}
308
309struct Modules {
310    count: ShaderModule,
311    scan: ShaderModule,
312    write: ShaderModule,
313    instances: ShaderModule,
314    scatter: ShaderModule,
315    vs: ShaderModule,
316    vs_full: ShaderModule,
317    fs: ShaderModule,
318    fs_full: ShaderModule,
319    vs_fill: ShaderModule,
320    fs_fill: ShaderModule,
321    vs_text: ShaderModule,
322    fs_text: ShaderModule,
323    vs_text_all: ShaderModule,
324    fs_text_all: ShaderModule,
325}
326
327#[cfg(not(target_arch = "wasm32"))]
328fn modules(dev: &Device) -> Result<Modules> {
329    let m = |w: &[u32]| ShaderModule::from_spirv(dev, w);
330    Ok(Modules { count: m(COUNT_SPV)?, scan: m(SCAN_SPV)?, write: m(WRITE_SPV)?, instances: m(INSTANCES_SPV)?, scatter: m(SCATTER_SPV)?, vs: m(VS_SPV)?, vs_full: m(VS_FULL_SPV)?, fs: m(FS_SPV)?,
331                 fs_full: m(FS_FULL_SPV)?, vs_fill: m(VS_FILL_SPV)?, fs_fill: m(FS_FILL_SPV)?, vs_text: m(VS_TEXT_SPV)?, fs_text: m(FS_TEXT_SPV)?, vs_text_all: m(VS_TEXT_ALL_SPV)?,
332                 fs_text_all: m(FS_TEXT_ALL_SPV)? })
333}
334
335#[cfg(target_arch = "wasm32")]
336fn modules(dev: &Device) -> Result<Modules> {
337    let c = ShaderModule::from_wgsl(dev, CULL_WGSL)?;
338    let s = ShaderModule::from_wgsl(dev, STROKE_WGSL)?;
339    let t = ShaderModule::from_wgsl(dev, TEXT_WGSL)?;
340    Ok(Modules { count: c.clone(), scan: c.clone(), write: c.clone(), instances: c, scatter: ShaderModule::from_wgsl(dev, SCATTER_WGSL)?, vs: s.clone(), vs_full: s.clone(), fs: s.clone(),
341                 fs_full: s.clone(), vs_fill: s.clone(), fs_fill: s, vs_text: t.clone(), fs_text: t.clone(), vs_text_all: t.clone(), fs_text_all: t })
342}
343
344impl Renderer {
345    pub fn new(dev: &Device, desc: &RendererDesc) -> Result<Renderer> {
346        if !(1..=FRAMES_MAX).contains(&desc.frames_in_flight) {
347            return Err(GpuError::Invalid("frames_in_flight: 1 ..= 3"));
348        }
349        if desc.color.is_srgb() || desc.color.is_depth() || desc.color.is_compressed() {
350            return Err(GpuError::Invalid("RendererDesc: a colour format without sRGB (render2d blends sRGB codes as they are)"));
351        }
352        let md = modules(dev)?;
353        let b = |binding, kind, stages| Binding { binding, kind, stages };
354        let (cs, vs) = (Stages::COMPUTE, Stages::VERTEX);
355        // (the fragment shader reads the view and the styles: the dash patterns)
356        let vfs = Stages::VERTEX | Stages::FRAGMENT;
357        let (read, rw) = (BindingKind::StorageBufferRead, BindingKind::StorageBuffer);
358        // (cull.wgsl's bindings: each pass names those it uses, none more than 7 storage buffers: WebGPU's least is 8 a stage)
359        // (11: the fill edges' segments in pixels, written by count; 12: the instances' spaces, written by instances, read
360        // by count; 13: the instances' transforms)
361        let count_layout = dev.create_bind_group_layout(&[b(0, BindingKind::UniformBuffer, cs), b(1, read, cs), b(2, read, cs), b(3, read, cs), b(4, rw, cs), b(5, rw, cs), b(11, rw, cs),
362                                                          b(12, rw, cs)])?;
363        let scan_layout = dev.create_bind_group_layout(&[b(5, rw, cs), b(6, read, cs), b(7, rw, cs), b(8, rw, cs), b(9, rw, cs)])?;
364        let write_layout = dev.create_bind_group_layout(&[b(3, read, cs), b(4, rw, cs), b(7, rw, cs), b(10, rw, cs), b(14, rw, cs)])?;
365        let inst_layout = dev.create_bind_group_layout(&[b(0, BindingKind::UniformBuffer, cs), b(12, rw, cs), b(13, read, cs)])?;
366        let scatter_layout = dev.create_bind_group_layout(&[b(0, read, cs), b(1, rw, cs)])?;
367        // (5: the hatch table, 6: the fill edges' segments in pixels; fs_fill reads the pool too; 7: the instance of each visible
368        // record of an insert, 8: the instances' spaces)
369        let draw_layout = dev.create_bind_group_layout(&[b(0, BindingKind::UniformBuffer, vfs), b(1, read, vfs), b(2, read, vfs), b(3, read, vs), b(4, read, vs), b(5, read, Stages::FRAGMENT),
370                                                         b(6, read, vfs), b(7, read, vs), b(8, read, vs)])?;
371        // (G6c: the text pipelines' own layout, the draw's and 9: the atlas, 10: the glyph table; the others keep theirs)
372        let text_layout = dev.create_bind_group_layout(&[b(0, BindingKind::UniformBuffer, vfs), b(1, read, vfs), b(2, read, vfs), b(3, read, vs), b(4, read, vs), b(5, read, Stages::FRAGMENT),
373                                                         b(6, read, vfs), b(7, read, vs), b(8, read, vs), b(9, BindingKind::Texture, Stages::FRAGMENT), b(10, read, vfs)])?;
374        let pl = |g: &BindGroupLayout, push: u32| dev.create_pipeline_layout(&PipelineLayoutDesc { groups: &[g], push_constants: push });
375        // (only scan, scatter and the draw read a push constant; a layout that says more than its pass sets is an error in the browser, where the
376        // values are a bind group)
377        let (count_pl, scan_pl, write_pl, scatter_pl, draw_pl) = (pl(&count_layout, 0)?, pl(&scan_layout, 16)?, pl(&write_layout, 0)?, pl(&scatter_layout, 4)?, pl(&draw_layout, 4)?);
378        let inst_pl = pl(&inst_layout, 16)?;
379        let text_pl = pl(&text_layout, 4)?;
380        let compute = |layout: &PipelineLayout, m: &ShaderModule, entry: &str| dev.create_compute_pipeline(&ComputePipelineDesc { layout, shader: ShaderStage::new(m, entry) });
381        let count = compute(&count_pl, &md.count, "count")?;
382        let scan = compute(&scan_pl, &md.scan, "scan")?;
383        let write = compute(&write_pl, &md.write, "write")?;
384        let scatter = compute(&scatter_pl, &md.scatter, "main")?;
385        let instances = compute(&inst_pl, &md.instances, "instances")?;
386        // premultiplied blending of sRGB codes; no depth (the overlap at joins: stroke.wgsl)
387        let stroke_with = |vs: &ShaderModule, ventry: &str, fs: &ShaderModule, fentry: &str, layout: &PipelineLayout| {
388            dev.create_render_pipeline(&RenderPipelineDesc {
389                layout,
390                vertex: ShaderStage::new(vs, ventry),
391                fragment: Some(ShaderStage::new(fs, fentry)),
392                buffers: &[],
393                topology: Topology::Triangles,
394                cull: Cull::None,
395                front_cw: false,
396                targets: &[ColorTarget { format: desc.color, blend: Some(Blend::PREMULTIPLIED), write_mask: 0xF }],
397                depth: None,
398            })
399        };
400        let stroke = stroke_with(&md.vs, "vs", &md.fs, "fs", &draw_pl)?;
401        let stroke_full = stroke_with(&md.vs_full, "vs_full", &md.fs_full, "fs_full", &draw_pl)?;
402        let stroke_fill = stroke_with(&md.vs_fill, "vs_fill", &md.fs_fill, "fs_fill", &draw_pl)?;
403        let text = stroke_with(&md.vs_text, "vs_text", &md.fs_text, "fs_text", &text_pl)?;
404        let text_all = stroke_with(&md.vs_text_all, "vs_text_all", &md.fs_text_all, "fs_text_all", &text_pl)?;
405        let mut idx = alloc::vec::Vec::with_capacity(BATCH as usize * 6);
406        for q in 0..BATCH {
407            let v = (q * 4) as u16;
408            idx.extend_from_slice(&[v, v + 1, v + 2, v + 2, v + 1, v + 3]);
409        }
410        let quads = dev.create_buffer(&BufferDesc { size: idx.len() as u64 * 2, usage: BufferUsage::INDEX, memory: MemoryKind::Device })?;
411        dev.queue().write_buffer(&quads, 0, &idx)?;
412        let (f, l) = (dev.features(), dev.limits());
413        let multi = dev.level() == Level::Voll && f.multi_draw_indirect && f.draw_indirect_first_instance;
414        // what the bindings and one dispatch reach: the pool and the visible list, a workgroup per page
415        let by_binding = l.max_storage_binding as u64 / RECORD_BYTES;
416        let max_entries = l.max_compute_workgroups[0].min(1 << 24);
417        let by_dispatch = max_entries as u64 * PAGE as u64;
418        // (below 2^29: bits 29 and 30 of a visible list's word carry the highlight, G6d)
419        let max_records = (by_binding / PAGE as u64 * PAGE as u64).min(by_dispatch).min(1 << 29) as u32;
420        let scatter_chunk = scatter_chunk(&l);
421        let info = dev.info();
422        let separate = desc.separate_scratch.unwrap_or(info.vendor_id == 0x8086 && info.backend == "Vulkan");
423        Ok(Renderer {
424            dev: dev.clone(),
425            desc: *desc,
426            multi,
427            separate,
428            max_records,
429            max_entries,
430            scatter_chunk,
431            tag: Arc::new(Tag),
432            count,
433            scan,
434            write,
435            scatter,
436            instances,
437            stroke,
438            stroke_full,
439            stroke_fill,
440            text,
441            text_all,
442            text_layout,
443            count_layout,
444            scan_layout,
445            write_layout,
446            scatter_layout,
447            inst_layout,
448            draw_layout,
449            quads,
450            hl: None,
451        })
452    }
453
454    /// (G6d) the highlight's pipelines, made once (Scene::prepare, when a scene highlights something)
455    pub(crate) fn ensure_hl(&mut self) -> Result<()> {
456        if self.hl.is_some() {
457            return Ok(());
458        }
459        let dev = self.dev.clone();
460        let md = hl_modules(&dev)?;
461        let b = |binding, kind, stages| Binding { binding, kind, stages };
462        let (cs, rw, read) = (Stages::COMPUTE, BindingKind::StorageBuffer, BindingKind::StorageBufferRead);
463        let write_layout = dev.create_bind_group_layout(&[b(3, read, cs), b(4, rw, cs), b(7, rw, cs), b(10, rw, cs), b(14, rw, cs), b(15, read, cs)])?;
464        let write_pl = dev.create_pipeline_layout(&PipelineLayoutDesc { groups: &[&write_layout], push_constants: 0 })?;
465        let write = dev.create_compute_pipeline(&ComputePipelineDesc { layout: &write_pl, shader: ShaderStage::new(&md.write, "write_hl") })?;
466        let draw_pl = dev.create_pipeline_layout(&PipelineLayoutDesc { groups: &[&self.draw_layout], push_constants: 4 })?;
467        let text_pl = dev.create_pipeline_layout(&PipelineLayoutDesc { groups: &[&self.text_layout], push_constants: 4 })?;
468        let color = self.desc.color;
469        let pipe = |vs: &ShaderModule, ventry: &str, fs: &ShaderModule, fentry: &str, layout: &PipelineLayout| {
470            dev.create_render_pipeline(&RenderPipelineDesc {
471                layout,
472                vertex: ShaderStage::new(vs, ventry),
473                fragment: Some(ShaderStage::new(fs, fentry)),
474                buffers: &[],
475                topology: Topology::Triangles,
476                cull: Cull::None,
477                front_cw: false,
478                targets: &[ColorTarget { format: color, blend: Some(Blend::PREMULTIPLIED), write_mask: 0xF }],
479                depth: None,
480            })
481        };
482        self.hl = Some(HlPipes {
483            write,
484            write_layout,
485            stroke: pipe(&md.vs, "vs", &md.fs, "fs", &draw_pl)?,
486            stroke_full: pipe(&md.vs_full, "vs_full", &md.fs_full, "fs_full", &draw_pl)?,
487            stroke_fill: pipe(&md.vs_fill, "vs_fill", &md.fs_fill, "fs_fill", &draw_pl)?,
488            text: pipe(&md.vs_text, "vs_text", &md.fs_text, "fs_text", &text_pl)?,
489            text_all: pipe(&md.vs_text_all, "vs_text_all", &md.fs_text_all, "fs_text_all", &text_pl)?,
490        });
491        Ok(())
492    }
493
494    /// (G6d) the write pass's bind group layout with the highlight (None until the first highlight)
495    pub(crate) fn hl_write_layout(&self) -> Option<&BindGroupLayout> {
496        self.hl.as_ref().map(|h| &h.write_layout)
497    }
498
499    pub fn device(&self) -> &Device {
500        &self.dev
501    }
502
503    pub fn desc(&self) -> &RendererDesc {
504        &self.desc
505    }
506
507    /// this device draws the visible layers with one multi-draw (level Voll)
508    pub fn multi_draw(&self) -> bool {
509        self.multi
510    }
511
512    /// the most records (segments, free places included) a scene's pool can hold on this device
513    pub fn max_records(&self) -> u32 {
514        self.max_records
515    }
516
517    /// one frame of a prepared scene into e: its uploads, its visibility, its render pass (the colour attachment's load
518    /// and clear as it says, sRGB codes)
519    pub fn record<'a>(&'a self, e: &mut CommandEncoder<'a>, s: &'a Scene, color: ColorAttachment<'a>) -> Result<()> {
520        if !s.tag.as_ref().is_some_and(|t| Arc::ptr_eq(t, &self.tag)) {
521            return Err(GpuError::Invalid("record: a scene of another Renderer, or one without a device"));
522        }
523        if !s.prepared {
524            return Err(GpuError::Invalid("record: Scene::prepare comes first"));
525        }
526        if s.stale {
527            return Err(GpuError::Invalid("record: the scene changed after Scene::prepare"));
528        }
529        if color.view.format() != self.desc.color {
530            return Err(GpuError::Invalid("record: the colour target is not in the renderer's format"));
531        }
532        if color.view.size() != s.size {
533            return Err(GpuError::Invalid("record: the colour target is not of the size Scene::prepare was given"));
534        }
535        let g = s.groups.as_ref().ok_or(GpuError::Invalid("record: Scene::prepare comes first"))?;
536        let f = &s.frames[s.slot];
537        let ts = match &s.ts {
538            Some(ts) if s.stats_on => Some(ts),
539            _ => None,
540        };
541        let base = s.slot as u32 * STAMPS;
542        if let Some(ts) = ts {
543            e.reset_timestamps(ts, base, STAMPS);
544            e.timestamp(ts, base);
545        }
546        // the frame before read and wrote everything this one writes: copies, the visibility's buffers, the indirect
547        // draws, the vertex shader's reads
548        e.barrier(Access::COPY_READ | Access::COPY_WRITE | Access::COMPUTE_READ | Access::COMPUTE_WRITE | Access::INDIRECT | Access::INDEX_VERTEX | Access::GRAPHICS_READ,
549                  Access::COPY_READ | Access::COPY_WRITE | Access::COMPUTE_READ | Access::COMPUTE_WRITE);
550        // a new pool: cleared (zeros are free records), then what stays copied over from the old one
551        if let Some((old, moves)) = &s.up.rebuild {
552            e.fill_buffer(&s.pool, 0, s.pool.size(), 0);
553            if !moves.is_empty() {
554                e.barrier(Access::COPY_WRITE, Access::COPY_WRITE);
555                for &(src, dst, size) in moves {
556                    e.copy_buffer(old, src, &s.pool, dst, size);
557                }
558            }
559            // (the records sent below overwrite places of both)
560            e.barrier(Access::COPY_WRITE, Access::COPY_WRITE | Access::COMPUTE_WRITE);
561        }
562        e.copy_buffer(&f.stage, 0, &s.view_ubo, 0, VIEW_BYTES);
563        if let Some((up, size)) = &s.up.styles {
564            e.copy_buffer(up, 0, &s.styles_buf, 0, *size);
565        }
566        // (the hatch table: covered by the same barriers as the styles, the one above against the frame before's fragment
567        // reads, the one below before this frame's)
568        if let Some((up, size)) = &s.up.hatch {
569            e.copy_buffer(up, 0, &s.hatch_buf, 0, *size);
570        }
571        // (G6c: the glyph table's rows, a copy beside the styles under the same two barriers: the one above against the frame
572        // before's vertex and fragment reads, the one below before this frame's)
573        if let Some((up, dst, size)) = &s.up.gtab {
574            e.copy_buffer(up, 0, &s.gtab_buf, *dst, *size);
575        }
576        // (G6c: new tiles of the atlas.  The texture from sampled (the frame before's fragment shaders read it: their reads
577        // finish first) or, new, from nothing to a copy's target, the tiles' rectangles, back to sampled before any shader of
578        // this frame reads it)
579        if let (Some(at), Some(tex)) = (&s.up.atlas, &s.atlas_tex) {
580            e.texture_barrier(tex, if at.fresh { Layout::Undefined } else { Layout::Sampled }, Layout::CopyDst);
581            for c in &at.copies {
582                e.copy_buffer_to_texture(&at.buf, DataLayout { offset: c.offset, bytes_per_row: c.row, rows_per_image: 0 },
583                                         TextureRegion { texture: tex, mip: 0, origin: [c.x, c.y, 0], size: [c.w, c.h, 1], base_layer: c.page, layers: 1 });
584            }
585            e.texture_barrier(tex, Layout::CopyDst, Layout::Sampled);
586        }
587        if let Some((up, order, layers)) = &s.up.tables {
588            if *order > 0 {
589                e.copy_buffer(up, 0, &s.einfo_buf, 0, *order);
590            }
591            if *layers > 0 {
592                e.copy_buffer(up, *order, &s.layers_buf, 0, *layers);
593            }
594        }
595        if let Some((up, runs)) = &s.up.runs {
596            for &(src, dst, size) in runs {
597                e.copy_buffer(up, src, &s.pool, dst, size);
598            }
599        }
600        // (the instances' transforms: under the same two barriers as the records, the one above against the frame before's
601        // instance pass, the one below before this frame's)
602        if let Some((up, runs)) = &s.up.insts {
603            for &(src, dst, size) in runs {
604                e.copy_buffer(up, src, &s.inst_buf, dst, size);
605            }
606        }
607        // (G6d: the highlight mask's changed words, read by write_hl; the overlay's records, styles, lists and fill edges, read
608        // by the vertex and fragment shaders: under the same two barriers as the records, the one above against the frame
609        // before's reads, the one below before this frame's)
610        if let (Some((up, runs)), Some(hb)) = (&s.up.hl, &s.hl.buf) {
611            for &(src, dst, size) in runs {
612                e.copy_buffer(up, src, hb, dst, size);
613            }
614        }
615        if let (Some(ov), Some(g)) = (&s.up.ov, &s.ov_gpu) {
616            for &(src, dst, size) in &ov.copies {
617                let to = match dst {
618                    0 => &g.view,
619                    1 => &g.pool,
620                    2 => &g.styles,
621                    3 => &g.visible,
622                    4 => &g.lists,
623                    _ => &g.epx,
624                };
625                e.copy_buffer(&ov.buf, src, to, 0, size);
626            }
627        }
628        if s.up.scatter > 0 {
629            // (G6e3) in pieces of what one dispatch reaches, each with its binding of the change buffer: one piece on most
630            // desktop GPUs, more on Metal, in the browser and on phones (65 535 workgroups) for millions of records
631            if f.scatter_groups.len() < s.up.scatter.div_ceil(self.scatter_chunk) as usize {
632                return Err(GpuError::Invalid("record: Scene::prepare comes first"));
633            }
634            e.set_compute_pipeline(&self.scatter);
635            let mut left = s.up.scatter;
636            for (k, group) in f.scatter_groups.iter().enumerate() {
637                if left == 0 {
638                    break;
639                }
640                let n = left.min(self.scatter_chunk);
641                if k > 0 {
642                    // (the pieces write other records of the pool; the barrier keeps the validation's view of one buffer
643                    // written by two dispatches quiet)
644                    e.barrier(Access::COMPUTE_WRITE, Access::COMPUTE_WRITE);
645                }
646                e.set_bind_group(0, group);
647                e.push_constants(0, &[n]);
648                e.dispatch(n.div_ceil(WG_SCATTER), 1, 1);
649                left -= n;
650            }
651        }
652        // the uploads (copies, scatter) before the visibility and the vertex shader read them
653        e.barrier(Access::COPY_WRITE | Access::COMPUTE_WRITE, Access::COMPUTE_READ | Access::GRAPHICS_READ);
654        if let Some(ts) = ts {
655            e.timestamp(ts, base + 1);
656        }
657        let layers = s.vis_layers;
658        if layers > 0 {
659            if s.inst_count > 0 {
660                // the instances' spaces of this frame (G6b2), before count reads them (the vertex shader reads them behind
661                // the barrier after write, which takes every compute write before it)
662                e.set_compute_pipeline(&self.instances);
663                e.set_bind_group(0, &g.inst);
664                e.push_constants(0, &[s.inst_count, 0, 0, 0]);
665                e.dispatch(s.inst_count.div_ceil(WG_INST), 1, 1);
666                e.barrier(Access::COMPUTE_WRITE, Access::COMPUTE_READ);
667            }
668            if s.entries > 0 {
669                e.set_compute_pipeline(&self.count);
670                e.set_bind_group(0, &g.count);
671                e.dispatch(s.entries, 1, 1);
672                // the counts and masks before the scan and the write read them
673                e.barrier(Access::COMPUTE_WRITE, Access::COMPUTE_READ);
674            }
675            e.set_compute_pipeline(&self.scan);
676            e.set_bind_group(0, &g.scan);
677            e.push_constants(0, &[s.entries, layers, self.multi as u32, 0]);
678            e.dispatch(1, 1, 1);
679            if s.entries > 0 {
680                // the offsets before the write reads them
681                e.barrier(Access::COMPUTE_WRITE, Access::COMPUTE_READ);
682                // (G6d: with a highlight the write that puts it into the visible list: the same buffers and the mask)
683                match (&self.hl, &s.hl_group, s.hl_on) {
684                    (Some(h), Some(hg), true) => {
685                        e.set_compute_pipeline(&h.write);
686                        e.set_bind_group(0, hg);
687                    }
688                    _ => {
689                        e.set_compute_pipeline(&self.write);
690                        e.set_bind_group(0, &g.write);
691                    }
692                }
693                e.dispatch(s.entries, 1, 1);
694            }
695            // the lists, the draws (scan) and the visible list (write) before the indirect draws and the vertex shader
696            e.barrier(Access::COMPUTE_WRITE, Access::INDIRECT | Access::GRAPHICS_READ | Access::COPY_READ);
697            if let (true, Some(rb)) = (s.stats_on, &f.readback) {
698                e.copy_buffer(&s.lists_buf, 0, rb, 0, layers as u64 * 16);
699            }
700        }
701        if let Some(ts) = ts {
702            e.timestamp(ts, base + 2);
703        }
704        // the runs to draw: (the first layer and how many, or None: the overlay), the pipeline, its bind group, whether its
705        // fragment shader needs scratch memory (fs_full, fs_fill, fs_text_all: they spill on Intel's Gen9)
706        let mut runs: alloc::vec::Vec<(Option<(u32, u32)>, &RenderPipeline, &BindGroup, bool)> = alloc::vec::Vec::new();
707        if layers > 0 {
708            // runs of visible layers that take the same pipeline: those with fills fs_fill, with arcs or dash patterns
709            // fs_full, the others fs; text alone fs_text, text among others fs_text_all (G6c: their own bind group)
710            // (G6d: a layer holding a highlighted entity takes the same class's pipeline with the highlight's vertex shader)
711            let hl = |k: u32| s.hl_on && self.hl.is_some() && s.hl_drawn.get(k as usize).copied().unwrap_or(false);
712            let class = |k: u32| (s.full.get(k as usize).copied().unwrap_or(scene::CLASS_PLAIN), hl(k));
713            let mut k = 0;
714            while k < layers {
715                let mut n = 1;
716                while k + n < layers && class(k + n) == class(k) {
717                    n += 1;
718                }
719                let (cls, lit) = class(k);
720                let (pipe, group) = match (self.hl.as_ref().filter(|_| lit), cls) {
721                    (Some(h), scene::CLASS_TEXT) => (&h.text, g.text.as_ref()),
722                    (Some(h), scene::CLASS_TEXT_ALL) => (&h.text_all, g.text.as_ref()),
723                    (Some(h), scene::CLASS_FILL) => (&h.stroke_fill, Some(&g.draw)),
724                    (Some(h), scene::CLASS_FULL) => (&h.stroke_full, Some(&g.draw)),
725                    (Some(h), _) => (&h.stroke, Some(&g.draw)),
726                    (None, scene::CLASS_TEXT) => (&self.text, g.text.as_ref()),
727                    (None, scene::CLASS_TEXT_ALL) => (&self.text_all, g.text.as_ref()),
728                    (None, scene::CLASS_FILL) => (&self.stroke_fill, Some(&g.draw)),
729                    (None, scene::CLASS_FULL) => (&self.stroke_full, Some(&g.draw)),
730                    (None, _) => (&self.stroke, Some(&g.draw)),
731                };
732                if let Some(group) = group {
733                    runs.push((Some((k, n)), pipe, group, matches!(cls, scene::CLASS_FULL | scene::CLASS_FILL | scene::CLASS_TEXT_ALL)));
734                }
735                k += n;
736            }
737        }
738        // (G6d) the overlay over everything: its own records, one draw of fs_fill (strokes, arcs, dashes, fills)
739        if let (Some(ov), Some(gg)) = (&s.up.ov, &s.ov_gpu) {
740            if let (true, Some(group)) = (ov.quads > 0, &gg.group) {
741                runs.push((None, &self.stroke_fill, group, true));
742            }
743        }
744        // (G6e3) where a pass ends: before a run whose fragment shader needs scratch memory, when the last such run before it
745        // had another pipeline (RendererDesc::separate_scratch; Mesa's Intel driver gives the fragment shaders of both draws
746        // the same scratch memory with their own strides and lets the second start while the first runs: on Gen9 they
747        // overwrote each other's spilled registers, 2 x 2 pixels wrong at random)
748        let mut cut = alloc::vec![false; runs.len()];
749        if self.separate {
750            let mut last: Option<&RenderPipeline> = None;
751            for (c, r) in cut.iter_mut().zip(&runs) {
752                if r.3 {
753                    *c = last.is_some_and(|q| !core::ptr::eq(q, r.1));
754                    last = Some(r.1);
755                }
756            }
757        }
758        let cuts = cut.iter().filter(|&&c| c).count();
759        let first = if cuts > 0 { ColorAttachment { store: true, after: Layout::ColorTarget, ..color } } else { color };
760        e.begin_render(&RenderPassDesc { color: &[first], depth: None });
761        let mut passes = 0;
762        for (r, &c) in runs.iter().zip(&cut) {
763            if c {
764                e.end_render();
765                // (the colour writes of the pass before, done, before this one's: the driver waits for its threads)
766                e.barrier(Access::COLOR_TARGET, Access::COLOR_TARGET);
767                passes += 1;
768                let next = ColorAttachment { load: Load::Keep, before: Layout::ColorTarget, ..color };
769                let next = if passes < cuts { ColorAttachment { store: true, after: Layout::ColorTarget, ..next } } else { next };
770                e.begin_render(&RenderPassDesc { color: &[next], depth: None });
771            }
772            e.set_render_pipeline(r.1);
773            e.set_bind_group(0, r.2);
774            e.set_index_buffer(&self.quads, 0, IndexFormat::U16);
775            match r.0 {
776                Some((k, n)) if self.multi => {
777                    e.push_constants(0, &[0u32]);
778                    e.draw_indexed_indirect_multi(&s.draws_buf, k as u64 * DRAW_BYTES, n, DRAW_BYTES as u32);
779                }
780                Some((k, n)) => {
781                    // WebGPU and Vulkan 1.1: no first instance is sure to work; the layer comes as a push constant
782                    for j in k..k + n {
783                        e.push_constants(0, &[j]);
784                        e.draw_indexed_indirect(&s.draws_buf, j as u64 * DRAW_BYTES);
785                    }
786                }
787                None => {
788                    if let Some(ov) = &s.up.ov {
789                        e.push_constants(0, &[0u32]);
790                        e.draw_indexed(6 * ov.quads.min(BATCH), ov.quads.div_ceil(BATCH), 0, 0, 0);
791                    }
792                }
793            }
794        }
795        e.end_render();
796        if let Some(ts) = ts {
797            e.timestamp(ts, base + 3);
798        }
799        if s.stats_on && layers > 0 {
800            e.barrier(Access::COPY_WRITE, Access::HOST_READ);
801        }
802        Ok(())
803    }
804}