1use super::*;
2
3#[cfg(not(target_arch = "wasm32"))]
5impl BandWorkerPool {
6 #[must_use]
12 pub(crate) fn new() -> Self {
13 let initial_cap: usize = ENGINE_WORKER_MAX_THREADS.saturating_mul(2);
14 Self {
15 dispatch_tasks: Mutex::new(Vec::with_capacity(initial_cap)),
16 }
17 }
18
19 fn execute_serial(
34 slice_spec: (&mut [u8], u32, u32, u32, usize),
35 commands: &[DrawCommand],
36 prepped: &[PreppedCommand],
37 aux: BandAuxSlices<'_>,
38 atlas: &GlyphAtlas,
39 render_opts: (f32, AntialiasingMode, BandRestoreSpec<'_>),
40 ) -> usize {
41 let (pixels, width, y_offset, height, start_byte): (&mut [u8], u32, u32, u32, usize) =
42 slice_spec;
43 let (scale, aa, restore): (f32, AntialiasingMode, BandRestoreSpec<'_>) = render_opts;
44 if let Some(src_buf) = restore.base_pixels {
45 let end_byte: usize = start_byte + pixels.len();
46 if let Some(src_slice) = src_buf.get(start_byte..end_byte) {
47 let x0_clamped: u32 = restore.x0.min(width);
48 let x1_clamped: u32 = restore.x1.clamp(x0_clamped, width);
49 restore_band_strip(
50 pixels,
51 src_slice,
52 (
53 (width as usize) * 4,
54 height as usize,
55 (x0_clamped as usize) * 4,
56 ((x1_clamped - x0_clamped) as usize) * 4,
57 ),
58 restore.scrim_luts,
59 );
60 }
61 }
62 let mut band: PixelBand<'_> = PixelBand {
63 width,
64 y_offset,
65 height,
66 pixels,
67 };
68 SoftwareRenderer::render_band(&mut band, commands, prepped, aux, atlas, (scale, aa))
69 }
70
71 #[must_use]
77 pub(crate) fn total_threads(&self) -> usize {
78 try_get_ready_engine_worker_pool().map_or(1, EngineWorkerPool::total_threads)
79 }
80
81 pub(crate) fn execute(
97 &self,
98 framebuffer: &mut Framebuffer,
99 band_range: (u32, u32, usize, usize),
100 cmd_slices: (&[DrawCommand], &[PreppedCommand]),
101 aux: BandAuxSlices<'_>,
102 atlas: &GlyphAtlas,
103 render_opts: (f32, AntialiasingMode, BandRestoreSpec<'_>),
104 ) -> usize {
105 let Self { dispatch_tasks } = self;
106 let worker_count: usize =
107 try_get_ready_engine_worker_pool().map_or(0, EngineWorkerPool::worker_count);
108 let (y0, y1, band_count, max_workers): (u32, u32, usize, usize) = band_range;
109 let (commands, prepped): (&[DrawCommand], &[PreppedCommand]) = cmd_slices;
110 let BandAuxSlices {
111 positioned_glyphs,
112 caret_rects,
113 rounded_clips,
114 corner_masks,
115 } = aux;
116 let (scale, aa, restore): (f32, AntialiasingMode, BandRestoreSpec<'_>) = render_opts;
117 let fb_w: u32 = framebuffer.get_width();
118 let fb_h: u32 = framebuffer.get_height();
119 let start_y: u32 = y0.min(fb_h);
120 let end_y: u32 = y1.clamp(start_y, fb_h);
121 let total_rows: u32 = end_y - start_y;
122 if total_rows == 0 || fb_w == 0 {
123 return 0;
124 }
125 let row_stride: usize = (fb_w as usize) * 4;
126 let start_byte: usize = (start_y as usize) * row_stride;
127 let end_byte: usize = (end_y as usize) * row_stride;
128 let Some(slice) = framebuffer.get_mut_pixels().get_mut(start_byte..end_byte) else {
129 return 0;
130 };
131 let strip_count: usize = band_count.max(1).min(total_rows as usize);
132 let worker_budget: usize = worker_count.min(max_workers);
133 if worker_budget == 0 || strip_count <= 1 {
134 return Self::execute_serial(
135 (slice, fb_w, start_y, total_rows, start_byte),
136 commands,
137 prepped,
138 aux,
139 atlas,
140 (scale, aa, restore),
141 );
142 }
143 let Ok(mut tasks) = dispatch_tasks.try_lock() else {
144 return Self::execute_serial(
145 (slice, fb_w, start_y, total_rows, start_byte),
146 commands,
147 prepped,
148 aux,
149 atlas,
150 (scale, aa, restore),
151 );
152 };
153 tasks.clear();
154 let rx0_clamped: u32 = restore.x0.min(fb_w);
155 let rx1_clamped: u32 = restore.x1.clamp(rx0_clamped, fb_w);
156 let restore_x0_bytes: usize = (rx0_clamped as usize) * 4;
157 let restore_row_bytes: usize = ((rx1_clamped - rx0_clamped) as usize) * 4;
158 let rows_per: usize = (total_rows as usize).div_ceil(strip_count);
159 let chunk_bytes: usize = rows_per * row_stride;
160 let mut cur_y: u32 = start_y;
161 let mut cur_byte_off: usize = start_byte;
162 for chunk in slice.chunks_mut(chunk_bytes) {
163 let chunk_len: usize = chunk.len();
164 let chunk_rows: u32 = (chunk_len / row_stride) as u32;
165 let base_ptr: usize = if let Some(src_buf) = restore.base_pixels {
166 let byte_end: usize = cur_byte_off + chunk_len;
167 if byte_end <= src_buf.len() {
168 unsafe { src_buf.as_ptr().add(cur_byte_off) as usize }
170 } else {
171 0
172 }
173 } else {
174 0
175 };
176 tasks.push(BandTaskSlice {
177 pixels_ptr: chunk.as_mut_ptr() as usize,
178 pixels_len: chunk_len,
179 width: fb_w,
180 y_start: cur_y,
181 height: chunk_rows,
182 base_src_ptr: base_ptr,
183 restore_x0_bytes,
184 restore_row_bytes,
185 });
186 cur_y += chunk_rows;
187 cur_byte_off += chunk_len;
188 }
189 let scrim_luts_ptr: usize = restore.scrim_luts.map_or(0, |luts: &[[u8; 256]; 4]| {
190 (luts as *const [[u8; 256]; 4]) as usize
191 });
192 let job: BandJob = BandJob {
193 kind: BandJobKind::RasterBands,
194 tasks_ptr: tasks.as_ptr() as usize,
195 tasks_len: tasks.len(),
196 commands_ptr: commands.as_ptr() as usize,
197 commands_len: commands.len(),
198 prepped_ptr: prepped.as_ptr() as usize,
199 prepped_len: prepped.len(),
200 glyphs_ptr: positioned_glyphs.as_ptr() as usize,
201 glyphs_len: positioned_glyphs.len(),
202 caret_rects_ptr: caret_rects.as_ptr() as usize,
203 caret_rects_len: caret_rects.len(),
204 rounded_clips_ptr: rounded_clips.as_ptr() as usize,
205 rounded_clips_len: rounded_clips.len(),
206 corner_masks_ptr: corner_masks.as_ptr() as usize,
207 corner_masks_len: corner_masks.len(),
208 atlas_ptr: (atlas as *const GlyphAtlas) as usize,
209 scrim_luts_ptr,
210 scale,
211 aa,
212 blur_desc: BlurPassDesc::default(),
213 next_idx: AlignedAtomicUsize::default(),
214 total_shaded: AlignedAtomicUsize::default(),
215 };
216 let dispatch_workers: usize = worker_budget.min(tasks.len().saturating_sub(1));
217 self.dispatch_job(&job, dispatch_workers)
218 }
219
220 pub(crate) fn execute_blur_pass(
233 &self,
234 kind: BandJobKind,
235 blur_desc: BlurPassDesc,
236 max_workers: usize,
237 ) -> usize {
238 let Self { dispatch_tasks } = self;
239 let worker_count: usize =
240 try_get_ready_engine_worker_pool().map_or(0, EngineWorkerPool::worker_count);
241 let worker_budget: usize = worker_count
242 .min(max_workers)
243 .min(blur_desc.strip_count.saturating_sub(1));
244 let job: BandJob = BandJob {
245 kind,
246 tasks_ptr: 0,
247 tasks_len: 0,
248 commands_ptr: 0,
249 commands_len: 0,
250 prepped_ptr: 0,
251 prepped_len: 0,
252 glyphs_ptr: 0,
253 glyphs_len: 0,
254 caret_rects_ptr: 0,
255 caret_rects_len: 0,
256 rounded_clips_ptr: 0,
257 rounded_clips_len: 0,
258 corner_masks_ptr: 0,
259 corner_masks_len: 0,
260 atlas_ptr: 0,
261 scrim_luts_ptr: 0,
262 scale: 1.0,
263 aa: AntialiasingMode::None,
264 blur_desc,
265 next_idx: AlignedAtomicUsize::default(),
266 total_shaded: AlignedAtomicUsize::default(),
267 };
268 if worker_budget == 0 {
269 run_band_job_loop(&job);
270 return job.total_shaded.load(Ordering::Acquire);
271 }
272 let Ok(_guard) = dispatch_tasks.try_lock() else {
273 run_band_job_loop(&job);
274 return job.total_shaded.load(Ordering::Acquire);
275 };
276 self.dispatch_job(&job, worker_budget)
277 }
278
279 pub(crate) fn execute_hash_tiles(
289 &self,
290 target_framebuffer: &Framebuffer,
291 hash_tiles: &mut [u64],
292 dirty_bits: Option<&[u64]>,
293 tiles_x: u32,
294 ) {
295 let total_tiles: usize = hash_tiles.len();
296 let total_chunks: usize = total_tiles.div_ceil(16);
297 let Self { dispatch_tasks } = self;
298 let worker_count: usize =
299 try_get_ready_engine_worker_pool().map_or(0, EngineWorkerPool::worker_count);
300 let worker_budget: usize = worker_count.min(5).min(total_chunks.saturating_sub(1));
301 let job: BandJob = BandJob {
302 kind: BandJobKind::HashTiles,
303 tasks_ptr: (target_framebuffer as *const Framebuffer) as usize,
304 tasks_len: total_chunks,
305 commands_ptr: hash_tiles.as_mut_ptr() as usize,
306 commands_len: total_tiles,
307 prepped_ptr: dirty_bits.map_or(0, |blue_val: &[u64]| blue_val.as_ptr() as usize),
308 prepped_len: tiles_x as usize,
309 glyphs_ptr: 0,
310 glyphs_len: 0,
311 caret_rects_ptr: 0,
312 caret_rects_len: 0,
313 rounded_clips_ptr: 0,
314 rounded_clips_len: 0,
315 corner_masks_ptr: 0,
316 corner_masks_len: 0,
317 atlas_ptr: 0,
318 scrim_luts_ptr: 0,
319 scale: 1.0,
320 aa: AntialiasingMode::None,
321 blur_desc: BlurPassDesc::default(),
322 next_idx: AlignedAtomicUsize::default(),
323 total_shaded: AlignedAtomicUsize::default(),
324 };
325 if worker_budget == 0 {
326 run_band_job_loop(&job);
327 return;
328 }
329 let Ok(_guard) = dispatch_tasks.try_lock() else {
330 run_band_job_loop(&job);
331 return;
332 };
333 let _: usize = self.dispatch_job(&job, worker_budget);
334 }
335
336 fn dispatch_job(&self, job: &BandJob, dispatch_workers: usize) -> usize {
347 if dispatch_workers == 0 {
348 run_band_job_loop(job);
349 return job.total_shaded.load(Ordering::Acquire);
350 }
351 if let Some(pool) = try_get_ready_engine_worker_pool() {
352 pool.dispatch_raw(
353 (job as *const BandJob) as usize,
354 band_job_trampoline,
355 dispatch_workers,
356 );
357 } else {
358 run_band_job_loop(job);
359 }
360 job.total_shaded.load(Ordering::Acquire)
361 }
362}
363
364impl TextLayoutCache {
366 #[must_use]
376 pub(crate) fn with_capacity(slot_cap: usize) -> Self {
377 let cap: usize = slot_cap.max(16).next_power_of_two();
378 let entry_cap: usize = cap / 2;
379 Self {
380 slots: vec![EMPTY_TEXT_LAYOUT_SLOT; cap],
381 entries: Vec::with_capacity(entry_cap),
382 entry_keys: Vec::with_capacity(entry_cap),
383 entry_last_used: Vec::with_capacity(entry_cap),
384 entry_bytes: Vec::with_capacity(entry_cap),
385 resident_bytes: 0,
386 budget_bytes: TEXT_LAYOUT_CACHE_BUDGET_BYTES,
387 lru_clock: 0,
388 cache_hits: 0,
389 cache_misses: 0,
390 evictions: 0,
391 }
392 }
393
394 #[inline]
404 #[must_use]
405 fn estimate_entry_bytes(layout: &TextLayoutResult) -> usize {
406 let mut bytes: usize = TEXT_LAYOUT_ENTRY_OVERHEAD_BYTES;
407 for line in layout.get_lines().iter() {
408 bytes = bytes
409 .saturating_add(TEXT_LINE_OVERHEAD_BYTES)
410 .saturating_add(line.get_text().len());
411 }
412 bytes
413 }
414
415 #[must_use]
425 pub(crate) fn stats(&self) -> (u64, u64, u64, usize) {
426 let Self {
427 cache_hits,
428 cache_misses,
429 evictions,
430 resident_bytes,
431 ..
432 } = self;
433 (*cache_hits, *cache_misses, *evictions, *resident_bytes)
434 }
435
436 #[must_use]
447 pub(crate) fn get(&self, idx: u32) -> Option<&TextLayoutResult> {
448 let Self { entries, .. } = self;
449 entries.get(idx as usize)
450 }
451
452 pub(crate) fn evict_lru_if_needed(&mut self) {
458 let Self {
459 slots,
460 entries,
461 entry_keys,
462 entry_last_used,
463 entry_bytes,
464 resident_bytes,
465 budget_bytes,
466 evictions,
467 ..
468 } = self;
469 let effective_budget: usize = if *budget_bytes == 0 {
470 TEXT_LAYOUT_CACHE_BUDGET_BYTES
471 } else {
472 *budget_bytes
473 };
474 let count: usize = entries.len();
475 if count <= TEXT_LAYOUT_CACHE_LIMIT && *resident_bytes <= effective_budget {
476 return;
477 }
478 let target_count: usize = (TEXT_LAYOUT_CACHE_LIMIT * 3) / 4;
479 let target_bytes: usize = (effective_budget * 3) / 4;
480 let mut order: Vec<usize> = (0..count).collect();
481 order.sort_unstable_by_key(|idx: &usize| entry_last_used.get(*idx).copied().unwrap_or(0));
482 let mut keep: Vec<bool> = vec![true; count];
483 let mut remaining_count: usize = count;
484 let mut remaining_bytes: usize = *resident_bytes;
485 let mut evicted_count: usize = 0;
486 for idx in order.into_iter() {
487 if remaining_count <= target_count && remaining_bytes <= target_bytes {
488 break;
489 }
490 keep[idx] = false;
491 remaining_count = remaining_count.saturating_sub(1);
492 remaining_bytes = remaining_bytes.saturating_sub(entry_bytes[idx]);
493 evicted_count += 1;
494 }
495 if evicted_count == 0 {
496 return;
497 }
498 let mut write_idx: usize = 0;
499 let mut next_resident: usize = 0;
500 for (read_idx, &kept) in keep.iter().enumerate() {
501 if kept {
502 if write_idx != read_idx {
503 entries.swap(write_idx, read_idx);
504 entry_keys.swap(write_idx, read_idx);
505 entry_last_used.swap(write_idx, read_idx);
506 entry_bytes.swap(write_idx, read_idx);
507 }
508 next_resident = next_resident.saturating_add(entry_bytes[write_idx]);
509 write_idx += 1;
510 }
511 }
512 entries.truncate(write_idx);
513 entry_keys.truncate(write_idx);
514 entry_last_used.truncate(write_idx);
515 entry_bytes.truncate(write_idx);
516 *resident_bytes = next_resident;
517 *evictions = evictions.saturating_add(evicted_count as u64);
518 if slots.len() > TEXT_LAYOUT_CACHE_SLOTS {
519 slots.resize(TEXT_LAYOUT_CACHE_SLOTS, EMPTY_TEXT_LAYOUT_SLOT);
520 }
521 slots.fill(EMPTY_TEXT_LAYOUT_SLOT);
522 if !slots.is_empty() {
523 let mask: usize = slots.len() - 1;
524 for (slot_entry_idx, &(key_hash, width_key)) in entry_keys.iter().enumerate() {
525 let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
526 while slots[idx].entry_idx != u32::MAX {
527 idx = (idx + 1) & mask;
528 }
529 slots[idx] = TextLayoutSlot {
530 key_hash,
531 width_key,
532 entry_idx: slot_entry_idx as u32,
533 };
534 }
535 }
536 }
537
538 #[inline(always)]
550 #[must_use]
551 fn slot_start(key_hash: u64, width_key: u32, mask: usize) -> usize {
552 let mixed: u64 = (key_hash ^ (width_key as u64)).wrapping_mul(FX_HASH_K64);
553 ((mixed ^ (mixed >> 32)) as usize) & mask
554 }
555
556 fn rehash(&mut self, new_cap: usize) {
563 let cap: usize = new_cap.max(TEXT_LAYOUT_CACHE_SLOTS).next_power_of_two();
564 let mask: usize = cap - 1;
565 let mut next_slots: Vec<TextLayoutSlot> = vec![EMPTY_TEXT_LAYOUT_SLOT; cap];
566 let Self { slots, .. } = self;
567 for old in slots.iter().copied() {
568 if old.entry_idx == u32::MAX {
569 continue;
570 }
571 let mut idx: usize = Self::slot_start(old.key_hash, old.width_key, mask);
572 while next_slots[idx].entry_idx != u32::MAX {
573 idx = (idx + 1) & mask;
574 }
575 next_slots[idx] = old;
576 }
577 *slots = next_slots;
578 }
579
580 pub(crate) fn get_or_insert_with<CallbackFn>(
593 &mut self,
594 key_hash: u64,
595 width_key: u32,
596 compute: CallbackFn,
597 ) -> u32
598 where
599 CallbackFn: FnOnce() -> TextLayoutResult,
600 {
601 let mut empty_slot: Option<usize> = None;
602 {
603 let Self {
604 slots,
605 entry_last_used,
606 lru_clock,
607 cache_hits,
608 ..
609 } = self;
610 if !slots.is_empty() {
611 let mask: usize = slots.len() - 1;
612 let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
613 loop {
614 let slot: TextLayoutSlot = slots[idx];
615 if slot.entry_idx == u32::MAX {
616 empty_slot = Some(idx);
617 break;
618 }
619 if slot.key_hash == key_hash && slot.width_key == width_key {
620 *cache_hits = cache_hits.wrapping_add(1);
621 *lru_clock = lru_clock.wrapping_add(1);
622 if let Some(tick) = entry_last_used.get_mut(slot.entry_idx as usize) {
623 *tick = *lru_clock;
624 }
625 return slot.entry_idx;
626 }
627 idx = (idx + 1) & mask;
628 }
629 }
630 }
631 let measured: TextLayoutResult = compute();
632 let entry_sz: usize = Self::estimate_entry_bytes(&measured);
633 let needs_rehash: bool = {
634 let Self { slots, entries, .. } = self;
635 slots.is_empty() || (entries.len() + 1).saturating_mul(2) > slots.len()
636 };
637 if needs_rehash {
638 let next_cap: usize = {
639 let Self { slots, .. } = self;
640 if slots.is_empty() {
641 TEXT_LAYOUT_CACHE_SLOTS
642 } else {
643 slots.len().saturating_mul(2)
644 }
645 };
646 self.rehash(next_cap);
647 empty_slot = None;
648 }
649 let Self {
650 slots,
651 entries,
652 entry_keys,
653 entry_last_used,
654 entry_bytes,
655 resident_bytes,
656 lru_clock,
657 cache_misses,
658 ..
659 } = self;
660 *cache_misses = cache_misses.wrapping_add(1);
661 *lru_clock = lru_clock.wrapping_add(1);
662 let entry_idx: u32 = entries.len() as u32;
663 entries.push(measured);
664 entry_keys.push((key_hash, width_key));
665 entry_last_used.push(*lru_clock);
666 entry_bytes.push(entry_sz);
667 *resident_bytes = resident_bytes.saturating_add(entry_sz);
668 let target_idx: usize = match empty_slot {
669 Some(idx) => idx,
670 None => {
671 let mask: usize = slots.len() - 1;
672 let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
673 while slots[idx].entry_idx != u32::MAX {
674 idx = (idx + 1) & mask;
675 }
676 idx
677 }
678 };
679 slots[target_idx] = TextLayoutSlot {
680 key_hash,
681 width_key,
682 entry_idx,
683 };
684 entry_idx
685 }
686}
687
688impl PositionedGlyphRunCache {
690 pub(crate) fn clear(&mut self) {
696 let Self {
697 slots,
698 glyph_slab,
699 entries,
700 entry_keys,
701 entry_last_used,
702 max_cached_slot,
703 miss_streak,
704 frame_misses,
705 ..
706 } = self;
707 slots.fill(EMPTY_POSITIONED_RUN_SLOT);
708 glyph_slab.clear();
709 entries.clear();
710 entry_keys.clear();
711 entry_last_used.clear();
712 *max_cached_slot = 0;
713 *miss_streak = 0;
714 *frame_misses = 0;
715 }
716
717 pub(crate) fn begin_frame(&mut self) {
723 let Self {
724 miss_streak,
725 frame_misses,
726 ..
727 } = self;
728 if *frame_misses < 8 {
729 *miss_streak = 0;
730 }
731 *frame_misses = 0;
732 }
733
734 #[inline(always)]
744 #[must_use]
745 pub(crate) fn is_streaming(&self) -> bool {
746 let Self { miss_streak, .. } = self;
747 *miss_streak >= 64
748 }
749
750 #[inline(always)]
756 pub(crate) fn record_streaming_miss(&mut self) {
757 let Self {
758 cache_misses,
759 miss_streak,
760 frame_misses,
761 ..
762 } = self;
763 *cache_misses = cache_misses.wrapping_add(1);
764 *miss_streak = miss_streak.saturating_add(1);
765 *frame_misses = frame_misses.saturating_add(1);
766 }
767
768 fn ensure_initialized(&mut self) {
774 let Self {
775 slots,
776 glyph_slab,
777 entries,
778 entry_keys,
779 entry_last_used,
780 evict_keep,
781 evict_slab_scratch,
782 ..
783 } = self;
784 if slots.is_empty() {
785 slots.resize(POSITIONED_RUN_CACHE_SLOTS, EMPTY_POSITIONED_RUN_SLOT);
786 entries.reserve_exact(POSITIONED_RUN_CACHE_LIMIT);
787 entry_keys.reserve_exact(POSITIONED_RUN_CACHE_LIMIT);
788 entry_last_used.reserve_exact(POSITIONED_RUN_CACHE_LIMIT);
789 glyph_slab.reserve_exact(POSITIONED_RUN_GLYPH_SLAB_CAP);
790 evict_keep.reserve_exact(POSITIONED_RUN_CACHE_LIMIT);
791 evict_slab_scratch.reserve_exact(POSITIONED_RUN_GLYPH_SLAB_CAP);
792 }
793 }
794
795 pub(crate) fn sync_atlas_epoch(&mut self, atlas: &GlyphAtlas) {
802 let evictions: u64 = atlas.get_evictions();
803 let font_rev: u64 = atlas.get_font_chain_revision();
804 let atlas_len: usize = atlas.len();
805 let needs_clear: bool = {
806 let Self {
807 entries,
808 atlas_evictions,
809 font_chain_revision,
810 max_cached_slot,
811 ..
812 } = self;
813 !entries.is_empty()
814 && (*atlas_evictions != evictions
815 || *font_chain_revision != font_rev
816 || (*max_cached_slot as usize) >= atlas_len)
817 };
818 if needs_clear {
819 self.clear();
820 }
821 let Self {
822 atlas_evictions,
823 font_chain_revision,
824 ..
825 } = self;
826 *atlas_evictions = evictions;
827 *font_chain_revision = font_rev;
828 }
829
830 #[must_use]
840 pub(crate) fn stats(&self) -> (u64, u64, usize) {
841 let Self {
842 cache_hits,
843 cache_misses,
844 entries,
845 ..
846 } = self;
847 (*cache_hits, *cache_misses, entries.len())
848 }
849
850 #[inline(always)]
863 #[must_use]
864 fn slot_start(key_hash: u64, width_bits: u32, phys_scale_milli: u32, mask: usize) -> usize {
865 let packed: u64 = (width_bits as u64) | ((phys_scale_milli as u64) << 32);
866 let mixed: u64 = (key_hash ^ packed).wrapping_mul(FX_HASH_K64);
867 ((mixed ^ (mixed >> 32)) as usize) & mask
868 }
869
870 fn compact_lru_to(&mut self, target_count: usize, target_glyphs: usize) {
878 let Self {
879 slots,
880 glyph_slab,
881 entries,
882 entry_keys,
883 entry_last_used,
884 evict_keep,
885 evict_slab_scratch,
886 max_cached_slot,
887 evictions,
888 ..
889 } = self;
890 let count: usize = entries.len();
891 if count == 0 {
892 return;
893 }
894 let mut min_tick: u64 = u64::MAX;
895 let mut max_tick: u64 = 0;
896 for &tick in entry_last_used.iter().take(count) {
897 min_tick = min_tick.min(tick);
898 max_tick = max_tick.max(tick);
899 }
900 let mut cutoff: u64 = max_tick.saturating_sub(target_count as u64);
901 let mut kept_est: usize = 0;
902 let mut kept_glyphs_est: usize = 0;
903 for idx in 0..count {
904 if entry_last_used[idx] > cutoff {
905 kept_est += 1;
906 kept_glyphs_est = kept_glyphs_est.saturating_add(entries[idx].glyph_len as usize);
907 }
908 }
909 if kept_est < target_count / 2 && max_tick > min_tick {
910 let span: u64 = max_tick.saturating_sub(min_tick);
911 cutoff = min_tick.saturating_add((span.saturating_mul(3)) / 4);
912 kept_est = 0;
913 kept_glyphs_est = 0;
914 for idx in 0..count {
915 if entry_last_used[idx] > cutoff {
916 kept_est += 1;
917 kept_glyphs_est =
918 kept_glyphs_est.saturating_add(entries[idx].glyph_len as usize);
919 }
920 }
921 }
922 let _: (usize, usize) = (kept_est, kept_glyphs_est);
923 evict_keep.clear();
924 evict_keep.resize(count, false);
925 let mut kept_count: usize = 0;
926 let mut kept_glyphs: usize = 0;
927 for idx in (0..count).rev() {
928 if entry_last_used[idx] > cutoff {
929 let g_len: usize = entries[idx].glyph_len as usize;
930 if kept_count < target_count && kept_glyphs.saturating_add(g_len) <= target_glyphs {
931 evict_keep[idx] = true;
932 kept_count += 1;
933 kept_glyphs = kept_glyphs.saturating_add(g_len);
934 }
935 }
936 }
937 let evicted_now: usize = count.saturating_sub(kept_count);
938 if evicted_now == 0 {
939 return;
940 }
941 evict_slab_scratch.clear();
942 let mut write_idx: usize = 0;
943 let mut next_max_slot: u32 = 0;
944 for (read_idx, &kept) in evict_keep.iter().enumerate() {
945 if kept {
946 let mut entry: CachedPositionedGlyphRun = entries[read_idx];
947 let old_s: usize = entry.glyph_start as usize;
948 let old_e: usize = old_s.saturating_add(entry.glyph_len as usize);
949 let new_start: u32 = evict_slab_scratch.len() as u32;
950 if old_e <= glyph_slab.len() {
951 evict_slab_scratch.extend_from_slice(&glyph_slab[old_s..old_e]);
952 }
953 entry.glyph_start = new_start;
954 entries[write_idx] = entry;
955 if write_idx != read_idx {
956 entry_keys[write_idx] = entry_keys[read_idx];
957 entry_last_used[write_idx] = entry_last_used[read_idx];
958 }
959 next_max_slot = next_max_slot.max(entry.max_glyph_slot);
960 write_idx += 1;
961 }
962 }
963 entries.truncate(write_idx);
964 entry_keys.truncate(write_idx);
965 entry_last_used.truncate(write_idx);
966 swap(glyph_slab, evict_slab_scratch);
967 evict_slab_scratch.clear();
968 *max_cached_slot = next_max_slot;
969 *evictions = evictions.saturating_add(evicted_now as u64);
970 slots.fill(EMPTY_POSITIONED_RUN_SLOT);
971 if !slots.is_empty() {
972 let mask: usize = slots.len() - 1;
973 for (slot_entry_idx, &(kh, wb, sm)) in entry_keys.iter().enumerate() {
974 let mut idx: usize = Self::slot_start(kh, wb, sm, mask);
975 while slots[idx].entry_idx != u32::MAX {
976 idx = (idx + 1) & mask;
977 }
978 slots[idx] = PositionedGlyphRunSlot {
979 key_hash: kh,
980 width_bits: wb,
981 phys_scale_milli: sm,
982 entry_idx: slot_entry_idx as u32,
983 };
984 }
985 }
986 }
987
988 pub(crate) fn evict_lru_if_needed(&mut self) {
994 let (count, slab_len): (usize, usize) = {
995 let Self {
996 entries,
997 glyph_slab,
998 ..
999 } = self;
1000 (entries.len(), glyph_slab.len())
1001 };
1002 let slab_trigger: usize =
1003 POSITIONED_RUN_GLYPH_SLAB_CAP.saturating_sub(POSITIONED_RUN_MAX_TEXT_LEN);
1004 if count < POSITIONED_RUN_CACHE_LIMIT && slab_len <= slab_trigger {
1005 return;
1006 }
1007 let target_count: usize = POSITIONED_RUN_CACHE_LIMIT / 4;
1008 let target_glyphs: usize = POSITIONED_RUN_GLYPH_SLAB_CAP / 4;
1009 self.compact_lru_to(target_count, target_glyphs);
1010 }
1011
1012 pub(crate) fn lookup(
1025 &mut self,
1026 key_hash: u64,
1027 width_bits: u32,
1028 phys_scale_milli: u32,
1029 ) -> Option<(CachedPositionedGlyphRun, &[PositionedGlyph])> {
1030 let Self {
1031 slots,
1032 glyph_slab,
1033 entries,
1034 entry_last_used,
1035 lru_clock,
1036 cache_hits,
1037 miss_streak,
1038 ..
1039 } = self;
1040 if slots.is_empty() {
1041 return None;
1042 }
1043 let mask: usize = slots.len() - 1;
1044 let mut idx: usize = Self::slot_start(key_hash, width_bits, phys_scale_milli, mask);
1045 loop {
1046 let slot: PositionedGlyphRunSlot = slots[idx];
1047 if slot.entry_idx == u32::MAX {
1048 return None;
1049 }
1050 if slot.key_hash == key_hash
1051 && slot.width_bits == width_bits
1052 && slot.phys_scale_milli == phys_scale_milli
1053 {
1054 *cache_hits = cache_hits.wrapping_add(1);
1055 *miss_streak = 0;
1056 *lru_clock = lru_clock.wrapping_add(1);
1057 if let Some(tick) = entry_last_used.get_mut(slot.entry_idx as usize) {
1058 *tick = *lru_clock;
1059 }
1060 let run: CachedPositionedGlyphRun = *entries.get(slot.entry_idx as usize)?;
1061 let g_s: usize = run.glyph_start as usize;
1062 let g_e: usize = g_s.saturating_add(run.glyph_len as usize);
1063 let slice: &[PositionedGlyph] = glyph_slab.get(g_s..g_e)?;
1064 return Some((run, slice));
1065 }
1066 idx = (idx + 1) & mask;
1067 }
1068 }
1069
1070 pub(crate) fn insert_with<CallbackFn>(
1083 &mut self,
1084 key: (u64, u32, u32),
1085 max_glyphs: usize,
1086 build_fn: CallbackFn,
1087 ) -> (CachedPositionedGlyphRun, &[PositionedGlyph])
1088 where
1089 CallbackFn: FnOnce(&mut Vec<PositionedGlyph>) -> (bool, u32),
1090 {
1091 self.ensure_initialized();
1092 let needs_evict: bool = {
1093 let Self {
1094 entries,
1095 glyph_slab,
1096 ..
1097 } = self;
1098 entries.len() >= POSITIONED_RUN_CACHE_LIMIT
1099 || glyph_slab.len().saturating_add(max_glyphs) > POSITIONED_RUN_GLYPH_SLAB_CAP
1100 };
1101 if needs_evict {
1102 let target_count: usize = POSITIONED_RUN_CACHE_LIMIT / 4;
1103 let target_glyphs: usize = POSITIONED_RUN_GLYPH_SLAB_CAP
1104 .saturating_sub(max_glyphs.max(POSITIONED_RUN_MAX_TEXT_LEN))
1105 .min(POSITIONED_RUN_GLYPH_SLAB_CAP / 4);
1106 self.compact_lru_to(target_count, target_glyphs);
1107 }
1108 let (key_hash, width_bits, phys_scale_milli): (u64, u32, u32) = key;
1109 let Self {
1110 slots,
1111 glyph_slab,
1112 entries,
1113 entry_keys,
1114 entry_last_used,
1115 lru_clock,
1116 max_cached_slot,
1117 cache_misses,
1118 miss_streak,
1119 frame_misses,
1120 ..
1121 } = self;
1122 let glyph_start: usize = glyph_slab.len();
1123 let (has_fractional_x, max_glyph_slot): (bool, u32) = build_fn(glyph_slab);
1124 let glyph_end: usize = glyph_slab.len();
1125 let run: CachedPositionedGlyphRun = CachedPositionedGlyphRun {
1126 glyph_start: glyph_start as u32,
1127 glyph_len: (glyph_end.saturating_sub(glyph_start)) as u32,
1128 has_fractional_x,
1129 max_glyph_slot,
1130 };
1131 *cache_misses = cache_misses.wrapping_add(1);
1132 *miss_streak = miss_streak.saturating_add(1);
1133 *frame_misses = frame_misses.saturating_add(1);
1134 *lru_clock = lru_clock.wrapping_add(1);
1135 *max_cached_slot = (*max_cached_slot).max(max_glyph_slot);
1136 let entry_idx: u32 = entries.len() as u32;
1137 entries.push(run);
1138 entry_keys.push((key_hash, width_bits, phys_scale_milli));
1139 entry_last_used.push(*lru_clock);
1140 let mask: usize = slots.len() - 1;
1141 let mut idx: usize = Self::slot_start(key_hash, width_bits, phys_scale_milli, mask);
1142 while slots[idx].entry_idx != u32::MAX {
1143 idx = (idx + 1) & mask;
1144 }
1145 slots[idx] = PositionedGlyphRunSlot {
1146 key_hash,
1147 width_bits,
1148 phys_scale_milli,
1149 entry_idx,
1150 };
1151 (run, &glyph_slab[glyph_start..glyph_end])
1152 }
1153}
1154
1155impl CornerMaskCache {
1157 #[must_use]
1167 pub(crate) fn len(&self) -> usize {
1168 let Self { entries } = self;
1169 entries.len()
1170 }
1171
1172 #[must_use]
1182 pub(crate) fn entries(&self) -> &[CachedCornerMask] {
1183 let Self { entries } = self;
1184 entries.as_slice()
1185 }
1186
1187 pub(crate) fn clear(&mut self) {
1193 let Self { entries } = self;
1194 entries.clear();
1195 }
1196
1197 #[must_use]
1209 fn build_quadrant(radius: f32, quadrant: u8, aa_enabled: bool) -> CachedCornerMask {
1210 let dim: usize = (radius + 1.0).ceil().max(1.0) as usize;
1211 let dim_f: f32 = dim as f32;
1212 let half_extent: f32 = dim_f + 64.0;
1213 let cx_lim: f32 = half_extent - radius;
1214 let r_in: f32 = radius - 1.0;
1215 let r_in_sq: f32 = r_in * r_in;
1216 let r_out: f32 = radius + 1.0;
1217 let r_out_sq: f32 = r_out * r_out;
1218 let r_sq: f32 = radius * radius;
1219 let mut cov: Vec<u8> = vec![16; dim * dim];
1220 let mut row_spans: Vec<CornerMaskRowSpan> = Vec::with_capacity(dim);
1221 let is_left: bool = quadrant == 0 || quadrant == 3;
1222 let is_top: bool = quadrant == 0 || quadrant == 1;
1223 for my in 0..dim {
1224 let py: f32 = if is_top {
1225 (my as f32) + 0.5 - half_extent
1226 } else {
1227 (my as f32) + 0.5 + (half_extent - dim_f)
1228 };
1229 let qy: f32 = py.abs() - cx_lim;
1230 let row_off: usize = my * dim;
1231 for mx in 0..dim {
1232 let px: f32 = if is_left {
1233 (mx as f32) + 0.5 - half_extent
1234 } else {
1235 (mx as f32) + 0.5 + (half_extent - dim_f)
1236 };
1237 let qx: f32 = px.abs() - cx_lim;
1238 let hits: u8 = if qx <= 0.0 || qy <= 0.0 {
1239 let dist: f32 = qx.max(qy) - radius;
1240 if dist <= -1.0 {
1241 16
1242 } else if dist >= 1.0 {
1243 0
1244 } else if !aa_enabled {
1245 if dist <= 0.0 { 16 } else { 0 }
1246 } else {
1247 let char_item: f32 = rounded_box_supersampled_coverage(
1248 px,
1249 py,
1250 half_extent,
1251 half_extent,
1252 radius,
1253 0.0,
1254 )
1255 .0;
1256 (char_item * 16.0).round() as u8
1257 }
1258 } else {
1259 let d_sq: f32 = qx * qx + qy * qy;
1260 if r_in >= 0.0 && d_sq <= r_in_sq {
1261 16
1262 } else if d_sq >= r_out_sq {
1263 0
1264 } else if !aa_enabled {
1265 if d_sq <= r_sq { 16 } else { 0 }
1266 } else {
1267 let color_item: f32 = rounded_box_supersampled_coverage(
1268 px,
1269 py,
1270 half_extent,
1271 half_extent,
1272 radius,
1273 0.0,
1274 )
1275 .0;
1276 (color_item * 16.0).round() as u8
1277 }
1278 };
1279 cov[row_off + mx] = hits;
1280 }
1281 let row_slice: &[u8] = &cov[row_off..row_off + dim];
1282 let span: CornerMaskRowSpan = if is_left {
1283 let dirty_end: usize = row_slice
1284 .iter()
1285 .rposition(|&cell_item: &u8| cell_item < 16)
1286 .map(|idx: usize| idx + 1)
1287 .unwrap_or(0);
1288 let ext_end: usize = row_slice
1289 .iter()
1290 .take(dirty_end)
1291 .take_while(|&&component_val: &&u8| component_val == 0)
1292 .count();
1293 CornerMaskRowSpan {
1294 ext_start: 0,
1295 ext_end: ext_end as u16,
1296 aa_start: ext_end as u16,
1297 aa_end: dirty_end as u16,
1298 dirty_start: 0,
1299 dirty_end: dirty_end as u16,
1300 }
1301 } else {
1302 let dirty_start: usize = row_slice
1303 .iter()
1304 .position(|&char_item_primary: &u8| char_item_primary < 16)
1305 .unwrap_or(dim);
1306 let trailing_zeros: usize = row_slice[dirty_start..]
1307 .iter()
1308 .rev()
1309 .take_while(|&&char_item_secondary: &&u8| char_item_secondary == 0)
1310 .count();
1311 let ext_start: usize = dim - trailing_zeros;
1312 CornerMaskRowSpan {
1313 ext_start: ext_start as u16,
1314 ext_end: dim as u16,
1315 aa_start: dirty_start as u16,
1316 aa_end: ext_start.max(dirty_start) as u16,
1317 dirty_start: dirty_start as u16,
1318 dirty_end: dim as u16,
1319 }
1320 };
1321 row_spans.push(span);
1322 }
1323 CachedCornerMask {
1324 radius_bits: radius.to_bits(),
1325 quadrant,
1326 aa_enabled,
1327 dim: dim as u16,
1328 cov,
1329 row_spans,
1330 }
1331 }
1332
1333 fn get_or_build(&mut self, radius: f32, quadrant: u8, aa_enabled: bool) -> u32 {
1346 let bits: u32 = radius.to_bits();
1347 let Self { entries } = self;
1348 for (idx, entry) in entries.iter().enumerate() {
1349 if entry.radius_bits == bits
1350 && entry.quadrant == quadrant
1351 && entry.aa_enabled == aa_enabled
1352 {
1353 return idx as u32;
1354 }
1355 }
1356 let idx: u32 = entries.len() as u32;
1357 entries.push(Self::build_quadrant(radius, quadrant, aa_enabled));
1358 idx
1359 }
1360
1361 pub(crate) fn resolve_quadrants(
1374 &mut self,
1375 rect: Rect,
1376 radius: CornerRadius,
1377 aa: AntialiasingMode,
1378 ) -> [u32; 4] {
1379 let mut ids: [u32; 4] = [u32::MAX; 4];
1380 let half_w: f32 = rect.get_width() * 0.5;
1381 let half_h: f32 = rect.get_height() * 0.5;
1382 let max_r: f32 = half_w.min(half_h).max(0.0);
1383 if max_r <= 0.25 {
1384 return ids;
1385 }
1386 let x0: f32 = rect.get_x();
1387 let y0: f32 = rect.get_y();
1388 let x1: f32 = rect.right();
1389 let y1: f32 = rect.bottom();
1390 if (x0 - x0.round()).abs() > 1e-4
1391 || (y0 - y0.round()).abs() > 1e-4
1392 || (x1 - x1.round()).abs() > 1e-4
1393 || (y1 - y1.round()).abs() > 1e-4
1394 {
1395 return ids;
1396 }
1397 let aa_enabled: bool = aa != AntialiasingMode::None;
1398 let radii: [f32; 4] = [
1399 radius.get_top_left().min(max_r),
1400 radius.get_top_right().min(max_r),
1401 radius.get_bottom_right().min(max_r),
1402 radius.get_bottom_left().min(max_r),
1403 ];
1404 for (query_val, red_val) in radii.into_iter().enumerate() {
1405 if red_val > 0.25 && red_val + 1.5 < half_w && red_val + 1.5 < half_h {
1406 let dim: u32 = (red_val + 1.0).ceil() as u32;
1407 if dim > 0 && dim <= CORNER_MASK_MAX_DIM {
1408 ids[query_val] = self.get_or_build(red_val, query_val as u8, aa_enabled);
1409 }
1410 }
1411 }
1412 ids
1413 }
1414}
1415
1416impl SoftwareRenderer {
1418 #[must_use]
1430 pub fn with_config(width: u32, height: u32, config: RenderConfig) -> Self {
1431 Self::with_font_provider(width, height, config, NativeSystemFont::deterministic())
1432 }
1433
1434 #[must_use]
1447 pub fn with_font_provider(
1448 width: u32,
1449 height: u32,
1450 config: RenderConfig,
1451 font_provider: NativeSystemFont,
1452 ) -> Self {
1453 let allocate_cpu_fb: bool = !config.get_direct_gpu_present() && width > 0 && height > 0;
1454 let (
1455 framebuffer,
1456 text_layout_cache,
1457 clip_cap,
1458 prepped_cap,
1459 rc_cap,
1460 glyph_cap,
1461 line_cap,
1462 caret_cap,
1463 ): (
1464 Option<Framebuffer>,
1465 TextLayoutCache,
1466 usize,
1467 usize,
1468 usize,
1469 usize,
1470 usize,
1471 usize,
1472 ) = if allocate_cpu_fb {
1473 (
1474 Some(Framebuffer::allocate(width, height)),
1475 TextLayoutCache::with_capacity(TEXT_LAYOUT_CACHE_SLOTS),
1476 16,
1477 256,
1478 32,
1479 2048,
1480 64,
1481 8,
1482 )
1483 } else {
1484 (None, TextLayoutCache::default(), 0, 0, 0, 0, 0, 0)
1485 };
1486 let cull_cap: usize = if allocate_cpu_fb { 256 } else { 0 };
1487 let sentinel_cap: usize = if allocate_cpu_fb { 32 } else { 0 };
1488 let (hash_tile_cap, hash_dirty_cap): (usize, usize) = if allocate_cpu_fb {
1489 let tx: usize = width.div_ceil(FB_HASH_TILE_W) as usize;
1490 let ty: usize = height.div_ceil(FB_HASH_TILE_H) as usize;
1491 let total: usize = tx.saturating_mul(ty);
1492 (total, total.div_ceil(64))
1493 } else {
1494 (0, 0)
1495 };
1496 Self {
1497 framebuffer,
1498 glyph_atlas: GlyphAtlas::default(),
1499 font_provider,
1500 measurer: DeterministicTextMeasurer,
1501 text_layout_cache,
1502 positioned_glyph_run_cache: PositionedGlyphRunCache::default(),
1503 blur_horiz_scratch: Vec::new(),
1504 cull_keep_scratch: Vec::with_capacity(cull_cap),
1505 cull_compacted_scratch: Vec::with_capacity(cull_cap),
1506 cull_sentinels_scratch: Vec::with_capacity(sentinel_cap),
1507 clip_stack: Vec::with_capacity(clip_cap),
1508 rounded_clip_stack: Vec::with_capacity(clip_cap),
1509 antialiasing: config.get_antialiasing(),
1510 tile_size: config.get_tile_size().max(16),
1511 base_cache_width: 0,
1512 base_cache_height: 0,
1513 base_cache_hash: 0,
1514 prev_base_hash: 0,
1515 base_cache_pixels: Vec::new(),
1516 prepped_scratch: Vec::with_capacity(prepped_cap),
1517 rounded_clips_scratch: Vec::with_capacity(rc_cap),
1518 positioned_glyphs_scratch: Vec::with_capacity(glyph_cap),
1519 line_glyphs_scratch: Vec::with_capacity(line_cap),
1520 caret_rects_scratch: Vec::with_capacity(caret_cap),
1521 corner_mask_cache: CornerMaskCache::default(),
1522 prev_portal_bounds: None,
1523 prev_portal_scrim: None,
1524 prepped_bounds: None,
1525 prepped_fg_bounds: None,
1526 clip_scope_scratch: Vec::with_capacity(clip_cap),
1527 cached_scrim_color: None,
1528 cached_scrim_luts: None,
1529 serial_dispatches: 0,
1530 parallel_dispatches: 0,
1531 culled_occluded_commands: 0,
1532 adaptive_parallel_threshold_pixels: ADAPTIVE_PARALLEL_DEFAULT_PIXELS,
1533 adaptive_threshold_override: 0,
1534 last_serial_us: 0,
1535 last_parallel_us: 0,
1536 rendered_frames: 0,
1537 telemetry_enabled: false,
1538 high_frequency_active: false,
1539 hash_tiles: Vec::with_capacity(hash_tile_cap),
1540 hash_dirty_bits: Vec::with_capacity(hash_dirty_cap),
1541 hash_tiles_w: 0,
1542 hash_tiles_h: 0,
1543 hash_tiles_valid: false,
1544 }
1545 }
1546
1547 fn mark_hash_dirty_rect(&mut self, rect: Rect) {
1554 let Self {
1555 hash_dirty_bits,
1556 hash_tiles_w,
1557 hash_tiles_h,
1558 hash_tiles_valid,
1559 ..
1560 } = self;
1561 if !*hash_tiles_valid || *hash_tiles_w == 0 || *hash_tiles_h == 0 {
1562 return;
1563 }
1564 let width_val: u32 = *hash_tiles_w;
1565 let height_val: u32 = *hash_tiles_h;
1566 let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(width_val);
1567 let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(height_val);
1568 let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(width_val);
1569 let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(height_val);
1570 if x0 >= x1 || y0 >= y1 {
1571 return;
1572 }
1573 let tiles_x: u32 = width_val.div_ceil(FB_HASH_TILE_W);
1574 let tx0: u32 = x0 / FB_HASH_TILE_W;
1575 let tx1: u32 = (x1 - 1) / FB_HASH_TILE_W;
1576 let ty0: u32 = y0 / FB_HASH_TILE_H;
1577 let ty1: u32 = (y1 - 1) / FB_HASH_TILE_H;
1578 for ty in ty0..=ty1 {
1579 let row_base: usize = (ty as usize).saturating_mul(tiles_x as usize);
1580 for tx in tx0..=tx1 {
1581 let tile_idx: usize = row_base.saturating_add(tx as usize);
1582 let word_idx: usize = tile_idx >> 6;
1583 let bit_mask: u64 = 1_u64 << (tile_idx & 63);
1584 if let Some(word) = hash_dirty_bits.get_mut(word_idx) {
1585 *word |= bit_mask;
1586 }
1587 }
1588 }
1589 }
1590
1591 #[must_use]
1601 pub(crate) fn incremental_framebuffer_hash(&mut self) -> u64 {
1602 let Self {
1603 framebuffer,
1604 hash_tiles,
1605 hash_dirty_bits,
1606 hash_tiles_w,
1607 hash_tiles_h,
1608 hash_tiles_valid,
1609 ..
1610 } = self;
1611 let Some(frame_pixels) = framebuffer.as_ref() else {
1612 return EMPTY_FRAMEBUFFER.fnv1a_hash();
1613 };
1614 let width_val: u32 = frame_pixels.get_width();
1615 let height_val: u32 = frame_pixels.get_height();
1616 if width_val == 0 || height_val == 0 || frame_pixels.get_pixels().is_empty() {
1617 *hash_tiles_valid = false;
1618 return frame_pixels.fnv1a_hash();
1619 }
1620 let tiles_x: u32 = width_val.div_ceil(FB_HASH_TILE_W);
1621 let tiles_y: u32 = height_val.div_ceil(FB_HASH_TILE_H);
1622 let total_tiles: usize = (tiles_x as usize).saturating_mul(tiles_y as usize);
1623 if !*hash_tiles_valid
1624 || *hash_tiles_w != width_val
1625 || *hash_tiles_h != height_val
1626 || hash_tiles.len() != total_tiles
1627 {
1628 hash_tiles.resize(total_tiles, 0);
1629 let dirty_words: usize = total_tiles.div_ceil(64);
1630 hash_dirty_bits.clear();
1631 hash_dirty_bits.resize(dirty_words, 0);
1632 #[cfg(not(target_arch = "wasm32"))]
1633 let hashed_parallel: bool = if total_tiles >= 256
1634 && let Some(pool) = try_get_ready_band_worker_pool()
1635 {
1636 pool.execute_hash_tiles(frame_pixels, hash_tiles.as_mut_slice(), None, tiles_x);
1637 true
1638 } else {
1639 false
1640 };
1641 #[cfg(target_arch = "wasm32")]
1642 let hashed_parallel: bool = false;
1643 if !hashed_parallel {
1644 let mut idx: usize = 0;
1645 for ty in 0..tiles_y {
1646 for tx in 0..tiles_x {
1647 hash_tiles[idx] = frame_pixels.hash_tile_fnv1a(tx, ty);
1648 idx += 1;
1649 }
1650 }
1651 }
1652 *hash_tiles_w = width_val;
1653 *hash_tiles_h = height_val;
1654 *hash_tiles_valid = true;
1655 return Framebuffer::fold_tile_hashes(width_val, height_val, hash_tiles.as_slice());
1656 }
1657 let mut dirty_tile_count: usize = 0;
1658 for &word in hash_dirty_bits.iter() {
1659 dirty_tile_count = dirty_tile_count.saturating_add(word.count_ones() as usize);
1660 }
1661 #[cfg(not(target_arch = "wasm32"))]
1662 if dirty_tile_count >= 256
1663 && let Some(pool) = try_get_ready_band_worker_pool()
1664 {
1665 pool.execute_hash_tiles(
1666 frame_pixels,
1667 hash_tiles.as_mut_slice(),
1668 Some(hash_dirty_bits.as_slice()),
1669 tiles_x,
1670 );
1671 hash_dirty_bits.fill(0);
1672 return Framebuffer::fold_tile_hashes(width_val, height_val, hash_tiles.as_slice());
1673 }
1674 for (word_idx, word_ref) in hash_dirty_bits.iter_mut().enumerate() {
1675 let mut word: u64 = *word_ref;
1676 if word == 0 {
1677 continue;
1678 }
1679 *word_ref = 0;
1680 let base_tile: usize = word_idx << 6;
1681 while word != 0 {
1682 let bit: usize = word.trailing_zeros() as usize;
1683 word &= word - 1;
1684 let tile_idx: usize = base_tile.saturating_add(bit);
1685 if tile_idx < total_tiles {
1686 let ty: u32 = (tile_idx / (tiles_x as usize)) as u32;
1687 let tx: u32 = (tile_idx % (tiles_x as usize)) as u32;
1688 hash_tiles[tile_idx] = frame_pixels.hash_tile_fnv1a(tx, ty);
1689 }
1690 }
1691 }
1692 Framebuffer::fold_tile_hashes(width_val, height_val, hash_tiles.as_slice())
1693 }
1694
1695 #[must_use]
1705 pub fn get_framebuffer(&self) -> &Framebuffer {
1706 self.framebuffer.as_ref().unwrap_or(&EMPTY_FRAMEBUFFER)
1707 }
1708
1709 #[must_use]
1719 pub fn framebuffer_opt(&self) -> Option<&Framebuffer> {
1720 let Self { framebuffer, .. } = self;
1721 framebuffer.as_ref()
1722 }
1723
1724 #[must_use]
1734 pub fn allocated_framebuffer_bytes(&self) -> usize {
1735 let Self { framebuffer, .. } = self;
1736 framebuffer.as_ref().map_or(0, Framebuffer::allocated_bytes)
1737 }
1738
1739 pub fn release_framebuffer(&mut self) {
1745 let Self {
1746 framebuffer,
1747 base_cache_width,
1748 base_cache_height,
1749 base_cache_hash,
1750 prev_base_hash,
1751 base_cache_pixels,
1752 prev_portal_bounds,
1753 prev_portal_scrim,
1754 ..
1755 } = self;
1756 *framebuffer = None;
1757 *base_cache_width = 0;
1758 *base_cache_height = 0;
1759 *base_cache_hash = 0;
1760 *prev_base_hash = 0;
1761 base_cache_pixels.clear();
1762 base_cache_pixels.shrink_to_fit();
1763 *prev_portal_bounds = None;
1764 *prev_portal_scrim = None;
1765 }
1766
1767 pub(crate) fn ensure_framebuffer(
1779 &mut self,
1780 width: u32,
1781 height: u32,
1782 ) -> (&mut Framebuffer, bool) {
1783 let Self { framebuffer, .. } = self;
1784 let mut resized: bool = false;
1785 let target_framebuffer: &mut Framebuffer = framebuffer.get_or_insert_with(|| {
1786 resized = true;
1787 Framebuffer::allocate(width, height)
1788 });
1789 if !resized {
1790 resized = target_framebuffer.resize(width, height);
1791 }
1792 (target_framebuffer, resized)
1793 }
1794
1795 pub fn set_font_provider(&mut self, font_provider: NativeSystemFont) -> &mut Self {
1806 let Self {
1807 font_provider: slot,
1808 positioned_glyph_run_cache,
1809 ..
1810 } = self;
1811 *slot = font_provider;
1812 positioned_glyph_run_cache.clear();
1813 self
1814 }
1815
1816 pub fn set_high_frequency_active(&mut self, active: bool) {
1823 let Self {
1824 high_frequency_active,
1825 ..
1826 } = self;
1827 *high_frequency_active = active;
1828 set_band_worker_spin_active(active);
1829 }
1830
1831 #[must_use]
1841 pub fn blur_scratch_capacity(&self) -> usize {
1842 self.get_blur_horiz_scratch().capacity()
1843 }
1844
1845 #[must_use]
1855 pub fn positioned_glyph_run_cache_stats(&self) -> (u64, u64, usize) {
1856 self.get_positioned_glyph_run_cache().stats()
1857 }
1858
1859 fn finish_frame_render(&mut self) {
1865 let was_first_frame: bool = self.get_rendered_frames() == 0;
1866 let Self {
1867 rendered_frames, ..
1868 } = self;
1869 *rendered_frames = rendered_frames.saturating_add(1);
1870 if was_first_frame {
1871 warm_band_worker_pool_async();
1872 }
1873 }
1874
1875 pub fn set_adaptive_parallel_threshold(&mut self, min_pixels: Option<usize>) {
1882 let Self {
1883 adaptive_threshold_override,
1884 adaptive_parallel_threshold_pixels,
1885 ..
1886 } = self;
1887 match min_pixels {
1888 Some(px) => {
1889 let clamped: usize = px.max(1);
1890 *adaptive_threshold_override = clamped;
1891 *adaptive_parallel_threshold_pixels = clamped;
1892 }
1893 None => {
1894 *adaptive_threshold_override = 0;
1895 *adaptive_parallel_threshold_pixels = ADAPTIVE_PARALLEL_DEFAULT_PIXELS;
1896 }
1897 }
1898 }
1899
1900 #[must_use]
1910 pub fn adaptive_parallel_threshold(&self) -> usize {
1911 if self.get_adaptive_threshold_override() > 0 {
1912 self.get_adaptive_threshold_override()
1913 } else if self.get_adaptive_parallel_threshold_pixels() > 0 {
1914 self.get_adaptive_parallel_threshold_pixels()
1915 } else {
1916 ADAPTIVE_PARALLEL_DEFAULT_PIXELS
1917 }
1918 }
1919
1920 #[must_use]
1932 fn detect_full_viewport_scrim(
1933 commands: &[DrawCommand],
1934 prepped: &[PreppedCommand],
1935 dims: (u32, u32, f32),
1936 ) -> Option<Color> {
1937 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
1938 let first: &PreppedCommand = prepped.first()?;
1939 if first.get_cmd_index() == usize::MAX || first.get_rounded_clip_len() != 0 {
1940 return None;
1941 }
1942 let clip: Rect = first.get_active_clip();
1943 let fw: f32 = phys_w as f32;
1944 let fh: f32 = phys_h as f32;
1945 if clip.get_x() > 0.0 || clip.get_y() > 0.0 || clip.right() < fw || clip.bottom() < fh {
1946 return None;
1947 }
1948 if let DrawCommand::FillRoundedRect {
1949 rect,
1950 color,
1951 radius,
1952 border,
1953 } = &commands[first.get_cmd_index()]
1954 {
1955 let sa: u8 = color.get_alpha();
1956 if sa > 0 && sa < 255 && radius.max_radius() <= 0.0 && border.get_width() <= 0.0 {
1957 let phys: Rect = snap_physical_rect(*rect, scale);
1958 if phys.get_x() <= 0.0
1959 && phys.get_y() <= 0.0
1960 && phys.right() >= fw
1961 && phys.bottom() >= fh
1962 {
1963 return Some(*color);
1964 }
1965 }
1966 }
1967 None
1968 }
1969
1970 #[must_use]
1982 fn rect_pixel_area(rect: Rect, phys_w: u32, phys_h: u32) -> usize {
1983 let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(phys_w);
1984 let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(phys_h);
1985 let x1: u32 = (rect.right().ceil().max(0.0) as u32).clamp(x0, phys_w);
1986 let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).clamp(y0, phys_h);
1987 ((x1 - x0) as usize).saturating_mul((y1 - y0) as usize)
1988 }
1989
1990 pub fn render(&mut self, display_list: &DisplayList, damage: DamageRegion) -> (usize, usize) {
2002 let scale: f32 = display_list.get_scale_factor().max(0.5);
2003 let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
2004 let phys_h: u32 =
2005 ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
2006 let (_, resized): (&mut Framebuffer, bool) = self.ensure_framebuffer(phys_w, phys_h);
2007 if resized {
2008 self.set_base_cache_hash(0);
2009 self.set_prev_base_hash(0);
2010 self.set_base_cache_width(0);
2011 self.set_base_cache_height(0);
2012 self.set_prev_portal_bounds(None);
2013 self.set_prev_portal_scrim(None);
2014 let Self {
2015 hash_tiles_valid, ..
2016 } = self;
2017 *hash_tiles_valid = false;
2018 }
2019 let effective_damage: DamageRegion = if resized {
2020 DamageRegion::full()
2021 } else {
2022 damage
2023 };
2024 let (norm_rects, norm_count): ([Rect; 8], usize) =
2025 effective_damage.normalized_rects(phys_w, phys_h);
2026 if norm_count == 0 {
2027 return (0, 0);
2028 }
2029 let tile_sz: u32 = self.get_tile_size().max(16);
2030 let commands: &[DrawCommand] = display_list.get_commands().as_slice();
2031 let split: usize = display_list.get_portal_split_index().min(commands.len());
2032 let has_portals: bool = split > 0 && split < commands.len();
2033 if norm_count > 1 {
2034 let mut sum_area: usize = 0;
2035 for sub in norm_rects.iter().take(norm_count) {
2036 sum_area = sum_area.saturating_add(Self::rect_pixel_area(*sub, phys_w, phys_h));
2037 }
2038 let union_area: usize = effective_damage
2039 .resolve(phys_w, phys_h)
2040 .map_or(0, |rect_bounds: Rect| {
2041 Self::rect_pixel_area(rect_bounds, phys_w, phys_h)
2042 });
2043 if sum_area.saturating_mul(4) < union_area.saturating_mul(3) {
2044 if !has_portals {
2045 self.set_base_cache_hash(0);
2046 self.set_prev_base_hash(0);
2047 }
2048 self.set_prev_portal_bounds(None);
2049 self.set_prev_portal_scrim(None);
2050 let mut total_tiles: usize = 0;
2051 let mut total_shaded: usize = 0;
2052 for sub_clip in norm_rects.iter().take(norm_count).copied() {
2053 let tx: usize =
2054 ((sub_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
2055 let ty: usize =
2056 ((sub_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
2057 total_tiles = total_tiles.saturating_add(tx.saturating_mul(ty));
2058 self.prepare_frame_range(
2059 display_list,
2060 (0, commands.len()),
2061 sub_clip,
2062 (phys_w, phys_h, scale),
2063 );
2064 let shaded: usize = self.execute_prepared_bands(
2065 commands,
2066 sub_clip,
2067 (phys_w, phys_h, scale),
2068 (false, None, 0),
2069 );
2070 self.mark_hash_dirty_rect(sub_clip);
2071 total_shaded = total_shaded.saturating_add(shaded);
2072 }
2073 self.finish_frame_render();
2074 return (total_tiles, total_shaded);
2075 }
2076 }
2077 let root_clip: Rect = if norm_count == 1 {
2078 norm_rects[0]
2079 } else {
2080 let Some(resolved) = effective_damage.resolve(phys_w, phys_h) else {
2081 return (0, 0);
2082 };
2083 resolved
2084 };
2085 let tiles_x: usize = ((root_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
2086 let tiles_y: usize = ((root_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
2087 let tiles_updated: usize = tiles_x.saturating_mul(tiles_y);
2088 let is_full_frame: bool = root_clip.get_x() <= 0.0
2089 && root_clip.get_y() <= 0.0
2090 && root_clip.get_width() >= (phys_w as f32)
2091 && root_clip.get_height() >= (phys_h as f32);
2092 if has_portals && is_full_frame {
2093 let base_hash: u64 = display_list.base_layer_hash();
2094 let fb_len: usize = self
2095 .framebuffer_opt()
2096 .map_or(0, |target_framebuffer: &Framebuffer| {
2097 target_framebuffer.get_pixels().len()
2098 });
2099 let cache_hit: bool = base_hash != 0
2100 && self.get_base_cache_hash() == base_hash
2101 && self.get_base_cache_width() == phys_w
2102 && self.get_base_cache_height() == phys_h
2103 && self.get_base_cache_pixels().len() == fb_len;
2104 if cache_hit {
2105 self.prepare_frame_range(
2106 display_list,
2107 (split, commands.len()),
2108 root_clip,
2109 (phys_w, phys_h, scale),
2110 );
2111 let cur_scrim: Option<Color> = Self::detect_full_viewport_scrim(
2112 commands,
2113 self.get_prepped_scratch().as_slice(),
2114 (phys_w, phys_h, scale),
2115 );
2116 let (cur_fg_bounds, prev_scrim, prev_bounds): (
2117 Option<Rect>,
2118 Option<Color>,
2119 Option<Rect>,
2120 ) = {
2121 let Self {
2122 prepped_fg_bounds,
2123 prepped_bounds,
2124 prev_portal_scrim,
2125 prev_portal_bounds,
2126 ..
2127 } = self;
2128 let fg: Option<Rect> = if cur_scrim.is_some() {
2129 *prepped_fg_bounds
2130 } else {
2131 *prepped_bounds
2132 };
2133 (fg, *prev_portal_scrim, *prev_portal_bounds)
2134 };
2135 self.set_prev_portal_scrim(cur_scrim);
2136 self.set_prev_portal_bounds(cur_fg_bounds);
2137 let prepped_start: usize = usize::from(cur_scrim.is_some());
2138 let (portal_rects, portal_count): ([Rect; 8], usize) = if cur_scrim == prev_scrim {
2139 let mut portal_damage: DamageRegion = DamageRegion::default();
2140 if let Some(prev_r) = prev_bounds {
2141 portal_damage.add_rect(prev_r);
2142 }
2143 if let Some(cur_r) = cur_fg_bounds {
2144 portal_damage.add_rect(cur_r);
2145 }
2146 portal_damage.normalized_rects(phys_w, phys_h)
2147 } else {
2148 let mut full_arr: [Rect; 8] = [Rect::default(); 8];
2149 full_arr[0] = root_clip;
2150 (full_arr, 1)
2151 };
2152 if portal_count == 0 {
2153 self.finish_frame_render();
2154 return (tiles_updated, 1);
2155 }
2156 let mut total_portal_shaded: usize = 0;
2157 for dirty_clip in portal_rects.iter().take(portal_count).copied() {
2158 let scrim_shaded: usize = if cur_scrim.is_some() {
2159 Self::rect_pixel_area(dirty_clip, phys_w, phys_h)
2160 } else {
2161 0
2162 };
2163 let band_shaded: usize = self.execute_prepared_bands(
2164 commands,
2165 dirty_clip,
2166 (phys_w, phys_h, scale),
2167 (true, cur_scrim, prepped_start),
2168 );
2169 self.mark_hash_dirty_rect(dirty_clip);
2170 total_portal_shaded = total_portal_shaded
2171 .saturating_add(scrim_shaded)
2172 .saturating_add(band_shaded);
2173 }
2174 self.finish_frame_render();
2175 return (tiles_updated, total_portal_shaded.max(1));
2176 }
2177 self.prepare_frame_range(display_list, (0, split), root_clip, (phys_w, phys_h, scale));
2178 let base_shaded: usize = self.execute_prepared_bands(
2179 commands,
2180 root_clip,
2181 (phys_w, phys_h, scale),
2182 (false, None, 0),
2183 );
2184 let base_stable: bool = base_hash != 0 && self.get_prev_base_hash() == base_hash;
2185 self.set_prev_base_hash(base_hash);
2186 if base_stable {
2187 let Self {
2188 framebuffer,
2189 base_cache_pixels,
2190 base_cache_width,
2191 base_cache_height,
2192 base_cache_hash,
2193 ..
2194 } = self;
2195 if let Some(frame_pixels) = framebuffer.as_ref() {
2196 let src_pixels: &[u8] = frame_pixels.get_pixels().as_slice();
2197 if base_cache_pixels.len() != src_pixels.len() {
2198 base_cache_pixels.resize(src_pixels.len(), 0);
2199 }
2200 base_cache_pixels.copy_from_slice(src_pixels);
2201 *base_cache_width = phys_w;
2202 *base_cache_height = phys_h;
2203 *base_cache_hash = base_hash;
2204 }
2205 }
2206 self.prepare_frame_range(
2207 display_list,
2208 (split, commands.len()),
2209 root_clip,
2210 (phys_w, phys_h, scale),
2211 );
2212 let cur_scrim: Option<Color> = Self::detect_full_viewport_scrim(
2213 commands,
2214 self.get_prepped_scratch().as_slice(),
2215 (phys_w, phys_h, scale),
2216 );
2217 let cur_fg_bounds: Option<Rect> = {
2218 let Self {
2219 prepped_fg_bounds,
2220 prepped_bounds,
2221 ..
2222 } = self;
2223 if cur_scrim.is_some() {
2224 *prepped_fg_bounds
2225 } else {
2226 *prepped_bounds
2227 }
2228 };
2229 self.set_prev_portal_scrim(cur_scrim);
2230 self.set_prev_portal_bounds(cur_fg_bounds);
2231 let portal_shaded: usize = self.execute_prepared_bands(
2232 commands,
2233 root_clip,
2234 (phys_w, phys_h, scale),
2235 (false, None, 0),
2236 );
2237 let Self {
2238 hash_tiles_valid, ..
2239 } = self;
2240 *hash_tiles_valid = false;
2241 self.finish_frame_render();
2242 return (tiles_updated, base_shaded.saturating_add(portal_shaded));
2243 }
2244 if !has_portals {
2245 self.set_base_cache_hash(0);
2246 self.set_prev_base_hash(0);
2247 }
2248 self.set_prev_portal_bounds(None);
2249 self.set_prev_portal_scrim(None);
2250 self.prepare_frame_range(
2251 display_list,
2252 (0, commands.len()),
2253 root_clip,
2254 (phys_w, phys_h, scale),
2255 );
2256 let pixels_shaded: usize = self.execute_prepared_bands(
2257 commands,
2258 root_clip,
2259 (phys_w, phys_h, scale),
2260 (false, None, 0),
2261 );
2262 if is_full_frame {
2263 let Self {
2264 hash_tiles_valid, ..
2265 } = self;
2266 *hash_tiles_valid = false;
2267 } else {
2268 self.mark_hash_dirty_rect(root_clip);
2269 }
2270 self.finish_frame_render();
2271 (tiles_updated, pixels_shaded)
2272 }
2273
2274 fn execute_prepared_slice(
2290 framebuffer: &mut Framebuffer,
2291 clip_spec: (u32, u32, u32, u32, u32),
2292 cmd_slices: (&[DrawCommand], &[PreppedCommand]),
2293 aux: BandAuxSlices<'_>,
2294 atlas_ref: &GlyphAtlas,
2295 render_opts: (f32, AntialiasingMode, BandRestoreSpec<'_>, bool, bool),
2296 dispatch_state: (&mut u64, &mut u64, &mut usize, usize, &mut u64, &mut u64),
2297 ) -> usize {
2298 let (phys_w, clip_x0, clip_y0, clip_x1, clip_y1): (u32, u32, u32, u32, u32) = clip_spec;
2299 let (commands, prepped_slice): (&[DrawCommand], &[PreppedCommand]) = cmd_slices;
2300 let (scale, aa, restore_spec, allow_parallel, telemetry_enabled): (
2301 f32,
2302 AntialiasingMode,
2303 BandRestoreSpec<'_>,
2304 bool,
2305 bool,
2306 ) = render_opts;
2307 let (
2308 serial_dispatches,
2309 parallel_dispatches,
2310 adaptive_parallel_threshold_pixels,
2311 adaptive_threshold_override,
2312 last_serial_us,
2313 last_parallel_us,
2314 ): (&mut u64, &mut u64, &mut usize, usize, &mut u64, &mut u64) = dispatch_state;
2315 let restore_base_cache: bool = restore_spec.base_pixels.is_some();
2316 if prepped_slice.is_empty() && !restore_base_cache {
2317 return 0;
2318 }
2319 let clip_w: u32 = clip_x1.saturating_sub(clip_x0);
2320 let clip_h: u32 = clip_y1.saturating_sub(clip_y0);
2321 if clip_w == 0 || clip_h == 0 {
2322 return 0;
2323 }
2324 #[cfg(not(target_arch = "wasm32"))]
2325 let mut has_backdrop_blur: bool = false;
2326 #[cfg(not(target_arch = "wasm32"))]
2327 let mut complexity_bonus: usize = aux.rounded_clips.len().saturating_mul(16_384);
2328 #[cfg(not(target_arch = "wasm32"))]
2329 for item in prepped_slice.iter() {
2330 let idx: usize = item.get_cmd_index();
2331 if idx != usize::MAX {
2332 match &commands[idx] {
2333 DrawCommand::BackdropBlur { .. } => {
2334 has_backdrop_blur = true;
2335 break;
2336 }
2337 DrawCommand::BoxShadow { .. } => {
2338 complexity_bonus = complexity_bonus.saturating_add(12_288);
2339 }
2340 DrawCommand::TextRun { .. } => {
2341 complexity_bonus = complexity_bonus.saturating_add(4_096);
2342 }
2343 _ => {}
2344 }
2345 }
2346 }
2347 #[cfg(not(target_arch = "wasm32"))]
2348 let pixel_area: usize = (clip_w as usize).saturating_mul(clip_h as usize);
2349 #[cfg(not(target_arch = "wasm32"))]
2350 let active_min_pixels: usize = if adaptive_threshold_override > 0 {
2351 adaptive_threshold_override
2352 } else if *adaptive_parallel_threshold_pixels > 0 {
2353 *adaptive_parallel_threshold_pixels
2354 } else {
2355 ADAPTIVE_PARALLEL_DEFAULT_PIXELS
2356 };
2357 #[cfg(not(target_arch = "wasm32"))]
2358 {
2359 let many_cmds: bool =
2360 prepped_slice.len() >= BAND_DISPATCH_MIN_CMDS || restore_base_cache;
2361 let large_area: bool = pixel_area >= BAND_DISPATCH_MIN_PIXELS.saturating_mul(2);
2362 let enough_work: bool = many_cmds || large_area;
2363 if allow_parallel
2364 && !has_backdrop_blur
2365 && pixel_area >= active_min_pixels.max(SMALL_DAMAGE_SINGLE_THREAD_PIXELS)
2366 && clip_h >= BAND_DISPATCH_MIN_HEIGHT
2367 && enough_work
2368 {
2369 let effective_area: usize = pixel_area.saturating_add(complexity_bonus);
2370 if effective_area >= BAND_DISPATCH_MIN_PIXELS.saturating_mul(2)
2371 && let Some(pool) = try_get_ready_band_worker_pool()
2372 {
2373 let desired_threads: usize =
2374 (effective_area / BAND_DISPATCH_MIN_PIXELS).clamp(1, pool.total_threads());
2375 let strip_count: usize = (desired_threads.saturating_mul(2))
2376 .min((clip_h / 24) as usize)
2377 .max(1);
2378 if strip_count > 1 && desired_threads > 1 {
2379 *parallel_dispatches = parallel_dispatches.wrapping_add(1);
2380 let t0_opt: Option<Instant> = if telemetry_enabled {
2381 Some(Instant::now())
2382 } else {
2383 None
2384 };
2385 let shaded: usize = pool.execute(
2386 framebuffer,
2387 (
2388 clip_y0,
2389 clip_y1,
2390 strip_count,
2391 desired_threads.saturating_sub(1),
2392 ),
2393 (commands, prepped_slice),
2394 aux,
2395 atlas_ref,
2396 (scale, aa, restore_spec),
2397 );
2398 if let Some(t0) = t0_opt {
2399 let elapsed_us: u64 = t0.elapsed().as_micros() as u64;
2400 *last_parallel_us = elapsed_us;
2401 if adaptive_threshold_override == 0 && elapsed_us < 280 {
2402 let step: usize = (active_min_pixels / 2).max(16_384);
2403 *adaptive_parallel_threshold_pixels = active_min_pixels
2404 .saturating_add(step)
2405 .min(ADAPTIVE_PARALLEL_MAX_PIXELS);
2406 }
2407 }
2408 return shaded;
2409 }
2410 }
2411 }
2412 }
2413 #[cfg(target_arch = "wasm32")]
2414 {
2415 let _: bool = allow_parallel;
2416 let _: bool = telemetry_enabled;
2417 let _: &mut u64 = parallel_dispatches;
2418 let _: &mut usize = adaptive_parallel_threshold_pixels;
2419 let _: usize = adaptive_threshold_override;
2420 let _: &mut u64 = last_serial_us;
2421 let _: &mut u64 = last_parallel_us;
2422 }
2423 *serial_dispatches = serial_dispatches.wrapping_add(1);
2424 #[cfg(not(target_arch = "wasm32"))]
2425 let serial_t0_opt: Option<Instant> = if telemetry_enabled {
2426 Some(Instant::now())
2427 } else {
2428 None
2429 };
2430 let row_stride: usize = (phys_w as usize) * 4;
2431 let start_byte: usize = (clip_y0 as usize) * row_stride;
2432 let end_byte: usize = (clip_y1 as usize) * row_stride;
2433 let Some(slice) = framebuffer.get_mut_pixels().get_mut(start_byte..end_byte) else {
2434 return 0;
2435 };
2436 if let Some(src_buf) = restore_spec.base_pixels
2437 && let Some(src_slice) = src_buf.get(start_byte..end_byte)
2438 {
2439 restore_band_strip(
2440 slice,
2441 src_slice,
2442 (
2443 row_stride,
2444 clip_h as usize,
2445 (restore_spec.x0 as usize) * 4,
2446 (restore_spec.x1.saturating_sub(restore_spec.x0) as usize) * 4,
2447 ),
2448 restore_spec.scrim_luts,
2449 );
2450 }
2451 let mut band: PixelBand<'_> = PixelBand {
2452 width: phys_w,
2453 y_offset: clip_y0,
2454 height: clip_h,
2455 pixels: slice,
2456 };
2457 let shaded_serial: usize = Self::render_band(
2458 &mut band,
2459 commands,
2460 prepped_slice,
2461 aux,
2462 atlas_ref,
2463 (scale, aa),
2464 );
2465 #[cfg(not(target_arch = "wasm32"))]
2466 if let Some(serial_t0) = serial_t0_opt {
2467 let elapsed_us: u64 = serial_t0.elapsed().as_micros() as u64;
2468 *last_serial_us = elapsed_us;
2469 if adaptive_threshold_override == 0 && !has_backdrop_blur {
2470 if pixel_area >= ADAPTIVE_PARALLEL_MIN_PIXELS && elapsed_us > 900 {
2471 let step: usize = (active_min_pixels / 8).max(4096);
2472 *adaptive_parallel_threshold_pixels = active_min_pixels
2473 .saturating_sub(step)
2474 .max(ADAPTIVE_PARALLEL_MIN_PIXELS);
2475 } else if pixel_area >= ADAPTIVE_PARALLEL_MIN_PIXELS && elapsed_us < 220 {
2476 let step: usize = (active_min_pixels / 16).max(2048);
2477 *adaptive_parallel_threshold_pixels = active_min_pixels
2478 .saturating_add(step)
2479 .min(ADAPTIVE_PARALLEL_MAX_PIXELS);
2480 }
2481 }
2482 }
2483 shaded_serial
2484 }
2485
2486 fn execute_backdrop_blur_separable(
2502 framebuffer: &mut Framebuffer,
2503 blur_horiz_scratch: &mut Vec<[u8; 4]>,
2504 rect: Rect,
2505 radius: CornerRadius,
2506 blur_and_scale: (f32, f32),
2507 clip: Rect,
2508 dispatch_opts: (bool, &mut u64, &mut u64),
2509 ) -> usize {
2510 let (blur_radius, scale): (f32, f32) = blur_and_scale;
2511 let (allow_parallel, serial_dispatches, parallel_dispatches): (bool, &mut u64, &mut u64) =
2512 dispatch_opts;
2513 let phys_rect: Rect = snap_physical_rect(rect, scale);
2514 let phys_radius: CornerRadius = Self::scale_radius(radius, scale);
2515 let phys_blur: f32 = (blur_radius * scale).clamp(0.5, 48.0);
2516 let Some(vis) = phys_rect.intersect(clip) else {
2517 return 0;
2518 };
2519 let fb_w: u32 = framebuffer.get_width();
2520 let fb_h: u32 = framebuffer.get_height();
2521 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
2522 let x1: u32 = (vis.right().ceil().max(0.0) as u32).clamp(x0, fb_w);
2523 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(fb_h);
2524 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(y0, fb_h);
2525 if x0 >= x1 || y0 >= y1 {
2526 return 0;
2527 }
2528 let rad: u32 = (phys_blur * 0.5).round().clamp(1.0, 24.0) as u32;
2529 let clip_x0: u32 = (clip.get_x().floor().max(0.0) as u32).min(fb_w);
2530 let clip_x1: u32 = (clip.right().ceil().max(0.0) as u32).clamp(clip_x0, fb_w);
2531 let clip_y0: u32 = (clip.get_y().floor().max(0.0) as u32).min(fb_h);
2532 let clip_y1: u32 = (clip.bottom().ceil().max(0.0) as u32).clamp(clip_y0, fb_h);
2533 let sx0: u32 = x0.saturating_sub(rad).max(clip_x0);
2534 let sx1: u32 = x1.saturating_add(rad).min(clip_x1);
2535 let sy0: u32 = y0.saturating_sub(rad).max(clip_y0);
2536 let sy1: u32 = y1.saturating_add(rad).min(clip_y1);
2537 let stroke_width: u32 = sx1.saturating_sub(sx0);
2538 let sh: u32 = sy1.saturating_sub(sy0);
2539 let needed: usize = (stroke_width as usize).saturating_mul(sh as usize);
2540 if needed == 0 {
2541 return 0;
2542 }
2543 if blur_horiz_scratch.len() < needed {
2544 blur_horiz_scratch.resize(needed, [0, 0, 0, 0]);
2545 }
2546 let fb_pixels: &mut [u8] = framebuffer.get_mut_pixels().as_mut_slice();
2547 let desc: BlurPassDesc = BlurPassDesc {
2548 #[cfg(not(target_arch = "wasm32"))]
2549 fb_ptr: fb_pixels.as_mut_ptr() as usize,
2550 #[cfg(not(target_arch = "wasm32"))]
2551 fb_len: fb_pixels.len(),
2552 fb_w,
2553 #[cfg(not(target_arch = "wasm32"))]
2554 horiz_ptr: blur_horiz_scratch.as_mut_ptr() as usize,
2555 #[cfg(not(target_arch = "wasm32"))]
2556 horiz_len: needed,
2557 sx0,
2558 sy0,
2559 sw: stroke_width,
2560 sh,
2561 x0,
2562 x1,
2563 y0,
2564 y1,
2565 rad,
2566 inv_win_q24: blur_inv_window_q24(rad),
2567 has_radius: phys_radius.max_radius() > 0.25,
2568 rect: phys_rect,
2569 radius: phys_radius,
2570 #[cfg(not(target_arch = "wasm32"))]
2571 strip_count: 1,
2572 #[cfg(not(target_arch = "wasm32"))]
2573 strip_rows: 1,
2574 };
2575 #[cfg(not(target_arch = "wasm32"))]
2576 {
2577 let blur_h: u32 = y1.saturating_sub(y0);
2578 let blur_area: usize =
2579 ((x1.saturating_sub(x0)) as usize).saturating_mul(blur_h as usize);
2580 if allow_parallel
2581 && blur_area >= BLUR_PARALLEL_MIN_PIXELS
2582 && blur_h >= BLUR_PARALLEL_MIN_HEIGHT
2583 && let Some(pool) = try_get_ready_band_worker_pool()
2584 {
2585 let desired_threads: usize =
2586 (blur_area / BLUR_PARALLEL_MIN_PIXELS).clamp(1, pool.total_threads());
2587 if desired_threads > 1 {
2588 let mut pass_desc: BlurPassDesc = desc;
2589 let h_strips: usize = desired_threads
2590 .saturating_mul(2)
2591 .min((sh / 8).max(1) as usize)
2592 .max(1);
2593 if h_strips > 1 {
2594 pass_desc.strip_count = h_strips;
2595 pass_desc.strip_rows = sh.div_ceil(h_strips as u32).max(1);
2596 let _: usize = pool.execute_blur_pass(
2597 BandJobKind::BlurHoriz,
2598 pass_desc,
2599 desired_threads.saturating_sub(1),
2600 );
2601 } else {
2602 blur_horiz_strip(&pass_desc, 0, sh as usize);
2603 }
2604 let v_strips: usize = desired_threads
2605 .saturating_mul(2)
2606 .min((blur_h / 8).max(1) as usize)
2607 .max(1);
2608 if v_strips > 1 {
2609 pass_desc.strip_count = v_strips;
2610 pass_desc.strip_rows = blur_h.div_ceil(v_strips as u32).max(1);
2611 *parallel_dispatches = parallel_dispatches.wrapping_add(1);
2612 return pool.execute_blur_pass(
2613 BandJobKind::BlurVert,
2614 pass_desc,
2615 desired_threads.saturating_sub(1),
2616 );
2617 }
2618 *serial_dispatches = serial_dispatches.wrapping_add(1);
2619 return blur_vert_strip(&pass_desc, y0, y1);
2620 }
2621 }
2622 }
2623 #[cfg(target_arch = "wasm32")]
2624 {
2625 let _: bool = allow_parallel;
2626 let _: &mut u64 = parallel_dispatches;
2627 }
2628 *serial_dispatches = serial_dispatches.wrapping_add(1);
2629 let horiz_slice: &mut [[u8; 4]] = &mut blur_horiz_scratch[..needed];
2630 blur_horiz_strip_slices(fb_pixels, horiz_slice, &desc, (0, sh as usize));
2631 let fb_stride: usize = (fb_w as usize) * 4;
2632 let strip_start: usize = (y0 as usize).saturating_mul(fb_stride);
2633 let strip_end: usize = (y1 as usize).saturating_mul(fb_stride);
2634 let Some(fb_strip) = fb_pixels.get_mut(strip_start..strip_end) else {
2635 return 0;
2636 };
2637 blur_vert_strip_slices(fb_strip, horiz_slice, &desc, (y0, y1))
2638 }
2639
2640 fn execute_prepared_bands(
2654 &mut self,
2655 commands: &[DrawCommand],
2656 root_clip: Rect,
2657 dims: (u32, u32, f32),
2658 restore_opts: (bool, Option<Color>, usize),
2659 ) -> usize {
2660 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
2661 let (restore_base_cache, scrim_color, prepped_start): (bool, Option<Color>, usize) =
2662 restore_opts;
2663 let clip_x0: u32 = (root_clip.get_x().floor().max(0.0) as u32).min(phys_w);
2664 let clip_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
2665 let clip_x1: u32 = (root_clip.right().ceil().max(0.0) as u32).clamp(clip_x0, phys_w);
2666 let clip_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).clamp(clip_y0, phys_h);
2667 let clip_w: u32 = clip_x1.saturating_sub(clip_x0);
2668 let clip_h: u32 = clip_y1.saturating_sub(clip_y0);
2669 if clip_w == 0 || clip_h == 0 {
2670 return 0;
2671 }
2672 let Self {
2673 framebuffer,
2674 glyph_atlas,
2675 blur_horiz_scratch,
2676 base_cache_pixels,
2677 prepped_scratch,
2678 positioned_glyphs_scratch,
2679 caret_rects_scratch,
2680 rounded_clips_scratch,
2681 corner_mask_cache,
2682 antialiasing,
2683 cached_scrim_color,
2684 cached_scrim_luts,
2685 serial_dispatches,
2686 parallel_dispatches,
2687 adaptive_parallel_threshold_pixels,
2688 adaptive_threshold_override,
2689 last_serial_us,
2690 last_parallel_us,
2691 rendered_frames,
2692 telemetry_enabled,
2693 ..
2694 } = self;
2695 let Some(frame_pixels) = framebuffer.as_mut() else {
2696 return 0;
2697 };
2698 let aa: AntialiasingMode = *antialiasing;
2699 let allow_parallel: bool = *rendered_frames > 0;
2700 let record_timing: bool = *telemetry_enabled;
2701 let threshold_override: usize = *adaptive_threshold_override;
2702 let clamped_start: usize = prepped_start.min(prepped_scratch.len());
2703 let prepped_slice: &[PreppedCommand] = &prepped_scratch.as_slice()[clamped_start..];
2704 if prepped_slice.is_empty() && !restore_base_cache {
2705 return 0;
2706 }
2707 let scrim_luts_ref: Option<&[[u8; 256]; 4]> = if let Some(scrim_c) = scrim_color {
2708 if *cached_scrim_color != Some(scrim_c) || cached_scrim_luts.is_none() {
2709 *cached_scrim_color = Some(scrim_c);
2710 *cached_scrim_luts = Some(Box::new(build_linear_blend_luts(scrim_c)));
2711 }
2712 cached_scrim_luts.as_deref()
2713 } else {
2714 None
2715 };
2716 let aux: BandAuxSlices<'_> = BandAuxSlices {
2717 positioned_glyphs: positioned_glyphs_scratch.as_slice(),
2718 caret_rects: caret_rects_scratch.as_slice(),
2719 rounded_clips: rounded_clips_scratch.as_slice(),
2720 corner_masks: corner_mask_cache.entries(),
2721 };
2722 let atlas_ref: &GlyphAtlas = glyph_atlas;
2723 let restore_spec: BandRestoreSpec<'_> = BandRestoreSpec {
2724 base_pixels: if restore_base_cache {
2725 Some(base_cache_pixels.as_slice())
2726 } else {
2727 None
2728 },
2729 x0: clip_x0,
2730 x1: clip_x1,
2731 scrim_luts: scrim_luts_ref,
2732 };
2733 let empty_restore: BandRestoreSpec<'_> = BandRestoreSpec {
2734 base_pixels: None,
2735 x0: clip_x0,
2736 x1: clip_x1,
2737 scrim_luts: None,
2738 };
2739 let mut total_shaded: usize = 0;
2740 let mut chunk_start: usize = 0;
2741 let mut pending_restore: bool = restore_base_cache;
2742 for (pos, item) in prepped_slice.iter().enumerate() {
2743 let cmd_idx: usize = item.get_cmd_index();
2744 if cmd_idx != usize::MAX
2745 && item.get_rounded_clip_len() == 0
2746 && let DrawCommand::BackdropBlur {
2747 rect,
2748 radius,
2749 blur_radius,
2750 } = &commands[cmd_idx]
2751 {
2752 if chunk_start < pos || pending_restore {
2753 let spec: BandRestoreSpec<'_> = if pending_restore {
2754 restore_spec
2755 } else {
2756 empty_restore
2757 };
2758 total_shaded = total_shaded.saturating_add(Self::execute_prepared_slice(
2759 frame_pixels,
2760 (phys_w, clip_x0, clip_y0, clip_x1, clip_y1),
2761 (commands, &prepped_slice[chunk_start..pos]),
2762 aux,
2763 atlas_ref,
2764 (scale, aa, spec, allow_parallel, record_timing),
2765 (
2766 serial_dispatches,
2767 parallel_dispatches,
2768 adaptive_parallel_threshold_pixels,
2769 threshold_override,
2770 last_serial_us,
2771 last_parallel_us,
2772 ),
2773 ));
2774 pending_restore = false;
2775 }
2776 if let Some(blur_clip) = item.get_active_clip().intersect(root_clip) {
2777 total_shaded =
2778 total_shaded.saturating_add(Self::execute_backdrop_blur_separable(
2779 frame_pixels,
2780 blur_horiz_scratch,
2781 *rect,
2782 *radius,
2783 (*blur_radius, scale),
2784 blur_clip,
2785 (allow_parallel, serial_dispatches, parallel_dispatches),
2786 ));
2787 }
2788 chunk_start = pos + 1;
2789 }
2790 }
2791 if chunk_start < prepped_slice.len() || pending_restore {
2792 let spec: BandRestoreSpec<'_> = if pending_restore {
2793 restore_spec
2794 } else {
2795 empty_restore
2796 };
2797 total_shaded = total_shaded.saturating_add(Self::execute_prepared_slice(
2798 frame_pixels,
2799 (phys_w, clip_x0, clip_y0, clip_x1, clip_y1),
2800 (commands, &prepped_slice[chunk_start..]),
2801 aux,
2802 atlas_ref,
2803 (scale, aa, spec, allow_parallel, record_timing),
2804 (
2805 serial_dispatches,
2806 parallel_dispatches,
2807 adaptive_parallel_threshold_pixels,
2808 threshold_override,
2809 last_serial_us,
2810 last_parallel_us,
2811 ),
2812 ));
2813 }
2814 total_shaded
2815 }
2816
2817 fn prepare_frame_range(
2827 &mut self,
2828 display_list: &DisplayList,
2829 range: (usize, usize),
2830 root_clip: Rect,
2831 dims: (u32, u32, f32),
2832 ) {
2833 let (start_idx, end_idx): (usize, usize) = range;
2834 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
2835 let commands: &[DrawCommand] = display_list.get_commands().as_slice();
2836 let clamped_end: usize = end_idx.min(commands.len());
2837 let clamped_start: usize = start_idx.min(clamped_end);
2838 let Self {
2839 glyph_atlas,
2840 font_provider,
2841 measurer,
2842 text_layout_cache,
2843 positioned_glyph_run_cache,
2844 cull_keep_scratch,
2845 cull_compacted_scratch,
2846 cull_sentinels_scratch,
2847 clip_stack,
2848 rounded_clip_stack,
2849 prepped_scratch: prepped,
2850 rounded_clips_scratch: rounded_clips,
2851 positioned_glyphs_scratch: positioned_glyphs,
2852 line_glyphs_scratch: line_scratch,
2853 caret_rects_scratch: caret_rects,
2854 corner_mask_cache,
2855 prepped_bounds,
2856 prepped_fg_bounds,
2857 clip_scope_scratch: clip_scopes,
2858 antialiasing,
2859 culled_occluded_commands,
2860 ..
2861 } = self;
2862 let aa: AntialiasingMode = *antialiasing;
2863 prepped.clear();
2864 prepped.reserve(clamped_end - clamped_start);
2865 *prepped_bounds = None;
2866 *prepped_fg_bounds = None;
2867 rounded_clips.clear();
2868 positioned_glyphs.clear();
2869 caret_rects.clear();
2870 clip_stack.clear();
2871 clip_stack.push(root_clip);
2872 rounded_clip_stack.clear();
2873 rounded_clip_stack.push(None);
2874 let root_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
2875 let root_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
2876 clip_scopes.clear();
2877 clip_scopes.push((root_y0, root_y1, None));
2878 let mut empty_clip_depth: usize = 0;
2879 let mut has_first_cmd: bool = false;
2880 glyph_atlas.evict_if_over_budget();
2881 positioned_glyph_run_cache.sync_atlas_epoch(glyph_atlas);
2882 positioned_glyph_run_cache.begin_frame();
2883 glyph_atlas.set_slots_pinned(true);
2884 text_layout_cache.evict_lru_if_needed();
2885 positioned_glyph_run_cache.evict_lru_if_needed();
2886 if corner_mask_cache.len() > CORNER_MASK_CACHE_LIMIT {
2887 corner_mask_cache.clear();
2888 }
2889 for (offset, cmd) in commands[clamped_start..clamped_end].iter().enumerate() {
2890 if empty_clip_depth > 0 {
2891 match cmd {
2892 DrawCommand::PushClip(_) | DrawCommand::PushRoundedClip { .. } => {
2893 empty_clip_depth += 1;
2894 }
2895 DrawCommand::PopClip => {
2896 empty_clip_depth -= 1;
2897 }
2898 _ => {}
2899 }
2900 continue;
2901 }
2902 let cmd_index: usize = clamped_start + offset;
2903 let active_clip: Rect = clip_stack.last().copied().unwrap_or(root_clip);
2904 match cmd {
2905 DrawCommand::PushClip(rect) => {
2906 let phys: Rect = snap_physical_rect(*rect, scale);
2907 let Some(next) = active_clip.intersect(phys) else {
2908 empty_clip_depth = 1;
2909 continue;
2910 };
2911 let nx0: u32 = (next.get_x().floor().max(0.0) as u32).min(phys_w);
2912 let nx1: u32 = (next.right().ceil().max(0.0) as u32).min(phys_w);
2913 let ny0: u32 = (next.get_y().floor().max(0.0) as u32).min(phys_h);
2914 let ny1: u32 = (next.bottom().ceil().max(0.0) as u32).min(phys_h);
2915 if nx0 >= nx1 || ny0 >= ny1 {
2916 empty_clip_depth = 1;
2917 continue;
2918 }
2919 clip_stack.push(next);
2920 rounded_clip_stack.push(None);
2921 let (parent_y0, parent_y1, _): (u32, u32, Option<usize>) = clip_scopes
2922 .last()
2923 .copied()
2924 .unwrap_or((root_y0, root_y1, None));
2925 if ny0 > parent_y0 || ny1 < parent_y1 {
2926 let slot_idx: usize = prepped.len();
2927 prepped.push(PreppedCommand {
2928 cmd_index: usize::MAX,
2929 active_clip: next,
2930 y0: ny0,
2931 y1: ny1,
2932 opaque_cutout_h: Rect::default(),
2933 opaque_cutout_v: Rect::default(),
2934 glyph_run_start: 0,
2935 glyph_run_len: 0,
2936 caret_rect_idx: u32::MAX,
2937 rounded_clip_start: 0,
2938 rounded_clip_len: 0,
2939 skip_delta: 1,
2940 });
2941 clip_scopes.push((ny0, ny1, Some(slot_idx)));
2942 } else {
2943 clip_scopes.push((parent_y0, parent_y1, None));
2944 }
2945 }
2946 DrawCommand::PushRoundedClip { rect, radius } => {
2947 let phys: Rect = snap_physical_rect(*rect, scale);
2948 let Some(next) = active_clip.intersect(phys) else {
2949 empty_clip_depth = 1;
2950 continue;
2951 };
2952 let nx0: u32 = (next.get_x().floor().max(0.0) as u32).min(phys_w);
2953 let nx1: u32 = (next.right().ceil().max(0.0) as u32).min(phys_w);
2954 let ny0: u32 = (next.get_y().floor().max(0.0) as u32).min(phys_h);
2955 let ny1: u32 = (next.bottom().ceil().max(0.0) as u32).min(phys_h);
2956 if nx0 >= nx1 || ny0 >= ny1 {
2957 empty_clip_depth = 1;
2958 continue;
2959 }
2960 clip_stack.push(next);
2961 let phys_r: CornerRadius = Self::scale_radius(*radius, scale);
2962 if phys.get_width() > 0.0
2963 && phys.get_height() > 0.0
2964 && phys_r.max_radius() > 0.25
2965 {
2966 let corner_mask_ids: [u32; 4] =
2967 corner_mask_cache.resolve_quadrants(phys, phys_r, aa);
2968 rounded_clip_stack.push(Some(RoundedClipMask {
2969 rect: phys,
2970 radius: phys_r,
2971 corner_mask_ids,
2972 }));
2973 } else {
2974 rounded_clip_stack.push(None);
2975 }
2976 let (parent_y0, parent_y1, _): (u32, u32, Option<usize>) = clip_scopes
2977 .last()
2978 .copied()
2979 .unwrap_or((root_y0, root_y1, None));
2980 if ny0 > parent_y0 || ny1 < parent_y1 {
2981 let slot_idx: usize = prepped.len();
2982 prepped.push(PreppedCommand {
2983 cmd_index: usize::MAX,
2984 active_clip: next,
2985 y0: ny0,
2986 y1: ny1,
2987 opaque_cutout_h: Rect::default(),
2988 opaque_cutout_v: Rect::default(),
2989 glyph_run_start: 0,
2990 glyph_run_len: 0,
2991 caret_rect_idx: u32::MAX,
2992 rounded_clip_start: 0,
2993 rounded_clip_len: 0,
2994 skip_delta: 1,
2995 });
2996 clip_scopes.push((ny0, ny1, Some(slot_idx)));
2997 } else {
2998 clip_scopes.push((parent_y0, parent_y1, None));
2999 }
3000 }
3001 DrawCommand::PopClip => {
3002 if clip_stack.len() > 1 {
3003 clip_stack.pop();
3004 let _: Option<Option<RoundedClipMask>> = rounded_clip_stack.pop();
3005 if let Some((_, _, Some(slot_idx))) = clip_scopes.pop() {
3006 let span_len: usize = prepped.len().saturating_sub(slot_idx);
3007 if span_len <= 1 {
3008 prepped.truncate(slot_idx);
3009 } else if span_len == 2 {
3010 let only_cmd: PreppedCommand = prepped[slot_idx + 1];
3011 prepped[slot_idx] = only_cmd;
3012 let _: Option<PreppedCommand> = prepped.pop();
3013 } else {
3014 prepped[slot_idx].skip_delta = span_len as u32;
3015 }
3016 }
3017 }
3018 }
3019 DrawCommand::Clear(clear_color) => {
3020 let y0: u32 = (active_clip.get_y().floor().max(0.0) as u32).min(phys_h);
3021 let y1: u32 = (active_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
3022 if y0 < y1 {
3023 let (mut rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3024 rounded_clip_stack.as_slice(),
3025 rounded_clips,
3026 active_clip,
3027 );
3028 let covers_root: bool = active_clip.get_x() <= root_clip.get_x()
3029 && active_clip.get_y() <= root_clip.get_y()
3030 && active_clip.right() >= root_clip.right()
3031 && active_clip.bottom() >= root_clip.bottom();
3032 let no_open_sentinels: bool = clip_scopes
3033 .iter()
3034 .all(|&(_, _, slot): &(u32, u32, Option<usize>)| slot.is_none());
3035 if clamped_start == 0
3036 && !prepped.is_empty()
3037 && rc_len == 0
3038 && clear_color.get_alpha() == 255
3039 && covers_root
3040 && no_open_sentinels
3041 {
3042 prepped.clear();
3043 rounded_clips.clear();
3044 positioned_glyphs.clear();
3045 caret_rects.clear();
3046 *prepped_bounds = None;
3047 *prepped_fg_bounds = None;
3048 has_first_cmd = false;
3049 rc_start = 0;
3050 }
3051 if has_first_cmd {
3052 expand_opt_rect(prepped_fg_bounds, active_clip);
3053 }
3054 has_first_cmd = true;
3055 expand_opt_rect(prepped_bounds, active_clip);
3056 let (cut_h, cut_v): (Rect, Rect) = if rc_len == 0
3057 && cmd_index + 1 < clamped_end
3058 && clear_color.get_alpha() == 255
3059 {
3060 Self::resolve_opaque_clear_cutout(commands.get(cmd_index + 1), scale)
3061 } else {
3062 (Rect::default(), Rect::default())
3063 };
3064 prepped.push(PreppedCommand {
3065 cmd_index,
3066 active_clip,
3067 y0,
3068 y1,
3069 opaque_cutout_h: cut_h,
3070 opaque_cutout_v: cut_v,
3071 glyph_run_start: 0,
3072 glyph_run_len: 0,
3073 caret_rect_idx: u32::MAX,
3074 rounded_clip_start: rc_start,
3075 rounded_clip_len: rc_len,
3076 skip_delta: 0,
3077 });
3078 }
3079 }
3080 DrawCommand::FillRoundedRect {
3081 rect,
3082 color,
3083 radius,
3084 border,
3085 } => {
3086 let phys: Rect = snap_physical_rect(*rect, scale);
3087 if let Some(vis) = phys.intersect(active_clip) {
3088 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3089 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3090 if y0 < y1 {
3091 let (mut rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3092 rounded_clip_stack.as_slice(),
3093 rounded_clips,
3094 vis,
3095 );
3096 let no_border: bool =
3097 border.get_width() <= 0.0 || border.get_color().get_alpha() == 0;
3098 let covers_root: bool = vis.get_x() <= root_clip.get_x()
3099 && vis.get_y() <= root_clip.get_y()
3100 && vis.right() >= root_clip.right()
3101 && vis.bottom() >= root_clip.bottom();
3102 let no_open_sentinels: bool = clip_scopes
3103 .iter()
3104 .all(|&(_, _, slot): &(u32, u32, Option<usize>)| slot.is_none());
3105 if clamped_start == 0
3106 && !prepped.is_empty()
3107 && rc_len == 0
3108 && color.get_alpha() == 255
3109 && radius.max_radius() <= 0.0
3110 && no_border
3111 && covers_root
3112 && no_open_sentinels
3113 {
3114 prepped.clear();
3115 rounded_clips.clear();
3116 positioned_glyphs.clear();
3117 caret_rects.clear();
3118 *prepped_bounds = None;
3119 *prepped_fg_bounds = None;
3120 has_first_cmd = false;
3121 rc_start = 0;
3122 }
3123 if has_first_cmd {
3124 expand_opt_rect(prepped_fg_bounds, vis);
3125 }
3126 has_first_cmd = true;
3127 expand_opt_rect(prepped_bounds, vis);
3128 prepped.push(PreppedCommand {
3129 cmd_index,
3130 active_clip,
3131 y0,
3132 y1,
3133 opaque_cutout_h: Rect::default(),
3134 opaque_cutout_v: Rect::default(),
3135 glyph_run_start: 0,
3136 glyph_run_len: 0,
3137 caret_rect_idx: u32::MAX,
3138 rounded_clip_start: rc_start,
3139 rounded_clip_len: rc_len,
3140 skip_delta: 0,
3141 });
3142 }
3143 }
3144 }
3145 DrawCommand::LinearGradientRect { rect, .. }
3146 | DrawCommand::BackdropBlur { rect, .. }
3147 | DrawCommand::Image { rect, .. }
3148 | DrawCommand::SharedImage { rect, .. }
3149 | DrawCommand::SpriteRegion { rect, .. }
3150 | DrawCommand::ExternalSurface { rect, .. } => {
3151 let phys: Rect = snap_physical_rect(*rect, scale);
3152 if let Some(vis) = phys.intersect(active_clip) {
3153 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3154 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3155 if y0 < y1 {
3156 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3157 rounded_clip_stack.as_slice(),
3158 rounded_clips,
3159 vis,
3160 );
3161 if has_first_cmd {
3162 expand_opt_rect(prepped_fg_bounds, vis);
3163 }
3164 has_first_cmd = true;
3165 expand_opt_rect(prepped_bounds, vis);
3166 prepped.push(PreppedCommand {
3167 cmd_index,
3168 active_clip,
3169 y0,
3170 y1,
3171 opaque_cutout_h: Rect::default(),
3172 opaque_cutout_v: Rect::default(),
3173 glyph_run_start: 0,
3174 glyph_run_len: 0,
3175 caret_rect_idx: u32::MAX,
3176 rounded_clip_start: rc_start,
3177 rounded_clip_len: rc_len,
3178 skip_delta: 0,
3179 });
3180 }
3181 }
3182 }
3183 DrawCommand::BoxShadow { rect, shadow, .. } => {
3184 if shadow.get_color().get_alpha() == 0 {
3185 continue;
3186 }
3187 let spread: f32 = shadow.get_spread_radius() * scale;
3188 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
3189 let sigma: f32 = (blur * 0.5).max(0.75);
3190 let pad: f32 = (sigma * 3.0).ceil();
3191 let base_rect: Rect = snap_physical_rect(*rect, scale);
3192 let caster_rect: Rect = Rect::new(
3193 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
3194 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
3195 (base_rect.get_width() + spread * 2.0).max(1.0),
3196 (base_rect.get_height() + spread * 2.0).max(1.0),
3197 );
3198 let shadow_rect: Rect = Rect::new(
3199 caster_rect.get_x() - pad,
3200 caster_rect.get_y() - pad,
3201 caster_rect.get_width() + pad * 2.0,
3202 caster_rect.get_height() + pad * 2.0,
3203 );
3204 if let Some(vis) = shadow_rect.intersect(active_clip) {
3205 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3206 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3207 if y0 < y1 {
3208 let (cut_h, cut_v): (Rect, Rect) = Self::resolve_opaque_shadow_cutout(
3209 commands.get(cmd_index + 1),
3210 scale,
3211 );
3212 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3213 rounded_clip_stack.as_slice(),
3214 rounded_clips,
3215 vis,
3216 );
3217 if has_first_cmd {
3218 expand_opt_rect(prepped_fg_bounds, vis);
3219 }
3220 has_first_cmd = true;
3221 expand_opt_rect(prepped_bounds, vis);
3222 prepped.push(PreppedCommand {
3223 cmd_index,
3224 active_clip,
3225 y0,
3226 y1,
3227 opaque_cutout_h: cut_h,
3228 opaque_cutout_v: cut_v,
3229 glyph_run_start: 0,
3230 glyph_run_len: 0,
3231 caret_rect_idx: u32::MAX,
3232 rounded_clip_start: rc_start,
3233 rounded_clip_len: rc_len,
3234 skip_delta: 0,
3235 });
3236 }
3237 }
3238 }
3239 DrawCommand::TextRun { rect, text, style } => {
3240 if text.is_empty() || style.get_color().get_alpha() == 0 {
3241 continue;
3242 }
3243 let phys_rect: Rect = Self::scale_rect(*rect, scale);
3244 let pad: f32 = style.get_font_size() * scale * 0.5;
3245 let expanded: Rect = Rect::new(
3246 phys_rect.get_x() - pad,
3247 phys_rect.get_y() - pad,
3248 phys_rect.get_width() + pad * 2.0,
3249 phys_rect.get_height() + pad * 2.0,
3250 );
3251 let Some(vis) = expanded.intersect(active_clip) else {
3252 continue;
3253 };
3254 let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3255 let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3256 if vis_y0 >= vis_y1 {
3257 continue;
3258 }
3259 let key_hash: u64 = hash_text_layout_key(text, *style);
3260 let width_bits: u32 = rect.get_width().to_bits();
3261 let phys_scale_milli: u32 = (scale * 1000.0).round() as u32;
3262 let base_x_phys: f32 = (rect.get_x() * scale).round();
3263 let base_y_phys: f32 = (rect.get_y() * scale).round();
3264 let (glyph_run_start, glyph_run_len): (u32, u32) = if text.len()
3265 <= POSITIONED_RUN_MAX_TEXT_LEN
3266 {
3267 if let Some((cached_run, cached_glyphs)) = positioned_glyph_run_cache
3268 .lookup(key_hash, width_bits, phys_scale_milli)
3269 {
3270 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3271 Self::emit_cached_glyph_run(
3272 cached_glyphs,
3273 (base_x_phys as i32, base_y_phys as i32),
3274 (active_clip, phys_w, phys_h),
3275 positioned_glyphs,
3276 )
3277 } else {
3278 let max_w: f32 = rect.get_width().max(1.0);
3279 if let Some((line_str, line_h)) =
3280 measurer.try_single_line(text, *style, Some(max_w))
3281 {
3282 Self::resolve_single_line_glyphs(
3283 (line_str, line_h),
3284 *rect,
3285 *style,
3286 (active_clip, phys_w, phys_h, scale),
3287 (glyph_atlas, font_provider),
3288 positioned_glyphs,
3289 line_scratch,
3290 )
3291 } else {
3292 let width_key: u32 =
3293 ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3294 let layout_idx: u32 = text_layout_cache.get_or_insert_with(
3295 key_hash,
3296 width_key,
3297 || measurer.measure(text, *style, Some(max_w)),
3298 );
3299 if let Some(layout) = text_layout_cache.get(layout_idx) {
3300 Self::resolve_text_run_glyphs(
3301 layout,
3302 *rect,
3303 *style,
3304 (active_clip, phys_w, phys_h, scale),
3305 (glyph_atlas, font_provider),
3306 positioned_glyphs,
3307 line_scratch,
3308 )
3309 } else {
3310 (0, 0)
3311 }
3312 }
3313 }
3314 } else {
3315 let max_w: f32 = rect.get_width().max(1.0);
3316 if let Some((line_str, line_h)) =
3317 measurer.try_single_line(text, *style, Some(max_w))
3318 {
3319 if style.get_align() == TextAlign::Left
3320 && line_str.is_ascii()
3321 && base_x_phys >= 0.0
3322 {
3323 let run_start: u32 = positioned_glyphs.len() as u32;
3324 let clip_x0_i: i32 = active_clip.get_x().ceil().max(0.0) as i32;
3325 let clip_y0_i: i32 = (active_clip.get_y().ceil().max(0.0)
3326 as i32)
3327 .min(phys_h as i32);
3328 let clip_x1_i: i32 = (active_clip.right().floor().max(0.0)
3329 as i32)
3330 .min(phys_w as i32);
3331 let clip_y1_i: i32 = (active_clip.bottom().floor().max(0.0)
3332 as i32)
3333 .min(phys_h as i32);
3334 let bx_i: i32 = base_x_phys as i32;
3335 let by_i: i32 = base_y_phys as i32;
3336 let phys_font_size: f32 = style.get_font_size() * scale;
3337 let size_tenths: u16 =
3338 (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
3339 let bold: bool = style.get_weight().is_bold();
3340 let monospace: bool =
3341 style.get_family() == FontFamily::Monospace;
3342 let italic: bool = style.get_italic();
3343 let key_meta: (u16, bool, bool, bool) =
3344 (size_tenths, bold, monospace, italic);
3345 let ascii_table_idx: usize = glyph_atlas.ascii_table_index(
3346 size_tenths,
3347 bold,
3348 monospace,
3349 italic,
3350 );
3351 let line_h_phys: f32 = line_h * scale;
3352 let letter_sp: f32 = style.get_letter_spacing() * scale;
3353 let space_step: f32 =
3354 measure_char_advance(' ', *style) * scale + letter_sp;
3355 let clip_ok: bool =
3356 clip_x0_i < clip_x1_i && clip_y0_i < clip_y1_i;
3357 if positioned_glyph_run_cache.is_streaming() {
3358 positioned_glyph_run_cache.record_streaming_miss();
3359 if clip_ok {
3360 let mut pen_x: f32 = 0.0;
3361 for &byte in line_str.as_bytes() {
3362 if byte == b' ' {
3363 pen_x += space_step;
3364 continue;
3365 }
3366 let gx0: i32 = bx_i + (pen_x.round() as i32);
3367 if gx0 >= clip_x1_i {
3368 break;
3369 }
3370 let slot: u32 = glyph_atlas
3371 .get_or_rasterize_ascii_slot_with(
3372 ascii_table_idx,
3373 byte,
3374 key_meta,
3375 font_provider,
3376 );
3377 let glyph: &RasterizedGlyph =
3378 glyph_atlas.glyph_by_slot(slot);
3379 let adv_phys: f32 = (glyph.get_advance() as f32)
3380 .max(1.0)
3381 + letter_sp;
3382 let gw_u32: u32 = glyph.get_width();
3383 let gh_u32: u32 = glyph.get_height();
3384 let gw_u16: u16 =
3385 gw_u32.min(u16::MAX as u32) as u16;
3386 let gh_u16: u16 =
3387 gh_u32.min(u16::MAX as u32) as u16;
3388 if gx0 + (gw_u16 as i32) > clip_x0_i {
3389 let gy0: i32 = by_i
3390 + (((line_h_phys - (gh_u32 as f32)) * 0.5)
3391 .round()
3392 as i32);
3393 if gy0 < clip_y1_i
3394 && gy0 + (gh_u16 as i32) > clip_y0_i
3395 {
3396 positioned_glyphs.push(
3397 PositionedGlyph::new(
3398 slot, gx0, gy0, gw_u16, gh_u16,
3399 ),
3400 );
3401 }
3402 }
3403 pen_x += adv_phys;
3404 }
3405 }
3406 } else {
3407 let (_, _): (CachedPositionedGlyphRun, &[PositionedGlyph]) =
3408 positioned_glyph_run_cache.insert_with(
3409 (key_hash, width_bits, phys_scale_milli),
3410 line_str.len(),
3411 |out_slab: &mut Vec<PositionedGlyph>| {
3412 let mut pen_x: f32 = 0.0;
3413 let mut has_frac: bool = false;
3414 let mut max_slot: u32 = 0;
3415 for &byte in line_str.as_bytes() {
3416 if byte == b' ' {
3417 pen_x += space_step;
3418 continue;
3419 }
3420 let slot: u32 = glyph_atlas
3421 .get_or_rasterize_ascii_slot_with(
3422 ascii_table_idx,
3423 byte,
3424 key_meta,
3425 font_provider,
3426 );
3427 max_slot = max_slot.max(slot);
3428 let glyph: &RasterizedGlyph =
3429 glyph_atlas.glyph_by_slot(slot);
3430 let adv_phys: f32 =
3431 (glyph.get_advance() as f32).max(1.0)
3432 + letter_sp;
3433 let pen_x_round: f32 = pen_x.round();
3434 if (pen_x - pen_x_round).abs() > 1e-4 {
3435 has_frac = true;
3436 }
3437 let gw_u32: u32 = glyph.get_width();
3438 let gh_u32: u32 = glyph.get_height();
3439 let gw_u16: u16 =
3440 gw_u32.min(u16::MAX as u32) as u16;
3441 let gh_u16: u16 =
3442 gh_u32.min(u16::MAX as u32) as u16;
3443 let rx: i32 = pen_x_round as i32;
3444 let ry: i32 =
3445 ((line_h_phys - (gh_u32 as f32)) * 0.5)
3446 .round()
3447 as i32;
3448 out_slab.push(PositionedGlyph::new(
3449 slot, rx, ry, gw_u16, gh_u16,
3450 ));
3451 if clip_ok {
3452 let gx0: i32 = bx_i + rx;
3453 let gy0: i32 = by_i + ry;
3454 if gx0 + (gw_u16 as i32) > clip_x0_i
3455 && gx0 < clip_x1_i
3456 && gy0 < clip_y1_i
3457 && gy0 + (gh_u16 as i32) > clip_y0_i
3458 {
3459 positioned_glyphs.push(
3460 PositionedGlyph::new(
3461 slot, gx0, gy0, gw_u16,
3462 gh_u16,
3463 ),
3464 );
3465 }
3466 }
3467 pen_x += adv_phys;
3468 }
3469 (has_frac, max_slot)
3470 },
3471 );
3472 }
3473 let run_len: u32 =
3474 (positioned_glyphs.len() as u32).saturating_sub(run_start);
3475 (run_start, run_len)
3476 } else {
3477 let (cached_run, cached_glyphs): (
3478 CachedPositionedGlyphRun,
3479 &[PositionedGlyph],
3480 ) = positioned_glyph_run_cache.insert_with(
3481 (key_hash, width_bits, phys_scale_milli),
3482 line_str.len(),
3483 |out_slab: &mut Vec<PositionedGlyph>| {
3484 Self::append_single_line_positioned_glyph_run(
3485 (line_str, line_h),
3486 *rect,
3487 *style,
3488 scale,
3489 (glyph_atlas, font_provider),
3490 line_scratch,
3491 out_slab,
3492 )
3493 },
3494 );
3495 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3496 Self::emit_cached_glyph_run(
3497 cached_glyphs,
3498 (base_x_phys as i32, base_y_phys as i32),
3499 (active_clip, phys_w, phys_h),
3500 positioned_glyphs,
3501 )
3502 } else {
3503 Self::resolve_single_line_glyphs(
3504 (line_str, line_h),
3505 *rect,
3506 *style,
3507 (active_clip, phys_w, phys_h, scale),
3508 (glyph_atlas, font_provider),
3509 positioned_glyphs,
3510 line_scratch,
3511 )
3512 }
3513 }
3514 } else {
3515 let width_key: u32 =
3516 ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3517 let layout_idx: u32 = text_layout_cache.get_or_insert_with(
3518 key_hash,
3519 width_key,
3520 || measurer.measure(text, *style, Some(max_w)),
3521 );
3522 if let Some(layout) = text_layout_cache.get(layout_idx) {
3523 let (cached_run, cached_glyphs): (
3524 CachedPositionedGlyphRun,
3525 &[PositionedGlyph],
3526 ) = positioned_glyph_run_cache.insert_with(
3527 (key_hash, width_bits, phys_scale_milli),
3528 text.len(),
3529 |out_slab: &mut Vec<PositionedGlyph>| {
3530 Self::append_cached_positioned_glyph_run(
3531 layout,
3532 *rect,
3533 *style,
3534 scale,
3535 (glyph_atlas, font_provider),
3536 line_scratch,
3537 out_slab,
3538 )
3539 },
3540 );
3541 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3542 Self::emit_cached_glyph_run(
3543 cached_glyphs,
3544 (base_x_phys as i32, base_y_phys as i32),
3545 (active_clip, phys_w, phys_h),
3546 positioned_glyphs,
3547 )
3548 } else {
3549 Self::resolve_text_run_glyphs(
3550 layout,
3551 *rect,
3552 *style,
3553 (active_clip, phys_w, phys_h, scale),
3554 (glyph_atlas, font_provider),
3555 positioned_glyphs,
3556 line_scratch,
3557 )
3558 }
3559 } else {
3560 (0, 0)
3561 }
3562 }
3563 }
3564 } else {
3565 let max_w: f32 = rect.get_width().max(1.0);
3566 let width_key: u32 = ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3567 let layout_idx: u32 =
3568 text_layout_cache.get_or_insert_with(key_hash, width_key, || {
3569 measurer.measure(text, *style, Some(max_w))
3570 });
3571 if let Some(layout) = text_layout_cache.get(layout_idx) {
3572 Self::resolve_text_run_glyphs(
3573 layout,
3574 *rect,
3575 *style,
3576 (active_clip, phys_w, phys_h, scale),
3577 (glyph_atlas, font_provider),
3578 positioned_glyphs,
3579 line_scratch,
3580 )
3581 } else {
3582 (0, 0)
3583 }
3584 };
3585 if glyph_run_len == 0 {
3586 continue;
3587 }
3588 let clip_x0_i: i32 = active_clip.get_x().ceil().max(0.0) as i32;
3589 let clip_y0_i: i32 =
3590 (active_clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
3591 let clip_x1_i: i32 =
3592 (active_clip.right().floor().max(0.0) as i32).min(phys_w as i32);
3593 let clip_y1_i: i32 =
3594 (active_clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
3595 let mut min_gx: i32 = i32::MAX;
3596 let mut min_gy: i32 = i32::MAX;
3597 let mut max_gx: i32 = i32::MIN;
3598 let mut max_gy: i32 = i32::MIN;
3599 let g_s: usize = glyph_run_start as usize;
3600 let g_e: usize = g_s.saturating_add(glyph_run_len as usize);
3601 for green_val in positioned_glyphs[g_s..g_e].iter() {
3602 let gx0: i32 = green_val.x.max(clip_x0_i);
3603 let gx1: i32 = (green_val.x + green_val.width as i32).min(clip_x1_i);
3604 let gy0: i32 = green_val.y.max(clip_y0_i);
3605 let gy1: i32 = (green_val.y + green_val.height as i32).min(clip_y1_i);
3606 if gx0 < gx1 && gy0 < gy1 {
3607 min_gx = min_gx.min(gx0);
3608 min_gy = min_gy.min(gy0);
3609 max_gx = max_gx.max(gx1);
3610 max_gy = max_gy.max(gy1);
3611 }
3612 }
3613 let (y0, y1, run_vis): (u32, u32, Rect) = if min_gx < max_gx && min_gy < max_gy
3614 {
3615 let ty0: u32 = (min_gy.max(0) as u32).min(phys_h);
3616 let ty1: u32 = (max_gy.max(0) as u32).min(phys_h);
3617 if ty0 >= ty1 {
3618 continue;
3619 }
3620 (
3621 ty0,
3622 ty1,
3623 Rect::new(
3624 min_gx as f32,
3625 min_gy as f32,
3626 (max_gx - min_gx) as f32,
3627 (max_gy - min_gy) as f32,
3628 ),
3629 )
3630 } else {
3631 (vis_y0, vis_y1, vis)
3632 };
3633 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3634 rounded_clip_stack.as_slice(),
3635 rounded_clips,
3636 run_vis,
3637 );
3638 if has_first_cmd {
3639 expand_opt_rect(prepped_fg_bounds, run_vis);
3640 }
3641 has_first_cmd = true;
3642 expand_opt_rect(prepped_bounds, run_vis);
3643 prepped.push(PreppedCommand {
3644 cmd_index,
3645 active_clip,
3646 y0,
3647 y1,
3648 opaque_cutout_h: Rect::default(),
3649 opaque_cutout_v: Rect::default(),
3650 glyph_run_start,
3651 glyph_run_len,
3652 caret_rect_idx: u32::MAX,
3653 rounded_clip_start: rc_start,
3654 rounded_clip_len: rc_len,
3655 skip_delta: 0,
3656 });
3657 }
3658 DrawCommand::TextCaret {
3659 text_rect,
3660 content_rect,
3661 text,
3662 style,
3663 caret_height,
3664 color,
3665 multiline,
3666 } => {
3667 if color.get_alpha() == 0 {
3668 continue;
3669 }
3670 let phys_content: Rect = Self::scale_rect(*content_rect, scale);
3671 let Some(vis) = phys_content.intersect(active_clip) else {
3672 continue;
3673 };
3674 let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3675 let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3676 if vis_y0 >= vis_y1 {
3677 continue;
3678 }
3679 let (max_w, width_key): (Option<f32>, u32) = if *multiline {
3680 let width_val: f32 = content_rect.get_width().max(1.0);
3681 (
3682 Some(width_val),
3683 ((width_val * 10.0).round() as u32).min(u32::MAX - 1),
3684 )
3685 } else {
3686 (None, u32::MAX)
3687 };
3688 let key_hash: u64 = hash_text_layout_key(text, *style);
3689 let layout_idx: u32 =
3690 text_layout_cache.get_or_insert_with(key_hash, width_key, || {
3691 measurer.measure(text, *style, max_w)
3692 });
3693 let caret_rect: Rect = Self::resolve_text_caret_rect(
3694 text_layout_cache.get(layout_idx),
3695 (*text_rect, *content_rect),
3696 *style,
3697 (*caret_height, scale, *multiline),
3698 (glyph_atlas, font_provider),
3699 );
3700 let Some(caret_vis) = caret_rect.intersect(active_clip) else {
3701 continue;
3702 };
3703 let y0: u32 = (caret_vis.get_y().floor().max(0.0) as u32).min(phys_h);
3704 let y1: u32 = (caret_vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3705 if y0 >= y1 {
3706 continue;
3707 }
3708 let caret_rect_idx: u32 = caret_rects.len() as u32;
3709 caret_rects.push(caret_rect);
3710 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3711 rounded_clip_stack.as_slice(),
3712 rounded_clips,
3713 caret_vis,
3714 );
3715 if has_first_cmd {
3716 expand_opt_rect(prepped_fg_bounds, caret_vis);
3717 }
3718 has_first_cmd = true;
3719 expand_opt_rect(prepped_bounds, caret_vis);
3720 prepped.push(PreppedCommand {
3721 cmd_index,
3722 active_clip,
3723 y0,
3724 y1,
3725 opaque_cutout_h: Rect::default(),
3726 opaque_cutout_v: Rect::default(),
3727 glyph_run_start: 0,
3728 glyph_run_len: 0,
3729 caret_rect_idx,
3730 rounded_clip_start: rc_start,
3731 rounded_clip_len: rc_len,
3732 skip_delta: 0,
3733 });
3734 }
3735 DrawCommand::Line {
3736 from, to, width, ..
3737 } => {
3738 let half_w: f32 = (width * scale).max(1.0) * 0.5 + 1.0;
3739 let min_x: f32 = from.get_x().min(to.get_x()) * scale - half_w;
3740 let min_y: f32 = from.get_y().min(to.get_y()) * scale - half_w;
3741 let max_x: f32 = from.get_x().max(to.get_x()) * scale + half_w;
3742 let max_y: f32 = from.get_y().max(to.get_y()) * scale + half_w;
3743 if let Some(vis) =
3744 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
3745 {
3746 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3747 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3748 if y0 < y1 {
3749 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3750 rounded_clip_stack.as_slice(),
3751 rounded_clips,
3752 vis,
3753 );
3754 if has_first_cmd {
3755 expand_opt_rect(prepped_fg_bounds, vis);
3756 }
3757 has_first_cmd = true;
3758 expand_opt_rect(prepped_bounds, vis);
3759 prepped.push(PreppedCommand {
3760 cmd_index,
3761 active_clip,
3762 y0,
3763 y1,
3764 opaque_cutout_h: Rect::default(),
3765 opaque_cutout_v: Rect::default(),
3766 glyph_run_start: 0,
3767 glyph_run_len: 0,
3768 caret_rect_idx: u32::MAX,
3769 rounded_clip_start: rc_start,
3770 rounded_clip_len: rc_len,
3771 skip_delta: 0,
3772 });
3773 }
3774 }
3775 }
3776 DrawCommand::Circle { center, radius, .. } => {
3777 let red_val: f32 = radius * scale + 1.0;
3778 let bounds: Rect = Rect::new(
3779 center.get_x() * scale - red_val,
3780 center.get_y() * scale - red_val,
3781 red_val * 2.0,
3782 red_val * 2.0,
3783 );
3784 if let Some(vis) = bounds.intersect(active_clip) {
3785 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3786 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3787 if y0 < y1 {
3788 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3789 rounded_clip_stack.as_slice(),
3790 rounded_clips,
3791 vis,
3792 );
3793 if has_first_cmd {
3794 expand_opt_rect(prepped_fg_bounds, vis);
3795 }
3796 has_first_cmd = true;
3797 expand_opt_rect(prepped_bounds, vis);
3798 prepped.push(PreppedCommand {
3799 cmd_index,
3800 active_clip,
3801 y0,
3802 y1,
3803 opaque_cutout_h: Rect::default(),
3804 opaque_cutout_v: Rect::default(),
3805 glyph_run_start: 0,
3806 glyph_run_len: 0,
3807 caret_rect_idx: u32::MAX,
3808 rounded_clip_start: rc_start,
3809 rounded_clip_len: rc_len,
3810 skip_delta: 0,
3811 });
3812 }
3813 }
3814 }
3815 DrawCommand::Triangle { p0, p1, p2, .. } => {
3816 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.0;
3817 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.0;
3818 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.0;
3819 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.0;
3820 if let Some(vis) =
3821 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
3822 {
3823 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3824 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3825 if y0 < y1 {
3826 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3827 rounded_clip_stack.as_slice(),
3828 rounded_clips,
3829 vis,
3830 );
3831 if has_first_cmd {
3832 expand_opt_rect(prepped_fg_bounds, vis);
3833 }
3834 has_first_cmd = true;
3835 expand_opt_rect(prepped_bounds, vis);
3836 prepped.push(PreppedCommand {
3837 cmd_index,
3838 active_clip,
3839 y0,
3840 y1,
3841 opaque_cutout_h: Rect::default(),
3842 opaque_cutout_v: Rect::default(),
3843 glyph_run_start: 0,
3844 glyph_run_len: 0,
3845 caret_rect_idx: u32::MAX,
3846 rounded_clip_start: rc_start,
3847 rounded_clip_len: rc_len,
3848 skip_delta: 0,
3849 });
3850 }
3851 }
3852 }
3853 }
3854 }
3855 while let Some((_, _, opt_slot)) = clip_scopes.pop() {
3856 if let Some(slot_idx) = opt_slot {
3857 let span_len: usize = prepped.len().saturating_sub(slot_idx);
3858 if span_len <= 1 {
3859 prepped.truncate(slot_idx);
3860 } else if span_len == 2 {
3861 let only_cmd: PreppedCommand = prepped[slot_idx + 1];
3862 prepped[slot_idx] = only_cmd;
3863 let _: Option<PreppedCommand> = prepped.pop();
3864 } else {
3865 prepped[slot_idx].skip_delta = span_len as u32;
3866 }
3867 }
3868 }
3869 let culled_now: usize = Self::cull_occluded_prepped_commands(
3870 commands,
3871 prepped,
3872 (phys_w, phys_h, scale),
3873 cull_keep_scratch,
3874 cull_compacted_scratch,
3875 cull_sentinels_scratch,
3876 );
3877 *culled_occluded_commands = culled_occluded_commands.saturating_add(culled_now as u64);
3878 glyph_atlas.set_slots_pinned(false);
3879 }
3880
3881 #[must_use]
3893 fn command_cull_bounds(cmd: &DrawCommand, active_clip: Rect, scale: f32) -> Option<Rect> {
3894 let raw: Rect = match cmd {
3895 DrawCommand::Clear(_) => active_clip,
3896 DrawCommand::FillRoundedRect { rect, .. }
3897 | DrawCommand::LinearGradientRect { rect, .. }
3898 | DrawCommand::Image { rect, .. }
3899 | DrawCommand::SharedImage { rect, .. }
3900 | DrawCommand::SpriteRegion { rect, .. }
3901 | DrawCommand::ExternalSurface { rect, .. }
3902 | DrawCommand::BackdropBlur { rect, .. } => snap_physical_rect(*rect, scale),
3903 DrawCommand::BoxShadow { rect, shadow, .. } => {
3904 let spread: f32 = shadow.get_spread_radius() * scale;
3905 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
3906 let sigma: f32 = (blur * 0.5).max(0.75);
3907 let pad: f32 = (sigma * 3.0).ceil();
3908 let base: Rect = snap_physical_rect(*rect, scale);
3909 Rect::new(
3910 base.get_x() + (shadow.get_offset_x() * scale).round() - spread - pad,
3911 base.get_y() + (shadow.get_offset_y() * scale).round() - spread - pad,
3912 (base.get_width() + spread * 2.0).max(1.0) + pad * 2.0,
3913 (base.get_height() + spread * 2.0).max(1.0) + pad * 2.0,
3914 )
3915 }
3916 DrawCommand::TextRun { rect, style, .. } => {
3917 let phys: Rect = Self::scale_rect(*rect, scale);
3918 let pad: f32 = style.get_font_size() * scale * 0.5 + 2.0;
3919 Rect::new(
3920 phys.get_x() - pad,
3921 phys.get_y() - pad,
3922 phys.get_width() + pad * 2.0,
3923 phys.get_height() + pad * 2.0,
3924 )
3925 }
3926 DrawCommand::TextCaret { content_rect, .. } => snap_physical_rect(*content_rect, scale),
3927 DrawCommand::Line {
3928 from, to, width, ..
3929 } => {
3930 let pad: f32 = (width * scale).max(1.0) + 2.0;
3931 let x0: f32 = from.get_x().min(to.get_x()) * scale - pad;
3932 let y0: f32 = from.get_y().min(to.get_y()) * scale - pad;
3933 let x1: f32 = from.get_x().max(to.get_x()) * scale + pad;
3934 let y1: f32 = from.get_y().max(to.get_y()) * scale + pad;
3935 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
3936 }
3937 DrawCommand::Circle { center, radius, .. } => {
3938 let red_val: f32 = radius * scale + 2.0;
3939 Rect::new(
3940 center.get_x() * scale - red_val,
3941 center.get_y() * scale - red_val,
3942 red_val * 2.0,
3943 red_val * 2.0,
3944 )
3945 }
3946 DrawCommand::Triangle { p0, p1, p2, .. } => {
3947 let x0: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 2.0;
3948 let y0: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 2.0;
3949 let x1: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 2.0;
3950 let y1: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 2.0;
3951 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
3952 }
3953 DrawCommand::PushClip(_)
3954 | DrawCommand::PushRoundedClip { .. }
3955 | DrawCommand::PopClip => {
3956 return None;
3957 }
3958 };
3959 raw.intersect(active_clip)
3960 }
3961
3962 #[must_use]
3974 fn opaque_inscribed_rect(cmd: &DrawCommand, item: PreppedCommand, scale: f32) -> Option<Rect> {
3975 if item.get_rounded_clip_len() != 0 {
3976 return None;
3977 }
3978 let (rect, radius): (Rect, CornerRadius) = match cmd {
3979 DrawCommand::FillRoundedRect {
3980 rect,
3981 color,
3982 radius,
3983 border,
3984 } if color.get_alpha() == 255
3985 && (border.get_width() <= 0.0 || border.get_color().get_alpha() == 255) =>
3986 {
3987 (*rect, *radius)
3988 }
3989 DrawCommand::LinearGradientRect {
3990 rect,
3991 gradient,
3992 radius,
3993 } if gradient.get_start_color().get_alpha() == 255
3994 && gradient.get_end_color().get_alpha() == 255 =>
3995 {
3996 (*rect, *radius)
3997 }
3998 _ => return None,
3999 };
4000 let phys: Rect = snap_physical_rect(rect, scale);
4001 let phys_r: CornerRadius = Self::scale_radius(radius, scale);
4002 let max_r: f32 = phys_r
4003 .max_radius()
4004 .min(phys.get_width() * 0.5)
4005 .min(phys.get_height() * 0.5);
4006 let inscribed: Rect = if max_r > 0.0 {
4007 phys.inset(Edges::all(max_r.ceil()))
4008 } else {
4009 phys
4010 };
4011 if inscribed.get_width() < 1.0 || inscribed.get_height() < 1.0 {
4012 return None;
4013 }
4014 let occ: Rect = inscribed.intersect(item.get_active_clip())?;
4015 if occ.get_width() >= 1.0 && occ.get_height() >= 1.0 {
4016 Some(occ)
4017 } else {
4018 None
4019 }
4020 }
4021
4022 fn cull_occluded_prepped_commands(
4037 commands: &[DrawCommand],
4038 prepped: &mut Vec<PreppedCommand>,
4039 dims: (u32, u32, f32),
4040 keep: &mut Vec<bool>,
4041 compacted: &mut Vec<PreppedCommand>,
4042 open_sentinels: &mut Vec<(usize, usize)>,
4043 ) -> usize {
4044 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
4045 let len: usize = prepped.len();
4046 if len < 2 {
4047 return 0;
4048 }
4049 keep.clear();
4050 keep.resize(len, true);
4051 let mut occluders: [Rect; OCCLUSION_MAX_OCCLUDERS] =
4052 [Rect::default(); OCCLUSION_MAX_OCCLUDERS];
4053 let mut occluder_count: usize = 0;
4054 let mut combined_tile_mask: u64 = 0;
4055 let mut culled: usize = 0;
4056 for idx in (0..len).rev() {
4057 let item: PreppedCommand = prepped[idx];
4058 if item.get_cmd_index() == usize::MAX {
4059 continue;
4060 }
4061 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
4062 if matches!(cmd, DrawCommand::BackdropBlur { .. }) {
4063 occluder_count = 0;
4064 combined_tile_mask = 0;
4065 continue;
4066 }
4067 if (occluder_count > 0 || combined_tile_mask != 0)
4068 && let Some(vis) = Self::command_cull_bounds(cmd, item.get_active_clip(), scale)
4069 {
4070 let vis_mask: u64 = occlusion_tile_mask_overlapped(vis, phys_w, phys_h);
4071 let mut covered: bool =
4072 vis_mask != 0 && (vis_mask & combined_tile_mask) == vis_mask;
4073 if !covered {
4074 for occ in occluders.iter().take(occluder_count) {
4075 if vis.get_x() >= occ.get_x()
4076 && vis.get_y() >= occ.get_y()
4077 && vis.right() <= occ.right()
4078 && vis.bottom() <= occ.bottom()
4079 {
4080 covered = true;
4081 break;
4082 }
4083 }
4084 }
4085 if covered {
4086 keep[idx] = false;
4087 culled += 1;
4088 continue;
4089 }
4090 }
4091 if let Some(occ) = Self::opaque_inscribed_rect(cmd, item, scale) {
4092 combined_tile_mask |= occlusion_tile_mask_contained(occ, phys_w, phys_h);
4093 if occluder_count < OCCLUSION_MAX_OCCLUDERS {
4094 occluders[occluder_count] = occ;
4095 occluder_count += 1;
4096 } else {
4097 let occ_area: f32 = occ.get_width() * occ.get_height();
4098 let mut min_i: usize = 0;
4099 let mut min_area: f32 = occluders[0].get_width() * occluders[0].get_height();
4100 for (slot, occ_ref) in occluders
4101 .iter()
4102 .enumerate()
4103 .take(OCCLUSION_MAX_OCCLUDERS)
4104 .skip(1)
4105 {
4106 let area: f32 = occ_ref.get_width() * occ_ref.get_height();
4107 if area < min_area {
4108 min_area = area;
4109 min_i = slot;
4110 }
4111 }
4112 if occ_area > min_area {
4113 occluders[min_i] = occ;
4114 }
4115 }
4116 }
4117 }
4118 if culled == 0 {
4119 return 0;
4120 }
4121 compacted.clear();
4122 compacted.reserve(len.saturating_sub(culled));
4123 open_sentinels.clear();
4124 for (old_idx, &kept) in keep.iter().enumerate() {
4125 while let Some(&(new_s, old_end)) = open_sentinels.last() {
4126 if old_end <= old_idx {
4127 let _: Option<(usize, usize)> = open_sentinels.pop();
4128 let span: u32 = (compacted.len().saturating_sub(new_s)).max(1) as u32;
4129 compacted[new_s].set_skip_delta(span);
4130 } else {
4131 break;
4132 }
4133 }
4134 if kept {
4135 let item: PreppedCommand = prepped[old_idx];
4136 if item.get_cmd_index() == usize::MAX {
4137 let old_end: usize = old_idx.saturating_add(item.get_skip_delta() as usize);
4138 open_sentinels.push((compacted.len(), old_end));
4139 }
4140 compacted.push(item);
4141 }
4142 }
4143 while let Some((new_s, _)) = open_sentinels.pop() {
4144 let span: u32 = (compacted.len().saturating_sub(new_s)).max(1) as u32;
4145 compacted[new_s].set_skip_delta(span);
4146 }
4147 swap(prepped, compacted);
4148 culled
4149 }
4150
4151 fn raster_backdrop_blur(
4165 band: &mut PixelBand<'_>,
4166 rect: Rect,
4167 radius: CornerRadius,
4168 blur_radius: f32,
4169 clip: Rect,
4170 ) -> usize {
4171 let Some(vis) = rect.intersect(clip) else {
4172 return 0;
4173 };
4174 let border_width: u32 = band.width();
4175 let band_y0: u32 = band.y_offset();
4176 let band_y1: u32 = band.y_end();
4177 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(border_width);
4178 let x1: u32 = (vis.right().ceil().max(0.0) as u32).clamp(x0, border_width);
4179 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
4180 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(y0, band_y1);
4181 if x0 >= x1 || y0 >= y1 {
4182 return 0;
4183 }
4184 let rad: u32 = (blur_radius * 0.5).round().clamp(1.0, 24.0) as u32;
4185 let clip_x0: u32 = (clip.get_x().floor().max(0.0) as u32).min(border_width);
4186 let clip_x1: u32 = (clip.right().ceil().max(0.0) as u32).clamp(clip_x0, border_width);
4187 let clip_y0: u32 = (clip.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
4188 let clip_y1: u32 = (clip.bottom().ceil().max(0.0) as u32).clamp(clip_y0, band_y1);
4189 let sx0: u32 = x0.saturating_sub(rad).max(clip_x0);
4190 let sx1: u32 = x1.saturating_add(rad).min(clip_x1);
4191 let sy0: u32 = y0.saturating_sub(rad).max(clip_y0);
4192 let sy1: u32 = y1.saturating_add(rad).min(clip_y1);
4193 let stroke_width: u32 = sx1.saturating_sub(sx0);
4194 let sh: u32 = sy1.saturating_sub(sy0);
4195 let needed: usize = (stroke_width as usize).saturating_mul(sh as usize);
4196 if needed == 0 {
4197 return 0;
4198 }
4199 let mut horiz: Vec<[u8; 4]> = BAND_BLUR_HORIZ_SCRATCH
4200 .try_with(|cell: &RefCell<Vec<[u8; 4]>>| {
4201 cell.try_borrow_mut()
4202 .ok()
4203 .map(|mut guard: RefMut<'_, Vec<[u8; 4]>>| take(&mut *guard))
4204 })
4205 .ok()
4206 .flatten()
4207 .unwrap_or_default();
4208 if horiz.len() < needed {
4209 horiz.resize(needed, [0, 0, 0, 0]);
4210 }
4211 let y0_rel: u32 = y0.saturating_sub(band_y0);
4212 let y1_rel: u32 = y1.saturating_sub(band_y0);
4213 let sy0_rel: u32 = sy0.saturating_sub(band_y0);
4214 let shifted_rect: Rect = Rect::new(
4215 rect.get_x(),
4216 rect.get_y() - (band_y0 as f32),
4217 rect.get_width(),
4218 rect.get_height(),
4219 );
4220 let desc: BlurPassDesc = BlurPassDesc {
4221 #[cfg(not(target_arch = "wasm32"))]
4222 fb_ptr: 0,
4223 #[cfg(not(target_arch = "wasm32"))]
4224 fb_len: 0,
4225 fb_w: border_width,
4226 #[cfg(not(target_arch = "wasm32"))]
4227 horiz_ptr: 0,
4228 #[cfg(not(target_arch = "wasm32"))]
4229 horiz_len: needed,
4230 sx0,
4231 sy0: sy0_rel,
4232 sw: stroke_width,
4233 sh,
4234 x0,
4235 x1,
4236 y0: y0_rel,
4237 y1: y1_rel,
4238 rad,
4239 inv_win_q24: blur_inv_window_q24(rad),
4240 has_radius: radius.max_radius() > 0.25,
4241 rect: shifted_rect,
4242 radius,
4243 #[cfg(not(target_arch = "wasm32"))]
4244 strip_count: 1,
4245 #[cfg(not(target_arch = "wasm32"))]
4246 strip_rows: sh.max(1),
4247 };
4248 let horiz_slice: &mut [[u8; 4]] = &mut horiz[..needed];
4249 blur_horiz_strip_slices(band.pixels, horiz_slice, &desc, (0, sh as usize));
4250 let fb_stride: usize = (border_width as usize) * 4;
4251 let strip_start: usize = (y0_rel as usize).saturating_mul(fb_stride);
4252 let strip_end: usize = (y1_rel as usize).saturating_mul(fb_stride);
4253 let shaded: usize = if let Some(fb_strip) = band.pixels.get_mut(strip_start..strip_end) {
4254 blur_vert_strip_slices(fb_strip, horiz_slice, &desc, (y0_rel, y1_rel))
4255 } else {
4256 0
4257 };
4258 let _: bool = BAND_BLUR_HORIZ_SCRATCH
4259 .try_with(|cell: &RefCell<Vec<[u8; 4]>>| {
4260 if let Ok(mut guard) = cell.try_borrow_mut() {
4261 *guard = horiz;
4262 }
4263 })
4264 .is_ok();
4265 shaded
4266 }
4267
4268 #[must_use]
4278 pub fn text_layout_cache_stats(&self) -> (u64, u64, u64, usize) {
4279 self.get_text_layout_cache().stats()
4280 }
4281
4282 fn append_relative_line_glyphs(
4294 line_info: (&str, f32),
4295 metrics: (f32, f32, f32, f32),
4296 font_meta: (TextAlign, usize, (u16, bool, bool, bool)),
4297 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4298 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4299 out_glyphs: &mut Vec<PositionedGlyph>,
4300 state: (&mut bool, &mut u32),
4301 ) {
4302 let (line_str, line_off_y): (&str, f32) = line_info;
4303 let (line_h_phys, box_w_phys, letter_sp, space_step): (f32, f32, f32, f32) = metrics;
4304 let (align, ascii_table_idx, key_meta): (TextAlign, usize, (u16, bool, bool, bool)) =
4305 font_meta;
4306 let (size_tenths, bold, monospace, italic): (u16, bool, bool, bool) = key_meta;
4307 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4308 let (has_fractional_x, max_glyph_slot): (&mut bool, &mut u32) = state;
4309 line_scratch.clear();
4310 let mut line_w_phys: f32 = 0.0;
4311 if line_str.is_ascii() {
4312 for &byte in line_str.as_bytes() {
4313 if byte == b' ' {
4314 line_w_phys += space_step;
4315 line_scratch.push((u32::MAX, space_step, 0, 0));
4316 } else {
4317 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
4318 ascii_table_idx,
4319 byte,
4320 key_meta,
4321 font_provider,
4322 );
4323 *max_glyph_slot = (*max_glyph_slot).max(slot);
4324 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4325 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4326 line_w_phys += adv_phys;
4327 line_scratch.push((
4328 slot,
4329 adv_phys,
4330 glyph.get_width().min(u16::MAX as u32) as u16,
4331 glyph.get_height().min(u16::MAX as u32) as u16,
4332 ));
4333 }
4334 }
4335 } else {
4336 for ch in line_str.chars() {
4337 if ch == ' ' {
4338 line_w_phys += space_step;
4339 line_scratch.push((u32::MAX, space_step, 0, 0));
4340 } else {
4341 let slot: u32 = if ch.is_ascii() {
4342 glyph_atlas.get_or_rasterize_ascii_slot_with(
4343 ascii_table_idx,
4344 ch as u8,
4345 key_meta,
4346 font_provider,
4347 )
4348 } else {
4349 let key: GlyphKey = GlyphKey {
4350 codepoint: ch,
4351 size_tenths,
4352 bold,
4353 monospace,
4354 italic,
4355 };
4356 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4357 };
4358 *max_glyph_slot = (*max_glyph_slot).max(slot);
4359 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4360 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4361 line_w_phys += adv_phys;
4362 line_scratch.push((
4363 slot,
4364 adv_phys,
4365 glyph.get_width().min(u16::MAX as u32) as u16,
4366 glyph.get_height().min(u16::MAX as u32) as u16,
4367 ));
4368 }
4369 }
4370 }
4371 let fit_scale: f32 = if box_w_phys > 1.0 && line_w_phys > box_w_phys + 1.0 {
4372 (box_w_phys / line_w_phys).clamp(0.72, 1.0)
4373 } else {
4374 1.0
4375 };
4376 let fitted_w_phys: f32 = line_w_phys * fit_scale;
4377 let align_x: f32 = match align {
4378 TextAlign::Left => 0.0,
4379 TextAlign::Center => ((box_w_phys - fitted_w_phys) * 0.5).max(0.0),
4380 TextAlign::Right => (box_w_phys - fitted_w_phys).max(0.0),
4381 };
4382 let mut pen_x: f32 = align_x.round();
4383 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4384 if slot == u32::MAX {
4385 pen_x += adv_phys * fit_scale;
4386 continue;
4387 }
4388 let pen_x_round: f32 = pen_x.round();
4389 if (pen_x - pen_x_round).abs() > 1e-4 {
4390 *has_fractional_x = true;
4391 }
4392 let glyph_v_off: f32 = ((line_h_phys - (gh_u16 as f32)) * 0.5).round();
4393 out_glyphs.push(PositionedGlyph::new(
4394 slot,
4395 pen_x_round as i32,
4396 (line_off_y + glyph_v_off) as i32,
4397 gw_u16,
4398 gh_u16,
4399 ));
4400 pen_x += adv_phys * fit_scale;
4401 }
4402 }
4403
4404 fn append_single_line_positioned_glyph_run(
4420 line_info: (&str, f32),
4421 rect: Rect,
4422 style: TextStyle,
4423 scale: f32,
4424 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4425 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4426 out_glyphs: &mut Vec<PositionedGlyph>,
4427 ) -> (bool, u32) {
4428 let (line_str, line_height_px): (&str, f32) = line_info;
4429 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4430 let phys_font_size: f32 = style.get_font_size() * scale;
4431 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4432 let bold: bool = style.get_weight().is_bold();
4433 let monospace: bool = style.get_family() == FontFamily::Monospace;
4434 let italic: bool = style.get_italic();
4435 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4436 let ascii_table_idx: usize =
4437 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4438 let line_h_phys: f32 = line_height_px * scale;
4439 let box_w_phys: f32 = rect.get_width() * scale;
4440 let letter_sp: f32 = style.get_letter_spacing() * scale;
4441 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4442 let mut has_fractional_x: bool = false;
4443 let mut max_glyph_slot: u32 = 0;
4444 Self::append_relative_line_glyphs(
4445 (line_str, 0.0),
4446 (line_h_phys, box_w_phys, letter_sp, space_step),
4447 (style.get_align(), ascii_table_idx, key_meta),
4448 (glyph_atlas, font_provider),
4449 line_scratch,
4450 out_glyphs,
4451 (&mut has_fractional_x, &mut max_glyph_slot),
4452 );
4453 (has_fractional_x, max_glyph_slot)
4454 }
4455
4456 fn append_cached_positioned_glyph_run(
4472 layout: &TextLayoutResult,
4473 rect: Rect,
4474 style: TextStyle,
4475 scale: f32,
4476 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4477 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4478 out_glyphs: &mut Vec<PositionedGlyph>,
4479 ) -> (bool, u32) {
4480 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4481 let phys_font_size: f32 = style.get_font_size() * scale;
4482 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4483 let bold: bool = style.get_weight().is_bold();
4484 let monospace: bool = style.get_family() == FontFamily::Monospace;
4485 let italic: bool = style.get_italic();
4486 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4487 let ascii_table_idx: usize =
4488 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4489 let line_h_phys: f32 = layout.get_line_height_px() * scale;
4490 let box_w_phys: f32 = rect.get_width() * scale;
4491 let letter_sp: f32 = style.get_letter_spacing() * scale;
4492 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4493 let align: TextAlign = style.get_align();
4494 let mut has_fractional_x: bool = false;
4495 let mut max_glyph_slot: u32 = 0;
4496 for (line_idx, line) in layout.get_lines().iter().enumerate() {
4497 let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
4498 Self::append_relative_line_glyphs(
4499 (line.get_text().as_str(), line_off_y),
4500 (line_h_phys, box_w_phys, letter_sp, space_step),
4501 (align, ascii_table_idx, key_meta),
4502 (glyph_atlas, font_provider),
4503 line_scratch,
4504 out_glyphs,
4505 (&mut has_fractional_x, &mut max_glyph_slot),
4506 );
4507 }
4508 (has_fractional_x, max_glyph_slot)
4509 }
4510
4511 fn emit_cached_glyph_run(
4524 cached_glyphs: &[PositionedGlyph],
4525 origin: (i32, i32),
4526 clip_dims: (Rect, u32, u32),
4527 out_glyphs: &mut Vec<PositionedGlyph>,
4528 ) -> (u32, u32) {
4529 let (base_x, base_y): (i32, i32) = origin;
4530 let (clip, phys_w, phys_h): (Rect, u32, u32) = clip_dims;
4531 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4532 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4533 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4534 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4535 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4536 return (0, 0);
4537 }
4538 let run_start: u32 = out_glyphs.len() as u32;
4539 for green_val in cached_glyphs.iter() {
4540 let gx0: i32 = base_x + green_val.get_x();
4541 let gw: i32 = green_val.get_width() as i32;
4542 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4543 let gy0: i32 = base_y + green_val.get_y();
4544 let gh: i32 = green_val.get_height() as i32;
4545 if gy0 < clip_y1 && gy0 + gh > clip_y0 {
4546 out_glyphs.push(PositionedGlyph::new(
4547 green_val.get_glyph_idx(),
4548 gx0,
4549 gy0,
4550 green_val.get_width(),
4551 green_val.get_height(),
4552 ));
4553 }
4554 }
4555 }
4556 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
4557 (run_start, run_len)
4558 }
4559
4560 fn resolve_single_line_glyphs(
4576 line_info: (&str, f32),
4577 rect: Rect,
4578 style: TextStyle,
4579 clip_dims: (Rect, u32, u32, f32),
4580 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4581 out_glyphs: &mut Vec<PositionedGlyph>,
4582 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4583 ) -> (u32, u32) {
4584 let (line_str, line_height_px): (&str, f32) = line_info;
4585 let (clip, phys_w, phys_h, scale): (Rect, u32, u32, f32) = clip_dims;
4586 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4587 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4588 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4589 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4590 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4591 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4592 return (0, 0);
4593 }
4594 let line_h_phys: f32 = line_height_px * scale;
4595 let base_x_phys: f32 = (rect.get_x() * scale).round();
4596 let base_y_phys: f32 = (rect.get_y() * scale).round();
4597 if (base_y_phys + line_h_phys) < (clip_y0 as f32) || base_y_phys > (clip_y1 as f32) {
4598 return (0, 0);
4599 }
4600 let phys_font_size: f32 = style.get_font_size() * scale;
4601 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4602 let bold: bool = style.get_weight().is_bold();
4603 let monospace: bool = style.get_family() == FontFamily::Monospace;
4604 let italic: bool = style.get_italic();
4605 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4606 let ascii_table_idx: usize =
4607 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4608 let box_w_phys: f32 = rect.get_width() * scale;
4609 let letter_sp: f32 = style.get_letter_spacing() * scale;
4610 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4611 let align: TextAlign = style.get_align();
4612 let run_start: u32 = out_glyphs.len() as u32;
4613 let clip_x1_f: f32 = clip_x1 as f32;
4614 line_scratch.clear();
4615 let mut line_w_phys: f32 = 0.0;
4616 for ch in line_str.chars() {
4617 if ch == ' ' {
4618 line_w_phys += space_step;
4619 line_scratch.push((u32::MAX, space_step, 0, 0));
4620 } else {
4621 let slot: u32 = if ch.is_ascii() {
4622 glyph_atlas.get_or_rasterize_ascii_slot_with(
4623 ascii_table_idx,
4624 ch as u8,
4625 key_meta,
4626 font_provider,
4627 )
4628 } else {
4629 let key: GlyphKey = GlyphKey {
4630 codepoint: ch,
4631 size_tenths,
4632 bold,
4633 monospace,
4634 italic,
4635 };
4636 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4637 };
4638 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4639 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4640 line_w_phys += adv_phys;
4641 line_scratch.push((
4642 slot,
4643 adv_phys,
4644 glyph.get_width().min(u16::MAX as u32) as u16,
4645 glyph.get_height().min(u16::MAX as u32) as u16,
4646 ));
4647 }
4648 }
4649 let fit_scale: f32 = if box_w_phys > 1.0 && line_w_phys > box_w_phys + 1.0 {
4650 (box_w_phys / line_w_phys).clamp(0.72, 1.0)
4651 } else {
4652 1.0
4653 };
4654 let fitted_w_phys: f32 = line_w_phys * fit_scale;
4655 let align_x: f32 = match align {
4656 TextAlign::Left => 0.0,
4657 TextAlign::Center => ((box_w_phys - fitted_w_phys) * 0.5).max(0.0),
4658 TextAlign::Right => (box_w_phys - fitted_w_phys).max(0.0),
4659 };
4660 let mut pen_x: f32 = base_x_phys + align_x.round();
4661 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4662 if pen_x > clip_x1_f {
4663 break;
4664 }
4665 if slot == u32::MAX {
4666 pen_x += adv_phys * fit_scale;
4667 continue;
4668 }
4669 let gx0: i32 = pen_x.round() as i32;
4670 let gw: i32 = gw_u16 as i32;
4671 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4672 let gy0: i32 =
4673 (base_y_phys + ((line_h_phys - (gh_u16 as f32)) * 0.5).round()) as i32;
4674 if gy0 < clip_y1 && gy0 + (gh_u16 as i32) > clip_y0 {
4675 out_glyphs.push(PositionedGlyph::new(slot, gx0, gy0, gw_u16, gh_u16));
4676 }
4677 }
4678 pen_x += adv_phys * fit_scale;
4679 }
4680 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
4681 (run_start, run_len)
4682 }
4683
4684 fn resolve_text_run_glyphs(
4700 layout: &TextLayoutResult,
4701 rect: Rect,
4702 style: TextStyle,
4703 clip_dims: (Rect, u32, u32, f32),
4704 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4705 out_glyphs: &mut Vec<PositionedGlyph>,
4706 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4707 ) -> (u32, u32) {
4708 let (clip, phys_w, phys_h, scale): (Rect, u32, u32, f32) = clip_dims;
4709 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4710 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4711 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4712 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4713 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4714 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4715 return (0, 0);
4716 }
4717 let phys_font_size: f32 = style.get_font_size() * scale;
4718 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4719 let bold: bool = style.get_weight().is_bold();
4720 let monospace: bool = style.get_family() == FontFamily::Monospace;
4721 let italic: bool = style.get_italic();
4722 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4723 let ascii_table_idx: usize =
4724 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4725 let line_h_phys: f32 = layout.get_line_height_px() * scale;
4726 let box_w_phys: f32 = rect.get_width() * scale;
4727 let letter_sp: f32 = style.get_letter_spacing() * scale;
4728 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4729 let base_x_phys: f32 = (rect.get_x() * scale).round();
4730 let base_y_phys: f32 = (rect.get_y() * scale).round();
4731 let clip_x1_f: f32 = clip_x1 as f32;
4732 let clip_y0_f: f32 = clip_y0 as f32;
4733 let clip_y1_f: f32 = clip_y1 as f32;
4734 let align: TextAlign = style.get_align();
4735 let run_start: u32 = out_glyphs.len() as u32;
4736 for (line_idx, line) in layout.get_lines().iter().enumerate() {
4737 let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
4738 let pen_y: f32 = base_y_phys + line_off_y;
4739 if (pen_y + line_h_phys) < clip_y0_f || pen_y > clip_y1_f {
4740 continue;
4741 }
4742 let line_str: &str = line.get_text().as_str();
4743 line_scratch.clear();
4744 let mut line_w_phys: f32 = 0.0;
4745 if line_str.is_ascii() {
4746 for &byte in line_str.as_bytes() {
4747 if byte == b' ' {
4748 line_w_phys += space_step;
4749 line_scratch.push((u32::MAX, space_step, 0, 0));
4750 } else {
4751 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
4752 ascii_table_idx,
4753 byte,
4754 key_meta,
4755 font_provider,
4756 );
4757 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4758 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4759 line_w_phys += adv_phys;
4760 line_scratch.push((
4761 slot,
4762 adv_phys,
4763 glyph.get_width().min(u16::MAX as u32) as u16,
4764 glyph.get_height().min(u16::MAX as u32) as u16,
4765 ));
4766 }
4767 }
4768 } else {
4769 for ch in line_str.chars() {
4770 if ch == ' ' {
4771 line_w_phys += space_step;
4772 line_scratch.push((u32::MAX, space_step, 0, 0));
4773 } else {
4774 let slot: u32 = if ch.is_ascii() {
4775 glyph_atlas.get_or_rasterize_ascii_slot_with(
4776 ascii_table_idx,
4777 ch as u8,
4778 key_meta,
4779 font_provider,
4780 )
4781 } else {
4782 let key: GlyphKey = GlyphKey {
4783 codepoint: ch,
4784 size_tenths,
4785 bold,
4786 monospace,
4787 italic,
4788 };
4789 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4790 };
4791 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4792 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4793 line_w_phys += adv_phys;
4794 line_scratch.push((
4795 slot,
4796 adv_phys,
4797 glyph.get_width().min(u16::MAX as u32) as u16,
4798 glyph.get_height().min(u16::MAX as u32) as u16,
4799 ));
4800 }
4801 }
4802 }
4803 let fit_scale: f32 = if box_w_phys > 1.0 && line_w_phys > box_w_phys + 1.0 {
4804 (box_w_phys / line_w_phys).clamp(0.72, 1.0)
4805 } else {
4806 1.0
4807 };
4808 let fitted_w_phys: f32 = line_w_phys * fit_scale;
4809 let align_x: f32 = match align {
4810 TextAlign::Left => 0.0,
4811 TextAlign::Center => ((box_w_phys - fitted_w_phys) * 0.5).max(0.0),
4812 TextAlign::Right => (box_w_phys - fitted_w_phys).max(0.0),
4813 };
4814 let mut pen_x: f32 = base_x_phys + align_x.round();
4815 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4816 if slot == u32::MAX {
4817 pen_x += adv_phys * fit_scale;
4818 continue;
4819 }
4820 if pen_x > clip_x1_f {
4821 break;
4822 }
4823 let gx0: i32 = pen_x.round() as i32;
4824 let gw: i32 = gw_u16 as i32;
4825 let gh: i32 = gh_u16 as i32;
4826 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4827 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
4828 let gy0: i32 = (pen_y + glyph_v_off) as i32;
4829 if gy0 < clip_y1 && gy0 + gh > clip_y0 {
4830 out_glyphs.push(PositionedGlyph::new(slot, gx0, gy0, gw_u16, gh_u16));
4831 }
4832 }
4833 pen_x += adv_phys * fit_scale;
4834 }
4835 }
4836 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
4837 (run_start, run_len)
4838 }
4839
4840 #[must_use]
4854 fn resolve_text_caret_rect(
4855 layout_opt: Option<&TextLayoutResult>,
4856 rects: (Rect, Rect),
4857 style: TextStyle,
4858 caret_opts: (f32, f32, bool),
4859 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4860 ) -> Rect {
4861 let (text_rect, content_rect): (Rect, Rect) = rects;
4862 let (caret_height, scale, multiline): (f32, f32, bool) = caret_opts;
4863 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4864 let phys_font_size: f32 = style.get_font_size() * scale;
4865 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4866 let bold: bool = style.get_weight().is_bold();
4867 let monospace: bool = style.get_family() == FontFamily::Monospace;
4868 let italic: bool = style.get_italic();
4869 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4870 let letter_sp: f32 = style.get_letter_spacing() * scale;
4871 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4872 let (last_w_phys, line_idx, line_h_phys): (f32, usize, f32) =
4873 if let Some(layout) = layout_opt {
4874 let lh: f32 = layout.get_line_height_px() * scale;
4875 let idx: usize = layout.get_lines().len().saturating_sub(1);
4876 let w_phys: f32 = if let Some(line) = layout.get_lines().last() {
4877 let ascii_table_idx: usize =
4878 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4879 let mut acc: f32 = 0.0;
4880 for ch in line.get_text().chars() {
4881 if ch == ' ' {
4882 acc += space_step;
4883 } else {
4884 let slot: u32 = if ch.is_ascii() {
4885 glyph_atlas.get_or_rasterize_ascii_slot_with(
4886 ascii_table_idx,
4887 ch as u8,
4888 key_meta,
4889 font_provider,
4890 )
4891 } else {
4892 let key: GlyphKey = GlyphKey {
4893 codepoint: ch,
4894 size_tenths,
4895 bold,
4896 monospace,
4897 italic,
4898 };
4899 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4900 };
4901 let adv: f32 =
4902 (glyph_atlas.glyph_by_slot(slot).get_advance() as f32).max(1.0);
4903 acc += adv + letter_sp;
4904 }
4905 }
4906 acc
4907 } else {
4908 0.0
4909 };
4910 (w_phys, idx, lh)
4911 } else {
4912 (
4913 0.0,
4914 0,
4915 (style.get_font_size() * style.get_line_height()).max(1.0) * scale,
4916 )
4917 };
4918 let caret_h_phys: f32 = (caret_height * scale).max(2.0);
4919 let caret_w_phys: f32 = (1.5 * scale).max(1.5);
4920 let min_x: f32 = content_rect.get_x() * scale;
4921 let max_x: f32 = (content_rect.right() * scale - caret_w_phys - 1.0).max(min_x);
4922 let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.0 * scale } else { 0.0 };
4923 let caret_x_phys: f32 = (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys)
4924 .min(max_x)
4925 .max(min_x);
4926 let caret_y_phys: f32 = if multiline {
4927 let raw_y: f32 = content_rect.get_y() * scale
4928 + (line_idx as f32) * line_h_phys
4929 + ((line_h_phys - caret_h_phys) * 0.5).max(0.0);
4930 raw_y
4931 .min(content_rect.bottom() * scale - caret_h_phys)
4932 .max(content_rect.get_y() * scale)
4933 } else {
4934 content_rect.get_y() * scale
4935 + ((content_rect.get_height() * scale - caret_h_phys) * 0.5).max(0.0)
4936 };
4937 Rect::new(
4938 caret_x_phys.round(),
4939 caret_y_phys.round(),
4940 caret_w_phys.round().max(1.0),
4941 caret_h_phys.round().max(2.0),
4942 )
4943 }
4944
4945 #[must_use]
4957 fn collect_active_rounded(
4958 stack: &[Option<RoundedClipMask>],
4959 out: &mut Vec<RoundedClipMask>,
4960 vis: Rect,
4961 ) -> (u32, u16) {
4962 let start: u32 = out.len() as u32;
4963 for entry in stack.iter().copied().flatten() {
4964 if rect_intersects_rounded_corners(vis, entry.get_rect(), entry.get_radius()) {
4965 out.push(entry);
4966 }
4967 }
4968 let len: u16 = (out.len() as u32)
4969 .saturating_sub(start)
4970 .min(u16::MAX as u32) as u16;
4971 (start, len)
4972 }
4973
4974 #[must_use]
4985 fn resolve_opaque_clear_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
4986 let Some(DrawCommand::FillRoundedRect {
4987 rect,
4988 color,
4989 radius,
4990 border,
4991 }) = next_cmd
4992 else {
4993 return (Rect::default(), Rect::default());
4994 };
4995 if color.get_alpha() != 255 {
4996 return (Rect::default(), Rect::default());
4997 }
4998 let border_width: f32 = if border.get_width() > 0.0 && border.get_color().get_alpha() < 255
4999 {
5000 (border.get_width() * scale).max(1.0)
5001 } else {
5002 0.0
5003 };
5004 let phys: Rect = snap_physical_rect(*rect, scale);
5005 let r_max: f32 = Self::scale_radius(*radius, scale)
5006 .max_radius()
5007 .min(phys.get_width() * 0.5)
5008 .min(phys.get_height() * 0.5);
5009 let pad: f32 = 1.5 + border_width;
5010 let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
5011 let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
5012 let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
5013 Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
5014 } else {
5015 Rect::default()
5016 };
5017 let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
5018 let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
5019 let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
5020 Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
5021 } else {
5022 Rect::default()
5023 };
5024 (cut_h, cut_v)
5025 }
5026
5027 #[must_use]
5038 fn resolve_opaque_shadow_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
5039 let Some(DrawCommand::FillRoundedRect {
5040 rect,
5041 color,
5042 radius,
5043 ..
5044 }) = next_cmd
5045 else {
5046 return (Rect::default(), Rect::default());
5047 };
5048 if color.get_alpha() != 255 {
5049 return (Rect::default(), Rect::default());
5050 }
5051 let phys: Rect = snap_physical_rect(*rect, scale);
5052 let r_max: f32 = Self::scale_radius(*radius, scale)
5053 .max_radius()
5054 .min(phys.get_width() * 0.5)
5055 .min(phys.get_height() * 0.5);
5056 let pad: f32 = 1.5;
5057 let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
5058 let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
5059 let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
5060 Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
5061 } else {
5062 Rect::default()
5063 };
5064 let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
5065 let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
5066 let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
5067 Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
5068 } else {
5069 Rect::default()
5070 };
5071 (cut_h, cut_v)
5072 }
5073
5074 fn save_single_cached_rounded_corners(
5089 band: &mut PixelBand<'_>,
5090 mask: RoundedClipMask,
5091 clip: Rect,
5092 band_bounds: (u32, u32, u32),
5093 corner_masks: &[CachedCornerMask],
5094 scratch: &mut BandCornerScratch,
5095 ) -> bool {
5096 let (fb_w, band_y0, band_y1): (u32, u32, u32) = band_bounds;
5097 let clip_x0: i32 = (clip.get_x().floor().max(0.0) as u32).min(fb_w) as i32;
5098 let clip_y0: i32 = (clip.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
5099 let clip_x1: i32 = (clip.right().ceil().max(0.0) as u32).min(fb_w) as i32;
5100 let clip_y1: i32 = (clip.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
5101 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
5102 return false;
5103 }
5104 let rect: Rect = mask.get_rect();
5105 let rx0_i: i32 = rect.get_x().round() as i32;
5106 let ry0_i: i32 = rect.get_y().round() as i32;
5107 let rx1_i: i32 = rect.right().round() as i32;
5108 let ry1_i: i32 = rect.bottom().round() as i32;
5109 let mask_ids: [u32; 4] = mask.get_corner_mask_ids();
5110 scratch.saved_bytes.clear();
5111 scratch.saved_rows.clear();
5112 for (query_val, &mask_id) in mask_ids.iter().enumerate() {
5113 if mask_id == u32::MAX {
5114 continue;
5115 }
5116 let Some(cm) = corner_masks.get(mask_id as usize) else {
5117 continue;
5118 };
5119 let dim_i: i32 = cm.dim as i32;
5120 let origin_x: i32 = if query_val == 0 || query_val == 3 {
5121 rx0_i
5122 } else {
5123 rx1_i - dim_i
5124 };
5125 let origin_y: i32 = if query_val == 0 || query_val == 1 {
5126 ry0_i
5127 } else {
5128 ry1_i - dim_i
5129 };
5130 let bx0: i32 = origin_x.max(clip_x0);
5131 let bx1: i32 = (origin_x + dim_i).min(clip_x1);
5132 let by0: i32 = origin_y.max(clip_y0);
5133 let by1: i32 = (origin_y + dim_i).min(clip_y1);
5134 if bx0 >= bx1 || by0 >= by1 {
5135 continue;
5136 }
5137 for y_i in by0..by1 {
5138 let my: usize = (y_i - origin_y) as usize;
5139 let span: CornerMaskRowSpan = cm.row_spans[my];
5140 if span.dirty_start >= span.dirty_end {
5141 continue;
5142 }
5143 let sx0_i: i32 = (origin_x + (span.dirty_start as i32)).max(bx0);
5144 let sx1_i: i32 = (origin_x + (span.dirty_end as i32)).min(bx1);
5145 if sx0_i >= sx1_i {
5146 continue;
5147 }
5148 let pos_y: u32 = y_i as u32;
5149 let sx0: u32 = sx0_i as u32;
5150 let sx1: u32 = sx1_i as u32;
5151 if let Some(row) = band.row_slice_mut(pos_y) {
5152 let b0: usize = (sx0 as usize) * 4;
5153 let b1: usize = (sx1 as usize) * 4;
5154 let byte_off: usize = scratch.saved_bytes.len();
5155 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5156 scratch.saved_rows.push(SavedCornerRow {
5157 y: pos_y,
5158 sx0,
5159 sx1,
5160 byte_off,
5161 mask_id,
5162 origin_x,
5163 origin_y,
5164 });
5165 }
5166 }
5167 }
5168 !scratch.saved_rows.is_empty()
5169 }
5170
5171 fn restore_single_cached_rounded_corners(
5179 band: &mut PixelBand<'_>,
5180 corner_masks: &[CachedCornerMask],
5181 scratch: &BandCornerScratch,
5182 ) {
5183 let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
5184 for entry in scratch.saved_rows.iter() {
5185 let Some(row) = band.row_slice_mut(entry.y) else {
5186 continue;
5187 };
5188 let cm: &CachedCornerMask = &corner_masks[entry.mask_id as usize];
5189 let dim: usize = cm.dim as usize;
5190 let my: usize = ((entry.y as i32) - entry.origin_y) as usize;
5191 let span: CornerMaskRowSpan = cm.row_spans[my];
5192 let sx0_i: i32 = entry.sx0 as i32;
5193 let sx1_i: i32 = entry.sx1 as i32;
5194 if span.ext_start < span.ext_end {
5195 let ex0: i32 = (entry.origin_x + (span.ext_start as i32)).max(sx0_i);
5196 let ex1: i32 = (entry.origin_x + (span.ext_end as i32)).min(sx1_i);
5197 if ex0 < ex1 {
5198 let dst_b0: usize = (ex0 as usize) * 4;
5199 let dst_b1: usize = (ex1 as usize) * 4;
5200 let src_b0: usize = entry.byte_off + ((ex0 - sx0_i) as usize) * 4;
5201 let src_b1: usize = src_b0 + (dst_b1 - dst_b0);
5202 row[dst_b0..dst_b1].copy_from_slice(&saved_bytes[src_b0..src_b1]);
5203 }
5204 }
5205 if span.aa_start < span.aa_end {
5206 let ax0: i32 = (entry.origin_x + (span.aa_start as i32)).max(sx0_i);
5207 let ax1: i32 = (entry.origin_x + (span.aa_end as i32)).min(sx1_i);
5208 if ax0 < ax1 {
5209 let cov_row: &[u8] = &cm.cov[my * dim..(my + 1) * dim];
5210 for x_i in ax0..ax1 {
5211 let mx: usize = (x_i - entry.origin_x) as usize;
5212 let cov_u8: u8 = cov_row[mx];
5213 if cov_u8 >= 16 {
5214 continue;
5215 }
5216 let dst_off: usize = (x_i as usize) * 4;
5217 let src_off: usize = entry.byte_off + ((x_i - sx0_i) as usize) * 4;
5218 let saved_rgba: [u8; 4] = [
5219 saved_bytes[src_off],
5220 saved_bytes[src_off + 1],
5221 saved_bytes[src_off + 2],
5222 saved_bytes[src_off + 3],
5223 ];
5224 if cov_u8 == 0 {
5225 row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
5226 } else {
5227 let cov: f32 = (cov_u8 as f32) * 0.0625;
5228 lerp_pixel_slice_from_saved_linear(
5229 &mut row[dst_off..dst_off + 4],
5230 saved_rgba,
5231 cov,
5232 );
5233 }
5234 }
5235 }
5236 }
5237 }
5238 }
5239
5240 pub(crate) fn render_band(
5255 band: &mut PixelBand<'_>,
5256 commands: &[DrawCommand],
5257 prepped: &[PreppedCommand],
5258 aux: BandAuxSlices<'_>,
5259 glyph_atlas: &GlyphAtlas,
5260 render_opts: (f32, AntialiasingMode),
5261 ) -> usize {
5262 let BandAuxSlices {
5263 positioned_glyphs,
5264 caret_rects,
5265 rounded_clips,
5266 corner_masks,
5267 } = aux;
5268 let (scale, aa): (f32, AntialiasingMode) = render_opts;
5269 let band_y0: u32 = band.y_offset();
5270 let band_y1: u32 = band.y_end();
5271 let fb_w: u32 = band.width();
5272 let band_rect: Rect =
5273 Rect::new(0.0, band_y0 as f32, fb_w as f32, (band_y1 - band_y0) as f32);
5274 let has_any_rounded: bool = !rounded_clips.is_empty();
5275 let mut scratch: BandCornerScratch = if has_any_rounded {
5276 BAND_CORNER_SCRATCH
5277 .try_with(|cell: &RefCell<BandCornerScratch>| {
5278 cell.try_borrow_mut()
5279 .ok()
5280 .map(|mut guard: RefMut<'_, BandCornerScratch>| take(&mut *guard))
5281 })
5282 .ok()
5283 .flatten()
5284 .unwrap_or_default()
5285 } else {
5286 BandCornerScratch::default()
5287 };
5288 let mut shaded: usize = 0;
5289 let prepped_len: usize = prepped.len();
5290 let mut idx: usize = 0;
5291 while idx < prepped_len {
5292 let item: &PreppedCommand = &prepped[idx];
5293 if item.get_cmd_index() == usize::MAX {
5294 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
5295 idx += (item.get_skip_delta() as usize).max(1);
5296 } else {
5297 idx += 1;
5298 }
5299 continue;
5300 }
5301 idx += 1;
5302 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
5303 continue;
5304 }
5305 let Some(active_clip) = item.get_active_clip().intersect(band_rect) else {
5306 continue;
5307 };
5308 let rc_len: usize = item.get_rounded_clip_len() as usize;
5309 let item_masks: &[RoundedClipMask] = if rc_len > 0 {
5310 let start: usize = item.get_rounded_clip_start() as usize;
5311 let end: usize = start.saturating_add(rc_len).min(rounded_clips.len());
5312 &rounded_clips[start..end]
5313 } else {
5314 &[]
5315 };
5316 let mut corner_mode: u8 = 0;
5317 if item_masks.len() == 1 {
5318 let mask: RoundedClipMask = item_masks[0];
5319 let rect: Rect = mask.get_rect();
5320 let max_r: f32 = (rect.get_width() * 0.5)
5321 .min(rect.get_height() * 0.5)
5322 .max(0.0);
5323 let radius: CornerRadius = mask.get_radius();
5324 let radii: [f32; 4] = [
5325 radius.get_top_left().min(max_r),
5326 radius.get_top_right().min(max_r),
5327 radius.get_bottom_right().min(max_r),
5328 radius.get_bottom_left().min(max_r),
5329 ];
5330 let ids: [u32; 4] = mask.get_corner_mask_ids();
5331 let all_cached: bool =
5332 radii
5333 .iter()
5334 .zip(ids.iter())
5335 .all(|(&red_val, &id): (&f32, &u32)| {
5336 red_val <= 0.25 || (id as usize) < corner_masks.len()
5337 });
5338 if all_cached {
5339 if Self::save_single_cached_rounded_corners(
5340 band,
5341 mask,
5342 active_clip,
5343 (fb_w, band_y0, band_y1),
5344 corner_masks,
5345 &mut scratch,
5346 ) {
5347 corner_mode = 1;
5348 }
5349 } else {
5350 scratch.corner_boxes.clear();
5351 scratch.saved_bytes.clear();
5352 collect_rounded_clip_boxes(
5353 mask,
5354 active_clip,
5355 (fb_w, band_y0, band_y1),
5356 &mut scratch.corner_boxes,
5357 );
5358 if !scratch.corner_boxes.is_empty() {
5359 for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
5360 let b0: usize = (bx0 as usize) * 4;
5361 let b1: usize = (bx1 as usize) * 4;
5362 for pos_y in by0..by1 {
5363 if let Some(row) = band.row_slice_mut(pos_y) {
5364 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5365 }
5366 }
5367 }
5368 corner_mode = 2;
5369 }
5370 }
5371 } else if !item_masks.is_empty() {
5372 scratch.corner_boxes.clear();
5373 scratch.saved_bytes.clear();
5374 for mask in item_masks.iter().copied() {
5375 collect_rounded_clip_boxes(
5376 mask,
5377 active_clip,
5378 (fb_w, band_y0, band_y1),
5379 &mut scratch.corner_boxes,
5380 );
5381 }
5382 if !scratch.corner_boxes.is_empty() {
5383 for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
5384 let b0: usize = (bx0 as usize) * 4;
5385 let b1: usize = (bx1 as usize) * 4;
5386 for coord_y in by0..by1 {
5387 if let Some(row) = band.row_slice_mut(coord_y) {
5388 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5389 }
5390 }
5391 }
5392 corner_mode = 2;
5393 }
5394 }
5395 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
5396 shaded += match cmd {
5397 DrawCommand::Clear(color) => {
5398 let cutouts: (Rect, Rect) =
5399 (item.get_opaque_cutout_h(), item.get_opaque_cutout_v());
5400 if cutouts.0.get_width() > 0.0 || cutouts.1.get_width() > 0.0 {
5401 let cx0: u32 = (active_clip.get_x().floor().max(0.0) as u32).min(fb_w);
5402 let cx1: u32 = (active_clip.right().ceil().max(0.0) as u32).min(fb_w);
5403 let cy0: u32 = (active_clip.get_y().floor().max(0.0) as u32)
5404 .max(band_y0)
5405 .min(band_y1);
5406 let cy1: u32 = (active_clip.bottom().ceil().max(0.0) as u32)
5407 .max(band_y0)
5408 .min(band_y1);
5409 let rgba: [u8; 4] = [
5410 color.get_red(),
5411 color.get_green(),
5412 color.get_blue(),
5413 color.get_alpha(),
5414 ];
5415 let mut count: usize = 0;
5416 if cx0 < cx1 && cy0 < cy1 {
5417 for sample_y in cy0..cy1 {
5418 let (cut0, cut1): (u32, u32) =
5419 Self::shadow_row_cutout(sample_y, cutouts, cx0, cx1);
5420 if cut0 <= cx0 && cut1 >= cx1 {
5421 continue;
5422 }
5423 if let Some(row) = band.row_slice_mut(sample_y) {
5424 if cut0 < cut1 {
5425 if cx0 < cut0 {
5426 fill_rgba_span_32(
5427 &mut row[(cx0 as usize) * 4..(cut0 as usize) * 4],
5428 rgba,
5429 );
5430 count += (cut0 - cx0) as usize;
5431 }
5432 if cut1 < cx1 {
5433 fill_rgba_span_32(
5434 &mut row[(cut1 as usize) * 4..(cx1 as usize) * 4],
5435 rgba,
5436 );
5437 count += (cx1 - cut1) as usize;
5438 }
5439 } else {
5440 fill_rgba_span_32(
5441 &mut row[(cx0 as usize) * 4..(cx1 as usize) * 4],
5442 rgba,
5443 );
5444 count += (cx1 - cx0) as usize;
5445 }
5446 }
5447 }
5448 }
5449 count
5450 } else if active_clip.get_x() <= 0.0
5451 && active_clip.get_width() >= (band.width() as f32)
5452 && active_clip.get_y() <= (band_y0 as f32)
5453 && active_clip.bottom() >= (band_y1 as f32)
5454 {
5455 band.clear(*color);
5456 (band.width() as usize) * ((band_y1 - band_y0) as usize)
5457 } else {
5458 Self::fill_rect_clipped(band, active_clip, *color, active_clip)
5459 }
5460 }
5461 DrawCommand::FillRoundedRect {
5462 rect,
5463 color,
5464 radius,
5465 border,
5466 } => {
5467 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5468 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5469 let border_width: f32 = if border.get_width() > 0.0 {
5470 (border.get_width() * scale).max(1.0)
5471 } else {
5472 0.0
5473 };
5474 let phys_border: Border = Border::new(border_width, border.get_color());
5475 Self::raster_rounded_rect(
5476 band,
5477 phys_rect,
5478 *color,
5479 phys_radius,
5480 phys_border,
5481 active_clip,
5482 aa,
5483 )
5484 }
5485 DrawCommand::LinearGradientRect {
5486 rect,
5487 gradient,
5488 radius,
5489 } => {
5490 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5491 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5492 Self::raster_gradient_rect(
5493 band,
5494 phys_rect,
5495 *gradient,
5496 phys_radius,
5497 active_clip,
5498 aa,
5499 )
5500 }
5501 DrawCommand::BoxShadow {
5502 rect,
5503 radius,
5504 shadow,
5505 } => {
5506 let spread: f32 = shadow.get_spread_radius() * scale;
5507 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
5508 let sigma: f32 = (blur * 0.5).max(0.75);
5509 let pad: f32 = (sigma * 3.0).ceil();
5510 let base_rect: Rect = snap_physical_rect(*rect, scale);
5511 let caster_rect: Rect = Rect::new(
5512 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
5513 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
5514 (base_rect.get_width() + spread * 2.0).max(1.0),
5515 (base_rect.get_height() + spread * 2.0).max(1.0),
5516 );
5517 let shadow_rect: Rect = Rect::new(
5518 caster_rect.get_x() - pad,
5519 caster_rect.get_y() - pad,
5520 caster_rect.get_width() + pad * 2.0,
5521 caster_rect.get_height() + pad * 2.0,
5522 );
5523 let raw_r: CornerRadius = Self::scale_radius(*radius, scale);
5524 let phys_radius: CornerRadius = CornerRadius::new(
5525 (raw_r.get_top_left() + spread).max(0.0),
5526 (raw_r.get_top_right() + spread).max(0.0),
5527 (raw_r.get_bottom_right() + spread).max(0.0),
5528 (raw_r.get_bottom_left() + spread).max(0.0),
5529 );
5530 Self::raster_shadow(
5531 band,
5532 (shadow_rect, caster_rect, active_clip),
5533 phys_radius,
5534 sigma,
5535 shadow.get_color(),
5536 (item.get_opaque_cutout_h(), item.get_opaque_cutout_v()),
5537 )
5538 }
5539 DrawCommand::BackdropBlur {
5540 rect,
5541 radius,
5542 blur_radius,
5543 } => {
5544 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5545 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5546 let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 48.0);
5547 Self::raster_backdrop_blur(band, phys_rect, phys_radius, phys_blur, active_clip)
5548 }
5549 DrawCommand::TextRun { style, .. } => {
5550 let g_start: usize = item.get_glyph_run_start() as usize;
5551 let g_len: usize = item.get_glyph_run_len() as usize;
5552 if let Some(run_slice) = positioned_glyphs.get(g_start..g_start + g_len) {
5553 Self::raster_text_run_band(
5554 band,
5555 run_slice,
5556 style.get_color(),
5557 active_clip,
5558 glyph_atlas,
5559 )
5560 } else {
5561 0
5562 }
5563 }
5564 DrawCommand::TextCaret { color, .. } => {
5565 let cidx: usize = item.get_caret_rect_idx() as usize;
5566 if let Some(&caret_rect) = caret_rects.get(cidx) {
5567 Self::raster_rounded_rect(
5568 band,
5569 caret_rect,
5570 *color,
5571 CornerRadius::all(0.5 * scale),
5572 Border::default(),
5573 active_clip,
5574 aa,
5575 )
5576 } else {
5577 0
5578 }
5579 }
5580 DrawCommand::Image {
5581 rect,
5582 buffer,
5583 radius,
5584 } => {
5585 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5586 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5587 Self::raster_rgba_bytes(
5588 band,
5589 phys_rect,
5590 (buffer.get_width(), buffer.get_height(), buffer.get_pixels()),
5591 phys_radius,
5592 active_clip,
5593 aa,
5594 )
5595 }
5596 DrawCommand::SharedImage {
5597 rect,
5598 width,
5599 height,
5600 pixels,
5601 radius,
5602 } => {
5603 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5604 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5605 Self::raster_rgba_bytes(
5606 band,
5607 phys_rect,
5608 (*width, *height, pixels.as_slice()),
5609 phys_radius,
5610 active_clip,
5611 aa,
5612 )
5613 }
5614 DrawCommand::Line {
5615 from,
5616 to,
5617 color,
5618 width,
5619 } => {
5620 let p0: Point = Point::new(from.get_x() * scale, from.get_y() * scale);
5621 let p1: Point = Point::new(to.get_x() * scale, to.get_y() * scale);
5622 Self::raster_line(
5623 band,
5624 p0,
5625 p1,
5626 *color,
5627 (width * scale).max(1.0),
5628 active_clip,
5629 aa,
5630 )
5631 }
5632 DrawCommand::Circle {
5633 center,
5634 radius,
5635 color,
5636 } => {
5637 let point_coords: Point =
5638 Point::new(center.get_x() * scale, center.get_y() * scale);
5639 Self::raster_circle(band, point_coords, radius * scale, *color, active_clip, aa)
5640 }
5641 DrawCommand::Triangle { p0, p1, p2, color } => {
5642 let v0: Point = Point::new(p0.get_x() * scale, p0.get_y() * scale);
5643 let v1: Point = Point::new(p1.get_x() * scale, p1.get_y() * scale);
5644 let v2: Point = Point::new(p2.get_x() * scale, p2.get_y() * scale);
5645 Self::raster_triangle(band, v0, v1, v2, *color, active_clip, aa)
5646 }
5647 DrawCommand::SpriteRegion {
5648 rect,
5649 buffer,
5650 src_rect,
5651 tint,
5652 } => {
5653 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5654 Self::raster_sprite_region(
5655 band,
5656 phys_rect,
5657 buffer,
5658 *src_rect,
5659 *tint,
5660 active_clip,
5661 aa,
5662 )
5663 }
5664 DrawCommand::ExternalSurface { .. }
5665 | DrawCommand::PushClip(_)
5666 | DrawCommand::PushRoundedClip { .. }
5667 | DrawCommand::PopClip => 0,
5668 };
5669 if corner_mode == 1 {
5670 Self::restore_single_cached_rounded_corners(band, corner_masks, &scratch);
5671 } else if corner_mode == 2 {
5672 let multi_mask: bool = item_masks.len() > 1;
5673 let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
5674 let mut byte_cursor: usize = 0;
5675 for (box_idx, &(bx0, by0, bx1, by1)) in scratch.corner_boxes.iter().enumerate() {
5676 for value_y in by0..by1 {
5677 let Some(row) = band.row_slice_mut(value_y) else {
5678 byte_cursor += ((bx1 - bx0) as usize) * 4;
5679 continue;
5680 };
5681 for pos_x in bx0..bx1 {
5682 let saved_rgba: [u8; 4] = [
5683 saved_bytes[byte_cursor],
5684 saved_bytes[byte_cursor + 1],
5685 saved_bytes[byte_cursor + 2],
5686 saved_bytes[byte_cursor + 3],
5687 ];
5688 byte_cursor += 4;
5689 if multi_mask
5690 && scratch.corner_boxes[..box_idx].iter().any(
5691 |&(px0, py0, px1, py1): &(u32, u32, u32, u32)| {
5692 pos_x >= px0
5693 && pos_x < px1
5694 && value_y >= py0
5695 && value_y < py1
5696 },
5697 )
5698 {
5699 continue;
5700 }
5701 let mut cov: f32 = 1.0;
5702 for mask in item_masks.iter().copied() {
5703 cov *= rounded_clip_coverage_cached(
5704 pos_x,
5705 value_y,
5706 mask,
5707 corner_masks,
5708 aa,
5709 );
5710 if cov <= 0.0005 {
5711 break;
5712 }
5713 }
5714 let dst_off: usize = (pos_x as usize) * 4;
5715 if cov <= 0.0005 {
5716 row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
5717 } else if cov < 0.9995 {
5718 lerp_pixel_slice_from_saved_linear(
5719 &mut row[dst_off..dst_off + 4],
5720 saved_rgba,
5721 cov,
5722 );
5723 }
5724 }
5725 }
5726 }
5727 }
5728 }
5729 if has_any_rounded {
5730 let _: bool = BAND_CORNER_SCRATCH
5731 .try_with(|cell: &RefCell<BandCornerScratch>| {
5732 if let Ok(mut guard) = cell.try_borrow_mut() {
5733 *guard = scratch;
5734 }
5735 })
5736 .is_ok();
5737 }
5738 shaded
5739 }
5740
5741 fn scale_rect(rect: Rect, scale: f32) -> Rect {
5752 Rect::new(
5753 rect.get_x() * scale,
5754 rect.get_y() * scale,
5755 rect.get_width() * scale,
5756 rect.get_height() * scale,
5757 )
5758 }
5759
5760 fn scale_radius(radius: CornerRadius, scale: f32) -> CornerRadius {
5771 CornerRadius::new(
5772 radius.get_top_left() * scale,
5773 radius.get_top_right() * scale,
5774 radius.get_bottom_right() * scale,
5775 radius.get_bottom_left() * scale,
5776 )
5777 }
5778
5779 fn fill_rect_clipped(band: &mut PixelBand<'_>, rect: Rect, color: Color, clip: Rect) -> usize {
5792 if color.get_alpha() == 0 {
5793 return 0;
5794 }
5795 let Some(vis) = rect.intersect(clip) else {
5796 return 0;
5797 };
5798 let fb_w: u32 = band.width();
5799 let band_y0: u32 = band.y_offset();
5800 let band_y1: u32 = band.y_end();
5801 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
5802 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
5803 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
5804 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
5805 if x0 >= x1 || y0 >= y1 {
5806 return 0;
5807 }
5808 let span_len: usize = (x1 - x0) as usize;
5809 let rows: usize = (y1 - y0) as usize;
5810 let sa: u8 = color.get_alpha();
5811 if sa == 255 {
5812 band.fill_rect_opaque_preclipped(
5813 x0,
5814 x1,
5815 y0,
5816 y1,
5817 [color.get_red(), color.get_green(), color.get_blue(), 255],
5818 );
5819 } else if let Some((rows_buf, row_stride)) = band.rows_slice_mut(y0, y1) {
5820 let bx0: usize = (x0 as usize) * 4;
5821 let bx1: usize = (x1 as usize) * 4;
5822 if span_len.saturating_mul(rows) >= 512 {
5823 let luts: [[u8; 256]; 4] = build_linear_blend_luts(color);
5824 for row in rows_buf.chunks_exact_mut(row_stride) {
5825 fill_span_linear_luts_slice(&mut row[bx0..bx1], &luts);
5826 }
5827 } else {
5828 for row in rows_buf.chunks_exact_mut(row_stride) {
5829 fill_span_linear_slice(&mut row[bx0..bx1], color);
5830 }
5831 }
5832 }
5833 span_len * rows
5834 }
5835
5836 #[must_use]
5851 fn build_vertical_edge_strip(
5852 x_span: (u32, u32),
5853 geom: (f32, f32, f32, f32),
5854 colors: (Color, Border),
5855 lin_colors: ([f32; 4], [f32; 4]),
5856 aa: AntialiasingMode,
5857 out: &mut [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP],
5858 ) -> (usize, usize) {
5859 let (x_start, x_end): (u32, u32) = x_span;
5860 let (cx, half_w, half_h, border_width): (f32, f32, f32, f32) = geom;
5861 let (color, border): (Color, Border) = colors;
5862 let (fill_lin, border_lin): ([f32; 4], [f32; 4]) = lin_colors;
5863 let has_border: bool = border_width > 0.0 && border.get_color().get_alpha() > 0;
5864 let inner_hw: f32 = (half_w - border_width).max(0.0);
5865 let inner_hh: f32 = (half_h - border_width).max(0.0);
5866 let mut len: usize = 0;
5867 let mut shaded: usize = 0;
5868 for pos_x in x_start..x_end {
5869 let px: f32 = (pos_x as f32) + 0.5 - cx;
5870 let dist: f32 = px.abs() - half_w;
5871 if dist > 0.85 {
5872 continue;
5873 }
5874 if !has_border {
5875 if dist < -0.85 {
5876 let sa: u8 = color.get_alpha();
5877 if sa > 0 {
5878 let alpha_val: f32 = (sa as f32) * (1.0 / 255.0);
5879 out[len] = EdgeBlendSample {
5880 x: pos_x,
5881 rgba: [color.get_red(), color.get_green(), color.get_blue(), 255],
5882 sr_a: fill_lin[0] * alpha_val,
5883 sg_a: fill_lin[1] * alpha_val,
5884 sb_a: fill_lin[2] * alpha_val,
5885 inv_a: 1.0 - alpha_val,
5886 sa_u32: sa as u32,
5887 is_opaque: sa == 255,
5888 };
5889 len += 1;
5890 shaded += 1;
5891 }
5892 continue;
5893 }
5894 let outer_cov: f32 = sdf_coverage(dist, aa);
5895 if outer_cov > 0.0 && color.get_alpha() > 0 {
5896 let alpha_f: f32 = ((color.get_alpha() as f32) * (1.0 / 255.0)) * outer_cov;
5897 shaded += 1;
5898 if alpha_f > 0.0002 {
5899 let first_val: f32 = alpha_f.clamp(0.0, 1.0);
5900 out[len] = EdgeBlendSample {
5901 x: pos_x,
5902 rgba: [color.get_red(), color.get_green(), color.get_blue(), 255],
5903 sr_a: fill_lin[0] * first_val,
5904 sg_a: fill_lin[1] * first_val,
5905 sb_a: fill_lin[2] * first_val,
5906 inv_a: 1.0 - first_val,
5907 sa_u32: (first_val * 255.0) as u32,
5908 is_opaque: first_val >= 0.9995,
5909 };
5910 len += 1;
5911 }
5912 }
5913 continue;
5914 }
5915 if dist < -(border_width + 0.85) {
5916 let sa: u8 = color.get_alpha();
5917 if sa > 0 {
5918 let area_val: f32 = (sa as f32) * (1.0 / 255.0);
5919 out[len] = EdgeBlendSample {
5920 x: pos_x,
5921 rgba: [color.get_red(), color.get_green(), color.get_blue(), 255],
5922 sr_a: fill_lin[0] * area_val,
5923 sg_a: fill_lin[1] * area_val,
5924 sb_a: fill_lin[2] * area_val,
5925 inv_a: 1.0 - area_val,
5926 sa_u32: sa as u32,
5927 is_opaque: sa == 255,
5928 };
5929 len += 1;
5930 shaded += 1;
5931 }
5932 continue;
5933 }
5934 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
5935 px.abs() - inner_hw
5936 } else {
5937 2.0
5938 };
5939 if dist < -0.85 && inner_dist > 0.85 {
5940 let bc: Color = border.get_color();
5941 let sa: u8 = bc.get_alpha();
5942 let alpha_val_primary: f32 = (sa as f32) * (1.0 / 255.0);
5943 out[len] = EdgeBlendSample {
5944 x: pos_x,
5945 rgba: [bc.get_red(), bc.get_green(), bc.get_blue(), 255],
5946 sr_a: border_lin[0] * alpha_val_primary,
5947 sg_a: border_lin[1] * alpha_val_primary,
5948 sb_a: border_lin[2] * alpha_val_primary,
5949 inv_a: 1.0 - alpha_val_primary,
5950 sa_u32: sa as u32,
5951 is_opaque: sa == 255,
5952 };
5953 len += 1;
5954 shaded += 1;
5955 continue;
5956 }
5957 let outer_cov: f32 = sdf_coverage(dist, aa);
5958 if outer_cov <= 0.0 {
5959 continue;
5960 }
5961 let inner_cov: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
5962 sdf_coverage(inner_dist, aa)
5963 } else {
5964 0.0
5965 };
5966 let mixed: Color =
5967 composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
5968 let sa: u8 = mixed.get_alpha();
5969 if sa > 0 {
5970 let alpha_val_secondary: f32 = (sa as f32) * (1.0 / 255.0);
5971 out[len] = EdgeBlendSample {
5972 x: pos_x,
5973 rgba: [mixed.get_red(), mixed.get_green(), mixed.get_blue(), 255],
5974 sr_a: SRGB_TO_LIN_LUT[mixed.get_red() as usize] * alpha_val_secondary,
5975 sg_a: SRGB_TO_LIN_LUT[mixed.get_green() as usize] * alpha_val_secondary,
5976 sb_a: SRGB_TO_LIN_LUT[mixed.get_blue() as usize] * alpha_val_secondary,
5977 inv_a: 1.0 - alpha_val_secondary,
5978 sa_u32: sa as u32,
5979 is_opaque: sa == 255,
5980 };
5981 len += 1;
5982 shaded += 1;
5983 }
5984 }
5985 (len, shaded)
5986 }
5987
5988 fn raster_rounded_rect(
6004 band: &mut PixelBand<'_>,
6005 rect: Rect,
6006 color: Color,
6007 radius: CornerRadius,
6008 border: Border,
6009 clip: Rect,
6010 aa: AntialiasingMode,
6011 ) -> usize {
6012 let Some(vis) = rect.intersect(clip) else {
6013 return 0;
6014 };
6015 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_alpha() > 0;
6016 if radius.max_radius() <= 0.0 && !has_border {
6017 return Self::fill_rect_clipped(band, rect, color, clip);
6018 }
6019 if radius.max_radius() <= 0.0 && has_border && aa != AntialiasingMode::Msaa4x {
6020 let border_width: f32 = border.get_width();
6021 let bw_r: f32 = border_width.round();
6022 let rx: f32 = rect.get_x();
6023 let ry: f32 = rect.get_y();
6024 let rw: f32 = rect.get_width();
6025 let rh: f32 = rect.get_height();
6026 let int_aligned: bool = bw_r >= 1.0
6027 && (border_width - bw_r).abs() < 1e-4
6028 && (rx - rx.round()).abs() < 1e-4
6029 && (ry - ry.round()).abs() < 1e-4
6030 && (rw - rw.round()).abs() < 1e-4
6031 && (rh - rh.round()).abs() < 1e-4
6032 && rw >= bw_r * 2.0
6033 && rh >= bw_r * 2.0;
6034 if int_aligned {
6035 let bc: Color = border.get_color();
6036 let exact_border: Color = if bw_r < 2.0 {
6037 let b_lin: [f32; 4] = [
6038 SRGB_TO_LIN_LUT[bc.get_red() as usize],
6039 SRGB_TO_LIN_LUT[bc.get_green() as usize],
6040 SRGB_TO_LIN_LUT[bc.get_blue() as usize],
6041 (bc.get_alpha() as f32) / 255.0,
6042 ];
6043 composite_fill_and_border_precomputed([0.0; 4], b_lin, 1.0, 0.0)
6044 } else {
6045 bc
6046 };
6047 let mut shaded_fast: usize = 0;
6048 shaded_fast +=
6049 Self::fill_rect_clipped(band, Rect::new(rx, ry, rw, bw_r), exact_border, clip);
6050 shaded_fast += Self::fill_rect_clipped(
6051 band,
6052 Rect::new(rx, ry + rh - bw_r, rw, bw_r),
6053 exact_border,
6054 clip,
6055 );
6056 let mid_h: f32 = rh - bw_r * 2.0;
6057 if mid_h > 0.0 {
6058 shaded_fast += Self::fill_rect_clipped(
6059 band,
6060 Rect::new(rx, ry + bw_r, bw_r, mid_h),
6061 exact_border,
6062 clip,
6063 );
6064 shaded_fast += Self::fill_rect_clipped(
6065 band,
6066 Rect::new(rx + rw - bw_r, ry + bw_r, bw_r, mid_h),
6067 exact_border,
6068 clip,
6069 );
6070 let mid_w: f32 = rw - bw_r * 2.0;
6071 if mid_w > 0.0 && color.get_alpha() > 0 {
6072 shaded_fast += Self::fill_rect_clipped(
6073 band,
6074 Rect::new(rx + bw_r, ry + bw_r, mid_w, mid_h),
6075 color,
6076 clip,
6077 );
6078 }
6079 }
6080 return shaded_fast;
6081 }
6082 }
6083 let half_w: f32 = rect.get_width() * 0.5;
6084 let half_h: f32 = rect.get_height() * 0.5;
6085 let cx: f32 = rect.get_x() + half_w;
6086 let cy: f32 = rect.get_y() + half_h;
6087 let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
6088 let fb_w: u32 = band.width();
6089 let band_y0: u32 = band.y_offset();
6090 let band_y1: u32 = band.y_end();
6091 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6092 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6093 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6094 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6095 if x0 >= x1 || y0 >= y1 {
6096 return 0;
6097 }
6098 let effective_r: f32 = radius.max_radius().min(half_w).min(half_h);
6099 let safe_inset: f32 = effective_r.max(border_w) + 1.5;
6100 let edge_inset: f32 = border_w + 1.5;
6101 let iy0: u32 = ((rect.get_y() + safe_inset).ceil().max(0.0) as u32).clamp(y0, y1);
6102 let iy1: u32 = ((rect.bottom() - safe_inset).floor().max(0.0) as u32).clamp(y0, y1);
6103 let ix0: u32 = ((rect.get_x() + edge_inset).ceil().max(0.0) as u32).clamp(x0, x1);
6104 let ix1: u32 = ((rect.right() - edge_inset).floor().max(0.0) as u32).clamp(x0, x1);
6105 let cx0: u32 = ((rect.get_x() + safe_inset).ceil().max(0.0) as u32).clamp(x0, x1);
6106 let cx1: u32 = ((rect.right() - safe_inset).floor().max(0.0) as u32).clamp(x0, x1);
6107 let has_interior: bool = iy0 < iy1 && ix0 < ix1;
6108 let has_center_band: bool = cx0 < cx1;
6109 let fill_lin: [f32; 4] = [
6110 SRGB_TO_LIN_LUT[color.get_red() as usize],
6111 SRGB_TO_LIN_LUT[color.get_green() as usize],
6112 SRGB_TO_LIN_LUT[color.get_blue() as usize],
6113 (color.get_alpha() as f32) / 255.0,
6114 ];
6115 let bc: Color = border.get_color();
6116 let border_lin: [f32; 4] = [
6117 SRGB_TO_LIN_LUT[bc.get_red() as usize],
6118 SRGB_TO_LIN_LUT[bc.get_green() as usize],
6119 SRGB_TO_LIN_LUT[bc.get_blue() as usize],
6120 (bc.get_alpha() as f32) / 255.0,
6121 ];
6122 let interior_luts: Option<[[u8; 256]; 4]> = if has_interior
6123 && color.get_alpha() > 0
6124 && color.get_alpha() < 255
6125 && ((ix1 - ix0) as usize).saturating_mul((iy1 - iy0) as usize) >= 512
6126 {
6127 Some(build_linear_blend_luts(color))
6128 } else {
6129 None
6130 };
6131 let mut shaded: usize = 0;
6132 if has_interior {
6133 for pos_y in y0..iy0 {
6134 let py: f32 = (pos_y as f32) + 0.5 - cy;
6135 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6136 if has_center_band {
6137 shaded += Self::raster_rounded_corner_band_row(
6138 band,
6139 pos_y,
6140 (x0, cx0, cx1, x1),
6141 box_geom,
6142 radius,
6143 (color, border, fill_lin, border_lin),
6144 (interior_luts.as_ref(), aa),
6145 );
6146 } else if let Some(row) = band.row_slice_mut(pos_y) {
6147 for pos_x in x0..x1 {
6148 shaded += Self::shade_rounded_pixel_row(
6149 row,
6150 pos_x,
6151 box_geom,
6152 radius,
6153 (color, border, fill_lin, border_lin),
6154 aa,
6155 );
6156 }
6157 }
6158 }
6159 let use_1d_strip: bool = ((ix0 - x0) as usize) <= ROUNDED_EDGE_STRIP_CAP
6160 && ((x1 - ix1) as usize) <= ROUNDED_EDGE_STRIP_CAP;
6161 if use_1d_strip {
6162 let mut left_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
6163 [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
6164 let mut right_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
6165 [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
6166 let (left_len, left_shaded): (usize, usize) = if x0 < ix0 {
6167 Self::build_vertical_edge_strip(
6168 (x0, ix0),
6169 (cx, half_w, half_h, border_w),
6170 (color, border),
6171 (fill_lin, border_lin),
6172 aa,
6173 &mut left_strip,
6174 )
6175 } else {
6176 (0, 0)
6177 };
6178 let (right_len, right_shaded): (usize, usize) = if ix1 < x1 {
6179 Self::build_vertical_edge_strip(
6180 (ix1, x1),
6181 (cx, half_w, half_h, border_w),
6182 (color, border),
6183 (fill_lin, border_lin),
6184 aa,
6185 &mut right_strip,
6186 )
6187 } else {
6188 (0, 0)
6189 };
6190 let left_slice: &[EdgeBlendSample] = &left_strip[..left_len];
6191 let right_slice: &[EdgeBlendSample] = &right_strip[..right_len];
6192 let edge_shaded: usize = left_shaded + right_shaded;
6193 let has_edges: bool = left_len > 0 || right_len > 0;
6194 let fill_visible: bool = color.get_alpha() > 0;
6195 let fill_opaque: bool = color.get_alpha() == 255;
6196 let fill_rgba: [u8; 4] =
6197 [color.get_red(), color.get_green(), color.get_blue(), 255];
6198 let interior_span: usize = (ix1 - ix0) as usize;
6199 let ix0_b: usize = (ix0 as usize) * 4;
6200 let ix1_b: usize = (ix1 as usize) * 4;
6201 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
6202 for row in rows_buf.chunks_exact_mut(row_stride) {
6203 if fill_visible {
6204 if fill_opaque {
6205 fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
6206 } else if let Some(ref luts) = interior_luts {
6207 fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
6208 } else {
6209 fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
6210 }
6211 shaded += interior_span;
6212 }
6213 if has_edges {
6214 if left_len > 0 {
6215 apply_edge_strip_row(row, left_slice);
6216 }
6217 if right_len > 0 {
6218 apply_edge_strip_row(row, right_slice);
6219 }
6220 shaded += edge_shaded;
6221 }
6222 }
6223 }
6224 } else {
6225 let fill_visible: bool = color.get_alpha() > 0;
6226 let fill_opaque: bool = color.get_alpha() == 255;
6227 let fill_rgba: [u8; 4] =
6228 [color.get_red(), color.get_green(), color.get_blue(), 255];
6229 let interior_span: usize = (ix1 - ix0) as usize;
6230 let ix0_b: usize = (ix0 as usize) * 4;
6231 let ix1_b: usize = (ix1 as usize) * 4;
6232 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
6233 for (coord_y, row) in (iy0..iy1).zip(rows_buf.chunks_exact_mut(row_stride)) {
6234 let py: f32 = (coord_y as f32) + 0.5 - cy;
6235 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6236 if fill_visible {
6237 if fill_opaque {
6238 fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
6239 } else if let Some(ref luts) = interior_luts {
6240 fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
6241 } else {
6242 fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
6243 }
6244 shaded += interior_span;
6245 }
6246 for coord_x in x0..ix0 {
6247 shaded += Self::shade_rounded_pixel_row(
6248 row,
6249 coord_x,
6250 box_geom,
6251 radius,
6252 (color, border, fill_lin, border_lin),
6253 aa,
6254 );
6255 }
6256 for sample_x in ix1..x1 {
6257 shaded += Self::shade_rounded_pixel_row(
6258 row,
6259 sample_x,
6260 box_geom,
6261 radius,
6262 (color, border, fill_lin, border_lin),
6263 aa,
6264 );
6265 }
6266 }
6267 }
6268 }
6269 for sample_y in iy1..y1 {
6270 let py: f32 = (sample_y as f32) + 0.5 - cy;
6271 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6272 if has_center_band {
6273 shaded += Self::raster_rounded_corner_band_row(
6274 band,
6275 sample_y,
6276 (x0, cx0, cx1, x1),
6277 box_geom,
6278 radius,
6279 (color, border, fill_lin, border_lin),
6280 (interior_luts.as_ref(), aa),
6281 );
6282 } else if let Some(row) = band.row_slice_mut(sample_y) {
6283 for value_x in x0..x1 {
6284 shaded += Self::shade_rounded_pixel_row(
6285 row,
6286 value_x,
6287 box_geom,
6288 radius,
6289 (color, border, fill_lin, border_lin),
6290 aa,
6291 );
6292 }
6293 }
6294 }
6295 return shaded;
6296 }
6297 for value_y in y0..y1 {
6298 let py: f32 = (value_y as f32) + 0.5 - cy;
6299 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6300 if has_center_band {
6301 shaded += Self::raster_rounded_corner_band_row(
6302 band,
6303 value_y,
6304 (x0, cx0, cx1, x1),
6305 box_geom,
6306 radius,
6307 (color, border, fill_lin, border_lin),
6308 (interior_luts.as_ref(), aa),
6309 );
6310 } else if let Some(row) = band.row_slice_mut(value_y) {
6311 for pos_x_primary in x0..x1 {
6312 shaded += Self::shade_rounded_pixel_row(
6313 row,
6314 pos_x_primary,
6315 box_geom,
6316 radius,
6317 (color, border, fill_lin, border_lin),
6318 aa,
6319 );
6320 }
6321 }
6322 }
6323 shaded
6324 }
6325
6326 #[inline(always)]
6342 fn raster_rounded_corner_band_row(
6343 band: &mut PixelBand<'_>,
6344 pos_y: u32,
6345 x_bounds: (u32, u32, u32, u32),
6346 geom: (f32, f32, f32, f32),
6347 radius: CornerRadius,
6348 style_colors: (Color, Border, [f32; 4], [f32; 4]),
6349 opts: (Option<&[[u8; 256]; 4]>, AntialiasingMode),
6350 ) -> usize {
6351 let (interior_luts, aa): (Option<&[[u8; 256]; 4]>, AntialiasingMode) = opts;
6352 let Some(row) = band.row_slice_mut(pos_y) else {
6353 return 0;
6354 };
6355 let (x0, cx0, cx1, x1): (u32, u32, u32, u32) = x_bounds;
6356 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
6357 let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
6358 style_colors;
6359 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_alpha() > 0;
6360 let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
6361 let inner_thresh: f32 = if has_border {
6362 -(border_w + 0.85)
6363 } else {
6364 -0.85
6365 };
6366 let py_abs: f32 = py.abs();
6367 let fill_visible: bool = color.get_alpha() > 0;
6368 let fill_opaque: bool = color.get_alpha() == 255;
6369 let fill_rgba: [u8; 4] = [color.get_red(), color.get_green(), color.get_blue(), 255];
6370 let mut shaded: usize = 0;
6371 if x0 < cx0 {
6372 let pure_left: bool = ((cx0 - 1) as f32) + 0.5 < cx;
6373 if pure_left {
6374 let r_l: f32 = (if py < 0.0 {
6375 radius.get_top_left()
6376 } else {
6377 radius.get_bottom_left()
6378 })
6379 .min(half_w)
6380 .min(half_h)
6381 .max(0.0);
6382 let qy: f32 = py_abs - half_h + r_l;
6383 let r_out: f32 = r_l + 0.85;
6384 if qy <= r_out + 0.05 {
6385 let vis_l0: u32 = if qy > 0.0 {
6386 let max_vis_abs: f32 =
6387 (half_w - r_l) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
6388 ((cx - max_vis_abs - 0.5).floor().max(0.0) as u32).clamp(x0, cx0)
6389 } else {
6390 x0
6391 };
6392 let r_in: f32 = r_l + inner_thresh;
6393 let max_in_abs: f32 = if qy <= 0.0 {
6394 if qy < r_in - 0.05 {
6395 half_w + inner_thresh - 1.0
6396 } else {
6397 -1.0
6398 }
6399 } else if r_in > 0.0 && qy < r_in - 0.05 {
6400 (half_w - r_l) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
6401 } else {
6402 -1.0
6403 };
6404 let in_l0: u32 = if max_in_abs > 0.0 {
6405 ((cx - max_in_abs - 0.5).ceil().max(0.0) as u32).clamp(vis_l0, cx0)
6406 } else {
6407 cx0
6408 };
6409 for pos_x in vis_l0..in_l0 {
6410 shaded += Self::shade_rounded_pixel_row(
6411 row,
6412 pos_x,
6413 geom,
6414 radius,
6415 style_colors,
6416 aa,
6417 );
6418 }
6419 if in_l0 < cx0 && fill_visible {
6420 let b0: usize = (in_l0 as usize) * 4;
6421 let b1: usize = (cx0 as usize) * 4;
6422 if fill_opaque {
6423 fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
6424 } else if let Some(luts) = interior_luts {
6425 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6426 } else {
6427 fill_span_linear_slice(&mut row[b0..b1], color);
6428 }
6429 shaded += (cx0 - in_l0) as usize;
6430 }
6431 }
6432 } else {
6433 for coord_x in x0..cx0 {
6434 shaded +=
6435 Self::shade_rounded_pixel_row(row, coord_x, geom, radius, style_colors, aa);
6436 }
6437 }
6438 }
6439 if cx1 < x1 {
6440 let pure_right: bool = (cx1 as f32) + 0.5 >= cx;
6441 if pure_right {
6442 let r_r: f32 = (if py < 0.0 {
6443 radius.get_top_right()
6444 } else {
6445 radius.get_bottom_right()
6446 })
6447 .min(half_w)
6448 .min(half_h)
6449 .max(0.0);
6450 let qy: f32 = py_abs - half_h + r_r;
6451 let r_out: f32 = r_r + 0.85;
6452 if qy <= r_out + 0.05 {
6453 let vis_r1: u32 = if qy > 0.0 {
6454 let max_vis_abs: f32 =
6455 (half_w - r_r) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
6456 ((cx + max_vis_abs + 0.5).ceil().max(0.0) as u32).clamp(cx1, x1)
6457 } else {
6458 x1
6459 };
6460 let r_in: f32 = r_r + inner_thresh;
6461 let max_in_abs: f32 = if qy <= 0.0 {
6462 if qy < r_in - 0.05 {
6463 half_w + inner_thresh - 1.0
6464 } else {
6465 -1.0
6466 }
6467 } else if r_in > 0.0 && qy < r_in - 0.05 {
6468 (half_w - r_r) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
6469 } else {
6470 -1.0
6471 };
6472 let in_r1: u32 = if max_in_abs > 0.0 {
6473 ((cx + max_in_abs - 0.5).floor().max(0.0) as u32).clamp(cx1, vis_r1)
6474 } else {
6475 cx1
6476 };
6477 if cx1 < in_r1 && fill_visible {
6478 let b0: usize = (cx1 as usize) * 4;
6479 let b1: usize = (in_r1 as usize) * 4;
6480 if fill_opaque {
6481 fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
6482 } else if let Some(luts) = interior_luts {
6483 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6484 } else {
6485 fill_span_linear_slice(&mut row[b0..b1], color);
6486 }
6487 shaded += (in_r1 - cx1) as usize;
6488 }
6489 for sample_x in in_r1..vis_r1 {
6490 shaded += Self::shade_rounded_pixel_row(
6491 row,
6492 sample_x,
6493 geom,
6494 radius,
6495 style_colors,
6496 aa,
6497 );
6498 }
6499 }
6500 } else {
6501 for value_x in cx1..x1 {
6502 shaded +=
6503 Self::shade_rounded_pixel_row(row, value_x, geom, radius, style_colors, aa);
6504 }
6505 }
6506 }
6507 let dist_y: f32 = py_abs - half_h;
6508 let outer_cov: f32 = sdf_coverage(dist_y, aa);
6509 if outer_cov > 0.0 {
6510 let b0: usize = (cx0 as usize) * 4;
6511 let b1: usize = (cx1 as usize) * 4;
6512 if has_border {
6513 let inner_hh: f32 = (half_h - border_w).max(0.0);
6514 let inner_cov: f32 = if inner_hh > 0.0 && half_w > border_w {
6515 sdf_coverage(py_abs - inner_hh, aa)
6516 } else {
6517 0.0
6518 };
6519 let mixed: Color = composite_fill_and_border_precomputed(
6520 fill_lin, border_lin, outer_cov, inner_cov,
6521 );
6522 if mixed.get_alpha() > 0 {
6523 fill_span_linear_slice(&mut row[b0..b1], mixed);
6524 }
6525 shaded += (cx1 - cx0) as usize;
6526 } else if fill_visible {
6527 let row_color: Color = color.multiply_alpha(outer_cov);
6528 if row_color == color
6529 && let Some(luts) = interior_luts
6530 {
6531 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6532 } else {
6533 fill_span_linear_slice(&mut row[b0..b1], row_color);
6534 }
6535 shaded += (cx1 - cx0) as usize;
6536 }
6537 }
6538 shaded
6539 }
6540
6541 #[inline(always)]
6556 fn shade_rounded_pixel_row(
6557 row: &mut [u8],
6558 pos_x: u32,
6559 geom: (f32, f32, f32, f32),
6560 radius: CornerRadius,
6561 style_colors: (Color, Border, [f32; 4], [f32; 4]),
6562 aa: AntialiasingMode,
6563 ) -> usize {
6564 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
6565 let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
6566 style_colors;
6567 let fill_rgb: [f32; 3] = [fill_lin[0], fill_lin[1], fill_lin[2]];
6568 let px: f32 = (pos_x as f32) + 0.5 - cx;
6569 let corner_r: f32 = quadrant_corner_radius(radius, px, py)
6570 .min(half_w)
6571 .min(half_h);
6572 let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
6573 if dist > 0.85 {
6574 return 0;
6575 }
6576 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_alpha() > 0;
6577 let border_width: f32 = if has_border { border.get_width() } else { 0.0 };
6578 if !has_border {
6579 if dist < -0.85 {
6580 if color.get_alpha() > 0 {
6581 blend_row_pixel_linear_precomputed(row, pos_x, color, fill_rgb);
6582 return 1;
6583 }
6584 return 0;
6585 }
6586 let in_corner_edge: bool = aa != AntialiasingMode::None
6587 && corner_r > 0.5
6588 && px.abs() > (half_w - corner_r - 1.5)
6589 && py.abs() > (half_h - corner_r - 1.5);
6590 let outer_cov: f32 = if in_corner_edge {
6591 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
6592 } else {
6593 sdf_coverage(dist, aa)
6594 };
6595 if outer_cov > 0.0 && color.get_alpha() > 0 {
6596 let alpha_f: f32 = ((color.get_alpha() as f32) * (1.0 / 255.0)) * outer_cov;
6597 blend_row_pixel_f32_precomputed(row, pos_x, color, fill_rgb, alpha_f);
6598 return 1;
6599 }
6600 return 0;
6601 }
6602 if dist < -(border_width + 0.85) {
6603 if color.get_alpha() > 0 {
6604 blend_row_pixel_linear_precomputed(row, pos_x, color, fill_rgb);
6605 return 1;
6606 }
6607 return 0;
6608 }
6609 let inner_hw: f32 = (half_w - border_width).max(0.0);
6610 let inner_hh: f32 = (half_h - border_width).max(0.0);
6611 let inner_r: f32 = (corner_r - border_width).max(0.0);
6612 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6613 rounded_box_sdf(px, py, inner_hw, inner_hh, inner_r)
6614 } else {
6615 2.0
6616 };
6617 if dist < -0.85 && inner_dist > 0.85 {
6618 let border_rgb: [f32; 3] = [border_lin[0], border_lin[1], border_lin[2]];
6619 blend_row_pixel_linear_precomputed(row, pos_x, border.get_color(), border_rgb);
6620 return 1;
6621 }
6622 let in_corner_zone: bool = aa != AntialiasingMode::None
6623 && corner_r > 0.5
6624 && px.abs() > (half_w - corner_r - 1.5)
6625 && py.abs() > (half_h - corner_r - 1.5);
6626 let (outer_cov, inner_cov): (f32, f32) = if in_corner_zone {
6627 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, border_width)
6628 } else {
6629 let oc: f32 = sdf_coverage(dist, aa);
6630 if oc <= 0.0 {
6631 return 0;
6632 }
6633 let ic: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6634 sdf_coverage(inner_dist, aa)
6635 } else {
6636 0.0
6637 };
6638 (oc, ic)
6639 };
6640 if outer_cov <= 0.0 {
6641 return 0;
6642 }
6643 let mixed: Color =
6644 composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
6645 if mixed.get_alpha() > 0 {
6646 let mixed_rgb: [f32; 3] = [
6647 SRGB_TO_LIN_LUT[mixed.get_red() as usize],
6648 SRGB_TO_LIN_LUT[mixed.get_green() as usize],
6649 SRGB_TO_LIN_LUT[mixed.get_blue() as usize],
6650 ];
6651 blend_row_pixel_linear_precomputed(row, pos_x, mixed, mixed_rgb);
6652 return 1;
6653 }
6654 0
6655 }
6656
6657 #[inline(always)]
6670 fn fill_vertical_gradient_span(
6671 band: &mut PixelBand<'_>,
6672 coords: (u32, u32, u32),
6673 sample: Color,
6674 cov: f32,
6675 ) -> usize {
6676 let (sx0, sx1, pos_y): (u32, u32, u32) = coords;
6677 if sx0 >= sx1 || cov <= 0.0 {
6678 return 0;
6679 }
6680 let alpha_f: f32 = ((sample.get_alpha() as f32) * (1.0 / 255.0)) * cov;
6681 if alpha_f >= 0.9995 {
6682 band.fill_span(
6683 sx0,
6684 sx1,
6685 pos_y,
6686 Color::new(sample.get_red(), sample.get_green(), sample.get_blue(), 255),
6687 );
6688 } else if alpha_f > 0.0005 {
6689 band.blend_shadow_span_const_alpha(sx0, sx1, pos_y, sample, alpha_f);
6690 } else if alpha_f > 0.0002
6691 && let Some(row) = band.row_slice_mut(pos_y)
6692 {
6693 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
6694 for pos_x in sx0..sx1 {
6695 blend_gradient_row_pixel(row, pos_x, y_term, sample, cov);
6696 }
6697 }
6698 (sx1 - sx0) as usize
6699 }
6700
6701 #[inline(always)]
6714 fn fill_angled_gradient_span(
6715 row: &mut [u8],
6716 coords: (u32, u32, f32),
6717 step: (f32, f32, f32),
6718 stops: (Color, Color),
6719 ) -> usize {
6720 let (sx0, sx1, y_term): (u32, u32, f32) = coords;
6721 let (t_start, dt_dx, cov): (f32, f32, f32) = step;
6722 let (start_c, end_c): (Color, Color) = stops;
6723 if sx0 >= sx1 || cov <= 0.0 {
6724 return 0;
6725 }
6726 let byte_start: usize = (sx0 as usize) * 4;
6727 let byte_end: usize = (sx1 as usize) * 4;
6728 if byte_end > row.len() {
6729 return 0;
6730 }
6731 let sr_f: f32 = start_c.get_red() as f32;
6732 let sg_f: f32 = start_c.get_green() as f32;
6733 let sb_f: f32 = start_c.get_blue() as f32;
6734 let er_f: f32 = end_c.get_red() as f32;
6735 let eg_f: f32 = end_c.get_green() as f32;
6736 let eb_f: f32 = end_c.get_blue() as f32;
6737 let both_opaque: bool = start_c.get_alpha() == 255 && end_c.get_alpha() == 255;
6738 let mut t_cur: f32 = t_start;
6739 if both_opaque && cov >= 0.9995 {
6740 let chunks: &mut [[u8; 4]] = row[byte_start..byte_end].as_chunks_mut::<4>().0;
6741 for px in chunks.iter_mut() {
6742 let factor_val: f32 = t_cur.clamp(0.0, 1.0);
6743 let inv: f32 = 1.0 - factor_val;
6744 px[0] = (sr_f * inv + er_f * factor_val + 0.5) as u8;
6745 px[1] = (sg_f * inv + eg_f * factor_val + 0.5) as u8;
6746 px[2] = (sb_f * inv + eb_f * factor_val + 0.5) as u8;
6747 px[3] = 255;
6748 t_cur += dt_dx;
6749 }
6750 return (sx1 - sx0) as usize;
6751 }
6752 let sa_f: f32 = start_c.get_alpha() as f32;
6753 let ea_f: f32 = end_c.get_alpha() as f32;
6754 for pos_x in sx0..sx1 {
6755 let callback_ref: f32 = t_cur.clamp(0.0, 1.0);
6756 let inv: f32 = 1.0 - callback_ref;
6757 let sample: Color = Color::new(
6758 (sr_f * inv + er_f * callback_ref + 0.5) as u8,
6759 (sg_f * inv + eg_f * callback_ref + 0.5) as u8,
6760 (sb_f * inv + eb_f * callback_ref + 0.5) as u8,
6761 (sa_f * inv + ea_f * callback_ref + 0.5) as u8,
6762 );
6763 blend_gradient_row_pixel(row, pos_x, y_term, sample, cov);
6764 t_cur += dt_dx;
6765 }
6766 (sx1 - sx0) as usize
6767 }
6768
6769 fn raster_gradient_rect(
6784 band: &mut PixelBand<'_>,
6785 rect: Rect,
6786 gradient: LinearGradient,
6787 radius: CornerRadius,
6788 clip: Rect,
6789 aa: AntialiasingMode,
6790 ) -> usize {
6791 let Some(vis) = rect.intersect(clip) else {
6792 return 0;
6793 };
6794 let fb_w: u32 = band.width();
6795 let band_y0: u32 = band.y_offset();
6796 let band_y1: u32 = band.y_end();
6797 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6798 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6799 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6800 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6801 if x0 >= x1 || y0 >= y1 {
6802 return 0;
6803 }
6804 let rad: f32 = gradient.get_angle_deg().to_radians();
6805 let dir_x: f32 = rad.sin();
6806 let dir_y: f32 = rad.cos();
6807 let start_c: Color = gradient.get_start_color();
6808 let end_c: Color = gradient.get_end_color();
6809 let half_w: f32 = rect.get_width() * 0.5;
6810 let half_h: f32 = rect.get_height() * 0.5;
6811 let cx: f32 = rect.get_x() + half_w;
6812 let cy: f32 = rect.get_y() + half_h;
6813 let inv_w: f32 = if rect.get_width() > 0.0 {
6814 1.0 / rect.get_width()
6815 } else {
6816 0.0
6817 };
6818 let inv_h: f32 = if rect.get_height() > 0.0 {
6819 1.0 / rect.get_height()
6820 } else {
6821 0.0
6822 };
6823 let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
6824 let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
6825 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
6826 let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
6827 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
6828 let cx0: u32 = ((rect.get_x() + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
6829 let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
6830 let is_vertical: bool = dir_x.abs() < 1e-5;
6831 let dt_dx: f32 = inv_w * dir_x;
6832 let rect_x: f32 = rect.get_x();
6833 let rect_y: f32 = rect.get_y();
6834 let mut shaded: usize = 0;
6835 if is_vertical {
6836 for pos_y in y0..iy0 {
6837 let py: f32 = (pos_y as f32) + 0.5 - cy;
6838 let ny: f32 = ((pos_y as f32) - rect_y) * inv_h;
6839 let blend_factor: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
6840 let sample: Color = start_c.lerp(end_c, blend_factor);
6841 let dist_y: f32 = py.abs() - half_h;
6842 let mid_cov: f32 = if dist_y > 0.85 {
6843 0.0
6844 } else if dist_y < -0.85 {
6845 1.0
6846 } else {
6847 sdf_coverage(dist_y, aa)
6848 };
6849 if cx0 < cx1 && mid_cov > 0.0 {
6850 shaded +=
6851 Self::fill_vertical_gradient_span(band, (cx0, cx1, pos_y), sample, mid_cov);
6852 }
6853 if (x0 < cx0 || cx1 < x1)
6854 && let Some(row) = band.row_slice_mut(pos_y)
6855 {
6856 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
6857 for pos_x in x0..cx0 {
6858 let px: f32 = (pos_x as f32) + 0.5 - cx;
6859 let cov: f32 =
6860 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
6861 if cov > 0.0 {
6862 blend_gradient_row_pixel(row, pos_x, y_term, sample, cov);
6863 shaded += 1;
6864 }
6865 }
6866 for coord_x in cx1..x1 {
6867 let px: f32 = (coord_x as f32) + 0.5 - cx;
6868 let cov: f32 =
6869 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
6870 if cov > 0.0 {
6871 blend_gradient_row_pixel(row, coord_x, y_term, sample, cov);
6872 shaded += 1;
6873 }
6874 }
6875 }
6876 }
6877 for coord_y in iy0..iy1 {
6878 let ny: f32 = ((coord_y as f32) - rect_y) * inv_h;
6879 let time_step: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
6880 let sample: Color = start_c.lerp(end_c, time_step);
6881 if ix0 < ix1 {
6882 shaded +=
6883 Self::fill_vertical_gradient_span(band, (ix0, ix1, coord_y), sample, 1.0);
6884 }
6885 if (x0 < ix0 || ix1 < x1)
6886 && let Some(row) = band.row_slice_mut(coord_y)
6887 {
6888 let y_term: f32 = (coord_y as f32) * 0.005_837_15;
6889 for sample_x in x0..ix0 {
6890 let dist: f32 = ((sample_x as f32) + 0.5 - cx).abs() - half_w;
6891 if dist <= 0.85 {
6892 let cov: f32 = if dist < -0.85 {
6893 1.0
6894 } else {
6895 sdf_coverage(dist, aa)
6896 };
6897 if cov > 0.0 {
6898 blend_gradient_row_pixel(row, sample_x, y_term, sample, cov);
6899 shaded += 1;
6900 }
6901 }
6902 }
6903 for value_x in ix1..x1 {
6904 let dist: f32 = ((value_x as f32) + 0.5 - cx).abs() - half_w;
6905 if dist <= 0.85 {
6906 let cov: f32 = if dist < -0.85 {
6907 1.0
6908 } else {
6909 sdf_coverage(dist, aa)
6910 };
6911 if cov > 0.0 {
6912 blend_gradient_row_pixel(row, value_x, y_term, sample, cov);
6913 shaded += 1;
6914 }
6915 }
6916 }
6917 }
6918 }
6919 for sample_y in iy1..y1 {
6920 let py: f32 = (sample_y as f32) + 0.5 - cy;
6921 let ny: f32 = ((sample_y as f32) - rect_y) * inv_h;
6922 let token_val: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
6923 let sample: Color = start_c.lerp(end_c, token_val);
6924 let dist_y: f32 = py.abs() - half_h;
6925 let mid_cov: f32 = if dist_y > 0.85 {
6926 0.0
6927 } else if dist_y < -0.85 {
6928 1.0
6929 } else {
6930 sdf_coverage(dist_y, aa)
6931 };
6932 if cx0 < cx1 && mid_cov > 0.0 {
6933 shaded += Self::fill_vertical_gradient_span(
6934 band,
6935 (cx0, cx1, sample_y),
6936 sample,
6937 mid_cov,
6938 );
6939 }
6940 if (x0 < cx0 || cx1 < x1)
6941 && let Some(row) = band.row_slice_mut(sample_y)
6942 {
6943 let y_term: f32 = (sample_y as f32) * 0.005_837_15;
6944 for pos_x_primary in x0..cx0 {
6945 let px: f32 = (pos_x_primary as f32) + 0.5 - cx;
6946 let cov: f32 =
6947 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
6948 if cov > 0.0 {
6949 blend_gradient_row_pixel(row, pos_x_primary, y_term, sample, cov);
6950 shaded += 1;
6951 }
6952 }
6953 for pos_x_secondary in cx1..x1 {
6954 let px: f32 = (pos_x_secondary as f32) + 0.5 - cx;
6955 let cov: f32 =
6956 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
6957 if cov > 0.0 {
6958 blend_gradient_row_pixel(row, pos_x_secondary, y_term, sample, cov);
6959 shaded += 1;
6960 }
6961 }
6962 }
6963 }
6964 return shaded;
6965 }
6966 for value_y in y0..iy0 {
6967 let Some(row) = band.row_slice_mut(value_y) else {
6968 continue;
6969 };
6970 let py: f32 = (value_y as f32) + 0.5 - cy;
6971 let ny: f32 = ((value_y as f32) - rect_y) * inv_h;
6972 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
6973 let y_term: f32 = (value_y as f32) * 0.005_837_15;
6974 let dist_y: f32 = py.abs() - half_h;
6975 let mid_cov: f32 = if dist_y > 0.85 {
6976 0.0
6977 } else if dist_y < -0.85 {
6978 1.0
6979 } else {
6980 sdf_coverage(dist_y, aa)
6981 };
6982 if cx0 < cx1 && mid_cov > 0.0 {
6983 let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
6984 shaded += Self::fill_angled_gradient_span(
6985 row,
6986 (cx0, cx1, y_term),
6987 (t_start, dt_dx, mid_cov),
6988 (start_c, end_c),
6989 );
6990 }
6991 for pos_x_next in x0..cx0 {
6992 let px: f32 = (pos_x_next as f32) + 0.5 - cx;
6993 let cov: f32 =
6994 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
6995 if cov > 0.0 {
6996 let nx: f32 = ((pos_x_next as f32) - rect_x) * inv_w;
6997 let target_val: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
6998 blend_gradient_row_pixel(
6999 row,
7000 pos_x_next,
7001 y_term,
7002 start_c.lerp(end_c, target_val),
7003 cov,
7004 );
7005 shaded += 1;
7006 }
7007 }
7008 for pos_x_alt in cx1..x1 {
7009 let px: f32 = (pos_x_alt as f32) + 0.5 - cx;
7010 let cov: f32 =
7011 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7012 if cov > 0.0 {
7013 let nx: f32 = ((pos_x_alt as f32) - rect_x) * inv_w;
7014 let blend_factor_primary: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7015 blend_gradient_row_pixel(
7016 row,
7017 pos_x_alt,
7018 y_term,
7019 start_c.lerp(end_c, blend_factor_primary),
7020 cov,
7021 );
7022 shaded += 1;
7023 }
7024 }
7025 }
7026 for pos_y_primary in iy0..iy1 {
7027 let Some(row) = band.row_slice_mut(pos_y_primary) else {
7028 continue;
7029 };
7030 let ny: f32 = ((pos_y_primary as f32) - rect_y) * inv_h;
7031 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
7032 let y_term: f32 = (pos_y_primary as f32) * 0.005_837_15;
7033 if ix0 < ix1 {
7034 let t_start: f32 = (((ix0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
7035 shaded += Self::fill_angled_gradient_span(
7036 row,
7037 (ix0, ix1, y_term),
7038 (t_start, dt_dx, 1.0),
7039 (start_c, end_c),
7040 );
7041 }
7042 for pos_x_inner in x0..ix0 {
7043 let dist: f32 = ((pos_x_inner as f32) + 0.5 - cx).abs() - half_w;
7044 if dist <= 0.85 {
7045 let cov: f32 = if dist < -0.85 {
7046 1.0
7047 } else {
7048 sdf_coverage(dist, aa)
7049 };
7050 if cov > 0.0 {
7051 let nx: f32 = ((pos_x_inner as f32) - rect_x) * inv_w;
7052 let blend_factor_secondary: f32 =
7053 ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7054 blend_gradient_row_pixel(
7055 row,
7056 pos_x_inner,
7057 y_term,
7058 start_c.lerp(end_c, blend_factor_secondary),
7059 cov,
7060 );
7061 shaded += 1;
7062 }
7063 }
7064 }
7065 for pos_x_local in ix1..x1 {
7066 let dist: f32 = ((pos_x_local as f32) + 0.5 - cx).abs() - half_w;
7067 if dist <= 0.85 {
7068 let cov: f32 = if dist < -0.85 {
7069 1.0
7070 } else {
7071 sdf_coverage(dist, aa)
7072 };
7073 if cov > 0.0 {
7074 let nx: f32 = ((pos_x_local as f32) - rect_x) * inv_w;
7075 let blend_factor_next: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7076 blend_gradient_row_pixel(
7077 row,
7078 pos_x_local,
7079 y_term,
7080 start_c.lerp(end_c, blend_factor_next),
7081 cov,
7082 );
7083 shaded += 1;
7084 }
7085 }
7086 }
7087 }
7088 for pos_y_secondary in iy1..y1 {
7089 let Some(row) = band.row_slice_mut(pos_y_secondary) else {
7090 continue;
7091 };
7092 let py: f32 = (pos_y_secondary as f32) + 0.5 - cy;
7093 let ny: f32 = ((pos_y_secondary as f32) - rect_y) * inv_h;
7094 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
7095 let y_term: f32 = (pos_y_secondary as f32) * 0.005_837_15;
7096 let dist_y: f32 = py.abs() - half_h;
7097 let mid_cov: f32 = if dist_y > 0.85 {
7098 0.0
7099 } else if dist_y < -0.85 {
7100 1.0
7101 } else {
7102 sdf_coverage(dist_y, aa)
7103 };
7104 if cx0 < cx1 && mid_cov > 0.0 {
7105 let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
7106 shaded += Self::fill_angled_gradient_span(
7107 row,
7108 (cx0, cx1, y_term),
7109 (t_start, dt_dx, mid_cov),
7110 (start_c, end_c),
7111 );
7112 }
7113 for pos_x_cur in x0..cx0 {
7114 let px: f32 = (pos_x_cur as f32) + 0.5 - cx;
7115 let cov: f32 =
7116 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7117 if cov > 0.0 {
7118 let nx: f32 = ((pos_x_cur as f32) - rect_x) * inv_w;
7119 let blend_factor_alt: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7120 blend_gradient_row_pixel(
7121 row,
7122 pos_x_cur,
7123 y_term,
7124 start_c.lerp(end_c, blend_factor_alt),
7125 cov,
7126 );
7127 shaded += 1;
7128 }
7129 }
7130 for pos_x_slot in cx1..x1 {
7131 let px: f32 = (pos_x_slot as f32) + 0.5 - cx;
7132 let cov: f32 =
7133 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7134 if cov > 0.0 {
7135 let nx: f32 = ((pos_x_slot as f32) - rect_x) * inv_w;
7136 let blend_factor_inner: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7137 blend_gradient_row_pixel(
7138 row,
7139 pos_x_slot,
7140 y_term,
7141 start_c.lerp(end_c, blend_factor_inner),
7142 cov,
7143 );
7144 shaded += 1;
7145 }
7146 }
7147 }
7148 shaded
7149 }
7150
7151 #[must_use]
7164 fn shadow_row_cutout(pos_y: u32, cutouts: (Rect, Rect), x0: u32, x1: u32) -> (u32, u32) {
7165 let (cut_h, cut_v): (Rect, Rect) = cutouts;
7166 let yf: f32 = (pos_y as f32) + 0.5;
7167 if cut_h.get_width() > 0.0
7168 && cut_h.get_height() > 0.0
7169 && yf >= cut_h.get_y()
7170 && yf < cut_h.bottom()
7171 {
7172 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
7173 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, x1);
7174 return (cx0, cx1);
7175 }
7176 if cut_v.get_width() > 0.0
7177 && cut_v.get_height() > 0.0
7178 && yf >= cut_v.get_y()
7179 && yf < cut_v.bottom()
7180 {
7181 let cx0: u32 = (cut_v.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
7182 let cx1: u32 = (cut_v.right().floor().max(0.0) as u32).clamp(cx0, x1);
7183 return (cx0, cx1);
7184 }
7185 (x1, x1)
7186 }
7187
7188 #[inline(always)]
7202 fn raster_shadow_middle_span(
7203 band: &mut PixelBand<'_>,
7204 ctx: &ShadowRenderContext,
7205 pos_y: u32,
7206 cutout: (u32, u32),
7207 mid_alpha: f32,
7208 ) -> usize {
7209 if !ctx.has_mid_x || mid_alpha <= 0.0005 {
7210 return 0;
7211 }
7212 let (cut0, cut1): (u32, u32) = cutout;
7213 let sx0: u32 = ctx.lx1;
7214 let sx1: u32 = ctx.rx0;
7215 let mut shaded: usize = 0;
7216 if cut0 < cut1 {
7217 let m0_end: u32 = cut0.min(sx1);
7218 if sx0 < m0_end {
7219 band.blend_shadow_span_const_alpha(sx0, m0_end, pos_y, ctx.color, mid_alpha);
7220 shaded += (m0_end - sx0) as usize;
7221 }
7222 let m1_start: u32 = cut1.max(sx0);
7223 if m1_start < sx1 {
7224 band.blend_shadow_span_const_alpha(m1_start, sx1, pos_y, ctx.color, mid_alpha);
7225 shaded += (sx1 - m1_start) as usize;
7226 }
7227 } else {
7228 band.blend_shadow_span_const_alpha(sx0, sx1, pos_y, ctx.color, mid_alpha);
7229 shaded += (sx1 - sx0) as usize;
7230 }
7231 shaded
7232 }
7233
7234 fn raster_shadow_corner_row_symmetric(
7247 band: &mut PixelBand<'_>,
7248 ctx: &ShadowRenderContext,
7249 pos_y: u32,
7250 cutouts: (Rect, Rect),
7251 ) -> usize {
7252 let py: f32 = (pos_y as f32) + 0.5 - ctx.cy;
7253 let py_abs: f32 = py.abs();
7254 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(pos_y, cutouts, ctx.x0, ctx.x1);
7255 let mut shaded: usize = 0;
7256 if ctx.has_mid_x {
7257 let dist_y: f32 = py_abs - ctx.half_h;
7258 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7259 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7260 } else {
7261 0.0
7262 };
7263 shaded += Self::raster_shadow_middle_span(band, ctx, pos_y, (cut0, cut1), mid_alpha);
7264 }
7265 let (la0, la1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0, cut1);
7266 let (ra0, ra1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0, cut1);
7267 let mut u0: i32 = i32::MAX;
7268 let mut u1: i32 = i32::MIN;
7269 if la0 < la1 {
7270 u0 = u0.min(la0 as i32);
7271 u1 = u1.max(la1 as i32);
7272 }
7273 if ra0 < ra1 {
7274 u0 = u0.min(ctx.mirror_x_sum - (ra1 as i32) + 1);
7275 u1 = u1.max(ctx.mirror_x_sum - (ra0 as i32) + 1);
7276 }
7277 if u0 >= u1 {
7278 return shaded;
7279 }
7280 let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
7281 let qy_pos: f32 = qy.max(0.0);
7282 let qy_pos_sq: f32 = qy_pos * qy_pos;
7283 if qy > 0.0 {
7284 if qy_pos_sq >= ctx.cutoff_r_safe_sq {
7285 return shaded;
7286 }
7287 let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
7288 let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
7289 let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
7290 u0 = u0.max(tight_u0);
7291 if u0 >= u1 {
7292 return shaded;
7293 }
7294 }
7295 let Some(row) = band.row_slice_mut(pos_y) else {
7296 return shaded;
7297 };
7298 let sdf_geom: (f32, f32, f32, f32) =
7299 (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
7300 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
7301 let x0_i: i32 = ctx.x0 as i32;
7302 let lx1_i: i32 = ctx.lx1 as i32;
7303 let rx0_i: i32 = ctx.rx0 as i32;
7304 let x1_i: i32 = ctx.x1 as i32;
7305 let cut0_i: i32 = cut0 as i32;
7306 let cut1_i: i32 = cut1 as i32;
7307 for xl_i in u0..u1 {
7308 let xr_i: i32 = ctx.mirror_x_sum - xl_i;
7309 let do_l: bool = xl_i >= x0_i && xl_i < lx1_i && (xl_i < cut0_i || xl_i >= cut1_i);
7310 let do_r: bool = xr_i >= rx0_i && xr_i < x1_i && (xr_i < cut0_i || xr_i >= cut1_i);
7311 if !do_l && !do_r {
7312 continue;
7313 }
7314 let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
7315 let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
7316 if dist >= ctx.cutoff {
7317 continue;
7318 }
7319 let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7320 if alpha_f <= 0.0005 {
7321 continue;
7322 }
7323 let alpha_val: f32 = alpha_f.clamp(0.0, 1.0);
7324 if alpha_val >= 0.9995 {
7325 if do_l {
7326 let off: usize = (xl_i as usize) * 4;
7327 row[off] = ctx.color_rgb[0];
7328 row[off + 1] = ctx.color_rgb[1];
7329 row[off + 2] = ctx.color_rgb[2];
7330 row[off + 3] = 255;
7331 shaded += 1;
7332 }
7333 if do_r {
7334 let off: usize = (xr_i as usize) * 4;
7335 row[off] = ctx.color_rgb[0];
7336 row[off + 1] = ctx.color_rgb[1];
7337 row[off + 2] = ctx.color_rgb[2];
7338 row[off + 3] = 255;
7339 shaded += 1;
7340 }
7341 } else {
7342 let inv_a: f32 = 1.0 - alpha_val;
7343 let sa_u32: u32 = (alpha_val * 255.0) as u32;
7344 let params: ShadowStripParams = ShadowStripParams {
7345 sr_a: ctx.lin_rgb[0] * alpha_val,
7346 sg_a: ctx.lin_rgb[1] * alpha_val,
7347 sb_a: ctx.lin_rgb[2] * alpha_val,
7348 inv_a,
7349 sa_u32,
7350 inv_a_u32: 255 - sa_u32,
7351 };
7352 let mut cache: ShadowPixelCache = ShadowPixelCache::default();
7353 if do_l {
7354 blend_shadow_mirrored_pixel(row, xl_i as u32, y_term, params, &mut cache);
7355 shaded += 1;
7356 }
7357 if do_r {
7358 blend_shadow_mirrored_pixel(row, xr_i as u32, y_term, params, &mut cache);
7359 shaded += 1;
7360 }
7361 }
7362 }
7363 shaded
7364 }
7365
7366 fn raster_shadow_corner_pair_symmetric(
7380 band: &mut PixelBand<'_>,
7381 ctx: &ShadowRenderContext,
7382 y_t: u32,
7383 y_b: u32,
7384 cutouts: (Rect, Rect),
7385 ) -> usize {
7386 let py: f32 = (y_t as f32) + 0.5 - ctx.cy;
7387 let py_abs: f32 = py.abs();
7388 let (cut0_t, cut1_t): (u32, u32) = Self::shadow_row_cutout(y_t, cutouts, ctx.x0, ctx.x1);
7389 let (cut0_b, cut1_b): (u32, u32) = Self::shadow_row_cutout(y_b, cutouts, ctx.x0, ctx.x1);
7390 let mut shaded: usize = 0;
7391 if ctx.has_mid_x {
7392 let dist_y: f32 = py_abs - ctx.half_h;
7393 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7394 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7395 } else {
7396 0.0
7397 };
7398 if mid_alpha > 0.0005 {
7399 shaded +=
7400 Self::raster_shadow_middle_span(band, ctx, y_t, (cut0_t, cut1_t), mid_alpha);
7401 shaded +=
7402 Self::raster_shadow_middle_span(band, ctx, y_b, (cut0_b, cut1_b), mid_alpha);
7403 }
7404 }
7405 let (lat0, lat1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_t, cut1_t);
7406 let (rat0, rat1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_t, cut1_t);
7407 let (lab0, lab1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_b, cut1_b);
7408 let (rab0, rab1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_b, cut1_b);
7409 let mut u0: i32 = i32::MAX;
7410 let mut u1: i32 = i32::MIN;
7411 if lat0 < lat1 {
7412 u0 = u0.min(lat0 as i32);
7413 u1 = u1.max(lat1 as i32);
7414 }
7415 if rat0 < rat1 {
7416 u0 = u0.min(ctx.mirror_x_sum - (rat1 as i32) + 1);
7417 u1 = u1.max(ctx.mirror_x_sum - (rat0 as i32) + 1);
7418 }
7419 if lab0 < lab1 {
7420 u0 = u0.min(lab0 as i32);
7421 u1 = u1.max(lab1 as i32);
7422 }
7423 if rab0 < rab1 {
7424 u0 = u0.min(ctx.mirror_x_sum - (rab1 as i32) + 1);
7425 u1 = u1.max(ctx.mirror_x_sum - (rab0 as i32) + 1);
7426 }
7427 if u0 >= u1 {
7428 return shaded;
7429 }
7430 let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
7431 let qy_pos: f32 = qy.max(0.0);
7432 let qy_pos_sq: f32 = qy_pos * qy_pos;
7433 if qy > 0.0 {
7434 if qy_pos_sq >= ctx.cutoff_r_safe_sq {
7435 return shaded;
7436 }
7437 let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
7438 let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
7439 let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
7440 u0 = u0.max(tight_u0);
7441 if u0 >= u1 {
7442 return shaded;
7443 }
7444 }
7445 let Some((row_t, row_b)) = band.two_row_slices_mut(y_t, y_b) else {
7446 return shaded;
7447 };
7448 let sdf_geom: (f32, f32, f32, f32) =
7449 (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
7450 let y_term_t: f32 = (y_t as f32) * 0.005_837_15;
7451 let y_term_b: f32 = (y_b as f32) * 0.005_837_15;
7452 let x0_i: i32 = ctx.x0 as i32;
7453 let lx1_i: i32 = ctx.lx1 as i32;
7454 let rx0_i: i32 = ctx.rx0 as i32;
7455 let x1_i: i32 = ctx.x1 as i32;
7456 let cut0_ti: i32 = cut0_t as i32;
7457 let cut1_ti: i32 = cut1_t as i32;
7458 let cut0_bi: i32 = cut0_b as i32;
7459 let cut1_bi: i32 = cut1_b as i32;
7460 for xl_i in u0..u1 {
7461 let xr_i: i32 = ctx.mirror_x_sum - xl_i;
7462 let in_l: bool = xl_i >= x0_i && xl_i < lx1_i;
7463 let in_r: bool = xr_i >= rx0_i && xr_i < x1_i;
7464 let do_lt: bool = in_l && (xl_i < cut0_ti || xl_i >= cut1_ti);
7465 let do_rt: bool = in_r && (xr_i < cut0_ti || xr_i >= cut1_ti);
7466 let do_lb: bool = in_l && (xl_i < cut0_bi || xl_i >= cut1_bi);
7467 let do_rb: bool = in_r && (xr_i < cut0_bi || xr_i >= cut1_bi);
7468 if !do_lt && !do_rt && !do_lb && !do_rb {
7469 continue;
7470 }
7471 let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
7472 let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
7473 if dist >= ctx.cutoff {
7474 continue;
7475 }
7476 let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7477 if alpha_f <= 0.0005 {
7478 continue;
7479 }
7480 let alpha_val: f32 = alpha_f.clamp(0.0, 1.0);
7481 if alpha_val >= 0.9995 {
7482 if do_lt {
7483 let off: usize = (xl_i as usize) * 4;
7484 row_t[off] = ctx.color_rgb[0];
7485 row_t[off + 1] = ctx.color_rgb[1];
7486 row_t[off + 2] = ctx.color_rgb[2];
7487 row_t[off + 3] = 255;
7488 shaded += 1;
7489 }
7490 if do_rt {
7491 let off: usize = (xr_i as usize) * 4;
7492 row_t[off] = ctx.color_rgb[0];
7493 row_t[off + 1] = ctx.color_rgb[1];
7494 row_t[off + 2] = ctx.color_rgb[2];
7495 row_t[off + 3] = 255;
7496 shaded += 1;
7497 }
7498 if do_lb {
7499 let off: usize = (xl_i as usize) * 4;
7500 row_b[off] = ctx.color_rgb[0];
7501 row_b[off + 1] = ctx.color_rgb[1];
7502 row_b[off + 2] = ctx.color_rgb[2];
7503 row_b[off + 3] = 255;
7504 shaded += 1;
7505 }
7506 if do_rb {
7507 let off: usize = (xr_i as usize) * 4;
7508 row_b[off] = ctx.color_rgb[0];
7509 row_b[off + 1] = ctx.color_rgb[1];
7510 row_b[off + 2] = ctx.color_rgb[2];
7511 row_b[off + 3] = 255;
7512 shaded += 1;
7513 }
7514 } else {
7515 let inv_a: f32 = 1.0 - alpha_val;
7516 let sa_u32: u32 = (alpha_val * 255.0) as u32;
7517 let params: ShadowStripParams = ShadowStripParams {
7518 sr_a: ctx.lin_rgb[0] * alpha_val,
7519 sg_a: ctx.lin_rgb[1] * alpha_val,
7520 sb_a: ctx.lin_rgb[2] * alpha_val,
7521 inv_a,
7522 sa_u32,
7523 inv_a_u32: 255 - sa_u32,
7524 };
7525 let mut cache: ShadowPixelCache = ShadowPixelCache::default();
7526 if do_lt {
7527 blend_shadow_mirrored_pixel(row_t, xl_i as u32, y_term_t, params, &mut cache);
7528 shaded += 1;
7529 }
7530 if do_rt {
7531 blend_shadow_mirrored_pixel(row_t, xr_i as u32, y_term_t, params, &mut cache);
7532 shaded += 1;
7533 }
7534 if do_lb {
7535 blend_shadow_mirrored_pixel(row_b, xl_i as u32, y_term_b, params, &mut cache);
7536 shaded += 1;
7537 }
7538 if do_rb {
7539 blend_shadow_mirrored_pixel(row_b, xr_i as u32, y_term_b, params, &mut cache);
7540 shaded += 1;
7541 }
7542 }
7543 }
7544 shaded
7545 }
7546
7547 fn raster_shadow_corner_row_general(
7561 band: &mut PixelBand<'_>,
7562 ctx: &ShadowRenderContext,
7563 radius: CornerRadius,
7564 pos_y: u32,
7565 cutouts: (Rect, Rect),
7566 ) -> usize {
7567 let py: f32 = (pos_y as f32) + 0.5 - ctx.cy;
7568 let py_abs: f32 = py.abs();
7569 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(pos_y, cutouts, ctx.x0, ctx.x1);
7570 let spans: [(u32, u32); 2] = if cut0 < cut1 {
7571 [(ctx.x0, cut0), (cut1, ctx.x1)]
7572 } else {
7573 [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
7574 };
7575 let mut shaded: usize = 0;
7576 if ctx.has_mid_x {
7577 let dist_y: f32 = py_abs - ctx.half_h;
7578 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7579 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7580 } else {
7581 0.0
7582 };
7583 shaded += Self::raster_shadow_middle_span(band, ctx, pos_y, (cut0, cut1), mid_alpha);
7584 }
7585 let Some(row) = band.row_slice_mut(pos_y) else {
7586 return shaded;
7587 };
7588 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
7589 let r_l: f32 = (if py < 0.0 {
7590 radius.get_top_left()
7591 } else {
7592 radius.get_bottom_left()
7593 })
7594 .min(ctx.half_w)
7595 .min(ctx.half_h)
7596 .max(0.0);
7597 let r_r: f32 = (if py < 0.0 {
7598 radius.get_top_right()
7599 } else {
7600 radius.get_bottom_right()
7601 })
7602 .min(ctx.half_w)
7603 .min(ctx.half_h)
7604 .max(0.0);
7605 let qy_l: f32 = py_abs - ctx.half_h + r_l;
7606 let qy_l_pos: f32 = qy_l.max(0.0);
7607 let qy_l_sq: f32 = qy_l_pos * qy_l_pos;
7608 let cut_l_r: f32 = ctx.cutoff + r_l + 1e-3;
7609 let geom_l: (f32, f32, f32, f32) = (ctx.half_w, r_l, ctx.cutoff, cut_l_r * cut_l_r);
7610 let qy_r: f32 = py_abs - ctx.half_h + r_r;
7611 let qy_r_pos: f32 = qy_r.max(0.0);
7612 let qy_r_sq: f32 = qy_r_pos * qy_r_pos;
7613 let cut_r_r: f32 = ctx.cutoff + r_r + 1e-3;
7614 let geom_r: (f32, f32, f32, f32) = (ctx.half_w, r_r, ctx.cutoff, cut_r_r * cut_r_r);
7615 for (rx0, rx1) in spans.into_iter() {
7616 if rx0 >= rx1 {
7617 continue;
7618 }
7619 if ctx.has_mid_x {
7620 let l_end: u32 = rx1.min(ctx.lx1);
7621 for pos_x in rx0..l_end {
7622 let px: f32 = (pos_x as f32) + 0.5 - ctx.cx;
7623 let dist: f32 = if px < 0.0 {
7624 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7625 } else {
7626 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7627 };
7628 if dist < ctx.cutoff {
7629 let alpha_f: f32 =
7630 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7631 if alpha_f > 0.0005 {
7632 blend_shadow_row_pixel(
7633 row,
7634 pos_x,
7635 y_term,
7636 ctx.color_rgb,
7637 ctx.lin_rgb,
7638 alpha_f,
7639 );
7640 shaded += 1;
7641 }
7642 }
7643 }
7644 let r_start: u32 = rx0.max(ctx.rx0);
7645 for coord_x in r_start..rx1 {
7646 let px: f32 = (coord_x as f32) + 0.5 - ctx.cx;
7647 let dist: f32 = if px < 0.0 {
7648 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7649 } else {
7650 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7651 };
7652 if dist < ctx.cutoff {
7653 let alpha_f: f32 =
7654 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7655 if alpha_f > 0.0005 {
7656 blend_shadow_row_pixel(
7657 row,
7658 coord_x,
7659 y_term,
7660 ctx.color_rgb,
7661 ctx.lin_rgb,
7662 alpha_f,
7663 );
7664 shaded += 1;
7665 }
7666 }
7667 }
7668 } else {
7669 for sample_x in rx0..rx1 {
7670 let px: f32 = (sample_x as f32) + 0.5 - ctx.cx;
7671 let dist: f32 = if px < 0.0 {
7672 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7673 } else {
7674 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7675 };
7676 if dist >= ctx.cutoff {
7677 continue;
7678 }
7679 let alpha_f: f32 =
7680 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7681 if alpha_f > 0.0005 {
7682 blend_shadow_row_pixel(
7683 row,
7684 sample_x,
7685 y_term,
7686 ctx.color_rgb,
7687 ctx.lin_rgb,
7688 alpha_f,
7689 );
7690 shaded += 1;
7691 }
7692 }
7693 }
7694 }
7695 shaded
7696 }
7697
7698 fn raster_shadow_vertical_strips(
7711 band: &mut PixelBand<'_>,
7712 ctx: &ShadowRenderContext,
7713 y_span: (u32, u32),
7714 cutouts: (Rect, Rect),
7715 ) -> usize {
7716 let (sy0, sy1): (u32, u32) = y_span;
7717 if sy0 >= sy1 {
7718 return 0;
7719 }
7720 let (cut_h, _): (Rect, Rect) = cutouts;
7721 let sy0_f: f32 = (sy0 as f32) + 0.5;
7722 let sy1_last_f: f32 = ((sy1 - 1) as f32) + 0.5;
7723 let const_cut: Option<(u32, u32)> = if cut_h.get_width() > 0.0
7724 && cut_h.get_height() > 0.0
7725 && sy0_f >= cut_h.get_y()
7726 && sy1_last_f < cut_h.bottom()
7727 {
7728 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(ctx.x0, ctx.x1);
7729 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, ctx.x1);
7730 Some((cx0, cx1))
7731 } else {
7732 None
7733 };
7734 let (l_build0, l_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
7735 active_span_bounds(ctx.x0, ctx.lx1, c0, c1)
7736 } else {
7737 (ctx.x0, ctx.lx1)
7738 };
7739 let (r_build0, r_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
7740 active_span_bounds(ctx.rx0, ctx.x1, c0, c1)
7741 } else {
7742 (ctx.rx0, ctx.x1)
7743 };
7744 let mut shaded: usize = 0;
7745 let ran_tls: bool = BAND_SHADOW_SCRATCH
7746 .try_with(|cell: &RefCell<BandShadowScratch>| {
7747 if let Ok(mut scratch) = cell.try_borrow_mut() {
7748 let BandShadowScratch {
7749 left_hot,
7750 left_params,
7751 right_hot,
7752 right_params,
7753 } = &mut *scratch;
7754 let (l_act0, l_act1): (u32, u32) = build_shadow_vertical_strip(
7755 (l_build0, l_build1),
7756 ctx,
7757 left_hot,
7758 left_params,
7759 );
7760 let (r_act0, r_act1): (u32, u32) = build_shadow_vertical_strip(
7761 (r_build0, r_build1),
7762 ctx,
7763 right_hot,
7764 right_params,
7765 );
7766 if l_act0 >= l_act1 && r_act0 >= r_act1 {
7767 return;
7768 }
7769 let l_hot_s: &mut [ShadowStripHot] = left_hot.as_mut_slice();
7770 let l_par_s: &[ShadowStripParams] = left_params.as_slice();
7771 let r_hot_s: &mut [ShadowStripHot] = right_hot.as_mut_slice();
7772 let r_par_s: &[ShadowStripParams] = right_params.as_slice();
7773 for pos_y in sy0..sy1 {
7774 let Some(row) = band.row_slice_mut(pos_y) else {
7775 continue;
7776 };
7777 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
7778 let (cut0, cut1): (u32, u32) = const_cut.unwrap_or_else(|| {
7779 Self::shadow_row_cutout(pos_y, cutouts, ctx.x0, ctx.x1)
7780 });
7781 if l_act0 < l_act1 {
7782 if cut0 < cut1 {
7783 let a_end: u32 = cut0.min(l_act1);
7784 if l_act0 < a_end {
7785 shaded += apply_shadow_strip_span(
7786 row,
7787 (l_act0, a_end, l_act0),
7788 y_term,
7789 ctx.color_rgb,
7790 l_hot_s,
7791 l_par_s,
7792 );
7793 }
7794 let b_start: u32 = cut1.max(l_act0);
7795 if b_start < l_act1 {
7796 shaded += apply_shadow_strip_span(
7797 row,
7798 (b_start, l_act1, l_act0),
7799 y_term,
7800 ctx.color_rgb,
7801 l_hot_s,
7802 l_par_s,
7803 );
7804 }
7805 } else {
7806 shaded += apply_shadow_strip_span(
7807 row,
7808 (l_act0, l_act1, l_act0),
7809 y_term,
7810 ctx.color_rgb,
7811 l_hot_s,
7812 l_par_s,
7813 );
7814 }
7815 }
7816 if r_act0 < r_act1 {
7817 if cut0 < cut1 {
7818 let a_end: u32 = cut0.min(r_act1);
7819 if r_act0 < a_end {
7820 shaded += apply_shadow_strip_span(
7821 row,
7822 (r_act0, a_end, r_act0),
7823 y_term,
7824 ctx.color_rgb,
7825 r_hot_s,
7826 r_par_s,
7827 );
7828 }
7829 let b_start: u32 = cut1.max(r_act0);
7830 if b_start < r_act1 {
7831 shaded += apply_shadow_strip_span(
7832 row,
7833 (b_start, r_act1, r_act0),
7834 y_term,
7835 ctx.color_rgb,
7836 r_hot_s,
7837 r_par_s,
7838 );
7839 }
7840 } else {
7841 shaded += apply_shadow_strip_span(
7842 row,
7843 (r_act0, r_act1, r_act0),
7844 y_term,
7845 ctx.color_rgb,
7846 r_hot_s,
7847 r_par_s,
7848 );
7849 }
7850 }
7851 }
7852 }
7853 })
7854 .is_ok();
7855 if !ran_tls {
7856 for coord_y in sy0..sy1 {
7857 let Some(row) = band.row_slice_mut(coord_y) else {
7858 continue;
7859 };
7860 let y_term: f32 = (coord_y as f32) * 0.005_837_15;
7861 let (cut0, cut1): (u32, u32) = const_cut
7862 .unwrap_or_else(|| Self::shadow_row_cutout(coord_y, cutouts, ctx.x0, ctx.x1));
7863 let spans: [(u32, u32); 2] = if cut0 < cut1 {
7864 [(ctx.x0, cut0), (cut1, ctx.x1)]
7865 } else {
7866 [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
7867 };
7868 for (rx0, rx1) in spans.into_iter() {
7869 let left_end: u32 = rx1.min(ctx.lx1);
7870 for pos_x in rx0..left_end {
7871 let dist: f32 = ((pos_x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
7872 if dist < ctx.cutoff {
7873 let alpha_f: f32 =
7874 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7875 if alpha_f > 0.0005 {
7876 blend_shadow_row_pixel(
7877 row,
7878 pos_x,
7879 y_term,
7880 ctx.color_rgb,
7881 ctx.lin_rgb,
7882 alpha_f,
7883 );
7884 shaded += 1;
7885 }
7886 }
7887 }
7888 let right_start: u32 = rx0.max(ctx.rx0);
7889 for coord_x in right_start..rx1 {
7890 let dist: f32 = ((coord_x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
7891 if dist < ctx.cutoff {
7892 let alpha_f: f32 =
7893 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7894 if alpha_f > 0.0005 {
7895 blend_shadow_row_pixel(
7896 row,
7897 coord_x,
7898 y_term,
7899 ctx.color_rgb,
7900 ctx.lin_rgb,
7901 alpha_f,
7902 );
7903 shaded += 1;
7904 }
7905 }
7906 }
7907 }
7908 }
7909 }
7910 shaded
7911 }
7912
7913 fn raster_shadow(
7928 band: &mut PixelBand<'_>,
7929 rects: (Rect, Rect, Rect),
7930 radius: CornerRadius,
7931 sigma: f32,
7932 color: Color,
7933 cutouts: (Rect, Rect),
7934 ) -> usize {
7935 let (shadow_rect, caster_rect, clip): (Rect, Rect, Rect) = rects;
7936 if color.get_alpha() == 0 {
7937 return 0;
7938 }
7939 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
7940 if base_alpha <= 0.0005 {
7941 return 0;
7942 }
7943 let Some(vis) = shadow_rect.intersect(clip) else {
7944 return 0;
7945 };
7946 let fb_w: u32 = band.width();
7947 let band_y0: u32 = band.y_offset();
7948 let band_y1: u32 = band.y_end();
7949 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
7950 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
7951 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
7952 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
7953 if x0 >= x1 || y0 >= y1 {
7954 return 0;
7955 }
7956 let half_w: f32 = (caster_rect.get_width() * 0.5).max(0.5);
7957 let half_h: f32 = (caster_rect.get_height() * 0.5).max(0.5);
7958 let cx: f32 = caster_rect.get_x() + half_w;
7959 let cy: f32 = caster_rect.get_y() + half_h;
7960 let inv_sigma: f32 = 1.0 / sigma.max(0.5);
7961 let cutoff: f32 = sigma * 3.0;
7962 let r_max: f32 = radius.max_radius();
7963 let inner_inset: f32 = cutoff + r_max;
7964 let sy0: u32 = ((caster_rect.get_y() + inner_inset).ceil().max(0.0) as u32).clamp(y0, y1);
7965 let sy1: u32 = ((caster_rect.bottom() - inner_inset).floor().max(0.0) as u32).clamp(y0, y1);
7966 let sx0: u32 = ((caster_rect.get_x() + inner_inset).ceil().max(0.0) as u32).clamp(x0, x1);
7967 let sx1: u32 = ((caster_rect.right() - inner_inset).floor().max(0.0) as u32).clamp(x0, x1);
7968 let has_mid_x: bool = sx0 < sx1;
7969 let has_mid_y: bool = sy0 < sy1;
7970 let r_tl: f32 = radius.get_top_left();
7971 let uniform_radius: bool = r_tl == radius.get_top_right()
7972 && r_tl == radius.get_bottom_right()
7973 && r_tl == radius.get_bottom_left();
7974 let two_cx_f: f32 = 2.0 * cx;
7975 let two_cx_i: i32 = two_cx_f.round() as i32;
7976 let x_symmetric: bool =
7977 uniform_radius && (two_cx_i as f32) == two_cx_f && two_cx_f.abs() < 16_777_216.0;
7978 let two_cy_f: f32 = 2.0 * cy;
7979 let two_cy_i: i32 = two_cy_f.round() as i32;
7980 let y_symmetric: bool =
7981 x_symmetric && (two_cy_i as f32) == two_cy_f && two_cy_f.abs() < 16_777_216.0;
7982 let uniform_r: f32 = r_tl.min(half_w).min(half_h).max(0.0);
7983 let cutoff_r_safe: f32 = cutoff + uniform_r + 1e-3;
7984 let (lx1, rx0): (u32, u32) = if has_mid_x {
7985 (sx0, sx1)
7986 } else if x_symmetric {
7987 let split_x: u32 = ((two_cx_i + 1).div_euclid(2).max(0) as u32).clamp(x0, x1);
7988 (split_x, split_x)
7989 } else {
7990 (x1, x1)
7991 };
7992 let color_rgb: [u8; 3] = [color.get_red(), color.get_green(), color.get_blue()];
7993 let lin_rgb: [f32; 3] = [
7994 SRGB_TO_LIN_LUT[color_rgb[0] as usize],
7995 SRGB_TO_LIN_LUT[color_rgb[1] as usize],
7996 SRGB_TO_LIN_LUT[color_rgb[2] as usize],
7997 ];
7998 let ctx: ShadowRenderContext = ShadowRenderContext {
7999 color,
8000 color_rgb,
8001 lin_rgb,
8002 cx,
8003 cy,
8004 half_w,
8005 half_h,
8006 base_alpha,
8007 inv_sigma,
8008 cutoff,
8009 uniform_r,
8010 cutoff_r_safe_sq: cutoff_r_safe * cutoff_r_safe,
8011 x0,
8012 x1,
8013 lx1,
8014 rx0,
8015 mirror_x_sum: two_cx_i - 1,
8016 has_mid_x,
8017 };
8018 let mut shaded: usize = 0;
8019 if x_symmetric {
8020 let (top_end, bot_start): (u32, u32) = if has_mid_x && has_mid_y {
8021 (sy0, sy1)
8022 } else if y_symmetric {
8023 let split_y: u32 = ((two_cy_i + 1).div_euclid(2).max(0) as u32).clamp(y0, y1);
8024 (split_y, split_y)
8025 } else {
8026 (y1, y1)
8027 };
8028 let mirror_y_sum: i32 = two_cy_i - 1;
8029 let mut mirrored_b0: u32 = y1;
8030 let mut mirrored_b1: u32 = bot_start;
8031 for y_t in y0..top_end {
8032 let y_b_i: i32 = if y_symmetric {
8033 mirror_y_sum - (y_t as i32)
8034 } else {
8035 -1
8036 };
8037 if y_b_i >= (bot_start as i32) && y_b_i < (y1 as i32) {
8038 let y_b: u32 = y_b_i as u32;
8039 mirrored_b0 = mirrored_b0.min(y_b);
8040 mirrored_b1 = mirrored_b1.max(y_b + 1);
8041 shaded +=
8042 Self::raster_shadow_corner_pair_symmetric(band, &ctx, y_t, y_b, cutouts);
8043 } else {
8044 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_t, cutouts);
8045 }
8046 }
8047 if has_mid_x && has_mid_y {
8048 shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
8049 }
8050 if mirrored_b0 < mirrored_b1 {
8051 for y_b in bot_start..mirrored_b0 {
8052 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8053 }
8054 for y_b in mirrored_b1..y1 {
8055 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8056 }
8057 } else {
8058 for y_b in bot_start..y1 {
8059 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8060 }
8061 }
8062 } else if has_mid_x && has_mid_y {
8063 for pos_y in y0..sy0 {
8064 shaded +=
8065 Self::raster_shadow_corner_row_general(band, &ctx, radius, pos_y, cutouts);
8066 }
8067 shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
8068 for coord_y in sy1..y1 {
8069 shaded +=
8070 Self::raster_shadow_corner_row_general(band, &ctx, radius, coord_y, cutouts);
8071 }
8072 } else {
8073 for sample_y in y0..y1 {
8074 shaded +=
8075 Self::raster_shadow_corner_row_general(band, &ctx, radius, sample_y, cutouts);
8076 }
8077 }
8078 shaded
8079 }
8080
8081 fn raster_text_run_band(
8095 band: &mut PixelBand<'_>,
8096 positioned_glyphs: &[PositionedGlyph],
8097 color: Color,
8098 clip: Rect,
8099 glyph_atlas: &GlyphAtlas,
8100 ) -> usize {
8101 let fb_w: i32 = band.width() as i32;
8102 let band_y0: i32 = band.y_offset() as i32;
8103 let band_y1: i32 = band.y_end() as i32;
8104 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
8105 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).clamp(band_y0, band_y1);
8106 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(fb_w);
8107 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).clamp(band_y0, band_y1);
8108 if color.get_alpha() == 0 || clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
8109 return 0;
8110 }
8111 let mut shaded: usize = 0;
8112 for pg in positioned_glyphs.iter() {
8113 let gy0: i32 = pg.get_y();
8114 let gh: i32 = pg.get_height() as i32;
8115 if gy0 >= clip_y1 || gy0 + gh <= clip_y0 {
8116 continue;
8117 }
8118 let gx0: i32 = pg.get_x();
8119 let gw: i32 = pg.get_width() as i32;
8120 if gx0 >= clip_x1 || gx0 + gw <= clip_x0 {
8121 continue;
8122 }
8123 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(pg.get_glyph_idx());
8124 let py_start: i32 = (clip_y0 - gy0).max(0);
8125 let py_end: i32 = (clip_y1 - gy0).min(gh);
8126 let px_start: i32 = (clip_x0 - gx0).max(0);
8127 let px_end: i32 = (clip_x1 - gx0).min(gw);
8128 if py_start < py_end && px_start < px_end {
8129 let dy0: u32 = (gy0 + py_start) as u32;
8130 let dy1: u32 = (gy0 + py_end) as u32;
8131 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(dy0, dy1) {
8132 let cov_bytes: &[u8] = glyph.get_coverage().as_slice();
8133 let gw_usize: usize = gw as usize;
8134 let bx0: usize = ((gx0 + px_start) as usize) * 4;
8135 let bx1: usize = ((gx0 + px_end) as usize) * 4;
8136 let start_u: usize = px_start as usize;
8137 let end_u: usize = px_end as usize;
8138 let mut cov_off: usize = (py_start as usize) * gw_usize;
8139 for row in rows_buf.chunks_exact_mut(row_stride) {
8140 let row_slice: &[u8] = &cov_bytes[cov_off + start_u..cov_off + end_u];
8141 shaded += blend_glyph_row_span(&mut row[bx0..bx1], row_slice, color);
8142 cov_off += gw_usize;
8143 }
8144 }
8145 }
8146 }
8147 shaded
8148 }
8149
8150 #[inline(always)]
8159 fn blit_opaque_horiz_packed_u32(
8160 vrow: &[u32],
8161 dst_x0: usize,
8162 x_packed: &[u32],
8163 dst_row: &mut [u8],
8164 ) {
8165 let len: usize = x_packed.len();
8166 let span_bytes_start: usize = dst_x0 * 4;
8167 let span_bytes_end: usize = (dst_x0 + len) * 4;
8168 if span_bytes_end > dst_row.len() || vrow.len() < 2 {
8169 return;
8170 }
8171 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
8172 .as_chunks_mut::<4>()
8173 .0;
8174 let vptr: *const u32 = vrow.as_ptr();
8175 let dptr: *mut [u8; 4] = dst_chunks.as_mut_ptr();
8176 let lptr: *const u32 = x_packed.as_ptr();
8177 let mut item_index: usize = 0;
8178 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8179 {
8180 let v256: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(256);
8181 let v128_round: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(128);
8182 let alpha_mask: core::arch::wasm32::v128 = core::arch::wasm32::u32x4_splat(0xFF00_0000);
8183 while item_index + 2 <= len {
8184 unsafe {
8186 let e0: u32 = *lptr.add(item_index);
8187 let e1: u32 = *lptr.add(item_index + 1);
8188 let sx_a: usize = (e0 >> 9) as usize;
8189 let wx_a: u16 = (e0 & 0x1FF) as u16;
8190 let sx_b: usize = (e1 >> 9) as usize;
8191 let wx_b: u16 = (e1 & 0x1FF) as u16;
8192 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8193 let pair_b: u64 = vptr.add(sx_b).cast::<u64>().read_unaligned();
8194 let p0_u32: core::arch::wasm32::v128 =
8195 core::arch::wasm32::u32x4(pair_a as u32, pair_b as u32, 0, 0);
8196 let p1_u32: core::arch::wasm32::v128 = core::arch::wasm32::u32x4(
8197 (pair_a >> 32) as u32,
8198 (pair_b >> 32) as u32,
8199 0,
8200 0,
8201 );
8202 let p0_16: core::arch::wasm32::v128 =
8203 core::arch::wasm32::u16x8_extend_low_u8x16(p0_u32);
8204 let p1_16: core::arch::wasm32::v128 =
8205 core::arch::wasm32::u16x8_extend_low_u8x16(p1_u32);
8206 let wx_v: core::arch::wasm32::v128 =
8207 core::arch::wasm32::u16x8(wx_a, wx_a, wx_a, wx_a, wx_b, wx_b, wx_b, wx_b);
8208 let iwx_v: core::arch::wasm32::v128 = core::arch::wasm32::i16x8_sub(v256, wx_v);
8209 let sum: core::arch::wasm32::v128 = core::arch::wasm32::i16x8_add(
8210 core::arch::wasm32::i16x8_add(
8211 core::arch::wasm32::i16x8_mul(p0_16, iwx_v),
8212 core::arch::wasm32::i16x8_mul(p1_16, wx_v),
8213 ),
8214 v128_round,
8215 );
8216 let shr: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(sum, 8);
8217 let packed: core::arch::wasm32::v128 = core::arch::wasm32::v128_or(
8218 core::arch::wasm32::u8x16_narrow_i16x8(shr, shr),
8219 alpha_mask,
8220 );
8221 core::arch::wasm32::v128_store64_lane::<0>(
8222 packed,
8223 dptr.add(item_index).cast::<u64>(),
8224 );
8225 }
8226 item_index += 2;
8227 }
8228 }
8229 #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
8230 while item_index + 2 <= len {
8231 unsafe {
8233 let e0: u32 = *lptr.add(item_index);
8234 let e1: u32 = *lptr.add(item_index + 1);
8235 let sx_a: usize = (e0 >> 9) as usize;
8236 let wx_a: u32 = e0 & 0x1FF;
8237 let iwx_a: u32 = 256 - wx_a;
8238 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8239 let p0_a: u32 = pair_a as u32;
8240 let p1_a: u32 = (pair_a >> 32) as u32;
8241 let rb_a: u32 =
8242 (((p0_a & 0x00FF_00FF) * iwx_a + (p1_a & 0x00FF_00FF) * wx_a + 0x0080_0080)
8243 >> 8)
8244 & 0x00FF_00FF;
8245 let g_a: u32 =
8246 ((((p0_a >> 8) & 0x00FF) * iwx_a + ((p1_a >> 8) & 0x00FF) * wx_a + 128) >> 8)
8247 << 8;
8248 *dptr.add(item_index) = (rb_a | g_a | 0xFF00_0000).to_le_bytes();
8249 let sx_b: usize = (e1 >> 9) as usize;
8250 let wx_b: u32 = e1 & 0x1FF;
8251 let iwx_b: u32 = 256 - wx_b;
8252 let pair_b: u64 = vptr.add(sx_b).cast::<u64>().read_unaligned();
8253 let p0_b: u32 = pair_b as u32;
8254 let p1_b: u32 = (pair_b >> 32) as u32;
8255 let rb_b: u32 =
8256 (((p0_b & 0x00FF_00FF) * iwx_b + (p1_b & 0x00FF_00FF) * wx_b + 0x0080_0080)
8257 >> 8)
8258 & 0x00FF_00FF;
8259 let g_b: u32 =
8260 ((((p0_b >> 8) & 0x00FF) * iwx_b + ((p1_b >> 8) & 0x00FF) * wx_b + 128) >> 8)
8261 << 8;
8262 *dptr.add(item_index + 1) = (rb_b | g_b | 0xFF00_0000).to_le_bytes();
8263 }
8264 item_index += 2;
8265 }
8266 if item_index < len {
8267 unsafe {
8269 let e0: u32 = *lptr.add(item_index);
8270 let sx_a: usize = (e0 >> 9) as usize;
8271 let wx_a: u32 = e0 & 0x1FF;
8272 let iwx_a: u32 = 256 - wx_a;
8273 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8274 let p0_a: u32 = pair_a as u32;
8275 let p1_a: u32 = (pair_a >> 32) as u32;
8276 let rb_a: u32 =
8277 (((p0_a & 0x00FF_00FF) * iwx_a + (p1_a & 0x00FF_00FF) * wx_a + 0x0080_0080)
8278 >> 8)
8279 & 0x00FF_00FF;
8280 let g_a: u32 =
8281 ((((p0_a >> 8) & 0x00FF) * iwx_a + ((p1_a >> 8) & 0x00FF) * wx_a + 128) >> 8)
8282 << 8;
8283 *dptr.add(item_index) = (rb_a | g_a | 0xFF00_0000).to_le_bytes();
8284 }
8285 }
8286 }
8287
8288 #[inline(always)]
8296 fn copy_opaque_row_to_vrow(src0: &[[u8; 4]], sx_range: (usize, usize), vrow: &mut [u32]) {
8297 let (sx_min, sx_max): (usize, usize) = sx_range;
8298 for (&px, out) in src0[sx_min..=sx_max]
8299 .iter()
8300 .zip(vrow[sx_min..=sx_max].iter_mut())
8301 {
8302 *out = u32::from_le_bytes(px);
8303 }
8304 vrow[sx_max + 1] = vrow[sx_max];
8305 }
8306
8307 #[inline(always)]
8317 fn blend_opaque_rows_vert_swar(
8318 src0: &[[u8; 4]],
8319 src1: &[[u8; 4]],
8320 sx_range: (usize, usize),
8321 weights: (u32, u32),
8322 vrow: &mut [u32],
8323 ) {
8324 let (sx_min, sx_max): (usize, usize) = sx_range;
8325 let (wy, iwy): (u32, u32) = weights;
8326 let s0_slice: &[[u8; 4]] = &src0[sx_min..=sx_max];
8327 let s1_slice: &[[u8; 4]] = &src1[sx_min..=sx_max];
8328 let dst_slice: &mut [u32] = &mut vrow[sx_min..=sx_max];
8329 let mut idx: usize = 0;
8330 let count: usize = dst_slice.len();
8331 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8332 if count >= 4 {
8333 unsafe {
8335 let s0_ptr: *const u8 = s0_slice.as_ptr().cast();
8336 let s1_ptr: *const u8 = s1_slice.as_ptr().cast();
8337 let d_ptr: *mut u8 = dst_slice.as_mut_ptr().cast();
8338 let v_wy: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(wy as u16);
8339 let v_iwy: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(iwy as u16);
8340 let v_round: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(128);
8341 let v_alpha: core::arch::wasm32::v128 =
8342 core::arch::wasm32::u32x4_splat(0xFF00_0000);
8343 while idx + 4 <= count {
8344 let b_off: usize = idx * 4;
8345 let a16: core::arch::wasm32::v128 =
8346 core::arch::wasm32::v128_load(s0_ptr.add(b_off).cast());
8347 let b16: core::arch::wasm32::v128 =
8348 core::arch::wasm32::v128_load(s1_ptr.add(b_off).cast());
8349 let a_lo: core::arch::wasm32::v128 =
8350 core::arch::wasm32::u16x8_extend_low_u8x16(a16);
8351 let b_lo: core::arch::wasm32::v128 =
8352 core::arch::wasm32::u16x8_extend_low_u8x16(b16);
8353 let a_hi: core::arch::wasm32::v128 =
8354 core::arch::wasm32::u16x8_extend_high_u8x16(a16);
8355 let b_hi: core::arch::wasm32::v128 =
8356 core::arch::wasm32::u16x8_extend_high_u8x16(b16);
8357 let lo: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(
8358 core::arch::wasm32::i16x8_add(
8359 core::arch::wasm32::i16x8_add(
8360 core::arch::wasm32::i16x8_mul(a_lo, v_iwy),
8361 core::arch::wasm32::i16x8_mul(b_lo, v_wy),
8362 ),
8363 v_round,
8364 ),
8365 8,
8366 );
8367 let hi: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(
8368 core::arch::wasm32::i16x8_add(
8369 core::arch::wasm32::i16x8_add(
8370 core::arch::wasm32::i16x8_mul(a_hi, v_iwy),
8371 core::arch::wasm32::i16x8_mul(b_hi, v_wy),
8372 ),
8373 v_round,
8374 ),
8375 8,
8376 );
8377 let packed: core::arch::wasm32::v128 = core::arch::wasm32::v128_or(
8378 core::arch::wasm32::u8x16_narrow_i16x8(lo, hi),
8379 v_alpha,
8380 );
8381 core::arch::wasm32::v128_store(d_ptr.add(b_off).cast(), packed);
8382 idx += 4;
8383 }
8384 }
8385 }
8386 while idx < count {
8387 let p0: u32 = u32::from_le_bytes(s0_slice[idx]);
8388 let p1: u32 = u32::from_le_bytes(s1_slice[idx]);
8389 let rb: u32 = (((p0 & 0x00FF_00FF) * iwy + (p1 & 0x00FF_00FF) * wy + 0x0080_0080) >> 8)
8390 & 0x00FF_00FF;
8391 let green_val: u32 =
8392 ((((p0 >> 8) & 0x00FF) * iwy + ((p1 >> 8) & 0x00FF) * wy + 128) >> 8) << 8;
8393 dst_slice[idx] = (rb | green_val) | 0xFF00_0000;
8394 idx += 1;
8395 }
8396 vrow[sx_max + 1] = vrow[sx_max];
8397 }
8398
8399 #[inline(always)]
8413 fn blit_bilinear_span_precomputed(
8414 y_params: (usize, usize, u32, u32),
8415 dst_x0: usize,
8416 x_lut: &[(usize, usize, u32)],
8417 src_bytes: &[u8],
8418 dst_row: &mut [u8],
8419 ) -> usize {
8420 let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
8421 let span_bytes_start: usize = dst_x0 * 4;
8422 let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
8423 if span_bytes_end > dst_row.len() {
8424 return 0;
8425 }
8426 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
8427 .as_chunks_mut::<4>()
8428 .0;
8429 let src_len: usize = src_bytes.len();
8430 let mut shaded: usize = 0;
8431 if wy == 0 {
8432 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
8433 let i0: usize = (row0 + sx0) * 4;
8434 let i1: usize = (row0 + sx1) * 4;
8435 if i1 + 4 > src_len {
8436 continue;
8437 }
8438 let iwx: u32 = 256 - wx;
8439 let a0: u32 = src_bytes[i0 + 3] as u32;
8440 let a1: u32 = src_bytes[i1 + 3] as u32;
8441 if (a0 & a1) == 255 {
8442 dp[0] = (((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128)
8443 >> 8) as u8;
8444 dp[1] =
8445 (((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128)
8446 >> 8) as u8;
8447 dp[2] =
8448 (((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128)
8449 >> 8) as u8;
8450 dp[3] = 255;
8451 shaded += 1;
8452 continue;
8453 }
8454 let aw0: u32 = a0 * iwx;
8455 let aw1: u32 = a1 * wx;
8456 let a_val: u32 = (aw0 + aw1 + 128) >> 8;
8457 if a_val == 0 {
8458 continue;
8459 }
8460 let pr: u32 =
8461 ((src_bytes[i0] as u32) * aw0 + (src_bytes[i1] as u32) * aw1 + 128) >> 8;
8462 let pg: u32 =
8463 ((src_bytes[i0 + 1] as u32) * aw0 + (src_bytes[i1 + 1] as u32) * aw1 + 128)
8464 >> 8;
8465 let pb: u32 =
8466 ((src_bytes[i0 + 2] as u32) * aw0 + (src_bytes[i1 + 2] as u32) * aw1 + 128)
8467 >> 8;
8468 let inv_a: u32 = 255 - a_val;
8469 let vr: u32 = pr + (dp[0] as u32) * inv_a + 128;
8470 let vg: u32 = pg + (dp[1] as u32) * inv_a + 128;
8471 let vb: u32 = pb + (dp[2] as u32) * inv_a + 128;
8472 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
8473 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
8474 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
8475 dp[3] = 255;
8476 shaded += 1;
8477 }
8478 return shaded;
8479 }
8480 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
8481 let i00: usize = (row0 + sx0) * 4;
8482 let i10: usize = (row0 + sx1) * 4;
8483 let i01: usize = (row1 + sx0) * 4;
8484 let i11: usize = (row1 + sx1) * 4;
8485 if i11 + 4 > src_len {
8486 continue;
8487 }
8488 let iwx: u32 = 256 - wx;
8489 let w00: u32 = iwx * iwy;
8490 let w10: u32 = wx * iwy;
8491 let w01: u32 = iwx * wy;
8492 let w11: u32 = wx * wy;
8493 let a00: u32 = src_bytes[i00 + 3] as u32;
8494 let a10: u32 = src_bytes[i10 + 3] as u32;
8495 let a01: u32 = src_bytes[i01 + 3] as u32;
8496 let a11: u32 = src_bytes[i11 + 3] as u32;
8497 if (a00 & a10 & a01 & a11) == 255 {
8498 dp[0] = (((src_bytes[i00] as u32) * w00
8499 + (src_bytes[i10] as u32) * w10
8500 + (src_bytes[i01] as u32) * w01
8501 + (src_bytes[i11] as u32) * w11
8502 + 32768)
8503 >> 16) as u8;
8504 dp[1] = (((src_bytes[i00 + 1] as u32) * w00
8505 + (src_bytes[i10 + 1] as u32) * w10
8506 + (src_bytes[i01 + 1] as u32) * w01
8507 + (src_bytes[i11 + 1] as u32) * w11
8508 + 32768)
8509 >> 16) as u8;
8510 dp[2] = (((src_bytes[i00 + 2] as u32) * w00
8511 + (src_bytes[i10 + 2] as u32) * w10
8512 + (src_bytes[i01 + 2] as u32) * w01
8513 + (src_bytes[i11 + 2] as u32) * w11
8514 + 32768)
8515 >> 16) as u8;
8516 dp[3] = 255;
8517 shaded += 1;
8518 continue;
8519 }
8520 let aw00: u64 = (a00 as u64) * (w00 as u64);
8521 let aw10: u64 = (a10 as u64) * (w10 as u64);
8522 let aw01: u64 = (a01 as u64) * (w01 as u64);
8523 let aw11: u64 = (a11 as u64) * (w11 as u64);
8524 let a_val: u32 = ((aw00 + aw10 + aw01 + aw11 + 32768) >> 16) as u32;
8525 if a_val == 0 {
8526 continue;
8527 }
8528 let pr: u32 = (((src_bytes[i00] as u64) * aw00
8529 + (src_bytes[i10] as u64) * aw10
8530 + (src_bytes[i01] as u64) * aw01
8531 + (src_bytes[i11] as u64) * aw11
8532 + 32768)
8533 >> 16) as u32;
8534 let pg: u32 = (((src_bytes[i00 + 1] as u64) * aw00
8535 + (src_bytes[i10 + 1] as u64) * aw10
8536 + (src_bytes[i01 + 1] as u64) * aw01
8537 + (src_bytes[i11 + 1] as u64) * aw11
8538 + 32768)
8539 >> 16) as u32;
8540 let pb: u32 = (((src_bytes[i00 + 2] as u64) * aw00
8541 + (src_bytes[i10 + 2] as u64) * aw10
8542 + (src_bytes[i01 + 2] as u64) * aw01
8543 + (src_bytes[i11 + 2] as u64) * aw11
8544 + 32768)
8545 >> 16) as u32;
8546 let inv_a: u32 = 255 - a_val;
8547 let vr: u32 = pr + (dp[0] as u32) * inv_a + 128;
8548 let vg: u32 = pg + (dp[1] as u32) * inv_a + 128;
8549 let vb: u32 = pb + (dp[2] as u32) * inv_a + 128;
8550 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
8551 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
8552 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
8553 dp[3] = 255;
8554 shaded += 1;
8555 }
8556 shaded
8557 }
8558
8559 fn raster_image_bilinear_with_lut(
8575 band: &mut PixelBand<'_>,
8576 rect: Rect,
8577 src_info: (u32, u32, &[u8]),
8578 bounds: (u32, u32, u32, u32),
8579 radius: CornerRadius,
8580 aa: AntialiasingMode,
8581 x_lut: &mut Vec<(usize, usize, u32)>,
8582 ) -> usize {
8583 let (src_w, src_h, src_bytes): (u32, u32, &[u8]) = src_info;
8584 let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
8585 let rect_x: f32 = rect.get_x();
8586 let rect_y: f32 = rect.get_y();
8587 let half_w: f32 = rect.get_width() * 0.5;
8588 let half_h: f32 = rect.get_height() * 0.5;
8589 let cx: f32 = rect_x + half_w;
8590 let cy: f32 = rect_y + half_h;
8591 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
8592 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
8593 let src_w_f: f32 = src_w as f32;
8594 let src_h_f: f32 = src_h as f32;
8595 let src_w_usize: usize = src_w as usize;
8596 let max_sx: usize = src_w_usize.saturating_sub(1);
8597 let max_sy: usize = (src_h as usize).saturating_sub(1);
8598 let has_radius: bool = radius.max_radius() > 0.0;
8599 x_lut.clear();
8600 for pos_x in x0..x1 {
8601 let tex_u: f32 = (((pos_x as f32) + 0.5 - rect_x) * inv_dst_w).clamp(0.0, 1.0);
8602 let fx: f32 = (tex_u * src_w_f - 0.5).clamp(0.0, max_sx as f32);
8603 let sx0: usize = (fx.floor() as usize).min(max_sx);
8604 let sx1: usize = (sx0 + 1).min(max_sx);
8605 let wx: u32 = ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8606 x_lut.push((sx0, sx1, wx));
8607 }
8608 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
8609 if !has_radius {
8610 let x0_u: usize = x0 as usize;
8611 let sx_min: usize = x_lut_ref
8612 .first()
8613 .map_or(0, |event_ref: &(usize, usize, u32)| event_ref.0);
8614 let sx_max: usize = x_lut_ref
8615 .last()
8616 .map_or(0, |error_val: &(usize, usize, u32)| error_val.1)
8617 .min(max_sx);
8618 let src_row_bytes_len: usize = src_w_usize * 4;
8619 let can_fast_opaque: bool = !x_lut_ref.is_empty()
8620 && sx_min <= sx_max
8621 && sx_max < src_w_usize
8622 && (src_h as usize) * src_row_bytes_len <= src_bytes.len();
8623 if can_fast_opaque {
8624 let mut cached_op_sy: usize = usize::MAX;
8625 let mut cached_op_val: bool = false;
8626 let mut cached_op_sy2: usize = usize::MAX;
8627 let mut cached_op_val2: bool = false;
8628 let ran_vrow: bool = BAND_IMAGE_VROW_U32
8629 .try_with(|cell: &RefCell<Vec<u32>>| {
8630 let _ran_packed: bool = BAND_IMAGE_X_PACKED
8631 .try_with(|pcell: &RefCell<Vec<u32>>| {
8632 if let (Ok(mut vrow_guard), Ok(mut packed_guard)) =
8633 (cell.try_borrow_mut(), pcell.try_borrow_mut())
8634 {
8635 if vrow_guard.len() < src_w_usize + 1 {
8636 vrow_guard.resize(src_w_usize + 1, 0);
8637 }
8638 packed_guard.clear();
8639 for &(sx0, _, wx) in x_lut_ref.iter() {
8640 packed_guard.push(((sx0 as u32) << 9) | (wx & 0x1FF));
8641 }
8642 let x_packed_ref: &[u32] = packed_guard.as_slice();
8643 let vrow: &mut [u32] = vrow_guard.as_mut_slice();
8644 let mut prev_vkey: (usize, usize, u32) =
8645 (usize::MAX, usize::MAX, u32::MAX);
8646 let check_start: usize = sx_min * 4;
8647 let check_end: usize = (sx_max + 1) * 4;
8648 for pos_y in y0..y1 {
8649 let Some(dst_row) = band.row_slice_mut(pos_y) else {
8650 continue;
8651 };
8652 let item_val: f32 = (((pos_y as f32) + 0.5 - rect_y)
8653 * inv_dst_h)
8654 .clamp(0.0, 1.0);
8655 let fy: f32 =
8656 (item_val * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8657 let sy0: usize = (fy.floor() as usize).min(max_sy);
8658 let sy1: usize = (sy0 + 1).min(max_sy);
8659 let wy: u32 =
8660 ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0)
8661 as u32;
8662 let r0_off: usize = sy0 * src_row_bytes_len;
8663 let op0: bool = if sy0 == cached_op_sy {
8664 cached_op_val
8665 } else if sy0 == cached_op_sy2 {
8666 cached_op_val2
8667 } else {
8668 let val: bool = is_rgba_slice_opaque(
8669 &src_bytes
8670 [(r0_off + check_start)..(r0_off + check_end)],
8671 );
8672 cached_op_sy2 = cached_op_sy;
8673 cached_op_val2 = cached_op_val;
8674 cached_op_sy = sy0;
8675 cached_op_val = val;
8676 val
8677 };
8678 if wy == 0 || sy0 == sy1 {
8679 if op0 {
8680 let vkey: (usize, usize, u32) = (sy0, sy0, 0);
8681 if prev_vkey != vkey {
8682 let row0_px: &[[u8; 4]] = src_bytes
8683 [r0_off..(r0_off + src_row_bytes_len)]
8684 .as_chunks::<4>()
8685 .0;
8686 Self::copy_opaque_row_to_vrow(
8687 row0_px,
8688 (sx_min, sx_max),
8689 vrow,
8690 );
8691 prev_vkey = vkey;
8692 }
8693 Self::blit_opaque_horiz_packed_u32(
8694 vrow,
8695 x0_u,
8696 x_packed_ref,
8697 dst_row,
8698 );
8699 continue;
8700 }
8701 } else if op0 {
8702 let r1_off: usize = sy1 * src_row_bytes_len;
8703 let op1: bool = if sy1 == cached_op_sy {
8704 cached_op_val
8705 } else if sy1 == cached_op_sy2 {
8706 cached_op_val2
8707 } else {
8708 let val: bool = is_rgba_slice_opaque(
8709 &src_bytes[(r1_off + check_start)
8710 ..(r1_off + check_end)],
8711 );
8712 cached_op_sy2 = cached_op_sy;
8713 cached_op_val2 = cached_op_val;
8714 cached_op_sy = sy1;
8715 cached_op_val = val;
8716 val
8717 };
8718 if op1 {
8719 let vkey: (usize, usize, u32) = (sy0, sy1, wy);
8720 if prev_vkey != vkey {
8721 let row0_px: &[[u8; 4]] = src_bytes
8722 [r0_off..(r0_off + src_row_bytes_len)]
8723 .as_chunks::<4>()
8724 .0;
8725 let row1_px: &[[u8; 4]] = src_bytes
8726 [r1_off..(r1_off + src_row_bytes_len)]
8727 .as_chunks::<4>()
8728 .0;
8729 Self::blend_opaque_rows_vert_swar(
8730 row0_px,
8731 row1_px,
8732 (sx_min, sx_max),
8733 (wy, 256 - wy),
8734 vrow,
8735 );
8736 prev_vkey = vkey;
8737 }
8738 Self::blit_opaque_horiz_packed_u32(
8739 vrow,
8740 x0_u,
8741 x_packed_ref,
8742 dst_row,
8743 );
8744 continue;
8745 }
8746 }
8747 let y_params: (usize, usize, u32, u32) =
8748 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8749 let _: usize = Self::blit_bilinear_span_precomputed(
8750 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
8751 );
8752 }
8753 }
8754 })
8755 .is_ok();
8756 })
8757 .is_ok();
8758 if ran_vrow {
8759 return ((x1 - x0) as usize) * ((y1 - y0) as usize);
8760 }
8761 }
8762 for coord_y in y0..y1 {
8763 let Some(dst_row) = band.row_slice_mut(coord_y) else {
8764 continue;
8765 };
8766 let tex_v: f32 = (((coord_y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
8767 let fy: f32 = (tex_v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8768 let sy0: usize = (fy.floor() as usize).min(max_sy);
8769 let sy1: usize = (sy0 + 1).min(max_sy);
8770 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8771 let y_params: (usize, usize, u32, u32) =
8772 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8773 let _: usize = Self::blit_bilinear_span_precomputed(
8774 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
8775 );
8776 }
8777 return ((x1 - x0) as usize) * ((y1 - y0) as usize);
8778 }
8779 let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
8780 let ix0: u32 = ((rect_x + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
8781 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
8782 let iy0: u32 = ((rect_y + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
8783 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
8784 let cx0: u32 = ((rect_x + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
8785 let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
8786 let mut shaded: usize = 0;
8787 for sample_y in y0..iy0 {
8788 let Some(dst_row) = band.row_slice_mut(sample_y) else {
8789 continue;
8790 };
8791 let bary_v: f32 = (((sample_y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
8792 let fy: f32 = (bary_v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8793 let sy0: usize = (fy.floor() as usize).min(max_sy);
8794 let sy1: usize = (sy0 + 1).min(max_sy);
8795 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8796 let y_params: (usize, usize, u32, u32) =
8797 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8798 let py: f32 = (sample_y as f32) + 0.5 - cy;
8799 let dist_y: f32 = py.abs() - half_h;
8800 let mid_cov: f32 = sdf_coverage(dist_y, aa);
8801 if cx0 < cx1 && mid_cov > 0.0 {
8802 let lut_s: usize = (cx0 - x0) as usize;
8803 let lut_e: usize = (cx1 - x0) as usize;
8804 if mid_cov >= 0.9995 {
8805 let _: usize = Self::blit_bilinear_span_precomputed(
8806 y_params,
8807 cx0 as usize,
8808 &x_lut_ref[lut_s..lut_e],
8809 src_bytes,
8810 dst_row,
8811 );
8812 } else {
8813 for coord_x in cx0..cx1 {
8814 let rgba: [u8; 4] = sample_bilinear_fixed(
8815 src_bytes,
8816 y_params,
8817 x_lut_ref[(coord_x - x0) as usize],
8818 );
8819 let off: usize = (coord_x as usize) * 4;
8820 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
8821 }
8822 }
8823 shaded += (cx1 - cx0) as usize;
8824 }
8825 for sample_x in x0..cx0 {
8826 let px: f32 = (sample_x as f32) + 0.5 - cx;
8827 let cr: f32 = quadrant_corner_radius(radius, px, py);
8828 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
8829 if cov > 0.0 {
8830 let rgba: [u8; 4] = sample_bilinear_fixed(
8831 src_bytes,
8832 y_params,
8833 x_lut_ref[(sample_x - x0) as usize],
8834 );
8835 let off: usize = (sample_x as usize) * 4;
8836 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8837 shaded += 1;
8838 }
8839 }
8840 for value_x in cx1..x1 {
8841 let px: f32 = (value_x as f32) + 0.5 - cx;
8842 let cr: f32 = quadrant_corner_radius(radius, px, py);
8843 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
8844 if cov > 0.0 {
8845 let rgba: [u8; 4] = sample_bilinear_fixed(
8846 src_bytes,
8847 y_params,
8848 x_lut_ref[(value_x - x0) as usize],
8849 );
8850 let off: usize = (value_x as usize) * 4;
8851 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8852 shaded += 1;
8853 }
8854 }
8855 }
8856 for value_y in iy0..iy1 {
8857 let Some(dst_row) = band.row_slice_mut(value_y) else {
8858 continue;
8859 };
8860 let sample_val: f32 = (((value_y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
8861 let fy: f32 = (sample_val * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8862 let sy0: usize = (fy.floor() as usize).min(max_sy);
8863 let sy1: usize = (sy0 + 1).min(max_sy);
8864 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8865 let y_params: (usize, usize, u32, u32) =
8866 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8867 if ix0 < ix1 {
8868 let lut_s: usize = (ix0 - x0) as usize;
8869 let lut_e: usize = (ix1 - x0) as usize;
8870 let _: usize = Self::blit_bilinear_span_precomputed(
8871 y_params,
8872 ix0 as usize,
8873 &x_lut_ref[lut_s..lut_e],
8874 src_bytes,
8875 dst_row,
8876 );
8877 shaded += (ix1 - ix0) as usize;
8878 }
8879 for pos_x_primary in x0..ix0 {
8880 let dist: f32 = ((pos_x_primary as f32) + 0.5 - cx).abs() - half_w;
8881 let cov: f32 = sdf_coverage(dist, aa);
8882 if cov > 0.0 {
8883 let rgba: [u8; 4] = sample_bilinear_fixed(
8884 src_bytes,
8885 y_params,
8886 x_lut_ref[(pos_x_primary - x0) as usize],
8887 );
8888 let off: usize = (pos_x_primary as usize) * 4;
8889 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8890 shaded += 1;
8891 }
8892 }
8893 for pos_x_secondary in ix1..x1 {
8894 let dist: f32 = ((pos_x_secondary as f32) + 0.5 - cx).abs() - half_w;
8895 let cov: f32 = sdf_coverage(dist, aa);
8896 if cov > 0.0 {
8897 let rgba: [u8; 4] = sample_bilinear_fixed(
8898 src_bytes,
8899 y_params,
8900 x_lut_ref[(pos_x_secondary - x0) as usize],
8901 );
8902 let off: usize = (pos_x_secondary as usize) * 4;
8903 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8904 shaded += 1;
8905 }
8906 }
8907 }
8908 for pos_y_primary in iy1..y1 {
8909 let Some(dst_row) = band.row_slice_mut(pos_y_primary) else {
8910 continue;
8911 };
8912 let item_val_primary: f32 =
8913 (((pos_y_primary as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
8914 let fy: f32 = (item_val_primary * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8915 let sy0: usize = (fy.floor() as usize).min(max_sy);
8916 let sy1: usize = (sy0 + 1).min(max_sy);
8917 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8918 let y_params: (usize, usize, u32, u32) =
8919 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8920 let py: f32 = (pos_y_primary as f32) + 0.5 - cy;
8921 let dist_y: f32 = py.abs() - half_h;
8922 let mid_cov: f32 = sdf_coverage(dist_y, aa);
8923 if cx0 < cx1 && mid_cov > 0.0 {
8924 let lut_s: usize = (cx0 - x0) as usize;
8925 let lut_e: usize = (cx1 - x0) as usize;
8926 if mid_cov >= 0.9995 {
8927 let _: usize = Self::blit_bilinear_span_precomputed(
8928 y_params,
8929 cx0 as usize,
8930 &x_lut_ref[lut_s..lut_e],
8931 src_bytes,
8932 dst_row,
8933 );
8934 } else {
8935 for pos_x_next in cx0..cx1 {
8936 let rgba: [u8; 4] = sample_bilinear_fixed(
8937 src_bytes,
8938 y_params,
8939 x_lut_ref[(pos_x_next - x0) as usize],
8940 );
8941 let off: usize = (pos_x_next as usize) * 4;
8942 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
8943 }
8944 }
8945 shaded += (cx1 - cx0) as usize;
8946 }
8947 for pos_x_alt in x0..cx0 {
8948 let px: f32 = (pos_x_alt as f32) + 0.5 - cx;
8949 let cr: f32 = quadrant_corner_radius(radius, px, py);
8950 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
8951 if cov > 0.0 {
8952 let rgba: [u8; 4] = sample_bilinear_fixed(
8953 src_bytes,
8954 y_params,
8955 x_lut_ref[(pos_x_alt - x0) as usize],
8956 );
8957 let off: usize = (pos_x_alt as usize) * 4;
8958 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8959 shaded += 1;
8960 }
8961 }
8962 for pos_x_inner in cx1..x1 {
8963 let px: f32 = (pos_x_inner as f32) + 0.5 - cx;
8964 let cr: f32 = quadrant_corner_radius(radius, px, py);
8965 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
8966 if cov > 0.0 {
8967 let rgba: [u8; 4] = sample_bilinear_fixed(
8968 src_bytes,
8969 y_params,
8970 x_lut_ref[(pos_x_inner - x0) as usize],
8971 );
8972 let off: usize = (pos_x_inner as usize) * 4;
8973 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8974 shaded += 1;
8975 }
8976 }
8977 }
8978 shaded
8979 }
8980
8981 fn raster_rgba_bytes(
8996 band: &mut PixelBand<'_>,
8997 rect: Rect,
8998 source: (u32, u32, &[u8]),
8999 radius: CornerRadius,
9000 clip: Rect,
9001 aa: AntialiasingMode,
9002 ) -> usize {
9003 let (src_w, src_h, src_bytes): (u32, u32, &[u8]) = source;
9004 if src_w == 0 || src_h == 0 {
9005 return 0;
9006 }
9007 let Some(vis) = rect.intersect(clip) else {
9008 return 0;
9009 };
9010 let fb_w: u32 = band.width();
9011 let band_y0: u32 = band.y_offset();
9012 let band_y1: u32 = band.y_end();
9013 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9014 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9015 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9016 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9017 if x0 >= x1 || y0 >= y1 {
9018 return 0;
9019 }
9020 let half_w: f32 = rect.get_width() * 0.5;
9021 let half_h: f32 = rect.get_height() * 0.5;
9022 let cx: f32 = rect.get_x() + half_w;
9023 let cy: f32 = rect.get_y() + half_h;
9024 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
9025 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
9026 let use_bilinear: bool = aa != AntialiasingMode::None
9027 && ((rect.get_width() - (src_w as f32)).abs() > 0.5
9028 || (rect.get_height() - (src_h as f32)).abs() > 0.5);
9029 let has_radius: bool = radius.max_radius() > 0.0;
9030 let max_sx: usize = (src_w as usize).saturating_sub(1);
9031 let max_sy: usize = (src_h as usize).saturating_sub(1);
9032 let src_w_usize: usize = src_w as usize;
9033 let is_exact_1to1: bool = !use_bilinear
9034 && (rect.get_width() - (src_w as f32)).abs() <= 0.01
9035 && (rect.get_height() - (src_h as f32)).abs() <= 0.01
9036 && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
9037 && (rect.get_y() - rect.get_y().round()).abs() <= 0.01;
9038 let rx0_i: i32 = rect.get_x().round() as i32;
9039 let ry0_i: i32 = rect.get_y().round() as i32;
9040 if is_exact_1to1
9041 && !has_radius
9042 && (x0 as i32) >= rx0_i
9043 && (x1 as i32) <= rx0_i + (src_w as i32)
9044 && (y0 as i32) >= ry0_i
9045 && (y1 as i32) <= ry0_i + (src_h as i32)
9046 {
9047 let span_w: usize = (x1 - x0) as usize;
9048 let src_x_off: usize = ((x0 as i32) - rx0_i) as usize;
9049 let dst_byte0: usize = (x0 as usize) * 4;
9050 let dst_byte1: usize = (x1 as usize) * 4;
9051 for pos_y in y0..y1 {
9052 let Some(dst_row) = band.row_slice_mut(pos_y) else {
9053 continue;
9054 };
9055 let sy: usize = ((pos_y as i32) - ry0_i) as usize;
9056 let src_byte0: usize = (sy * src_w_usize + src_x_off) * 4;
9057 let src_byte1: usize = src_byte0 + span_w * 4;
9058 if src_byte1 <= src_bytes.len() && dst_byte1 <= dst_row.len() {
9059 blit_1to1_rgba_span(
9060 &src_bytes[src_byte0..src_byte1],
9061 &mut dst_row[dst_byte0..dst_byte1],
9062 );
9063 }
9064 }
9065 return span_w * ((y1 - y0) as usize);
9066 }
9067 if use_bilinear {
9068 let mut shaded: usize = 0;
9069 let ran_tls: bool = BAND_IMAGE_X_LUT
9070 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
9071 if let Ok(mut guard) = cell.try_borrow_mut() {
9072 shaded = Self::raster_image_bilinear_with_lut(
9073 band,
9074 rect,
9075 (src_w, src_h, src_bytes),
9076 (x0, y0, x1, y1),
9077 radius,
9078 aa,
9079 &mut guard,
9080 );
9081 }
9082 })
9083 .is_ok();
9084 if !ran_tls {
9085 let mut fallback_lut: Vec<(usize, usize, u32)> =
9086 Vec::with_capacity((x1 - x0) as usize);
9087 shaded = Self::raster_image_bilinear_with_lut(
9088 band,
9089 rect,
9090 (src_w, src_h, src_bytes),
9091 (x0, y0, x1, y1),
9092 radius,
9093 aa,
9094 &mut fallback_lut,
9095 );
9096 }
9097 return shaded;
9098 }
9099 if !has_radius && (src_h as usize) * src_w_usize * 4 <= src_bytes.len() {
9100 let x0_u: usize = x0 as usize;
9101 let span_w: usize = (x1 - x0) as usize;
9102 let dst_b0: usize = x0_u * 4;
9103 let dst_b1: usize = (x1 as usize) * 4;
9104 let src_w_f: f32 = src_w as f32;
9105 let src_h_f: f32 = src_h as f32;
9106 let mut sx_arr_ok: bool = false;
9107 let _ran_tls_nn: bool = BAND_IMAGE_X_LUT
9108 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
9109 if let Ok(mut lut) = cell.try_borrow_mut() {
9110 lut.clear();
9111 for pos_x in x0..x1 {
9112 let tex_u: f32 =
9113 (((pos_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9114 let sx: usize = ((tex_u * src_w_f).floor() as usize).min(max_sx);
9115 lut.push((sx, 0, 0));
9116 }
9117 let lut_ref: &[(usize, usize, u32)] = lut.as_slice();
9118 let row_bytes_len: usize = src_w_usize * 4;
9119 let mut cached_sy: usize = usize::MAX;
9120 let mut cached_opaque: bool = false;
9121 for coord_y in y0..y1 {
9122 let Some(dst_row) = band.row_slice_mut(coord_y) else {
9123 continue;
9124 };
9125 if dst_b1 > dst_row.len() {
9126 continue;
9127 }
9128 let item_val: f32 = (((coord_y as f32) + 0.5 - rect.get_y())
9129 * inv_dst_h)
9130 .clamp(0.0, 1.0);
9131 let sy: usize = ((item_val * src_h_f).floor() as usize).min(max_sy);
9132 let r_off: usize = sy * row_bytes_len;
9133 let row_slice: &[u8] = &src_bytes[r_off..(r_off + row_bytes_len)];
9134 let is_op: bool = if sy == cached_sy {
9135 cached_opaque
9136 } else {
9137 cached_sy = sy;
9138 cached_opaque = is_rgba_slice_opaque(row_slice);
9139 cached_opaque
9140 };
9141 let src_px: &[[u8; 4]] = row_slice.as_chunks::<4>().0;
9142 let dst_px: &mut [[u8; 4]] =
9143 dst_row[dst_b0..dst_b1].as_chunks_mut::<4>().0;
9144 if is_op {
9145 let sptr: *const [u8; 4] = src_px.as_ptr();
9146 for (dp, &(sx, _, _)) in dst_px.iter_mut().zip(lut_ref.iter()) {
9147 *dp = unsafe { *sptr.add(sx) };
9149 }
9150 } else {
9151 for (dp, &(sx, _, _)) in dst_px.iter_mut().zip(lut_ref.iter()) {
9152 blend_rgba_pixel_with_cov(dp, src_px[sx], 1.0);
9153 }
9154 }
9155 }
9156 sx_arr_ok = true;
9157 }
9158 })
9159 .is_ok();
9160 if sx_arr_ok {
9161 return span_w * ((y1 - y0) as usize);
9162 }
9163 }
9164 let mut shaded: usize = 0;
9165 let r_max: f32 = if has_radius {
9166 radius.max_radius().min(half_w).min(half_h).max(0.0)
9167 } else {
9168 0.0
9169 };
9170 let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
9171 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
9172 let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
9173 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
9174 let can_1to1_interior: bool = is_exact_1to1
9175 && (ix0 as i32) >= rx0_i
9176 && (ix1 as i32) <= rx0_i + (src_w as i32)
9177 && (iy0 as i32) >= ry0_i
9178 && (iy1 as i32) <= ry0_i + (src_h as i32);
9179 for sample_y in y0..y1 {
9180 let Some(dst_row) = band.row_slice_mut(sample_y) else {
9181 continue;
9182 };
9183 let tex_v: f32 = (((sample_y as f32) + 0.5 - rect.get_y()) * inv_dst_h).clamp(0.0, 1.0);
9184 let py: f32 = (sample_y as f32) + 0.5 - cy;
9185 let sy: usize = ((tex_v * (src_h as f32)).floor() as usize).min(max_sy);
9186 let row: usize = sy * src_w_usize;
9187 if has_radius && can_1to1_interior && sample_y >= iy0 && sample_y < iy1 && ix0 < ix1 {
9188 let src_off: usize = (row + (((ix0 as i32) - rx0_i) as usize)) * 4;
9189 let span_bytes: usize = ((ix1 - ix0) as usize) * 4;
9190 let dst_off: usize = (ix0 as usize) * 4;
9191 if src_off + span_bytes <= src_bytes.len() && dst_off + span_bytes <= dst_row.len()
9192 {
9193 blit_1to1_rgba_span(
9194 &src_bytes[src_off..src_off + span_bytes],
9195 &mut dst_row[dst_off..dst_off + span_bytes],
9196 );
9197 }
9198 shaded += (ix1 - ix0) as usize;
9199 for coord_x in x0..ix0 {
9200 let dist: f32 = ((coord_x as f32) + 0.5 - cx).abs() - half_w;
9201 let cov: f32 = sdf_coverage(dist, aa);
9202 if cov > 0.0 {
9203 let bary_u: f32 =
9204 (((coord_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9205 let sx: usize = ((bary_u * (src_w as f32)).floor() as usize).min(max_sx);
9206 let idx: usize = (row + sx) * 4;
9207 if idx + 4 <= src_bytes.len() {
9208 let off: usize = (coord_x as usize) * 4;
9209 blend_rgba_pixel_with_cov(
9210 &mut dst_row[off..off + 4],
9211 [
9212 src_bytes[idx],
9213 src_bytes[idx + 1],
9214 src_bytes[idx + 2],
9215 src_bytes[idx + 3],
9216 ],
9217 cov,
9218 );
9219 shaded += 1;
9220 }
9221 }
9222 }
9223 for sample_x in ix1..x1 {
9224 let dist: f32 = ((sample_x as f32) + 0.5 - cx).abs() - half_w;
9225 let cov: f32 = sdf_coverage(dist, aa);
9226 if cov > 0.0 {
9227 let unit_u: f32 =
9228 (((sample_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9229 let sx: usize = ((unit_u * (src_w as f32)).floor() as usize).min(max_sx);
9230 let idx: usize = (row + sx) * 4;
9231 if idx + 4 <= src_bytes.len() {
9232 let off: usize = (sample_x as usize) * 4;
9233 blend_rgba_pixel_with_cov(
9234 &mut dst_row[off..off + 4],
9235 [
9236 src_bytes[idx],
9237 src_bytes[idx + 1],
9238 src_bytes[idx + 2],
9239 src_bytes[idx + 3],
9240 ],
9241 cov,
9242 );
9243 shaded += 1;
9244 }
9245 }
9246 }
9247 continue;
9248 }
9249 for value_x in x0..x1 {
9250 let cov: f32 = if has_radius {
9251 let px: f32 = (value_x as f32) + 0.5 - cx;
9252 let cr: f32 = quadrant_corner_radius(radius, px, py);
9253 sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
9254 } else {
9255 1.0
9256 };
9257 if cov <= 0.0 {
9258 continue;
9259 }
9260 let upper_val: f32 =
9261 (((value_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9262 let sx: usize = ((upper_val * (src_w as f32)).floor() as usize).min(max_sx);
9263 let idx: usize = (row + sx) * 4;
9264 if idx + 4 <= src_bytes.len() {
9265 let off: usize = (value_x as usize) * 4;
9266 blend_rgba_pixel_with_cov(
9267 &mut dst_row[off..off + 4],
9268 [
9269 src_bytes[idx],
9270 src_bytes[idx + 1],
9271 src_bytes[idx + 2],
9272 src_bytes[idx + 3],
9273 ],
9274 cov,
9275 );
9276 shaded += 1;
9277 }
9278 }
9279 }
9280 shaded
9281 }
9282
9283 fn raster_line(
9299 band: &mut PixelBand<'_>,
9300 from: Point,
9301 to: Point,
9302 color: Color,
9303 width: f32,
9304 clip: Rect,
9305 aa: AntialiasingMode,
9306 ) -> usize {
9307 if color.get_alpha() == 0 {
9308 return 0;
9309 }
9310 let half_w: f32 = width * 0.5;
9311 let min_x: f32 = from.get_x().min(to.get_x()) - half_w - 1.0;
9312 let min_y: f32 = from.get_y().min(to.get_y()) - half_w - 1.0;
9313 let max_x: f32 = from.get_x().max(to.get_x()) + half_w + 1.0;
9314 let max_y: f32 = from.get_y().max(to.get_y()) + half_w + 1.0;
9315 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
9316 else {
9317 return 0;
9318 };
9319 let fb_w: u32 = band.width();
9320 let band_y0: u32 = band.y_offset();
9321 let band_y1: u32 = band.y_end();
9322 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9323 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9324 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9325 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9326 if x0 >= x1 || y0 >= y1 {
9327 return 0;
9328 }
9329 let fx0: f32 = from.get_x();
9330 let fy0: f32 = from.get_y();
9331 let dx: f32 = to.get_x() - fx0;
9332 let dy: f32 = to.get_y() - fy0;
9333 let len_sq: f32 = (dx * dx + dy * dy).max(1e-6);
9334 let inv_len_sq: f32 = 1.0 / len_sq;
9335 let outer_r: f32 = half_w + 0.9;
9336 let outer_r_sq: f32 = outer_r * outer_r;
9337 let inner_r: f32 = (half_w - 0.9).max(0.0);
9338 let inner_r_sq: f32 = inner_r * inner_r;
9339 let has_inner: bool = half_w > 0.9;
9340 let use_oriented_x: bool = dy.abs() > 1e-4;
9341 let slope_x_per_y: f32 = if use_oriented_x { dx / dy } else { 0.0 };
9342 let x_pad: f32 = if use_oriented_x {
9343 outer_r * (len_sq.sqrt() / dy.abs()) + 0.5
9344 } else {
9345 0.0
9346 };
9347 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
9348 let lin_rgb: [f32; 3] = [
9349 SRGB_TO_LIN_LUT[color.get_red() as usize],
9350 SRGB_TO_LIN_LUT[color.get_green() as usize],
9351 SRGB_TO_LIN_LUT[color.get_blue() as usize],
9352 ];
9353 let mut shaded: usize = 0;
9354 for pos_y in y0..y1 {
9355 let py: f32 = (pos_y as f32) + 0.5;
9356 let py_off: f32 = py - fy0;
9357 let (row_x0, row_x1): (u32, u32) = if use_oriented_x {
9358 let x_center: f32 = fx0 + py_off * slope_x_per_y;
9359 let rx0: u32 = ((x_center - x_pad).floor().max(0.0) as u32).clamp(x0, x1);
9360 let rx1: u32 = ((x_center + x_pad).ceil().max(0.0) as u32).clamp(rx0, x1);
9361 (rx0, rx1)
9362 } else {
9363 (x0, x1)
9364 };
9365 if row_x0 >= row_x1 {
9366 continue;
9367 }
9368 let Some(row) = band.row_slice_mut(pos_y) else {
9369 continue;
9370 };
9371 let py_dy: f32 = py_off * dy;
9372 for pos_x in row_x0..row_x1 {
9373 let px: f32 = (pos_x as f32) + 0.5;
9374 let blend_factor: f32 = (((px - fx0) * dx + py_dy) * inv_len_sq).clamp(0.0, 1.0);
9375 let dpx: f32 = px - (fx0 + blend_factor * dx);
9376 let dpy: f32 = py - (fy0 + blend_factor * dy);
9377 let dist_sq: f32 = dpx * dpx + dpy * dpy;
9378 if dist_sq >= outer_r_sq {
9379 continue;
9380 }
9381 let cov: f32 = if has_inner && dist_sq <= inner_r_sq {
9382 1.0
9383 } else {
9384 sdf_coverage(dist_sq.sqrt() - half_w, aa)
9385 };
9386 if cov > 0.0 {
9387 blend_row_pixel_f32_precomputed(row, pos_x, color, lin_rgb, base_alpha * cov);
9388 shaded += 1;
9389 }
9390 }
9391 }
9392 shaded
9393 }
9394
9395 fn raster_circle(
9410 band: &mut PixelBand<'_>,
9411 center: Point,
9412 radius: f32,
9413 color: Color,
9414 clip: Rect,
9415 aa: AntialiasingMode,
9416 ) -> usize {
9417 if radius <= 0.0 || color.get_alpha() == 0 {
9418 return 0;
9419 }
9420 let bounds: Rect = Rect::new(
9421 center.get_x() - radius - 1.0,
9422 center.get_y() - radius - 1.0,
9423 (radius + 1.0) * 2.0,
9424 (radius + 1.0) * 2.0,
9425 );
9426 let Some(vis) = bounds.intersect(clip) else {
9427 return 0;
9428 };
9429 let fb_w: u32 = band.width();
9430 let band_y0: u32 = band.y_offset();
9431 let band_y1: u32 = band.y_end();
9432 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9433 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9434 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9435 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9436 if x0 >= x1 || y0 >= y1 {
9437 return 0;
9438 }
9439 let outer_r: f32 = if aa == AntialiasingMode::None {
9440 radius + 0.5
9441 } else {
9442 radius + 0.65
9443 };
9444 let inner_r: f32 = if aa == AntialiasingMode::None {
9445 (radius - 0.5).max(0.0)
9446 } else {
9447 (radius - 0.65).max(0.0)
9448 };
9449 let outer_r2: f32 = outer_r * outer_r;
9450 let inner_r2: f32 = inner_r * inner_r;
9451 let r2: f32 = radius * radius;
9452 let cx: f32 = center.get_x();
9453 let cy: f32 = center.get_y();
9454 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
9455 let lin_rgb: [f32; 3] = [
9456 SRGB_TO_LIN_LUT[color.get_red() as usize],
9457 SRGB_TO_LIN_LUT[color.get_green() as usize],
9458 SRGB_TO_LIN_LUT[color.get_blue() as usize],
9459 ];
9460 let interior_luts: Option<[[u8; 256]; 4]> = if color.get_alpha() < 255 && radius >= 12.0 {
9461 Some(build_linear_blend_luts(color))
9462 } else {
9463 None
9464 };
9465 let mut shaded: usize = 0;
9466 for pos_y in y0..y1 {
9467 let dy: f32 = (pos_y as f32) + 0.5 - cy;
9468 let dy2: f32 = dy * dy;
9469 if dy2 >= outer_r2 {
9470 continue;
9471 }
9472 let out_dx: f32 = (outer_r2 - dy2).sqrt();
9473 let row_x0: u32 = ((cx - out_dx).floor().max(0.0) as u32).clamp(x0, x1);
9474 let row_x1: u32 = ((cx + out_dx).ceil().max(0.0) as u32).clamp(row_x0, x1);
9475 if row_x0 >= row_x1 {
9476 continue;
9477 }
9478 if dy2 < inner_r2 && inner_r > 0.65 {
9479 let in_dx: f32 = (inner_r2 - dy2).sqrt();
9480 let in_x0: u32 = ((cx - in_dx).ceil().max(0.0) as u32).clamp(row_x0, row_x1);
9481 let in_x1: u32 = ((cx + in_dx).floor().max(0.0) as u32).clamp(in_x0, row_x1);
9482 if in_x0 < in_x1 {
9483 if let Some(ref luts) = interior_luts {
9484 band.fill_span_linear_luts(in_x0, in_x1, pos_y, luts);
9485 } else {
9486 band.fill_span_linear(in_x0, in_x1, pos_y, color);
9487 }
9488 shaded += (in_x1 - in_x0) as usize;
9489 }
9490 if (row_x0 < in_x0 || in_x1 < row_x1)
9491 && let Some(row) = band.row_slice_mut(pos_y)
9492 {
9493 for pos_x in row_x0..in_x0 {
9494 let dx: f32 = (pos_x as f32) + 0.5 - cx;
9495 let cov: f32 = if aa == AntialiasingMode::None {
9496 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9497 } else {
9498 circle_supersampled_coverage(dx, dy, radius)
9499 };
9500 if cov > 0.0 {
9501 blend_row_pixel_f32_precomputed(
9502 row,
9503 pos_x,
9504 color,
9505 lin_rgb,
9506 base_alpha * cov,
9507 );
9508 shaded += 1;
9509 }
9510 }
9511 for coord_x in in_x1..row_x1 {
9512 let dx: f32 = (coord_x as f32) + 0.5 - cx;
9513 let cov: f32 = if aa == AntialiasingMode::None {
9514 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9515 } else {
9516 circle_supersampled_coverage(dx, dy, radius)
9517 };
9518 if cov > 0.0 {
9519 blend_row_pixel_f32_precomputed(
9520 row,
9521 coord_x,
9522 color,
9523 lin_rgb,
9524 base_alpha * cov,
9525 );
9526 shaded += 1;
9527 }
9528 }
9529 }
9530 } else if let Some(row) = band.row_slice_mut(pos_y) {
9531 for sample_x in row_x0..row_x1 {
9532 let dx: f32 = (sample_x as f32) + 0.5 - cx;
9533 let cov: f32 = if aa == AntialiasingMode::None {
9534 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9535 } else {
9536 circle_supersampled_coverage(dx, dy, radius)
9537 };
9538 if cov > 0.0 {
9539 blend_row_pixel_f32_precomputed(
9540 row,
9541 sample_x,
9542 color,
9543 lin_rgb,
9544 base_alpha * cov,
9545 );
9546 shaded += 1;
9547 }
9548 }
9549 }
9550 }
9551 shaded
9552 }
9553
9554 #[inline(always)]
9567 #[must_use]
9568 fn solve_triangle_scanline_interval(
9569 d_base: [f32; 3],
9570 a_step: [f32; 3],
9571 thresh: f32,
9572 max_s: f32,
9573 ) -> (f32, f32) {
9574 let mut s_min: f32 = 0.0;
9575 let mut s_max: f32 = max_s;
9576 for idx in 0..3usize {
9577 let alpha_val: f32 = a_step[idx];
9578 let delta_val: f32 = d_base[idx];
9579 if alpha_val > 1e-6 {
9580 let bound: f32 = (thresh - delta_val) / alpha_val;
9581 if bound > s_min {
9582 s_min = bound;
9583 }
9584 } else if alpha_val < -1e-6 {
9585 let bound: f32 = (thresh - delta_val) / alpha_val;
9586 if bound < s_max {
9587 s_max = bound;
9588 }
9589 } else if delta_val < thresh {
9590 return (1.0, 0.0);
9591 }
9592 }
9593 (s_min, s_max)
9594 }
9595
9596 fn raster_triangle(
9612 band: &mut PixelBand<'_>,
9613 p0: Point,
9614 p1: Point,
9615 p2: Point,
9616 color: Color,
9617 clip: Rect,
9618 aa: AntialiasingMode,
9619 ) -> usize {
9620 if color.get_alpha() == 0 {
9621 return 0;
9622 }
9623 let dx0: f32 = p1.get_x() - p0.get_x();
9624 let dy0: f32 = p1.get_y() - p0.get_y();
9625 let dx1: f32 = p2.get_x() - p1.get_x();
9626 let dy1: f32 = p2.get_y() - p1.get_y();
9627 let dx2: f32 = p0.get_x() - p2.get_x();
9628 let dy2: f32 = p0.get_y() - p2.get_y();
9629 let area: f32 = dx0 * (p2.get_y() - p0.get_y()) - dy0 * (p2.get_x() - p0.get_x());
9630 if area.abs() < 1e-5 {
9631 return 0;
9632 }
9633 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) - 1.0;
9634 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) - 1.0;
9635 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) + 1.0;
9636 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) + 1.0;
9637 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
9638 else {
9639 return 0;
9640 };
9641 let fb_w: u32 = band.width();
9642 let band_y0: u32 = band.y_offset();
9643 let band_y1: u32 = band.y_end();
9644 let clip_x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9645 let clip_x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9646 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9647 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9648 if clip_x0 >= clip_x1 || y0 >= y1 {
9649 return 0;
9650 }
9651 if aa == AntialiasingMode::None {
9652 let edges: [(Point, Point); 3] = [(p0, p1), (p1, p2), (p2, p0)];
9653 let mut shaded: usize = 0;
9654 for pos_y in y0..y1 {
9655 let py: f32 = (pos_y as f32) + 0.5;
9656 let mut min_ix: f32 = f32::INFINITY;
9657 let mut max_ix: f32 = f32::NEG_INFINITY;
9658 for (alpha_val, blue_val) in edges.iter() {
9659 let ay: f32 = alpha_val.get_y();
9660 let by: f32 = blue_val.get_y();
9661 if (ay <= py && by > py) || (by <= py && ay > py) {
9662 let blend_factor: f32 = (py - ay) / (by - ay);
9663 let ix: f32 = alpha_val.get_x()
9664 + blend_factor * (blue_val.get_x() - alpha_val.get_x());
9665 min_ix = min_ix.min(ix);
9666 max_ix = max_ix.max(ix);
9667 }
9668 }
9669 if min_ix <= max_ix {
9670 let sx0: u32 = (min_ix.floor().max(0.0) as u32).clamp(clip_x0, clip_x1);
9671 let sx1: u32 = (max_ix.ceil().max(0.0) as u32).clamp(clip_x0, clip_x1);
9672 if sx0 < sx1 {
9673 band.fill_span_linear(sx0, sx1, pos_y, color);
9674 shaded += (sx1 - sx0) as usize;
9675 }
9676 }
9677 }
9678 return shaded;
9679 }
9680 let sign: f32 = if area > 0.0 { 1.0 } else { -1.0 };
9681 let inv_l0: f32 = sign / dx0.hypot(dy0).max(1e-5);
9682 let inv_l1: f32 = sign / dx1.hypot(dy1).max(1e-5);
9683 let inv_l2: f32 = sign / dx2.hypot(dy2).max(1e-5);
9684 let a_step: [f32; 3] = [-dy0 * inv_l0, -dy1 * inv_l1, -dy2 * inv_l2];
9685 let b_step: [f32; 3] = [dx0 * inv_l0, dx1 * inv_l1, dx2 * inv_l2];
9686 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
9687 let lin_rgb: [f32; 3] = [
9688 SRGB_TO_LIN_LUT[color.get_red() as usize],
9689 SRGB_TO_LIN_LUT[color.get_green() as usize],
9690 SRGB_TO_LIN_LUT[color.get_blue() as usize],
9691 ];
9692 let interior_luts: Option<[[u8; 256]; 4]> =
9693 if color.get_alpha() < 255 && (area.abs() * 0.5) >= 256.0 {
9694 Some(build_linear_blend_luts(color))
9695 } else {
9696 None
9697 };
9698 let px_base: f32 = (clip_x0 as f32) + 0.5;
9699 let max_s: f32 = (clip_x1 - clip_x0) as f32;
9700 let py_start: f32 = (y0 as f32) + 0.5;
9701 let mut d_row: [f32; 3] = [
9702 (dx0 * (py_start - p0.get_y()) - dy0 * (px_base - p0.get_x())) * inv_l0,
9703 (dx1 * (py_start - p1.get_y()) - dy1 * (px_base - p1.get_x())) * inv_l1,
9704 (dx2 * (py_start - p2.get_y()) - dy2 * (px_base - p2.get_x())) * inv_l2,
9705 ];
9706 let edge_deltas: [(f32, f32); 3] = [(dx0, dy0), (dx1, dy1), (dx2, dy2)];
9707 let verts: (Point, Point, Point) = (p0, p1, p2);
9708 let mut shaded: usize = 0;
9709 for coord_y in y0..y1 {
9710 let py: f32 = (coord_y as f32) + 0.5;
9711 let (out_min, out_max): (f32, f32) =
9712 Self::solve_triangle_scanline_interval(d_row, a_step, -0.86, max_s);
9713 if out_min <= out_max {
9714 let k_out0: u32 = out_min.floor().max(0.0) as u32;
9715 let k_out1: u32 = (out_max.ceil().max(0.0) as u32).saturating_add(1);
9716 let row_x0: u32 = clip_x0.saturating_add(k_out0).clamp(clip_x0, clip_x1);
9717 let row_x1: u32 = clip_x0.saturating_add(k_out1).clamp(row_x0, clip_x1);
9718 if row_x0 < row_x1 {
9719 let (in_min, in_max): (f32, f32) =
9720 Self::solve_triangle_scanline_interval(d_row, a_step, 0.86, max_s);
9721 let (in_x0, in_x1): (u32, u32) = if in_min <= in_max && in_max >= 0.0 {
9722 let k_in0: u32 = in_min.ceil().max(0.0) as u32;
9723 let k_in1: u32 = (in_max.floor().max(0.0) as u32).saturating_add(1);
9724 let ix0: u32 = clip_x0.saturating_add(k_in0).clamp(row_x0, row_x1);
9725 let ix1: u32 = clip_x0.saturating_add(k_in1).clamp(ix0, row_x1);
9726 (ix0, ix1)
9727 } else {
9728 (row_x1, row_x1)
9729 };
9730 if in_x0 < in_x1 {
9731 if let Some(ref luts) = interior_luts {
9732 band.fill_span_linear_luts(in_x0, in_x1, coord_y, luts);
9733 } else {
9734 band.fill_span_linear(in_x0, in_x1, coord_y, color);
9735 }
9736 shaded += (in_x1 - in_x0) as usize;
9737 }
9738 if (row_x0 < in_x0 || in_x1 < row_x1)
9739 && let Some(row) = band.row_slice_mut(coord_y)
9740 {
9741 let mut rim_spans: [(u32, u32); 2] = [(row_x0, in_x0), (in_x1, row_x1)];
9742 if in_x0 >= in_x1 {
9743 rim_spans = [(row_x0, row_x1), (row_x1, row_x1)];
9744 }
9745 for (sx0, sx1) in rim_spans.into_iter() {
9746 if sx0 >= sx1 {
9747 continue;
9748 }
9749 let s0: f32 = (sx0 - clip_x0) as f32;
9750 let mut d0: f32 = d_row[0] + a_step[0] * s0;
9751 let mut d1: f32 = d_row[1] + a_step[1] * s0;
9752 let mut d2: f32 = d_row[2] + a_step[2] * s0;
9753 for pos_x in sx0..sx1 {
9754 if d0 >= -0.85 && d1 >= -0.85 && d2 >= -0.85 {
9755 if d0 > 0.85 && d1 > 0.85 && d2 > 0.85 {
9756 blend_row_pixel_linear_precomputed(
9757 row, pos_x, color, lin_rgb,
9758 );
9759 shaded += 1;
9760 } else {
9761 let px: f32 = (pos_x as f32) + 0.5;
9762 let cov: f32 = triangle_supersampled_coverage_precomputed(
9763 (px, py),
9764 verts,
9765 edge_deltas,
9766 sign,
9767 );
9768 if cov >= 0.999 {
9769 blend_row_pixel_linear_precomputed(
9770 row, pos_x, color, lin_rgb,
9771 );
9772 shaded += 1;
9773 } else if cov > 0.0 {
9774 blend_row_pixel_f32_precomputed(
9775 row,
9776 pos_x,
9777 color,
9778 lin_rgb,
9779 base_alpha * cov,
9780 );
9781 shaded += 1;
9782 }
9783 }
9784 }
9785 d0 += a_step[0];
9786 d1 += a_step[1];
9787 d2 += a_step[2];
9788 }
9789 }
9790 }
9791 }
9792 }
9793 d_row[0] += b_step[0];
9794 d_row[1] += b_step[1];
9795 d_row[2] += b_step[2];
9796 }
9797 shaded
9798 }
9799
9800 #[inline(always)]
9815 fn blit_sprite_span_tinted(
9816 y_params: (usize, usize, u32, u32),
9817 dst_x0: usize,
9818 x_lut: &[(usize, usize, u32)],
9819 src_bytes: &[u8],
9820 dst_row: &mut [u8],
9821 tint: Color,
9822 ) -> usize {
9823 let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
9824 let span_bytes_start: usize = dst_x0 * 4;
9825 let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
9826 if span_bytes_end > dst_row.len() {
9827 return 0;
9828 }
9829 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
9830 .as_chunks_mut::<4>()
9831 .0;
9832 let src_len: usize = src_bytes.len();
9833 let transform_val: u32 = tint.get_red() as u32;
9834 let tg: u32 = tint.get_green() as u32;
9835 let tb: u32 = tint.get_blue() as u32;
9836 let ta: u32 = tint.get_alpha() as u32;
9837 let mut shaded: usize = 0;
9838 if wy == 0 {
9839 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
9840 let i0: usize = (row0 + sx0) * 4;
9841 let i1: usize = (row0 + sx1) * 4;
9842 if i1 + 4 > src_len {
9843 continue;
9844 }
9845 let iwx: u32 = 256 - wx;
9846 let a0: u32 = src_bytes[i0 + 3] as u32;
9847 let a1: u32 = src_bytes[i1 + 3] as u32;
9848 let (sr_raw, sg_raw, sb_raw, sa_raw): (u32, u32, u32, u32) = if (a0 & a1) == 255 {
9849 (
9850 ((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128) >> 8,
9851 ((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128)
9852 >> 8,
9853 ((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128)
9854 >> 8,
9855 255,
9856 )
9857 } else {
9858 let aw0: u32 = a0 * iwx;
9859 let aw1: u32 = a1 * wx;
9860 let a_sum: u32 = aw0 + aw1;
9861 let a_out: u32 = (a_sum + 128) >> 8;
9862 if a_out == 0 || a_sum == 0 {
9863 continue;
9864 }
9865 let half_a: u32 = a_sum >> 1;
9866 (
9867 (((src_bytes[i0] as u32) * aw0 + (src_bytes[i1] as u32) * aw1 + half_a)
9868 / a_sum)
9869 .min(255),
9870 (((src_bytes[i0 + 1] as u32) * aw0
9871 + (src_bytes[i1 + 1] as u32) * aw1
9872 + half_a)
9873 / a_sum)
9874 .min(255),
9875 (((src_bytes[i0 + 2] as u32) * aw0
9876 + (src_bytes[i1 + 2] as u32) * aw1
9877 + half_a)
9878 / a_sum)
9879 .min(255),
9880 a_out,
9881 )
9882 };
9883 let rr: u32 = sr_raw * transform_val + 128;
9884 let gg: u32 = sg_raw * tg + 128;
9885 let bb: u32 = sb_raw * tb + 128;
9886 let aa_v: u32 = sa_raw * ta + 128;
9887 let red_val: u32 = (rr + (rr >> 8)) >> 8;
9888 let green_val: u32 = (gg + (gg >> 8)) >> 8;
9889 let blue_val: u32 = (bb + (bb >> 8)) >> 8;
9890 let alpha_val: u32 = (aa_v + (aa_v >> 8)) >> 8;
9891 if alpha_val == 255 {
9892 dp[0] = red_val as u8;
9893 dp[1] = green_val as u8;
9894 dp[2] = blue_val as u8;
9895 dp[3] = 255;
9896 } else if alpha_val > 0 {
9897 let inv_a: u32 = 255 - alpha_val;
9898 let vr: u32 = red_val * alpha_val + (dp[0] as u32) * inv_a + 128;
9899 let vg: u32 = green_val * alpha_val + (dp[1] as u32) * inv_a + 128;
9900 let vb: u32 = blue_val * alpha_val + (dp[2] as u32) * inv_a + 128;
9901 let va: u32 = (dp[3] as u32) * inv_a + 128;
9902 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
9903 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
9904 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
9905 dp[3] = (alpha_val + ((va + (va >> 8)) >> 8)).min(255) as u8;
9906 }
9907 shaded += 1;
9908 }
9909 return shaded;
9910 }
9911 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
9912 let i00: usize = (row0 + sx0) * 4;
9913 let i10: usize = (row0 + sx1) * 4;
9914 let i01: usize = (row1 + sx0) * 4;
9915 let i11: usize = (row1 + sx1) * 4;
9916 if i11 + 4 > src_len {
9917 continue;
9918 }
9919 let iwx: u32 = 256 - wx;
9920 let w00: u32 = iwx * iwy;
9921 let w10: u32 = wx * iwy;
9922 let w01: u32 = iwx * wy;
9923 let w11: u32 = wx * wy;
9924 let a00: u32 = src_bytes[i00 + 3] as u32;
9925 let a10: u32 = src_bytes[i10 + 3] as u32;
9926 let a01: u32 = src_bytes[i01 + 3] as u32;
9927 let a11: u32 = src_bytes[i11 + 3] as u32;
9928 let (sr_raw, sg_raw, sb_raw, sa_raw): (u32, u32, u32, u32) =
9929 if (a00 & a10 & a01 & a11) == 255 {
9930 (
9931 ((src_bytes[i00] as u32) * w00
9932 + (src_bytes[i10] as u32) * w10
9933 + (src_bytes[i01] as u32) * w01
9934 + (src_bytes[i11] as u32) * w11
9935 + 32768)
9936 >> 16,
9937 ((src_bytes[i00 + 1] as u32) * w00
9938 + (src_bytes[i10 + 1] as u32) * w10
9939 + (src_bytes[i01 + 1] as u32) * w01
9940 + (src_bytes[i11 + 1] as u32) * w11
9941 + 32768)
9942 >> 16,
9943 ((src_bytes[i00 + 2] as u32) * w00
9944 + (src_bytes[i10 + 2] as u32) * w10
9945 + (src_bytes[i01 + 2] as u32) * w01
9946 + (src_bytes[i11 + 2] as u32) * w11
9947 + 32768)
9948 >> 16,
9949 255,
9950 )
9951 } else {
9952 let aw00: u64 = (a00 as u64) * (w00 as u64);
9953 let aw10: u64 = (a10 as u64) * (w10 as u64);
9954 let aw01: u64 = (a01 as u64) * (w01 as u64);
9955 let aw11: u64 = (a11 as u64) * (w11 as u64);
9956 let a_sum: u64 = aw00 + aw10 + aw01 + aw11;
9957 let a_out: u32 = ((a_sum + 32768) >> 16) as u32;
9958 if a_out == 0 || a_sum == 0 {
9959 continue;
9960 }
9961 let half_a: u64 = a_sum >> 1;
9962 (
9963 ((((src_bytes[i00] as u64) * aw00
9964 + (src_bytes[i10] as u64) * aw10
9965 + (src_bytes[i01] as u64) * aw01
9966 + (src_bytes[i11] as u64) * aw11
9967 + half_a)
9968 / a_sum)
9969 .min(255)) as u32,
9970 ((((src_bytes[i00 + 1] as u64) * aw00
9971 + (src_bytes[i10 + 1] as u64) * aw10
9972 + (src_bytes[i01 + 1] as u64) * aw01
9973 + (src_bytes[i11 + 1] as u64) * aw11
9974 + half_a)
9975 / a_sum)
9976 .min(255)) as u32,
9977 ((((src_bytes[i00 + 2] as u64) * aw00
9978 + (src_bytes[i10 + 2] as u64) * aw10
9979 + (src_bytes[i01 + 2] as u64) * aw01
9980 + (src_bytes[i11 + 2] as u64) * aw11
9981 + half_a)
9982 / a_sum)
9983 .min(255)) as u32,
9984 a_out,
9985 )
9986 };
9987 let rr: u32 = sr_raw * transform_val + 128;
9988 let gg: u32 = sg_raw * tg + 128;
9989 let bb: u32 = sb_raw * tb + 128;
9990 let aa_v: u32 = sa_raw * ta + 128;
9991 let radius_val: u32 = (rr + (rr >> 8)) >> 8;
9992 let geometry_val: u32 = (gg + (gg >> 8)) >> 8;
9993 let byte_val: u32 = (bb + (bb >> 8)) >> 8;
9994 let first_val: u32 = (aa_v + (aa_v >> 8)) >> 8;
9995 if first_val == 255 {
9996 dp[0] = radius_val as u8;
9997 dp[1] = geometry_val as u8;
9998 dp[2] = byte_val as u8;
9999 dp[3] = 255;
10000 } else if first_val > 0 {
10001 let inv_a: u32 = 255 - first_val;
10002 let vr: u32 = radius_val * first_val + (dp[0] as u32) * inv_a + 128;
10003 let vg: u32 = geometry_val * first_val + (dp[1] as u32) * inv_a + 128;
10004 let vb: u32 = byte_val * first_val + (dp[2] as u32) * inv_a + 128;
10005 let va: u32 = (dp[3] as u32) * inv_a + 128;
10006 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
10007 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
10008 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
10009 dp[3] = (first_val + ((va + (va >> 8)) >> 8)).min(255) as u8;
10010 }
10011 shaded += 1;
10012 }
10013 shaded
10014 }
10015
10016 fn raster_sprite_region_with_lut(
10032 band: &mut PixelBand<'_>,
10033 rects: (Rect, Rect),
10034 src_info: (u32, u32, &[u8]),
10035 bounds: (u32, u32, u32, u32),
10036 tint: Color,
10037 use_bilinear: bool,
10038 x_lut: &mut Vec<(usize, usize, u32)>,
10039 ) -> usize {
10040 let (rect, src_rect): (Rect, Rect) = rects;
10041 let (buf_w, buf_h, src_bytes): (u32, u32, &[u8]) = src_info;
10042 let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
10043 let inv_w: f32 = 1.0 / rect.get_width().max(1.0);
10044 let inv_h: f32 = 1.0 / rect.get_height().max(1.0);
10045 let untinted: bool = tint == COLOR_WHITE;
10046 let max_sx: u32 = ((src_rect.right().ceil() as u32).saturating_sub(1)).min(buf_w - 1);
10047 let max_sy: u32 = ((src_rect.bottom().ceil() as u32).saturating_sub(1)).min(buf_h - 1);
10048 let min_sx: u32 = (src_rect.get_x().floor().max(0.0) as u32).min(max_sx);
10049 let min_sy: u32 = (src_rect.get_y().floor().max(0.0) as u32).min(max_sy);
10050 let buf_w_usize: usize = buf_w as usize;
10051 let rect_x: f32 = rect.get_x();
10052 let rect_y: f32 = rect.get_y();
10053 let src_x: f32 = src_rect.get_x();
10054 let src_y: f32 = src_rect.get_y();
10055 let src_w: f32 = src_rect.get_width();
10056 let src_h: f32 = src_rect.get_height();
10057 let min_sx_f: f32 = min_sx as f32;
10058 let max_sx_f: f32 = max_sx as f32;
10059 let min_sy_f: f32 = min_sy as f32;
10060 let max_sy_f: f32 = max_sy as f32;
10061 x_lut.clear();
10062 for pos_x in x0..x1 {
10063 let tex_u: f32 = (((pos_x as f32) + 0.5 - rect_x) * inv_w).clamp(0.0, 1.0);
10064 let fx: f32 = (src_x + tex_u * src_w - 0.5).clamp(min_sx_f, max_sx_f);
10065 let sx0: u32 = (fx.floor() as u32).clamp(min_sx, max_sx);
10066 let sx1: u32 = if use_bilinear {
10067 (sx0 + 1).min(max_sx)
10068 } else {
10069 sx0
10070 };
10071 let wx: u32 = if use_bilinear {
10072 ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
10073 } else {
10074 0
10075 };
10076 x_lut.push((sx0 as usize, sx1 as usize, wx));
10077 }
10078 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
10079 let x0_u: usize = x0 as usize;
10080 let mut shaded: usize = 0;
10081 for pos_y in y0..y1 {
10082 let Some(dst_row) = band.row_slice_mut(pos_y) else {
10083 continue;
10084 };
10085 let item_val: f32 = (((pos_y as f32) + 0.5 - rect_y) * inv_h).clamp(0.0, 1.0);
10086 let fy: f32 = (src_y + item_val * src_h - 0.5).clamp(min_sy_f, max_sy_f);
10087 let sy0: u32 = (fy.floor() as u32).clamp(min_sy, max_sy);
10088 let sy1: u32 = if use_bilinear {
10089 (sy0 + 1).min(max_sy)
10090 } else {
10091 sy0
10092 };
10093 let wy: u32 = if use_bilinear {
10094 ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
10095 } else {
10096 0
10097 };
10098 let y_params: (usize, usize, u32, u32) = (
10099 (sy0 as usize) * buf_w_usize,
10100 (sy1 as usize) * buf_w_usize,
10101 wy,
10102 256 - wy,
10103 );
10104 if untinted {
10105 shaded += Self::blit_bilinear_span_precomputed(
10106 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
10107 );
10108 } else {
10109 shaded += Self::blit_sprite_span_tinted(
10110 y_params, x0_u, x_lut_ref, src_bytes, dst_row, tint,
10111 );
10112 }
10113 }
10114 shaded
10115 }
10116
10117 fn raster_sprite_region(
10133 band: &mut PixelBand<'_>,
10134 rect: Rect,
10135 buffer: &ImageBuffer,
10136 src_rect: Rect,
10137 tint: Color,
10138 clip: Rect,
10139 aa: AntialiasingMode,
10140 ) -> usize {
10141 if buffer.get_width() == 0
10142 || buffer.get_height() == 0
10143 || tint.get_alpha() == 0
10144 || src_rect.get_width() <= 0.0
10145 || src_rect.get_height() <= 0.0
10146 {
10147 return 0;
10148 }
10149 let Some(vis) = rect.intersect(clip) else {
10150 return 0;
10151 };
10152 let fb_w: u32 = band.width();
10153 let band_y0: u32 = band.y_offset();
10154 let band_y1: u32 = band.y_end();
10155 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
10156 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
10157 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
10158 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
10159 if x0 >= x1 || y0 >= y1 {
10160 return 0;
10161 }
10162 let buf_w: u32 = buffer.get_width();
10163 let buf_h: u32 = buffer.get_height();
10164 let src_bytes: &[u8] = buffer.get_pixels();
10165 let use_bilinear: bool = aa != AntialiasingMode::None
10166 && ((rect.get_width() - src_rect.get_width()).abs() > 0.5
10167 || (rect.get_height() - src_rect.get_height()).abs() > 0.5);
10168 if !use_bilinear
10169 && tint == COLOR_WHITE
10170 && (rect.get_width() - src_rect.get_width()).abs() <= 0.01
10171 && (rect.get_height() - src_rect.get_height()).abs() <= 0.01
10172 && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
10173 && (rect.get_y() - rect.get_y().round()).abs() <= 0.01
10174 && (src_rect.get_x() - src_rect.get_x().round()).abs() <= 0.01
10175 && (src_rect.get_y() - src_rect.get_y().round()).abs() <= 0.01
10176 {
10177 let rx0_i: i32 = rect.get_x().round() as i32;
10178 let ry0_i: i32 = rect.get_y().round() as i32;
10179 let sx0_i: i32 = src_rect.get_x().round() as i32;
10180 let sy0_i: i32 = src_rect.get_y().round() as i32;
10181 let span_w: usize = (x1 - x0) as usize;
10182 let src_x0_i: i32 = sx0_i + ((x0 as i32) - rx0_i);
10183 let src_y0_i: i32 = sy0_i + ((y0 as i32) - ry0_i);
10184 let src_y1_i: i32 = sy0_i + ((y1 as i32) - ry0_i);
10185 if src_x0_i >= 0
10186 && src_x0_i + (span_w as i32) <= (buf_w as i32)
10187 && src_y0_i >= 0
10188 && src_y1_i <= (buf_h as i32)
10189 {
10190 let buf_w_u: usize = buf_w as usize;
10191 let dst_b0: usize = (x0 as usize) * 4;
10192 let dst_b1: usize = (x1 as usize) * 4;
10193 let src_x0_u: usize = src_x0_i as usize;
10194 for pos_y in y0..y1 {
10195 let Some(dst_row) = band.row_slice_mut(pos_y) else {
10196 continue;
10197 };
10198 let sy: usize = (sy0_i + ((pos_y as i32) - ry0_i)) as usize;
10199 let src_b0: usize = (sy * buf_w_u + src_x0_u) * 4;
10200 let src_b1: usize = src_b0 + span_w * 4;
10201 if src_b1 <= src_bytes.len() && dst_b1 <= dst_row.len() {
10202 blit_1to1_rgba_span(
10203 &src_bytes[src_b0..src_b1],
10204 &mut dst_row[dst_b0..dst_b1],
10205 );
10206 }
10207 }
10208 return span_w * ((y1 - y0) as usize);
10209 }
10210 }
10211 let mut shaded: usize = 0;
10212 let ran_tls: bool = BAND_IMAGE_X_LUT
10213 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
10214 if let Ok(mut guard) = cell.try_borrow_mut() {
10215 shaded = Self::raster_sprite_region_with_lut(
10216 band,
10217 (rect, src_rect),
10218 (buf_w, buf_h, src_bytes),
10219 (x0, y0, x1, y1),
10220 tint,
10221 use_bilinear,
10222 &mut guard,
10223 );
10224 }
10225 })
10226 .is_ok();
10227 if !ran_tls {
10228 let mut fallback_lut: Vec<(usize, usize, u32)> = Vec::with_capacity((x1 - x0) as usize);
10229 shaded = Self::raster_sprite_region_with_lut(
10230 band,
10231 (rect, src_rect),
10232 (buf_w, buf_h, src_bytes),
10233 (x0, y0, x1, y1),
10234 tint,
10235 use_bilinear,
10236 &mut fallback_lut,
10237 );
10238 }
10239 shaded
10240 }
10241}