Skip to main content

euv_core/render/software/
impl.rs

1use super::*;
2
3/// Persistent work-stealing multi-core band pool methods for `BandWorkerPool`.
4#[cfg(not(target_arch = "wasm32"))]
5/// Inherent implementation of [`BandWorkerPool`].
6impl BandWorkerPool {
7    /// Creates a persistent worker pool sized to the host CPU count (clamped to `1..=16` total threads including the caller).
8    ///
9    /// # Returns
10    ///
11    /// - `Self` - Initialized worker pool with warm background threads.
12    #[must_use]
13    pub(crate) fn new() -> Self {
14        let total: usize = available_parallelism()
15            .map(usize::from)
16            .unwrap_or(4)
17            .clamp(1, BAND_WORKER_MAX_THREADS);
18        let requested_workers: usize = total.saturating_sub(1);
19        let mut slots: Vec<BandWorkerSlot> = Vec::with_capacity(requested_workers);
20        for _ in 0..requested_workers {
21            slots.push(BandWorkerSlot::default());
22        }
23        let shared: Arc<BandPoolShared> = Arc::new(BandPoolShared {
24            active_job: AtomicUsize::new(0),
25            active_workers: AtomicUsize::new(0),
26            caller_parked: AtomicUsize::new(0),
27            shutdown: AtomicUsize::new(0),
28            caller_lock: Mutex::new(()),
29            wake_caller: Condvar::new(),
30            slots,
31        });
32        let mut handles: Vec<JoinHandle<()>> = Vec::with_capacity(requested_workers);
33        for idx in 0..requested_workers {
34            let shared_clone: Arc<BandPoolShared> = Arc::clone(&shared);
35            let name: String = format!("{BAND_WORKER_THREAD_PREFIX}-{idx}");
36            if let Ok(handle) = Builder::new().name(name).spawn(move || {
37                let slot: &BandWorkerSlot = &shared_clone.slots[idx];
38                let mut seen_epoch: usize = 0;
39                loop {
40                    let mut spins: u32 = 0;
41                    let job_ptr: usize = loop {
42                        let cur_epoch: usize = slot.epoch.load(Ordering::Acquire);
43                        if cur_epoch != seen_epoch {
44                            let ptr: usize = shared_clone.active_job.load(Ordering::Acquire);
45                            if ptr != 0 {
46                                seen_epoch = cur_epoch;
47                                break ptr;
48                            }
49                        }
50                        if shared_clone.shutdown.load(Ordering::Acquire) != 0 {
51                            return;
52                        }
53                        if spins < BAND_WORKER_SPIN_LIMIT {
54                            spins += 1;
55                            spin_loop();
56                            continue;
57                        }
58                        let Ok(mut guard) = slot.lock.lock() else {
59                            return;
60                        };
61                        slot.parked.store(1, Ordering::SeqCst);
62                        let parked_ptr: Option<usize> = loop {
63                            let locked_epoch: usize = slot.epoch.load(Ordering::SeqCst);
64                            if locked_epoch != seen_epoch {
65                                let ptr: usize = shared_clone.active_job.load(Ordering::Acquire);
66                                if ptr != 0 {
67                                    seen_epoch = locked_epoch;
68                                    break Some(ptr);
69                                }
70                            }
71                            if shared_clone.shutdown.load(Ordering::SeqCst) != 0 {
72                                break None;
73                            }
74                            let Ok(next_guard) = slot.wake.wait(guard) else {
75                                break None;
76                            };
77                            guard = next_guard;
78                        };
79                        slot.parked.store(0, Ordering::SeqCst);
80                        let Some(ptr) = parked_ptr else {
81                            return;
82                        };
83                        break ptr;
84                    };
85                    // SAFETY: Caller keeps `BandJob` pinned on its stack until `workers_done >= active_workers`.
86                    let job: &BandJob = unsafe { &*(job_ptr as *const BandJob) };
87                    run_band_job_loop(job);
88                    let expected: usize = shared_clone.active_workers.load(Ordering::Acquire);
89                    let finished: usize = job.workers_done.fetch_add(1, Ordering::SeqCst) + 1;
90                    if finished >= expected
91                        && shared_clone.caller_parked.load(Ordering::SeqCst) != 0
92                        && let Ok(_guard) = shared_clone.caller_lock.lock()
93                    {
94                        shared_clone.wake_caller.notify_one();
95                    }
96                }
97            }) {
98                handles.push(handle);
99            } else {
100                break;
101            }
102        }
103        let worker_count: usize = handles.len();
104        Self {
105            worker_count,
106            dispatch_tasks: Mutex::new(Vec::with_capacity(
107                worker_count.saturating_add(1).saturating_mul(2),
108            )),
109            shared,
110            handles,
111        }
112    }
113
114    /// Executes a contiguous horizontal framebuffer slice serially on the calling thread with optional cached backdrop restore.
115    ///
116    /// # Arguments
117    ///
118    /// - `(&mut [u8], u32, u32, u32, usize)` - Tuple `(pixels, width, y_offset, height, start_byte_offset)`.
119    /// - `&[DrawCommand]` - Display list commands.
120    /// - `&[PreppedCommand]` - Pre-clipped command table.
121    /// - `BandAuxSlices<'_>` - Pre-positioned glyphs, caret rects, rounded clips, and cached quadrant masks.
122    /// - `&GlyphAtlas` - Shared read-only glyph atlas.
123    /// - `(f32, AntialiasingMode, BandRestoreSpec<'_>)` - Tuple of `(scale, antialiasing, restore_spec)`.
124    ///
125    /// # Returns
126    ///
127    /// - `usize` - Total shaded pixel count across the slice.
128    fn execute_serial(
129        slice_spec: (&mut [u8], u32, u32, u32, usize),
130        commands: &[DrawCommand],
131        prepped: &[PreppedCommand],
132        aux: BandAuxSlices<'_>,
133        atlas: &GlyphAtlas,
134        render_opts: (f32, AntialiasingMode, BandRestoreSpec<'_>),
135    ) -> usize {
136        let (pixels, width, y_offset, height, start_byte): (&mut [u8], u32, u32, u32, usize) =
137            slice_spec;
138        let (scale, aa, restore): (f32, AntialiasingMode, BandRestoreSpec<'_>) = render_opts;
139        if let Some(src_buf) = restore.base_pixels {
140            let end_byte: usize = start_byte + pixels.len();
141            if let Some(src_slice) = src_buf.get(start_byte..end_byte) {
142                let x0_clamped: u32 = restore.x0.min(width);
143                let x1_clamped: u32 = restore.x1.clamp(x0_clamped, width);
144                restore_band_strip(
145                    pixels,
146                    src_slice,
147                    (
148                        (width as usize) * 4,
149                        height as usize,
150                        (x0_clamped as usize) * 4,
151                        ((x1_clamped - x0_clamped) as usize) * 4,
152                    ),
153                    restore.scrim_luts,
154                );
155            }
156        }
157        let mut band: PixelBand<'_> = PixelBand {
158            width,
159            y_offset,
160            height,
161            pixels,
162        };
163        SoftwareRenderer::render_band(&mut band, commands, prepped, aux, atlas, (scale, aa))
164    }
165
166    /// Returns total participating rasterizer threads (background workers plus the calling main thread).
167    ///
168    /// # Returns
169    ///
170    /// - `usize` - Total active thread count in `1..=16`.
171    #[must_use]
172    pub(crate) fn total_threads(&self) -> usize {
173        let Self { worker_count, .. } = self;
174        worker_count.saturating_add(1)
175    }
176
177    /// Dispatches horizontal pixel strips across the persistent worker pool without per-frame task or band allocations.
178    ///
179    /// # Arguments
180    ///
181    /// - `&Self` - Worker pool reference.
182    /// - `&mut Framebuffer` - Target mutable framebuffer.
183    /// - `(u32, u32, usize, usize)` - Tuple `(clip_y0, clip_y1, strip_count, max_workers)`.
184    /// - `(&[DrawCommand], &[PreppedCommand])` - Display list commands and pre-clipped command table.
185    /// - `BandAuxSlices<'_>` - Pre-positioned glyphs, caret rects, rounded clips, and cached quadrant masks.
186    /// - `&GlyphAtlas` - Shared read-only glyph atlas.
187    /// - `(f32, AntialiasingMode, BandRestoreSpec<'_>)` - Tuple of `(scale, antialiasing, restore_spec)`.
188    ///
189    /// # Returns
190    ///
191    /// - `usize` - Total shaded pixel count across all strips.
192    pub(crate) fn execute(
193        &self,
194        framebuffer: &mut Framebuffer,
195        band_range: (u32, u32, usize, usize),
196        cmd_slices: (&[DrawCommand], &[PreppedCommand]),
197        aux: BandAuxSlices<'_>,
198        atlas: &GlyphAtlas,
199        render_opts: (f32, AntialiasingMode, BandRestoreSpec<'_>),
200    ) -> usize {
201        let Self {
202            worker_count,
203            dispatch_tasks,
204            shared,
205            ..
206        } = self;
207        let (y0, y1, band_count, max_workers): (u32, u32, usize, usize) = band_range;
208        let (commands, prepped): (&[DrawCommand], &[PreppedCommand]) = cmd_slices;
209        let (positioned_glyphs, caret_rects, rounded_clips, corner_masks): (
210            &[PositionedGlyph],
211            &[Rect],
212            &[RoundedClipMask],
213            &[CachedCornerMask],
214        ) = aux;
215        let (scale, aa, restore): (f32, AntialiasingMode, BandRestoreSpec<'_>) = render_opts;
216        let fb_w: u32 = framebuffer.get_width();
217        let fb_h: u32 = framebuffer.get_height();
218        let start_y: u32 = y0.min(fb_h);
219        let end_y: u32 = y1.clamp(start_y, fb_h);
220        let total_rows: u32 = end_y - start_y;
221        if total_rows == 0 || fb_w == 0 {
222            return 0;
223        }
224        let row_stride: usize = (fb_w as usize) * 4;
225        let start_byte: usize = (start_y as usize) * row_stride;
226        let end_byte: usize = (end_y as usize) * row_stride;
227        let Some(slice) = framebuffer.get_mut_pixels().get_mut(start_byte..end_byte) else {
228            return 0;
229        };
230        let strip_count: usize = band_count.max(1).min(total_rows as usize);
231        let worker_budget: usize = (*worker_count).min(max_workers);
232        if worker_budget == 0 || strip_count <= 1 {
233            return Self::execute_serial(
234                (slice, fb_w, start_y, total_rows, start_byte),
235                commands,
236                prepped,
237                aux,
238                atlas,
239                (scale, aa, restore),
240            );
241        }
242        let Ok(mut tasks) = dispatch_tasks.try_lock() else {
243            return Self::execute_serial(
244                (slice, fb_w, start_y, total_rows, start_byte),
245                commands,
246                prepped,
247                aux,
248                atlas,
249                (scale, aa, restore),
250            );
251        };
252        tasks.clear();
253        let rx0_clamped: u32 = restore.x0.min(fb_w);
254        let rx1_clamped: u32 = restore.x1.clamp(rx0_clamped, fb_w);
255        let restore_x0_bytes: usize = (rx0_clamped as usize) * 4;
256        let restore_row_bytes: usize = ((rx1_clamped - rx0_clamped) as usize) * 4;
257        let rows_per: usize = (total_rows as usize).div_ceil(strip_count);
258        let chunk_bytes: usize = rows_per * row_stride;
259        let mut cur_y: u32 = start_y;
260        let mut cur_byte_off: usize = start_byte;
261        for chunk in slice.chunks_mut(chunk_bytes) {
262            let chunk_len: usize = chunk.len();
263            let chunk_rows: u32 = (chunk_len / row_stride) as u32;
264            let base_ptr: usize = if let Some(src_buf) = restore.base_pixels {
265                let byte_end: usize = cur_byte_off + chunk_len;
266                if byte_end <= src_buf.len() {
267                    // SAFETY: `cur_byte_off <= byte_end <= src_buf.len()` stays within `src_buf`.
268                    unsafe { src_buf.as_ptr().add(cur_byte_off) as usize }
269                } else {
270                    0
271                }
272            } else {
273                0
274            };
275            tasks.push(BandTaskSlice {
276                pixels_ptr: chunk.as_mut_ptr() as usize,
277                pixels_len: chunk_len,
278                width: fb_w,
279                y_start: cur_y,
280                height: chunk_rows,
281                base_src_ptr: base_ptr,
282                restore_x0_bytes,
283                restore_row_bytes,
284            });
285            cur_y += chunk_rows;
286            cur_byte_off += chunk_len;
287        }
288        let scrim_luts_ptr: usize = restore.scrim_luts.map_or(0, |luts: &RgbaLutQuad| {
289            (luts as *const RgbaLutQuad) as usize
290        });
291        let job: BandJob = BandJob {
292            tasks_ptr: tasks.as_ptr() as usize,
293            tasks_len: tasks.len(),
294            commands_ptr: commands.as_ptr() as usize,
295            commands_len: commands.len(),
296            prepped_ptr: prepped.as_ptr() as usize,
297            prepped_len: prepped.len(),
298            glyphs_ptr: positioned_glyphs.as_ptr() as usize,
299            glyphs_len: positioned_glyphs.len(),
300            caret_rects_ptr: caret_rects.as_ptr() as usize,
301            caret_rects_len: caret_rects.len(),
302            rounded_clips_ptr: rounded_clips.as_ptr() as usize,
303            rounded_clips_len: rounded_clips.len(),
304            corner_masks_ptr: corner_masks.as_ptr() as usize,
305            corner_masks_len: corner_masks.len(),
306            atlas_ptr: (atlas as *const GlyphAtlas) as usize,
307            scrim_luts_ptr,
308            scale,
309            aa,
310            next_idx: AtomicUsize::new(0),
311            workers_done: AtomicUsize::new(0),
312            total_shaded: AtomicUsize::new(0),
313        };
314        let dispatch_workers: usize = worker_budget.min(tasks.len().saturating_sub(1));
315        if dispatch_workers == 0 {
316            run_band_job_loop(&job);
317            return job.total_shaded.load(Ordering::Acquire);
318        }
319        shared
320            .active_workers
321            .store(dispatch_workers, Ordering::Relaxed);
322        shared
323            .active_job
324            .store((&job as *const BandJob) as usize, Ordering::Release);
325        let active_slots: &[BandWorkerSlot] = &shared.slots[..dispatch_workers];
326        for slot in active_slots.iter() {
327            let next_epoch: usize = slot.epoch.load(Ordering::Relaxed).wrapping_add(1);
328            slot.epoch.store(next_epoch, Ordering::SeqCst);
329        }
330        for slot in active_slots.iter() {
331            if slot.parked.load(Ordering::SeqCst) != 0
332                && let Ok(_guard) = slot.lock.lock()
333            {
334                slot.wake.notify_one();
335            }
336        }
337        run_band_job_loop(&job);
338        let mut caller_spins: u32 = 0;
339        while job.workers_done.load(Ordering::Acquire) < dispatch_workers {
340            if caller_spins < BAND_CALLER_SPIN_LIMIT {
341                caller_spins += 1;
342                spin_loop();
343                continue;
344            }
345            if let Ok(mut guard) = shared.caller_lock.lock() {
346                shared.caller_parked.store(1, Ordering::SeqCst);
347                while job.workers_done.load(Ordering::SeqCst) < dispatch_workers {
348                    let Ok(next_guard) = shared.wake_caller.wait(guard) else {
349                        break;
350                    };
351                    guard = next_guard;
352                }
353                shared.caller_parked.store(0, Ordering::SeqCst);
354            } else {
355                spin_loop();
356            }
357        }
358        shared.active_job.store(0, Ordering::Release);
359        job.total_shaded.load(Ordering::Acquire)
360    }
361}
362
363/// Clean shutdown and thread join when a `BandWorkerPool` instance is dropped.
364#[cfg(not(target_arch = "wasm32"))]
365/// Implements [`Drop`] for [`BandWorkerPool`].
366impl Drop for BandWorkerPool {
367    /// Signals all background worker threads to exit and joins every handle.
368    ///
369    /// # Arguments
370    ///
371    /// - `&Self` - Dropping band worker pool.
372    fn drop(&mut self) {
373        let Self {
374            shared, handles, ..
375        } = self;
376        shared.shutdown.store(1, Ordering::SeqCst);
377        for slot in shared.slots.iter() {
378            if let Ok(_guard) = slot.lock.lock() {
379                slot.wake.notify_one();
380            }
381        }
382        for handle in handles.drain(..) {
383            let _: Result<(), Box<dyn Any + Send>> = handle.join();
384        }
385    }
386}
387
388/// Zero-clone SipHash-free open-addressed lookup, bounded LRU eviction, and telemetry operations for `TextLayoutCache`.
389impl TextLayoutCache {
390    /// Creates a pre-allocated cache with power-of-two slot capacity.
391    ///
392    /// # Arguments
393    ///
394    /// - `usize` - Requested slot table capacity (rounded up to a power of two).
395    ///
396    /// # Returns
397    ///
398    /// - `Self` - Pre-allocated empty text layout cache.
399    #[must_use]
400    pub(crate) fn with_capacity(slot_cap: usize) -> Self {
401        let cap: usize = slot_cap.max(16).next_power_of_two();
402        let entry_cap: usize = cap / 2;
403        Self {
404            slots: vec![EMPTY_TEXT_LAYOUT_SLOT; cap],
405            entries: Vec::with_capacity(entry_cap),
406            entry_keys: Vec::with_capacity(entry_cap),
407            entry_last_used: Vec::with_capacity(entry_cap),
408            entry_bytes: Vec::with_capacity(entry_cap),
409            resident_bytes: 0,
410            budget_bytes: TEXT_LAYOUT_CACHE_BUDGET_BYTES,
411            lru_clock: 0,
412            cache_hits: 0,
413            cache_misses: 0,
414            evictions: 0,
415        }
416    }
417
418    /// Estimates the resident heap footprint in bytes of one cached `TextLayoutResult`.
419    ///
420    /// # Arguments
421    ///
422    /// - `&TextLayoutResult` - Cached text layout entry.
423    ///
424    /// # Returns
425    ///
426    /// - `usize` - Approximate resident memory footprint in bytes.
427    #[inline]
428    #[must_use]
429    fn estimate_entry_bytes(layout: &TextLayoutResult) -> usize {
430        let mut bytes: usize = TEXT_LAYOUT_ENTRY_OVERHEAD_BYTES;
431        for line in layout.get_lines().iter() {
432            bytes = bytes
433                .saturating_add(TEXT_LINE_OVERHEAD_BYTES)
434                .saturating_add(line.get_text().len());
435        }
436        bytes
437    }
438
439    /// Returns cumulative telemetry `(hits, misses, evictions, resident_bytes)` for this text layout cache.
440    ///
441    /// # Arguments
442    ///
443    /// - `&Self` - Cache reference.
444    ///
445    /// # Returns
446    ///
447    /// - `(u64, u64, u64, usize)` - Tuple `(cache_hits, cache_misses, evictions, resident_bytes)`.
448    #[must_use]
449    pub(crate) fn stats(&self) -> (u64, u64, u64, usize) {
450        let Self {
451            cache_hits,
452            cache_misses,
453            evictions,
454            resident_bytes,
455            ..
456        } = self;
457        (*cache_hits, *cache_misses, *evictions, *resident_bytes)
458    }
459
460    /// Returns the cached `TextLayoutResult` stored at arena index `idx`, if valid.
461    ///
462    /// # Arguments
463    ///
464    /// - `&Self` - Cache reference.
465    /// - `u32` - Arena index returned by `get_or_insert_with`.
466    ///
467    /// # Returns
468    ///
469    /// - `Option<&TextLayoutResult>` - Borrowed cached layout entry.
470    #[must_use]
471    pub(crate) fn get(&self, idx: u32) -> Option<&TextLayoutResult> {
472        let Self { entries, .. } = self;
473        entries.get(idx as usize)
474    }
475
476    /// Evicts cold least-recently-used entries at frame boundaries when count or resident memory exceeds budget.
477    ///
478    /// # Arguments
479    ///
480    /// - `&Self` - Mutable cache reference.
481    pub(crate) fn evict_lru_if_needed(&mut self) {
482        let Self {
483            slots,
484            entries,
485            entry_keys,
486            entry_last_used,
487            entry_bytes,
488            resident_bytes,
489            budget_bytes,
490            evictions,
491            ..
492        } = self;
493        let effective_budget: usize = if *budget_bytes == 0 {
494            TEXT_LAYOUT_CACHE_BUDGET_BYTES
495        } else {
496            *budget_bytes
497        };
498        let count: usize = entries.len();
499        if count <= TEXT_LAYOUT_CACHE_LIMIT && *resident_bytes <= effective_budget {
500            return;
501        }
502        let target_count: usize = (TEXT_LAYOUT_CACHE_LIMIT * 3) / 4;
503        let target_bytes: usize = (effective_budget * 3) / 4;
504        let mut order: Vec<usize> = (0..count).collect();
505        order.sort_unstable_by_key(|idx: &usize| entry_last_used.get(*idx).copied().unwrap_or(0));
506        let mut keep: Vec<bool> = vec![true; count];
507        let mut remaining_count: usize = count;
508        let mut remaining_bytes: usize = *resident_bytes;
509        let mut evicted_count: usize = 0;
510        for idx in order.into_iter() {
511            if remaining_count <= target_count && remaining_bytes <= target_bytes {
512                break;
513            }
514            keep[idx] = false;
515            remaining_count = remaining_count.saturating_sub(1);
516            remaining_bytes = remaining_bytes.saturating_sub(entry_bytes[idx]);
517            evicted_count += 1;
518        }
519        if evicted_count == 0 {
520            return;
521        }
522        let mut write_idx: usize = 0;
523        let mut next_resident: usize = 0;
524        for (read_idx, &kept) in keep.iter().enumerate() {
525            if kept {
526                if write_idx != read_idx {
527                    entries.swap(write_idx, read_idx);
528                    entry_keys.swap(write_idx, read_idx);
529                    entry_last_used.swap(write_idx, read_idx);
530                    entry_bytes.swap(write_idx, read_idx);
531                }
532                next_resident = next_resident.saturating_add(entry_bytes[write_idx]);
533                write_idx += 1;
534            }
535        }
536        entries.truncate(write_idx);
537        entry_keys.truncate(write_idx);
538        entry_last_used.truncate(write_idx);
539        entry_bytes.truncate(write_idx);
540        *resident_bytes = next_resident;
541        *evictions = evictions.saturating_add(evicted_count as u64);
542        if slots.len() > TEXT_LAYOUT_CACHE_SLOTS {
543            slots.resize(TEXT_LAYOUT_CACHE_SLOTS, EMPTY_TEXT_LAYOUT_SLOT);
544        }
545        slots.fill(EMPTY_TEXT_LAYOUT_SLOT);
546        if !slots.is_empty() {
547            let mask: usize = slots.len() - 1;
548            for (slot_entry_idx, &(key_hash, width_key)) in entry_keys.iter().enumerate() {
549                let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
550                while slots[idx].entry_idx != u32::MAX {
551                    idx = (idx + 1) & mask;
552                }
553                slots[idx] = TextLayoutSlot {
554                    key_hash,
555                    width_key,
556                    entry_idx: slot_entry_idx as u32,
557                };
558            }
559        }
560    }
561
562    /// Computes the initial power-of-two probe index for `(key_hash, width_key)`.
563    ///
564    /// # Arguments
565    ///
566    /// - `u64` - Deterministic text+style hash.
567    /// - `u32` - Quantized wrap width key.
568    /// - `usize` - Power-of-two bitmask (`slots.len() - 1`).
569    ///
570    /// # Returns
571    ///
572    /// - `usize` - Starting probe index in `0..=mask`.
573    #[inline(always)]
574    #[must_use]
575    fn slot_start(key_hash: u64, width_key: u32, mask: usize) -> usize {
576        let mixed: u64 = (key_hash ^ (width_key as u64)).wrapping_mul(FX_HASH_K64);
577        ((mixed ^ (mixed >> 32)) as usize) & mask
578    }
579
580    /// Rehashes all live slots into a new power-of-two table of size `new_cap`.
581    ///
582    /// # Arguments
583    ///
584    /// - `&Self` - Mutable cache reference.
585    /// - `usize` - Target power-of-two slot capacity.
586    fn rehash(&mut self, new_cap: usize) {
587        let cap: usize = new_cap.max(TEXT_LAYOUT_CACHE_SLOTS).next_power_of_two();
588        let mask: usize = cap - 1;
589        let mut next_slots: Vec<TextLayoutSlot> = vec![EMPTY_TEXT_LAYOUT_SLOT; cap];
590        let Self { slots, .. } = self;
591        for old in slots.iter().copied() {
592            if old.entry_idx == u32::MAX {
593                continue;
594            }
595            let mut idx: usize = Self::slot_start(old.key_hash, old.width_key, mask);
596            while next_slots[idx].entry_idx != u32::MAX {
597                idx = (idx + 1) & mask;
598            }
599            next_slots[idx] = old;
600        }
601        *slots = next_slots;
602    }
603
604    /// Looks up `(key_hash, width_key)` without cloning, inserting the result of `compute` on a miss.
605    ///
606    /// # Arguments
607    ///
608    /// - `&Self` - Mutable cache reference.
609    /// - `u64` - Deterministic text+style hash.
610    /// - `u32` - Quantized wrap width key (`u32::MAX` for unbounded lines).
611    /// - `F` - Lazy layout computation invoked only on a cache miss.
612    ///
613    /// # Returns
614    ///
615    /// - `u32` - Stable arena index into `entries()` for the remainder of the current frame.
616    pub(crate) fn get_or_insert_with<F>(&mut self, key_hash: u64, width_key: u32, compute: F) -> u32
617    where
618        F: FnOnce() -> TextLayoutResult,
619    {
620        let mut empty_slot: Option<usize> = None;
621        {
622            let Self {
623                slots,
624                entry_last_used,
625                lru_clock,
626                cache_hits,
627                ..
628            } = self;
629            if !slots.is_empty() {
630                let mask: usize = slots.len() - 1;
631                let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
632                loop {
633                    let slot: TextLayoutSlot = slots[idx];
634                    if slot.entry_idx == u32::MAX {
635                        empty_slot = Some(idx);
636                        break;
637                    }
638                    if slot.key_hash == key_hash && slot.width_key == width_key {
639                        *cache_hits = cache_hits.wrapping_add(1);
640                        *lru_clock = lru_clock.wrapping_add(1);
641                        if let Some(tick) = entry_last_used.get_mut(slot.entry_idx as usize) {
642                            *tick = *lru_clock;
643                        }
644                        return slot.entry_idx;
645                    }
646                    idx = (idx + 1) & mask;
647                }
648            }
649        }
650        let measured: TextLayoutResult = compute();
651        let entry_sz: usize = Self::estimate_entry_bytes(&measured);
652        let needs_rehash: bool = {
653            let Self { slots, entries, .. } = self;
654            slots.is_empty() || (entries.len() + 1).saturating_mul(2) > slots.len()
655        };
656        if needs_rehash {
657            let next_cap: usize = {
658                let Self { slots, .. } = self;
659                if slots.is_empty() {
660                    TEXT_LAYOUT_CACHE_SLOTS
661                } else {
662                    slots.len().saturating_mul(2)
663                }
664            };
665            self.rehash(next_cap);
666            empty_slot = None;
667        }
668        let Self {
669            slots,
670            entries,
671            entry_keys,
672            entry_last_used,
673            entry_bytes,
674            resident_bytes,
675            lru_clock,
676            cache_misses,
677            ..
678        } = self;
679        *cache_misses = cache_misses.wrapping_add(1);
680        *lru_clock = lru_clock.wrapping_add(1);
681        let entry_idx: u32 = entries.len() as u32;
682        entries.push(measured);
683        entry_keys.push((key_hash, width_key));
684        entry_last_used.push(*lru_clock);
685        entry_bytes.push(entry_sz);
686        *resident_bytes = resident_bytes.saturating_add(entry_sz);
687        let target_idx: usize = match empty_slot {
688            Some(idx) => idx,
689            None => {
690                let mask: usize = slots.len() - 1;
691                let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
692                while slots[idx].entry_idx != u32::MAX {
693                    idx = (idx + 1) & mask;
694                }
695                idx
696            }
697        };
698        slots[target_idx] = TextLayoutSlot {
699            key_hash,
700            width_key,
701            entry_idx,
702        };
703        entry_idx
704    }
705}
706
707/// Precomputed rounded-clip corner coverage cache operations for `CornerMaskCache`.
708impl CornerMaskCache {
709    /// Returns the number of cached quadrant coverage masks.
710    ///
711    /// # Arguments
712    ///
713    /// - `&Self` - Cache reference.
714    ///
715    /// # Returns
716    ///
717    /// - `usize` - Count of cached quadrant masks.
718    #[must_use]
719    pub(crate) fn len(&self) -> usize {
720        let Self { entries } = self;
721        entries.len()
722    }
723
724    /// Returns the read-only slice of cached quadrant masks shared across band workers.
725    ///
726    /// # Arguments
727    ///
728    /// - `&Self` - Cache reference.
729    ///
730    /// # Returns
731    ///
732    /// - `&[CachedCornerMask]` - Contiguous cached corner mask slice.
733    #[must_use]
734    pub(crate) fn entries(&self) -> &[CachedCornerMask] {
735        let Self { entries } = self;
736        entries.as_slice()
737    }
738
739    /// Clears all cached corner masks when exceeding the bounded retention limit.
740    ///
741    /// # Arguments
742    ///
743    /// - `&Self` - Mutable cache reference.
744    pub(crate) fn clear(&mut self) {
745        let Self { entries } = self;
746        entries.clear();
747    }
748
749    /// Builds an exact `0..=16` 4x4 RGSS coverage grid and per-row span table for one corner quadrant.
750    ///
751    /// # Arguments
752    ///
753    /// - `f32` - Clamped physical corner radius (`> 0.25`).
754    /// - `u8` - Quadrant index (`0 = TL`, `1 = TR`, `2 = BR`, `3 = BL`).
755    /// - `bool` - True when 4x4 RGSS anti-aliasing is active.
756    ///
757    /// # Returns
758    ///
759    /// - `CachedCornerMask` - Precomputed coverage grid and row spans.
760    #[must_use]
761    fn build_quadrant(radius: f32, quadrant: u8, aa_enabled: bool) -> CachedCornerMask {
762        let dim: usize = (radius + 1.0).ceil().max(1.0) as usize;
763        let dim_f: f32 = dim as f32;
764        let half_extent: f32 = dim_f + 64.0;
765        let cx_lim: f32 = half_extent - radius;
766        let r_in: f32 = radius - 1.0;
767        let r_in_sq: f32 = r_in * r_in;
768        let r_out: f32 = radius + 1.0;
769        let r_out_sq: f32 = r_out * r_out;
770        let r_sq: f32 = radius * radius;
771        let mut cov: Vec<u8> = vec![16; dim * dim];
772        let mut row_spans: Vec<CornerMaskRowSpan> = Vec::with_capacity(dim);
773        let is_left: bool = quadrant == 0 || quadrant == 3;
774        let is_top: bool = quadrant == 0 || quadrant == 1;
775        for my in 0..dim {
776            let py: f32 = if is_top {
777                (my as f32) + 0.5 - half_extent
778            } else {
779                (my as f32) + 0.5 + (half_extent - dim_f)
780            };
781            let qy: f32 = py.abs() - cx_lim;
782            let row_off: usize = my * dim;
783            for mx in 0..dim {
784                let px: f32 = if is_left {
785                    (mx as f32) + 0.5 - half_extent
786                } else {
787                    (mx as f32) + 0.5 + (half_extent - dim_f)
788                };
789                let qx: f32 = px.abs() - cx_lim;
790                let hits: u8 = if qx <= 0.0 || qy <= 0.0 {
791                    let dist: f32 = qx.max(qy) - radius;
792                    if dist <= -1.0 {
793                        16
794                    } else if dist >= 1.0 {
795                        0
796                    } else if !aa_enabled {
797                        if dist <= 0.0 { 16 } else { 0 }
798                    } else {
799                        let c: f32 = rounded_box_supersampled_coverage(
800                            px,
801                            py,
802                            half_extent,
803                            half_extent,
804                            radius,
805                            0.0,
806                        )
807                        .0;
808                        (c * 16.0).round() as u8
809                    }
810                } else {
811                    let d_sq: f32 = qx * qx + qy * qy;
812                    if r_in >= 0.0 && d_sq <= r_in_sq {
813                        16
814                    } else if d_sq >= r_out_sq {
815                        0
816                    } else if !aa_enabled {
817                        if d_sq <= r_sq { 16 } else { 0 }
818                    } else {
819                        let c: f32 = rounded_box_supersampled_coverage(
820                            px,
821                            py,
822                            half_extent,
823                            half_extent,
824                            radius,
825                            0.0,
826                        )
827                        .0;
828                        (c * 16.0).round() as u8
829                    }
830                };
831                cov[row_off + mx] = hits;
832            }
833            let row_slice: &[u8] = &cov[row_off..row_off + dim];
834            let span: CornerMaskRowSpan = if is_left {
835                let dirty_end: usize = row_slice
836                    .iter()
837                    .rposition(|&c: &u8| c < 16)
838                    .map(|idx: usize| idx + 1)
839                    .unwrap_or(0);
840                let ext_end: usize = row_slice
841                    .iter()
842                    .take(dirty_end)
843                    .take_while(|&&c: &&u8| c == 0)
844                    .count();
845                CornerMaskRowSpan {
846                    ext_start: 0,
847                    ext_end: ext_end as u16,
848                    aa_start: ext_end as u16,
849                    aa_end: dirty_end as u16,
850                    dirty_start: 0,
851                    dirty_end: dirty_end as u16,
852                }
853            } else {
854                let dirty_start: usize = row_slice.iter().position(|&c: &u8| c < 16).unwrap_or(dim);
855                let trailing_zeros: usize = row_slice[dirty_start..]
856                    .iter()
857                    .rev()
858                    .take_while(|&&c: &&u8| c == 0)
859                    .count();
860                let ext_start: usize = dim - trailing_zeros;
861                CornerMaskRowSpan {
862                    ext_start: ext_start as u16,
863                    ext_end: dim as u16,
864                    aa_start: dirty_start as u16,
865                    aa_end: ext_start.max(dirty_start) as u16,
866                    dirty_start: dirty_start as u16,
867                    dirty_end: dim as u16,
868                }
869            };
870            row_spans.push(span);
871        }
872        CachedCornerMask {
873            radius_bits: radius.to_bits(),
874            quadrant,
875            aa_enabled,
876            dim: dim as u16,
877            cov,
878            row_spans,
879        }
880    }
881
882    /// Returns the cached mask index for `(radius, quadrant, aa_enabled)`, building and caching it on a miss.
883    ///
884    /// # Arguments
885    ///
886    /// - `&Self` - Mutable cache reference.
887    /// - `f32` - Clamped physical corner radius.
888    /// - `u8` - Quadrant index (`0 = TL`, `1 = TR`, `2 = BR`, `3 = BL`).
889    /// - `bool` - True when anti-aliasing is enabled.
890    ///
891    /// # Returns
892    ///
893    /// - `u32` - Index into `entries()`.
894    fn get_or_build(&mut self, radius: f32, quadrant: u8, aa_enabled: bool) -> u32 {
895        let bits: u32 = radius.to_bits();
896        let Self { entries } = self;
897        for (idx, entry) in entries.iter().enumerate() {
898            if entry.radius_bits == bits
899                && entry.quadrant == quadrant
900                && entry.aa_enabled == aa_enabled
901            {
902                return idx as u32;
903            }
904        }
905        let idx: u32 = entries.len() as u32;
906        entries.push(Self::build_quadrant(radius, quadrant, aa_enabled));
907        idx
908    }
909
910    /// Resolves cached quadrant mask IDs `[tl, tr, br, bl]` for an integer-snapped `RoundedClipMask`.
911    ///
912    /// # Arguments
913    ///
914    /// - `&Self` - Mutable cache reference.
915    /// - `Rect` - Physical clip rectangle.
916    /// - `CornerRadius` - Physical corner radii.
917    /// - `AntialiasingMode` - Active anti-aliasing policy.
918    ///
919    /// # Returns
920    ///
921    /// - `[u32; 4]` - Quadrant mask IDs (`u32::MAX` when inactive or uncached).
922    pub(crate) fn resolve_quadrants(
923        &mut self,
924        rect: Rect,
925        radius: CornerRadius,
926        aa: AntialiasingMode,
927    ) -> [u32; 4] {
928        let mut ids: [u32; 4] = [u32::MAX; 4];
929        let half_w: f32 = rect.get_width() * 0.5;
930        let half_h: f32 = rect.get_height() * 0.5;
931        let max_r: f32 = half_w.min(half_h).max(0.0);
932        if max_r <= 0.25 {
933            return ids;
934        }
935        let x0: f32 = rect.get_x();
936        let y0: f32 = rect.get_y();
937        let x1: f32 = rect.right();
938        let y1: f32 = rect.bottom();
939        if (x0 - x0.round()).abs() > 1e-4
940            || (y0 - y0.round()).abs() > 1e-4
941            || (x1 - x1.round()).abs() > 1e-4
942            || (y1 - y1.round()).abs() > 1e-4
943        {
944            return ids;
945        }
946        let aa_enabled: bool = aa != AntialiasingMode::None;
947        let radii: [f32; 4] = [
948            radius.get_top_left().min(max_r),
949            radius.get_top_right().min(max_r),
950            radius.get_bottom_right().min(max_r),
951            radius.get_bottom_left().min(max_r),
952        ];
953        for (q, r) in radii.into_iter().enumerate() {
954            if r > 0.25 && r + 1.5 < half_w && r + 1.5 < half_h {
955                let dim: u32 = (r + 1.0).ceil() as u32;
956                if dim > 0 && dim <= CORNER_MASK_MAX_DIM {
957                    ids[q] = self.get_or_build(r, q as u8, aa_enabled);
958                }
959            }
960        }
961        ids
962    }
963}
964
965/// Multi-core lossless analytical-SDF and tile-band software rasterizer methods for `SoftwareRenderer`.
966impl SoftwareRenderer {
967    /// Creates a software renderer configured for `width x height` physical pixels.
968    ///
969    /// # Arguments
970    ///
971    /// - `u32` - Physical width.
972    /// - `u32` - Physical height.
973    /// - `RenderConfig` - Rendering configuration.
974    ///
975    /// # Returns
976    ///
977    /// - `Self` - Ready-to-draw software renderer.
978    #[must_use]
979    pub fn with_config(width: u32, height: u32, config: RenderConfig) -> Self {
980        Self::with_font_provider(width, height, config, NativeSystemFont::deterministic())
981    }
982
983    /// Creates a software renderer configured with an explicit `NativeSystemFont` provider.
984    ///
985    /// # Arguments
986    ///
987    /// - `u32` - Physical width.
988    /// - `u32` - Physical height.
989    /// - `RenderConfig` - Rendering configuration.
990    /// - `NativeSystemFont` - Native OS or deterministic font provider.
991    ///
992    /// # Returns
993    ///
994    /// - `Self` - Ready-to-draw software renderer.
995    #[must_use]
996    pub fn with_font_provider(
997        width: u32,
998        height: u32,
999        config: RenderConfig,
1000        font_provider: NativeSystemFont,
1001    ) -> Self {
1002        Self {
1003            framebuffer: Framebuffer::allocate(width, height),
1004            glyph_atlas: GlyphAtlas::default(),
1005            font_provider,
1006            measurer: DeterministicTextMeasurer,
1007            text_layout_cache: TextLayoutCache::with_capacity(TEXT_LAYOUT_CACHE_SLOTS),
1008            clip_stack: Vec::with_capacity(8),
1009            rounded_clip_stack: Vec::with_capacity(8),
1010            antialiasing: config.get_antialiasing(),
1011            tile_size: config.get_tile_size().max(16),
1012            base_cache_width: 0,
1013            base_cache_height: 0,
1014            base_cache_hash: 0,
1015            prev_base_hash: 0,
1016            base_cache_pixels: Vec::new(),
1017            prepped_scratch: Vec::with_capacity(64),
1018            rounded_clips_scratch: Vec::with_capacity(16),
1019            positioned_glyphs_scratch: Vec::with_capacity(256),
1020            line_glyphs_scratch: Vec::with_capacity(64),
1021            caret_rects_scratch: Vec::with_capacity(4),
1022            corner_mask_cache: CornerMaskCache::default(),
1023            prev_portal_bounds: None,
1024            prev_portal_scrim: None,
1025            prepped_bounds: None,
1026            prepped_fg_bounds: None,
1027            clip_scope_scratch: Vec::with_capacity(8),
1028            cached_scrim_color: None,
1029            cached_scrim_luts: None,
1030            serial_dispatches: 0,
1031            parallel_dispatches: 0,
1032        }
1033    }
1034
1035    /// Detects whether `prepped_scratch[0]` is a pure full-viewport borderless unrounded translucent scrim.
1036    ///
1037    /// # Arguments
1038    ///
1039    /// - `&[DrawCommand]` - Full display list commands.
1040    /// - `&[PreppedCommand]` - Prepped portal commands.
1041    /// - `(u32, u32, f32)` - Tuple `(phys_w, phys_h, scale)`.
1042    ///
1043    /// # Returns
1044    ///
1045    /// - `Option<Color>` - Full-viewport translucent scrim color if fusable into backdrop restore.
1046    #[must_use]
1047    fn detect_full_viewport_scrim(
1048        commands: &[DrawCommand],
1049        prepped: &[PreppedCommand],
1050        dims: (u32, u32, f32),
1051    ) -> Option<Color> {
1052        let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
1053        let first: &PreppedCommand = prepped.first()?;
1054        if first.get_cmd_index() == usize::MAX || first.get_rounded_clip_len() != 0 {
1055            return None;
1056        }
1057        let clip: Rect = first.get_active_clip();
1058        let fw: f32 = phys_w as f32;
1059        let fh: f32 = phys_h as f32;
1060        if clip.get_x() > 0.0 || clip.get_y() > 0.0 || clip.right() < fw || clip.bottom() < fh {
1061            return None;
1062        }
1063        if let DrawCommand::FillRoundedRect {
1064            rect,
1065            color,
1066            radius,
1067            border,
1068        } = &commands[first.get_cmd_index()]
1069        {
1070            let sa: u8 = color.get_a();
1071            if sa > 0 && sa < 255 && radius.max_radius() <= 0.0 && border.get_width() <= 0.0 {
1072                let phys: Rect = snap_physical_rect(*rect, scale);
1073                if phys.get_x() <= 0.0
1074                    && phys.get_y() <= 0.0
1075                    && phys.right() >= fw
1076                    && phys.bottom() >= fh
1077                {
1078                    return Some(*color);
1079                }
1080            }
1081        }
1082        None
1083    }
1084
1085    /// Computes the clamped integer physical pixel area covered by `rect` within `(phys_w, phys_h)`.
1086    ///
1087    /// # Arguments
1088    ///
1089    /// - `Rect` - Physical rectangle to measure.
1090    /// - `u32` - Surface physical width.
1091    /// - `u32` - Surface physical height.
1092    ///
1093    /// # Returns
1094    ///
1095    /// - `usize` - Clamped integer pixel count.
1096    #[must_use]
1097    fn rect_pixel_area(rect: Rect, phys_w: u32, phys_h: u32) -> usize {
1098        let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(phys_w);
1099        let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(phys_h);
1100        let x1: u32 = (rect.right().ceil().max(0.0) as u32).clamp(x0, phys_w);
1101        let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).clamp(y0, phys_h);
1102        ((x1 - x0) as usize).saturating_mul((y1 - y0) as usize)
1103    }
1104
1105    /// Rasterizes `display_list` into the internal `Framebuffer` clipped to `damage` using multi-core parallel horizontal bands and dirty-rect scoped portal backdrop caching.
1106    ///
1107    /// # Arguments
1108    ///
1109    /// - `&Self` - Mutable software renderer.
1110    /// - `&DisplayList` - Backend-agnostic draw command stream.
1111    /// - `DamageRegion` - Optional dirty damage region for partial rasterization.
1112    ///
1113    /// # Returns
1114    ///
1115    /// - `(usize, usize)` - Tuple of `(tiles_updated, pixels_shaded)`.
1116    pub fn render(&mut self, display_list: &DisplayList, damage: DamageRegion) -> (usize, usize) {
1117        let scale: f32 = display_list.get_scale_factor().max(0.5);
1118        let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
1119        let phys_h: u32 =
1120            ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
1121        let resized: bool = self.get_mut_framebuffer().resize(phys_w, phys_h);
1122        if resized {
1123            self.set_base_cache_hash(0);
1124            self.set_prev_base_hash(0);
1125            self.set_base_cache_width(0);
1126            self.set_base_cache_height(0);
1127            self.set_prev_portal_bounds(None);
1128            self.set_prev_portal_scrim(None);
1129        }
1130        let effective_damage: DamageRegion = if resized {
1131            DamageRegion::full()
1132        } else {
1133            damage
1134        };
1135        let (norm_rects, norm_count): ([Rect; 8], usize) =
1136            effective_damage.normalized_rects(phys_w, phys_h);
1137        if norm_count == 0 {
1138            return (0, 0);
1139        }
1140        let tile_sz: u32 = self.get_tile_size().max(16);
1141        let commands: &[DrawCommand] = display_list.get_commands().as_slice();
1142        let split: usize = display_list.get_portal_split_index().min(commands.len());
1143        let has_portals: bool = split > 0 && split < commands.len();
1144        if norm_count > 1 {
1145            let mut sum_area: usize = 0;
1146            for sub in norm_rects.iter().take(norm_count) {
1147                sum_area = sum_area.saturating_add(Self::rect_pixel_area(*sub, phys_w, phys_h));
1148            }
1149            let union_area: usize = effective_damage
1150                .resolve(phys_w, phys_h)
1151                .map_or(0, |u: Rect| Self::rect_pixel_area(u, phys_w, phys_h));
1152            if sum_area.saturating_mul(4) < union_area.saturating_mul(3) {
1153                if !has_portals {
1154                    self.set_base_cache_hash(0);
1155                    self.set_prev_base_hash(0);
1156                }
1157                self.set_prev_portal_bounds(None);
1158                self.set_prev_portal_scrim(None);
1159                let mut total_tiles: usize = 0;
1160                let mut total_shaded: usize = 0;
1161                for sub_clip in norm_rects.iter().take(norm_count).copied() {
1162                    let tx: usize =
1163                        ((sub_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
1164                    let ty: usize =
1165                        ((sub_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
1166                    total_tiles = total_tiles.saturating_add(tx.saturating_mul(ty));
1167                    self.prepare_frame_range(
1168                        display_list,
1169                        (0, commands.len()),
1170                        sub_clip,
1171                        (phys_w, phys_h, scale),
1172                    );
1173                    let shaded: usize = self.execute_prepared_bands(
1174                        commands,
1175                        sub_clip,
1176                        (phys_w, phys_h, scale),
1177                        (false, None, 0),
1178                    );
1179                    total_shaded = total_shaded.saturating_add(shaded);
1180                }
1181                return (total_tiles, total_shaded);
1182            }
1183        }
1184        let root_clip: Rect = if norm_count == 1 {
1185            norm_rects[0]
1186        } else {
1187            let Some(resolved) = effective_damage.resolve(phys_w, phys_h) else {
1188                return (0, 0);
1189            };
1190            resolved
1191        };
1192        let tiles_x: usize = ((root_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
1193        let tiles_y: usize = ((root_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
1194        let tiles_updated: usize = tiles_x.saturating_mul(tiles_y);
1195        let is_full_frame: bool = root_clip.get_x() <= 0.0
1196            && root_clip.get_y() <= 0.0
1197            && root_clip.get_width() >= (phys_w as f32)
1198            && root_clip.get_height() >= (phys_h as f32);
1199        if has_portals && is_full_frame {
1200            let base_hash: u64 = display_list.base_layer_hash();
1201            let fb_len: usize = self.get_framebuffer().get_pixels().len();
1202            let cache_hit: bool = base_hash != 0
1203                && self.get_base_cache_hash() == base_hash
1204                && self.get_base_cache_width() == phys_w
1205                && self.get_base_cache_height() == phys_h
1206                && self.get_base_cache_pixels().len() == fb_len;
1207            if cache_hit {
1208                self.prepare_frame_range(
1209                    display_list,
1210                    (split, commands.len()),
1211                    root_clip,
1212                    (phys_w, phys_h, scale),
1213                );
1214                let cur_scrim: Option<Color> = Self::detect_full_viewport_scrim(
1215                    commands,
1216                    self.get_prepped_scratch().as_slice(),
1217                    (phys_w, phys_h, scale),
1218                );
1219                let cur_fg_bounds: Option<Rect> = if cur_scrim.is_some() {
1220                    self.get_prepped_fg_bounds()
1221                } else {
1222                    self.get_prepped_bounds()
1223                };
1224                let prev_scrim: Option<Color> = self.get_prev_portal_scrim();
1225                let prev_bounds: Option<Rect> = self.get_prev_portal_bounds();
1226                self.set_prev_portal_scrim(cur_scrim);
1227                self.set_prev_portal_bounds(cur_fg_bounds);
1228                let prepped_start: usize = usize::from(cur_scrim.is_some());
1229                let (portal_rects, portal_count): ([Rect; 8], usize) = if cur_scrim == prev_scrim {
1230                    let mut portal_damage: DamageRegion = DamageRegion::default();
1231                    if let Some(prev_r) = prev_bounds {
1232                        portal_damage.add_rect(prev_r);
1233                    }
1234                    if let Some(cur_r) = cur_fg_bounds {
1235                        portal_damage.add_rect(cur_r);
1236                    }
1237                    portal_damage.normalized_rects(phys_w, phys_h)
1238                } else {
1239                    let mut full_arr: [Rect; 8] = [Rect::default(); 8];
1240                    full_arr[0] = root_clip;
1241                    (full_arr, 1)
1242                };
1243                if portal_count == 0 {
1244                    return (tiles_updated, 1);
1245                }
1246                let mut total_portal_shaded: usize = 0;
1247                for dirty_clip in portal_rects.iter().take(portal_count).copied() {
1248                    let scrim_shaded: usize = if cur_scrim.is_some() {
1249                        Self::rect_pixel_area(dirty_clip, phys_w, phys_h)
1250                    } else {
1251                        0
1252                    };
1253                    let band_shaded: usize = self.execute_prepared_bands(
1254                        commands,
1255                        dirty_clip,
1256                        (phys_w, phys_h, scale),
1257                        (true, cur_scrim, prepped_start),
1258                    );
1259                    total_portal_shaded = total_portal_shaded
1260                        .saturating_add(scrim_shaded)
1261                        .saturating_add(band_shaded);
1262                }
1263                return (tiles_updated, total_portal_shaded.max(1));
1264            }
1265            self.prepare_frame_range(display_list, (0, split), root_clip, (phys_w, phys_h, scale));
1266            let base_shaded: usize = self.execute_prepared_bands(
1267                commands,
1268                root_clip,
1269                (phys_w, phys_h, scale),
1270                (false, None, 0),
1271            );
1272            let base_stable: bool = base_hash != 0 && self.get_prev_base_hash() == base_hash;
1273            self.set_prev_base_hash(base_hash);
1274            if base_stable {
1275                let Self {
1276                    framebuffer,
1277                    base_cache_pixels,
1278                    base_cache_width,
1279                    base_cache_height,
1280                    base_cache_hash,
1281                    ..
1282                } = self;
1283                let src_pixels: &[u8] = framebuffer.get_pixels().as_slice();
1284                if base_cache_pixels.len() != src_pixels.len() {
1285                    base_cache_pixels.resize(src_pixels.len(), 0);
1286                }
1287                base_cache_pixels.copy_from_slice(src_pixels);
1288                *base_cache_width = phys_w;
1289                *base_cache_height = phys_h;
1290                *base_cache_hash = base_hash;
1291            }
1292            self.prepare_frame_range(
1293                display_list,
1294                (split, commands.len()),
1295                root_clip,
1296                (phys_w, phys_h, scale),
1297            );
1298            let cur_scrim: Option<Color> = Self::detect_full_viewport_scrim(
1299                commands,
1300                self.get_prepped_scratch().as_slice(),
1301                (phys_w, phys_h, scale),
1302            );
1303            let cur_fg_bounds: Option<Rect> = if cur_scrim.is_some() {
1304                self.get_prepped_fg_bounds()
1305            } else {
1306                self.get_prepped_bounds()
1307            };
1308            self.set_prev_portal_scrim(cur_scrim);
1309            self.set_prev_portal_bounds(cur_fg_bounds);
1310            let portal_shaded: usize = self.execute_prepared_bands(
1311                commands,
1312                root_clip,
1313                (phys_w, phys_h, scale),
1314                (false, None, 0),
1315            );
1316            return (tiles_updated, base_shaded.saturating_add(portal_shaded));
1317        }
1318        if !has_portals {
1319            self.set_base_cache_hash(0);
1320            self.set_prev_base_hash(0);
1321        }
1322        self.set_prev_portal_bounds(None);
1323        self.set_prev_portal_scrim(None);
1324        self.prepare_frame_range(
1325            display_list,
1326            (0, commands.len()),
1327            root_clip,
1328            (phys_w, phys_h, scale),
1329        );
1330        let pixels_shaded: usize = self.execute_prepared_bands(
1331            commands,
1332            root_clip,
1333            (phys_w, phys_h, scale),
1334            (false, None, 0),
1335        );
1336        (tiles_updated, pixels_shaded)
1337    }
1338
1339    /// Executes prepared scratch buffers across horizontal bands with optional dirty-rect backdrop restore, small-damage single-thread fast path, and fused scrim LUT.
1340    ///
1341    /// # Arguments
1342    ///
1343    /// - `&Self` - Mutable software renderer holding populated scratch buffers.
1344    /// - `&[DrawCommand]` - Full frame draw command slice.
1345    /// - `Rect` - Root physical damage clip rectangle.
1346    /// - `(u32, u32, f32)` - Tuple `(phys_w, phys_h, scale)`.
1347    /// - `(bool, Option<Color>, usize)` - Tuple `(restore_base_cache, fused_scrim_color, prepped_start)`.
1348    ///
1349    /// # Returns
1350    ///
1351    /// - `usize` - Total shaded pixel count.
1352    fn execute_prepared_bands(
1353        &mut self,
1354        commands: &[DrawCommand],
1355        root_clip: Rect,
1356        dims: (u32, u32, f32),
1357        restore_opts: (bool, Option<Color>, usize),
1358    ) -> usize {
1359        let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
1360        let (restore_base_cache, scrim_color, prepped_start): (bool, Option<Color>, usize) =
1361            restore_opts;
1362        let clip_x0: u32 = (root_clip.get_x().floor().max(0.0) as u32).min(phys_w);
1363        let clip_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
1364        let clip_x1: u32 = (root_clip.right().ceil().max(0.0) as u32).clamp(clip_x0, phys_w);
1365        let clip_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).clamp(clip_y0, phys_h);
1366        let clip_w: u32 = clip_x1.saturating_sub(clip_x0);
1367        let clip_h: u32 = clip_y1.saturating_sub(clip_y0);
1368        if clip_w == 0 || clip_h == 0 {
1369            return 0;
1370        }
1371        let Self {
1372            framebuffer,
1373            glyph_atlas,
1374            base_cache_pixels,
1375            prepped_scratch,
1376            positioned_glyphs_scratch,
1377            caret_rects_scratch,
1378            rounded_clips_scratch,
1379            corner_mask_cache,
1380            antialiasing,
1381            cached_scrim_color,
1382            cached_scrim_luts,
1383            serial_dispatches,
1384            parallel_dispatches,
1385            ..
1386        } = self;
1387        let aa: AntialiasingMode = *antialiasing;
1388        let clamped_start: usize = prepped_start.min(prepped_scratch.len());
1389        let prepped_slice: &[PreppedCommand] = &prepped_scratch.as_slice()[clamped_start..];
1390        if prepped_slice.is_empty() && !restore_base_cache {
1391            return 0;
1392        }
1393        let scrim_luts_ref: Option<&RgbaLutQuad> = if let Some(scrim_c) = scrim_color {
1394            if *cached_scrim_color != Some(scrim_c) || cached_scrim_luts.is_none() {
1395                *cached_scrim_color = Some(scrim_c);
1396                *cached_scrim_luts = Some(Box::new(build_linear_blend_luts(scrim_c)));
1397            }
1398            cached_scrim_luts.as_deref()
1399        } else {
1400            None
1401        };
1402        let glyphs_slice: &[PositionedGlyph] = positioned_glyphs_scratch.as_slice();
1403        let caret_rects_slice: &[Rect] = caret_rects_scratch.as_slice();
1404        let rounded_clips_slice: &[RoundedClipMask] = rounded_clips_scratch.as_slice();
1405        let corner_masks_slice: &[CachedCornerMask] = corner_mask_cache.entries();
1406        let atlas_ref: &GlyphAtlas = glyph_atlas;
1407        let restore_spec: BandRestoreSpec<'_> = BandRestoreSpec {
1408            base_pixels: if restore_base_cache {
1409                Some(base_cache_pixels.as_slice())
1410            } else {
1411                None
1412            },
1413            x0: clip_x0,
1414            x1: clip_x1,
1415            scrim_luts: scrim_luts_ref,
1416        };
1417        #[cfg(not(target_arch = "wasm32"))]
1418        {
1419            let pixel_area: usize = (clip_w as usize).saturating_mul(clip_h as usize);
1420            let many_cmds: bool =
1421                prepped_slice.len() >= BAND_DISPATCH_MIN_CMDS || restore_base_cache;
1422            let large_area: bool = pixel_area >= BAND_DISPATCH_MIN_PIXELS.saturating_mul(2);
1423            let enough_work: bool = many_cmds || large_area;
1424            if pixel_area >= SMALL_DAMAGE_SINGLE_THREAD_PIXELS
1425                && clip_h >= BAND_DISPATCH_MIN_HEIGHT
1426                && enough_work
1427            {
1428                let effective_area: usize =
1429                    pixel_area.saturating_add(rounded_clips_slice.len().saturating_mul(16_384));
1430                if effective_area >= BAND_DISPATCH_MIN_PIXELS.saturating_mul(2) {
1431                    let pool: &BandWorkerPool = global_band_worker_pool();
1432                    let desired_threads: usize =
1433                        (effective_area / BAND_DISPATCH_MIN_PIXELS).clamp(1, pool.total_threads());
1434                    let strip_count: usize = (desired_threads.saturating_mul(2))
1435                        .min((clip_h / 24) as usize)
1436                        .max(1);
1437                    if strip_count > 1 && desired_threads > 1 {
1438                        *parallel_dispatches = parallel_dispatches.wrapping_add(1);
1439                        return pool.execute(
1440                            framebuffer,
1441                            (
1442                                clip_y0,
1443                                clip_y1,
1444                                strip_count,
1445                                desired_threads.saturating_sub(1),
1446                            ),
1447                            (commands, prepped_slice),
1448                            (
1449                                glyphs_slice,
1450                                caret_rects_slice,
1451                                rounded_clips_slice,
1452                                corner_masks_slice,
1453                            ),
1454                            atlas_ref,
1455                            (scale, aa, restore_spec),
1456                        );
1457                    }
1458                }
1459            }
1460        }
1461        #[cfg(target_arch = "wasm32")]
1462        let _: &mut u64 = parallel_dispatches;
1463        *serial_dispatches = serial_dispatches.wrapping_add(1);
1464        let row_stride: usize = (phys_w as usize) * 4;
1465        let start_byte: usize = (clip_y0 as usize) * row_stride;
1466        let end_byte: usize = (clip_y1 as usize) * row_stride;
1467        let Some(slice) = framebuffer.get_mut_pixels().get_mut(start_byte..end_byte) else {
1468            return 0;
1469        };
1470        if let Some(src_buf) = restore_spec.base_pixels
1471            && let Some(src_slice) = src_buf.get(start_byte..end_byte)
1472        {
1473            restore_band_strip(
1474                slice,
1475                src_slice,
1476                (
1477                    row_stride,
1478                    clip_h as usize,
1479                    (restore_spec.x0 as usize) * 4,
1480                    (restore_spec.x1.saturating_sub(restore_spec.x0) as usize) * 4,
1481                ),
1482                restore_spec.scrim_luts,
1483            );
1484        }
1485        let mut band: PixelBand<'_> = PixelBand {
1486            width: phys_w,
1487            y_offset: clip_y0,
1488            height: clip_h,
1489            pixels: slice,
1490        };
1491        Self::render_band(
1492            &mut band,
1493            commands,
1494            prepped_slice,
1495            (
1496                glyphs_slice,
1497                caret_rects_slice,
1498                rounded_clips_slice,
1499                corner_masks_slice,
1500            ),
1501            atlas_ref,
1502            (scale, aa),
1503        )
1504    }
1505
1506    /// Runs a lightweight main-thread pre-pass over `commands[range.0..range.1]` into reusable scratch buffers to resolve clips, opaque shadow cutouts, cached text layouts, and pre-positioned glyphs.
1507    ///
1508    /// # Arguments
1509    ///
1510    /// - `&Self` - Mutable software renderer.
1511    /// - `&DisplayList` - Incoming command stream.
1512    /// - `(usize, usize)` - Command slice `(start_idx, end_idx)` into `display_list.get_commands()`.
1513    /// - `Rect` - Root physical damage clip rectangle.
1514    /// - `(u32, u32, f32)` - Tuple `(phys_w, phys_h, scale)`.
1515    fn prepare_frame_range(
1516        &mut self,
1517        display_list: &DisplayList,
1518        range: (usize, usize),
1519        root_clip: Rect,
1520        dims: (u32, u32, f32),
1521    ) {
1522        let (start_idx, end_idx): (usize, usize) = range;
1523        let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
1524        let commands: &[DrawCommand] = display_list.get_commands().as_slice();
1525        let clamped_end: usize = end_idx.min(commands.len());
1526        let clamped_start: usize = start_idx.min(clamped_end);
1527        let Self {
1528            glyph_atlas,
1529            font_provider,
1530            measurer,
1531            text_layout_cache,
1532            clip_stack,
1533            rounded_clip_stack,
1534            prepped_scratch: prepped,
1535            rounded_clips_scratch: rounded_clips,
1536            positioned_glyphs_scratch: positioned_glyphs,
1537            line_glyphs_scratch: line_scratch,
1538            caret_rects_scratch: caret_rects,
1539            corner_mask_cache,
1540            prepped_bounds,
1541            prepped_fg_bounds,
1542            clip_scope_scratch: clip_scopes,
1543            antialiasing,
1544            ..
1545        } = self;
1546        let aa: AntialiasingMode = *antialiasing;
1547        prepped.clear();
1548        prepped.reserve(clamped_end - clamped_start);
1549        *prepped_bounds = None;
1550        *prepped_fg_bounds = None;
1551        rounded_clips.clear();
1552        positioned_glyphs.clear();
1553        caret_rects.clear();
1554        clip_stack.clear();
1555        clip_stack.push(root_clip);
1556        rounded_clip_stack.clear();
1557        rounded_clip_stack.push(None);
1558        let root_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
1559        let root_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
1560        clip_scopes.clear();
1561        clip_scopes.push((root_y0, root_y1, None));
1562        let mut empty_clip_depth: usize = 0;
1563        let mut has_first_cmd: bool = false;
1564        glyph_atlas.evict_if_over_budget();
1565        glyph_atlas.set_slots_pinned(true);
1566        text_layout_cache.evict_lru_if_needed();
1567        if corner_mask_cache.len() > CORNER_MASK_CACHE_LIMIT {
1568            corner_mask_cache.clear();
1569        }
1570        for (offset, cmd) in commands[clamped_start..clamped_end].iter().enumerate() {
1571            if empty_clip_depth > 0 {
1572                match cmd {
1573                    DrawCommand::PushClip(_) | DrawCommand::PushRoundedClip { .. } => {
1574                        empty_clip_depth += 1;
1575                    }
1576                    DrawCommand::PopClip => {
1577                        empty_clip_depth -= 1;
1578                    }
1579                    _ => {}
1580                }
1581                continue;
1582            }
1583            let cmd_index: usize = clamped_start + offset;
1584            let active_clip: Rect = clip_stack.last().copied().unwrap_or(root_clip);
1585            match cmd {
1586                DrawCommand::PushClip(rect) => {
1587                    let phys: Rect = snap_physical_rect(*rect, scale);
1588                    let Some(next) = active_clip.intersect(phys) else {
1589                        empty_clip_depth = 1;
1590                        continue;
1591                    };
1592                    let nx0: u32 = (next.get_x().floor().max(0.0) as u32).min(phys_w);
1593                    let nx1: u32 = (next.right().ceil().max(0.0) as u32).min(phys_w);
1594                    let ny0: u32 = (next.get_y().floor().max(0.0) as u32).min(phys_h);
1595                    let ny1: u32 = (next.bottom().ceil().max(0.0) as u32).min(phys_h);
1596                    if nx0 >= nx1 || ny0 >= ny1 {
1597                        empty_clip_depth = 1;
1598                        continue;
1599                    }
1600                    clip_stack.push(next);
1601                    rounded_clip_stack.push(None);
1602                    let (parent_y0, parent_y1, _): (u32, u32, Option<usize>) = clip_scopes
1603                        .last()
1604                        .copied()
1605                        .unwrap_or((root_y0, root_y1, None));
1606                    if ny0 > parent_y0 || ny1 < parent_y1 {
1607                        let slot_idx: usize = prepped.len();
1608                        prepped.push(PreppedCommand {
1609                            cmd_index: usize::MAX,
1610                            active_clip: next,
1611                            y0: ny0,
1612                            y1: ny1,
1613                            opaque_cutout_h: Rect::default(),
1614                            opaque_cutout_v: Rect::default(),
1615                            glyph_run_start: 0,
1616                            glyph_run_len: 0,
1617                            caret_rect_idx: u32::MAX,
1618                            rounded_clip_start: 0,
1619                            rounded_clip_len: 0,
1620                            skip_delta: 1,
1621                        });
1622                        clip_scopes.push((ny0, ny1, Some(slot_idx)));
1623                    } else {
1624                        clip_scopes.push((parent_y0, parent_y1, None));
1625                    }
1626                }
1627                DrawCommand::PushRoundedClip { rect, radius } => {
1628                    let phys: Rect = snap_physical_rect(*rect, scale);
1629                    let Some(next) = active_clip.intersect(phys) else {
1630                        empty_clip_depth = 1;
1631                        continue;
1632                    };
1633                    let nx0: u32 = (next.get_x().floor().max(0.0) as u32).min(phys_w);
1634                    let nx1: u32 = (next.right().ceil().max(0.0) as u32).min(phys_w);
1635                    let ny0: u32 = (next.get_y().floor().max(0.0) as u32).min(phys_h);
1636                    let ny1: u32 = (next.bottom().ceil().max(0.0) as u32).min(phys_h);
1637                    if nx0 >= nx1 || ny0 >= ny1 {
1638                        empty_clip_depth = 1;
1639                        continue;
1640                    }
1641                    clip_stack.push(next);
1642                    let phys_r: CornerRadius = Self::scale_radius(*radius, scale);
1643                    if phys.get_width() > 0.0
1644                        && phys.get_height() > 0.0
1645                        && phys_r.max_radius() > 0.25
1646                    {
1647                        let corner_mask_ids: [u32; 4] =
1648                            corner_mask_cache.resolve_quadrants(phys, phys_r, aa);
1649                        rounded_clip_stack.push(Some(RoundedClipMask {
1650                            rect: phys,
1651                            radius: phys_r,
1652                            corner_mask_ids,
1653                        }));
1654                    } else {
1655                        rounded_clip_stack.push(None);
1656                    }
1657                    let (parent_y0, parent_y1, _): (u32, u32, Option<usize>) = clip_scopes
1658                        .last()
1659                        .copied()
1660                        .unwrap_or((root_y0, root_y1, None));
1661                    if ny0 > parent_y0 || ny1 < parent_y1 {
1662                        let slot_idx: usize = prepped.len();
1663                        prepped.push(PreppedCommand {
1664                            cmd_index: usize::MAX,
1665                            active_clip: next,
1666                            y0: ny0,
1667                            y1: ny1,
1668                            opaque_cutout_h: Rect::default(),
1669                            opaque_cutout_v: Rect::default(),
1670                            glyph_run_start: 0,
1671                            glyph_run_len: 0,
1672                            caret_rect_idx: u32::MAX,
1673                            rounded_clip_start: 0,
1674                            rounded_clip_len: 0,
1675                            skip_delta: 1,
1676                        });
1677                        clip_scopes.push((ny0, ny1, Some(slot_idx)));
1678                    } else {
1679                        clip_scopes.push((parent_y0, parent_y1, None));
1680                    }
1681                }
1682                DrawCommand::PopClip => {
1683                    if clip_stack.len() > 1 {
1684                        clip_stack.pop();
1685                        let _: Option<Option<RoundedClipMask>> = rounded_clip_stack.pop();
1686                        if let Some((_, _, Some(slot_idx))) = clip_scopes.pop() {
1687                            let span_len: usize = prepped.len().saturating_sub(slot_idx);
1688                            if span_len <= 1 {
1689                                prepped.truncate(slot_idx);
1690                            } else if span_len == 2 {
1691                                let only_cmd: PreppedCommand = prepped[slot_idx + 1];
1692                                prepped[slot_idx] = only_cmd;
1693                                let _: Option<PreppedCommand> = prepped.pop();
1694                            } else {
1695                                prepped[slot_idx].skip_delta = span_len as u32;
1696                            }
1697                        }
1698                    }
1699                }
1700                DrawCommand::Clear(clear_color) => {
1701                    let y0: u32 = (active_clip.get_y().floor().max(0.0) as u32).min(phys_h);
1702                    let y1: u32 = (active_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
1703                    if y0 < y1 {
1704                        let (mut rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
1705                            rounded_clip_stack.as_slice(),
1706                            rounded_clips,
1707                            active_clip,
1708                        );
1709                        let covers_root: bool = active_clip.get_x() <= root_clip.get_x()
1710                            && active_clip.get_y() <= root_clip.get_y()
1711                            && active_clip.right() >= root_clip.right()
1712                            && active_clip.bottom() >= root_clip.bottom();
1713                        let no_open_sentinels: bool = clip_scopes
1714                            .iter()
1715                            .all(|&(_, _, slot): &(u32, u32, Option<usize>)| slot.is_none());
1716                        if clamped_start == 0
1717                            && !prepped.is_empty()
1718                            && rc_len == 0
1719                            && clear_color.get_a() == 255
1720                            && covers_root
1721                            && no_open_sentinels
1722                        {
1723                            prepped.clear();
1724                            rounded_clips.clear();
1725                            positioned_glyphs.clear();
1726                            caret_rects.clear();
1727                            *prepped_bounds = None;
1728                            *prepped_fg_bounds = None;
1729                            has_first_cmd = false;
1730                            rc_start = 0;
1731                        }
1732                        if has_first_cmd {
1733                            expand_opt_rect(prepped_fg_bounds, active_clip);
1734                        }
1735                        has_first_cmd = true;
1736                        expand_opt_rect(prepped_bounds, active_clip);
1737                        prepped.push(PreppedCommand {
1738                            cmd_index,
1739                            active_clip,
1740                            y0,
1741                            y1,
1742                            opaque_cutout_h: Rect::default(),
1743                            opaque_cutout_v: Rect::default(),
1744                            glyph_run_start: 0,
1745                            glyph_run_len: 0,
1746                            caret_rect_idx: u32::MAX,
1747                            rounded_clip_start: rc_start,
1748                            rounded_clip_len: rc_len,
1749                            skip_delta: 0,
1750                        });
1751                    }
1752                }
1753                DrawCommand::FillRoundedRect {
1754                    rect,
1755                    color,
1756                    radius,
1757                    border,
1758                } => {
1759                    let phys: Rect = snap_physical_rect(*rect, scale);
1760                    if let Some(vis) = phys.intersect(active_clip) {
1761                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
1762                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
1763                        if y0 < y1 {
1764                            let (mut rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
1765                                rounded_clip_stack.as_slice(),
1766                                rounded_clips,
1767                                vis,
1768                            );
1769                            let no_border: bool =
1770                                border.get_width() <= 0.0 || border.get_color().get_a() == 0;
1771                            let covers_root: bool = vis.get_x() <= root_clip.get_x()
1772                                && vis.get_y() <= root_clip.get_y()
1773                                && vis.right() >= root_clip.right()
1774                                && vis.bottom() >= root_clip.bottom();
1775                            let no_open_sentinels: bool = clip_scopes
1776                                .iter()
1777                                .all(|&(_, _, slot): &(u32, u32, Option<usize>)| slot.is_none());
1778                            if clamped_start == 0
1779                                && !prepped.is_empty()
1780                                && rc_len == 0
1781                                && color.get_a() == 255
1782                                && radius.max_radius() <= 0.0
1783                                && no_border
1784                                && covers_root
1785                                && no_open_sentinels
1786                            {
1787                                prepped.clear();
1788                                rounded_clips.clear();
1789                                positioned_glyphs.clear();
1790                                caret_rects.clear();
1791                                *prepped_bounds = None;
1792                                *prepped_fg_bounds = None;
1793                                has_first_cmd = false;
1794                                rc_start = 0;
1795                            }
1796                            if has_first_cmd {
1797                                expand_opt_rect(prepped_fg_bounds, vis);
1798                            }
1799                            has_first_cmd = true;
1800                            expand_opt_rect(prepped_bounds, vis);
1801                            prepped.push(PreppedCommand {
1802                                cmd_index,
1803                                active_clip,
1804                                y0,
1805                                y1,
1806                                opaque_cutout_h: Rect::default(),
1807                                opaque_cutout_v: Rect::default(),
1808                                glyph_run_start: 0,
1809                                glyph_run_len: 0,
1810                                caret_rect_idx: u32::MAX,
1811                                rounded_clip_start: rc_start,
1812                                rounded_clip_len: rc_len,
1813                                skip_delta: 0,
1814                            });
1815                        }
1816                    }
1817                }
1818                DrawCommand::LinearGradientRect { rect, .. }
1819                | DrawCommand::Image { rect, .. }
1820                | DrawCommand::SpriteRegion { rect, .. } => {
1821                    let phys: Rect = snap_physical_rect(*rect, scale);
1822                    if let Some(vis) = phys.intersect(active_clip) {
1823                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
1824                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
1825                        if y0 < y1 {
1826                            let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
1827                                rounded_clip_stack.as_slice(),
1828                                rounded_clips,
1829                                vis,
1830                            );
1831                            if has_first_cmd {
1832                                expand_opt_rect(prepped_fg_bounds, vis);
1833                            }
1834                            has_first_cmd = true;
1835                            expand_opt_rect(prepped_bounds, vis);
1836                            prepped.push(PreppedCommand {
1837                                cmd_index,
1838                                active_clip,
1839                                y0,
1840                                y1,
1841                                opaque_cutout_h: Rect::default(),
1842                                opaque_cutout_v: Rect::default(),
1843                                glyph_run_start: 0,
1844                                glyph_run_len: 0,
1845                                caret_rect_idx: u32::MAX,
1846                                rounded_clip_start: rc_start,
1847                                rounded_clip_len: rc_len,
1848                                skip_delta: 0,
1849                            });
1850                        }
1851                    }
1852                }
1853                DrawCommand::BoxShadow { rect, shadow, .. } => {
1854                    if shadow.get_color().get_a() == 0 {
1855                        continue;
1856                    }
1857                    let spread: f32 = shadow.get_spread_radius() * scale;
1858                    let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
1859                    let sigma: f32 = (blur * 0.5).max(0.75);
1860                    let pad: f32 = (sigma * 3.0).ceil();
1861                    let base_rect: Rect = snap_physical_rect(*rect, scale);
1862                    let caster_rect: Rect = Rect::new(
1863                        base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
1864                        base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
1865                        (base_rect.get_width() + spread * 2.0).max(1.0),
1866                        (base_rect.get_height() + spread * 2.0).max(1.0),
1867                    );
1868                    let shadow_rect: Rect = Rect::new(
1869                        caster_rect.get_x() - pad,
1870                        caster_rect.get_y() - pad,
1871                        caster_rect.get_width() + pad * 2.0,
1872                        caster_rect.get_height() + pad * 2.0,
1873                    );
1874                    if let Some(vis) = shadow_rect.intersect(active_clip) {
1875                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
1876                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
1877                        if y0 < y1 {
1878                            let (cut_h, cut_v): (Rect, Rect) = Self::resolve_opaque_shadow_cutout(
1879                                commands.get(cmd_index + 1),
1880                                scale,
1881                            );
1882                            let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
1883                                rounded_clip_stack.as_slice(),
1884                                rounded_clips,
1885                                vis,
1886                            );
1887                            if has_first_cmd {
1888                                expand_opt_rect(prepped_fg_bounds, vis);
1889                            }
1890                            has_first_cmd = true;
1891                            expand_opt_rect(prepped_bounds, vis);
1892                            prepped.push(PreppedCommand {
1893                                cmd_index,
1894                                active_clip,
1895                                y0,
1896                                y1,
1897                                opaque_cutout_h: cut_h,
1898                                opaque_cutout_v: cut_v,
1899                                glyph_run_start: 0,
1900                                glyph_run_len: 0,
1901                                caret_rect_idx: u32::MAX,
1902                                rounded_clip_start: rc_start,
1903                                rounded_clip_len: rc_len,
1904                                skip_delta: 0,
1905                            });
1906                        }
1907                    }
1908                }
1909                DrawCommand::TextRun { rect, text, style } => {
1910                    if text.is_empty() || style.get_color().get_a() == 0 {
1911                        continue;
1912                    }
1913                    let phys_rect: Rect = Self::scale_rect(*rect, scale);
1914                    let pad: f32 = style.get_font_size() * scale * 0.5;
1915                    let expanded: Rect = Rect::new(
1916                        phys_rect.get_x() - pad,
1917                        phys_rect.get_y() - pad,
1918                        phys_rect.get_width() + pad * 2.0,
1919                        phys_rect.get_height() + pad * 2.0,
1920                    );
1921                    let Some(vis) = expanded.intersect(active_clip) else {
1922                        continue;
1923                    };
1924                    let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
1925                    let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
1926                    if vis_y0 >= vis_y1 {
1927                        continue;
1928                    }
1929                    let max_w: f32 = rect.get_width().max(1.0);
1930                    let width_key: u32 = ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
1931                    let key_hash: u64 = hash_text_layout_key(text, *style);
1932                    let layout_idx: u32 =
1933                        text_layout_cache.get_or_insert_with(key_hash, width_key, || {
1934                            measurer.measure(text, *style, Some(max_w))
1935                        });
1936                    let (glyph_run_start, glyph_run_len): (u32, u32) =
1937                        if let Some(layout) = text_layout_cache.get(layout_idx) {
1938                            Self::resolve_text_run_glyphs(
1939                                layout,
1940                                *rect,
1941                                *style,
1942                                (active_clip, phys_w, phys_h, scale),
1943                                (glyph_atlas, font_provider),
1944                                positioned_glyphs,
1945                                line_scratch,
1946                            )
1947                        } else {
1948                            (0, 0)
1949                        };
1950                    if glyph_run_len == 0 {
1951                        continue;
1952                    }
1953                    let clip_y0: u32 = (active_clip.get_y().floor().max(0.0) as u32).min(phys_h);
1954                    let clip_y1: u32 = (active_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
1955                    let mut tight_y0: u32 = phys_h;
1956                    let mut tight_y1: u32 = 0;
1957                    let mut glyph_bounds: Option<Rect> = None;
1958                    let g_s: usize = glyph_run_start as usize;
1959                    let g_e: usize = g_s.saturating_add(glyph_run_len as usize);
1960                    for g in positioned_glyphs[g_s..g_e].iter() {
1961                        let g_rect: Rect =
1962                            Rect::new(g.x as f32, g.y as f32, g.width as f32, g.height as f32);
1963                        if let Some(clipped_g) = g_rect.intersect(active_clip) {
1964                            expand_opt_rect(&mut glyph_bounds, clipped_g);
1965                            let gy0: u32 = (g.y.max(0) as u32).min(phys_h);
1966                            let gy1: u32 = ((g.y + g.height as i32).max(0) as u32).min(phys_h);
1967                            tight_y0 = tight_y0.min(gy0);
1968                            tight_y1 = tight_y1.max(gy1);
1969                        }
1970                    }
1971                    let (y0, y1, run_vis): (u32, u32, Rect) = if let Some(gb) = glyph_bounds {
1972                        let ty0: u32 = tight_y0.max(clip_y0);
1973                        let ty1: u32 = tight_y1.min(clip_y1);
1974                        if ty0 >= ty1 {
1975                            continue;
1976                        }
1977                        (ty0, ty1, gb)
1978                    } else {
1979                        (vis_y0, vis_y1, vis)
1980                    };
1981                    let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
1982                        rounded_clip_stack.as_slice(),
1983                        rounded_clips,
1984                        run_vis,
1985                    );
1986                    if has_first_cmd {
1987                        expand_opt_rect(prepped_fg_bounds, run_vis);
1988                    }
1989                    has_first_cmd = true;
1990                    expand_opt_rect(prepped_bounds, run_vis);
1991                    prepped.push(PreppedCommand {
1992                        cmd_index,
1993                        active_clip,
1994                        y0,
1995                        y1,
1996                        opaque_cutout_h: Rect::default(),
1997                        opaque_cutout_v: Rect::default(),
1998                        glyph_run_start,
1999                        glyph_run_len,
2000                        caret_rect_idx: u32::MAX,
2001                        rounded_clip_start: rc_start,
2002                        rounded_clip_len: rc_len,
2003                        skip_delta: 0,
2004                    });
2005                }
2006                DrawCommand::TextCaret {
2007                    text_rect,
2008                    content_rect,
2009                    text,
2010                    style,
2011                    caret_height,
2012                    color,
2013                    multiline,
2014                } => {
2015                    if color.get_a() == 0 {
2016                        continue;
2017                    }
2018                    let phys_content: Rect = Self::scale_rect(*content_rect, scale);
2019                    let Some(vis) = phys_content.intersect(active_clip) else {
2020                        continue;
2021                    };
2022                    let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
2023                    let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2024                    if vis_y0 >= vis_y1 {
2025                        continue;
2026                    }
2027                    let (max_w, width_key): (Option<f32>, u32) = if *multiline {
2028                        let w: f32 = content_rect.get_width().max(1.0);
2029                        (Some(w), ((w * 10.0).round() as u32).min(u32::MAX - 1))
2030                    } else {
2031                        (None, u32::MAX)
2032                    };
2033                    let key_hash: u64 = hash_text_layout_key(text, *style);
2034                    let layout_idx: u32 =
2035                        text_layout_cache.get_or_insert_with(key_hash, width_key, || {
2036                            measurer.measure(text, *style, max_w)
2037                        });
2038                    let caret_rect: Rect = Self::resolve_text_caret_rect(
2039                        text_layout_cache.get(layout_idx),
2040                        (*text_rect, *content_rect),
2041                        *style,
2042                        (*caret_height, scale, *multiline),
2043                        (glyph_atlas, font_provider),
2044                    );
2045                    let Some(caret_vis) = caret_rect.intersect(active_clip) else {
2046                        continue;
2047                    };
2048                    let y0: u32 = (caret_vis.get_y().floor().max(0.0) as u32).min(phys_h);
2049                    let y1: u32 = (caret_vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2050                    if y0 >= y1 {
2051                        continue;
2052                    }
2053                    let caret_rect_idx: u32 = caret_rects.len() as u32;
2054                    caret_rects.push(caret_rect);
2055                    let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
2056                        rounded_clip_stack.as_slice(),
2057                        rounded_clips,
2058                        caret_vis,
2059                    );
2060                    if has_first_cmd {
2061                        expand_opt_rect(prepped_fg_bounds, caret_vis);
2062                    }
2063                    has_first_cmd = true;
2064                    expand_opt_rect(prepped_bounds, caret_vis);
2065                    prepped.push(PreppedCommand {
2066                        cmd_index,
2067                        active_clip,
2068                        y0,
2069                        y1,
2070                        opaque_cutout_h: Rect::default(),
2071                        opaque_cutout_v: Rect::default(),
2072                        glyph_run_start: 0,
2073                        glyph_run_len: 0,
2074                        caret_rect_idx,
2075                        rounded_clip_start: rc_start,
2076                        rounded_clip_len: rc_len,
2077                        skip_delta: 0,
2078                    });
2079                }
2080                DrawCommand::Line {
2081                    from, to, width, ..
2082                } => {
2083                    let half_w: f32 = (width * scale).max(1.0) * 0.5 + 1.0;
2084                    let min_x: f32 = from.get_x().min(to.get_x()) * scale - half_w;
2085                    let min_y: f32 = from.get_y().min(to.get_y()) * scale - half_w;
2086                    let max_x: f32 = from.get_x().max(to.get_x()) * scale + half_w;
2087                    let max_y: f32 = from.get_y().max(to.get_y()) * scale + half_w;
2088                    if let Some(vis) =
2089                        Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
2090                    {
2091                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
2092                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2093                        if y0 < y1 {
2094                            let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
2095                                rounded_clip_stack.as_slice(),
2096                                rounded_clips,
2097                                vis,
2098                            );
2099                            if has_first_cmd {
2100                                expand_opt_rect(prepped_fg_bounds, vis);
2101                            }
2102                            has_first_cmd = true;
2103                            expand_opt_rect(prepped_bounds, vis);
2104                            prepped.push(PreppedCommand {
2105                                cmd_index,
2106                                active_clip,
2107                                y0,
2108                                y1,
2109                                opaque_cutout_h: Rect::default(),
2110                                opaque_cutout_v: Rect::default(),
2111                                glyph_run_start: 0,
2112                                glyph_run_len: 0,
2113                                caret_rect_idx: u32::MAX,
2114                                rounded_clip_start: rc_start,
2115                                rounded_clip_len: rc_len,
2116                                skip_delta: 0,
2117                            });
2118                        }
2119                    }
2120                }
2121                DrawCommand::Circle { center, radius, .. } => {
2122                    let r: f32 = radius * scale + 1.0;
2123                    let bounds: Rect = Rect::new(
2124                        center.get_x() * scale - r,
2125                        center.get_y() * scale - r,
2126                        r * 2.0,
2127                        r * 2.0,
2128                    );
2129                    if let Some(vis) = bounds.intersect(active_clip) {
2130                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
2131                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2132                        if y0 < y1 {
2133                            let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
2134                                rounded_clip_stack.as_slice(),
2135                                rounded_clips,
2136                                vis,
2137                            );
2138                            if has_first_cmd {
2139                                expand_opt_rect(prepped_fg_bounds, vis);
2140                            }
2141                            has_first_cmd = true;
2142                            expand_opt_rect(prepped_bounds, vis);
2143                            prepped.push(PreppedCommand {
2144                                cmd_index,
2145                                active_clip,
2146                                y0,
2147                                y1,
2148                                opaque_cutout_h: Rect::default(),
2149                                opaque_cutout_v: Rect::default(),
2150                                glyph_run_start: 0,
2151                                glyph_run_len: 0,
2152                                caret_rect_idx: u32::MAX,
2153                                rounded_clip_start: rc_start,
2154                                rounded_clip_len: rc_len,
2155                                skip_delta: 0,
2156                            });
2157                        }
2158                    }
2159                }
2160                DrawCommand::Triangle { p0, p1, p2, .. } => {
2161                    let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.0;
2162                    let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.0;
2163                    let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.0;
2164                    let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.0;
2165                    if let Some(vis) =
2166                        Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
2167                    {
2168                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
2169                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2170                        if y0 < y1 {
2171                            let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
2172                                rounded_clip_stack.as_slice(),
2173                                rounded_clips,
2174                                vis,
2175                            );
2176                            if has_first_cmd {
2177                                expand_opt_rect(prepped_fg_bounds, vis);
2178                            }
2179                            has_first_cmd = true;
2180                            expand_opt_rect(prepped_bounds, vis);
2181                            prepped.push(PreppedCommand {
2182                                cmd_index,
2183                                active_clip,
2184                                y0,
2185                                y1,
2186                                opaque_cutout_h: Rect::default(),
2187                                opaque_cutout_v: Rect::default(),
2188                                glyph_run_start: 0,
2189                                glyph_run_len: 0,
2190                                caret_rect_idx: u32::MAX,
2191                                rounded_clip_start: rc_start,
2192                                rounded_clip_len: rc_len,
2193                                skip_delta: 0,
2194                            });
2195                        }
2196                    }
2197                }
2198            }
2199        }
2200        while let Some((_, _, opt_slot)) = clip_scopes.pop() {
2201            if let Some(slot_idx) = opt_slot {
2202                let span_len: usize = prepped.len().saturating_sub(slot_idx);
2203                if span_len <= 1 {
2204                    prepped.truncate(slot_idx);
2205                } else if span_len == 2 {
2206                    let only_cmd: PreppedCommand = prepped[slot_idx + 1];
2207                    prepped[slot_idx] = only_cmd;
2208                    let _: Option<PreppedCommand> = prepped.pop();
2209                } else {
2210                    prepped[slot_idx].skip_delta = span_len as u32;
2211                }
2212            }
2213        }
2214        glyph_atlas.set_slots_pinned(false);
2215    }
2216
2217    /// Returns cumulative `TextLayoutCache` telemetry `(hits, misses, evictions, resident_bytes)`.
2218    ///
2219    /// # Arguments
2220    ///
2221    /// - `&Self` - Software renderer reference.
2222    ///
2223    /// # Returns
2224    ///
2225    /// - `(u64, u64, u64, usize)` - Tuple `(cache_hits, cache_misses, evictions, resident_bytes)`.
2226    #[must_use]
2227    pub fn text_layout_cache_stats(&self) -> (u64, u64, u64, usize) {
2228        self.get_text_layout_cache().stats()
2229    }
2230
2231    /// Resolves and positions every visible glyph of a `TextRun` once on the main thread using direct ASCII slot tables.
2232    ///
2233    /// # Arguments
2234    ///
2235    /// - `&TextLayoutResult` - Cached wrapped lines for the text run.
2236    /// - `Rect` - Logical text bounding box.
2237    /// - `TextStyle` - Typography style.
2238    /// - `(Rect, u32, u32, f32)` - Tuple `(active_clip, phys_w, phys_h, scale)`.
2239    /// - `(&mut GlyphAtlas, &NativeSystemFont)` - Mutable glyph atlas and system font provider.
2240    /// - `&mut Vec<PositionedGlyph>` - Frame-wide flat output buffer for pre-positioned glyphs.
2241    /// - `&mut Vec<(u32, f32, u16, u16)>` - Reusable single-line scratch buffer for `Center`/`Right` alignment.
2242    ///
2243    /// # Returns
2244    ///
2245    /// - `(u32, u32)` - `(start_index, count)` range inside `out_glyphs`.
2246    fn resolve_text_run_glyphs(
2247        layout: &TextLayoutResult,
2248        rect: Rect,
2249        style: TextStyle,
2250        clip_dims: (Rect, u32, u32, f32),
2251        atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
2252        out_glyphs: &mut Vec<PositionedGlyph>,
2253        line_scratch: &mut Vec<(u32, f32, u16, u16)>,
2254    ) -> (u32, u32) {
2255        let (clip, phys_w, phys_h, scale): (Rect, u32, u32, f32) = clip_dims;
2256        let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
2257        let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
2258        let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
2259        let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
2260        let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
2261        if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
2262            return (0, 0);
2263        }
2264        let phys_font_size: f32 = style.get_font_size() * scale;
2265        let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
2266        let bold: bool = style.get_weight().is_bold();
2267        let monospace: bool = style.get_family() == FontFamily::Monospace;
2268        let italic: bool = style.get_italic();
2269        let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
2270        let ascii_table_idx: usize =
2271            glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
2272        let line_h_phys: f32 = layout.get_line_height_px() * scale;
2273        let box_w_phys: f32 = rect.get_width() * scale;
2274        let letter_sp: f32 = style.get_letter_spacing() * scale;
2275        let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
2276        let base_x_phys: f32 = (rect.get_x() * scale).round();
2277        let base_y_phys: f32 = (rect.get_y() * scale).round();
2278        let clip_x1_f: f32 = clip_x1 as f32;
2279        let clip_y0_f: f32 = clip_y0 as f32;
2280        let clip_y1_f: f32 = clip_y1 as f32;
2281        let align: TextAlign = style.get_align();
2282        let run_start: u32 = out_glyphs.len() as u32;
2283        for (line_idx, line) in layout.get_lines().iter().enumerate() {
2284            let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
2285            let pen_y: f32 = base_y_phys + line_off_y;
2286            if (pen_y + line_h_phys) < clip_y0_f || pen_y > clip_y1_f {
2287                continue;
2288            }
2289            let line_str: &str = line.get_text().as_str();
2290            if align == TextAlign::Left {
2291                let mut pen_x: f32 = base_x_phys;
2292                if line_str.is_ascii() {
2293                    for &byte in line_str.as_bytes() {
2294                        if byte == b' ' {
2295                            pen_x += space_step;
2296                            continue;
2297                        }
2298                        if pen_x > clip_x1_f {
2299                            break;
2300                        }
2301                        let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
2302                            ascii_table_idx,
2303                            byte,
2304                            key_meta,
2305                            font_provider,
2306                        );
2307                        let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
2308                        let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
2309                        let gx0: i32 = pen_x.round() as i32;
2310                        let gw: i32 = glyph.get_width() as i32;
2311                        if gx0 + gw > clip_x0 && gx0 < clip_x1 {
2312                            let gh: u32 = glyph.get_height();
2313                            let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
2314                            let gy0: i32 = (pen_y + glyph_v_off) as i32;
2315                            if gy0 < clip_y1 && gy0 + (gh as i32) > clip_y0 {
2316                                out_glyphs.push(PositionedGlyph {
2317                                    glyph_idx: slot,
2318                                    x: gx0,
2319                                    y: gy0,
2320                                    width: (gw as u32).min(u16::MAX as u32) as u16,
2321                                    height: gh.min(u16::MAX as u32) as u16,
2322                                });
2323                            }
2324                        }
2325                        pen_x += adv_phys;
2326                    }
2327                } else {
2328                    for ch in line_str.chars() {
2329                        if ch == ' ' {
2330                            pen_x += space_step;
2331                            continue;
2332                        }
2333                        if pen_x > clip_x1_f {
2334                            break;
2335                        }
2336                        let slot: u32 = if ch.is_ascii() {
2337                            glyph_atlas.get_or_rasterize_ascii_slot_with(
2338                                ascii_table_idx,
2339                                ch as u8,
2340                                key_meta,
2341                                font_provider,
2342                            )
2343                        } else {
2344                            let key: GlyphKey = GlyphKey {
2345                                codepoint: ch,
2346                                size_tenths,
2347                                bold,
2348                                monospace,
2349                                italic,
2350                            };
2351                            glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
2352                        };
2353                        let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
2354                        let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
2355                        let gx0: i32 = pen_x.round() as i32;
2356                        let gw: i32 = glyph.get_width() as i32;
2357                        if gx0 + gw > clip_x0 && gx0 < clip_x1 {
2358                            let gh: u32 = glyph.get_height();
2359                            let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
2360                            let gy0: i32 = (pen_y + glyph_v_off) as i32;
2361                            if gy0 < clip_y1 && gy0 + (gh as i32) > clip_y0 {
2362                                out_glyphs.push(PositionedGlyph {
2363                                    glyph_idx: slot,
2364                                    x: gx0,
2365                                    y: gy0,
2366                                    width: (gw as u32).min(u16::MAX as u32) as u16,
2367                                    height: gh.min(u16::MAX as u32) as u16,
2368                                });
2369                            }
2370                        }
2371                        pen_x += adv_phys;
2372                    }
2373                }
2374            } else {
2375                line_scratch.clear();
2376                let mut line_w_phys: f32 = 0.0;
2377                if line_str.is_ascii() {
2378                    for &byte in line_str.as_bytes() {
2379                        if byte == b' ' {
2380                            line_w_phys += space_step;
2381                            line_scratch.push((u32::MAX, space_step, 0, 0));
2382                        } else {
2383                            let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
2384                                ascii_table_idx,
2385                                byte,
2386                                key_meta,
2387                                font_provider,
2388                            );
2389                            let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
2390                            let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
2391                            line_w_phys += adv_phys;
2392                            line_scratch.push((
2393                                slot,
2394                                adv_phys,
2395                                glyph.get_width().min(u16::MAX as u32) as u16,
2396                                glyph.get_height().min(u16::MAX as u32) as u16,
2397                            ));
2398                        }
2399                    }
2400                } else {
2401                    for ch in line_str.chars() {
2402                        if ch == ' ' {
2403                            line_w_phys += space_step;
2404                            line_scratch.push((u32::MAX, space_step, 0, 0));
2405                        } else {
2406                            let slot: u32 = if ch.is_ascii() {
2407                                glyph_atlas.get_or_rasterize_ascii_slot_with(
2408                                    ascii_table_idx,
2409                                    ch as u8,
2410                                    key_meta,
2411                                    font_provider,
2412                                )
2413                            } else {
2414                                let key: GlyphKey = GlyphKey {
2415                                    codepoint: ch,
2416                                    size_tenths,
2417                                    bold,
2418                                    monospace,
2419                                    italic,
2420                                };
2421                                glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
2422                            };
2423                            let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
2424                            let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
2425                            line_w_phys += adv_phys;
2426                            line_scratch.push((
2427                                slot,
2428                                adv_phys,
2429                                glyph.get_width().min(u16::MAX as u32) as u16,
2430                                glyph.get_height().min(u16::MAX as u32) as u16,
2431                            ));
2432                        }
2433                    }
2434                }
2435                let align_x: f32 = if align == TextAlign::Center {
2436                    ((box_w_phys - line_w_phys) * 0.5).max(0.0)
2437                } else {
2438                    (box_w_phys - line_w_phys).max(0.0)
2439                };
2440                let mut pen_x: f32 = base_x_phys + align_x.round();
2441                for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
2442                    if slot == u32::MAX {
2443                        pen_x += adv_phys;
2444                        continue;
2445                    }
2446                    if pen_x > clip_x1_f {
2447                        break;
2448                    }
2449                    let gx0: i32 = pen_x.round() as i32;
2450                    let gw: i32 = gw_u16 as i32;
2451                    let gh: i32 = gh_u16 as i32;
2452                    if gx0 + gw > clip_x0 && gx0 < clip_x1 {
2453                        let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
2454                        let gy0: i32 = (pen_y + glyph_v_off) as i32;
2455                        if gy0 < clip_y1 && gy0 + gh > clip_y0 {
2456                            out_glyphs.push(PositionedGlyph {
2457                                glyph_idx: slot,
2458                                x: gx0,
2459                                y: gy0,
2460                                width: gw_u16,
2461                                height: gh_u16,
2462                            });
2463                        }
2464                    }
2465                    pen_x += adv_phys;
2466                }
2467            }
2468        }
2469        let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
2470        (run_start, run_len)
2471    }
2472
2473    /// Precomputes the exact physical pixel rectangle for `DrawCommand::TextCaret` using direct ASCII slot lookup.
2474    ///
2475    /// # Arguments
2476    ///
2477    /// - `Option<&TextLayoutResult>` - Cached wrapped text layout, if present.
2478    /// - `(Rect, Rect)` - Tuple `(text_rect, content_rect)` in logical pixels.
2479    /// - `TextStyle` - Typography style.
2480    /// - `(f32, f32, bool)` - Tuple `(caret_height, scale, multiline)`.
2481    /// - `(&mut GlyphAtlas, &NativeSystemFont)` - Mutable glyph atlas and system font provider.
2482    ///
2483    /// # Returns
2484    ///
2485    /// - `Rect` - Physical pixel caret rectangle ready for band rasterization.
2486    #[must_use]
2487    fn resolve_text_caret_rect(
2488        layout_opt: Option<&TextLayoutResult>,
2489        rects: (Rect, Rect),
2490        style: TextStyle,
2491        caret_opts: (f32, f32, bool),
2492        atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
2493    ) -> Rect {
2494        let (text_rect, content_rect): (Rect, Rect) = rects;
2495        let (caret_height, scale, multiline): (f32, f32, bool) = caret_opts;
2496        let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
2497        let phys_font_size: f32 = style.get_font_size() * scale;
2498        let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
2499        let bold: bool = style.get_weight().is_bold();
2500        let monospace: bool = style.get_family() == FontFamily::Monospace;
2501        let italic: bool = style.get_italic();
2502        let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
2503        let letter_sp: f32 = style.get_letter_spacing() * scale;
2504        let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
2505        let (last_w_phys, line_idx, line_h_phys): (f32, usize, f32) =
2506            if let Some(layout) = layout_opt {
2507                let lh: f32 = layout.get_line_height_px() * scale;
2508                let idx: usize = layout.get_lines().len().saturating_sub(1);
2509                let w_phys: f32 = if let Some(line) = layout.get_lines().last() {
2510                    let ascii_table_idx: usize =
2511                        glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
2512                    let mut acc: f32 = 0.0;
2513                    for ch in line.get_text().chars() {
2514                        if ch == ' ' {
2515                            acc += space_step;
2516                        } else {
2517                            let slot: u32 = if ch.is_ascii() {
2518                                glyph_atlas.get_or_rasterize_ascii_slot_with(
2519                                    ascii_table_idx,
2520                                    ch as u8,
2521                                    key_meta,
2522                                    font_provider,
2523                                )
2524                            } else {
2525                                let key: GlyphKey = GlyphKey {
2526                                    codepoint: ch,
2527                                    size_tenths,
2528                                    bold,
2529                                    monospace,
2530                                    italic,
2531                                };
2532                                glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
2533                            };
2534                            let adv: f32 =
2535                                (glyph_atlas.glyph_by_slot(slot).get_advance() as f32).max(1.0);
2536                            acc += adv + letter_sp;
2537                        }
2538                    }
2539                    acc
2540                } else {
2541                    0.0
2542                };
2543                (w_phys, idx, lh)
2544            } else {
2545                (
2546                    0.0,
2547                    0,
2548                    (style.get_font_size() * style.get_line_height()).max(1.0) * scale,
2549                )
2550            };
2551        let caret_h_phys: f32 = (caret_height * scale).max(2.0);
2552        let caret_w_phys: f32 = (1.5 * scale).max(1.5);
2553        let min_x: f32 = content_rect.get_x() * scale;
2554        let max_x: f32 = (content_rect.right() * scale - caret_w_phys - 1.0).max(min_x);
2555        let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.5 * scale } else { 0.0 };
2556        let caret_x_phys: f32 = (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys)
2557            .min(max_x)
2558            .max(min_x);
2559        let caret_y_phys: f32 = if multiline {
2560            let raw_y: f32 = content_rect.get_y() * scale
2561                + (line_idx as f32) * line_h_phys
2562                + ((line_h_phys - caret_h_phys) * 0.5).max(0.0);
2563            raw_y
2564                .min(content_rect.bottom() * scale - caret_h_phys)
2565                .max(content_rect.get_y() * scale)
2566        } else {
2567            content_rect.get_y() * scale
2568                + ((content_rect.get_height() * scale - caret_h_phys) * 0.5).max(0.0)
2569        };
2570        Rect::new(
2571            caret_x_phys.round(),
2572            caret_y_phys.round(),
2573            caret_w_phys.round().max(1.0),
2574            caret_h_phys.round().max(2.0),
2575        )
2576    }
2577
2578    /// Collects active rounded clip masks intersecting `vis` into `out` and returns their `(start, len)` span.
2579    ///
2580    /// # Arguments
2581    ///
2582    /// - `&[Option<RoundedClipMask>]` - Current rounded clip stack.
2583    /// - `&mut Vec<RoundedClipMask>` - Frame-wide rounded clip output buffer.
2584    /// - `Rect` - Visible clipped physical bounds of the command.
2585    ///
2586    /// # Returns
2587    ///
2588    /// - `(u32, u16)` - `(start_index, mask_count)` slice range inside `out`.
2589    #[must_use]
2590    fn collect_active_rounded(
2591        stack: &[Option<RoundedClipMask>],
2592        out: &mut Vec<RoundedClipMask>,
2593        vis: Rect,
2594    ) -> (u32, u16) {
2595        let start: u32 = out.len() as u32;
2596        for entry in stack.iter().copied().flatten() {
2597            if rect_intersects_rounded_corners(vis, entry.get_rect(), entry.get_radius()) {
2598                out.push(entry);
2599            }
2600        }
2601        let len: u16 = (out.len() as u32)
2602            .saturating_sub(start)
2603            .min(u16::MAX as u32) as u16;
2604        (start, len)
2605    }
2606
2607    /// Computes two strictly-interior opaque cutout rectangles `(horizontal_bar, vertical_bar)` if the next command is an opaque `FillRoundedRect`.
2608    ///
2609    /// # Arguments
2610    ///
2611    /// - `Option<&DrawCommand>` - Immediately following command in the display list.
2612    /// - `f32` - Active DPI scale factor.
2613    ///
2614    /// # Returns
2615    ///
2616    /// - `(Rect, Rect)` - Opaque inner rectangles safely skipped by `raster_shadow` with zero visual change.
2617    #[must_use]
2618    fn resolve_opaque_shadow_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
2619        let Some(DrawCommand::FillRoundedRect {
2620            rect,
2621            color,
2622            radius,
2623            ..
2624        }) = next_cmd
2625        else {
2626            return (Rect::default(), Rect::default());
2627        };
2628        if color.get_a() != 255 {
2629            return (Rect::default(), Rect::default());
2630        }
2631        let phys: Rect = snap_physical_rect(*rect, scale);
2632        let r_max: f32 = Self::scale_radius(*radius, scale)
2633            .max_radius()
2634            .min(phys.get_width() * 0.5)
2635            .min(phys.get_height() * 0.5);
2636        let pad: f32 = 1.5;
2637        let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
2638        let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
2639        let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
2640            Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
2641        } else {
2642            Rect::default()
2643        };
2644        let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
2645        let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
2646        let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
2647            Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
2648        } else {
2649            Rect::default()
2650        };
2651        (cut_h, cut_v)
2652    }
2653
2654    /// Saves only the non-interior (`cov < 16`) corner rows of a single cached `RoundedClipMask` via bulk row copies.
2655    ///
2656    /// # Arguments
2657    ///
2658    /// - `&mut PixelBand<'_>` - Target pixel band.
2659    /// - `RoundedClipMask` - Single active rounded clip mask.
2660    /// - `Rect` - Active band-clipped bounds.
2661    /// - `(u32, u32, u32)` - Tuple `(fb_w, band_y0, band_y1)`.
2662    /// - `&[CachedCornerMask]` - Read-only cached quadrant masks.
2663    /// - `&mut BandCornerScratch` - Reusable per-thread scratch storage.
2664    ///
2665    /// # Returns
2666    ///
2667    /// - `bool` - True when at least one dirty corner row was saved (or `false` if no dirty pixels intersect).
2668    fn save_single_cached_rounded_corners(
2669        band: &mut PixelBand<'_>,
2670        mask: RoundedClipMask,
2671        clip: Rect,
2672        band_bounds: (u32, u32, u32),
2673        corner_masks: &[CachedCornerMask],
2674        scratch: &mut BandCornerScratch,
2675    ) -> bool {
2676        let (fb_w, band_y0, band_y1): (u32, u32, u32) = band_bounds;
2677        let clip_x0: i32 = (clip.get_x().floor().max(0.0) as u32).min(fb_w) as i32;
2678        let clip_y0: i32 = (clip.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
2679        let clip_x1: i32 = (clip.right().ceil().max(0.0) as u32).min(fb_w) as i32;
2680        let clip_y1: i32 = (clip.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
2681        if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
2682            return false;
2683        }
2684        let rect: Rect = mask.get_rect();
2685        let rx0_i: i32 = rect.get_x().round() as i32;
2686        let ry0_i: i32 = rect.get_y().round() as i32;
2687        let rx1_i: i32 = rect.right().round() as i32;
2688        let ry1_i: i32 = rect.bottom().round() as i32;
2689        let mask_ids: [u32; 4] = mask.get_corner_mask_ids();
2690        scratch.saved_bytes.clear();
2691        scratch.saved_rows.clear();
2692        for (q, &mask_id) in mask_ids.iter().enumerate() {
2693            if mask_id == u32::MAX {
2694                continue;
2695            }
2696            let Some(cm) = corner_masks.get(mask_id as usize) else {
2697                continue;
2698            };
2699            let dim_i: i32 = cm.dim as i32;
2700            let origin_x: i32 = if q == 0 || q == 3 {
2701                rx0_i
2702            } else {
2703                rx1_i - dim_i
2704            };
2705            let origin_y: i32 = if q == 0 || q == 1 {
2706                ry0_i
2707            } else {
2708                ry1_i - dim_i
2709            };
2710            let bx0: i32 = origin_x.max(clip_x0);
2711            let bx1: i32 = (origin_x + dim_i).min(clip_x1);
2712            let by0: i32 = origin_y.max(clip_y0);
2713            let by1: i32 = (origin_y + dim_i).min(clip_y1);
2714            if bx0 >= bx1 || by0 >= by1 {
2715                continue;
2716            }
2717            for y_i in by0..by1 {
2718                let my: usize = (y_i - origin_y) as usize;
2719                let span: CornerMaskRowSpan = cm.row_spans[my];
2720                if span.dirty_start >= span.dirty_end {
2721                    continue;
2722                }
2723                let sx0_i: i32 = (origin_x + (span.dirty_start as i32)).max(bx0);
2724                let sx1_i: i32 = (origin_x + (span.dirty_end as i32)).min(bx1);
2725                if sx0_i >= sx1_i {
2726                    continue;
2727                }
2728                let y: u32 = y_i as u32;
2729                let sx0: u32 = sx0_i as u32;
2730                let sx1: u32 = sx1_i as u32;
2731                if let Some(row) = band.row_slice_mut(y) {
2732                    let b0: usize = (sx0 as usize) * 4;
2733                    let b1: usize = (sx1 as usize) * 4;
2734                    let byte_off: usize = scratch.saved_bytes.len();
2735                    scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
2736                    scratch.saved_rows.push(SavedCornerRow {
2737                        y,
2738                        sx0,
2739                        sx1,
2740                        byte_off,
2741                        mask_id,
2742                        origin_x,
2743                        origin_y,
2744                    });
2745                }
2746            }
2747        }
2748        !scratch.saved_rows.is_empty()
2749    }
2750
2751    /// Restores exterior corner runs via bulk `copy_from_slice` and blends only the 1-3px anti-aliased boundary pixels.
2752    ///
2753    /// # Arguments
2754    ///
2755    /// - `&mut PixelBand<'_>` - Target pixel band.
2756    /// - `&[CachedCornerMask]` - Read-only cached quadrant masks.
2757    /// - `&BandCornerScratch` - Saved corner bytes and row descriptors.
2758    fn restore_single_cached_rounded_corners(
2759        band: &mut PixelBand<'_>,
2760        corner_masks: &[CachedCornerMask],
2761        scratch: &BandCornerScratch,
2762    ) {
2763        let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
2764        for entry in scratch.saved_rows.iter() {
2765            let Some(row) = band.row_slice_mut(entry.y) else {
2766                continue;
2767            };
2768            let cm: &CachedCornerMask = &corner_masks[entry.mask_id as usize];
2769            let dim: usize = cm.dim as usize;
2770            let my: usize = ((entry.y as i32) - entry.origin_y) as usize;
2771            let span: CornerMaskRowSpan = cm.row_spans[my];
2772            let sx0_i: i32 = entry.sx0 as i32;
2773            let sx1_i: i32 = entry.sx1 as i32;
2774            if span.ext_start < span.ext_end {
2775                let ex0: i32 = (entry.origin_x + (span.ext_start as i32)).max(sx0_i);
2776                let ex1: i32 = (entry.origin_x + (span.ext_end as i32)).min(sx1_i);
2777                if ex0 < ex1 {
2778                    let dst_b0: usize = (ex0 as usize) * 4;
2779                    let dst_b1: usize = (ex1 as usize) * 4;
2780                    let src_b0: usize = entry.byte_off + ((ex0 - sx0_i) as usize) * 4;
2781                    let src_b1: usize = src_b0 + (dst_b1 - dst_b0);
2782                    row[dst_b0..dst_b1].copy_from_slice(&saved_bytes[src_b0..src_b1]);
2783                }
2784            }
2785            if span.aa_start < span.aa_end {
2786                let ax0: i32 = (entry.origin_x + (span.aa_start as i32)).max(sx0_i);
2787                let ax1: i32 = (entry.origin_x + (span.aa_end as i32)).min(sx1_i);
2788                if ax0 < ax1 {
2789                    let cov_row: &[u8] = &cm.cov[my * dim..(my + 1) * dim];
2790                    for x_i in ax0..ax1 {
2791                        let mx: usize = (x_i - entry.origin_x) as usize;
2792                        let cov_u8: u8 = cov_row[mx];
2793                        if cov_u8 >= 16 {
2794                            continue;
2795                        }
2796                        let dst_off: usize = (x_i as usize) * 4;
2797                        let src_off: usize = entry.byte_off + ((x_i - sx0_i) as usize) * 4;
2798                        let saved_rgba: [u8; 4] = [
2799                            saved_bytes[src_off],
2800                            saved_bytes[src_off + 1],
2801                            saved_bytes[src_off + 2],
2802                            saved_bytes[src_off + 3],
2803                        ];
2804                        if cov_u8 == 0 {
2805                            row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
2806                        } else {
2807                            let cov: f32 = (cov_u8 as f32) * 0.0625;
2808                            lerp_pixel_slice_from_saved_linear(
2809                                &mut row[dst_off..dst_off + 4],
2810                                saved_rgba,
2811                                cov,
2812                            );
2813                        }
2814                    }
2815                }
2816            }
2817        }
2818    }
2819
2820    /// Executes all prepped commands overlapping `band`'s vertical slice `[y_offset, y_end)` completely lock-free.
2821    ///
2822    /// # Arguments
2823    ///
2824    /// - `&mut PixelBand<'_>` - Disjoint mutable horizontal pixel band.
2825    /// - `&[DrawCommand]` - Full frame draw command slice.
2826    /// - `&[PreppedCommand]` - Pre-clipped command list.
2827    /// - `BandAuxSlices<'_>` - Pre-positioned glyphs, caret rectangles, active rounded clip masks, and cached corner masks.
2828    /// - `&GlyphAtlas` - Immutable pre-warmed glyph atlas.
2829    /// - `(f32, AntialiasingMode)` - Tuple `(scale, antialiasing)`.
2830    ///
2831    /// # Returns
2832    ///
2833    /// - `usize` - Total shaded pixels in this band.
2834    pub(crate) fn render_band(
2835        band: &mut PixelBand<'_>,
2836        commands: &[DrawCommand],
2837        prepped: &[PreppedCommand],
2838        aux: BandAuxSlices<'_>,
2839        glyph_atlas: &GlyphAtlas,
2840        render_opts: (f32, AntialiasingMode),
2841    ) -> usize {
2842        let (positioned_glyphs, caret_rects, rounded_clips, corner_masks): (
2843            &[PositionedGlyph],
2844            &[Rect],
2845            &[RoundedClipMask],
2846            &[CachedCornerMask],
2847        ) = aux;
2848        let (scale, aa): (f32, AntialiasingMode) = render_opts;
2849        let band_y0: u32 = band.y_offset();
2850        let band_y1: u32 = band.y_end();
2851        let fb_w: u32 = band.width();
2852        let band_rect: Rect =
2853            Rect::new(0.0, band_y0 as f32, fb_w as f32, (band_y1 - band_y0) as f32);
2854        let has_any_rounded: bool = !rounded_clips.is_empty();
2855        let mut scratch: BandCornerScratch = if has_any_rounded {
2856            BAND_CORNER_SCRATCH
2857                .try_with(|cell: &RefCell<BandCornerScratch>| {
2858                    cell.try_borrow_mut()
2859                        .ok()
2860                        .map(|mut guard: RefMut<'_, BandCornerScratch>| take(&mut *guard))
2861                })
2862                .ok()
2863                .flatten()
2864                .unwrap_or_default()
2865        } else {
2866            BandCornerScratch::default()
2867        };
2868        let mut shaded: usize = 0;
2869        let prepped_len: usize = prepped.len();
2870        let mut idx: usize = 0;
2871        while idx < prepped_len {
2872            let item: &PreppedCommand = &prepped[idx];
2873            if item.get_cmd_index() == usize::MAX {
2874                if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
2875                    idx += (item.get_skip_delta() as usize).max(1);
2876                } else {
2877                    idx += 1;
2878                }
2879                continue;
2880            }
2881            idx += 1;
2882            if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
2883                continue;
2884            }
2885            let Some(active_clip) = item.get_active_clip().intersect(band_rect) else {
2886                continue;
2887            };
2888            let rc_len: usize = item.get_rounded_clip_len() as usize;
2889            let item_masks: &[RoundedClipMask] = if rc_len > 0 {
2890                let start: usize = item.get_rounded_clip_start() as usize;
2891                let end: usize = start.saturating_add(rc_len).min(rounded_clips.len());
2892                &rounded_clips[start..end]
2893            } else {
2894                &[]
2895            };
2896            let mut corner_mode: u8 = 0;
2897            if item_masks.len() == 1 {
2898                let mask: RoundedClipMask = item_masks[0];
2899                let rect: Rect = mask.get_rect();
2900                let max_r: f32 = (rect.get_width() * 0.5)
2901                    .min(rect.get_height() * 0.5)
2902                    .max(0.0);
2903                let radius: CornerRadius = mask.get_radius();
2904                let radii: [f32; 4] = [
2905                    radius.get_top_left().min(max_r),
2906                    radius.get_top_right().min(max_r),
2907                    radius.get_bottom_right().min(max_r),
2908                    radius.get_bottom_left().min(max_r),
2909                ];
2910                let ids: [u32; 4] = mask.get_corner_mask_ids();
2911                let all_cached: bool = radii
2912                    .iter()
2913                    .zip(ids.iter())
2914                    .all(|(&r, &id): (&f32, &u32)| r <= 0.25 || (id as usize) < corner_masks.len());
2915                if all_cached {
2916                    if Self::save_single_cached_rounded_corners(
2917                        band,
2918                        mask,
2919                        active_clip,
2920                        (fb_w, band_y0, band_y1),
2921                        corner_masks,
2922                        &mut scratch,
2923                    ) {
2924                        corner_mode = 1;
2925                    }
2926                } else {
2927                    scratch.corner_boxes.clear();
2928                    scratch.saved_bytes.clear();
2929                    collect_rounded_clip_boxes(
2930                        mask,
2931                        active_clip,
2932                        (fb_w, band_y0, band_y1),
2933                        &mut scratch.corner_boxes,
2934                    );
2935                    if !scratch.corner_boxes.is_empty() {
2936                        for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
2937                            let b0: usize = (bx0 as usize) * 4;
2938                            let b1: usize = (bx1 as usize) * 4;
2939                            for y in by0..by1 {
2940                                if let Some(row) = band.row_slice_mut(y) {
2941                                    scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
2942                                }
2943                            }
2944                        }
2945                        corner_mode = 2;
2946                    }
2947                }
2948            } else if !item_masks.is_empty() {
2949                scratch.corner_boxes.clear();
2950                scratch.saved_bytes.clear();
2951                for mask in item_masks.iter().copied() {
2952                    collect_rounded_clip_boxes(
2953                        mask,
2954                        active_clip,
2955                        (fb_w, band_y0, band_y1),
2956                        &mut scratch.corner_boxes,
2957                    );
2958                }
2959                if !scratch.corner_boxes.is_empty() {
2960                    for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
2961                        let b0: usize = (bx0 as usize) * 4;
2962                        let b1: usize = (bx1 as usize) * 4;
2963                        for y in by0..by1 {
2964                            if let Some(row) = band.row_slice_mut(y) {
2965                                scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
2966                            }
2967                        }
2968                    }
2969                    corner_mode = 2;
2970                }
2971            }
2972            let cmd: &DrawCommand = &commands[item.get_cmd_index()];
2973            shaded += match cmd {
2974                DrawCommand::Clear(color) => {
2975                    if active_clip.get_x() <= 0.0
2976                        && active_clip.get_width() >= (band.width() as f32)
2977                        && active_clip.get_y() <= (band_y0 as f32)
2978                        && active_clip.bottom() >= (band_y1 as f32)
2979                    {
2980                        band.clear(*color);
2981                        (band.width() as usize) * ((band_y1 - band_y0) as usize)
2982                    } else {
2983                        Self::fill_rect_clipped(band, active_clip, *color, active_clip)
2984                    }
2985                }
2986                DrawCommand::FillRoundedRect {
2987                    rect,
2988                    color,
2989                    radius,
2990                    border,
2991                } => {
2992                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
2993                    let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
2994                    let bw: f32 = if border.get_width() > 0.0 {
2995                        (border.get_width() * scale).max(1.0)
2996                    } else {
2997                        0.0
2998                    };
2999                    let phys_border: Border = Border::new(bw, border.get_color());
3000                    Self::raster_rounded_rect(
3001                        band,
3002                        phys_rect,
3003                        *color,
3004                        phys_radius,
3005                        phys_border,
3006                        active_clip,
3007                        aa,
3008                    )
3009                }
3010                DrawCommand::LinearGradientRect {
3011                    rect,
3012                    gradient,
3013                    radius,
3014                } => {
3015                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
3016                    let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
3017                    Self::raster_gradient_rect(
3018                        band,
3019                        phys_rect,
3020                        *gradient,
3021                        phys_radius,
3022                        active_clip,
3023                        aa,
3024                    )
3025                }
3026                DrawCommand::BoxShadow {
3027                    rect,
3028                    radius,
3029                    shadow,
3030                } => {
3031                    let spread: f32 = shadow.get_spread_radius() * scale;
3032                    let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
3033                    let sigma: f32 = (blur * 0.5).max(0.75);
3034                    let pad: f32 = (sigma * 3.0).ceil();
3035                    let base_rect: Rect = snap_physical_rect(*rect, scale);
3036                    let caster_rect: Rect = Rect::new(
3037                        base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
3038                        base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
3039                        (base_rect.get_width() + spread * 2.0).max(1.0),
3040                        (base_rect.get_height() + spread * 2.0).max(1.0),
3041                    );
3042                    let shadow_rect: Rect = Rect::new(
3043                        caster_rect.get_x() - pad,
3044                        caster_rect.get_y() - pad,
3045                        caster_rect.get_width() + pad * 2.0,
3046                        caster_rect.get_height() + pad * 2.0,
3047                    );
3048                    let raw_r: CornerRadius = Self::scale_radius(*radius, scale);
3049                    let phys_radius: CornerRadius = CornerRadius::new(
3050                        (raw_r.get_top_left() + spread).max(0.0),
3051                        (raw_r.get_top_right() + spread).max(0.0),
3052                        (raw_r.get_bottom_right() + spread).max(0.0),
3053                        (raw_r.get_bottom_left() + spread).max(0.0),
3054                    );
3055                    Self::raster_shadow(
3056                        band,
3057                        (shadow_rect, caster_rect, active_clip),
3058                        phys_radius,
3059                        sigma,
3060                        shadow.get_color(),
3061                        (item.get_opaque_cutout_h(), item.get_opaque_cutout_v()),
3062                    )
3063                }
3064                DrawCommand::TextRun { style, .. } => {
3065                    let g_start: usize = item.get_glyph_run_start() as usize;
3066                    let g_len: usize = item.get_glyph_run_len() as usize;
3067                    if let Some(run_slice) = positioned_glyphs.get(g_start..g_start + g_len) {
3068                        Self::raster_text_run_band(
3069                            band,
3070                            run_slice,
3071                            style.get_color(),
3072                            active_clip,
3073                            glyph_atlas,
3074                        )
3075                    } else {
3076                        0
3077                    }
3078                }
3079                DrawCommand::TextCaret { color, .. } => {
3080                    let cidx: usize = item.get_caret_rect_idx() as usize;
3081                    if let Some(&caret_rect) = caret_rects.get(cidx) {
3082                        Self::raster_rounded_rect(
3083                            band,
3084                            caret_rect,
3085                            *color,
3086                            CornerRadius::all(0.5 * scale),
3087                            Border::default(),
3088                            active_clip,
3089                            aa,
3090                        )
3091                    } else {
3092                        0
3093                    }
3094                }
3095                DrawCommand::Image {
3096                    rect,
3097                    buffer,
3098                    radius,
3099                } => {
3100                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
3101                    let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
3102                    Self::raster_image(band, phys_rect, buffer, phys_radius, active_clip, aa)
3103                }
3104                DrawCommand::Line {
3105                    from,
3106                    to,
3107                    color,
3108                    width,
3109                } => {
3110                    let p0: Point = Point::new(from.get_x() * scale, from.get_y() * scale);
3111                    let p1: Point = Point::new(to.get_x() * scale, to.get_y() * scale);
3112                    Self::raster_line(
3113                        band,
3114                        p0,
3115                        p1,
3116                        *color,
3117                        (width * scale).max(1.0),
3118                        active_clip,
3119                        aa,
3120                    )
3121                }
3122                DrawCommand::Circle {
3123                    center,
3124                    radius,
3125                    color,
3126                } => {
3127                    let c: Point = Point::new(center.get_x() * scale, center.get_y() * scale);
3128                    Self::raster_circle(band, c, radius * scale, *color, active_clip, aa)
3129                }
3130                DrawCommand::Triangle { p0, p1, p2, color } => {
3131                    let v0: Point = Point::new(p0.get_x() * scale, p0.get_y() * scale);
3132                    let v1: Point = Point::new(p1.get_x() * scale, p1.get_y() * scale);
3133                    let v2: Point = Point::new(p2.get_x() * scale, p2.get_y() * scale);
3134                    Self::raster_triangle(band, v0, v1, v2, *color, active_clip, aa)
3135                }
3136                DrawCommand::SpriteRegion {
3137                    rect,
3138                    buffer,
3139                    src_rect,
3140                    tint,
3141                } => {
3142                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
3143                    Self::raster_sprite_region(
3144                        band,
3145                        phys_rect,
3146                        buffer,
3147                        *src_rect,
3148                        *tint,
3149                        active_clip,
3150                        aa,
3151                    )
3152                }
3153                DrawCommand::PushClip(_)
3154                | DrawCommand::PushRoundedClip { .. }
3155                | DrawCommand::PopClip => 0,
3156            };
3157            if corner_mode == 1 {
3158                Self::restore_single_cached_rounded_corners(band, corner_masks, &scratch);
3159            } else if corner_mode == 2 {
3160                let multi_mask: bool = item_masks.len() > 1;
3161                let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
3162                let mut byte_cursor: usize = 0;
3163                for (box_idx, &(bx0, by0, bx1, by1)) in scratch.corner_boxes.iter().enumerate() {
3164                    for y in by0..by1 {
3165                        let Some(row) = band.row_slice_mut(y) else {
3166                            byte_cursor += ((bx1 - bx0) as usize) * 4;
3167                            continue;
3168                        };
3169                        for x in bx0..bx1 {
3170                            let saved_rgba: [u8; 4] = [
3171                                saved_bytes[byte_cursor],
3172                                saved_bytes[byte_cursor + 1],
3173                                saved_bytes[byte_cursor + 2],
3174                                saved_bytes[byte_cursor + 3],
3175                            ];
3176                            byte_cursor += 4;
3177                            if multi_mask
3178                                && scratch.corner_boxes[..box_idx].iter().any(
3179                                    |&(px0, py0, px1, py1): &(u32, u32, u32, u32)| {
3180                                        x >= px0 && x < px1 && y >= py0 && y < py1
3181                                    },
3182                                )
3183                            {
3184                                continue;
3185                            }
3186                            let mut cov: f32 = 1.0;
3187                            for mask in item_masks.iter().copied() {
3188                                cov *= rounded_clip_coverage_cached(x, y, mask, corner_masks, aa);
3189                                if cov <= 0.0005 {
3190                                    break;
3191                                }
3192                            }
3193                            let dst_off: usize = (x as usize) * 4;
3194                            if cov <= 0.0005 {
3195                                row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
3196                            } else if cov < 0.9995 {
3197                                lerp_pixel_slice_from_saved_linear(
3198                                    &mut row[dst_off..dst_off + 4],
3199                                    saved_rgba,
3200                                    cov,
3201                                );
3202                            }
3203                        }
3204                    }
3205                }
3206            }
3207        }
3208        if has_any_rounded {
3209            let _: bool = BAND_CORNER_SCRATCH
3210                .try_with(|cell: &RefCell<BandCornerScratch>| {
3211                    if let Ok(mut guard) = cell.try_borrow_mut() {
3212                        *guard = scratch;
3213                    }
3214                })
3215                .is_ok();
3216        }
3217        shaded
3218    }
3219
3220    /// Scales a logical rectangle into physical pixels.
3221    ///
3222    /// # Arguments
3223    ///
3224    /// - `Rect` - Logical rectangle.
3225    /// - `f32` - Scale factor.
3226    ///
3227    /// # Returns
3228    ///
3229    /// - `Rect` - Physical pixel rectangle.
3230    fn scale_rect(rect: Rect, scale: f32) -> Rect {
3231        Rect::new(
3232            rect.get_x() * scale,
3233            rect.get_y() * scale,
3234            rect.get_width() * scale,
3235            rect.get_height() * scale,
3236        )
3237    }
3238
3239    /// Scales logical corner radii into physical pixel radii.
3240    ///
3241    /// # Arguments
3242    ///
3243    /// - `CornerRadius` - Logical corner radii.
3244    /// - `f32` - Scale factor.
3245    ///
3246    /// # Returns
3247    ///
3248    /// - `CornerRadius` - Physical corner radii.
3249    fn scale_radius(radius: CornerRadius, scale: f32) -> CornerRadius {
3250        CornerRadius::new(
3251            radius.get_top_left() * scale,
3252            radius.get_top_right() * scale,
3253            radius.get_bottom_right() * scale,
3254            radius.get_bottom_left() * scale,
3255        )
3256    }
3257
3258    /// Fast axis-aligned solid rectangle fill clipped against `clip`.
3259    ///
3260    /// # Arguments
3261    ///
3262    /// - `&mut PixelBand<'_>` - Target pixel band.
3263    /// - `Rect` - Physical rectangle.
3264    /// - `Color` - Fill color.
3265    /// - `Rect` - Active clip rectangle.
3266    ///
3267    /// # Returns
3268    ///
3269    /// - `usize` - Number of pixels shaded.
3270    fn fill_rect_clipped(band: &mut PixelBand<'_>, rect: Rect, color: Color, clip: Rect) -> usize {
3271        if color.get_a() == 0 {
3272            return 0;
3273        }
3274        let Some(vis) = rect.intersect(clip) else {
3275            return 0;
3276        };
3277        let fb_w: u32 = band.width();
3278        let band_y0: u32 = band.y_offset();
3279        let band_y1: u32 = band.y_end();
3280        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
3281        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
3282        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
3283        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
3284        if x0 >= x1 || y0 >= y1 {
3285            return 0;
3286        }
3287        let span_len: usize = (x1 - x0) as usize;
3288        let rows: usize = (y1 - y0) as usize;
3289        let sa: u8 = color.get_a();
3290        if sa == 255 {
3291            band.fill_rect_opaque_preclipped(
3292                x0,
3293                x1,
3294                y0,
3295                y1,
3296                [color.get_r(), color.get_g(), color.get_b(), 255],
3297            );
3298        } else if let Some((rows_buf, row_stride)) = band.rows_slice_mut(y0, y1) {
3299            let bx0: usize = (x0 as usize) * 4;
3300            let bx1: usize = (x1 as usize) * 4;
3301            if span_len.saturating_mul(rows) >= 512 {
3302                let luts: ([u8; 256], [u8; 256], [u8; 256], [u8; 256]) =
3303                    build_linear_blend_luts(color);
3304                for row in rows_buf.chunks_exact_mut(row_stride) {
3305                    fill_span_linear_luts_slice(&mut row[bx0..bx1], &luts);
3306                }
3307            } else {
3308                for row in rows_buf.chunks_exact_mut(row_stride) {
3309                    fill_span_linear_slice(&mut row[bx0..bx1], color);
3310                }
3311            }
3312        }
3313        span_len * rows
3314    }
3315
3316    /// Precomputes 1D horizontal edge samples for vertical side strip `x_start..x_end` into stack buffer `out`.
3317    ///
3318    /// # Arguments
3319    ///
3320    /// - `(u32, u32)` - Inclusive/exclusive horizontal span `(x_start, x_end)`.
3321    /// - `(f32, f32, f32, f32)` - Box geometry `(center_x, half_w, half_h, border_w)`.
3322    /// - `(Color, Border)` - Fill color and border specification.
3323    /// - `([f32; 4], [f32; 4])` - Precomputed linear fill and border tuples `(lin_r, lin_g, lin_b, alpha_norm)`.
3324    /// - `AntialiasingMode` - Active anti-aliasing policy.
3325    /// - `&mut [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP]` - Stack-allocated sample destination.
3326    ///
3327    /// # Returns
3328    ///
3329    /// - `(usize, usize)` - Tuple `(sample_count, shaded_count)` written to `out`.
3330    #[must_use]
3331    fn build_vertical_edge_strip(
3332        x_span: (u32, u32),
3333        geom: (f32, f32, f32, f32),
3334        colors: (Color, Border),
3335        lin_colors: ([f32; 4], [f32; 4]),
3336        aa: AntialiasingMode,
3337        out: &mut [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP],
3338    ) -> (usize, usize) {
3339        let (x_start, x_end): (u32, u32) = x_span;
3340        let (cx, half_w, half_h, bw): (f32, f32, f32, f32) = geom;
3341        let (color, border): (Color, Border) = colors;
3342        let (fill_lin, border_lin): ([f32; 4], [f32; 4]) = lin_colors;
3343        let has_border: bool = bw > 0.0 && border.get_color().get_a() > 0;
3344        let inner_hw: f32 = (half_w - bw).max(0.0);
3345        let inner_hh: f32 = (half_h - bw).max(0.0);
3346        let mut len: usize = 0;
3347        let mut shaded: usize = 0;
3348        for x in x_start..x_end {
3349            let px: f32 = (x as f32) + 0.5 - cx;
3350            let dist: f32 = px.abs() - half_w;
3351            if dist > 0.85 {
3352                continue;
3353            }
3354            if !has_border {
3355                if dist < -0.85 {
3356                    let sa: u8 = color.get_a();
3357                    if sa > 0 {
3358                        let a: f32 = (sa as f32) * (1.0 / 255.0);
3359                        out[len] = EdgeBlendSample {
3360                            x,
3361                            rgba: [color.get_r(), color.get_g(), color.get_b(), 255],
3362                            sr_a: fill_lin[0] * a,
3363                            sg_a: fill_lin[1] * a,
3364                            sb_a: fill_lin[2] * a,
3365                            inv_a: 1.0 - a,
3366                            sa_u32: sa as u32,
3367                            is_opaque: sa == 255,
3368                        };
3369                        len += 1;
3370                        shaded += 1;
3371                    }
3372                    continue;
3373                }
3374                let outer_cov: f32 = sdf_coverage(dist, aa);
3375                if outer_cov > 0.0 && color.get_a() > 0 {
3376                    let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * outer_cov;
3377                    shaded += 1;
3378                    if alpha_f > 0.0002 {
3379                        let a: f32 = alpha_f.clamp(0.0, 1.0);
3380                        out[len] = EdgeBlendSample {
3381                            x,
3382                            rgba: [color.get_r(), color.get_g(), color.get_b(), 255],
3383                            sr_a: fill_lin[0] * a,
3384                            sg_a: fill_lin[1] * a,
3385                            sb_a: fill_lin[2] * a,
3386                            inv_a: 1.0 - a,
3387                            sa_u32: (a * 255.0) as u32,
3388                            is_opaque: a >= 0.9995,
3389                        };
3390                        len += 1;
3391                    }
3392                }
3393                continue;
3394            }
3395            if dist < -(bw + 0.85) {
3396                let sa: u8 = color.get_a();
3397                if sa > 0 {
3398                    let a: f32 = (sa as f32) * (1.0 / 255.0);
3399                    out[len] = EdgeBlendSample {
3400                        x,
3401                        rgba: [color.get_r(), color.get_g(), color.get_b(), 255],
3402                        sr_a: fill_lin[0] * a,
3403                        sg_a: fill_lin[1] * a,
3404                        sb_a: fill_lin[2] * a,
3405                        inv_a: 1.0 - a,
3406                        sa_u32: sa as u32,
3407                        is_opaque: sa == 255,
3408                    };
3409                    len += 1;
3410                    shaded += 1;
3411                }
3412                continue;
3413            }
3414            let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
3415                px.abs() - inner_hw
3416            } else {
3417                2.0
3418            };
3419            if dist < -0.85 && inner_dist > 0.85 {
3420                let bc: Color = border.get_color();
3421                let sa: u8 = bc.get_a();
3422                let a: f32 = (sa as f32) * (1.0 / 255.0);
3423                out[len] = EdgeBlendSample {
3424                    x,
3425                    rgba: [bc.get_r(), bc.get_g(), bc.get_b(), 255],
3426                    sr_a: border_lin[0] * a,
3427                    sg_a: border_lin[1] * a,
3428                    sb_a: border_lin[2] * a,
3429                    inv_a: 1.0 - a,
3430                    sa_u32: sa as u32,
3431                    is_opaque: sa == 255,
3432                };
3433                len += 1;
3434                shaded += 1;
3435                continue;
3436            }
3437            let outer_cov: f32 = sdf_coverage(dist, aa);
3438            if outer_cov <= 0.0 {
3439                continue;
3440            }
3441            let inner_cov: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
3442                sdf_coverage(inner_dist, aa)
3443            } else {
3444                0.0
3445            };
3446            let mixed: Color =
3447                composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
3448            let sa: u8 = mixed.get_a();
3449            if sa > 0 {
3450                let a: f32 = (sa as f32) * (1.0 / 255.0);
3451                out[len] = EdgeBlendSample {
3452                    x,
3453                    rgba: [mixed.get_r(), mixed.get_g(), mixed.get_b(), 255],
3454                    sr_a: SRGB_TO_LIN_LUT[mixed.get_r() as usize] * a,
3455                    sg_a: SRGB_TO_LIN_LUT[mixed.get_g() as usize] * a,
3456                    sb_a: SRGB_TO_LIN_LUT[mixed.get_b() as usize] * a,
3457                    inv_a: 1.0 - a,
3458                    sa_u32: sa as u32,
3459                    is_opaque: sa == 255,
3460                };
3461                len += 1;
3462                shaded += 1;
3463            }
3464        }
3465        (len, shaded)
3466    }
3467
3468    /// Rasterizes a rounded rectangle with optional border using edge-bounded 4x4 RGSS supersampling, precomputed 1D vertical edge strips, and linear-light spans.
3469    ///
3470    /// # Arguments
3471    ///
3472    /// - `&mut PixelBand<'_>` - Target pixel band.
3473    /// - `Rect` - Physical rectangle bounds.
3474    /// - `Color` - Fill color.
3475    /// - `CornerRadius` - Physical corner radii.
3476    /// - `Border` - Physical border specification.
3477    /// - `Rect` - Active clip bounds.
3478    /// - `AntialiasingMode` - Active AA policy.
3479    ///
3480    /// # Returns
3481    ///
3482    /// - `usize` - Number of pixels shaded.
3483    fn raster_rounded_rect(
3484        band: &mut PixelBand<'_>,
3485        rect: Rect,
3486        color: Color,
3487        radius: CornerRadius,
3488        border: Border,
3489        clip: Rect,
3490        aa: AntialiasingMode,
3491    ) -> usize {
3492        let Some(vis) = rect.intersect(clip) else {
3493            return 0;
3494        };
3495        let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
3496        if radius.max_radius() <= 0.0 && !has_border {
3497            return Self::fill_rect_clipped(band, rect, color, clip);
3498        }
3499        let half_w: f32 = rect.get_width() * 0.5;
3500        let half_h: f32 = rect.get_height() * 0.5;
3501        let cx: f32 = rect.get_x() + half_w;
3502        let cy: f32 = rect.get_y() + half_h;
3503        let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
3504        let fb_w: u32 = band.width();
3505        let band_y0: u32 = band.y_offset();
3506        let band_y1: u32 = band.y_end();
3507        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
3508        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
3509        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
3510        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
3511        if x0 >= x1 || y0 >= y1 {
3512            return 0;
3513        }
3514        let effective_r: f32 = radius.max_radius().min(half_w).min(half_h);
3515        let safe_inset: f32 = effective_r.max(border_w) + 1.5;
3516        let edge_inset: f32 = border_w + 1.5;
3517        let iy0: u32 = ((rect.get_y() + safe_inset).ceil().max(0.0) as u32).clamp(y0, y1);
3518        let iy1: u32 = ((rect.bottom() - safe_inset).floor().max(0.0) as u32).clamp(y0, y1);
3519        let ix0: u32 = ((rect.get_x() + edge_inset).ceil().max(0.0) as u32).clamp(x0, x1);
3520        let ix1: u32 = ((rect.right() - edge_inset).floor().max(0.0) as u32).clamp(x0, x1);
3521        let cx0: u32 = ((rect.get_x() + safe_inset).ceil().max(0.0) as u32).clamp(x0, x1);
3522        let cx1: u32 = ((rect.right() - safe_inset).floor().max(0.0) as u32).clamp(x0, x1);
3523        let has_interior: bool = iy0 < iy1 && ix0 < ix1;
3524        let has_center_band: bool = cx0 < cx1;
3525        let fill_lin: [f32; 4] = [
3526            SRGB_TO_LIN_LUT[color.get_r() as usize],
3527            SRGB_TO_LIN_LUT[color.get_g() as usize],
3528            SRGB_TO_LIN_LUT[color.get_b() as usize],
3529            (color.get_a() as f32) / 255.0,
3530        ];
3531        let bc: Color = border.get_color();
3532        let border_lin: [f32; 4] = [
3533            SRGB_TO_LIN_LUT[bc.get_r() as usize],
3534            SRGB_TO_LIN_LUT[bc.get_g() as usize],
3535            SRGB_TO_LIN_LUT[bc.get_b() as usize],
3536            (bc.get_a() as f32) / 255.0,
3537        ];
3538        let interior_luts: Option<RgbaLutQuad> = if has_interior
3539            && color.get_a() > 0
3540            && color.get_a() < 255
3541            && ((ix1 - ix0) as usize).saturating_mul((iy1 - iy0) as usize) >= 512
3542        {
3543            Some(build_linear_blend_luts(color))
3544        } else {
3545            None
3546        };
3547        let mut shaded: usize = 0;
3548        if has_interior {
3549            for y in y0..iy0 {
3550                let py: f32 = (y as f32) + 0.5 - cy;
3551                let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
3552                if has_center_band {
3553                    shaded += Self::raster_rounded_corner_band_row(
3554                        band,
3555                        y,
3556                        (x0, cx0, cx1, x1),
3557                        box_geom,
3558                        radius,
3559                        (color, border, fill_lin, border_lin),
3560                        (interior_luts.as_ref(), aa),
3561                    );
3562                } else if let Some(row) = band.row_slice_mut(y) {
3563                    for x in x0..x1 {
3564                        shaded += Self::shade_rounded_pixel_row(
3565                            row,
3566                            x,
3567                            box_geom,
3568                            radius,
3569                            (color, border, fill_lin, border_lin),
3570                            aa,
3571                        );
3572                    }
3573                }
3574            }
3575            let use_1d_strip: bool = ((ix0 - x0) as usize) <= ROUNDED_EDGE_STRIP_CAP
3576                && ((x1 - ix1) as usize) <= ROUNDED_EDGE_STRIP_CAP;
3577            if use_1d_strip {
3578                let mut left_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
3579                    [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
3580                let mut right_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
3581                    [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
3582                let (left_len, left_shaded): (usize, usize) = if x0 < ix0 {
3583                    Self::build_vertical_edge_strip(
3584                        (x0, ix0),
3585                        (cx, half_w, half_h, border_w),
3586                        (color, border),
3587                        (fill_lin, border_lin),
3588                        aa,
3589                        &mut left_strip,
3590                    )
3591                } else {
3592                    (0, 0)
3593                };
3594                let (right_len, right_shaded): (usize, usize) = if ix1 < x1 {
3595                    Self::build_vertical_edge_strip(
3596                        (ix1, x1),
3597                        (cx, half_w, half_h, border_w),
3598                        (color, border),
3599                        (fill_lin, border_lin),
3600                        aa,
3601                        &mut right_strip,
3602                    )
3603                } else {
3604                    (0, 0)
3605                };
3606                let left_slice: &[EdgeBlendSample] = &left_strip[..left_len];
3607                let right_slice: &[EdgeBlendSample] = &right_strip[..right_len];
3608                let edge_shaded: usize = left_shaded + right_shaded;
3609                let has_edges: bool = left_len > 0 || right_len > 0;
3610                let fill_visible: bool = color.get_a() > 0;
3611                let fill_opaque: bool = color.get_a() == 255;
3612                let fill_rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
3613                let interior_span: usize = (ix1 - ix0) as usize;
3614                let ix0_b: usize = (ix0 as usize) * 4;
3615                let ix1_b: usize = (ix1 as usize) * 4;
3616                if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
3617                    for row in rows_buf.chunks_exact_mut(row_stride) {
3618                        if fill_visible {
3619                            if fill_opaque {
3620                                fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
3621                            } else if let Some(ref luts) = interior_luts {
3622                                fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
3623                            } else {
3624                                fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
3625                            }
3626                            shaded += interior_span;
3627                        }
3628                        if has_edges {
3629                            if left_len > 0 {
3630                                apply_edge_strip_row(row, left_slice);
3631                            }
3632                            if right_len > 0 {
3633                                apply_edge_strip_row(row, right_slice);
3634                            }
3635                            shaded += edge_shaded;
3636                        }
3637                    }
3638                }
3639            } else {
3640                let fill_visible: bool = color.get_a() > 0;
3641                let fill_opaque: bool = color.get_a() == 255;
3642                let fill_rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
3643                let interior_span: usize = (ix1 - ix0) as usize;
3644                let ix0_b: usize = (ix0 as usize) * 4;
3645                let ix1_b: usize = (ix1 as usize) * 4;
3646                if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
3647                    for (y, row) in (iy0..iy1).zip(rows_buf.chunks_exact_mut(row_stride)) {
3648                        let py: f32 = (y as f32) + 0.5 - cy;
3649                        let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
3650                        if fill_visible {
3651                            if fill_opaque {
3652                                fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
3653                            } else if let Some(ref luts) = interior_luts {
3654                                fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
3655                            } else {
3656                                fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
3657                            }
3658                            shaded += interior_span;
3659                        }
3660                        for x in x0..ix0 {
3661                            shaded += Self::shade_rounded_pixel_row(
3662                                row,
3663                                x,
3664                                box_geom,
3665                                radius,
3666                                (color, border, fill_lin, border_lin),
3667                                aa,
3668                            );
3669                        }
3670                        for x in ix1..x1 {
3671                            shaded += Self::shade_rounded_pixel_row(
3672                                row,
3673                                x,
3674                                box_geom,
3675                                radius,
3676                                (color, border, fill_lin, border_lin),
3677                                aa,
3678                            );
3679                        }
3680                    }
3681                }
3682            }
3683            for y in iy1..y1 {
3684                let py: f32 = (y as f32) + 0.5 - cy;
3685                let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
3686                if has_center_band {
3687                    shaded += Self::raster_rounded_corner_band_row(
3688                        band,
3689                        y,
3690                        (x0, cx0, cx1, x1),
3691                        box_geom,
3692                        radius,
3693                        (color, border, fill_lin, border_lin),
3694                        (interior_luts.as_ref(), aa),
3695                    );
3696                } else if let Some(row) = band.row_slice_mut(y) {
3697                    for x in x0..x1 {
3698                        shaded += Self::shade_rounded_pixel_row(
3699                            row,
3700                            x,
3701                            box_geom,
3702                            radius,
3703                            (color, border, fill_lin, border_lin),
3704                            aa,
3705                        );
3706                    }
3707                }
3708            }
3709            return shaded;
3710        }
3711        for y in y0..y1 {
3712            let py: f32 = (y as f32) + 0.5 - cy;
3713            let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
3714            if has_center_band {
3715                shaded += Self::raster_rounded_corner_band_row(
3716                    band,
3717                    y,
3718                    (x0, cx0, cx1, x1),
3719                    box_geom,
3720                    radius,
3721                    (color, border, fill_lin, border_lin),
3722                    (interior_luts.as_ref(), aa),
3723                );
3724            } else if let Some(row) = band.row_slice_mut(y) {
3725                for x in x0..x1 {
3726                    shaded += Self::shade_rounded_pixel_row(
3727                        row,
3728                        x,
3729                        box_geom,
3730                        radius,
3731                        (color, border, fill_lin, border_lin),
3732                        aa,
3733                    );
3734                }
3735            }
3736        }
3737        shaded
3738    }
3739
3740    /// Rasterizes one corner-band row `[x0, cx0)`, `[cx0, cx1)`, and `[cx1, x1)` using analytical exterior rejection and bulk interior span fills.
3741    ///
3742    /// # Arguments
3743    ///
3744    /// - `&mut PixelBand<'_>` - Target pixel band.
3745    /// - `u32` - Global physical Y row coordinate.
3746    /// - `(u32, u32, u32, u32)` - Clamped horizontal bounds `(x0, cx0, cx1, x1)`.
3747    /// - `(f32, f32, f32, f32)` - Box geometry `(cx, py, half_w, half_h)`.
3748    /// - `CornerRadius` - Physical corner radii.
3749    /// - `(Color, Border, [f32; 4], [f32; 4])` - Fill color, border spec, and precomputed linear fill/border tuples.
3750    /// - `(Option<&RgbaLutQuad>, AntialiasingMode)` - Optional prebuilt linear-light LUT and active AA policy.
3751    ///
3752    /// # Returns
3753    ///
3754    /// - `usize` - Exact shaded pixel count matching per-pixel evaluation.
3755    #[inline(always)]
3756    fn raster_rounded_corner_band_row(
3757        band: &mut PixelBand<'_>,
3758        y: u32,
3759        x_bounds: (u32, u32, u32, u32),
3760        geom: (f32, f32, f32, f32),
3761        radius: CornerRadius,
3762        style_colors: (Color, Border, [f32; 4], [f32; 4]),
3763        opts: (Option<&RgbaLutQuad>, AntialiasingMode),
3764    ) -> usize {
3765        let (interior_luts, aa): (Option<&RgbaLutQuad>, AntialiasingMode) = opts;
3766        let Some(row) = band.row_slice_mut(y) else {
3767            return 0;
3768        };
3769        let (x0, cx0, cx1, x1): (u32, u32, u32, u32) = x_bounds;
3770        let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
3771        let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
3772            style_colors;
3773        let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
3774        let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
3775        let inner_thresh: f32 = if has_border {
3776            -(border_w + 0.85)
3777        } else {
3778            -0.85
3779        };
3780        let py_abs: f32 = py.abs();
3781        let fill_visible: bool = color.get_a() > 0;
3782        let fill_opaque: bool = color.get_a() == 255;
3783        let fill_rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
3784        let mut shaded: usize = 0;
3785        if x0 < cx0 {
3786            let pure_left: bool = ((cx0 - 1) as f32) + 0.5 < cx;
3787            if pure_left {
3788                let r_l: f32 = (if py < 0.0 {
3789                    radius.get_top_left()
3790                } else {
3791                    radius.get_bottom_left()
3792                })
3793                .min(half_w)
3794                .min(half_h)
3795                .max(0.0);
3796                let qy: f32 = py_abs - half_h + r_l;
3797                let r_out: f32 = r_l + 0.85;
3798                if qy <= r_out + 0.05 {
3799                    let vis_l0: u32 = if qy > 0.0 {
3800                        let max_vis_abs: f32 =
3801                            (half_w - r_l) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
3802                        ((cx - max_vis_abs - 0.5).floor().max(0.0) as u32).clamp(x0, cx0)
3803                    } else {
3804                        x0
3805                    };
3806                    let r_in: f32 = r_l + inner_thresh;
3807                    let max_in_abs: f32 = if qy <= 0.0 {
3808                        if qy < r_in - 0.05 {
3809                            half_w + inner_thresh - 1.0
3810                        } else {
3811                            -1.0
3812                        }
3813                    } else if r_in > 0.0 && qy < r_in - 0.05 {
3814                        (half_w - r_l) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
3815                    } else {
3816                        -1.0
3817                    };
3818                    let in_l0: u32 = if max_in_abs > 0.0 {
3819                        ((cx - max_in_abs - 0.5).ceil().max(0.0) as u32).clamp(vis_l0, cx0)
3820                    } else {
3821                        cx0
3822                    };
3823                    for x in vis_l0..in_l0 {
3824                        shaded +=
3825                            Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
3826                    }
3827                    if in_l0 < cx0 && fill_visible {
3828                        let b0: usize = (in_l0 as usize) * 4;
3829                        let b1: usize = (cx0 as usize) * 4;
3830                        if fill_opaque {
3831                            fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
3832                        } else if let Some(luts) = interior_luts {
3833                            fill_span_linear_luts_slice(&mut row[b0..b1], luts);
3834                        } else {
3835                            fill_span_linear_slice(&mut row[b0..b1], color);
3836                        }
3837                        shaded += (cx0 - in_l0) as usize;
3838                    }
3839                }
3840            } else {
3841                for x in x0..cx0 {
3842                    shaded += Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
3843                }
3844            }
3845        }
3846        if cx1 < x1 {
3847            let pure_right: bool = (cx1 as f32) + 0.5 >= cx;
3848            if pure_right {
3849                let r_r: f32 = (if py < 0.0 {
3850                    radius.get_top_right()
3851                } else {
3852                    radius.get_bottom_right()
3853                })
3854                .min(half_w)
3855                .min(half_h)
3856                .max(0.0);
3857                let qy: f32 = py_abs - half_h + r_r;
3858                let r_out: f32 = r_r + 0.85;
3859                if qy <= r_out + 0.05 {
3860                    let vis_r1: u32 = if qy > 0.0 {
3861                        let max_vis_abs: f32 =
3862                            (half_w - r_r) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
3863                        ((cx + max_vis_abs + 0.5).ceil().max(0.0) as u32).clamp(cx1, x1)
3864                    } else {
3865                        x1
3866                    };
3867                    let r_in: f32 = r_r + inner_thresh;
3868                    let max_in_abs: f32 = if qy <= 0.0 {
3869                        if qy < r_in - 0.05 {
3870                            half_w + inner_thresh - 1.0
3871                        } else {
3872                            -1.0
3873                        }
3874                    } else if r_in > 0.0 && qy < r_in - 0.05 {
3875                        (half_w - r_r) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
3876                    } else {
3877                        -1.0
3878                    };
3879                    let in_r1: u32 = if max_in_abs > 0.0 {
3880                        ((cx + max_in_abs - 0.5).floor().max(0.0) as u32).clamp(cx1, vis_r1)
3881                    } else {
3882                        cx1
3883                    };
3884                    if cx1 < in_r1 && fill_visible {
3885                        let b0: usize = (cx1 as usize) * 4;
3886                        let b1: usize = (in_r1 as usize) * 4;
3887                        if fill_opaque {
3888                            fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
3889                        } else if let Some(luts) = interior_luts {
3890                            fill_span_linear_luts_slice(&mut row[b0..b1], luts);
3891                        } else {
3892                            fill_span_linear_slice(&mut row[b0..b1], color);
3893                        }
3894                        shaded += (in_r1 - cx1) as usize;
3895                    }
3896                    for x in in_r1..vis_r1 {
3897                        shaded +=
3898                            Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
3899                    }
3900                }
3901            } else {
3902                for x in cx1..x1 {
3903                    shaded += Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
3904                }
3905            }
3906        }
3907        let dist_y: f32 = py_abs - half_h;
3908        let outer_cov: f32 = sdf_coverage(dist_y, aa);
3909        if outer_cov > 0.0 {
3910            let b0: usize = (cx0 as usize) * 4;
3911            let b1: usize = (cx1 as usize) * 4;
3912            if has_border {
3913                let inner_hh: f32 = (half_h - border_w).max(0.0);
3914                let inner_cov: f32 = if inner_hh > 0.0 && half_w > border_w {
3915                    sdf_coverage(py_abs - inner_hh, aa)
3916                } else {
3917                    0.0
3918                };
3919                let mixed: Color = composite_fill_and_border_precomputed(
3920                    fill_lin, border_lin, outer_cov, inner_cov,
3921                );
3922                if mixed.get_a() > 0 {
3923                    fill_span_linear_slice(&mut row[b0..b1], mixed);
3924                }
3925                shaded += (cx1 - cx0) as usize;
3926            } else if fill_visible {
3927                let row_color: Color = color.multiply_alpha(outer_cov);
3928                if row_color == color
3929                    && let Some(luts) = interior_luts
3930                {
3931                    fill_span_linear_luts_slice(&mut row[b0..b1], luts);
3932                } else {
3933                    fill_span_linear_slice(&mut row[b0..b1], row_color);
3934                }
3935                shaded += (cx1 - cx0) as usize;
3936            }
3937        }
3938        shaded
3939    }
3940
3941    /// Evaluates fast early-rejected analytical SDF and edge-only 4x4 RGSS coverage directly onto a mutable scanline slice.
3942    ///
3943    /// # Arguments
3944    ///
3945    /// - `&mut [u8]` - Target scanline RGBA8 slice.
3946    /// - `u32` - Global pixel X coordinate.
3947    /// - `(f32, f32, f32, f32)` - Box geometry `(center_x, rel_py, half_w, half_h)`.
3948    /// - `CornerRadius` - Physical corner radii.
3949    /// - `(Color, Border, [f32; 4], [f32; 4])` - Fill color, border spec, and precomputed linear fill/border tuples.
3950    /// - `AntialiasingMode` - Active AA policy.
3951    ///
3952    /// # Returns
3953    ///
3954    /// - `usize` - `1` if the pixel was shaded, `0` otherwise.
3955    #[inline(always)]
3956    fn shade_rounded_pixel_row(
3957        row: &mut [u8],
3958        x: u32,
3959        geom: (f32, f32, f32, f32),
3960        radius: CornerRadius,
3961        style_colors: (Color, Border, [f32; 4], [f32; 4]),
3962        aa: AntialiasingMode,
3963    ) -> usize {
3964        let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
3965        let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
3966            style_colors;
3967        let fill_rgb: [f32; 3] = [fill_lin[0], fill_lin[1], fill_lin[2]];
3968        let px: f32 = (x as f32) + 0.5 - cx;
3969        let corner_r: f32 = quadrant_corner_radius(radius, px, py)
3970            .min(half_w)
3971            .min(half_h);
3972        let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
3973        if dist > 0.85 {
3974            return 0;
3975        }
3976        let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
3977        let bw: f32 = if has_border { border.get_width() } else { 0.0 };
3978        if !has_border {
3979            if dist < -0.85 {
3980                if color.get_a() > 0 {
3981                    blend_row_pixel_linear_precomputed(row, x, color, fill_rgb);
3982                    return 1;
3983                }
3984                return 0;
3985            }
3986            let in_corner_edge: bool = aa != AntialiasingMode::None
3987                && corner_r > 0.5
3988                && px.abs() > (half_w - corner_r - 1.5)
3989                && py.abs() > (half_h - corner_r - 1.5);
3990            let outer_cov: f32 = if in_corner_edge {
3991                rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
3992            } else {
3993                sdf_coverage(dist, aa)
3994            };
3995            if outer_cov > 0.0 && color.get_a() > 0 {
3996                let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * outer_cov;
3997                blend_row_pixel_f32_precomputed(row, x, color, fill_rgb, alpha_f);
3998                return 1;
3999            }
4000            return 0;
4001        }
4002        if dist < -(bw + 0.85) {
4003            if color.get_a() > 0 {
4004                blend_row_pixel_linear_precomputed(row, x, color, fill_rgb);
4005                return 1;
4006            }
4007            return 0;
4008        }
4009        let inner_hw: f32 = (half_w - bw).max(0.0);
4010        let inner_hh: f32 = (half_h - bw).max(0.0);
4011        let inner_r: f32 = (corner_r - bw).max(0.0);
4012        let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
4013            rounded_box_sdf(px, py, inner_hw, inner_hh, inner_r)
4014        } else {
4015            2.0
4016        };
4017        if dist < -0.85 && inner_dist > 0.85 {
4018            let border_rgb: [f32; 3] = [border_lin[0], border_lin[1], border_lin[2]];
4019            blend_row_pixel_linear_precomputed(row, x, border.get_color(), border_rgb);
4020            return 1;
4021        }
4022        let in_corner_zone: bool = aa != AntialiasingMode::None
4023            && corner_r > 0.5
4024            && px.abs() > (half_w - corner_r - 1.5)
4025            && py.abs() > (half_h - corner_r - 1.5);
4026        let (outer_cov, inner_cov): (f32, f32) = if in_corner_zone {
4027            rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, bw)
4028        } else {
4029            let oc: f32 = sdf_coverage(dist, aa);
4030            if oc <= 0.0 {
4031                return 0;
4032            }
4033            let ic: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
4034                sdf_coverage(inner_dist, aa)
4035            } else {
4036                0.0
4037            };
4038            (oc, ic)
4039        };
4040        if outer_cov <= 0.0 {
4041            return 0;
4042        }
4043        let mixed: Color =
4044            composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
4045        if mixed.get_a() > 0 {
4046            let mixed_rgb: [f32; 3] = [
4047                SRGB_TO_LIN_LUT[mixed.get_r() as usize],
4048                SRGB_TO_LIN_LUT[mixed.get_g() as usize],
4049                SRGB_TO_LIN_LUT[mixed.get_b() as usize],
4050            ];
4051            blend_row_pixel_linear_precomputed(row, x, mixed, mixed_rgb);
4052            return 1;
4053        }
4054        0
4055    }
4056
4057    /// Fills a constant-coverage horizontal span `[sx0, sx1)` on row `y` for a pure vertical gradient.
4058    ///
4059    /// # Arguments
4060    ///
4061    /// - `&mut PixelBand<'_>` - Target pixel band.
4062    /// - `(u32, u32, u32)` - Tuple `(sx0, sx1, y)` defining the horizontal span.
4063    /// - `Color` - Row-constant interpolated gradient color.
4064    /// - `f32` - Row-constant coverage in `(0.0, 1.0]`.
4065    ///
4066    /// # Returns
4067    ///
4068    /// - `usize` - Number of pixels shaded across `[sx0, sx1)`.
4069    #[inline(always)]
4070    fn fill_vertical_gradient_span(
4071        band: &mut PixelBand<'_>,
4072        coords: (u32, u32, u32),
4073        sample: Color,
4074        cov: f32,
4075    ) -> usize {
4076        let (sx0, sx1, y): (u32, u32, u32) = coords;
4077        if sx0 >= sx1 || cov <= 0.0 {
4078            return 0;
4079        }
4080        let alpha_f: f32 = ((sample.get_a() as f32) * (1.0 / 255.0)) * cov;
4081        if alpha_f >= 0.9995 {
4082            band.fill_span(
4083                sx0,
4084                sx1,
4085                y,
4086                Color::new(sample.get_r(), sample.get_g(), sample.get_b(), 255),
4087            );
4088        } else if alpha_f > 0.0005 {
4089            band.blend_shadow_span_const_alpha(sx0, sx1, y, sample, alpha_f);
4090        } else if alpha_f > 0.0002
4091            && let Some(row) = band.row_slice_mut(y)
4092        {
4093            let y_term: f32 = (y as f32) * 0.005_837_15;
4094            for x in sx0..sx1 {
4095                blend_gradient_row_pixel(row, x, y_term, sample, cov);
4096            }
4097        }
4098        (sx1 - sx0) as usize
4099    }
4100
4101    /// Fills a full-coverage or constant-coverage horizontal span `[sx0, sx1)` for a horizontal or diagonal gradient.
4102    ///
4103    /// # Arguments
4104    ///
4105    /// - `&mut [u8]` - Mutable target framebuffer scanline slice.
4106    /// - `(u32, u32, f32)` - Tuple `(sx0, sx1, y_term)` for span bounds and IGN phase.
4107    /// - `(f32, f32, f32)` - Tuple `(t_start, dt_dx, cov)` for incremental gradient stepping.
4108    /// - `(Color, Color)` - Gradient endpoints `(start_color, end_color)`.
4109    ///
4110    /// # Returns
4111    ///
4112    /// - `usize` - Number of pixels shaded across `[sx0, sx1)`.
4113    #[inline(always)]
4114    fn fill_angled_gradient_span(
4115        row: &mut [u8],
4116        coords: (u32, u32, f32),
4117        step: (f32, f32, f32),
4118        stops: (Color, Color),
4119    ) -> usize {
4120        let (sx0, sx1, y_term): (u32, u32, f32) = coords;
4121        let (t_start, dt_dx, cov): (f32, f32, f32) = step;
4122        let (start_c, end_c): (Color, Color) = stops;
4123        if sx0 >= sx1 || cov <= 0.0 {
4124            return 0;
4125        }
4126        let byte_start: usize = (sx0 as usize) * 4;
4127        let byte_end: usize = (sx1 as usize) * 4;
4128        if byte_end > row.len() {
4129            return 0;
4130        }
4131        let sr_f: f32 = start_c.get_r() as f32;
4132        let sg_f: f32 = start_c.get_g() as f32;
4133        let sb_f: f32 = start_c.get_b() as f32;
4134        let er_f: f32 = end_c.get_r() as f32;
4135        let eg_f: f32 = end_c.get_g() as f32;
4136        let eb_f: f32 = end_c.get_b() as f32;
4137        let both_opaque: bool = start_c.get_a() == 255 && end_c.get_a() == 255;
4138        let mut t_cur: f32 = t_start;
4139        if both_opaque && cov >= 0.9995 {
4140            let chunks: &mut [[u8; 4]] = row[byte_start..byte_end].as_chunks_mut::<4>().0;
4141            for px in chunks.iter_mut() {
4142                let f: f32 = t_cur.clamp(0.0, 1.0);
4143                let inv: f32 = 1.0 - f;
4144                px[0] = (sr_f * inv + er_f * f + 0.5) as u8;
4145                px[1] = (sg_f * inv + eg_f * f + 0.5) as u8;
4146                px[2] = (sb_f * inv + eb_f * f + 0.5) as u8;
4147                px[3] = 255;
4148                t_cur += dt_dx;
4149            }
4150            return (sx1 - sx0) as usize;
4151        }
4152        let sa_f: f32 = start_c.get_a() as f32;
4153        let ea_f: f32 = end_c.get_a() as f32;
4154        for x in sx0..sx1 {
4155            let f: f32 = t_cur.clamp(0.0, 1.0);
4156            let inv: f32 = 1.0 - f;
4157            let sample: Color = Color::new(
4158                (sr_f * inv + er_f * f + 0.5) as u8,
4159                (sg_f * inv + eg_f * f + 0.5) as u8,
4160                (sb_f * inv + eb_f * f + 0.5) as u8,
4161                (sa_f * inv + ea_f * f + 0.5) as u8,
4162            );
4163            blend_gradient_row_pixel(row, x, y_term, sample, cov);
4164            t_cur += dt_dx;
4165        }
4166        (sx1 - sx0) as usize
4167    }
4168
4169    /// Rasterizes a two-stop linear gradient inside an SDF rounded rectangle with vertical/interior fast paths and corner AA.
4170    ///
4171    /// # Arguments
4172    ///
4173    /// - `&mut PixelBand<'_>` - Target pixel band.
4174    /// - `Rect` - Physical bounds.
4175    /// - `LinearGradient` - Gradient angle and stops.
4176    /// - `CornerRadius` - Physical corner radii.
4177    /// - `Rect` - Active clip bounds.
4178    /// - `AntialiasingMode` - Active AA policy.
4179    ///
4180    /// # Returns
4181    ///
4182    /// - `usize` - Shaded pixel count.
4183    fn raster_gradient_rect(
4184        band: &mut PixelBand<'_>,
4185        rect: Rect,
4186        gradient: LinearGradient,
4187        radius: CornerRadius,
4188        clip: Rect,
4189        aa: AntialiasingMode,
4190    ) -> usize {
4191        let Some(vis) = rect.intersect(clip) else {
4192            return 0;
4193        };
4194        let fb_w: u32 = band.width();
4195        let band_y0: u32 = band.y_offset();
4196        let band_y1: u32 = band.y_end();
4197        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
4198        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
4199        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
4200        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
4201        if x0 >= x1 || y0 >= y1 {
4202            return 0;
4203        }
4204        let rad: f32 = gradient.get_angle_deg().to_radians();
4205        let dir_x: f32 = rad.sin();
4206        let dir_y: f32 = rad.cos();
4207        let start_c: Color = gradient.get_start_color();
4208        let end_c: Color = gradient.get_end_color();
4209        let half_w: f32 = rect.get_width() * 0.5;
4210        let half_h: f32 = rect.get_height() * 0.5;
4211        let cx: f32 = rect.get_x() + half_w;
4212        let cy: f32 = rect.get_y() + half_h;
4213        let inv_w: f32 = if rect.get_width() > 0.0 {
4214            1.0 / rect.get_width()
4215        } else {
4216            0.0
4217        };
4218        let inv_h: f32 = if rect.get_height() > 0.0 {
4219            1.0 / rect.get_height()
4220        } else {
4221            0.0
4222        };
4223        let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
4224        let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
4225        let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
4226        let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
4227        let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
4228        let cx0: u32 = ((rect.get_x() + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
4229        let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
4230        let is_vertical: bool = dir_x.abs() < 1e-5;
4231        let dt_dx: f32 = inv_w * dir_x;
4232        let rect_x: f32 = rect.get_x();
4233        let rect_y: f32 = rect.get_y();
4234        let mut shaded: usize = 0;
4235        if is_vertical {
4236            for y in y0..iy0 {
4237                let py: f32 = (y as f32) + 0.5 - cy;
4238                let ny: f32 = ((y as f32) - rect_y) * inv_h;
4239                let t: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
4240                let sample: Color = start_c.lerp(end_c, t);
4241                let dist_y: f32 = py.abs() - half_h;
4242                let mid_cov: f32 = if dist_y > 0.85 {
4243                    0.0
4244                } else if dist_y < -0.85 {
4245                    1.0
4246                } else {
4247                    sdf_coverage(dist_y, aa)
4248                };
4249                if cx0 < cx1 && mid_cov > 0.0 {
4250                    shaded +=
4251                        Self::fill_vertical_gradient_span(band, (cx0, cx1, y), sample, mid_cov);
4252                }
4253                if (x0 < cx0 || cx1 < x1)
4254                    && let Some(row) = band.row_slice_mut(y)
4255                {
4256                    let y_term: f32 = (y as f32) * 0.005_837_15;
4257                    for x in x0..cx0 {
4258                        let px: f32 = (x as f32) + 0.5 - cx;
4259                        let cov: f32 =
4260                            gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4261                        if cov > 0.0 {
4262                            blend_gradient_row_pixel(row, x, y_term, sample, cov);
4263                            shaded += 1;
4264                        }
4265                    }
4266                    for x in cx1..x1 {
4267                        let px: f32 = (x as f32) + 0.5 - cx;
4268                        let cov: f32 =
4269                            gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4270                        if cov > 0.0 {
4271                            blend_gradient_row_pixel(row, x, y_term, sample, cov);
4272                            shaded += 1;
4273                        }
4274                    }
4275                }
4276            }
4277            for y in iy0..iy1 {
4278                let ny: f32 = ((y as f32) - rect_y) * inv_h;
4279                let t: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
4280                let sample: Color = start_c.lerp(end_c, t);
4281                if ix0 < ix1 {
4282                    shaded += Self::fill_vertical_gradient_span(band, (ix0, ix1, y), sample, 1.0);
4283                }
4284                if (x0 < ix0 || ix1 < x1)
4285                    && let Some(row) = band.row_slice_mut(y)
4286                {
4287                    let y_term: f32 = (y as f32) * 0.005_837_15;
4288                    for x in x0..ix0 {
4289                        let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
4290                        if dist <= 0.85 {
4291                            let cov: f32 = if dist < -0.85 {
4292                                1.0
4293                            } else {
4294                                sdf_coverage(dist, aa)
4295                            };
4296                            if cov > 0.0 {
4297                                blend_gradient_row_pixel(row, x, y_term, sample, cov);
4298                                shaded += 1;
4299                            }
4300                        }
4301                    }
4302                    for x in ix1..x1 {
4303                        let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
4304                        if dist <= 0.85 {
4305                            let cov: f32 = if dist < -0.85 {
4306                                1.0
4307                            } else {
4308                                sdf_coverage(dist, aa)
4309                            };
4310                            if cov > 0.0 {
4311                                blend_gradient_row_pixel(row, x, y_term, sample, cov);
4312                                shaded += 1;
4313                            }
4314                        }
4315                    }
4316                }
4317            }
4318            for y in iy1..y1 {
4319                let py: f32 = (y as f32) + 0.5 - cy;
4320                let ny: f32 = ((y as f32) - rect_y) * inv_h;
4321                let t: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
4322                let sample: Color = start_c.lerp(end_c, t);
4323                let dist_y: f32 = py.abs() - half_h;
4324                let mid_cov: f32 = if dist_y > 0.85 {
4325                    0.0
4326                } else if dist_y < -0.85 {
4327                    1.0
4328                } else {
4329                    sdf_coverage(dist_y, aa)
4330                };
4331                if cx0 < cx1 && mid_cov > 0.0 {
4332                    shaded +=
4333                        Self::fill_vertical_gradient_span(band, (cx0, cx1, y), sample, mid_cov);
4334                }
4335                if (x0 < cx0 || cx1 < x1)
4336                    && let Some(row) = band.row_slice_mut(y)
4337                {
4338                    let y_term: f32 = (y as f32) * 0.005_837_15;
4339                    for x in x0..cx0 {
4340                        let px: f32 = (x as f32) + 0.5 - cx;
4341                        let cov: f32 =
4342                            gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4343                        if cov > 0.0 {
4344                            blend_gradient_row_pixel(row, x, y_term, sample, cov);
4345                            shaded += 1;
4346                        }
4347                    }
4348                    for x in cx1..x1 {
4349                        let px: f32 = (x as f32) + 0.5 - cx;
4350                        let cov: f32 =
4351                            gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4352                        if cov > 0.0 {
4353                            blend_gradient_row_pixel(row, x, y_term, sample, cov);
4354                            shaded += 1;
4355                        }
4356                    }
4357                }
4358            }
4359            return shaded;
4360        }
4361        for y in y0..iy0 {
4362            let Some(row) = band.row_slice_mut(y) else {
4363                continue;
4364            };
4365            let py: f32 = (y as f32) + 0.5 - cy;
4366            let ny: f32 = ((y as f32) - rect_y) * inv_h;
4367            let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
4368            let y_term: f32 = (y as f32) * 0.005_837_15;
4369            let dist_y: f32 = py.abs() - half_h;
4370            let mid_cov: f32 = if dist_y > 0.85 {
4371                0.0
4372            } else if dist_y < -0.85 {
4373                1.0
4374            } else {
4375                sdf_coverage(dist_y, aa)
4376            };
4377            if cx0 < cx1 && mid_cov > 0.0 {
4378                let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
4379                shaded += Self::fill_angled_gradient_span(
4380                    row,
4381                    (cx0, cx1, y_term),
4382                    (t_start, dt_dx, mid_cov),
4383                    (start_c, end_c),
4384                );
4385            }
4386            for x in x0..cx0 {
4387                let px: f32 = (x as f32) + 0.5 - cx;
4388                let cov: f32 =
4389                    gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4390                if cov > 0.0 {
4391                    let nx: f32 = ((x as f32) - rect_x) * inv_w;
4392                    let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4393                    blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4394                    shaded += 1;
4395                }
4396            }
4397            for x in cx1..x1 {
4398                let px: f32 = (x as f32) + 0.5 - cx;
4399                let cov: f32 =
4400                    gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4401                if cov > 0.0 {
4402                    let nx: f32 = ((x as f32) - rect_x) * inv_w;
4403                    let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4404                    blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4405                    shaded += 1;
4406                }
4407            }
4408        }
4409        for y in iy0..iy1 {
4410            let Some(row) = band.row_slice_mut(y) else {
4411                continue;
4412            };
4413            let ny: f32 = ((y as f32) - rect_y) * inv_h;
4414            let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
4415            let y_term: f32 = (y as f32) * 0.005_837_15;
4416            if ix0 < ix1 {
4417                let t_start: f32 = (((ix0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
4418                shaded += Self::fill_angled_gradient_span(
4419                    row,
4420                    (ix0, ix1, y_term),
4421                    (t_start, dt_dx, 1.0),
4422                    (start_c, end_c),
4423                );
4424            }
4425            for x in x0..ix0 {
4426                let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
4427                if dist <= 0.85 {
4428                    let cov: f32 = if dist < -0.85 {
4429                        1.0
4430                    } else {
4431                        sdf_coverage(dist, aa)
4432                    };
4433                    if cov > 0.0 {
4434                        let nx: f32 = ((x as f32) - rect_x) * inv_w;
4435                        let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4436                        blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4437                        shaded += 1;
4438                    }
4439                }
4440            }
4441            for x in ix1..x1 {
4442                let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
4443                if dist <= 0.85 {
4444                    let cov: f32 = if dist < -0.85 {
4445                        1.0
4446                    } else {
4447                        sdf_coverage(dist, aa)
4448                    };
4449                    if cov > 0.0 {
4450                        let nx: f32 = ((x as f32) - rect_x) * inv_w;
4451                        let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4452                        blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4453                        shaded += 1;
4454                    }
4455                }
4456            }
4457        }
4458        for y in iy1..y1 {
4459            let Some(row) = band.row_slice_mut(y) else {
4460                continue;
4461            };
4462            let py: f32 = (y as f32) + 0.5 - cy;
4463            let ny: f32 = ((y as f32) - rect_y) * inv_h;
4464            let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
4465            let y_term: f32 = (y as f32) * 0.005_837_15;
4466            let dist_y: f32 = py.abs() - half_h;
4467            let mid_cov: f32 = if dist_y > 0.85 {
4468                0.0
4469            } else if dist_y < -0.85 {
4470                1.0
4471            } else {
4472                sdf_coverage(dist_y, aa)
4473            };
4474            if cx0 < cx1 && mid_cov > 0.0 {
4475                let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
4476                shaded += Self::fill_angled_gradient_span(
4477                    row,
4478                    (cx0, cx1, y_term),
4479                    (t_start, dt_dx, mid_cov),
4480                    (start_c, end_c),
4481                );
4482            }
4483            for x in x0..cx0 {
4484                let px: f32 = (x as f32) + 0.5 - cx;
4485                let cov: f32 =
4486                    gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4487                if cov > 0.0 {
4488                    let nx: f32 = ((x as f32) - rect_x) * inv_w;
4489                    let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4490                    blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4491                    shaded += 1;
4492                }
4493            }
4494            for x in cx1..x1 {
4495                let px: f32 = (x as f32) + 0.5 - cx;
4496                let cov: f32 =
4497                    gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4498                if cov > 0.0 {
4499                    let nx: f32 = ((x as f32) - rect_x) * inv_w;
4500                    let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4501                    blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4502                    shaded += 1;
4503                }
4504            }
4505        }
4506        shaded
4507    }
4508
4509    /// Computes the horizontal opaque-interior skip interval `[cut_x0, cut_x1)` for shadow row `y`.
4510    ///
4511    /// # Arguments
4512    ///
4513    /// - `u32` - Global physical Y row.
4514    /// - `(Rect, Rect)` - Opaque cutout cross `(horizontal_bar, vertical_bar)`.
4515    /// - `u32` - Clamped row start X.
4516    /// - `u32` - Clamped row end X.
4517    ///
4518    /// # Returns
4519    ///
4520    /// - `(u32, u32)` - Opaque X span safely skippable on row `y`.
4521    #[must_use]
4522    fn shadow_row_cutout(y: u32, cutouts: (Rect, Rect), x0: u32, x1: u32) -> (u32, u32) {
4523        let (cut_h, cut_v): (Rect, Rect) = cutouts;
4524        let yf: f32 = (y as f32) + 0.5;
4525        if cut_h.get_width() > 0.0
4526            && cut_h.get_height() > 0.0
4527            && yf >= cut_h.get_y()
4528            && yf < cut_h.bottom()
4529        {
4530            let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
4531            let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, x1);
4532            return (cx0, cx1);
4533        }
4534        if cut_v.get_width() > 0.0
4535            && cut_v.get_height() > 0.0
4536            && yf >= cut_v.get_y()
4537            && yf < cut_v.bottom()
4538        {
4539            let cx0: u32 = (cut_v.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
4540            let cx1: u32 = (cut_v.right().floor().max(0.0) as u32).clamp(cx0, x1);
4541            return (cx0, cx1);
4542        }
4543        (x1, x1)
4544    }
4545
4546    /// Blends the constant-alpha horizontal middle span `[sx0, sx1)` on row `y` while skipping cutout `[cut0, cut1)`.
4547    ///
4548    /// # Arguments
4549    ///
4550    /// - `&mut PixelBand<'_>` - Target pixel band.
4551    /// - `&ShadowRenderCtx` - Shared shadow geometry and color context.
4552    /// - `u32` - Global physical Y row coordinate.
4553    /// - `(u32, u32)` - Opaque cutout interval `(cut0, cut1)` on row `y`.
4554    /// - `f32` - Constant middle-span shadow opacity `mid_alpha`.
4555    ///
4556    /// # Returns
4557    ///
4558    /// - `usize` - Shaded pixel count across the middle span.
4559    #[inline(always)]
4560    fn raster_shadow_middle_span(
4561        band: &mut PixelBand<'_>,
4562        ctx: &ShadowRenderCtx,
4563        y: u32,
4564        cutout: (u32, u32),
4565        mid_alpha: f32,
4566    ) -> usize {
4567        if !ctx.has_mid_x || mid_alpha <= 0.0005 {
4568            return 0;
4569        }
4570        let (cut0, cut1): (u32, u32) = cutout;
4571        let sx0: u32 = ctx.lx1;
4572        let sx1: u32 = ctx.rx0;
4573        let mut shaded: usize = 0;
4574        if cut0 < cut1 {
4575            let m0_end: u32 = cut0.min(sx1);
4576            if sx0 < m0_end {
4577                band.blend_shadow_span_const_alpha(sx0, m0_end, y, ctx.color, mid_alpha);
4578                shaded += (m0_end - sx0) as usize;
4579            }
4580            let m1_start: u32 = cut1.max(sx0);
4581            if m1_start < sx1 {
4582                band.blend_shadow_span_const_alpha(m1_start, sx1, y, ctx.color, mid_alpha);
4583                shaded += (sx1 - m1_start) as usize;
4584            }
4585        } else {
4586            band.blend_shadow_span_const_alpha(sx0, sx1, y, ctx.color, mid_alpha);
4587            shaded += (sx1 - sx0) as usize;
4588        }
4589        shaded
4590    }
4591
4592    /// Rasterizes a single uniform-radius shadow corner row using 2x horizontal left/right symmetry.
4593    ///
4594    /// # Arguments
4595    ///
4596    /// - `&mut PixelBand<'_>` - Target pixel band.
4597    /// - `&ShadowRenderCtx` - Shared shadow geometry and color context.
4598    /// - `u32` - Global physical Y row coordinate.
4599    /// - `(Rect, Rect)` - Opaque cutout rectangles `(cut_h, cut_v)`.
4600    ///
4601    /// # Returns
4602    ///
4603    /// - `usize` - Shaded pixel count on row `y`.
4604    fn raster_shadow_corner_row_symmetric(
4605        band: &mut PixelBand<'_>,
4606        ctx: &ShadowRenderCtx,
4607        y: u32,
4608        cutouts: (Rect, Rect),
4609    ) -> usize {
4610        let py: f32 = (y as f32) + 0.5 - ctx.cy;
4611        let py_abs: f32 = py.abs();
4612        let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1);
4613        let mut shaded: usize = 0;
4614        if ctx.has_mid_x {
4615            let dist_y: f32 = py_abs - ctx.half_h;
4616            let mid_alpha: f32 = if dist_y < ctx.cutoff {
4617                ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
4618            } else {
4619                0.0
4620            };
4621            shaded += Self::raster_shadow_middle_span(band, ctx, y, (cut0, cut1), mid_alpha);
4622        }
4623        let (la0, la1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0, cut1);
4624        let (ra0, ra1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0, cut1);
4625        let mut u0: i32 = i32::MAX;
4626        let mut u1: i32 = i32::MIN;
4627        if la0 < la1 {
4628            u0 = u0.min(la0 as i32);
4629            u1 = u1.max(la1 as i32);
4630        }
4631        if ra0 < ra1 {
4632            u0 = u0.min(ctx.mirror_x_sum - (ra1 as i32) + 1);
4633            u1 = u1.max(ctx.mirror_x_sum - (ra0 as i32) + 1);
4634        }
4635        if u0 >= u1 {
4636            return shaded;
4637        }
4638        let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
4639        let qy_pos: f32 = qy.max(0.0);
4640        let qy_pos_sq: f32 = qy_pos * qy_pos;
4641        if qy > 0.0 {
4642            if qy_pos_sq >= ctx.cutoff_r_safe_sq {
4643                return shaded;
4644            }
4645            let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
4646            let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
4647            let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
4648            u0 = u0.max(tight_u0);
4649            if u0 >= u1 {
4650                return shaded;
4651            }
4652        }
4653        let Some(row) = band.row_slice_mut(y) else {
4654            return shaded;
4655        };
4656        let sdf_geom: (f32, f32, f32, f32) =
4657            (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
4658        let y_term: f32 = (y as f32) * 0.005_837_15;
4659        let x0_i: i32 = ctx.x0 as i32;
4660        let lx1_i: i32 = ctx.lx1 as i32;
4661        let rx0_i: i32 = ctx.rx0 as i32;
4662        let x1_i: i32 = ctx.x1 as i32;
4663        let cut0_i: i32 = cut0 as i32;
4664        let cut1_i: i32 = cut1 as i32;
4665        for xl_i in u0..u1 {
4666            let xr_i: i32 = ctx.mirror_x_sum - xl_i;
4667            let do_l: bool = xl_i >= x0_i && xl_i < lx1_i && (xl_i < cut0_i || xl_i >= cut1_i);
4668            let do_r: bool = xr_i >= rx0_i && xr_i < x1_i && (xr_i < cut0_i || xr_i >= cut1_i);
4669            if !do_l && !do_r {
4670                continue;
4671            }
4672            let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
4673            let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
4674            if dist >= ctx.cutoff {
4675                continue;
4676            }
4677            let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
4678            if alpha_f <= 0.0005 {
4679                continue;
4680            }
4681            let a: f32 = alpha_f.clamp(0.0, 1.0);
4682            if a >= 0.9995 {
4683                if do_l {
4684                    let off: usize = (xl_i as usize) * 4;
4685                    row[off] = ctx.color_rgb[0];
4686                    row[off + 1] = ctx.color_rgb[1];
4687                    row[off + 2] = ctx.color_rgb[2];
4688                    row[off + 3] = 255;
4689                    shaded += 1;
4690                }
4691                if do_r {
4692                    let off: usize = (xr_i as usize) * 4;
4693                    row[off] = ctx.color_rgb[0];
4694                    row[off + 1] = ctx.color_rgb[1];
4695                    row[off + 2] = ctx.color_rgb[2];
4696                    row[off + 3] = 255;
4697                    shaded += 1;
4698                }
4699            } else {
4700                let inv_a: f32 = 1.0 - a;
4701                let sa_u32: u32 = (a * 255.0) as u32;
4702                let params: ShadowStripParams = ShadowStripParams {
4703                    sr_a: ctx.lin_rgb[0] * a,
4704                    sg_a: ctx.lin_rgb[1] * a,
4705                    sb_a: ctx.lin_rgb[2] * a,
4706                    inv_a,
4707                    sa_u32,
4708                    inv_a_u32: 255 - sa_u32,
4709                };
4710                let mut cache: ShadowPixelCache = ShadowPixelCache::default();
4711                if do_l {
4712                    blend_shadow_mirrored_pixel(row, xl_i as u32, y_term, params, &mut cache);
4713                    shaded += 1;
4714                }
4715                if do_r {
4716                    blend_shadow_mirrored_pixel(row, xr_i as u32, y_term, params, &mut cache);
4717                    shaded += 1;
4718                }
4719            }
4720        }
4721        shaded
4722    }
4723
4724    /// Rasterizes a vertically mirrored pair of uniform-radius shadow corner rows (`y_t < y_b`) with 4-quadrant SDF and LUT reuse.
4725    ///
4726    /// # Arguments
4727    ///
4728    /// - `&mut PixelBand<'_>` - Target pixel band.
4729    /// - `&ShadowRenderCtx` - Shared shadow geometry and color context.
4730    /// - `u32` - Upper global physical Y row coordinate (`y_t < y_b`).
4731    /// - `u32` - Lower mirrored global physical Y row coordinate (`y_b > y_t`).
4732    /// - `(Rect, Rect)` - Opaque cutout rectangles `(cut_h, cut_v)`.
4733    ///
4734    /// # Returns
4735    ///
4736    /// - `usize` - Total shaded pixel count across both rows `y_t` and `y_b`.
4737    fn raster_shadow_corner_pair_symmetric(
4738        band: &mut PixelBand<'_>,
4739        ctx: &ShadowRenderCtx,
4740        y_t: u32,
4741        y_b: u32,
4742        cutouts: (Rect, Rect),
4743    ) -> usize {
4744        let py: f32 = (y_t as f32) + 0.5 - ctx.cy;
4745        let py_abs: f32 = py.abs();
4746        let (cut0_t, cut1_t): (u32, u32) = Self::shadow_row_cutout(y_t, cutouts, ctx.x0, ctx.x1);
4747        let (cut0_b, cut1_b): (u32, u32) = Self::shadow_row_cutout(y_b, cutouts, ctx.x0, ctx.x1);
4748        let mut shaded: usize = 0;
4749        if ctx.has_mid_x {
4750            let dist_y: f32 = py_abs - ctx.half_h;
4751            let mid_alpha: f32 = if dist_y < ctx.cutoff {
4752                ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
4753            } else {
4754                0.0
4755            };
4756            if mid_alpha > 0.0005 {
4757                shaded +=
4758                    Self::raster_shadow_middle_span(band, ctx, y_t, (cut0_t, cut1_t), mid_alpha);
4759                shaded +=
4760                    Self::raster_shadow_middle_span(band, ctx, y_b, (cut0_b, cut1_b), mid_alpha);
4761            }
4762        }
4763        let (lat0, lat1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_t, cut1_t);
4764        let (rat0, rat1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_t, cut1_t);
4765        let (lab0, lab1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_b, cut1_b);
4766        let (rab0, rab1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_b, cut1_b);
4767        let mut u0: i32 = i32::MAX;
4768        let mut u1: i32 = i32::MIN;
4769        if lat0 < lat1 {
4770            u0 = u0.min(lat0 as i32);
4771            u1 = u1.max(lat1 as i32);
4772        }
4773        if rat0 < rat1 {
4774            u0 = u0.min(ctx.mirror_x_sum - (rat1 as i32) + 1);
4775            u1 = u1.max(ctx.mirror_x_sum - (rat0 as i32) + 1);
4776        }
4777        if lab0 < lab1 {
4778            u0 = u0.min(lab0 as i32);
4779            u1 = u1.max(lab1 as i32);
4780        }
4781        if rab0 < rab1 {
4782            u0 = u0.min(ctx.mirror_x_sum - (rab1 as i32) + 1);
4783            u1 = u1.max(ctx.mirror_x_sum - (rab0 as i32) + 1);
4784        }
4785        if u0 >= u1 {
4786            return shaded;
4787        }
4788        let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
4789        let qy_pos: f32 = qy.max(0.0);
4790        let qy_pos_sq: f32 = qy_pos * qy_pos;
4791        if qy > 0.0 {
4792            if qy_pos_sq >= ctx.cutoff_r_safe_sq {
4793                return shaded;
4794            }
4795            let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
4796            let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
4797            let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
4798            u0 = u0.max(tight_u0);
4799            if u0 >= u1 {
4800                return shaded;
4801            }
4802        }
4803        let Some((row_t, row_b)) = band.two_row_slices_mut(y_t, y_b) else {
4804            return shaded;
4805        };
4806        let sdf_geom: (f32, f32, f32, f32) =
4807            (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
4808        let y_term_t: f32 = (y_t as f32) * 0.005_837_15;
4809        let y_term_b: f32 = (y_b as f32) * 0.005_837_15;
4810        let x0_i: i32 = ctx.x0 as i32;
4811        let lx1_i: i32 = ctx.lx1 as i32;
4812        let rx0_i: i32 = ctx.rx0 as i32;
4813        let x1_i: i32 = ctx.x1 as i32;
4814        let cut0_ti: i32 = cut0_t as i32;
4815        let cut1_ti: i32 = cut1_t as i32;
4816        let cut0_bi: i32 = cut0_b as i32;
4817        let cut1_bi: i32 = cut1_b as i32;
4818        for xl_i in u0..u1 {
4819            let xr_i: i32 = ctx.mirror_x_sum - xl_i;
4820            let in_l: bool = xl_i >= x0_i && xl_i < lx1_i;
4821            let in_r: bool = xr_i >= rx0_i && xr_i < x1_i;
4822            let do_lt: bool = in_l && (xl_i < cut0_ti || xl_i >= cut1_ti);
4823            let do_rt: bool = in_r && (xr_i < cut0_ti || xr_i >= cut1_ti);
4824            let do_lb: bool = in_l && (xl_i < cut0_bi || xl_i >= cut1_bi);
4825            let do_rb: bool = in_r && (xr_i < cut0_bi || xr_i >= cut1_bi);
4826            if !do_lt && !do_rt && !do_lb && !do_rb {
4827                continue;
4828            }
4829            let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
4830            let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
4831            if dist >= ctx.cutoff {
4832                continue;
4833            }
4834            let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
4835            if alpha_f <= 0.0005 {
4836                continue;
4837            }
4838            let a: f32 = alpha_f.clamp(0.0, 1.0);
4839            if a >= 0.9995 {
4840                if do_lt {
4841                    let off: usize = (xl_i as usize) * 4;
4842                    row_t[off] = ctx.color_rgb[0];
4843                    row_t[off + 1] = ctx.color_rgb[1];
4844                    row_t[off + 2] = ctx.color_rgb[2];
4845                    row_t[off + 3] = 255;
4846                    shaded += 1;
4847                }
4848                if do_rt {
4849                    let off: usize = (xr_i as usize) * 4;
4850                    row_t[off] = ctx.color_rgb[0];
4851                    row_t[off + 1] = ctx.color_rgb[1];
4852                    row_t[off + 2] = ctx.color_rgb[2];
4853                    row_t[off + 3] = 255;
4854                    shaded += 1;
4855                }
4856                if do_lb {
4857                    let off: usize = (xl_i as usize) * 4;
4858                    row_b[off] = ctx.color_rgb[0];
4859                    row_b[off + 1] = ctx.color_rgb[1];
4860                    row_b[off + 2] = ctx.color_rgb[2];
4861                    row_b[off + 3] = 255;
4862                    shaded += 1;
4863                }
4864                if do_rb {
4865                    let off: usize = (xr_i as usize) * 4;
4866                    row_b[off] = ctx.color_rgb[0];
4867                    row_b[off + 1] = ctx.color_rgb[1];
4868                    row_b[off + 2] = ctx.color_rgb[2];
4869                    row_b[off + 3] = 255;
4870                    shaded += 1;
4871                }
4872            } else {
4873                let inv_a: f32 = 1.0 - a;
4874                let sa_u32: u32 = (a * 255.0) as u32;
4875                let params: ShadowStripParams = ShadowStripParams {
4876                    sr_a: ctx.lin_rgb[0] * a,
4877                    sg_a: ctx.lin_rgb[1] * a,
4878                    sb_a: ctx.lin_rgb[2] * a,
4879                    inv_a,
4880                    sa_u32,
4881                    inv_a_u32: 255 - sa_u32,
4882                };
4883                let mut cache: ShadowPixelCache = ShadowPixelCache::default();
4884                if do_lt {
4885                    blend_shadow_mirrored_pixel(row_t, xl_i as u32, y_term_t, params, &mut cache);
4886                    shaded += 1;
4887                }
4888                if do_rt {
4889                    blend_shadow_mirrored_pixel(row_t, xr_i as u32, y_term_t, params, &mut cache);
4890                    shaded += 1;
4891                }
4892                if do_lb {
4893                    blend_shadow_mirrored_pixel(row_b, xl_i as u32, y_term_b, params, &mut cache);
4894                    shaded += 1;
4895                }
4896                if do_rb {
4897                    blend_shadow_mirrored_pixel(row_b, xr_i as u32, y_term_b, params, &mut cache);
4898                    shaded += 1;
4899                }
4900            }
4901        }
4902        shaded
4903    }
4904
4905    /// Rasterizes a general (asymmetric-radius or unaligned-center) shadow corner row directly into `row_slice_mut`.
4906    ///
4907    /// # Arguments
4908    ///
4909    /// - `&mut PixelBand<'_>` - Target pixel band.
4910    /// - `&ShadowRenderCtx` - Shared shadow geometry and color context.
4911    /// - `CornerRadius` - Per-quadrant physical corner radii.
4912    /// - `u32` - Global physical Y row coordinate.
4913    /// - `(Rect, Rect)` - Opaque cutout rectangles `(cut_h, cut_v)`.
4914    ///
4915    /// # Returns
4916    ///
4917    /// - `usize` - Shaded pixel count on row `y`.
4918    fn raster_shadow_corner_row_general(
4919        band: &mut PixelBand<'_>,
4920        ctx: &ShadowRenderCtx,
4921        radius: CornerRadius,
4922        y: u32,
4923        cutouts: (Rect, Rect),
4924    ) -> usize {
4925        let py: f32 = (y as f32) + 0.5 - ctx.cy;
4926        let py_abs: f32 = py.abs();
4927        let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1);
4928        let spans: [(u32, u32); 2] = if cut0 < cut1 {
4929            [(ctx.x0, cut0), (cut1, ctx.x1)]
4930        } else {
4931            [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
4932        };
4933        let mut shaded: usize = 0;
4934        if ctx.has_mid_x {
4935            let dist_y: f32 = py_abs - ctx.half_h;
4936            let mid_alpha: f32 = if dist_y < ctx.cutoff {
4937                ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
4938            } else {
4939                0.0
4940            };
4941            shaded += Self::raster_shadow_middle_span(band, ctx, y, (cut0, cut1), mid_alpha);
4942        }
4943        let Some(row) = band.row_slice_mut(y) else {
4944            return shaded;
4945        };
4946        let y_term: f32 = (y as f32) * 0.005_837_15;
4947        let r_l: f32 = (if py < 0.0 {
4948            radius.get_top_left()
4949        } else {
4950            radius.get_bottom_left()
4951        })
4952        .min(ctx.half_w)
4953        .min(ctx.half_h)
4954        .max(0.0);
4955        let r_r: f32 = (if py < 0.0 {
4956            radius.get_top_right()
4957        } else {
4958            radius.get_bottom_right()
4959        })
4960        .min(ctx.half_w)
4961        .min(ctx.half_h)
4962        .max(0.0);
4963        let qy_l: f32 = py_abs - ctx.half_h + r_l;
4964        let qy_l_pos: f32 = qy_l.max(0.0);
4965        let qy_l_sq: f32 = qy_l_pos * qy_l_pos;
4966        let cut_l_r: f32 = ctx.cutoff + r_l + 1e-3;
4967        let geom_l: (f32, f32, f32, f32) = (ctx.half_w, r_l, ctx.cutoff, cut_l_r * cut_l_r);
4968        let qy_r: f32 = py_abs - ctx.half_h + r_r;
4969        let qy_r_pos: f32 = qy_r.max(0.0);
4970        let qy_r_sq: f32 = qy_r_pos * qy_r_pos;
4971        let cut_r_r: f32 = ctx.cutoff + r_r + 1e-3;
4972        let geom_r: (f32, f32, f32, f32) = (ctx.half_w, r_r, ctx.cutoff, cut_r_r * cut_r_r);
4973        for (rx0, rx1) in spans.into_iter() {
4974            if rx0 >= rx1 {
4975                continue;
4976            }
4977            if ctx.has_mid_x {
4978                let l_end: u32 = rx1.min(ctx.lx1);
4979                for x in rx0..l_end {
4980                    let px: f32 = (x as f32) + 0.5 - ctx.cx;
4981                    let dist: f32 = if px < 0.0 {
4982                        shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
4983                    } else {
4984                        shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
4985                    };
4986                    if dist < ctx.cutoff {
4987                        let alpha_f: f32 =
4988                            ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
4989                        if alpha_f > 0.0005 {
4990                            blend_shadow_row_pixel(
4991                                row,
4992                                x,
4993                                y_term,
4994                                ctx.color_rgb,
4995                                ctx.lin_rgb,
4996                                alpha_f,
4997                            );
4998                            shaded += 1;
4999                        }
5000                    }
5001                }
5002                let r_start: u32 = rx0.max(ctx.rx0);
5003                for x in r_start..rx1 {
5004                    let px: f32 = (x as f32) + 0.5 - ctx.cx;
5005                    let dist: f32 = if px < 0.0 {
5006                        shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
5007                    } else {
5008                        shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
5009                    };
5010                    if dist < ctx.cutoff {
5011                        let alpha_f: f32 =
5012                            ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5013                        if alpha_f > 0.0005 {
5014                            blend_shadow_row_pixel(
5015                                row,
5016                                x,
5017                                y_term,
5018                                ctx.color_rgb,
5019                                ctx.lin_rgb,
5020                                alpha_f,
5021                            );
5022                            shaded += 1;
5023                        }
5024                    }
5025                }
5026            } else {
5027                for x in rx0..rx1 {
5028                    let px: f32 = (x as f32) + 0.5 - ctx.cx;
5029                    let dist: f32 = if px < 0.0 {
5030                        shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
5031                    } else {
5032                        shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
5033                    };
5034                    if dist >= ctx.cutoff {
5035                        continue;
5036                    }
5037                    let alpha_f: f32 =
5038                        ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5039                    if alpha_f > 0.0005 {
5040                        blend_shadow_row_pixel(row, x, y_term, ctx.color_rgb, ctx.lin_rgb, alpha_f);
5041                        shaded += 1;
5042                    }
5043                }
5044            }
5045        }
5046        shaded
5047    }
5048
5049    /// Rasterizes the vertical left/right shadow side strips across `sy0..sy1` using a precomputed 1D falloff LUT.
5050    ///
5051    /// # Arguments
5052    ///
5053    /// - `&mut PixelBand<'_>` - Target pixel band.
5054    /// - `&ShadowRenderCtx` - Shared shadow geometry and color context.
5055    /// - `(u32, u32)` - Vertical interior row interval `(sy0, sy1)`.
5056    /// - `(Rect, Rect)` - Opaque cutout rectangles `(cut_h, cut_v)`.
5057    ///
5058    /// # Returns
5059    ///
5060    /// - `usize` - Total shaded pixel count across `sy0..sy1`.
5061    fn raster_shadow_vertical_strips(
5062        band: &mut PixelBand<'_>,
5063        ctx: &ShadowRenderCtx,
5064        y_span: (u32, u32),
5065        cutouts: (Rect, Rect),
5066    ) -> usize {
5067        let (sy0, sy1): (u32, u32) = y_span;
5068        if sy0 >= sy1 {
5069            return 0;
5070        }
5071        let (cut_h, _): (Rect, Rect) = cutouts;
5072        let sy0_f: f32 = (sy0 as f32) + 0.5;
5073        let sy1_last_f: f32 = ((sy1 - 1) as f32) + 0.5;
5074        let const_cut: Option<(u32, u32)> = if cut_h.get_width() > 0.0
5075            && cut_h.get_height() > 0.0
5076            && sy0_f >= cut_h.get_y()
5077            && sy1_last_f < cut_h.bottom()
5078        {
5079            let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(ctx.x0, ctx.x1);
5080            let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, ctx.x1);
5081            Some((cx0, cx1))
5082        } else {
5083            None
5084        };
5085        let (l_build0, l_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
5086            active_span_bounds(ctx.x0, ctx.lx1, c0, c1)
5087        } else {
5088            (ctx.x0, ctx.lx1)
5089        };
5090        let (r_build0, r_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
5091            active_span_bounds(ctx.rx0, ctx.x1, c0, c1)
5092        } else {
5093            (ctx.rx0, ctx.x1)
5094        };
5095        let mut shaded: usize = 0;
5096        let ran_tls: bool = BAND_SHADOW_SCRATCH
5097            .try_with(|cell: &RefCell<BandShadowScratch>| {
5098                if let Ok(mut scratch) = cell.try_borrow_mut() {
5099                    let BandShadowScratch {
5100                        left_hot,
5101                        left_params,
5102                        right_hot,
5103                        right_params,
5104                    } = &mut *scratch;
5105                    let (l_act0, l_act1): (u32, u32) = build_shadow_vertical_strip(
5106                        (l_build0, l_build1),
5107                        ctx,
5108                        left_hot,
5109                        left_params,
5110                    );
5111                    let (r_act0, r_act1): (u32, u32) = build_shadow_vertical_strip(
5112                        (r_build0, r_build1),
5113                        ctx,
5114                        right_hot,
5115                        right_params,
5116                    );
5117                    if l_act0 >= l_act1 && r_act0 >= r_act1 {
5118                        return;
5119                    }
5120                    let l_hot_s: &mut [ShadowStripHot] = left_hot.as_mut_slice();
5121                    let l_par_s: &[ShadowStripParams] = left_params.as_slice();
5122                    let r_hot_s: &mut [ShadowStripHot] = right_hot.as_mut_slice();
5123                    let r_par_s: &[ShadowStripParams] = right_params.as_slice();
5124                    for y in sy0..sy1 {
5125                        let Some(row) = band.row_slice_mut(y) else {
5126                            continue;
5127                        };
5128                        let y_term: f32 = (y as f32) * 0.005_837_15;
5129                        let (cut0, cut1): (u32, u32) = const_cut
5130                            .unwrap_or_else(|| Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1));
5131                        if l_act0 < l_act1 {
5132                            if cut0 < cut1 {
5133                                let a_end: u32 = cut0.min(l_act1);
5134                                if l_act0 < a_end {
5135                                    shaded += apply_shadow_strip_span(
5136                                        row,
5137                                        (l_act0, a_end, l_act0),
5138                                        y_term,
5139                                        ctx.color_rgb,
5140                                        l_hot_s,
5141                                        l_par_s,
5142                                    );
5143                                }
5144                                let b_start: u32 = cut1.max(l_act0);
5145                                if b_start < l_act1 {
5146                                    shaded += apply_shadow_strip_span(
5147                                        row,
5148                                        (b_start, l_act1, l_act0),
5149                                        y_term,
5150                                        ctx.color_rgb,
5151                                        l_hot_s,
5152                                        l_par_s,
5153                                    );
5154                                }
5155                            } else {
5156                                shaded += apply_shadow_strip_span(
5157                                    row,
5158                                    (l_act0, l_act1, l_act0),
5159                                    y_term,
5160                                    ctx.color_rgb,
5161                                    l_hot_s,
5162                                    l_par_s,
5163                                );
5164                            }
5165                        }
5166                        if r_act0 < r_act1 {
5167                            if cut0 < cut1 {
5168                                let a_end: u32 = cut0.min(r_act1);
5169                                if r_act0 < a_end {
5170                                    shaded += apply_shadow_strip_span(
5171                                        row,
5172                                        (r_act0, a_end, r_act0),
5173                                        y_term,
5174                                        ctx.color_rgb,
5175                                        r_hot_s,
5176                                        r_par_s,
5177                                    );
5178                                }
5179                                let b_start: u32 = cut1.max(r_act0);
5180                                if b_start < r_act1 {
5181                                    shaded += apply_shadow_strip_span(
5182                                        row,
5183                                        (b_start, r_act1, r_act0),
5184                                        y_term,
5185                                        ctx.color_rgb,
5186                                        r_hot_s,
5187                                        r_par_s,
5188                                    );
5189                                }
5190                            } else {
5191                                shaded += apply_shadow_strip_span(
5192                                    row,
5193                                    (r_act0, r_act1, r_act0),
5194                                    y_term,
5195                                    ctx.color_rgb,
5196                                    r_hot_s,
5197                                    r_par_s,
5198                                );
5199                            }
5200                        }
5201                    }
5202                }
5203            })
5204            .is_ok();
5205        if !ran_tls {
5206            for y in sy0..sy1 {
5207                let Some(row) = band.row_slice_mut(y) else {
5208                    continue;
5209                };
5210                let y_term: f32 = (y as f32) * 0.005_837_15;
5211                let (cut0, cut1): (u32, u32) = const_cut
5212                    .unwrap_or_else(|| Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1));
5213                let spans: [(u32, u32); 2] = if cut0 < cut1 {
5214                    [(ctx.x0, cut0), (cut1, ctx.x1)]
5215                } else {
5216                    [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
5217                };
5218                for (rx0, rx1) in spans.into_iter() {
5219                    let left_end: u32 = rx1.min(ctx.lx1);
5220                    for x in rx0..left_end {
5221                        let dist: f32 = ((x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
5222                        if dist < ctx.cutoff {
5223                            let alpha_f: f32 =
5224                                ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5225                            if alpha_f > 0.0005 {
5226                                blend_shadow_row_pixel(
5227                                    row,
5228                                    x,
5229                                    y_term,
5230                                    ctx.color_rgb,
5231                                    ctx.lin_rgb,
5232                                    alpha_f,
5233                                );
5234                                shaded += 1;
5235                            }
5236                        }
5237                    }
5238                    let right_start: u32 = rx0.max(ctx.rx0);
5239                    for x in right_start..rx1 {
5240                        let dist: f32 = ((x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
5241                        if dist < ctx.cutoff {
5242                            let alpha_f: f32 =
5243                                ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5244                            if alpha_f > 0.0005 {
5245                                blend_shadow_row_pixel(
5246                                    row,
5247                                    x,
5248                                    y_term,
5249                                    ctx.color_rgb,
5250                                    ctx.lin_rgb,
5251                                    alpha_f,
5252                                );
5253                                shaded += 1;
5254                            }
5255                        }
5256                    }
5257                }
5258            }
5259        }
5260        shaded
5261    }
5262
5263    /// Rasterizes a lossless 2D analytical Gaussian `erfc` LUT drop shadow skipping strictly-opaque card interiors.
5264    ///
5265    /// # Arguments
5266    ///
5267    /// - `&mut PixelBand<'_>` - Target pixel band.
5268    /// - `(Rect, Rect, Rect)` - Tuple `(shadow_rect, caster_rect, clip)` in physical pixels.
5269    /// - `CornerRadius` - Per-quadrant physical corner radii.
5270    /// - `f32` - Gaussian standard deviation `sigma` in physical pixels.
5271    /// - `Color` - Shadow tint color.
5272    /// - `(Rect, Rect)` - Strictly-opaque interior cutout rectangles from immediately following opaque card.
5273    ///
5274    /// # Returns
5275    ///
5276    /// - `usize` - Shaded pixel count.
5277    fn raster_shadow(
5278        band: &mut PixelBand<'_>,
5279        rects: (Rect, Rect, Rect),
5280        radius: CornerRadius,
5281        sigma: f32,
5282        color: Color,
5283        cutouts: (Rect, Rect),
5284    ) -> usize {
5285        let (shadow_rect, caster_rect, clip): (Rect, Rect, Rect) = rects;
5286        if color.get_a() == 0 {
5287            return 0;
5288        }
5289        let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
5290        if base_alpha <= 0.0005 {
5291            return 0;
5292        }
5293        let Some(vis) = shadow_rect.intersect(clip) else {
5294            return 0;
5295        };
5296        let fb_w: u32 = band.width();
5297        let band_y0: u32 = band.y_offset();
5298        let band_y1: u32 = band.y_end();
5299        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
5300        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
5301        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
5302        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
5303        if x0 >= x1 || y0 >= y1 {
5304            return 0;
5305        }
5306        let half_w: f32 = (caster_rect.get_width() * 0.5).max(0.5);
5307        let half_h: f32 = (caster_rect.get_height() * 0.5).max(0.5);
5308        let cx: f32 = caster_rect.get_x() + half_w;
5309        let cy: f32 = caster_rect.get_y() + half_h;
5310        let inv_sigma: f32 = 1.0 / sigma.max(0.5);
5311        let cutoff: f32 = sigma * 3.0;
5312        let r_max: f32 = radius.max_radius();
5313        let inner_inset: f32 = cutoff + r_max;
5314        let sy0: u32 = ((caster_rect.get_y() + inner_inset).ceil().max(0.0) as u32).clamp(y0, y1);
5315        let sy1: u32 = ((caster_rect.bottom() - inner_inset).floor().max(0.0) as u32).clamp(y0, y1);
5316        let sx0: u32 = ((caster_rect.get_x() + inner_inset).ceil().max(0.0) as u32).clamp(x0, x1);
5317        let sx1: u32 = ((caster_rect.right() - inner_inset).floor().max(0.0) as u32).clamp(x0, x1);
5318        let has_mid_x: bool = sx0 < sx1;
5319        let has_mid_y: bool = sy0 < sy1;
5320        let r_tl: f32 = radius.get_top_left();
5321        let uniform_radius: bool = r_tl == radius.get_top_right()
5322            && r_tl == radius.get_bottom_right()
5323            && r_tl == radius.get_bottom_left();
5324        let two_cx_f: f32 = 2.0 * cx;
5325        let two_cx_i: i32 = two_cx_f.round() as i32;
5326        let x_symmetric: bool =
5327            uniform_radius && (two_cx_i as f32) == two_cx_f && two_cx_f.abs() < 16_777_216.0;
5328        let two_cy_f: f32 = 2.0 * cy;
5329        let two_cy_i: i32 = two_cy_f.round() as i32;
5330        let y_symmetric: bool =
5331            x_symmetric && (two_cy_i as f32) == two_cy_f && two_cy_f.abs() < 16_777_216.0;
5332        let uniform_r: f32 = r_tl.min(half_w).min(half_h).max(0.0);
5333        let cutoff_r_safe: f32 = cutoff + uniform_r + 1e-3;
5334        let (lx1, rx0): (u32, u32) = if has_mid_x {
5335            (sx0, sx1)
5336        } else if x_symmetric {
5337            let split_x: u32 = ((two_cx_i + 1).div_euclid(2).max(0) as u32).clamp(x0, x1);
5338            (split_x, split_x)
5339        } else {
5340            (x1, x1)
5341        };
5342        let color_rgb: [u8; 3] = [color.get_r(), color.get_g(), color.get_b()];
5343        let lin_rgb: [f32; 3] = [
5344            SRGB_TO_LIN_LUT[color_rgb[0] as usize],
5345            SRGB_TO_LIN_LUT[color_rgb[1] as usize],
5346            SRGB_TO_LIN_LUT[color_rgb[2] as usize],
5347        ];
5348        let ctx: ShadowRenderCtx = ShadowRenderCtx {
5349            color,
5350            color_rgb,
5351            lin_rgb,
5352            cx,
5353            cy,
5354            half_w,
5355            half_h,
5356            base_alpha,
5357            inv_sigma,
5358            cutoff,
5359            uniform_r,
5360            cutoff_r_safe_sq: cutoff_r_safe * cutoff_r_safe,
5361            x0,
5362            x1,
5363            lx1,
5364            rx0,
5365            mirror_x_sum: two_cx_i - 1,
5366            has_mid_x,
5367        };
5368        let mut shaded: usize = 0;
5369        if x_symmetric {
5370            let (top_end, bot_start): (u32, u32) = if has_mid_x && has_mid_y {
5371                (sy0, sy1)
5372            } else if y_symmetric {
5373                let split_y: u32 = ((two_cy_i + 1).div_euclid(2).max(0) as u32).clamp(y0, y1);
5374                (split_y, split_y)
5375            } else {
5376                (y1, y1)
5377            };
5378            let mirror_y_sum: i32 = two_cy_i - 1;
5379            let mut mirrored_b0: u32 = y1;
5380            let mut mirrored_b1: u32 = bot_start;
5381            for y_t in y0..top_end {
5382                let y_b_i: i32 = if y_symmetric {
5383                    mirror_y_sum - (y_t as i32)
5384                } else {
5385                    -1
5386                };
5387                if y_b_i >= (bot_start as i32) && y_b_i < (y1 as i32) {
5388                    let y_b: u32 = y_b_i as u32;
5389                    mirrored_b0 = mirrored_b0.min(y_b);
5390                    mirrored_b1 = mirrored_b1.max(y_b + 1);
5391                    shaded +=
5392                        Self::raster_shadow_corner_pair_symmetric(band, &ctx, y_t, y_b, cutouts);
5393                } else {
5394                    shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_t, cutouts);
5395                }
5396            }
5397            if has_mid_x && has_mid_y {
5398                shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
5399            }
5400            if mirrored_b0 < mirrored_b1 {
5401                for y_b in bot_start..mirrored_b0 {
5402                    shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
5403                }
5404                for y_b in mirrored_b1..y1 {
5405                    shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
5406                }
5407            } else {
5408                for y_b in bot_start..y1 {
5409                    shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
5410                }
5411            }
5412        } else if has_mid_x && has_mid_y {
5413            for y in y0..sy0 {
5414                shaded += Self::raster_shadow_corner_row_general(band, &ctx, radius, y, cutouts);
5415            }
5416            shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
5417            for y in sy1..y1 {
5418                shaded += Self::raster_shadow_corner_row_general(band, &ctx, radius, y, cutouts);
5419            }
5420        } else {
5421            for y in y0..y1 {
5422                shaded += Self::raster_shadow_corner_row_general(band, &ctx, radius, y, cutouts);
5423            }
5424        }
5425        shaded
5426    }
5427
5428    /// Rasterizes a pre-positioned glyph slice into `band` using direct slot indexing with zero HashMap lookups.
5429    ///
5430    /// # Arguments
5431    ///
5432    /// - `&mut PixelBand<'_>` - Target pixel band.
5433    /// - `&[PositionedGlyph]` - Pre-positioned glyph instances for this text run.
5434    /// - `Color` - Foreground text color.
5435    /// - `Rect` - Active physical clip bounds.
5436    /// - `&GlyphAtlas` - Read-only pre-warmed glyph atlas.
5437    ///
5438    /// # Returns
5439    ///
5440    /// - `usize` - Shaded pixel count.
5441    fn raster_text_run_band(
5442        band: &mut PixelBand<'_>,
5443        positioned_glyphs: &[PositionedGlyph],
5444        color: Color,
5445        clip: Rect,
5446        glyph_atlas: &GlyphAtlas,
5447    ) -> usize {
5448        let fb_w: i32 = band.width() as i32;
5449        let band_y0: i32 = band.y_offset() as i32;
5450        let band_y1: i32 = band.y_end() as i32;
5451        let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
5452        let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).clamp(band_y0, band_y1);
5453        let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(fb_w);
5454        let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).clamp(band_y0, band_y1);
5455        if color.get_a() == 0 || clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
5456            return 0;
5457        }
5458        let mut shaded: usize = 0;
5459        for pg in positioned_glyphs.iter() {
5460            let gy0: i32 = pg.y;
5461            let gh: i32 = pg.height as i32;
5462            if gy0 >= clip_y1 || gy0 + gh <= clip_y0 {
5463                continue;
5464            }
5465            let gx0: i32 = pg.x;
5466            let gw: i32 = pg.width as i32;
5467            if gx0 >= clip_x1 || gx0 + gw <= clip_x0 {
5468                continue;
5469            }
5470            let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(pg.glyph_idx);
5471            let py_start: i32 = (clip_y0 - gy0).max(0);
5472            let py_end: i32 = (clip_y1 - gy0).min(gh);
5473            let px_start: i32 = (clip_x0 - gx0).max(0);
5474            let px_end: i32 = (clip_x1 - gx0).min(gw);
5475            if py_start < py_end && px_start < px_end {
5476                let dy0: u32 = (gy0 + py_start) as u32;
5477                let dy1: u32 = (gy0 + py_end) as u32;
5478                if let Some((rows_buf, row_stride)) = band.rows_slice_mut(dy0, dy1) {
5479                    let cov_bytes: &[u8] = glyph.get_coverage().as_slice();
5480                    let gw_usize: usize = gw as usize;
5481                    let bx0: usize = ((gx0 + px_start) as usize) * 4;
5482                    let bx1: usize = ((gx0 + px_end) as usize) * 4;
5483                    let start_u: usize = px_start as usize;
5484                    let end_u: usize = px_end as usize;
5485                    let mut cov_off: usize = (py_start as usize) * gw_usize;
5486                    for row in rows_buf.chunks_exact_mut(row_stride) {
5487                        let row_slice: &[u8] = &cov_bytes[cov_off + start_u..cov_off + end_u];
5488                        shaded += blend_glyph_row_span(&mut row[bx0..bx1], row_slice, color);
5489                        cov_off += gw_usize;
5490                    }
5491                }
5492            }
5493        }
5494        shaded
5495    }
5496
5497    /// Blits a full-coverage bilinear RGBA8 horizontal sub-span using precomputed 8.8 vertical and horizontal LUT entries.
5498    ///
5499    /// # Arguments
5500    ///
5501    /// - `(usize, usize, u32, u32)` - Vertical row parameters `(row0_px, row1_px, wy_256, iwy_256)`.
5502    /// - `usize` - Starting destination X pixel coordinate within `dst_row`.
5503    /// - `&[(usize, usize, u32)]` - Horizontal sample LUT slice `(sx0, sx1, wx_256)` for this span.
5504    /// - `&[u8]` - Source RGBA8 pixel slice.
5505    /// - `&mut [u8]` - Destination framebuffer row slice.
5506    ///
5507    /// # Returns
5508    ///
5509    /// - `usize` - Number of non-transparent destination pixels shaded.
5510    #[inline(always)]
5511    fn blit_bilinear_span_precomputed(
5512        y_params: (usize, usize, u32, u32),
5513        dst_x0: usize,
5514        x_lut: &[(usize, usize, u32)],
5515        src_bytes: &[u8],
5516        dst_row: &mut [u8],
5517    ) -> usize {
5518        let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
5519        let span_bytes_start: usize = dst_x0 * 4;
5520        let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
5521        if span_bytes_end > dst_row.len() {
5522            return 0;
5523        }
5524        let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
5525            .as_chunks_mut::<4>()
5526            .0;
5527        let src_len: usize = src_bytes.len();
5528        let mut shaded: usize = 0;
5529        if wy == 0 {
5530            for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
5531                let i0: usize = (row0 + sx0) * 4;
5532                let i1: usize = (row0 + sx1) * 4;
5533                if i1 + 4 > src_len {
5534                    continue;
5535                }
5536                let iwx: u32 = 256 - wx;
5537                let a0: u32 = src_bytes[i0 + 3] as u32;
5538                let a1: u32 = src_bytes[i1 + 3] as u32;
5539                if (a0 & a1) == 255 {
5540                    dp[0] = (((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128)
5541                        >> 8) as u8;
5542                    dp[1] =
5543                        (((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128)
5544                            >> 8) as u8;
5545                    dp[2] =
5546                        (((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128)
5547                            >> 8) as u8;
5548                    dp[3] = 255;
5549                    shaded += 1;
5550                    continue;
5551                }
5552                let a_val: u32 = (a0 * iwx + a1 * wx + 128) >> 8;
5553                if a_val == 0 {
5554                    continue;
5555                }
5556                let r: u32 =
5557                    ((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128) >> 8;
5558                let g: u32 =
5559                    ((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128) >> 8;
5560                let b: u32 =
5561                    ((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128) >> 8;
5562                let inv_a: u32 = 255 - a_val;
5563                let vr: u32 = r * a_val + (dp[0] as u32) * inv_a + 128;
5564                let vg: u32 = g * a_val + (dp[1] as u32) * inv_a + 128;
5565                let vb: u32 = b * a_val + (dp[2] as u32) * inv_a + 128;
5566                dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
5567                dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
5568                dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
5569                dp[3] = 255;
5570                shaded += 1;
5571            }
5572            return shaded;
5573        }
5574        for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
5575            let i00: usize = (row0 + sx0) * 4;
5576            let i10: usize = (row0 + sx1) * 4;
5577            let i01: usize = (row1 + sx0) * 4;
5578            let i11: usize = (row1 + sx1) * 4;
5579            if i11 + 4 > src_len {
5580                continue;
5581            }
5582            let iwx: u32 = 256 - wx;
5583            let w00: u32 = iwx * iwy;
5584            let w10: u32 = wx * iwy;
5585            let w01: u32 = iwx * wy;
5586            let w11: u32 = wx * wy;
5587            let a00: u32 = src_bytes[i00 + 3] as u32;
5588            let a10: u32 = src_bytes[i10 + 3] as u32;
5589            let a01: u32 = src_bytes[i01 + 3] as u32;
5590            let a11: u32 = src_bytes[i11 + 3] as u32;
5591            if (a00 & a10 & a01 & a11) == 255 {
5592                dp[0] = (((src_bytes[i00] as u32) * w00
5593                    + (src_bytes[i10] as u32) * w10
5594                    + (src_bytes[i01] as u32) * w01
5595                    + (src_bytes[i11] as u32) * w11
5596                    + 32768)
5597                    >> 16) as u8;
5598                dp[1] = (((src_bytes[i00 + 1] as u32) * w00
5599                    + (src_bytes[i10 + 1] as u32) * w10
5600                    + (src_bytes[i01 + 1] as u32) * w01
5601                    + (src_bytes[i11 + 1] as u32) * w11
5602                    + 32768)
5603                    >> 16) as u8;
5604                dp[2] = (((src_bytes[i00 + 2] as u32) * w00
5605                    + (src_bytes[i10 + 2] as u32) * w10
5606                    + (src_bytes[i01 + 2] as u32) * w01
5607                    + (src_bytes[i11 + 2] as u32) * w11
5608                    + 32768)
5609                    >> 16) as u8;
5610                dp[3] = 255;
5611                shaded += 1;
5612                continue;
5613            }
5614            let a_val: u32 = (a00 * w00 + a10 * w10 + a01 * w01 + a11 * w11 + 32768) >> 16;
5615            if a_val == 0 {
5616                continue;
5617            }
5618            let r: u32 = ((src_bytes[i00] as u32) * w00
5619                + (src_bytes[i10] as u32) * w10
5620                + (src_bytes[i01] as u32) * w01
5621                + (src_bytes[i11] as u32) * w11
5622                + 32768)
5623                >> 16;
5624            let g: u32 = ((src_bytes[i00 + 1] as u32) * w00
5625                + (src_bytes[i10 + 1] as u32) * w10
5626                + (src_bytes[i01 + 1] as u32) * w01
5627                + (src_bytes[i11 + 1] as u32) * w11
5628                + 32768)
5629                >> 16;
5630            let b: u32 = ((src_bytes[i00 + 2] as u32) * w00
5631                + (src_bytes[i10 + 2] as u32) * w10
5632                + (src_bytes[i01 + 2] as u32) * w01
5633                + (src_bytes[i11 + 2] as u32) * w11
5634                + 32768)
5635                >> 16;
5636            let inv_a: u32 = 255 - a_val;
5637            let vr: u32 = r * a_val + (dp[0] as u32) * inv_a + 128;
5638            let vg: u32 = g * a_val + (dp[1] as u32) * inv_a + 128;
5639            let vb: u32 = b * a_val + (dp[2] as u32) * inv_a + 128;
5640            dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
5641            dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
5642            dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
5643            dp[3] = 255;
5644            shaded += 1;
5645        }
5646        shaded
5647    }
5648
5649    /// Executes bilinear image rasterization using reusable horizontal LUT buffer `x_lut`.
5650    ///
5651    /// # Arguments
5652    ///
5653    /// - `&mut PixelBand<'_>` - Target pixel band.
5654    /// - `Rect` - Physical destination bounds.
5655    /// - `(u32, u32, &[u8])` - Source dimensions and RGBA8 slice `(src_w, src_h, src_bytes)`.
5656    /// - `(u32, u32, u32, u32)` - Clipped visible pixel bounds `(x0, y0, x1, y1)`.
5657    /// - `CornerRadius` - Physical corner radii.
5658    /// - `AntialiasingMode` - Active AA policy.
5659    /// - `&mut Vec<(usize, usize, u32)>` - Reusable horizontal sample LUT buffer.
5660    ///
5661    /// # Returns
5662    ///
5663    /// - `usize` - Shaded pixel count.
5664    fn raster_image_bilinear_with_lut(
5665        band: &mut PixelBand<'_>,
5666        rect: Rect,
5667        src_info: (u32, u32, &[u8]),
5668        bounds: (u32, u32, u32, u32),
5669        radius: CornerRadius,
5670        aa: AntialiasingMode,
5671        x_lut: &mut Vec<(usize, usize, u32)>,
5672    ) -> usize {
5673        let (src_w, src_h, src_bytes): (u32, u32, &[u8]) = src_info;
5674        let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
5675        let rect_x: f32 = rect.get_x();
5676        let rect_y: f32 = rect.get_y();
5677        let half_w: f32 = rect.get_width() * 0.5;
5678        let half_h: f32 = rect.get_height() * 0.5;
5679        let cx: f32 = rect_x + half_w;
5680        let cy: f32 = rect_y + half_h;
5681        let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
5682        let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
5683        let src_w_f: f32 = src_w as f32;
5684        let src_h_f: f32 = src_h as f32;
5685        let src_w_usize: usize = src_w as usize;
5686        let max_sx: usize = src_w_usize.saturating_sub(1);
5687        let max_sy: usize = (src_h as usize).saturating_sub(1);
5688        let has_radius: bool = radius.max_radius() > 0.0;
5689        x_lut.clear();
5690        for x in x0..x1 {
5691            let u: f32 = (((x as f32) + 0.5 - rect_x) * inv_dst_w).clamp(0.0, 1.0);
5692            let fx: f32 = (u * src_w_f - 0.5).clamp(0.0, max_sx as f32);
5693            let sx0: usize = (fx.floor() as usize).min(max_sx);
5694            let sx1: usize = (sx0 + 1).min(max_sx);
5695            let wx: u32 = ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
5696            x_lut.push((sx0, sx1, wx));
5697        }
5698        let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
5699        if !has_radius {
5700            let x0_u: usize = x0 as usize;
5701            for y in y0..y1 {
5702                let Some(dst_row) = band.row_slice_mut(y) else {
5703                    continue;
5704                };
5705                let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
5706                let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
5707                let sy0: usize = (fy.floor() as usize).min(max_sy);
5708                let sy1: usize = (sy0 + 1).min(max_sy);
5709                let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
5710                let y_params: (usize, usize, u32, u32) =
5711                    (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
5712                let _: usize = Self::blit_bilinear_span_precomputed(
5713                    y_params, x0_u, x_lut_ref, src_bytes, dst_row,
5714                );
5715            }
5716            return ((x1 - x0) as usize) * ((y1 - y0) as usize);
5717        }
5718        let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
5719        let ix0: u32 = ((rect_x + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
5720        let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
5721        let iy0: u32 = ((rect_y + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
5722        let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
5723        let cx0: u32 = ((rect_x + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
5724        let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
5725        let mut shaded: usize = 0;
5726        for y in y0..iy0 {
5727            let Some(dst_row) = band.row_slice_mut(y) else {
5728                continue;
5729            };
5730            let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
5731            let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
5732            let sy0: usize = (fy.floor() as usize).min(max_sy);
5733            let sy1: usize = (sy0 + 1).min(max_sy);
5734            let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
5735            let y_params: (usize, usize, u32, u32) =
5736                (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
5737            let py: f32 = (y as f32) + 0.5 - cy;
5738            let dist_y: f32 = py.abs() - half_h;
5739            let mid_cov: f32 = sdf_coverage(dist_y, aa);
5740            if cx0 < cx1 && mid_cov > 0.0 {
5741                let lut_s: usize = (cx0 - x0) as usize;
5742                let lut_e: usize = (cx1 - x0) as usize;
5743                if mid_cov >= 0.9995 {
5744                    let _: usize = Self::blit_bilinear_span_precomputed(
5745                        y_params,
5746                        cx0 as usize,
5747                        &x_lut_ref[lut_s..lut_e],
5748                        src_bytes,
5749                        dst_row,
5750                    );
5751                } else {
5752                    for x in cx0..cx1 {
5753                        let rgba: [u8; 4] = sample_bilinear_fixed(
5754                            src_bytes,
5755                            y_params,
5756                            x_lut_ref[(x - x0) as usize],
5757                        );
5758                        let off: usize = (x as usize) * 4;
5759                        blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
5760                    }
5761                }
5762                shaded += (cx1 - cx0) as usize;
5763            }
5764            for x in x0..cx0 {
5765                let px: f32 = (x as f32) + 0.5 - cx;
5766                let cr: f32 = quadrant_corner_radius(radius, px, py);
5767                let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
5768                if cov > 0.0 {
5769                    let rgba: [u8; 4] =
5770                        sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
5771                    let off: usize = (x as usize) * 4;
5772                    blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
5773                    shaded += 1;
5774                }
5775            }
5776            for x in cx1..x1 {
5777                let px: f32 = (x as f32) + 0.5 - cx;
5778                let cr: f32 = quadrant_corner_radius(radius, px, py);
5779                let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
5780                if cov > 0.0 {
5781                    let rgba: [u8; 4] =
5782                        sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
5783                    let off: usize = (x as usize) * 4;
5784                    blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
5785                    shaded += 1;
5786                }
5787            }
5788        }
5789        for y in iy0..iy1 {
5790            let Some(dst_row) = band.row_slice_mut(y) else {
5791                continue;
5792            };
5793            let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
5794            let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
5795            let sy0: usize = (fy.floor() as usize).min(max_sy);
5796            let sy1: usize = (sy0 + 1).min(max_sy);
5797            let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
5798            let y_params: (usize, usize, u32, u32) =
5799                (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
5800            if ix0 < ix1 {
5801                let lut_s: usize = (ix0 - x0) as usize;
5802                let lut_e: usize = (ix1 - x0) as usize;
5803                let _: usize = Self::blit_bilinear_span_precomputed(
5804                    y_params,
5805                    ix0 as usize,
5806                    &x_lut_ref[lut_s..lut_e],
5807                    src_bytes,
5808                    dst_row,
5809                );
5810                shaded += (ix1 - ix0) as usize;
5811            }
5812            for x in x0..ix0 {
5813                let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
5814                let cov: f32 = sdf_coverage(dist, aa);
5815                if cov > 0.0 {
5816                    let rgba: [u8; 4] =
5817                        sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
5818                    let off: usize = (x as usize) * 4;
5819                    blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
5820                    shaded += 1;
5821                }
5822            }
5823            for x in ix1..x1 {
5824                let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
5825                let cov: f32 = sdf_coverage(dist, aa);
5826                if cov > 0.0 {
5827                    let rgba: [u8; 4] =
5828                        sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
5829                    let off: usize = (x as usize) * 4;
5830                    blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
5831                    shaded += 1;
5832                }
5833            }
5834        }
5835        for y in iy1..y1 {
5836            let Some(dst_row) = band.row_slice_mut(y) else {
5837                continue;
5838            };
5839            let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
5840            let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
5841            let sy0: usize = (fy.floor() as usize).min(max_sy);
5842            let sy1: usize = (sy0 + 1).min(max_sy);
5843            let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
5844            let y_params: (usize, usize, u32, u32) =
5845                (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
5846            let py: f32 = (y as f32) + 0.5 - cy;
5847            let dist_y: f32 = py.abs() - half_h;
5848            let mid_cov: f32 = sdf_coverage(dist_y, aa);
5849            if cx0 < cx1 && mid_cov > 0.0 {
5850                let lut_s: usize = (cx0 - x0) as usize;
5851                let lut_e: usize = (cx1 - x0) as usize;
5852                if mid_cov >= 0.9995 {
5853                    let _: usize = Self::blit_bilinear_span_precomputed(
5854                        y_params,
5855                        cx0 as usize,
5856                        &x_lut_ref[lut_s..lut_e],
5857                        src_bytes,
5858                        dst_row,
5859                    );
5860                } else {
5861                    for x in cx0..cx1 {
5862                        let rgba: [u8; 4] = sample_bilinear_fixed(
5863                            src_bytes,
5864                            y_params,
5865                            x_lut_ref[(x - x0) as usize],
5866                        );
5867                        let off: usize = (x as usize) * 4;
5868                        blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
5869                    }
5870                }
5871                shaded += (cx1 - cx0) as usize;
5872            }
5873            for x in x0..cx0 {
5874                let px: f32 = (x as f32) + 0.5 - cx;
5875                let cr: f32 = quadrant_corner_radius(radius, px, py);
5876                let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
5877                if cov > 0.0 {
5878                    let rgba: [u8; 4] =
5879                        sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
5880                    let off: usize = (x as usize) * 4;
5881                    blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
5882                    shaded += 1;
5883                }
5884            }
5885            for x in cx1..x1 {
5886                let px: f32 = (x as f32) + 0.5 - cx;
5887                let cr: f32 = quadrant_corner_radius(radius, px, py);
5888                let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
5889                if cov > 0.0 {
5890                    let rgba: [u8; 4] =
5891                        sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
5892                    let off: usize = (x as usize) * 4;
5893                    blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
5894                    shaded += 1;
5895                }
5896            }
5897        }
5898        shaded
5899    }
5900
5901    /// Blits a decoded `ImageBuffer` into `band` with 1:1 scanline fast paths, reusable `x_lut` bilinear filtering, and corner-only SDF clipping.
5902    ///
5903    /// # Arguments
5904    ///
5905    /// - `&mut PixelBand<'_>` - Target pixel band.
5906    /// - `Rect` - Physical destination bounds.
5907    /// - `&ImageBuffer` - Source RGBA8 image.
5908    /// - `CornerRadius` - Physical corner radii.
5909    /// - `Rect` - Active clip bounds.
5910    /// - `AntialiasingMode` - Active AA policy.
5911    ///
5912    /// # Returns
5913    ///
5914    /// - `usize` - Shaded pixel count.
5915    fn raster_image(
5916        band: &mut PixelBand<'_>,
5917        rect: Rect,
5918        buffer: &ImageBuffer,
5919        radius: CornerRadius,
5920        clip: Rect,
5921        aa: AntialiasingMode,
5922    ) -> usize {
5923        if buffer.get_width() == 0 || buffer.get_height() == 0 {
5924            return 0;
5925        }
5926        let Some(vis) = rect.intersect(clip) else {
5927            return 0;
5928        };
5929        let fb_w: u32 = band.width();
5930        let band_y0: u32 = band.y_offset();
5931        let band_y1: u32 = band.y_end();
5932        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
5933        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
5934        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
5935        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
5936        if x0 >= x1 || y0 >= y1 {
5937            return 0;
5938        }
5939        let half_w: f32 = rect.get_width() * 0.5;
5940        let half_h: f32 = rect.get_height() * 0.5;
5941        let cx: f32 = rect.get_x() + half_w;
5942        let cy: f32 = rect.get_y() + half_h;
5943        let src_w: u32 = buffer.get_width();
5944        let src_h: u32 = buffer.get_height();
5945        let src_bytes: &[u8] = buffer.get_pixels().as_slice();
5946        let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
5947        let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
5948        let use_bilinear: bool = aa != AntialiasingMode::None
5949            && ((rect.get_width() - (src_w as f32)).abs() > 0.5
5950                || (rect.get_height() - (src_h as f32)).abs() > 0.5);
5951        let has_radius: bool = radius.max_radius() > 0.0;
5952        let max_sx: usize = (src_w as usize).saturating_sub(1);
5953        let max_sy: usize = (src_h as usize).saturating_sub(1);
5954        let src_w_usize: usize = src_w as usize;
5955        let is_exact_1to1: bool = !use_bilinear
5956            && (rect.get_width() - (src_w as f32)).abs() <= 0.01
5957            && (rect.get_height() - (src_h as f32)).abs() <= 0.01
5958            && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
5959            && (rect.get_y() - rect.get_y().round()).abs() <= 0.01;
5960        let rx0_i: i32 = rect.get_x().round() as i32;
5961        let ry0_i: i32 = rect.get_y().round() as i32;
5962        if is_exact_1to1
5963            && !has_radius
5964            && (x0 as i32) >= rx0_i
5965            && (x1 as i32) <= rx0_i + (src_w as i32)
5966            && (y0 as i32) >= ry0_i
5967            && (y1 as i32) <= ry0_i + (src_h as i32)
5968        {
5969            let span_w: usize = (x1 - x0) as usize;
5970            let src_x_off: usize = ((x0 as i32) - rx0_i) as usize;
5971            let dst_byte0: usize = (x0 as usize) * 4;
5972            let dst_byte1: usize = (x1 as usize) * 4;
5973            for y in y0..y1 {
5974                let Some(dst_row) = band.row_slice_mut(y) else {
5975                    continue;
5976                };
5977                let sy: usize = ((y as i32) - ry0_i) as usize;
5978                let src_byte0: usize = (sy * src_w_usize + src_x_off) * 4;
5979                let src_byte1: usize = src_byte0 + span_w * 4;
5980                if src_byte1 <= src_bytes.len() && dst_byte1 <= dst_row.len() {
5981                    blit_1to1_rgba_span(
5982                        &src_bytes[src_byte0..src_byte1],
5983                        &mut dst_row[dst_byte0..dst_byte1],
5984                    );
5985                }
5986            }
5987            return span_w * ((y1 - y0) as usize);
5988        }
5989        if use_bilinear {
5990            let mut shaded: usize = 0;
5991            let ran_tls: bool = BAND_IMAGE_X_LUT
5992                .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
5993                    if let Ok(mut guard) = cell.try_borrow_mut() {
5994                        shaded = Self::raster_image_bilinear_with_lut(
5995                            band,
5996                            rect,
5997                            (src_w, src_h, src_bytes),
5998                            (x0, y0, x1, y1),
5999                            radius,
6000                            aa,
6001                            &mut guard,
6002                        );
6003                    }
6004                })
6005                .is_ok();
6006            if !ran_tls {
6007                let mut fallback_lut: Vec<(usize, usize, u32)> =
6008                    Vec::with_capacity((x1 - x0) as usize);
6009                shaded = Self::raster_image_bilinear_with_lut(
6010                    band,
6011                    rect,
6012                    (src_w, src_h, src_bytes),
6013                    (x0, y0, x1, y1),
6014                    radius,
6015                    aa,
6016                    &mut fallback_lut,
6017                );
6018            }
6019            return shaded;
6020        }
6021        let mut shaded: usize = 0;
6022        let r_max: f32 = if has_radius {
6023            radius.max_radius().min(half_w).min(half_h).max(0.0)
6024        } else {
6025            0.0
6026        };
6027        let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
6028        let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
6029        let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
6030        let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
6031        let can_1to1_interior: bool = is_exact_1to1
6032            && (ix0 as i32) >= rx0_i
6033            && (ix1 as i32) <= rx0_i + (src_w as i32)
6034            && (iy0 as i32) >= ry0_i
6035            && (iy1 as i32) <= ry0_i + (src_h as i32);
6036        for y in y0..y1 {
6037            let Some(dst_row) = band.row_slice_mut(y) else {
6038                continue;
6039            };
6040            let v: f32 = (((y as f32) + 0.5 - rect.get_y()) * inv_dst_h).clamp(0.0, 1.0);
6041            let py: f32 = (y as f32) + 0.5 - cy;
6042            let sy: usize = ((v * (src_h as f32)).floor() as usize).min(max_sy);
6043            let row: usize = sy * src_w_usize;
6044            if has_radius && can_1to1_interior && y >= iy0 && y < iy1 && ix0 < ix1 {
6045                let src_off: usize = (row + (((ix0 as i32) - rx0_i) as usize)) * 4;
6046                let span_bytes: usize = ((ix1 - ix0) as usize) * 4;
6047                let dst_off: usize = (ix0 as usize) * 4;
6048                if src_off + span_bytes <= src_bytes.len() && dst_off + span_bytes <= dst_row.len()
6049                {
6050                    blit_1to1_rgba_span(
6051                        &src_bytes[src_off..src_off + span_bytes],
6052                        &mut dst_row[dst_off..dst_off + span_bytes],
6053                    );
6054                }
6055                shaded += (ix1 - ix0) as usize;
6056                for x in x0..ix0 {
6057                    let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
6058                    let cov: f32 = sdf_coverage(dist, aa);
6059                    if cov > 0.0 {
6060                        let u: f32 =
6061                            (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
6062                        let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
6063                        let idx: usize = (row + sx) * 4;
6064                        if idx + 4 <= src_bytes.len() {
6065                            let off: usize = (x as usize) * 4;
6066                            blend_rgba_pixel_with_cov(
6067                                &mut dst_row[off..off + 4],
6068                                [
6069                                    src_bytes[idx],
6070                                    src_bytes[idx + 1],
6071                                    src_bytes[idx + 2],
6072                                    src_bytes[idx + 3],
6073                                ],
6074                                cov,
6075                            );
6076                            shaded += 1;
6077                        }
6078                    }
6079                }
6080                for x in ix1..x1 {
6081                    let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
6082                    let cov: f32 = sdf_coverage(dist, aa);
6083                    if cov > 0.0 {
6084                        let u: f32 =
6085                            (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
6086                        let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
6087                        let idx: usize = (row + sx) * 4;
6088                        if idx + 4 <= src_bytes.len() {
6089                            let off: usize = (x as usize) * 4;
6090                            blend_rgba_pixel_with_cov(
6091                                &mut dst_row[off..off + 4],
6092                                [
6093                                    src_bytes[idx],
6094                                    src_bytes[idx + 1],
6095                                    src_bytes[idx + 2],
6096                                    src_bytes[idx + 3],
6097                                ],
6098                                cov,
6099                            );
6100                            shaded += 1;
6101                        }
6102                    }
6103                }
6104                continue;
6105            }
6106            for x in x0..x1 {
6107                let cov: f32 = if has_radius {
6108                    let px: f32 = (x as f32) + 0.5 - cx;
6109                    let cr: f32 = quadrant_corner_radius(radius, px, py);
6110                    sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
6111                } else {
6112                    1.0
6113                };
6114                if cov <= 0.0 {
6115                    continue;
6116                }
6117                let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
6118                let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
6119                let idx: usize = (row + sx) * 4;
6120                if idx + 4 <= src_bytes.len() {
6121                    let off: usize = (x as usize) * 4;
6122                    blend_rgba_pixel_with_cov(
6123                        &mut dst_row[off..off + 4],
6124                        [
6125                            src_bytes[idx],
6126                            src_bytes[idx + 1],
6127                            src_bytes[idx + 2],
6128                            src_bytes[idx + 3],
6129                        ],
6130                        cov,
6131                    );
6132                    shaded += 1;
6133                }
6134            }
6135        }
6136        shaded
6137    }
6138
6139    /// Rasterizes an anti-aliased line segment between `from` and `to` using oriented scanline X-bounds and squared-distance rejection.
6140    ///
6141    /// # Arguments
6142    ///
6143    /// - `&mut PixelBand<'_>` - Target pixel band.
6144    /// - `Point` - Physical start point.
6145    /// - `Point` - Physical end point.
6146    /// - `Color` - Stroke color.
6147    /// - `f32` - Physical stroke width.
6148    /// - `Rect` - Active clip bounds.
6149    /// - `AntialiasingMode` - Active AA policy.
6150    ///
6151    /// # Returns
6152    ///
6153    /// - `usize` - Shaded pixel count.
6154    fn raster_line(
6155        band: &mut PixelBand<'_>,
6156        from: Point,
6157        to: Point,
6158        color: Color,
6159        width: f32,
6160        clip: Rect,
6161        aa: AntialiasingMode,
6162    ) -> usize {
6163        if color.get_a() == 0 {
6164            return 0;
6165        }
6166        let half_w: f32 = width * 0.5;
6167        let min_x: f32 = from.get_x().min(to.get_x()) - half_w - 1.0;
6168        let min_y: f32 = from.get_y().min(to.get_y()) - half_w - 1.0;
6169        let max_x: f32 = from.get_x().max(to.get_x()) + half_w + 1.0;
6170        let max_y: f32 = from.get_y().max(to.get_y()) + half_w + 1.0;
6171        let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
6172        else {
6173            return 0;
6174        };
6175        let fb_w: u32 = band.width();
6176        let band_y0: u32 = band.y_offset();
6177        let band_y1: u32 = band.y_end();
6178        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6179        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6180        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6181        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6182        if x0 >= x1 || y0 >= y1 {
6183            return 0;
6184        }
6185        let fx0: f32 = from.get_x();
6186        let fy0: f32 = from.get_y();
6187        let dx: f32 = to.get_x() - fx0;
6188        let dy: f32 = to.get_y() - fy0;
6189        let len_sq: f32 = (dx * dx + dy * dy).max(1e-6);
6190        let inv_len_sq: f32 = 1.0 / len_sq;
6191        let outer_r: f32 = half_w + 0.9;
6192        let outer_r_sq: f32 = outer_r * outer_r;
6193        let inner_r: f32 = (half_w - 0.9).max(0.0);
6194        let inner_r_sq: f32 = inner_r * inner_r;
6195        let has_inner: bool = half_w > 0.9;
6196        let use_oriented_x: bool = dy.abs() > 1e-4;
6197        let slope_x_per_y: f32 = if use_oriented_x { dx / dy } else { 0.0 };
6198        let x_pad: f32 = if use_oriented_x {
6199            outer_r * (len_sq.sqrt() / dy.abs()) + 0.5
6200        } else {
6201            0.0
6202        };
6203        let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
6204        let lin_rgb: [f32; 3] = [
6205            SRGB_TO_LIN_LUT[color.get_r() as usize],
6206            SRGB_TO_LIN_LUT[color.get_g() as usize],
6207            SRGB_TO_LIN_LUT[color.get_b() as usize],
6208        ];
6209        let mut shaded: usize = 0;
6210        for y in y0..y1 {
6211            let py: f32 = (y as f32) + 0.5;
6212            let py_off: f32 = py - fy0;
6213            let (row_x0, row_x1): (u32, u32) = if use_oriented_x {
6214                let x_center: f32 = fx0 + py_off * slope_x_per_y;
6215                let rx0: u32 = ((x_center - x_pad).floor().max(0.0) as u32).clamp(x0, x1);
6216                let rx1: u32 = ((x_center + x_pad).ceil().max(0.0) as u32).clamp(rx0, x1);
6217                (rx0, rx1)
6218            } else {
6219                (x0, x1)
6220            };
6221            if row_x0 >= row_x1 {
6222                continue;
6223            }
6224            let Some(row) = band.row_slice_mut(y) else {
6225                continue;
6226            };
6227            let py_dy: f32 = py_off * dy;
6228            for x in row_x0..row_x1 {
6229                let px: f32 = (x as f32) + 0.5;
6230                let t: f32 = (((px - fx0) * dx + py_dy) * inv_len_sq).clamp(0.0, 1.0);
6231                let dpx: f32 = px - (fx0 + t * dx);
6232                let dpy: f32 = py - (fy0 + t * dy);
6233                let dist_sq: f32 = dpx * dpx + dpy * dpy;
6234                if dist_sq >= outer_r_sq {
6235                    continue;
6236                }
6237                let cov: f32 = if has_inner && dist_sq <= inner_r_sq {
6238                    1.0
6239                } else {
6240                    sdf_coverage(dist_sq.sqrt() - half_w, aa)
6241                };
6242                if cov > 0.0 {
6243                    blend_row_pixel_f32_precomputed(row, x, color, lin_rgb, base_alpha * cov);
6244                    shaded += 1;
6245                }
6246            }
6247        }
6248        shaded
6249    }
6250
6251    /// Rasterizes an analytical SDF anti-aliased filled circle with LUT interior chord fills and tight 4x4 RGSS rim sampling.
6252    ///
6253    /// # Arguments
6254    ///
6255    /// - `&mut PixelBand<'_>` - Target pixel band.
6256    /// - `Point` - Physical center point.
6257    /// - `f32` - Physical radius.
6258    /// - `Color` - Fill color.
6259    /// - `Rect` - Active clip bounds.
6260    /// - `AntialiasingMode` - Active AA policy.
6261    ///
6262    /// # Returns
6263    ///
6264    /// - `usize` - Shaded pixel count.
6265    fn raster_circle(
6266        band: &mut PixelBand<'_>,
6267        center: Point,
6268        radius: f32,
6269        color: Color,
6270        clip: Rect,
6271        aa: AntialiasingMode,
6272    ) -> usize {
6273        if radius <= 0.0 || color.get_a() == 0 {
6274            return 0;
6275        }
6276        let bounds: Rect = Rect::new(
6277            center.get_x() - radius - 1.0,
6278            center.get_y() - radius - 1.0,
6279            (radius + 1.0) * 2.0,
6280            (radius + 1.0) * 2.0,
6281        );
6282        let Some(vis) = bounds.intersect(clip) else {
6283            return 0;
6284        };
6285        let fb_w: u32 = band.width();
6286        let band_y0: u32 = band.y_offset();
6287        let band_y1: u32 = band.y_end();
6288        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6289        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6290        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6291        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6292        if x0 >= x1 || y0 >= y1 {
6293            return 0;
6294        }
6295        let outer_r: f32 = if aa == AntialiasingMode::None {
6296            radius + 0.5
6297        } else {
6298            radius + 0.65
6299        };
6300        let inner_r: f32 = if aa == AntialiasingMode::None {
6301            (radius - 0.5).max(0.0)
6302        } else {
6303            (radius - 0.65).max(0.0)
6304        };
6305        let outer_r2: f32 = outer_r * outer_r;
6306        let inner_r2: f32 = inner_r * inner_r;
6307        let r2: f32 = radius * radius;
6308        let cx: f32 = center.get_x();
6309        let cy: f32 = center.get_y();
6310        let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
6311        let lin_rgb: [f32; 3] = [
6312            SRGB_TO_LIN_LUT[color.get_r() as usize],
6313            SRGB_TO_LIN_LUT[color.get_g() as usize],
6314            SRGB_TO_LIN_LUT[color.get_b() as usize],
6315        ];
6316        let interior_luts: Option<RgbaLutQuad> = if color.get_a() < 255 && radius >= 12.0 {
6317            Some(build_linear_blend_luts(color))
6318        } else {
6319            None
6320        };
6321        let mut shaded: usize = 0;
6322        for y in y0..y1 {
6323            let dy: f32 = (y as f32) + 0.5 - cy;
6324            let dy2: f32 = dy * dy;
6325            if dy2 >= outer_r2 {
6326                continue;
6327            }
6328            let out_dx: f32 = (outer_r2 - dy2).sqrt();
6329            let row_x0: u32 = ((cx - out_dx).floor().max(0.0) as u32).clamp(x0, x1);
6330            let row_x1: u32 = ((cx + out_dx).ceil().max(0.0) as u32).clamp(row_x0, x1);
6331            if row_x0 >= row_x1 {
6332                continue;
6333            }
6334            if dy2 < inner_r2 && inner_r > 0.65 {
6335                let in_dx: f32 = (inner_r2 - dy2).sqrt();
6336                let in_x0: u32 = ((cx - in_dx).ceil().max(0.0) as u32).clamp(row_x0, row_x1);
6337                let in_x1: u32 = ((cx + in_dx).floor().max(0.0) as u32).clamp(in_x0, row_x1);
6338                if in_x0 < in_x1 {
6339                    if let Some(ref luts) = interior_luts {
6340                        band.fill_span_linear_luts(in_x0, in_x1, y, luts);
6341                    } else {
6342                        band.fill_span_linear(in_x0, in_x1, y, color);
6343                    }
6344                    shaded += (in_x1 - in_x0) as usize;
6345                }
6346                if (row_x0 < in_x0 || in_x1 < row_x1)
6347                    && let Some(row) = band.row_slice_mut(y)
6348                {
6349                    for x in row_x0..in_x0 {
6350                        let dx: f32 = (x as f32) + 0.5 - cx;
6351                        let cov: f32 = if aa == AntialiasingMode::None {
6352                            if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
6353                        } else {
6354                            circle_supersampled_coverage(dx, dy, radius)
6355                        };
6356                        if cov > 0.0 {
6357                            blend_row_pixel_f32_precomputed(
6358                                row,
6359                                x,
6360                                color,
6361                                lin_rgb,
6362                                base_alpha * cov,
6363                            );
6364                            shaded += 1;
6365                        }
6366                    }
6367                    for x in in_x1..row_x1 {
6368                        let dx: f32 = (x as f32) + 0.5 - cx;
6369                        let cov: f32 = if aa == AntialiasingMode::None {
6370                            if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
6371                        } else {
6372                            circle_supersampled_coverage(dx, dy, radius)
6373                        };
6374                        if cov > 0.0 {
6375                            blend_row_pixel_f32_precomputed(
6376                                row,
6377                                x,
6378                                color,
6379                                lin_rgb,
6380                                base_alpha * cov,
6381                            );
6382                            shaded += 1;
6383                        }
6384                    }
6385                }
6386            } else if let Some(row) = band.row_slice_mut(y) {
6387                for x in row_x0..row_x1 {
6388                    let dx: f32 = (x as f32) + 0.5 - cx;
6389                    let cov: f32 = if aa == AntialiasingMode::None {
6390                        if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
6391                    } else {
6392                        circle_supersampled_coverage(dx, dy, radius)
6393                    };
6394                    if cov > 0.0 {
6395                        blend_row_pixel_f32_precomputed(row, x, color, lin_rgb, base_alpha * cov);
6396                        shaded += 1;
6397                    }
6398                }
6399            }
6400        }
6401        shaded
6402    }
6403
6404    /// Solves the 1D horizontal interval `[s_min, s_max]` where all three linear edge distances satisfy `d_i(s) >= thresh`.
6405    ///
6406    /// # Arguments
6407    ///
6408    /// - `[f32; 3]` - Edge distances `[d0, d1, d2]` evaluated at scanline reference `px_base`.
6409    /// - `[f32; 3]` - Per-pixel horizontal edge distance steps `[a0, a1, a2]`.
6410    /// - `f32` - Distance threshold (`-0.86` for outer rim, `+0.86` for solid interior).
6411    /// - `f32` - Upper horizontal offset bound `(clip_x1 - clip_x0) as f32`.
6412    ///
6413    /// # Returns
6414    ///
6415    /// - `(f32, f32)` - Active offset interval `(s_min, s_max)` (`s_min > s_max` when empty).
6416    #[inline(always)]
6417    #[must_use]
6418    fn solve_triangle_scanline_interval(
6419        d_base: [f32; 3],
6420        a_step: [f32; 3],
6421        thresh: f32,
6422        max_s: f32,
6423    ) -> (f32, f32) {
6424        let mut s_min: f32 = 0.0;
6425        let mut s_max: f32 = max_s;
6426        for idx in 0..3usize {
6427            let a: f32 = a_step[idx];
6428            let d: f32 = d_base[idx];
6429            if a > 1e-6 {
6430                let bound: f32 = (thresh - d) / a;
6431                if bound > s_min {
6432                    s_min = bound;
6433                }
6434            } else if a < -1e-6 {
6435                let bound: f32 = (thresh - d) / a;
6436                if bound < s_max {
6437                    s_max = bound;
6438                }
6439            } else if d < thresh {
6440                return (1.0, 0.0);
6441            }
6442        }
6443        (s_min, s_max)
6444    }
6445
6446    /// Rasterizes a solid filled triangle using scanline edge-interval solving, LUT interior span fills, and edge-only 4x4 RGSS.
6447    ///
6448    /// # Arguments
6449    ///
6450    /// - `&mut PixelBand<'_>` - Target pixel band.
6451    /// - `Point` - First physical vertex.
6452    /// - `Point` - Second physical vertex.
6453    /// - `Point` - Third physical vertex.
6454    /// - `Color` - Fill color.
6455    /// - `Rect` - Active clip bounds.
6456    /// - `AntialiasingMode` - Active AA policy.
6457    ///
6458    /// # Returns
6459    ///
6460    /// - `usize` - Shaded pixel count.
6461    fn raster_triangle(
6462        band: &mut PixelBand<'_>,
6463        p0: Point,
6464        p1: Point,
6465        p2: Point,
6466        color: Color,
6467        clip: Rect,
6468        aa: AntialiasingMode,
6469    ) -> usize {
6470        if color.get_a() == 0 {
6471            return 0;
6472        }
6473        let dx0: f32 = p1.get_x() - p0.get_x();
6474        let dy0: f32 = p1.get_y() - p0.get_y();
6475        let dx1: f32 = p2.get_x() - p1.get_x();
6476        let dy1: f32 = p2.get_y() - p1.get_y();
6477        let dx2: f32 = p0.get_x() - p2.get_x();
6478        let dy2: f32 = p0.get_y() - p2.get_y();
6479        let area: f32 = dx0 * (p2.get_y() - p0.get_y()) - dy0 * (p2.get_x() - p0.get_x());
6480        if area.abs() < 1e-5 {
6481            return 0;
6482        }
6483        let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) - 1.0;
6484        let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) - 1.0;
6485        let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) + 1.0;
6486        let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) + 1.0;
6487        let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
6488        else {
6489            return 0;
6490        };
6491        let fb_w: u32 = band.width();
6492        let band_y0: u32 = band.y_offset();
6493        let band_y1: u32 = band.y_end();
6494        let clip_x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6495        let clip_x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6496        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6497        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6498        if clip_x0 >= clip_x1 || y0 >= y1 {
6499            return 0;
6500        }
6501        if aa == AntialiasingMode::None {
6502            let edges: [(Point, Point); 3] = [(p0, p1), (p1, p2), (p2, p0)];
6503            let mut shaded: usize = 0;
6504            for y in y0..y1 {
6505                let py: f32 = (y as f32) + 0.5;
6506                let mut min_ix: f32 = f32::INFINITY;
6507                let mut max_ix: f32 = f32::NEG_INFINITY;
6508                for (a, b) in edges.iter() {
6509                    let ay: f32 = a.get_y();
6510                    let by: f32 = b.get_y();
6511                    if (ay <= py && by > py) || (by <= py && ay > py) {
6512                        let t: f32 = (py - ay) / (by - ay);
6513                        let ix: f32 = a.get_x() + t * (b.get_x() - a.get_x());
6514                        min_ix = min_ix.min(ix);
6515                        max_ix = max_ix.max(ix);
6516                    }
6517                }
6518                if min_ix <= max_ix {
6519                    let sx0: u32 = (min_ix.floor().max(0.0) as u32).clamp(clip_x0, clip_x1);
6520                    let sx1: u32 = (max_ix.ceil().max(0.0) as u32).clamp(clip_x0, clip_x1);
6521                    if sx0 < sx1 {
6522                        band.fill_span_linear(sx0, sx1, y, color);
6523                        shaded += (sx1 - sx0) as usize;
6524                    }
6525                }
6526            }
6527            return shaded;
6528        }
6529        let sign: f32 = if area > 0.0 { 1.0 } else { -1.0 };
6530        let inv_l0: f32 = sign / dx0.hypot(dy0).max(1e-5);
6531        let inv_l1: f32 = sign / dx1.hypot(dy1).max(1e-5);
6532        let inv_l2: f32 = sign / dx2.hypot(dy2).max(1e-5);
6533        let a_step: [f32; 3] = [-dy0 * inv_l0, -dy1 * inv_l1, -dy2 * inv_l2];
6534        let b_step: [f32; 3] = [dx0 * inv_l0, dx1 * inv_l1, dx2 * inv_l2];
6535        let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
6536        let lin_rgb: [f32; 3] = [
6537            SRGB_TO_LIN_LUT[color.get_r() as usize],
6538            SRGB_TO_LIN_LUT[color.get_g() as usize],
6539            SRGB_TO_LIN_LUT[color.get_b() as usize],
6540        ];
6541        let interior_luts: Option<RgbaLutQuad> =
6542            if color.get_a() < 255 && (area.abs() * 0.5) >= 256.0 {
6543                Some(build_linear_blend_luts(color))
6544            } else {
6545                None
6546            };
6547        let px_base: f32 = (clip_x0 as f32) + 0.5;
6548        let max_s: f32 = (clip_x1 - clip_x0) as f32;
6549        let py_start: f32 = (y0 as f32) + 0.5;
6550        let mut d_row: [f32; 3] = [
6551            (dx0 * (py_start - p0.get_y()) - dy0 * (px_base - p0.get_x())) * inv_l0,
6552            (dx1 * (py_start - p1.get_y()) - dy1 * (px_base - p1.get_x())) * inv_l1,
6553            (dx2 * (py_start - p2.get_y()) - dy2 * (px_base - p2.get_x())) * inv_l2,
6554        ];
6555        let edge_deltas: [(f32, f32); 3] = [(dx0, dy0), (dx1, dy1), (dx2, dy2)];
6556        let verts: (Point, Point, Point) = (p0, p1, p2);
6557        let mut shaded: usize = 0;
6558        for y in y0..y1 {
6559            let py: f32 = (y as f32) + 0.5;
6560            let (out_min, out_max): (f32, f32) =
6561                Self::solve_triangle_scanline_interval(d_row, a_step, -0.86, max_s);
6562            if out_min <= out_max {
6563                let k_out0: u32 = out_min.floor().max(0.0) as u32;
6564                let k_out1: u32 = (out_max.ceil().max(0.0) as u32).saturating_add(1);
6565                let row_x0: u32 = clip_x0.saturating_add(k_out0).clamp(clip_x0, clip_x1);
6566                let row_x1: u32 = clip_x0.saturating_add(k_out1).clamp(row_x0, clip_x1);
6567                if row_x0 < row_x1 {
6568                    let (in_min, in_max): (f32, f32) =
6569                        Self::solve_triangle_scanline_interval(d_row, a_step, 0.86, max_s);
6570                    let (in_x0, in_x1): (u32, u32) = if in_min <= in_max && in_max >= 0.0 {
6571                        let k_in0: u32 = in_min.ceil().max(0.0) as u32;
6572                        let k_in1: u32 = (in_max.floor().max(0.0) as u32).saturating_add(1);
6573                        let ix0: u32 = clip_x0.saturating_add(k_in0).clamp(row_x0, row_x1);
6574                        let ix1: u32 = clip_x0.saturating_add(k_in1).clamp(ix0, row_x1);
6575                        (ix0, ix1)
6576                    } else {
6577                        (row_x1, row_x1)
6578                    };
6579                    if in_x0 < in_x1 {
6580                        if let Some(ref luts) = interior_luts {
6581                            band.fill_span_linear_luts(in_x0, in_x1, y, luts);
6582                        } else {
6583                            band.fill_span_linear(in_x0, in_x1, y, color);
6584                        }
6585                        shaded += (in_x1 - in_x0) as usize;
6586                    }
6587                    if (row_x0 < in_x0 || in_x1 < row_x1)
6588                        && let Some(row) = band.row_slice_mut(y)
6589                    {
6590                        let mut rim_spans: [(u32, u32); 2] = [(row_x0, in_x0), (in_x1, row_x1)];
6591                        if in_x0 >= in_x1 {
6592                            rim_spans = [(row_x0, row_x1), (row_x1, row_x1)];
6593                        }
6594                        for (sx0, sx1) in rim_spans.into_iter() {
6595                            if sx0 >= sx1 {
6596                                continue;
6597                            }
6598                            let s0: f32 = (sx0 - clip_x0) as f32;
6599                            let mut d0: f32 = d_row[0] + a_step[0] * s0;
6600                            let mut d1: f32 = d_row[1] + a_step[1] * s0;
6601                            let mut d2: f32 = d_row[2] + a_step[2] * s0;
6602                            for x in sx0..sx1 {
6603                                if d0 >= -0.85 && d1 >= -0.85 && d2 >= -0.85 {
6604                                    if d0 > 0.85 && d1 > 0.85 && d2 > 0.85 {
6605                                        blend_row_pixel_linear_precomputed(row, x, color, lin_rgb);
6606                                        shaded += 1;
6607                                    } else {
6608                                        let px: f32 = (x as f32) + 0.5;
6609                                        let cov: f32 = triangle_supersampled_coverage_precomputed(
6610                                            (px, py),
6611                                            verts,
6612                                            edge_deltas,
6613                                            sign,
6614                                        );
6615                                        if cov >= 0.999 {
6616                                            blend_row_pixel_linear_precomputed(
6617                                                row, x, color, lin_rgb,
6618                                            );
6619                                            shaded += 1;
6620                                        } else if cov > 0.0 {
6621                                            blend_row_pixel_f32_precomputed(
6622                                                row,
6623                                                x,
6624                                                color,
6625                                                lin_rgb,
6626                                                base_alpha * cov,
6627                                            );
6628                                            shaded += 1;
6629                                        }
6630                                    }
6631                                }
6632                                d0 += a_step[0];
6633                                d1 += a_step[1];
6634                                d2 += a_step[2];
6635                            }
6636                        }
6637                    }
6638                }
6639            }
6640            d_row[0] += b_step[0];
6641            d_row[1] += b_step[1];
6642            d_row[2] += b_step[2];
6643        }
6644        shaded
6645    }
6646
6647    /// Blits a bilinearly filtered sprite scanline with multiplicative `tint` using precomputed 8.8 LUTs.
6648    ///
6649    /// # Arguments
6650    ///
6651    /// - `(usize, usize, u32, u32)` - Vertical row parameters `(row0_px, row1_px, wy_256, iwy_256)`.
6652    /// - `usize` - Starting destination X pixel coordinate within `dst_row`.
6653    /// - `&[(usize, usize, u32)]` - Horizontal sample LUT slice `(sx0, sx1, wx_256)`.
6654    /// - `&[u8]` - Source RGBA8 sprite sheet buffer.
6655    /// - `&mut [u8]` - Destination framebuffer row slice.
6656    /// - `Color` - Multiplicative tint RGBA color.
6657    ///
6658    /// # Returns
6659    ///
6660    /// - `usize` - Number of non-transparent sprite pixels shaded.
6661    #[inline(always)]
6662    fn blit_sprite_span_tinted(
6663        y_params: (usize, usize, u32, u32),
6664        dst_x0: usize,
6665        x_lut: &[(usize, usize, u32)],
6666        src_bytes: &[u8],
6667        dst_row: &mut [u8],
6668        tint: Color,
6669    ) -> usize {
6670        let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
6671        let span_bytes_start: usize = dst_x0 * 4;
6672        let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
6673        if span_bytes_end > dst_row.len() {
6674            return 0;
6675        }
6676        let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
6677            .as_chunks_mut::<4>()
6678            .0;
6679        let src_len: usize = src_bytes.len();
6680        let tr: u32 = tint.get_r() as u32;
6681        let tg: u32 = tint.get_g() as u32;
6682        let tb: u32 = tint.get_b() as u32;
6683        let ta: u32 = tint.get_a() as u32;
6684        let mut shaded: usize = 0;
6685        if wy == 0 {
6686            for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
6687                let i0: usize = (row0 + sx0) * 4;
6688                let i1: usize = (row0 + sx1) * 4;
6689                if i1 + 4 > src_len {
6690                    continue;
6691                }
6692                let iwx: u32 = 256 - wx;
6693                let sa_raw: u32 =
6694                    ((src_bytes[i0 + 3] as u32) * iwx + (src_bytes[i1 + 3] as u32) * wx + 128) >> 8;
6695                if sa_raw == 0 {
6696                    continue;
6697                }
6698                let sr_raw: u32 =
6699                    ((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128) >> 8;
6700                let sg_raw: u32 =
6701                    ((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128) >> 8;
6702                let sb_raw: u32 =
6703                    ((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128) >> 8;
6704                let rr: u32 = sr_raw * tr + 128;
6705                let gg: u32 = sg_raw * tg + 128;
6706                let bb: u32 = sb_raw * tb + 128;
6707                let aa_v: u32 = sa_raw * ta + 128;
6708                let r: u32 = (rr + (rr >> 8)) >> 8;
6709                let g: u32 = (gg + (gg >> 8)) >> 8;
6710                let b: u32 = (bb + (bb >> 8)) >> 8;
6711                let a: u32 = (aa_v + (aa_v >> 8)) >> 8;
6712                if a == 255 {
6713                    dp[0] = r as u8;
6714                    dp[1] = g as u8;
6715                    dp[2] = b as u8;
6716                    dp[3] = 255;
6717                } else if a > 0 {
6718                    let inv_a: u32 = 255 - a;
6719                    let vr: u32 = r * a + (dp[0] as u32) * inv_a + 128;
6720                    let vg: u32 = g * a + (dp[1] as u32) * inv_a + 128;
6721                    let vb: u32 = b * a + (dp[2] as u32) * inv_a + 128;
6722                    let va: u32 = (dp[3] as u32) * inv_a + 128;
6723                    dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
6724                    dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
6725                    dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
6726                    dp[3] = (a + ((va + (va >> 8)) >> 8)).min(255) as u8;
6727                }
6728                shaded += 1;
6729            }
6730            return shaded;
6731        }
6732        for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
6733            let i00: usize = (row0 + sx0) * 4;
6734            let i10: usize = (row0 + sx1) * 4;
6735            let i01: usize = (row1 + sx0) * 4;
6736            let i11: usize = (row1 + sx1) * 4;
6737            if i11 + 4 > src_len {
6738                continue;
6739            }
6740            let iwx: u32 = 256 - wx;
6741            let w00: u32 = iwx * iwy;
6742            let w10: u32 = wx * iwy;
6743            let w01: u32 = iwx * wy;
6744            let w11: u32 = wx * wy;
6745            let sa_raw: u32 = ((src_bytes[i00 + 3] as u32) * w00
6746                + (src_bytes[i10 + 3] as u32) * w10
6747                + (src_bytes[i01 + 3] as u32) * w01
6748                + (src_bytes[i11 + 3] as u32) * w11
6749                + 32768)
6750                >> 16;
6751            if sa_raw == 0 {
6752                continue;
6753            }
6754            let sr_raw: u32 = ((src_bytes[i00] as u32) * w00
6755                + (src_bytes[i10] as u32) * w10
6756                + (src_bytes[i01] as u32) * w01
6757                + (src_bytes[i11] as u32) * w11
6758                + 32768)
6759                >> 16;
6760            let sg_raw: u32 = ((src_bytes[i00 + 1] as u32) * w00
6761                + (src_bytes[i10 + 1] as u32) * w10
6762                + (src_bytes[i01 + 1] as u32) * w01
6763                + (src_bytes[i11 + 1] as u32) * w11
6764                + 32768)
6765                >> 16;
6766            let sb_raw: u32 = ((src_bytes[i00 + 2] as u32) * w00
6767                + (src_bytes[i10 + 2] as u32) * w10
6768                + (src_bytes[i01 + 2] as u32) * w01
6769                + (src_bytes[i11 + 2] as u32) * w11
6770                + 32768)
6771                >> 16;
6772            let rr: u32 = sr_raw * tr + 128;
6773            let gg: u32 = sg_raw * tg + 128;
6774            let bb: u32 = sb_raw * tb + 128;
6775            let aa_v: u32 = sa_raw * ta + 128;
6776            let r: u32 = (rr + (rr >> 8)) >> 8;
6777            let g: u32 = (gg + (gg >> 8)) >> 8;
6778            let b: u32 = (bb + (bb >> 8)) >> 8;
6779            let a: u32 = (aa_v + (aa_v >> 8)) >> 8;
6780            if a == 255 {
6781                dp[0] = r as u8;
6782                dp[1] = g as u8;
6783                dp[2] = b as u8;
6784                dp[3] = 255;
6785            } else if a > 0 {
6786                let inv_a: u32 = 255 - a;
6787                let vr: u32 = r * a + (dp[0] as u32) * inv_a + 128;
6788                let vg: u32 = g * a + (dp[1] as u32) * inv_a + 128;
6789                let vb: u32 = b * a + (dp[2] as u32) * inv_a + 128;
6790                let va: u32 = (dp[3] as u32) * inv_a + 128;
6791                dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
6792                dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
6793                dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
6794                dp[3] = (a + ((va + (va >> 8)) >> 8)).min(255) as u8;
6795            }
6796            shaded += 1;
6797        }
6798        shaded
6799    }
6800
6801    /// Executes `raster_sprite_region` using reusable horizontal fixed-point sample buffer `x_lut`.
6802    ///
6803    /// # Arguments
6804    ///
6805    /// - `&mut PixelBand<'_>` - Target pixel band.
6806    /// - `(Rect, Rect)` - Tuple `(dst_rect, src_rect)` in physical/source pixels.
6807    /// - `(u32, u32, &[u8])` - Source sprite sheet `(buf_w, buf_h, src_bytes)`.
6808    /// - `(u32, u32, u32, u32)` - Clipped visible bounds `(x0, y0, x1, y1)`.
6809    /// - `Color` - Multiplicative tint color.
6810    /// - `bool` - Whether bilinear filtering is active.
6811    /// - `&mut Vec<(usize, usize, u32)>` - Reusable horizontal LUT scratch buffer.
6812    ///
6813    /// # Returns
6814    ///
6815    /// - `usize` - Number of shaded sprite pixels.
6816    fn raster_sprite_region_with_lut(
6817        band: &mut PixelBand<'_>,
6818        rects: (Rect, Rect),
6819        src_info: (u32, u32, &[u8]),
6820        bounds: (u32, u32, u32, u32),
6821        tint: Color,
6822        use_bilinear: bool,
6823        x_lut: &mut Vec<(usize, usize, u32)>,
6824    ) -> usize {
6825        let (rect, src_rect): (Rect, Rect) = rects;
6826        let (buf_w, buf_h, src_bytes): (u32, u32, &[u8]) = src_info;
6827        let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
6828        let inv_w: f32 = 1.0 / rect.get_width().max(1.0);
6829        let inv_h: f32 = 1.0 / rect.get_height().max(1.0);
6830        let untinted: bool = tint == COLOR_WHITE;
6831        let max_sx: u32 = ((src_rect.right().ceil() as u32).saturating_sub(1)).min(buf_w - 1);
6832        let max_sy: u32 = ((src_rect.bottom().ceil() as u32).saturating_sub(1)).min(buf_h - 1);
6833        let min_sx: u32 = (src_rect.get_x().floor().max(0.0) as u32).min(max_sx);
6834        let min_sy: u32 = (src_rect.get_y().floor().max(0.0) as u32).min(max_sy);
6835        let buf_w_usize: usize = buf_w as usize;
6836        let rect_x: f32 = rect.get_x();
6837        let rect_y: f32 = rect.get_y();
6838        let src_x: f32 = src_rect.get_x();
6839        let src_y: f32 = src_rect.get_y();
6840        let src_w: f32 = src_rect.get_width();
6841        let src_h: f32 = src_rect.get_height();
6842        let min_sx_f: f32 = min_sx as f32;
6843        let max_sx_f: f32 = max_sx as f32;
6844        let min_sy_f: f32 = min_sy as f32;
6845        let max_sy_f: f32 = max_sy as f32;
6846        x_lut.clear();
6847        for x in x0..x1 {
6848            let u: f32 = (((x as f32) + 0.5 - rect_x) * inv_w).clamp(0.0, 1.0);
6849            let fx: f32 = (src_x + u * src_w - 0.5).clamp(min_sx_f, max_sx_f);
6850            let sx0: u32 = (fx.floor() as u32).clamp(min_sx, max_sx);
6851            let sx1: u32 = if use_bilinear {
6852                (sx0 + 1).min(max_sx)
6853            } else {
6854                sx0
6855            };
6856            let wx: u32 = if use_bilinear {
6857                ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
6858            } else {
6859                0
6860            };
6861            x_lut.push((sx0 as usize, sx1 as usize, wx));
6862        }
6863        let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
6864        let x0_u: usize = x0 as usize;
6865        let mut shaded: usize = 0;
6866        for y in y0..y1 {
6867            let Some(dst_row) = band.row_slice_mut(y) else {
6868                continue;
6869            };
6870            let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_h).clamp(0.0, 1.0);
6871            let fy: f32 = (src_y + v * src_h - 0.5).clamp(min_sy_f, max_sy_f);
6872            let sy0: u32 = (fy.floor() as u32).clamp(min_sy, max_sy);
6873            let sy1: u32 = if use_bilinear {
6874                (sy0 + 1).min(max_sy)
6875            } else {
6876                sy0
6877            };
6878            let wy: u32 = if use_bilinear {
6879                ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
6880            } else {
6881                0
6882            };
6883            let y_params: (usize, usize, u32, u32) = (
6884                (sy0 as usize) * buf_w_usize,
6885                (sy1 as usize) * buf_w_usize,
6886                wy,
6887                256 - wy,
6888            );
6889            if untinted {
6890                shaded += Self::blit_bilinear_span_precomputed(
6891                    y_params, x0_u, x_lut_ref, src_bytes, dst_row,
6892                );
6893            } else {
6894                shaded += Self::blit_sprite_span_tinted(
6895                    y_params, x0_u, x_lut_ref, src_bytes, dst_row, tint,
6896                );
6897            }
6898        }
6899        shaded
6900    }
6901
6902    /// Blits a cropped sub-rectangle of an `ImageBuffer` sprite sheet into `band` with fixed-point `x_lut` filtering and optional tint.
6903    ///
6904    /// # Arguments
6905    ///
6906    /// - `&mut PixelBand<'_>` - Target pixel band.
6907    /// - `Rect` - Physical destination bounds.
6908    /// - `&ImageBuffer` - Source sprite-sheet RGBA8 buffer.
6909    /// - `Rect` - Source pixel sub-rectangle.
6910    /// - `Color` - Multiplicative tint color.
6911    /// - `Rect` - Active clip bounds.
6912    /// - `AntialiasingMode` - Active AA policy.
6913    ///
6914    /// # Returns
6915    ///
6916    /// - `usize` - Shaded pixel count.
6917    fn raster_sprite_region(
6918        band: &mut PixelBand<'_>,
6919        rect: Rect,
6920        buffer: &ImageBuffer,
6921        src_rect: Rect,
6922        tint: Color,
6923        clip: Rect,
6924        aa: AntialiasingMode,
6925    ) -> usize {
6926        if buffer.get_width() == 0
6927            || buffer.get_height() == 0
6928            || tint.get_a() == 0
6929            || src_rect.get_width() <= 0.0
6930            || src_rect.get_height() <= 0.0
6931        {
6932            return 0;
6933        }
6934        let Some(vis) = rect.intersect(clip) else {
6935            return 0;
6936        };
6937        let fb_w: u32 = band.width();
6938        let band_y0: u32 = band.y_offset();
6939        let band_y1: u32 = band.y_end();
6940        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6941        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6942        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6943        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6944        if x0 >= x1 || y0 >= y1 {
6945            return 0;
6946        }
6947        let buf_w: u32 = buffer.get_width();
6948        let buf_h: u32 = buffer.get_height();
6949        let src_bytes: &[u8] = buffer.get_pixels().as_slice();
6950        let use_bilinear: bool = aa != AntialiasingMode::None
6951            && ((rect.get_width() - src_rect.get_width()).abs() > 0.5
6952                || (rect.get_height() - src_rect.get_height()).abs() > 0.5);
6953        if !use_bilinear
6954            && tint == COLOR_WHITE
6955            && (rect.get_width() - src_rect.get_width()).abs() <= 0.01
6956            && (rect.get_height() - src_rect.get_height()).abs() <= 0.01
6957            && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
6958            && (rect.get_y() - rect.get_y().round()).abs() <= 0.01
6959            && (src_rect.get_x() - src_rect.get_x().round()).abs() <= 0.01
6960            && (src_rect.get_y() - src_rect.get_y().round()).abs() <= 0.01
6961        {
6962            let rx0_i: i32 = rect.get_x().round() as i32;
6963            let ry0_i: i32 = rect.get_y().round() as i32;
6964            let sx0_i: i32 = src_rect.get_x().round() as i32;
6965            let sy0_i: i32 = src_rect.get_y().round() as i32;
6966            let span_w: usize = (x1 - x0) as usize;
6967            let src_x0_i: i32 = sx0_i + ((x0 as i32) - rx0_i);
6968            let src_y0_i: i32 = sy0_i + ((y0 as i32) - ry0_i);
6969            let src_y1_i: i32 = sy0_i + ((y1 as i32) - ry0_i);
6970            if src_x0_i >= 0
6971                && src_x0_i + (span_w as i32) <= (buf_w as i32)
6972                && src_y0_i >= 0
6973                && src_y1_i <= (buf_h as i32)
6974            {
6975                let buf_w_u: usize = buf_w as usize;
6976                let dst_b0: usize = (x0 as usize) * 4;
6977                let dst_b1: usize = (x1 as usize) * 4;
6978                let src_x0_u: usize = src_x0_i as usize;
6979                for y in y0..y1 {
6980                    let Some(dst_row) = band.row_slice_mut(y) else {
6981                        continue;
6982                    };
6983                    let sy: usize = (sy0_i + ((y as i32) - ry0_i)) as usize;
6984                    let src_b0: usize = (sy * buf_w_u + src_x0_u) * 4;
6985                    let src_b1: usize = src_b0 + span_w * 4;
6986                    if src_b1 <= src_bytes.len() && dst_b1 <= dst_row.len() {
6987                        blit_1to1_rgba_span(
6988                            &src_bytes[src_b0..src_b1],
6989                            &mut dst_row[dst_b0..dst_b1],
6990                        );
6991                    }
6992                }
6993                return span_w * ((y1 - y0) as usize);
6994            }
6995        }
6996        let mut shaded: usize = 0;
6997        let ran_tls: bool = BAND_IMAGE_X_LUT
6998            .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
6999                if let Ok(mut guard) = cell.try_borrow_mut() {
7000                    shaded = Self::raster_sprite_region_with_lut(
7001                        band,
7002                        (rect, src_rect),
7003                        (buf_w, buf_h, src_bytes),
7004                        (x0, y0, x1, y1),
7005                        tint,
7006                        use_bilinear,
7007                        &mut guard,
7008                    );
7009                }
7010            })
7011            .is_ok();
7012        if !ran_tls {
7013            let mut fallback_lut: Vec<(usize, usize, u32)> = Vec::with_capacity((x1 - x0) as usize);
7014            shaded = Self::raster_sprite_region_with_lut(
7015                band,
7016                (rect, src_rect),
7017                (buf_w, buf_h, src_bytes),
7018                (x0, y0, x1, y1),
7019                tint,
7020                use_bilinear,
7021                &mut fallback_lut,
7022            );
7023        }
7024        shaded
7025    }
7026}