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..=8` 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, 8);
18        let worker_count: usize = total.saturating_sub(1);
19        let shared: Arc<(Mutex<BandPoolState>, Condvar, Condvar)> = Arc::new((
20            Mutex::new(BandPoolState::default()),
21            Condvar::new(),
22            Condvar::new(),
23        ));
24        for idx in 0..worker_count {
25            let shared_clone: Arc<(Mutex<BandPoolState>, Condvar, Condvar)> = Arc::clone(&shared);
26            let name: String = format!("{BAND_WORKER_THREAD_PREFIX}-{idx}");
27            let _: io::Result<JoinHandle<()>> = Builder::new().name(name).spawn(move || {
28                let mut seen_epoch: u64 = 0;
29                loop {
30                    let job_ptr: usize = {
31                        let (lock, wake_workers, _wake_caller): &(
32                            Mutex<BandPoolState>,
33                            Condvar,
34                            Condvar,
35                        ) = &shared_clone;
36                        let Ok(mut state) = lock.lock() else {
37                            break;
38                        };
39                        while state.get_epoch() == seen_epoch || state.get_active_job() == 0 {
40                            let Ok(next_guard) = wake_workers.wait(state) else {
41                                return;
42                            };
43                            state = next_guard;
44                        }
45                        seen_epoch = state.get_epoch();
46                        state.get_active_job()
47                    };
48                    let job: &BandJob = unsafe { &*(job_ptr as *const BandJob) };
49                    run_band_job_loop(job);
50                    let finished: usize = job.workers_done.fetch_add(1, Ordering::AcqRel) + 1;
51                    if finished >= worker_count {
52                        let (lock, _wake_workers, wake_caller): &(
53                            Mutex<BandPoolState>,
54                            Condvar,
55                            Condvar,
56                        ) = &shared_clone;
57                        let _guard: Result<
58                            MutexGuard<'_, BandPoolState>,
59                            PoisonError<MutexGuard<'_, BandPoolState>>,
60                        > = lock.lock();
61                        wake_caller.notify_one();
62                    }
63                }
64            });
65        }
66        Self {
67            worker_count,
68            dispatch_lock: Mutex::new(()),
69            shared,
70        }
71    }
72
73    /// Executes bands serially on the calling thread with optional cached backdrop restore.
74    ///
75    /// # Arguments
76    ///
77    /// - `&mut [PixelBand<'_>]` - Disjoint horizontal framebuffer strips.
78    /// - `&[DrawCommand]` - Display list commands.
79    /// - `&[PreppedCommand]` - Pre-clipped command table.
80    /// - `&[TextLayoutResult]` - Pre-measured text layouts.
81    /// - `&GlyphAtlas` - Shared read-only glyph atlas.
82    /// - `(f32, AntialiasingMode)` - Tuple of `(scale, antialiasing)`.
83    /// - `Option<&[u8]>` - Optional cached base-scene RGBA8 pixel slice.
84    ///
85    /// # Returns
86    ///
87    /// - `usize` - Total shaded pixel count across all strips.
88    fn execute_serial(
89        bands: &mut [PixelBand<'_>],
90        commands: &[DrawCommand],
91        prepped: &[PreppedCommand],
92        layouts: &[TextLayoutResult],
93        atlas: &GlyphAtlas,
94        render_opts: (f32, AntialiasingMode),
95        base_restore: Option<&[u8]>,
96    ) -> usize {
97        let (scale, aa): (f32, AntialiasingMode) = render_opts;
98        let mut total: usize = 0;
99        for band in bands.iter_mut() {
100            if let Some(src_buf) = base_restore {
101                let byte_off: usize = (band.y_offset as usize) * (band.width as usize) * 4;
102                let byte_end: usize = byte_off + band.pixels.len();
103                if let Some(src_slice) = src_buf.get(byte_off..byte_end) {
104                    band.pixels.copy_from_slice(src_slice);
105                }
106            }
107            total +=
108                SoftwareRenderer::render_band(band, commands, prepped, layouts, atlas, scale, aa);
109        }
110        total
111    }
112
113    /// Returns total participating rasterizer threads (background workers plus the calling main thread).
114    ///
115    /// # Returns
116    ///
117    /// - `usize` - Total active thread count in `1..=6`.
118    #[must_use]
119    pub(crate) fn total_threads(&self) -> usize {
120        let Self { worker_count, .. } = self;
121        worker_count.saturating_add(1)
122    }
123
124    /// Dispatches horizontal pixel bands across the persistent worker pool with optional parallel backdrop restore and synchronous completion.
125    ///
126    /// # Arguments
127    ///
128    /// - `&Self` - Worker pool reference.
129    /// - `&mut [PixelBand<'_>]` - Disjoint horizontal framebuffer strips.
130    /// - `&[DrawCommand]` - Display list commands.
131    /// - `&[PreppedCommand]` - Pre-clipped command table.
132    /// - `&[TextLayoutResult]` - Pre-measured text layouts.
133    /// - `&GlyphAtlas` - Shared read-only glyph atlas.
134    /// - `(f32, AntialiasingMode, Option<&[u8]>)` - Tuple of `(scale, antialiasing, optional_base_restore)`.
135    ///
136    /// # Returns
137    ///
138    /// - `usize` - Total shaded pixel count across all strips.
139    pub(crate) fn execute(
140        &self,
141        bands: &mut [PixelBand<'_>],
142        commands: &[DrawCommand],
143        prepped: &[PreppedCommand],
144        layouts: &[TextLayoutResult],
145        atlas: &GlyphAtlas,
146        render_opts: (f32, AntialiasingMode, Option<&[u8]>),
147    ) -> usize {
148        let Self {
149            worker_count,
150            dispatch_lock,
151            shared,
152        } = self;
153        let (scale, aa, base_restore): (f32, AntialiasingMode, Option<&[u8]>) = render_opts;
154        if *worker_count == 0 || bands.len() <= 1 {
155            return Self::execute_serial(
156                bands,
157                commands,
158                prepped,
159                layouts,
160                atlas,
161                (scale, aa),
162                base_restore,
163            );
164        }
165        let Ok(_dispatch_guard) = dispatch_lock.try_lock() else {
166            return Self::execute_serial(
167                bands,
168                commands,
169                prepped,
170                layouts,
171                atlas,
172                (scale, aa),
173                base_restore,
174            );
175        };
176        let mut tasks: Vec<BandTaskSlice> = Vec::with_capacity(bands.len());
177        for band in bands.iter_mut() {
178            let base_ptr: usize = if let Some(src_buf) = base_restore {
179                let byte_off: usize = (band.y_offset as usize) * (band.width as usize) * 4;
180                let byte_end: usize = byte_off + band.pixels.len();
181                if byte_end <= src_buf.len() {
182                    unsafe { src_buf.as_ptr().add(byte_off) as usize }
183                } else {
184                    0
185                }
186            } else {
187                0
188            };
189            tasks.push(BandTaskSlice {
190                pixels_ptr: band.pixels.as_mut_ptr() as usize,
191                pixels_len: band.pixels.len(),
192                width: band.width,
193                y_start: band.y_offset,
194                height: band.height,
195                base_src_ptr: base_ptr,
196            });
197        }
198        let job: BandJob = BandJob {
199            tasks_ptr: tasks.as_ptr() as usize,
200            tasks_len: tasks.len(),
201            commands_ptr: commands.as_ptr() as usize,
202            commands_len: commands.len(),
203            prepped_ptr: prepped.as_ptr() as usize,
204            prepped_len: prepped.len(),
205            layouts_ptr: layouts.as_ptr() as usize,
206            layouts_len: layouts.len(),
207            atlas_ptr: (atlas as *const GlyphAtlas) as usize,
208            scale,
209            aa,
210            next_idx: AtomicUsize::new(0),
211            workers_done: AtomicUsize::new(0),
212            total_shaded: AtomicUsize::new(0),
213        };
214        let (lock, wake_workers, wake_caller): &(Mutex<BandPoolState>, Condvar, Condvar) = shared;
215        {
216            if let Ok(mut state) = lock.lock() {
217                let next_epoch: u64 = state.get_epoch().wrapping_add(1);
218                state.set_active_job((&job as *const BandJob) as usize);
219                state.set_epoch(next_epoch);
220                wake_workers.notify_all();
221            } else {
222                run_band_job_loop(&job);
223                return job.total_shaded.load(Ordering::Acquire);
224            }
225        }
226        run_band_job_loop(&job);
227        let mut wait_guard: Option<MutexGuard<'_, BandPoolState>> = lock.lock().ok();
228        while let Some(state) = wait_guard.take() {
229            if job.workers_done.load(Ordering::Acquire) >= *worker_count {
230                let mut done_state: MutexGuard<'_, BandPoolState> = state;
231                done_state.set_active_job(0);
232                break;
233            }
234            wait_guard = wake_caller.wait(state).ok();
235        }
236        job.total_shaded.load(Ordering::Acquire)
237    }
238}
239
240/// Multi-core lossless analytical-SDF and tile-band software rasterizer methods for `SoftwareRenderer`.
241impl SoftwareRenderer {
242    /// Creates a software renderer configured for `width x height` physical pixels.
243    ///
244    /// # Arguments
245    ///
246    /// - `u32` - Physical width.
247    /// - `u32` - Physical height.
248    /// - `RenderConfig` - Rendering configuration.
249    ///
250    /// # Returns
251    ///
252    /// - `Self` - Ready-to-draw software renderer.
253    #[must_use]
254    pub fn with_config(width: u32, height: u32, config: RenderConfig) -> Self {
255        Self::with_font_provider(width, height, config, NativeSystemFont::deterministic())
256    }
257
258    /// Creates a software renderer configured with an explicit `NativeSystemFont` provider.
259    ///
260    /// # Arguments
261    ///
262    /// - `u32` - Physical width.
263    /// - `u32` - Physical height.
264    /// - `RenderConfig` - Rendering configuration.
265    /// - `NativeSystemFont` - Native OS or deterministic font provider.
266    ///
267    /// # Returns
268    ///
269    /// - `Self` - Ready-to-draw software renderer.
270    #[must_use]
271    pub fn with_font_provider(
272        width: u32,
273        height: u32,
274        config: RenderConfig,
275        font_provider: NativeSystemFont,
276    ) -> Self {
277        Self {
278            framebuffer: Framebuffer::allocate(width, height),
279            glyph_atlas: GlyphAtlas::default(),
280            font_provider,
281            measurer: DeterministicTextMeasurer,
282            text_layout_cache: HashMap::with_capacity(128),
283            clip_stack: Vec::with_capacity(8),
284            antialiasing: config.get_antialiasing(),
285            tile_size: config.get_tile_size().max(16),
286            base_cache_width: 0,
287            base_cache_height: 0,
288            base_cache_hash: 0,
289            base_cache_pixels: Vec::new(),
290        }
291    }
292
293    /// Rasterizes `display_list` into the internal `Framebuffer` clipped to `damage` using multi-core parallel horizontal bands and lossless portal backdrop caching.
294    ///
295    /// # Arguments
296    ///
297    /// - `&Self` - Mutable software renderer.
298    /// - `&DisplayList` - Backend-agnostic draw command stream.
299    /// - `DamageRegion` - Optional dirty damage region for partial rasterization.
300    ///
301    /// # Returns
302    ///
303    /// - `(usize, usize)` - Tuple of `(tiles_updated, pixels_shaded)`.
304    pub fn render(&mut self, display_list: &DisplayList, damage: DamageRegion) -> (usize, usize) {
305        let scale: f32 = display_list.get_scale_factor().max(0.5);
306        let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
307        let phys_h: u32 =
308            ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
309        let resized: bool = self.get_mut_framebuffer().resize(phys_w, phys_h);
310        if resized {
311            self.set_base_cache_hash(0);
312            self.set_base_cache_width(0);
313            self.set_base_cache_height(0);
314        }
315        let effective_damage: DamageRegion = if resized {
316            DamageRegion::full()
317        } else {
318            damage
319        };
320        let Some(root_clip) = effective_damage.resolve(phys_w, phys_h) else {
321            return (0, 0);
322        };
323        let tile_sz: u32 = self.get_tile_size().max(16);
324        let tiles_x: usize = ((root_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
325        let tiles_y: usize = ((root_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
326        let tiles_updated: usize = tiles_x.saturating_mul(tiles_y);
327        let commands: &[DrawCommand] = display_list.get_commands().as_slice();
328        let split: usize = display_list.get_portal_split_index().min(commands.len());
329        let has_portals: bool = split > 0 && split < commands.len();
330        let is_full_frame: bool = root_clip.get_x() <= 0.0
331            && root_clip.get_y() <= 0.0
332            && root_clip.get_width() >= (phys_w as f32)
333            && root_clip.get_height() >= (phys_h as f32);
334        if has_portals && is_full_frame {
335            let base_hash: u64 = display_list.base_layer_hash();
336            let fb_len: usize = self.get_framebuffer().get_pixels().len();
337            let cache_hit: bool = base_hash != 0
338                && self.get_base_cache_hash() == base_hash
339                && self.get_base_cache_width() == phys_w
340                && self.get_base_cache_height() == phys_h
341                && self.get_base_cache_pixels().len() == fb_len;
342            if cache_hit {
343                let (prepped, text_layouts): (Vec<PreppedCommand>, Vec<TextLayoutResult>) = self
344                    .prepare_frame_range(
345                        display_list,
346                        split,
347                        commands.len(),
348                        root_clip,
349                        scale,
350                        phys_h,
351                    );
352                let pixels_shaded: usize = self.execute_prepared_bands(
353                    commands,
354                    prepped.as_slice(),
355                    text_layouts.as_slice(),
356                    root_clip,
357                    (phys_w, phys_h, scale),
358                    true,
359                );
360                return (tiles_updated, pixels_shaded.max(1));
361            }
362            let (base_prepped, base_layouts): (Vec<PreppedCommand>, Vec<TextLayoutResult>) =
363                self.prepare_frame_range(display_list, 0, split, root_clip, scale, phys_h);
364            let base_shaded: usize = self.execute_prepared_bands(
365                commands,
366                base_prepped.as_slice(),
367                base_layouts.as_slice(),
368                root_clip,
369                (phys_w, phys_h, scale),
370                false,
371            );
372            {
373                let Self {
374                    framebuffer,
375                    base_cache_pixels,
376                    base_cache_width,
377                    base_cache_height,
378                    base_cache_hash,
379                    ..
380                } = self;
381                let src_pixels: &[u8] = framebuffer.get_pixels().as_slice();
382                if base_cache_pixels.len() != src_pixels.len() {
383                    base_cache_pixels.resize(src_pixels.len(), 0);
384                }
385                base_cache_pixels.copy_from_slice(src_pixels);
386                *base_cache_width = phys_w;
387                *base_cache_height = phys_h;
388                *base_cache_hash = base_hash;
389            }
390            let (portal_prepped, portal_layouts): (Vec<PreppedCommand>, Vec<TextLayoutResult>) =
391                self.prepare_frame_range(
392                    display_list,
393                    split,
394                    commands.len(),
395                    root_clip,
396                    scale,
397                    phys_h,
398                );
399            let portal_shaded: usize = self.execute_prepared_bands(
400                commands,
401                portal_prepped.as_slice(),
402                portal_layouts.as_slice(),
403                root_clip,
404                (phys_w, phys_h, scale),
405                false,
406            );
407            return (tiles_updated, base_shaded.saturating_add(portal_shaded));
408        }
409        if !has_portals {
410            self.set_base_cache_hash(0);
411        }
412        let (prepped, text_layouts): (Vec<PreppedCommand>, Vec<TextLayoutResult>) =
413            self.prepare_frame_range(display_list, 0, commands.len(), root_clip, scale, phys_h);
414        let pixels_shaded: usize = self.execute_prepared_bands(
415            commands,
416            prepped.as_slice(),
417            text_layouts.as_slice(),
418            root_clip,
419            (phys_w, phys_h, scale),
420            false,
421        );
422        (tiles_updated, pixels_shaded)
423    }
424
425    /// Executes prepped commands across horizontal bands with optional parallel restore from `base_cache_pixels`.
426    ///
427    /// # Arguments
428    ///
429    /// - `&Self` - Mutable software renderer.
430    /// - `&[DrawCommand]` - Full frame draw command slice.
431    /// - `&[PreppedCommand]` - Pre-clipped command slice.
432    /// - `&[TextLayoutResult]` - Pre-measured text layouts.
433    /// - `Rect` - Root physical damage clip rectangle.
434    /// - `(u32, u32, f32)` - Tuple `(phys_w, phys_h, scale)`.
435    /// - `bool` - Whether to restore `base_cache_pixels` into each strip before rasterizing.
436    ///
437    /// # Returns
438    ///
439    /// - `usize` - Total shaded pixel count.
440    fn execute_prepared_bands(
441        &mut self,
442        commands: &[DrawCommand],
443        prepped_slice: &[PreppedCommand],
444        layouts_slice: &[TextLayoutResult],
445        root_clip: Rect,
446        dims: (u32, u32, f32),
447        restore_base_cache: bool,
448    ) -> usize {
449        let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
450        let aa: AntialiasingMode = self.get_antialiasing();
451        let clip_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
452        let clip_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
453        let clip_w: u32 = (root_clip.get_width().ceil().max(0.0) as u32).min(phys_w);
454        let clip_h: u32 = clip_y1.saturating_sub(clip_y0);
455        let Self {
456            framebuffer,
457            glyph_atlas,
458            base_cache_pixels,
459            ..
460        } = self;
461        let atlas_ref: &GlyphAtlas = glyph_atlas;
462        let base_restore: Option<&[u8]> = if restore_base_cache {
463            Some(base_cache_pixels.as_slice())
464        } else {
465            None
466        };
467        #[cfg(not(target_arch = "wasm32"))]
468        {
469            if (clip_w as usize).saturating_mul(clip_h as usize) >= 65_536 && clip_h >= 64 {
470                let pool: &BandWorkerPool = global_band_worker_pool();
471                let strip_count: usize = (pool.total_threads().saturating_mul(2))
472                    .min((clip_h / 24) as usize)
473                    .max(1);
474                if strip_count > 1 && pool.total_threads() > 1 {
475                    let mut bands: Vec<PixelBand<'_>> =
476                        framebuffer.split_bands_mut(clip_y0, clip_y1, strip_count);
477                    return pool.execute(
478                        bands.as_mut_slice(),
479                        commands,
480                        prepped_slice,
481                        layouts_slice,
482                        atlas_ref,
483                        (scale, aa, base_restore),
484                    );
485                }
486            }
487            if let Some(src_buf) = base_restore
488                && src_buf.len() == framebuffer.get_pixels().len()
489            {
490                framebuffer.get_mut_pixels().copy_from_slice(src_buf);
491            }
492            let mut band: PixelBand<'_> = framebuffer.as_band_mut();
493            Self::render_band(
494                &mut band,
495                commands,
496                prepped_slice,
497                layouts_slice,
498                atlas_ref,
499                scale,
500                aa,
501            )
502        }
503        #[cfg(target_arch = "wasm32")]
504        {
505            let _: (u32, u32) = (clip_w, clip_h);
506            if let Some(src_buf) = base_restore
507                && src_buf.len() == framebuffer.get_pixels().len()
508            {
509                framebuffer.get_mut_pixels().copy_from_slice(src_buf);
510            }
511            let mut band: PixelBand<'_> = framebuffer.as_band_mut();
512            Self::render_band(
513                &mut band,
514                commands,
515                prepped_slice,
516                layouts_slice,
517                atlas_ref,
518                scale,
519                aa,
520            )
521        }
522    }
523
524    /// Runs a lightweight main-thread pre-pass over `commands[start_idx..end_idx]` to resolve clips, opaque shadow cutouts, cached text layouts, and warm `GlyphAtlas`.
525    ///
526    /// # Arguments
527    ///
528    /// - `&Self` - Mutable software renderer.
529    /// - `&DisplayList` - Incoming command stream.
530    /// - `usize` - Inclusive start index into `display_list.get_commands()`.
531    /// - `usize` - Exclusive end index into `display_list.get_commands()`.
532    /// - `Rect` - Root physical damage clip rectangle.
533    /// - `f32` - Active DPI scale factor.
534    /// - `u32` - Framebuffer physical height.
535    ///
536    /// # Returns
537    ///
538    /// - `(Vec<PreppedCommand>, Vec<TextLayoutResult>)` - Band-ready commands and pre-measured text layouts.
539    fn prepare_frame_range(
540        &mut self,
541        display_list: &DisplayList,
542        start_idx: usize,
543        end_idx: usize,
544        root_clip: Rect,
545        scale: f32,
546        phys_h: u32,
547    ) -> (Vec<PreppedCommand>, Vec<TextLayoutResult>) {
548        let commands: &[DrawCommand] = display_list.get_commands().as_slice();
549        let clamped_end: usize = end_idx.min(commands.len());
550        let clamped_start: usize = start_idx.min(clamped_end);
551        let mut prepped: Vec<PreppedCommand> = Vec::with_capacity(clamped_end - clamped_start);
552        let mut text_layouts: Vec<TextLayoutResult> = Vec::new();
553        let Self {
554            glyph_atlas,
555            font_provider,
556            measurer,
557            text_layout_cache,
558            clip_stack,
559            ..
560        } = self;
561        clip_stack.clear();
562        clip_stack.push(root_clip);
563        if text_layout_cache.len() > TEXT_LAYOUT_CACHE_LIMIT {
564            text_layout_cache.clear();
565        }
566        for (offset, cmd) in commands[clamped_start..clamped_end].iter().enumerate() {
567            let cmd_index: usize = clamped_start + offset;
568            let active_clip: Rect = clip_stack.last().copied().unwrap_or(root_clip);
569            match cmd {
570                DrawCommand::PushClip(rect) => {
571                    let phys: Rect = snap_physical_rect(*rect, scale);
572                    let next: Rect = active_clip.intersect(phys).unwrap_or_default();
573                    clip_stack.push(next);
574                }
575                DrawCommand::PopClip => {
576                    if clip_stack.len() > 1 {
577                        clip_stack.pop();
578                    }
579                }
580                DrawCommand::Clear(_) => {
581                    let y0: u32 = (active_clip.get_y().floor().max(0.0) as u32).min(phys_h);
582                    let y1: u32 = (active_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
583                    if y0 < y1 {
584                        prepped.push(PreppedCommand {
585                            cmd_index,
586                            active_clip,
587                            y0,
588                            y1,
589                            opaque_cutout_h: Rect::default(),
590                            opaque_cutout_v: Rect::default(),
591                            text_layout_idx: u32::MAX,
592                        });
593                    }
594                }
595                DrawCommand::FillRoundedRect { rect, .. }
596                | DrawCommand::LinearGradientRect { rect, .. }
597                | DrawCommand::Image { rect, .. }
598                | DrawCommand::SpriteRegion { rect, .. } => {
599                    let phys: Rect = snap_physical_rect(*rect, scale);
600                    if let Some(vis) = phys.intersect(active_clip) {
601                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
602                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
603                        if y0 < y1 {
604                            prepped.push(PreppedCommand {
605                                cmd_index,
606                                active_clip,
607                                y0,
608                                y1,
609                                opaque_cutout_h: Rect::default(),
610                                opaque_cutout_v: Rect::default(),
611                                text_layout_idx: u32::MAX,
612                            });
613                        }
614                    }
615                }
616                DrawCommand::BoxShadow { rect, shadow, .. } => {
617                    if shadow.get_color().get_a() == 0 {
618                        continue;
619                    }
620                    let spread: f32 = shadow.get_spread_radius() * scale;
621                    let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
622                    let sigma: f32 = (blur * 0.5).max(0.75);
623                    let pad: f32 = (sigma * 3.0).ceil();
624                    let base_rect: Rect = snap_physical_rect(*rect, scale);
625                    let caster_rect: Rect = Rect::new(
626                        base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
627                        base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
628                        (base_rect.get_width() + spread * 2.0).max(1.0),
629                        (base_rect.get_height() + spread * 2.0).max(1.0),
630                    );
631                    let shadow_rect: Rect = Rect::new(
632                        caster_rect.get_x() - pad,
633                        caster_rect.get_y() - pad,
634                        caster_rect.get_width() + pad * 2.0,
635                        caster_rect.get_height() + pad * 2.0,
636                    );
637                    if let Some(vis) = shadow_rect.intersect(active_clip) {
638                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
639                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
640                        if y0 < y1 {
641                            let (cut_h, cut_v): (Rect, Rect) = Self::resolve_opaque_shadow_cutout(
642                                commands.get(cmd_index + 1),
643                                scale,
644                            );
645                            prepped.push(PreppedCommand {
646                                cmd_index,
647                                active_clip,
648                                y0,
649                                y1,
650                                opaque_cutout_h: cut_h,
651                                opaque_cutout_v: cut_v,
652                                text_layout_idx: u32::MAX,
653                            });
654                        }
655                    }
656                }
657                DrawCommand::TextRun { rect, text, style } => {
658                    if text.is_empty() || style.get_color().get_a() == 0 {
659                        continue;
660                    }
661                    let phys_rect: Rect = Self::scale_rect(*rect, scale);
662                    let pad: f32 = style.get_font_size() * scale * 0.5;
663                    let expanded: Rect = Rect::new(
664                        phys_rect.get_x() - pad,
665                        phys_rect.get_y() - pad,
666                        phys_rect.get_width() + pad * 2.0,
667                        phys_rect.get_height() + pad * 2.0,
668                    );
669                    let Some(vis) = expanded.intersect(active_clip) else {
670                        continue;
671                    };
672                    let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
673                    let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
674                    if y0 >= y1 {
675                        continue;
676                    }
677                    let max_w: f32 = rect.get_width().max(1.0);
678                    let cache_key: (u64, u32) = (
679                        hash_text_layout_key(text, *style),
680                        (max_w * 10.0).round() as u32,
681                    );
682                    let layout: TextLayoutResult =
683                        if let Some(cached) = text_layout_cache.get(&cache_key) {
684                            cached.clone()
685                        } else {
686                            let measured: TextLayoutResult =
687                                measurer.measure(text, *style, Some(max_w));
688                            text_layout_cache.insert(cache_key, measured.clone());
689                            measured
690                        };
691                    let phys_font_size: f32 = style.get_font_size() * scale;
692                    for line in layout.get_lines().iter() {
693                        for ch in line.get_text().chars() {
694                            if ch != ' ' {
695                                let key: GlyphKey =
696                                    GlyphKey::from_style(ch, phys_font_size, style.get_weight());
697                                let _: &RasterizedGlyph =
698                                    glyph_atlas.get_or_rasterize_with(key, font_provider);
699                            }
700                        }
701                    }
702                    let layout_idx: u32 = text_layouts.len() as u32;
703                    text_layouts.push(layout);
704                    prepped.push(PreppedCommand {
705                        cmd_index,
706                        active_clip,
707                        y0,
708                        y1,
709                        opaque_cutout_h: Rect::default(),
710                        opaque_cutout_v: Rect::default(),
711                        text_layout_idx: layout_idx,
712                    });
713                }
714                DrawCommand::Line {
715                    from, to, width, ..
716                } => {
717                    let half_w: f32 = (width * scale).max(1.0) * 0.5 + 1.0;
718                    let min_x: f32 = from.get_x().min(to.get_x()) * scale - half_w;
719                    let min_y: f32 = from.get_y().min(to.get_y()) * scale - half_w;
720                    let max_x: f32 = from.get_x().max(to.get_x()) * scale + half_w;
721                    let max_y: f32 = from.get_y().max(to.get_y()) * scale + half_w;
722                    if let Some(vis) =
723                        Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
724                    {
725                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
726                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
727                        if y0 < y1 {
728                            prepped.push(PreppedCommand {
729                                cmd_index,
730                                active_clip,
731                                y0,
732                                y1,
733                                opaque_cutout_h: Rect::default(),
734                                opaque_cutout_v: Rect::default(),
735                                text_layout_idx: u32::MAX,
736                            });
737                        }
738                    }
739                }
740                DrawCommand::Circle { center, radius, .. } => {
741                    let r: f32 = radius * scale + 1.0;
742                    let bounds: Rect = Rect::new(
743                        center.get_x() * scale - r,
744                        center.get_y() * scale - r,
745                        r * 2.0,
746                        r * 2.0,
747                    );
748                    if let Some(vis) = bounds.intersect(active_clip) {
749                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
750                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
751                        if y0 < y1 {
752                            prepped.push(PreppedCommand {
753                                cmd_index,
754                                active_clip,
755                                y0,
756                                y1,
757                                opaque_cutout_h: Rect::default(),
758                                opaque_cutout_v: Rect::default(),
759                                text_layout_idx: u32::MAX,
760                            });
761                        }
762                    }
763                }
764                DrawCommand::Triangle { p0, p1, p2, .. } => {
765                    let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.0;
766                    let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.0;
767                    let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.0;
768                    let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.0;
769                    if let Some(vis) =
770                        Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
771                    {
772                        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
773                        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
774                        if y0 < y1 {
775                            prepped.push(PreppedCommand {
776                                cmd_index,
777                                active_clip,
778                                y0,
779                                y1,
780                                opaque_cutout_h: Rect::default(),
781                                opaque_cutout_v: Rect::default(),
782                                text_layout_idx: u32::MAX,
783                            });
784                        }
785                    }
786                }
787            }
788        }
789        (prepped, text_layouts)
790    }
791
792    /// Computes two strictly-interior opaque cutout rectangles `(horizontal_bar, vertical_bar)` if the next command is an opaque `FillRoundedRect`.
793    ///
794    /// # Arguments
795    ///
796    /// - `Option<&DrawCommand>` - Immediately following command in the display list.
797    /// - `f32` - Active DPI scale factor.
798    ///
799    /// # Returns
800    ///
801    /// - `(Rect, Rect)` - Opaque inner rectangles safely skipped by `raster_shadow` with zero visual change.
802    #[must_use]
803    fn resolve_opaque_shadow_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
804        let Some(DrawCommand::FillRoundedRect {
805            rect,
806            color,
807            radius,
808            ..
809        }) = next_cmd
810        else {
811            return (Rect::default(), Rect::default());
812        };
813        if color.get_a() != 255 {
814            return (Rect::default(), Rect::default());
815        }
816        let phys: Rect = snap_physical_rect(*rect, scale);
817        let r_max: f32 = Self::scale_radius(*radius, scale)
818            .max_radius()
819            .min(phys.get_width() * 0.5)
820            .min(phys.get_height() * 0.5);
821        let pad: f32 = 1.5;
822        let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
823        let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
824        let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
825            Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
826        } else {
827            Rect::default()
828        };
829        let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
830        let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
831        let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
832            Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
833        } else {
834            Rect::default()
835        };
836        (cut_h, cut_v)
837    }
838
839    /// Executes all prepped commands overlapping `band`'s vertical slice `[y_offset, y_end)` completely lock-free.
840    ///
841    /// # Arguments
842    ///
843    /// - `&mut PixelBand<'_>` - Disjoint mutable horizontal pixel band.
844    /// - `&[DrawCommand]` - Full frame draw command slice.
845    /// - `&[PreppedCommand]` - Pre-clipped command list.
846    /// - `&[TextLayoutResult]` - Pre-measured text layouts.
847    /// - `&GlyphAtlas` - Immutable pre-warmed glyph atlas.
848    /// - `f32` - Active DPI scale factor.
849    /// - `AntialiasingMode` - Active anti-aliasing policy.
850    ///
851    /// # Returns
852    ///
853    /// - `usize` - Total shaded pixels in this band.
854    pub(crate) fn render_band(
855        band: &mut PixelBand<'_>,
856        commands: &[DrawCommand],
857        prepped: &[PreppedCommand],
858        text_layouts: &[TextLayoutResult],
859        glyph_atlas: &GlyphAtlas,
860        scale: f32,
861        aa: AntialiasingMode,
862    ) -> usize {
863        let band_y0: u32 = band.y_offset();
864        let band_y1: u32 = band.y_end();
865        let band_rect: Rect = Rect::new(
866            0.0,
867            band_y0 as f32,
868            band.width() as f32,
869            (band_y1 - band_y0) as f32,
870        );
871        let mut shaded: usize = 0;
872        for item in prepped.iter() {
873            if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
874                continue;
875            }
876            let Some(active_clip) = item.get_active_clip().intersect(band_rect) else {
877                continue;
878            };
879            let cmd: &DrawCommand = &commands[item.get_cmd_index()];
880            shaded += match cmd {
881                DrawCommand::Clear(color) => {
882                    if active_clip.get_x() <= 0.0
883                        && active_clip.get_width() >= (band.width() as f32)
884                        && active_clip.get_y() <= (band_y0 as f32)
885                        && active_clip.bottom() >= (band_y1 as f32)
886                    {
887                        band.clear(*color);
888                        (band.width() as usize) * ((band_y1 - band_y0) as usize)
889                    } else {
890                        Self::fill_rect_clipped(band, active_clip, *color, active_clip)
891                    }
892                }
893                DrawCommand::FillRoundedRect {
894                    rect,
895                    color,
896                    radius,
897                    border,
898                } => {
899                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
900                    let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
901                    let bw: f32 = if border.get_width() > 0.0 {
902                        (border.get_width() * scale).max(1.0)
903                    } else {
904                        0.0
905                    };
906                    let phys_border: Border = Border::new(bw, border.get_color());
907                    Self::raster_rounded_rect(
908                        band,
909                        phys_rect,
910                        *color,
911                        phys_radius,
912                        phys_border,
913                        active_clip,
914                        aa,
915                    )
916                }
917                DrawCommand::LinearGradientRect {
918                    rect,
919                    gradient,
920                    radius,
921                } => {
922                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
923                    let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
924                    Self::raster_gradient_rect(
925                        band,
926                        phys_rect,
927                        *gradient,
928                        phys_radius,
929                        active_clip,
930                        aa,
931                    )
932                }
933                DrawCommand::BoxShadow {
934                    rect,
935                    radius,
936                    shadow,
937                } => {
938                    let spread: f32 = shadow.get_spread_radius() * scale;
939                    let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
940                    let sigma: f32 = (blur * 0.5).max(0.75);
941                    let pad: f32 = (sigma * 3.0).ceil();
942                    let base_rect: Rect = snap_physical_rect(*rect, scale);
943                    let caster_rect: Rect = Rect::new(
944                        base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
945                        base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
946                        (base_rect.get_width() + spread * 2.0).max(1.0),
947                        (base_rect.get_height() + spread * 2.0).max(1.0),
948                    );
949                    let shadow_rect: Rect = Rect::new(
950                        caster_rect.get_x() - pad,
951                        caster_rect.get_y() - pad,
952                        caster_rect.get_width() + pad * 2.0,
953                        caster_rect.get_height() + pad * 2.0,
954                    );
955                    let raw_r: CornerRadius = Self::scale_radius(*radius, scale);
956                    let phys_radius: CornerRadius = CornerRadius::new(
957                        (raw_r.get_top_left() + spread).max(0.0),
958                        (raw_r.get_top_right() + spread).max(0.0),
959                        (raw_r.get_bottom_right() + spread).max(0.0),
960                        (raw_r.get_bottom_left() + spread).max(0.0),
961                    );
962                    Self::raster_shadow(
963                        band,
964                        (shadow_rect, caster_rect, active_clip),
965                        phys_radius,
966                        sigma,
967                        shadow.get_color(),
968                        (item.get_opaque_cutout_h(), item.get_opaque_cutout_v()),
969                    )
970                }
971                DrawCommand::TextRun { rect, style, .. } => {
972                    let lidx: usize = item.get_text_layout_idx() as usize;
973                    if let Some(layout) = text_layouts.get(lidx) {
974                        Self::raster_text_run_band(
975                            band,
976                            *rect,
977                            layout,
978                            *style,
979                            scale,
980                            active_clip,
981                            glyph_atlas,
982                        )
983                    } else {
984                        0
985                    }
986                }
987                DrawCommand::Image {
988                    rect,
989                    buffer,
990                    radius,
991                } => {
992                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
993                    let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
994                    Self::raster_image(band, phys_rect, buffer, phys_radius, active_clip, aa)
995                }
996                DrawCommand::Line {
997                    from,
998                    to,
999                    color,
1000                    width,
1001                } => {
1002                    let p0: Point = Point::new(from.get_x() * scale, from.get_y() * scale);
1003                    let p1: Point = Point::new(to.get_x() * scale, to.get_y() * scale);
1004                    Self::raster_line(
1005                        band,
1006                        p0,
1007                        p1,
1008                        *color,
1009                        (width * scale).max(1.0),
1010                        active_clip,
1011                        aa,
1012                    )
1013                }
1014                DrawCommand::Circle {
1015                    center,
1016                    radius,
1017                    color,
1018                } => {
1019                    let c: Point = Point::new(center.get_x() * scale, center.get_y() * scale);
1020                    Self::raster_circle(band, c, radius * scale, *color, active_clip, aa)
1021                }
1022                DrawCommand::Triangle { p0, p1, p2, color } => {
1023                    let v0: Point = Point::new(p0.get_x() * scale, p0.get_y() * scale);
1024                    let v1: Point = Point::new(p1.get_x() * scale, p1.get_y() * scale);
1025                    let v2: Point = Point::new(p2.get_x() * scale, p2.get_y() * scale);
1026                    Self::raster_triangle(band, v0, v1, v2, *color, active_clip, aa)
1027                }
1028                DrawCommand::SpriteRegion {
1029                    rect,
1030                    buffer,
1031                    src_rect,
1032                    tint,
1033                } => {
1034                    let phys_rect: Rect = snap_physical_rect(*rect, scale);
1035                    Self::raster_sprite_region(
1036                        band,
1037                        phys_rect,
1038                        buffer,
1039                        *src_rect,
1040                        *tint,
1041                        active_clip,
1042                        aa,
1043                    )
1044                }
1045                DrawCommand::PushClip(_) | DrawCommand::PopClip => 0,
1046            };
1047        }
1048        shaded
1049    }
1050
1051    /// Scales a logical rectangle into physical pixels.
1052    ///
1053    /// # Arguments
1054    ///
1055    /// - `Rect` - Logical rectangle.
1056    /// - `f32` - Scale factor.
1057    ///
1058    /// # Returns
1059    ///
1060    /// - `Rect` - Physical pixel rectangle.
1061    fn scale_rect(rect: Rect, scale: f32) -> Rect {
1062        Rect::new(
1063            rect.get_x() * scale,
1064            rect.get_y() * scale,
1065            rect.get_width() * scale,
1066            rect.get_height() * scale,
1067        )
1068    }
1069
1070    /// Scales logical corner radii into physical pixel radii.
1071    ///
1072    /// # Arguments
1073    ///
1074    /// - `CornerRadius` - Logical corner radii.
1075    /// - `f32` - Scale factor.
1076    ///
1077    /// # Returns
1078    ///
1079    /// - `CornerRadius` - Physical corner radii.
1080    fn scale_radius(radius: CornerRadius, scale: f32) -> CornerRadius {
1081        CornerRadius::new(
1082            radius.get_top_left() * scale,
1083            radius.get_top_right() * scale,
1084            radius.get_bottom_right() * scale,
1085            radius.get_bottom_left() * scale,
1086        )
1087    }
1088
1089    /// Fast axis-aligned solid rectangle fill clipped against `clip`.
1090    ///
1091    /// # Arguments
1092    ///
1093    /// - `&mut PixelBand<'_>` - Target pixel band.
1094    /// - `Rect` - Physical rectangle.
1095    /// - `Color` - Fill color.
1096    /// - `Rect` - Active clip rectangle.
1097    ///
1098    /// # Returns
1099    ///
1100    /// - `usize` - Number of pixels shaded.
1101    fn fill_rect_clipped(band: &mut PixelBand<'_>, rect: Rect, color: Color, clip: Rect) -> usize {
1102        if color.get_a() == 0 {
1103            return 0;
1104        }
1105        let Some(vis) = rect.intersect(clip) else {
1106            return 0;
1107        };
1108        let fb_w: u32 = band.width();
1109        let band_y0: u32 = band.y_offset();
1110        let band_y1: u32 = band.y_end();
1111        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1112        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1113        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1114        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1115        if x0 >= x1 || y0 >= y1 {
1116            return 0;
1117        }
1118        let span_len: usize = (x1 - x0) as usize;
1119        let rows: usize = (y1 - y0) as usize;
1120        let sa: u8 = color.get_a();
1121        if sa < 255 && span_len.saturating_mul(rows) >= 512 {
1122            let luts: ([u8; 256], [u8; 256], [u8; 256], [u8; 256]) = build_linear_blend_luts(color);
1123            for y in y0..y1 {
1124                band.fill_span_linear_luts(x0, x1, y, &luts);
1125            }
1126        } else {
1127            for y in y0..y1 {
1128                band.fill_span_linear(x0, x1, y, color);
1129            }
1130        }
1131        span_len * rows
1132    }
1133
1134    /// Rasterizes a rounded rectangle with optional border using edge-bounded 4x4 RGSS supersampling and linear-light spans.
1135    ///
1136    /// # Arguments
1137    ///
1138    /// - `&mut PixelBand<'_>` - Target pixel band.
1139    /// - `Rect` - Physical rectangle bounds.
1140    /// - `Color` - Fill color.
1141    /// - `CornerRadius` - Physical corner radii.
1142    /// - `Border` - Physical border specification.
1143    /// - `Rect` - Active clip bounds.
1144    /// - `AntialiasingMode` - Active AA policy.
1145    ///
1146    /// # Returns
1147    ///
1148    /// - `usize` - Number of pixels shaded.
1149    fn raster_rounded_rect(
1150        band: &mut PixelBand<'_>,
1151        rect: Rect,
1152        color: Color,
1153        radius: CornerRadius,
1154        border: Border,
1155        clip: Rect,
1156        aa: AntialiasingMode,
1157    ) -> usize {
1158        let Some(vis) = rect.intersect(clip) else {
1159            return 0;
1160        };
1161        let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
1162        if radius.max_radius() <= 0.0 && !has_border {
1163            return Self::fill_rect_clipped(band, rect, color, clip);
1164        }
1165        let half_w: f32 = rect.get_width() * 0.5;
1166        let half_h: f32 = rect.get_height() * 0.5;
1167        let cx: f32 = rect.get_x() + half_w;
1168        let cy: f32 = rect.get_y() + half_h;
1169        let border_w: f32 = border.get_width();
1170        let fb_w: u32 = band.width();
1171        let band_y0: u32 = band.y_offset();
1172        let band_y1: u32 = band.y_end();
1173        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1174        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1175        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1176        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1177        let safe_inset: f32 = radius.max_radius().max(border_w) + 1.5;
1178        let edge_inset: f32 = border_w + 1.5;
1179        let iy0: u32 = ((rect.get_y() + safe_inset).ceil().max(0.0) as u32).clamp(y0, y1);
1180        let iy1: u32 = ((rect.bottom() - safe_inset).floor().max(0.0) as u32).clamp(y0, y1);
1181        let ix0: u32 = ((rect.get_x() + edge_inset).ceil().max(0.0) as u32).clamp(x0, x1);
1182        let ix1: u32 = ((rect.right() - edge_inset).floor().max(0.0) as u32).clamp(x0, x1);
1183        let cx0: u32 = ((rect.get_x() + safe_inset).ceil().max(0.0) as u32).clamp(x0, x1);
1184        let cx1: u32 = ((rect.right() - safe_inset).floor().max(0.0) as u32).clamp(x0, x1);
1185        let has_interior: bool = iy0 < iy1 && ix0 < ix1;
1186        let has_center_band: bool = cx0 < cx1;
1187        let interior_luts: Option<RgbaLutQuad> = if has_interior
1188            && color.get_a() > 0
1189            && color.get_a() < 255
1190            && ((ix1 - ix0) as usize).saturating_mul((iy1 - iy0) as usize) >= 512
1191        {
1192            Some(build_linear_blend_luts(color))
1193        } else {
1194            None
1195        };
1196        let mut shaded: usize = 0;
1197        for y in y0..y1 {
1198            let py: f32 = (y as f32) + 0.5 - cy;
1199            let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
1200            if has_interior && y >= iy0 && y < iy1 {
1201                for x in x0..ix0 {
1202                    shaded += Self::shade_rounded_pixel(
1203                        band,
1204                        (x, y),
1205                        box_geom,
1206                        radius,
1207                        color,
1208                        border,
1209                        aa,
1210                    );
1211                }
1212                if color.get_a() > 0 {
1213                    if let Some(ref luts) = interior_luts {
1214                        band.fill_span_linear_luts(ix0, ix1, y, luts);
1215                    } else {
1216                        band.fill_span_linear(ix0, ix1, y, color);
1217                    }
1218                    shaded += (ix1 - ix0) as usize;
1219                }
1220                for x in ix1..x1 {
1221                    shaded += Self::shade_rounded_pixel(
1222                        band,
1223                        (x, y),
1224                        box_geom,
1225                        radius,
1226                        color,
1227                        border,
1228                        aa,
1229                    );
1230                }
1231            } else if has_center_band {
1232                for x in x0..cx0 {
1233                    shaded += Self::shade_rounded_pixel(
1234                        band,
1235                        (x, y),
1236                        box_geom,
1237                        radius,
1238                        color,
1239                        border,
1240                        aa,
1241                    );
1242                }
1243                let dist_y: f32 = py.abs() - half_h;
1244                let outer_cov: f32 = sdf_coverage(dist_y, aa);
1245                if outer_cov > 0.0 {
1246                    if has_border {
1247                        let inner_hh: f32 = (half_h - border_w).max(0.0);
1248                        let inner_cov: f32 = if inner_hh > 0.0 && half_w > border_w {
1249                            sdf_coverage(py.abs() - inner_hh, aa)
1250                        } else {
1251                            0.0
1252                        };
1253                        let mixed: Color = composite_fill_and_border(
1254                            color,
1255                            border.get_color(),
1256                            outer_cov,
1257                            inner_cov,
1258                        );
1259                        if mixed.get_a() > 0 {
1260                            band.fill_span_linear(cx0, cx1, y, mixed);
1261                        }
1262                        shaded += (cx1 - cx0) as usize;
1263                    } else if color.get_a() > 0 {
1264                        band.fill_span_linear(cx0, cx1, y, color.multiply_alpha(outer_cov));
1265                        shaded += (cx1 - cx0) as usize;
1266                    }
1267                }
1268                for x in cx1..x1 {
1269                    shaded += Self::shade_rounded_pixel(
1270                        band,
1271                        (x, y),
1272                        box_geom,
1273                        radius,
1274                        color,
1275                        border,
1276                        aa,
1277                    );
1278                }
1279            } else {
1280                for x in x0..x1 {
1281                    shaded += Self::shade_rounded_pixel(
1282                        band,
1283                        (x, y),
1284                        box_geom,
1285                        radius,
1286                        color,
1287                        border,
1288                        aa,
1289                    );
1290                }
1291            }
1292        }
1293        shaded
1294    }
1295
1296    /// Evaluates fast early-rejected analytical SDF and edge-only 4x4 RGSS coverage for a single edge/corner pixel.
1297    ///
1298    /// # Arguments
1299    ///
1300    /// - `&mut PixelBand<'_>` - Target pixel band.
1301    /// - `(u32, u32)` - Global pixel `(x, y)` coordinates.
1302    /// - `(f32, f32, f32, f32)` - Box geometry `(center_x, rel_py, half_w, half_h)`.
1303    /// - `CornerRadius` - Physical corner radii.
1304    /// - `Color` - Fill color.
1305    /// - `Border` - Border width and color.
1306    /// - `AntialiasingMode` - Active AA policy.
1307    ///
1308    /// # Returns
1309    ///
1310    /// - `usize` - `1` if the pixel was shaded, `0` otherwise.
1311    fn shade_rounded_pixel(
1312        band: &mut PixelBand<'_>,
1313        pos: (u32, u32),
1314        geom: (f32, f32, f32, f32),
1315        radius: CornerRadius,
1316        color: Color,
1317        border: Border,
1318        aa: AntialiasingMode,
1319    ) -> usize {
1320        let (x, y): (u32, u32) = pos;
1321        let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
1322        let px: f32 = (x as f32) + 0.5 - cx;
1323        let corner_r: f32 = quadrant_corner_radius(radius, px, py)
1324            .min(half_w)
1325            .min(half_h);
1326        let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
1327        if dist > 0.85 {
1328            return 0;
1329        }
1330        let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
1331        let bw: f32 = if has_border { border.get_width() } else { 0.0 };
1332        if !has_border {
1333            if dist < -0.85 {
1334                if color.get_a() > 0 {
1335                    band.blend_pixel_linear_dithered(x, y, color, 0.0);
1336                    return 1;
1337                }
1338                return 0;
1339            }
1340            let in_corner_edge: bool = aa != AntialiasingMode::None
1341                && corner_r > 0.5
1342                && px.abs() > (half_w - corner_r - 1.5)
1343                && py.abs() > (half_h - corner_r - 1.5);
1344            let outer_cov: f32 = if in_corner_edge {
1345                rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
1346            } else {
1347                sdf_coverage(dist, aa)
1348            };
1349            if outer_cov > 0.0 && color.get_a() > 0 {
1350                let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * outer_cov;
1351                band.blend_pixel_f32_dithered(x, y, color, alpha_f, 0.0);
1352                return 1;
1353            }
1354            return 0;
1355        }
1356        if dist < -(bw + 0.85) {
1357            if color.get_a() > 0 {
1358                band.blend_pixel_linear_dithered(x, y, color, 0.0);
1359                return 1;
1360            }
1361            return 0;
1362        }
1363        let inner_hw: f32 = (half_w - bw).max(0.0);
1364        let inner_hh: f32 = (half_h - bw).max(0.0);
1365        let inner_r: f32 = (corner_r - bw).max(0.0);
1366        let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
1367            rounded_box_sdf(px, py, inner_hw, inner_hh, inner_r)
1368        } else {
1369            2.0
1370        };
1371        if dist < -0.85 && inner_dist > 0.85 {
1372            band.blend_pixel_linear_dithered(x, y, border.get_color(), 0.0);
1373            return 1;
1374        }
1375        let in_corner_zone: bool = aa != AntialiasingMode::None
1376            && corner_r > 0.5
1377            && px.abs() > (half_w - corner_r - 1.5)
1378            && py.abs() > (half_h - corner_r - 1.5);
1379        let (outer_cov, inner_cov): (f32, f32) = if in_corner_zone {
1380            rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, bw)
1381        } else {
1382            let oc: f32 = sdf_coverage(dist, aa);
1383            if oc <= 0.0 {
1384                return 0;
1385            }
1386            let ic: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
1387                sdf_coverage(inner_dist, aa)
1388            } else {
1389                0.0
1390            };
1391            (oc, ic)
1392        };
1393        if outer_cov <= 0.0 {
1394            return 0;
1395        }
1396        let mixed: Color =
1397            composite_fill_and_border(color, border.get_color(), outer_cov, inner_cov);
1398        if mixed.get_a() > 0 {
1399            band.blend_pixel_linear_dithered(x, y, mixed, 0.0);
1400            return 1;
1401        }
1402        0
1403    }
1404
1405    /// Rasterizes a two-stop linear gradient inside an SDF rounded rectangle with edge-bounded RGSS and IGN dithering.
1406    ///
1407    /// # Arguments
1408    ///
1409    /// - `&mut PixelBand<'_>` - Target pixel band.
1410    /// - `Rect` - Physical bounds.
1411    /// - `LinearGradient` - Gradient angle and stops.
1412    /// - `CornerRadius` - Physical corner radii.
1413    /// - `Rect` - Active clip bounds.
1414    /// - `AntialiasingMode` - Active AA policy.
1415    ///
1416    /// # Returns
1417    ///
1418    /// - `usize` - Shaded pixel count.
1419    fn raster_gradient_rect(
1420        band: &mut PixelBand<'_>,
1421        rect: Rect,
1422        gradient: LinearGradient,
1423        radius: CornerRadius,
1424        clip: Rect,
1425        aa: AntialiasingMode,
1426    ) -> usize {
1427        let Some(vis) = rect.intersect(clip) else {
1428            return 0;
1429        };
1430        let rad: f32 = gradient.get_angle_deg().to_radians();
1431        let dir_x: f32 = rad.sin();
1432        let dir_y: f32 = rad.cos();
1433        let half_w: f32 = rect.get_width() * 0.5;
1434        let half_h: f32 = rect.get_height() * 0.5;
1435        let cx: f32 = rect.get_x() + half_w;
1436        let cy: f32 = rect.get_y() + half_h;
1437        let inv_w: f32 = if rect.get_width() > 0.0 {
1438            1.0 / rect.get_width()
1439        } else {
1440            0.0
1441        };
1442        let inv_h: f32 = if rect.get_height() > 0.0 {
1443            1.0 / rect.get_height()
1444        } else {
1445            0.0
1446        };
1447        let fb_w: u32 = band.width();
1448        let band_y0: u32 = band.y_offset();
1449        let band_y1: u32 = band.y_end();
1450        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1451        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1452        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1453        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1454        let mut shaded: usize = 0;
1455        for y in y0..y1 {
1456            let py: f32 = (y as f32) + 0.5 - cy;
1457            let ny: f32 = ((y as f32) - rect.get_y()) * inv_h;
1458            for x in x0..x1 {
1459                let px: f32 = (x as f32) + 0.5 - cx;
1460                let corner_r: f32 = quadrant_corner_radius(radius, px, py)
1461                    .min(half_w)
1462                    .min(half_h);
1463                let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
1464                if dist > 0.85 {
1465                    continue;
1466                }
1467                let cov: f32 = if dist < -0.85 {
1468                    1.0
1469                } else {
1470                    let in_corner: bool = aa != AntialiasingMode::None
1471                        && corner_r > 0.5
1472                        && px.abs() > (half_w - corner_r - 1.5)
1473                        && py.abs() > (half_h - corner_r - 1.5);
1474                    if in_corner {
1475                        rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
1476                    } else {
1477                        sdf_coverage(dist, aa)
1478                    }
1479                };
1480                if cov <= 0.0 {
1481                    continue;
1482                }
1483                let nx: f32 = ((x as f32) - rect.get_x()) * inv_w;
1484                let t: f32 = ((nx - 0.5) * dir_x + (ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
1485                let base_sample: Color =
1486                    gradient.get_start_color().lerp(gradient.get_end_color(), t);
1487                let alpha_f: f32 = ((base_sample.get_a() as f32) * (1.0 / 255.0)) * cov;
1488                let dither: f32 = interleaved_gradient_noise(x, y);
1489                band.blend_pixel_f32_dithered(x, y, base_sample, alpha_f, dither);
1490                shaded += 1;
1491            }
1492        }
1493        shaded
1494    }
1495
1496    /// Computes the horizontal opaque-interior skip interval `[cut_x0, cut_x1)` for shadow row `y`.
1497    ///
1498    /// # Arguments
1499    ///
1500    /// - `u32` - Global physical Y row.
1501    /// - `(Rect, Rect)` - Opaque cutout cross `(horizontal_bar, vertical_bar)`.
1502    /// - `u32` - Clamped row start X.
1503    /// - `u32` - Clamped row end X.
1504    ///
1505    /// # Returns
1506    ///
1507    /// - `(u32, u32)` - Opaque X span safely skippable on row `y`.
1508    #[must_use]
1509    fn shadow_row_cutout(y: u32, cutouts: (Rect, Rect), x0: u32, x1: u32) -> (u32, u32) {
1510        let (cut_h, cut_v): (Rect, Rect) = cutouts;
1511        let yf: f32 = (y as f32) + 0.5;
1512        if cut_h.get_width() > 0.0
1513            && cut_h.get_height() > 0.0
1514            && yf >= cut_h.get_y()
1515            && yf < cut_h.bottom()
1516        {
1517            let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
1518            let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, x1);
1519            return (cx0, cx1);
1520        }
1521        if cut_v.get_width() > 0.0
1522            && cut_v.get_height() > 0.0
1523            && yf >= cut_v.get_y()
1524            && yf < cut_v.bottom()
1525        {
1526            let cx0: u32 = (cut_v.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
1527            let cx1: u32 = (cut_v.right().floor().max(0.0) as u32).clamp(cx0, x1);
1528            return (cx0, cx1);
1529        }
1530        (x1, x1)
1531    }
1532
1533    /// Rasterizes a lossless 2D analytical Gaussian `erfc` LUT drop shadow skipping strictly-opaque card interiors.
1534    ///
1535    /// # Arguments
1536    ///
1537    /// - `&mut PixelBand<'_>` - Target pixel band.
1538    /// - `(Rect, Rect, Rect)` - Tuple `(shadow_rect, caster_rect, clip)` in physical pixels.
1539    /// - `CornerRadius` - Per-quadrant physical corner radii.
1540    /// - `f32` - Gaussian standard deviation `sigma` in physical pixels.
1541    /// - `Color` - Shadow tint color.
1542    /// - `(Rect, Rect)` - Strictly-opaque interior cutout rectangles from immediately following opaque card.
1543    ///
1544    /// # Returns
1545    ///
1546    /// - `usize` - Shaded pixel count.
1547    fn raster_shadow(
1548        band: &mut PixelBand<'_>,
1549        rects: (Rect, Rect, Rect),
1550        radius: CornerRadius,
1551        sigma: f32,
1552        color: Color,
1553        cutouts: (Rect, Rect),
1554    ) -> usize {
1555        let (shadow_rect, caster_rect, clip): (Rect, Rect, Rect) = rects;
1556        if color.get_a() == 0 {
1557            return 0;
1558        }
1559        let Some(vis) = shadow_rect.intersect(clip) else {
1560            return 0;
1561        };
1562        let half_w: f32 = (caster_rect.get_width() * 0.5).max(0.5);
1563        let half_h: f32 = (caster_rect.get_height() * 0.5).max(0.5);
1564        let cx: f32 = caster_rect.get_x() + half_w;
1565        let cy: f32 = caster_rect.get_y() + half_h;
1566        let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
1567        let inv_sigma: f32 = 1.0 / sigma.max(0.5);
1568        let cutoff: f32 = sigma * 3.0;
1569        let fb_w: u32 = band.width();
1570        let band_y0: u32 = band.y_offset();
1571        let band_y1: u32 = band.y_end();
1572        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1573        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1574        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1575        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1576        let r_max: f32 = radius.max_radius();
1577        let inner_inset: f32 = cutoff + r_max;
1578        let sy0: u32 = ((caster_rect.get_y() + inner_inset).ceil().max(0.0) as u32).clamp(y0, y1);
1579        let sy1: u32 = ((caster_rect.bottom() - inner_inset).floor().max(0.0) as u32).clamp(y0, y1);
1580        let sx0: u32 = ((caster_rect.get_x() + inner_inset).ceil().max(0.0) as u32).clamp(x0, x1);
1581        let sx1: u32 = ((caster_rect.right() - inner_inset).floor().max(0.0) as u32).clamp(x0, x1);
1582        let has_mid_x: bool = sx0 < sx1;
1583        let has_mid_y: bool = sy0 < sy1;
1584        let mut shaded: usize = 0;
1585        for y in y0..y1 {
1586            let py: f32 = (y as f32) + 0.5 - cy;
1587            let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(y, cutouts, x0, x1);
1588            let spans: [(u32, u32); 2] = if cut0 < cut1 {
1589                [(x0, cut0), (cut1, x1)]
1590            } else {
1591                [(x0, x1), (x1, x1)]
1592            };
1593            if has_mid_x && has_mid_y && y >= sy0 && y < sy1 {
1594                for (rx0, rx1) in spans.into_iter() {
1595                    let left_end: u32 = rx1.min(sx0);
1596                    for x in rx0..left_end {
1597                        let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
1598                        if dist < cutoff {
1599                            let alpha_f: f32 =
1600                                base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1601                            if alpha_f > 0.0005 {
1602                                band.blend_pixel_f32_dithered(
1603                                    x,
1604                                    y,
1605                                    color,
1606                                    alpha_f,
1607                                    interleaved_gradient_noise(x, y),
1608                                );
1609                                shaded += 1;
1610                            }
1611                        }
1612                    }
1613                    let right_start: u32 = rx0.max(sx1);
1614                    for x in right_start..rx1 {
1615                        let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
1616                        if dist < cutoff {
1617                            let alpha_f: f32 =
1618                                base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1619                            if alpha_f > 0.0005 {
1620                                band.blend_pixel_f32_dithered(
1621                                    x,
1622                                    y,
1623                                    color,
1624                                    alpha_f,
1625                                    interleaved_gradient_noise(x, y),
1626                                );
1627                                shaded += 1;
1628                            }
1629                        }
1630                    }
1631                }
1632            } else if has_mid_x {
1633                let dist_y: f32 = py.abs() - half_h;
1634                let mid_alpha: f32 = if dist_y < cutoff {
1635                    base_alpha * fast_gaussian_shadow_falloff(dist_y, inv_sigma)
1636                } else {
1637                    0.0
1638                };
1639                for (rx0, rx1) in spans.into_iter() {
1640                    if rx0 >= rx1 {
1641                        continue;
1642                    }
1643                    let l_end: u32 = rx1.min(sx0);
1644                    for x in rx0..l_end {
1645                        let px: f32 = (x as f32) + 0.5 - cx;
1646                        let cr: f32 = quadrant_corner_radius(radius, px, py);
1647                        let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, cr);
1648                        if dist < cutoff {
1649                            let alpha_f: f32 =
1650                                base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1651                            if alpha_f > 0.0005 {
1652                                band.blend_pixel_f32_dithered(
1653                                    x,
1654                                    y,
1655                                    color,
1656                                    alpha_f,
1657                                    interleaved_gradient_noise(x, y),
1658                                );
1659                                shaded += 1;
1660                            }
1661                        }
1662                    }
1663                    let m_start: u32 = rx0.max(sx0);
1664                    let m_end: u32 = rx1.min(sx1);
1665                    if mid_alpha > 0.0005 && m_start < m_end {
1666                        band.blend_shadow_span_const_alpha(m_start, m_end, y, color, mid_alpha);
1667                        shaded += (m_end - m_start) as usize;
1668                    }
1669                    let r_start: u32 = rx0.max(sx1);
1670                    for x in r_start..rx1 {
1671                        let px: f32 = (x as f32) + 0.5 - cx;
1672                        let cr: f32 = quadrant_corner_radius(radius, px, py);
1673                        let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, cr);
1674                        if dist < cutoff {
1675                            let alpha_f: f32 =
1676                                base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1677                            if alpha_f > 0.0005 {
1678                                band.blend_pixel_f32_dithered(
1679                                    x,
1680                                    y,
1681                                    color,
1682                                    alpha_f,
1683                                    interleaved_gradient_noise(x, y),
1684                                );
1685                                shaded += 1;
1686                            }
1687                        }
1688                    }
1689                }
1690            } else {
1691                for (rx0, rx1) in spans.into_iter() {
1692                    for x in rx0..rx1 {
1693                        let px: f32 = (x as f32) + 0.5 - cx;
1694                        let cr: f32 = quadrant_corner_radius(radius, px, py);
1695                        let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, cr);
1696                        if dist >= cutoff {
1697                            continue;
1698                        }
1699                        let alpha_f: f32 =
1700                            base_alpha * fast_gaussian_shadow_falloff(dist, inv_sigma);
1701                        if alpha_f > 0.0005 {
1702                            band.blend_pixel_f32_dithered(
1703                                x,
1704                                y,
1705                                color,
1706                                alpha_f,
1707                                interleaved_gradient_noise(x, y),
1708                            );
1709                            shaded += 1;
1710                        }
1711                    }
1712                }
1713            }
1714        }
1715        shaded
1716    }
1717
1718    /// Rasterizes a pre-measured UTF-8 text run into `band` using the immutable pre-warmed `GlyphAtlas`.
1719    ///
1720    /// # Arguments
1721    ///
1722    /// - `&mut PixelBand<'_>` - Target pixel band.
1723    /// - `Rect` - Logical text bounding box.
1724    /// - `&TextLayoutResult` - Pre-measured wrapped lines.
1725    /// - `TextStyle` - Typography style.
1726    /// - `f32` - Active DPI scale factor.
1727    /// - `Rect` - Active physical clip bounds.
1728    /// - `&GlyphAtlas` - Read-only pre-warmed glyph atlas.
1729    ///
1730    /// # Returns
1731    ///
1732    /// - `usize` - Shaded pixel count.
1733    fn raster_text_run_band(
1734        band: &mut PixelBand<'_>,
1735        rect: Rect,
1736        layout: &TextLayoutResult,
1737        style: TextStyle,
1738        scale: f32,
1739        clip: Rect,
1740        glyph_atlas: &GlyphAtlas,
1741    ) -> usize {
1742        let phys_font_size: f32 = style.get_font_size() * scale;
1743        let line_h_phys: f32 = layout.get_line_height_px() * scale;
1744        let box_w_phys: f32 = rect.get_width() * scale;
1745        let color: Color = style.get_color();
1746        let fb_w: i32 = band.width() as i32;
1747        let band_y0: i32 = band.y_offset() as i32;
1748        let band_y1: i32 = band.y_end() as i32;
1749        let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
1750        let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).clamp(band_y0, band_y1);
1751        let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(fb_w);
1752        let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).clamp(band_y0, band_y1);
1753        if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
1754            return 0;
1755        }
1756        let letter_sp: f32 = style.get_letter_spacing() * scale;
1757        let space_adv: f32 = measure_char_advance(' ', style) * scale;
1758        let glyphs: &HashMap<GlyphKey, RasterizedGlyph> = glyph_atlas.get_glyphs();
1759        let mut shaded: usize = 0;
1760        for (line_idx, line) in layout.get_lines().iter().enumerate() {
1761            let pen_y: f32 = rect.get_y() * scale + (line_idx as f32) * line_h_phys;
1762            if (pen_y + line_h_phys) < (clip_y0 as f32) || pen_y > (clip_y1 as f32) {
1763                continue;
1764            }
1765            let align_x: f32 = match style.get_align() {
1766                TextAlign::Left => 0.0,
1767                TextAlign::Center | TextAlign::Right => {
1768                    let mut line_w_phys: f32 = 0.0;
1769                    for ch in line.get_text().chars() {
1770                        if ch == ' ' {
1771                            line_w_phys += space_adv + letter_sp;
1772                        } else {
1773                            let key: GlyphKey =
1774                                GlyphKey::from_style(ch, phys_font_size, style.get_weight());
1775                            let adv: f32 = glyphs
1776                                .get(&key)
1777                                .map(|g: &RasterizedGlyph| (g.get_advance() as f32).max(1.0))
1778                                .unwrap_or(space_adv);
1779                            line_w_phys += adv + letter_sp;
1780                        }
1781                    }
1782                    if style.get_align() == TextAlign::Center {
1783                        ((box_w_phys - line_w_phys) * 0.5).max(0.0)
1784                    } else {
1785                        (box_w_phys - line_w_phys).max(0.0)
1786                    }
1787                }
1788            };
1789            let mut pen_x: f32 = rect.get_x() * scale + align_x;
1790            for ch in line.get_text().chars() {
1791                if ch == ' ' {
1792                    pen_x += space_adv + letter_sp;
1793                    continue;
1794                }
1795                if pen_x > (clip_x1 as f32) {
1796                    break;
1797                }
1798                let key: GlyphKey = GlyphKey::from_style(ch, phys_font_size, style.get_weight());
1799                let Some(glyph) = glyphs.get(&key) else {
1800                    pen_x += space_adv + letter_sp;
1801                    continue;
1802                };
1803                let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
1804                let gx0: i32 = pen_x.round() as i32;
1805                let gy0: i32 =
1806                    (pen_y + (line_h_phys - (glyph.get_height() as f32)) * 0.5).round() as i32;
1807                let gw: i32 = glyph.get_width() as i32;
1808                let gh: i32 = glyph.get_height() as i32;
1809                let py_start: i32 = (clip_y0 - gy0).max(0);
1810                let py_end: i32 = (clip_y1 - gy0).min(gh);
1811                let px_start: i32 = (clip_x0 - gx0).max(0);
1812                let px_end: i32 = (clip_x1 - gx0).min(gw);
1813                if py_start < py_end && px_start < px_end {
1814                    let cov_bytes: &[u8] = glyph.get_coverage().as_slice();
1815                    let gw_usize: usize = gw as usize;
1816                    let dx: u32 = (gx0 + px_start) as u32;
1817                    let start_u: usize = px_start as usize;
1818                    let end_u: usize = px_end as usize;
1819                    for py in py_start..py_end {
1820                        let dy: u32 = (gy0 + py) as u32;
1821                        let row_off: usize = (py as usize) * gw_usize;
1822                        let row_slice: &[u8] = &cov_bytes[row_off + start_u..row_off + end_u];
1823                        shaded += band.blend_glyph_row(dx, dy, row_slice, color);
1824                    }
1825                }
1826                pen_x += adv_phys;
1827            }
1828        }
1829        shaded
1830    }
1831
1832    /// Blits a single bilinear-interpolated RGBA8 image scanline into `dst_row` using fixed-point 8.8 weights.
1833    ///
1834    /// # Arguments
1835    ///
1836    /// - `(usize, usize, f32, f32, f32)` - Row geometry `(y, x0, rect_y, inv_dst_h, src_h_f)`.
1837    /// - `(usize, usize)` - Source image dimensions `(src_w, max_sy)`.
1838    /// - `&[(usize, usize, u32)]` - Precomputed horizontal sample LUT `(sx0, sx1, wx_256)`.
1839    /// - `&[u8]` - Source RGBA8 pixel slice.
1840    /// - `&mut [u8]` - Destination framebuffer row slice.
1841    fn blit_bilinear_row(
1842        geom: (usize, usize, f32, f32, f32),
1843        src_dims: (usize, usize),
1844        x_lut: &[(usize, usize, u32)],
1845        src_bytes: &[u8],
1846        dst_row: &mut [u8],
1847    ) {
1848        let (y, x0, rect_y, inv_dst_h, src_h_f): (usize, usize, f32, f32, f32) = geom;
1849        let (src_w_usize, max_sy): (usize, usize) = src_dims;
1850        let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
1851        let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
1852        let sy0: usize = (fy.floor() as usize).min(max_sy);
1853        let sy1: usize = (sy0 + 1).min(max_sy);
1854        let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
1855        let iwy: u32 = 256 - wy;
1856        let row0: usize = sy0 * src_w_usize;
1857        let row1: usize = sy1 * src_w_usize;
1858        let src_len: usize = src_bytes.len();
1859        for (lx, &(sx0, sx1, wx)) in x_lut.iter().enumerate() {
1860            let i00: usize = (row0 + sx0) * 4;
1861            let i10: usize = (row0 + sx1) * 4;
1862            let i01: usize = (row1 + sx0) * 4;
1863            let i11: usize = (row1 + sx1) * 4;
1864            if i11 + 4 > src_len {
1865                continue;
1866            }
1867            let didx: usize = (x0 + lx) * 4;
1868            if didx + 4 > dst_row.len() {
1869                continue;
1870            }
1871            let iwx: u32 = 256 - wx;
1872            let w00: u32 = iwx * iwy;
1873            let w10: u32 = wx * iwy;
1874            let w01: u32 = iwx * wy;
1875            let w11: u32 = wx * wy;
1876            let a00: u32 = src_bytes[i00 + 3] as u32;
1877            let a10: u32 = src_bytes[i10 + 3] as u32;
1878            let a01: u32 = src_bytes[i01 + 3] as u32;
1879            let a11: u32 = src_bytes[i11 + 3] as u32;
1880            if (a00 & a10 & a01 & a11) == 255 {
1881                dst_row[didx] = (((src_bytes[i00] as u32) * w00
1882                    + (src_bytes[i10] as u32) * w10
1883                    + (src_bytes[i01] as u32) * w01
1884                    + (src_bytes[i11] as u32) * w11
1885                    + 32768)
1886                    >> 16) as u8;
1887                dst_row[didx + 1] = (((src_bytes[i00 + 1] as u32) * w00
1888                    + (src_bytes[i10 + 1] as u32) * w10
1889                    + (src_bytes[i01 + 1] as u32) * w01
1890                    + (src_bytes[i11 + 1] as u32) * w11
1891                    + 32768)
1892                    >> 16) as u8;
1893                dst_row[didx + 2] = (((src_bytes[i00 + 2] as u32) * w00
1894                    + (src_bytes[i10 + 2] as u32) * w10
1895                    + (src_bytes[i01 + 2] as u32) * w01
1896                    + (src_bytes[i11 + 2] as u32) * w11
1897                    + 32768)
1898                    >> 16) as u8;
1899                dst_row[didx + 3] = 255;
1900                continue;
1901            }
1902            let a_val: u32 = (a00 * w00 + a10 * w10 + a01 * w01 + a11 * w11 + 32768) >> 16;
1903            if a_val == 0 {
1904                continue;
1905            }
1906            let r: u32 = ((src_bytes[i00] as u32) * w00
1907                + (src_bytes[i10] as u32) * w10
1908                + (src_bytes[i01] as u32) * w01
1909                + (src_bytes[i11] as u32) * w11
1910                + 32768)
1911                >> 16;
1912            let g: u32 = ((src_bytes[i00 + 1] as u32) * w00
1913                + (src_bytes[i10 + 1] as u32) * w10
1914                + (src_bytes[i01 + 1] as u32) * w01
1915                + (src_bytes[i11 + 1] as u32) * w11
1916                + 32768)
1917                >> 16;
1918            let b: u32 = ((src_bytes[i00 + 2] as u32) * w00
1919                + (src_bytes[i10 + 2] as u32) * w10
1920                + (src_bytes[i01 + 2] as u32) * w01
1921                + (src_bytes[i11 + 2] as u32) * w11
1922                + 32768)
1923                >> 16;
1924            let inv_a: u32 = 255 - a_val;
1925            dst_row[didx] = ((r * a_val + (dst_row[didx] as u32) * inv_a + 127) / 255) as u8;
1926            dst_row[didx + 1] =
1927                ((g * a_val + (dst_row[didx + 1] as u32) * inv_a + 127) / 255) as u8;
1928            dst_row[didx + 2] =
1929                ((b * a_val + (dst_row[didx + 2] as u32) * inv_a + 127) / 255) as u8;
1930            dst_row[didx + 3] = 255;
1931        }
1932    }
1933
1934    /// Blits a decoded `ImageBuffer` into `band` with bilinear filtering and per-quadrant SDF rounded clip.
1935    ///
1936    /// # Arguments
1937    ///
1938    /// - `&mut PixelBand<'_>` - Target pixel band.
1939    /// - `Rect` - Physical destination bounds.
1940    /// - `&ImageBuffer` - Source RGBA8 image.
1941    /// - `CornerRadius` - Physical corner radii.
1942    /// - `Rect` - Active clip bounds.
1943    /// - `AntialiasingMode` - Active AA policy.
1944    ///
1945    /// # Returns
1946    ///
1947    /// - `usize` - Shaded pixel count.
1948    fn raster_image(
1949        band: &mut PixelBand<'_>,
1950        rect: Rect,
1951        buffer: &ImageBuffer,
1952        radius: CornerRadius,
1953        clip: Rect,
1954        aa: AntialiasingMode,
1955    ) -> usize {
1956        if buffer.get_width() == 0 || buffer.get_height() == 0 {
1957            return 0;
1958        }
1959        let Some(vis) = rect.intersect(clip) else {
1960            return 0;
1961        };
1962        let half_w: f32 = rect.get_width() * 0.5;
1963        let half_h: f32 = rect.get_height() * 0.5;
1964        let cx: f32 = rect.get_x() + half_w;
1965        let cy: f32 = rect.get_y() + half_h;
1966        let fb_w: u32 = band.width();
1967        let band_y0: u32 = band.y_offset();
1968        let band_y1: u32 = band.y_end();
1969        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
1970        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
1971        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
1972        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
1973        let src_w: u32 = buffer.get_width();
1974        let src_h: u32 = buffer.get_height();
1975        let src_bytes: &[u8] = buffer.get_pixels().as_slice();
1976        let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
1977        let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
1978        let use_bilinear: bool = aa != AntialiasingMode::None
1979            && ((rect.get_width() - (src_w as f32)).abs() > 0.5
1980                || (rect.get_height() - (src_h as f32)).abs() > 0.5);
1981        let has_radius: bool = radius.max_radius() > 0.0;
1982        let max_sx: usize = (src_w as usize).saturating_sub(1);
1983        let max_sy: usize = (src_h as usize).saturating_sub(1);
1984        let src_w_usize: usize = src_w as usize;
1985        if !has_radius && use_bilinear && x0 < x1 && y0 < y1 {
1986            let span_w: usize = (x1 - x0) as usize;
1987            let mut x_lut: Vec<(usize, usize, u32)> = Vec::with_capacity(span_w);
1988            for x in x0..x1 {
1989                let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
1990                let fx: f32 = (u * (src_w as f32) - 0.5).clamp(0.0, max_sx as f32);
1991                let sx0: usize = (fx.floor() as usize).min(max_sx);
1992                let sx1: usize = (sx0 + 1).min(max_sx);
1993                let wx: u32 = ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
1994                x_lut.push((sx0, sx1, wx));
1995            }
1996            let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
1997            let rect_y: f32 = rect.get_y();
1998            let src_h_f: f32 = src_h as f32;
1999            let x0_usize: usize = x0 as usize;
2000            for y in y0..y1 {
2001                if let Some(row_buf) = band.row_slice_mut(y) {
2002                    Self::blit_bilinear_row(
2003                        (y as usize, x0_usize, rect_y, inv_dst_h, src_h_f),
2004                        (src_w_usize, max_sy),
2005                        x_lut_ref,
2006                        src_bytes,
2007                        row_buf,
2008                    );
2009                }
2010            }
2011            return span_w * ((y1 - y0) as usize);
2012        }
2013        let mut shaded: usize = 0;
2014        for y in y0..y1 {
2015            let v: f32 = (((y as f32) + 0.5 - rect.get_y()) * inv_dst_h).clamp(0.0, 1.0);
2016            let py: f32 = (y as f32) + 0.5 - cy;
2017            if use_bilinear {
2018                let fy: f32 = (v * (src_h as f32) - 0.5).clamp(0.0, max_sy as f32);
2019                let sy0: usize = (fy.floor() as usize).min(max_sy);
2020                let sy1: usize = (sy0 + 1).min(max_sy);
2021                let wy: f32 = fy - (sy0 as f32);
2022                let iwy: f32 = 1.0 - wy;
2023                let row0: usize = sy0 * src_w_usize;
2024                let row1: usize = sy1 * src_w_usize;
2025                for x in x0..x1 {
2026                    let cov: f32 = if has_radius {
2027                        let px: f32 = (x as f32) + 0.5 - cx;
2028                        let cr: f32 = quadrant_corner_radius(radius, px, py);
2029                        sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
2030                    } else {
2031                        1.0
2032                    };
2033                    if cov <= 0.0 {
2034                        continue;
2035                    }
2036                    let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
2037                    let fx: f32 = (u * (src_w as f32) - 0.5).clamp(0.0, max_sx as f32);
2038                    let sx0: usize = (fx.floor() as usize).min(max_sx);
2039                    let sx1: usize = (sx0 + 1).min(max_sx);
2040                    let wx: f32 = fx - (sx0 as f32);
2041                    let iwx: f32 = 1.0 - wx;
2042                    let i00: usize = (row0 + sx0) * 4;
2043                    let i10: usize = (row0 + sx1) * 4;
2044                    let i01: usize = (row1 + sx0) * 4;
2045                    let i11: usize = (row1 + sx1) * 4;
2046                    if i11 + 4 <= src_bytes.len() {
2047                        let w00: f32 = iwx * iwy;
2048                        let w10: f32 = wx * iwy;
2049                        let w01: f32 = iwx * wy;
2050                        let w11: f32 = wx * wy;
2051                        let r: u8 = ((src_bytes[i00] as f32) * w00
2052                            + (src_bytes[i10] as f32) * w10
2053                            + (src_bytes[i01] as f32) * w01
2054                            + (src_bytes[i11] as f32) * w11)
2055                            .round() as u8;
2056                        let g: u8 = ((src_bytes[i00 + 1] as f32) * w00
2057                            + (src_bytes[i10 + 1] as f32) * w10
2058                            + (src_bytes[i01 + 1] as f32) * w01
2059                            + (src_bytes[i11 + 1] as f32) * w11)
2060                            .round() as u8;
2061                        let b: u8 = ((src_bytes[i00 + 2] as f32) * w00
2062                            + (src_bytes[i10 + 2] as f32) * w10
2063                            + (src_bytes[i01 + 2] as f32) * w01
2064                            + (src_bytes[i11 + 2] as f32) * w11)
2065                            .round() as u8;
2066                        let a: u8 = ((src_bytes[i00 + 3] as f32) * w00
2067                            + (src_bytes[i10 + 3] as f32) * w10
2068                            + (src_bytes[i01 + 3] as f32) * w01
2069                            + (src_bytes[i11 + 3] as f32) * w11)
2070                            .round() as u8;
2071                        let sample: Color = Color::new(r, g, b, a).multiply_alpha(cov);
2072                        band.blend_pixel(x, y, sample);
2073                        shaded += 1;
2074                    }
2075                }
2076            } else {
2077                let sy: usize = ((v * (src_h as f32)).floor() as usize).min(max_sy);
2078                let row: usize = sy * src_w_usize;
2079                for x in x0..x1 {
2080                    let cov: f32 = if has_radius {
2081                        let px: f32 = (x as f32) + 0.5 - cx;
2082                        let cr: f32 = quadrant_corner_radius(radius, px, py);
2083                        sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
2084                    } else {
2085                        1.0
2086                    };
2087                    if cov <= 0.0 {
2088                        continue;
2089                    }
2090                    let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
2091                    let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
2092                    let idx: usize = (row + sx) * 4;
2093                    if idx + 4 <= src_bytes.len() {
2094                        let sample: Color = Color::new(
2095                            src_bytes[idx],
2096                            src_bytes[idx + 1],
2097                            src_bytes[idx + 2],
2098                            src_bytes[idx + 3],
2099                        )
2100                        .multiply_alpha(cov);
2101                        band.blend_pixel(x, y, sample);
2102                        shaded += 1;
2103                    }
2104                }
2105            }
2106        }
2107        shaded
2108    }
2109
2110    /// Rasterizes an anti-aliased line segment between `from` and `to`.
2111    ///
2112    /// # Arguments
2113    ///
2114    /// - `&mut PixelBand<'_>` - Target pixel band.
2115    /// - `Point` - Physical start point.
2116    /// - `Point` - Physical end point.
2117    /// - `Color` - Stroke color.
2118    /// - `f32` - Physical stroke width.
2119    /// - `Rect` - Active clip bounds.
2120    /// - `AntialiasingMode` - Active AA policy.
2121    ///
2122    /// # Returns
2123    ///
2124    /// - `usize` - Shaded pixel count.
2125    fn raster_line(
2126        band: &mut PixelBand<'_>,
2127        from: Point,
2128        to: Point,
2129        color: Color,
2130        width: f32,
2131        clip: Rect,
2132        aa: AntialiasingMode,
2133    ) -> usize {
2134        let half_w: f32 = width * 0.5;
2135        let min_x: f32 = from.get_x().min(to.get_x()) - half_w - 1.0;
2136        let min_y: f32 = from.get_y().min(to.get_y()) - half_w - 1.0;
2137        let max_x: f32 = from.get_x().max(to.get_x()) + half_w + 1.0;
2138        let max_y: f32 = from.get_y().max(to.get_y()) + half_w + 1.0;
2139        let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
2140        else {
2141            return 0;
2142        };
2143        let dx: f32 = to.get_x() - from.get_x();
2144        let dy: f32 = to.get_y() - from.get_y();
2145        let len_sq: f32 = (dx * dx + dy * dy).max(1e-6);
2146        let fb_w: u32 = band.width();
2147        let band_y0: u32 = band.y_offset();
2148        let band_y1: u32 = band.y_end();
2149        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2150        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2151        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2152        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2153        let mut shaded: usize = 0;
2154        for y in y0..y1 {
2155            let py: f32 = (y as f32) + 0.5;
2156            for x in x0..x1 {
2157                let px: f32 = (x as f32) + 0.5;
2158                let t: f32 = (((px - from.get_x()) * dx + (py - from.get_y()) * dy) / len_sq)
2159                    .clamp(0.0, 1.0);
2160                let proj_x: f32 = from.get_x() + t * dx;
2161                let proj_y: f32 = from.get_y() + t * dy;
2162                let dist: f32 =
2163                    ((px - proj_x) * (px - proj_x) + (py - proj_y) * (py - proj_y)).sqrt() - half_w;
2164                let cov: f32 = sdf_coverage(dist, aa);
2165                if cov > 0.0 {
2166                    let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * cov;
2167                    band.blend_pixel_f32_dithered(x, y, color, alpha_f, 0.0);
2168                    shaded += 1;
2169                }
2170            }
2171        }
2172        shaded
2173    }
2174
2175    /// Rasterizes an analytical SDF anti-aliased filled circle with 4x4 RGSS perimeter sampling.
2176    ///
2177    /// # Arguments
2178    ///
2179    /// - `&mut PixelBand<'_>` - Target pixel band.
2180    /// - `Point` - Physical center point.
2181    /// - `f32` - Physical radius.
2182    /// - `Color` - Fill color.
2183    /// - `Rect` - Active clip bounds.
2184    /// - `AntialiasingMode` - Active AA policy.
2185    ///
2186    /// # Returns
2187    ///
2188    /// - `usize` - Shaded pixel count.
2189    fn raster_circle(
2190        band: &mut PixelBand<'_>,
2191        center: Point,
2192        radius: f32,
2193        color: Color,
2194        clip: Rect,
2195        aa: AntialiasingMode,
2196    ) -> usize {
2197        if radius <= 0.0 || color.get_a() == 0 {
2198            return 0;
2199        }
2200        let bounds: Rect = Rect::new(
2201            center.get_x() - radius - 1.0,
2202            center.get_y() - radius - 1.0,
2203            (radius + 1.0) * 2.0,
2204            (radius + 1.0) * 2.0,
2205        );
2206        let Some(vis) = bounds.intersect(clip) else {
2207            return 0;
2208        };
2209        let fb_w: u32 = band.width();
2210        let band_y0: u32 = band.y_offset();
2211        let band_y1: u32 = band.y_end();
2212        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2213        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2214        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2215        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2216        let outer_r: f32 = radius + 1.0;
2217        let inner_r: f32 = (radius - 1.0).max(0.0);
2218        let outer_r2: f32 = outer_r * outer_r;
2219        let inner_r2: f32 = inner_r * inner_r;
2220        let cx: f32 = center.get_x();
2221        let cy: f32 = center.get_y();
2222        let mut shaded: usize = 0;
2223        let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
2224        for y in y0..y1 {
2225            let dy: f32 = (y as f32) + 0.5 - cy;
2226            let dy2: f32 = dy * dy;
2227            if dy2 >= outer_r2 {
2228                continue;
2229            }
2230            let out_dx: f32 = (outer_r2 - dy2).sqrt();
2231            let row_x0: u32 = ((cx - out_dx).floor().max(0.0) as u32).clamp(x0, x1);
2232            let row_x1: u32 = ((cx + out_dx).ceil().max(0.0) as u32).clamp(x0, x1);
2233            if dy2 < inner_r2 && inner_r > 1.0 {
2234                let in_dx: f32 = (inner_r2 - dy2).sqrt();
2235                let in_x0: u32 = ((cx - in_dx).ceil().max(0.0) as u32).clamp(row_x0, row_x1);
2236                let in_x1: u32 = ((cx + in_dx).floor().max(0.0) as u32).clamp(row_x0, row_x1);
2237                for x in row_x0..in_x0 {
2238                    let dx: f32 = (x as f32) + 0.5 - cx;
2239                    let cov: f32 = if aa == AntialiasingMode::None {
2240                        sdf_coverage((dx * dx + dy2).sqrt() - radius, aa)
2241                    } else {
2242                        circle_supersampled_coverage(dx, dy, radius)
2243                    };
2244                    if cov > 0.0 {
2245                        band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2246                        shaded += 1;
2247                    }
2248                }
2249                if in_x0 < in_x1 {
2250                    band.fill_span_linear(in_x0, in_x1, y, color);
2251                    shaded += (in_x1 - in_x0) as usize;
2252                }
2253                for x in in_x1..row_x1 {
2254                    let dx: f32 = (x as f32) + 0.5 - cx;
2255                    let cov: f32 = if aa == AntialiasingMode::None {
2256                        sdf_coverage((dx * dx + dy2).sqrt() - radius, aa)
2257                    } else {
2258                        circle_supersampled_coverage(dx, dy, radius)
2259                    };
2260                    if cov > 0.0 {
2261                        band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2262                        shaded += 1;
2263                    }
2264                }
2265            } else {
2266                for x in row_x0..row_x1 {
2267                    let dx: f32 = (x as f32) + 0.5 - cx;
2268                    let cov: f32 = if aa == AntialiasingMode::None {
2269                        sdf_coverage((dx * dx + dy2).sqrt() - radius, aa)
2270                    } else {
2271                        circle_supersampled_coverage(dx, dy, radius)
2272                    };
2273                    if cov > 0.0 {
2274                        band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2275                        shaded += 1;
2276                    }
2277                }
2278            }
2279        }
2280        shaded
2281    }
2282
2283    /// Rasterizes a solid filled triangle using fast signed-edge classification and edge-only 4x4 RGSS.
2284    ///
2285    /// # Arguments
2286    ///
2287    /// - `&mut PixelBand<'_>` - Target pixel band.
2288    /// - `Point` - First physical vertex.
2289    /// - `Point` - Second physical vertex.
2290    /// - `Point` - Third physical vertex.
2291    /// - `Color` - Fill color.
2292    /// - `Rect` - Active clip bounds.
2293    /// - `AntialiasingMode` - Active AA policy.
2294    ///
2295    /// # Returns
2296    ///
2297    /// - `usize` - Shaded pixel count.
2298    fn raster_triangle(
2299        band: &mut PixelBand<'_>,
2300        p0: Point,
2301        p1: Point,
2302        p2: Point,
2303        color: Color,
2304        clip: Rect,
2305        aa: AntialiasingMode,
2306    ) -> usize {
2307        if color.get_a() == 0 {
2308            return 0;
2309        }
2310        let area: f32 = (p1.get_x() - p0.get_x()) * (p2.get_y() - p0.get_y())
2311            - (p1.get_y() - p0.get_y()) * (p2.get_x() - p0.get_x());
2312        if area.abs() < 1e-5 {
2313            return 0;
2314        }
2315        let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) - 1.0;
2316        let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) - 1.0;
2317        let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) + 1.0;
2318        let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) + 1.0;
2319        let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
2320        else {
2321            return 0;
2322        };
2323        let fb_w: u32 = band.width();
2324        let band_y0: u32 = band.y_offset();
2325        let band_y1: u32 = band.y_end();
2326        let clip_x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2327        let clip_x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2328        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2329        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2330        let edges: [(Point, Point); 3] = [(p0, p1), (p1, p2), (p2, p0)];
2331        let sign: f32 = if area > 0.0 { 1.0 } else { -1.0 };
2332        let inv_l0: f32 = sign
2333            / (p1.get_x() - p0.get_x())
2334                .hypot(p1.get_y() - p0.get_y())
2335                .max(1e-5);
2336        let inv_l1: f32 = sign
2337            / (p2.get_x() - p1.get_x())
2338                .hypot(p2.get_y() - p1.get_y())
2339                .max(1e-5);
2340        let inv_l2: f32 = sign
2341            / (p0.get_x() - p2.get_x())
2342                .hypot(p0.get_y() - p2.get_y())
2343                .max(1e-5);
2344        let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
2345        let mut shaded: usize = 0;
2346        for y in y0..y1 {
2347            let py: f32 = (y as f32) + 0.5;
2348            if aa == AntialiasingMode::None {
2349                let mut min_ix: f32 = f32::INFINITY;
2350                let mut max_ix: f32 = f32::NEG_INFINITY;
2351                for (a, b) in edges.iter() {
2352                    let ay: f32 = a.get_y();
2353                    let by: f32 = b.get_y();
2354                    if (ay <= py && by > py) || (by <= py && ay > py) {
2355                        let t: f32 = (py - ay) / (by - ay);
2356                        let ix: f32 = a.get_x() + t * (b.get_x() - a.get_x());
2357                        min_ix = min_ix.min(ix);
2358                        max_ix = max_ix.max(ix);
2359                    }
2360                }
2361                if min_ix <= max_ix {
2362                    let sx0: u32 = (min_ix.floor().max(0.0) as u32).clamp(clip_x0, clip_x1);
2363                    let sx1: u32 = (max_ix.ceil().max(0.0) as u32).clamp(clip_x0, clip_x1);
2364                    if sx0 < sx1 {
2365                        band.fill_span_linear(sx0, sx1, y, color);
2366                        shaded += (sx1 - sx0) as usize;
2367                    }
2368                }
2369                continue;
2370            }
2371            for x in clip_x0..clip_x1 {
2372                let px: f32 = (x as f32) + 0.5;
2373                let d0: f32 = ((p1.get_x() - p0.get_x()) * (py - p0.get_y())
2374                    - (p1.get_y() - p0.get_y()) * (px - p0.get_x()))
2375                    * inv_l0;
2376                if d0 < -0.85 {
2377                    continue;
2378                }
2379                let d1: f32 = ((p2.get_x() - p1.get_x()) * (py - p1.get_y())
2380                    - (p2.get_y() - p1.get_y()) * (px - p1.get_x()))
2381                    * inv_l1;
2382                if d1 < -0.85 {
2383                    continue;
2384                }
2385                let d2: f32 = ((p0.get_x() - p2.get_x()) * (py - p2.get_y())
2386                    - (p0.get_y() - p2.get_y()) * (px - p2.get_x()))
2387                    * inv_l2;
2388                if d2 < -0.85 {
2389                    continue;
2390                }
2391                if d0 > 0.85 && d1 > 0.85 && d2 > 0.85 {
2392                    band.blend_pixel_linear_dithered(x, y, color, 0.0);
2393                    shaded += 1;
2394                    continue;
2395                }
2396                let cov: f32 = triangle_supersampled_coverage(px, py, p0, p1, p2);
2397                if cov >= 0.999 {
2398                    band.blend_pixel_linear_dithered(x, y, color, 0.0);
2399                    shaded += 1;
2400                } else if cov > 0.0 {
2401                    band.blend_pixel_f32_dithered(x, y, color, base_alpha * cov, 0.0);
2402                    shaded += 1;
2403                }
2404            }
2405        }
2406        shaded
2407    }
2408
2409    /// Blits a cropped sub-rectangle of an `ImageBuffer` sprite sheet into `band` with bilinear filtering and optional tint.
2410    ///
2411    /// # Arguments
2412    ///
2413    /// - `&mut PixelBand<'_>` - Target pixel band.
2414    /// - `Rect` - Physical destination bounds.
2415    /// - `&ImageBuffer` - Source sprite-sheet RGBA8 buffer.
2416    /// - `Rect` - Source pixel sub-rectangle.
2417    /// - `Color` - Multiplicative tint color.
2418    /// - `Rect` - Active clip bounds.
2419    /// - `AntialiasingMode` - Active AA policy.
2420    ///
2421    /// # Returns
2422    ///
2423    /// - `usize` - Shaded pixel count.
2424    fn raster_sprite_region(
2425        band: &mut PixelBand<'_>,
2426        rect: Rect,
2427        buffer: &ImageBuffer,
2428        src_rect: Rect,
2429        tint: Color,
2430        clip: Rect,
2431        aa: AntialiasingMode,
2432    ) -> usize {
2433        if buffer.get_width() == 0
2434            || buffer.get_height() == 0
2435            || tint.get_a() == 0
2436            || src_rect.get_width() <= 0.0
2437            || src_rect.get_height() <= 0.0
2438        {
2439            return 0;
2440        }
2441        let Some(vis) = rect.intersect(clip) else {
2442            return 0;
2443        };
2444        let fb_w: u32 = band.width();
2445        let band_y0: u32 = band.y_offset();
2446        let band_y1: u32 = band.y_end();
2447        let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2448        let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2449        let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
2450        let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
2451        let buf_w: u32 = buffer.get_width();
2452        let buf_h: u32 = buffer.get_height();
2453        let src_bytes: &[u8] = buffer.get_pixels().as_slice();
2454        let inv_w: f32 = 1.0 / rect.get_width().max(1.0);
2455        let inv_h: f32 = 1.0 / rect.get_height().max(1.0);
2456        let untinted: bool = tint == COLOR_WHITE;
2457        let tr: u32 = tint.get_r() as u32;
2458        let tg: u32 = tint.get_g() as u32;
2459        let tb: u32 = tint.get_b() as u32;
2460        let ta: u32 = tint.get_a() as u32;
2461        let use_bilinear: bool = aa != AntialiasingMode::None
2462            && ((rect.get_width() - src_rect.get_width()).abs() > 0.5
2463                || (rect.get_height() - src_rect.get_height()).abs() > 0.5);
2464        let max_sx: u32 = ((src_rect.right().ceil() as u32).saturating_sub(1)).min(buf_w - 1);
2465        let max_sy: u32 = ((src_rect.bottom().ceil() as u32).saturating_sub(1)).min(buf_h - 1);
2466        let min_sx: u32 = (src_rect.get_x().floor().max(0.0) as u32).min(max_sx);
2467        let min_sy: u32 = (src_rect.get_y().floor().max(0.0) as u32).min(max_sy);
2468        let buf_w_usize: usize = buf_w as usize;
2469        let mut shaded: usize = 0;
2470        for y in y0..y1 {
2471            let v: f32 = (((y as f32) + 0.5 - rect.get_y()) * inv_h).clamp(0.0, 1.0);
2472            let fy: f32 = (src_rect.get_y() + v * src_rect.get_height() - 0.5)
2473                .clamp(min_sy as f32, max_sy as f32);
2474            let sy0: u32 = (fy.floor() as u32).clamp(min_sy, max_sy);
2475            let sy1: u32 = (sy0 + 1).min(max_sy);
2476            let wy: f32 = if use_bilinear { fy - (sy0 as f32) } else { 0.0 };
2477            let iwy: f32 = 1.0 - wy;
2478            let row0: usize = (sy0 as usize) * buf_w_usize;
2479            let row1: usize = (sy1 as usize) * buf_w_usize;
2480            for x in x0..x1 {
2481                let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_w).clamp(0.0, 1.0);
2482                let fx: f32 = (src_rect.get_x() + u * src_rect.get_width() - 0.5)
2483                    .clamp(min_sx as f32, max_sx as f32);
2484                let sx0: u32 = (fx.floor() as u32).clamp(min_sx, max_sx);
2485                let sx1: u32 = (sx0 + 1).min(max_sx);
2486                let (sr_u8, sg_u8, sb_u8, sa_u8): (u8, u8, u8, u8) = if use_bilinear {
2487                    let wx: f32 = fx - (sx0 as f32);
2488                    let iwx: f32 = 1.0 - wx;
2489                    let i00: usize = (row0 + (sx0 as usize)) * 4;
2490                    let i10: usize = (row0 + (sx1 as usize)) * 4;
2491                    let i01: usize = (row1 + (sx0 as usize)) * 4;
2492                    let i11: usize = (row1 + (sx1 as usize)) * 4;
2493                    if i11 + 4 > src_bytes.len() {
2494                        continue;
2495                    }
2496                    let w00: f32 = iwx * iwy;
2497                    let w10: f32 = wx * iwy;
2498                    let w01: f32 = iwx * wy;
2499                    let w11: f32 = wx * wy;
2500                    (
2501                        ((src_bytes[i00] as f32) * w00
2502                            + (src_bytes[i10] as f32) * w10
2503                            + (src_bytes[i01] as f32) * w01
2504                            + (src_bytes[i11] as f32) * w11)
2505                            .round() as u8,
2506                        ((src_bytes[i00 + 1] as f32) * w00
2507                            + (src_bytes[i10 + 1] as f32) * w10
2508                            + (src_bytes[i01 + 1] as f32) * w01
2509                            + (src_bytes[i11 + 1] as f32) * w11)
2510                            .round() as u8,
2511                        ((src_bytes[i00 + 2] as f32) * w00
2512                            + (src_bytes[i10 + 2] as f32) * w10
2513                            + (src_bytes[i01 + 2] as f32) * w01
2514                            + (src_bytes[i11 + 2] as f32) * w11)
2515                            .round() as u8,
2516                        ((src_bytes[i00 + 3] as f32) * w00
2517                            + (src_bytes[i10 + 3] as f32) * w10
2518                            + (src_bytes[i01 + 3] as f32) * w01
2519                            + (src_bytes[i11 + 3] as f32) * w11)
2520                            .round() as u8,
2521                    )
2522                } else {
2523                    let idx: usize = (row0 + (sx0 as usize)) * 4;
2524                    if idx + 4 > src_bytes.len() {
2525                        continue;
2526                    }
2527                    (
2528                        src_bytes[idx],
2529                        src_bytes[idx + 1],
2530                        src_bytes[idx + 2],
2531                        src_bytes[idx + 3],
2532                    )
2533                };
2534                if sa_u8 == 0 {
2535                    continue;
2536                }
2537                let sample: Color = if untinted {
2538                    Color::new(sr_u8, sg_u8, sb_u8, sa_u8)
2539                } else {
2540                    let rr: u32 = (sr_u8 as u32) * tr + 128;
2541                    let gg: u32 = (sg_u8 as u32) * tg + 128;
2542                    let bb: u32 = (sb_u8 as u32) * tb + 128;
2543                    let aa_v: u32 = (sa_u8 as u32) * ta + 128;
2544                    Color::new(
2545                        ((rr + (rr >> 8)) >> 8) as u8,
2546                        ((gg + (gg >> 8)) >> 8) as u8,
2547                        ((bb + (bb >> 8)) >> 8) as u8,
2548                        ((aa_v + (aa_v >> 8)) >> 8) as u8,
2549                    )
2550                };
2551                band.blend_pixel(x, y, sample);
2552                shaded += 1;
2553            }
2554        }
2555        shaded
2556    }
2557}