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