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(PositionedGlyph {
3555 glyph_idx: slot,
3556 x: gx0,
3557 y: gy0,
3558 width: gw_u16,
3559 height: gh_u16,
3560 });
3561 }
3562 }
3563 pen_x += adv_phys;
3564 }
3565 }
3566 } else {
3567 let (_, _): (CachedPositionedGlyphRun, &[PositionedGlyph]) =
3568 positioned_glyph_run_cache.insert_with(
3569 (key_hash, width_bits, phys_scale_milli),
3570 line_str.len(),
3571 |out_slab: &mut Vec<PositionedGlyph>| {
3572 let mut pen_x: f32 = 0.0;
3573 let mut has_frac: bool = false;
3574 let mut max_slot: u32 = 0;
3575 for &byte in line_str.as_bytes() {
3576 if byte == b' ' {
3577 pen_x += space_step;
3578 continue;
3579 }
3580 let slot: u32 = glyph_atlas
3581 .get_or_rasterize_ascii_slot_with(
3582 ascii_table_idx,
3583 byte,
3584 key_meta,
3585 font_provider,
3586 );
3587 max_slot = max_slot.max(slot);
3588 let glyph: &RasterizedGlyph =
3589 glyph_atlas.glyph_by_slot(slot);
3590 let adv_phys: f32 =
3591 (glyph.get_advance() as f32).max(1.0)
3592 + letter_sp;
3593 let pen_x_round: f32 = pen_x.round();
3594 if (pen_x - pen_x_round).abs() > 1e-4 {
3595 has_frac = true;
3596 }
3597 let gw_u32: u32 = glyph.get_width();
3598 let gh_u32: u32 = glyph.get_height();
3599 let gw_u16: u16 =
3600 gw_u32.min(u16::MAX as u32) as u16;
3601 let gh_u16: u16 =
3602 gh_u32.min(u16::MAX as u32) as u16;
3603 let rx: i32 = pen_x_round as i32;
3604 let ry: i32 =
3605 ((line_h_phys - (gh_u32 as f32)) * 0.5)
3606 .round()
3607 as i32;
3608 out_slab.push(PositionedGlyph {
3609 glyph_idx: slot,
3610 x: rx,
3611 y: ry,
3612 width: gw_u16,
3613 height: gh_u16,
3614 });
3615 if clip_ok {
3616 let gx0: i32 = bx_i + rx;
3617 let gy0: i32 = by_i + ry;
3618 if gx0 + (gw_u16 as i32) > clip_x0_i
3619 && gx0 < clip_x1_i
3620 && gy0 < clip_y1_i
3621 && gy0 + (gh_u16 as i32) > clip_y0_i
3622 {
3623 positioned_glyphs.push(
3624 PositionedGlyph {
3625 glyph_idx: slot,
3626 x: gx0,
3627 y: gy0,
3628 width: gw_u16,
3629 height: gh_u16,
3630 },
3631 );
3632 }
3633 }
3634 pen_x += adv_phys;
3635 }
3636 (has_frac, max_slot)
3637 },
3638 );
3639 }
3640 let run_len: u32 =
3641 (positioned_glyphs.len() as u32).saturating_sub(run_start);
3642 (run_start, run_len)
3643 } else {
3644 let (cached_run, cached_glyphs): (
3645 CachedPositionedGlyphRun,
3646 &[PositionedGlyph],
3647 ) = positioned_glyph_run_cache.insert_with(
3648 (key_hash, width_bits, phys_scale_milli),
3649 line_str.len(),
3650 |out_slab: &mut Vec<PositionedGlyph>| {
3651 Self::append_single_line_positioned_glyph_run(
3652 (line_str, line_h),
3653 *rect,
3654 *style,
3655 scale,
3656 (glyph_atlas, font_provider),
3657 line_scratch,
3658 out_slab,
3659 )
3660 },
3661 );
3662 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3663 Self::emit_cached_glyph_run(
3664 cached_glyphs,
3665 (base_x_phys as i32, base_y_phys as i32),
3666 (active_clip, phys_w, phys_h),
3667 positioned_glyphs,
3668 )
3669 } else {
3670 Self::resolve_single_line_glyphs(
3671 (line_str, line_h),
3672 *rect,
3673 *style,
3674 (active_clip, phys_w, phys_h, scale),
3675 (glyph_atlas, font_provider),
3676 positioned_glyphs,
3677 line_scratch,
3678 )
3679 }
3680 }
3681 } else {
3682 let width_key: u32 =
3683 ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3684 let layout_idx: u32 = text_layout_cache.get_or_insert_with(
3685 key_hash,
3686 width_key,
3687 || measurer.measure(text, *style, Some(max_w)),
3688 );
3689 if let Some(layout) = text_layout_cache.get(layout_idx) {
3690 let (cached_run, cached_glyphs): (
3691 CachedPositionedGlyphRun,
3692 &[PositionedGlyph],
3693 ) = positioned_glyph_run_cache.insert_with(
3694 (key_hash, width_bits, phys_scale_milli),
3695 text.len(),
3696 |out_slab: &mut Vec<PositionedGlyph>| {
3697 Self::append_cached_positioned_glyph_run(
3698 layout,
3699 *rect,
3700 *style,
3701 scale,
3702 (glyph_atlas, font_provider),
3703 line_scratch,
3704 out_slab,
3705 )
3706 },
3707 );
3708 if !cached_run.has_fractional_x || base_x_phys >= 0.0 {
3709 Self::emit_cached_glyph_run(
3710 cached_glyphs,
3711 (base_x_phys as i32, base_y_phys as i32),
3712 (active_clip, phys_w, phys_h),
3713 positioned_glyphs,
3714 )
3715 } else {
3716 Self::resolve_text_run_glyphs(
3717 layout,
3718 *rect,
3719 *style,
3720 (active_clip, phys_w, phys_h, scale),
3721 (glyph_atlas, font_provider),
3722 positioned_glyphs,
3723 line_scratch,
3724 )
3725 }
3726 } else {
3727 (0, 0)
3728 }
3729 }
3730 }
3731 } else {
3732 let max_w: f32 = rect.get_width().max(1.0);
3733 let width_key: u32 = ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
3734 let layout_idx: u32 =
3735 text_layout_cache.get_or_insert_with(key_hash, width_key, || {
3736 measurer.measure(text, *style, Some(max_w))
3737 });
3738 if let Some(layout) = text_layout_cache.get(layout_idx) {
3739 Self::resolve_text_run_glyphs(
3740 layout,
3741 *rect,
3742 *style,
3743 (active_clip, phys_w, phys_h, scale),
3744 (glyph_atlas, font_provider),
3745 positioned_glyphs,
3746 line_scratch,
3747 )
3748 } else {
3749 (0, 0)
3750 }
3751 };
3752 if glyph_run_len == 0 {
3753 continue;
3754 }
3755 let clip_x0_i: i32 = active_clip.get_x().ceil().max(0.0) as i32;
3756 let clip_y0_i: i32 =
3757 (active_clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
3758 let clip_x1_i: i32 =
3759 (active_clip.right().floor().max(0.0) as i32).min(phys_w as i32);
3760 let clip_y1_i: i32 =
3761 (active_clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
3762 let mut min_gx: i32 = i32::MAX;
3763 let mut min_gy: i32 = i32::MAX;
3764 let mut max_gx: i32 = i32::MIN;
3765 let mut max_gy: i32 = i32::MIN;
3766 let g_s: usize = glyph_run_start as usize;
3767 let g_e: usize = g_s.saturating_add(glyph_run_len as usize);
3768 for g in positioned_glyphs[g_s..g_e].iter() {
3769 let gx0: i32 = g.x.max(clip_x0_i);
3770 let gx1: i32 = (g.x + g.width as i32).min(clip_x1_i);
3771 let gy0: i32 = g.y.max(clip_y0_i);
3772 let gy1: i32 = (g.y + g.height as i32).min(clip_y1_i);
3773 if gx0 < gx1 && gy0 < gy1 {
3774 min_gx = min_gx.min(gx0);
3775 min_gy = min_gy.min(gy0);
3776 max_gx = max_gx.max(gx1);
3777 max_gy = max_gy.max(gy1);
3778 }
3779 }
3780 let (y0, y1, run_vis): (u32, u32, Rect) = if min_gx < max_gx && min_gy < max_gy
3781 {
3782 let ty0: u32 = (min_gy.max(0) as u32).min(phys_h);
3783 let ty1: u32 = (max_gy.max(0) as u32).min(phys_h);
3784 if ty0 >= ty1 {
3785 continue;
3786 }
3787 (
3788 ty0,
3789 ty1,
3790 Rect::new(
3791 min_gx as f32,
3792 min_gy as f32,
3793 (max_gx - min_gx) as f32,
3794 (max_gy - min_gy) as f32,
3795 ),
3796 )
3797 } else {
3798 (vis_y0, vis_y1, vis)
3799 };
3800 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3801 rounded_clip_stack.as_slice(),
3802 rounded_clips,
3803 run_vis,
3804 );
3805 if has_first_cmd {
3806 expand_opt_rect(prepped_fg_bounds, run_vis);
3807 }
3808 has_first_cmd = true;
3809 expand_opt_rect(prepped_bounds, run_vis);
3810 prepped.push(PreppedCommand {
3811 cmd_index,
3812 active_clip,
3813 y0,
3814 y1,
3815 opaque_cutout_h: Rect::default(),
3816 opaque_cutout_v: Rect::default(),
3817 glyph_run_start,
3818 glyph_run_len,
3819 caret_rect_idx: u32::MAX,
3820 rounded_clip_start: rc_start,
3821 rounded_clip_len: rc_len,
3822 skip_delta: 0,
3823 });
3824 }
3825 DrawCommand::TextCaret {
3826 text_rect,
3827 content_rect,
3828 text,
3829 style,
3830 caret_height,
3831 color,
3832 multiline,
3833 } => {
3834 if color.get_a() == 0 {
3835 continue;
3836 }
3837 let phys_content: Rect = Self::scale_rect(*content_rect, scale);
3838 let Some(vis) = phys_content.intersect(active_clip) else {
3839 continue;
3840 };
3841 let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3842 let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3843 if vis_y0 >= vis_y1 {
3844 continue;
3845 }
3846 let (max_w, width_key): (Option<f32>, u32) = if *multiline {
3847 let w: f32 = content_rect.get_width().max(1.0);
3848 (Some(w), ((w * 10.0).round() as u32).min(u32::MAX - 1))
3849 } else {
3850 (None, u32::MAX)
3851 };
3852 let key_hash: u64 = hash_text_layout_key(text, *style);
3853 let layout_idx: u32 =
3854 text_layout_cache.get_or_insert_with(key_hash, width_key, || {
3855 measurer.measure(text, *style, max_w)
3856 });
3857 let caret_rect: Rect = Self::resolve_text_caret_rect(
3858 text_layout_cache.get(layout_idx),
3859 (*text_rect, *content_rect),
3860 *style,
3861 (*caret_height, scale, *multiline),
3862 (glyph_atlas, font_provider),
3863 );
3864 let Some(caret_vis) = caret_rect.intersect(active_clip) else {
3865 continue;
3866 };
3867 let y0: u32 = (caret_vis.get_y().floor().max(0.0) as u32).min(phys_h);
3868 let y1: u32 = (caret_vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3869 if y0 >= y1 {
3870 continue;
3871 }
3872 let caret_rect_idx: u32 = caret_rects.len() as u32;
3873 caret_rects.push(caret_rect);
3874 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3875 rounded_clip_stack.as_slice(),
3876 rounded_clips,
3877 caret_vis,
3878 );
3879 if has_first_cmd {
3880 expand_opt_rect(prepped_fg_bounds, caret_vis);
3881 }
3882 has_first_cmd = true;
3883 expand_opt_rect(prepped_bounds, caret_vis);
3884 prepped.push(PreppedCommand {
3885 cmd_index,
3886 active_clip,
3887 y0,
3888 y1,
3889 opaque_cutout_h: Rect::default(),
3890 opaque_cutout_v: Rect::default(),
3891 glyph_run_start: 0,
3892 glyph_run_len: 0,
3893 caret_rect_idx,
3894 rounded_clip_start: rc_start,
3895 rounded_clip_len: rc_len,
3896 skip_delta: 0,
3897 });
3898 }
3899 DrawCommand::Line {
3900 from, to, width, ..
3901 } => {
3902 let half_w: f32 = (width * scale).max(1.0) * 0.5 + 1.0;
3903 let min_x: f32 = from.get_x().min(to.get_x()) * scale - half_w;
3904 let min_y: f32 = from.get_y().min(to.get_y()) * scale - half_w;
3905 let max_x: f32 = from.get_x().max(to.get_x()) * scale + half_w;
3906 let max_y: f32 = from.get_y().max(to.get_y()) * scale + half_w;
3907 if let Some(vis) =
3908 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
3909 {
3910 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3911 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3912 if y0 < y1 {
3913 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3914 rounded_clip_stack.as_slice(),
3915 rounded_clips,
3916 vis,
3917 );
3918 if has_first_cmd {
3919 expand_opt_rect(prepped_fg_bounds, vis);
3920 }
3921 has_first_cmd = true;
3922 expand_opt_rect(prepped_bounds, vis);
3923 prepped.push(PreppedCommand {
3924 cmd_index,
3925 active_clip,
3926 y0,
3927 y1,
3928 opaque_cutout_h: Rect::default(),
3929 opaque_cutout_v: Rect::default(),
3930 glyph_run_start: 0,
3931 glyph_run_len: 0,
3932 caret_rect_idx: u32::MAX,
3933 rounded_clip_start: rc_start,
3934 rounded_clip_len: rc_len,
3935 skip_delta: 0,
3936 });
3937 }
3938 }
3939 }
3940 DrawCommand::Circle { center, radius, .. } => {
3941 let r: f32 = radius * scale + 1.0;
3942 let bounds: Rect = Rect::new(
3943 center.get_x() * scale - r,
3944 center.get_y() * scale - r,
3945 r * 2.0,
3946 r * 2.0,
3947 );
3948 if let Some(vis) = bounds.intersect(active_clip) {
3949 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3950 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3951 if y0 < y1 {
3952 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3953 rounded_clip_stack.as_slice(),
3954 rounded_clips,
3955 vis,
3956 );
3957 if has_first_cmd {
3958 expand_opt_rect(prepped_fg_bounds, vis);
3959 }
3960 has_first_cmd = true;
3961 expand_opt_rect(prepped_bounds, vis);
3962 prepped.push(PreppedCommand {
3963 cmd_index,
3964 active_clip,
3965 y0,
3966 y1,
3967 opaque_cutout_h: Rect::default(),
3968 opaque_cutout_v: Rect::default(),
3969 glyph_run_start: 0,
3970 glyph_run_len: 0,
3971 caret_rect_idx: u32::MAX,
3972 rounded_clip_start: rc_start,
3973 rounded_clip_len: rc_len,
3974 skip_delta: 0,
3975 });
3976 }
3977 }
3978 }
3979 DrawCommand::Triangle { p0, p1, p2, .. } => {
3980 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.0;
3981 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.0;
3982 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.0;
3983 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.0;
3984 if let Some(vis) =
3985 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
3986 {
3987 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
3988 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
3989 if y0 < y1 {
3990 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
3991 rounded_clip_stack.as_slice(),
3992 rounded_clips,
3993 vis,
3994 );
3995 if has_first_cmd {
3996 expand_opt_rect(prepped_fg_bounds, vis);
3997 }
3998 has_first_cmd = true;
3999 expand_opt_rect(prepped_bounds, vis);
4000 prepped.push(PreppedCommand {
4001 cmd_index,
4002 active_clip,
4003 y0,
4004 y1,
4005 opaque_cutout_h: Rect::default(),
4006 opaque_cutout_v: Rect::default(),
4007 glyph_run_start: 0,
4008 glyph_run_len: 0,
4009 caret_rect_idx: u32::MAX,
4010 rounded_clip_start: rc_start,
4011 rounded_clip_len: rc_len,
4012 skip_delta: 0,
4013 });
4014 }
4015 }
4016 }
4017 }
4018 }
4019 while let Some((_, _, opt_slot)) = clip_scopes.pop() {
4020 if let Some(slot_idx) = opt_slot {
4021 let span_len: usize = prepped.len().saturating_sub(slot_idx);
4022 if span_len <= 1 {
4023 prepped.truncate(slot_idx);
4024 } else if span_len == 2 {
4025 let only_cmd: PreppedCommand = prepped[slot_idx + 1];
4026 prepped[slot_idx] = only_cmd;
4027 let _: Option<PreppedCommand> = prepped.pop();
4028 } else {
4029 prepped[slot_idx].skip_delta = span_len as u32;
4030 }
4031 }
4032 }
4033 let culled_now: usize = Self::cull_occluded_prepped_commands(
4034 commands,
4035 prepped,
4036 (phys_w, phys_h, scale),
4037 cull_keep_scratch,
4038 cull_compacted_scratch,
4039 cull_sentinels_scratch,
4040 );
4041 *culled_occluded_commands = culled_occluded_commands.saturating_add(culled_now as u64);
4042 glyph_atlas.set_slots_pinned(false);
4043 }
4044
4045 #[must_use]
4057 fn command_cull_bounds(cmd: &DrawCommand, active_clip: Rect, scale: f32) -> Option<Rect> {
4058 let raw: Rect = match cmd {
4059 DrawCommand::Clear(_) => active_clip,
4060 DrawCommand::FillRoundedRect { rect, .. }
4061 | DrawCommand::LinearGradientRect { rect, .. }
4062 | DrawCommand::Image { rect, .. }
4063 | DrawCommand::SharedImage { rect, .. }
4064 | DrawCommand::SpriteRegion { rect, .. }
4065 | DrawCommand::BackdropBlur { rect, .. } => snap_physical_rect(*rect, scale),
4066 DrawCommand::BoxShadow { rect, shadow, .. } => {
4067 let spread: f32 = shadow.get_spread_radius() * scale;
4068 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
4069 let sigma: f32 = (blur * 0.5).max(0.75);
4070 let pad: f32 = (sigma * 3.0).ceil();
4071 let base: Rect = snap_physical_rect(*rect, scale);
4072 Rect::new(
4073 base.get_x() + (shadow.get_offset_x() * scale).round() - spread - pad,
4074 base.get_y() + (shadow.get_offset_y() * scale).round() - spread - pad,
4075 (base.get_width() + spread * 2.0).max(1.0) + pad * 2.0,
4076 (base.get_height() + spread * 2.0).max(1.0) + pad * 2.0,
4077 )
4078 }
4079 DrawCommand::TextRun { rect, style, .. } => {
4080 let phys: Rect = Self::scale_rect(*rect, scale);
4081 let pad: f32 = style.get_font_size() * scale * 0.5 + 2.0;
4082 Rect::new(
4083 phys.get_x() - pad,
4084 phys.get_y() - pad,
4085 phys.get_width() + pad * 2.0,
4086 phys.get_height() + pad * 2.0,
4087 )
4088 }
4089 DrawCommand::TextCaret { content_rect, .. } => snap_physical_rect(*content_rect, scale),
4090 DrawCommand::Line {
4091 from, to, width, ..
4092 } => {
4093 let pad: f32 = (width * scale).max(1.0) + 2.0;
4094 let x0: f32 = from.get_x().min(to.get_x()) * scale - pad;
4095 let y0: f32 = from.get_y().min(to.get_y()) * scale - pad;
4096 let x1: f32 = from.get_x().max(to.get_x()) * scale + pad;
4097 let y1: f32 = from.get_y().max(to.get_y()) * scale + pad;
4098 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
4099 }
4100 DrawCommand::Circle { center, radius, .. } => {
4101 let r: f32 = radius * scale + 2.0;
4102 Rect::new(
4103 center.get_x() * scale - r,
4104 center.get_y() * scale - r,
4105 r * 2.0,
4106 r * 2.0,
4107 )
4108 }
4109 DrawCommand::Triangle { p0, p1, p2, .. } => {
4110 let x0: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 2.0;
4111 let y0: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 2.0;
4112 let x1: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 2.0;
4113 let y1: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 2.0;
4114 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
4115 }
4116 DrawCommand::PushClip(_)
4117 | DrawCommand::PushRoundedClip { .. }
4118 | DrawCommand::PopClip => {
4119 return None;
4120 }
4121 };
4122 raw.intersect(active_clip)
4123 }
4124
4125 #[must_use]
4137 fn opaque_inscribed_rect(cmd: &DrawCommand, item: PreppedCommand, scale: f32) -> Option<Rect> {
4138 if item.get_rounded_clip_len() != 0 {
4139 return None;
4140 }
4141 let (rect, radius): (Rect, CornerRadius) = match cmd {
4142 DrawCommand::FillRoundedRect {
4143 rect,
4144 color,
4145 radius,
4146 border,
4147 } if color.get_a() == 255
4148 && (border.get_width() <= 0.0 || border.get_color().get_a() == 255) =>
4149 {
4150 (*rect, *radius)
4151 }
4152 DrawCommand::LinearGradientRect {
4153 rect,
4154 gradient,
4155 radius,
4156 } if gradient.get_start_color().get_a() == 255
4157 && gradient.get_end_color().get_a() == 255 =>
4158 {
4159 (*rect, *radius)
4160 }
4161 _ => return None,
4162 };
4163 let phys: Rect = snap_physical_rect(rect, scale);
4164 let phys_r: CornerRadius = Self::scale_radius(radius, scale);
4165 let max_r: f32 = phys_r
4166 .max_radius()
4167 .min(phys.get_width() * 0.5)
4168 .min(phys.get_height() * 0.5);
4169 let inscribed: Rect = if max_r > 0.0 {
4170 phys.inset(Edges::all(max_r.ceil()))
4171 } else {
4172 phys
4173 };
4174 if inscribed.get_width() < 1.0 || inscribed.get_height() < 1.0 {
4175 return None;
4176 }
4177 let occ: Rect = inscribed.intersect(item.get_active_clip())?;
4178 if occ.get_width() >= 1.0 && occ.get_height() >= 1.0 {
4179 Some(occ)
4180 } else {
4181 None
4182 }
4183 }
4184
4185 fn cull_occluded_prepped_commands(
4200 commands: &[DrawCommand],
4201 prepped: &mut Vec<PreppedCommand>,
4202 dims: (u32, u32, f32),
4203 keep: &mut Vec<bool>,
4204 compacted: &mut Vec<PreppedCommand>,
4205 open_sentinels: &mut Vec<(usize, usize)>,
4206 ) -> usize {
4207 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
4208 let len: usize = prepped.len();
4209 if len < 2 {
4210 return 0;
4211 }
4212 keep.clear();
4213 keep.resize(len, true);
4214 let mut occluders: [Rect; OCCLUSION_MAX_OCCLUDERS] =
4215 [Rect::default(); OCCLUSION_MAX_OCCLUDERS];
4216 let mut occluder_count: usize = 0;
4217 let mut combined_tile_mask: u64 = 0;
4218 let mut culled: usize = 0;
4219 for idx in (0..len).rev() {
4220 let item: PreppedCommand = prepped[idx];
4221 if item.get_cmd_index() == usize::MAX {
4222 continue;
4223 }
4224 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
4225 if matches!(cmd, DrawCommand::BackdropBlur { .. }) {
4226 occluder_count = 0;
4227 combined_tile_mask = 0;
4228 continue;
4229 }
4230 if (occluder_count > 0 || combined_tile_mask != 0)
4231 && let Some(vis) = Self::command_cull_bounds(cmd, item.get_active_clip(), scale)
4232 {
4233 let vis_mask: u64 = occlusion_tile_mask_overlapped(vis, phys_w, phys_h);
4234 let mut covered: bool =
4235 vis_mask != 0 && (vis_mask & combined_tile_mask) == vis_mask;
4236 if !covered {
4237 for occ in occluders.iter().take(occluder_count) {
4238 if vis.get_x() >= occ.get_x()
4239 && vis.get_y() >= occ.get_y()
4240 && vis.right() <= occ.right()
4241 && vis.bottom() <= occ.bottom()
4242 {
4243 covered = true;
4244 break;
4245 }
4246 }
4247 }
4248 if covered {
4249 keep[idx] = false;
4250 culled += 1;
4251 continue;
4252 }
4253 }
4254 if let Some(occ) = Self::opaque_inscribed_rect(cmd, item, scale) {
4255 combined_tile_mask |= occlusion_tile_mask_contained(occ, phys_w, phys_h);
4256 if occluder_count < OCCLUSION_MAX_OCCLUDERS {
4257 occluders[occluder_count] = occ;
4258 occluder_count += 1;
4259 } else {
4260 let occ_area: f32 = occ.get_width() * occ.get_height();
4261 let mut min_i: usize = 0;
4262 let mut min_area: f32 = occluders[0].get_width() * occluders[0].get_height();
4263 for (slot, occ_ref) in occluders
4264 .iter()
4265 .enumerate()
4266 .take(OCCLUSION_MAX_OCCLUDERS)
4267 .skip(1)
4268 {
4269 let area: f32 = occ_ref.get_width() * occ_ref.get_height();
4270 if area < min_area {
4271 min_area = area;
4272 min_i = slot;
4273 }
4274 }
4275 if occ_area > min_area {
4276 occluders[min_i] = occ;
4277 }
4278 }
4279 }
4280 }
4281 if culled == 0 {
4282 return 0;
4283 }
4284 compacted.clear();
4285 compacted.reserve(len.saturating_sub(culled));
4286 open_sentinels.clear();
4287 for (old_idx, &kept) in keep.iter().enumerate() {
4288 while let Some(&(new_s, old_end)) = open_sentinels.last() {
4289 if old_end <= old_idx {
4290 let _: Option<(usize, usize)> = open_sentinels.pop();
4291 let span: u32 = (compacted.len().saturating_sub(new_s)).max(1) as u32;
4292 compacted[new_s].set_skip_delta(span);
4293 } else {
4294 break;
4295 }
4296 }
4297 if kept {
4298 let item: PreppedCommand = prepped[old_idx];
4299 if item.get_cmd_index() == usize::MAX {
4300 let old_end: usize = old_idx.saturating_add(item.get_skip_delta() as usize);
4301 open_sentinels.push((compacted.len(), old_end));
4302 }
4303 compacted.push(item);
4304 }
4305 }
4306 while let Some((new_s, _)) = open_sentinels.pop() {
4307 let span: u32 = (compacted.len().saturating_sub(new_s)).max(1) as u32;
4308 compacted[new_s].set_skip_delta(span);
4309 }
4310 swap(prepped, compacted);
4311 culled
4312 }
4313
4314 fn raster_backdrop_blur(
4328 band: &mut PixelBand<'_>,
4329 rect: Rect,
4330 radius: CornerRadius,
4331 blur_radius: f32,
4332 clip: Rect,
4333 ) -> usize {
4334 let Some(vis) = rect.intersect(clip) else {
4335 return 0;
4336 };
4337 let bw: u32 = band.width();
4338 let band_y0: u32 = band.y_offset();
4339 let band_y1: u32 = band.y_end();
4340 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(bw);
4341 let x1: u32 = (vis.right().ceil().max(0.0) as u32).clamp(x0, bw);
4342 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
4343 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(y0, band_y1);
4344 if x0 >= x1 || y0 >= y1 {
4345 return 0;
4346 }
4347 let rad: u32 = (blur_radius * 0.5).round().clamp(1.0, 24.0) as u32;
4348 let sx0: u32 = x0.saturating_sub(rad);
4349 let sx1: u32 = x1.saturating_add(rad).min(bw);
4350 let sy0: u32 = y0.saturating_sub(rad).max(band_y0);
4351 let sy1: u32 = y1.saturating_add(rad).min(band_y1);
4352 let sw: u32 = sx1.saturating_sub(sx0);
4353 let sh: u32 = sy1.saturating_sub(sy0);
4354 let needed: usize = (sw as usize).saturating_mul(sh as usize);
4355 if needed == 0 {
4356 return 0;
4357 }
4358 let mut horiz: Vec<[u8; 4]> = BAND_BLUR_HORIZ_SCRATCH
4359 .try_with(|cell: &RefCell<Vec<[u8; 4]>>| {
4360 cell.try_borrow_mut()
4361 .ok()
4362 .map(|mut guard: RefMut<'_, Vec<[u8; 4]>>| take(&mut *guard))
4363 })
4364 .ok()
4365 .flatten()
4366 .unwrap_or_default();
4367 if horiz.len() < needed {
4368 horiz.resize(needed, [0, 0, 0, 0]);
4369 }
4370 let y0_rel: u32 = y0.saturating_sub(band_y0);
4371 let y1_rel: u32 = y1.saturating_sub(band_y0);
4372 let sy0_rel: u32 = sy0.saturating_sub(band_y0);
4373 let shifted_rect: Rect = Rect::new(
4374 rect.get_x(),
4375 rect.get_y() - (band_y0 as f32),
4376 rect.get_width(),
4377 rect.get_height(),
4378 );
4379 let desc: BlurPassDesc = BlurPassDesc {
4380 #[cfg(not(target_arch = "wasm32"))]
4381 fb_ptr: 0,
4382 #[cfg(not(target_arch = "wasm32"))]
4383 fb_len: 0,
4384 fb_w: bw,
4385 #[cfg(not(target_arch = "wasm32"))]
4386 horiz_ptr: 0,
4387 #[cfg(not(target_arch = "wasm32"))]
4388 horiz_len: needed,
4389 sx0,
4390 sy0: sy0_rel,
4391 sw,
4392 sh,
4393 x0,
4394 x1,
4395 y0: y0_rel,
4396 y1: y1_rel,
4397 rad,
4398 inv_win_q24: blur_inv_window_q24(rad),
4399 has_radius: radius.max_radius() > 0.25,
4400 rect: shifted_rect,
4401 radius,
4402 #[cfg(not(target_arch = "wasm32"))]
4403 strip_count: 1,
4404 #[cfg(not(target_arch = "wasm32"))]
4405 strip_rows: sh.max(1),
4406 };
4407 let horiz_slice: &mut [[u8; 4]] = &mut horiz[..needed];
4408 blur_horiz_strip_slices(band.pixels, horiz_slice, &desc, (0, sh as usize));
4409 let fb_stride: usize = (bw as usize) * 4;
4410 let strip_start: usize = (y0_rel as usize).saturating_mul(fb_stride);
4411 let strip_end: usize = (y1_rel as usize).saturating_mul(fb_stride);
4412 let shaded: usize = if let Some(fb_strip) = band.pixels.get_mut(strip_start..strip_end) {
4413 blur_vert_strip_slices(fb_strip, horiz_slice, &desc, (y0_rel, y1_rel))
4414 } else {
4415 0
4416 };
4417 let _: bool = BAND_BLUR_HORIZ_SCRATCH
4418 .try_with(|cell: &RefCell<Vec<[u8; 4]>>| {
4419 if let Ok(mut guard) = cell.try_borrow_mut() {
4420 *guard = horiz;
4421 }
4422 })
4423 .is_ok();
4424 shaded
4425 }
4426
4427 #[must_use]
4437 pub fn text_layout_cache_stats(&self) -> (u64, u64, u64, usize) {
4438 self.get_text_layout_cache().stats()
4439 }
4440
4441 fn append_relative_line_glyphs(
4453 line_info: (&str, f32),
4454 metrics: (f32, f32, f32, f32),
4455 font_meta: (TextAlign, usize, (u16, bool, bool, bool)),
4456 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4457 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4458 out_glyphs: &mut Vec<PositionedGlyph>,
4459 state: (&mut bool, &mut u32),
4460 ) {
4461 let (line_str, line_off_y): (&str, f32) = line_info;
4462 let (line_h_phys, box_w_phys, letter_sp, space_step): (f32, f32, f32, f32) = metrics;
4463 let (align, ascii_table_idx, key_meta): (TextAlign, usize, (u16, bool, bool, bool)) =
4464 font_meta;
4465 let (size_tenths, bold, monospace, italic): (u16, bool, bool, bool) = key_meta;
4466 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4467 let (has_fractional_x, max_glyph_slot): (&mut bool, &mut u32) = state;
4468 if align == TextAlign::Left {
4469 let mut pen_x: f32 = 0.0;
4470 if line_str.is_ascii() {
4471 for &byte in line_str.as_bytes() {
4472 if byte == b' ' {
4473 pen_x += space_step;
4474 continue;
4475 }
4476 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
4477 ascii_table_idx,
4478 byte,
4479 key_meta,
4480 font_provider,
4481 );
4482 *max_glyph_slot = (*max_glyph_slot).max(slot);
4483 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4484 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4485 let pen_x_round: f32 = pen_x.round();
4486 if (pen_x - pen_x_round).abs() > 1e-4 {
4487 *has_fractional_x = true;
4488 }
4489 let gh: u32 = glyph.get_height();
4490 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
4491 out_glyphs.push(PositionedGlyph {
4492 glyph_idx: slot,
4493 x: pen_x_round as i32,
4494 y: (line_off_y + glyph_v_off) as i32,
4495 width: glyph.get_width().min(u16::MAX as u32) as u16,
4496 height: gh.min(u16::MAX as u32) as u16,
4497 });
4498 pen_x += adv_phys;
4499 }
4500 } else {
4501 for ch in line_str.chars() {
4502 if ch == ' ' {
4503 pen_x += space_step;
4504 continue;
4505 }
4506 let slot: u32 = if ch.is_ascii() {
4507 glyph_atlas.get_or_rasterize_ascii_slot_with(
4508 ascii_table_idx,
4509 ch as u8,
4510 key_meta,
4511 font_provider,
4512 )
4513 } else {
4514 let key: GlyphKey = GlyphKey {
4515 codepoint: ch,
4516 size_tenths,
4517 bold,
4518 monospace,
4519 italic,
4520 };
4521 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4522 };
4523 *max_glyph_slot = (*max_glyph_slot).max(slot);
4524 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4525 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4526 let pen_x_round: f32 = pen_x.round();
4527 if (pen_x - pen_x_round).abs() > 1e-4 {
4528 *has_fractional_x = true;
4529 }
4530 let gh: u32 = glyph.get_height();
4531 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
4532 out_glyphs.push(PositionedGlyph {
4533 glyph_idx: slot,
4534 x: pen_x_round as i32,
4535 y: (line_off_y + glyph_v_off) as i32,
4536 width: glyph.get_width().min(u16::MAX as u32) as u16,
4537 height: gh.min(u16::MAX as u32) as u16,
4538 });
4539 pen_x += adv_phys;
4540 }
4541 }
4542 } else {
4543 line_scratch.clear();
4544 let mut line_w_phys: f32 = 0.0;
4545 if line_str.is_ascii() {
4546 for &byte in line_str.as_bytes() {
4547 if byte == b' ' {
4548 line_w_phys += space_step;
4549 line_scratch.push((u32::MAX, space_step, 0, 0));
4550 } else {
4551 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
4552 ascii_table_idx,
4553 byte,
4554 key_meta,
4555 font_provider,
4556 );
4557 *max_glyph_slot = (*max_glyph_slot).max(slot);
4558 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4559 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4560 line_w_phys += adv_phys;
4561 line_scratch.push((
4562 slot,
4563 adv_phys,
4564 glyph.get_width().min(u16::MAX as u32) as u16,
4565 glyph.get_height().min(u16::MAX as u32) as u16,
4566 ));
4567 }
4568 }
4569 } else {
4570 for ch in line_str.chars() {
4571 if ch == ' ' {
4572 line_w_phys += space_step;
4573 line_scratch.push((u32::MAX, space_step, 0, 0));
4574 } else {
4575 let slot: u32 = if ch.is_ascii() {
4576 glyph_atlas.get_or_rasterize_ascii_slot_with(
4577 ascii_table_idx,
4578 ch as u8,
4579 key_meta,
4580 font_provider,
4581 )
4582 } else {
4583 let key: GlyphKey = GlyphKey {
4584 codepoint: ch,
4585 size_tenths,
4586 bold,
4587 monospace,
4588 italic,
4589 };
4590 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4591 };
4592 *max_glyph_slot = (*max_glyph_slot).max(slot);
4593 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4594 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4595 line_w_phys += adv_phys;
4596 line_scratch.push((
4597 slot,
4598 adv_phys,
4599 glyph.get_width().min(u16::MAX as u32) as u16,
4600 glyph.get_height().min(u16::MAX as u32) as u16,
4601 ));
4602 }
4603 }
4604 }
4605 let align_x: f32 = if align == TextAlign::Center {
4606 ((box_w_phys - line_w_phys) * 0.5).max(0.0)
4607 } else {
4608 (box_w_phys - line_w_phys).max(0.0)
4609 };
4610 let mut pen_x: f32 = align_x.round();
4611 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4612 if slot == u32::MAX {
4613 pen_x += adv_phys;
4614 continue;
4615 }
4616 let pen_x_round: f32 = pen_x.round();
4617 if (pen_x - pen_x_round).abs() > 1e-4 {
4618 *has_fractional_x = true;
4619 }
4620 let glyph_v_off: f32 = ((line_h_phys - (gh_u16 as f32)) * 0.5).round();
4621 out_glyphs.push(PositionedGlyph {
4622 glyph_idx: slot,
4623 x: pen_x_round as i32,
4624 y: (line_off_y + glyph_v_off) as i32,
4625 width: gw_u16,
4626 height: gh_u16,
4627 });
4628 pen_x += adv_phys;
4629 }
4630 }
4631 }
4632
4633 fn append_single_line_positioned_glyph_run(
4649 line_info: (&str, f32),
4650 rect: Rect,
4651 style: TextStyle,
4652 scale: f32,
4653 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4654 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4655 out_glyphs: &mut Vec<PositionedGlyph>,
4656 ) -> (bool, u32) {
4657 let (line_str, line_height_px): (&str, f32) = line_info;
4658 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4659 let phys_font_size: f32 = style.get_font_size() * scale;
4660 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4661 let bold: bool = style.get_weight().is_bold();
4662 let monospace: bool = style.get_family() == FontFamily::Monospace;
4663 let italic: bool = style.get_italic();
4664 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4665 let ascii_table_idx: usize =
4666 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4667 let line_h_phys: f32 = line_height_px * scale;
4668 let box_w_phys: f32 = rect.get_width() * scale;
4669 let letter_sp: f32 = style.get_letter_spacing() * scale;
4670 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4671 let mut has_fractional_x: bool = false;
4672 let mut max_glyph_slot: u32 = 0;
4673 Self::append_relative_line_glyphs(
4674 (line_str, 0.0),
4675 (line_h_phys, box_w_phys, letter_sp, space_step),
4676 (style.get_align(), ascii_table_idx, key_meta),
4677 (glyph_atlas, font_provider),
4678 line_scratch,
4679 out_glyphs,
4680 (&mut has_fractional_x, &mut max_glyph_slot),
4681 );
4682 (has_fractional_x, max_glyph_slot)
4683 }
4684
4685 fn append_cached_positioned_glyph_run(
4701 layout: &TextLayoutResult,
4702 rect: Rect,
4703 style: TextStyle,
4704 scale: f32,
4705 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4706 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4707 out_glyphs: &mut Vec<PositionedGlyph>,
4708 ) -> (bool, u32) {
4709 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4710 let phys_font_size: f32 = style.get_font_size() * scale;
4711 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4712 let bold: bool = style.get_weight().is_bold();
4713 let monospace: bool = style.get_family() == FontFamily::Monospace;
4714 let italic: bool = style.get_italic();
4715 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4716 let ascii_table_idx: usize =
4717 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4718 let line_h_phys: f32 = layout.get_line_height_px() * scale;
4719 let box_w_phys: f32 = rect.get_width() * scale;
4720 let letter_sp: f32 = style.get_letter_spacing() * scale;
4721 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4722 let align: TextAlign = style.get_align();
4723 let mut has_fractional_x: bool = false;
4724 let mut max_glyph_slot: u32 = 0;
4725 for (line_idx, line) in layout.get_lines().iter().enumerate() {
4726 let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
4727 Self::append_relative_line_glyphs(
4728 (line.get_text().as_str(), line_off_y),
4729 (line_h_phys, box_w_phys, letter_sp, space_step),
4730 (align, ascii_table_idx, key_meta),
4731 (glyph_atlas, font_provider),
4732 line_scratch,
4733 out_glyphs,
4734 (&mut has_fractional_x, &mut max_glyph_slot),
4735 );
4736 }
4737 (has_fractional_x, max_glyph_slot)
4738 }
4739
4740 fn emit_cached_glyph_run(
4753 cached_glyphs: &[PositionedGlyph],
4754 origin: (i32, i32),
4755 clip_dims: (Rect, u32, u32),
4756 out_glyphs: &mut Vec<PositionedGlyph>,
4757 ) -> (u32, u32) {
4758 let (base_x, base_y): (i32, i32) = origin;
4759 let (clip, phys_w, phys_h): (Rect, u32, u32) = clip_dims;
4760 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4761 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4762 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4763 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4764 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4765 return (0, 0);
4766 }
4767 let run_start: u32 = out_glyphs.len() as u32;
4768 for g in cached_glyphs.iter() {
4769 let gx0: i32 = base_x + g.x;
4770 let gw: i32 = g.width as i32;
4771 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4772 let gy0: i32 = base_y + g.y;
4773 let gh: i32 = g.height as i32;
4774 if gy0 < clip_y1 && gy0 + gh > clip_y0 {
4775 out_glyphs.push(PositionedGlyph {
4776 glyph_idx: g.glyph_idx,
4777 x: gx0,
4778 y: gy0,
4779 width: g.width,
4780 height: g.height,
4781 });
4782 }
4783 }
4784 }
4785 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
4786 (run_start, run_len)
4787 }
4788
4789 fn resolve_single_line_glyphs(
4805 line_info: (&str, f32),
4806 rect: Rect,
4807 style: TextStyle,
4808 clip_dims: (Rect, u32, u32, f32),
4809 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4810 out_glyphs: &mut Vec<PositionedGlyph>,
4811 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4812 ) -> (u32, u32) {
4813 let (line_str, line_height_px): (&str, f32) = line_info;
4814 let (clip, phys_w, phys_h, scale): (Rect, u32, u32, f32) = clip_dims;
4815 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4816 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4817 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4818 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4819 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4820 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4821 return (0, 0);
4822 }
4823 let line_h_phys: f32 = line_height_px * scale;
4824 let base_x_phys: f32 = (rect.get_x() * scale).round();
4825 let base_y_phys: f32 = (rect.get_y() * scale).round();
4826 if (base_y_phys + line_h_phys) < (clip_y0 as f32) || base_y_phys > (clip_y1 as f32) {
4827 return (0, 0);
4828 }
4829 let phys_font_size: f32 = style.get_font_size() * scale;
4830 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4831 let bold: bool = style.get_weight().is_bold();
4832 let monospace: bool = style.get_family() == FontFamily::Monospace;
4833 let italic: bool = style.get_italic();
4834 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
4835 let ascii_table_idx: usize =
4836 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
4837 let box_w_phys: f32 = rect.get_width() * scale;
4838 let letter_sp: f32 = style.get_letter_spacing() * scale;
4839 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
4840 let align: TextAlign = style.get_align();
4841 let run_start: u32 = out_glyphs.len() as u32;
4842 let clip_x1_f: f32 = clip_x1 as f32;
4843 if align == TextAlign::Left {
4844 let mut pen_x: f32 = base_x_phys;
4845 for ch in line_str.chars() {
4846 if pen_x > clip_x1_f {
4847 break;
4848 }
4849 if ch == ' ' {
4850 pen_x += space_step;
4851 continue;
4852 }
4853 let slot: u32 = if ch.is_ascii() {
4854 glyph_atlas.get_or_rasterize_ascii_slot_with(
4855 ascii_table_idx,
4856 ch as u8,
4857 key_meta,
4858 font_provider,
4859 )
4860 } else {
4861 let key: GlyphKey = GlyphKey {
4862 codepoint: ch,
4863 size_tenths,
4864 bold,
4865 monospace,
4866 italic,
4867 };
4868 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4869 };
4870 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4871 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4872 let gx0: i32 = pen_x.round() as i32;
4873 let gw: i32 = glyph.get_width() as i32;
4874 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4875 let gh: u32 = glyph.get_height();
4876 let gy0: i32 =
4877 (base_y_phys + ((line_h_phys - (gh as f32)) * 0.5).round()) as i32;
4878 if gy0 < clip_y1 && gy0 + (gh as i32) > clip_y0 {
4879 out_glyphs.push(PositionedGlyph {
4880 glyph_idx: slot,
4881 x: gx0,
4882 y: gy0,
4883 width: glyph.get_width().min(u16::MAX as u32) as u16,
4884 height: gh.min(u16::MAX as u32) as u16,
4885 });
4886 }
4887 }
4888 pen_x += adv_phys;
4889 }
4890 } else {
4891 line_scratch.clear();
4892 let mut line_w_phys: f32 = 0.0;
4893 for ch in line_str.chars() {
4894 if ch == ' ' {
4895 line_w_phys += space_step;
4896 line_scratch.push((u32::MAX, space_step, 0, 0));
4897 } else {
4898 let slot: u32 = if ch.is_ascii() {
4899 glyph_atlas.get_or_rasterize_ascii_slot_with(
4900 ascii_table_idx,
4901 ch as u8,
4902 key_meta,
4903 font_provider,
4904 )
4905 } else {
4906 let key: GlyphKey = GlyphKey {
4907 codepoint: ch,
4908 size_tenths,
4909 bold,
4910 monospace,
4911 italic,
4912 };
4913 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
4914 };
4915 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
4916 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
4917 line_w_phys += adv_phys;
4918 line_scratch.push((
4919 slot,
4920 adv_phys,
4921 glyph.get_width().min(u16::MAX as u32) as u16,
4922 glyph.get_height().min(u16::MAX as u32) as u16,
4923 ));
4924 }
4925 }
4926 let align_x: f32 = if align == TextAlign::Center {
4927 ((box_w_phys - line_w_phys) * 0.5).max(0.0)
4928 } else {
4929 (box_w_phys - line_w_phys).max(0.0)
4930 };
4931 let mut pen_x: f32 = base_x_phys + align_x.round();
4932 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
4933 if pen_x > clip_x1_f {
4934 break;
4935 }
4936 if slot == u32::MAX {
4937 pen_x += adv_phys;
4938 continue;
4939 }
4940 let gx0: i32 = pen_x.round() as i32;
4941 let gw: i32 = gw_u16 as i32;
4942 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
4943 let gy0: i32 =
4944 (base_y_phys + ((line_h_phys - (gh_u16 as f32)) * 0.5).round()) as i32;
4945 if gy0 < clip_y1 && gy0 + (gh_u16 as i32) > clip_y0 {
4946 out_glyphs.push(PositionedGlyph {
4947 glyph_idx: slot,
4948 x: gx0,
4949 y: gy0,
4950 width: gw_u16,
4951 height: gh_u16,
4952 });
4953 }
4954 }
4955 pen_x += adv_phys;
4956 }
4957 }
4958 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
4959 (run_start, run_len)
4960 }
4961
4962 fn resolve_text_run_glyphs(
4978 layout: &TextLayoutResult,
4979 rect: Rect,
4980 style: TextStyle,
4981 clip_dims: (Rect, u32, u32, f32),
4982 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
4983 out_glyphs: &mut Vec<PositionedGlyph>,
4984 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
4985 ) -> (u32, u32) {
4986 let (clip, phys_w, phys_h, scale): (Rect, u32, u32, f32) = clip_dims;
4987 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
4988 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
4989 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
4990 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
4991 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
4992 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
4993 return (0, 0);
4994 }
4995 let phys_font_size: f32 = style.get_font_size() * scale;
4996 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
4997 let bold: bool = style.get_weight().is_bold();
4998 let monospace: bool = style.get_family() == FontFamily::Monospace;
4999 let italic: bool = style.get_italic();
5000 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
5001 let ascii_table_idx: usize =
5002 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
5003 let line_h_phys: f32 = layout.get_line_height_px() * scale;
5004 let box_w_phys: f32 = rect.get_width() * scale;
5005 let letter_sp: f32 = style.get_letter_spacing() * scale;
5006 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
5007 let base_x_phys: f32 = (rect.get_x() * scale).round();
5008 let base_y_phys: f32 = (rect.get_y() * scale).round();
5009 let clip_x1_f: f32 = clip_x1 as f32;
5010 let clip_y0_f: f32 = clip_y0 as f32;
5011 let clip_y1_f: f32 = clip_y1 as f32;
5012 let align: TextAlign = style.get_align();
5013 let run_start: u32 = out_glyphs.len() as u32;
5014 for (line_idx, line) in layout.get_lines().iter().enumerate() {
5015 let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
5016 let pen_y: f32 = base_y_phys + line_off_y;
5017 if (pen_y + line_h_phys) < clip_y0_f || pen_y > clip_y1_f {
5018 continue;
5019 }
5020 let line_str: &str = line.get_text().as_str();
5021 if align == TextAlign::Left {
5022 let mut pen_x: f32 = base_x_phys;
5023 if line_str.is_ascii() {
5024 for &byte in line_str.as_bytes() {
5025 if byte == b' ' {
5026 pen_x += space_step;
5027 continue;
5028 }
5029 if pen_x > clip_x1_f {
5030 break;
5031 }
5032 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
5033 ascii_table_idx,
5034 byte,
5035 key_meta,
5036 font_provider,
5037 );
5038 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
5039 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
5040 let gx0: i32 = pen_x.round() as i32;
5041 let gw: i32 = glyph.get_width() as i32;
5042 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
5043 let gh: u32 = glyph.get_height();
5044 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
5045 let gy0: i32 = (pen_y + glyph_v_off) as i32;
5046 if gy0 < clip_y1 && gy0 + (gh as i32) > clip_y0 {
5047 out_glyphs.push(PositionedGlyph {
5048 glyph_idx: slot,
5049 x: gx0,
5050 y: gy0,
5051 width: (gw as u32).min(u16::MAX as u32) as u16,
5052 height: gh.min(u16::MAX as u32) as u16,
5053 });
5054 }
5055 }
5056 pen_x += adv_phys;
5057 }
5058 } else {
5059 for ch in line_str.chars() {
5060 if ch == ' ' {
5061 pen_x += space_step;
5062 continue;
5063 }
5064 if pen_x > clip_x1_f {
5065 break;
5066 }
5067 let slot: u32 = if ch.is_ascii() {
5068 glyph_atlas.get_or_rasterize_ascii_slot_with(
5069 ascii_table_idx,
5070 ch as u8,
5071 key_meta,
5072 font_provider,
5073 )
5074 } else {
5075 let key: GlyphKey = GlyphKey {
5076 codepoint: ch,
5077 size_tenths,
5078 bold,
5079 monospace,
5080 italic,
5081 };
5082 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
5083 };
5084 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
5085 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
5086 let gx0: i32 = pen_x.round() as i32;
5087 let gw: i32 = glyph.get_width() as i32;
5088 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
5089 let gh: u32 = glyph.get_height();
5090 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
5091 let gy0: i32 = (pen_y + glyph_v_off) as i32;
5092 if gy0 < clip_y1 && gy0 + (gh as i32) > clip_y0 {
5093 out_glyphs.push(PositionedGlyph {
5094 glyph_idx: slot,
5095 x: gx0,
5096 y: gy0,
5097 width: (gw as u32).min(u16::MAX as u32) as u16,
5098 height: gh.min(u16::MAX as u32) as u16,
5099 });
5100 }
5101 }
5102 pen_x += adv_phys;
5103 }
5104 }
5105 } else {
5106 line_scratch.clear();
5107 let mut line_w_phys: f32 = 0.0;
5108 if line_str.is_ascii() {
5109 for &byte in line_str.as_bytes() {
5110 if byte == b' ' {
5111 line_w_phys += space_step;
5112 line_scratch.push((u32::MAX, space_step, 0, 0));
5113 } else {
5114 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
5115 ascii_table_idx,
5116 byte,
5117 key_meta,
5118 font_provider,
5119 );
5120 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
5121 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
5122 line_w_phys += adv_phys;
5123 line_scratch.push((
5124 slot,
5125 adv_phys,
5126 glyph.get_width().min(u16::MAX as u32) as u16,
5127 glyph.get_height().min(u16::MAX as u32) as u16,
5128 ));
5129 }
5130 }
5131 } else {
5132 for ch in line_str.chars() {
5133 if ch == ' ' {
5134 line_w_phys += space_step;
5135 line_scratch.push((u32::MAX, space_step, 0, 0));
5136 } else {
5137 let slot: u32 = if ch.is_ascii() {
5138 glyph_atlas.get_or_rasterize_ascii_slot_with(
5139 ascii_table_idx,
5140 ch as u8,
5141 key_meta,
5142 font_provider,
5143 )
5144 } else {
5145 let key: GlyphKey = GlyphKey {
5146 codepoint: ch,
5147 size_tenths,
5148 bold,
5149 monospace,
5150 italic,
5151 };
5152 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
5153 };
5154 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
5155 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
5156 line_w_phys += adv_phys;
5157 line_scratch.push((
5158 slot,
5159 adv_phys,
5160 glyph.get_width().min(u16::MAX as u32) as u16,
5161 glyph.get_height().min(u16::MAX as u32) as u16,
5162 ));
5163 }
5164 }
5165 }
5166 let align_x: f32 = if align == TextAlign::Center {
5167 ((box_w_phys - line_w_phys) * 0.5).max(0.0)
5168 } else {
5169 (box_w_phys - line_w_phys).max(0.0)
5170 };
5171 let mut pen_x: f32 = base_x_phys + align_x.round();
5172 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
5173 if slot == u32::MAX {
5174 pen_x += adv_phys;
5175 continue;
5176 }
5177 if pen_x > clip_x1_f {
5178 break;
5179 }
5180 let gx0: i32 = pen_x.round() as i32;
5181 let gw: i32 = gw_u16 as i32;
5182 let gh: i32 = gh_u16 as i32;
5183 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
5184 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
5185 let gy0: i32 = (pen_y + glyph_v_off) as i32;
5186 if gy0 < clip_y1 && gy0 + gh > clip_y0 {
5187 out_glyphs.push(PositionedGlyph {
5188 glyph_idx: slot,
5189 x: gx0,
5190 y: gy0,
5191 width: gw_u16,
5192 height: gh_u16,
5193 });
5194 }
5195 }
5196 pen_x += adv_phys;
5197 }
5198 }
5199 }
5200 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
5201 (run_start, run_len)
5202 }
5203
5204 #[must_use]
5218 fn resolve_text_caret_rect(
5219 layout_opt: Option<&TextLayoutResult>,
5220 rects: (Rect, Rect),
5221 style: TextStyle,
5222 caret_opts: (f32, f32, bool),
5223 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
5224 ) -> Rect {
5225 let (text_rect, content_rect): (Rect, Rect) = rects;
5226 let (caret_height, scale, multiline): (f32, f32, bool) = caret_opts;
5227 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
5228 let phys_font_size: f32 = style.get_font_size() * scale;
5229 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
5230 let bold: bool = style.get_weight().is_bold();
5231 let monospace: bool = style.get_family() == FontFamily::Monospace;
5232 let italic: bool = style.get_italic();
5233 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
5234 let letter_sp: f32 = style.get_letter_spacing() * scale;
5235 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
5236 let (last_w_phys, line_idx, line_h_phys): (f32, usize, f32) =
5237 if let Some(layout) = layout_opt {
5238 let lh: f32 = layout.get_line_height_px() * scale;
5239 let idx: usize = layout.get_lines().len().saturating_sub(1);
5240 let w_phys: f32 = if let Some(line) = layout.get_lines().last() {
5241 let ascii_table_idx: usize =
5242 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
5243 let mut acc: f32 = 0.0;
5244 for ch in line.get_text().chars() {
5245 if ch == ' ' {
5246 acc += space_step;
5247 } else {
5248 let slot: u32 = if ch.is_ascii() {
5249 glyph_atlas.get_or_rasterize_ascii_slot_with(
5250 ascii_table_idx,
5251 ch as u8,
5252 key_meta,
5253 font_provider,
5254 )
5255 } else {
5256 let key: GlyphKey = GlyphKey {
5257 codepoint: ch,
5258 size_tenths,
5259 bold,
5260 monospace,
5261 italic,
5262 };
5263 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
5264 };
5265 let adv: f32 =
5266 (glyph_atlas.glyph_by_slot(slot).get_advance() as f32).max(1.0);
5267 acc += adv + letter_sp;
5268 }
5269 }
5270 acc
5271 } else {
5272 0.0
5273 };
5274 (w_phys, idx, lh)
5275 } else {
5276 (
5277 0.0,
5278 0,
5279 (style.get_font_size() * style.get_line_height()).max(1.0) * scale,
5280 )
5281 };
5282 let caret_h_phys: f32 = (caret_height * scale).max(2.0);
5283 let caret_w_phys: f32 = (1.5 * scale).max(1.5);
5284 let min_x: f32 = content_rect.get_x() * scale;
5285 let max_x: f32 = (content_rect.right() * scale - caret_w_phys - 1.0).max(min_x);
5286 let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.5 * scale } else { 0.0 };
5287 let caret_x_phys: f32 = (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys)
5288 .min(max_x)
5289 .max(min_x);
5290 let caret_y_phys: f32 = if multiline {
5291 let raw_y: f32 = content_rect.get_y() * scale
5292 + (line_idx as f32) * line_h_phys
5293 + ((line_h_phys - caret_h_phys) * 0.5).max(0.0);
5294 raw_y
5295 .min(content_rect.bottom() * scale - caret_h_phys)
5296 .max(content_rect.get_y() * scale)
5297 } else {
5298 content_rect.get_y() * scale
5299 + ((content_rect.get_height() * scale - caret_h_phys) * 0.5).max(0.0)
5300 };
5301 Rect::new(
5302 caret_x_phys.round(),
5303 caret_y_phys.round(),
5304 caret_w_phys.round().max(1.0),
5305 caret_h_phys.round().max(2.0),
5306 )
5307 }
5308
5309 #[must_use]
5321 fn collect_active_rounded(
5322 stack: &[Option<RoundedClipMask>],
5323 out: &mut Vec<RoundedClipMask>,
5324 vis: Rect,
5325 ) -> (u32, u16) {
5326 let start: u32 = out.len() as u32;
5327 for entry in stack.iter().copied().flatten() {
5328 if rect_intersects_rounded_corners(vis, entry.get_rect(), entry.get_radius()) {
5329 out.push(entry);
5330 }
5331 }
5332 let len: u16 = (out.len() as u32)
5333 .saturating_sub(start)
5334 .min(u16::MAX as u32) as u16;
5335 (start, len)
5336 }
5337
5338 #[must_use]
5349 fn resolve_opaque_clear_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
5350 let Some(DrawCommand::FillRoundedRect {
5351 rect,
5352 color,
5353 radius,
5354 border,
5355 }) = next_cmd
5356 else {
5357 return (Rect::default(), Rect::default());
5358 };
5359 if color.get_a() != 255 {
5360 return (Rect::default(), Rect::default());
5361 }
5362 let bw: f32 = if border.get_width() > 0.0 && border.get_color().get_a() < 255 {
5363 (border.get_width() * scale).max(1.0)
5364 } else {
5365 0.0
5366 };
5367 let phys: Rect = snap_physical_rect(*rect, scale);
5368 let r_max: f32 = Self::scale_radius(*radius, scale)
5369 .max_radius()
5370 .min(phys.get_width() * 0.5)
5371 .min(phys.get_height() * 0.5);
5372 let pad: f32 = 1.5 + bw;
5373 let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
5374 let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
5375 let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
5376 Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
5377 } else {
5378 Rect::default()
5379 };
5380 let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
5381 let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
5382 let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
5383 Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
5384 } else {
5385 Rect::default()
5386 };
5387 (cut_h, cut_v)
5388 }
5389
5390 #[must_use]
5401 fn resolve_opaque_shadow_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
5402 let Some(DrawCommand::FillRoundedRect {
5403 rect,
5404 color,
5405 radius,
5406 ..
5407 }) = next_cmd
5408 else {
5409 return (Rect::default(), Rect::default());
5410 };
5411 if color.get_a() != 255 {
5412 return (Rect::default(), Rect::default());
5413 }
5414 let phys: Rect = snap_physical_rect(*rect, scale);
5415 let r_max: f32 = Self::scale_radius(*radius, scale)
5416 .max_radius()
5417 .min(phys.get_width() * 0.5)
5418 .min(phys.get_height() * 0.5);
5419 let pad: f32 = 1.5;
5420 let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
5421 let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
5422 let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
5423 Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
5424 } else {
5425 Rect::default()
5426 };
5427 let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
5428 let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
5429 let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
5430 Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
5431 } else {
5432 Rect::default()
5433 };
5434 (cut_h, cut_v)
5435 }
5436
5437 fn save_single_cached_rounded_corners(
5452 band: &mut PixelBand<'_>,
5453 mask: RoundedClipMask,
5454 clip: Rect,
5455 band_bounds: (u32, u32, u32),
5456 corner_masks: &[CachedCornerMask],
5457 scratch: &mut BandCornerScratch,
5458 ) -> bool {
5459 let (fb_w, band_y0, band_y1): (u32, u32, u32) = band_bounds;
5460 let clip_x0: i32 = (clip.get_x().floor().max(0.0) as u32).min(fb_w) as i32;
5461 let clip_y0: i32 = (clip.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
5462 let clip_x1: i32 = (clip.right().ceil().max(0.0) as u32).min(fb_w) as i32;
5463 let clip_y1: i32 = (clip.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
5464 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
5465 return false;
5466 }
5467 let rect: Rect = mask.get_rect();
5468 let rx0_i: i32 = rect.get_x().round() as i32;
5469 let ry0_i: i32 = rect.get_y().round() as i32;
5470 let rx1_i: i32 = rect.right().round() as i32;
5471 let ry1_i: i32 = rect.bottom().round() as i32;
5472 let mask_ids: [u32; 4] = mask.get_corner_mask_ids();
5473 scratch.saved_bytes.clear();
5474 scratch.saved_rows.clear();
5475 for (q, &mask_id) in mask_ids.iter().enumerate() {
5476 if mask_id == u32::MAX {
5477 continue;
5478 }
5479 let Some(cm) = corner_masks.get(mask_id as usize) else {
5480 continue;
5481 };
5482 let dim_i: i32 = cm.dim as i32;
5483 let origin_x: i32 = if q == 0 || q == 3 {
5484 rx0_i
5485 } else {
5486 rx1_i - dim_i
5487 };
5488 let origin_y: i32 = if q == 0 || q == 1 {
5489 ry0_i
5490 } else {
5491 ry1_i - dim_i
5492 };
5493 let bx0: i32 = origin_x.max(clip_x0);
5494 let bx1: i32 = (origin_x + dim_i).min(clip_x1);
5495 let by0: i32 = origin_y.max(clip_y0);
5496 let by1: i32 = (origin_y + dim_i).min(clip_y1);
5497 if bx0 >= bx1 || by0 >= by1 {
5498 continue;
5499 }
5500 for y_i in by0..by1 {
5501 let my: usize = (y_i - origin_y) as usize;
5502 let span: CornerMaskRowSpan = cm.row_spans[my];
5503 if span.dirty_start >= span.dirty_end {
5504 continue;
5505 }
5506 let sx0_i: i32 = (origin_x + (span.dirty_start as i32)).max(bx0);
5507 let sx1_i: i32 = (origin_x + (span.dirty_end as i32)).min(bx1);
5508 if sx0_i >= sx1_i {
5509 continue;
5510 }
5511 let y: u32 = y_i as u32;
5512 let sx0: u32 = sx0_i as u32;
5513 let sx1: u32 = sx1_i as u32;
5514 if let Some(row) = band.row_slice_mut(y) {
5515 let b0: usize = (sx0 as usize) * 4;
5516 let b1: usize = (sx1 as usize) * 4;
5517 let byte_off: usize = scratch.saved_bytes.len();
5518 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5519 scratch.saved_rows.push(SavedCornerRow {
5520 y,
5521 sx0,
5522 sx1,
5523 byte_off,
5524 mask_id,
5525 origin_x,
5526 origin_y,
5527 });
5528 }
5529 }
5530 }
5531 !scratch.saved_rows.is_empty()
5532 }
5533
5534 fn restore_single_cached_rounded_corners(
5542 band: &mut PixelBand<'_>,
5543 corner_masks: &[CachedCornerMask],
5544 scratch: &BandCornerScratch,
5545 ) {
5546 let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
5547 for entry in scratch.saved_rows.iter() {
5548 let Some(row) = band.row_slice_mut(entry.y) else {
5549 continue;
5550 };
5551 let cm: &CachedCornerMask = &corner_masks[entry.mask_id as usize];
5552 let dim: usize = cm.dim as usize;
5553 let my: usize = ((entry.y as i32) - entry.origin_y) as usize;
5554 let span: CornerMaskRowSpan = cm.row_spans[my];
5555 let sx0_i: i32 = entry.sx0 as i32;
5556 let sx1_i: i32 = entry.sx1 as i32;
5557 if span.ext_start < span.ext_end {
5558 let ex0: i32 = (entry.origin_x + (span.ext_start as i32)).max(sx0_i);
5559 let ex1: i32 = (entry.origin_x + (span.ext_end as i32)).min(sx1_i);
5560 if ex0 < ex1 {
5561 let dst_b0: usize = (ex0 as usize) * 4;
5562 let dst_b1: usize = (ex1 as usize) * 4;
5563 let src_b0: usize = entry.byte_off + ((ex0 - sx0_i) as usize) * 4;
5564 let src_b1: usize = src_b0 + (dst_b1 - dst_b0);
5565 row[dst_b0..dst_b1].copy_from_slice(&saved_bytes[src_b0..src_b1]);
5566 }
5567 }
5568 if span.aa_start < span.aa_end {
5569 let ax0: i32 = (entry.origin_x + (span.aa_start as i32)).max(sx0_i);
5570 let ax1: i32 = (entry.origin_x + (span.aa_end as i32)).min(sx1_i);
5571 if ax0 < ax1 {
5572 let cov_row: &[u8] = &cm.cov[my * dim..(my + 1) * dim];
5573 for x_i in ax0..ax1 {
5574 let mx: usize = (x_i - entry.origin_x) as usize;
5575 let cov_u8: u8 = cov_row[mx];
5576 if cov_u8 >= 16 {
5577 continue;
5578 }
5579 let dst_off: usize = (x_i as usize) * 4;
5580 let src_off: usize = entry.byte_off + ((x_i - sx0_i) as usize) * 4;
5581 let saved_rgba: [u8; 4] = [
5582 saved_bytes[src_off],
5583 saved_bytes[src_off + 1],
5584 saved_bytes[src_off + 2],
5585 saved_bytes[src_off + 3],
5586 ];
5587 if cov_u8 == 0 {
5588 row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
5589 } else {
5590 let cov: f32 = (cov_u8 as f32) * 0.0625;
5591 lerp_pixel_slice_from_saved_linear(
5592 &mut row[dst_off..dst_off + 4],
5593 saved_rgba,
5594 cov,
5595 );
5596 }
5597 }
5598 }
5599 }
5600 }
5601 }
5602
5603 pub(crate) fn render_band(
5618 band: &mut PixelBand<'_>,
5619 commands: &[DrawCommand],
5620 prepped: &[PreppedCommand],
5621 aux: BandAuxSlices<'_>,
5622 glyph_atlas: &GlyphAtlas,
5623 render_opts: (f32, AntialiasingMode),
5624 ) -> usize {
5625 let BandAuxSlices {
5626 positioned_glyphs,
5627 caret_rects,
5628 rounded_clips,
5629 corner_masks,
5630 } = aux;
5631 let (scale, aa): (f32, AntialiasingMode) = render_opts;
5632 let band_y0: u32 = band.y_offset();
5633 let band_y1: u32 = band.y_end();
5634 let fb_w: u32 = band.width();
5635 let band_rect: Rect =
5636 Rect::new(0.0, band_y0 as f32, fb_w as f32, (band_y1 - band_y0) as f32);
5637 let has_any_rounded: bool = !rounded_clips.is_empty();
5638 let mut scratch: BandCornerScratch = if has_any_rounded {
5639 BAND_CORNER_SCRATCH
5640 .try_with(|cell: &RefCell<BandCornerScratch>| {
5641 cell.try_borrow_mut()
5642 .ok()
5643 .map(|mut guard: RefMut<'_, BandCornerScratch>| take(&mut *guard))
5644 })
5645 .ok()
5646 .flatten()
5647 .unwrap_or_default()
5648 } else {
5649 BandCornerScratch::default()
5650 };
5651 let mut shaded: usize = 0;
5652 let prepped_len: usize = prepped.len();
5653 let mut idx: usize = 0;
5654 while idx < prepped_len {
5655 let item: &PreppedCommand = &prepped[idx];
5656 if item.get_cmd_index() == usize::MAX {
5657 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
5658 idx += (item.get_skip_delta() as usize).max(1);
5659 } else {
5660 idx += 1;
5661 }
5662 continue;
5663 }
5664 idx += 1;
5665 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
5666 continue;
5667 }
5668 let Some(active_clip) = item.get_active_clip().intersect(band_rect) else {
5669 continue;
5670 };
5671 let rc_len: usize = item.get_rounded_clip_len() as usize;
5672 let item_masks: &[RoundedClipMask] = if rc_len > 0 {
5673 let start: usize = item.get_rounded_clip_start() as usize;
5674 let end: usize = start.saturating_add(rc_len).min(rounded_clips.len());
5675 &rounded_clips[start..end]
5676 } else {
5677 &[]
5678 };
5679 let mut corner_mode: u8 = 0;
5680 if item_masks.len() == 1 {
5681 let mask: RoundedClipMask = item_masks[0];
5682 let rect: Rect = mask.get_rect();
5683 let max_r: f32 = (rect.get_width() * 0.5)
5684 .min(rect.get_height() * 0.5)
5685 .max(0.0);
5686 let radius: CornerRadius = mask.get_radius();
5687 let radii: [f32; 4] = [
5688 radius.get_top_left().min(max_r),
5689 radius.get_top_right().min(max_r),
5690 radius.get_bottom_right().min(max_r),
5691 radius.get_bottom_left().min(max_r),
5692 ];
5693 let ids: [u32; 4] = mask.get_corner_mask_ids();
5694 let all_cached: bool = radii
5695 .iter()
5696 .zip(ids.iter())
5697 .all(|(&r, &id): (&f32, &u32)| r <= 0.25 || (id as usize) < corner_masks.len());
5698 if all_cached {
5699 if Self::save_single_cached_rounded_corners(
5700 band,
5701 mask,
5702 active_clip,
5703 (fb_w, band_y0, band_y1),
5704 corner_masks,
5705 &mut scratch,
5706 ) {
5707 corner_mode = 1;
5708 }
5709 } else {
5710 scratch.corner_boxes.clear();
5711 scratch.saved_bytes.clear();
5712 collect_rounded_clip_boxes(
5713 mask,
5714 active_clip,
5715 (fb_w, band_y0, band_y1),
5716 &mut scratch.corner_boxes,
5717 );
5718 if !scratch.corner_boxes.is_empty() {
5719 for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
5720 let b0: usize = (bx0 as usize) * 4;
5721 let b1: usize = (bx1 as usize) * 4;
5722 for y in by0..by1 {
5723 if let Some(row) = band.row_slice_mut(y) {
5724 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5725 }
5726 }
5727 }
5728 corner_mode = 2;
5729 }
5730 }
5731 } else if !item_masks.is_empty() {
5732 scratch.corner_boxes.clear();
5733 scratch.saved_bytes.clear();
5734 for mask in item_masks.iter().copied() {
5735 collect_rounded_clip_boxes(
5736 mask,
5737 active_clip,
5738 (fb_w, band_y0, band_y1),
5739 &mut scratch.corner_boxes,
5740 );
5741 }
5742 if !scratch.corner_boxes.is_empty() {
5743 for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
5744 let b0: usize = (bx0 as usize) * 4;
5745 let b1: usize = (bx1 as usize) * 4;
5746 for y in by0..by1 {
5747 if let Some(row) = band.row_slice_mut(y) {
5748 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
5749 }
5750 }
5751 }
5752 corner_mode = 2;
5753 }
5754 }
5755 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
5756 shaded += match cmd {
5757 DrawCommand::Clear(color) => {
5758 let cutouts: (Rect, Rect) =
5759 (item.get_opaque_cutout_h(), item.get_opaque_cutout_v());
5760 if cutouts.0.get_width() > 0.0 || cutouts.1.get_width() > 0.0 {
5761 let cx0: u32 = (active_clip.get_x().floor().max(0.0) as u32).min(fb_w);
5762 let cx1: u32 = (active_clip.right().ceil().max(0.0) as u32).min(fb_w);
5763 let cy0: u32 = (active_clip.get_y().floor().max(0.0) as u32)
5764 .max(band_y0)
5765 .min(band_y1);
5766 let cy1: u32 = (active_clip.bottom().ceil().max(0.0) as u32)
5767 .max(band_y0)
5768 .min(band_y1);
5769 let rgba: [u8; 4] =
5770 [color.get_r(), color.get_g(), color.get_b(), color.get_a()];
5771 let mut count: usize = 0;
5772 if cx0 < cx1 && cy0 < cy1 {
5773 for y in cy0..cy1 {
5774 let (cut0, cut1): (u32, u32) =
5775 Self::shadow_row_cutout(y, cutouts, cx0, cx1);
5776 if cut0 <= cx0 && cut1 >= cx1 {
5777 continue;
5778 }
5779 if let Some(row) = band.row_slice_mut(y) {
5780 if cut0 < cut1 {
5781 if cx0 < cut0 {
5782 fill_rgba_span_32(
5783 &mut row[(cx0 as usize) * 4..(cut0 as usize) * 4],
5784 rgba,
5785 );
5786 count += (cut0 - cx0) as usize;
5787 }
5788 if cut1 < cx1 {
5789 fill_rgba_span_32(
5790 &mut row[(cut1 as usize) * 4..(cx1 as usize) * 4],
5791 rgba,
5792 );
5793 count += (cx1 - cut1) as usize;
5794 }
5795 } else {
5796 fill_rgba_span_32(
5797 &mut row[(cx0 as usize) * 4..(cx1 as usize) * 4],
5798 rgba,
5799 );
5800 count += (cx1 - cx0) as usize;
5801 }
5802 }
5803 }
5804 }
5805 count
5806 } else if active_clip.get_x() <= 0.0
5807 && active_clip.get_width() >= (band.width() as f32)
5808 && active_clip.get_y() <= (band_y0 as f32)
5809 && active_clip.bottom() >= (band_y1 as f32)
5810 {
5811 band.clear(*color);
5812 (band.width() as usize) * ((band_y1 - band_y0) as usize)
5813 } else {
5814 Self::fill_rect_clipped(band, active_clip, *color, active_clip)
5815 }
5816 }
5817 DrawCommand::FillRoundedRect {
5818 rect,
5819 color,
5820 radius,
5821 border,
5822 } => {
5823 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5824 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5825 let bw: f32 = if border.get_width() > 0.0 {
5826 (border.get_width() * scale).max(1.0)
5827 } else {
5828 0.0
5829 };
5830 let phys_border: Border = Border::new(bw, border.get_color());
5831 Self::raster_rounded_rect(
5832 band,
5833 phys_rect,
5834 *color,
5835 phys_radius,
5836 phys_border,
5837 active_clip,
5838 aa,
5839 )
5840 }
5841 DrawCommand::LinearGradientRect {
5842 rect,
5843 gradient,
5844 radius,
5845 } => {
5846 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5847 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5848 Self::raster_gradient_rect(
5849 band,
5850 phys_rect,
5851 *gradient,
5852 phys_radius,
5853 active_clip,
5854 aa,
5855 )
5856 }
5857 DrawCommand::BoxShadow {
5858 rect,
5859 radius,
5860 shadow,
5861 } => {
5862 let spread: f32 = shadow.get_spread_radius() * scale;
5863 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
5864 let sigma: f32 = (blur * 0.5).max(0.75);
5865 let pad: f32 = (sigma * 3.0).ceil();
5866 let base_rect: Rect = snap_physical_rect(*rect, scale);
5867 let caster_rect: Rect = Rect::new(
5868 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
5869 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
5870 (base_rect.get_width() + spread * 2.0).max(1.0),
5871 (base_rect.get_height() + spread * 2.0).max(1.0),
5872 );
5873 let shadow_rect: Rect = Rect::new(
5874 caster_rect.get_x() - pad,
5875 caster_rect.get_y() - pad,
5876 caster_rect.get_width() + pad * 2.0,
5877 caster_rect.get_height() + pad * 2.0,
5878 );
5879 let raw_r: CornerRadius = Self::scale_radius(*radius, scale);
5880 let phys_radius: CornerRadius = CornerRadius::new(
5881 (raw_r.get_top_left() + spread).max(0.0),
5882 (raw_r.get_top_right() + spread).max(0.0),
5883 (raw_r.get_bottom_right() + spread).max(0.0),
5884 (raw_r.get_bottom_left() + spread).max(0.0),
5885 );
5886 Self::raster_shadow(
5887 band,
5888 (shadow_rect, caster_rect, active_clip),
5889 phys_radius,
5890 sigma,
5891 shadow.get_color(),
5892 (item.get_opaque_cutout_h(), item.get_opaque_cutout_v()),
5893 )
5894 }
5895 DrawCommand::BackdropBlur {
5896 rect,
5897 radius,
5898 blur_radius,
5899 } => {
5900 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5901 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5902 let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 48.0);
5903 Self::raster_backdrop_blur(band, phys_rect, phys_radius, phys_blur, active_clip)
5904 }
5905 DrawCommand::TextRun { style, .. } => {
5906 let g_start: usize = item.get_glyph_run_start() as usize;
5907 let g_len: usize = item.get_glyph_run_len() as usize;
5908 if let Some(run_slice) = positioned_glyphs.get(g_start..g_start + g_len) {
5909 Self::raster_text_run_band(
5910 band,
5911 run_slice,
5912 style.get_color(),
5913 active_clip,
5914 glyph_atlas,
5915 )
5916 } else {
5917 0
5918 }
5919 }
5920 DrawCommand::TextCaret { color, .. } => {
5921 let cidx: usize = item.get_caret_rect_idx() as usize;
5922 if let Some(&caret_rect) = caret_rects.get(cidx) {
5923 Self::raster_rounded_rect(
5924 band,
5925 caret_rect,
5926 *color,
5927 CornerRadius::all(0.5 * scale),
5928 Border::default(),
5929 active_clip,
5930 aa,
5931 )
5932 } else {
5933 0
5934 }
5935 }
5936 DrawCommand::Image {
5937 rect,
5938 buffer,
5939 radius,
5940 } => {
5941 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5942 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5943 Self::raster_rgba_bytes(
5944 band,
5945 phys_rect,
5946 (buffer.get_width(), buffer.get_height(), buffer.get_pixels()),
5947 phys_radius,
5948 active_clip,
5949 aa,
5950 )
5951 }
5952 DrawCommand::SharedImage {
5953 rect,
5954 width,
5955 height,
5956 pixels,
5957 radius,
5958 } => {
5959 let phys_rect: Rect = snap_physical_rect(*rect, scale);
5960 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
5961 Self::raster_rgba_bytes(
5962 band,
5963 phys_rect,
5964 (*width, *height, pixels.as_slice()),
5965 phys_radius,
5966 active_clip,
5967 aa,
5968 )
5969 }
5970 DrawCommand::Line {
5971 from,
5972 to,
5973 color,
5974 width,
5975 } => {
5976 let p0: Point = Point::new(from.get_x() * scale, from.get_y() * scale);
5977 let p1: Point = Point::new(to.get_x() * scale, to.get_y() * scale);
5978 Self::raster_line(
5979 band,
5980 p0,
5981 p1,
5982 *color,
5983 (width * scale).max(1.0),
5984 active_clip,
5985 aa,
5986 )
5987 }
5988 DrawCommand::Circle {
5989 center,
5990 radius,
5991 color,
5992 } => {
5993 let c: Point = Point::new(center.get_x() * scale, center.get_y() * scale);
5994 Self::raster_circle(band, c, radius * scale, *color, active_clip, aa)
5995 }
5996 DrawCommand::Triangle { p0, p1, p2, color } => {
5997 let v0: Point = Point::new(p0.get_x() * scale, p0.get_y() * scale);
5998 let v1: Point = Point::new(p1.get_x() * scale, p1.get_y() * scale);
5999 let v2: Point = Point::new(p2.get_x() * scale, p2.get_y() * scale);
6000 Self::raster_triangle(band, v0, v1, v2, *color, active_clip, aa)
6001 }
6002 DrawCommand::SpriteRegion {
6003 rect,
6004 buffer,
6005 src_rect,
6006 tint,
6007 } => {
6008 let phys_rect: Rect = snap_physical_rect(*rect, scale);
6009 Self::raster_sprite_region(
6010 band,
6011 phys_rect,
6012 buffer,
6013 *src_rect,
6014 *tint,
6015 active_clip,
6016 aa,
6017 )
6018 }
6019 DrawCommand::PushClip(_)
6020 | DrawCommand::PushRoundedClip { .. }
6021 | DrawCommand::PopClip => 0,
6022 };
6023 if corner_mode == 1 {
6024 Self::restore_single_cached_rounded_corners(band, corner_masks, &scratch);
6025 } else if corner_mode == 2 {
6026 let multi_mask: bool = item_masks.len() > 1;
6027 let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
6028 let mut byte_cursor: usize = 0;
6029 for (box_idx, &(bx0, by0, bx1, by1)) in scratch.corner_boxes.iter().enumerate() {
6030 for y in by0..by1 {
6031 let Some(row) = band.row_slice_mut(y) else {
6032 byte_cursor += ((bx1 - bx0) as usize) * 4;
6033 continue;
6034 };
6035 for x in bx0..bx1 {
6036 let saved_rgba: [u8; 4] = [
6037 saved_bytes[byte_cursor],
6038 saved_bytes[byte_cursor + 1],
6039 saved_bytes[byte_cursor + 2],
6040 saved_bytes[byte_cursor + 3],
6041 ];
6042 byte_cursor += 4;
6043 if multi_mask
6044 && scratch.corner_boxes[..box_idx].iter().any(
6045 |&(px0, py0, px1, py1): &(u32, u32, u32, u32)| {
6046 x >= px0 && x < px1 && y >= py0 && y < py1
6047 },
6048 )
6049 {
6050 continue;
6051 }
6052 let mut cov: f32 = 1.0;
6053 for mask in item_masks.iter().copied() {
6054 cov *= rounded_clip_coverage_cached(x, y, mask, corner_masks, aa);
6055 if cov <= 0.0005 {
6056 break;
6057 }
6058 }
6059 let dst_off: usize = (x as usize) * 4;
6060 if cov <= 0.0005 {
6061 row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
6062 } else if cov < 0.9995 {
6063 lerp_pixel_slice_from_saved_linear(
6064 &mut row[dst_off..dst_off + 4],
6065 saved_rgba,
6066 cov,
6067 );
6068 }
6069 }
6070 }
6071 }
6072 }
6073 }
6074 if has_any_rounded {
6075 let _: bool = BAND_CORNER_SCRATCH
6076 .try_with(|cell: &RefCell<BandCornerScratch>| {
6077 if let Ok(mut guard) = cell.try_borrow_mut() {
6078 *guard = scratch;
6079 }
6080 })
6081 .is_ok();
6082 }
6083 shaded
6084 }
6085
6086 fn scale_rect(rect: Rect, scale: f32) -> Rect {
6097 Rect::new(
6098 rect.get_x() * scale,
6099 rect.get_y() * scale,
6100 rect.get_width() * scale,
6101 rect.get_height() * scale,
6102 )
6103 }
6104
6105 fn scale_radius(radius: CornerRadius, scale: f32) -> CornerRadius {
6116 CornerRadius::new(
6117 radius.get_top_left() * scale,
6118 radius.get_top_right() * scale,
6119 radius.get_bottom_right() * scale,
6120 radius.get_bottom_left() * scale,
6121 )
6122 }
6123
6124 fn fill_rect_clipped(band: &mut PixelBand<'_>, rect: Rect, color: Color, clip: Rect) -> usize {
6137 if color.get_a() == 0 {
6138 return 0;
6139 }
6140 let Some(vis) = rect.intersect(clip) else {
6141 return 0;
6142 };
6143 let fb_w: u32 = band.width();
6144 let band_y0: u32 = band.y_offset();
6145 let band_y1: u32 = band.y_end();
6146 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6147 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6148 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6149 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6150 if x0 >= x1 || y0 >= y1 {
6151 return 0;
6152 }
6153 let span_len: usize = (x1 - x0) as usize;
6154 let rows: usize = (y1 - y0) as usize;
6155 let sa: u8 = color.get_a();
6156 if sa == 255 {
6157 band.fill_rect_opaque_preclipped(
6158 x0,
6159 x1,
6160 y0,
6161 y1,
6162 [color.get_r(), color.get_g(), color.get_b(), 255],
6163 );
6164 } else if let Some((rows_buf, row_stride)) = band.rows_slice_mut(y0, y1) {
6165 let bx0: usize = (x0 as usize) * 4;
6166 let bx1: usize = (x1 as usize) * 4;
6167 if span_len.saturating_mul(rows) >= 512 {
6168 let luts: [[u8; 256]; 4] = build_linear_blend_luts(color);
6169 for row in rows_buf.chunks_exact_mut(row_stride) {
6170 fill_span_linear_luts_slice(&mut row[bx0..bx1], &luts);
6171 }
6172 } else {
6173 for row in rows_buf.chunks_exact_mut(row_stride) {
6174 fill_span_linear_slice(&mut row[bx0..bx1], color);
6175 }
6176 }
6177 }
6178 span_len * rows
6179 }
6180
6181 #[must_use]
6196 fn build_vertical_edge_strip(
6197 x_span: (u32, u32),
6198 geom: (f32, f32, f32, f32),
6199 colors: (Color, Border),
6200 lin_colors: ([f32; 4], [f32; 4]),
6201 aa: AntialiasingMode,
6202 out: &mut [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP],
6203 ) -> (usize, usize) {
6204 let (x_start, x_end): (u32, u32) = x_span;
6205 let (cx, half_w, half_h, bw): (f32, f32, f32, f32) = geom;
6206 let (color, border): (Color, Border) = colors;
6207 let (fill_lin, border_lin): ([f32; 4], [f32; 4]) = lin_colors;
6208 let has_border: bool = bw > 0.0 && border.get_color().get_a() > 0;
6209 let inner_hw: f32 = (half_w - bw).max(0.0);
6210 let inner_hh: f32 = (half_h - bw).max(0.0);
6211 let mut len: usize = 0;
6212 let mut shaded: usize = 0;
6213 for x in x_start..x_end {
6214 let px: f32 = (x as f32) + 0.5 - cx;
6215 let dist: f32 = px.abs() - half_w;
6216 if dist > 0.85 {
6217 continue;
6218 }
6219 if !has_border {
6220 if dist < -0.85 {
6221 let sa: u8 = color.get_a();
6222 if sa > 0 {
6223 let a: f32 = (sa as f32) * (1.0 / 255.0);
6224 out[len] = EdgeBlendSample {
6225 x,
6226 rgba: [color.get_r(), color.get_g(), color.get_b(), 255],
6227 sr_a: fill_lin[0] * a,
6228 sg_a: fill_lin[1] * a,
6229 sb_a: fill_lin[2] * a,
6230 inv_a: 1.0 - a,
6231 sa_u32: sa as u32,
6232 is_opaque: sa == 255,
6233 };
6234 len += 1;
6235 shaded += 1;
6236 }
6237 continue;
6238 }
6239 let outer_cov: f32 = sdf_coverage(dist, aa);
6240 if outer_cov > 0.0 && color.get_a() > 0 {
6241 let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * outer_cov;
6242 shaded += 1;
6243 if alpha_f > 0.0002 {
6244 let a: f32 = alpha_f.clamp(0.0, 1.0);
6245 out[len] = EdgeBlendSample {
6246 x,
6247 rgba: [color.get_r(), color.get_g(), color.get_b(), 255],
6248 sr_a: fill_lin[0] * a,
6249 sg_a: fill_lin[1] * a,
6250 sb_a: fill_lin[2] * a,
6251 inv_a: 1.0 - a,
6252 sa_u32: (a * 255.0) as u32,
6253 is_opaque: a >= 0.9995,
6254 };
6255 len += 1;
6256 }
6257 }
6258 continue;
6259 }
6260 if dist < -(bw + 0.85) {
6261 let sa: u8 = color.get_a();
6262 if sa > 0 {
6263 let a: f32 = (sa as f32) * (1.0 / 255.0);
6264 out[len] = EdgeBlendSample {
6265 x,
6266 rgba: [color.get_r(), color.get_g(), color.get_b(), 255],
6267 sr_a: fill_lin[0] * a,
6268 sg_a: fill_lin[1] * a,
6269 sb_a: fill_lin[2] * a,
6270 inv_a: 1.0 - a,
6271 sa_u32: sa as u32,
6272 is_opaque: sa == 255,
6273 };
6274 len += 1;
6275 shaded += 1;
6276 }
6277 continue;
6278 }
6279 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6280 px.abs() - inner_hw
6281 } else {
6282 2.0
6283 };
6284 if dist < -0.85 && inner_dist > 0.85 {
6285 let bc: Color = border.get_color();
6286 let sa: u8 = bc.get_a();
6287 let a: f32 = (sa as f32) * (1.0 / 255.0);
6288 out[len] = EdgeBlendSample {
6289 x,
6290 rgba: [bc.get_r(), bc.get_g(), bc.get_b(), 255],
6291 sr_a: border_lin[0] * a,
6292 sg_a: border_lin[1] * a,
6293 sb_a: border_lin[2] * a,
6294 inv_a: 1.0 - a,
6295 sa_u32: sa as u32,
6296 is_opaque: sa == 255,
6297 };
6298 len += 1;
6299 shaded += 1;
6300 continue;
6301 }
6302 let outer_cov: f32 = sdf_coverage(dist, aa);
6303 if outer_cov <= 0.0 {
6304 continue;
6305 }
6306 let inner_cov: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6307 sdf_coverage(inner_dist, aa)
6308 } else {
6309 0.0
6310 };
6311 let mixed: Color =
6312 composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
6313 let sa: u8 = mixed.get_a();
6314 if sa > 0 {
6315 let a: f32 = (sa as f32) * (1.0 / 255.0);
6316 out[len] = EdgeBlendSample {
6317 x,
6318 rgba: [mixed.get_r(), mixed.get_g(), mixed.get_b(), 255],
6319 sr_a: SRGB_TO_LIN_LUT[mixed.get_r() as usize] * a,
6320 sg_a: SRGB_TO_LIN_LUT[mixed.get_g() as usize] * a,
6321 sb_a: SRGB_TO_LIN_LUT[mixed.get_b() as usize] * a,
6322 inv_a: 1.0 - a,
6323 sa_u32: sa as u32,
6324 is_opaque: sa == 255,
6325 };
6326 len += 1;
6327 shaded += 1;
6328 }
6329 }
6330 (len, shaded)
6331 }
6332
6333 fn raster_rounded_rect(
6349 band: &mut PixelBand<'_>,
6350 rect: Rect,
6351 color: Color,
6352 radius: CornerRadius,
6353 border: Border,
6354 clip: Rect,
6355 aa: AntialiasingMode,
6356 ) -> usize {
6357 let Some(vis) = rect.intersect(clip) else {
6358 return 0;
6359 };
6360 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
6361 if radius.max_radius() <= 0.0 && !has_border {
6362 return Self::fill_rect_clipped(band, rect, color, clip);
6363 }
6364 if radius.max_radius() <= 0.0 && has_border && aa != AntialiasingMode::Msaa4x {
6365 let bw: f32 = border.get_width();
6366 let bw_r: f32 = bw.round();
6367 let rx: f32 = rect.get_x();
6368 let ry: f32 = rect.get_y();
6369 let rw: f32 = rect.get_width();
6370 let rh: f32 = rect.get_height();
6371 let int_aligned: bool = bw_r >= 1.0
6372 && (bw - bw_r).abs() < 1e-4
6373 && (rx - rx.round()).abs() < 1e-4
6374 && (ry - ry.round()).abs() < 1e-4
6375 && (rw - rw.round()).abs() < 1e-4
6376 && (rh - rh.round()).abs() < 1e-4
6377 && rw >= bw_r * 2.0
6378 && rh >= bw_r * 2.0;
6379 if int_aligned {
6380 let bc: Color = border.get_color();
6381 let exact_border: Color = if bw_r < 2.0 {
6382 let b_lin: [f32; 4] = [
6383 SRGB_TO_LIN_LUT[bc.get_r() as usize],
6384 SRGB_TO_LIN_LUT[bc.get_g() as usize],
6385 SRGB_TO_LIN_LUT[bc.get_b() as usize],
6386 (bc.get_a() as f32) / 255.0,
6387 ];
6388 composite_fill_and_border_precomputed([0.0; 4], b_lin, 1.0, 0.0)
6389 } else {
6390 bc
6391 };
6392 let mut shaded_fast: usize = 0;
6393 shaded_fast +=
6394 Self::fill_rect_clipped(band, Rect::new(rx, ry, rw, bw_r), exact_border, clip);
6395 shaded_fast += Self::fill_rect_clipped(
6396 band,
6397 Rect::new(rx, ry + rh - bw_r, rw, bw_r),
6398 exact_border,
6399 clip,
6400 );
6401 let mid_h: f32 = rh - bw_r * 2.0;
6402 if mid_h > 0.0 {
6403 shaded_fast += Self::fill_rect_clipped(
6404 band,
6405 Rect::new(rx, ry + bw_r, bw_r, mid_h),
6406 exact_border,
6407 clip,
6408 );
6409 shaded_fast += Self::fill_rect_clipped(
6410 band,
6411 Rect::new(rx + rw - bw_r, ry + bw_r, bw_r, mid_h),
6412 exact_border,
6413 clip,
6414 );
6415 let mid_w: f32 = rw - bw_r * 2.0;
6416 if mid_w > 0.0 && color.get_a() > 0 {
6417 shaded_fast += Self::fill_rect_clipped(
6418 band,
6419 Rect::new(rx + bw_r, ry + bw_r, mid_w, mid_h),
6420 color,
6421 clip,
6422 );
6423 }
6424 }
6425 return shaded_fast;
6426 }
6427 }
6428 let half_w: f32 = rect.get_width() * 0.5;
6429 let half_h: f32 = rect.get_height() * 0.5;
6430 let cx: f32 = rect.get_x() + half_w;
6431 let cy: f32 = rect.get_y() + half_h;
6432 let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
6433 let fb_w: u32 = band.width();
6434 let band_y0: u32 = band.y_offset();
6435 let band_y1: u32 = band.y_end();
6436 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6437 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6438 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6439 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6440 if x0 >= x1 || y0 >= y1 {
6441 return 0;
6442 }
6443 let effective_r: f32 = radius.max_radius().min(half_w).min(half_h);
6444 let safe_inset: f32 = effective_r.max(border_w) + 1.5;
6445 let edge_inset: f32 = border_w + 1.5;
6446 let iy0: u32 = ((rect.get_y() + safe_inset).ceil().max(0.0) as u32).clamp(y0, y1);
6447 let iy1: u32 = ((rect.bottom() - safe_inset).floor().max(0.0) as u32).clamp(y0, y1);
6448 let ix0: u32 = ((rect.get_x() + edge_inset).ceil().max(0.0) as u32).clamp(x0, x1);
6449 let ix1: u32 = ((rect.right() - edge_inset).floor().max(0.0) as u32).clamp(x0, x1);
6450 let cx0: u32 = ((rect.get_x() + safe_inset).ceil().max(0.0) as u32).clamp(x0, x1);
6451 let cx1: u32 = ((rect.right() - safe_inset).floor().max(0.0) as u32).clamp(x0, x1);
6452 let has_interior: bool = iy0 < iy1 && ix0 < ix1;
6453 let has_center_band: bool = cx0 < cx1;
6454 let fill_lin: [f32; 4] = [
6455 SRGB_TO_LIN_LUT[color.get_r() as usize],
6456 SRGB_TO_LIN_LUT[color.get_g() as usize],
6457 SRGB_TO_LIN_LUT[color.get_b() as usize],
6458 (color.get_a() as f32) / 255.0,
6459 ];
6460 let bc: Color = border.get_color();
6461 let border_lin: [f32; 4] = [
6462 SRGB_TO_LIN_LUT[bc.get_r() as usize],
6463 SRGB_TO_LIN_LUT[bc.get_g() as usize],
6464 SRGB_TO_LIN_LUT[bc.get_b() as usize],
6465 (bc.get_a() as f32) / 255.0,
6466 ];
6467 let interior_luts: Option<[[u8; 256]; 4]> = if has_interior
6468 && color.get_a() > 0
6469 && color.get_a() < 255
6470 && ((ix1 - ix0) as usize).saturating_mul((iy1 - iy0) as usize) >= 512
6471 {
6472 Some(build_linear_blend_luts(color))
6473 } else {
6474 None
6475 };
6476 let mut shaded: usize = 0;
6477 if has_interior {
6478 for y in y0..iy0 {
6479 let py: f32 = (y as f32) + 0.5 - cy;
6480 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6481 if has_center_band {
6482 shaded += Self::raster_rounded_corner_band_row(
6483 band,
6484 y,
6485 (x0, cx0, cx1, x1),
6486 box_geom,
6487 radius,
6488 (color, border, fill_lin, border_lin),
6489 (interior_luts.as_ref(), aa),
6490 );
6491 } else if let Some(row) = band.row_slice_mut(y) {
6492 for x in x0..x1 {
6493 shaded += Self::shade_rounded_pixel_row(
6494 row,
6495 x,
6496 box_geom,
6497 radius,
6498 (color, border, fill_lin, border_lin),
6499 aa,
6500 );
6501 }
6502 }
6503 }
6504 let use_1d_strip: bool = ((ix0 - x0) as usize) <= ROUNDED_EDGE_STRIP_CAP
6505 && ((x1 - ix1) as usize) <= ROUNDED_EDGE_STRIP_CAP;
6506 if use_1d_strip {
6507 let mut left_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
6508 [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
6509 let mut right_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
6510 [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
6511 let (left_len, left_shaded): (usize, usize) = if x0 < ix0 {
6512 Self::build_vertical_edge_strip(
6513 (x0, ix0),
6514 (cx, half_w, half_h, border_w),
6515 (color, border),
6516 (fill_lin, border_lin),
6517 aa,
6518 &mut left_strip,
6519 )
6520 } else {
6521 (0, 0)
6522 };
6523 let (right_len, right_shaded): (usize, usize) = if ix1 < x1 {
6524 Self::build_vertical_edge_strip(
6525 (ix1, x1),
6526 (cx, half_w, half_h, border_w),
6527 (color, border),
6528 (fill_lin, border_lin),
6529 aa,
6530 &mut right_strip,
6531 )
6532 } else {
6533 (0, 0)
6534 };
6535 let left_slice: &[EdgeBlendSample] = &left_strip[..left_len];
6536 let right_slice: &[EdgeBlendSample] = &right_strip[..right_len];
6537 let edge_shaded: usize = left_shaded + right_shaded;
6538 let has_edges: bool = left_len > 0 || right_len > 0;
6539 let fill_visible: bool = color.get_a() > 0;
6540 let fill_opaque: bool = color.get_a() == 255;
6541 let fill_rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
6542 let interior_span: usize = (ix1 - ix0) as usize;
6543 let ix0_b: usize = (ix0 as usize) * 4;
6544 let ix1_b: usize = (ix1 as usize) * 4;
6545 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
6546 for row in rows_buf.chunks_exact_mut(row_stride) {
6547 if fill_visible {
6548 if fill_opaque {
6549 fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
6550 } else if let Some(ref luts) = interior_luts {
6551 fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
6552 } else {
6553 fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
6554 }
6555 shaded += interior_span;
6556 }
6557 if has_edges {
6558 if left_len > 0 {
6559 apply_edge_strip_row(row, left_slice);
6560 }
6561 if right_len > 0 {
6562 apply_edge_strip_row(row, right_slice);
6563 }
6564 shaded += edge_shaded;
6565 }
6566 }
6567 }
6568 } else {
6569 let fill_visible: bool = color.get_a() > 0;
6570 let fill_opaque: bool = color.get_a() == 255;
6571 let fill_rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
6572 let interior_span: usize = (ix1 - ix0) as usize;
6573 let ix0_b: usize = (ix0 as usize) * 4;
6574 let ix1_b: usize = (ix1 as usize) * 4;
6575 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
6576 for (y, row) in (iy0..iy1).zip(rows_buf.chunks_exact_mut(row_stride)) {
6577 let py: f32 = (y as f32) + 0.5 - cy;
6578 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6579 if fill_visible {
6580 if fill_opaque {
6581 fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
6582 } else if let Some(ref luts) = interior_luts {
6583 fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
6584 } else {
6585 fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
6586 }
6587 shaded += interior_span;
6588 }
6589 for x in x0..ix0 {
6590 shaded += Self::shade_rounded_pixel_row(
6591 row,
6592 x,
6593 box_geom,
6594 radius,
6595 (color, border, fill_lin, border_lin),
6596 aa,
6597 );
6598 }
6599 for x in ix1..x1 {
6600 shaded += Self::shade_rounded_pixel_row(
6601 row,
6602 x,
6603 box_geom,
6604 radius,
6605 (color, border, fill_lin, border_lin),
6606 aa,
6607 );
6608 }
6609 }
6610 }
6611 }
6612 for y in iy1..y1 {
6613 let py: f32 = (y as f32) + 0.5 - cy;
6614 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6615 if has_center_band {
6616 shaded += Self::raster_rounded_corner_band_row(
6617 band,
6618 y,
6619 (x0, cx0, cx1, x1),
6620 box_geom,
6621 radius,
6622 (color, border, fill_lin, border_lin),
6623 (interior_luts.as_ref(), aa),
6624 );
6625 } else if let Some(row) = band.row_slice_mut(y) {
6626 for x in x0..x1 {
6627 shaded += Self::shade_rounded_pixel_row(
6628 row,
6629 x,
6630 box_geom,
6631 radius,
6632 (color, border, fill_lin, border_lin),
6633 aa,
6634 );
6635 }
6636 }
6637 }
6638 return shaded;
6639 }
6640 for y in y0..y1 {
6641 let py: f32 = (y as f32) + 0.5 - cy;
6642 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
6643 if has_center_band {
6644 shaded += Self::raster_rounded_corner_band_row(
6645 band,
6646 y,
6647 (x0, cx0, cx1, x1),
6648 box_geom,
6649 radius,
6650 (color, border, fill_lin, border_lin),
6651 (interior_luts.as_ref(), aa),
6652 );
6653 } else if let Some(row) = band.row_slice_mut(y) {
6654 for x in x0..x1 {
6655 shaded += Self::shade_rounded_pixel_row(
6656 row,
6657 x,
6658 box_geom,
6659 radius,
6660 (color, border, fill_lin, border_lin),
6661 aa,
6662 );
6663 }
6664 }
6665 }
6666 shaded
6667 }
6668
6669 #[inline(always)]
6685 fn raster_rounded_corner_band_row(
6686 band: &mut PixelBand<'_>,
6687 y: u32,
6688 x_bounds: (u32, u32, u32, u32),
6689 geom: (f32, f32, f32, f32),
6690 radius: CornerRadius,
6691 style_colors: (Color, Border, [f32; 4], [f32; 4]),
6692 opts: (Option<&[[u8; 256]; 4]>, AntialiasingMode),
6693 ) -> usize {
6694 let (interior_luts, aa): (Option<&[[u8; 256]; 4]>, AntialiasingMode) = opts;
6695 let Some(row) = band.row_slice_mut(y) else {
6696 return 0;
6697 };
6698 let (x0, cx0, cx1, x1): (u32, u32, u32, u32) = x_bounds;
6699 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
6700 let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
6701 style_colors;
6702 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
6703 let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
6704 let inner_thresh: f32 = if has_border {
6705 -(border_w + 0.85)
6706 } else {
6707 -0.85
6708 };
6709 let py_abs: f32 = py.abs();
6710 let fill_visible: bool = color.get_a() > 0;
6711 let fill_opaque: bool = color.get_a() == 255;
6712 let fill_rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
6713 let mut shaded: usize = 0;
6714 if x0 < cx0 {
6715 let pure_left: bool = ((cx0 - 1) as f32) + 0.5 < cx;
6716 if pure_left {
6717 let r_l: f32 = (if py < 0.0 {
6718 radius.get_top_left()
6719 } else {
6720 radius.get_bottom_left()
6721 })
6722 .min(half_w)
6723 .min(half_h)
6724 .max(0.0);
6725 let qy: f32 = py_abs - half_h + r_l;
6726 let r_out: f32 = r_l + 0.85;
6727 if qy <= r_out + 0.05 {
6728 let vis_l0: u32 = if qy > 0.0 {
6729 let max_vis_abs: f32 =
6730 (half_w - r_l) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
6731 ((cx - max_vis_abs - 0.5).floor().max(0.0) as u32).clamp(x0, cx0)
6732 } else {
6733 x0
6734 };
6735 let r_in: f32 = r_l + inner_thresh;
6736 let max_in_abs: f32 = if qy <= 0.0 {
6737 if qy < r_in - 0.05 {
6738 half_w + inner_thresh - 1.0
6739 } else {
6740 -1.0
6741 }
6742 } else if r_in > 0.0 && qy < r_in - 0.05 {
6743 (half_w - r_l) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
6744 } else {
6745 -1.0
6746 };
6747 let in_l0: u32 = if max_in_abs > 0.0 {
6748 ((cx - max_in_abs - 0.5).ceil().max(0.0) as u32).clamp(vis_l0, cx0)
6749 } else {
6750 cx0
6751 };
6752 for x in vis_l0..in_l0 {
6753 shaded +=
6754 Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
6755 }
6756 if in_l0 < cx0 && fill_visible {
6757 let b0: usize = (in_l0 as usize) * 4;
6758 let b1: usize = (cx0 as usize) * 4;
6759 if fill_opaque {
6760 fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
6761 } else if let Some(luts) = interior_luts {
6762 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6763 } else {
6764 fill_span_linear_slice(&mut row[b0..b1], color);
6765 }
6766 shaded += (cx0 - in_l0) as usize;
6767 }
6768 }
6769 } else {
6770 for x in x0..cx0 {
6771 shaded += Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
6772 }
6773 }
6774 }
6775 if cx1 < x1 {
6776 let pure_right: bool = (cx1 as f32) + 0.5 >= cx;
6777 if pure_right {
6778 let r_r: f32 = (if py < 0.0 {
6779 radius.get_top_right()
6780 } else {
6781 radius.get_bottom_right()
6782 })
6783 .min(half_w)
6784 .min(half_h)
6785 .max(0.0);
6786 let qy: f32 = py_abs - half_h + r_r;
6787 let r_out: f32 = r_r + 0.85;
6788 if qy <= r_out + 0.05 {
6789 let vis_r1: u32 = if qy > 0.0 {
6790 let max_vis_abs: f32 =
6791 (half_w - r_r) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
6792 ((cx + max_vis_abs + 0.5).ceil().max(0.0) as u32).clamp(cx1, x1)
6793 } else {
6794 x1
6795 };
6796 let r_in: f32 = r_r + inner_thresh;
6797 let max_in_abs: f32 = if qy <= 0.0 {
6798 if qy < r_in - 0.05 {
6799 half_w + inner_thresh - 1.0
6800 } else {
6801 -1.0
6802 }
6803 } else if r_in > 0.0 && qy < r_in - 0.05 {
6804 (half_w - r_r) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
6805 } else {
6806 -1.0
6807 };
6808 let in_r1: u32 = if max_in_abs > 0.0 {
6809 ((cx + max_in_abs - 0.5).floor().max(0.0) as u32).clamp(cx1, vis_r1)
6810 } else {
6811 cx1
6812 };
6813 if cx1 < in_r1 && fill_visible {
6814 let b0: usize = (cx1 as usize) * 4;
6815 let b1: usize = (in_r1 as usize) * 4;
6816 if fill_opaque {
6817 fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
6818 } else if let Some(luts) = interior_luts {
6819 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6820 } else {
6821 fill_span_linear_slice(&mut row[b0..b1], color);
6822 }
6823 shaded += (in_r1 - cx1) as usize;
6824 }
6825 for x in in_r1..vis_r1 {
6826 shaded +=
6827 Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
6828 }
6829 }
6830 } else {
6831 for x in cx1..x1 {
6832 shaded += Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
6833 }
6834 }
6835 }
6836 let dist_y: f32 = py_abs - half_h;
6837 let outer_cov: f32 = sdf_coverage(dist_y, aa);
6838 if outer_cov > 0.0 {
6839 let b0: usize = (cx0 as usize) * 4;
6840 let b1: usize = (cx1 as usize) * 4;
6841 if has_border {
6842 let inner_hh: f32 = (half_h - border_w).max(0.0);
6843 let inner_cov: f32 = if inner_hh > 0.0 && half_w > border_w {
6844 sdf_coverage(py_abs - inner_hh, aa)
6845 } else {
6846 0.0
6847 };
6848 let mixed: Color = composite_fill_and_border_precomputed(
6849 fill_lin, border_lin, outer_cov, inner_cov,
6850 );
6851 if mixed.get_a() > 0 {
6852 fill_span_linear_slice(&mut row[b0..b1], mixed);
6853 }
6854 shaded += (cx1 - cx0) as usize;
6855 } else if fill_visible {
6856 let row_color: Color = color.multiply_alpha(outer_cov);
6857 if row_color == color
6858 && let Some(luts) = interior_luts
6859 {
6860 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
6861 } else {
6862 fill_span_linear_slice(&mut row[b0..b1], row_color);
6863 }
6864 shaded += (cx1 - cx0) as usize;
6865 }
6866 }
6867 shaded
6868 }
6869
6870 #[inline(always)]
6885 fn shade_rounded_pixel_row(
6886 row: &mut [u8],
6887 x: u32,
6888 geom: (f32, f32, f32, f32),
6889 radius: CornerRadius,
6890 style_colors: (Color, Border, [f32; 4], [f32; 4]),
6891 aa: AntialiasingMode,
6892 ) -> usize {
6893 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
6894 let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
6895 style_colors;
6896 let fill_rgb: [f32; 3] = [fill_lin[0], fill_lin[1], fill_lin[2]];
6897 let px: f32 = (x as f32) + 0.5 - cx;
6898 let corner_r: f32 = quadrant_corner_radius(radius, px, py)
6899 .min(half_w)
6900 .min(half_h);
6901 let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
6902 if dist > 0.85 {
6903 return 0;
6904 }
6905 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
6906 let bw: f32 = if has_border { border.get_width() } else { 0.0 };
6907 if !has_border {
6908 if dist < -0.85 {
6909 if color.get_a() > 0 {
6910 blend_row_pixel_linear_precomputed(row, x, color, fill_rgb);
6911 return 1;
6912 }
6913 return 0;
6914 }
6915 let in_corner_edge: bool = aa != AntialiasingMode::None
6916 && corner_r > 0.5
6917 && px.abs() > (half_w - corner_r - 1.5)
6918 && py.abs() > (half_h - corner_r - 1.5);
6919 let outer_cov: f32 = if in_corner_edge {
6920 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
6921 } else {
6922 sdf_coverage(dist, aa)
6923 };
6924 if outer_cov > 0.0 && color.get_a() > 0 {
6925 let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * outer_cov;
6926 blend_row_pixel_f32_precomputed(row, x, color, fill_rgb, alpha_f);
6927 return 1;
6928 }
6929 return 0;
6930 }
6931 if dist < -(bw + 0.85) {
6932 if color.get_a() > 0 {
6933 blend_row_pixel_linear_precomputed(row, x, color, fill_rgb);
6934 return 1;
6935 }
6936 return 0;
6937 }
6938 let inner_hw: f32 = (half_w - bw).max(0.0);
6939 let inner_hh: f32 = (half_h - bw).max(0.0);
6940 let inner_r: f32 = (corner_r - bw).max(0.0);
6941 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6942 rounded_box_sdf(px, py, inner_hw, inner_hh, inner_r)
6943 } else {
6944 2.0
6945 };
6946 if dist < -0.85 && inner_dist > 0.85 {
6947 let border_rgb: [f32; 3] = [border_lin[0], border_lin[1], border_lin[2]];
6948 blend_row_pixel_linear_precomputed(row, x, border.get_color(), border_rgb);
6949 return 1;
6950 }
6951 let in_corner_zone: bool = aa != AntialiasingMode::None
6952 && corner_r > 0.5
6953 && px.abs() > (half_w - corner_r - 1.5)
6954 && py.abs() > (half_h - corner_r - 1.5);
6955 let (outer_cov, inner_cov): (f32, f32) = if in_corner_zone {
6956 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, bw)
6957 } else {
6958 let oc: f32 = sdf_coverage(dist, aa);
6959 if oc <= 0.0 {
6960 return 0;
6961 }
6962 let ic: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
6963 sdf_coverage(inner_dist, aa)
6964 } else {
6965 0.0
6966 };
6967 (oc, ic)
6968 };
6969 if outer_cov <= 0.0 {
6970 return 0;
6971 }
6972 let mixed: Color =
6973 composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
6974 if mixed.get_a() > 0 {
6975 let mixed_rgb: [f32; 3] = [
6976 SRGB_TO_LIN_LUT[mixed.get_r() as usize],
6977 SRGB_TO_LIN_LUT[mixed.get_g() as usize],
6978 SRGB_TO_LIN_LUT[mixed.get_b() as usize],
6979 ];
6980 blend_row_pixel_linear_precomputed(row, x, mixed, mixed_rgb);
6981 return 1;
6982 }
6983 0
6984 }
6985
6986 #[inline(always)]
6999 fn fill_vertical_gradient_span(
7000 band: &mut PixelBand<'_>,
7001 coords: (u32, u32, u32),
7002 sample: Color,
7003 cov: f32,
7004 ) -> usize {
7005 let (sx0, sx1, y): (u32, u32, u32) = coords;
7006 if sx0 >= sx1 || cov <= 0.0 {
7007 return 0;
7008 }
7009 let alpha_f: f32 = ((sample.get_a() as f32) * (1.0 / 255.0)) * cov;
7010 if alpha_f >= 0.9995 {
7011 band.fill_span(
7012 sx0,
7013 sx1,
7014 y,
7015 Color::new(sample.get_r(), sample.get_g(), sample.get_b(), 255),
7016 );
7017 } else if alpha_f > 0.0005 {
7018 band.blend_shadow_span_const_alpha(sx0, sx1, y, sample, alpha_f);
7019 } else if alpha_f > 0.0002
7020 && let Some(row) = band.row_slice_mut(y)
7021 {
7022 let y_term: f32 = (y as f32) * 0.005_837_15;
7023 for x in sx0..sx1 {
7024 blend_gradient_row_pixel(row, x, y_term, sample, cov);
7025 }
7026 }
7027 (sx1 - sx0) as usize
7028 }
7029
7030 #[inline(always)]
7043 fn fill_angled_gradient_span(
7044 row: &mut [u8],
7045 coords: (u32, u32, f32),
7046 step: (f32, f32, f32),
7047 stops: (Color, Color),
7048 ) -> usize {
7049 let (sx0, sx1, y_term): (u32, u32, f32) = coords;
7050 let (t_start, dt_dx, cov): (f32, f32, f32) = step;
7051 let (start_c, end_c): (Color, Color) = stops;
7052 if sx0 >= sx1 || cov <= 0.0 {
7053 return 0;
7054 }
7055 let byte_start: usize = (sx0 as usize) * 4;
7056 let byte_end: usize = (sx1 as usize) * 4;
7057 if byte_end > row.len() {
7058 return 0;
7059 }
7060 let sr_f: f32 = start_c.get_r() as f32;
7061 let sg_f: f32 = start_c.get_g() as f32;
7062 let sb_f: f32 = start_c.get_b() as f32;
7063 let er_f: f32 = end_c.get_r() as f32;
7064 let eg_f: f32 = end_c.get_g() as f32;
7065 let eb_f: f32 = end_c.get_b() as f32;
7066 let both_opaque: bool = start_c.get_a() == 255 && end_c.get_a() == 255;
7067 let mut t_cur: f32 = t_start;
7068 if both_opaque && cov >= 0.9995 {
7069 let chunks: &mut [[u8; 4]] = row[byte_start..byte_end].as_chunks_mut::<4>().0;
7070 for px in chunks.iter_mut() {
7071 let f: f32 = t_cur.clamp(0.0, 1.0);
7072 let inv: f32 = 1.0 - f;
7073 px[0] = (sr_f * inv + er_f * f + 0.5) as u8;
7074 px[1] = (sg_f * inv + eg_f * f + 0.5) as u8;
7075 px[2] = (sb_f * inv + eb_f * f + 0.5) as u8;
7076 px[3] = 255;
7077 t_cur += dt_dx;
7078 }
7079 return (sx1 - sx0) as usize;
7080 }
7081 let sa_f: f32 = start_c.get_a() as f32;
7082 let ea_f: f32 = end_c.get_a() as f32;
7083 for x in sx0..sx1 {
7084 let f: f32 = t_cur.clamp(0.0, 1.0);
7085 let inv: f32 = 1.0 - f;
7086 let sample: Color = Color::new(
7087 (sr_f * inv + er_f * f + 0.5) as u8,
7088 (sg_f * inv + eg_f * f + 0.5) as u8,
7089 (sb_f * inv + eb_f * f + 0.5) as u8,
7090 (sa_f * inv + ea_f * f + 0.5) as u8,
7091 );
7092 blend_gradient_row_pixel(row, x, y_term, sample, cov);
7093 t_cur += dt_dx;
7094 }
7095 (sx1 - sx0) as usize
7096 }
7097
7098 fn raster_gradient_rect(
7113 band: &mut PixelBand<'_>,
7114 rect: Rect,
7115 gradient: LinearGradient,
7116 radius: CornerRadius,
7117 clip: Rect,
7118 aa: AntialiasingMode,
7119 ) -> usize {
7120 let Some(vis) = rect.intersect(clip) else {
7121 return 0;
7122 };
7123 let fb_w: u32 = band.width();
7124 let band_y0: u32 = band.y_offset();
7125 let band_y1: u32 = band.y_end();
7126 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
7127 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
7128 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
7129 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
7130 if x0 >= x1 || y0 >= y1 {
7131 return 0;
7132 }
7133 let rad: f32 = gradient.get_angle_deg().to_radians();
7134 let dir_x: f32 = rad.sin();
7135 let dir_y: f32 = rad.cos();
7136 let start_c: Color = gradient.get_start_color();
7137 let end_c: Color = gradient.get_end_color();
7138 let half_w: f32 = rect.get_width() * 0.5;
7139 let half_h: f32 = rect.get_height() * 0.5;
7140 let cx: f32 = rect.get_x() + half_w;
7141 let cy: f32 = rect.get_y() + half_h;
7142 let inv_w: f32 = if rect.get_width() > 0.0 {
7143 1.0 / rect.get_width()
7144 } else {
7145 0.0
7146 };
7147 let inv_h: f32 = if rect.get_height() > 0.0 {
7148 1.0 / rect.get_height()
7149 } else {
7150 0.0
7151 };
7152 let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
7153 let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
7154 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
7155 let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
7156 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
7157 let cx0: u32 = ((rect.get_x() + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
7158 let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
7159 let is_vertical: bool = dir_x.abs() < 1e-5;
7160 let dt_dx: f32 = inv_w * dir_x;
7161 let rect_x: f32 = rect.get_x();
7162 let rect_y: f32 = rect.get_y();
7163 let mut shaded: usize = 0;
7164 if is_vertical {
7165 for y in y0..iy0 {
7166 let py: f32 = (y as f32) + 0.5 - cy;
7167 let ny: f32 = ((y as f32) - rect_y) * inv_h;
7168 let t: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
7169 let sample: Color = start_c.lerp(end_c, t);
7170 let dist_y: f32 = py.abs() - half_h;
7171 let mid_cov: f32 = if dist_y > 0.85 {
7172 0.0
7173 } else if dist_y < -0.85 {
7174 1.0
7175 } else {
7176 sdf_coverage(dist_y, aa)
7177 };
7178 if cx0 < cx1 && mid_cov > 0.0 {
7179 shaded +=
7180 Self::fill_vertical_gradient_span(band, (cx0, cx1, y), sample, mid_cov);
7181 }
7182 if (x0 < cx0 || cx1 < x1)
7183 && let Some(row) = band.row_slice_mut(y)
7184 {
7185 let y_term: f32 = (y as f32) * 0.005_837_15;
7186 for x in x0..cx0 {
7187 let px: f32 = (x as f32) + 0.5 - cx;
7188 let cov: f32 =
7189 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7190 if cov > 0.0 {
7191 blend_gradient_row_pixel(row, x, y_term, sample, cov);
7192 shaded += 1;
7193 }
7194 }
7195 for x in cx1..x1 {
7196 let px: f32 = (x as f32) + 0.5 - cx;
7197 let cov: f32 =
7198 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7199 if cov > 0.0 {
7200 blend_gradient_row_pixel(row, x, y_term, sample, cov);
7201 shaded += 1;
7202 }
7203 }
7204 }
7205 }
7206 for y in iy0..iy1 {
7207 let ny: f32 = ((y as f32) - rect_y) * inv_h;
7208 let t: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
7209 let sample: Color = start_c.lerp(end_c, t);
7210 if ix0 < ix1 {
7211 shaded += Self::fill_vertical_gradient_span(band, (ix0, ix1, y), sample, 1.0);
7212 }
7213 if (x0 < ix0 || ix1 < x1)
7214 && let Some(row) = band.row_slice_mut(y)
7215 {
7216 let y_term: f32 = (y as f32) * 0.005_837_15;
7217 for x in x0..ix0 {
7218 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
7219 if dist <= 0.85 {
7220 let cov: f32 = if dist < -0.85 {
7221 1.0
7222 } else {
7223 sdf_coverage(dist, aa)
7224 };
7225 if cov > 0.0 {
7226 blend_gradient_row_pixel(row, x, y_term, sample, cov);
7227 shaded += 1;
7228 }
7229 }
7230 }
7231 for x in ix1..x1 {
7232 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
7233 if dist <= 0.85 {
7234 let cov: f32 = if dist < -0.85 {
7235 1.0
7236 } else {
7237 sdf_coverage(dist, aa)
7238 };
7239 if cov > 0.0 {
7240 blend_gradient_row_pixel(row, x, y_term, sample, cov);
7241 shaded += 1;
7242 }
7243 }
7244 }
7245 }
7246 }
7247 for y in iy1..y1 {
7248 let py: f32 = (y as f32) + 0.5 - cy;
7249 let ny: f32 = ((y as f32) - rect_y) * inv_h;
7250 let t: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
7251 let sample: Color = start_c.lerp(end_c, t);
7252 let dist_y: f32 = py.abs() - half_h;
7253 let mid_cov: f32 = if dist_y > 0.85 {
7254 0.0
7255 } else if dist_y < -0.85 {
7256 1.0
7257 } else {
7258 sdf_coverage(dist_y, aa)
7259 };
7260 if cx0 < cx1 && mid_cov > 0.0 {
7261 shaded +=
7262 Self::fill_vertical_gradient_span(band, (cx0, cx1, y), sample, mid_cov);
7263 }
7264 if (x0 < cx0 || cx1 < x1)
7265 && let Some(row) = band.row_slice_mut(y)
7266 {
7267 let y_term: f32 = (y as f32) * 0.005_837_15;
7268 for x in x0..cx0 {
7269 let px: f32 = (x as f32) + 0.5 - cx;
7270 let cov: f32 =
7271 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7272 if cov > 0.0 {
7273 blend_gradient_row_pixel(row, x, y_term, sample, cov);
7274 shaded += 1;
7275 }
7276 }
7277 for x in cx1..x1 {
7278 let px: f32 = (x as f32) + 0.5 - cx;
7279 let cov: f32 =
7280 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7281 if cov > 0.0 {
7282 blend_gradient_row_pixel(row, x, y_term, sample, cov);
7283 shaded += 1;
7284 }
7285 }
7286 }
7287 }
7288 return shaded;
7289 }
7290 for y in y0..iy0 {
7291 let Some(row) = band.row_slice_mut(y) else {
7292 continue;
7293 };
7294 let py: f32 = (y as f32) + 0.5 - cy;
7295 let ny: f32 = ((y as f32) - rect_y) * inv_h;
7296 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
7297 let y_term: f32 = (y as f32) * 0.005_837_15;
7298 let dist_y: f32 = py.abs() - half_h;
7299 let mid_cov: f32 = if dist_y > 0.85 {
7300 0.0
7301 } else if dist_y < -0.85 {
7302 1.0
7303 } else {
7304 sdf_coverage(dist_y, aa)
7305 };
7306 if cx0 < cx1 && mid_cov > 0.0 {
7307 let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
7308 shaded += Self::fill_angled_gradient_span(
7309 row,
7310 (cx0, cx1, y_term),
7311 (t_start, dt_dx, mid_cov),
7312 (start_c, end_c),
7313 );
7314 }
7315 for x in x0..cx0 {
7316 let px: f32 = (x as f32) + 0.5 - cx;
7317 let cov: f32 =
7318 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7319 if cov > 0.0 {
7320 let nx: f32 = ((x as f32) - rect_x) * inv_w;
7321 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7322 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
7323 shaded += 1;
7324 }
7325 }
7326 for x in cx1..x1 {
7327 let px: f32 = (x as f32) + 0.5 - cx;
7328 let cov: f32 =
7329 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7330 if cov > 0.0 {
7331 let nx: f32 = ((x as f32) - rect_x) * inv_w;
7332 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7333 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
7334 shaded += 1;
7335 }
7336 }
7337 }
7338 for y in iy0..iy1 {
7339 let Some(row) = band.row_slice_mut(y) else {
7340 continue;
7341 };
7342 let ny: f32 = ((y as f32) - rect_y) * inv_h;
7343 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
7344 let y_term: f32 = (y as f32) * 0.005_837_15;
7345 if ix0 < ix1 {
7346 let t_start: f32 = (((ix0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
7347 shaded += Self::fill_angled_gradient_span(
7348 row,
7349 (ix0, ix1, y_term),
7350 (t_start, dt_dx, 1.0),
7351 (start_c, end_c),
7352 );
7353 }
7354 for x in x0..ix0 {
7355 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
7356 if dist <= 0.85 {
7357 let cov: f32 = if dist < -0.85 {
7358 1.0
7359 } else {
7360 sdf_coverage(dist, aa)
7361 };
7362 if cov > 0.0 {
7363 let nx: f32 = ((x as f32) - rect_x) * inv_w;
7364 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7365 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
7366 shaded += 1;
7367 }
7368 }
7369 }
7370 for x in ix1..x1 {
7371 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
7372 if dist <= 0.85 {
7373 let cov: f32 = if dist < -0.85 {
7374 1.0
7375 } else {
7376 sdf_coverage(dist, aa)
7377 };
7378 if cov > 0.0 {
7379 let nx: f32 = ((x as f32) - rect_x) * inv_w;
7380 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7381 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
7382 shaded += 1;
7383 }
7384 }
7385 }
7386 }
7387 for y in iy1..y1 {
7388 let Some(row) = band.row_slice_mut(y) else {
7389 continue;
7390 };
7391 let py: f32 = (y as f32) + 0.5 - cy;
7392 let ny: f32 = ((y as f32) - rect_y) * inv_h;
7393 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
7394 let y_term: f32 = (y as f32) * 0.005_837_15;
7395 let dist_y: f32 = py.abs() - half_h;
7396 let mid_cov: f32 = if dist_y > 0.85 {
7397 0.0
7398 } else if dist_y < -0.85 {
7399 1.0
7400 } else {
7401 sdf_coverage(dist_y, aa)
7402 };
7403 if cx0 < cx1 && mid_cov > 0.0 {
7404 let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
7405 shaded += Self::fill_angled_gradient_span(
7406 row,
7407 (cx0, cx1, y_term),
7408 (t_start, dt_dx, mid_cov),
7409 (start_c, end_c),
7410 );
7411 }
7412 for x in x0..cx0 {
7413 let px: f32 = (x as f32) + 0.5 - cx;
7414 let cov: f32 =
7415 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7416 if cov > 0.0 {
7417 let nx: f32 = ((x as f32) - rect_x) * inv_w;
7418 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7419 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
7420 shaded += 1;
7421 }
7422 }
7423 for x in cx1..x1 {
7424 let px: f32 = (x as f32) + 0.5 - cx;
7425 let cov: f32 =
7426 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
7427 if cov > 0.0 {
7428 let nx: f32 = ((x as f32) - rect_x) * inv_w;
7429 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
7430 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
7431 shaded += 1;
7432 }
7433 }
7434 }
7435 shaded
7436 }
7437
7438 #[must_use]
7451 fn shadow_row_cutout(y: u32, cutouts: (Rect, Rect), x0: u32, x1: u32) -> (u32, u32) {
7452 let (cut_h, cut_v): (Rect, Rect) = cutouts;
7453 let yf: f32 = (y as f32) + 0.5;
7454 if cut_h.get_width() > 0.0
7455 && cut_h.get_height() > 0.0
7456 && yf >= cut_h.get_y()
7457 && yf < cut_h.bottom()
7458 {
7459 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
7460 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, x1);
7461 return (cx0, cx1);
7462 }
7463 if cut_v.get_width() > 0.0
7464 && cut_v.get_height() > 0.0
7465 && yf >= cut_v.get_y()
7466 && yf < cut_v.bottom()
7467 {
7468 let cx0: u32 = (cut_v.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
7469 let cx1: u32 = (cut_v.right().floor().max(0.0) as u32).clamp(cx0, x1);
7470 return (cx0, cx1);
7471 }
7472 (x1, x1)
7473 }
7474
7475 #[inline(always)]
7489 fn raster_shadow_middle_span(
7490 band: &mut PixelBand<'_>,
7491 ctx: &ShadowRenderCtx,
7492 y: u32,
7493 cutout: (u32, u32),
7494 mid_alpha: f32,
7495 ) -> usize {
7496 if !ctx.has_mid_x || mid_alpha <= 0.0005 {
7497 return 0;
7498 }
7499 let (cut0, cut1): (u32, u32) = cutout;
7500 let sx0: u32 = ctx.lx1;
7501 let sx1: u32 = ctx.rx0;
7502 let mut shaded: usize = 0;
7503 if cut0 < cut1 {
7504 let m0_end: u32 = cut0.min(sx1);
7505 if sx0 < m0_end {
7506 band.blend_shadow_span_const_alpha(sx0, m0_end, y, ctx.color, mid_alpha);
7507 shaded += (m0_end - sx0) as usize;
7508 }
7509 let m1_start: u32 = cut1.max(sx0);
7510 if m1_start < sx1 {
7511 band.blend_shadow_span_const_alpha(m1_start, sx1, y, ctx.color, mid_alpha);
7512 shaded += (sx1 - m1_start) as usize;
7513 }
7514 } else {
7515 band.blend_shadow_span_const_alpha(sx0, sx1, y, ctx.color, mid_alpha);
7516 shaded += (sx1 - sx0) as usize;
7517 }
7518 shaded
7519 }
7520
7521 fn raster_shadow_corner_row_symmetric(
7534 band: &mut PixelBand<'_>,
7535 ctx: &ShadowRenderCtx,
7536 y: u32,
7537 cutouts: (Rect, Rect),
7538 ) -> usize {
7539 let py: f32 = (y as f32) + 0.5 - ctx.cy;
7540 let py_abs: f32 = py.abs();
7541 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1);
7542 let mut shaded: usize = 0;
7543 if ctx.has_mid_x {
7544 let dist_y: f32 = py_abs - ctx.half_h;
7545 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7546 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7547 } else {
7548 0.0
7549 };
7550 shaded += Self::raster_shadow_middle_span(band, ctx, y, (cut0, cut1), mid_alpha);
7551 }
7552 let (la0, la1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0, cut1);
7553 let (ra0, ra1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0, cut1);
7554 let mut u0: i32 = i32::MAX;
7555 let mut u1: i32 = i32::MIN;
7556 if la0 < la1 {
7557 u0 = u0.min(la0 as i32);
7558 u1 = u1.max(la1 as i32);
7559 }
7560 if ra0 < ra1 {
7561 u0 = u0.min(ctx.mirror_x_sum - (ra1 as i32) + 1);
7562 u1 = u1.max(ctx.mirror_x_sum - (ra0 as i32) + 1);
7563 }
7564 if u0 >= u1 {
7565 return shaded;
7566 }
7567 let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
7568 let qy_pos: f32 = qy.max(0.0);
7569 let qy_pos_sq: f32 = qy_pos * qy_pos;
7570 if qy > 0.0 {
7571 if qy_pos_sq >= ctx.cutoff_r_safe_sq {
7572 return shaded;
7573 }
7574 let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
7575 let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
7576 let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
7577 u0 = u0.max(tight_u0);
7578 if u0 >= u1 {
7579 return shaded;
7580 }
7581 }
7582 let Some(row) = band.row_slice_mut(y) else {
7583 return shaded;
7584 };
7585 let sdf_geom: (f32, f32, f32, f32) =
7586 (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
7587 let y_term: f32 = (y as f32) * 0.005_837_15;
7588 let x0_i: i32 = ctx.x0 as i32;
7589 let lx1_i: i32 = ctx.lx1 as i32;
7590 let rx0_i: i32 = ctx.rx0 as i32;
7591 let x1_i: i32 = ctx.x1 as i32;
7592 let cut0_i: i32 = cut0 as i32;
7593 let cut1_i: i32 = cut1 as i32;
7594 for xl_i in u0..u1 {
7595 let xr_i: i32 = ctx.mirror_x_sum - xl_i;
7596 let do_l: bool = xl_i >= x0_i && xl_i < lx1_i && (xl_i < cut0_i || xl_i >= cut1_i);
7597 let do_r: bool = xr_i >= rx0_i && xr_i < x1_i && (xr_i < cut0_i || xr_i >= cut1_i);
7598 if !do_l && !do_r {
7599 continue;
7600 }
7601 let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
7602 let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
7603 if dist >= ctx.cutoff {
7604 continue;
7605 }
7606 let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7607 if alpha_f <= 0.0005 {
7608 continue;
7609 }
7610 let a: f32 = alpha_f.clamp(0.0, 1.0);
7611 if a >= 0.9995 {
7612 if do_l {
7613 let off: usize = (xl_i as usize) * 4;
7614 row[off] = ctx.color_rgb[0];
7615 row[off + 1] = ctx.color_rgb[1];
7616 row[off + 2] = ctx.color_rgb[2];
7617 row[off + 3] = 255;
7618 shaded += 1;
7619 }
7620 if do_r {
7621 let off: usize = (xr_i as usize) * 4;
7622 row[off] = ctx.color_rgb[0];
7623 row[off + 1] = ctx.color_rgb[1];
7624 row[off + 2] = ctx.color_rgb[2];
7625 row[off + 3] = 255;
7626 shaded += 1;
7627 }
7628 } else {
7629 let inv_a: f32 = 1.0 - a;
7630 let sa_u32: u32 = (a * 255.0) as u32;
7631 let params: ShadowStripParams = ShadowStripParams {
7632 sr_a: ctx.lin_rgb[0] * a,
7633 sg_a: ctx.lin_rgb[1] * a,
7634 sb_a: ctx.lin_rgb[2] * a,
7635 inv_a,
7636 sa_u32,
7637 inv_a_u32: 255 - sa_u32,
7638 };
7639 let mut cache: ShadowPixelCache = ShadowPixelCache::default();
7640 if do_l {
7641 blend_shadow_mirrored_pixel(row, xl_i as u32, y_term, params, &mut cache);
7642 shaded += 1;
7643 }
7644 if do_r {
7645 blend_shadow_mirrored_pixel(row, xr_i as u32, y_term, params, &mut cache);
7646 shaded += 1;
7647 }
7648 }
7649 }
7650 shaded
7651 }
7652
7653 fn raster_shadow_corner_pair_symmetric(
7667 band: &mut PixelBand<'_>,
7668 ctx: &ShadowRenderCtx,
7669 y_t: u32,
7670 y_b: u32,
7671 cutouts: (Rect, Rect),
7672 ) -> usize {
7673 let py: f32 = (y_t as f32) + 0.5 - ctx.cy;
7674 let py_abs: f32 = py.abs();
7675 let (cut0_t, cut1_t): (u32, u32) = Self::shadow_row_cutout(y_t, cutouts, ctx.x0, ctx.x1);
7676 let (cut0_b, cut1_b): (u32, u32) = Self::shadow_row_cutout(y_b, cutouts, ctx.x0, ctx.x1);
7677 let mut shaded: usize = 0;
7678 if ctx.has_mid_x {
7679 let dist_y: f32 = py_abs - ctx.half_h;
7680 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7681 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7682 } else {
7683 0.0
7684 };
7685 if mid_alpha > 0.0005 {
7686 shaded +=
7687 Self::raster_shadow_middle_span(band, ctx, y_t, (cut0_t, cut1_t), mid_alpha);
7688 shaded +=
7689 Self::raster_shadow_middle_span(band, ctx, y_b, (cut0_b, cut1_b), mid_alpha);
7690 }
7691 }
7692 let (lat0, lat1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_t, cut1_t);
7693 let (rat0, rat1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_t, cut1_t);
7694 let (lab0, lab1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_b, cut1_b);
7695 let (rab0, rab1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_b, cut1_b);
7696 let mut u0: i32 = i32::MAX;
7697 let mut u1: i32 = i32::MIN;
7698 if lat0 < lat1 {
7699 u0 = u0.min(lat0 as i32);
7700 u1 = u1.max(lat1 as i32);
7701 }
7702 if rat0 < rat1 {
7703 u0 = u0.min(ctx.mirror_x_sum - (rat1 as i32) + 1);
7704 u1 = u1.max(ctx.mirror_x_sum - (rat0 as i32) + 1);
7705 }
7706 if lab0 < lab1 {
7707 u0 = u0.min(lab0 as i32);
7708 u1 = u1.max(lab1 as i32);
7709 }
7710 if rab0 < rab1 {
7711 u0 = u0.min(ctx.mirror_x_sum - (rab1 as i32) + 1);
7712 u1 = u1.max(ctx.mirror_x_sum - (rab0 as i32) + 1);
7713 }
7714 if u0 >= u1 {
7715 return shaded;
7716 }
7717 let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
7718 let qy_pos: f32 = qy.max(0.0);
7719 let qy_pos_sq: f32 = qy_pos * qy_pos;
7720 if qy > 0.0 {
7721 if qy_pos_sq >= ctx.cutoff_r_safe_sq {
7722 return shaded;
7723 }
7724 let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
7725 let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
7726 let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
7727 u0 = u0.max(tight_u0);
7728 if u0 >= u1 {
7729 return shaded;
7730 }
7731 }
7732 let Some((row_t, row_b)) = band.two_row_slices_mut(y_t, y_b) else {
7733 return shaded;
7734 };
7735 let sdf_geom: (f32, f32, f32, f32) =
7736 (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
7737 let y_term_t: f32 = (y_t as f32) * 0.005_837_15;
7738 let y_term_b: f32 = (y_b as f32) * 0.005_837_15;
7739 let x0_i: i32 = ctx.x0 as i32;
7740 let lx1_i: i32 = ctx.lx1 as i32;
7741 let rx0_i: i32 = ctx.rx0 as i32;
7742 let x1_i: i32 = ctx.x1 as i32;
7743 let cut0_ti: i32 = cut0_t as i32;
7744 let cut1_ti: i32 = cut1_t as i32;
7745 let cut0_bi: i32 = cut0_b as i32;
7746 let cut1_bi: i32 = cut1_b as i32;
7747 for xl_i in u0..u1 {
7748 let xr_i: i32 = ctx.mirror_x_sum - xl_i;
7749 let in_l: bool = xl_i >= x0_i && xl_i < lx1_i;
7750 let in_r: bool = xr_i >= rx0_i && xr_i < x1_i;
7751 let do_lt: bool = in_l && (xl_i < cut0_ti || xl_i >= cut1_ti);
7752 let do_rt: bool = in_r && (xr_i < cut0_ti || xr_i >= cut1_ti);
7753 let do_lb: bool = in_l && (xl_i < cut0_bi || xl_i >= cut1_bi);
7754 let do_rb: bool = in_r && (xr_i < cut0_bi || xr_i >= cut1_bi);
7755 if !do_lt && !do_rt && !do_lb && !do_rb {
7756 continue;
7757 }
7758 let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
7759 let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
7760 if dist >= ctx.cutoff {
7761 continue;
7762 }
7763 let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7764 if alpha_f <= 0.0005 {
7765 continue;
7766 }
7767 let a: f32 = alpha_f.clamp(0.0, 1.0);
7768 if a >= 0.9995 {
7769 if do_lt {
7770 let off: usize = (xl_i as usize) * 4;
7771 row_t[off] = ctx.color_rgb[0];
7772 row_t[off + 1] = ctx.color_rgb[1];
7773 row_t[off + 2] = ctx.color_rgb[2];
7774 row_t[off + 3] = 255;
7775 shaded += 1;
7776 }
7777 if do_rt {
7778 let off: usize = (xr_i as usize) * 4;
7779 row_t[off] = ctx.color_rgb[0];
7780 row_t[off + 1] = ctx.color_rgb[1];
7781 row_t[off + 2] = ctx.color_rgb[2];
7782 row_t[off + 3] = 255;
7783 shaded += 1;
7784 }
7785 if do_lb {
7786 let off: usize = (xl_i as usize) * 4;
7787 row_b[off] = ctx.color_rgb[0];
7788 row_b[off + 1] = ctx.color_rgb[1];
7789 row_b[off + 2] = ctx.color_rgb[2];
7790 row_b[off + 3] = 255;
7791 shaded += 1;
7792 }
7793 if do_rb {
7794 let off: usize = (xr_i as usize) * 4;
7795 row_b[off] = ctx.color_rgb[0];
7796 row_b[off + 1] = ctx.color_rgb[1];
7797 row_b[off + 2] = ctx.color_rgb[2];
7798 row_b[off + 3] = 255;
7799 shaded += 1;
7800 }
7801 } else {
7802 let inv_a: f32 = 1.0 - a;
7803 let sa_u32: u32 = (a * 255.0) as u32;
7804 let params: ShadowStripParams = ShadowStripParams {
7805 sr_a: ctx.lin_rgb[0] * a,
7806 sg_a: ctx.lin_rgb[1] * a,
7807 sb_a: ctx.lin_rgb[2] * a,
7808 inv_a,
7809 sa_u32,
7810 inv_a_u32: 255 - sa_u32,
7811 };
7812 let mut cache: ShadowPixelCache = ShadowPixelCache::default();
7813 if do_lt {
7814 blend_shadow_mirrored_pixel(row_t, xl_i as u32, y_term_t, params, &mut cache);
7815 shaded += 1;
7816 }
7817 if do_rt {
7818 blend_shadow_mirrored_pixel(row_t, xr_i as u32, y_term_t, params, &mut cache);
7819 shaded += 1;
7820 }
7821 if do_lb {
7822 blend_shadow_mirrored_pixel(row_b, xl_i as u32, y_term_b, params, &mut cache);
7823 shaded += 1;
7824 }
7825 if do_rb {
7826 blend_shadow_mirrored_pixel(row_b, xr_i as u32, y_term_b, params, &mut cache);
7827 shaded += 1;
7828 }
7829 }
7830 }
7831 shaded
7832 }
7833
7834 fn raster_shadow_corner_row_general(
7848 band: &mut PixelBand<'_>,
7849 ctx: &ShadowRenderCtx,
7850 radius: CornerRadius,
7851 y: u32,
7852 cutouts: (Rect, Rect),
7853 ) -> usize {
7854 let py: f32 = (y as f32) + 0.5 - ctx.cy;
7855 let py_abs: f32 = py.abs();
7856 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1);
7857 let spans: [(u32, u32); 2] = if cut0 < cut1 {
7858 [(ctx.x0, cut0), (cut1, ctx.x1)]
7859 } else {
7860 [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
7861 };
7862 let mut shaded: usize = 0;
7863 if ctx.has_mid_x {
7864 let dist_y: f32 = py_abs - ctx.half_h;
7865 let mid_alpha: f32 = if dist_y < ctx.cutoff {
7866 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
7867 } else {
7868 0.0
7869 };
7870 shaded += Self::raster_shadow_middle_span(band, ctx, y, (cut0, cut1), mid_alpha);
7871 }
7872 let Some(row) = band.row_slice_mut(y) else {
7873 return shaded;
7874 };
7875 let y_term: f32 = (y as f32) * 0.005_837_15;
7876 let r_l: f32 = (if py < 0.0 {
7877 radius.get_top_left()
7878 } else {
7879 radius.get_bottom_left()
7880 })
7881 .min(ctx.half_w)
7882 .min(ctx.half_h)
7883 .max(0.0);
7884 let r_r: f32 = (if py < 0.0 {
7885 radius.get_top_right()
7886 } else {
7887 radius.get_bottom_right()
7888 })
7889 .min(ctx.half_w)
7890 .min(ctx.half_h)
7891 .max(0.0);
7892 let qy_l: f32 = py_abs - ctx.half_h + r_l;
7893 let qy_l_pos: f32 = qy_l.max(0.0);
7894 let qy_l_sq: f32 = qy_l_pos * qy_l_pos;
7895 let cut_l_r: f32 = ctx.cutoff + r_l + 1e-3;
7896 let geom_l: (f32, f32, f32, f32) = (ctx.half_w, r_l, ctx.cutoff, cut_l_r * cut_l_r);
7897 let qy_r: f32 = py_abs - ctx.half_h + r_r;
7898 let qy_r_pos: f32 = qy_r.max(0.0);
7899 let qy_r_sq: f32 = qy_r_pos * qy_r_pos;
7900 let cut_r_r: f32 = ctx.cutoff + r_r + 1e-3;
7901 let geom_r: (f32, f32, f32, f32) = (ctx.half_w, r_r, ctx.cutoff, cut_r_r * cut_r_r);
7902 for (rx0, rx1) in spans.into_iter() {
7903 if rx0 >= rx1 {
7904 continue;
7905 }
7906 if ctx.has_mid_x {
7907 let l_end: u32 = rx1.min(ctx.lx1);
7908 for x in rx0..l_end {
7909 let px: f32 = (x as f32) + 0.5 - ctx.cx;
7910 let dist: f32 = if px < 0.0 {
7911 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7912 } else {
7913 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7914 };
7915 if dist < ctx.cutoff {
7916 let alpha_f: f32 =
7917 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7918 if alpha_f > 0.0005 {
7919 blend_shadow_row_pixel(
7920 row,
7921 x,
7922 y_term,
7923 ctx.color_rgb,
7924 ctx.lin_rgb,
7925 alpha_f,
7926 );
7927 shaded += 1;
7928 }
7929 }
7930 }
7931 let r_start: u32 = rx0.max(ctx.rx0);
7932 for x in r_start..rx1 {
7933 let px: f32 = (x as f32) + 0.5 - ctx.cx;
7934 let dist: f32 = if px < 0.0 {
7935 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7936 } else {
7937 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7938 };
7939 if dist < ctx.cutoff {
7940 let alpha_f: f32 =
7941 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7942 if alpha_f > 0.0005 {
7943 blend_shadow_row_pixel(
7944 row,
7945 x,
7946 y_term,
7947 ctx.color_rgb,
7948 ctx.lin_rgb,
7949 alpha_f,
7950 );
7951 shaded += 1;
7952 }
7953 }
7954 }
7955 } else {
7956 for x in rx0..rx1 {
7957 let px: f32 = (x as f32) + 0.5 - ctx.cx;
7958 let dist: f32 = if px < 0.0 {
7959 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
7960 } else {
7961 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
7962 };
7963 if dist >= ctx.cutoff {
7964 continue;
7965 }
7966 let alpha_f: f32 =
7967 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
7968 if alpha_f > 0.0005 {
7969 blend_shadow_row_pixel(row, x, y_term, ctx.color_rgb, ctx.lin_rgb, alpha_f);
7970 shaded += 1;
7971 }
7972 }
7973 }
7974 }
7975 shaded
7976 }
7977
7978 fn raster_shadow_vertical_strips(
7991 band: &mut PixelBand<'_>,
7992 ctx: &ShadowRenderCtx,
7993 y_span: (u32, u32),
7994 cutouts: (Rect, Rect),
7995 ) -> usize {
7996 let (sy0, sy1): (u32, u32) = y_span;
7997 if sy0 >= sy1 {
7998 return 0;
7999 }
8000 let (cut_h, _): (Rect, Rect) = cutouts;
8001 let sy0_f: f32 = (sy0 as f32) + 0.5;
8002 let sy1_last_f: f32 = ((sy1 - 1) as f32) + 0.5;
8003 let const_cut: Option<(u32, u32)> = if cut_h.get_width() > 0.0
8004 && cut_h.get_height() > 0.0
8005 && sy0_f >= cut_h.get_y()
8006 && sy1_last_f < cut_h.bottom()
8007 {
8008 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(ctx.x0, ctx.x1);
8009 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, ctx.x1);
8010 Some((cx0, cx1))
8011 } else {
8012 None
8013 };
8014 let (l_build0, l_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
8015 active_span_bounds(ctx.x0, ctx.lx1, c0, c1)
8016 } else {
8017 (ctx.x0, ctx.lx1)
8018 };
8019 let (r_build0, r_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
8020 active_span_bounds(ctx.rx0, ctx.x1, c0, c1)
8021 } else {
8022 (ctx.rx0, ctx.x1)
8023 };
8024 let mut shaded: usize = 0;
8025 let ran_tls: bool = BAND_SHADOW_SCRATCH
8026 .try_with(|cell: &RefCell<BandShadowScratch>| {
8027 if let Ok(mut scratch) = cell.try_borrow_mut() {
8028 let BandShadowScratch {
8029 left_hot,
8030 left_params,
8031 right_hot,
8032 right_params,
8033 } = &mut *scratch;
8034 let (l_act0, l_act1): (u32, u32) = build_shadow_vertical_strip(
8035 (l_build0, l_build1),
8036 ctx,
8037 left_hot,
8038 left_params,
8039 );
8040 let (r_act0, r_act1): (u32, u32) = build_shadow_vertical_strip(
8041 (r_build0, r_build1),
8042 ctx,
8043 right_hot,
8044 right_params,
8045 );
8046 if l_act0 >= l_act1 && r_act0 >= r_act1 {
8047 return;
8048 }
8049 let l_hot_s: &mut [ShadowStripHot] = left_hot.as_mut_slice();
8050 let l_par_s: &[ShadowStripParams] = left_params.as_slice();
8051 let r_hot_s: &mut [ShadowStripHot] = right_hot.as_mut_slice();
8052 let r_par_s: &[ShadowStripParams] = right_params.as_slice();
8053 for y in sy0..sy1 {
8054 let Some(row) = band.row_slice_mut(y) else {
8055 continue;
8056 };
8057 let y_term: f32 = (y as f32) * 0.005_837_15;
8058 let (cut0, cut1): (u32, u32) = const_cut
8059 .unwrap_or_else(|| Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1));
8060 if l_act0 < l_act1 {
8061 if cut0 < cut1 {
8062 let a_end: u32 = cut0.min(l_act1);
8063 if l_act0 < a_end {
8064 shaded += apply_shadow_strip_span(
8065 row,
8066 (l_act0, a_end, l_act0),
8067 y_term,
8068 ctx.color_rgb,
8069 l_hot_s,
8070 l_par_s,
8071 );
8072 }
8073 let b_start: u32 = cut1.max(l_act0);
8074 if b_start < l_act1 {
8075 shaded += apply_shadow_strip_span(
8076 row,
8077 (b_start, l_act1, l_act0),
8078 y_term,
8079 ctx.color_rgb,
8080 l_hot_s,
8081 l_par_s,
8082 );
8083 }
8084 } else {
8085 shaded += apply_shadow_strip_span(
8086 row,
8087 (l_act0, l_act1, l_act0),
8088 y_term,
8089 ctx.color_rgb,
8090 l_hot_s,
8091 l_par_s,
8092 );
8093 }
8094 }
8095 if r_act0 < r_act1 {
8096 if cut0 < cut1 {
8097 let a_end: u32 = cut0.min(r_act1);
8098 if r_act0 < a_end {
8099 shaded += apply_shadow_strip_span(
8100 row,
8101 (r_act0, a_end, r_act0),
8102 y_term,
8103 ctx.color_rgb,
8104 r_hot_s,
8105 r_par_s,
8106 );
8107 }
8108 let b_start: u32 = cut1.max(r_act0);
8109 if b_start < r_act1 {
8110 shaded += apply_shadow_strip_span(
8111 row,
8112 (b_start, r_act1, r_act0),
8113 y_term,
8114 ctx.color_rgb,
8115 r_hot_s,
8116 r_par_s,
8117 );
8118 }
8119 } else {
8120 shaded += apply_shadow_strip_span(
8121 row,
8122 (r_act0, r_act1, r_act0),
8123 y_term,
8124 ctx.color_rgb,
8125 r_hot_s,
8126 r_par_s,
8127 );
8128 }
8129 }
8130 }
8131 }
8132 })
8133 .is_ok();
8134 if !ran_tls {
8135 for y in sy0..sy1 {
8136 let Some(row) = band.row_slice_mut(y) else {
8137 continue;
8138 };
8139 let y_term: f32 = (y as f32) * 0.005_837_15;
8140 let (cut0, cut1): (u32, u32) = const_cut
8141 .unwrap_or_else(|| Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1));
8142 let spans: [(u32, u32); 2] = if cut0 < cut1 {
8143 [(ctx.x0, cut0), (cut1, ctx.x1)]
8144 } else {
8145 [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
8146 };
8147 for (rx0, rx1) in spans.into_iter() {
8148 let left_end: u32 = rx1.min(ctx.lx1);
8149 for x in rx0..left_end {
8150 let dist: f32 = ((x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
8151 if dist < ctx.cutoff {
8152 let alpha_f: f32 =
8153 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
8154 if alpha_f > 0.0005 {
8155 blend_shadow_row_pixel(
8156 row,
8157 x,
8158 y_term,
8159 ctx.color_rgb,
8160 ctx.lin_rgb,
8161 alpha_f,
8162 );
8163 shaded += 1;
8164 }
8165 }
8166 }
8167 let right_start: u32 = rx0.max(ctx.rx0);
8168 for x in right_start..rx1 {
8169 let dist: f32 = ((x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
8170 if dist < ctx.cutoff {
8171 let alpha_f: f32 =
8172 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
8173 if alpha_f > 0.0005 {
8174 blend_shadow_row_pixel(
8175 row,
8176 x,
8177 y_term,
8178 ctx.color_rgb,
8179 ctx.lin_rgb,
8180 alpha_f,
8181 );
8182 shaded += 1;
8183 }
8184 }
8185 }
8186 }
8187 }
8188 }
8189 shaded
8190 }
8191
8192 fn raster_shadow(
8207 band: &mut PixelBand<'_>,
8208 rects: (Rect, Rect, Rect),
8209 radius: CornerRadius,
8210 sigma: f32,
8211 color: Color,
8212 cutouts: (Rect, Rect),
8213 ) -> usize {
8214 let (shadow_rect, caster_rect, clip): (Rect, Rect, Rect) = rects;
8215 if color.get_a() == 0 {
8216 return 0;
8217 }
8218 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
8219 if base_alpha <= 0.0005 {
8220 return 0;
8221 }
8222 let Some(vis) = shadow_rect.intersect(clip) else {
8223 return 0;
8224 };
8225 let fb_w: u32 = band.width();
8226 let band_y0: u32 = band.y_offset();
8227 let band_y1: u32 = band.y_end();
8228 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
8229 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
8230 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
8231 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
8232 if x0 >= x1 || y0 >= y1 {
8233 return 0;
8234 }
8235 let half_w: f32 = (caster_rect.get_width() * 0.5).max(0.5);
8236 let half_h: f32 = (caster_rect.get_height() * 0.5).max(0.5);
8237 let cx: f32 = caster_rect.get_x() + half_w;
8238 let cy: f32 = caster_rect.get_y() + half_h;
8239 let inv_sigma: f32 = 1.0 / sigma.max(0.5);
8240 let cutoff: f32 = sigma * 3.0;
8241 let r_max: f32 = radius.max_radius();
8242 let inner_inset: f32 = cutoff + r_max;
8243 let sy0: u32 = ((caster_rect.get_y() + inner_inset).ceil().max(0.0) as u32).clamp(y0, y1);
8244 let sy1: u32 = ((caster_rect.bottom() - inner_inset).floor().max(0.0) as u32).clamp(y0, y1);
8245 let sx0: u32 = ((caster_rect.get_x() + inner_inset).ceil().max(0.0) as u32).clamp(x0, x1);
8246 let sx1: u32 = ((caster_rect.right() - inner_inset).floor().max(0.0) as u32).clamp(x0, x1);
8247 let has_mid_x: bool = sx0 < sx1;
8248 let has_mid_y: bool = sy0 < sy1;
8249 let r_tl: f32 = radius.get_top_left();
8250 let uniform_radius: bool = r_tl == radius.get_top_right()
8251 && r_tl == radius.get_bottom_right()
8252 && r_tl == radius.get_bottom_left();
8253 let two_cx_f: f32 = 2.0 * cx;
8254 let two_cx_i: i32 = two_cx_f.round() as i32;
8255 let x_symmetric: bool =
8256 uniform_radius && (two_cx_i as f32) == two_cx_f && two_cx_f.abs() < 16_777_216.0;
8257 let two_cy_f: f32 = 2.0 * cy;
8258 let two_cy_i: i32 = two_cy_f.round() as i32;
8259 let y_symmetric: bool =
8260 x_symmetric && (two_cy_i as f32) == two_cy_f && two_cy_f.abs() < 16_777_216.0;
8261 let uniform_r: f32 = r_tl.min(half_w).min(half_h).max(0.0);
8262 let cutoff_r_safe: f32 = cutoff + uniform_r + 1e-3;
8263 let (lx1, rx0): (u32, u32) = if has_mid_x {
8264 (sx0, sx1)
8265 } else if x_symmetric {
8266 let split_x: u32 = ((two_cx_i + 1).div_euclid(2).max(0) as u32).clamp(x0, x1);
8267 (split_x, split_x)
8268 } else {
8269 (x1, x1)
8270 };
8271 let color_rgb: [u8; 3] = [color.get_r(), color.get_g(), color.get_b()];
8272 let lin_rgb: [f32; 3] = [
8273 SRGB_TO_LIN_LUT[color_rgb[0] as usize],
8274 SRGB_TO_LIN_LUT[color_rgb[1] as usize],
8275 SRGB_TO_LIN_LUT[color_rgb[2] as usize],
8276 ];
8277 let ctx: ShadowRenderCtx = ShadowRenderCtx {
8278 color,
8279 color_rgb,
8280 lin_rgb,
8281 cx,
8282 cy,
8283 half_w,
8284 half_h,
8285 base_alpha,
8286 inv_sigma,
8287 cutoff,
8288 uniform_r,
8289 cutoff_r_safe_sq: cutoff_r_safe * cutoff_r_safe,
8290 x0,
8291 x1,
8292 lx1,
8293 rx0,
8294 mirror_x_sum: two_cx_i - 1,
8295 has_mid_x,
8296 };
8297 let mut shaded: usize = 0;
8298 if x_symmetric {
8299 let (top_end, bot_start): (u32, u32) = if has_mid_x && has_mid_y {
8300 (sy0, sy1)
8301 } else if y_symmetric {
8302 let split_y: u32 = ((two_cy_i + 1).div_euclid(2).max(0) as u32).clamp(y0, y1);
8303 (split_y, split_y)
8304 } else {
8305 (y1, y1)
8306 };
8307 let mirror_y_sum: i32 = two_cy_i - 1;
8308 let mut mirrored_b0: u32 = y1;
8309 let mut mirrored_b1: u32 = bot_start;
8310 for y_t in y0..top_end {
8311 let y_b_i: i32 = if y_symmetric {
8312 mirror_y_sum - (y_t as i32)
8313 } else {
8314 -1
8315 };
8316 if y_b_i >= (bot_start as i32) && y_b_i < (y1 as i32) {
8317 let y_b: u32 = y_b_i as u32;
8318 mirrored_b0 = mirrored_b0.min(y_b);
8319 mirrored_b1 = mirrored_b1.max(y_b + 1);
8320 shaded +=
8321 Self::raster_shadow_corner_pair_symmetric(band, &ctx, y_t, y_b, cutouts);
8322 } else {
8323 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_t, cutouts);
8324 }
8325 }
8326 if has_mid_x && has_mid_y {
8327 shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
8328 }
8329 if mirrored_b0 < mirrored_b1 {
8330 for y_b in bot_start..mirrored_b0 {
8331 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8332 }
8333 for y_b in mirrored_b1..y1 {
8334 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8335 }
8336 } else {
8337 for y_b in bot_start..y1 {
8338 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
8339 }
8340 }
8341 } else if has_mid_x && has_mid_y {
8342 for y in y0..sy0 {
8343 shaded += Self::raster_shadow_corner_row_general(band, &ctx, radius, y, cutouts);
8344 }
8345 shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
8346 for y in sy1..y1 {
8347 shaded += Self::raster_shadow_corner_row_general(band, &ctx, radius, y, cutouts);
8348 }
8349 } else {
8350 for y in y0..y1 {
8351 shaded += Self::raster_shadow_corner_row_general(band, &ctx, radius, y, cutouts);
8352 }
8353 }
8354 shaded
8355 }
8356
8357 fn raster_text_run_band(
8371 band: &mut PixelBand<'_>,
8372 positioned_glyphs: &[PositionedGlyph],
8373 color: Color,
8374 clip: Rect,
8375 glyph_atlas: &GlyphAtlas,
8376 ) -> usize {
8377 let fb_w: i32 = band.width() as i32;
8378 let band_y0: i32 = band.y_offset() as i32;
8379 let band_y1: i32 = band.y_end() as i32;
8380 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
8381 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).clamp(band_y0, band_y1);
8382 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(fb_w);
8383 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).clamp(band_y0, band_y1);
8384 if color.get_a() == 0 || clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
8385 return 0;
8386 }
8387 let mut shaded: usize = 0;
8388 for pg in positioned_glyphs.iter() {
8389 let gy0: i32 = pg.y;
8390 let gh: i32 = pg.height as i32;
8391 if gy0 >= clip_y1 || gy0 + gh <= clip_y0 {
8392 continue;
8393 }
8394 let gx0: i32 = pg.x;
8395 let gw: i32 = pg.width as i32;
8396 if gx0 >= clip_x1 || gx0 + gw <= clip_x0 {
8397 continue;
8398 }
8399 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(pg.glyph_idx);
8400 let py_start: i32 = (clip_y0 - gy0).max(0);
8401 let py_end: i32 = (clip_y1 - gy0).min(gh);
8402 let px_start: i32 = (clip_x0 - gx0).max(0);
8403 let px_end: i32 = (clip_x1 - gx0).min(gw);
8404 if py_start < py_end && px_start < px_end {
8405 let dy0: u32 = (gy0 + py_start) as u32;
8406 let dy1: u32 = (gy0 + py_end) as u32;
8407 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(dy0, dy1) {
8408 let cov_bytes: &[u8] = glyph.get_coverage().as_slice();
8409 let gw_usize: usize = gw as usize;
8410 let bx0: usize = ((gx0 + px_start) as usize) * 4;
8411 let bx1: usize = ((gx0 + px_end) as usize) * 4;
8412 let start_u: usize = px_start as usize;
8413 let end_u: usize = px_end as usize;
8414 let mut cov_off: usize = (py_start as usize) * gw_usize;
8415 for row in rows_buf.chunks_exact_mut(row_stride) {
8416 let row_slice: &[u8] = &cov_bytes[cov_off + start_u..cov_off + end_u];
8417 shaded += blend_glyph_row_span(&mut row[bx0..bx1], row_slice, color);
8418 cov_off += gw_usize;
8419 }
8420 }
8421 }
8422 }
8423 shaded
8424 }
8425
8426 #[inline(always)]
8435 fn blit_opaque_horiz_packed_u32(
8436 vrow: &[u32],
8437 dst_x0: usize,
8438 x_packed: &[u32],
8439 dst_row: &mut [u8],
8440 ) {
8441 let len: usize = x_packed.len();
8442 let span_bytes_start: usize = dst_x0 * 4;
8443 let span_bytes_end: usize = (dst_x0 + len) * 4;
8444 if span_bytes_end > dst_row.len() || vrow.len() < 2 {
8445 return;
8446 }
8447 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
8448 .as_chunks_mut::<4>()
8449 .0;
8450 let vptr: *const u32 = vrow.as_ptr();
8451 let dptr: *mut [u8; 4] = dst_chunks.as_mut_ptr();
8452 let lptr: *const u32 = x_packed.as_ptr();
8453 let mut i: usize = 0;
8454 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8455 {
8456 let v256: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(256);
8457 let v128_round: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(128);
8458 let alpha_mask: core::arch::wasm32::v128 = core::arch::wasm32::u32x4_splat(0xFF00_0000);
8459 while i + 2 <= len {
8460 unsafe {
8462 let e0: u32 = *lptr.add(i);
8463 let e1: u32 = *lptr.add(i + 1);
8464 let sx_a: usize = (e0 >> 9) as usize;
8465 let wx_a: u16 = (e0 & 0x1FF) as u16;
8466 let sx_b: usize = (e1 >> 9) as usize;
8467 let wx_b: u16 = (e1 & 0x1FF) as u16;
8468 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8469 let pair_b: u64 = vptr.add(sx_b).cast::<u64>().read_unaligned();
8470 let p0_u32: core::arch::wasm32::v128 =
8471 core::arch::wasm32::u32x4(pair_a as u32, pair_b as u32, 0, 0);
8472 let p1_u32: core::arch::wasm32::v128 = core::arch::wasm32::u32x4(
8473 (pair_a >> 32) as u32,
8474 (pair_b >> 32) as u32,
8475 0,
8476 0,
8477 );
8478 let p0_16: core::arch::wasm32::v128 =
8479 core::arch::wasm32::u16x8_extend_low_u8x16(p0_u32);
8480 let p1_16: core::arch::wasm32::v128 =
8481 core::arch::wasm32::u16x8_extend_low_u8x16(p1_u32);
8482 let wx_v: core::arch::wasm32::v128 =
8483 core::arch::wasm32::u16x8(wx_a, wx_a, wx_a, wx_a, wx_b, wx_b, wx_b, wx_b);
8484 let iwx_v: core::arch::wasm32::v128 = core::arch::wasm32::i16x8_sub(v256, wx_v);
8485 let sum: core::arch::wasm32::v128 = core::arch::wasm32::i16x8_add(
8486 core::arch::wasm32::i16x8_add(
8487 core::arch::wasm32::i16x8_mul(p0_16, iwx_v),
8488 core::arch::wasm32::i16x8_mul(p1_16, wx_v),
8489 ),
8490 v128_round,
8491 );
8492 let shr: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(sum, 8);
8493 let packed: core::arch::wasm32::v128 = core::arch::wasm32::v128_or(
8494 core::arch::wasm32::u8x16_narrow_i16x8(shr, shr),
8495 alpha_mask,
8496 );
8497 core::arch::wasm32::v128_store64_lane::<0>(packed, dptr.add(i).cast::<u64>());
8498 }
8499 i += 2;
8500 }
8501 }
8502 #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
8503 while i + 2 <= len {
8504 unsafe {
8506 let e0: u32 = *lptr.add(i);
8507 let e1: u32 = *lptr.add(i + 1);
8508 let sx_a: usize = (e0 >> 9) as usize;
8509 let wx_a: u32 = e0 & 0x1FF;
8510 let iwx_a: u32 = 256 - wx_a;
8511 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8512 let p0_a: u32 = pair_a as u32;
8513 let p1_a: u32 = (pair_a >> 32) as u32;
8514 let rb_a: u32 =
8515 (((p0_a & 0x00FF_00FF) * iwx_a + (p1_a & 0x00FF_00FF) * wx_a + 0x0080_0080)
8516 >> 8)
8517 & 0x00FF_00FF;
8518 let g_a: u32 =
8519 ((((p0_a >> 8) & 0x00FF) * iwx_a + ((p1_a >> 8) & 0x00FF) * wx_a + 128) >> 8)
8520 << 8;
8521 *dptr.add(i) = (rb_a | g_a | 0xFF00_0000).to_le_bytes();
8522 let sx_b: usize = (e1 >> 9) as usize;
8523 let wx_b: u32 = e1 & 0x1FF;
8524 let iwx_b: u32 = 256 - wx_b;
8525 let pair_b: u64 = vptr.add(sx_b).cast::<u64>().read_unaligned();
8526 let p0_b: u32 = pair_b as u32;
8527 let p1_b: u32 = (pair_b >> 32) as u32;
8528 let rb_b: u32 =
8529 (((p0_b & 0x00FF_00FF) * iwx_b + (p1_b & 0x00FF_00FF) * wx_b + 0x0080_0080)
8530 >> 8)
8531 & 0x00FF_00FF;
8532 let g_b: u32 =
8533 ((((p0_b >> 8) & 0x00FF) * iwx_b + ((p1_b >> 8) & 0x00FF) * wx_b + 128) >> 8)
8534 << 8;
8535 *dptr.add(i + 1) = (rb_b | g_b | 0xFF00_0000).to_le_bytes();
8536 }
8537 i += 2;
8538 }
8539 if i < len {
8540 unsafe {
8542 let e0: u32 = *lptr.add(i);
8543 let sx_a: usize = (e0 >> 9) as usize;
8544 let wx_a: u32 = e0 & 0x1FF;
8545 let iwx_a: u32 = 256 - wx_a;
8546 let pair_a: u64 = vptr.add(sx_a).cast::<u64>().read_unaligned();
8547 let p0_a: u32 = pair_a as u32;
8548 let p1_a: u32 = (pair_a >> 32) as u32;
8549 let rb_a: u32 =
8550 (((p0_a & 0x00FF_00FF) * iwx_a + (p1_a & 0x00FF_00FF) * wx_a + 0x0080_0080)
8551 >> 8)
8552 & 0x00FF_00FF;
8553 let g_a: u32 =
8554 ((((p0_a >> 8) & 0x00FF) * iwx_a + ((p1_a >> 8) & 0x00FF) * wx_a + 128) >> 8)
8555 << 8;
8556 *dptr.add(i) = (rb_a | g_a | 0xFF00_0000).to_le_bytes();
8557 }
8558 }
8559 }
8560
8561 #[inline(always)]
8569 fn copy_opaque_row_to_vrow(src0: &[[u8; 4]], sx_range: (usize, usize), vrow: &mut [u32]) {
8570 let (sx_min, sx_max): (usize, usize) = sx_range;
8571 for (&px, out) in src0[sx_min..=sx_max]
8572 .iter()
8573 .zip(vrow[sx_min..=sx_max].iter_mut())
8574 {
8575 *out = u32::from_le_bytes(px);
8576 }
8577 vrow[sx_max + 1] = vrow[sx_max];
8578 }
8579
8580 #[inline(always)]
8590 fn blend_opaque_rows_vert_swar(
8591 src0: &[[u8; 4]],
8592 src1: &[[u8; 4]],
8593 sx_range: (usize, usize),
8594 weights: (u32, u32),
8595 vrow: &mut [u32],
8596 ) {
8597 let (sx_min, sx_max): (usize, usize) = sx_range;
8598 let (wy, iwy): (u32, u32) = weights;
8599 let s0_slice: &[[u8; 4]] = &src0[sx_min..=sx_max];
8600 let s1_slice: &[[u8; 4]] = &src1[sx_min..=sx_max];
8601 let dst_slice: &mut [u32] = &mut vrow[sx_min..=sx_max];
8602 let mut idx: usize = 0;
8603 let count: usize = dst_slice.len();
8604 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8605 if count >= 4 {
8606 unsafe {
8608 let s0_ptr: *const u8 = s0_slice.as_ptr().cast();
8609 let s1_ptr: *const u8 = s1_slice.as_ptr().cast();
8610 let d_ptr: *mut u8 = dst_slice.as_mut_ptr().cast();
8611 let v_wy: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(wy as u16);
8612 let v_iwy: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(iwy as u16);
8613 let v_round: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_splat(128);
8614 let v_alpha: core::arch::wasm32::v128 =
8615 core::arch::wasm32::u32x4_splat(0xFF00_0000);
8616 while idx + 4 <= count {
8617 let b_off: usize = idx * 4;
8618 let a16: core::arch::wasm32::v128 =
8619 core::arch::wasm32::v128_load(s0_ptr.add(b_off).cast());
8620 let b16: core::arch::wasm32::v128 =
8621 core::arch::wasm32::v128_load(s1_ptr.add(b_off).cast());
8622 let a_lo: core::arch::wasm32::v128 =
8623 core::arch::wasm32::u16x8_extend_low_u8x16(a16);
8624 let b_lo: core::arch::wasm32::v128 =
8625 core::arch::wasm32::u16x8_extend_low_u8x16(b16);
8626 let a_hi: core::arch::wasm32::v128 =
8627 core::arch::wasm32::u16x8_extend_high_u8x16(a16);
8628 let b_hi: core::arch::wasm32::v128 =
8629 core::arch::wasm32::u16x8_extend_high_u8x16(b16);
8630 let lo: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(
8631 core::arch::wasm32::i16x8_add(
8632 core::arch::wasm32::i16x8_add(
8633 core::arch::wasm32::i16x8_mul(a_lo, v_iwy),
8634 core::arch::wasm32::i16x8_mul(b_lo, v_wy),
8635 ),
8636 v_round,
8637 ),
8638 8,
8639 );
8640 let hi: core::arch::wasm32::v128 = core::arch::wasm32::u16x8_shr(
8641 core::arch::wasm32::i16x8_add(
8642 core::arch::wasm32::i16x8_add(
8643 core::arch::wasm32::i16x8_mul(a_hi, v_iwy),
8644 core::arch::wasm32::i16x8_mul(b_hi, v_wy),
8645 ),
8646 v_round,
8647 ),
8648 8,
8649 );
8650 let packed: core::arch::wasm32::v128 = core::arch::wasm32::v128_or(
8651 core::arch::wasm32::u8x16_narrow_i16x8(lo, hi),
8652 v_alpha,
8653 );
8654 core::arch::wasm32::v128_store(d_ptr.add(b_off).cast(), packed);
8655 idx += 4;
8656 }
8657 }
8658 }
8659 while idx < count {
8660 let p0: u32 = u32::from_le_bytes(s0_slice[idx]);
8661 let p1: u32 = u32::from_le_bytes(s1_slice[idx]);
8662 let rb: u32 = (((p0 & 0x00FF_00FF) * iwy + (p1 & 0x00FF_00FF) * wy + 0x0080_0080) >> 8)
8663 & 0x00FF_00FF;
8664 let g: u32 = ((((p0 >> 8) & 0x00FF) * iwy + ((p1 >> 8) & 0x00FF) * wy + 128) >> 8) << 8;
8665 dst_slice[idx] = (rb | g) | 0xFF00_0000;
8666 idx += 1;
8667 }
8668 vrow[sx_max + 1] = vrow[sx_max];
8669 }
8670
8671 #[inline(always)]
8685 fn blit_bilinear_span_precomputed(
8686 y_params: (usize, usize, u32, u32),
8687 dst_x0: usize,
8688 x_lut: &[(usize, usize, u32)],
8689 src_bytes: &[u8],
8690 dst_row: &mut [u8],
8691 ) -> usize {
8692 let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
8693 let span_bytes_start: usize = dst_x0 * 4;
8694 let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
8695 if span_bytes_end > dst_row.len() {
8696 return 0;
8697 }
8698 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
8699 .as_chunks_mut::<4>()
8700 .0;
8701 let src_len: usize = src_bytes.len();
8702 let mut shaded: usize = 0;
8703 if wy == 0 {
8704 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
8705 let i0: usize = (row0 + sx0) * 4;
8706 let i1: usize = (row0 + sx1) * 4;
8707 if i1 + 4 > src_len {
8708 continue;
8709 }
8710 let iwx: u32 = 256 - wx;
8711 let a0: u32 = src_bytes[i0 + 3] as u32;
8712 let a1: u32 = src_bytes[i1 + 3] as u32;
8713 if (a0 & a1) == 255 {
8714 dp[0] = (((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128)
8715 >> 8) as u8;
8716 dp[1] =
8717 (((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128)
8718 >> 8) as u8;
8719 dp[2] =
8720 (((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128)
8721 >> 8) as u8;
8722 dp[3] = 255;
8723 shaded += 1;
8724 continue;
8725 }
8726 let aw0: u32 = a0 * iwx;
8727 let aw1: u32 = a1 * wx;
8728 let a_val: u32 = (aw0 + aw1 + 128) >> 8;
8729 if a_val == 0 {
8730 continue;
8731 }
8732 let pr: u32 =
8733 ((src_bytes[i0] as u32) * aw0 + (src_bytes[i1] as u32) * aw1 + 128) >> 8;
8734 let pg: u32 =
8735 ((src_bytes[i0 + 1] as u32) * aw0 + (src_bytes[i1 + 1] as u32) * aw1 + 128)
8736 >> 8;
8737 let pb: u32 =
8738 ((src_bytes[i0 + 2] as u32) * aw0 + (src_bytes[i1 + 2] as u32) * aw1 + 128)
8739 >> 8;
8740 let inv_a: u32 = 255 - a_val;
8741 let vr: u32 = pr + (dp[0] as u32) * inv_a + 128;
8742 let vg: u32 = pg + (dp[1] as u32) * inv_a + 128;
8743 let vb: u32 = pb + (dp[2] as u32) * inv_a + 128;
8744 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
8745 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
8746 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
8747 dp[3] = 255;
8748 shaded += 1;
8749 }
8750 return shaded;
8751 }
8752 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
8753 let i00: usize = (row0 + sx0) * 4;
8754 let i10: usize = (row0 + sx1) * 4;
8755 let i01: usize = (row1 + sx0) * 4;
8756 let i11: usize = (row1 + sx1) * 4;
8757 if i11 + 4 > src_len {
8758 continue;
8759 }
8760 let iwx: u32 = 256 - wx;
8761 let w00: u32 = iwx * iwy;
8762 let w10: u32 = wx * iwy;
8763 let w01: u32 = iwx * wy;
8764 let w11: u32 = wx * wy;
8765 let a00: u32 = src_bytes[i00 + 3] as u32;
8766 let a10: u32 = src_bytes[i10 + 3] as u32;
8767 let a01: u32 = src_bytes[i01 + 3] as u32;
8768 let a11: u32 = src_bytes[i11 + 3] as u32;
8769 if (a00 & a10 & a01 & a11) == 255 {
8770 dp[0] = (((src_bytes[i00] as u32) * w00
8771 + (src_bytes[i10] as u32) * w10
8772 + (src_bytes[i01] as u32) * w01
8773 + (src_bytes[i11] as u32) * w11
8774 + 32768)
8775 >> 16) as u8;
8776 dp[1] = (((src_bytes[i00 + 1] as u32) * w00
8777 + (src_bytes[i10 + 1] as u32) * w10
8778 + (src_bytes[i01 + 1] as u32) * w01
8779 + (src_bytes[i11 + 1] as u32) * w11
8780 + 32768)
8781 >> 16) as u8;
8782 dp[2] = (((src_bytes[i00 + 2] as u32) * w00
8783 + (src_bytes[i10 + 2] as u32) * w10
8784 + (src_bytes[i01 + 2] as u32) * w01
8785 + (src_bytes[i11 + 2] as u32) * w11
8786 + 32768)
8787 >> 16) as u8;
8788 dp[3] = 255;
8789 shaded += 1;
8790 continue;
8791 }
8792 let aw00: u64 = (a00 as u64) * (w00 as u64);
8793 let aw10: u64 = (a10 as u64) * (w10 as u64);
8794 let aw01: u64 = (a01 as u64) * (w01 as u64);
8795 let aw11: u64 = (a11 as u64) * (w11 as u64);
8796 let a_val: u32 = ((aw00 + aw10 + aw01 + aw11 + 32768) >> 16) as u32;
8797 if a_val == 0 {
8798 continue;
8799 }
8800 let pr: u32 = (((src_bytes[i00] as u64) * aw00
8801 + (src_bytes[i10] as u64) * aw10
8802 + (src_bytes[i01] as u64) * aw01
8803 + (src_bytes[i11] as u64) * aw11
8804 + 32768)
8805 >> 16) as u32;
8806 let pg: u32 = (((src_bytes[i00 + 1] as u64) * aw00
8807 + (src_bytes[i10 + 1] as u64) * aw10
8808 + (src_bytes[i01 + 1] as u64) * aw01
8809 + (src_bytes[i11 + 1] as u64) * aw11
8810 + 32768)
8811 >> 16) as u32;
8812 let pb: u32 = (((src_bytes[i00 + 2] as u64) * aw00
8813 + (src_bytes[i10 + 2] as u64) * aw10
8814 + (src_bytes[i01 + 2] as u64) * aw01
8815 + (src_bytes[i11 + 2] as u64) * aw11
8816 + 32768)
8817 >> 16) as u32;
8818 let inv_a: u32 = 255 - a_val;
8819 let vr: u32 = pr + (dp[0] as u32) * inv_a + 128;
8820 let vg: u32 = pg + (dp[1] as u32) * inv_a + 128;
8821 let vb: u32 = pb + (dp[2] as u32) * inv_a + 128;
8822 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
8823 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
8824 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
8825 dp[3] = 255;
8826 shaded += 1;
8827 }
8828 shaded
8829 }
8830
8831 fn raster_image_bilinear_with_lut(
8847 band: &mut PixelBand<'_>,
8848 rect: Rect,
8849 src_info: (u32, u32, &[u8]),
8850 bounds: (u32, u32, u32, u32),
8851 radius: CornerRadius,
8852 aa: AntialiasingMode,
8853 x_lut: &mut Vec<(usize, usize, u32)>,
8854 ) -> usize {
8855 let (src_w, src_h, src_bytes): (u32, u32, &[u8]) = src_info;
8856 let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
8857 let rect_x: f32 = rect.get_x();
8858 let rect_y: f32 = rect.get_y();
8859 let half_w: f32 = rect.get_width() * 0.5;
8860 let half_h: f32 = rect.get_height() * 0.5;
8861 let cx: f32 = rect_x + half_w;
8862 let cy: f32 = rect_y + half_h;
8863 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
8864 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
8865 let src_w_f: f32 = src_w as f32;
8866 let src_h_f: f32 = src_h as f32;
8867 let src_w_usize: usize = src_w as usize;
8868 let max_sx: usize = src_w_usize.saturating_sub(1);
8869 let max_sy: usize = (src_h as usize).saturating_sub(1);
8870 let has_radius: bool = radius.max_radius() > 0.0;
8871 x_lut.clear();
8872 for x in x0..x1 {
8873 let u: f32 = (((x as f32) + 0.5 - rect_x) * inv_dst_w).clamp(0.0, 1.0);
8874 let fx: f32 = (u * src_w_f - 0.5).clamp(0.0, max_sx as f32);
8875 let sx0: usize = (fx.floor() as usize).min(max_sx);
8876 let sx1: usize = (sx0 + 1).min(max_sx);
8877 let wx: u32 = ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
8878 x_lut.push((sx0, sx1, wx));
8879 }
8880 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
8881 if !has_radius {
8882 let x0_u: usize = x0 as usize;
8883 let sx_min: usize = x_lut_ref.first().map_or(0, |e: &(usize, usize, u32)| e.0);
8884 let sx_max: usize = x_lut_ref
8885 .last()
8886 .map_or(0, |e: &(usize, usize, u32)| e.1)
8887 .min(max_sx);
8888 let src_row_bytes_len: usize = src_w_usize * 4;
8889 let can_fast_opaque: bool = !x_lut_ref.is_empty()
8890 && sx_min <= sx_max
8891 && sx_max < src_w_usize
8892 && (src_h as usize) * src_row_bytes_len <= src_bytes.len();
8893 if can_fast_opaque {
8894 let mut cached_op_sy: usize = usize::MAX;
8895 let mut cached_op_val: bool = false;
8896 let mut cached_op_sy2: usize = usize::MAX;
8897 let mut cached_op_val2: bool = false;
8898 let ran_vrow: bool = BAND_IMAGE_VROW_U32
8899 .try_with(|cell: &RefCell<Vec<u32>>| {
8900 let _ran_packed: bool = BAND_IMAGE_X_PACKED
8901 .try_with(|pcell: &RefCell<Vec<u32>>| {
8902 if let (Ok(mut vrow_guard), Ok(mut packed_guard)) =
8903 (cell.try_borrow_mut(), pcell.try_borrow_mut())
8904 {
8905 if vrow_guard.len() < src_w_usize + 1 {
8906 vrow_guard.resize(src_w_usize + 1, 0);
8907 }
8908 packed_guard.clear();
8909 for &(sx0, _, wx) in x_lut_ref.iter() {
8910 packed_guard.push(((sx0 as u32) << 9) | (wx & 0x1FF));
8911 }
8912 let x_packed_ref: &[u32] = packed_guard.as_slice();
8913 let vrow: &mut [u32] = vrow_guard.as_mut_slice();
8914 let mut prev_vkey: (usize, usize, u32) =
8915 (usize::MAX, usize::MAX, u32::MAX);
8916 let check_start: usize = sx_min * 4;
8917 let check_end: usize = (sx_max + 1) * 4;
8918 for y in y0..y1 {
8919 let Some(dst_row) = band.row_slice_mut(y) else {
8920 continue;
8921 };
8922 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h)
8923 .clamp(0.0, 1.0);
8924 let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
8925 let sy0: usize = (fy.floor() as usize).min(max_sy);
8926 let sy1: usize = (sy0 + 1).min(max_sy);
8927 let wy: u32 =
8928 ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0)
8929 as u32;
8930 let r0_off: usize = sy0 * src_row_bytes_len;
8931 let op0: bool = if sy0 == cached_op_sy {
8932 cached_op_val
8933 } else if sy0 == cached_op_sy2 {
8934 cached_op_val2
8935 } else {
8936 let val: bool = is_rgba_slice_opaque(
8937 &src_bytes
8938 [(r0_off + check_start)..(r0_off + check_end)],
8939 );
8940 cached_op_sy2 = cached_op_sy;
8941 cached_op_val2 = cached_op_val;
8942 cached_op_sy = sy0;
8943 cached_op_val = val;
8944 val
8945 };
8946 if wy == 0 || sy0 == sy1 {
8947 if op0 {
8948 let vkey: (usize, usize, u32) = (sy0, sy0, 0);
8949 if prev_vkey != vkey {
8950 let row0_px: &[[u8; 4]] = src_bytes
8951 [r0_off..(r0_off + src_row_bytes_len)]
8952 .as_chunks::<4>()
8953 .0;
8954 Self::copy_opaque_row_to_vrow(
8955 row0_px,
8956 (sx_min, sx_max),
8957 vrow,
8958 );
8959 prev_vkey = vkey;
8960 }
8961 Self::blit_opaque_horiz_packed_u32(
8962 vrow,
8963 x0_u,
8964 x_packed_ref,
8965 dst_row,
8966 );
8967 continue;
8968 }
8969 } else if op0 {
8970 let r1_off: usize = sy1 * src_row_bytes_len;
8971 let op1: bool = if sy1 == cached_op_sy {
8972 cached_op_val
8973 } else if sy1 == cached_op_sy2 {
8974 cached_op_val2
8975 } else {
8976 let val: bool = is_rgba_slice_opaque(
8977 &src_bytes[(r1_off + check_start)
8978 ..(r1_off + check_end)],
8979 );
8980 cached_op_sy2 = cached_op_sy;
8981 cached_op_val2 = cached_op_val;
8982 cached_op_sy = sy1;
8983 cached_op_val = val;
8984 val
8985 };
8986 if op1 {
8987 let vkey: (usize, usize, u32) = (sy0, sy1, wy);
8988 if prev_vkey != vkey {
8989 let row0_px: &[[u8; 4]] = src_bytes
8990 [r0_off..(r0_off + src_row_bytes_len)]
8991 .as_chunks::<4>()
8992 .0;
8993 let row1_px: &[[u8; 4]] = src_bytes
8994 [r1_off..(r1_off + src_row_bytes_len)]
8995 .as_chunks::<4>()
8996 .0;
8997 Self::blend_opaque_rows_vert_swar(
8998 row0_px,
8999 row1_px,
9000 (sx_min, sx_max),
9001 (wy, 256 - wy),
9002 vrow,
9003 );
9004 prev_vkey = vkey;
9005 }
9006 Self::blit_opaque_horiz_packed_u32(
9007 vrow,
9008 x0_u,
9009 x_packed_ref,
9010 dst_row,
9011 );
9012 continue;
9013 }
9014 }
9015 let y_params: (usize, usize, u32, u32) =
9016 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
9017 let _: usize = Self::blit_bilinear_span_precomputed(
9018 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
9019 );
9020 }
9021 }
9022 })
9023 .is_ok();
9024 })
9025 .is_ok();
9026 if ran_vrow {
9027 return ((x1 - x0) as usize) * ((y1 - y0) as usize);
9028 }
9029 }
9030 for y in y0..y1 {
9031 let Some(dst_row) = band.row_slice_mut(y) else {
9032 continue;
9033 };
9034 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
9035 let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
9036 let sy0: usize = (fy.floor() as usize).min(max_sy);
9037 let sy1: usize = (sy0 + 1).min(max_sy);
9038 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
9039 let y_params: (usize, usize, u32, u32) =
9040 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
9041 let _: usize = Self::blit_bilinear_span_precomputed(
9042 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
9043 );
9044 }
9045 return ((x1 - x0) as usize) * ((y1 - y0) as usize);
9046 }
9047 let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
9048 let ix0: u32 = ((rect_x + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
9049 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
9050 let iy0: u32 = ((rect_y + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
9051 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
9052 let cx0: u32 = ((rect_x + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
9053 let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
9054 let mut shaded: usize = 0;
9055 for y in y0..iy0 {
9056 let Some(dst_row) = band.row_slice_mut(y) else {
9057 continue;
9058 };
9059 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
9060 let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
9061 let sy0: usize = (fy.floor() as usize).min(max_sy);
9062 let sy1: usize = (sy0 + 1).min(max_sy);
9063 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
9064 let y_params: (usize, usize, u32, u32) =
9065 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
9066 let py: f32 = (y as f32) + 0.5 - cy;
9067 let dist_y: f32 = py.abs() - half_h;
9068 let mid_cov: f32 = sdf_coverage(dist_y, aa);
9069 if cx0 < cx1 && mid_cov > 0.0 {
9070 let lut_s: usize = (cx0 - x0) as usize;
9071 let lut_e: usize = (cx1 - x0) as usize;
9072 if mid_cov >= 0.9995 {
9073 let _: usize = Self::blit_bilinear_span_precomputed(
9074 y_params,
9075 cx0 as usize,
9076 &x_lut_ref[lut_s..lut_e],
9077 src_bytes,
9078 dst_row,
9079 );
9080 } else {
9081 for x in cx0..cx1 {
9082 let rgba: [u8; 4] = sample_bilinear_fixed(
9083 src_bytes,
9084 y_params,
9085 x_lut_ref[(x - x0) as usize],
9086 );
9087 let off: usize = (x as usize) * 4;
9088 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
9089 }
9090 }
9091 shaded += (cx1 - cx0) as usize;
9092 }
9093 for x in x0..cx0 {
9094 let px: f32 = (x as f32) + 0.5 - cx;
9095 let cr: f32 = quadrant_corner_radius(radius, px, py);
9096 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
9097 if cov > 0.0 {
9098 let rgba: [u8; 4] =
9099 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
9100 let off: usize = (x as usize) * 4;
9101 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9102 shaded += 1;
9103 }
9104 }
9105 for x in cx1..x1 {
9106 let px: f32 = (x as f32) + 0.5 - cx;
9107 let cr: f32 = quadrant_corner_radius(radius, px, py);
9108 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
9109 if cov > 0.0 {
9110 let rgba: [u8; 4] =
9111 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
9112 let off: usize = (x as usize) * 4;
9113 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9114 shaded += 1;
9115 }
9116 }
9117 }
9118 for y in iy0..iy1 {
9119 let Some(dst_row) = band.row_slice_mut(y) else {
9120 continue;
9121 };
9122 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
9123 let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
9124 let sy0: usize = (fy.floor() as usize).min(max_sy);
9125 let sy1: usize = (sy0 + 1).min(max_sy);
9126 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
9127 let y_params: (usize, usize, u32, u32) =
9128 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
9129 if ix0 < ix1 {
9130 let lut_s: usize = (ix0 - x0) as usize;
9131 let lut_e: usize = (ix1 - x0) as usize;
9132 let _: usize = Self::blit_bilinear_span_precomputed(
9133 y_params,
9134 ix0 as usize,
9135 &x_lut_ref[lut_s..lut_e],
9136 src_bytes,
9137 dst_row,
9138 );
9139 shaded += (ix1 - ix0) as usize;
9140 }
9141 for x in x0..ix0 {
9142 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
9143 let cov: f32 = sdf_coverage(dist, aa);
9144 if cov > 0.0 {
9145 let rgba: [u8; 4] =
9146 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
9147 let off: usize = (x as usize) * 4;
9148 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9149 shaded += 1;
9150 }
9151 }
9152 for x in ix1..x1 {
9153 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
9154 let cov: f32 = sdf_coverage(dist, aa);
9155 if cov > 0.0 {
9156 let rgba: [u8; 4] =
9157 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
9158 let off: usize = (x as usize) * 4;
9159 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9160 shaded += 1;
9161 }
9162 }
9163 }
9164 for y in iy1..y1 {
9165 let Some(dst_row) = band.row_slice_mut(y) else {
9166 continue;
9167 };
9168 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
9169 let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
9170 let sy0: usize = (fy.floor() as usize).min(max_sy);
9171 let sy1: usize = (sy0 + 1).min(max_sy);
9172 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
9173 let y_params: (usize, usize, u32, u32) =
9174 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
9175 let py: f32 = (y as f32) + 0.5 - cy;
9176 let dist_y: f32 = py.abs() - half_h;
9177 let mid_cov: f32 = sdf_coverage(dist_y, aa);
9178 if cx0 < cx1 && mid_cov > 0.0 {
9179 let lut_s: usize = (cx0 - x0) as usize;
9180 let lut_e: usize = (cx1 - x0) as usize;
9181 if mid_cov >= 0.9995 {
9182 let _: usize = Self::blit_bilinear_span_precomputed(
9183 y_params,
9184 cx0 as usize,
9185 &x_lut_ref[lut_s..lut_e],
9186 src_bytes,
9187 dst_row,
9188 );
9189 } else {
9190 for x in cx0..cx1 {
9191 let rgba: [u8; 4] = sample_bilinear_fixed(
9192 src_bytes,
9193 y_params,
9194 x_lut_ref[(x - x0) as usize],
9195 );
9196 let off: usize = (x as usize) * 4;
9197 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
9198 }
9199 }
9200 shaded += (cx1 - cx0) as usize;
9201 }
9202 for x in x0..cx0 {
9203 let px: f32 = (x as f32) + 0.5 - cx;
9204 let cr: f32 = quadrant_corner_radius(radius, px, py);
9205 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
9206 if cov > 0.0 {
9207 let rgba: [u8; 4] =
9208 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
9209 let off: usize = (x as usize) * 4;
9210 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9211 shaded += 1;
9212 }
9213 }
9214 for x in cx1..x1 {
9215 let px: f32 = (x as f32) + 0.5 - cx;
9216 let cr: f32 = quadrant_corner_radius(radius, px, py);
9217 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
9218 if cov > 0.0 {
9219 let rgba: [u8; 4] =
9220 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
9221 let off: usize = (x as usize) * 4;
9222 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
9223 shaded += 1;
9224 }
9225 }
9226 }
9227 shaded
9228 }
9229
9230 fn raster_rgba_bytes(
9245 band: &mut PixelBand<'_>,
9246 rect: Rect,
9247 source: (u32, u32, &[u8]),
9248 radius: CornerRadius,
9249 clip: Rect,
9250 aa: AntialiasingMode,
9251 ) -> usize {
9252 let (src_w, src_h, src_bytes): (u32, u32, &[u8]) = source;
9253 if src_w == 0 || src_h == 0 {
9254 return 0;
9255 }
9256 let Some(vis) = rect.intersect(clip) else {
9257 return 0;
9258 };
9259 let fb_w: u32 = band.width();
9260 let band_y0: u32 = band.y_offset();
9261 let band_y1: u32 = band.y_end();
9262 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9263 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9264 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9265 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9266 if x0 >= x1 || y0 >= y1 {
9267 return 0;
9268 }
9269 let half_w: f32 = rect.get_width() * 0.5;
9270 let half_h: f32 = rect.get_height() * 0.5;
9271 let cx: f32 = rect.get_x() + half_w;
9272 let cy: f32 = rect.get_y() + half_h;
9273 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
9274 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
9275 let use_bilinear: bool = aa != AntialiasingMode::None
9276 && ((rect.get_width() - (src_w as f32)).abs() > 0.5
9277 || (rect.get_height() - (src_h as f32)).abs() > 0.5);
9278 let has_radius: bool = radius.max_radius() > 0.0;
9279 let max_sx: usize = (src_w as usize).saturating_sub(1);
9280 let max_sy: usize = (src_h as usize).saturating_sub(1);
9281 let src_w_usize: usize = src_w as usize;
9282 let is_exact_1to1: bool = !use_bilinear
9283 && (rect.get_width() - (src_w as f32)).abs() <= 0.01
9284 && (rect.get_height() - (src_h as f32)).abs() <= 0.01
9285 && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
9286 && (rect.get_y() - rect.get_y().round()).abs() <= 0.01;
9287 let rx0_i: i32 = rect.get_x().round() as i32;
9288 let ry0_i: i32 = rect.get_y().round() as i32;
9289 if is_exact_1to1
9290 && !has_radius
9291 && (x0 as i32) >= rx0_i
9292 && (x1 as i32) <= rx0_i + (src_w as i32)
9293 && (y0 as i32) >= ry0_i
9294 && (y1 as i32) <= ry0_i + (src_h as i32)
9295 {
9296 let span_w: usize = (x1 - x0) as usize;
9297 let src_x_off: usize = ((x0 as i32) - rx0_i) as usize;
9298 let dst_byte0: usize = (x0 as usize) * 4;
9299 let dst_byte1: usize = (x1 as usize) * 4;
9300 for y in y0..y1 {
9301 let Some(dst_row) = band.row_slice_mut(y) else {
9302 continue;
9303 };
9304 let sy: usize = ((y as i32) - ry0_i) as usize;
9305 let src_byte0: usize = (sy * src_w_usize + src_x_off) * 4;
9306 let src_byte1: usize = src_byte0 + span_w * 4;
9307 if src_byte1 <= src_bytes.len() && dst_byte1 <= dst_row.len() {
9308 blit_1to1_rgba_span(
9309 &src_bytes[src_byte0..src_byte1],
9310 &mut dst_row[dst_byte0..dst_byte1],
9311 );
9312 }
9313 }
9314 return span_w * ((y1 - y0) as usize);
9315 }
9316 if use_bilinear {
9317 let mut shaded: usize = 0;
9318 let ran_tls: bool = BAND_IMAGE_X_LUT
9319 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
9320 if let Ok(mut guard) = cell.try_borrow_mut() {
9321 shaded = Self::raster_image_bilinear_with_lut(
9322 band,
9323 rect,
9324 (src_w, src_h, src_bytes),
9325 (x0, y0, x1, y1),
9326 radius,
9327 aa,
9328 &mut guard,
9329 );
9330 }
9331 })
9332 .is_ok();
9333 if !ran_tls {
9334 let mut fallback_lut: Vec<(usize, usize, u32)> =
9335 Vec::with_capacity((x1 - x0) as usize);
9336 shaded = Self::raster_image_bilinear_with_lut(
9337 band,
9338 rect,
9339 (src_w, src_h, src_bytes),
9340 (x0, y0, x1, y1),
9341 radius,
9342 aa,
9343 &mut fallback_lut,
9344 );
9345 }
9346 return shaded;
9347 }
9348 if !has_radius && (src_h as usize) * src_w_usize * 4 <= src_bytes.len() {
9349 let x0_u: usize = x0 as usize;
9350 let span_w: usize = (x1 - x0) as usize;
9351 let dst_b0: usize = x0_u * 4;
9352 let dst_b1: usize = (x1 as usize) * 4;
9353 let src_w_f: f32 = src_w as f32;
9354 let src_h_f: f32 = src_h as f32;
9355 let mut sx_arr_ok: bool = false;
9356 let _ran_tls_nn: bool = BAND_IMAGE_X_LUT
9357 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
9358 if let Ok(mut lut) = cell.try_borrow_mut() {
9359 lut.clear();
9360 for x in x0..x1 {
9361 let u: f32 =
9362 (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9363 let sx: usize = ((u * src_w_f).floor() as usize).min(max_sx);
9364 lut.push((sx, 0, 0));
9365 }
9366 let lut_ref: &[(usize, usize, u32)] = lut.as_slice();
9367 let row_bytes_len: usize = src_w_usize * 4;
9368 let mut cached_sy: usize = usize::MAX;
9369 let mut cached_opaque: bool = false;
9370 for y in y0..y1 {
9371 let Some(dst_row) = band.row_slice_mut(y) else {
9372 continue;
9373 };
9374 if dst_b1 > dst_row.len() {
9375 continue;
9376 }
9377 let v: f32 =
9378 (((y as f32) + 0.5 - rect.get_y()) * inv_dst_h).clamp(0.0, 1.0);
9379 let sy: usize = ((v * src_h_f).floor() as usize).min(max_sy);
9380 let r_off: usize = sy * row_bytes_len;
9381 let row_slice: &[u8] = &src_bytes[r_off..(r_off + row_bytes_len)];
9382 let is_op: bool = if sy == cached_sy {
9383 cached_opaque
9384 } else {
9385 cached_sy = sy;
9386 cached_opaque = is_rgba_slice_opaque(row_slice);
9387 cached_opaque
9388 };
9389 let src_px: &[[u8; 4]] = row_slice.as_chunks::<4>().0;
9390 let dst_px: &mut [[u8; 4]] =
9391 dst_row[dst_b0..dst_b1].as_chunks_mut::<4>().0;
9392 if is_op {
9393 let sptr: *const [u8; 4] = src_px.as_ptr();
9394 for (dp, &(sx, _, _)) in dst_px.iter_mut().zip(lut_ref.iter()) {
9395 *dp = unsafe { *sptr.add(sx) };
9397 }
9398 } else {
9399 for (dp, &(sx, _, _)) in dst_px.iter_mut().zip(lut_ref.iter()) {
9400 blend_rgba_pixel_with_cov(dp, src_px[sx], 1.0);
9401 }
9402 }
9403 }
9404 sx_arr_ok = true;
9405 }
9406 })
9407 .is_ok();
9408 if sx_arr_ok {
9409 return span_w * ((y1 - y0) as usize);
9410 }
9411 }
9412 let mut shaded: usize = 0;
9413 let r_max: f32 = if has_radius {
9414 radius.max_radius().min(half_w).min(half_h).max(0.0)
9415 } else {
9416 0.0
9417 };
9418 let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
9419 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
9420 let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
9421 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
9422 let can_1to1_interior: bool = is_exact_1to1
9423 && (ix0 as i32) >= rx0_i
9424 && (ix1 as i32) <= rx0_i + (src_w as i32)
9425 && (iy0 as i32) >= ry0_i
9426 && (iy1 as i32) <= ry0_i + (src_h as i32);
9427 for y in y0..y1 {
9428 let Some(dst_row) = band.row_slice_mut(y) else {
9429 continue;
9430 };
9431 let v: f32 = (((y as f32) + 0.5 - rect.get_y()) * inv_dst_h).clamp(0.0, 1.0);
9432 let py: f32 = (y as f32) + 0.5 - cy;
9433 let sy: usize = ((v * (src_h as f32)).floor() as usize).min(max_sy);
9434 let row: usize = sy * src_w_usize;
9435 if has_radius && can_1to1_interior && y >= iy0 && y < iy1 && ix0 < ix1 {
9436 let src_off: usize = (row + (((ix0 as i32) - rx0_i) as usize)) * 4;
9437 let span_bytes: usize = ((ix1 - ix0) as usize) * 4;
9438 let dst_off: usize = (ix0 as usize) * 4;
9439 if src_off + span_bytes <= src_bytes.len() && dst_off + span_bytes <= dst_row.len()
9440 {
9441 blit_1to1_rgba_span(
9442 &src_bytes[src_off..src_off + span_bytes],
9443 &mut dst_row[dst_off..dst_off + span_bytes],
9444 );
9445 }
9446 shaded += (ix1 - ix0) as usize;
9447 for x in x0..ix0 {
9448 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
9449 let cov: f32 = sdf_coverage(dist, aa);
9450 if cov > 0.0 {
9451 let u: f32 =
9452 (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9453 let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
9454 let idx: usize = (row + sx) * 4;
9455 if idx + 4 <= src_bytes.len() {
9456 let off: usize = (x as usize) * 4;
9457 blend_rgba_pixel_with_cov(
9458 &mut dst_row[off..off + 4],
9459 [
9460 src_bytes[idx],
9461 src_bytes[idx + 1],
9462 src_bytes[idx + 2],
9463 src_bytes[idx + 3],
9464 ],
9465 cov,
9466 );
9467 shaded += 1;
9468 }
9469 }
9470 }
9471 for x in ix1..x1 {
9472 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
9473 let cov: f32 = sdf_coverage(dist, aa);
9474 if cov > 0.0 {
9475 let u: f32 =
9476 (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9477 let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
9478 let idx: usize = (row + sx) * 4;
9479 if idx + 4 <= src_bytes.len() {
9480 let off: usize = (x as usize) * 4;
9481 blend_rgba_pixel_with_cov(
9482 &mut dst_row[off..off + 4],
9483 [
9484 src_bytes[idx],
9485 src_bytes[idx + 1],
9486 src_bytes[idx + 2],
9487 src_bytes[idx + 3],
9488 ],
9489 cov,
9490 );
9491 shaded += 1;
9492 }
9493 }
9494 }
9495 continue;
9496 }
9497 for x in x0..x1 {
9498 let cov: f32 = if has_radius {
9499 let px: f32 = (x as f32) + 0.5 - cx;
9500 let cr: f32 = quadrant_corner_radius(radius, px, py);
9501 sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
9502 } else {
9503 1.0
9504 };
9505 if cov <= 0.0 {
9506 continue;
9507 }
9508 let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
9509 let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
9510 let idx: usize = (row + sx) * 4;
9511 if idx + 4 <= src_bytes.len() {
9512 let off: usize = (x as usize) * 4;
9513 blend_rgba_pixel_with_cov(
9514 &mut dst_row[off..off + 4],
9515 [
9516 src_bytes[idx],
9517 src_bytes[idx + 1],
9518 src_bytes[idx + 2],
9519 src_bytes[idx + 3],
9520 ],
9521 cov,
9522 );
9523 shaded += 1;
9524 }
9525 }
9526 }
9527 shaded
9528 }
9529
9530 fn raster_line(
9546 band: &mut PixelBand<'_>,
9547 from: Point,
9548 to: Point,
9549 color: Color,
9550 width: f32,
9551 clip: Rect,
9552 aa: AntialiasingMode,
9553 ) -> usize {
9554 if color.get_a() == 0 {
9555 return 0;
9556 }
9557 let half_w: f32 = width * 0.5;
9558 let min_x: f32 = from.get_x().min(to.get_x()) - half_w - 1.0;
9559 let min_y: f32 = from.get_y().min(to.get_y()) - half_w - 1.0;
9560 let max_x: f32 = from.get_x().max(to.get_x()) + half_w + 1.0;
9561 let max_y: f32 = from.get_y().max(to.get_y()) + half_w + 1.0;
9562 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
9563 else {
9564 return 0;
9565 };
9566 let fb_w: u32 = band.width();
9567 let band_y0: u32 = band.y_offset();
9568 let band_y1: u32 = band.y_end();
9569 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9570 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9571 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9572 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9573 if x0 >= x1 || y0 >= y1 {
9574 return 0;
9575 }
9576 let fx0: f32 = from.get_x();
9577 let fy0: f32 = from.get_y();
9578 let dx: f32 = to.get_x() - fx0;
9579 let dy: f32 = to.get_y() - fy0;
9580 let len_sq: f32 = (dx * dx + dy * dy).max(1e-6);
9581 let inv_len_sq: f32 = 1.0 / len_sq;
9582 let outer_r: f32 = half_w + 0.9;
9583 let outer_r_sq: f32 = outer_r * outer_r;
9584 let inner_r: f32 = (half_w - 0.9).max(0.0);
9585 let inner_r_sq: f32 = inner_r * inner_r;
9586 let has_inner: bool = half_w > 0.9;
9587 let use_oriented_x: bool = dy.abs() > 1e-4;
9588 let slope_x_per_y: f32 = if use_oriented_x { dx / dy } else { 0.0 };
9589 let x_pad: f32 = if use_oriented_x {
9590 outer_r * (len_sq.sqrt() / dy.abs()) + 0.5
9591 } else {
9592 0.0
9593 };
9594 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
9595 let lin_rgb: [f32; 3] = [
9596 SRGB_TO_LIN_LUT[color.get_r() as usize],
9597 SRGB_TO_LIN_LUT[color.get_g() as usize],
9598 SRGB_TO_LIN_LUT[color.get_b() as usize],
9599 ];
9600 let mut shaded: usize = 0;
9601 for y in y0..y1 {
9602 let py: f32 = (y as f32) + 0.5;
9603 let py_off: f32 = py - fy0;
9604 let (row_x0, row_x1): (u32, u32) = if use_oriented_x {
9605 let x_center: f32 = fx0 + py_off * slope_x_per_y;
9606 let rx0: u32 = ((x_center - x_pad).floor().max(0.0) as u32).clamp(x0, x1);
9607 let rx1: u32 = ((x_center + x_pad).ceil().max(0.0) as u32).clamp(rx0, x1);
9608 (rx0, rx1)
9609 } else {
9610 (x0, x1)
9611 };
9612 if row_x0 >= row_x1 {
9613 continue;
9614 }
9615 let Some(row) = band.row_slice_mut(y) else {
9616 continue;
9617 };
9618 let py_dy: f32 = py_off * dy;
9619 for x in row_x0..row_x1 {
9620 let px: f32 = (x as f32) + 0.5;
9621 let t: f32 = (((px - fx0) * dx + py_dy) * inv_len_sq).clamp(0.0, 1.0);
9622 let dpx: f32 = px - (fx0 + t * dx);
9623 let dpy: f32 = py - (fy0 + t * dy);
9624 let dist_sq: f32 = dpx * dpx + dpy * dpy;
9625 if dist_sq >= outer_r_sq {
9626 continue;
9627 }
9628 let cov: f32 = if has_inner && dist_sq <= inner_r_sq {
9629 1.0
9630 } else {
9631 sdf_coverage(dist_sq.sqrt() - half_w, aa)
9632 };
9633 if cov > 0.0 {
9634 blend_row_pixel_f32_precomputed(row, x, color, lin_rgb, base_alpha * cov);
9635 shaded += 1;
9636 }
9637 }
9638 }
9639 shaded
9640 }
9641
9642 fn raster_circle(
9657 band: &mut PixelBand<'_>,
9658 center: Point,
9659 radius: f32,
9660 color: Color,
9661 clip: Rect,
9662 aa: AntialiasingMode,
9663 ) -> usize {
9664 if radius <= 0.0 || color.get_a() == 0 {
9665 return 0;
9666 }
9667 let bounds: Rect = Rect::new(
9668 center.get_x() - radius - 1.0,
9669 center.get_y() - radius - 1.0,
9670 (radius + 1.0) * 2.0,
9671 (radius + 1.0) * 2.0,
9672 );
9673 let Some(vis) = bounds.intersect(clip) else {
9674 return 0;
9675 };
9676 let fb_w: u32 = band.width();
9677 let band_y0: u32 = band.y_offset();
9678 let band_y1: u32 = band.y_end();
9679 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9680 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9681 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9682 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9683 if x0 >= x1 || y0 >= y1 {
9684 return 0;
9685 }
9686 let outer_r: f32 = if aa == AntialiasingMode::None {
9687 radius + 0.5
9688 } else {
9689 radius + 0.65
9690 };
9691 let inner_r: f32 = if aa == AntialiasingMode::None {
9692 (radius - 0.5).max(0.0)
9693 } else {
9694 (radius - 0.65).max(0.0)
9695 };
9696 let outer_r2: f32 = outer_r * outer_r;
9697 let inner_r2: f32 = inner_r * inner_r;
9698 let r2: f32 = radius * radius;
9699 let cx: f32 = center.get_x();
9700 let cy: f32 = center.get_y();
9701 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
9702 let lin_rgb: [f32; 3] = [
9703 SRGB_TO_LIN_LUT[color.get_r() as usize],
9704 SRGB_TO_LIN_LUT[color.get_g() as usize],
9705 SRGB_TO_LIN_LUT[color.get_b() as usize],
9706 ];
9707 let interior_luts: Option<[[u8; 256]; 4]> = if color.get_a() < 255 && radius >= 12.0 {
9708 Some(build_linear_blend_luts(color))
9709 } else {
9710 None
9711 };
9712 let mut shaded: usize = 0;
9713 for y in y0..y1 {
9714 let dy: f32 = (y as f32) + 0.5 - cy;
9715 let dy2: f32 = dy * dy;
9716 if dy2 >= outer_r2 {
9717 continue;
9718 }
9719 let out_dx: f32 = (outer_r2 - dy2).sqrt();
9720 let row_x0: u32 = ((cx - out_dx).floor().max(0.0) as u32).clamp(x0, x1);
9721 let row_x1: u32 = ((cx + out_dx).ceil().max(0.0) as u32).clamp(row_x0, x1);
9722 if row_x0 >= row_x1 {
9723 continue;
9724 }
9725 if dy2 < inner_r2 && inner_r > 0.65 {
9726 let in_dx: f32 = (inner_r2 - dy2).sqrt();
9727 let in_x0: u32 = ((cx - in_dx).ceil().max(0.0) as u32).clamp(row_x0, row_x1);
9728 let in_x1: u32 = ((cx + in_dx).floor().max(0.0) as u32).clamp(in_x0, row_x1);
9729 if in_x0 < in_x1 {
9730 if let Some(ref luts) = interior_luts {
9731 band.fill_span_linear_luts(in_x0, in_x1, y, luts);
9732 } else {
9733 band.fill_span_linear(in_x0, in_x1, y, color);
9734 }
9735 shaded += (in_x1 - in_x0) as usize;
9736 }
9737 if (row_x0 < in_x0 || in_x1 < row_x1)
9738 && let Some(row) = band.row_slice_mut(y)
9739 {
9740 for x in row_x0..in_x0 {
9741 let dx: f32 = (x as f32) + 0.5 - cx;
9742 let cov: f32 = if aa == AntialiasingMode::None {
9743 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9744 } else {
9745 circle_supersampled_coverage(dx, dy, radius)
9746 };
9747 if cov > 0.0 {
9748 blend_row_pixel_f32_precomputed(
9749 row,
9750 x,
9751 color,
9752 lin_rgb,
9753 base_alpha * cov,
9754 );
9755 shaded += 1;
9756 }
9757 }
9758 for x in in_x1..row_x1 {
9759 let dx: f32 = (x as f32) + 0.5 - cx;
9760 let cov: f32 = if aa == AntialiasingMode::None {
9761 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9762 } else {
9763 circle_supersampled_coverage(dx, dy, radius)
9764 };
9765 if cov > 0.0 {
9766 blend_row_pixel_f32_precomputed(
9767 row,
9768 x,
9769 color,
9770 lin_rgb,
9771 base_alpha * cov,
9772 );
9773 shaded += 1;
9774 }
9775 }
9776 }
9777 } else if let Some(row) = band.row_slice_mut(y) {
9778 for x in row_x0..row_x1 {
9779 let dx: f32 = (x as f32) + 0.5 - cx;
9780 let cov: f32 = if aa == AntialiasingMode::None {
9781 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
9782 } else {
9783 circle_supersampled_coverage(dx, dy, radius)
9784 };
9785 if cov > 0.0 {
9786 blend_row_pixel_f32_precomputed(row, x, color, lin_rgb, base_alpha * cov);
9787 shaded += 1;
9788 }
9789 }
9790 }
9791 }
9792 shaded
9793 }
9794
9795 #[inline(always)]
9808 #[must_use]
9809 fn solve_triangle_scanline_interval(
9810 d_base: [f32; 3],
9811 a_step: [f32; 3],
9812 thresh: f32,
9813 max_s: f32,
9814 ) -> (f32, f32) {
9815 let mut s_min: f32 = 0.0;
9816 let mut s_max: f32 = max_s;
9817 for idx in 0..3usize {
9818 let a: f32 = a_step[idx];
9819 let d: f32 = d_base[idx];
9820 if a > 1e-6 {
9821 let bound: f32 = (thresh - d) / a;
9822 if bound > s_min {
9823 s_min = bound;
9824 }
9825 } else if a < -1e-6 {
9826 let bound: f32 = (thresh - d) / a;
9827 if bound < s_max {
9828 s_max = bound;
9829 }
9830 } else if d < thresh {
9831 return (1.0, 0.0);
9832 }
9833 }
9834 (s_min, s_max)
9835 }
9836
9837 fn raster_triangle(
9853 band: &mut PixelBand<'_>,
9854 p0: Point,
9855 p1: Point,
9856 p2: Point,
9857 color: Color,
9858 clip: Rect,
9859 aa: AntialiasingMode,
9860 ) -> usize {
9861 if color.get_a() == 0 {
9862 return 0;
9863 }
9864 let dx0: f32 = p1.get_x() - p0.get_x();
9865 let dy0: f32 = p1.get_y() - p0.get_y();
9866 let dx1: f32 = p2.get_x() - p1.get_x();
9867 let dy1: f32 = p2.get_y() - p1.get_y();
9868 let dx2: f32 = p0.get_x() - p2.get_x();
9869 let dy2: f32 = p0.get_y() - p2.get_y();
9870 let area: f32 = dx0 * (p2.get_y() - p0.get_y()) - dy0 * (p2.get_x() - p0.get_x());
9871 if area.abs() < 1e-5 {
9872 return 0;
9873 }
9874 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) - 1.0;
9875 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) - 1.0;
9876 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) + 1.0;
9877 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) + 1.0;
9878 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
9879 else {
9880 return 0;
9881 };
9882 let fb_w: u32 = band.width();
9883 let band_y0: u32 = band.y_offset();
9884 let band_y1: u32 = band.y_end();
9885 let clip_x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
9886 let clip_x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
9887 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
9888 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
9889 if clip_x0 >= clip_x1 || y0 >= y1 {
9890 return 0;
9891 }
9892 if aa == AntialiasingMode::None {
9893 let edges: [(Point, Point); 3] = [(p0, p1), (p1, p2), (p2, p0)];
9894 let mut shaded: usize = 0;
9895 for y in y0..y1 {
9896 let py: f32 = (y as f32) + 0.5;
9897 let mut min_ix: f32 = f32::INFINITY;
9898 let mut max_ix: f32 = f32::NEG_INFINITY;
9899 for (a, b) in edges.iter() {
9900 let ay: f32 = a.get_y();
9901 let by: f32 = b.get_y();
9902 if (ay <= py && by > py) || (by <= py && ay > py) {
9903 let t: f32 = (py - ay) / (by - ay);
9904 let ix: f32 = a.get_x() + t * (b.get_x() - a.get_x());
9905 min_ix = min_ix.min(ix);
9906 max_ix = max_ix.max(ix);
9907 }
9908 }
9909 if min_ix <= max_ix {
9910 let sx0: u32 = (min_ix.floor().max(0.0) as u32).clamp(clip_x0, clip_x1);
9911 let sx1: u32 = (max_ix.ceil().max(0.0) as u32).clamp(clip_x0, clip_x1);
9912 if sx0 < sx1 {
9913 band.fill_span_linear(sx0, sx1, y, color);
9914 shaded += (sx1 - sx0) as usize;
9915 }
9916 }
9917 }
9918 return shaded;
9919 }
9920 let sign: f32 = if area > 0.0 { 1.0 } else { -1.0 };
9921 let inv_l0: f32 = sign / dx0.hypot(dy0).max(1e-5);
9922 let inv_l1: f32 = sign / dx1.hypot(dy1).max(1e-5);
9923 let inv_l2: f32 = sign / dx2.hypot(dy2).max(1e-5);
9924 let a_step: [f32; 3] = [-dy0 * inv_l0, -dy1 * inv_l1, -dy2 * inv_l2];
9925 let b_step: [f32; 3] = [dx0 * inv_l0, dx1 * inv_l1, dx2 * inv_l2];
9926 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
9927 let lin_rgb: [f32; 3] = [
9928 SRGB_TO_LIN_LUT[color.get_r() as usize],
9929 SRGB_TO_LIN_LUT[color.get_g() as usize],
9930 SRGB_TO_LIN_LUT[color.get_b() as usize],
9931 ];
9932 let interior_luts: Option<[[u8; 256]; 4]> =
9933 if color.get_a() < 255 && (area.abs() * 0.5) >= 256.0 {
9934 Some(build_linear_blend_luts(color))
9935 } else {
9936 None
9937 };
9938 let px_base: f32 = (clip_x0 as f32) + 0.5;
9939 let max_s: f32 = (clip_x1 - clip_x0) as f32;
9940 let py_start: f32 = (y0 as f32) + 0.5;
9941 let mut d_row: [f32; 3] = [
9942 (dx0 * (py_start - p0.get_y()) - dy0 * (px_base - p0.get_x())) * inv_l0,
9943 (dx1 * (py_start - p1.get_y()) - dy1 * (px_base - p1.get_x())) * inv_l1,
9944 (dx2 * (py_start - p2.get_y()) - dy2 * (px_base - p2.get_x())) * inv_l2,
9945 ];
9946 let edge_deltas: [(f32, f32); 3] = [(dx0, dy0), (dx1, dy1), (dx2, dy2)];
9947 let verts: (Point, Point, Point) = (p0, p1, p2);
9948 let mut shaded: usize = 0;
9949 for y in y0..y1 {
9950 let py: f32 = (y as f32) + 0.5;
9951 let (out_min, out_max): (f32, f32) =
9952 Self::solve_triangle_scanline_interval(d_row, a_step, -0.86, max_s);
9953 if out_min <= out_max {
9954 let k_out0: u32 = out_min.floor().max(0.0) as u32;
9955 let k_out1: u32 = (out_max.ceil().max(0.0) as u32).saturating_add(1);
9956 let row_x0: u32 = clip_x0.saturating_add(k_out0).clamp(clip_x0, clip_x1);
9957 let row_x1: u32 = clip_x0.saturating_add(k_out1).clamp(row_x0, clip_x1);
9958 if row_x0 < row_x1 {
9959 let (in_min, in_max): (f32, f32) =
9960 Self::solve_triangle_scanline_interval(d_row, a_step, 0.86, max_s);
9961 let (in_x0, in_x1): (u32, u32) = if in_min <= in_max && in_max >= 0.0 {
9962 let k_in0: u32 = in_min.ceil().max(0.0) as u32;
9963 let k_in1: u32 = (in_max.floor().max(0.0) as u32).saturating_add(1);
9964 let ix0: u32 = clip_x0.saturating_add(k_in0).clamp(row_x0, row_x1);
9965 let ix1: u32 = clip_x0.saturating_add(k_in1).clamp(ix0, row_x1);
9966 (ix0, ix1)
9967 } else {
9968 (row_x1, row_x1)
9969 };
9970 if in_x0 < in_x1 {
9971 if let Some(ref luts) = interior_luts {
9972 band.fill_span_linear_luts(in_x0, in_x1, y, luts);
9973 } else {
9974 band.fill_span_linear(in_x0, in_x1, y, color);
9975 }
9976 shaded += (in_x1 - in_x0) as usize;
9977 }
9978 if (row_x0 < in_x0 || in_x1 < row_x1)
9979 && let Some(row) = band.row_slice_mut(y)
9980 {
9981 let mut rim_spans: [(u32, u32); 2] = [(row_x0, in_x0), (in_x1, row_x1)];
9982 if in_x0 >= in_x1 {
9983 rim_spans = [(row_x0, row_x1), (row_x1, row_x1)];
9984 }
9985 for (sx0, sx1) in rim_spans.into_iter() {
9986 if sx0 >= sx1 {
9987 continue;
9988 }
9989 let s0: f32 = (sx0 - clip_x0) as f32;
9990 let mut d0: f32 = d_row[0] + a_step[0] * s0;
9991 let mut d1: f32 = d_row[1] + a_step[1] * s0;
9992 let mut d2: f32 = d_row[2] + a_step[2] * s0;
9993 for x in sx0..sx1 {
9994 if d0 >= -0.85 && d1 >= -0.85 && d2 >= -0.85 {
9995 if d0 > 0.85 && d1 > 0.85 && d2 > 0.85 {
9996 blend_row_pixel_linear_precomputed(row, x, color, lin_rgb);
9997 shaded += 1;
9998 } else {
9999 let px: f32 = (x as f32) + 0.5;
10000 let cov: f32 = triangle_supersampled_coverage_precomputed(
10001 (px, py),
10002 verts,
10003 edge_deltas,
10004 sign,
10005 );
10006 if cov >= 0.999 {
10007 blend_row_pixel_linear_precomputed(
10008 row, x, color, lin_rgb,
10009 );
10010 shaded += 1;
10011 } else if cov > 0.0 {
10012 blend_row_pixel_f32_precomputed(
10013 row,
10014 x,
10015 color,
10016 lin_rgb,
10017 base_alpha * cov,
10018 );
10019 shaded += 1;
10020 }
10021 }
10022 }
10023 d0 += a_step[0];
10024 d1 += a_step[1];
10025 d2 += a_step[2];
10026 }
10027 }
10028 }
10029 }
10030 }
10031 d_row[0] += b_step[0];
10032 d_row[1] += b_step[1];
10033 d_row[2] += b_step[2];
10034 }
10035 shaded
10036 }
10037
10038 #[inline(always)]
10053 fn blit_sprite_span_tinted(
10054 y_params: (usize, usize, u32, u32),
10055 dst_x0: usize,
10056 x_lut: &[(usize, usize, u32)],
10057 src_bytes: &[u8],
10058 dst_row: &mut [u8],
10059 tint: Color,
10060 ) -> usize {
10061 let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
10062 let span_bytes_start: usize = dst_x0 * 4;
10063 let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
10064 if span_bytes_end > dst_row.len() {
10065 return 0;
10066 }
10067 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
10068 .as_chunks_mut::<4>()
10069 .0;
10070 let src_len: usize = src_bytes.len();
10071 let tr: u32 = tint.get_r() as u32;
10072 let tg: u32 = tint.get_g() as u32;
10073 let tb: u32 = tint.get_b() as u32;
10074 let ta: u32 = tint.get_a() as u32;
10075 let mut shaded: usize = 0;
10076 if wy == 0 {
10077 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
10078 let i0: usize = (row0 + sx0) * 4;
10079 let i1: usize = (row0 + sx1) * 4;
10080 if i1 + 4 > src_len {
10081 continue;
10082 }
10083 let iwx: u32 = 256 - wx;
10084 let a0: u32 = src_bytes[i0 + 3] as u32;
10085 let a1: u32 = src_bytes[i1 + 3] as u32;
10086 let (sr_raw, sg_raw, sb_raw, sa_raw): (u32, u32, u32, u32) = if (a0 & a1) == 255 {
10087 (
10088 ((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128) >> 8,
10089 ((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128)
10090 >> 8,
10091 ((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128)
10092 >> 8,
10093 255,
10094 )
10095 } else {
10096 let aw0: u32 = a0 * iwx;
10097 let aw1: u32 = a1 * wx;
10098 let a_sum: u32 = aw0 + aw1;
10099 let a_out: u32 = (a_sum + 128) >> 8;
10100 if a_out == 0 || a_sum == 0 {
10101 continue;
10102 }
10103 let half_a: u32 = a_sum >> 1;
10104 (
10105 (((src_bytes[i0] as u32) * aw0 + (src_bytes[i1] as u32) * aw1 + half_a)
10106 / a_sum)
10107 .min(255),
10108 (((src_bytes[i0 + 1] as u32) * aw0
10109 + (src_bytes[i1 + 1] as u32) * aw1
10110 + half_a)
10111 / a_sum)
10112 .min(255),
10113 (((src_bytes[i0 + 2] as u32) * aw0
10114 + (src_bytes[i1 + 2] as u32) * aw1
10115 + half_a)
10116 / a_sum)
10117 .min(255),
10118 a_out,
10119 )
10120 };
10121 let rr: u32 = sr_raw * tr + 128;
10122 let gg: u32 = sg_raw * tg + 128;
10123 let bb: u32 = sb_raw * tb + 128;
10124 let aa_v: u32 = sa_raw * ta + 128;
10125 let r: u32 = (rr + (rr >> 8)) >> 8;
10126 let g: u32 = (gg + (gg >> 8)) >> 8;
10127 let b: u32 = (bb + (bb >> 8)) >> 8;
10128 let a: u32 = (aa_v + (aa_v >> 8)) >> 8;
10129 if a == 255 {
10130 dp[0] = r as u8;
10131 dp[1] = g as u8;
10132 dp[2] = b as u8;
10133 dp[3] = 255;
10134 } else if a > 0 {
10135 let inv_a: u32 = 255 - a;
10136 let vr: u32 = r * a + (dp[0] as u32) * inv_a + 128;
10137 let vg: u32 = g * a + (dp[1] as u32) * inv_a + 128;
10138 let vb: u32 = b * a + (dp[2] as u32) * inv_a + 128;
10139 let va: u32 = (dp[3] as u32) * inv_a + 128;
10140 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
10141 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
10142 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
10143 dp[3] = (a + ((va + (va >> 8)) >> 8)).min(255) as u8;
10144 }
10145 shaded += 1;
10146 }
10147 return shaded;
10148 }
10149 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
10150 let i00: usize = (row0 + sx0) * 4;
10151 let i10: usize = (row0 + sx1) * 4;
10152 let i01: usize = (row1 + sx0) * 4;
10153 let i11: usize = (row1 + sx1) * 4;
10154 if i11 + 4 > src_len {
10155 continue;
10156 }
10157 let iwx: u32 = 256 - wx;
10158 let w00: u32 = iwx * iwy;
10159 let w10: u32 = wx * iwy;
10160 let w01: u32 = iwx * wy;
10161 let w11: u32 = wx * wy;
10162 let a00: u32 = src_bytes[i00 + 3] as u32;
10163 let a10: u32 = src_bytes[i10 + 3] as u32;
10164 let a01: u32 = src_bytes[i01 + 3] as u32;
10165 let a11: u32 = src_bytes[i11 + 3] as u32;
10166 let (sr_raw, sg_raw, sb_raw, sa_raw): (u32, u32, u32, u32) =
10167 if (a00 & a10 & a01 & a11) == 255 {
10168 (
10169 ((src_bytes[i00] as u32) * w00
10170 + (src_bytes[i10] as u32) * w10
10171 + (src_bytes[i01] as u32) * w01
10172 + (src_bytes[i11] as u32) * w11
10173 + 32768)
10174 >> 16,
10175 ((src_bytes[i00 + 1] as u32) * w00
10176 + (src_bytes[i10 + 1] as u32) * w10
10177 + (src_bytes[i01 + 1] as u32) * w01
10178 + (src_bytes[i11 + 1] as u32) * w11
10179 + 32768)
10180 >> 16,
10181 ((src_bytes[i00 + 2] as u32) * w00
10182 + (src_bytes[i10 + 2] as u32) * w10
10183 + (src_bytes[i01 + 2] as u32) * w01
10184 + (src_bytes[i11 + 2] as u32) * w11
10185 + 32768)
10186 >> 16,
10187 255,
10188 )
10189 } else {
10190 let aw00: u64 = (a00 as u64) * (w00 as u64);
10191 let aw10: u64 = (a10 as u64) * (w10 as u64);
10192 let aw01: u64 = (a01 as u64) * (w01 as u64);
10193 let aw11: u64 = (a11 as u64) * (w11 as u64);
10194 let a_sum: u64 = aw00 + aw10 + aw01 + aw11;
10195 let a_out: u32 = ((a_sum + 32768) >> 16) as u32;
10196 if a_out == 0 || a_sum == 0 {
10197 continue;
10198 }
10199 let half_a: u64 = a_sum >> 1;
10200 (
10201 ((((src_bytes[i00] as u64) * aw00
10202 + (src_bytes[i10] as u64) * aw10
10203 + (src_bytes[i01] as u64) * aw01
10204 + (src_bytes[i11] as u64) * aw11
10205 + half_a)
10206 / a_sum)
10207 .min(255)) as u32,
10208 ((((src_bytes[i00 + 1] as u64) * aw00
10209 + (src_bytes[i10 + 1] as u64) * aw10
10210 + (src_bytes[i01 + 1] as u64) * aw01
10211 + (src_bytes[i11 + 1] as u64) * aw11
10212 + half_a)
10213 / a_sum)
10214 .min(255)) as u32,
10215 ((((src_bytes[i00 + 2] as u64) * aw00
10216 + (src_bytes[i10 + 2] as u64) * aw10
10217 + (src_bytes[i01 + 2] as u64) * aw01
10218 + (src_bytes[i11 + 2] as u64) * aw11
10219 + half_a)
10220 / a_sum)
10221 .min(255)) as u32,
10222 a_out,
10223 )
10224 };
10225 let rr: u32 = sr_raw * tr + 128;
10226 let gg: u32 = sg_raw * tg + 128;
10227 let bb: u32 = sb_raw * tb + 128;
10228 let aa_v: u32 = sa_raw * ta + 128;
10229 let r: u32 = (rr + (rr >> 8)) >> 8;
10230 let g: u32 = (gg + (gg >> 8)) >> 8;
10231 let b: u32 = (bb + (bb >> 8)) >> 8;
10232 let a: u32 = (aa_v + (aa_v >> 8)) >> 8;
10233 if a == 255 {
10234 dp[0] = r as u8;
10235 dp[1] = g as u8;
10236 dp[2] = b as u8;
10237 dp[3] = 255;
10238 } else if a > 0 {
10239 let inv_a: u32 = 255 - a;
10240 let vr: u32 = r * a + (dp[0] as u32) * inv_a + 128;
10241 let vg: u32 = g * a + (dp[1] as u32) * inv_a + 128;
10242 let vb: u32 = b * a + (dp[2] as u32) * inv_a + 128;
10243 let va: u32 = (dp[3] as u32) * inv_a + 128;
10244 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
10245 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
10246 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
10247 dp[3] = (a + ((va + (va >> 8)) >> 8)).min(255) as u8;
10248 }
10249 shaded += 1;
10250 }
10251 shaded
10252 }
10253
10254 fn raster_sprite_region_with_lut(
10270 band: &mut PixelBand<'_>,
10271 rects: (Rect, Rect),
10272 src_info: (u32, u32, &[u8]),
10273 bounds: (u32, u32, u32, u32),
10274 tint: Color,
10275 use_bilinear: bool,
10276 x_lut: &mut Vec<(usize, usize, u32)>,
10277 ) -> usize {
10278 let (rect, src_rect): (Rect, Rect) = rects;
10279 let (buf_w, buf_h, src_bytes): (u32, u32, &[u8]) = src_info;
10280 let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
10281 let inv_w: f32 = 1.0 / rect.get_width().max(1.0);
10282 let inv_h: f32 = 1.0 / rect.get_height().max(1.0);
10283 let untinted: bool = tint == COLOR_WHITE;
10284 let max_sx: u32 = ((src_rect.right().ceil() as u32).saturating_sub(1)).min(buf_w - 1);
10285 let max_sy: u32 = ((src_rect.bottom().ceil() as u32).saturating_sub(1)).min(buf_h - 1);
10286 let min_sx: u32 = (src_rect.get_x().floor().max(0.0) as u32).min(max_sx);
10287 let min_sy: u32 = (src_rect.get_y().floor().max(0.0) as u32).min(max_sy);
10288 let buf_w_usize: usize = buf_w as usize;
10289 let rect_x: f32 = rect.get_x();
10290 let rect_y: f32 = rect.get_y();
10291 let src_x: f32 = src_rect.get_x();
10292 let src_y: f32 = src_rect.get_y();
10293 let src_w: f32 = src_rect.get_width();
10294 let src_h: f32 = src_rect.get_height();
10295 let min_sx_f: f32 = min_sx as f32;
10296 let max_sx_f: f32 = max_sx as f32;
10297 let min_sy_f: f32 = min_sy as f32;
10298 let max_sy_f: f32 = max_sy as f32;
10299 x_lut.clear();
10300 for x in x0..x1 {
10301 let u: f32 = (((x as f32) + 0.5 - rect_x) * inv_w).clamp(0.0, 1.0);
10302 let fx: f32 = (src_x + u * src_w - 0.5).clamp(min_sx_f, max_sx_f);
10303 let sx0: u32 = (fx.floor() as u32).clamp(min_sx, max_sx);
10304 let sx1: u32 = if use_bilinear {
10305 (sx0 + 1).min(max_sx)
10306 } else {
10307 sx0
10308 };
10309 let wx: u32 = if use_bilinear {
10310 ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
10311 } else {
10312 0
10313 };
10314 x_lut.push((sx0 as usize, sx1 as usize, wx));
10315 }
10316 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
10317 let x0_u: usize = x0 as usize;
10318 let mut shaded: usize = 0;
10319 for y in y0..y1 {
10320 let Some(dst_row) = band.row_slice_mut(y) else {
10321 continue;
10322 };
10323 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_h).clamp(0.0, 1.0);
10324 let fy: f32 = (src_y + v * src_h - 0.5).clamp(min_sy_f, max_sy_f);
10325 let sy0: u32 = (fy.floor() as u32).clamp(min_sy, max_sy);
10326 let sy1: u32 = if use_bilinear {
10327 (sy0 + 1).min(max_sy)
10328 } else {
10329 sy0
10330 };
10331 let wy: u32 = if use_bilinear {
10332 ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
10333 } else {
10334 0
10335 };
10336 let y_params: (usize, usize, u32, u32) = (
10337 (sy0 as usize) * buf_w_usize,
10338 (sy1 as usize) * buf_w_usize,
10339 wy,
10340 256 - wy,
10341 );
10342 if untinted {
10343 shaded += Self::blit_bilinear_span_precomputed(
10344 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
10345 );
10346 } else {
10347 shaded += Self::blit_sprite_span_tinted(
10348 y_params, x0_u, x_lut_ref, src_bytes, dst_row, tint,
10349 );
10350 }
10351 }
10352 shaded
10353 }
10354
10355 fn raster_sprite_region(
10371 band: &mut PixelBand<'_>,
10372 rect: Rect,
10373 buffer: &ImageBuffer,
10374 src_rect: Rect,
10375 tint: Color,
10376 clip: Rect,
10377 aa: AntialiasingMode,
10378 ) -> usize {
10379 if buffer.get_width() == 0
10380 || buffer.get_height() == 0
10381 || tint.get_a() == 0
10382 || src_rect.get_width() <= 0.0
10383 || src_rect.get_height() <= 0.0
10384 {
10385 return 0;
10386 }
10387 let Some(vis) = rect.intersect(clip) else {
10388 return 0;
10389 };
10390 let fb_w: u32 = band.width();
10391 let band_y0: u32 = band.y_offset();
10392 let band_y1: u32 = band.y_end();
10393 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
10394 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
10395 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
10396 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
10397 if x0 >= x1 || y0 >= y1 {
10398 return 0;
10399 }
10400 let buf_w: u32 = buffer.get_width();
10401 let buf_h: u32 = buffer.get_height();
10402 let src_bytes: &[u8] = buffer.get_pixels();
10403 let use_bilinear: bool = aa != AntialiasingMode::None
10404 && ((rect.get_width() - src_rect.get_width()).abs() > 0.5
10405 || (rect.get_height() - src_rect.get_height()).abs() > 0.5);
10406 if !use_bilinear
10407 && tint == COLOR_WHITE
10408 && (rect.get_width() - src_rect.get_width()).abs() <= 0.01
10409 && (rect.get_height() - src_rect.get_height()).abs() <= 0.01
10410 && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
10411 && (rect.get_y() - rect.get_y().round()).abs() <= 0.01
10412 && (src_rect.get_x() - src_rect.get_x().round()).abs() <= 0.01
10413 && (src_rect.get_y() - src_rect.get_y().round()).abs() <= 0.01
10414 {
10415 let rx0_i: i32 = rect.get_x().round() as i32;
10416 let ry0_i: i32 = rect.get_y().round() as i32;
10417 let sx0_i: i32 = src_rect.get_x().round() as i32;
10418 let sy0_i: i32 = src_rect.get_y().round() as i32;
10419 let span_w: usize = (x1 - x0) as usize;
10420 let src_x0_i: i32 = sx0_i + ((x0 as i32) - rx0_i);
10421 let src_y0_i: i32 = sy0_i + ((y0 as i32) - ry0_i);
10422 let src_y1_i: i32 = sy0_i + ((y1 as i32) - ry0_i);
10423 if src_x0_i >= 0
10424 && src_x0_i + (span_w as i32) <= (buf_w as i32)
10425 && src_y0_i >= 0
10426 && src_y1_i <= (buf_h as i32)
10427 {
10428 let buf_w_u: usize = buf_w as usize;
10429 let dst_b0: usize = (x0 as usize) * 4;
10430 let dst_b1: usize = (x1 as usize) * 4;
10431 let src_x0_u: usize = src_x0_i as usize;
10432 for y in y0..y1 {
10433 let Some(dst_row) = band.row_slice_mut(y) else {
10434 continue;
10435 };
10436 let sy: usize = (sy0_i + ((y as i32) - ry0_i)) as usize;
10437 let src_b0: usize = (sy * buf_w_u + src_x0_u) * 4;
10438 let src_b1: usize = src_b0 + span_w * 4;
10439 if src_b1 <= src_bytes.len() && dst_b1 <= dst_row.len() {
10440 blit_1to1_rgba_span(
10441 &src_bytes[src_b0..src_b1],
10442 &mut dst_row[dst_b0..dst_b1],
10443 );
10444 }
10445 }
10446 return span_w * ((y1 - y0) as usize);
10447 }
10448 }
10449 let mut shaded: usize = 0;
10450 let ran_tls: bool = BAND_IMAGE_X_LUT
10451 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
10452 if let Ok(mut guard) = cell.try_borrow_mut() {
10453 shaded = Self::raster_sprite_region_with_lut(
10454 band,
10455 (rect, src_rect),
10456 (buf_w, buf_h, src_bytes),
10457 (x0, y0, x1, y1),
10458 tint,
10459 use_bilinear,
10460 &mut guard,
10461 );
10462 }
10463 })
10464 .is_ok();
10465 if !ran_tls {
10466 let mut fallback_lut: Vec<(usize, usize, u32)> = Vec::with_capacity((x1 - x0) as usize);
10467 shaded = Self::raster_sprite_region_with_lut(
10468 band,
10469 (rect, src_rect),
10470 (buf_w, buf_h, src_bytes),
10471 (x0, y0, x1, y1),
10472 tint,
10473 use_bilinear,
10474 &mut fallback_lut,
10475 );
10476 }
10477 shaded
10478 }
10479}