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 sx0: u32 = x0.saturating_sub(rad);
2530 let sx1: u32 = x1.saturating_add(rad).min(fb_w);
2531 let sy0: u32 = y0.saturating_sub(rad);
2532 let sy1: u32 = y1.saturating_add(rad).min(fb_h);
2533 let stroke_width: u32 = sx1.saturating_sub(sx0);
2534 let sh: u32 = sy1.saturating_sub(sy0);
2535 let needed: usize = (stroke_width as usize).saturating_mul(sh as usize);
2536 if needed == 0 {
2537 return 0;
2538 }
2539 if blur_horiz_scratch.len() < needed {
2540 blur_horiz_scratch.resize(needed, [0, 0, 0, 0]);
2541 }
2542 let fb_pixels: &mut [u8] = framebuffer.get_mut_pixels().as_mut_slice();
2543 let desc: BlurPassDesc = BlurPassDesc {
2544 #[cfg(not(target_arch = "wasm32"))]
2545 fb_ptr: fb_pixels.as_mut_ptr() as usize,
2546 #[cfg(not(target_arch = "wasm32"))]
2547 fb_len: fb_pixels.len(),
2548 fb_w,
2549 #[cfg(not(target_arch = "wasm32"))]
2550 horiz_ptr: blur_horiz_scratch.as_mut_ptr() as usize,
2551 #[cfg(not(target_arch = "wasm32"))]
2552 horiz_len: needed,
2553 sx0,
2554 sy0,
2555 sw: stroke_width,
2556 sh,
2557 x0,
2558 x1,
2559 y0,
2560 y1,
2561 rad,
2562 inv_win_q24: blur_inv_window_q24(rad),
2563 has_radius: phys_radius.max_radius() > 0.25,
2564 rect: phys_rect,
2565 radius: phys_radius,
2566 #[cfg(not(target_arch = "wasm32"))]
2567 strip_count: 1,
2568 #[cfg(not(target_arch = "wasm32"))]
2569 strip_rows: 1,
2570 };
2571 #[cfg(not(target_arch = "wasm32"))]
2572 {
2573 let blur_h: u32 = y1.saturating_sub(y0);
2574 let blur_area: usize =
2575 ((x1.saturating_sub(x0)) as usize).saturating_mul(blur_h as usize);
2576 if allow_parallel
2577 && blur_area >= BLUR_PARALLEL_MIN_PIXELS
2578 && blur_h >= BLUR_PARALLEL_MIN_HEIGHT
2579 && let Some(pool) = try_get_ready_band_worker_pool()
2580 {
2581 let desired_threads: usize =
2582 (blur_area / BLUR_PARALLEL_MIN_PIXELS).clamp(1, pool.total_threads());
2583 if desired_threads > 1 {
2584 let mut pass_desc: BlurPassDesc = desc;
2585 let h_strips: usize = desired_threads
2586 .saturating_mul(2)
2587 .min((sh / 8).max(1) as usize)
2588 .max(1);
2589 if h_strips > 1 {
2590 pass_desc.strip_count = h_strips;
2591 pass_desc.strip_rows = sh.div_ceil(h_strips as u32).max(1);
2592 let _: usize = pool.execute_blur_pass(
2593 BandJobKind::BlurHoriz,
2594 pass_desc,
2595 desired_threads.saturating_sub(1),
2596 );
2597 } else {
2598 blur_horiz_strip(&pass_desc, 0, sh as usize);
2599 }
2600 let v_strips: usize = desired_threads
2601 .saturating_mul(2)
2602 .min((blur_h / 8).max(1) as usize)
2603 .max(1);
2604 if v_strips > 1 {
2605 pass_desc.strip_count = v_strips;
2606 pass_desc.strip_rows = blur_h.div_ceil(v_strips as u32).max(1);
2607 *parallel_dispatches = parallel_dispatches.wrapping_add(1);
2608 return pool.execute_blur_pass(
2609 BandJobKind::BlurVert,
2610 pass_desc,
2611 desired_threads.saturating_sub(1),
2612 );
2613 }
2614 *serial_dispatches = serial_dispatches.wrapping_add(1);
2615 return blur_vert_strip(&pass_desc, y0, y1);
2616 }
2617 }
2618 }
2619 #[cfg(target_arch = "wasm32")]
2620 {
2621 let _: bool = allow_parallel;
2622 let _: &mut u64 = parallel_dispatches;
2623 }
2624 *serial_dispatches = serial_dispatches.wrapping_add(1);
2625 let horiz_slice: &mut [[u8; 4]] = &mut blur_horiz_scratch[..needed];
2626 blur_horiz_strip_slices(fb_pixels, horiz_slice, &desc, (0, sh as usize));
2627 let fb_stride: usize = (fb_w as usize) * 4;
2628 let strip_start: usize = (y0 as usize).saturating_mul(fb_stride);
2629 let strip_end: usize = (y1 as usize).saturating_mul(fb_stride);
2630 let Some(fb_strip) = fb_pixels.get_mut(strip_start..strip_end) else {
2631 return 0;
2632 };
2633 blur_vert_strip_slices(fb_strip, horiz_slice, &desc, (y0, y1))
2634 }
2635
2636 fn execute_prepared_bands(
2650 &mut self,
2651 commands: &[DrawCommand],
2652 root_clip: Rect,
2653 dims: (u32, u32, f32),
2654 restore_opts: (bool, Option<Color>, usize),
2655 ) -> usize {
2656 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
2657 let (restore_base_cache, scrim_color, prepped_start): (bool, Option<Color>, usize) =
2658 restore_opts;
2659 let clip_x0: u32 = (root_clip.get_x().floor().max(0.0) as u32).min(phys_w);
2660 let clip_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
2661 let clip_x1: u32 = (root_clip.right().ceil().max(0.0) as u32).clamp(clip_x0, phys_w);
2662 let clip_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).clamp(clip_y0, phys_h);
2663 let clip_w: u32 = clip_x1.saturating_sub(clip_x0);
2664 let clip_h: u32 = clip_y1.saturating_sub(clip_y0);
2665 if clip_w == 0 || clip_h == 0 {
2666 return 0;
2667 }
2668 let Self {
2669 framebuffer,
2670 glyph_atlas,
2671 blur_horiz_scratch,
2672 base_cache_pixels,
2673 prepped_scratch,
2674 positioned_glyphs_scratch,
2675 caret_rects_scratch,
2676 rounded_clips_scratch,
2677 corner_mask_cache,
2678 antialiasing,
2679 cached_scrim_color,
2680 cached_scrim_luts,
2681 serial_dispatches,
2682 parallel_dispatches,
2683 adaptive_parallel_threshold_pixels,
2684 adaptive_threshold_override,
2685 last_serial_us,
2686 last_parallel_us,
2687 rendered_frames,
2688 telemetry_enabled,
2689 ..
2690 } = self;
2691 let Some(frame_pixels) = framebuffer.as_mut() else {
2692 return 0;
2693 };
2694 let aa: AntialiasingMode = *antialiasing;
2695 let allow_parallel: bool = *rendered_frames > 0;
2696 let record_timing: bool = *telemetry_enabled;
2697 let threshold_override: usize = *adaptive_threshold_override;
2698 let clamped_start: usize = prepped_start.min(prepped_scratch.len());
2699 let prepped_slice: &[PreppedCommand] = &prepped_scratch.as_slice()[clamped_start..];
2700 if prepped_slice.is_empty() && !restore_base_cache {
2701 return 0;
2702 }
2703 let scrim_luts_ref: Option<&[[u8; 256]; 4]> = if let Some(scrim_c) = scrim_color {
2704 if *cached_scrim_color != Some(scrim_c) || cached_scrim_luts.is_none() {
2705 *cached_scrim_color = Some(scrim_c);
2706 *cached_scrim_luts = Some(Box::new(build_linear_blend_luts(scrim_c)));
2707 }
2708 cached_scrim_luts.as_deref()
2709 } else {
2710 None
2711 };
2712 let aux: BandAuxSlices<'_> = BandAuxSlices {
2713 positioned_glyphs: positioned_glyphs_scratch.as_slice(),
2714 caret_rects: caret_rects_scratch.as_slice(),
2715 rounded_clips: rounded_clips_scratch.as_slice(),
2716 corner_masks: corner_mask_cache.entries(),
2717 };
2718 let atlas_ref: &GlyphAtlas = glyph_atlas;
2719 let restore_spec: BandRestoreSpec<'_> = BandRestoreSpec {
2720 base_pixels: if restore_base_cache {
2721 Some(base_cache_pixels.as_slice())
2722 } else {
2723 None
2724 },
2725 x0: clip_x0,
2726 x1: clip_x1,
2727 scrim_luts: scrim_luts_ref,
2728 };
2729 let empty_restore: BandRestoreSpec<'_> = BandRestoreSpec {
2730 base_pixels: None,
2731 x0: clip_x0,
2732 x1: clip_x1,
2733 scrim_luts: None,
2734 };
2735 let mut total_shaded: usize = 0;
2736 let mut chunk_start: usize = 0;
2737 let mut pending_restore: bool = restore_base_cache;
2738 for (pos, item) in prepped_slice.iter().enumerate() {
2739 let cmd_idx: usize = item.get_cmd_index();
2740 if cmd_idx != usize::MAX
2741 && item.get_rounded_clip_len() == 0
2742 && let DrawCommand::BackdropBlur {
2743 rect,
2744 radius,
2745 blur_radius,
2746 } = &commands[cmd_idx]
2747 {
2748 if chunk_start < pos || pending_restore {
2749 let spec: BandRestoreSpec<'_> = if pending_restore {
2750 restore_spec
2751 } else {
2752 empty_restore
2753 };
2754 total_shaded = total_shaded.saturating_add(Self::execute_prepared_slice(
2755 frame_pixels,
2756 (phys_w, clip_x0, clip_y0, clip_x1, clip_y1),
2757 (commands, &prepped_slice[chunk_start..pos]),
2758 aux,
2759 atlas_ref,
2760 (scale, aa, spec, allow_parallel, record_timing),
2761 (
2762 serial_dispatches,
2763 parallel_dispatches,
2764 adaptive_parallel_threshold_pixels,
2765 threshold_override,
2766 last_serial_us,
2767 last_parallel_us,
2768 ),
2769 ));
2770 pending_restore = false;
2771 }
2772 if let Some(blur_clip) = item.get_active_clip().intersect(root_clip) {
2773 total_shaded =
2774 total_shaded.saturating_add(Self::execute_backdrop_blur_separable(
2775 frame_pixels,
2776 blur_horiz_scratch,
2777 *rect,
2778 *radius,
2779 (*blur_radius, scale),
2780 blur_clip,
2781 (allow_parallel, serial_dispatches, parallel_dispatches),
2782 ));
2783 }
2784 chunk_start = pos + 1;
2785 }
2786 }
2787 if chunk_start < prepped_slice.len() || pending_restore {
2788 let spec: BandRestoreSpec<'_> = if pending_restore {
2789 restore_spec
2790 } else {
2791 empty_restore
2792 };
2793 total_shaded = total_shaded.saturating_add(Self::execute_prepared_slice(
2794 frame_pixels,
2795 (phys_w, clip_x0, clip_y0, clip_x1, clip_y1),
2796 (commands, &prepped_slice[chunk_start..]),
2797 aux,
2798 atlas_ref,
2799 (scale, aa, spec, allow_parallel, record_timing),
2800 (
2801 serial_dispatches,
2802 parallel_dispatches,
2803 adaptive_parallel_threshold_pixels,
2804 threshold_override,
2805 last_serial_us,
2806 last_parallel_us,
2807 ),
2808 ));
2809 }
2810 total_shaded
2811 }
2812
2813 fn prepare_frame_range(
2823 &mut self,
2824 display_list: &DisplayList,
2825 range: (usize, usize),
2826 root_clip: Rect,
2827 dims: (u32, u32, f32),
2828 ) {
2829 let (start_idx, end_idx): (usize, usize) = range;
2830 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
2831 let commands: &[DrawCommand] = display_list.get_commands().as_slice();
2832 let clamped_end: usize = end_idx.min(commands.len());
2833 let clamped_start: usize = start_idx.min(clamped_end);
2834 let Self {
2835 glyph_atlas,
2836 font_provider,
2837 measurer,
2838 text_layout_cache,
2839 positioned_glyph_run_cache,
2840 cull_keep_scratch,
2841 cull_compacted_scratch,
2842 cull_sentinels_scratch,
2843 clip_stack,
2844 rounded_clip_stack,
2845 prepped_scratch: prepped,
2846 rounded_clips_scratch: rounded_clips,
2847 positioned_glyphs_scratch: positioned_glyphs,
2848 line_glyphs_scratch: line_scratch,
2849 caret_rects_scratch: caret_rects,
2850 corner_mask_cache,
2851 prepped_bounds,
2852 prepped_fg_bounds,
2853 clip_scope_scratch: clip_scopes,
2854 antialiasing,
2855 culled_occluded_commands,
2856 ..
2857 } = self;
2858 let aa: AntialiasingMode = *antialiasing;
2859 prepped.clear();
2860 prepped.reserve(clamped_end - clamped_start);
2861 *prepped_bounds = None;
2862 *prepped_fg_bounds = None;
2863 rounded_clips.clear();
2864 positioned_glyphs.clear();
2865 caret_rects.clear();
2866 clip_stack.clear();
2867 clip_stack.push(root_clip);
2868 rounded_clip_stack.clear();
2869 rounded_clip_stack.push(None);
2870 let root_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
2871 let root_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
2872 clip_scopes.clear();
2873 clip_scopes.push((root_y0, root_y1, None));
2874 let mut empty_clip_depth: usize = 0;
2875 let mut has_first_cmd: bool = false;
2876 glyph_atlas.evict_if_over_budget();
2877 positioned_glyph_run_cache.sync_atlas_epoch(glyph_atlas);
2878 positioned_glyph_run_cache.begin_frame();
2879 glyph_atlas.set_slots_pinned(true);
2880 text_layout_cache.evict_lru_if_needed();
2881 positioned_glyph_run_cache.evict_lru_if_needed();
2882 if corner_mask_cache.len() > CORNER_MASK_CACHE_LIMIT {
2883 corner_mask_cache.clear();
2884 }
2885 for (offset, cmd) in commands[clamped_start..clamped_end].iter().enumerate() {
2886 if empty_clip_depth > 0 {
2887 match cmd {
2888 DrawCommand::PushClip(_) | DrawCommand::PushRoundedClip { .. } => {
2889 empty_clip_depth += 1;
2890 }
2891 DrawCommand::PopClip => {
2892 empty_clip_depth -= 1;
2893 }
2894 _ => {}
2895 }
2896 continue;
2897 }
2898 let cmd_index: usize = clamped_start + offset;
2899 let active_clip: Rect = clip_stack.last().copied().unwrap_or(root_clip);
2900 match cmd {
2901 DrawCommand::PushClip(rect) => {
2902 let phys: Rect = snap_physical_rect(*rect, scale);
2903 let Some(next) = active_clip.intersect(phys) else {
2904 empty_clip_depth = 1;
2905 continue;
2906 };
2907 let nx0: u32 = (next.get_x().floor().max(0.0) as u32).min(phys_w);
2908 let nx1: u32 = (next.right().ceil().max(0.0) as u32).min(phys_w);
2909 let ny0: u32 = (next.get_y().floor().max(0.0) as u32).min(phys_h);
2910 let ny1: u32 = (next.bottom().ceil().max(0.0) as u32).min(phys_h);
2911 if nx0 >= nx1 || ny0 >= ny1 {
2912 empty_clip_depth = 1;
2913 continue;
2914 }
2915 clip_stack.push(next);
2916 rounded_clip_stack.push(None);
2917 let (parent_y0, parent_y1, _): (u32, u32, Option<usize>) = clip_scopes
2918 .last()
2919 .copied()
2920 .unwrap_or((root_y0, root_y1, None));
2921 if ny0 > parent_y0 || ny1 < parent_y1 {
2922 let slot_idx: usize = prepped.len();
2923 prepped.push(PreppedCommand {
2924 cmd_index: usize::MAX,
2925 active_clip: next,
2926 y0: ny0,
2927 y1: ny1,
2928 opaque_cutout_h: Rect::default(),
2929 opaque_cutout_v: Rect::default(),
2930 glyph_run_start: 0,
2931 glyph_run_len: 0,
2932 caret_rect_idx: u32::MAX,
2933 rounded_clip_start: 0,
2934 rounded_clip_len: 0,
2935 skip_delta: 1,
2936 });
2937 clip_scopes.push((ny0, ny1, Some(slot_idx)));
2938 } else {
2939 clip_scopes.push((parent_y0, parent_y1, None));
2940 }
2941 }
2942 DrawCommand::PushRoundedClip { rect, radius } => {
2943 let phys: Rect = snap_physical_rect(*rect, scale);
2944 let Some(next) = active_clip.intersect(phys) else {
2945 empty_clip_depth = 1;
2946 continue;
2947 };
2948 let nx0: u32 = (next.get_x().floor().max(0.0) as u32).min(phys_w);
2949 let nx1: u32 = (next.right().ceil().max(0.0) as u32).min(phys_w);
2950 let ny0: u32 = (next.get_y().floor().max(0.0) as u32).min(phys_h);
2951 let ny1: u32 = (next.bottom().ceil().max(0.0) as u32).min(phys_h);
2952 if nx0 >= nx1 || ny0 >= ny1 {
2953 empty_clip_depth = 1;
2954 continue;
2955 }
2956 clip_stack.push(next);
2957 let phys_r: CornerRadius = Self::scale_radius(*radius, scale);
2958 if phys.get_width() > 0.0
2959 && phys.get_height() > 0.0
2960 && phys_r.max_radius() > 0.25
2961 {
2962 let corner_mask_ids: [u32; 4] =
2963 corner_mask_cache.resolve_quadrants(phys, phys_r, aa);
2964 rounded_clip_stack.push(Some(RoundedClipMask {
2965 rect: phys,
2966 radius: phys_r,
2967 corner_mask_ids,
2968 }));
2969 } else {
2970 rounded_clip_stack.push(None);
2971 }
2972 let (parent_y0, parent_y1, _): (u32, u32, Option<usize>) = clip_scopes
2973 .last()
2974 .copied()
2975 .unwrap_or((root_y0, root_y1, None));
2976 if ny0 > parent_y0 || ny1 < parent_y1 {
2977 let slot_idx: usize = prepped.len();
2978 prepped.push(PreppedCommand {
2979 cmd_index: usize::MAX,
2980 active_clip: next,
2981 y0: ny0,
2982 y1: ny1,
2983 opaque_cutout_h: Rect::default(),
2984 opaque_cutout_v: Rect::default(),
2985 glyph_run_start: 0,
2986 glyph_run_len: 0,
2987 caret_rect_idx: u32::MAX,
2988 rounded_clip_start: 0,
2989 rounded_clip_len: 0,
2990 skip_delta: 1,
2991 });
2992 clip_scopes.push((ny0, ny1, Some(slot_idx)));
2993 } else {
2994 clip_scopes.push((parent_y0, parent_y1, None));
2995 }
2996 }
2997 DrawCommand::PopClip => {
2998 if clip_stack.len() > 1 {
2999 clip_stack.pop();
3000 let _: Option<Option<RoundedClipMask>> = rounded_clip_stack.pop();
3001 if let Some((_, _, Some(slot_idx))) = clip_scopes.pop() {
3002 let span_len: usize = prepped.len().saturating_sub(slot_idx);
3003 if span_len <= 1 {
3004 prepped.truncate(slot_idx);
3005 } else if span_len == 2 {
3006 let only_cmd: PreppedCommand = prepped[slot_idx + 1];
3007 prepped[slot_idx] = only_cmd;
3008 let _: Option<PreppedCommand> = prepped.pop();
3009 } else {
3010 prepped[slot_idx].skip_delta = span_len as u32;
3011 }
3012 }
3013 }
3014 }
3015 DrawCommand::Clear(clear_color) => {
3016 let y0: u32 = (active_clip.get_y().floor().max(0.0) as u32).min(phys_h);
3017 let y1: u32 = (active_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
3018 if y0 < y1 {
3019 let (mut rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3020 rounded_clip_stack.as_slice(),
3021 rounded_clips,
3022 active_clip,
3023 );
3024 let covers_root: bool = active_clip.get_x() <= root_clip.get_x()
3025 && active_clip.get_y() <= root_clip.get_y()
3026 && active_clip.right() >= root_clip.right()
3027 && active_clip.bottom() >= root_clip.bottom();
3028 let no_open_sentinels: bool = clip_scopes
3029 .iter()
3030 .all(|&(_, _, slot): &(u32, u32, Option<usize>)| slot.is_none());
3031 if clamped_start == 0
3032 && !prepped.is_empty()
3033 && rc_len == 0
3034 && clear_color.get_alpha() == 255
3035 && covers_root
3036 && no_open_sentinels
3037 {
3038 prepped.clear();
3039 rounded_clips.clear();
3040 positioned_glyphs.clear();
3041 caret_rects.clear();
3042 *prepped_bounds = None;
3043 *prepped_fg_bounds = None;
3044 has_first_cmd = false;
3045 rc_start = 0;
3046 }
3047 if has_first_cmd {
3048 expand_opt_rect(prepped_fg_bounds, active_clip);
3049 }
3050 has_first_cmd = true;
3051 expand_opt_rect(prepped_bounds, active_clip);
3052 let (cut_h, cut_v): (Rect, Rect) = if rc_len == 0
3053 && cmd_index + 1 < clamped_end
3054 && clear_color.get_alpha() == 255
3055 {
3056 Self::resolve_opaque_clear_cutout(commands.get(cmd_index + 1), scale)
3057 } else {
3058 (Rect::default(), Rect::default())
3059 };
3060 prepped.push(PreppedCommand {
3061 cmd_index,
3062 active_clip,
3063 y0,
3064 y1,
3065 opaque_cutout_h: cut_h,
3066 opaque_cutout_v: cut_v,
3067 glyph_run_start: 0,
3068 glyph_run_len: 0,
3069 caret_rect_idx: u32::MAX,
3070 rounded_clip_start: rc_start,
3071 rounded_clip_len: rc_len,
3072 skip_delta: 0,
3073 });
3074 }
3075 }
3076 DrawCommand::FillRoundedRect {
3077 rect,
3078 color,
3079 radius,
3080 border,
3081 } => {
3082 let phys: Rect = snap_physical_rect(*rect, scale);
3083 if let Some(vis) = phys.intersect(active_clip) {
3084 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3085 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3086 if y0 < y1 {
3087 let (mut rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3088 rounded_clip_stack.as_slice(),
3089 rounded_clips,
3090 vis,
3091 );
3092 let no_border: bool =
3093 border.get_width() <= 0.0 || border.get_color().get_alpha() == 0;
3094 let covers_root: bool = vis.get_x() <= root_clip.get_x()
3095 && vis.get_y() <= root_clip.get_y()
3096 && vis.right() >= root_clip.right()
3097 && vis.bottom() >= root_clip.bottom();
3098 let no_open_sentinels: bool = clip_scopes
3099 .iter()
3100 .all(|&(_, _, slot): &(u32, u32, Option<usize>)| slot.is_none());
3101 if clamped_start == 0
3102 && !prepped.is_empty()
3103 && rc_len == 0
3104 && color.get_alpha() == 255
3105 && radius.max_radius() <= 0.0
3106 && no_border
3107 && covers_root
3108 && no_open_sentinels
3109 {
3110 prepped.clear();
3111 rounded_clips.clear();
3112 positioned_glyphs.clear();
3113 caret_rects.clear();
3114 *prepped_bounds = None;
3115 *prepped_fg_bounds = None;
3116 has_first_cmd = false;
3117 rc_start = 0;
3118 }
3119 if has_first_cmd {
3120 expand_opt_rect(prepped_fg_bounds, vis);
3121 }
3122 has_first_cmd = true;
3123 expand_opt_rect(prepped_bounds, vis);
3124 prepped.push(PreppedCommand {
3125 cmd_index,
3126 active_clip,
3127 y0,
3128 y1,
3129 opaque_cutout_h: Rect::default(),
3130 opaque_cutout_v: Rect::default(),
3131 glyph_run_start: 0,
3132 glyph_run_len: 0,
3133 caret_rect_idx: u32::MAX,
3134 rounded_clip_start: rc_start,
3135 rounded_clip_len: rc_len,
3136 skip_delta: 0,
3137 });
3138 }
3139 }
3140 }
3141 DrawCommand::LinearGradientRect { rect, .. }
3142 | DrawCommand::BackdropBlur { rect, .. }
3143 | DrawCommand::Image { rect, .. }
3144 | DrawCommand::SharedImage { rect, .. }
3145 | DrawCommand::SpriteRegion { rect, .. }
3146 | DrawCommand::ExternalSurface { rect, .. } => {
3147 let phys: Rect = snap_physical_rect(*rect, scale);
3148 if let Some(vis) = phys.intersect(active_clip) {
3149 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3150 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3151 if y0 < y1 {
3152 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3153 rounded_clip_stack.as_slice(),
3154 rounded_clips,
3155 vis,
3156 );
3157 if has_first_cmd {
3158 expand_opt_rect(prepped_fg_bounds, vis);
3159 }
3160 has_first_cmd = true;
3161 expand_opt_rect(prepped_bounds, vis);
3162 prepped.push(PreppedCommand {
3163 cmd_index,
3164 active_clip,
3165 y0,
3166 y1,
3167 opaque_cutout_h: Rect::default(),
3168 opaque_cutout_v: Rect::default(),
3169 glyph_run_start: 0,
3170 glyph_run_len: 0,
3171 caret_rect_idx: u32::MAX,
3172 rounded_clip_start: rc_start,
3173 rounded_clip_len: rc_len,
3174 skip_delta: 0,
3175 });
3176 }
3177 }
3178 }
3179 DrawCommand::BoxShadow { rect, shadow, .. } => {
3180 if shadow.get_color().get_alpha() == 0 {
3181 continue;
3182 }
3183 let spread: f32 = shadow.get_spread_radius() * scale;
3184 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
3185 let sigma: f32 = (blur * 0.5).max(0.75);
3186 let pad: f32 = (sigma * 3.0).ceil();
3187 let base_rect: Rect = snap_physical_rect(*rect, scale);
3188 let caster_rect: Rect = Rect::new(
3189 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
3190 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
3191 (base_rect.get_width() + spread * 2.0).max(1.0),
3192 (base_rect.get_height() + spread * 2.0).max(1.0),
3193 );
3194 let shadow_rect: Rect = Rect::new(
3195 caster_rect.get_x() - pad,
3196 caster_rect.get_y() - pad,
3197 caster_rect.get_width() + pad * 2.0,
3198 caster_rect.get_height() + pad * 2.0,
3199 );
3200 if let Some(vis) = shadow_rect.intersect(active_clip) {
3201 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3202 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3203 if y0 < y1 {
3204 let (cut_h, cut_v): (Rect, Rect) = Self::resolve_opaque_shadow_cutout(
3205 commands.get(cmd_index + 1),
3206 scale,
3207 );
3208 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3209 rounded_clip_stack.as_slice(),
3210 rounded_clips,
3211 vis,
3212 );
3213 if has_first_cmd {
3214 expand_opt_rect(prepped_fg_bounds, vis);
3215 }
3216 has_first_cmd = true;
3217 expand_opt_rect(prepped_bounds, vis);
3218 prepped.push(PreppedCommand {
3219 cmd_index,
3220 active_clip,
3221 y0,
3222 y1,
3223 opaque_cutout_h: cut_h,
3224 opaque_cutout_v: cut_v,
3225 glyph_run_start: 0,
3226 glyph_run_len: 0,
3227 caret_rect_idx: u32::MAX,
3228 rounded_clip_start: rc_start,
3229 rounded_clip_len: rc_len,
3230 skip_delta: 0,
3231 });
3232 }
3233 }
3234 }
3235 DrawCommand::TextRun { rect, text, style } => {
3236 if text.is_empty() || style.get_color().get_alpha() == 0 {
3237 continue;
3238 }
3239 let phys_rect: Rect = Self::scale_rect(*rect, scale);
3240 let pad: f32 = style.get_font_size() * scale * 0.5;
3241 let expanded: Rect = Rect::new(
3242 phys_rect.get_x() - pad,
3243 phys_rect.get_y() - pad,
3244 phys_rect.get_width() + pad * 2.0,
3245 phys_rect.get_height() + pad * 2.0,
3246 );
3247 let Some(vis) = expanded.intersect(active_clip) else {
3248 continue;
3249 };
3250 let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3251 let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3252 if vis_y0 >= vis_y1 {
3253 continue;
3254 }
3255 let key_hash: u64 = hash_text_layout_key(text, *style);
3256 let width_bits: u32 = rect.get_width().to_bits();
3257 let phys_scale_milli: u32 = (scale * 1000.0).round() as u32;
3258 let base_x_phys: f32 = (rect.get_x() * scale).round();
3259 let base_y_phys: f32 = (rect.get_y() * scale).round();
3260 let (glyph_run_start, glyph_run_len): (u32, u32) = if text.len()
3261 <= POSITIONED_RUN_MAX_TEXT_LEN
3262 {
3263 if let Some((cached_run, cached_glyphs)) = positioned_glyph_run_cache
3264 .lookup(key_hash, width_bits, phys_scale_milli)
3265 {
3266 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3267 Self::emit_cached_glyph_run(
3268 cached_glyphs,
3269 (base_x_phys as i32, base_y_phys as i32),
3270 (active_clip, phys_w, phys_h),
3271 positioned_glyphs,
3272 )
3273 } else {
3274 let max_w: f32 = rect.get_width().max(1.0);
3275 if let Some((line_str, line_h)) =
3276 measurer.try_single_line(text, *style, Some(max_w))
3277 {
3278 Self::resolve_single_line_glyphs(
3279 (line_str, line_h),
3280 *rect,
3281 *style,
3282 (active_clip, phys_w, phys_h, scale),
3283 (glyph_atlas, font_provider),
3284 positioned_glyphs,
3285 line_scratch,
3286 )
3287 } else {
3288 let width_key: u32 =
3289 ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3290 let layout_idx: u32 = text_layout_cache.get_or_insert_with(
3291 key_hash,
3292 width_key,
3293 || measurer.measure(text, *style, Some(max_w)),
3294 );
3295 if let Some(layout) = text_layout_cache.get(layout_idx) {
3296 Self::resolve_text_run_glyphs(
3297 layout,
3298 *rect,
3299 *style,
3300 (active_clip, phys_w, phys_h, scale),
3301 (glyph_atlas, font_provider),
3302 positioned_glyphs,
3303 line_scratch,
3304 )
3305 } else {
3306 (0, 0)
3307 }
3308 }
3309 }
3310 } else {
3311 let max_w: f32 = rect.get_width().max(1.0);
3312 if let Some((line_str, line_h)) =
3313 measurer.try_single_line(text, *style, Some(max_w))
3314 {
3315 if style.get_align() == TextAlign::Left
3316 && line_str.is_ascii()
3317 && base_x_phys >= 0.0
3318 {
3319 let run_start: u32 = positioned_glyphs.len() as u32;
3320 let clip_x0_i: i32 = active_clip.get_x().ceil().max(0.0) as i32;
3321 let clip_y0_i: i32 = (active_clip.get_y().ceil().max(0.0)
3322 as i32)
3323 .min(phys_h as i32);
3324 let clip_x1_i: i32 = (active_clip.right().floor().max(0.0)
3325 as i32)
3326 .min(phys_w as i32);
3327 let clip_y1_i: i32 = (active_clip.bottom().floor().max(0.0)
3328 as i32)
3329 .min(phys_h as i32);
3330 let bx_i: i32 = base_x_phys as i32;
3331 let by_i: i32 = base_y_phys as i32;
3332 let phys_font_size: f32 = style.get_font_size() * scale;
3333 let size_tenths: u16 =
3334 (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
3335 let bold: bool = style.get_weight().is_bold();
3336 let monospace: bool =
3337 style.get_family() == FontFamily::Monospace;
3338 let italic: bool = style.get_italic();
3339 let key_meta: (u16, bool, bool, bool) =
3340 (size_tenths, bold, monospace, italic);
3341 let ascii_table_idx: usize = glyph_atlas.ascii_table_index(
3342 size_tenths,
3343 bold,
3344 monospace,
3345 italic,
3346 );
3347 let line_h_phys: f32 = line_h * scale;
3348 let letter_sp: f32 = style.get_letter_spacing() * scale;
3349 let space_step: f32 =
3350 measure_char_advance(' ', *style) * scale + letter_sp;
3351 let clip_ok: bool =
3352 clip_x0_i < clip_x1_i && clip_y0_i < clip_y1_i;
3353 if positioned_glyph_run_cache.is_streaming() {
3354 positioned_glyph_run_cache.record_streaming_miss();
3355 if clip_ok {
3356 let mut pen_x: f32 = 0.0;
3357 for &byte in line_str.as_bytes() {
3358 if byte == b' ' {
3359 pen_x += space_step;
3360 continue;
3361 }
3362 let gx0: i32 = bx_i + (pen_x.round() as i32);
3363 if gx0 >= clip_x1_i {
3364 break;
3365 }
3366 let slot: u32 = glyph_atlas
3367 .get_or_rasterize_ascii_slot_with(
3368 ascii_table_idx,
3369 byte,
3370 key_meta,
3371 font_provider,
3372 );
3373 let glyph: &RasterizedGlyph =
3374 glyph_atlas.glyph_by_slot(slot);
3375 let adv_phys: f32 = (glyph.get_advance() as f32)
3376 .max(1.0)
3377 + letter_sp;
3378 let gw_u32: u32 = glyph.get_width();
3379 let gh_u32: u32 = glyph.get_height();
3380 let gw_u16: u16 =
3381 gw_u32.min(u16::MAX as u32) as u16;
3382 let gh_u16: u16 =
3383 gh_u32.min(u16::MAX as u32) as u16;
3384 if gx0 + (gw_u16 as i32) > clip_x0_i {
3385 let gy0: i32 = by_i
3386 + (((line_h_phys - (gh_u32 as f32)) * 0.5)
3387 .round()
3388 as i32);
3389 if gy0 < clip_y1_i
3390 && gy0 + (gh_u16 as i32) > clip_y0_i
3391 {
3392 positioned_glyphs.push(
3393 PositionedGlyph::new(
3394 slot, gx0, gy0, gw_u16, gh_u16,
3395 ),
3396 );
3397 }
3398 }
3399 pen_x += adv_phys;
3400 }
3401 }
3402 } else {
3403 let (_, _): (CachedPositionedGlyphRun, &[PositionedGlyph]) =
3404 positioned_glyph_run_cache.insert_with(
3405 (key_hash, width_bits, phys_scale_milli),
3406 line_str.len(),
3407 |out_slab: &mut Vec<PositionedGlyph>| {
3408 let mut pen_x: f32 = 0.0;
3409 let mut has_frac: bool = false;
3410 let mut max_slot: u32 = 0;
3411 for &byte in line_str.as_bytes() {
3412 if byte == b' ' {
3413 pen_x += space_step;
3414 continue;
3415 }
3416 let slot: u32 = glyph_atlas
3417 .get_or_rasterize_ascii_slot_with(
3418 ascii_table_idx,
3419 byte,
3420 key_meta,
3421 font_provider,
3422 );
3423 max_slot = max_slot.max(slot);
3424 let glyph: &RasterizedGlyph =
3425 glyph_atlas.glyph_by_slot(slot);
3426 let adv_phys: f32 =
3427 (glyph.get_advance() as f32).max(1.0)
3428 + letter_sp;
3429 let pen_x_round: f32 = pen_x.round();
3430 if (pen_x - pen_x_round).abs() > 1e-4 {
3431 has_frac = true;
3432 }
3433 let gw_u32: u32 = glyph.get_width();
3434 let gh_u32: u32 = glyph.get_height();
3435 let gw_u16: u16 =
3436 gw_u32.min(u16::MAX as u32) as u16;
3437 let gh_u16: u16 =
3438 gh_u32.min(u16::MAX as u32) as u16;
3439 let rx: i32 = pen_x_round as i32;
3440 let ry: i32 =
3441 ((line_h_phys - (gh_u32 as f32)) * 0.5)
3442 .round()
3443 as i32;
3444 out_slab.push(PositionedGlyph::new(
3445 slot, rx, ry, gw_u16, gh_u16,
3446 ));
3447 if clip_ok {
3448 let gx0: i32 = bx_i + rx;
3449 let gy0: i32 = by_i + ry;
3450 if gx0 + (gw_u16 as i32) > clip_x0_i
3451 && gx0 < clip_x1_i
3452 && gy0 < clip_y1_i
3453 && gy0 + (gh_u16 as i32) > clip_y0_i
3454 {
3455 positioned_glyphs.push(
3456 PositionedGlyph::new(
3457 slot, gx0, gy0, gw_u16,
3458 gh_u16,
3459 ),
3460 );
3461 }
3462 }
3463 pen_x += adv_phys;
3464 }
3465 (has_frac, max_slot)
3466 },
3467 );
3468 }
3469 let run_len: u32 =
3470 (positioned_glyphs.len() as u32).saturating_sub(run_start);
3471 (run_start, run_len)
3472 } else {
3473 let (cached_run, cached_glyphs): (
3474 CachedPositionedGlyphRun,
3475 &[PositionedGlyph],
3476 ) = positioned_glyph_run_cache.insert_with(
3477 (key_hash, width_bits, phys_scale_milli),
3478 line_str.len(),
3479 |out_slab: &mut Vec<PositionedGlyph>| {
3480 Self::append_single_line_positioned_glyph_run(
3481 (line_str, line_h),
3482 *rect,
3483 *style,
3484 scale,
3485 (glyph_atlas, font_provider),
3486 line_scratch,
3487 out_slab,
3488 )
3489 },
3490 );
3491 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3492 Self::emit_cached_glyph_run(
3493 cached_glyphs,
3494 (base_x_phys as i32, base_y_phys as i32),
3495 (active_clip, phys_w, phys_h),
3496 positioned_glyphs,
3497 )
3498 } else {
3499 Self::resolve_single_line_glyphs(
3500 (line_str, line_h),
3501 *rect,
3502 *style,
3503 (active_clip, phys_w, phys_h, scale),
3504 (glyph_atlas, font_provider),
3505 positioned_glyphs,
3506 line_scratch,
3507 )
3508 }
3509 }
3510 } else {
3511 let width_key: u32 =
3512 ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3513 let layout_idx: u32 = text_layout_cache.get_or_insert_with(
3514 key_hash,
3515 width_key,
3516 || measurer.measure(text, *style, Some(max_w)),
3517 );
3518 if let Some(layout) = text_layout_cache.get(layout_idx) {
3519 let (cached_run, cached_glyphs): (
3520 CachedPositionedGlyphRun,
3521 &[PositionedGlyph],
3522 ) = positioned_glyph_run_cache.insert_with(
3523 (key_hash, width_bits, phys_scale_milli),
3524 text.len(),
3525 |out_slab: &mut Vec<PositionedGlyph>| {
3526 Self::append_cached_positioned_glyph_run(
3527 layout,
3528 *rect,
3529 *style,
3530 scale,
3531 (glyph_atlas, font_provider),
3532 line_scratch,
3533 out_slab,
3534 )
3535 },
3536 );
3537 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3538 Self::emit_cached_glyph_run(
3539 cached_glyphs,
3540 (base_x_phys as i32, base_y_phys as i32),
3541 (active_clip, phys_w, phys_h),
3542 positioned_glyphs,
3543 )
3544 } else {
3545 Self::resolve_text_run_glyphs(
3546 layout,
3547 *rect,
3548 *style,
3549 (active_clip, phys_w, phys_h, scale),
3550 (glyph_atlas, font_provider),
3551 positioned_glyphs,
3552 line_scratch,
3553 )
3554 }
3555 } else {
3556 (0, 0)
3557 }
3558 }
3559 }
3560 } else {
3561 let max_w: f32 = rect.get_width().max(1.0);
3562 let width_key: u32 = ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3563 let layout_idx: u32 =
3564 text_layout_cache.get_or_insert_with(key_hash, width_key, || {
3565 measurer.measure(text, *style, Some(max_w))
3566 });
3567 if let Some(layout) = text_layout_cache.get(layout_idx) {
3568 Self::resolve_text_run_glyphs(
3569 layout,
3570 *rect,
3571 *style,
3572 (active_clip, phys_w, phys_h, scale),
3573 (glyph_atlas, font_provider),
3574 positioned_glyphs,
3575 line_scratch,
3576 )
3577 } else {
3578 (0, 0)
3579 }
3580 };
3581 if glyph_run_len == 0 {
3582 continue;
3583 }
3584 let clip_x0_i: i32 = active_clip.get_x().ceil().max(0.0) as i32;
3585 let clip_y0_i: i32 =
3586 (active_clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
3587 let clip_x1_i: i32 =
3588 (active_clip.right().floor().max(0.0) as i32).min(phys_w as i32);
3589 let clip_y1_i: i32 =
3590 (active_clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
3591 let mut min_gx: i32 = i32::MAX;
3592 let mut min_gy: i32 = i32::MAX;
3593 let mut max_gx: i32 = i32::MIN;
3594 let mut max_gy: i32 = i32::MIN;
3595 let g_s: usize = glyph_run_start as usize;
3596 let g_e: usize = g_s.saturating_add(glyph_run_len as usize);
3597 for green_val in positioned_glyphs[g_s..g_e].iter() {
3598 let gx0: i32 = green_val.x.max(clip_x0_i);
3599 let gx1: i32 = (green_val.x + green_val.width as i32).min(clip_x1_i);
3600 let gy0: i32 = green_val.y.max(clip_y0_i);
3601 let gy1: i32 = (green_val.y + green_val.height as i32).min(clip_y1_i);
3602 if gx0 < gx1 && gy0 < gy1 {
3603 min_gx = min_gx.min(gx0);
3604 min_gy = min_gy.min(gy0);
3605 max_gx = max_gx.max(gx1);
3606 max_gy = max_gy.max(gy1);
3607 }
3608 }
3609 let (y0, y1, run_vis): (u32, u32, Rect) = if min_gx < max_gx && min_gy < max_gy
3610 {
3611 let ty0: u32 = (min_gy.max(0) as u32).min(phys_h);
3612 let ty1: u32 = (max_gy.max(0) as u32).min(phys_h);
3613 if ty0 >= ty1 {
3614 continue;
3615 }
3616 (
3617 ty0,
3618 ty1,
3619 Rect::new(
3620 min_gx as f32,
3621 min_gy as f32,
3622 (max_gx - min_gx) as f32,
3623 (max_gy - min_gy) as f32,
3624 ),
3625 )
3626 } else {
3627 (vis_y0, vis_y1, vis)
3628 };
3629 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3630 rounded_clip_stack.as_slice(),
3631 rounded_clips,
3632 run_vis,
3633 );
3634 if has_first_cmd {
3635 expand_opt_rect(prepped_fg_bounds, run_vis);
3636 }
3637 has_first_cmd = true;
3638 expand_opt_rect(prepped_bounds, run_vis);
3639 prepped.push(PreppedCommand {
3640 cmd_index,
3641 active_clip,
3642 y0,
3643 y1,
3644 opaque_cutout_h: Rect::default(),
3645 opaque_cutout_v: Rect::default(),
3646 glyph_run_start,
3647 glyph_run_len,
3648 caret_rect_idx: u32::MAX,
3649 rounded_clip_start: rc_start,
3650 rounded_clip_len: rc_len,
3651 skip_delta: 0,
3652 });
3653 }
3654 DrawCommand::TextCaret {
3655 text_rect,
3656 content_rect,
3657 text,
3658 style,
3659 caret_height,
3660 color,
3661 multiline,
3662 } => {
3663 if color.get_alpha() == 0 {
3664 continue;
3665 }
3666 let phys_content: Rect = Self::scale_rect(*content_rect, scale);
3667 let Some(vis) = phys_content.intersect(active_clip) else {
3668 continue;
3669 };
3670 let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3671 let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3672 if vis_y0 >= vis_y1 {
3673 continue;
3674 }
3675 let (max_w, width_key): (Option<f32>, u32) = if *multiline {
3676 let width_val: f32 = content_rect.get_width().max(1.0);
3677 (
3678 Some(width_val),
3679 ((width_val * 10.0).round() as u32).min(u32::MAX - 1),
3680 )
3681 } else {
3682 (None, u32::MAX)
3683 };
3684 let key_hash: u64 = hash_text_layout_key(text, *style);
3685 let layout_idx: u32 =
3686 text_layout_cache.get_or_insert_with(key_hash, width_key, || {
3687 measurer.measure(text, *style, max_w)
3688 });
3689 let caret_rect: Rect = Self::resolve_text_caret_rect(
3690 text_layout_cache.get(layout_idx),
3691 (*text_rect, *content_rect),
3692 *style,
3693 (*caret_height, scale, *multiline),
3694 (glyph_atlas, font_provider),
3695 );
3696 let Some(caret_vis) = caret_rect.intersect(active_clip) else {
3697 continue;
3698 };
3699 let y0: u32 = (caret_vis.get_y().floor().max(0.0) as u32).min(phys_h);
3700 let y1: u32 = (caret_vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3701 if y0 >= y1 {
3702 continue;
3703 }
3704 let caret_rect_idx: u32 = caret_rects.len() as u32;
3705 caret_rects.push(caret_rect);
3706 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3707 rounded_clip_stack.as_slice(),
3708 rounded_clips,
3709 caret_vis,
3710 );
3711 if has_first_cmd {
3712 expand_opt_rect(prepped_fg_bounds, caret_vis);
3713 }
3714 has_first_cmd = true;
3715 expand_opt_rect(prepped_bounds, caret_vis);
3716 prepped.push(PreppedCommand {
3717 cmd_index,
3718 active_clip,
3719 y0,
3720 y1,
3721 opaque_cutout_h: Rect::default(),
3722 opaque_cutout_v: Rect::default(),
3723 glyph_run_start: 0,
3724 glyph_run_len: 0,
3725 caret_rect_idx,
3726 rounded_clip_start: rc_start,
3727 rounded_clip_len: rc_len,
3728 skip_delta: 0,
3729 });
3730 }
3731 DrawCommand::Line {
3732 from, to, width, ..
3733 } => {
3734 let half_w: f32 = (width * scale).max(1.0) * 0.5 + 1.0;
3735 let min_x: f32 = from.get_x().min(to.get_x()) * scale - half_w;
3736 let min_y: f32 = from.get_y().min(to.get_y()) * scale - half_w;
3737 let max_x: f32 = from.get_x().max(to.get_x()) * scale + half_w;
3738 let max_y: f32 = from.get_y().max(to.get_y()) * scale + half_w;
3739 if let Some(vis) =
3740 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
3741 {
3742 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3743 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3744 if y0 < y1 {
3745 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3746 rounded_clip_stack.as_slice(),
3747 rounded_clips,
3748 vis,
3749 );
3750 if has_first_cmd {
3751 expand_opt_rect(prepped_fg_bounds, vis);
3752 }
3753 has_first_cmd = true;
3754 expand_opt_rect(prepped_bounds, vis);
3755 prepped.push(PreppedCommand {
3756 cmd_index,
3757 active_clip,
3758 y0,
3759 y1,
3760 opaque_cutout_h: Rect::default(),
3761 opaque_cutout_v: Rect::default(),
3762 glyph_run_start: 0,
3763 glyph_run_len: 0,
3764 caret_rect_idx: u32::MAX,
3765 rounded_clip_start: rc_start,
3766 rounded_clip_len: rc_len,
3767 skip_delta: 0,
3768 });
3769 }
3770 }
3771 }
3772 DrawCommand::Circle { center, radius, .. } => {
3773 let red_val: f32 = radius * scale + 1.0;
3774 let bounds: Rect = Rect::new(
3775 center.get_x() * scale - red_val,
3776 center.get_y() * scale - red_val,
3777 red_val * 2.0,
3778 red_val * 2.0,
3779 );
3780 if let Some(vis) = bounds.intersect(active_clip) {
3781 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3782 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3783 if y0 < y1 {
3784 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3785 rounded_clip_stack.as_slice(),
3786 rounded_clips,
3787 vis,
3788 );
3789 if has_first_cmd {
3790 expand_opt_rect(prepped_fg_bounds, vis);
3791 }
3792 has_first_cmd = true;
3793 expand_opt_rect(prepped_bounds, vis);
3794 prepped.push(PreppedCommand {
3795 cmd_index,
3796 active_clip,
3797 y0,
3798 y1,
3799 opaque_cutout_h: Rect::default(),
3800 opaque_cutout_v: Rect::default(),
3801 glyph_run_start: 0,
3802 glyph_run_len: 0,
3803 caret_rect_idx: u32::MAX,
3804 rounded_clip_start: rc_start,
3805 rounded_clip_len: rc_len,
3806 skip_delta: 0,
3807 });
3808 }
3809 }
3810 }
3811 DrawCommand::Triangle { p0, p1, p2, .. } => {
3812 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.0;
3813 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.0;
3814 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.0;
3815 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.0;
3816 if let Some(vis) =
3817 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
3818 {
3819 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3820 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3821 if y0 < y1 {
3822 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3823 rounded_clip_stack.as_slice(),
3824 rounded_clips,
3825 vis,
3826 );
3827 if has_first_cmd {
3828 expand_opt_rect(prepped_fg_bounds, vis);
3829 }
3830 has_first_cmd = true;
3831 expand_opt_rect(prepped_bounds, vis);
3832 prepped.push(PreppedCommand {
3833 cmd_index,
3834 active_clip,
3835 y0,
3836 y1,
3837 opaque_cutout_h: Rect::default(),
3838 opaque_cutout_v: Rect::default(),
3839 glyph_run_start: 0,
3840 glyph_run_len: 0,
3841 caret_rect_idx: u32::MAX,
3842 rounded_clip_start: rc_start,
3843 rounded_clip_len: rc_len,
3844 skip_delta: 0,
3845 });
3846 }
3847 }
3848 }
3849 }
3850 }
3851 while let Some((_, _, opt_slot)) = clip_scopes.pop() {
3852 if let Some(slot_idx) = opt_slot {
3853 let span_len: usize = prepped.len().saturating_sub(slot_idx);
3854 if span_len <= 1 {
3855 prepped.truncate(slot_idx);
3856 } else if span_len == 2 {
3857 let only_cmd: PreppedCommand = prepped[slot_idx + 1];
3858 prepped[slot_idx] = only_cmd;
3859 let _: Option<PreppedCommand> = prepped.pop();
3860 } else {
3861 prepped[slot_idx].skip_delta = span_len as u32;
3862 }
3863 }
3864 }
3865 let culled_now: usize = Self::cull_occluded_prepped_commands(
3866 commands,
3867 prepped,
3868 (phys_w, phys_h, scale),
3869 cull_keep_scratch,
3870 cull_compacted_scratch,
3871 cull_sentinels_scratch,
3872 );
3873 *culled_occluded_commands = culled_occluded_commands.saturating_add(culled_now as u64);
3874 glyph_atlas.set_slots_pinned(false);
3875 }
3876
3877 #[must_use]
3889 fn command_cull_bounds(cmd: &DrawCommand, active_clip: Rect, scale: f32) -> Option<Rect> {
3890 let raw: Rect = match cmd {
3891 DrawCommand::Clear(_) => active_clip,
3892 DrawCommand::FillRoundedRect { rect, .. }
3893 | DrawCommand::LinearGradientRect { rect, .. }
3894 | DrawCommand::Image { rect, .. }
3895 | DrawCommand::SharedImage { rect, .. }
3896 | DrawCommand::SpriteRegion { rect, .. }
3897 | DrawCommand::ExternalSurface { rect, .. }
3898 | DrawCommand::BackdropBlur { rect, .. } => snap_physical_rect(*rect, scale),
3899 DrawCommand::BoxShadow { rect, shadow, .. } => {
3900 let spread: f32 = shadow.get_spread_radius() * scale;
3901 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
3902 let sigma: f32 = (blur * 0.5).max(0.75);
3903 let pad: f32 = (sigma * 3.0).ceil();
3904 let base: Rect = snap_physical_rect(*rect, scale);
3905 Rect::new(
3906 base.get_x() + (shadow.get_offset_x() * scale).round() - spread - pad,
3907 base.get_y() + (shadow.get_offset_y() * scale).round() - spread - pad,
3908 (base.get_width() + spread * 2.0).max(1.0) + pad * 2.0,
3909 (base.get_height() + spread * 2.0).max(1.0) + pad * 2.0,
3910 )
3911 }
3912 DrawCommand::TextRun { rect, style, .. } => {
3913 let phys: Rect = Self::scale_rect(*rect, scale);
3914 let pad: f32 = style.get_font_size() * scale * 0.5 + 2.0;
3915 Rect::new(
3916 phys.get_x() - pad,
3917 phys.get_y() - pad,
3918 phys.get_width() + pad * 2.0,
3919 phys.get_height() + pad * 2.0,
3920 )
3921 }
3922 DrawCommand::TextCaret { content_rect, .. } => snap_physical_rect(*content_rect, scale),
3923 DrawCommand::Line {
3924 from, to, width, ..
3925 } => {
3926 let pad: f32 = (width * scale).max(1.0) + 2.0;
3927 let x0: f32 = from.get_x().min(to.get_x()) * scale - pad;
3928 let y0: f32 = from.get_y().min(to.get_y()) * scale - pad;
3929 let x1: f32 = from.get_x().max(to.get_x()) * scale + pad;
3930 let y1: f32 = from.get_y().max(to.get_y()) * scale + pad;
3931 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
3932 }
3933 DrawCommand::Circle { center, radius, .. } => {
3934 let red_val: f32 = radius * scale + 2.0;
3935 Rect::new(
3936 center.get_x() * scale - red_val,
3937 center.get_y() * scale - red_val,
3938 red_val * 2.0,
3939 red_val * 2.0,
3940 )
3941 }
3942 DrawCommand::Triangle { p0, p1, p2, .. } => {
3943 let x0: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 2.0;
3944 let y0: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 2.0;
3945 let x1: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 2.0;
3946 let y1: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 2.0;
3947 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
3948 }
3949 DrawCommand::PushClip(_)
3950 | DrawCommand::PushRoundedClip { .. }
3951 | DrawCommand::PopClip => {
3952 return None;
3953 }
3954 };
3955 raw.intersect(active_clip)
3956 }
3957
3958 #[must_use]
3970 fn opaque_inscribed_rect(cmd: &DrawCommand, item: PreppedCommand, scale: f32) -> Option<Rect> {
3971 if item.get_rounded_clip_len() != 0 {
3972 return None;
3973 }
3974 let (rect, radius): (Rect, CornerRadius) = match cmd {
3975 DrawCommand::FillRoundedRect {
3976 rect,
3977 color,
3978 radius,
3979 border,
3980 } if color.get_alpha() == 255
3981 && (border.get_width() <= 0.0 || border.get_color().get_alpha() == 255) =>
3982 {
3983 (*rect, *radius)
3984 }
3985 DrawCommand::LinearGradientRect {
3986 rect,
3987 gradient,
3988 radius,
3989 } if gradient.get_start_color().get_alpha() == 255
3990 && gradient.get_end_color().get_alpha() == 255 =>
3991 {
3992 (*rect, *radius)
3993 }
3994 _ => return None,
3995 };
3996 let phys: Rect = snap_physical_rect(rect, scale);
3997 let phys_r: CornerRadius = Self::scale_radius(radius, scale);
3998 let max_r: f32 = phys_r
3999 .max_radius()
4000 .min(phys.get_width() * 0.5)
4001 .min(phys.get_height() * 0.5);
4002 let inscribed: Rect = if max_r > 0.0 {
4003 phys.inset(Edges::all(max_r.ceil()))
4004 } else {
4005 phys
4006 };
4007 if inscribed.get_width() < 1.0 || inscribed.get_height() < 1.0 {
4008 return None;
4009 }
4010 let occ: Rect = inscribed.intersect(item.get_active_clip())?;
4011 if occ.get_width() >= 1.0 && occ.get_height() >= 1.0 {
4012 Some(occ)
4013 } else {
4014 None
4015 }
4016 }
4017
4018 fn cull_occluded_prepped_commands(
4033 commands: &[DrawCommand],
4034 prepped: &mut Vec<PreppedCommand>,
4035 dims: (u32, u32, f32),
4036 keep: &mut Vec<bool>,
4037 compacted: &mut Vec<PreppedCommand>,
4038 open_sentinels: &mut Vec<(usize, usize)>,
4039 ) -> usize {
4040 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
4041 let len: usize = prepped.len();
4042 if len < 2 {
4043 return 0;
4044 }
4045 keep.clear();
4046 keep.resize(len, true);
4047 let mut occluders: [Rect; OCCLUSION_MAX_OCCLUDERS] =
4048 [Rect::default(); OCCLUSION_MAX_OCCLUDERS];
4049 let mut occluder_count: usize = 0;
4050 let mut combined_tile_mask: u64 = 0;
4051 let mut culled: usize = 0;
4052 for idx in (0..len).rev() {
4053 let item: PreppedCommand = prepped[idx];
4054 if item.get_cmd_index() == usize::MAX {
4055 continue;
4056 }
4057 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
4058 if matches!(cmd, DrawCommand::BackdropBlur { .. }) {
4059 occluder_count = 0;
4060 combined_tile_mask = 0;
4061 continue;
4062 }
4063 if (occluder_count > 0 || combined_tile_mask != 0)
4064 && let Some(vis) = Self::command_cull_bounds(cmd, item.get_active_clip(), scale)
4065 {
4066 let vis_mask: u64 = occlusion_tile_mask_overlapped(vis, phys_w, phys_h);
4067 let mut covered: bool =
4068 vis_mask != 0 && (vis_mask & combined_tile_mask) == vis_mask;
4069 if !covered {
4070 for occ in occluders.iter().take(occluder_count) {
4071 if vis.get_x() >= occ.get_x()
4072 && vis.get_y() >= occ.get_y()
4073 && vis.right() <= occ.right()
4074 && vis.bottom() <= occ.bottom()
4075 {
4076 covered = true;
4077 break;
4078 }
4079 }
4080 }
4081 if covered {
4082 keep[idx] = false;
4083 culled += 1;
4084 continue;
4085 }
4086 }
4087 if let Some(occ) = Self::opaque_inscribed_rect(cmd, item, scale) {
4088 combined_tile_mask |= occlusion_tile_mask_contained(occ, phys_w, phys_h);
4089 if occluder_count < OCCLUSION_MAX_OCCLUDERS {
4090 occluders[occluder_count] = occ;
4091 occluder_count += 1;
4092 } else {
4093 let occ_area: f32 = occ.get_width() * occ.get_height();
4094 let mut min_i: usize = 0;
4095 let mut min_area: f32 = occluders[0].get_width() * occluders[0].get_height();
4096 for (slot, occ_ref) in occluders
4097 .iter()
4098 .enumerate()
4099 .take(OCCLUSION_MAX_OCCLUDERS)
4100 .skip(1)
4101 {
4102 let area: f32 = occ_ref.get_width() * occ_ref.get_height();
4103 if area < min_area {
4104 min_area = area;
4105 min_i = slot;
4106 }
4107 }
4108 if occ_area > min_area {
4109 occluders[min_i] = occ;
4110 }
4111 }
4112 }
4113 }
4114 if culled == 0 {
4115 return 0;
4116 }
4117 compacted.clear();
4118 compacted.reserve(len.saturating_sub(culled));
4119 open_sentinels.clear();
4120 for (old_idx, &kept) in keep.iter().enumerate() {
4121 while let Some(&(new_s, old_end)) = open_sentinels.last() {
4122 if old_end <= old_idx {
4123 let _: Option<(usize, usize)> = open_sentinels.pop();
4124 let span: u32 = (compacted.len().saturating_sub(new_s)).max(1) as u32;
4125 compacted[new_s].set_skip_delta(span);
4126 } else {
4127 break;
4128 }
4129 }
4130 if kept {
4131 let item: PreppedCommand = prepped[old_idx];
4132 if item.get_cmd_index() == usize::MAX {
4133 let old_end: usize = old_idx.saturating_add(item.get_skip_delta() as usize);
4134 open_sentinels.push((compacted.len(), old_end));
4135 }
4136 compacted.push(item);
4137 }
4138 }
4139 while let Some((new_s, _)) = open_sentinels.pop() {
4140 let span: u32 = (compacted.len().saturating_sub(new_s)).max(1) as u32;
4141 compacted[new_s].set_skip_delta(span);
4142 }
4143 swap(prepped, compacted);
4144 culled
4145 }
4146
4147 fn raster_backdrop_blur(
4161 band: &mut PixelBand<'_>,
4162 rect: Rect,
4163 radius: CornerRadius,
4164 blur_radius: f32,
4165 clip: Rect,
4166 ) -> usize {
4167 let Some(vis) = rect.intersect(clip) else {
4168 return 0;
4169 };
4170 let border_width: u32 = band.width();
4171 let band_y0: u32 = band.y_offset();
4172 let band_y1: u32 = band.y_end();
4173 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(border_width);
4174 let x1: u32 = (vis.right().ceil().max(0.0) as u32).clamp(x0, border_width);
4175 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
4176 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(y0, band_y1);
4177 if x0 >= x1 || y0 >= y1 {
4178 return 0;
4179 }
4180 let rad: u32 = (blur_radius * 0.5).round().clamp(1.0, 24.0) as u32;
4181 let sx0: u32 = x0.saturating_sub(rad);
4182 let sx1: u32 = x1.saturating_add(rad).min(border_width);
4183 let sy0: u32 = y0.saturating_sub(rad).max(band_y0);
4184 let sy1: u32 = y1.saturating_add(rad).min(band_y1);
4185 let stroke_width: u32 = sx1.saturating_sub(sx0);
4186 let sh: u32 = sy1.saturating_sub(sy0);
4187 let needed: usize = (stroke_width as usize).saturating_mul(sh as usize);
4188 if needed == 0 {
4189 return 0;
4190 }
4191 let mut horiz: Vec<[u8; 4]> = BAND_BLUR_HORIZ_SCRATCH
4192 .try_with(|cell: &RefCell<Vec<[u8; 4]>>| {
4193 cell.try_borrow_mut()
4194 .ok()
4195 .map(|mut guard: RefMut<'_, Vec<[u8; 4]>>| take(&mut *guard))
4196 })
4197 .ok()
4198 .flatten()
4199 .unwrap_or_default();
4200 if horiz.len() < needed {
4201 horiz.resize(needed, [0, 0, 0, 0]);
4202 }
4203 let y0_rel: u32 = y0.saturating_sub(band_y0);
4204 let y1_rel: u32 = y1.saturating_sub(band_y0);
4205 let sy0_rel: u32 = sy0.saturating_sub(band_y0);
4206 let shifted_rect: Rect = Rect::new(
4207 rect.get_x(),
4208 rect.get_y() - (band_y0 as f32),
4209 rect.get_width(),
4210 rect.get_height(),
4211 );
4212 let desc: BlurPassDesc = BlurPassDesc {
4213 #[cfg(not(target_arch = "wasm32"))]
4214 fb_ptr: 0,
4215 #[cfg(not(target_arch = "wasm32"))]
4216 fb_len: 0,
4217 fb_w: border_width,
4218 #[cfg(not(target_arch = "wasm32"))]
4219 horiz_ptr: 0,
4220 #[cfg(not(target_arch = "wasm32"))]
4221 horiz_len: needed,
4222 sx0,
4223 sy0: sy0_rel,
4224 sw: stroke_width,
4225 sh,
4226 x0,
4227 x1,
4228 y0: y0_rel,
4229 y1: y1_rel,
4230 rad,
4231 inv_win_q24: blur_inv_window_q24(rad),
4232 has_radius: radius.max_radius() > 0.25,
4233 rect: shifted_rect,
4234 radius,
4235 #[cfg(not(target_arch = "wasm32"))]
4236 strip_count: 1,
4237 #[cfg(not(target_arch = "wasm32"))]
4238 strip_rows: sh.max(1),
4239 };
4240 let horiz_slice: &mut [[u8; 4]] = &mut horiz[..needed];
4241 blur_horiz_strip_slices(band.pixels, horiz_slice, &desc, (0, sh as usize));
4242 let fb_stride: usize = (border_width as usize) * 4;
4243 let strip_start: usize = (y0_rel as usize).saturating_mul(fb_stride);
4244 let strip_end: usize = (y1_rel as usize).saturating_mul(fb_stride);
4245 let shaded: usize = if let Some(fb_strip) = band.pixels.get_mut(strip_start..strip_end) {
4246 blur_vert_strip_slices(fb_strip, horiz_slice, &desc, (y0_rel, y1_rel))
4247 } else {
4248 0
4249 };
4250 let _: bool = BAND_BLUR_HORIZ_SCRATCH
4251 .try_with(|cell: &RefCell<Vec<[u8; 4]>>| {
4252 if let Ok(mut guard) = cell.try_borrow_mut() {
4253 *guard = horiz;
4254 }
4255 })
4256 .is_ok();
4257 shaded
4258 }
4259
4260 #[must_use]
4270 pub fn text_layout_cache_stats(&self) -> (u64, u64, u64, usize) {
4271 self.get_text_layout_cache().stats()
4272 }
4273
4274 fn append_relative_line_glyphs(
4286 line_info: (&str, f32),
4287 metrics: (f32, f32, f32, f32),
4288 font_meta: (TextAlign, usize, (u16, bool, bool, bool)),
4289 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4290 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4291 out_glyphs: &mut Vec<PositionedGlyph>,
4292 state: (&mut bool, &mut u32),
4293 ) {
4294 let (line_str, line_off_y): (&str, f32) = line_info;
4295 let (line_h_phys, box_w_phys, letter_sp, space_step): (f32, f32, f32, f32) = metrics;
4296 let (align, ascii_table_idx, key_meta): (TextAlign, usize, (u16, bool, bool, bool)) =
4297 font_meta;
4298 let (size_tenths, bold, monospace, italic): (u16, bool, bool, bool) = key_meta;
4299 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4300 let (has_fractional_x, max_glyph_slot): (&mut bool, &mut u32) = state;
4301 line_scratch.clear();
4302 let mut line_w_phys: f32 = 0.0;
4303 if line_str.is_ascii() {
4304 for &byte in line_str.as_bytes() {
4305 if byte == b' ' {
4306 line_w_phys += space_step;
4307 line_scratch.push((u32::MAX, space_step, 0, 0));
4308 } else {
4309 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
4310 ascii_table_idx,
4311 byte,
4312 key_meta,
4313 font_provider,
4314 );
4315 *max_glyph_slot = (*max_glyph_slot).max(slot);
4316 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4317 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4318 line_w_phys += adv_phys;
4319 line_scratch.push((
4320 slot,
4321 adv_phys,
4322 glyph.get_width().min(u16::MAX as u32) as u16,
4323 glyph.get_height().min(u16::MAX as u32) as u16,
4324 ));
4325 }
4326 }
4327 } else {
4328 for ch in line_str.chars() {
4329 if ch == ' ' {
4330 line_w_phys += space_step;
4331 line_scratch.push((u32::MAX, space_step, 0, 0));
4332 } else {
4333 let slot: u32 = if ch.is_ascii() {
4334 glyph_atlas.get_or_rasterize_ascii_slot_with(
4335 ascii_table_idx,
4336 ch as u8,
4337 key_meta,
4338 font_provider,
4339 )
4340 } else {
4341 let key: GlyphKey = GlyphKey {
4342 codepoint: ch,
4343 size_tenths,
4344 bold,
4345 monospace,
4346 italic,
4347 };
4348 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4349 };
4350 *max_glyph_slot = (*max_glyph_slot).max(slot);
4351 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4352 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4353 line_w_phys += adv_phys;
4354 line_scratch.push((
4355 slot,
4356 adv_phys,
4357 glyph.get_width().min(u16::MAX as u32) as u16,
4358 glyph.get_height().min(u16::MAX as u32) as u16,
4359 ));
4360 }
4361 }
4362 }
4363 let fit_scale: f32 = if box_w_phys > 1.0 && line_w_phys > box_w_phys + 1.0 {
4364 (box_w_phys / line_w_phys).clamp(0.72, 1.0)
4365 } else {
4366 1.0
4367 };
4368 let fitted_w_phys: f32 = line_w_phys * fit_scale;
4369 let align_x: f32 = match align {
4370 TextAlign::Left => 0.0,
4371 TextAlign::Center => ((box_w_phys - fitted_w_phys) * 0.5).max(0.0),
4372 TextAlign::Right => (box_w_phys - fitted_w_phys).max(0.0),
4373 };
4374 let mut pen_x: f32 = align_x.round();
4375 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4376 if slot == u32::MAX {
4377 pen_x += adv_phys * fit_scale;
4378 continue;
4379 }
4380 let pen_x_round: f32 = pen_x.round();
4381 if (pen_x - pen_x_round).abs() > 1e-4 {
4382 *has_fractional_x = true;
4383 }
4384 let glyph_v_off: f32 = ((line_h_phys - (gh_u16 as f32)) * 0.5).round();
4385 out_glyphs.push(PositionedGlyph::new(
4386 slot,
4387 pen_x_round as i32,
4388 (line_off_y + glyph_v_off) as i32,
4389 gw_u16,
4390 gh_u16,
4391 ));
4392 pen_x += adv_phys * fit_scale;
4393 }
4394 }
4395
4396 fn append_single_line_positioned_glyph_run(
4412 line_info: (&str, f32),
4413 rect: Rect,
4414 style: TextStyle,
4415 scale: f32,
4416 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4417 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4418 out_glyphs: &mut Vec<PositionedGlyph>,
4419 ) -> (bool, u32) {
4420 let (line_str, line_height_px): (&str, f32) = line_info;
4421 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4422 let phys_font_size: f32 = style.get_font_size() * scale;
4423 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4424 let bold: bool = style.get_weight().is_bold();
4425 let monospace: bool = style.get_family() == FontFamily::Monospace;
4426 let italic: bool = style.get_italic();
4427 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4428 let ascii_table_idx: usize =
4429 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4430 let line_h_phys: f32 = line_height_px * scale;
4431 let box_w_phys: f32 = rect.get_width() * scale;
4432 let letter_sp: f32 = style.get_letter_spacing() * scale;
4433 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4434 let mut has_fractional_x: bool = false;
4435 let mut max_glyph_slot: u32 = 0;
4436 Self::append_relative_line_glyphs(
4437 (line_str, 0.0),
4438 (line_h_phys, box_w_phys, letter_sp, space_step),
4439 (style.get_align(), ascii_table_idx, key_meta),
4440 (glyph_atlas, font_provider),
4441 line_scratch,
4442 out_glyphs,
4443 (&mut has_fractional_x, &mut max_glyph_slot),
4444 );
4445 (has_fractional_x, max_glyph_slot)
4446 }
4447
4448 fn append_cached_positioned_glyph_run(
4464 layout: &TextLayoutResult,
4465 rect: Rect,
4466 style: TextStyle,
4467 scale: f32,
4468 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4469 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4470 out_glyphs: &mut Vec<PositionedGlyph>,
4471 ) -> (bool, u32) {
4472 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4473 let phys_font_size: f32 = style.get_font_size() * scale;
4474 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4475 let bold: bool = style.get_weight().is_bold();
4476 let monospace: bool = style.get_family() == FontFamily::Monospace;
4477 let italic: bool = style.get_italic();
4478 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4479 let ascii_table_idx: usize =
4480 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4481 let line_h_phys: f32 = layout.get_line_height_px() * scale;
4482 let box_w_phys: f32 = rect.get_width() * scale;
4483 let letter_sp: f32 = style.get_letter_spacing() * scale;
4484 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4485 let align: TextAlign = style.get_align();
4486 let mut has_fractional_x: bool = false;
4487 let mut max_glyph_slot: u32 = 0;
4488 for (line_idx, line) in layout.get_lines().iter().enumerate() {
4489 let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
4490 Self::append_relative_line_glyphs(
4491 (line.get_text().as_str(), line_off_y),
4492 (line_h_phys, box_w_phys, letter_sp, space_step),
4493 (align, ascii_table_idx, key_meta),
4494 (glyph_atlas, font_provider),
4495 line_scratch,
4496 out_glyphs,
4497 (&mut has_fractional_x, &mut max_glyph_slot),
4498 );
4499 }
4500 (has_fractional_x, max_glyph_slot)
4501 }
4502
4503 fn emit_cached_glyph_run(
4516 cached_glyphs: &[PositionedGlyph],
4517 origin: (i32, i32),
4518 clip_dims: (Rect, u32, u32),
4519 out_glyphs: &mut Vec<PositionedGlyph>,
4520 ) -> (u32, u32) {
4521 let (base_x, base_y): (i32, i32) = origin;
4522 let (clip, phys_w, phys_h): (Rect, u32, u32) = clip_dims;
4523 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4524 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4525 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4526 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4527 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4528 return (0, 0);
4529 }
4530 let run_start: u32 = out_glyphs.len() as u32;
4531 for green_val in cached_glyphs.iter() {
4532 let gx0: i32 = base_x + green_val.get_x();
4533 let gw: i32 = green_val.get_width() as i32;
4534 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4535 let gy0: i32 = base_y + green_val.get_y();
4536 let gh: i32 = green_val.get_height() as i32;
4537 if gy0 < clip_y1 && gy0 + gh > clip_y0 {
4538 out_glyphs.push(PositionedGlyph::new(
4539 green_val.get_glyph_idx(),
4540 gx0,
4541 gy0,
4542 green_val.get_width(),
4543 green_val.get_height(),
4544 ));
4545 }
4546 }
4547 }
4548 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
4549 (run_start, run_len)
4550 }
4551
4552 fn resolve_single_line_glyphs(
4568 line_info: (&str, f32),
4569 rect: Rect,
4570 style: TextStyle,
4571 clip_dims: (Rect, u32, u32, f32),
4572 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4573 out_glyphs: &mut Vec<PositionedGlyph>,
4574 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4575 ) -> (u32, u32) {
4576 let (line_str, line_height_px): (&str, f32) = line_info;
4577 let (clip, phys_w, phys_h, scale): (Rect, u32, u32, f32) = clip_dims;
4578 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4579 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4580 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4581 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4582 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4583 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4584 return (0, 0);
4585 }
4586 let line_h_phys: f32 = line_height_px * scale;
4587 let base_x_phys: f32 = (rect.get_x() * scale).round();
4588 let base_y_phys: f32 = (rect.get_y() * scale).round();
4589 if (base_y_phys + line_h_phys) < (clip_y0 as f32) || base_y_phys > (clip_y1 as f32) {
4590 return (0, 0);
4591 }
4592 let phys_font_size: f32 = style.get_font_size() * scale;
4593 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4594 let bold: bool = style.get_weight().is_bold();
4595 let monospace: bool = style.get_family() == FontFamily::Monospace;
4596 let italic: bool = style.get_italic();
4597 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4598 let ascii_table_idx: usize =
4599 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4600 let box_w_phys: f32 = rect.get_width() * scale;
4601 let letter_sp: f32 = style.get_letter_spacing() * scale;
4602 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4603 let align: TextAlign = style.get_align();
4604 let run_start: u32 = out_glyphs.len() as u32;
4605 let clip_x1_f: f32 = clip_x1 as f32;
4606 line_scratch.clear();
4607 let mut line_w_phys: f32 = 0.0;
4608 for ch in line_str.chars() {
4609 if ch == ' ' {
4610 line_w_phys += space_step;
4611 line_scratch.push((u32::MAX, space_step, 0, 0));
4612 } else {
4613 let slot: u32 = if ch.is_ascii() {
4614 glyph_atlas.get_or_rasterize_ascii_slot_with(
4615 ascii_table_idx,
4616 ch as u8,
4617 key_meta,
4618 font_provider,
4619 )
4620 } else {
4621 let key: GlyphKey = GlyphKey {
4622 codepoint: ch,
4623 size_tenths,
4624 bold,
4625 monospace,
4626 italic,
4627 };
4628 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4629 };
4630 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4631 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4632 line_w_phys += adv_phys;
4633 line_scratch.push((
4634 slot,
4635 adv_phys,
4636 glyph.get_width().min(u16::MAX as u32) as u16,
4637 glyph.get_height().min(u16::MAX as u32) as u16,
4638 ));
4639 }
4640 }
4641 let fit_scale: f32 = if box_w_phys > 1.0 && line_w_phys > box_w_phys + 1.0 {
4642 (box_w_phys / line_w_phys).clamp(0.72, 1.0)
4643 } else {
4644 1.0
4645 };
4646 let fitted_w_phys: f32 = line_w_phys * fit_scale;
4647 let align_x: f32 = match align {
4648 TextAlign::Left => 0.0,
4649 TextAlign::Center => ((box_w_phys - fitted_w_phys) * 0.5).max(0.0),
4650 TextAlign::Right => (box_w_phys - fitted_w_phys).max(0.0),
4651 };
4652 let mut pen_x: f32 = base_x_phys + align_x.round();
4653 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4654 if pen_x > clip_x1_f {
4655 break;
4656 }
4657 if slot == u32::MAX {
4658 pen_x += adv_phys * fit_scale;
4659 continue;
4660 }
4661 let gx0: i32 = pen_x.round() as i32;
4662 let gw: i32 = gw_u16 as i32;
4663 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4664 let gy0: i32 =
4665 (base_y_phys + ((line_h_phys - (gh_u16 as f32)) * 0.5).round()) as i32;
4666 if gy0 < clip_y1 && gy0 + (gh_u16 as i32) > clip_y0 {
4667 out_glyphs.push(PositionedGlyph::new(slot, gx0, gy0, gw_u16, gh_u16));
4668 }
4669 }
4670 pen_x += adv_phys * fit_scale;
4671 }
4672 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
4673 (run_start, run_len)
4674 }
4675
4676 fn resolve_text_run_glyphs(
4692 layout: &TextLayoutResult,
4693 rect: Rect,
4694 style: TextStyle,
4695 clip_dims: (Rect, u32, u32, f32),
4696 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4697 out_glyphs: &mut Vec<PositionedGlyph>,
4698 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4699 ) -> (u32, u32) {
4700 let (clip, phys_w, phys_h, scale): (Rect, u32, u32, f32) = clip_dims;
4701 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4702 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4703 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4704 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4705 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4706 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4707 return (0, 0);
4708 }
4709 let phys_font_size: f32 = style.get_font_size() * scale;
4710 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4711 let bold: bool = style.get_weight().is_bold();
4712 let monospace: bool = style.get_family() == FontFamily::Monospace;
4713 let italic: bool = style.get_italic();
4714 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4715 let ascii_table_idx: usize =
4716 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4717 let line_h_phys: f32 = layout.get_line_height_px() * scale;
4718 let box_w_phys: f32 = rect.get_width() * scale;
4719 let letter_sp: f32 = style.get_letter_spacing() * scale;
4720 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4721 let base_x_phys: f32 = (rect.get_x() * scale).round();
4722 let base_y_phys: f32 = (rect.get_y() * scale).round();
4723 let clip_x1_f: f32 = clip_x1 as f32;
4724 let clip_y0_f: f32 = clip_y0 as f32;
4725 let clip_y1_f: f32 = clip_y1 as f32;
4726 let align: TextAlign = style.get_align();
4727 let run_start: u32 = out_glyphs.len() as u32;
4728 for (line_idx, line) in layout.get_lines().iter().enumerate() {
4729 let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
4730 let pen_y: f32 = base_y_phys + line_off_y;
4731 if (pen_y + line_h_phys) < clip_y0_f || pen_y > clip_y1_f {
4732 continue;
4733 }
4734 let line_str: &str = line.get_text().as_str();
4735 line_scratch.clear();
4736 let mut line_w_phys: f32 = 0.0;
4737 if line_str.is_ascii() {
4738 for &byte in line_str.as_bytes() {
4739 if byte == b' ' {
4740 line_w_phys += space_step;
4741 line_scratch.push((u32::MAX, space_step, 0, 0));
4742 } else {
4743 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
4744 ascii_table_idx,
4745 byte,
4746 key_meta,
4747 font_provider,
4748 );
4749 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4750 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4751 line_w_phys += adv_phys;
4752 line_scratch.push((
4753 slot,
4754 adv_phys,
4755 glyph.get_width().min(u16::MAX as u32) as u16,
4756 glyph.get_height().min(u16::MAX as u32) as u16,
4757 ));
4758 }
4759 }
4760 } else {
4761 for ch in line_str.chars() {
4762 if ch == ' ' {
4763 line_w_phys += space_step;
4764 line_scratch.push((u32::MAX, space_step, 0, 0));
4765 } else {
4766 let slot: u32 = if ch.is_ascii() {
4767 glyph_atlas.get_or_rasterize_ascii_slot_with(
4768 ascii_table_idx,
4769 ch as u8,
4770 key_meta,
4771 font_provider,
4772 )
4773 } else {
4774 let key: GlyphKey = GlyphKey {
4775 codepoint: ch,
4776 size_tenths,
4777 bold,
4778 monospace,
4779 italic,
4780 };
4781 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4782 };
4783 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4784 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4785 line_w_phys += adv_phys;
4786 line_scratch.push((
4787 slot,
4788 adv_phys,
4789 glyph.get_width().min(u16::MAX as u32) as u16,
4790 glyph.get_height().min(u16::MAX as u32) as u16,
4791 ));
4792 }
4793 }
4794 }
4795 let fit_scale: f32 = if box_w_phys > 1.0 && line_w_phys > box_w_phys + 1.0 {
4796 (box_w_phys / line_w_phys).clamp(0.72, 1.0)
4797 } else {
4798 1.0
4799 };
4800 let fitted_w_phys: f32 = line_w_phys * fit_scale;
4801 let align_x: f32 = match align {
4802 TextAlign::Left => 0.0,
4803 TextAlign::Center => ((box_w_phys - fitted_w_phys) * 0.5).max(0.0),
4804 TextAlign::Right => (box_w_phys - fitted_w_phys).max(0.0),
4805 };
4806 let mut pen_x: f32 = base_x_phys + align_x.round();
4807 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4808 if slot == u32::MAX {
4809 pen_x += adv_phys * fit_scale;
4810 continue;
4811 }
4812 if pen_x > clip_x1_f {
4813 break;
4814 }
4815 let gx0: i32 = pen_x.round() as i32;
4816 let gw: i32 = gw_u16 as i32;
4817 let gh: i32 = gh_u16 as i32;
4818 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4819 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
4820 let gy0: i32 = (pen_y + glyph_v_off) as i32;
4821 if gy0 < clip_y1 && gy0 + gh > clip_y0 {
4822 out_glyphs.push(PositionedGlyph::new(slot, gx0, gy0, gw_u16, gh_u16));
4823 }
4824 }
4825 pen_x += adv_phys * fit_scale;
4826 }
4827 }
4828 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
4829 (run_start, run_len)
4830 }
4831
4832 #[must_use]
4846 fn resolve_text_caret_rect(
4847 layout_opt: Option<&TextLayoutResult>,
4848 rects: (Rect, Rect),
4849 style: TextStyle,
4850 caret_opts: (f32, f32, bool),
4851 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4852 ) -> Rect {
4853 let (text_rect, content_rect): (Rect, Rect) = rects;
4854 let (caret_height, scale, multiline): (f32, f32, bool) = caret_opts;
4855 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4856 let phys_font_size: f32 = style.get_font_size() * scale;
4857 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4858 let bold: bool = style.get_weight().is_bold();
4859 let monospace: bool = style.get_family() == FontFamily::Monospace;
4860 let italic: bool = style.get_italic();
4861 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4862 let letter_sp: f32 = style.get_letter_spacing() * scale;
4863 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4864 let (last_w_phys, line_idx, line_h_phys): (f32, usize, f32) =
4865 if let Some(layout) = layout_opt {
4866 let lh: f32 = layout.get_line_height_px() * scale;
4867 let idx: usize = layout.get_lines().len().saturating_sub(1);
4868 let w_phys: f32 = if let Some(line) = layout.get_lines().last() {
4869 let ascii_table_idx: usize =
4870 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4871 let mut acc: f32 = 0.0;
4872 for ch in line.get_text().chars() {
4873 if ch == ' ' {
4874 acc += space_step;
4875 } else {
4876 let slot: u32 = if ch.is_ascii() {
4877 glyph_atlas.get_or_rasterize_ascii_slot_with(
4878 ascii_table_idx,
4879 ch as u8,
4880 key_meta,
4881 font_provider,
4882 )
4883 } else {
4884 let key: GlyphKey = GlyphKey {
4885 codepoint: ch,
4886 size_tenths,
4887 bold,
4888 monospace,
4889 italic,
4890 };
4891 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4892 };
4893 let adv: f32 =
4894 (glyph_atlas.glyph_by_slot(slot).get_advance() as f32).max(1.0);
4895 acc += adv + letter_sp;
4896 }
4897 }
4898 acc
4899 } else {
4900 0.0
4901 };
4902 (w_phys, idx, lh)
4903 } else {
4904 (
4905 0.0,
4906 0,
4907 (style.get_font_size() * style.get_line_height()).max(1.0) * scale,
4908 )
4909 };
4910 let caret_h_phys: f32 = (caret_height * scale).max(2.0);
4911 let caret_w_phys: f32 = (1.5 * scale).max(1.5);
4912 let min_x: f32 = content_rect.get_x() * scale;
4913 let max_x: f32 = (content_rect.right() * scale - caret_w_phys - 1.0).max(min_x);
4914 let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.0 * scale } else { 0.0 };
4915 let caret_x_phys: f32 = (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys)
4916 .min(max_x)
4917 .max(min_x);
4918 let caret_y_phys: f32 = if multiline {
4919 let raw_y: f32 = content_rect.get_y() * scale
4920 + (line_idx as f32) * line_h_phys
4921 + ((line_h_phys - caret_h_phys) * 0.5).max(0.0);
4922 raw_y
4923 .min(content_rect.bottom() * scale - caret_h_phys)
4924 .max(content_rect.get_y() * scale)
4925 } else {
4926 content_rect.get_y() * scale
4927 + ((content_rect.get_height() * scale - caret_h_phys) * 0.5).max(0.0)
4928 };
4929 Rect::new(
4930 caret_x_phys.round(),
4931 caret_y_phys.round(),
4932 caret_w_phys.round().max(1.0),
4933 caret_h_phys.round().max(2.0),
4934 )
4935 }
4936
4937 #[must_use]
4949 fn collect_active_rounded(
4950 stack: &[Option<RoundedClipMask>],
4951 out: &mut Vec<RoundedClipMask>,
4952 vis: Rect,
4953 ) -> (u32, u16) {
4954 let start: u32 = out.len() as u32;
4955 for entry in stack.iter().copied().flatten() {
4956 if rect_intersects_rounded_corners(vis, entry.get_rect(), entry.get_radius()) {
4957 out.push(entry);
4958 }
4959 }
4960 let len: u16 = (out.len() as u32)
4961 .saturating_sub(start)
4962 .min(u16::MAX as u32) as u16;
4963 (start, len)
4964 }
4965
4966 #[must_use]
4977 fn resolve_opaque_clear_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
4978 let Some(DrawCommand::FillRoundedRect {
4979 rect,
4980 color,
4981 radius,
4982 border,
4983 }) = next_cmd
4984 else {
4985 return (Rect::default(), Rect::default());
4986 };
4987 if color.get_alpha() != 255 {
4988 return (Rect::default(), Rect::default());
4989 }
4990 let border_width: f32 = if border.get_width() > 0.0 && border.get_color().get_alpha() < 255
4991 {
4992 (border.get_width() * scale).max(1.0)
4993 } else {
4994 0.0
4995 };
4996 let phys: Rect = snap_physical_rect(*rect, scale);
4997 let r_max: f32 = Self::scale_radius(*radius, scale)
4998 .max_radius()
4999 .min(phys.get_width() * 0.5)
5000 .min(phys.get_height() * 0.5);
5001 let pad: f32 = 1.5 + border_width;
5002 let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
5003 let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
5004 let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
5005 Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
5006 } else {
5007 Rect::default()
5008 };
5009 let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
5010 let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
5011 let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
5012 Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
5013 } else {
5014 Rect::default()
5015 };
5016 (cut_h, cut_v)
5017 }
5018
5019 #[must_use]
5030 fn resolve_opaque_shadow_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
5031 let Some(DrawCommand::FillRoundedRect {
5032 rect,
5033 color,
5034 radius,
5035 ..
5036 }) = next_cmd
5037 else {
5038 return (Rect::default(), Rect::default());
5039 };
5040 if color.get_alpha() != 255 {
5041 return (Rect::default(), Rect::default());
5042 }
5043 let phys: Rect = snap_physical_rect(*rect, scale);
5044 let r_max: f32 = Self::scale_radius(*radius, scale)
5045 .max_radius()
5046 .min(phys.get_width() * 0.5)
5047 .min(phys.get_height() * 0.5);
5048 let pad: f32 = 1.5;
5049 let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
5050 let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
5051 let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
5052 Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
5053 } else {
5054 Rect::default()
5055 };
5056 let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
5057 let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
5058 let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
5059 Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
5060 } else {
5061 Rect::default()
5062 };
5063 (cut_h, cut_v)
5064 }
5065
5066 fn save_single_cached_rounded_corners(
5081 band: &mut PixelBand<'_>,
5082 mask: RoundedClipMask,
5083 clip: Rect,
5084 band_bounds: (u32, u32, u32),
5085 corner_masks: &[CachedCornerMask],
5086 scratch: &mut BandCornerScratch,
5087 ) -> bool {
5088 let (fb_w, band_y0, band_y1): (u32, u32, u32) = band_bounds;
5089 let clip_x0: i32 = (clip.get_x().floor().max(0.0) as u32).min(fb_w) as i32;
5090 let clip_y0: i32 = (clip.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
5091 let clip_x1: i32 = (clip.right().ceil().max(0.0) as u32).min(fb_w) as i32;
5092 let clip_y1: i32 = (clip.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
5093 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
5094 return false;
5095 }
5096 let rect: Rect = mask.get_rect();
5097 let rx0_i: i32 = rect.get_x().round() as i32;
5098 let ry0_i: i32 = rect.get_y().round() as i32;
5099 let rx1_i: i32 = rect.right().round() as i32;
5100 let ry1_i: i32 = rect.bottom().round() as i32;
5101 let mask_ids: [u32; 4] = mask.get_corner_mask_ids();
5102 scratch.saved_bytes.clear();
5103 scratch.saved_rows.clear();
5104 for (query_val, &mask_id) in mask_ids.iter().enumerate() {
5105 if mask_id == u32::MAX {
5106 continue;
5107 }
5108 let Some(cm) = corner_masks.get(mask_id as usize) else {
5109 continue;
5110 };
5111 let dim_i: i32 = cm.dim as i32;
5112 let origin_x: i32 = if query_val == 0 || query_val == 3 {
5113 rx0_i
5114 } else {
5115 rx1_i - dim_i
5116 };
5117 let origin_y: i32 = if query_val == 0 || query_val == 1 {
5118 ry0_i
5119 } else {
5120 ry1_i - dim_i
5121 };
5122 let bx0: i32 = origin_x.max(clip_x0);
5123 let bx1: i32 = (origin_x + dim_i).min(clip_x1);
5124 let by0: i32 = origin_y.max(clip_y0);
5125 let by1: i32 = (origin_y + dim_i).min(clip_y1);
5126 if bx0 >= bx1 || by0 >= by1 {
5127 continue;
5128 }
5129 for y_i in by0..by1 {
5130 let my: usize = (y_i - origin_y) as usize;
5131 let span: CornerMaskRowSpan = cm.row_spans[my];
5132 if span.dirty_start >= span.dirty_end {
5133 continue;
5134 }
5135 let sx0_i: i32 = (origin_x + (span.dirty_start as i32)).max(bx0);
5136 let sx1_i: i32 = (origin_x + (span.dirty_end as i32)).min(bx1);
5137 if sx0_i >= sx1_i {
5138 continue;
5139 }
5140 let pos_y: u32 = y_i as u32;
5141 let sx0: u32 = sx0_i as u32;
5142 let sx1: u32 = sx1_i as u32;
5143 if let Some(row) = band.row_slice_mut(pos_y) {
5144 let b0: usize = (sx0 as usize) * 4;
5145 let b1: usize = (sx1 as usize) * 4;
5146 let byte_off: usize = scratch.saved_bytes.len();
5147 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5148 scratch.saved_rows.push(SavedCornerRow {
5149 y: pos_y,
5150 sx0,
5151 sx1,
5152 byte_off,
5153 mask_id,
5154 origin_x,
5155 origin_y,
5156 });
5157 }
5158 }
5159 }
5160 !scratch.saved_rows.is_empty()
5161 }
5162
5163 fn restore_single_cached_rounded_corners(
5171 band: &mut PixelBand<'_>,
5172 corner_masks: &[CachedCornerMask],
5173 scratch: &BandCornerScratch,
5174 ) {
5175 let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
5176 for entry in scratch.saved_rows.iter() {
5177 let Some(row) = band.row_slice_mut(entry.y) else {
5178 continue;
5179 };
5180 let cm: &CachedCornerMask = &corner_masks[entry.mask_id as usize];
5181 let dim: usize = cm.dim as usize;
5182 let my: usize = ((entry.y as i32) - entry.origin_y) as usize;
5183 let span: CornerMaskRowSpan = cm.row_spans[my];
5184 let sx0_i: i32 = entry.sx0 as i32;
5185 let sx1_i: i32 = entry.sx1 as i32;
5186 if span.ext_start < span.ext_end {
5187 let ex0: i32 = (entry.origin_x + (span.ext_start as i32)).max(sx0_i);
5188 let ex1: i32 = (entry.origin_x + (span.ext_end as i32)).min(sx1_i);
5189 if ex0 < ex1 {
5190 let dst_b0: usize = (ex0 as usize) * 4;
5191 let dst_b1: usize = (ex1 as usize) * 4;
5192 let src_b0: usize = entry.byte_off + ((ex0 - sx0_i) as usize) * 4;
5193 let src_b1: usize = src_b0 + (dst_b1 - dst_b0);
5194 row[dst_b0..dst_b1].copy_from_slice(&saved_bytes[src_b0..src_b1]);
5195 }
5196 }
5197 if span.aa_start < span.aa_end {
5198 let ax0: i32 = (entry.origin_x + (span.aa_start as i32)).max(sx0_i);
5199 let ax1: i32 = (entry.origin_x + (span.aa_end as i32)).min(sx1_i);
5200 if ax0 < ax1 {
5201 let cov_row: &[u8] = &cm.cov[my * dim..(my + 1) * dim];
5202 for x_i in ax0..ax1 {
5203 let mx: usize = (x_i - entry.origin_x) as usize;
5204 let cov_u8: u8 = cov_row[mx];
5205 if cov_u8 >= 16 {
5206 continue;
5207 }
5208 let dst_off: usize = (x_i as usize) * 4;
5209 let src_off: usize = entry.byte_off + ((x_i - sx0_i) as usize) * 4;
5210 let saved_rgba: [u8; 4] = [
5211 saved_bytes[src_off],
5212 saved_bytes[src_off + 1],
5213 saved_bytes[src_off + 2],
5214 saved_bytes[src_off + 3],
5215 ];
5216 if cov_u8 == 0 {
5217 row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
5218 } else {
5219 let cov: f32 = (cov_u8 as f32) * 0.0625;
5220 lerp_pixel_slice_from_saved_linear(
5221 &mut row[dst_off..dst_off + 4],
5222 saved_rgba,
5223 cov,
5224 );
5225 }
5226 }
5227 }
5228 }
5229 }
5230 }
5231
5232 pub(crate) fn render_band(
5247 band: &mut PixelBand<'_>,
5248 commands: &[DrawCommand],
5249 prepped: &[PreppedCommand],
5250 aux: BandAuxSlices<'_>,
5251 glyph_atlas: &GlyphAtlas,
5252 render_opts: (f32, AntialiasingMode),
5253 ) -> usize {
5254 let BandAuxSlices {
5255 positioned_glyphs,
5256 caret_rects,
5257 rounded_clips,
5258 corner_masks,
5259 } = aux;
5260 let (scale, aa): (f32, AntialiasingMode) = render_opts;
5261 let band_y0: u32 = band.y_offset();
5262 let band_y1: u32 = band.y_end();
5263 let fb_w: u32 = band.width();
5264 let band_rect: Rect =
5265 Rect::new(0.0, band_y0 as f32, fb_w as f32, (band_y1 - band_y0) as f32);
5266 let has_any_rounded: bool = !rounded_clips.is_empty();
5267 let mut scratch: BandCornerScratch = if has_any_rounded {
5268 BAND_CORNER_SCRATCH
5269 .try_with(|cell: &RefCell<BandCornerScratch>| {
5270 cell.try_borrow_mut()
5271 .ok()
5272 .map(|mut guard: RefMut<'_, BandCornerScratch>| take(&mut *guard))
5273 })
5274 .ok()
5275 .flatten()
5276 .unwrap_or_default()
5277 } else {
5278 BandCornerScratch::default()
5279 };
5280 let mut shaded: usize = 0;
5281 let prepped_len: usize = prepped.len();
5282 let mut idx: usize = 0;
5283 while idx < prepped_len {
5284 let item: &PreppedCommand = &prepped[idx];
5285 if item.get_cmd_index() == usize::MAX {
5286 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
5287 idx += (item.get_skip_delta() as usize).max(1);
5288 } else {
5289 idx += 1;
5290 }
5291 continue;
5292 }
5293 idx += 1;
5294 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
5295 continue;
5296 }
5297 let Some(active_clip) = item.get_active_clip().intersect(band_rect) else {
5298 continue;
5299 };
5300 let rc_len: usize = item.get_rounded_clip_len() as usize;
5301 let item_masks: &[RoundedClipMask] = if rc_len > 0 {
5302 let start: usize = item.get_rounded_clip_start() as usize;
5303 let end: usize = start.saturating_add(rc_len).min(rounded_clips.len());
5304 &rounded_clips[start..end]
5305 } else {
5306 &[]
5307 };
5308 let mut corner_mode: u8 = 0;
5309 if item_masks.len() == 1 {
5310 let mask: RoundedClipMask = item_masks[0];
5311 let rect: Rect = mask.get_rect();
5312 let max_r: f32 = (rect.get_width() * 0.5)
5313 .min(rect.get_height() * 0.5)
5314 .max(0.0);
5315 let radius: CornerRadius = mask.get_radius();
5316 let radii: [f32; 4] = [
5317 radius.get_top_left().min(max_r),
5318 radius.get_top_right().min(max_r),
5319 radius.get_bottom_right().min(max_r),
5320 radius.get_bottom_left().min(max_r),
5321 ];
5322 let ids: [u32; 4] = mask.get_corner_mask_ids();
5323 let all_cached: bool =
5324 radii
5325 .iter()
5326 .zip(ids.iter())
5327 .all(|(&red_val, &id): (&f32, &u32)| {
5328 red_val <= 0.25 || (id as usize) < corner_masks.len()
5329 });
5330 if all_cached {
5331 if Self::save_single_cached_rounded_corners(
5332 band,
5333 mask,
5334 active_clip,
5335 (fb_w, band_y0, band_y1),
5336 corner_masks,
5337 &mut scratch,
5338 ) {
5339 corner_mode = 1;
5340 }
5341 } else {
5342 scratch.corner_boxes.clear();
5343 scratch.saved_bytes.clear();
5344 collect_rounded_clip_boxes(
5345 mask,
5346 active_clip,
5347 (fb_w, band_y0, band_y1),
5348 &mut scratch.corner_boxes,
5349 );
5350 if !scratch.corner_boxes.is_empty() {
5351 for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
5352 let b0: usize = (bx0 as usize) * 4;
5353 let b1: usize = (bx1 as usize) * 4;
5354 for pos_y in by0..by1 {
5355 if let Some(row) = band.row_slice_mut(pos_y) {
5356 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5357 }
5358 }
5359 }
5360 corner_mode = 2;
5361 }
5362 }
5363 } else if !item_masks.is_empty() {
5364 scratch.corner_boxes.clear();
5365 scratch.saved_bytes.clear();
5366 for mask in item_masks.iter().copied() {
5367 collect_rounded_clip_boxes(
5368 mask,
5369 active_clip,
5370 (fb_w, band_y0, band_y1),
5371 &mut scratch.corner_boxes,
5372 );
5373 }
5374 if !scratch.corner_boxes.is_empty() {
5375 for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
5376 let b0: usize = (bx0 as usize) * 4;
5377 let b1: usize = (bx1 as usize) * 4;
5378 for coord_y in by0..by1 {
5379 if let Some(row) = band.row_slice_mut(coord_y) {
5380 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5381 }
5382 }
5383 }
5384 corner_mode = 2;
5385 }
5386 }
5387 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
5388 shaded += match cmd {
5389 DrawCommand::Clear(color) => {
5390 let cutouts: (Rect, Rect) =
5391 (item.get_opaque_cutout_h(), item.get_opaque_cutout_v());
5392 if cutouts.0.get_width() > 0.0 || cutouts.1.get_width() > 0.0 {
5393 let cx0: u32 = (active_clip.get_x().floor().max(0.0) as u32).min(fb_w);
5394 let cx1: u32 = (active_clip.right().ceil().max(0.0) as u32).min(fb_w);
5395 let cy0: u32 = (active_clip.get_y().floor().max(0.0) as u32)
5396 .max(band_y0)
5397 .min(band_y1);
5398 let cy1: u32 = (active_clip.bottom().ceil().max(0.0) as u32)
5399 .max(band_y0)
5400 .min(band_y1);
5401 let rgba: [u8; 4] = [
5402 color.get_red(),
5403 color.get_green(),
5404 color.get_blue(),
5405 color.get_alpha(),
5406 ];
5407 let mut count: usize = 0;
5408 if cx0 < cx1 && cy0 < cy1 {
5409 for sample_y in cy0..cy1 {
5410 let (cut0, cut1): (u32, u32) =
5411 Self::shadow_row_cutout(sample_y, cutouts, cx0, cx1);
5412 if cut0 <= cx0 && cut1 >= cx1 {
5413 continue;
5414 }
5415 if let Some(row) = band.row_slice_mut(sample_y) {
5416 if cut0 < cut1 {
5417 if cx0 < cut0 {
5418 fill_rgba_span_32(
5419 &mut row[(cx0 as usize) * 4..(cut0 as usize) * 4],
5420 rgba,
5421 );
5422 count += (cut0 - cx0) as usize;
5423 }
5424 if cut1 < cx1 {
5425 fill_rgba_span_32(
5426 &mut row[(cut1 as usize) * 4..(cx1 as usize) * 4],
5427 rgba,
5428 );
5429 count += (cx1 - cut1) as usize;
5430 }
5431 } else {
5432 fill_rgba_span_32(
5433 &mut row[(cx0 as usize) * 4..(cx1 as usize) * 4],
5434 rgba,
5435 );
5436 count += (cx1 - cx0) as usize;
5437 }
5438 }
5439 }
5440 }
5441 count
5442 } else if active_clip.get_x() <= 0.0
5443 && active_clip.get_width() >= (band.width() as f32)
5444 && active_clip.get_y() <= (band_y0 as f32)
5445 && active_clip.bottom() >= (band_y1 as f32)
5446 {
5447 band.clear(*color);
5448 (band.width() as usize) * ((band_y1 - band_y0) as usize)
5449 } else {
5450 Self::fill_rect_clipped(band, active_clip, *color, active_clip)
5451 }
5452 }
5453 DrawCommand::FillRoundedRect {
5454 rect,
5455 color,
5456 radius,
5457 border,
5458 } => {
5459 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5460 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5461 let border_width: f32 = if border.get_width() > 0.0 {
5462 (border.get_width() * scale).max(1.0)
5463 } else {
5464 0.0
5465 };
5466 let phys_border: Border = Border::new(border_width, border.get_color());
5467 Self::raster_rounded_rect(
5468 band,
5469 phys_rect,
5470 *color,
5471 phys_radius,
5472 phys_border,
5473 active_clip,
5474 aa,
5475 )
5476 }
5477 DrawCommand::LinearGradientRect {
5478 rect,
5479 gradient,
5480 radius,
5481 } => {
5482 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5483 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5484 Self::raster_gradient_rect(
5485 band,
5486 phys_rect,
5487 *gradient,
5488 phys_radius,
5489 active_clip,
5490 aa,
5491 )
5492 }
5493 DrawCommand::BoxShadow {
5494 rect,
5495 radius,
5496 shadow,
5497 } => {
5498 let spread: f32 = shadow.get_spread_radius() * scale;
5499 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
5500 let sigma: f32 = (blur * 0.5).max(0.75);
5501 let pad: f32 = (sigma * 3.0).ceil();
5502 let base_rect: Rect = snap_physical_rect(*rect, scale);
5503 let caster_rect: Rect = Rect::new(
5504 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
5505 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
5506 (base_rect.get_width() + spread * 2.0).max(1.0),
5507 (base_rect.get_height() + spread * 2.0).max(1.0),
5508 );
5509 let shadow_rect: Rect = Rect::new(
5510 caster_rect.get_x() - pad,
5511 caster_rect.get_y() - pad,
5512 caster_rect.get_width() + pad * 2.0,
5513 caster_rect.get_height() + pad * 2.0,
5514 );
5515 let raw_r: CornerRadius = Self::scale_radius(*radius, scale);
5516 let phys_radius: CornerRadius = CornerRadius::new(
5517 (raw_r.get_top_left() + spread).max(0.0),
5518 (raw_r.get_top_right() + spread).max(0.0),
5519 (raw_r.get_bottom_right() + spread).max(0.0),
5520 (raw_r.get_bottom_left() + spread).max(0.0),
5521 );
5522 Self::raster_shadow(
5523 band,
5524 (shadow_rect, caster_rect, active_clip),
5525 phys_radius,
5526 sigma,
5527 shadow.get_color(),
5528 (item.get_opaque_cutout_h(), item.get_opaque_cutout_v()),
5529 )
5530 }
5531 DrawCommand::BackdropBlur {
5532 rect,
5533 radius,
5534 blur_radius,
5535 } => {
5536 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5537 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5538 let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 48.0);
5539 Self::raster_backdrop_blur(band, phys_rect, phys_radius, phys_blur, active_clip)
5540 }
5541 DrawCommand::TextRun { style, .. } => {
5542 let g_start: usize = item.get_glyph_run_start() as usize;
5543 let g_len: usize = item.get_glyph_run_len() as usize;
5544 if let Some(run_slice) = positioned_glyphs.get(g_start..g_start + g_len) {
5545 Self::raster_text_run_band(
5546 band,
5547 run_slice,
5548 style.get_color(),
5549 active_clip,
5550 glyph_atlas,
5551 )
5552 } else {
5553 0
5554 }
5555 }
5556 DrawCommand::TextCaret { color, .. } => {
5557 let cidx: usize = item.get_caret_rect_idx() as usize;
5558 if let Some(&caret_rect) = caret_rects.get(cidx) {
5559 Self::raster_rounded_rect(
5560 band,
5561 caret_rect,
5562 *color,
5563 CornerRadius::all(0.5 * scale),
5564 Border::default(),
5565 active_clip,
5566 aa,
5567 )
5568 } else {
5569 0
5570 }
5571 }
5572 DrawCommand::Image {
5573 rect,
5574 buffer,
5575 radius,
5576 } => {
5577 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5578 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5579 Self::raster_rgba_bytes(
5580 band,
5581 phys_rect,
5582 (buffer.get_width(), buffer.get_height(), buffer.get_pixels()),
5583 phys_radius,
5584 active_clip,
5585 aa,
5586 )
5587 }
5588 DrawCommand::SharedImage {
5589 rect,
5590 width,
5591 height,
5592 pixels,
5593 radius,
5594 } => {
5595 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5596 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5597 Self::raster_rgba_bytes(
5598 band,
5599 phys_rect,
5600 (*width, *height, pixels.as_slice()),
5601 phys_radius,
5602 active_clip,
5603 aa,
5604 )
5605 }
5606 DrawCommand::Line {
5607 from,
5608 to,
5609 color,
5610 width,
5611 } => {
5612 let p0: Point = Point::new(from.get_x() * scale, from.get_y() * scale);
5613 let p1: Point = Point::new(to.get_x() * scale, to.get_y() * scale);
5614 Self::raster_line(
5615 band,
5616 p0,
5617 p1,
5618 *color,
5619 (width * scale).max(1.0),
5620 active_clip,
5621 aa,
5622 )
5623 }
5624 DrawCommand::Circle {
5625 center,
5626 radius,
5627 color,
5628 } => {
5629 let point_coords: Point =
5630 Point::new(center.get_x() * scale, center.get_y() * scale);
5631 Self::raster_circle(band, point_coords, radius * scale, *color, active_clip, aa)
5632 }
5633 DrawCommand::Triangle { p0, p1, p2, color } => {
5634 let v0: Point = Point::new(p0.get_x() * scale, p0.get_y() * scale);
5635 let v1: Point = Point::new(p1.get_x() * scale, p1.get_y() * scale);
5636 let v2: Point = Point::new(p2.get_x() * scale, p2.get_y() * scale);
5637 Self::raster_triangle(band, v0, v1, v2, *color, active_clip, aa)
5638 }
5639 DrawCommand::SpriteRegion {
5640 rect,
5641 buffer,
5642 src_rect,
5643 tint,
5644 } => {
5645 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5646 Self::raster_sprite_region(
5647 band,
5648 phys_rect,
5649 buffer,
5650 *src_rect,
5651 *tint,
5652 active_clip,
5653 aa,
5654 )
5655 }
5656 DrawCommand::ExternalSurface { .. }
5657 | DrawCommand::PushClip(_)
5658 | DrawCommand::PushRoundedClip { .. }
5659 | DrawCommand::PopClip => 0,
5660 };
5661 if corner_mode == 1 {
5662 Self::restore_single_cached_rounded_corners(band, corner_masks, &scratch);
5663 } else if corner_mode == 2 {
5664 let multi_mask: bool = item_masks.len() > 1;
5665 let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
5666 let mut byte_cursor: usize = 0;
5667 for (box_idx, &(bx0, by0, bx1, by1)) in scratch.corner_boxes.iter().enumerate() {
5668 for value_y in by0..by1 {
5669 let Some(row) = band.row_slice_mut(value_y) else {
5670 byte_cursor += ((bx1 - bx0) as usize) * 4;
5671 continue;
5672 };
5673 for pos_x in bx0..bx1 {
5674 let saved_rgba: [u8; 4] = [
5675 saved_bytes[byte_cursor],
5676 saved_bytes[byte_cursor + 1],
5677 saved_bytes[byte_cursor + 2],
5678 saved_bytes[byte_cursor + 3],
5679 ];
5680 byte_cursor += 4;
5681 if multi_mask
5682 && scratch.corner_boxes[..box_idx].iter().any(
5683 |&(px0, py0, px1, py1): &(u32, u32, u32, u32)| {
5684 pos_x >= px0
5685 && pos_x < px1
5686 && value_y >= py0
5687 && value_y < py1
5688 },
5689 )
5690 {
5691 continue;
5692 }
5693 let mut cov: f32 = 1.0;
5694 for mask in item_masks.iter().copied() {
5695 cov *= rounded_clip_coverage_cached(
5696 pos_x,
5697 value_y,
5698 mask,
5699 corner_masks,
5700 aa,
5701 );
5702 if cov <= 0.0005 {
5703 break;
5704 }
5705 }
5706 let dst_off: usize = (pos_x as usize) * 4;
5707 if cov <= 0.0005 {
5708 row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
5709 } else if cov < 0.9995 {
5710 lerp_pixel_slice_from_saved_linear(
5711 &mut row[dst_off..dst_off + 4],
5712 saved_rgba,
5713 cov,
5714 );
5715 }
5716 }
5717 }
5718 }
5719 }
5720 }
5721 if has_any_rounded {
5722 let _: bool = BAND_CORNER_SCRATCH
5723 .try_with(|cell: &RefCell<BandCornerScratch>| {
5724 if let Ok(mut guard) = cell.try_borrow_mut() {
5725 *guard = scratch;
5726 }
5727 })
5728 .is_ok();
5729 }
5730 shaded
5731 }
5732
5733 fn scale_rect(rect: Rect, scale: f32) -> Rect {
5744 Rect::new(
5745 rect.get_x() * scale,
5746 rect.get_y() * scale,
5747 rect.get_width() * scale,
5748 rect.get_height() * scale,
5749 )
5750 }
5751
5752 fn scale_radius(radius: CornerRadius, scale: f32) -> CornerRadius {
5763 CornerRadius::new(
5764 radius.get_top_left() * scale,
5765 radius.get_top_right() * scale,
5766 radius.get_bottom_right() * scale,
5767 radius.get_bottom_left() * scale,
5768 )
5769 }
5770
5771 fn fill_rect_clipped(band: &mut PixelBand<'_>, rect: Rect, color: Color, clip: Rect) -> usize {
5784 if color.get_alpha() == 0 {
5785 return 0;
5786 }
5787 let Some(vis) = rect.intersect(clip) else {
5788 return 0;
5789 };
5790 let fb_w: u32 = band.width();
5791 let band_y0: u32 = band.y_offset();
5792 let band_y1: u32 = band.y_end();
5793 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
5794 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
5795 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
5796 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
5797 if x0 >= x1 || y0 >= y1 {
5798 return 0;
5799 }
5800 let span_len: usize = (x1 - x0) as usize;
5801 let rows: usize = (y1 - y0) as usize;
5802 let sa: u8 = color.get_alpha();
5803 if sa == 255 {
5804 band.fill_rect_opaque_preclipped(
5805 x0,
5806 x1,
5807 y0,
5808 y1,
5809 [color.get_red(), color.get_green(), color.get_blue(), 255],
5810 );
5811 } else if let Some((rows_buf, row_stride)) = band.rows_slice_mut(y0, y1) {
5812 let bx0: usize = (x0 as usize) * 4;
5813 let bx1: usize = (x1 as usize) * 4;
5814 if span_len.saturating_mul(rows) >= 512 {
5815 let luts: [[u8; 256]; 4] = build_linear_blend_luts(color);
5816 for row in rows_buf.chunks_exact_mut(row_stride) {
5817 fill_span_linear_luts_slice(&mut row[bx0..bx1], &luts);
5818 }
5819 } else {
5820 for row in rows_buf.chunks_exact_mut(row_stride) {
5821 fill_span_linear_slice(&mut row[bx0..bx1], color);
5822 }
5823 }
5824 }
5825 span_len * rows
5826 }
5827
5828 #[must_use]
5843 fn build_vertical_edge_strip(
5844 x_span: (u32, u32),
5845 geom: (f32, f32, f32, f32),
5846 colors: (Color, Border),
5847 lin_colors: ([f32; 4], [f32; 4]),
5848 aa: AntialiasingMode,
5849 out: &mut [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP],
5850 ) -> (usize, usize) {
5851 let (x_start, x_end): (u32, u32) = x_span;
5852 let (cx, half_w, half_h, border_width): (f32, f32, f32, f32) = geom;
5853 let (color, border): (Color, Border) = colors;
5854 let (fill_lin, border_lin): ([f32; 4], [f32; 4]) = lin_colors;
5855 let has_border: bool = border_width > 0.0 && border.get_color().get_alpha() > 0;
5856 let inner_hw: f32 = (half_w - border_width).max(0.0);
5857 let inner_hh: f32 = (half_h - border_width).max(0.0);
5858 let mut len: usize = 0;
5859 let mut shaded: usize = 0;
5860 for pos_x in x_start..x_end {
5861 let px: f32 = (pos_x as f32) + 0.5 - cx;
5862 let dist: f32 = px.abs() - half_w;
5863 if dist > 0.85 {
5864 continue;
5865 }
5866 if !has_border {
5867 if dist < -0.85 {
5868 let sa: u8 = color.get_alpha();
5869 if sa > 0 {
5870 let alpha_val: f32 = (sa as f32) * (1.0 / 255.0);
5871 out[len] = EdgeBlendSample {
5872 x: pos_x,
5873 rgba: [color.get_red(), color.get_green(), color.get_blue(), 255],
5874 sr_a: fill_lin[0] * alpha_val,
5875 sg_a: fill_lin[1] * alpha_val,
5876 sb_a: fill_lin[2] * alpha_val,
5877 inv_a: 1.0 - alpha_val,
5878 sa_u32: sa as u32,
5879 is_opaque: sa == 255,
5880 };
5881 len += 1;
5882 shaded += 1;
5883 }
5884 continue;
5885 }
5886 let outer_cov: f32 = sdf_coverage(dist, aa);
5887 if outer_cov > 0.0 && color.get_alpha() > 0 {
5888 let alpha_f: f32 = ((color.get_alpha() as f32) * (1.0 / 255.0)) * outer_cov;
5889 shaded += 1;
5890 if alpha_f > 0.0002 {
5891 let first_val: f32 = alpha_f.clamp(0.0, 1.0);
5892 out[len] = EdgeBlendSample {
5893 x: pos_x,
5894 rgba: [color.get_red(), color.get_green(), color.get_blue(), 255],
5895 sr_a: fill_lin[0] * first_val,
5896 sg_a: fill_lin[1] * first_val,
5897 sb_a: fill_lin[2] * first_val,
5898 inv_a: 1.0 - first_val,
5899 sa_u32: (first_val * 255.0) as u32,
5900 is_opaque: first_val >= 0.9995,
5901 };
5902 len += 1;
5903 }
5904 }
5905 continue;
5906 }
5907 if dist < -(border_width + 0.85) {
5908 let sa: u8 = color.get_alpha();
5909 if sa > 0 {
5910 let area_val: f32 = (sa as f32) * (1.0 / 255.0);
5911 out[len] = EdgeBlendSample {
5912 x: pos_x,
5913 rgba: [color.get_red(), color.get_green(), color.get_blue(), 255],
5914 sr_a: fill_lin[0] * area_val,
5915 sg_a: fill_lin[1] * area_val,
5916 sb_a: fill_lin[2] * area_val,
5917 inv_a: 1.0 - area_val,
5918 sa_u32: sa as u32,
5919 is_opaque: sa == 255,
5920 };
5921 len += 1;
5922 shaded += 1;
5923 }
5924 continue;
5925 }
5926 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
5927 px.abs() - inner_hw
5928 } else {
5929 2.0
5930 };
5931 if dist < -0.85 && inner_dist > 0.85 {
5932 let bc: Color = border.get_color();
5933 let sa: u8 = bc.get_alpha();
5934 let alpha_val_primary: f32 = (sa as f32) * (1.0 / 255.0);
5935 out[len] = EdgeBlendSample {
5936 x: pos_x,
5937 rgba: [bc.get_red(), bc.get_green(), bc.get_blue(), 255],
5938 sr_a: border_lin[0] * alpha_val_primary,
5939 sg_a: border_lin[1] * alpha_val_primary,
5940 sb_a: border_lin[2] * alpha_val_primary,
5941 inv_a: 1.0 - alpha_val_primary,
5942 sa_u32: sa as u32,
5943 is_opaque: sa == 255,
5944 };
5945 len += 1;
5946 shaded += 1;
5947 continue;
5948 }
5949 let outer_cov: f32 = sdf_coverage(dist, aa);
5950 if outer_cov <= 0.0 {
5951 continue;
5952 }
5953 let inner_cov: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
5954 sdf_coverage(inner_dist, aa)
5955 } else {
5956 0.0
5957 };
5958 let mixed: Color =
5959 composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
5960 let sa: u8 = mixed.get_alpha();
5961 if sa > 0 {
5962 let alpha_val_secondary: f32 = (sa as f32) * (1.0 / 255.0);
5963 out[len] = EdgeBlendSample {
5964 x: pos_x,
5965 rgba: [mixed.get_red(), mixed.get_green(), mixed.get_blue(), 255],
5966 sr_a: SRGB_TO_LIN_LUT[mixed.get_red() as usize] * alpha_val_secondary,
5967 sg_a: SRGB_TO_LIN_LUT[mixed.get_green() as usize] * alpha_val_secondary,
5968 sb_a: SRGB_TO_LIN_LUT[mixed.get_blue() as usize] * alpha_val_secondary,
5969 inv_a: 1.0 - alpha_val_secondary,
5970 sa_u32: sa as u32,
5971 is_opaque: sa == 255,
5972 };
5973 len += 1;
5974 shaded += 1;
5975 }
5976 }
5977 (len, shaded)
5978 }
5979
5980 fn raster_rounded_rect(
5996 band: &mut PixelBand<'_>,
5997 rect: Rect,
5998 color: Color,
5999 radius: CornerRadius,
6000 border: Border,
6001 clip: Rect,
6002 aa: AntialiasingMode,
6003 ) -> usize {
6004 let Some(vis) = rect.intersect(clip) else {
6005 return 0;
6006 };
6007 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_alpha() > 0;
6008 if radius.max_radius() <= 0.0 && !has_border {
6009 return Self::fill_rect_clipped(band, rect, color, clip);
6010 }
6011 if radius.max_radius() <= 0.0 && has_border && aa != AntialiasingMode::Msaa4x {
6012 let border_width: f32 = border.get_width();
6013 let bw_r: f32 = border_width.round();
6014 let rx: f32 = rect.get_x();
6015 let ry: f32 = rect.get_y();
6016 let rw: f32 = rect.get_width();
6017 let rh: f32 = rect.get_height();
6018 let int_aligned: bool = bw_r >= 1.0
6019 && (border_width - bw_r).abs() < 1e-4
6020 && (rx - rx.round()).abs() < 1e-4
6021 && (ry - ry.round()).abs() < 1e-4
6022 && (rw - rw.round()).abs() < 1e-4
6023 && (rh - rh.round()).abs() < 1e-4
6024 && rw >= bw_r * 2.0
6025 && rh >= bw_r * 2.0;
6026 if int_aligned {
6027 let bc: Color = border.get_color();
6028 let exact_border: Color = if bw_r < 2.0 {
6029 let b_lin: [f32; 4] = [
6030 SRGB_TO_LIN_LUT[bc.get_red() as usize],
6031 SRGB_TO_LIN_LUT[bc.get_green() as usize],
6032 SRGB_TO_LIN_LUT[bc.get_blue() as usize],
6033 (bc.get_alpha() as f32) / 255.0,
6034 ];
6035 composite_fill_and_border_precomputed([0.0; 4], b_lin, 1.0, 0.0)
6036 } else {
6037 bc
6038 };
6039 let mut shaded_fast: usize = 0;
6040 shaded_fast +=
6041 Self::fill_rect_clipped(band, Rect::new(rx, ry, rw, bw_r), exact_border, clip);
6042 shaded_fast += Self::fill_rect_clipped(
6043 band,
6044 Rect::new(rx, ry + rh - bw_r, rw, bw_r),
6045 exact_border,
6046 clip,
6047 );
6048 let mid_h: f32 = rh - bw_r * 2.0;
6049 if mid_h > 0.0 {
6050 shaded_fast += Self::fill_rect_clipped(
6051 band,
6052 Rect::new(rx, ry + bw_r, bw_r, mid_h),
6053 exact_border,
6054 clip,
6055 );
6056 shaded_fast += Self::fill_rect_clipped(
6057 band,
6058 Rect::new(rx + rw - bw_r, ry + bw_r, bw_r, mid_h),
6059 exact_border,
6060 clip,
6061 );
6062 let mid_w: f32 = rw - bw_r * 2.0;
6063 if mid_w > 0.0 && color.get_alpha() > 0 {
6064 shaded_fast += Self::fill_rect_clipped(
6065 band,
6066 Rect::new(rx + bw_r, ry + bw_r, mid_w, mid_h),
6067 color,
6068 clip,
6069 );
6070 }
6071 }
6072 return shaded_fast;
6073 }
6074 }
6075 let half_w: f32 = rect.get_width() * 0.5;
6076 let half_h: f32 = rect.get_height() * 0.5;
6077 let cx: f32 = rect.get_x() + half_w;
6078 let cy: f32 = rect.get_y() + half_h;
6079 let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
6080 let fb_w: u32 = band.width();
6081 let band_y0: u32 = band.y_offset();
6082 let band_y1: u32 = band.y_end();
6083 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6084 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6085 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6086 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6087 if x0 >= x1 || y0 >= y1 {
6088 return 0;
6089 }
6090 let effective_r: f32 = radius.max_radius().min(half_w).min(half_h);
6091 let safe_inset: f32 = effective_r.max(border_w) + 1.5;
6092 let edge_inset: f32 = border_w + 1.5;
6093 let iy0: u32 = ((rect.get_y() + safe_inset).ceil().max(0.0) as u32).clamp(y0, y1);
6094 let iy1: u32 = ((rect.bottom() - safe_inset).floor().max(0.0) as u32).clamp(y0, y1);
6095 let ix0: u32 = ((rect.get_x() + edge_inset).ceil().max(0.0) as u32).clamp(x0, x1);
6096 let ix1: u32 = ((rect.right() - edge_inset).floor().max(0.0) as u32).clamp(x0, x1);
6097 let cx0: u32 = ((rect.get_x() + safe_inset).ceil().max(0.0) as u32).clamp(x0, x1);
6098 let cx1: u32 = ((rect.right() - safe_inset).floor().max(0.0) as u32).clamp(x0, x1);
6099 let has_interior: bool = iy0 < iy1 && ix0 < ix1;
6100 let has_center_band: bool = cx0 < cx1;
6101 let fill_lin: [f32; 4] = [
6102 SRGB_TO_LIN_LUT[color.get_red() as usize],
6103 SRGB_TO_LIN_LUT[color.get_green() as usize],
6104 SRGB_TO_LIN_LUT[color.get_blue() as usize],
6105 (color.get_alpha() as f32) / 255.0,
6106 ];
6107 let bc: Color = border.get_color();
6108 let border_lin: [f32; 4] = [
6109 SRGB_TO_LIN_LUT[bc.get_red() as usize],
6110 SRGB_TO_LIN_LUT[bc.get_green() as usize],
6111 SRGB_TO_LIN_LUT[bc.get_blue() as usize],
6112 (bc.get_alpha() as f32) / 255.0,
6113 ];
6114 let interior_luts: Option<[[u8; 256]; 4]> = if has_interior
6115 && color.get_alpha() > 0
6116 && color.get_alpha() < 255
6117 && ((ix1 - ix0) as usize).saturating_mul((iy1 - iy0) as usize) >= 512
6118 {
6119 Some(build_linear_blend_luts(color))
6120 } else {
6121 None
6122 };
6123 let mut shaded: usize = 0;
6124 if has_interior {
6125 for pos_y in y0..iy0 {
6126 let py: f32 = (pos_y as f32) + 0.5 - cy;
6127 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6128 if has_center_band {
6129 shaded += Self::raster_rounded_corner_band_row(
6130 band,
6131 pos_y,
6132 (x0, cx0, cx1, x1),
6133 box_geom,
6134 radius,
6135 (color, border, fill_lin, border_lin),
6136 (interior_luts.as_ref(), aa),
6137 );
6138 } else if let Some(row) = band.row_slice_mut(pos_y) {
6139 for pos_x in x0..x1 {
6140 shaded += Self::shade_rounded_pixel_row(
6141 row,
6142 pos_x,
6143 box_geom,
6144 radius,
6145 (color, border, fill_lin, border_lin),
6146 aa,
6147 );
6148 }
6149 }
6150 }
6151 let use_1d_strip: bool = ((ix0 - x0) as usize) <= ROUNDED_EDGE_STRIP_CAP
6152 && ((x1 - ix1) as usize) <= ROUNDED_EDGE_STRIP_CAP;
6153 if use_1d_strip {
6154 let mut left_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
6155 [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
6156 let mut right_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
6157 [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
6158 let (left_len, left_shaded): (usize, usize) = if x0 < ix0 {
6159 Self::build_vertical_edge_strip(
6160 (x0, ix0),
6161 (cx, half_w, half_h, border_w),
6162 (color, border),
6163 (fill_lin, border_lin),
6164 aa,
6165 &mut left_strip,
6166 )
6167 } else {
6168 (0, 0)
6169 };
6170 let (right_len, right_shaded): (usize, usize) = if ix1 < x1 {
6171 Self::build_vertical_edge_strip(
6172 (ix1, x1),
6173 (cx, half_w, half_h, border_w),
6174 (color, border),
6175 (fill_lin, border_lin),
6176 aa,
6177 &mut right_strip,
6178 )
6179 } else {
6180 (0, 0)
6181 };
6182 let left_slice: &[EdgeBlendSample] = &left_strip[..left_len];
6183 let right_slice: &[EdgeBlendSample] = &right_strip[..right_len];
6184 let edge_shaded: usize = left_shaded + right_shaded;
6185 let has_edges: bool = left_len > 0 || right_len > 0;
6186 let fill_visible: bool = color.get_alpha() > 0;
6187 let fill_opaque: bool = color.get_alpha() == 255;
6188 let fill_rgba: [u8; 4] =
6189 [color.get_red(), color.get_green(), color.get_blue(), 255];
6190 let interior_span: usize = (ix1 - ix0) as usize;
6191 let ix0_b: usize = (ix0 as usize) * 4;
6192 let ix1_b: usize = (ix1 as usize) * 4;
6193 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
6194 for row in rows_buf.chunks_exact_mut(row_stride) {
6195 if fill_visible {
6196 if fill_opaque {
6197 fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
6198 } else if let Some(ref luts) = interior_luts {
6199 fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
6200 } else {
6201 fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
6202 }
6203 shaded += interior_span;
6204 }
6205 if has_edges {
6206 if left_len > 0 {
6207 apply_edge_strip_row(row, left_slice);
6208 }
6209 if right_len > 0 {
6210 apply_edge_strip_row(row, right_slice);
6211 }
6212 shaded += edge_shaded;
6213 }
6214 }
6215 }
6216 } else {
6217 let fill_visible: bool = color.get_alpha() > 0;
6218 let fill_opaque: bool = color.get_alpha() == 255;
6219 let fill_rgba: [u8; 4] =
6220 [color.get_red(), color.get_green(), color.get_blue(), 255];
6221 let interior_span: usize = (ix1 - ix0) as usize;
6222 let ix0_b: usize = (ix0 as usize) * 4;
6223 let ix1_b: usize = (ix1 as usize) * 4;
6224 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
6225 for (coord_y, row) in (iy0..iy1).zip(rows_buf.chunks_exact_mut(row_stride)) {
6226 let py: f32 = (coord_y as f32) + 0.5 - cy;
6227 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6228 if fill_visible {
6229 if fill_opaque {
6230 fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
6231 } else if let Some(ref luts) = interior_luts {
6232 fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
6233 } else {
6234 fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
6235 }
6236 shaded += interior_span;
6237 }
6238 for coord_x in x0..ix0 {
6239 shaded += Self::shade_rounded_pixel_row(
6240 row,
6241 coord_x,
6242 box_geom,
6243 radius,
6244 (color, border, fill_lin, border_lin),
6245 aa,
6246 );
6247 }
6248 for sample_x in ix1..x1 {
6249 shaded += Self::shade_rounded_pixel_row(
6250 row,
6251 sample_x,
6252 box_geom,
6253 radius,
6254 (color, border, fill_lin, border_lin),
6255 aa,
6256 );
6257 }
6258 }
6259 }
6260 }
6261 for sample_y in iy1..y1 {
6262 let py: f32 = (sample_y as f32) + 0.5 - cy;
6263 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6264 if has_center_band {
6265 shaded += Self::raster_rounded_corner_band_row(
6266 band,
6267 sample_y,
6268 (x0, cx0, cx1, x1),
6269 box_geom,
6270 radius,
6271 (color, border, fill_lin, border_lin),
6272 (interior_luts.as_ref(), aa),
6273 );
6274 } else if let Some(row) = band.row_slice_mut(sample_y) {
6275 for value_x in x0..x1 {
6276 shaded += Self::shade_rounded_pixel_row(
6277 row,
6278 value_x,
6279 box_geom,
6280 radius,
6281 (color, border, fill_lin, border_lin),
6282 aa,
6283 );
6284 }
6285 }
6286 }
6287 return shaded;
6288 }
6289 for value_y in y0..y1 {
6290 let py: f32 = (value_y as f32) + 0.5 - cy;
6291 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6292 if has_center_band {
6293 shaded += Self::raster_rounded_corner_band_row(
6294 band,
6295 value_y,
6296 (x0, cx0, cx1, x1),
6297 box_geom,
6298 radius,
6299 (color, border, fill_lin, border_lin),
6300 (interior_luts.as_ref(), aa),
6301 );
6302 } else if let Some(row) = band.row_slice_mut(value_y) {
6303 for pos_x_primary in x0..x1 {
6304 shaded += Self::shade_rounded_pixel_row(
6305 row,
6306 pos_x_primary,
6307 box_geom,
6308 radius,
6309 (color, border, fill_lin, border_lin),
6310 aa,
6311 );
6312 }
6313 }
6314 }
6315 shaded
6316 }
6317
6318 #[inline(always)]
6334 fn raster_rounded_corner_band_row(
6335 band: &mut PixelBand<'_>,
6336 pos_y: u32,
6337 x_bounds: (u32, u32, u32, u32),
6338 geom: (f32, f32, f32, f32),
6339 radius: CornerRadius,
6340 style_colors: (Color, Border, [f32; 4], [f32; 4]),
6341 opts: (Option<&[[u8; 256]; 4]>, AntialiasingMode),
6342 ) -> usize {
6343 let (interior_luts, aa): (Option<&[[u8; 256]; 4]>, AntialiasingMode) = opts;
6344 let Some(row) = band.row_slice_mut(pos_y) else {
6345 return 0;
6346 };
6347 let (x0, cx0, cx1, x1): (u32, u32, u32, u32) = x_bounds;
6348 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
6349 let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
6350 style_colors;
6351 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_alpha() > 0;
6352 let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
6353 let inner_thresh: f32 = if has_border {
6354 -(border_w + 0.85)
6355 } else {
6356 -0.85
6357 };
6358 let py_abs: f32 = py.abs();
6359 let fill_visible: bool = color.get_alpha() > 0;
6360 let fill_opaque: bool = color.get_alpha() == 255;
6361 let fill_rgba: [u8; 4] = [color.get_red(), color.get_green(), color.get_blue(), 255];
6362 let mut shaded: usize = 0;
6363 if x0 < cx0 {
6364 let pure_left: bool = ((cx0 - 1) as f32) + 0.5 < cx;
6365 if pure_left {
6366 let r_l: f32 = (if py < 0.0 {
6367 radius.get_top_left()
6368 } else {
6369 radius.get_bottom_left()
6370 })
6371 .min(half_w)
6372 .min(half_h)
6373 .max(0.0);
6374 let qy: f32 = py_abs - half_h + r_l;
6375 let r_out: f32 = r_l + 0.85;
6376 if qy <= r_out + 0.05 {
6377 let vis_l0: u32 = if qy > 0.0 {
6378 let max_vis_abs: f32 =
6379 (half_w - r_l) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
6380 ((cx - max_vis_abs - 0.5).floor().max(0.0) as u32).clamp(x0, cx0)
6381 } else {
6382 x0
6383 };
6384 let r_in: f32 = r_l + inner_thresh;
6385 let max_in_abs: f32 = if qy <= 0.0 {
6386 if qy < r_in - 0.05 {
6387 half_w + inner_thresh - 1.0
6388 } else {
6389 -1.0
6390 }
6391 } else if r_in > 0.0 && qy < r_in - 0.05 {
6392 (half_w - r_l) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
6393 } else {
6394 -1.0
6395 };
6396 let in_l0: u32 = if max_in_abs > 0.0 {
6397 ((cx - max_in_abs - 0.5).ceil().max(0.0) as u32).clamp(vis_l0, cx0)
6398 } else {
6399 cx0
6400 };
6401 for pos_x in vis_l0..in_l0 {
6402 shaded += Self::shade_rounded_pixel_row(
6403 row,
6404 pos_x,
6405 geom,
6406 radius,
6407 style_colors,
6408 aa,
6409 );
6410 }
6411 if in_l0 < cx0 && fill_visible {
6412 let b0: usize = (in_l0 as usize) * 4;
6413 let b1: usize = (cx0 as usize) * 4;
6414 if fill_opaque {
6415 fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
6416 } else if let Some(luts) = interior_luts {
6417 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6418 } else {
6419 fill_span_linear_slice(&mut row[b0..b1], color);
6420 }
6421 shaded += (cx0 - in_l0) as usize;
6422 }
6423 }
6424 } else {
6425 for coord_x in x0..cx0 {
6426 shaded +=
6427 Self::shade_rounded_pixel_row(row, coord_x, geom, radius, style_colors, aa);
6428 }
6429 }
6430 }
6431 if cx1 < x1 {
6432 let pure_right: bool = (cx1 as f32) + 0.5 >= cx;
6433 if pure_right {
6434 let r_r: f32 = (if py < 0.0 {
6435 radius.get_top_right()
6436 } else {
6437 radius.get_bottom_right()
6438 })
6439 .min(half_w)
6440 .min(half_h)
6441 .max(0.0);
6442 let qy: f32 = py_abs - half_h + r_r;
6443 let r_out: f32 = r_r + 0.85;
6444 if qy <= r_out + 0.05 {
6445 let vis_r1: u32 = if qy > 0.0 {
6446 let max_vis_abs: f32 =
6447 (half_w - r_r) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
6448 ((cx + max_vis_abs + 0.5).ceil().max(0.0) as u32).clamp(cx1, x1)
6449 } else {
6450 x1
6451 };
6452 let r_in: f32 = r_r + inner_thresh;
6453 let max_in_abs: f32 = if qy <= 0.0 {
6454 if qy < r_in - 0.05 {
6455 half_w + inner_thresh - 1.0
6456 } else {
6457 -1.0
6458 }
6459 } else if r_in > 0.0 && qy < r_in - 0.05 {
6460 (half_w - r_r) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
6461 } else {
6462 -1.0
6463 };
6464 let in_r1: u32 = if max_in_abs > 0.0 {
6465 ((cx + max_in_abs - 0.5).floor().max(0.0) as u32).clamp(cx1, vis_r1)
6466 } else {
6467 cx1
6468 };
6469 if cx1 < in_r1 && fill_visible {
6470 let b0: usize = (cx1 as usize) * 4;
6471 let b1: usize = (in_r1 as usize) * 4;
6472 if fill_opaque {
6473 fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
6474 } else if let Some(luts) = interior_luts {
6475 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6476 } else {
6477 fill_span_linear_slice(&mut row[b0..b1], color);
6478 }
6479 shaded += (in_r1 - cx1) as usize;
6480 }
6481 for sample_x in in_r1..vis_r1 {
6482 shaded += Self::shade_rounded_pixel_row(
6483 row,
6484 sample_x,
6485 geom,
6486 radius,
6487 style_colors,
6488 aa,
6489 );
6490 }
6491 }
6492 } else {
6493 for value_x in cx1..x1 {
6494 shaded +=
6495 Self::shade_rounded_pixel_row(row, value_x, geom, radius, style_colors, aa);
6496 }
6497 }
6498 }
6499 let dist_y: f32 = py_abs - half_h;
6500 let outer_cov: f32 = sdf_coverage(dist_y, aa);
6501 if outer_cov > 0.0 {
6502 let b0: usize = (cx0 as usize) * 4;
6503 let b1: usize = (cx1 as usize) * 4;
6504 if has_border {
6505 let inner_hh: f32 = (half_h - border_w).max(0.0);
6506 let inner_cov: f32 = if inner_hh > 0.0 && half_w > border_w {
6507 sdf_coverage(py_abs - inner_hh, aa)
6508 } else {
6509 0.0
6510 };
6511 let mixed: Color = composite_fill_and_border_precomputed(
6512 fill_lin, border_lin, outer_cov, inner_cov,
6513 );
6514 if mixed.get_alpha() > 0 {
6515 fill_span_linear_slice(&mut row[b0..b1], mixed);
6516 }
6517 shaded += (cx1 - cx0) as usize;
6518 } else if fill_visible {
6519 let row_color: Color = color.multiply_alpha(outer_cov);
6520 if row_color == color
6521 && let Some(luts) = interior_luts
6522 {
6523 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6524 } else {
6525 fill_span_linear_slice(&mut row[b0..b1], row_color);
6526 }
6527 shaded += (cx1 - cx0) as usize;
6528 }
6529 }
6530 shaded
6531 }
6532
6533 #[inline(always)]
6548 fn shade_rounded_pixel_row(
6549 row: &mut [u8],
6550 pos_x: u32,
6551 geom: (f32, f32, f32, f32),
6552 radius: CornerRadius,
6553 style_colors: (Color, Border, [f32; 4], [f32; 4]),
6554 aa: AntialiasingMode,
6555 ) -> usize {
6556 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
6557 let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
6558 style_colors;
6559 let fill_rgb: [f32; 3] = [fill_lin[0], fill_lin[1], fill_lin[2]];
6560 let px: f32 = (pos_x as f32) + 0.5 - cx;
6561 let corner_r: f32 = quadrant_corner_radius(radius, px, py)
6562 .min(half_w)
6563 .min(half_h);
6564 let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
6565 if dist > 0.85 {
6566 return 0;
6567 }
6568 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_alpha() > 0;
6569 let border_width: f32 = if has_border { border.get_width() } else { 0.0 };
6570 if !has_border {
6571 if dist < -0.85 {
6572 if color.get_alpha() > 0 {
6573 blend_row_pixel_linear_precomputed(row, pos_x, color, fill_rgb);
6574 return 1;
6575 }
6576 return 0;
6577 }
6578 let in_corner_edge: bool = aa != AntialiasingMode::None
6579 && corner_r > 0.5
6580 && px.abs() > (half_w - corner_r - 1.5)
6581 && py.abs() > (half_h - corner_r - 1.5);
6582 let outer_cov: f32 = if in_corner_edge {
6583 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
6584 } else {
6585 sdf_coverage(dist, aa)
6586 };
6587 if outer_cov > 0.0 && color.get_alpha() > 0 {
6588 let alpha_f: f32 = ((color.get_alpha() as f32) * (1.0 / 255.0)) * outer_cov;
6589 blend_row_pixel_f32_precomputed(row, pos_x, color, fill_rgb, alpha_f);
6590 return 1;
6591 }
6592 return 0;
6593 }
6594 if dist < -(border_width + 0.85) {
6595 if color.get_alpha() > 0 {
6596 blend_row_pixel_linear_precomputed(row, pos_x, color, fill_rgb);
6597 return 1;
6598 }
6599 return 0;
6600 }
6601 let inner_hw: f32 = (half_w - border_width).max(0.0);
6602 let inner_hh: f32 = (half_h - border_width).max(0.0);
6603 let inner_r: f32 = (corner_r - border_width).max(0.0);
6604 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6605 rounded_box_sdf(px, py, inner_hw, inner_hh, inner_r)
6606 } else {
6607 2.0
6608 };
6609 if dist < -0.85 && inner_dist > 0.85 {
6610 let border_rgb: [f32; 3] = [border_lin[0], border_lin[1], border_lin[2]];
6611 blend_row_pixel_linear_precomputed(row, pos_x, border.get_color(), border_rgb);
6612 return 1;
6613 }
6614 let in_corner_zone: bool = aa != AntialiasingMode::None
6615 && corner_r > 0.5
6616 && px.abs() > (half_w - corner_r - 1.5)
6617 && py.abs() > (half_h - corner_r - 1.5);
6618 let (outer_cov, inner_cov): (f32, f32) = if in_corner_zone {
6619 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, border_width)
6620 } else {
6621 let oc: f32 = sdf_coverage(dist, aa);
6622 if oc <= 0.0 {
6623 return 0;
6624 }
6625 let ic: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6626 sdf_coverage(inner_dist, aa)
6627 } else {
6628 0.0
6629 };
6630 (oc, ic)
6631 };
6632 if outer_cov <= 0.0 {
6633 return 0;
6634 }
6635 let mixed: Color =
6636 composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
6637 if mixed.get_alpha() > 0 {
6638 let mixed_rgb: [f32; 3] = [
6639 SRGB_TO_LIN_LUT[mixed.get_red() as usize],
6640 SRGB_TO_LIN_LUT[mixed.get_green() as usize],
6641 SRGB_TO_LIN_LUT[mixed.get_blue() as usize],
6642 ];
6643 blend_row_pixel_linear_precomputed(row, pos_x, mixed, mixed_rgb);
6644 return 1;
6645 }
6646 0
6647 }
6648
6649 #[inline(always)]
6662 fn fill_vertical_gradient_span(
6663 band: &mut PixelBand<'_>,
6664 coords: (u32, u32, u32),
6665 sample: Color,
6666 cov: f32,
6667 ) -> usize {
6668 let (sx0, sx1, pos_y): (u32, u32, u32) = coords;
6669 if sx0 >= sx1 || cov <= 0.0 {
6670 return 0;
6671 }
6672 let alpha_f: f32 = ((sample.get_alpha() as f32) * (1.0 / 255.0)) * cov;
6673 if alpha_f >= 0.9995 {
6674 band.fill_span(
6675 sx0,
6676 sx1,
6677 pos_y,
6678 Color::new(sample.get_red(), sample.get_green(), sample.get_blue(), 255),
6679 );
6680 } else if alpha_f > 0.0005 {
6681 band.blend_shadow_span_const_alpha(sx0, sx1, pos_y, sample, alpha_f);
6682 } else if alpha_f > 0.0002
6683 && let Some(row) = band.row_slice_mut(pos_y)
6684 {
6685 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
6686 for pos_x in sx0..sx1 {
6687 blend_gradient_row_pixel(row, pos_x, y_term, sample, cov);
6688 }
6689 }
6690 (sx1 - sx0) as usize
6691 }
6692
6693 #[inline(always)]
6706 fn fill_angled_gradient_span(
6707 row: &mut [u8],
6708 coords: (u32, u32, f32),
6709 step: (f32, f32, f32),
6710 stops: (Color, Color),
6711 ) -> usize {
6712 let (sx0, sx1, y_term): (u32, u32, f32) = coords;
6713 let (t_start, dt_dx, cov): (f32, f32, f32) = step;
6714 let (start_c, end_c): (Color, Color) = stops;
6715 if sx0 >= sx1 || cov <= 0.0 {
6716 return 0;
6717 }
6718 let byte_start: usize = (sx0 as usize) * 4;
6719 let byte_end: usize = (sx1 as usize) * 4;
6720 if byte_end > row.len() {
6721 return 0;
6722 }
6723 let sr_f: f32 = start_c.get_red() as f32;
6724 let sg_f: f32 = start_c.get_green() as f32;
6725 let sb_f: f32 = start_c.get_blue() as f32;
6726 let er_f: f32 = end_c.get_red() as f32;
6727 let eg_f: f32 = end_c.get_green() as f32;
6728 let eb_f: f32 = end_c.get_blue() as f32;
6729 let both_opaque: bool = start_c.get_alpha() == 255 && end_c.get_alpha() == 255;
6730 let mut t_cur: f32 = t_start;
6731 if both_opaque && cov >= 0.9995 {
6732 let chunks: &mut [[u8; 4]] = row[byte_start..byte_end].as_chunks_mut::<4>().0;
6733 for px in chunks.iter_mut() {
6734 let factor_val: f32 = t_cur.clamp(0.0, 1.0);
6735 let inv: f32 = 1.0 - factor_val;
6736 px[0] = (sr_f * inv + er_f * factor_val + 0.5) as u8;
6737 px[1] = (sg_f * inv + eg_f * factor_val + 0.5) as u8;
6738 px[2] = (sb_f * inv + eb_f * factor_val + 0.5) as u8;
6739 px[3] = 255;
6740 t_cur += dt_dx;
6741 }
6742 return (sx1 - sx0) as usize;
6743 }
6744 let sa_f: f32 = start_c.get_alpha() as f32;
6745 let ea_f: f32 = end_c.get_alpha() as f32;
6746 for pos_x in sx0..sx1 {
6747 let callback_ref: f32 = t_cur.clamp(0.0, 1.0);
6748 let inv: f32 = 1.0 - callback_ref;
6749 let sample: Color = Color::new(
6750 (sr_f * inv + er_f * callback_ref + 0.5) as u8,
6751 (sg_f * inv + eg_f * callback_ref + 0.5) as u8,
6752 (sb_f * inv + eb_f * callback_ref + 0.5) as u8,
6753 (sa_f * inv + ea_f * callback_ref + 0.5) as u8,
6754 );
6755 blend_gradient_row_pixel(row, pos_x, y_term, sample, cov);
6756 t_cur += dt_dx;
6757 }
6758 (sx1 - sx0) as usize
6759 }
6760
6761 fn raster_gradient_rect(
6776 band: &mut PixelBand<'_>,
6777 rect: Rect,
6778 gradient: LinearGradient,
6779 radius: CornerRadius,
6780 clip: Rect,
6781 aa: AntialiasingMode,
6782 ) -> usize {
6783 let Some(vis) = rect.intersect(clip) else {
6784 return 0;
6785 };
6786 let fb_w: u32 = band.width();
6787 let band_y0: u32 = band.y_offset();
6788 let band_y1: u32 = band.y_end();
6789 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6790 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6791 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6792 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6793 if x0 >= x1 || y0 >= y1 {
6794 return 0;
6795 }
6796 let rad: f32 = gradient.get_angle_deg().to_radians();
6797 let dir_x: f32 = rad.sin();
6798 let dir_y: f32 = rad.cos();
6799 let start_c: Color = gradient.get_start_color();
6800 let end_c: Color = gradient.get_end_color();
6801 let half_w: f32 = rect.get_width() * 0.5;
6802 let half_h: f32 = rect.get_height() * 0.5;
6803 let cx: f32 = rect.get_x() + half_w;
6804 let cy: f32 = rect.get_y() + half_h;
6805 let inv_w: f32 = if rect.get_width() > 0.0 {
6806 1.0 / rect.get_width()
6807 } else {
6808 0.0
6809 };
6810 let inv_h: f32 = if rect.get_height() > 0.0 {
6811 1.0 / rect.get_height()
6812 } else {
6813 0.0
6814 };
6815 let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
6816 let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
6817 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
6818 let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
6819 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
6820 let cx0: u32 = ((rect.get_x() + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
6821 let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
6822 let is_vertical: bool = dir_x.abs() < 1e-5;
6823 let dt_dx: f32 = inv_w * dir_x;
6824 let rect_x: f32 = rect.get_x();
6825 let rect_y: f32 = rect.get_y();
6826 let mut shaded: usize = 0;
6827 if is_vertical {
6828 for pos_y in y0..iy0 {
6829 let py: f32 = (pos_y as f32) + 0.5 - cy;
6830 let ny: f32 = ((pos_y as f32) - rect_y) * inv_h;
6831 let blend_factor: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
6832 let sample: Color = start_c.lerp(end_c, blend_factor);
6833 let dist_y: f32 = py.abs() - half_h;
6834 let mid_cov: f32 = if dist_y > 0.85 {
6835 0.0
6836 } else if dist_y < -0.85 {
6837 1.0
6838 } else {
6839 sdf_coverage(dist_y, aa)
6840 };
6841 if cx0 < cx1 && mid_cov > 0.0 {
6842 shaded +=
6843 Self::fill_vertical_gradient_span(band, (cx0, cx1, pos_y), sample, mid_cov);
6844 }
6845 if (x0 < cx0 || cx1 < x1)
6846 && let Some(row) = band.row_slice_mut(pos_y)
6847 {
6848 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
6849 for pos_x in x0..cx0 {
6850 let px: f32 = (pos_x as f32) + 0.5 - cx;
6851 let cov: f32 =
6852 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
6853 if cov > 0.0 {
6854 blend_gradient_row_pixel(row, pos_x, y_term, sample, cov);
6855 shaded += 1;
6856 }
6857 }
6858 for coord_x in cx1..x1 {
6859 let px: f32 = (coord_x as f32) + 0.5 - cx;
6860 let cov: f32 =
6861 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
6862 if cov > 0.0 {
6863 blend_gradient_row_pixel(row, coord_x, y_term, sample, cov);
6864 shaded += 1;
6865 }
6866 }
6867 }
6868 }
6869 for coord_y in iy0..iy1 {
6870 let ny: f32 = ((coord_y as f32) - rect_y) * inv_h;
6871 let time_step: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
6872 let sample: Color = start_c.lerp(end_c, time_step);
6873 if ix0 < ix1 {
6874 shaded +=
6875 Self::fill_vertical_gradient_span(band, (ix0, ix1, coord_y), sample, 1.0);
6876 }
6877 if (x0 < ix0 || ix1 < x1)
6878 && let Some(row) = band.row_slice_mut(coord_y)
6879 {
6880 let y_term: f32 = (coord_y as f32) * 0.005_837_15;
6881 for sample_x in x0..ix0 {
6882 let dist: f32 = ((sample_x as f32) + 0.5 - cx).abs() - half_w;
6883 if dist <= 0.85 {
6884 let cov: f32 = if dist < -0.85 {
6885 1.0
6886 } else {
6887 sdf_coverage(dist, aa)
6888 };
6889 if cov > 0.0 {
6890 blend_gradient_row_pixel(row, sample_x, y_term, sample, cov);
6891 shaded += 1;
6892 }
6893 }
6894 }
6895 for value_x in ix1..x1 {
6896 let dist: f32 = ((value_x as f32) + 0.5 - cx).abs() - half_w;
6897 if dist <= 0.85 {
6898 let cov: f32 = if dist < -0.85 {
6899 1.0
6900 } else {
6901 sdf_coverage(dist, aa)
6902 };
6903 if cov > 0.0 {
6904 blend_gradient_row_pixel(row, value_x, y_term, sample, cov);
6905 shaded += 1;
6906 }
6907 }
6908 }
6909 }
6910 }
6911 for sample_y in iy1..y1 {
6912 let py: f32 = (sample_y as f32) + 0.5 - cy;
6913 let ny: f32 = ((sample_y as f32) - rect_y) * inv_h;
6914 let token_val: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
6915 let sample: Color = start_c.lerp(end_c, token_val);
6916 let dist_y: f32 = py.abs() - half_h;
6917 let mid_cov: f32 = if dist_y > 0.85 {
6918 0.0
6919 } else if dist_y < -0.85 {
6920 1.0
6921 } else {
6922 sdf_coverage(dist_y, aa)
6923 };
6924 if cx0 < cx1 && mid_cov > 0.0 {
6925 shaded += Self::fill_vertical_gradient_span(
6926 band,
6927 (cx0, cx1, sample_y),
6928 sample,
6929 mid_cov,
6930 );
6931 }
6932 if (x0 < cx0 || cx1 < x1)
6933 && let Some(row) = band.row_slice_mut(sample_y)
6934 {
6935 let y_term: f32 = (sample_y as f32) * 0.005_837_15;
6936 for pos_x_primary in x0..cx0 {
6937 let px: f32 = (pos_x_primary as f32) + 0.5 - cx;
6938 let cov: f32 =
6939 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
6940 if cov > 0.0 {
6941 blend_gradient_row_pixel(row, pos_x_primary, y_term, sample, cov);
6942 shaded += 1;
6943 }
6944 }
6945 for pos_x_secondary in cx1..x1 {
6946 let px: f32 = (pos_x_secondary as f32) + 0.5 - cx;
6947 let cov: f32 =
6948 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
6949 if cov > 0.0 {
6950 blend_gradient_row_pixel(row, pos_x_secondary, y_term, sample, cov);
6951 shaded += 1;
6952 }
6953 }
6954 }
6955 }
6956 return shaded;
6957 }
6958 for value_y in y0..iy0 {
6959 let Some(row) = band.row_slice_mut(value_y) else {
6960 continue;
6961 };
6962 let py: f32 = (value_y as f32) + 0.5 - cy;
6963 let ny: f32 = ((value_y as f32) - rect_y) * inv_h;
6964 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
6965 let y_term: f32 = (value_y as f32) * 0.005_837_15;
6966 let dist_y: f32 = py.abs() - half_h;
6967 let mid_cov: f32 = if dist_y > 0.85 {
6968 0.0
6969 } else if dist_y < -0.85 {
6970 1.0
6971 } else {
6972 sdf_coverage(dist_y, aa)
6973 };
6974 if cx0 < cx1 && mid_cov > 0.0 {
6975 let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
6976 shaded += Self::fill_angled_gradient_span(
6977 row,
6978 (cx0, cx1, y_term),
6979 (t_start, dt_dx, mid_cov),
6980 (start_c, end_c),
6981 );
6982 }
6983 for pos_x_next in x0..cx0 {
6984 let px: f32 = (pos_x_next as f32) + 0.5 - cx;
6985 let cov: f32 =
6986 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
6987 if cov > 0.0 {
6988 let nx: f32 = ((pos_x_next as f32) - rect_x) * inv_w;
6989 let target_val: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
6990 blend_gradient_row_pixel(
6991 row,
6992 pos_x_next,
6993 y_term,
6994 start_c.lerp(end_c, target_val),
6995 cov,
6996 );
6997 shaded += 1;
6998 }
6999 }
7000 for pos_x_alt in cx1..x1 {
7001 let px: f32 = (pos_x_alt as f32) + 0.5 - cx;
7002 let cov: f32 =
7003 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7004 if cov > 0.0 {
7005 let nx: f32 = ((pos_x_alt as f32) - rect_x) * inv_w;
7006 let blend_factor_primary: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7007 blend_gradient_row_pixel(
7008 row,
7009 pos_x_alt,
7010 y_term,
7011 start_c.lerp(end_c, blend_factor_primary),
7012 cov,
7013 );
7014 shaded += 1;
7015 }
7016 }
7017 }
7018 for pos_y_primary in iy0..iy1 {
7019 let Some(row) = band.row_slice_mut(pos_y_primary) else {
7020 continue;
7021 };
7022 let ny: f32 = ((pos_y_primary as f32) - rect_y) * inv_h;
7023 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
7024 let y_term: f32 = (pos_y_primary as f32) * 0.005_837_15;
7025 if ix0 < ix1 {
7026 let t_start: f32 = (((ix0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
7027 shaded += Self::fill_angled_gradient_span(
7028 row,
7029 (ix0, ix1, y_term),
7030 (t_start, dt_dx, 1.0),
7031 (start_c, end_c),
7032 );
7033 }
7034 for pos_x_inner in x0..ix0 {
7035 let dist: f32 = ((pos_x_inner as f32) + 0.5 - cx).abs() - half_w;
7036 if dist <= 0.85 {
7037 let cov: f32 = if dist < -0.85 {
7038 1.0
7039 } else {
7040 sdf_coverage(dist, aa)
7041 };
7042 if cov > 0.0 {
7043 let nx: f32 = ((pos_x_inner as f32) - rect_x) * inv_w;
7044 let blend_factor_secondary: f32 =
7045 ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7046 blend_gradient_row_pixel(
7047 row,
7048 pos_x_inner,
7049 y_term,
7050 start_c.lerp(end_c, blend_factor_secondary),
7051 cov,
7052 );
7053 shaded += 1;
7054 }
7055 }
7056 }
7057 for pos_x_local in ix1..x1 {
7058 let dist: f32 = ((pos_x_local as f32) + 0.5 - cx).abs() - half_w;
7059 if dist <= 0.85 {
7060 let cov: f32 = if dist < -0.85 {
7061 1.0
7062 } else {
7063 sdf_coverage(dist, aa)
7064 };
7065 if cov > 0.0 {
7066 let nx: f32 = ((pos_x_local as f32) - rect_x) * inv_w;
7067 let blend_factor_next: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7068 blend_gradient_row_pixel(
7069 row,
7070 pos_x_local,
7071 y_term,
7072 start_c.lerp(end_c, blend_factor_next),
7073 cov,
7074 );
7075 shaded += 1;
7076 }
7077 }
7078 }
7079 }
7080 for pos_y_secondary in iy1..y1 {
7081 let Some(row) = band.row_slice_mut(pos_y_secondary) else {
7082 continue;
7083 };
7084 let py: f32 = (pos_y_secondary as f32) + 0.5 - cy;
7085 let ny: f32 = ((pos_y_secondary as f32) - rect_y) * inv_h;
7086 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
7087 let y_term: f32 = (pos_y_secondary as f32) * 0.005_837_15;
7088 let dist_y: f32 = py.abs() - half_h;
7089 let mid_cov: f32 = if dist_y > 0.85 {
7090 0.0
7091 } else if dist_y < -0.85 {
7092 1.0
7093 } else {
7094 sdf_coverage(dist_y, aa)
7095 };
7096 if cx0 < cx1 && mid_cov > 0.0 {
7097 let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
7098 shaded += Self::fill_angled_gradient_span(
7099 row,
7100 (cx0, cx1, y_term),
7101 (t_start, dt_dx, mid_cov),
7102 (start_c, end_c),
7103 );
7104 }
7105 for pos_x_cur in x0..cx0 {
7106 let px: f32 = (pos_x_cur as f32) + 0.5 - cx;
7107 let cov: f32 =
7108 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7109 if cov > 0.0 {
7110 let nx: f32 = ((pos_x_cur as f32) - rect_x) * inv_w;
7111 let blend_factor_alt: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7112 blend_gradient_row_pixel(
7113 row,
7114 pos_x_cur,
7115 y_term,
7116 start_c.lerp(end_c, blend_factor_alt),
7117 cov,
7118 );
7119 shaded += 1;
7120 }
7121 }
7122 for pos_x_slot in cx1..x1 {
7123 let px: f32 = (pos_x_slot as f32) + 0.5 - cx;
7124 let cov: f32 =
7125 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7126 if cov > 0.0 {
7127 let nx: f32 = ((pos_x_slot as f32) - rect_x) * inv_w;
7128 let blend_factor_inner: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7129 blend_gradient_row_pixel(
7130 row,
7131 pos_x_slot,
7132 y_term,
7133 start_c.lerp(end_c, blend_factor_inner),
7134 cov,
7135 );
7136 shaded += 1;
7137 }
7138 }
7139 }
7140 shaded
7141 }
7142
7143 #[must_use]
7156 fn shadow_row_cutout(pos_y: u32, cutouts: (Rect, Rect), x0: u32, x1: u32) -> (u32, u32) {
7157 let (cut_h, cut_v): (Rect, Rect) = cutouts;
7158 let yf: f32 = (pos_y as f32) + 0.5;
7159 if cut_h.get_width() > 0.0
7160 && cut_h.get_height() > 0.0
7161 && yf >= cut_h.get_y()
7162 && yf < cut_h.bottom()
7163 {
7164 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
7165 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, x1);
7166 return (cx0, cx1);
7167 }
7168 if cut_v.get_width() > 0.0
7169 && cut_v.get_height() > 0.0
7170 && yf >= cut_v.get_y()
7171 && yf < cut_v.bottom()
7172 {
7173 let cx0: u32 = (cut_v.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
7174 let cx1: u32 = (cut_v.right().floor().max(0.0) as u32).clamp(cx0, x1);
7175 return (cx0, cx1);
7176 }
7177 (x1, x1)
7178 }
7179
7180 #[inline(always)]
7194 fn raster_shadow_middle_span(
7195 band: &mut PixelBand<'_>,
7196 ctx: &ShadowRenderContext,
7197 pos_y: u32,
7198 cutout: (u32, u32),
7199 mid_alpha: f32,
7200 ) -> usize {
7201 if !ctx.has_mid_x || mid_alpha <= 0.0005 {
7202 return 0;
7203 }
7204 let (cut0, cut1): (u32, u32) = cutout;
7205 let sx0: u32 = ctx.lx1;
7206 let sx1: u32 = ctx.rx0;
7207 let mut shaded: usize = 0;
7208 if cut0 < cut1 {
7209 let m0_end: u32 = cut0.min(sx1);
7210 if sx0 < m0_end {
7211 band.blend_shadow_span_const_alpha(sx0, m0_end, pos_y, ctx.color, mid_alpha);
7212 shaded += (m0_end - sx0) as usize;
7213 }
7214 let m1_start: u32 = cut1.max(sx0);
7215 if m1_start < sx1 {
7216 band.blend_shadow_span_const_alpha(m1_start, sx1, pos_y, ctx.color, mid_alpha);
7217 shaded += (sx1 - m1_start) as usize;
7218 }
7219 } else {
7220 band.blend_shadow_span_const_alpha(sx0, sx1, pos_y, ctx.color, mid_alpha);
7221 shaded += (sx1 - sx0) as usize;
7222 }
7223 shaded
7224 }
7225
7226 fn raster_shadow_corner_row_symmetric(
7239 band: &mut PixelBand<'_>,
7240 ctx: &ShadowRenderContext,
7241 pos_y: u32,
7242 cutouts: (Rect, Rect),
7243 ) -> usize {
7244 let py: f32 = (pos_y as f32) + 0.5 - ctx.cy;
7245 let py_abs: f32 = py.abs();
7246 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(pos_y, cutouts, ctx.x0, ctx.x1);
7247 let mut shaded: usize = 0;
7248 if ctx.has_mid_x {
7249 let dist_y: f32 = py_abs - ctx.half_h;
7250 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7251 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7252 } else {
7253 0.0
7254 };
7255 shaded += Self::raster_shadow_middle_span(band, ctx, pos_y, (cut0, cut1), mid_alpha);
7256 }
7257 let (la0, la1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0, cut1);
7258 let (ra0, ra1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0, cut1);
7259 let mut u0: i32 = i32::MAX;
7260 let mut u1: i32 = i32::MIN;
7261 if la0 < la1 {
7262 u0 = u0.min(la0 as i32);
7263 u1 = u1.max(la1 as i32);
7264 }
7265 if ra0 < ra1 {
7266 u0 = u0.min(ctx.mirror_x_sum - (ra1 as i32) + 1);
7267 u1 = u1.max(ctx.mirror_x_sum - (ra0 as i32) + 1);
7268 }
7269 if u0 >= u1 {
7270 return shaded;
7271 }
7272 let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
7273 let qy_pos: f32 = qy.max(0.0);
7274 let qy_pos_sq: f32 = qy_pos * qy_pos;
7275 if qy > 0.0 {
7276 if qy_pos_sq >= ctx.cutoff_r_safe_sq {
7277 return shaded;
7278 }
7279 let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
7280 let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
7281 let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
7282 u0 = u0.max(tight_u0);
7283 if u0 >= u1 {
7284 return shaded;
7285 }
7286 }
7287 let Some(row) = band.row_slice_mut(pos_y) else {
7288 return shaded;
7289 };
7290 let sdf_geom: (f32, f32, f32, f32) =
7291 (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
7292 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
7293 let x0_i: i32 = ctx.x0 as i32;
7294 let lx1_i: i32 = ctx.lx1 as i32;
7295 let rx0_i: i32 = ctx.rx0 as i32;
7296 let x1_i: i32 = ctx.x1 as i32;
7297 let cut0_i: i32 = cut0 as i32;
7298 let cut1_i: i32 = cut1 as i32;
7299 for xl_i in u0..u1 {
7300 let xr_i: i32 = ctx.mirror_x_sum - xl_i;
7301 let do_l: bool = xl_i >= x0_i && xl_i < lx1_i && (xl_i < cut0_i || xl_i >= cut1_i);
7302 let do_r: bool = xr_i >= rx0_i && xr_i < x1_i && (xr_i < cut0_i || xr_i >= cut1_i);
7303 if !do_l && !do_r {
7304 continue;
7305 }
7306 let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
7307 let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
7308 if dist >= ctx.cutoff {
7309 continue;
7310 }
7311 let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7312 if alpha_f <= 0.0005 {
7313 continue;
7314 }
7315 let alpha_val: f32 = alpha_f.clamp(0.0, 1.0);
7316 if alpha_val >= 0.9995 {
7317 if do_l {
7318 let off: usize = (xl_i as usize) * 4;
7319 row[off] = ctx.color_rgb[0];
7320 row[off + 1] = ctx.color_rgb[1];
7321 row[off + 2] = ctx.color_rgb[2];
7322 row[off + 3] = 255;
7323 shaded += 1;
7324 }
7325 if do_r {
7326 let off: usize = (xr_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 } else {
7334 let inv_a: f32 = 1.0 - alpha_val;
7335 let sa_u32: u32 = (alpha_val * 255.0) as u32;
7336 let params: ShadowStripParams = ShadowStripParams {
7337 sr_a: ctx.lin_rgb[0] * alpha_val,
7338 sg_a: ctx.lin_rgb[1] * alpha_val,
7339 sb_a: ctx.lin_rgb[2] * alpha_val,
7340 inv_a,
7341 sa_u32,
7342 inv_a_u32: 255 - sa_u32,
7343 };
7344 let mut cache: ShadowPixelCache = ShadowPixelCache::default();
7345 if do_l {
7346 blend_shadow_mirrored_pixel(row, xl_i as u32, y_term, params, &mut cache);
7347 shaded += 1;
7348 }
7349 if do_r {
7350 blend_shadow_mirrored_pixel(row, xr_i as u32, y_term, params, &mut cache);
7351 shaded += 1;
7352 }
7353 }
7354 }
7355 shaded
7356 }
7357
7358 fn raster_shadow_corner_pair_symmetric(
7372 band: &mut PixelBand<'_>,
7373 ctx: &ShadowRenderContext,
7374 y_t: u32,
7375 y_b: u32,
7376 cutouts: (Rect, Rect),
7377 ) -> usize {
7378 let py: f32 = (y_t as f32) + 0.5 - ctx.cy;
7379 let py_abs: f32 = py.abs();
7380 let (cut0_t, cut1_t): (u32, u32) = Self::shadow_row_cutout(y_t, cutouts, ctx.x0, ctx.x1);
7381 let (cut0_b, cut1_b): (u32, u32) = Self::shadow_row_cutout(y_b, cutouts, ctx.x0, ctx.x1);
7382 let mut shaded: usize = 0;
7383 if ctx.has_mid_x {
7384 let dist_y: f32 = py_abs - ctx.half_h;
7385 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7386 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7387 } else {
7388 0.0
7389 };
7390 if mid_alpha > 0.0005 {
7391 shaded +=
7392 Self::raster_shadow_middle_span(band, ctx, y_t, (cut0_t, cut1_t), mid_alpha);
7393 shaded +=
7394 Self::raster_shadow_middle_span(band, ctx, y_b, (cut0_b, cut1_b), mid_alpha);
7395 }
7396 }
7397 let (lat0, lat1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_t, cut1_t);
7398 let (rat0, rat1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_t, cut1_t);
7399 let (lab0, lab1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_b, cut1_b);
7400 let (rab0, rab1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_b, cut1_b);
7401 let mut u0: i32 = i32::MAX;
7402 let mut u1: i32 = i32::MIN;
7403 if lat0 < lat1 {
7404 u0 = u0.min(lat0 as i32);
7405 u1 = u1.max(lat1 as i32);
7406 }
7407 if rat0 < rat1 {
7408 u0 = u0.min(ctx.mirror_x_sum - (rat1 as i32) + 1);
7409 u1 = u1.max(ctx.mirror_x_sum - (rat0 as i32) + 1);
7410 }
7411 if lab0 < lab1 {
7412 u0 = u0.min(lab0 as i32);
7413 u1 = u1.max(lab1 as i32);
7414 }
7415 if rab0 < rab1 {
7416 u0 = u0.min(ctx.mirror_x_sum - (rab1 as i32) + 1);
7417 u1 = u1.max(ctx.mirror_x_sum - (rab0 as i32) + 1);
7418 }
7419 if u0 >= u1 {
7420 return shaded;
7421 }
7422 let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
7423 let qy_pos: f32 = qy.max(0.0);
7424 let qy_pos_sq: f32 = qy_pos * qy_pos;
7425 if qy > 0.0 {
7426 if qy_pos_sq >= ctx.cutoff_r_safe_sq {
7427 return shaded;
7428 }
7429 let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
7430 let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
7431 let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
7432 u0 = u0.max(tight_u0);
7433 if u0 >= u1 {
7434 return shaded;
7435 }
7436 }
7437 let Some((row_t, row_b)) = band.two_row_slices_mut(y_t, y_b) else {
7438 return shaded;
7439 };
7440 let sdf_geom: (f32, f32, f32, f32) =
7441 (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
7442 let y_term_t: f32 = (y_t as f32) * 0.005_837_15;
7443 let y_term_b: f32 = (y_b as f32) * 0.005_837_15;
7444 let x0_i: i32 = ctx.x0 as i32;
7445 let lx1_i: i32 = ctx.lx1 as i32;
7446 let rx0_i: i32 = ctx.rx0 as i32;
7447 let x1_i: i32 = ctx.x1 as i32;
7448 let cut0_ti: i32 = cut0_t as i32;
7449 let cut1_ti: i32 = cut1_t as i32;
7450 let cut0_bi: i32 = cut0_b as i32;
7451 let cut1_bi: i32 = cut1_b as i32;
7452 for xl_i in u0..u1 {
7453 let xr_i: i32 = ctx.mirror_x_sum - xl_i;
7454 let in_l: bool = xl_i >= x0_i && xl_i < lx1_i;
7455 let in_r: bool = xr_i >= rx0_i && xr_i < x1_i;
7456 let do_lt: bool = in_l && (xl_i < cut0_ti || xl_i >= cut1_ti);
7457 let do_rt: bool = in_r && (xr_i < cut0_ti || xr_i >= cut1_ti);
7458 let do_lb: bool = in_l && (xl_i < cut0_bi || xl_i >= cut1_bi);
7459 let do_rb: bool = in_r && (xr_i < cut0_bi || xr_i >= cut1_bi);
7460 if !do_lt && !do_rt && !do_lb && !do_rb {
7461 continue;
7462 }
7463 let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
7464 let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
7465 if dist >= ctx.cutoff {
7466 continue;
7467 }
7468 let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7469 if alpha_f <= 0.0005 {
7470 continue;
7471 }
7472 let alpha_val: f32 = alpha_f.clamp(0.0, 1.0);
7473 if alpha_val >= 0.9995 {
7474 if do_lt {
7475 let off: usize = (xl_i as usize) * 4;
7476 row_t[off] = ctx.color_rgb[0];
7477 row_t[off + 1] = ctx.color_rgb[1];
7478 row_t[off + 2] = ctx.color_rgb[2];
7479 row_t[off + 3] = 255;
7480 shaded += 1;
7481 }
7482 if do_rt {
7483 let off: usize = (xr_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_lb {
7491 let off: usize = (xl_i as usize) * 4;
7492 row_b[off] = ctx.color_rgb[0];
7493 row_b[off + 1] = ctx.color_rgb[1];
7494 row_b[off + 2] = ctx.color_rgb[2];
7495 row_b[off + 3] = 255;
7496 shaded += 1;
7497 }
7498 if do_rb {
7499 let off: usize = (xr_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 } else {
7507 let inv_a: f32 = 1.0 - alpha_val;
7508 let sa_u32: u32 = (alpha_val * 255.0) as u32;
7509 let params: ShadowStripParams = ShadowStripParams {
7510 sr_a: ctx.lin_rgb[0] * alpha_val,
7511 sg_a: ctx.lin_rgb[1] * alpha_val,
7512 sb_a: ctx.lin_rgb[2] * alpha_val,
7513 inv_a,
7514 sa_u32,
7515 inv_a_u32: 255 - sa_u32,
7516 };
7517 let mut cache: ShadowPixelCache = ShadowPixelCache::default();
7518 if do_lt {
7519 blend_shadow_mirrored_pixel(row_t, xl_i as u32, y_term_t, params, &mut cache);
7520 shaded += 1;
7521 }
7522 if do_rt {
7523 blend_shadow_mirrored_pixel(row_t, xr_i as u32, y_term_t, params, &mut cache);
7524 shaded += 1;
7525 }
7526 if do_lb {
7527 blend_shadow_mirrored_pixel(row_b, xl_i as u32, y_term_b, params, &mut cache);
7528 shaded += 1;
7529 }
7530 if do_rb {
7531 blend_shadow_mirrored_pixel(row_b, xr_i as u32, y_term_b, params, &mut cache);
7532 shaded += 1;
7533 }
7534 }
7535 }
7536 shaded
7537 }
7538
7539 fn raster_shadow_corner_row_general(
7553 band: &mut PixelBand<'_>,
7554 ctx: &ShadowRenderContext,
7555 radius: CornerRadius,
7556 pos_y: u32,
7557 cutouts: (Rect, Rect),
7558 ) -> usize {
7559 let py: f32 = (pos_y as f32) + 0.5 - ctx.cy;
7560 let py_abs: f32 = py.abs();
7561 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(pos_y, cutouts, ctx.x0, ctx.x1);
7562 let spans: [(u32, u32); 2] = if cut0 < cut1 {
7563 [(ctx.x0, cut0), (cut1, ctx.x1)]
7564 } else {
7565 [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
7566 };
7567 let mut shaded: usize = 0;
7568 if ctx.has_mid_x {
7569 let dist_y: f32 = py_abs - ctx.half_h;
7570 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7571 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7572 } else {
7573 0.0
7574 };
7575 shaded += Self::raster_shadow_middle_span(band, ctx, pos_y, (cut0, cut1), mid_alpha);
7576 }
7577 let Some(row) = band.row_slice_mut(pos_y) else {
7578 return shaded;
7579 };
7580 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
7581 let r_l: f32 = (if py < 0.0 {
7582 radius.get_top_left()
7583 } else {
7584 radius.get_bottom_left()
7585 })
7586 .min(ctx.half_w)
7587 .min(ctx.half_h)
7588 .max(0.0);
7589 let r_r: f32 = (if py < 0.0 {
7590 radius.get_top_right()
7591 } else {
7592 radius.get_bottom_right()
7593 })
7594 .min(ctx.half_w)
7595 .min(ctx.half_h)
7596 .max(0.0);
7597 let qy_l: f32 = py_abs - ctx.half_h + r_l;
7598 let qy_l_pos: f32 = qy_l.max(0.0);
7599 let qy_l_sq: f32 = qy_l_pos * qy_l_pos;
7600 let cut_l_r: f32 = ctx.cutoff + r_l + 1e-3;
7601 let geom_l: (f32, f32, f32, f32) = (ctx.half_w, r_l, ctx.cutoff, cut_l_r * cut_l_r);
7602 let qy_r: f32 = py_abs - ctx.half_h + r_r;
7603 let qy_r_pos: f32 = qy_r.max(0.0);
7604 let qy_r_sq: f32 = qy_r_pos * qy_r_pos;
7605 let cut_r_r: f32 = ctx.cutoff + r_r + 1e-3;
7606 let geom_r: (f32, f32, f32, f32) = (ctx.half_w, r_r, ctx.cutoff, cut_r_r * cut_r_r);
7607 for (rx0, rx1) in spans.into_iter() {
7608 if rx0 >= rx1 {
7609 continue;
7610 }
7611 if ctx.has_mid_x {
7612 let l_end: u32 = rx1.min(ctx.lx1);
7613 for pos_x in rx0..l_end {
7614 let px: f32 = (pos_x as f32) + 0.5 - ctx.cx;
7615 let dist: f32 = if px < 0.0 {
7616 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7617 } else {
7618 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7619 };
7620 if dist < ctx.cutoff {
7621 let alpha_f: f32 =
7622 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7623 if alpha_f > 0.0005 {
7624 blend_shadow_row_pixel(
7625 row,
7626 pos_x,
7627 y_term,
7628 ctx.color_rgb,
7629 ctx.lin_rgb,
7630 alpha_f,
7631 );
7632 shaded += 1;
7633 }
7634 }
7635 }
7636 let r_start: u32 = rx0.max(ctx.rx0);
7637 for coord_x in r_start..rx1 {
7638 let px: f32 = (coord_x as f32) + 0.5 - ctx.cx;
7639 let dist: f32 = if px < 0.0 {
7640 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7641 } else {
7642 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7643 };
7644 if dist < ctx.cutoff {
7645 let alpha_f: f32 =
7646 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7647 if alpha_f > 0.0005 {
7648 blend_shadow_row_pixel(
7649 row,
7650 coord_x,
7651 y_term,
7652 ctx.color_rgb,
7653 ctx.lin_rgb,
7654 alpha_f,
7655 );
7656 shaded += 1;
7657 }
7658 }
7659 }
7660 } else {
7661 for sample_x in rx0..rx1 {
7662 let px: f32 = (sample_x as f32) + 0.5 - ctx.cx;
7663 let dist: f32 = if px < 0.0 {
7664 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7665 } else {
7666 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7667 };
7668 if dist >= ctx.cutoff {
7669 continue;
7670 }
7671 let alpha_f: f32 =
7672 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7673 if alpha_f > 0.0005 {
7674 blend_shadow_row_pixel(
7675 row,
7676 sample_x,
7677 y_term,
7678 ctx.color_rgb,
7679 ctx.lin_rgb,
7680 alpha_f,
7681 );
7682 shaded += 1;
7683 }
7684 }
7685 }
7686 }
7687 shaded
7688 }
7689
7690 fn raster_shadow_vertical_strips(
7703 band: &mut PixelBand<'_>,
7704 ctx: &ShadowRenderContext,
7705 y_span: (u32, u32),
7706 cutouts: (Rect, Rect),
7707 ) -> usize {
7708 let (sy0, sy1): (u32, u32) = y_span;
7709 if sy0 >= sy1 {
7710 return 0;
7711 }
7712 let (cut_h, _): (Rect, Rect) = cutouts;
7713 let sy0_f: f32 = (sy0 as f32) + 0.5;
7714 let sy1_last_f: f32 = ((sy1 - 1) as f32) + 0.5;
7715 let const_cut: Option<(u32, u32)> = if cut_h.get_width() > 0.0
7716 && cut_h.get_height() > 0.0
7717 && sy0_f >= cut_h.get_y()
7718 && sy1_last_f < cut_h.bottom()
7719 {
7720 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(ctx.x0, ctx.x1);
7721 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, ctx.x1);
7722 Some((cx0, cx1))
7723 } else {
7724 None
7725 };
7726 let (l_build0, l_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
7727 active_span_bounds(ctx.x0, ctx.lx1, c0, c1)
7728 } else {
7729 (ctx.x0, ctx.lx1)
7730 };
7731 let (r_build0, r_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
7732 active_span_bounds(ctx.rx0, ctx.x1, c0, c1)
7733 } else {
7734 (ctx.rx0, ctx.x1)
7735 };
7736 let mut shaded: usize = 0;
7737 let ran_tls: bool = BAND_SHADOW_SCRATCH
7738 .try_with(|cell: &RefCell<BandShadowScratch>| {
7739 if let Ok(mut scratch) = cell.try_borrow_mut() {
7740 let BandShadowScratch {
7741 left_hot,
7742 left_params,
7743 right_hot,
7744 right_params,
7745 } = &mut *scratch;
7746 let (l_act0, l_act1): (u32, u32) = build_shadow_vertical_strip(
7747 (l_build0, l_build1),
7748 ctx,
7749 left_hot,
7750 left_params,
7751 );
7752 let (r_act0, r_act1): (u32, u32) = build_shadow_vertical_strip(
7753 (r_build0, r_build1),
7754 ctx,
7755 right_hot,
7756 right_params,
7757 );
7758 if l_act0 >= l_act1 && r_act0 >= r_act1 {
7759 return;
7760 }
7761 let l_hot_s: &mut [ShadowStripHot] = left_hot.as_mut_slice();
7762 let l_par_s: &[ShadowStripParams] = left_params.as_slice();
7763 let r_hot_s: &mut [ShadowStripHot] = right_hot.as_mut_slice();
7764 let r_par_s: &[ShadowStripParams] = right_params.as_slice();
7765 for pos_y in sy0..sy1 {
7766 let Some(row) = band.row_slice_mut(pos_y) else {
7767 continue;
7768 };
7769 let y_term: f32 = (pos_y as f32) * 0.005_837_15;
7770 let (cut0, cut1): (u32, u32) = const_cut.unwrap_or_else(|| {
7771 Self::shadow_row_cutout(pos_y, cutouts, ctx.x0, ctx.x1)
7772 });
7773 if l_act0 < l_act1 {
7774 if cut0 < cut1 {
7775 let a_end: u32 = cut0.min(l_act1);
7776 if l_act0 < a_end {
7777 shaded += apply_shadow_strip_span(
7778 row,
7779 (l_act0, a_end, l_act0),
7780 y_term,
7781 ctx.color_rgb,
7782 l_hot_s,
7783 l_par_s,
7784 );
7785 }
7786 let b_start: u32 = cut1.max(l_act0);
7787 if b_start < l_act1 {
7788 shaded += apply_shadow_strip_span(
7789 row,
7790 (b_start, l_act1, l_act0),
7791 y_term,
7792 ctx.color_rgb,
7793 l_hot_s,
7794 l_par_s,
7795 );
7796 }
7797 } else {
7798 shaded += apply_shadow_strip_span(
7799 row,
7800 (l_act0, l_act1, l_act0),
7801 y_term,
7802 ctx.color_rgb,
7803 l_hot_s,
7804 l_par_s,
7805 );
7806 }
7807 }
7808 if r_act0 < r_act1 {
7809 if cut0 < cut1 {
7810 let a_end: u32 = cut0.min(r_act1);
7811 if r_act0 < a_end {
7812 shaded += apply_shadow_strip_span(
7813 row,
7814 (r_act0, a_end, r_act0),
7815 y_term,
7816 ctx.color_rgb,
7817 r_hot_s,
7818 r_par_s,
7819 );
7820 }
7821 let b_start: u32 = cut1.max(r_act0);
7822 if b_start < r_act1 {
7823 shaded += apply_shadow_strip_span(
7824 row,
7825 (b_start, r_act1, r_act0),
7826 y_term,
7827 ctx.color_rgb,
7828 r_hot_s,
7829 r_par_s,
7830 );
7831 }
7832 } else {
7833 shaded += apply_shadow_strip_span(
7834 row,
7835 (r_act0, r_act1, r_act0),
7836 y_term,
7837 ctx.color_rgb,
7838 r_hot_s,
7839 r_par_s,
7840 );
7841 }
7842 }
7843 }
7844 }
7845 })
7846 .is_ok();
7847 if !ran_tls {
7848 for coord_y in sy0..sy1 {
7849 let Some(row) = band.row_slice_mut(coord_y) else {
7850 continue;
7851 };
7852 let y_term: f32 = (coord_y as f32) * 0.005_837_15;
7853 let (cut0, cut1): (u32, u32) = const_cut
7854 .unwrap_or_else(|| Self::shadow_row_cutout(coord_y, cutouts, ctx.x0, ctx.x1));
7855 let spans: [(u32, u32); 2] = if cut0 < cut1 {
7856 [(ctx.x0, cut0), (cut1, ctx.x1)]
7857 } else {
7858 [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
7859 };
7860 for (rx0, rx1) in spans.into_iter() {
7861 let left_end: u32 = rx1.min(ctx.lx1);
7862 for pos_x in rx0..left_end {
7863 let dist: f32 = ((pos_x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
7864 if dist < ctx.cutoff {
7865 let alpha_f: f32 =
7866 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7867 if alpha_f > 0.0005 {
7868 blend_shadow_row_pixel(
7869 row,
7870 pos_x,
7871 y_term,
7872 ctx.color_rgb,
7873 ctx.lin_rgb,
7874 alpha_f,
7875 );
7876 shaded += 1;
7877 }
7878 }
7879 }
7880 let right_start: u32 = rx0.max(ctx.rx0);
7881 for coord_x in right_start..rx1 {
7882 let dist: f32 = ((coord_x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
7883 if dist < ctx.cutoff {
7884 let alpha_f: f32 =
7885 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7886 if alpha_f > 0.0005 {
7887 blend_shadow_row_pixel(
7888 row,
7889 coord_x,
7890 y_term,
7891 ctx.color_rgb,
7892 ctx.lin_rgb,
7893 alpha_f,
7894 );
7895 shaded += 1;
7896 }
7897 }
7898 }
7899 }
7900 }
7901 }
7902 shaded
7903 }
7904
7905 fn raster_shadow(
7920 band: &mut PixelBand<'_>,
7921 rects: (Rect, Rect, Rect),
7922 radius: CornerRadius,
7923 sigma: f32,
7924 color: Color,
7925 cutouts: (Rect, Rect),
7926 ) -> usize {
7927 let (shadow_rect, caster_rect, clip): (Rect, Rect, Rect) = rects;
7928 if color.get_alpha() == 0 {
7929 return 0;
7930 }
7931 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
7932 if base_alpha <= 0.0005 {
7933 return 0;
7934 }
7935 let Some(vis) = shadow_rect.intersect(clip) else {
7936 return 0;
7937 };
7938 let fb_w: u32 = band.width();
7939 let band_y0: u32 = band.y_offset();
7940 let band_y1: u32 = band.y_end();
7941 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
7942 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
7943 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
7944 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
7945 if x0 >= x1 || y0 >= y1 {
7946 return 0;
7947 }
7948 let half_w: f32 = (caster_rect.get_width() * 0.5).max(0.5);
7949 let half_h: f32 = (caster_rect.get_height() * 0.5).max(0.5);
7950 let cx: f32 = caster_rect.get_x() + half_w;
7951 let cy: f32 = caster_rect.get_y() + half_h;
7952 let inv_sigma: f32 = 1.0 / sigma.max(0.5);
7953 let cutoff: f32 = sigma * 3.0;
7954 let r_max: f32 = radius.max_radius();
7955 let inner_inset: f32 = cutoff + r_max;
7956 let sy0: u32 = ((caster_rect.get_y() + inner_inset).ceil().max(0.0) as u32).clamp(y0, y1);
7957 let sy1: u32 = ((caster_rect.bottom() - inner_inset).floor().max(0.0) as u32).clamp(y0, y1);
7958 let sx0: u32 = ((caster_rect.get_x() + inner_inset).ceil().max(0.0) as u32).clamp(x0, x1);
7959 let sx1: u32 = ((caster_rect.right() - inner_inset).floor().max(0.0) as u32).clamp(x0, x1);
7960 let has_mid_x: bool = sx0 < sx1;
7961 let has_mid_y: bool = sy0 < sy1;
7962 let r_tl: f32 = radius.get_top_left();
7963 let uniform_radius: bool = r_tl == radius.get_top_right()
7964 && r_tl == radius.get_bottom_right()
7965 && r_tl == radius.get_bottom_left();
7966 let two_cx_f: f32 = 2.0 * cx;
7967 let two_cx_i: i32 = two_cx_f.round() as i32;
7968 let x_symmetric: bool =
7969 uniform_radius && (two_cx_i as f32) == two_cx_f && two_cx_f.abs() < 16_777_216.0;
7970 let two_cy_f: f32 = 2.0 * cy;
7971 let two_cy_i: i32 = two_cy_f.round() as i32;
7972 let y_symmetric: bool =
7973 x_symmetric && (two_cy_i as f32) == two_cy_f && two_cy_f.abs() < 16_777_216.0;
7974 let uniform_r: f32 = r_tl.min(half_w).min(half_h).max(0.0);
7975 let cutoff_r_safe: f32 = cutoff + uniform_r + 1e-3;
7976 let (lx1, rx0): (u32, u32) = if has_mid_x {
7977 (sx0, sx1)
7978 } else if x_symmetric {
7979 let split_x: u32 = ((two_cx_i + 1).div_euclid(2).max(0) as u32).clamp(x0, x1);
7980 (split_x, split_x)
7981 } else {
7982 (x1, x1)
7983 };
7984 let color_rgb: [u8; 3] = [color.get_red(), color.get_green(), color.get_blue()];
7985 let lin_rgb: [f32; 3] = [
7986 SRGB_TO_LIN_LUT[color_rgb[0] as usize],
7987 SRGB_TO_LIN_LUT[color_rgb[1] as usize],
7988 SRGB_TO_LIN_LUT[color_rgb[2] as usize],
7989 ];
7990 let ctx: ShadowRenderContext = ShadowRenderContext {
7991 color,
7992 color_rgb,
7993 lin_rgb,
7994 cx,
7995 cy,
7996 half_w,
7997 half_h,
7998 base_alpha,
7999 inv_sigma,
8000 cutoff,
8001 uniform_r,
8002 cutoff_r_safe_sq: cutoff_r_safe * cutoff_r_safe,
8003 x0,
8004 x1,
8005 lx1,
8006 rx0,
8007 mirror_x_sum: two_cx_i - 1,
8008 has_mid_x,
8009 };
8010 let mut shaded: usize = 0;
8011 if x_symmetric {
8012 let (top_end, bot_start): (u32, u32) = if has_mid_x && has_mid_y {
8013 (sy0, sy1)
8014 } else if y_symmetric {
8015 let split_y: u32 = ((two_cy_i + 1).div_euclid(2).max(0) as u32).clamp(y0, y1);
8016 (split_y, split_y)
8017 } else {
8018 (y1, y1)
8019 };
8020 let mirror_y_sum: i32 = two_cy_i - 1;
8021 let mut mirrored_b0: u32 = y1;
8022 let mut mirrored_b1: u32 = bot_start;
8023 for y_t in y0..top_end {
8024 let y_b_i: i32 = if y_symmetric {
8025 mirror_y_sum - (y_t as i32)
8026 } else {
8027 -1
8028 };
8029 if y_b_i >= (bot_start as i32) && y_b_i < (y1 as i32) {
8030 let y_b: u32 = y_b_i as u32;
8031 mirrored_b0 = mirrored_b0.min(y_b);
8032 mirrored_b1 = mirrored_b1.max(y_b + 1);
8033 shaded +=
8034 Self::raster_shadow_corner_pair_symmetric(band, &ctx, y_t, y_b, cutouts);
8035 } else {
8036 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_t, cutouts);
8037 }
8038 }
8039 if has_mid_x && has_mid_y {
8040 shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
8041 }
8042 if mirrored_b0 < mirrored_b1 {
8043 for y_b in bot_start..mirrored_b0 {
8044 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8045 }
8046 for y_b in mirrored_b1..y1 {
8047 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8048 }
8049 } else {
8050 for y_b in bot_start..y1 {
8051 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8052 }
8053 }
8054 } else if has_mid_x && has_mid_y {
8055 for pos_y in y0..sy0 {
8056 shaded +=
8057 Self::raster_shadow_corner_row_general(band, &ctx, radius, pos_y, cutouts);
8058 }
8059 shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
8060 for coord_y in sy1..y1 {
8061 shaded +=
8062 Self::raster_shadow_corner_row_general(band, &ctx, radius, coord_y, cutouts);
8063 }
8064 } else {
8065 for sample_y in y0..y1 {
8066 shaded +=
8067 Self::raster_shadow_corner_row_general(band, &ctx, radius, sample_y, cutouts);
8068 }
8069 }
8070 shaded
8071 }
8072
8073 fn raster_text_run_band(
8087 band: &mut PixelBand<'_>,
8088 positioned_glyphs: &[PositionedGlyph],
8089 color: Color,
8090 clip: Rect,
8091 glyph_atlas: &GlyphAtlas,
8092 ) -> usize {
8093 let fb_w: i32 = band.width() as i32;
8094 let band_y0: i32 = band.y_offset() as i32;
8095 let band_y1: i32 = band.y_end() as i32;
8096 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
8097 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).clamp(band_y0, band_y1);
8098 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(fb_w);
8099 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).clamp(band_y0, band_y1);
8100 if color.get_alpha() == 0 || clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
8101 return 0;
8102 }
8103 let mut shaded: usize = 0;
8104 for pg in positioned_glyphs.iter() {
8105 let gy0: i32 = pg.get_y();
8106 let gh: i32 = pg.get_height() as i32;
8107 if gy0 >= clip_y1 || gy0 + gh <= clip_y0 {
8108 continue;
8109 }
8110 let gx0: i32 = pg.get_x();
8111 let gw: i32 = pg.get_width() as i32;
8112 if gx0 >= clip_x1 || gx0 + gw <= clip_x0 {
8113 continue;
8114 }
8115 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(pg.get_glyph_idx());
8116 let py_start: i32 = (clip_y0 - gy0).max(0);
8117 let py_end: i32 = (clip_y1 - gy0).min(gh);
8118 let px_start: i32 = (clip_x0 - gx0).max(0);
8119 let px_end: i32 = (clip_x1 - gx0).min(gw);
8120 if py_start < py_end && px_start < px_end {
8121 let dy0: u32 = (gy0 + py_start) as u32;
8122 let dy1: u32 = (gy0 + py_end) as u32;
8123 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(dy0, dy1) {
8124 let cov_bytes: &[u8] = glyph.get_coverage().as_slice();
8125 let gw_usize: usize = gw as usize;
8126 let bx0: usize = ((gx0 + px_start) as usize) * 4;
8127 let bx1: usize = ((gx0 + px_end) as usize) * 4;
8128 let start_u: usize = px_start as usize;
8129 let end_u: usize = px_end as usize;
8130 let mut cov_off: usize = (py_start as usize) * gw_usize;
8131 for row in rows_buf.chunks_exact_mut(row_stride) {
8132 let row_slice: &[u8] = &cov_bytes[cov_off + start_u..cov_off + end_u];
8133 shaded += blend_glyph_row_span(&mut row[bx0..bx1], row_slice, color);
8134 cov_off += gw_usize;
8135 }
8136 }
8137 }
8138 }
8139 shaded
8140 }
8141
8142 #[inline(always)]
8151 fn blit_opaque_horiz_packed_u32(
8152 vrow: &[u32],
8153 dst_x0: usize,
8154 x_packed: &[u32],
8155 dst_row: &mut [u8],
8156 ) {
8157 let len: usize = x_packed.len();
8158 let span_bytes_start: usize = dst_x0 * 4;
8159 let span_bytes_end: usize = (dst_x0 + len) * 4;
8160 if span_bytes_end > dst_row.len() || vrow.len() < 2 {
8161 return;
8162 }
8163 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
8164 .as_chunks_mut::<4>()
8165 .0;
8166 let vptr: *const u32 = vrow.as_ptr();
8167 let dptr: *mut [u8; 4] = dst_chunks.as_mut_ptr();
8168 let lptr: *const u32 = x_packed.as_ptr();
8169 let mut item_index: usize = 0;
8170 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8171 {
8172 let v256: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(256);
8173 let v128_round: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(128);
8174 let alpha_mask: core::arch::wasm32::v128 = core::arch::wasm32::u32x4_splat(0xFF00_0000);
8175 while item_index + 2 <= len {
8176 unsafe {
8178 let e0: u32 = *lptr.add(item_index);
8179 let e1: u32 = *lptr.add(item_index + 1);
8180 let sx_a: usize = (e0 >> 9) as usize;
8181 let wx_a: u16 = (e0 & 0x1FF) as u16;
8182 let sx_b: usize = (e1 >> 9) as usize;
8183 let wx_b: u16 = (e1 & 0x1FF) as u16;
8184 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8185 let pair_b: u64 = vptr.add(sx_b).cast::<u64>().read_unaligned();
8186 let p0_u32: core::arch::wasm32::v128 =
8187 core::arch::wasm32::u32x4(pair_a as u32, pair_b as u32, 0, 0);
8188 let p1_u32: core::arch::wasm32::v128 = core::arch::wasm32::u32x4(
8189 (pair_a >> 32) as u32,
8190 (pair_b >> 32) as u32,
8191 0,
8192 0,
8193 );
8194 let p0_16: core::arch::wasm32::v128 =
8195 core::arch::wasm32::u16x8_extend_low_u8x16(p0_u32);
8196 let p1_16: core::arch::wasm32::v128 =
8197 core::arch::wasm32::u16x8_extend_low_u8x16(p1_u32);
8198 let wx_v: core::arch::wasm32::v128 =
8199 core::arch::wasm32::u16x8(wx_a, wx_a, wx_a, wx_a, wx_b, wx_b, wx_b, wx_b);
8200 let iwx_v: core::arch::wasm32::v128 = core::arch::wasm32::i16x8_sub(v256, wx_v);
8201 let sum: core::arch::wasm32::v128 = core::arch::wasm32::i16x8_add(
8202 core::arch::wasm32::i16x8_add(
8203 core::arch::wasm32::i16x8_mul(p0_16, iwx_v),
8204 core::arch::wasm32::i16x8_mul(p1_16, wx_v),
8205 ),
8206 v128_round,
8207 );
8208 let shr: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(sum, 8);
8209 let packed: core::arch::wasm32::v128 = core::arch::wasm32::v128_or(
8210 core::arch::wasm32::u8x16_narrow_i16x8(shr, shr),
8211 alpha_mask,
8212 );
8213 core::arch::wasm32::v128_store64_lane::<0>(
8214 packed,
8215 dptr.add(item_index).cast::<u64>(),
8216 );
8217 }
8218 item_index += 2;
8219 }
8220 }
8221 #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
8222 while item_index + 2 <= len {
8223 unsafe {
8225 let e0: u32 = *lptr.add(item_index);
8226 let e1: u32 = *lptr.add(item_index + 1);
8227 let sx_a: usize = (e0 >> 9) as usize;
8228 let wx_a: u32 = e0 & 0x1FF;
8229 let iwx_a: u32 = 256 - wx_a;
8230 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8231 let p0_a: u32 = pair_a as u32;
8232 let p1_a: u32 = (pair_a >> 32) as u32;
8233 let rb_a: u32 =
8234 (((p0_a & 0x00FF_00FF) * iwx_a + (p1_a & 0x00FF_00FF) * wx_a + 0x0080_0080)
8235 >> 8)
8236 & 0x00FF_00FF;
8237 let g_a: u32 =
8238 ((((p0_a >> 8) & 0x00FF) * iwx_a + ((p1_a >> 8) & 0x00FF) * wx_a + 128) >> 8)
8239 << 8;
8240 *dptr.add(item_index) = (rb_a | g_a | 0xFF00_0000).to_le_bytes();
8241 let sx_b: usize = (e1 >> 9) as usize;
8242 let wx_b: u32 = e1 & 0x1FF;
8243 let iwx_b: u32 = 256 - wx_b;
8244 let pair_b: u64 = vptr.add(sx_b).cast::<u64>().read_unaligned();
8245 let p0_b: u32 = pair_b as u32;
8246 let p1_b: u32 = (pair_b >> 32) as u32;
8247 let rb_b: u32 =
8248 (((p0_b & 0x00FF_00FF) * iwx_b + (p1_b & 0x00FF_00FF) * wx_b + 0x0080_0080)
8249 >> 8)
8250 & 0x00FF_00FF;
8251 let g_b: u32 =
8252 ((((p0_b >> 8) & 0x00FF) * iwx_b + ((p1_b >> 8) & 0x00FF) * wx_b + 128) >> 8)
8253 << 8;
8254 *dptr.add(item_index + 1) = (rb_b | g_b | 0xFF00_0000).to_le_bytes();
8255 }
8256 item_index += 2;
8257 }
8258 if item_index < len {
8259 unsafe {
8261 let e0: u32 = *lptr.add(item_index);
8262 let sx_a: usize = (e0 >> 9) as usize;
8263 let wx_a: u32 = e0 & 0x1FF;
8264 let iwx_a: u32 = 256 - wx_a;
8265 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8266 let p0_a: u32 = pair_a as u32;
8267 let p1_a: u32 = (pair_a >> 32) as u32;
8268 let rb_a: u32 =
8269 (((p0_a & 0x00FF_00FF) * iwx_a + (p1_a & 0x00FF_00FF) * wx_a + 0x0080_0080)
8270 >> 8)
8271 & 0x00FF_00FF;
8272 let g_a: u32 =
8273 ((((p0_a >> 8) & 0x00FF) * iwx_a + ((p1_a >> 8) & 0x00FF) * wx_a + 128) >> 8)
8274 << 8;
8275 *dptr.add(item_index) = (rb_a | g_a | 0xFF00_0000).to_le_bytes();
8276 }
8277 }
8278 }
8279
8280 #[inline(always)]
8288 fn copy_opaque_row_to_vrow(src0: &[[u8; 4]], sx_range: (usize, usize), vrow: &mut [u32]) {
8289 let (sx_min, sx_max): (usize, usize) = sx_range;
8290 for (&px, out) in src0[sx_min..=sx_max]
8291 .iter()
8292 .zip(vrow[sx_min..=sx_max].iter_mut())
8293 {
8294 *out = u32::from_le_bytes(px);
8295 }
8296 vrow[sx_max + 1] = vrow[sx_max];
8297 }
8298
8299 #[inline(always)]
8309 fn blend_opaque_rows_vert_swar(
8310 src0: &[[u8; 4]],
8311 src1: &[[u8; 4]],
8312 sx_range: (usize, usize),
8313 weights: (u32, u32),
8314 vrow: &mut [u32],
8315 ) {
8316 let (sx_min, sx_max): (usize, usize) = sx_range;
8317 let (wy, iwy): (u32, u32) = weights;
8318 let s0_slice: &[[u8; 4]] = &src0[sx_min..=sx_max];
8319 let s1_slice: &[[u8; 4]] = &src1[sx_min..=sx_max];
8320 let dst_slice: &mut [u32] = &mut vrow[sx_min..=sx_max];
8321 let mut idx: usize = 0;
8322 let count: usize = dst_slice.len();
8323 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8324 if count >= 4 {
8325 unsafe {
8327 let s0_ptr: *const u8 = s0_slice.as_ptr().cast();
8328 let s1_ptr: *const u8 = s1_slice.as_ptr().cast();
8329 let d_ptr: *mut u8 = dst_slice.as_mut_ptr().cast();
8330 let v_wy: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(wy as u16);
8331 let v_iwy: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(iwy as u16);
8332 let v_round: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(128);
8333 let v_alpha: core::arch::wasm32::v128 =
8334 core::arch::wasm32::u32x4_splat(0xFF00_0000);
8335 while idx + 4 <= count {
8336 let b_off: usize = idx * 4;
8337 let a16: core::arch::wasm32::v128 =
8338 core::arch::wasm32::v128_load(s0_ptr.add(b_off).cast());
8339 let b16: core::arch::wasm32::v128 =
8340 core::arch::wasm32::v128_load(s1_ptr.add(b_off).cast());
8341 let a_lo: core::arch::wasm32::v128 =
8342 core::arch::wasm32::u16x8_extend_low_u8x16(a16);
8343 let b_lo: core::arch::wasm32::v128 =
8344 core::arch::wasm32::u16x8_extend_low_u8x16(b16);
8345 let a_hi: core::arch::wasm32::v128 =
8346 core::arch::wasm32::u16x8_extend_high_u8x16(a16);
8347 let b_hi: core::arch::wasm32::v128 =
8348 core::arch::wasm32::u16x8_extend_high_u8x16(b16);
8349 let lo: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(
8350 core::arch::wasm32::i16x8_add(
8351 core::arch::wasm32::i16x8_add(
8352 core::arch::wasm32::i16x8_mul(a_lo, v_iwy),
8353 core::arch::wasm32::i16x8_mul(b_lo, v_wy),
8354 ),
8355 v_round,
8356 ),
8357 8,
8358 );
8359 let hi: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(
8360 core::arch::wasm32::i16x8_add(
8361 core::arch::wasm32::i16x8_add(
8362 core::arch::wasm32::i16x8_mul(a_hi, v_iwy),
8363 core::arch::wasm32::i16x8_mul(b_hi, v_wy),
8364 ),
8365 v_round,
8366 ),
8367 8,
8368 );
8369 let packed: core::arch::wasm32::v128 = core::arch::wasm32::v128_or(
8370 core::arch::wasm32::u8x16_narrow_i16x8(lo, hi),
8371 v_alpha,
8372 );
8373 core::arch::wasm32::v128_store(d_ptr.add(b_off).cast(), packed);
8374 idx += 4;
8375 }
8376 }
8377 }
8378 while idx < count {
8379 let p0: u32 = u32::from_le_bytes(s0_slice[idx]);
8380 let p1: u32 = u32::from_le_bytes(s1_slice[idx]);
8381 let rb: u32 = (((p0 & 0x00FF_00FF) * iwy + (p1 & 0x00FF_00FF) * wy + 0x0080_0080) >> 8)
8382 & 0x00FF_00FF;
8383 let green_val: u32 =
8384 ((((p0 >> 8) & 0x00FF) * iwy + ((p1 >> 8) & 0x00FF) * wy + 128) >> 8) << 8;
8385 dst_slice[idx] = (rb | green_val) | 0xFF00_0000;
8386 idx += 1;
8387 }
8388 vrow[sx_max + 1] = vrow[sx_max];
8389 }
8390
8391 #[inline(always)]
8405 fn blit_bilinear_span_precomputed(
8406 y_params: (usize, usize, u32, u32),
8407 dst_x0: usize,
8408 x_lut: &[(usize, usize, u32)],
8409 src_bytes: &[u8],
8410 dst_row: &mut [u8],
8411 ) -> usize {
8412 let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
8413 let span_bytes_start: usize = dst_x0 * 4;
8414 let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
8415 if span_bytes_end > dst_row.len() {
8416 return 0;
8417 }
8418 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
8419 .as_chunks_mut::<4>()
8420 .0;
8421 let src_len: usize = src_bytes.len();
8422 let mut shaded: usize = 0;
8423 if wy == 0 {
8424 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
8425 let i0: usize = (row0 + sx0) * 4;
8426 let i1: usize = (row0 + sx1) * 4;
8427 if i1 + 4 > src_len {
8428 continue;
8429 }
8430 let iwx: u32 = 256 - wx;
8431 let a0: u32 = src_bytes[i0 + 3] as u32;
8432 let a1: u32 = src_bytes[i1 + 3] as u32;
8433 if (a0 & a1) == 255 {
8434 dp[0] = (((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128)
8435 >> 8) as u8;
8436 dp[1] =
8437 (((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128)
8438 >> 8) as u8;
8439 dp[2] =
8440 (((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128)
8441 >> 8) as u8;
8442 dp[3] = 255;
8443 shaded += 1;
8444 continue;
8445 }
8446 let aw0: u32 = a0 * iwx;
8447 let aw1: u32 = a1 * wx;
8448 let a_val: u32 = (aw0 + aw1 + 128) >> 8;
8449 if a_val == 0 {
8450 continue;
8451 }
8452 let pr: u32 =
8453 ((src_bytes[i0] as u32) * aw0 + (src_bytes[i1] as u32) * aw1 + 128) >> 8;
8454 let pg: u32 =
8455 ((src_bytes[i0 + 1] as u32) * aw0 + (src_bytes[i1 + 1] as u32) * aw1 + 128)
8456 >> 8;
8457 let pb: u32 =
8458 ((src_bytes[i0 + 2] as u32) * aw0 + (src_bytes[i1 + 2] as u32) * aw1 + 128)
8459 >> 8;
8460 let inv_a: u32 = 255 - a_val;
8461 let vr: u32 = pr + (dp[0] as u32) * inv_a + 128;
8462 let vg: u32 = pg + (dp[1] as u32) * inv_a + 128;
8463 let vb: u32 = pb + (dp[2] as u32) * inv_a + 128;
8464 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
8465 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
8466 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
8467 dp[3] = 255;
8468 shaded += 1;
8469 }
8470 return shaded;
8471 }
8472 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
8473 let i00: usize = (row0 + sx0) * 4;
8474 let i10: usize = (row0 + sx1) * 4;
8475 let i01: usize = (row1 + sx0) * 4;
8476 let i11: usize = (row1 + sx1) * 4;
8477 if i11 + 4 > src_len {
8478 continue;
8479 }
8480 let iwx: u32 = 256 - wx;
8481 let w00: u32 = iwx * iwy;
8482 let w10: u32 = wx * iwy;
8483 let w01: u32 = iwx * wy;
8484 let w11: u32 = wx * wy;
8485 let a00: u32 = src_bytes[i00 + 3] as u32;
8486 let a10: u32 = src_bytes[i10 + 3] as u32;
8487 let a01: u32 = src_bytes[i01 + 3] as u32;
8488 let a11: u32 = src_bytes[i11 + 3] as u32;
8489 if (a00 & a10 & a01 & a11) == 255 {
8490 dp[0] = (((src_bytes[i00] as u32) * w00
8491 + (src_bytes[i10] as u32) * w10
8492 + (src_bytes[i01] as u32) * w01
8493 + (src_bytes[i11] as u32) * w11
8494 + 32768)
8495 >> 16) as u8;
8496 dp[1] = (((src_bytes[i00 + 1] as u32) * w00
8497 + (src_bytes[i10 + 1] as u32) * w10
8498 + (src_bytes[i01 + 1] as u32) * w01
8499 + (src_bytes[i11 + 1] as u32) * w11
8500 + 32768)
8501 >> 16) as u8;
8502 dp[2] = (((src_bytes[i00 + 2] as u32) * w00
8503 + (src_bytes[i10 + 2] as u32) * w10
8504 + (src_bytes[i01 + 2] as u32) * w01
8505 + (src_bytes[i11 + 2] as u32) * w11
8506 + 32768)
8507 >> 16) as u8;
8508 dp[3] = 255;
8509 shaded += 1;
8510 continue;
8511 }
8512 let aw00: u64 = (a00 as u64) * (w00 as u64);
8513 let aw10: u64 = (a10 as u64) * (w10 as u64);
8514 let aw01: u64 = (a01 as u64) * (w01 as u64);
8515 let aw11: u64 = (a11 as u64) * (w11 as u64);
8516 let a_val: u32 = ((aw00 + aw10 + aw01 + aw11 + 32768) >> 16) as u32;
8517 if a_val == 0 {
8518 continue;
8519 }
8520 let pr: u32 = (((src_bytes[i00] as u64) * aw00
8521 + (src_bytes[i10] as u64) * aw10
8522 + (src_bytes[i01] as u64) * aw01
8523 + (src_bytes[i11] as u64) * aw11
8524 + 32768)
8525 >> 16) as u32;
8526 let pg: u32 = (((src_bytes[i00 + 1] as u64) * aw00
8527 + (src_bytes[i10 + 1] as u64) * aw10
8528 + (src_bytes[i01 + 1] as u64) * aw01
8529 + (src_bytes[i11 + 1] as u64) * aw11
8530 + 32768)
8531 >> 16) as u32;
8532 let pb: u32 = (((src_bytes[i00 + 2] as u64) * aw00
8533 + (src_bytes[i10 + 2] as u64) * aw10
8534 + (src_bytes[i01 + 2] as u64) * aw01
8535 + (src_bytes[i11 + 2] as u64) * aw11
8536 + 32768)
8537 >> 16) as u32;
8538 let inv_a: u32 = 255 - a_val;
8539 let vr: u32 = pr + (dp[0] as u32) * inv_a + 128;
8540 let vg: u32 = pg + (dp[1] as u32) * inv_a + 128;
8541 let vb: u32 = pb + (dp[2] as u32) * inv_a + 128;
8542 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
8543 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
8544 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
8545 dp[3] = 255;
8546 shaded += 1;
8547 }
8548 shaded
8549 }
8550
8551 fn raster_image_bilinear_with_lut(
8567 band: &mut PixelBand<'_>,
8568 rect: Rect,
8569 src_info: (u32, u32, &[u8]),
8570 bounds: (u32, u32, u32, u32),
8571 radius: CornerRadius,
8572 aa: AntialiasingMode,
8573 x_lut: &mut Vec<(usize, usize, u32)>,
8574 ) -> usize {
8575 let (src_w, src_h, src_bytes): (u32, u32, &[u8]) = src_info;
8576 let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
8577 let rect_x: f32 = rect.get_x();
8578 let rect_y: f32 = rect.get_y();
8579 let half_w: f32 = rect.get_width() * 0.5;
8580 let half_h: f32 = rect.get_height() * 0.5;
8581 let cx: f32 = rect_x + half_w;
8582 let cy: f32 = rect_y + half_h;
8583 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
8584 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
8585 let src_w_f: f32 = src_w as f32;
8586 let src_h_f: f32 = src_h as f32;
8587 let src_w_usize: usize = src_w as usize;
8588 let max_sx: usize = src_w_usize.saturating_sub(1);
8589 let max_sy: usize = (src_h as usize).saturating_sub(1);
8590 let has_radius: bool = radius.max_radius() > 0.0;
8591 x_lut.clear();
8592 for pos_x in x0..x1 {
8593 let tex_u: f32 = (((pos_x as f32) + 0.5 - rect_x) * inv_dst_w).clamp(0.0, 1.0);
8594 let fx: f32 = (tex_u * src_w_f - 0.5).clamp(0.0, max_sx as f32);
8595 let sx0: usize = (fx.floor() as usize).min(max_sx);
8596 let sx1: usize = (sx0 + 1).min(max_sx);
8597 let wx: u32 = ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8598 x_lut.push((sx0, sx1, wx));
8599 }
8600 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
8601 if !has_radius {
8602 let x0_u: usize = x0 as usize;
8603 let sx_min: usize = x_lut_ref
8604 .first()
8605 .map_or(0, |event_ref: &(usize, usize, u32)| event_ref.0);
8606 let sx_max: usize = x_lut_ref
8607 .last()
8608 .map_or(0, |error_val: &(usize, usize, u32)| error_val.1)
8609 .min(max_sx);
8610 let src_row_bytes_len: usize = src_w_usize * 4;
8611 let can_fast_opaque: bool = !x_lut_ref.is_empty()
8612 && sx_min <= sx_max
8613 && sx_max < src_w_usize
8614 && (src_h as usize) * src_row_bytes_len <= src_bytes.len();
8615 if can_fast_opaque {
8616 let mut cached_op_sy: usize = usize::MAX;
8617 let mut cached_op_val: bool = false;
8618 let mut cached_op_sy2: usize = usize::MAX;
8619 let mut cached_op_val2: bool = false;
8620 let ran_vrow: bool = BAND_IMAGE_VROW_U32
8621 .try_with(|cell: &RefCell<Vec<u32>>| {
8622 let _ran_packed: bool = BAND_IMAGE_X_PACKED
8623 .try_with(|pcell: &RefCell<Vec<u32>>| {
8624 if let (Ok(mut vrow_guard), Ok(mut packed_guard)) =
8625 (cell.try_borrow_mut(), pcell.try_borrow_mut())
8626 {
8627 if vrow_guard.len() < src_w_usize + 1 {
8628 vrow_guard.resize(src_w_usize + 1, 0);
8629 }
8630 packed_guard.clear();
8631 for &(sx0, _, wx) in x_lut_ref.iter() {
8632 packed_guard.push(((sx0 as u32) << 9) | (wx & 0x1FF));
8633 }
8634 let x_packed_ref: &[u32] = packed_guard.as_slice();
8635 let vrow: &mut [u32] = vrow_guard.as_mut_slice();
8636 let mut prev_vkey: (usize, usize, u32) =
8637 (usize::MAX, usize::MAX, u32::MAX);
8638 let check_start: usize = sx_min * 4;
8639 let check_end: usize = (sx_max + 1) * 4;
8640 for pos_y in y0..y1 {
8641 let Some(dst_row) = band.row_slice_mut(pos_y) else {
8642 continue;
8643 };
8644 let item_val: f32 = (((pos_y as f32) + 0.5 - rect_y)
8645 * inv_dst_h)
8646 .clamp(0.0, 1.0);
8647 let fy: f32 =
8648 (item_val * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8649 let sy0: usize = (fy.floor() as usize).min(max_sy);
8650 let sy1: usize = (sy0 + 1).min(max_sy);
8651 let wy: u32 =
8652 ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0)
8653 as u32;
8654 let r0_off: usize = sy0 * src_row_bytes_len;
8655 let op0: bool = if sy0 == cached_op_sy {
8656 cached_op_val
8657 } else if sy0 == cached_op_sy2 {
8658 cached_op_val2
8659 } else {
8660 let val: bool = is_rgba_slice_opaque(
8661 &src_bytes
8662 [(r0_off + check_start)..(r0_off + check_end)],
8663 );
8664 cached_op_sy2 = cached_op_sy;
8665 cached_op_val2 = cached_op_val;
8666 cached_op_sy = sy0;
8667 cached_op_val = val;
8668 val
8669 };
8670 if wy == 0 || sy0 == sy1 {
8671 if op0 {
8672 let vkey: (usize, usize, u32) = (sy0, sy0, 0);
8673 if prev_vkey != vkey {
8674 let row0_px: &[[u8; 4]] = src_bytes
8675 [r0_off..(r0_off + src_row_bytes_len)]
8676 .as_chunks::<4>()
8677 .0;
8678 Self::copy_opaque_row_to_vrow(
8679 row0_px,
8680 (sx_min, sx_max),
8681 vrow,
8682 );
8683 prev_vkey = vkey;
8684 }
8685 Self::blit_opaque_horiz_packed_u32(
8686 vrow,
8687 x0_u,
8688 x_packed_ref,
8689 dst_row,
8690 );
8691 continue;
8692 }
8693 } else if op0 {
8694 let r1_off: usize = sy1 * src_row_bytes_len;
8695 let op1: bool = if sy1 == cached_op_sy {
8696 cached_op_val
8697 } else if sy1 == cached_op_sy2 {
8698 cached_op_val2
8699 } else {
8700 let val: bool = is_rgba_slice_opaque(
8701 &src_bytes[(r1_off + check_start)
8702 ..(r1_off + check_end)],
8703 );
8704 cached_op_sy2 = cached_op_sy;
8705 cached_op_val2 = cached_op_val;
8706 cached_op_sy = sy1;
8707 cached_op_val = val;
8708 val
8709 };
8710 if op1 {
8711 let vkey: (usize, usize, u32) = (sy0, sy1, wy);
8712 if prev_vkey != vkey {
8713 let row0_px: &[[u8; 4]] = src_bytes
8714 [r0_off..(r0_off + src_row_bytes_len)]
8715 .as_chunks::<4>()
8716 .0;
8717 let row1_px: &[[u8; 4]] = src_bytes
8718 [r1_off..(r1_off + src_row_bytes_len)]
8719 .as_chunks::<4>()
8720 .0;
8721 Self::blend_opaque_rows_vert_swar(
8722 row0_px,
8723 row1_px,
8724 (sx_min, sx_max),
8725 (wy, 256 - wy),
8726 vrow,
8727 );
8728 prev_vkey = vkey;
8729 }
8730 Self::blit_opaque_horiz_packed_u32(
8731 vrow,
8732 x0_u,
8733 x_packed_ref,
8734 dst_row,
8735 );
8736 continue;
8737 }
8738 }
8739 let y_params: (usize, usize, u32, u32) =
8740 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8741 let _: usize = Self::blit_bilinear_span_precomputed(
8742 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
8743 );
8744 }
8745 }
8746 })
8747 .is_ok();
8748 })
8749 .is_ok();
8750 if ran_vrow {
8751 return ((x1 - x0) as usize) * ((y1 - y0) as usize);
8752 }
8753 }
8754 for coord_y in y0..y1 {
8755 let Some(dst_row) = band.row_slice_mut(coord_y) else {
8756 continue;
8757 };
8758 let tex_v: f32 = (((coord_y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
8759 let fy: f32 = (tex_v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8760 let sy0: usize = (fy.floor() as usize).min(max_sy);
8761 let sy1: usize = (sy0 + 1).min(max_sy);
8762 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8763 let y_params: (usize, usize, u32, u32) =
8764 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8765 let _: usize = Self::blit_bilinear_span_precomputed(
8766 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
8767 );
8768 }
8769 return ((x1 - x0) as usize) * ((y1 - y0) as usize);
8770 }
8771 let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
8772 let ix0: u32 = ((rect_x + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
8773 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
8774 let iy0: u32 = ((rect_y + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
8775 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
8776 let cx0: u32 = ((rect_x + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
8777 let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
8778 let mut shaded: usize = 0;
8779 for sample_y in y0..iy0 {
8780 let Some(dst_row) = band.row_slice_mut(sample_y) else {
8781 continue;
8782 };
8783 let bary_v: f32 = (((sample_y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
8784 let fy: f32 = (bary_v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8785 let sy0: usize = (fy.floor() as usize).min(max_sy);
8786 let sy1: usize = (sy0 + 1).min(max_sy);
8787 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8788 let y_params: (usize, usize, u32, u32) =
8789 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8790 let py: f32 = (sample_y as f32) + 0.5 - cy;
8791 let dist_y: f32 = py.abs() - half_h;
8792 let mid_cov: f32 = sdf_coverage(dist_y, aa);
8793 if cx0 < cx1 && mid_cov > 0.0 {
8794 let lut_s: usize = (cx0 - x0) as usize;
8795 let lut_e: usize = (cx1 - x0) as usize;
8796 if mid_cov >= 0.9995 {
8797 let _: usize = Self::blit_bilinear_span_precomputed(
8798 y_params,
8799 cx0 as usize,
8800 &x_lut_ref[lut_s..lut_e],
8801 src_bytes,
8802 dst_row,
8803 );
8804 } else {
8805 for coord_x in cx0..cx1 {
8806 let rgba: [u8; 4] = sample_bilinear_fixed(
8807 src_bytes,
8808 y_params,
8809 x_lut_ref[(coord_x - x0) as usize],
8810 );
8811 let off: usize = (coord_x as usize) * 4;
8812 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
8813 }
8814 }
8815 shaded += (cx1 - cx0) as usize;
8816 }
8817 for sample_x in x0..cx0 {
8818 let px: f32 = (sample_x as f32) + 0.5 - cx;
8819 let cr: f32 = quadrant_corner_radius(radius, px, py);
8820 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
8821 if cov > 0.0 {
8822 let rgba: [u8; 4] = sample_bilinear_fixed(
8823 src_bytes,
8824 y_params,
8825 x_lut_ref[(sample_x - x0) as usize],
8826 );
8827 let off: usize = (sample_x as usize) * 4;
8828 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8829 shaded += 1;
8830 }
8831 }
8832 for value_x in cx1..x1 {
8833 let px: f32 = (value_x as f32) + 0.5 - cx;
8834 let cr: f32 = quadrant_corner_radius(radius, px, py);
8835 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
8836 if cov > 0.0 {
8837 let rgba: [u8; 4] = sample_bilinear_fixed(
8838 src_bytes,
8839 y_params,
8840 x_lut_ref[(value_x - x0) as usize],
8841 );
8842 let off: usize = (value_x as usize) * 4;
8843 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8844 shaded += 1;
8845 }
8846 }
8847 }
8848 for value_y in iy0..iy1 {
8849 let Some(dst_row) = band.row_slice_mut(value_y) else {
8850 continue;
8851 };
8852 let sample_val: f32 = (((value_y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
8853 let fy: f32 = (sample_val * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8854 let sy0: usize = (fy.floor() as usize).min(max_sy);
8855 let sy1: usize = (sy0 + 1).min(max_sy);
8856 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8857 let y_params: (usize, usize, u32, u32) =
8858 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8859 if ix0 < ix1 {
8860 let lut_s: usize = (ix0 - x0) as usize;
8861 let lut_e: usize = (ix1 - x0) as usize;
8862 let _: usize = Self::blit_bilinear_span_precomputed(
8863 y_params,
8864 ix0 as usize,
8865 &x_lut_ref[lut_s..lut_e],
8866 src_bytes,
8867 dst_row,
8868 );
8869 shaded += (ix1 - ix0) as usize;
8870 }
8871 for pos_x_primary in x0..ix0 {
8872 let dist: f32 = ((pos_x_primary as f32) + 0.5 - cx).abs() - half_w;
8873 let cov: f32 = sdf_coverage(dist, aa);
8874 if cov > 0.0 {
8875 let rgba: [u8; 4] = sample_bilinear_fixed(
8876 src_bytes,
8877 y_params,
8878 x_lut_ref[(pos_x_primary - x0) as usize],
8879 );
8880 let off: usize = (pos_x_primary as usize) * 4;
8881 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8882 shaded += 1;
8883 }
8884 }
8885 for pos_x_secondary in ix1..x1 {
8886 let dist: f32 = ((pos_x_secondary as f32) + 0.5 - cx).abs() - half_w;
8887 let cov: f32 = sdf_coverage(dist, aa);
8888 if cov > 0.0 {
8889 let rgba: [u8; 4] = sample_bilinear_fixed(
8890 src_bytes,
8891 y_params,
8892 x_lut_ref[(pos_x_secondary - x0) as usize],
8893 );
8894 let off: usize = (pos_x_secondary as usize) * 4;
8895 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8896 shaded += 1;
8897 }
8898 }
8899 }
8900 for pos_y_primary in iy1..y1 {
8901 let Some(dst_row) = band.row_slice_mut(pos_y_primary) else {
8902 continue;
8903 };
8904 let item_val_primary: f32 =
8905 (((pos_y_primary as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
8906 let fy: f32 = (item_val_primary * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8907 let sy0: usize = (fy.floor() as usize).min(max_sy);
8908 let sy1: usize = (sy0 + 1).min(max_sy);
8909 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8910 let y_params: (usize, usize, u32, u32) =
8911 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
8912 let py: f32 = (pos_y_primary as f32) + 0.5 - cy;
8913 let dist_y: f32 = py.abs() - half_h;
8914 let mid_cov: f32 = sdf_coverage(dist_y, aa);
8915 if cx0 < cx1 && mid_cov > 0.0 {
8916 let lut_s: usize = (cx0 - x0) as usize;
8917 let lut_e: usize = (cx1 - x0) as usize;
8918 if mid_cov >= 0.9995 {
8919 let _: usize = Self::blit_bilinear_span_precomputed(
8920 y_params,
8921 cx0 as usize,
8922 &x_lut_ref[lut_s..lut_e],
8923 src_bytes,
8924 dst_row,
8925 );
8926 } else {
8927 for pos_x_next in cx0..cx1 {
8928 let rgba: [u8; 4] = sample_bilinear_fixed(
8929 src_bytes,
8930 y_params,
8931 x_lut_ref[(pos_x_next - x0) as usize],
8932 );
8933 let off: usize = (pos_x_next as usize) * 4;
8934 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
8935 }
8936 }
8937 shaded += (cx1 - cx0) as usize;
8938 }
8939 for pos_x_alt in x0..cx0 {
8940 let px: f32 = (pos_x_alt as f32) + 0.5 - cx;
8941 let cr: f32 = quadrant_corner_radius(radius, px, py);
8942 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
8943 if cov > 0.0 {
8944 let rgba: [u8; 4] = sample_bilinear_fixed(
8945 src_bytes,
8946 y_params,
8947 x_lut_ref[(pos_x_alt - x0) as usize],
8948 );
8949 let off: usize = (pos_x_alt as usize) * 4;
8950 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8951 shaded += 1;
8952 }
8953 }
8954 for pos_x_inner in cx1..x1 {
8955 let px: f32 = (pos_x_inner as f32) + 0.5 - cx;
8956 let cr: f32 = quadrant_corner_radius(radius, px, py);
8957 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
8958 if cov > 0.0 {
8959 let rgba: [u8; 4] = sample_bilinear_fixed(
8960 src_bytes,
8961 y_params,
8962 x_lut_ref[(pos_x_inner - x0) as usize],
8963 );
8964 let off: usize = (pos_x_inner as usize) * 4;
8965 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
8966 shaded += 1;
8967 }
8968 }
8969 }
8970 shaded
8971 }
8972
8973 fn raster_rgba_bytes(
8988 band: &mut PixelBand<'_>,
8989 rect: Rect,
8990 source: (u32, u32, &[u8]),
8991 radius: CornerRadius,
8992 clip: Rect,
8993 aa: AntialiasingMode,
8994 ) -> usize {
8995 let (src_w, src_h, src_bytes): (u32, u32, &[u8]) = source;
8996 if src_w == 0 || src_h == 0 {
8997 return 0;
8998 }
8999 let Some(vis) = rect.intersect(clip) else {
9000 return 0;
9001 };
9002 let fb_w: u32 = band.width();
9003 let band_y0: u32 = band.y_offset();
9004 let band_y1: u32 = band.y_end();
9005 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9006 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9007 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9008 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9009 if x0 >= x1 || y0 >= y1 {
9010 return 0;
9011 }
9012 let half_w: f32 = rect.get_width() * 0.5;
9013 let half_h: f32 = rect.get_height() * 0.5;
9014 let cx: f32 = rect.get_x() + half_w;
9015 let cy: f32 = rect.get_y() + half_h;
9016 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
9017 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
9018 let use_bilinear: bool = aa != AntialiasingMode::None
9019 && ((rect.get_width() - (src_w as f32)).abs() > 0.5
9020 || (rect.get_height() - (src_h as f32)).abs() > 0.5);
9021 let has_radius: bool = radius.max_radius() > 0.0;
9022 let max_sx: usize = (src_w as usize).saturating_sub(1);
9023 let max_sy: usize = (src_h as usize).saturating_sub(1);
9024 let src_w_usize: usize = src_w as usize;
9025 let is_exact_1to1: bool = !use_bilinear
9026 && (rect.get_width() - (src_w as f32)).abs() <= 0.01
9027 && (rect.get_height() - (src_h as f32)).abs() <= 0.01
9028 && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
9029 && (rect.get_y() - rect.get_y().round()).abs() <= 0.01;
9030 let rx0_i: i32 = rect.get_x().round() as i32;
9031 let ry0_i: i32 = rect.get_y().round() as i32;
9032 if is_exact_1to1
9033 && !has_radius
9034 && (x0 as i32) >= rx0_i
9035 && (x1 as i32) <= rx0_i + (src_w as i32)
9036 && (y0 as i32) >= ry0_i
9037 && (y1 as i32) <= ry0_i + (src_h as i32)
9038 {
9039 let span_w: usize = (x1 - x0) as usize;
9040 let src_x_off: usize = ((x0 as i32) - rx0_i) as usize;
9041 let dst_byte0: usize = (x0 as usize) * 4;
9042 let dst_byte1: usize = (x1 as usize) * 4;
9043 for pos_y in y0..y1 {
9044 let Some(dst_row) = band.row_slice_mut(pos_y) else {
9045 continue;
9046 };
9047 let sy: usize = ((pos_y as i32) - ry0_i) as usize;
9048 let src_byte0: usize = (sy * src_w_usize + src_x_off) * 4;
9049 let src_byte1: usize = src_byte0 + span_w * 4;
9050 if src_byte1 <= src_bytes.len() && dst_byte1 <= dst_row.len() {
9051 blit_1to1_rgba_span(
9052 &src_bytes[src_byte0..src_byte1],
9053 &mut dst_row[dst_byte0..dst_byte1],
9054 );
9055 }
9056 }
9057 return span_w * ((y1 - y0) as usize);
9058 }
9059 if use_bilinear {
9060 let mut shaded: usize = 0;
9061 let ran_tls: bool = BAND_IMAGE_X_LUT
9062 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
9063 if let Ok(mut guard) = cell.try_borrow_mut() {
9064 shaded = Self::raster_image_bilinear_with_lut(
9065 band,
9066 rect,
9067 (src_w, src_h, src_bytes),
9068 (x0, y0, x1, y1),
9069 radius,
9070 aa,
9071 &mut guard,
9072 );
9073 }
9074 })
9075 .is_ok();
9076 if !ran_tls {
9077 let mut fallback_lut: Vec<(usize, usize, u32)> =
9078 Vec::with_capacity((x1 - x0) as usize);
9079 shaded = Self::raster_image_bilinear_with_lut(
9080 band,
9081 rect,
9082 (src_w, src_h, src_bytes),
9083 (x0, y0, x1, y1),
9084 radius,
9085 aa,
9086 &mut fallback_lut,
9087 );
9088 }
9089 return shaded;
9090 }
9091 if !has_radius && (src_h as usize) * src_w_usize * 4 <= src_bytes.len() {
9092 let x0_u: usize = x0 as usize;
9093 let span_w: usize = (x1 - x0) as usize;
9094 let dst_b0: usize = x0_u * 4;
9095 let dst_b1: usize = (x1 as usize) * 4;
9096 let src_w_f: f32 = src_w as f32;
9097 let src_h_f: f32 = src_h as f32;
9098 let mut sx_arr_ok: bool = false;
9099 let _ran_tls_nn: bool = BAND_IMAGE_X_LUT
9100 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
9101 if let Ok(mut lut) = cell.try_borrow_mut() {
9102 lut.clear();
9103 for pos_x in x0..x1 {
9104 let tex_u: f32 =
9105 (((pos_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9106 let sx: usize = ((tex_u * src_w_f).floor() as usize).min(max_sx);
9107 lut.push((sx, 0, 0));
9108 }
9109 let lut_ref: &[(usize, usize, u32)] = lut.as_slice();
9110 let row_bytes_len: usize = src_w_usize * 4;
9111 let mut cached_sy: usize = usize::MAX;
9112 let mut cached_opaque: bool = false;
9113 for coord_y in y0..y1 {
9114 let Some(dst_row) = band.row_slice_mut(coord_y) else {
9115 continue;
9116 };
9117 if dst_b1 > dst_row.len() {
9118 continue;
9119 }
9120 let item_val: f32 = (((coord_y as f32) + 0.5 - rect.get_y())
9121 * inv_dst_h)
9122 .clamp(0.0, 1.0);
9123 let sy: usize = ((item_val * src_h_f).floor() as usize).min(max_sy);
9124 let r_off: usize = sy * row_bytes_len;
9125 let row_slice: &[u8] = &src_bytes[r_off..(r_off + row_bytes_len)];
9126 let is_op: bool = if sy == cached_sy {
9127 cached_opaque
9128 } else {
9129 cached_sy = sy;
9130 cached_opaque = is_rgba_slice_opaque(row_slice);
9131 cached_opaque
9132 };
9133 let src_px: &[[u8; 4]] = row_slice.as_chunks::<4>().0;
9134 let dst_px: &mut [[u8; 4]] =
9135 dst_row[dst_b0..dst_b1].as_chunks_mut::<4>().0;
9136 if is_op {
9137 let sptr: *const [u8; 4] = src_px.as_ptr();
9138 for (dp, &(sx, _, _)) in dst_px.iter_mut().zip(lut_ref.iter()) {
9139 *dp = unsafe { *sptr.add(sx) };
9141 }
9142 } else {
9143 for (dp, &(sx, _, _)) in dst_px.iter_mut().zip(lut_ref.iter()) {
9144 blend_rgba_pixel_with_cov(dp, src_px[sx], 1.0);
9145 }
9146 }
9147 }
9148 sx_arr_ok = true;
9149 }
9150 })
9151 .is_ok();
9152 if sx_arr_ok {
9153 return span_w * ((y1 - y0) as usize);
9154 }
9155 }
9156 let mut shaded: usize = 0;
9157 let r_max: f32 = if has_radius {
9158 radius.max_radius().min(half_w).min(half_h).max(0.0)
9159 } else {
9160 0.0
9161 };
9162 let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
9163 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
9164 let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
9165 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
9166 let can_1to1_interior: bool = is_exact_1to1
9167 && (ix0 as i32) >= rx0_i
9168 && (ix1 as i32) <= rx0_i + (src_w as i32)
9169 && (iy0 as i32) >= ry0_i
9170 && (iy1 as i32) <= ry0_i + (src_h as i32);
9171 for sample_y in y0..y1 {
9172 let Some(dst_row) = band.row_slice_mut(sample_y) else {
9173 continue;
9174 };
9175 let tex_v: f32 = (((sample_y as f32) + 0.5 - rect.get_y()) * inv_dst_h).clamp(0.0, 1.0);
9176 let py: f32 = (sample_y as f32) + 0.5 - cy;
9177 let sy: usize = ((tex_v * (src_h as f32)).floor() as usize).min(max_sy);
9178 let row: usize = sy * src_w_usize;
9179 if has_radius && can_1to1_interior && sample_y >= iy0 && sample_y < iy1 && ix0 < ix1 {
9180 let src_off: usize = (row + (((ix0 as i32) - rx0_i) as usize)) * 4;
9181 let span_bytes: usize = ((ix1 - ix0) as usize) * 4;
9182 let dst_off: usize = (ix0 as usize) * 4;
9183 if src_off + span_bytes <= src_bytes.len() && dst_off + span_bytes <= dst_row.len()
9184 {
9185 blit_1to1_rgba_span(
9186 &src_bytes[src_off..src_off + span_bytes],
9187 &mut dst_row[dst_off..dst_off + span_bytes],
9188 );
9189 }
9190 shaded += (ix1 - ix0) as usize;
9191 for coord_x in x0..ix0 {
9192 let dist: f32 = ((coord_x as f32) + 0.5 - cx).abs() - half_w;
9193 let cov: f32 = sdf_coverage(dist, aa);
9194 if cov > 0.0 {
9195 let bary_u: f32 =
9196 (((coord_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9197 let sx: usize = ((bary_u * (src_w as f32)).floor() as usize).min(max_sx);
9198 let idx: usize = (row + sx) * 4;
9199 if idx + 4 <= src_bytes.len() {
9200 let off: usize = (coord_x as usize) * 4;
9201 blend_rgba_pixel_with_cov(
9202 &mut dst_row[off..off + 4],
9203 [
9204 src_bytes[idx],
9205 src_bytes[idx + 1],
9206 src_bytes[idx + 2],
9207 src_bytes[idx + 3],
9208 ],
9209 cov,
9210 );
9211 shaded += 1;
9212 }
9213 }
9214 }
9215 for sample_x in ix1..x1 {
9216 let dist: f32 = ((sample_x as f32) + 0.5 - cx).abs() - half_w;
9217 let cov: f32 = sdf_coverage(dist, aa);
9218 if cov > 0.0 {
9219 let unit_u: f32 =
9220 (((sample_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9221 let sx: usize = ((unit_u * (src_w as f32)).floor() as usize).min(max_sx);
9222 let idx: usize = (row + sx) * 4;
9223 if idx + 4 <= src_bytes.len() {
9224 let off: usize = (sample_x as usize) * 4;
9225 blend_rgba_pixel_with_cov(
9226 &mut dst_row[off..off + 4],
9227 [
9228 src_bytes[idx],
9229 src_bytes[idx + 1],
9230 src_bytes[idx + 2],
9231 src_bytes[idx + 3],
9232 ],
9233 cov,
9234 );
9235 shaded += 1;
9236 }
9237 }
9238 }
9239 continue;
9240 }
9241 for value_x in x0..x1 {
9242 let cov: f32 = if has_radius {
9243 let px: f32 = (value_x as f32) + 0.5 - cx;
9244 let cr: f32 = quadrant_corner_radius(radius, px, py);
9245 sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
9246 } else {
9247 1.0
9248 };
9249 if cov <= 0.0 {
9250 continue;
9251 }
9252 let upper_val: f32 =
9253 (((value_x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9254 let sx: usize = ((upper_val * (src_w as f32)).floor() as usize).min(max_sx);
9255 let idx: usize = (row + sx) * 4;
9256 if idx + 4 <= src_bytes.len() {
9257 let off: usize = (value_x as usize) * 4;
9258 blend_rgba_pixel_with_cov(
9259 &mut dst_row[off..off + 4],
9260 [
9261 src_bytes[idx],
9262 src_bytes[idx + 1],
9263 src_bytes[idx + 2],
9264 src_bytes[idx + 3],
9265 ],
9266 cov,
9267 );
9268 shaded += 1;
9269 }
9270 }
9271 }
9272 shaded
9273 }
9274
9275 fn raster_line(
9291 band: &mut PixelBand<'_>,
9292 from: Point,
9293 to: Point,
9294 color: Color,
9295 width: f32,
9296 clip: Rect,
9297 aa: AntialiasingMode,
9298 ) -> usize {
9299 if color.get_alpha() == 0 {
9300 return 0;
9301 }
9302 let half_w: f32 = width * 0.5;
9303 let min_x: f32 = from.get_x().min(to.get_x()) - half_w - 1.0;
9304 let min_y: f32 = from.get_y().min(to.get_y()) - half_w - 1.0;
9305 let max_x: f32 = from.get_x().max(to.get_x()) + half_w + 1.0;
9306 let max_y: f32 = from.get_y().max(to.get_y()) + half_w + 1.0;
9307 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
9308 else {
9309 return 0;
9310 };
9311 let fb_w: u32 = band.width();
9312 let band_y0: u32 = band.y_offset();
9313 let band_y1: u32 = band.y_end();
9314 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9315 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9316 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9317 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9318 if x0 >= x1 || y0 >= y1 {
9319 return 0;
9320 }
9321 let fx0: f32 = from.get_x();
9322 let fy0: f32 = from.get_y();
9323 let dx: f32 = to.get_x() - fx0;
9324 let dy: f32 = to.get_y() - fy0;
9325 let len_sq: f32 = (dx * dx + dy * dy).max(1e-6);
9326 let inv_len_sq: f32 = 1.0 / len_sq;
9327 let outer_r: f32 = half_w + 0.9;
9328 let outer_r_sq: f32 = outer_r * outer_r;
9329 let inner_r: f32 = (half_w - 0.9).max(0.0);
9330 let inner_r_sq: f32 = inner_r * inner_r;
9331 let has_inner: bool = half_w > 0.9;
9332 let use_oriented_x: bool = dy.abs() > 1e-4;
9333 let slope_x_per_y: f32 = if use_oriented_x { dx / dy } else { 0.0 };
9334 let x_pad: f32 = if use_oriented_x {
9335 outer_r * (len_sq.sqrt() / dy.abs()) + 0.5
9336 } else {
9337 0.0
9338 };
9339 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
9340 let lin_rgb: [f32; 3] = [
9341 SRGB_TO_LIN_LUT[color.get_red() as usize],
9342 SRGB_TO_LIN_LUT[color.get_green() as usize],
9343 SRGB_TO_LIN_LUT[color.get_blue() as usize],
9344 ];
9345 let mut shaded: usize = 0;
9346 for pos_y in y0..y1 {
9347 let py: f32 = (pos_y as f32) + 0.5;
9348 let py_off: f32 = py - fy0;
9349 let (row_x0, row_x1): (u32, u32) = if use_oriented_x {
9350 let x_center: f32 = fx0 + py_off * slope_x_per_y;
9351 let rx0: u32 = ((x_center - x_pad).floor().max(0.0) as u32).clamp(x0, x1);
9352 let rx1: u32 = ((x_center + x_pad).ceil().max(0.0) as u32).clamp(rx0, x1);
9353 (rx0, rx1)
9354 } else {
9355 (x0, x1)
9356 };
9357 if row_x0 >= row_x1 {
9358 continue;
9359 }
9360 let Some(row) = band.row_slice_mut(pos_y) else {
9361 continue;
9362 };
9363 let py_dy: f32 = py_off * dy;
9364 for pos_x in row_x0..row_x1 {
9365 let px: f32 = (pos_x as f32) + 0.5;
9366 let blend_factor: f32 = (((px - fx0) * dx + py_dy) * inv_len_sq).clamp(0.0, 1.0);
9367 let dpx: f32 = px - (fx0 + blend_factor * dx);
9368 let dpy: f32 = py - (fy0 + blend_factor * dy);
9369 let dist_sq: f32 = dpx * dpx + dpy * dpy;
9370 if dist_sq >= outer_r_sq {
9371 continue;
9372 }
9373 let cov: f32 = if has_inner && dist_sq <= inner_r_sq {
9374 1.0
9375 } else {
9376 sdf_coverage(dist_sq.sqrt() - half_w, aa)
9377 };
9378 if cov > 0.0 {
9379 blend_row_pixel_f32_precomputed(row, pos_x, color, lin_rgb, base_alpha * cov);
9380 shaded += 1;
9381 }
9382 }
9383 }
9384 shaded
9385 }
9386
9387 fn raster_circle(
9402 band: &mut PixelBand<'_>,
9403 center: Point,
9404 radius: f32,
9405 color: Color,
9406 clip: Rect,
9407 aa: AntialiasingMode,
9408 ) -> usize {
9409 if radius <= 0.0 || color.get_alpha() == 0 {
9410 return 0;
9411 }
9412 let bounds: Rect = Rect::new(
9413 center.get_x() - radius - 1.0,
9414 center.get_y() - radius - 1.0,
9415 (radius + 1.0) * 2.0,
9416 (radius + 1.0) * 2.0,
9417 );
9418 let Some(vis) = bounds.intersect(clip) else {
9419 return 0;
9420 };
9421 let fb_w: u32 = band.width();
9422 let band_y0: u32 = band.y_offset();
9423 let band_y1: u32 = band.y_end();
9424 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9425 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9426 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9427 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9428 if x0 >= x1 || y0 >= y1 {
9429 return 0;
9430 }
9431 let outer_r: f32 = if aa == AntialiasingMode::None {
9432 radius + 0.5
9433 } else {
9434 radius + 0.65
9435 };
9436 let inner_r: f32 = if aa == AntialiasingMode::None {
9437 (radius - 0.5).max(0.0)
9438 } else {
9439 (radius - 0.65).max(0.0)
9440 };
9441 let outer_r2: f32 = outer_r * outer_r;
9442 let inner_r2: f32 = inner_r * inner_r;
9443 let r2: f32 = radius * radius;
9444 let cx: f32 = center.get_x();
9445 let cy: f32 = center.get_y();
9446 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
9447 let lin_rgb: [f32; 3] = [
9448 SRGB_TO_LIN_LUT[color.get_red() as usize],
9449 SRGB_TO_LIN_LUT[color.get_green() as usize],
9450 SRGB_TO_LIN_LUT[color.get_blue() as usize],
9451 ];
9452 let interior_luts: Option<[[u8; 256]; 4]> = if color.get_alpha() < 255 && radius >= 12.0 {
9453 Some(build_linear_blend_luts(color))
9454 } else {
9455 None
9456 };
9457 let mut shaded: usize = 0;
9458 for pos_y in y0..y1 {
9459 let dy: f32 = (pos_y as f32) + 0.5 - cy;
9460 let dy2: f32 = dy * dy;
9461 if dy2 >= outer_r2 {
9462 continue;
9463 }
9464 let out_dx: f32 = (outer_r2 - dy2).sqrt();
9465 let row_x0: u32 = ((cx - out_dx).floor().max(0.0) as u32).clamp(x0, x1);
9466 let row_x1: u32 = ((cx + out_dx).ceil().max(0.0) as u32).clamp(row_x0, x1);
9467 if row_x0 >= row_x1 {
9468 continue;
9469 }
9470 if dy2 < inner_r2 && inner_r > 0.65 {
9471 let in_dx: f32 = (inner_r2 - dy2).sqrt();
9472 let in_x0: u32 = ((cx - in_dx).ceil().max(0.0) as u32).clamp(row_x0, row_x1);
9473 let in_x1: u32 = ((cx + in_dx).floor().max(0.0) as u32).clamp(in_x0, row_x1);
9474 if in_x0 < in_x1 {
9475 if let Some(ref luts) = interior_luts {
9476 band.fill_span_linear_luts(in_x0, in_x1, pos_y, luts);
9477 } else {
9478 band.fill_span_linear(in_x0, in_x1, pos_y, color);
9479 }
9480 shaded += (in_x1 - in_x0) as usize;
9481 }
9482 if (row_x0 < in_x0 || in_x1 < row_x1)
9483 && let Some(row) = band.row_slice_mut(pos_y)
9484 {
9485 for pos_x in row_x0..in_x0 {
9486 let dx: f32 = (pos_x as f32) + 0.5 - cx;
9487 let cov: f32 = if aa == AntialiasingMode::None {
9488 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9489 } else {
9490 circle_supersampled_coverage(dx, dy, radius)
9491 };
9492 if cov > 0.0 {
9493 blend_row_pixel_f32_precomputed(
9494 row,
9495 pos_x,
9496 color,
9497 lin_rgb,
9498 base_alpha * cov,
9499 );
9500 shaded += 1;
9501 }
9502 }
9503 for coord_x in in_x1..row_x1 {
9504 let dx: f32 = (coord_x as f32) + 0.5 - cx;
9505 let cov: f32 = if aa == AntialiasingMode::None {
9506 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9507 } else {
9508 circle_supersampled_coverage(dx, dy, radius)
9509 };
9510 if cov > 0.0 {
9511 blend_row_pixel_f32_precomputed(
9512 row,
9513 coord_x,
9514 color,
9515 lin_rgb,
9516 base_alpha * cov,
9517 );
9518 shaded += 1;
9519 }
9520 }
9521 }
9522 } else if let Some(row) = band.row_slice_mut(pos_y) {
9523 for sample_x in row_x0..row_x1 {
9524 let dx: f32 = (sample_x as f32) + 0.5 - cx;
9525 let cov: f32 = if aa == AntialiasingMode::None {
9526 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9527 } else {
9528 circle_supersampled_coverage(dx, dy, radius)
9529 };
9530 if cov > 0.0 {
9531 blend_row_pixel_f32_precomputed(
9532 row,
9533 sample_x,
9534 color,
9535 lin_rgb,
9536 base_alpha * cov,
9537 );
9538 shaded += 1;
9539 }
9540 }
9541 }
9542 }
9543 shaded
9544 }
9545
9546 #[inline(always)]
9559 #[must_use]
9560 fn solve_triangle_scanline_interval(
9561 d_base: [f32; 3],
9562 a_step: [f32; 3],
9563 thresh: f32,
9564 max_s: f32,
9565 ) -> (f32, f32) {
9566 let mut s_min: f32 = 0.0;
9567 let mut s_max: f32 = max_s;
9568 for idx in 0..3usize {
9569 let alpha_val: f32 = a_step[idx];
9570 let delta_val: f32 = d_base[idx];
9571 if alpha_val > 1e-6 {
9572 let bound: f32 = (thresh - delta_val) / alpha_val;
9573 if bound > s_min {
9574 s_min = bound;
9575 }
9576 } else if alpha_val < -1e-6 {
9577 let bound: f32 = (thresh - delta_val) / alpha_val;
9578 if bound < s_max {
9579 s_max = bound;
9580 }
9581 } else if delta_val < thresh {
9582 return (1.0, 0.0);
9583 }
9584 }
9585 (s_min, s_max)
9586 }
9587
9588 fn raster_triangle(
9604 band: &mut PixelBand<'_>,
9605 p0: Point,
9606 p1: Point,
9607 p2: Point,
9608 color: Color,
9609 clip: Rect,
9610 aa: AntialiasingMode,
9611 ) -> usize {
9612 if color.get_alpha() == 0 {
9613 return 0;
9614 }
9615 let dx0: f32 = p1.get_x() - p0.get_x();
9616 let dy0: f32 = p1.get_y() - p0.get_y();
9617 let dx1: f32 = p2.get_x() - p1.get_x();
9618 let dy1: f32 = p2.get_y() - p1.get_y();
9619 let dx2: f32 = p0.get_x() - p2.get_x();
9620 let dy2: f32 = p0.get_y() - p2.get_y();
9621 let area: f32 = dx0 * (p2.get_y() - p0.get_y()) - dy0 * (p2.get_x() - p0.get_x());
9622 if area.abs() < 1e-5 {
9623 return 0;
9624 }
9625 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) - 1.0;
9626 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) - 1.0;
9627 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) + 1.0;
9628 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) + 1.0;
9629 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
9630 else {
9631 return 0;
9632 };
9633 let fb_w: u32 = band.width();
9634 let band_y0: u32 = band.y_offset();
9635 let band_y1: u32 = band.y_end();
9636 let clip_x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9637 let clip_x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9638 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9639 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9640 if clip_x0 >= clip_x1 || y0 >= y1 {
9641 return 0;
9642 }
9643 if aa == AntialiasingMode::None {
9644 let edges: [(Point, Point); 3] = [(p0, p1), (p1, p2), (p2, p0)];
9645 let mut shaded: usize = 0;
9646 for pos_y in y0..y1 {
9647 let py: f32 = (pos_y as f32) + 0.5;
9648 let mut min_ix: f32 = f32::INFINITY;
9649 let mut max_ix: f32 = f32::NEG_INFINITY;
9650 for (alpha_val, blue_val) in edges.iter() {
9651 let ay: f32 = alpha_val.get_y();
9652 let by: f32 = blue_val.get_y();
9653 if (ay <= py && by > py) || (by <= py && ay > py) {
9654 let blend_factor: f32 = (py - ay) / (by - ay);
9655 let ix: f32 = alpha_val.get_x()
9656 + blend_factor * (blue_val.get_x() - alpha_val.get_x());
9657 min_ix = min_ix.min(ix);
9658 max_ix = max_ix.max(ix);
9659 }
9660 }
9661 if min_ix <= max_ix {
9662 let sx0: u32 = (min_ix.floor().max(0.0) as u32).clamp(clip_x0, clip_x1);
9663 let sx1: u32 = (max_ix.ceil().max(0.0) as u32).clamp(clip_x0, clip_x1);
9664 if sx0 < sx1 {
9665 band.fill_span_linear(sx0, sx1, pos_y, color);
9666 shaded += (sx1 - sx0) as usize;
9667 }
9668 }
9669 }
9670 return shaded;
9671 }
9672 let sign: f32 = if area > 0.0 { 1.0 } else { -1.0 };
9673 let inv_l0: f32 = sign / dx0.hypot(dy0).max(1e-5);
9674 let inv_l1: f32 = sign / dx1.hypot(dy1).max(1e-5);
9675 let inv_l2: f32 = sign / dx2.hypot(dy2).max(1e-5);
9676 let a_step: [f32; 3] = [-dy0 * inv_l0, -dy1 * inv_l1, -dy2 * inv_l2];
9677 let b_step: [f32; 3] = [dx0 * inv_l0, dx1 * inv_l1, dx2 * inv_l2];
9678 let base_alpha: f32 = (color.get_alpha() as f32) * (1.0 / 255.0);
9679 let lin_rgb: [f32; 3] = [
9680 SRGB_TO_LIN_LUT[color.get_red() as usize],
9681 SRGB_TO_LIN_LUT[color.get_green() as usize],
9682 SRGB_TO_LIN_LUT[color.get_blue() as usize],
9683 ];
9684 let interior_luts: Option<[[u8; 256]; 4]> =
9685 if color.get_alpha() < 255 && (area.abs() * 0.5) >= 256.0 {
9686 Some(build_linear_blend_luts(color))
9687 } else {
9688 None
9689 };
9690 let px_base: f32 = (clip_x0 as f32) + 0.5;
9691 let max_s: f32 = (clip_x1 - clip_x0) as f32;
9692 let py_start: f32 = (y0 as f32) + 0.5;
9693 let mut d_row: [f32; 3] = [
9694 (dx0 * (py_start - p0.get_y()) - dy0 * (px_base - p0.get_x())) * inv_l0,
9695 (dx1 * (py_start - p1.get_y()) - dy1 * (px_base - p1.get_x())) * inv_l1,
9696 (dx2 * (py_start - p2.get_y()) - dy2 * (px_base - p2.get_x())) * inv_l2,
9697 ];
9698 let edge_deltas: [(f32, f32); 3] = [(dx0, dy0), (dx1, dy1), (dx2, dy2)];
9699 let verts: (Point, Point, Point) = (p0, p1, p2);
9700 let mut shaded: usize = 0;
9701 for coord_y in y0..y1 {
9702 let py: f32 = (coord_y as f32) + 0.5;
9703 let (out_min, out_max): (f32, f32) =
9704 Self::solve_triangle_scanline_interval(d_row, a_step, -0.86, max_s);
9705 if out_min <= out_max {
9706 let k_out0: u32 = out_min.floor().max(0.0) as u32;
9707 let k_out1: u32 = (out_max.ceil().max(0.0) as u32).saturating_add(1);
9708 let row_x0: u32 = clip_x0.saturating_add(k_out0).clamp(clip_x0, clip_x1);
9709 let row_x1: u32 = clip_x0.saturating_add(k_out1).clamp(row_x0, clip_x1);
9710 if row_x0 < row_x1 {
9711 let (in_min, in_max): (f32, f32) =
9712 Self::solve_triangle_scanline_interval(d_row, a_step, 0.86, max_s);
9713 let (in_x0, in_x1): (u32, u32) = if in_min <= in_max && in_max >= 0.0 {
9714 let k_in0: u32 = in_min.ceil().max(0.0) as u32;
9715 let k_in1: u32 = (in_max.floor().max(0.0) as u32).saturating_add(1);
9716 let ix0: u32 = clip_x0.saturating_add(k_in0).clamp(row_x0, row_x1);
9717 let ix1: u32 = clip_x0.saturating_add(k_in1).clamp(ix0, row_x1);
9718 (ix0, ix1)
9719 } else {
9720 (row_x1, row_x1)
9721 };
9722 if in_x0 < in_x1 {
9723 if let Some(ref luts) = interior_luts {
9724 band.fill_span_linear_luts(in_x0, in_x1, coord_y, luts);
9725 } else {
9726 band.fill_span_linear(in_x0, in_x1, coord_y, color);
9727 }
9728 shaded += (in_x1 - in_x0) as usize;
9729 }
9730 if (row_x0 < in_x0 || in_x1 < row_x1)
9731 && let Some(row) = band.row_slice_mut(coord_y)
9732 {
9733 let mut rim_spans: [(u32, u32); 2] = [(row_x0, in_x0), (in_x1, row_x1)];
9734 if in_x0 >= in_x1 {
9735 rim_spans = [(row_x0, row_x1), (row_x1, row_x1)];
9736 }
9737 for (sx0, sx1) in rim_spans.into_iter() {
9738 if sx0 >= sx1 {
9739 continue;
9740 }
9741 let s0: f32 = (sx0 - clip_x0) as f32;
9742 let mut d0: f32 = d_row[0] + a_step[0] * s0;
9743 let mut d1: f32 = d_row[1] + a_step[1] * s0;
9744 let mut d2: f32 = d_row[2] + a_step[2] * s0;
9745 for pos_x in sx0..sx1 {
9746 if d0 >= -0.85 && d1 >= -0.85 && d2 >= -0.85 {
9747 if d0 > 0.85 && d1 > 0.85 && d2 > 0.85 {
9748 blend_row_pixel_linear_precomputed(
9749 row, pos_x, color, lin_rgb,
9750 );
9751 shaded += 1;
9752 } else {
9753 let px: f32 = (pos_x as f32) + 0.5;
9754 let cov: f32 = triangle_supersampled_coverage_precomputed(
9755 (px, py),
9756 verts,
9757 edge_deltas,
9758 sign,
9759 );
9760 if cov >= 0.999 {
9761 blend_row_pixel_linear_precomputed(
9762 row, pos_x, color, lin_rgb,
9763 );
9764 shaded += 1;
9765 } else if cov > 0.0 {
9766 blend_row_pixel_f32_precomputed(
9767 row,
9768 pos_x,
9769 color,
9770 lin_rgb,
9771 base_alpha * cov,
9772 );
9773 shaded += 1;
9774 }
9775 }
9776 }
9777 d0 += a_step[0];
9778 d1 += a_step[1];
9779 d2 += a_step[2];
9780 }
9781 }
9782 }
9783 }
9784 }
9785 d_row[0] += b_step[0];
9786 d_row[1] += b_step[1];
9787 d_row[2] += b_step[2];
9788 }
9789 shaded
9790 }
9791
9792 #[inline(always)]
9807 fn blit_sprite_span_tinted(
9808 y_params: (usize, usize, u32, u32),
9809 dst_x0: usize,
9810 x_lut: &[(usize, usize, u32)],
9811 src_bytes: &[u8],
9812 dst_row: &mut [u8],
9813 tint: Color,
9814 ) -> usize {
9815 let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
9816 let span_bytes_start: usize = dst_x0 * 4;
9817 let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
9818 if span_bytes_end > dst_row.len() {
9819 return 0;
9820 }
9821 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
9822 .as_chunks_mut::<4>()
9823 .0;
9824 let src_len: usize = src_bytes.len();
9825 let transform_val: u32 = tint.get_red() as u32;
9826 let tg: u32 = tint.get_green() as u32;
9827 let tb: u32 = tint.get_blue() as u32;
9828 let ta: u32 = tint.get_alpha() as u32;
9829 let mut shaded: usize = 0;
9830 if wy == 0 {
9831 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
9832 let i0: usize = (row0 + sx0) * 4;
9833 let i1: usize = (row0 + sx1) * 4;
9834 if i1 + 4 > src_len {
9835 continue;
9836 }
9837 let iwx: u32 = 256 - wx;
9838 let a0: u32 = src_bytes[i0 + 3] as u32;
9839 let a1: u32 = src_bytes[i1 + 3] as u32;
9840 let (sr_raw, sg_raw, sb_raw, sa_raw): (u32, u32, u32, u32) = if (a0 & a1) == 255 {
9841 (
9842 ((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128) >> 8,
9843 ((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128)
9844 >> 8,
9845 ((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128)
9846 >> 8,
9847 255,
9848 )
9849 } else {
9850 let aw0: u32 = a0 * iwx;
9851 let aw1: u32 = a1 * wx;
9852 let a_sum: u32 = aw0 + aw1;
9853 let a_out: u32 = (a_sum + 128) >> 8;
9854 if a_out == 0 || a_sum == 0 {
9855 continue;
9856 }
9857 let half_a: u32 = a_sum >> 1;
9858 (
9859 (((src_bytes[i0] as u32) * aw0 + (src_bytes[i1] as u32) * aw1 + half_a)
9860 / a_sum)
9861 .min(255),
9862 (((src_bytes[i0 + 1] as u32) * aw0
9863 + (src_bytes[i1 + 1] as u32) * aw1
9864 + half_a)
9865 / a_sum)
9866 .min(255),
9867 (((src_bytes[i0 + 2] as u32) * aw0
9868 + (src_bytes[i1 + 2] as u32) * aw1
9869 + half_a)
9870 / a_sum)
9871 .min(255),
9872 a_out,
9873 )
9874 };
9875 let rr: u32 = sr_raw * transform_val + 128;
9876 let gg: u32 = sg_raw * tg + 128;
9877 let bb: u32 = sb_raw * tb + 128;
9878 let aa_v: u32 = sa_raw * ta + 128;
9879 let red_val: u32 = (rr + (rr >> 8)) >> 8;
9880 let green_val: u32 = (gg + (gg >> 8)) >> 8;
9881 let blue_val: u32 = (bb + (bb >> 8)) >> 8;
9882 let alpha_val: u32 = (aa_v + (aa_v >> 8)) >> 8;
9883 if alpha_val == 255 {
9884 dp[0] = red_val as u8;
9885 dp[1] = green_val as u8;
9886 dp[2] = blue_val as u8;
9887 dp[3] = 255;
9888 } else if alpha_val > 0 {
9889 let inv_a: u32 = 255 - alpha_val;
9890 let vr: u32 = red_val * alpha_val + (dp[0] as u32) * inv_a + 128;
9891 let vg: u32 = green_val * alpha_val + (dp[1] as u32) * inv_a + 128;
9892 let vb: u32 = blue_val * alpha_val + (dp[2] as u32) * inv_a + 128;
9893 let va: u32 = (dp[3] as u32) * inv_a + 128;
9894 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
9895 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
9896 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
9897 dp[3] = (alpha_val + ((va + (va >> 8)) >> 8)).min(255) as u8;
9898 }
9899 shaded += 1;
9900 }
9901 return shaded;
9902 }
9903 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
9904 let i00: usize = (row0 + sx0) * 4;
9905 let i10: usize = (row0 + sx1) * 4;
9906 let i01: usize = (row1 + sx0) * 4;
9907 let i11: usize = (row1 + sx1) * 4;
9908 if i11 + 4 > src_len {
9909 continue;
9910 }
9911 let iwx: u32 = 256 - wx;
9912 let w00: u32 = iwx * iwy;
9913 let w10: u32 = wx * iwy;
9914 let w01: u32 = iwx * wy;
9915 let w11: u32 = wx * wy;
9916 let a00: u32 = src_bytes[i00 + 3] as u32;
9917 let a10: u32 = src_bytes[i10 + 3] as u32;
9918 let a01: u32 = src_bytes[i01 + 3] as u32;
9919 let a11: u32 = src_bytes[i11 + 3] as u32;
9920 let (sr_raw, sg_raw, sb_raw, sa_raw): (u32, u32, u32, u32) =
9921 if (a00 & a10 & a01 & a11) == 255 {
9922 (
9923 ((src_bytes[i00] as u32) * w00
9924 + (src_bytes[i10] as u32) * w10
9925 + (src_bytes[i01] as u32) * w01
9926 + (src_bytes[i11] as u32) * w11
9927 + 32768)
9928 >> 16,
9929 ((src_bytes[i00 + 1] as u32) * w00
9930 + (src_bytes[i10 + 1] as u32) * w10
9931 + (src_bytes[i01 + 1] as u32) * w01
9932 + (src_bytes[i11 + 1] as u32) * w11
9933 + 32768)
9934 >> 16,
9935 ((src_bytes[i00 + 2] as u32) * w00
9936 + (src_bytes[i10 + 2] as u32) * w10
9937 + (src_bytes[i01 + 2] as u32) * w01
9938 + (src_bytes[i11 + 2] as u32) * w11
9939 + 32768)
9940 >> 16,
9941 255,
9942 )
9943 } else {
9944 let aw00: u64 = (a00 as u64) * (w00 as u64);
9945 let aw10: u64 = (a10 as u64) * (w10 as u64);
9946 let aw01: u64 = (a01 as u64) * (w01 as u64);
9947 let aw11: u64 = (a11 as u64) * (w11 as u64);
9948 let a_sum: u64 = aw00 + aw10 + aw01 + aw11;
9949 let a_out: u32 = ((a_sum + 32768) >> 16) as u32;
9950 if a_out == 0 || a_sum == 0 {
9951 continue;
9952 }
9953 let half_a: u64 = a_sum >> 1;
9954 (
9955 ((((src_bytes[i00] as u64) * aw00
9956 + (src_bytes[i10] as u64) * aw10
9957 + (src_bytes[i01] as u64) * aw01
9958 + (src_bytes[i11] as u64) * aw11
9959 + half_a)
9960 / a_sum)
9961 .min(255)) as u32,
9962 ((((src_bytes[i00 + 1] as u64) * aw00
9963 + (src_bytes[i10 + 1] as u64) * aw10
9964 + (src_bytes[i01 + 1] as u64) * aw01
9965 + (src_bytes[i11 + 1] as u64) * aw11
9966 + half_a)
9967 / a_sum)
9968 .min(255)) as u32,
9969 ((((src_bytes[i00 + 2] as u64) * aw00
9970 + (src_bytes[i10 + 2] as u64) * aw10
9971 + (src_bytes[i01 + 2] as u64) * aw01
9972 + (src_bytes[i11 + 2] as u64) * aw11
9973 + half_a)
9974 / a_sum)
9975 .min(255)) as u32,
9976 a_out,
9977 )
9978 };
9979 let rr: u32 = sr_raw * transform_val + 128;
9980 let gg: u32 = sg_raw * tg + 128;
9981 let bb: u32 = sb_raw * tb + 128;
9982 let aa_v: u32 = sa_raw * ta + 128;
9983 let radius_val: u32 = (rr + (rr >> 8)) >> 8;
9984 let geometry_val: u32 = (gg + (gg >> 8)) >> 8;
9985 let byte_val: u32 = (bb + (bb >> 8)) >> 8;
9986 let first_val: u32 = (aa_v + (aa_v >> 8)) >> 8;
9987 if first_val == 255 {
9988 dp[0] = radius_val as u8;
9989 dp[1] = geometry_val as u8;
9990 dp[2] = byte_val as u8;
9991 dp[3] = 255;
9992 } else if first_val > 0 {
9993 let inv_a: u32 = 255 - first_val;
9994 let vr: u32 = radius_val * first_val + (dp[0] as u32) * inv_a + 128;
9995 let vg: u32 = geometry_val * first_val + (dp[1] as u32) * inv_a + 128;
9996 let vb: u32 = byte_val * first_val + (dp[2] as u32) * inv_a + 128;
9997 let va: u32 = (dp[3] as u32) * inv_a + 128;
9998 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
9999 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
10000 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
10001 dp[3] = (first_val + ((va + (va >> 8)) >> 8)).min(255) as u8;
10002 }
10003 shaded += 1;
10004 }
10005 shaded
10006 }
10007
10008 fn raster_sprite_region_with_lut(
10024 band: &mut PixelBand<'_>,
10025 rects: (Rect, Rect),
10026 src_info: (u32, u32, &[u8]),
10027 bounds: (u32, u32, u32, u32),
10028 tint: Color,
10029 use_bilinear: bool,
10030 x_lut: &mut Vec<(usize, usize, u32)>,
10031 ) -> usize {
10032 let (rect, src_rect): (Rect, Rect) = rects;
10033 let (buf_w, buf_h, src_bytes): (u32, u32, &[u8]) = src_info;
10034 let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
10035 let inv_w: f32 = 1.0 / rect.get_width().max(1.0);
10036 let inv_h: f32 = 1.0 / rect.get_height().max(1.0);
10037 let untinted: bool = tint == COLOR_WHITE;
10038 let max_sx: u32 = ((src_rect.right().ceil() as u32).saturating_sub(1)).min(buf_w - 1);
10039 let max_sy: u32 = ((src_rect.bottom().ceil() as u32).saturating_sub(1)).min(buf_h - 1);
10040 let min_sx: u32 = (src_rect.get_x().floor().max(0.0) as u32).min(max_sx);
10041 let min_sy: u32 = (src_rect.get_y().floor().max(0.0) as u32).min(max_sy);
10042 let buf_w_usize: usize = buf_w as usize;
10043 let rect_x: f32 = rect.get_x();
10044 let rect_y: f32 = rect.get_y();
10045 let src_x: f32 = src_rect.get_x();
10046 let src_y: f32 = src_rect.get_y();
10047 let src_w: f32 = src_rect.get_width();
10048 let src_h: f32 = src_rect.get_height();
10049 let min_sx_f: f32 = min_sx as f32;
10050 let max_sx_f: f32 = max_sx as f32;
10051 let min_sy_f: f32 = min_sy as f32;
10052 let max_sy_f: f32 = max_sy as f32;
10053 x_lut.clear();
10054 for pos_x in x0..x1 {
10055 let tex_u: f32 = (((pos_x as f32) + 0.5 - rect_x) * inv_w).clamp(0.0, 1.0);
10056 let fx: f32 = (src_x + tex_u * src_w - 0.5).clamp(min_sx_f, max_sx_f);
10057 let sx0: u32 = (fx.floor() as u32).clamp(min_sx, max_sx);
10058 let sx1: u32 = if use_bilinear {
10059 (sx0 + 1).min(max_sx)
10060 } else {
10061 sx0
10062 };
10063 let wx: u32 = if use_bilinear {
10064 ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
10065 } else {
10066 0
10067 };
10068 x_lut.push((sx0 as usize, sx1 as usize, wx));
10069 }
10070 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
10071 let x0_u: usize = x0 as usize;
10072 let mut shaded: usize = 0;
10073 for pos_y in y0..y1 {
10074 let Some(dst_row) = band.row_slice_mut(pos_y) else {
10075 continue;
10076 };
10077 let item_val: f32 = (((pos_y as f32) + 0.5 - rect_y) * inv_h).clamp(0.0, 1.0);
10078 let fy: f32 = (src_y + item_val * src_h - 0.5).clamp(min_sy_f, max_sy_f);
10079 let sy0: u32 = (fy.floor() as u32).clamp(min_sy, max_sy);
10080 let sy1: u32 = if use_bilinear {
10081 (sy0 + 1).min(max_sy)
10082 } else {
10083 sy0
10084 };
10085 let wy: u32 = if use_bilinear {
10086 ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
10087 } else {
10088 0
10089 };
10090 let y_params: (usize, usize, u32, u32) = (
10091 (sy0 as usize) * buf_w_usize,
10092 (sy1 as usize) * buf_w_usize,
10093 wy,
10094 256 - wy,
10095 );
10096 if untinted {
10097 shaded += Self::blit_bilinear_span_precomputed(
10098 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
10099 );
10100 } else {
10101 shaded += Self::blit_sprite_span_tinted(
10102 y_params, x0_u, x_lut_ref, src_bytes, dst_row, tint,
10103 );
10104 }
10105 }
10106 shaded
10107 }
10108
10109 fn raster_sprite_region(
10125 band: &mut PixelBand<'_>,
10126 rect: Rect,
10127 buffer: &ImageBuffer,
10128 src_rect: Rect,
10129 tint: Color,
10130 clip: Rect,
10131 aa: AntialiasingMode,
10132 ) -> usize {
10133 if buffer.get_width() == 0
10134 || buffer.get_height() == 0
10135 || tint.get_alpha() == 0
10136 || src_rect.get_width() <= 0.0
10137 || src_rect.get_height() <= 0.0
10138 {
10139 return 0;
10140 }
10141 let Some(vis) = rect.intersect(clip) else {
10142 return 0;
10143 };
10144 let fb_w: u32 = band.width();
10145 let band_y0: u32 = band.y_offset();
10146 let band_y1: u32 = band.y_end();
10147 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
10148 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
10149 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
10150 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
10151 if x0 >= x1 || y0 >= y1 {
10152 return 0;
10153 }
10154 let buf_w: u32 = buffer.get_width();
10155 let buf_h: u32 = buffer.get_height();
10156 let src_bytes: &[u8] = buffer.get_pixels();
10157 let use_bilinear: bool = aa != AntialiasingMode::None
10158 && ((rect.get_width() - src_rect.get_width()).abs() > 0.5
10159 || (rect.get_height() - src_rect.get_height()).abs() > 0.5);
10160 if !use_bilinear
10161 && tint == COLOR_WHITE
10162 && (rect.get_width() - src_rect.get_width()).abs() <= 0.01
10163 && (rect.get_height() - src_rect.get_height()).abs() <= 0.01
10164 && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
10165 && (rect.get_y() - rect.get_y().round()).abs() <= 0.01
10166 && (src_rect.get_x() - src_rect.get_x().round()).abs() <= 0.01
10167 && (src_rect.get_y() - src_rect.get_y().round()).abs() <= 0.01
10168 {
10169 let rx0_i: i32 = rect.get_x().round() as i32;
10170 let ry0_i: i32 = rect.get_y().round() as i32;
10171 let sx0_i: i32 = src_rect.get_x().round() as i32;
10172 let sy0_i: i32 = src_rect.get_y().round() as i32;
10173 let span_w: usize = (x1 - x0) as usize;
10174 let src_x0_i: i32 = sx0_i + ((x0 as i32) - rx0_i);
10175 let src_y0_i: i32 = sy0_i + ((y0 as i32) - ry0_i);
10176 let src_y1_i: i32 = sy0_i + ((y1 as i32) - ry0_i);
10177 if src_x0_i >= 0
10178 && src_x0_i + (span_w as i32) <= (buf_w as i32)
10179 && src_y0_i >= 0
10180 && src_y1_i <= (buf_h as i32)
10181 {
10182 let buf_w_u: usize = buf_w as usize;
10183 let dst_b0: usize = (x0 as usize) * 4;
10184 let dst_b1: usize = (x1 as usize) * 4;
10185 let src_x0_u: usize = src_x0_i as usize;
10186 for pos_y in y0..y1 {
10187 let Some(dst_row) = band.row_slice_mut(pos_y) else {
10188 continue;
10189 };
10190 let sy: usize = (sy0_i + ((pos_y as i32) - ry0_i)) as usize;
10191 let src_b0: usize = (sy * buf_w_u + src_x0_u) * 4;
10192 let src_b1: usize = src_b0 + span_w * 4;
10193 if src_b1 <= src_bytes.len() && dst_b1 <= dst_row.len() {
10194 blit_1to1_rgba_span(
10195 &src_bytes[src_b0..src_b1],
10196 &mut dst_row[dst_b0..dst_b1],
10197 );
10198 }
10199 }
10200 return span_w * ((y1 - y0) as usize);
10201 }
10202 }
10203 let mut shaded: usize = 0;
10204 let ran_tls: bool = BAND_IMAGE_X_LUT
10205 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
10206 if let Ok(mut guard) = cell.try_borrow_mut() {
10207 shaded = Self::raster_sprite_region_with_lut(
10208 band,
10209 (rect, src_rect),
10210 (buf_w, buf_h, src_bytes),
10211 (x0, y0, x1, y1),
10212 tint,
10213 use_bilinear,
10214 &mut guard,
10215 );
10216 }
10217 })
10218 .is_ok();
10219 if !ran_tls {
10220 let mut fallback_lut: Vec<(usize, usize, u32)> = Vec::with_capacity((x1 - x0) as usize);
10221 shaded = Self::raster_sprite_region_with_lut(
10222 band,
10223 (rect, src_rect),
10224 (buf_w, buf_h, src_bytes),
10225 (x0, y0, x1, y1),
10226 tint,
10227 use_bilinear,
10228 &mut fallback_lut,
10229 );
10230 }
10231 shaded
10232 }
10233}