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