Skip to main content

euv_core/render/software/
struct.rs

1use super::*;
2
3/// Single disjoint horizontal framebuffer strip dispatched to a persistent rasterization worker thread.
4#[cfg(not(target_arch = "wasm32"))]
5#[derive(Clone, Copy, Data, Debug, Default)]
6pub(crate) struct BandTaskSlice {
7    /// Raw mutable pixel buffer base address encoded as `usize` for `Send` transfer.
8    #[get(type(copy))]
9    pub(crate) pixels_ptr: usize,
10    /// Byte length of the disjoint horizontal pixel strip.
11    #[get(type(copy))]
12    pub(crate) pixels_len: usize,
13    /// Full framebuffer physical width in pixels.
14    #[get(type(copy))]
15    pub(crate) width: u32,
16    /// Inclusive top physical Y row of this strip.
17    #[get(type(copy))]
18    pub(crate) y_start: u32,
19    /// Number of physical rows inside this strip.
20    #[get(type(copy))]
21    pub(crate) height: u32,
22    /// Optional raw source pointer for parallel base-scene backdrop restore (`0` when unused).
23    #[get(type(copy))]
24    pub(crate) base_src_ptr: usize,
25    /// Horizontal byte offset within each row where backdrop restore starts.
26    #[get(type(copy))]
27    pub(crate) restore_x0_bytes: usize,
28    /// Horizontal byte length restored per row (`width * 4` for full-width contiguous restore).
29    #[get(type(copy))]
30    pub(crate) restore_row_bytes: usize,
31}
32
33/// Optional base-scene backdrop restore and fused full-viewport scrim LUT specification for band dispatch.
34#[derive(Clone, Copy, Debug, Default)]
35pub(crate) struct BandRestoreSpec<'a> {
36    /// Cached full-framebuffer RGBA8 base scene pixels, if restoring backdrop.
37    pub(crate) base_pixels: Option<&'a [u8]>,
38    /// Inclusive physical start X column to restore on each row.
39    pub(crate) x0: u32,
40    /// Exclusive physical end X column to restore on each row.
41    pub(crate) x1: u32,
42    /// Optional prebuilt 256-entry linear-light scrim LUT fused into backdrop restore.
43    pub(crate) scrim_luts: Option<&'a [[u8; 256]; 4]>,
44}
45
46/// Read-only auxiliary frame slices passed to band rasterizers (glyphs, caret rects, rounded clips, and cached corner masks).
47#[derive(Clone, Copy)]
48pub(crate) struct BandAuxSlices<'a> {
49    /// Pre-positioned glyph instances for the active frame.
50    pub(crate) positioned_glyphs: &'a [PositionedGlyph],
51    /// Pre-measured caret bounding rectangles for the active frame.
52    pub(crate) caret_rects: &'a [Rect],
53    /// Active rounded clip masks for the frame.
54    pub(crate) rounded_clips: &'a [RoundedClipMask],
55    /// Cached quadrant corner anti-aliasing masks.
56    pub(crate) corner_masks: &'a [CachedCornerMask],
57}
58
59/// Precomputed 1D horizontal edge pixel sample reused across every vertical interior scanline of a rounded rectangle.
60#[derive(Clone, Copy, Debug, Default)]
61pub(crate) struct EdgeBlendSample {
62    /// Physical X pixel coordinate inside the target scanline.
63    pub(crate) x: u32,
64    /// Direct RGBA8 bytes written verbatim when `is_opaque` is true.
65    pub(crate) rgba: [u8; 4],
66    /// Pre-multiplied linear red channel `SRGB_TO_LIN_LUT[r] * alpha`.
67    pub(crate) sr_a: f32,
68    /// Pre-multiplied linear green channel `SRGB_TO_LIN_LUT[g] * alpha`.
69    pub(crate) sg_a: f32,
70    /// Pre-multiplied linear blue channel `SRGB_TO_LIN_LUT[b] * alpha`.
71    pub(crate) sb_a: f32,
72    /// Complement opacity `1.0 - alpha`.
73    pub(crate) inv_a: f32,
74    /// Quantized source alpha in `0..=255` for destination alpha update.
75    pub(crate) sa_u32: u32,
76    /// True when the sample overwrites destination pixels without blending.
77    pub(crate) is_opaque: bool,
78}
79
80/// Precomputed per-row exterior, anti-aliased, and dirty horizontal spans inside a cached rounded-clip corner mask.
81#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
82pub(crate) struct CornerMaskRowSpan {
83    /// Inclusive start X (in mask-local `0..dim`) of the contiguous exterior (`cov == 0`) run.
84    pub(crate) ext_start: u16,
85    /// Exclusive end X of the contiguous exterior (`cov == 0`) run.
86    pub(crate) ext_end: u16,
87    /// Inclusive start X of the anti-aliased (`1..=15`) transition run.
88    pub(crate) aa_start: u16,
89    /// Exclusive end X of the anti-aliased (`1..=15`) transition run.
90    pub(crate) aa_end: u16,
91    /// Inclusive start X of all non-interior (`cov < 16`) pixels requiring save/restore.
92    pub(crate) dirty_start: u16,
93    /// Exclusive end X of all non-interior (`cov < 16`) pixels requiring save/restore.
94    pub(crate) dirty_end: u16,
95}
96
97/// Cached exact 4x4 RGSS coverage grid (`0..=16` hit counts) for one rounded-clip quadrant `(radius, quadrant, aa)`.
98#[derive(Clone, Debug)]
99pub(crate) struct CachedCornerMask {
100    /// Bit representation of the clamped physical corner radius `r.to_bits()`.
101    pub(crate) radius_bits: u32,
102    /// Quadrant index (`0 = TL`, `1 = TR`, `2 = BR`, `3 = BL`).
103    pub(crate) quadrant: u8,
104    /// Whether 4x4 RGSS anti-aliasing is enabled (`false` for `AntialiasingMode::None`).
105    pub(crate) aa_enabled: bool,
106    /// Side length of the square coverage grid in physical pixels (`ceil(r + 1)`).
107    pub(crate) dim: u16,
108    /// Row-major exact coverage hit counts in `0..=16` (`0` = outside, `16` = fully inside).
109    pub(crate) cov: Vec<u8>,
110    /// Per-row horizontal exterior/AA/dirty span bounds (`len == dim`).
111    pub(crate) row_spans: Vec<CornerMaskRowSpan>,
112}
113
114/// Persistent cache of precomputed rounded-clip corner coverage masks reused across cards and frames.
115#[derive(Clone, Debug, Default)]
116pub(crate) struct CornerMaskCache {
117    /// Contiguous arena of cached quadrant coverage masks indexed by `u32` ID.
118    pub(crate) entries: Vec<CachedCornerMask>,
119}
120
121/// Single saved horizontal row segment belonging to one cached rounded-clip corner.
122#[derive(Clone, Copy, Debug, Default)]
123pub(crate) struct SavedCornerRow {
124    /// Global physical Y row coordinate.
125    pub(crate) y: u32,
126    /// Inclusive global physical start X of the saved segment.
127    pub(crate) sx0: u32,
128    /// Exclusive global physical end X of the saved segment.
129    pub(crate) sx1: u32,
130    /// Byte offset into `BandCornerScratch::saved_bytes` where this row's RGBA bytes start.
131    pub(crate) byte_off: usize,
132    /// Index into `CornerMaskCache::entries` for this quadrant.
133    pub(crate) mask_id: u32,
134    /// Mask-local X origin in global physical coordinates.
135    pub(crate) origin_x: i32,
136    /// Mask-local Y origin in global physical coordinates.
137    pub(crate) origin_y: i32,
138}
139
140/// Per-thread reusable scratch buffers for rounded-clip corner save and restore in `render_band`.
141#[derive(Debug, Default)]
142pub(crate) struct BandCornerScratch {
143    /// Bulk RGBA8 byte buffer storing pre-command corner pixels via `extend_from_slice`.
144    pub(crate) saved_bytes: Vec<u8>,
145    /// Saved row descriptors for the single-mask cached fast path.
146    pub(crate) saved_rows: Vec<SavedCornerRow>,
147    /// Clipped corner box bounds for the multi-mask / fallback path.
148    pub(crate) corner_boxes: Vec<(u32, u32, u32, u32)>,
149}
150
151/// Active rounded-rectangle clip mask in physical pixels applied during software band rasterization.
152#[derive(Clone, Copy, Data, Debug, Default, PartialEq)]
153pub(crate) struct RoundedClipMask {
154    /// Physical clip rectangle bounds.
155    #[get(type(copy))]
156    pub(crate) rect: Rect,
157    /// Physical corner radii.
158    #[get(type(copy))]
159    pub(crate) radius: CornerRadius,
160    /// Cached quadrant mask IDs `[tl, tr, br, bl]` into `CornerMaskCache::entries` (`u32::MAX` = uncached/inactive).
161    #[get(type(copy))]
162    pub(crate) corner_mask_ids: [u32; 4],
163}
164
165/// Pre-positioned glyph instance resolved once per frame on the main thread for zero-lookup band blitting.
166#[derive(Clone, Copy, Data, Debug, Default, Eq, New, PartialEq)]
167pub(crate) struct PositionedGlyph {
168    /// Direct arena slot index into `GlyphAtlas::entries`.
169    #[get(type(copy))]
170    pub(crate) glyph_idx: u32,
171    /// Rounded physical X coordinate of the glyph's left edge.
172    #[get(type(copy))]
173    pub(crate) x: i32,
174    /// Rounded physical Y coordinate of the glyph's top edge.
175    #[get(type(copy))]
176    pub(crate) y: i32,
177    /// Cached glyph bitmap width in physical pixels for fast band culling.
178    #[get(type(copy))]
179    pub(crate) width: u16,
180    /// Cached glyph bitmap height in physical pixels for fast band culling.
181    #[get(type(copy))]
182    pub(crate) height: u16,
183}
184
185/// Cache-line-isolated 128-byte aligned atomic counter preventing Apple Silicon (128B) and x86 (64B) false sharing.
186#[cfg(not(target_arch = "wasm32"))]
187#[repr(align(128))]
188#[derive(Debug, Default)]
189pub(crate) struct AlignedAtomicUsize {
190    /// Underlying atomic word padded to its own 128-byte cache line.
191    pub(crate) value: AtomicUsize,
192}
193
194/// Shared read-only descriptor for separable sliding-window `BackdropBlur` passes executed serially or in parallel.
195#[derive(Clone, Copy, Debug, Default)]
196pub(crate) struct BlurPassDesc {
197    /// Raw mutable framebuffer RGBA8 pixel base pointer (`*mut u8 as usize`).
198    #[cfg(not(target_arch = "wasm32"))]
199    pub(crate) fb_ptr: usize,
200    /// Total framebuffer RGBA8 byte length.
201    #[cfg(not(target_arch = "wasm32"))]
202    pub(crate) fb_len: usize,
203    /// Full framebuffer physical width in pixels.
204    pub(crate) fb_w: u32,
205    /// Raw mutable persistent horizontal-pass scratch base pointer (`*mut [u8; 4] as usize`).
206    #[cfg(not(target_arch = "wasm32"))]
207    pub(crate) horiz_ptr: usize,
208    /// Element count (`sw * sh`) of the active slice inside `blur_horiz_scratch`.
209    #[cfg(not(target_arch = "wasm32"))]
210    pub(crate) horiz_len: usize,
211    /// Inclusive halo source start X in physical pixels.
212    pub(crate) sx0: u32,
213    /// Inclusive halo source start Y in physical pixels.
214    pub(crate) sy0: u32,
215    /// Halo source width in physical pixels (`sx1 - sx0`).
216    pub(crate) sw: u32,
217    /// Halo source height in physical pixels (`sy1 - sy0`).
218    pub(crate) sh: u32,
219    /// Inclusive destination blur start X in physical pixels.
220    pub(crate) x0: u32,
221    /// Inclusive destination blur start Y in physical pixels.
222    pub(crate) y0: u32,
223    /// Exclusive destination blur end X in physical pixels.
224    pub(crate) x1: u32,
225    /// Exclusive destination blur end Y in physical pixels.
226    pub(crate) y1: u32,
227    /// Clamped integer box-filter half-radius (`1..=24`).
228    pub(crate) rad: u32,
229    /// Exact fixed-point Q24 reciprocal `ceil(2^24 / (2*rad + 1))` matching integer division bit-for-bit.
230    pub(crate) inv_win_q24: u64,
231    /// Physical destination rectangle for rounded-corner clipping.
232    pub(crate) rect: Rect,
233    /// Physical corner radii for rounded-corner clipping.
234    pub(crate) radius: CornerRadius,
235    /// True when `radius.max_radius() > 0.25`.
236    pub(crate) has_radius: bool,
237    /// Number of rows processed per work-stealing strip in parallel blur passes.
238    #[cfg(not(target_arch = "wasm32"))]
239    pub(crate) strip_rows: u32,
240    /// Total number of parallel blur strips for the current pass.
241    #[cfg(not(target_arch = "wasm32"))]
242    pub(crate) strip_count: usize,
243}
244
245/// Shared 128-byte aligned frame dispatch state consumed lock-free by persistent band workers during a single job epoch.
246#[cfg(not(target_arch = "wasm32"))]
247#[repr(align(128))]
248#[derive(Debug)]
249pub(crate) struct BandJob {
250    /// Active job execution mode (`RasterBands`, `BlurHoriz`, or `BlurVert`).
251    pub(crate) kind: BandJobKind,
252    /// Base address of the caller-owned `BandTaskSlice` slice.
253    pub(crate) tasks_ptr: usize,
254    /// Number of horizontal strips in the frame job.
255    pub(crate) tasks_len: usize,
256    /// Base address of `DisplayList::commands`.
257    pub(crate) commands_ptr: usize,
258    /// Length of `DisplayList::commands`.
259    pub(crate) commands_len: usize,
260    /// Base address of the pre-processed `PreppedCommand` slice.
261    pub(crate) prepped_ptr: usize,
262    /// Length of the pre-processed `PreppedCommand` slice.
263    pub(crate) prepped_len: usize,
264    /// Base address of the per-frame pre-positioned `PositionedGlyph` slice.
265    pub(crate) glyphs_ptr: usize,
266    /// Length of the per-frame pre-positioned `PositionedGlyph` slice.
267    pub(crate) glyphs_len: usize,
268    /// Base address of the per-frame pre-computed `TextCaret` rectangle slice.
269    pub(crate) caret_rects_ptr: usize,
270    /// Length of the per-frame pre-computed `TextCaret` rectangle slice.
271    pub(crate) caret_rects_len: usize,
272    /// Base address of the per-frame active `RoundedClipMask` slice.
273    pub(crate) rounded_clips_ptr: usize,
274    /// Length of the per-frame active `RoundedClipMask` slice.
275    pub(crate) rounded_clips_len: usize,
276    /// Base address of the read-only cached quadrant corner masks slice.
277    pub(crate) corner_masks_ptr: usize,
278    /// Length of the read-only cached quadrant corner masks slice.
279    pub(crate) corner_masks_len: usize,
280    /// Base address of the shared read-only `GlyphAtlas`.
281    pub(crate) atlas_ptr: usize,
282    /// Optional raw pointer to a stack-pinned 4-channel RGBA blend LUT tuple fused into backdrop restore (`0` when unused).
283    pub(crate) scrim_luts_ptr: usize,
284    /// Active physical DPI scale factor.
285    pub(crate) scale: f32,
286    /// Active anti-aliasing policy.
287    pub(crate) aa: AntialiasingMode,
288    /// Descriptor used when `kind` is `BlurHoriz` or `BlurVert`.
289    pub(crate) blur_desc: BlurPassDesc,
290    /// Cache-line-isolated atomic work-stealing strip cursor shared by the caller and all worker threads.
291    pub(crate) next_idx: AlignedAtomicUsize,
292    /// Cache-line-isolated atomic count of worker threads that finished observing this epoch.
293    pub(crate) workers_done: AlignedAtomicUsize,
294    /// Cache-line-isolated atomic accumulated shaded pixel count across all strips.
295    pub(crate) total_shaded: AlignedAtomicUsize,
296}
297
298/// Per-worker cache-line-isolated wake slot eliminating N-way mutex convoys and false sharing.
299#[cfg(not(target_arch = "wasm32"))]
300#[repr(align(128))]
301#[derive(Debug, Default)]
302pub(crate) struct BandWorkerSlot {
303    /// Per-worker monotonically increasing dispatch epoch counter.
304    pub(crate) epoch: AtomicUsize,
305    /// Non-zero while this worker thread is parked inside `wake.wait`.
306    pub(crate) parked: AtomicUsize,
307    /// Private mutex guarding this worker's condvar sleep transition.
308    pub(crate) lock: Mutex<()>,
309    /// Condition variable waking only this worker on a new epoch or shutdown.
310    pub(crate) wake: Condvar,
311}
312
313/// Lock-free 128-byte aligned dispatch header and per-worker wake slots shared between the caller and persistent band workers.
314#[cfg(not(target_arch = "wasm32"))]
315#[repr(align(128))]
316#[derive(Debug, Default)]
317pub(crate) struct BandPoolShared {
318    /// Raw pointer address of the active `BandJob` (`0` while idle).
319    pub(crate) active_job: AtomicUsize,
320    /// Number of background workers dispatched for the current epoch.
321    pub(crate) active_workers: AtomicUsize,
322    /// Adaptive hybrid spin limit (`~3072` during active animation/scroll, `0` immediately on idle).
323    pub(crate) spin_limit: AtomicUsize,
324    /// Non-zero when the worker pool is shutting down during `Drop`.
325    pub(crate) shutdown: AtomicUsize,
326    /// Cache-line-isolated flag set while the calling thread is parked waiting for workers to finish.
327    pub(crate) caller_parked: AlignedAtomicUsize,
328    /// Mutex guarding caller parking transitions (bypassed on the spin fast-path).
329    pub(crate) caller_lock: Mutex<()>,
330    /// Condition variable waking a parked caller once all dispatched workers finish an epoch.
331    pub(crate) wake_caller: Condvar,
332    /// Contention-free per-worker wake slots indexed by worker ID `0..worker_count`.
333    pub(crate) slots: Vec<BandWorkerSlot>,
334}
335
336/// Persistent native worker pool eliminating per-frame `pthread_create` overhead on high-refresh mobile and desktop targets.
337#[cfg(not(target_arch = "wasm32"))]
338#[derive(Debug)]
339pub(crate) struct BandWorkerPool {
340    /// Number of background worker threads (excluding the calling main thread).
341    pub(crate) worker_count: usize,
342    /// Non-blocking guard owning reusable horizontal band task slices across frames.
343    pub(crate) dispatch_tasks: Mutex<Vec<BandTaskSlice>>,
344    /// Shared atomic dispatch state and condition variables.
345    pub(crate) shared: Arc<BandPoolShared>,
346    /// Background worker join handles drained cleanly on `Drop`.
347    pub(crate) handles: Vec<JoinHandle<()>>,
348}
349
350/// Preprocessed draw-command metadata computed once on the main thread before parallel band rasterization.
351#[derive(Clone, Copy, Data, Debug, Default, PartialEq)]
352pub(crate) struct PreppedCommand {
353    /// Original index inside `DisplayList::commands`.
354    #[get(type(copy))]
355    pub(crate) cmd_index: usize,
356    /// Active intersected physical clip rectangle for this command.
357    #[get(type(copy))]
358    pub(crate) active_clip: Rect,
359    /// Inclusive top physical Y row affected by this command.
360    #[get(type(copy))]
361    pub(crate) y0: u32,
362    /// Exclusive bottom physical Y row affected by this command.
363    #[get(type(copy))]
364    pub(crate) y1: u32,
365    /// Optional opaque inner vertical-span cutout for a `BoxShadow` followed immediately by an opaque `FillRoundedRect`.
366    #[get(type(copy))]
367    pub(crate) opaque_cutout_h: Rect,
368    /// Optional opaque inner horizontal-span cutout for a `BoxShadow` followed immediately by an opaque `FillRoundedRect`.
369    #[get(type(copy))]
370    pub(crate) opaque_cutout_v: Rect,
371    /// Start index into the per-frame `PositionedGlyph` slice for `TextRun` commands (`0` when unused).
372    #[get(type(copy))]
373    pub(crate) glyph_run_start: u32,
374    /// Count of pre-positioned glyphs for `TextRun` commands (`0` when unused).
375    #[get(type(copy))]
376    pub(crate) glyph_run_len: u32,
377    /// Optional index into the per-frame pre-resolved `TextCaret` rectangle slice (`u32::MAX` when unused).
378    #[get(type(copy))]
379    pub(crate) caret_rect_idx: u32,
380    /// Start index into the per-frame `RoundedClipMask` slice (`0` when unused).
381    #[get(type(copy))]
382    pub(crate) rounded_clip_start: u32,
383    /// Count of active `RoundedClipMask` entries touching this command (`0` on fast path).
384    #[get(type(copy))]
385    pub(crate) rounded_clip_len: u16,
386    /// Relative index jump inside `prepped_scratch` when a `usize::MAX` clip-scope sentinel misses a band.
387    #[get(type(copy))]
388    pub(crate) skip_delta: u32,
389}
390
391/// Single open-addressed slot in `TextLayoutCache` mapping `(key_hash, width_key)` to an arena index.
392#[derive(Clone, Copy, Debug, Eq, PartialEq)]
393pub(crate) struct TextLayoutSlot {
394    /// Deterministic 64-bit FxHash of source text bytes and typography style.
395    pub(crate) key_hash: u64,
396    /// Quantized wrap width (`(max_w * 10.0).round() as u32`, or `u32::MAX` for unbounded lines).
397    pub(crate) width_key: u32,
398    /// Arena index into `TextLayoutCache::entries` (`u32::MAX` marks an empty slot).
399    pub(crate) entry_idx: u32,
400}
401
402/// Zero-clone, SipHash-free open-addressed cache of wrapped `TextLayoutResult` entries with bounded LRU eviction and telemetry.
403#[derive(Clone, Debug, Default)]
404pub(crate) struct TextLayoutCache {
405    /// Power-of-two linear-probing slot table (`entry_idx == u32::MAX` denotes an empty slot).
406    pub(crate) slots: Vec<TextLayoutSlot>,
407    /// Contiguous arena owning cached `TextLayoutResult` entries read lock-free across band workers.
408    pub(crate) entries: Vec<TextLayoutResult>,
409    /// Lookup keys `(key_hash, width_key)` aligned 1:1 with `entries` for slot table reconstruction after LRU eviction.
410    pub(crate) entry_keys: Vec<(u64, u32)>,
411    /// Monotonic access ticks aligned 1:1 with `entries` for bounded LRU eviction.
412    pub(crate) entry_last_used: Vec<u64>,
413    /// Tracked resident byte footprint per entry aligned 1:1 with `entries`.
414    pub(crate) entry_bytes: Vec<usize>,
415    /// Current total resident memory in bytes across all cached layouts.
416    pub(crate) resident_bytes: usize,
417    /// Optional custom memory budget in bytes (`0` selects `TEXT_LAYOUT_CACHE_BUDGET_BYTES`).
418    pub(crate) budget_bytes: usize,
419    /// Monotonic access clock incremented on every cache lookup.
420    pub(crate) lru_clock: u64,
421    /// Cumulative count of text layout cache hits.
422    pub(crate) cache_hits: u64,
423    /// Cumulative count of text layout cache misses.
424    pub(crate) cache_misses: u64,
425    /// Cumulative count of evicted cold text layouts.
426    pub(crate) evictions: u64,
427}
428
429/// Single open-addressed slot in `PositionedGlyphRunCache` keyed by `(text_style_hash, width_bits, phys_scale_milli)`.
430#[derive(Clone, Copy, Debug, Eq, PartialEq)]
431pub(crate) struct PositionedGlyphRunSlot {
432    /// Deterministic 64-bit FxHash of source text bytes and typography style.
433    pub(crate) key_hash: u64,
434    /// IEEE-754 bits of the logical text box width.
435    pub(crate) width_bits: u32,
436    /// Quantized physical scale factor `(scale * 1000.0).round() as u32`.
437    pub(crate) phys_scale_milli: u32,
438    /// Arena index into `PositionedGlyphRunCache::entries` (`u32::MAX` marks an empty slot).
439    pub(crate) entry_idx: u32,
440}
441
442/// Cached relative-offset glyph sequence range inside `PositionedGlyphRunCache::glyph_slab`.
443#[derive(Clone, Copy, Debug, Default)]
444pub(crate) struct CachedPositionedGlyphRun {
445    /// Start index inside `PositionedGlyphRunCache::glyph_slab`.
446    pub(crate) glyph_start: u32,
447    /// Number of relative `PositionedGlyph` entries owned by this run.
448    pub(crate) glyph_len: u32,
449    /// True when any glyph had a non-integer relative X offset before rounding (guards negative-origin tie parity).
450    pub(crate) has_fractional_x: bool,
451    /// Maximum `GlyphAtlas` slot index referenced by this run for O(1) validity checks.
452    pub(crate) max_glyph_slot: u32,
453}
454
455/// Bounded open-addressed flat-slab cache of `CachedPositionedGlyphRun` entries keyed by `(text_hash, width_bits, phys_scale_milli)`.
456#[derive(Clone, Debug, Default)]
457pub(crate) struct PositionedGlyphRunCache {
458    /// Power-of-two linear-probing slot table (`entry_idx == u32::MAX` marks an empty slot).
459    pub(crate) slots: Vec<PositionedGlyphRunSlot>,
460    /// Contiguous flat glyph slab eliminating per-entry `Vec<PositionedGlyph>` heap allocations.
461    pub(crate) glyph_slab: Vec<PositionedGlyph>,
462    /// Contiguous arena of cached relative-positioned glyph run descriptors.
463    pub(crate) entries: Vec<CachedPositionedGlyphRun>,
464    /// Lookup keys `(key_hash, width_bits, phys_scale_milli)` aligned 1:1 with `entries`.
465    pub(crate) entry_keys: Vec<(u64, u32, u32)>,
466    /// Monotonic LRU access ticks aligned 1:1 with `entries`.
467    pub(crate) entry_last_used: Vec<u64>,
468    /// Pre-allocated keep-flag vector reused during zero-allocation LRU compaction.
469    pub(crate) evict_keep: Vec<bool>,
470    /// Pre-allocated destination slab reused during zero-allocation LRU compaction.
471    pub(crate) evict_slab_scratch: Vec<PositionedGlyph>,
472    /// Consecutive misses without any cache hit (detects streaming virtual-list text churn).
473    pub(crate) miss_streak: u32,
474    /// Misses observed during the current frame for streaming-churn decay on static frames.
475    pub(crate) frame_misses: u32,
476    /// Monotonic access clock incremented on lookups.
477    pub(crate) lru_clock: u64,
478    /// `GlyphAtlas::evictions` watermark last observed when populating cached slot indices.
479    pub(crate) atlas_evictions: u64,
480    /// `GlyphAtlas::font_chain_revision` watermark last observed when populating cached slot indices.
481    pub(crate) font_chain_revision: u64,
482    /// Highest `GlyphAtlas` slot index referenced across all cached runs.
483    pub(crate) max_cached_slot: u32,
484    /// Cumulative positioned glyph run cache hits (reused without `GlyphAtlas` mutation).
485    pub(crate) cache_hits: u64,
486    /// Cumulative positioned glyph run cache misses.
487    pub(crate) cache_misses: u64,
488    /// Cumulative evicted cold positioned glyph runs.
489    pub(crate) evictions: u64,
490}
491
492/// High-performance CPU tile and analytical-SDF software rasterizer with zero GPU dependencies.
493#[derive(Clone, Data, Debug, Default)]
494pub struct SoftwareRenderer {
495    /// Lazily allocated RGBA8 framebuffer (`None` when GPU direct-draw is active with zero CPU FB bytes).
496    #[get(skip)]
497    #[get_mut(skip)]
498    #[set(skip)]
499    pub(crate) framebuffer: Option<Framebuffer>,
500    /// Shared glyph rasterization atlas.
501    pub(crate) glyph_atlas: GlyphAtlas,
502    /// Native or deterministic font rasterization provider.
503    #[set(skip)]
504    pub(crate) font_provider: NativeSystemFont,
505    /// Deterministic text measurer matching `LayoutEngine` metrics.
506    #[get(type(copy))]
507    pub(crate) measurer: DeterministicTextMeasurer,
508    /// Zero-clone open-addressed cache of wrapped `TextLayoutResult` entries eliminating per-frame cloning and SipHash.
509    #[get(pub(crate))]
510    #[get_mut(pub(crate))]
511    #[set(pub(crate))]
512    pub(crate) text_layout_cache: TextLayoutCache,
513    /// Relative-offset `PositionedGlyphRun` cache keyed by `(text_hash, width_bits, phys_scale_milli)` for zero-LRU-mutation scroll reuse.
514    #[get(pub(crate))]
515    #[get_mut(pub(crate))]
516    #[set(skip)]
517    pub(crate) positioned_glyph_run_cache: PositionedGlyphRunCache,
518    /// Persistent scratch buffer for Pass 1 of separable sliding-window `BackdropBlur` (zero steady-state per-frame allocs).
519    #[get(pub(crate))]
520    #[get_mut(pub(crate))]
521    #[set(skip)]
522    pub(crate) blur_horiz_scratch: Vec<[u8; 4]>,
523    /// Persistent keep-flag buffer reused by `cull_occluded_prepped_commands` across frames.
524    #[get(skip)]
525    #[get_mut(skip)]
526    #[set(skip)]
527    pub(crate) cull_keep_scratch: Vec<bool>,
528    /// Persistent compacted command buffer reused by `cull_occluded_prepped_commands` across frames.
529    #[get(skip)]
530    #[get_mut(skip)]
531    #[set(skip)]
532    pub(crate) cull_compacted_scratch: Vec<PreppedCommand>,
533    /// Persistent open-sentinel stack reused by `cull_occluded_prepped_commands` across frames.
534    #[get(skip)]
535    #[get_mut(skip)]
536    #[set(skip)]
537    pub(crate) cull_sentinels_scratch: Vec<(usize, usize)>,
538    /// Active physical clip-rectangle stack.
539    #[get(pub(crate))]
540    #[get_mut(pub(crate))]
541    #[set(pub(crate))]
542    pub(crate) clip_stack: Vec<Rect>,
543    /// Parallel stack of optional rounded-rectangle clip masks aligned 1:1 with `clip_stack`.
544    #[get(pub(crate))]
545    #[get_mut(pub(crate))]
546    #[set(pub(crate))]
547    pub(crate) rounded_clip_stack: Vec<Option<RoundedClipMask>>,
548    /// Active anti-aliasing policy.
549    #[get(type(copy))]
550    pub(crate) antialiasing: AntialiasingMode,
551    /// Tile edge length in physical pixels for damage tile accounting.
552    #[get(type(copy))]
553    pub(crate) tile_size: u32,
554    /// Cached physical width of the static base-scene snapshot behind active portals.
555    #[get(pub(crate), type(copy))]
556    #[set(pub(crate))]
557    pub(crate) base_cache_width: u32,
558    /// Cached physical height of the static base-scene snapshot behind active portals.
559    #[get(pub(crate), type(copy))]
560    #[set(pub(crate))]
561    pub(crate) base_cache_height: u32,
562    /// Full base-layer command hash for the cached static backdrop (`0` when invalid).
563    #[get(pub(crate), type(copy))]
564    #[set(pub(crate))]
565    pub(crate) base_cache_hash: u64,
566    /// Base-layer command hash observed on the immediately preceding frame to avoid copying active scroll frames.
567    #[get(pub(crate), type(copy))]
568    #[set(pub(crate))]
569    pub(crate) prev_base_hash: u64,
570    /// Saved RGBA8 pixels of the static base scene beneath active portals for fast overlay compositing.
571    #[get(pub(crate))]
572    #[get_mut(pub(crate))]
573    #[set(pub(crate))]
574    pub(crate) base_cache_pixels: Vec<u8>,
575    /// Reusable pre-processed draw command buffer cleared at frame start to avoid per-frame allocations.
576    #[get(pub(crate))]
577    #[get_mut(pub(crate))]
578    #[set(pub(crate))]
579    pub(crate) prepped_scratch: Vec<PreppedCommand>,
580    /// Reusable active rounded-clip mask buffer cleared at frame start to avoid per-frame allocations.
581    #[get(pub(crate))]
582    #[get_mut(pub(crate))]
583    #[set(pub(crate))]
584    pub(crate) rounded_clips_scratch: Vec<RoundedClipMask>,
585    /// Reusable flat buffer of pre-positioned glyphs emitted once per frame for zero-lookup band rasterization.
586    #[get(pub(crate))]
587    #[get_mut(pub(crate))]
588    #[set(pub(crate))]
589    pub(crate) positioned_glyphs_scratch: Vec<PositionedGlyph>,
590    /// Reusable line buffer for single-lookup `Center`/`Right` text alignment positioning.
591    #[get(pub(crate))]
592    #[get_mut(pub(crate))]
593    #[set(pub(crate))]
594    pub(crate) line_glyphs_scratch: Vec<(u32, f32, u16, u16)>,
595    /// Reusable buffer of pre-computed physical caret rectangles for `DrawCommand::TextCaret`.
596    #[get(pub(crate))]
597    #[get_mut(pub(crate))]
598    #[set(pub(crate))]
599    pub(crate) caret_rects_scratch: Vec<Rect>,
600    /// Persistent cache of precomputed rounded-clip corner coverage masks reused across cards and frames.
601    #[get(pub(crate))]
602    #[get_mut(pub(crate))]
603    #[set(pub(crate))]
604    pub(crate) corner_mask_cache: CornerMaskCache,
605    /// Physical union bounds of the foreground portal commands painted on the previous cached frame.
606    #[get(pub(crate), type(copy))]
607    #[set(pub(crate))]
608    pub(crate) prev_portal_bounds: Option<Rect>,
609    /// Full-viewport translucent scrim color active on the previous cached portal frame, if any.
610    #[get(pub(crate), type(copy))]
611    #[set(pub(crate))]
612    pub(crate) prev_portal_scrim: Option<Color>,
613    /// Physical union bounds of all prepped commands emitted during the latest `prepare_frame_range`.
614    #[get(pub(crate), type(copy))]
615    #[set(pub(crate))]
616    pub(crate) prepped_bounds: Option<Rect>,
617    /// Physical union bounds of `prepped_scratch[1..]` emitted during the latest `prepare_frame_range`.
618    #[get(pub(crate), type(copy))]
619    #[set(pub(crate))]
620    pub(crate) prepped_fg_bounds: Option<Rect>,
621    /// Reusable clip-scope stack `(clip_y0, clip_y1, optional_sentinel_idx)` for O(1) off-band subtree skipping.
622    #[get(pub(crate))]
623    #[get_mut(pub(crate))]
624    #[set(pub(crate))]
625    pub(crate) clip_scope_scratch: Vec<(u32, u32, Option<usize>)>,
626    /// Cached full-viewport translucent scrim color matching `cached_scrim_luts`.
627    #[get(skip)]
628    #[get_mut(skip)]
629    #[set(skip)]
630    pub(crate) cached_scrim_color: Option<Color>,
631    /// Cached 256-entry per-channel linear-light scrim LUT reused across frames with identical scrim color.
632    #[get(skip)]
633    #[get_mut(skip)]
634    #[set(skip)]
635    pub(crate) cached_scrim_luts: Option<Box<[[u8; 256]; 4]>>,
636    /// Cumulative number of rasterization passes executed serially on the calling thread.
637    #[get(type(copy))]
638    #[get_mut(skip)]
639    #[set(skip)]
640    pub(crate) serial_dispatches: u64,
641    /// Cumulative number of rasterization passes dispatched across `BandWorkerPool`.
642    #[get(type(copy))]
643    #[get_mut(skip)]
644    #[set(skip)]
645    pub(crate) parallel_dispatches: u64,
646    /// Cumulative number of fully occluded draw commands culled without reordering translucent layers.
647    #[get(type(copy))]
648    #[get_mut(skip)]
649    #[set(skip)]
650    pub(crate) culled_occluded_commands: u64,
651    /// Current adaptive pixel-area threshold separating serial execution from multi-threaded band dispatch.
652    #[get(type(copy))]
653    #[get_mut(skip)]
654    #[set(skip)]
655    pub(crate) adaptive_parallel_threshold_pixels: usize,
656    /// Optional explicit pixel-area override for parallel band dispatch (`0` selects adaptive auto-tuning).
657    #[get(type(copy))]
658    #[get_mut(skip)]
659    #[set(skip)]
660    pub(crate) adaptive_threshold_override: usize,
661    /// Most recently observed serial band rasterization duration in microseconds.
662    #[get(type(copy))]
663    #[get_mut(skip)]
664    #[set(skip)]
665    pub(crate) last_serial_us: u64,
666    /// Most recently observed parallel band rasterization duration in microseconds.
667    #[get(type(copy))]
668    #[get_mut(skip)]
669    #[set(skip)]
670    pub(crate) last_parallel_us: u64,
671    /// Total frames rendered by this `SoftwareRenderer` (Frame 1 runs serially before async worker pool warm-up).
672    #[get(type(copy))]
673    #[get_mut(skip)]
674    #[set(skip)]
675    pub(crate) rendered_frames: u64,
676    /// Gates `Instant::now()` microsecond timing instrumentation inside `execute_prepared_bands` (`false` by default).
677    #[get(type(copy))]
678    pub(crate) telemetry_enabled: bool,
679    /// Tracks whether active animation or scrolling keeps `BandWorkerPool` adaptive hybrid spin enabled (`false` = `0` spin).
680    #[get(type(copy))]
681    #[set(skip)]
682    pub(crate) high_frequency_active: bool,
683    /// Cached per-tile (`128x16`) FNV-1a framebuffer hashes for O(dirty_tiles) bit-exact `incremental_framebuffer_hash`.
684    #[get(skip)]
685    #[get_mut(skip)]
686    #[set(skip)]
687    pub(crate) hash_tiles: Vec<u64>,
688    /// Bitset marking `128x16` framebuffer tiles dirtied since the last `incremental_framebuffer_hash` computation.
689    #[get(skip)]
690    #[get_mut(skip)]
691    #[set(skip)]
692    pub(crate) hash_dirty_bits: Vec<u64>,
693    /// Framebuffer width in pixels matching `hash_tiles`.
694    #[get(skip)]
695    #[get_mut(skip)]
696    #[set(skip)]
697    pub(crate) hash_tiles_w: u32,
698    /// Framebuffer height in pixels matching `hash_tiles`.
699    #[get(skip)]
700    #[get_mut(skip)]
701    #[set(skip)]
702    pub(crate) hash_tiles_h: u32,
703    /// True once `hash_tiles` holds valid hashes for `(hash_tiles_w, hash_tiles_h)`.
704    #[get(skip)]
705    #[get_mut(skip)]
706    #[set(skip)]
707    pub(crate) hash_tiles_valid: bool,
708}
709
710/// Compact 16-byte hot per-column cache entry reused across every vertical shadow strip scanline.
711#[derive(Clone, Copy, Debug, Default)]
712pub(crate) struct ShadowStripHot {
713    /// Precomputed horizontal IGN phase term `(x as f32) * 0.067_110_56`.
714    pub(crate) ign_x: f32,
715    /// Last observed destination RGBA8 bytes packed as native-endian `u32`.
716    pub(crate) cached_dst: u32,
717    /// Cached quantized sRGB Q4 red output prior to IGN dither addition.
718    pub(crate) q4_r: i16,
719    /// Cached quantized sRGB Q4 green output prior to IGN dither addition.
720    pub(crate) q4_g: i16,
721    /// Cached quantized sRGB Q4 blue output prior to IGN dither addition.
722    pub(crate) q4_b: i16,
723    /// Cached composited output alpha byte.
724    pub(crate) out_a: u8,
725    /// Column blend state (`0` = inactive, `1` = uncached blend, `2` = cached blend, `3` = opaque).
726    pub(crate) state: u8,
727}
728
729/// Precomputed linear-light blend factors for a single shadow column or mirrored corner sample.
730#[derive(Clone, Copy, Debug, Default)]
731pub(crate) struct ShadowStripParams {
732    /// Premultiplied linear red channel `SRGB_TO_LIN_LUT[r] * alpha`.
733    pub(crate) sr_a: f32,
734    /// Premultiplied linear green channel `SRGB_TO_LIN_LUT[g] * alpha`.
735    pub(crate) sg_a: f32,
736    /// Premultiplied linear blue channel `SRGB_TO_LIN_LUT[b] * alpha`.
737    pub(crate) sb_a: f32,
738    /// Complement opacity `1.0 - alpha`.
739    pub(crate) inv_a: f32,
740    /// Quantized source alpha `(alpha * 255.0) as u32`.
741    pub(crate) sa_u32: u32,
742    /// Complement integer alpha `255 - sa_u32`.
743    pub(crate) inv_a_u32: u32,
744}
745
746/// Single-pixel destination cache shared across 2x/4x symmetrically mirrored shadow corner writes.
747#[derive(Clone, Copy, Debug, Default)]
748pub(crate) struct ShadowPixelCache {
749    /// Last observed destination RGBA8 bytes packed as native-endian `u32`.
750    pub(crate) dst_u32: u32,
751    /// Cached quantized sRGB Q4 red output prior to IGN dither addition.
752    pub(crate) q4_r: i32,
753    /// Cached quantized sRGB Q4 green output prior to IGN dither addition.
754    pub(crate) q4_g: i32,
755    /// Cached quantized sRGB Q4 blue output prior to IGN dither addition.
756    pub(crate) q4_b: i32,
757    /// Cached composited output alpha byte.
758    pub(crate) out_a: u8,
759    /// Whether `dst_u32` and `q4_*` have been populated for the current corner sample.
760    pub(crate) valid: bool,
761}
762
763/// Per-thread reusable 1D horizontal shadow falloff strip buffers eliminating per-shadow allocations.
764#[derive(Debug, Default)]
765pub(crate) struct BandShadowScratch {
766    /// Hot per-column cache entries for the left vertical shadow strip.
767    pub(crate) left_hot: Vec<ShadowStripHot>,
768    /// Cold linear blend parameters for the left vertical shadow strip.
769    pub(crate) left_params: Vec<ShadowStripParams>,
770    /// Hot per-column cache entries for the right vertical shadow strip.
771    pub(crate) right_hot: Vec<ShadowStripHot>,
772    /// Cold linear blend parameters for the right vertical shadow strip.
773    pub(crate) right_params: Vec<ShadowStripParams>,
774}
775
776/// Precomputed geometry and hoisted linear tint constants shared across rows of one `raster_shadow` invocation.
777#[derive(Clone, Copy, Debug)]
778pub(crate) struct ShadowRenderCtx {
779    /// Shadow tint RGBA color passed to `blend_shadow_span_const_alpha`.
780    pub(crate) color: Color,
781    /// Shadow tint sRGB RGB bytes `[r, g, b]`.
782    pub(crate) color_rgb: [u8; 3],
783    /// Hoisted linear-light shadow tint `[sr, sg, sb]`.
784    pub(crate) lin_rgb: [f32; 3],
785    /// Caster horizontal center X in physical pixels.
786    pub(crate) cx: f32,
787    /// Caster vertical center Y in physical pixels.
788    pub(crate) cy: f32,
789    /// Caster half-width in physical pixels.
790    pub(crate) half_w: f32,
791    /// Caster half-height in physical pixels.
792    pub(crate) half_h: f32,
793    /// Normalized shadow tint alpha in `[0.0, 1.0]`.
794    pub(crate) base_alpha: f32,
795    /// Inverse Gaussian standard deviation `1.0 / sigma.max(0.5)`.
796    pub(crate) inv_sigma: f32,
797    /// Gaussian cutoff radius `3.0 * sigma`.
798    pub(crate) cutoff: f32,
799    /// Clamped uniform corner radius in physical pixels.
800    pub(crate) uniform_r: f32,
801    /// Conservative squared distance threshold `(cutoff + uniform_r + 1e-3)^2` for sqrt-free corner early reject.
802    pub(crate) cutoff_r_safe_sq: f32,
803    /// Clamped inclusive visible left X bound.
804    pub(crate) x0: u32,
805    /// Clamped exclusive visible right X bound.
806    pub(crate) x1: u32,
807    /// Exclusive end X of the left corner region (`sx0` when `has_mid_x`, else `split_x`).
808    pub(crate) lx1: u32,
809    /// Inclusive start X of the right corner region (`sx1` when `has_mid_x`, else `split_x`).
810    pub(crate) rx0: u32,
811    /// Horizontal mirror sum `(2 * cx).round() - 1` when `cx` is half-integer aligned.
812    pub(crate) mirror_x_sum: i32,
813    /// True when the shadow has a middle constant-alpha horizontal span (`sx0 < sx1`).
814    pub(crate) has_mid_x: bool,
815}