1use super::*;
2
3#[cfg(not(target_arch = "wasm32"))]
5impl BandWorkerPool {
7 #[must_use]
13 pub(crate) fn new() -> Self {
14 let total: usize = available_parallelism()
15 .map(usize::from)
16 .unwrap_or(4)
17 .clamp(1, BAND_WORKER_MAX_THREADS);
18 let requested_workers: usize = total.saturating_sub(1);
19 let mut slots: Vec<BandWorkerSlot> = Vec::with_capacity(requested_workers);
20 for _ in 0..requested_workers {
21 slots.push(BandWorkerSlot::default());
22 }
23 let shared: Arc<BandPoolShared> = Arc::new(BandPoolShared {
24 active_job: AtomicUsize::new(0),
25 active_workers: AtomicUsize::new(0),
26 caller_parked: AtomicUsize::new(0),
27 shutdown: AtomicUsize::new(0),
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 job_ptr: usize = loop {
42 let cur_epoch: usize = slot.epoch.load(Ordering::Acquire);
43 if cur_epoch != seen_epoch {
44 let ptr: usize = shared_clone.active_job.load(Ordering::Acquire);
45 if ptr != 0 {
46 seen_epoch = cur_epoch;
47 break ptr;
48 }
49 }
50 if shared_clone.shutdown.load(Ordering::Acquire) != 0 {
51 return;
52 }
53 if spins < BAND_WORKER_SPIN_LIMIT {
54 spins += 1;
55 spin_loop();
56 continue;
57 }
58 let Ok(mut guard) = slot.lock.lock() else {
59 return;
60 };
61 slot.parked.store(1, Ordering::SeqCst);
62 let parked_ptr: Option<usize> = loop {
63 let locked_epoch: usize = slot.epoch.load(Ordering::SeqCst);
64 if locked_epoch != seen_epoch {
65 let ptr: usize = shared_clone.active_job.load(Ordering::Acquire);
66 if ptr != 0 {
67 seen_epoch = locked_epoch;
68 break Some(ptr);
69 }
70 }
71 if shared_clone.shutdown.load(Ordering::SeqCst) != 0 {
72 break None;
73 }
74 let Ok(next_guard) = slot.wake.wait(guard) else {
75 break None;
76 };
77 guard = next_guard;
78 };
79 slot.parked.store(0, Ordering::SeqCst);
80 let Some(ptr) = parked_ptr else {
81 return;
82 };
83 break ptr;
84 };
85 let job: &BandJob = unsafe { &*(job_ptr as *const BandJob) };
87 run_band_job_loop(job);
88 let expected: usize = shared_clone.active_workers.load(Ordering::Acquire);
89 let finished: usize = job.workers_done.fetch_add(1, Ordering::SeqCst) + 1;
90 if finished >= expected
91 && shared_clone.caller_parked.load(Ordering::SeqCst) != 0
92 && let Ok(_guard) = shared_clone.caller_lock.lock()
93 {
94 shared_clone.wake_caller.notify_one();
95 }
96 }
97 }) {
98 handles.push(handle);
99 } else {
100 break;
101 }
102 }
103 let worker_count: usize = handles.len();
104 Self {
105 worker_count,
106 dispatch_tasks: Mutex::new(Vec::with_capacity(
107 worker_count.saturating_add(1).saturating_mul(2),
108 )),
109 shared,
110 handles,
111 }
112 }
113
114 fn execute_serial(
129 slice_spec: (&mut [u8], u32, u32, u32, usize),
130 commands: &[DrawCommand],
131 prepped: &[PreppedCommand],
132 aux: BandAuxSlices<'_>,
133 atlas: &GlyphAtlas,
134 render_opts: (f32, AntialiasingMode, BandRestoreSpec<'_>),
135 ) -> usize {
136 let (pixels, width, y_offset, height, start_byte): (&mut [u8], u32, u32, u32, usize) =
137 slice_spec;
138 let (scale, aa, restore): (f32, AntialiasingMode, BandRestoreSpec<'_>) = render_opts;
139 if let Some(src_buf) = restore.base_pixels {
140 let end_byte: usize = start_byte + pixels.len();
141 if let Some(src_slice) = src_buf.get(start_byte..end_byte) {
142 let x0_clamped: u32 = restore.x0.min(width);
143 let x1_clamped: u32 = restore.x1.clamp(x0_clamped, width);
144 restore_band_strip(
145 pixels,
146 src_slice,
147 (
148 (width as usize) * 4,
149 height as usize,
150 (x0_clamped as usize) * 4,
151 ((x1_clamped - x0_clamped) as usize) * 4,
152 ),
153 restore.scrim_luts,
154 );
155 }
156 }
157 let mut band: PixelBand<'_> = PixelBand {
158 width,
159 y_offset,
160 height,
161 pixels,
162 };
163 SoftwareRenderer::render_band(&mut band, commands, prepped, aux, atlas, (scale, aa))
164 }
165
166 #[must_use]
172 pub(crate) fn total_threads(&self) -> usize {
173 let Self { worker_count, .. } = self;
174 worker_count.saturating_add(1)
175 }
176
177 pub(crate) fn execute(
193 &self,
194 framebuffer: &mut Framebuffer,
195 band_range: (u32, u32, usize, usize),
196 cmd_slices: (&[DrawCommand], &[PreppedCommand]),
197 aux: BandAuxSlices<'_>,
198 atlas: &GlyphAtlas,
199 render_opts: (f32, AntialiasingMode, BandRestoreSpec<'_>),
200 ) -> usize {
201 let Self {
202 worker_count,
203 dispatch_tasks,
204 shared,
205 ..
206 } = self;
207 let (y0, y1, band_count, max_workers): (u32, u32, usize, usize) = band_range;
208 let (commands, prepped): (&[DrawCommand], &[PreppedCommand]) = cmd_slices;
209 let (positioned_glyphs, caret_rects, rounded_clips, corner_masks): (
210 &[PositionedGlyph],
211 &[Rect],
212 &[RoundedClipMask],
213 &[CachedCornerMask],
214 ) = aux;
215 let (scale, aa, restore): (f32, AntialiasingMode, BandRestoreSpec<'_>) = render_opts;
216 let fb_w: u32 = framebuffer.get_width();
217 let fb_h: u32 = framebuffer.get_height();
218 let start_y: u32 = y0.min(fb_h);
219 let end_y: u32 = y1.clamp(start_y, fb_h);
220 let total_rows: u32 = end_y - start_y;
221 if total_rows == 0 || fb_w == 0 {
222 return 0;
223 }
224 let row_stride: usize = (fb_w as usize) * 4;
225 let start_byte: usize = (start_y as usize) * row_stride;
226 let end_byte: usize = (end_y as usize) * row_stride;
227 let Some(slice) = framebuffer.get_mut_pixels().get_mut(start_byte..end_byte) else {
228 return 0;
229 };
230 let strip_count: usize = band_count.max(1).min(total_rows as usize);
231 let worker_budget: usize = (*worker_count).min(max_workers);
232 if worker_budget == 0 || strip_count <= 1 {
233 return Self::execute_serial(
234 (slice, fb_w, start_y, total_rows, start_byte),
235 commands,
236 prepped,
237 aux,
238 atlas,
239 (scale, aa, restore),
240 );
241 }
242 let Ok(mut tasks) = dispatch_tasks.try_lock() else {
243 return Self::execute_serial(
244 (slice, fb_w, start_y, total_rows, start_byte),
245 commands,
246 prepped,
247 aux,
248 atlas,
249 (scale, aa, restore),
250 );
251 };
252 tasks.clear();
253 let rx0_clamped: u32 = restore.x0.min(fb_w);
254 let rx1_clamped: u32 = restore.x1.clamp(rx0_clamped, fb_w);
255 let restore_x0_bytes: usize = (rx0_clamped as usize) * 4;
256 let restore_row_bytes: usize = ((rx1_clamped - rx0_clamped) as usize) * 4;
257 let rows_per: usize = (total_rows as usize).div_ceil(strip_count);
258 let chunk_bytes: usize = rows_per * row_stride;
259 let mut cur_y: u32 = start_y;
260 let mut cur_byte_off: usize = start_byte;
261 for chunk in slice.chunks_mut(chunk_bytes) {
262 let chunk_len: usize = chunk.len();
263 let chunk_rows: u32 = (chunk_len / row_stride) as u32;
264 let base_ptr: usize = if let Some(src_buf) = restore.base_pixels {
265 let byte_end: usize = cur_byte_off + chunk_len;
266 if byte_end <= src_buf.len() {
267 unsafe { src_buf.as_ptr().add(cur_byte_off) as usize }
269 } else {
270 0
271 }
272 } else {
273 0
274 };
275 tasks.push(BandTaskSlice {
276 pixels_ptr: chunk.as_mut_ptr() as usize,
277 pixels_len: chunk_len,
278 width: fb_w,
279 y_start: cur_y,
280 height: chunk_rows,
281 base_src_ptr: base_ptr,
282 restore_x0_bytes,
283 restore_row_bytes,
284 });
285 cur_y += chunk_rows;
286 cur_byte_off += chunk_len;
287 }
288 let scrim_luts_ptr: usize = restore.scrim_luts.map_or(0, |luts: &RgbaLutQuad| {
289 (luts as *const RgbaLutQuad) as usize
290 });
291 let job: BandJob = BandJob {
292 tasks_ptr: tasks.as_ptr() as usize,
293 tasks_len: tasks.len(),
294 commands_ptr: commands.as_ptr() as usize,
295 commands_len: commands.len(),
296 prepped_ptr: prepped.as_ptr() as usize,
297 prepped_len: prepped.len(),
298 glyphs_ptr: positioned_glyphs.as_ptr() as usize,
299 glyphs_len: positioned_glyphs.len(),
300 caret_rects_ptr: caret_rects.as_ptr() as usize,
301 caret_rects_len: caret_rects.len(),
302 rounded_clips_ptr: rounded_clips.as_ptr() as usize,
303 rounded_clips_len: rounded_clips.len(),
304 corner_masks_ptr: corner_masks.as_ptr() as usize,
305 corner_masks_len: corner_masks.len(),
306 atlas_ptr: (atlas as *const GlyphAtlas) as usize,
307 scrim_luts_ptr,
308 scale,
309 aa,
310 next_idx: AtomicUsize::new(0),
311 workers_done: AtomicUsize::new(0),
312 total_shaded: AtomicUsize::new(0),
313 };
314 let dispatch_workers: usize = worker_budget.min(tasks.len().saturating_sub(1));
315 if dispatch_workers == 0 {
316 run_band_job_loop(&job);
317 return job.total_shaded.load(Ordering::Acquire);
318 }
319 shared
320 .active_workers
321 .store(dispatch_workers, Ordering::Relaxed);
322 shared
323 .active_job
324 .store((&job as *const BandJob) as usize, Ordering::Release);
325 let active_slots: &[BandWorkerSlot] = &shared.slots[..dispatch_workers];
326 for slot in active_slots.iter() {
327 let next_epoch: usize = slot.epoch.load(Ordering::Relaxed).wrapping_add(1);
328 slot.epoch.store(next_epoch, Ordering::SeqCst);
329 }
330 for slot in active_slots.iter() {
331 if slot.parked.load(Ordering::SeqCst) != 0
332 && let Ok(_guard) = slot.lock.lock()
333 {
334 slot.wake.notify_one();
335 }
336 }
337 run_band_job_loop(&job);
338 let mut caller_spins: u32 = 0;
339 while job.workers_done.load(Ordering::Acquire) < dispatch_workers {
340 if caller_spins < BAND_CALLER_SPIN_LIMIT {
341 caller_spins += 1;
342 spin_loop();
343 continue;
344 }
345 if let Ok(mut guard) = shared.caller_lock.lock() {
346 shared.caller_parked.store(1, Ordering::SeqCst);
347 while job.workers_done.load(Ordering::SeqCst) < dispatch_workers {
348 let Ok(next_guard) = shared.wake_caller.wait(guard) else {
349 break;
350 };
351 guard = next_guard;
352 }
353 shared.caller_parked.store(0, Ordering::SeqCst);
354 } else {
355 spin_loop();
356 }
357 }
358 shared.active_job.store(0, Ordering::Release);
359 job.total_shaded.load(Ordering::Acquire)
360 }
361}
362
363#[cfg(not(target_arch = "wasm32"))]
365impl Drop for BandWorkerPool {
367 fn drop(&mut self) {
373 let Self {
374 shared, handles, ..
375 } = self;
376 shared.shutdown.store(1, Ordering::SeqCst);
377 for slot in shared.slots.iter() {
378 if let Ok(_guard) = slot.lock.lock() {
379 slot.wake.notify_one();
380 }
381 }
382 for handle in handles.drain(..) {
383 let _: Result<(), Box<dyn Any + Send>> = handle.join();
384 }
385 }
386}
387
388impl TextLayoutCache {
390 #[must_use]
400 pub(crate) fn with_capacity(slot_cap: usize) -> Self {
401 let cap: usize = slot_cap.max(16).next_power_of_two();
402 let entry_cap: usize = cap / 2;
403 Self {
404 slots: vec![EMPTY_TEXT_LAYOUT_SLOT; cap],
405 entries: Vec::with_capacity(entry_cap),
406 entry_keys: Vec::with_capacity(entry_cap),
407 entry_last_used: Vec::with_capacity(entry_cap),
408 entry_bytes: Vec::with_capacity(entry_cap),
409 resident_bytes: 0,
410 budget_bytes: TEXT_LAYOUT_CACHE_BUDGET_BYTES,
411 lru_clock: 0,
412 cache_hits: 0,
413 cache_misses: 0,
414 evictions: 0,
415 }
416 }
417
418 #[inline]
428 #[must_use]
429 fn estimate_entry_bytes(layout: &TextLayoutResult) -> usize {
430 let mut bytes: usize = TEXT_LAYOUT_ENTRY_OVERHEAD_BYTES;
431 for line in layout.get_lines().iter() {
432 bytes = bytes
433 .saturating_add(TEXT_LINE_OVERHEAD_BYTES)
434 .saturating_add(line.get_text().len());
435 }
436 bytes
437 }
438
439 #[must_use]
449 pub(crate) fn stats(&self) -> (u64, u64, u64, usize) {
450 let Self {
451 cache_hits,
452 cache_misses,
453 evictions,
454 resident_bytes,
455 ..
456 } = self;
457 (*cache_hits, *cache_misses, *evictions, *resident_bytes)
458 }
459
460 #[must_use]
471 pub(crate) fn get(&self, idx: u32) -> Option<&TextLayoutResult> {
472 let Self { entries, .. } = self;
473 entries.get(idx as usize)
474 }
475
476 pub(crate) fn evict_lru_if_needed(&mut self) {
482 let Self {
483 slots,
484 entries,
485 entry_keys,
486 entry_last_used,
487 entry_bytes,
488 resident_bytes,
489 budget_bytes,
490 evictions,
491 ..
492 } = self;
493 let effective_budget: usize = if *budget_bytes == 0 {
494 TEXT_LAYOUT_CACHE_BUDGET_BYTES
495 } else {
496 *budget_bytes
497 };
498 let count: usize = entries.len();
499 if count <= TEXT_LAYOUT_CACHE_LIMIT && *resident_bytes <= effective_budget {
500 return;
501 }
502 let target_count: usize = (TEXT_LAYOUT_CACHE_LIMIT * 3) / 4;
503 let target_bytes: usize = (effective_budget * 3) / 4;
504 let mut order: Vec<usize> = (0..count).collect();
505 order.sort_unstable_by_key(|idx: &usize| entry_last_used.get(*idx).copied().unwrap_or(0));
506 let mut keep: Vec<bool> = vec![true; count];
507 let mut remaining_count: usize = count;
508 let mut remaining_bytes: usize = *resident_bytes;
509 let mut evicted_count: usize = 0;
510 for idx in order.into_iter() {
511 if remaining_count <= target_count && remaining_bytes <= target_bytes {
512 break;
513 }
514 keep[idx] = false;
515 remaining_count = remaining_count.saturating_sub(1);
516 remaining_bytes = remaining_bytes.saturating_sub(entry_bytes[idx]);
517 evicted_count += 1;
518 }
519 if evicted_count == 0 {
520 return;
521 }
522 let mut write_idx: usize = 0;
523 let mut next_resident: usize = 0;
524 for (read_idx, &kept) in keep.iter().enumerate() {
525 if kept {
526 if write_idx != read_idx {
527 entries.swap(write_idx, read_idx);
528 entry_keys.swap(write_idx, read_idx);
529 entry_last_used.swap(write_idx, read_idx);
530 entry_bytes.swap(write_idx, read_idx);
531 }
532 next_resident = next_resident.saturating_add(entry_bytes[write_idx]);
533 write_idx += 1;
534 }
535 }
536 entries.truncate(write_idx);
537 entry_keys.truncate(write_idx);
538 entry_last_used.truncate(write_idx);
539 entry_bytes.truncate(write_idx);
540 *resident_bytes = next_resident;
541 *evictions = evictions.saturating_add(evicted_count as u64);
542 if slots.len() > TEXT_LAYOUT_CACHE_SLOTS {
543 slots.resize(TEXT_LAYOUT_CACHE_SLOTS, EMPTY_TEXT_LAYOUT_SLOT);
544 }
545 slots.fill(EMPTY_TEXT_LAYOUT_SLOT);
546 if !slots.is_empty() {
547 let mask: usize = slots.len() - 1;
548 for (slot_entry_idx, &(key_hash, width_key)) in entry_keys.iter().enumerate() {
549 let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
550 while slots[idx].entry_idx != u32::MAX {
551 idx = (idx + 1) & mask;
552 }
553 slots[idx] = TextLayoutSlot {
554 key_hash,
555 width_key,
556 entry_idx: slot_entry_idx as u32,
557 };
558 }
559 }
560 }
561
562 #[inline(always)]
574 #[must_use]
575 fn slot_start(key_hash: u64, width_key: u32, mask: usize) -> usize {
576 let mixed: u64 = (key_hash ^ (width_key as u64)).wrapping_mul(FX_HASH_K64);
577 ((mixed ^ (mixed >> 32)) as usize) & mask
578 }
579
580 fn rehash(&mut self, new_cap: usize) {
587 let cap: usize = new_cap.max(TEXT_LAYOUT_CACHE_SLOTS).next_power_of_two();
588 let mask: usize = cap - 1;
589 let mut next_slots: Vec<TextLayoutSlot> = vec![EMPTY_TEXT_LAYOUT_SLOT; cap];
590 let Self { slots, .. } = self;
591 for old in slots.iter().copied() {
592 if old.entry_idx == u32::MAX {
593 continue;
594 }
595 let mut idx: usize = Self::slot_start(old.key_hash, old.width_key, mask);
596 while next_slots[idx].entry_idx != u32::MAX {
597 idx = (idx + 1) & mask;
598 }
599 next_slots[idx] = old;
600 }
601 *slots = next_slots;
602 }
603
604 pub(crate) fn get_or_insert_with<F>(&mut self, key_hash: u64, width_key: u32, compute: F) -> u32
617 where
618 F: FnOnce() -> TextLayoutResult,
619 {
620 let mut empty_slot: Option<usize> = None;
621 {
622 let Self {
623 slots,
624 entry_last_used,
625 lru_clock,
626 cache_hits,
627 ..
628 } = self;
629 if !slots.is_empty() {
630 let mask: usize = slots.len() - 1;
631 let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
632 loop {
633 let slot: TextLayoutSlot = slots[idx];
634 if slot.entry_idx == u32::MAX {
635 empty_slot = Some(idx);
636 break;
637 }
638 if slot.key_hash == key_hash && slot.width_key == width_key {
639 *cache_hits = cache_hits.wrapping_add(1);
640 *lru_clock = lru_clock.wrapping_add(1);
641 if let Some(tick) = entry_last_used.get_mut(slot.entry_idx as usize) {
642 *tick = *lru_clock;
643 }
644 return slot.entry_idx;
645 }
646 idx = (idx + 1) & mask;
647 }
648 }
649 }
650 let measured: TextLayoutResult = compute();
651 let entry_sz: usize = Self::estimate_entry_bytes(&measured);
652 let needs_rehash: bool = {
653 let Self { slots, entries, .. } = self;
654 slots.is_empty() || (entries.len() + 1).saturating_mul(2) > slots.len()
655 };
656 if needs_rehash {
657 let next_cap: usize = {
658 let Self { slots, .. } = self;
659 if slots.is_empty() {
660 TEXT_LAYOUT_CACHE_SLOTS
661 } else {
662 slots.len().saturating_mul(2)
663 }
664 };
665 self.rehash(next_cap);
666 empty_slot = None;
667 }
668 let Self {
669 slots,
670 entries,
671 entry_keys,
672 entry_last_used,
673 entry_bytes,
674 resident_bytes,
675 lru_clock,
676 cache_misses,
677 ..
678 } = self;
679 *cache_misses = cache_misses.wrapping_add(1);
680 *lru_clock = lru_clock.wrapping_add(1);
681 let entry_idx: u32 = entries.len() as u32;
682 entries.push(measured);
683 entry_keys.push((key_hash, width_key));
684 entry_last_used.push(*lru_clock);
685 entry_bytes.push(entry_sz);
686 *resident_bytes = resident_bytes.saturating_add(entry_sz);
687 let target_idx: usize = match empty_slot {
688 Some(idx) => idx,
689 None => {
690 let mask: usize = slots.len() - 1;
691 let mut idx: usize = Self::slot_start(key_hash, width_key, mask);
692 while slots[idx].entry_idx != u32::MAX {
693 idx = (idx + 1) & mask;
694 }
695 idx
696 }
697 };
698 slots[target_idx] = TextLayoutSlot {
699 key_hash,
700 width_key,
701 entry_idx,
702 };
703 entry_idx
704 }
705}
706
707impl CornerMaskCache {
709 #[must_use]
719 pub(crate) fn len(&self) -> usize {
720 let Self { entries } = self;
721 entries.len()
722 }
723
724 #[must_use]
734 pub(crate) fn entries(&self) -> &[CachedCornerMask] {
735 let Self { entries } = self;
736 entries.as_slice()
737 }
738
739 pub(crate) fn clear(&mut self) {
745 let Self { entries } = self;
746 entries.clear();
747 }
748
749 #[must_use]
761 fn build_quadrant(radius: f32, quadrant: u8, aa_enabled: bool) -> CachedCornerMask {
762 let dim: usize = (radius + 1.0).ceil().max(1.0) as usize;
763 let dim_f: f32 = dim as f32;
764 let half_extent: f32 = dim_f + 64.0;
765 let cx_lim: f32 = half_extent - radius;
766 let r_in: f32 = radius - 1.0;
767 let r_in_sq: f32 = r_in * r_in;
768 let r_out: f32 = radius + 1.0;
769 let r_out_sq: f32 = r_out * r_out;
770 let r_sq: f32 = radius * radius;
771 let mut cov: Vec<u8> = vec![16; dim * dim];
772 let mut row_spans: Vec<CornerMaskRowSpan> = Vec::with_capacity(dim);
773 let is_left: bool = quadrant == 0 || quadrant == 3;
774 let is_top: bool = quadrant == 0 || quadrant == 1;
775 for my in 0..dim {
776 let py: f32 = if is_top {
777 (my as f32) + 0.5 - half_extent
778 } else {
779 (my as f32) + 0.5 + (half_extent - dim_f)
780 };
781 let qy: f32 = py.abs() - cx_lim;
782 let row_off: usize = my * dim;
783 for mx in 0..dim {
784 let px: f32 = if is_left {
785 (mx as f32) + 0.5 - half_extent
786 } else {
787 (mx as f32) + 0.5 + (half_extent - dim_f)
788 };
789 let qx: f32 = px.abs() - cx_lim;
790 let hits: u8 = if qx <= 0.0 || qy <= 0.0 {
791 let dist: f32 = qx.max(qy) - radius;
792 if dist <= -1.0 {
793 16
794 } else if dist >= 1.0 {
795 0
796 } else if !aa_enabled {
797 if dist <= 0.0 { 16 } else { 0 }
798 } else {
799 let c: f32 = rounded_box_supersampled_coverage(
800 px,
801 py,
802 half_extent,
803 half_extent,
804 radius,
805 0.0,
806 )
807 .0;
808 (c * 16.0).round() as u8
809 }
810 } else {
811 let d_sq: f32 = qx * qx + qy * qy;
812 if r_in >= 0.0 && d_sq <= r_in_sq {
813 16
814 } else if d_sq >= r_out_sq {
815 0
816 } else if !aa_enabled {
817 if d_sq <= r_sq { 16 } else { 0 }
818 } else {
819 let c: f32 = rounded_box_supersampled_coverage(
820 px,
821 py,
822 half_extent,
823 half_extent,
824 radius,
825 0.0,
826 )
827 .0;
828 (c * 16.0).round() as u8
829 }
830 };
831 cov[row_off + mx] = hits;
832 }
833 let row_slice: &[u8] = &cov[row_off..row_off + dim];
834 let span: CornerMaskRowSpan = if is_left {
835 let dirty_end: usize = row_slice
836 .iter()
837 .rposition(|&c: &u8| c < 16)
838 .map(|idx: usize| idx + 1)
839 .unwrap_or(0);
840 let ext_end: usize = row_slice
841 .iter()
842 .take(dirty_end)
843 .take_while(|&&c: &&u8| c == 0)
844 .count();
845 CornerMaskRowSpan {
846 ext_start: 0,
847 ext_end: ext_end as u16,
848 aa_start: ext_end as u16,
849 aa_end: dirty_end as u16,
850 dirty_start: 0,
851 dirty_end: dirty_end as u16,
852 }
853 } else {
854 let dirty_start: usize = row_slice.iter().position(|&c: &u8| c < 16).unwrap_or(dim);
855 let trailing_zeros: usize = row_slice[dirty_start..]
856 .iter()
857 .rev()
858 .take_while(|&&c: &&u8| c == 0)
859 .count();
860 let ext_start: usize = dim - trailing_zeros;
861 CornerMaskRowSpan {
862 ext_start: ext_start as u16,
863 ext_end: dim as u16,
864 aa_start: dirty_start as u16,
865 aa_end: ext_start.max(dirty_start) as u16,
866 dirty_start: dirty_start as u16,
867 dirty_end: dim as u16,
868 }
869 };
870 row_spans.push(span);
871 }
872 CachedCornerMask {
873 radius_bits: radius.to_bits(),
874 quadrant,
875 aa_enabled,
876 dim: dim as u16,
877 cov,
878 row_spans,
879 }
880 }
881
882 fn get_or_build(&mut self, radius: f32, quadrant: u8, aa_enabled: bool) -> u32 {
895 let bits: u32 = radius.to_bits();
896 let Self { entries } = self;
897 for (idx, entry) in entries.iter().enumerate() {
898 if entry.radius_bits == bits
899 && entry.quadrant == quadrant
900 && entry.aa_enabled == aa_enabled
901 {
902 return idx as u32;
903 }
904 }
905 let idx: u32 = entries.len() as u32;
906 entries.push(Self::build_quadrant(radius, quadrant, aa_enabled));
907 idx
908 }
909
910 pub(crate) fn resolve_quadrants(
923 &mut self,
924 rect: Rect,
925 radius: CornerRadius,
926 aa: AntialiasingMode,
927 ) -> [u32; 4] {
928 let mut ids: [u32; 4] = [u32::MAX; 4];
929 let half_w: f32 = rect.get_width() * 0.5;
930 let half_h: f32 = rect.get_height() * 0.5;
931 let max_r: f32 = half_w.min(half_h).max(0.0);
932 if max_r <= 0.25 {
933 return ids;
934 }
935 let x0: f32 = rect.get_x();
936 let y0: f32 = rect.get_y();
937 let x1: f32 = rect.right();
938 let y1: f32 = rect.bottom();
939 if (x0 - x0.round()).abs() > 1e-4
940 || (y0 - y0.round()).abs() > 1e-4
941 || (x1 - x1.round()).abs() > 1e-4
942 || (y1 - y1.round()).abs() > 1e-4
943 {
944 return ids;
945 }
946 let aa_enabled: bool = aa != AntialiasingMode::None;
947 let radii: [f32; 4] = [
948 radius.get_top_left().min(max_r),
949 radius.get_top_right().min(max_r),
950 radius.get_bottom_right().min(max_r),
951 radius.get_bottom_left().min(max_r),
952 ];
953 for (q, r) in radii.into_iter().enumerate() {
954 if r > 0.25 && r + 1.5 < half_w && r + 1.5 < half_h {
955 let dim: u32 = (r + 1.0).ceil() as u32;
956 if dim > 0 && dim <= CORNER_MASK_MAX_DIM {
957 ids[q] = self.get_or_build(r, q as u8, aa_enabled);
958 }
959 }
960 }
961 ids
962 }
963}
964
965impl SoftwareRenderer {
967 #[must_use]
979 pub fn with_config(width: u32, height: u32, config: RenderConfig) -> Self {
980 Self::with_font_provider(width, height, config, NativeSystemFont::deterministic())
981 }
982
983 #[must_use]
996 pub fn with_font_provider(
997 width: u32,
998 height: u32,
999 config: RenderConfig,
1000 font_provider: NativeSystemFont,
1001 ) -> Self {
1002 Self {
1003 framebuffer: Framebuffer::allocate(width, height),
1004 glyph_atlas: GlyphAtlas::default(),
1005 font_provider,
1006 measurer: DeterministicTextMeasurer,
1007 text_layout_cache: TextLayoutCache::with_capacity(TEXT_LAYOUT_CACHE_SLOTS),
1008 clip_stack: Vec::with_capacity(8),
1009 rounded_clip_stack: Vec::with_capacity(8),
1010 antialiasing: config.get_antialiasing(),
1011 tile_size: config.get_tile_size().max(16),
1012 base_cache_width: 0,
1013 base_cache_height: 0,
1014 base_cache_hash: 0,
1015 prev_base_hash: 0,
1016 base_cache_pixels: Vec::new(),
1017 prepped_scratch: Vec::with_capacity(64),
1018 rounded_clips_scratch: Vec::with_capacity(16),
1019 positioned_glyphs_scratch: Vec::with_capacity(256),
1020 line_glyphs_scratch: Vec::with_capacity(64),
1021 caret_rects_scratch: Vec::with_capacity(4),
1022 corner_mask_cache: CornerMaskCache::default(),
1023 prev_portal_bounds: None,
1024 prev_portal_scrim: None,
1025 prepped_bounds: None,
1026 prepped_fg_bounds: None,
1027 clip_scope_scratch: Vec::with_capacity(8),
1028 cached_scrim_color: None,
1029 cached_scrim_luts: None,
1030 serial_dispatches: 0,
1031 parallel_dispatches: 0,
1032 culled_occluded_commands: 0,
1033 adaptive_parallel_threshold_pixels: ADAPTIVE_PARALLEL_DEFAULT_PIXELS,
1034 adaptive_threshold_override: 0,
1035 last_serial_us: 0,
1036 last_parallel_us: 0,
1037 }
1038 }
1039
1040 pub fn set_adaptive_parallel_threshold(&mut self, min_pixels: Option<usize>) {
1047 let Self {
1048 adaptive_threshold_override,
1049 adaptive_parallel_threshold_pixels,
1050 ..
1051 } = self;
1052 match min_pixels {
1053 Some(px) => {
1054 let clamped: usize = px.max(1);
1055 *adaptive_threshold_override = clamped;
1056 *adaptive_parallel_threshold_pixels = clamped;
1057 }
1058 None => {
1059 *adaptive_threshold_override = 0;
1060 *adaptive_parallel_threshold_pixels = ADAPTIVE_PARALLEL_DEFAULT_PIXELS;
1061 }
1062 }
1063 }
1064
1065 #[must_use]
1075 pub fn adaptive_parallel_threshold(&self) -> usize {
1076 if self.get_adaptive_threshold_override() > 0 {
1077 self.get_adaptive_threshold_override()
1078 } else if self.get_adaptive_parallel_threshold_pixels() > 0 {
1079 self.get_adaptive_parallel_threshold_pixels()
1080 } else {
1081 ADAPTIVE_PARALLEL_DEFAULT_PIXELS
1082 }
1083 }
1084
1085 #[must_use]
1097 fn detect_full_viewport_scrim(
1098 commands: &[DrawCommand],
1099 prepped: &[PreppedCommand],
1100 dims: (u32, u32, f32),
1101 ) -> Option<Color> {
1102 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
1103 let first: &PreppedCommand = prepped.first()?;
1104 if first.get_cmd_index() == usize::MAX || first.get_rounded_clip_len() != 0 {
1105 return None;
1106 }
1107 let clip: Rect = first.get_active_clip();
1108 let fw: f32 = phys_w as f32;
1109 let fh: f32 = phys_h as f32;
1110 if clip.get_x() > 0.0 || clip.get_y() > 0.0 || clip.right() < fw || clip.bottom() < fh {
1111 return None;
1112 }
1113 if let DrawCommand::FillRoundedRect {
1114 rect,
1115 color,
1116 radius,
1117 border,
1118 } = &commands[first.get_cmd_index()]
1119 {
1120 let sa: u8 = color.get_a();
1121 if sa > 0 && sa < 255 && radius.max_radius() <= 0.0 && border.get_width() <= 0.0 {
1122 let phys: Rect = snap_physical_rect(*rect, scale);
1123 if phys.get_x() <= 0.0
1124 && phys.get_y() <= 0.0
1125 && phys.right() >= fw
1126 && phys.bottom() >= fh
1127 {
1128 return Some(*color);
1129 }
1130 }
1131 }
1132 None
1133 }
1134
1135 #[must_use]
1147 fn rect_pixel_area(rect: Rect, phys_w: u32, phys_h: u32) -> usize {
1148 let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(phys_w);
1149 let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(phys_h);
1150 let x1: u32 = (rect.right().ceil().max(0.0) as u32).clamp(x0, phys_w);
1151 let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).clamp(y0, phys_h);
1152 ((x1 - x0) as usize).saturating_mul((y1 - y0) as usize)
1153 }
1154
1155 pub fn render(&mut self, display_list: &DisplayList, damage: DamageRegion) -> (usize, usize) {
1167 let scale: f32 = display_list.get_scale_factor().max(0.5);
1168 let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
1169 let phys_h: u32 =
1170 ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
1171 let resized: bool = self.get_mut_framebuffer().resize(phys_w, phys_h);
1172 if resized {
1173 self.set_base_cache_hash(0);
1174 self.set_prev_base_hash(0);
1175 self.set_base_cache_width(0);
1176 self.set_base_cache_height(0);
1177 self.set_prev_portal_bounds(None);
1178 self.set_prev_portal_scrim(None);
1179 }
1180 let effective_damage: DamageRegion = if resized {
1181 DamageRegion::full()
1182 } else {
1183 damage
1184 };
1185 let (norm_rects, norm_count): ([Rect; 8], usize) =
1186 effective_damage.normalized_rects(phys_w, phys_h);
1187 if norm_count == 0 {
1188 return (0, 0);
1189 }
1190 let tile_sz: u32 = self.get_tile_size().max(16);
1191 let commands: &[DrawCommand] = display_list.get_commands().as_slice();
1192 let split: usize = display_list.get_portal_split_index().min(commands.len());
1193 let has_portals: bool = split > 0 && split < commands.len();
1194 if norm_count > 1 {
1195 let mut sum_area: usize = 0;
1196 for sub in norm_rects.iter().take(norm_count) {
1197 sum_area = sum_area.saturating_add(Self::rect_pixel_area(*sub, phys_w, phys_h));
1198 }
1199 let union_area: usize = effective_damage
1200 .resolve(phys_w, phys_h)
1201 .map_or(0, |u: Rect| Self::rect_pixel_area(u, phys_w, phys_h));
1202 if sum_area.saturating_mul(4) < union_area.saturating_mul(3) {
1203 if !has_portals {
1204 self.set_base_cache_hash(0);
1205 self.set_prev_base_hash(0);
1206 }
1207 self.set_prev_portal_bounds(None);
1208 self.set_prev_portal_scrim(None);
1209 let mut total_tiles: usize = 0;
1210 let mut total_shaded: usize = 0;
1211 for sub_clip in norm_rects.iter().take(norm_count).copied() {
1212 let tx: usize =
1213 ((sub_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
1214 let ty: usize =
1215 ((sub_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
1216 total_tiles = total_tiles.saturating_add(tx.saturating_mul(ty));
1217 self.prepare_frame_range(
1218 display_list,
1219 (0, commands.len()),
1220 sub_clip,
1221 (phys_w, phys_h, scale),
1222 );
1223 let shaded: usize = self.execute_prepared_bands(
1224 commands,
1225 sub_clip,
1226 (phys_w, phys_h, scale),
1227 (false, None, 0),
1228 );
1229 total_shaded = total_shaded.saturating_add(shaded);
1230 }
1231 return (total_tiles, total_shaded);
1232 }
1233 }
1234 let root_clip: Rect = if norm_count == 1 {
1235 norm_rects[0]
1236 } else {
1237 let Some(resolved) = effective_damage.resolve(phys_w, phys_h) else {
1238 return (0, 0);
1239 };
1240 resolved
1241 };
1242 let tiles_x: usize = ((root_clip.get_width().ceil() as u32).div_ceil(tile_sz)) as usize;
1243 let tiles_y: usize = ((root_clip.get_height().ceil() as u32).div_ceil(tile_sz)) as usize;
1244 let tiles_updated: usize = tiles_x.saturating_mul(tiles_y);
1245 let is_full_frame: bool = root_clip.get_x() <= 0.0
1246 && root_clip.get_y() <= 0.0
1247 && root_clip.get_width() >= (phys_w as f32)
1248 && root_clip.get_height() >= (phys_h as f32);
1249 if has_portals && is_full_frame {
1250 let base_hash: u64 = display_list.base_layer_hash();
1251 let fb_len: usize = self.get_framebuffer().get_pixels().len();
1252 let cache_hit: bool = base_hash != 0
1253 && self.get_base_cache_hash() == base_hash
1254 && self.get_base_cache_width() == phys_w
1255 && self.get_base_cache_height() == phys_h
1256 && self.get_base_cache_pixels().len() == fb_len;
1257 if cache_hit {
1258 self.prepare_frame_range(
1259 display_list,
1260 (split, commands.len()),
1261 root_clip,
1262 (phys_w, phys_h, scale),
1263 );
1264 let cur_scrim: Option<Color> = Self::detect_full_viewport_scrim(
1265 commands,
1266 self.get_prepped_scratch().as_slice(),
1267 (phys_w, phys_h, scale),
1268 );
1269 let (cur_fg_bounds, prev_scrim, prev_bounds): (
1270 Option<Rect>,
1271 Option<Color>,
1272 Option<Rect>,
1273 ) = {
1274 let Self {
1275 prepped_fg_bounds,
1276 prepped_bounds,
1277 prev_portal_scrim,
1278 prev_portal_bounds,
1279 ..
1280 } = self;
1281 let fg: Option<Rect> = if cur_scrim.is_some() {
1282 *prepped_fg_bounds
1283 } else {
1284 *prepped_bounds
1285 };
1286 (fg, *prev_portal_scrim, *prev_portal_bounds)
1287 };
1288 self.set_prev_portal_scrim(cur_scrim);
1289 self.set_prev_portal_bounds(cur_fg_bounds);
1290 let prepped_start: usize = usize::from(cur_scrim.is_some());
1291 let (portal_rects, portal_count): ([Rect; 8], usize) = if cur_scrim == prev_scrim {
1292 let mut portal_damage: DamageRegion = DamageRegion::default();
1293 if let Some(prev_r) = prev_bounds {
1294 portal_damage.add_rect(prev_r);
1295 }
1296 if let Some(cur_r) = cur_fg_bounds {
1297 portal_damage.add_rect(cur_r);
1298 }
1299 portal_damage.normalized_rects(phys_w, phys_h)
1300 } else {
1301 let mut full_arr: [Rect; 8] = [Rect::default(); 8];
1302 full_arr[0] = root_clip;
1303 (full_arr, 1)
1304 };
1305 if portal_count == 0 {
1306 return (tiles_updated, 1);
1307 }
1308 let mut total_portal_shaded: usize = 0;
1309 for dirty_clip in portal_rects.iter().take(portal_count).copied() {
1310 let scrim_shaded: usize = if cur_scrim.is_some() {
1311 Self::rect_pixel_area(dirty_clip, phys_w, phys_h)
1312 } else {
1313 0
1314 };
1315 let band_shaded: usize = self.execute_prepared_bands(
1316 commands,
1317 dirty_clip,
1318 (phys_w, phys_h, scale),
1319 (true, cur_scrim, prepped_start),
1320 );
1321 total_portal_shaded = total_portal_shaded
1322 .saturating_add(scrim_shaded)
1323 .saturating_add(band_shaded);
1324 }
1325 return (tiles_updated, total_portal_shaded.max(1));
1326 }
1327 self.prepare_frame_range(display_list, (0, split), root_clip, (phys_w, phys_h, scale));
1328 let base_shaded: usize = self.execute_prepared_bands(
1329 commands,
1330 root_clip,
1331 (phys_w, phys_h, scale),
1332 (false, None, 0),
1333 );
1334 let base_stable: bool = base_hash != 0 && self.get_prev_base_hash() == base_hash;
1335 self.set_prev_base_hash(base_hash);
1336 if base_stable {
1337 let Self {
1338 framebuffer,
1339 base_cache_pixels,
1340 base_cache_width,
1341 base_cache_height,
1342 base_cache_hash,
1343 ..
1344 } = self;
1345 let src_pixels: &[u8] = framebuffer.get_pixels().as_slice();
1346 if base_cache_pixels.len() != src_pixels.len() {
1347 base_cache_pixels.resize(src_pixels.len(), 0);
1348 }
1349 base_cache_pixels.copy_from_slice(src_pixels);
1350 *base_cache_width = phys_w;
1351 *base_cache_height = phys_h;
1352 *base_cache_hash = base_hash;
1353 }
1354 self.prepare_frame_range(
1355 display_list,
1356 (split, commands.len()),
1357 root_clip,
1358 (phys_w, phys_h, scale),
1359 );
1360 let cur_scrim: Option<Color> = Self::detect_full_viewport_scrim(
1361 commands,
1362 self.get_prepped_scratch().as_slice(),
1363 (phys_w, phys_h, scale),
1364 );
1365 let cur_fg_bounds: Option<Rect> = {
1366 let Self {
1367 prepped_fg_bounds,
1368 prepped_bounds,
1369 ..
1370 } = self;
1371 if cur_scrim.is_some() {
1372 *prepped_fg_bounds
1373 } else {
1374 *prepped_bounds
1375 }
1376 };
1377 self.set_prev_portal_scrim(cur_scrim);
1378 self.set_prev_portal_bounds(cur_fg_bounds);
1379 let portal_shaded: usize = self.execute_prepared_bands(
1380 commands,
1381 root_clip,
1382 (phys_w, phys_h, scale),
1383 (false, None, 0),
1384 );
1385 return (tiles_updated, base_shaded.saturating_add(portal_shaded));
1386 }
1387 if !has_portals {
1388 self.set_base_cache_hash(0);
1389 self.set_prev_base_hash(0);
1390 }
1391 self.set_prev_portal_bounds(None);
1392 self.set_prev_portal_scrim(None);
1393 self.prepare_frame_range(
1394 display_list,
1395 (0, commands.len()),
1396 root_clip,
1397 (phys_w, phys_h, scale),
1398 );
1399 let pixels_shaded: usize = self.execute_prepared_bands(
1400 commands,
1401 root_clip,
1402 (phys_w, phys_h, scale),
1403 (false, None, 0),
1404 );
1405 (tiles_updated, pixels_shaded)
1406 }
1407
1408 fn execute_prepared_bands(
1422 &mut self,
1423 commands: &[DrawCommand],
1424 root_clip: Rect,
1425 dims: (u32, u32, f32),
1426 restore_opts: (bool, Option<Color>, usize),
1427 ) -> usize {
1428 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
1429 let (restore_base_cache, scrim_color, prepped_start): (bool, Option<Color>, usize) =
1430 restore_opts;
1431 let clip_x0: u32 = (root_clip.get_x().floor().max(0.0) as u32).min(phys_w);
1432 let clip_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
1433 let clip_x1: u32 = (root_clip.right().ceil().max(0.0) as u32).clamp(clip_x0, phys_w);
1434 let clip_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).clamp(clip_y0, phys_h);
1435 let clip_w: u32 = clip_x1.saturating_sub(clip_x0);
1436 let clip_h: u32 = clip_y1.saturating_sub(clip_y0);
1437 if clip_w == 0 || clip_h == 0 {
1438 return 0;
1439 }
1440 let Self {
1441 framebuffer,
1442 glyph_atlas,
1443 base_cache_pixels,
1444 prepped_scratch,
1445 positioned_glyphs_scratch,
1446 caret_rects_scratch,
1447 rounded_clips_scratch,
1448 corner_mask_cache,
1449 antialiasing,
1450 cached_scrim_color,
1451 cached_scrim_luts,
1452 serial_dispatches,
1453 parallel_dispatches,
1454 adaptive_parallel_threshold_pixels,
1455 adaptive_threshold_override,
1456 last_serial_us,
1457 last_parallel_us,
1458 ..
1459 } = self;
1460 let aa: AntialiasingMode = *antialiasing;
1461 let clamped_start: usize = prepped_start.min(prepped_scratch.len());
1462 let prepped_slice: &[PreppedCommand] = &prepped_scratch.as_slice()[clamped_start..];
1463 if prepped_slice.is_empty() && !restore_base_cache {
1464 return 0;
1465 }
1466 let scrim_luts_ref: Option<&RgbaLutQuad> = if let Some(scrim_c) = scrim_color {
1467 if *cached_scrim_color != Some(scrim_c) || cached_scrim_luts.is_none() {
1468 *cached_scrim_color = Some(scrim_c);
1469 *cached_scrim_luts = Some(Box::new(build_linear_blend_luts(scrim_c)));
1470 }
1471 cached_scrim_luts.as_deref()
1472 } else {
1473 None
1474 };
1475 let glyphs_slice: &[PositionedGlyph] = positioned_glyphs_scratch.as_slice();
1476 let caret_rects_slice: &[Rect] = caret_rects_scratch.as_slice();
1477 let rounded_clips_slice: &[RoundedClipMask] = rounded_clips_scratch.as_slice();
1478 let corner_masks_slice: &[CachedCornerMask] = corner_mask_cache.entries();
1479 let atlas_ref: &GlyphAtlas = glyph_atlas;
1480 let restore_spec: BandRestoreSpec<'_> = BandRestoreSpec {
1481 base_pixels: if restore_base_cache {
1482 Some(base_cache_pixels.as_slice())
1483 } else {
1484 None
1485 },
1486 x0: clip_x0,
1487 x1: clip_x1,
1488 scrim_luts: scrim_luts_ref,
1489 };
1490 #[cfg(not(target_arch = "wasm32"))]
1491 let mut has_backdrop_blur: bool = false;
1492 #[cfg(not(target_arch = "wasm32"))]
1493 let mut complexity_bonus: usize = rounded_clips_slice.len().saturating_mul(16_384);
1494 #[cfg(not(target_arch = "wasm32"))]
1495 for item in prepped_slice.iter() {
1496 let idx: usize = item.get_cmd_index();
1497 if idx != usize::MAX {
1498 match &commands[idx] {
1499 DrawCommand::BackdropBlur { .. } => {
1500 has_backdrop_blur = true;
1501 break;
1502 }
1503 DrawCommand::BoxShadow { .. } => {
1504 complexity_bonus = complexity_bonus.saturating_add(12_288);
1505 }
1506 DrawCommand::TextRun { .. } => {
1507 complexity_bonus = complexity_bonus.saturating_add(4_096);
1508 }
1509 _ => {}
1510 }
1511 }
1512 }
1513 #[cfg(not(target_arch = "wasm32"))]
1514 let pixel_area: usize = (clip_w as usize).saturating_mul(clip_h as usize);
1515 #[cfg(not(target_arch = "wasm32"))]
1516 let active_min_pixels: usize = if *adaptive_threshold_override > 0 {
1517 *adaptive_threshold_override
1518 } else if *adaptive_parallel_threshold_pixels > 0 {
1519 *adaptive_parallel_threshold_pixels
1520 } else {
1521 ADAPTIVE_PARALLEL_DEFAULT_PIXELS
1522 };
1523 #[cfg(not(target_arch = "wasm32"))]
1524 {
1525 let many_cmds: bool =
1526 prepped_slice.len() >= BAND_DISPATCH_MIN_CMDS || restore_base_cache;
1527 let large_area: bool = pixel_area >= BAND_DISPATCH_MIN_PIXELS.saturating_mul(2);
1528 let enough_work: bool = many_cmds || large_area;
1529 if !has_backdrop_blur
1530 && pixel_area >= active_min_pixels.max(SMALL_DAMAGE_SINGLE_THREAD_PIXELS)
1531 && clip_h >= BAND_DISPATCH_MIN_HEIGHT
1532 && enough_work
1533 {
1534 let effective_area: usize = pixel_area.saturating_add(complexity_bonus);
1535 if effective_area >= BAND_DISPATCH_MIN_PIXELS.saturating_mul(2) {
1536 let pool: &BandWorkerPool = global_band_worker_pool();
1537 let desired_threads: usize =
1538 (effective_area / BAND_DISPATCH_MIN_PIXELS).clamp(1, pool.total_threads());
1539 let strip_count: usize = (desired_threads.saturating_mul(2))
1540 .min((clip_h / 24) as usize)
1541 .max(1);
1542 if strip_count > 1 && desired_threads > 1 {
1543 *parallel_dispatches = parallel_dispatches.wrapping_add(1);
1544 let t0: Instant = Instant::now();
1545 let shaded: usize = pool.execute(
1546 framebuffer,
1547 (
1548 clip_y0,
1549 clip_y1,
1550 strip_count,
1551 desired_threads.saturating_sub(1),
1552 ),
1553 (commands, prepped_slice),
1554 (
1555 glyphs_slice,
1556 caret_rects_slice,
1557 rounded_clips_slice,
1558 corner_masks_slice,
1559 ),
1560 atlas_ref,
1561 (scale, aa, restore_spec),
1562 );
1563 let elapsed_us: u64 = t0.elapsed().as_micros() as u64;
1564 *last_parallel_us = elapsed_us;
1565 if *adaptive_threshold_override == 0 && elapsed_us < 280 {
1566 let step: usize = (active_min_pixels / 8).max(4096);
1567 *adaptive_parallel_threshold_pixels = active_min_pixels
1568 .saturating_add(step)
1569 .min(ADAPTIVE_PARALLEL_MAX_PIXELS);
1570 }
1571 return shaded;
1572 }
1573 }
1574 }
1575 }
1576 #[cfg(target_arch = "wasm32")]
1577 {
1578 let _: &mut u64 = parallel_dispatches;
1579 let _: &mut usize = adaptive_parallel_threshold_pixels;
1580 let _: &mut usize = adaptive_threshold_override;
1581 let _: &mut u64 = last_serial_us;
1582 let _: &mut u64 = last_parallel_us;
1583 }
1584 *serial_dispatches = serial_dispatches.wrapping_add(1);
1585 #[cfg(not(target_arch = "wasm32"))]
1586 let serial_t0: Instant = Instant::now();
1587 let row_stride: usize = (phys_w as usize) * 4;
1588 let start_byte: usize = (clip_y0 as usize) * row_stride;
1589 let end_byte: usize = (clip_y1 as usize) * row_stride;
1590 let Some(slice) = framebuffer.get_mut_pixels().get_mut(start_byte..end_byte) else {
1591 return 0;
1592 };
1593 if let Some(src_buf) = restore_spec.base_pixels
1594 && let Some(src_slice) = src_buf.get(start_byte..end_byte)
1595 {
1596 restore_band_strip(
1597 slice,
1598 src_slice,
1599 (
1600 row_stride,
1601 clip_h as usize,
1602 (restore_spec.x0 as usize) * 4,
1603 (restore_spec.x1.saturating_sub(restore_spec.x0) as usize) * 4,
1604 ),
1605 restore_spec.scrim_luts,
1606 );
1607 }
1608 let mut band: PixelBand<'_> = PixelBand {
1609 width: phys_w,
1610 y_offset: clip_y0,
1611 height: clip_h,
1612 pixels: slice,
1613 };
1614 let shaded_serial: usize = Self::render_band(
1615 &mut band,
1616 commands,
1617 prepped_slice,
1618 (
1619 glyphs_slice,
1620 caret_rects_slice,
1621 rounded_clips_slice,
1622 corner_masks_slice,
1623 ),
1624 atlas_ref,
1625 (scale, aa),
1626 );
1627 #[cfg(not(target_arch = "wasm32"))]
1628 {
1629 let elapsed_us: u64 = serial_t0.elapsed().as_micros() as u64;
1630 *last_serial_us = elapsed_us;
1631 if *adaptive_threshold_override == 0 && !has_backdrop_blur {
1632 if pixel_area >= ADAPTIVE_PARALLEL_MIN_PIXELS && elapsed_us > 900 {
1633 let step: usize = (active_min_pixels / 8).max(4096);
1634 *adaptive_parallel_threshold_pixels = active_min_pixels
1635 .saturating_sub(step)
1636 .max(ADAPTIVE_PARALLEL_MIN_PIXELS);
1637 } else if pixel_area >= ADAPTIVE_PARALLEL_MIN_PIXELS && elapsed_us < 220 {
1638 let step: usize = (active_min_pixels / 16).max(2048);
1639 *adaptive_parallel_threshold_pixels = active_min_pixels
1640 .saturating_add(step)
1641 .min(ADAPTIVE_PARALLEL_MAX_PIXELS);
1642 }
1643 }
1644 }
1645 shaded_serial
1646 }
1647
1648 fn prepare_frame_range(
1658 &mut self,
1659 display_list: &DisplayList,
1660 range: (usize, usize),
1661 root_clip: Rect,
1662 dims: (u32, u32, f32),
1663 ) {
1664 let (start_idx, end_idx): (usize, usize) = range;
1665 let (phys_w, phys_h, scale): (u32, u32, f32) = dims;
1666 let commands: &[DrawCommand] = display_list.get_commands().as_slice();
1667 let clamped_end: usize = end_idx.min(commands.len());
1668 let clamped_start: usize = start_idx.min(clamped_end);
1669 let Self {
1670 glyph_atlas,
1671 font_provider,
1672 measurer,
1673 text_layout_cache,
1674 clip_stack,
1675 rounded_clip_stack,
1676 prepped_scratch: prepped,
1677 rounded_clips_scratch: rounded_clips,
1678 positioned_glyphs_scratch: positioned_glyphs,
1679 line_glyphs_scratch: line_scratch,
1680 caret_rects_scratch: caret_rects,
1681 corner_mask_cache,
1682 prepped_bounds,
1683 prepped_fg_bounds,
1684 clip_scope_scratch: clip_scopes,
1685 antialiasing,
1686 culled_occluded_commands,
1687 ..
1688 } = self;
1689 let aa: AntialiasingMode = *antialiasing;
1690 prepped.clear();
1691 prepped.reserve(clamped_end - clamped_start);
1692 *prepped_bounds = None;
1693 *prepped_fg_bounds = None;
1694 rounded_clips.clear();
1695 positioned_glyphs.clear();
1696 caret_rects.clear();
1697 clip_stack.clear();
1698 clip_stack.push(root_clip);
1699 rounded_clip_stack.clear();
1700 rounded_clip_stack.push(None);
1701 let root_y0: u32 = (root_clip.get_y().floor().max(0.0) as u32).min(phys_h);
1702 let root_y1: u32 = (root_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
1703 clip_scopes.clear();
1704 clip_scopes.push((root_y0, root_y1, None));
1705 let mut empty_clip_depth: usize = 0;
1706 let mut has_first_cmd: bool = false;
1707 glyph_atlas.evict_if_over_budget();
1708 glyph_atlas.set_slots_pinned(true);
1709 text_layout_cache.evict_lru_if_needed();
1710 if corner_mask_cache.len() > CORNER_MASK_CACHE_LIMIT {
1711 corner_mask_cache.clear();
1712 }
1713 for (offset, cmd) in commands[clamped_start..clamped_end].iter().enumerate() {
1714 if empty_clip_depth > 0 {
1715 match cmd {
1716 DrawCommand::PushClip(_) | DrawCommand::PushRoundedClip { .. } => {
1717 empty_clip_depth += 1;
1718 }
1719 DrawCommand::PopClip => {
1720 empty_clip_depth -= 1;
1721 }
1722 _ => {}
1723 }
1724 continue;
1725 }
1726 let cmd_index: usize = clamped_start + offset;
1727 let active_clip: Rect = clip_stack.last().copied().unwrap_or(root_clip);
1728 match cmd {
1729 DrawCommand::PushClip(rect) => {
1730 let phys: Rect = snap_physical_rect(*rect, scale);
1731 let Some(next) = active_clip.intersect(phys) else {
1732 empty_clip_depth = 1;
1733 continue;
1734 };
1735 let nx0: u32 = (next.get_x().floor().max(0.0) as u32).min(phys_w);
1736 let nx1: u32 = (next.right().ceil().max(0.0) as u32).min(phys_w);
1737 let ny0: u32 = (next.get_y().floor().max(0.0) as u32).min(phys_h);
1738 let ny1: u32 = (next.bottom().ceil().max(0.0) as u32).min(phys_h);
1739 if nx0 >= nx1 || ny0 >= ny1 {
1740 empty_clip_depth = 1;
1741 continue;
1742 }
1743 clip_stack.push(next);
1744 rounded_clip_stack.push(None);
1745 let (parent_y0, parent_y1, _): (u32, u32, Option<usize>) = clip_scopes
1746 .last()
1747 .copied()
1748 .unwrap_or((root_y0, root_y1, None));
1749 if ny0 > parent_y0 || ny1 < parent_y1 {
1750 let slot_idx: usize = prepped.len();
1751 prepped.push(PreppedCommand {
1752 cmd_index: usize::MAX,
1753 active_clip: next,
1754 y0: ny0,
1755 y1: ny1,
1756 opaque_cutout_h: Rect::default(),
1757 opaque_cutout_v: Rect::default(),
1758 glyph_run_start: 0,
1759 glyph_run_len: 0,
1760 caret_rect_idx: u32::MAX,
1761 rounded_clip_start: 0,
1762 rounded_clip_len: 0,
1763 skip_delta: 1,
1764 });
1765 clip_scopes.push((ny0, ny1, Some(slot_idx)));
1766 } else {
1767 clip_scopes.push((parent_y0, parent_y1, None));
1768 }
1769 }
1770 DrawCommand::PushRoundedClip { rect, radius } => {
1771 let phys: Rect = snap_physical_rect(*rect, scale);
1772 let Some(next) = active_clip.intersect(phys) else {
1773 empty_clip_depth = 1;
1774 continue;
1775 };
1776 let nx0: u32 = (next.get_x().floor().max(0.0) as u32).min(phys_w);
1777 let nx1: u32 = (next.right().ceil().max(0.0) as u32).min(phys_w);
1778 let ny0: u32 = (next.get_y().floor().max(0.0) as u32).min(phys_h);
1779 let ny1: u32 = (next.bottom().ceil().max(0.0) as u32).min(phys_h);
1780 if nx0 >= nx1 || ny0 >= ny1 {
1781 empty_clip_depth = 1;
1782 continue;
1783 }
1784 clip_stack.push(next);
1785 let phys_r: CornerRadius = Self::scale_radius(*radius, scale);
1786 if phys.get_width() > 0.0
1787 && phys.get_height() > 0.0
1788 && phys_r.max_radius() > 0.25
1789 {
1790 let corner_mask_ids: [u32; 4] =
1791 corner_mask_cache.resolve_quadrants(phys, phys_r, aa);
1792 rounded_clip_stack.push(Some(RoundedClipMask {
1793 rect: phys,
1794 radius: phys_r,
1795 corner_mask_ids,
1796 }));
1797 } else {
1798 rounded_clip_stack.push(None);
1799 }
1800 let (parent_y0, parent_y1, _): (u32, u32, Option<usize>) = clip_scopes
1801 .last()
1802 .copied()
1803 .unwrap_or((root_y0, root_y1, None));
1804 if ny0 > parent_y0 || ny1 < parent_y1 {
1805 let slot_idx: usize = prepped.len();
1806 prepped.push(PreppedCommand {
1807 cmd_index: usize::MAX,
1808 active_clip: next,
1809 y0: ny0,
1810 y1: ny1,
1811 opaque_cutout_h: Rect::default(),
1812 opaque_cutout_v: Rect::default(),
1813 glyph_run_start: 0,
1814 glyph_run_len: 0,
1815 caret_rect_idx: u32::MAX,
1816 rounded_clip_start: 0,
1817 rounded_clip_len: 0,
1818 skip_delta: 1,
1819 });
1820 clip_scopes.push((ny0, ny1, Some(slot_idx)));
1821 } else {
1822 clip_scopes.push((parent_y0, parent_y1, None));
1823 }
1824 }
1825 DrawCommand::PopClip => {
1826 if clip_stack.len() > 1 {
1827 clip_stack.pop();
1828 let _: Option<Option<RoundedClipMask>> = rounded_clip_stack.pop();
1829 if let Some((_, _, Some(slot_idx))) = clip_scopes.pop() {
1830 let span_len: usize = prepped.len().saturating_sub(slot_idx);
1831 if span_len <= 1 {
1832 prepped.truncate(slot_idx);
1833 } else if span_len == 2 {
1834 let only_cmd: PreppedCommand = prepped[slot_idx + 1];
1835 prepped[slot_idx] = only_cmd;
1836 let _: Option<PreppedCommand> = prepped.pop();
1837 } else {
1838 prepped[slot_idx].skip_delta = span_len as u32;
1839 }
1840 }
1841 }
1842 }
1843 DrawCommand::Clear(clear_color) => {
1844 let y0: u32 = (active_clip.get_y().floor().max(0.0) as u32).min(phys_h);
1845 let y1: u32 = (active_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
1846 if y0 < y1 {
1847 let (mut rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
1848 rounded_clip_stack.as_slice(),
1849 rounded_clips,
1850 active_clip,
1851 );
1852 let covers_root: bool = active_clip.get_x() <= root_clip.get_x()
1853 && active_clip.get_y() <= root_clip.get_y()
1854 && active_clip.right() >= root_clip.right()
1855 && active_clip.bottom() >= root_clip.bottom();
1856 let no_open_sentinels: bool = clip_scopes
1857 .iter()
1858 .all(|&(_, _, slot): &(u32, u32, Option<usize>)| slot.is_none());
1859 if clamped_start == 0
1860 && !prepped.is_empty()
1861 && rc_len == 0
1862 && clear_color.get_a() == 255
1863 && covers_root
1864 && no_open_sentinels
1865 {
1866 prepped.clear();
1867 rounded_clips.clear();
1868 positioned_glyphs.clear();
1869 caret_rects.clear();
1870 *prepped_bounds = None;
1871 *prepped_fg_bounds = None;
1872 has_first_cmd = false;
1873 rc_start = 0;
1874 }
1875 if has_first_cmd {
1876 expand_opt_rect(prepped_fg_bounds, active_clip);
1877 }
1878 has_first_cmd = true;
1879 expand_opt_rect(prepped_bounds, active_clip);
1880 prepped.push(PreppedCommand {
1881 cmd_index,
1882 active_clip,
1883 y0,
1884 y1,
1885 opaque_cutout_h: Rect::default(),
1886 opaque_cutout_v: Rect::default(),
1887 glyph_run_start: 0,
1888 glyph_run_len: 0,
1889 caret_rect_idx: u32::MAX,
1890 rounded_clip_start: rc_start,
1891 rounded_clip_len: rc_len,
1892 skip_delta: 0,
1893 });
1894 }
1895 }
1896 DrawCommand::FillRoundedRect {
1897 rect,
1898 color,
1899 radius,
1900 border,
1901 } => {
1902 let phys: Rect = snap_physical_rect(*rect, scale);
1903 if let Some(vis) = phys.intersect(active_clip) {
1904 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
1905 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
1906 if y0 < y1 {
1907 let (mut rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
1908 rounded_clip_stack.as_slice(),
1909 rounded_clips,
1910 vis,
1911 );
1912 let no_border: bool =
1913 border.get_width() <= 0.0 || border.get_color().get_a() == 0;
1914 let covers_root: bool = vis.get_x() <= root_clip.get_x()
1915 && vis.get_y() <= root_clip.get_y()
1916 && vis.right() >= root_clip.right()
1917 && vis.bottom() >= root_clip.bottom();
1918 let no_open_sentinels: bool = clip_scopes
1919 .iter()
1920 .all(|&(_, _, slot): &(u32, u32, Option<usize>)| slot.is_none());
1921 if clamped_start == 0
1922 && !prepped.is_empty()
1923 && rc_len == 0
1924 && color.get_a() == 255
1925 && radius.max_radius() <= 0.0
1926 && no_border
1927 && covers_root
1928 && no_open_sentinels
1929 {
1930 prepped.clear();
1931 rounded_clips.clear();
1932 positioned_glyphs.clear();
1933 caret_rects.clear();
1934 *prepped_bounds = None;
1935 *prepped_fg_bounds = None;
1936 has_first_cmd = false;
1937 rc_start = 0;
1938 }
1939 if has_first_cmd {
1940 expand_opt_rect(prepped_fg_bounds, vis);
1941 }
1942 has_first_cmd = true;
1943 expand_opt_rect(prepped_bounds, vis);
1944 prepped.push(PreppedCommand {
1945 cmd_index,
1946 active_clip,
1947 y0,
1948 y1,
1949 opaque_cutout_h: Rect::default(),
1950 opaque_cutout_v: Rect::default(),
1951 glyph_run_start: 0,
1952 glyph_run_len: 0,
1953 caret_rect_idx: u32::MAX,
1954 rounded_clip_start: rc_start,
1955 rounded_clip_len: rc_len,
1956 skip_delta: 0,
1957 });
1958 }
1959 }
1960 }
1961 DrawCommand::LinearGradientRect { rect, .. }
1962 | DrawCommand::BackdropBlur { rect, .. }
1963 | DrawCommand::Image { rect, .. }
1964 | DrawCommand::SpriteRegion { rect, .. } => {
1965 let phys: Rect = snap_physical_rect(*rect, scale);
1966 if let Some(vis) = phys.intersect(active_clip) {
1967 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
1968 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
1969 if y0 < y1 {
1970 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
1971 rounded_clip_stack.as_slice(),
1972 rounded_clips,
1973 vis,
1974 );
1975 if has_first_cmd {
1976 expand_opt_rect(prepped_fg_bounds, vis);
1977 }
1978 has_first_cmd = true;
1979 expand_opt_rect(prepped_bounds, vis);
1980 prepped.push(PreppedCommand {
1981 cmd_index,
1982 active_clip,
1983 y0,
1984 y1,
1985 opaque_cutout_h: Rect::default(),
1986 opaque_cutout_v: Rect::default(),
1987 glyph_run_start: 0,
1988 glyph_run_len: 0,
1989 caret_rect_idx: u32::MAX,
1990 rounded_clip_start: rc_start,
1991 rounded_clip_len: rc_len,
1992 skip_delta: 0,
1993 });
1994 }
1995 }
1996 }
1997 DrawCommand::BoxShadow { rect, shadow, .. } => {
1998 if shadow.get_color().get_a() == 0 {
1999 continue;
2000 }
2001 let spread: f32 = shadow.get_spread_radius() * scale;
2002 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
2003 let sigma: f32 = (blur * 0.5).max(0.75);
2004 let pad: f32 = (sigma * 3.0).ceil();
2005 let base_rect: Rect = snap_physical_rect(*rect, scale);
2006 let caster_rect: Rect = Rect::new(
2007 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
2008 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
2009 (base_rect.get_width() + spread * 2.0).max(1.0),
2010 (base_rect.get_height() + spread * 2.0).max(1.0),
2011 );
2012 let shadow_rect: Rect = Rect::new(
2013 caster_rect.get_x() - pad,
2014 caster_rect.get_y() - pad,
2015 caster_rect.get_width() + pad * 2.0,
2016 caster_rect.get_height() + pad * 2.0,
2017 );
2018 if let Some(vis) = shadow_rect.intersect(active_clip) {
2019 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
2020 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2021 if y0 < y1 {
2022 let (cut_h, cut_v): (Rect, Rect) = Self::resolve_opaque_shadow_cutout(
2023 commands.get(cmd_index + 1),
2024 scale,
2025 );
2026 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
2027 rounded_clip_stack.as_slice(),
2028 rounded_clips,
2029 vis,
2030 );
2031 if has_first_cmd {
2032 expand_opt_rect(prepped_fg_bounds, vis);
2033 }
2034 has_first_cmd = true;
2035 expand_opt_rect(prepped_bounds, vis);
2036 prepped.push(PreppedCommand {
2037 cmd_index,
2038 active_clip,
2039 y0,
2040 y1,
2041 opaque_cutout_h: cut_h,
2042 opaque_cutout_v: cut_v,
2043 glyph_run_start: 0,
2044 glyph_run_len: 0,
2045 caret_rect_idx: u32::MAX,
2046 rounded_clip_start: rc_start,
2047 rounded_clip_len: rc_len,
2048 skip_delta: 0,
2049 });
2050 }
2051 }
2052 }
2053 DrawCommand::TextRun { rect, text, style } => {
2054 if text.is_empty() || style.get_color().get_a() == 0 {
2055 continue;
2056 }
2057 let phys_rect: Rect = Self::scale_rect(*rect, scale);
2058 let pad: f32 = style.get_font_size() * scale * 0.5;
2059 let expanded: Rect = Rect::new(
2060 phys_rect.get_x() - pad,
2061 phys_rect.get_y() - pad,
2062 phys_rect.get_width() + pad * 2.0,
2063 phys_rect.get_height() + pad * 2.0,
2064 );
2065 let Some(vis) = expanded.intersect(active_clip) else {
2066 continue;
2067 };
2068 let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
2069 let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2070 if vis_y0 >= vis_y1 {
2071 continue;
2072 }
2073 let max_w: f32 = rect.get_width().max(1.0);
2074 let width_key: u32 = ((max_w * 10.0).round() as u32).min(u32::MAX - 1);
2075 let key_hash: u64 = hash_text_layout_key(text, *style);
2076 let layout_idx: u32 =
2077 text_layout_cache.get_or_insert_with(key_hash, width_key, || {
2078 measurer.measure(text, *style, Some(max_w))
2079 });
2080 let (glyph_run_start, glyph_run_len): (u32, u32) =
2081 if let Some(layout) = text_layout_cache.get(layout_idx) {
2082 Self::resolve_text_run_glyphs(
2083 layout,
2084 *rect,
2085 *style,
2086 (active_clip, phys_w, phys_h, scale),
2087 (glyph_atlas, font_provider),
2088 positioned_glyphs,
2089 line_scratch,
2090 )
2091 } else {
2092 (0, 0)
2093 };
2094 if glyph_run_len == 0 {
2095 continue;
2096 }
2097 let clip_y0: u32 = (active_clip.get_y().floor().max(0.0) as u32).min(phys_h);
2098 let clip_y1: u32 = (active_clip.bottom().ceil().max(0.0) as u32).min(phys_h);
2099 let mut tight_y0: u32 = phys_h;
2100 let mut tight_y1: u32 = 0;
2101 let mut glyph_bounds: Option<Rect> = None;
2102 let g_s: usize = glyph_run_start as usize;
2103 let g_e: usize = g_s.saturating_add(glyph_run_len as usize);
2104 for g in positioned_glyphs[g_s..g_e].iter() {
2105 let g_rect: Rect =
2106 Rect::new(g.x as f32, g.y as f32, g.width as f32, g.height as f32);
2107 if let Some(clipped_g) = g_rect.intersect(active_clip) {
2108 expand_opt_rect(&mut glyph_bounds, clipped_g);
2109 let gy0: u32 = (g.y.max(0) as u32).min(phys_h);
2110 let gy1: u32 = ((g.y + g.height as i32).max(0) as u32).min(phys_h);
2111 tight_y0 = tight_y0.min(gy0);
2112 tight_y1 = tight_y1.max(gy1);
2113 }
2114 }
2115 let (y0, y1, run_vis): (u32, u32, Rect) = if let Some(gb) = glyph_bounds {
2116 let ty0: u32 = tight_y0.max(clip_y0);
2117 let ty1: u32 = tight_y1.min(clip_y1);
2118 if ty0 >= ty1 {
2119 continue;
2120 }
2121 (ty0, ty1, gb)
2122 } else {
2123 (vis_y0, vis_y1, vis)
2124 };
2125 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
2126 rounded_clip_stack.as_slice(),
2127 rounded_clips,
2128 run_vis,
2129 );
2130 if has_first_cmd {
2131 expand_opt_rect(prepped_fg_bounds, run_vis);
2132 }
2133 has_first_cmd = true;
2134 expand_opt_rect(prepped_bounds, run_vis);
2135 prepped.push(PreppedCommand {
2136 cmd_index,
2137 active_clip,
2138 y0,
2139 y1,
2140 opaque_cutout_h: Rect::default(),
2141 opaque_cutout_v: Rect::default(),
2142 glyph_run_start,
2143 glyph_run_len,
2144 caret_rect_idx: u32::MAX,
2145 rounded_clip_start: rc_start,
2146 rounded_clip_len: rc_len,
2147 skip_delta: 0,
2148 });
2149 }
2150 DrawCommand::TextCaret {
2151 text_rect,
2152 content_rect,
2153 text,
2154 style,
2155 caret_height,
2156 color,
2157 multiline,
2158 } => {
2159 if color.get_a() == 0 {
2160 continue;
2161 }
2162 let phys_content: Rect = Self::scale_rect(*content_rect, scale);
2163 let Some(vis) = phys_content.intersect(active_clip) else {
2164 continue;
2165 };
2166 let vis_y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
2167 let vis_y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2168 if vis_y0 >= vis_y1 {
2169 continue;
2170 }
2171 let (max_w, width_key): (Option<f32>, u32) = if *multiline {
2172 let w: f32 = content_rect.get_width().max(1.0);
2173 (Some(w), ((w * 10.0).round() as u32).min(u32::MAX - 1))
2174 } else {
2175 (None, u32::MAX)
2176 };
2177 let key_hash: u64 = hash_text_layout_key(text, *style);
2178 let layout_idx: u32 =
2179 text_layout_cache.get_or_insert_with(key_hash, width_key, || {
2180 measurer.measure(text, *style, max_w)
2181 });
2182 let caret_rect: Rect = Self::resolve_text_caret_rect(
2183 text_layout_cache.get(layout_idx),
2184 (*text_rect, *content_rect),
2185 *style,
2186 (*caret_height, scale, *multiline),
2187 (glyph_atlas, font_provider),
2188 );
2189 let Some(caret_vis) = caret_rect.intersect(active_clip) else {
2190 continue;
2191 };
2192 let y0: u32 = (caret_vis.get_y().floor().max(0.0) as u32).min(phys_h);
2193 let y1: u32 = (caret_vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2194 if y0 >= y1 {
2195 continue;
2196 }
2197 let caret_rect_idx: u32 = caret_rects.len() as u32;
2198 caret_rects.push(caret_rect);
2199 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
2200 rounded_clip_stack.as_slice(),
2201 rounded_clips,
2202 caret_vis,
2203 );
2204 if has_first_cmd {
2205 expand_opt_rect(prepped_fg_bounds, caret_vis);
2206 }
2207 has_first_cmd = true;
2208 expand_opt_rect(prepped_bounds, caret_vis);
2209 prepped.push(PreppedCommand {
2210 cmd_index,
2211 active_clip,
2212 y0,
2213 y1,
2214 opaque_cutout_h: Rect::default(),
2215 opaque_cutout_v: Rect::default(),
2216 glyph_run_start: 0,
2217 glyph_run_len: 0,
2218 caret_rect_idx,
2219 rounded_clip_start: rc_start,
2220 rounded_clip_len: rc_len,
2221 skip_delta: 0,
2222 });
2223 }
2224 DrawCommand::Line {
2225 from, to, width, ..
2226 } => {
2227 let half_w: f32 = (width * scale).max(1.0) * 0.5 + 1.0;
2228 let min_x: f32 = from.get_x().min(to.get_x()) * scale - half_w;
2229 let min_y: f32 = from.get_y().min(to.get_y()) * scale - half_w;
2230 let max_x: f32 = from.get_x().max(to.get_x()) * scale + half_w;
2231 let max_y: f32 = from.get_y().max(to.get_y()) * scale + half_w;
2232 if let Some(vis) =
2233 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
2234 {
2235 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
2236 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2237 if y0 < y1 {
2238 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
2239 rounded_clip_stack.as_slice(),
2240 rounded_clips,
2241 vis,
2242 );
2243 if has_first_cmd {
2244 expand_opt_rect(prepped_fg_bounds, vis);
2245 }
2246 has_first_cmd = true;
2247 expand_opt_rect(prepped_bounds, vis);
2248 prepped.push(PreppedCommand {
2249 cmd_index,
2250 active_clip,
2251 y0,
2252 y1,
2253 opaque_cutout_h: Rect::default(),
2254 opaque_cutout_v: Rect::default(),
2255 glyph_run_start: 0,
2256 glyph_run_len: 0,
2257 caret_rect_idx: u32::MAX,
2258 rounded_clip_start: rc_start,
2259 rounded_clip_len: rc_len,
2260 skip_delta: 0,
2261 });
2262 }
2263 }
2264 }
2265 DrawCommand::Circle { center, radius, .. } => {
2266 let r: f32 = radius * scale + 1.0;
2267 let bounds: Rect = Rect::new(
2268 center.get_x() * scale - r,
2269 center.get_y() * scale - r,
2270 r * 2.0,
2271 r * 2.0,
2272 );
2273 if let Some(vis) = bounds.intersect(active_clip) {
2274 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
2275 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2276 if y0 < y1 {
2277 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
2278 rounded_clip_stack.as_slice(),
2279 rounded_clips,
2280 vis,
2281 );
2282 if has_first_cmd {
2283 expand_opt_rect(prepped_fg_bounds, vis);
2284 }
2285 has_first_cmd = true;
2286 expand_opt_rect(prepped_bounds, vis);
2287 prepped.push(PreppedCommand {
2288 cmd_index,
2289 active_clip,
2290 y0,
2291 y1,
2292 opaque_cutout_h: Rect::default(),
2293 opaque_cutout_v: Rect::default(),
2294 glyph_run_start: 0,
2295 glyph_run_len: 0,
2296 caret_rect_idx: u32::MAX,
2297 rounded_clip_start: rc_start,
2298 rounded_clip_len: rc_len,
2299 skip_delta: 0,
2300 });
2301 }
2302 }
2303 }
2304 DrawCommand::Triangle { p0, p1, p2, .. } => {
2305 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.0;
2306 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.0;
2307 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.0;
2308 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.0;
2309 if let Some(vis) =
2310 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(active_clip)
2311 {
2312 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).min(phys_h);
2313 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).min(phys_h);
2314 if y0 < y1 {
2315 let (rc_start, rc_len): (u32, u16) = Self::collect_active_rounded(
2316 rounded_clip_stack.as_slice(),
2317 rounded_clips,
2318 vis,
2319 );
2320 if has_first_cmd {
2321 expand_opt_rect(prepped_fg_bounds, vis);
2322 }
2323 has_first_cmd = true;
2324 expand_opt_rect(prepped_bounds, vis);
2325 prepped.push(PreppedCommand {
2326 cmd_index,
2327 active_clip,
2328 y0,
2329 y1,
2330 opaque_cutout_h: Rect::default(),
2331 opaque_cutout_v: Rect::default(),
2332 glyph_run_start: 0,
2333 glyph_run_len: 0,
2334 caret_rect_idx: u32::MAX,
2335 rounded_clip_start: rc_start,
2336 rounded_clip_len: rc_len,
2337 skip_delta: 0,
2338 });
2339 }
2340 }
2341 }
2342 }
2343 }
2344 while let Some((_, _, opt_slot)) = clip_scopes.pop() {
2345 if let Some(slot_idx) = opt_slot {
2346 let span_len: usize = prepped.len().saturating_sub(slot_idx);
2347 if span_len <= 1 {
2348 prepped.truncate(slot_idx);
2349 } else if span_len == 2 {
2350 let only_cmd: PreppedCommand = prepped[slot_idx + 1];
2351 prepped[slot_idx] = only_cmd;
2352 let _: Option<PreppedCommand> = prepped.pop();
2353 } else {
2354 prepped[slot_idx].skip_delta = span_len as u32;
2355 }
2356 }
2357 }
2358 let culled_now: usize = Self::cull_occluded_prepped_commands(commands, prepped, scale);
2359 *culled_occluded_commands = culled_occluded_commands.saturating_add(culled_now as u64);
2360 glyph_atlas.set_slots_pinned(false);
2361 }
2362
2363 #[must_use]
2375 fn command_cull_bounds(cmd: &DrawCommand, active_clip: Rect, scale: f32) -> Option<Rect> {
2376 let raw: Rect = match cmd {
2377 DrawCommand::Clear(_) => active_clip,
2378 DrawCommand::FillRoundedRect { rect, .. }
2379 | DrawCommand::LinearGradientRect { rect, .. }
2380 | DrawCommand::Image { rect, .. }
2381 | DrawCommand::SpriteRegion { rect, .. }
2382 | DrawCommand::BackdropBlur { rect, .. } => snap_physical_rect(*rect, scale),
2383 DrawCommand::BoxShadow { rect, shadow, .. } => {
2384 let spread: f32 = shadow.get_spread_radius() * scale;
2385 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
2386 let sigma: f32 = (blur * 0.5).max(0.75);
2387 let pad: f32 = (sigma * 3.0).ceil();
2388 let base: Rect = snap_physical_rect(*rect, scale);
2389 Rect::new(
2390 base.get_x() + (shadow.get_offset_x() * scale).round() - spread - pad,
2391 base.get_y() + (shadow.get_offset_y() * scale).round() - spread - pad,
2392 (base.get_width() + spread * 2.0).max(1.0) + pad * 2.0,
2393 (base.get_height() + spread * 2.0).max(1.0) + pad * 2.0,
2394 )
2395 }
2396 DrawCommand::TextRun { rect, style, .. } => {
2397 let phys: Rect = Self::scale_rect(*rect, scale);
2398 let pad: f32 = style.get_font_size() * scale * 0.5 + 2.0;
2399 Rect::new(
2400 phys.get_x() - pad,
2401 phys.get_y() - pad,
2402 phys.get_width() + pad * 2.0,
2403 phys.get_height() + pad * 2.0,
2404 )
2405 }
2406 DrawCommand::TextCaret { content_rect, .. } => snap_physical_rect(*content_rect, scale),
2407 DrawCommand::Line {
2408 from, to, width, ..
2409 } => {
2410 let pad: f32 = (width * scale).max(1.0) + 2.0;
2411 let x0: f32 = from.get_x().min(to.get_x()) * scale - pad;
2412 let y0: f32 = from.get_y().min(to.get_y()) * scale - pad;
2413 let x1: f32 = from.get_x().max(to.get_x()) * scale + pad;
2414 let y1: f32 = from.get_y().max(to.get_y()) * scale + pad;
2415 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
2416 }
2417 DrawCommand::Circle { center, radius, .. } => {
2418 let r: f32 = radius * scale + 2.0;
2419 Rect::new(
2420 center.get_x() * scale - r,
2421 center.get_y() * scale - r,
2422 r * 2.0,
2423 r * 2.0,
2424 )
2425 }
2426 DrawCommand::Triangle { p0, p1, p2, .. } => {
2427 let x0: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 2.0;
2428 let y0: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 2.0;
2429 let x1: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 2.0;
2430 let y1: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 2.0;
2431 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
2432 }
2433 DrawCommand::PushClip(_)
2434 | DrawCommand::PushRoundedClip { .. }
2435 | DrawCommand::PopClip => {
2436 return None;
2437 }
2438 };
2439 raw.intersect(active_clip)
2440 }
2441
2442 fn cull_occluded_prepped_commands(
2454 commands: &[DrawCommand],
2455 prepped: &mut Vec<PreppedCommand>,
2456 scale: f32,
2457 ) -> usize {
2458 let len: usize = prepped.len();
2459 if len < 2 {
2460 return 0;
2461 }
2462 let mut keep: Vec<bool> = vec![true; len];
2463 let mut occluders: [Rect; OCCLUSION_MAX_OCCLUDERS] =
2464 [Rect::default(); OCCLUSION_MAX_OCCLUDERS];
2465 let mut occluder_count: usize = 0;
2466 let mut culled: usize = 0;
2467 for idx in (0..len).rev() {
2468 let item: PreppedCommand = prepped[idx];
2469 if item.get_cmd_index() == usize::MAX {
2470 continue;
2471 }
2472 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
2473 if matches!(cmd, DrawCommand::BackdropBlur { .. }) {
2474 occluder_count = 0;
2475 continue;
2476 }
2477 if occluder_count > 0
2478 && let Some(vis) = Self::command_cull_bounds(cmd, item.get_active_clip(), scale)
2479 {
2480 let covered: bool = occluders.iter().take(occluder_count).any(|occ: &Rect| {
2481 vis.get_x() >= occ.get_x()
2482 && vis.get_y() >= occ.get_y()
2483 && vis.right() <= occ.right()
2484 && vis.bottom() <= occ.bottom()
2485 });
2486 if covered {
2487 keep[idx] = false;
2488 culled += 1;
2489 continue;
2490 }
2491 }
2492 if item.get_rounded_clip_len() == 0
2493 && let DrawCommand::FillRoundedRect {
2494 rect,
2495 color,
2496 radius,
2497 border,
2498 } = cmd
2499 && color.get_a() == 255
2500 && radius.max_radius() <= 0.0
2501 && (border.get_width() <= 0.0 || border.get_color().get_a() == 255)
2502 {
2503 let phys: Rect = snap_physical_rect(*rect, scale);
2504 if let Some(occ) = phys.intersect(item.get_active_clip())
2505 && occ.get_width() >= 1.0
2506 && occ.get_height() >= 1.0
2507 {
2508 if occluder_count < OCCLUSION_MAX_OCCLUDERS {
2509 occluders[occluder_count] = occ;
2510 occluder_count += 1;
2511 } else {
2512 let occ_area: f32 = occ.get_width() * occ.get_height();
2513 let mut min_i: usize = 0;
2514 let mut min_area: f32 =
2515 occluders[0].get_width() * occluders[0].get_height();
2516 for (slot, occ_ref) in occluders
2517 .iter()
2518 .enumerate()
2519 .take(OCCLUSION_MAX_OCCLUDERS)
2520 .skip(1)
2521 {
2522 let area: f32 = occ_ref.get_width() * occ_ref.get_height();
2523 if area < min_area {
2524 min_area = area;
2525 min_i = slot;
2526 }
2527 }
2528 if occ_area > min_area {
2529 occluders[min_i] = occ;
2530 }
2531 }
2532 }
2533 }
2534 }
2535 if culled == 0 {
2536 return 0;
2537 }
2538 let mut compacted: Vec<PreppedCommand> = Vec::with_capacity(len.saturating_sub(culled));
2539 let mut open_sentinels: Vec<(usize, usize)> = Vec::new();
2540 for (old_idx, &kept) in keep.iter().enumerate() {
2541 while let Some(&(new_s, old_end)) = open_sentinels.last() {
2542 if old_end <= old_idx {
2543 let _: Option<(usize, usize)> = open_sentinels.pop();
2544 let span: u32 = (compacted.len().saturating_sub(new_s)).max(1) as u32;
2545 compacted[new_s].set_skip_delta(span);
2546 } else {
2547 break;
2548 }
2549 }
2550 if kept {
2551 let item: PreppedCommand = prepped[old_idx];
2552 if item.get_cmd_index() == usize::MAX {
2553 let old_end: usize = old_idx.saturating_add(item.get_skip_delta() as usize);
2554 open_sentinels.push((compacted.len(), old_end));
2555 }
2556 compacted.push(item);
2557 }
2558 }
2559 while let Some((new_s, _)) = open_sentinels.pop() {
2560 let span: u32 = (compacted.len().saturating_sub(new_s)).max(1) as u32;
2561 compacted[new_s].set_skip_delta(span);
2562 }
2563 *prepped = compacted;
2564 culled
2565 }
2566
2567 fn raster_backdrop_blur(
2581 band: &mut PixelBand<'_>,
2582 rect: Rect,
2583 radius: CornerRadius,
2584 blur_radius: f32,
2585 clip: Rect,
2586 ) -> usize {
2587 let Some(vis) = rect.intersect(clip) else {
2588 return 0;
2589 };
2590 let bw: u32 = band.width();
2591 let band_y0: u32 = band.y_offset();
2592 let band_y1: u32 = band.y_end();
2593 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(bw);
2594 let x1: u32 = (vis.right().ceil().max(0.0) as u32).clamp(x0, bw);
2595 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
2596 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(y0, band_y1);
2597 if x0 >= x1 || y0 >= y1 {
2598 return 0;
2599 }
2600 let rad: u32 = (blur_radius * 0.5).round().clamp(1.0, 24.0) as u32;
2601 let sx0: u32 = x0.saturating_sub(rad);
2602 let sx1: u32 = x1.saturating_add(rad).min(bw);
2603 let sy0: u32 = y0.saturating_sub(rad).max(band_y0);
2604 let sy1: u32 = y1.saturating_add(rad).min(band_y1);
2605 let sw: usize = (sx1 - sx0) as usize;
2606 let sh: usize = (sy1 - sy0) as usize;
2607 let mut src: Vec<[u8; 4]> = Vec::with_capacity(sw.saturating_mul(sh));
2608 for y in sy0..sy1 {
2609 for x in sx0..sx1 {
2610 src.push(band.get_pixel_rgba(x, y));
2611 }
2612 }
2613 let mut horiz: Vec<[u8; 4]> = vec![[0, 0, 0, 0]; sw.saturating_mul(sh)];
2614 let r_i: isize = rad as isize;
2615 let sw_i: isize = sw as isize;
2616 let sh_i: isize = sh as isize;
2617 for ly in 0..sh {
2618 let row_off: usize = ly * sw;
2619 for lx in 0..sw {
2620 let mut ar: u32 = 0;
2621 let mut ag: u32 = 0;
2622 let mut ab: u32 = 0;
2623 let mut aa: u32 = 0;
2624 let mut cnt: u32 = 0;
2625 let lx_i: isize = lx as isize;
2626 for dx in -r_i..=r_i {
2627 let nx: usize = (lx_i + dx).clamp(0, sw_i - 1) as usize;
2628 let px: [u8; 4] = src[row_off + nx];
2629 ar += px[0] as u32;
2630 ag += px[1] as u32;
2631 ab += px[2] as u32;
2632 aa += px[3] as u32;
2633 cnt += 1;
2634 }
2635 horiz[row_off + lx] = [
2636 (ar / cnt) as u8,
2637 (ag / cnt) as u8,
2638 (ab / cnt) as u8,
2639 (aa / cnt) as u8,
2640 ];
2641 }
2642 }
2643 let has_radius: bool = radius.max_radius() > 0.25;
2644 let cx: f32 = rect.get_x() + rect.get_width() * 0.5;
2645 let cy: f32 = rect.get_y() + rect.get_height() * 0.5;
2646 let hx: f32 = rect.get_width() * 0.5;
2647 let hy: f32 = rect.get_height() * 0.5;
2648 let mut shaded: usize = 0;
2649 for y in y0..y1 {
2650 let ly: isize = (y - sy0) as isize;
2651 for x in x0..x1 {
2652 if has_radius {
2653 let px_f: f32 = (x as f32) + 0.5 - cx;
2654 let py_f: f32 = (y as f32) + 0.5 - cy;
2655 let corner_r: f32 = if px_f < 0.0 {
2656 if py_f < 0.0 {
2657 radius.get_top_left()
2658 } else {
2659 radius.get_bottom_left()
2660 }
2661 } else if py_f < 0.0 {
2662 radius.get_top_right()
2663 } else {
2664 radius.get_bottom_right()
2665 }
2666 .min(hx)
2667 .min(hy)
2668 .max(0.0);
2669 let qx: f32 = px_f.abs() - (hx - corner_r);
2670 let qy: f32 = py_f.abs() - (hy - corner_r);
2671 let dist: f32 = qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - corner_r;
2672 if dist > 0.5 {
2673 continue;
2674 }
2675 }
2676 let lx: usize = (x - sx0) as usize;
2677 let mut ar: u32 = 0;
2678 let mut ag: u32 = 0;
2679 let mut ab: u32 = 0;
2680 let mut aa: u32 = 0;
2681 let mut cnt: u32 = 0;
2682 for dy in -r_i..=r_i {
2683 let ny: usize = (ly + dy).clamp(0, sh_i - 1) as usize;
2684 let px: [u8; 4] = horiz[ny * sw + lx];
2685 ar += px[0] as u32;
2686 ag += px[1] as u32;
2687 ab += px[2] as u32;
2688 aa += px[3] as u32;
2689 cnt += 1;
2690 }
2691 band.set_pixel_rgba(
2692 x,
2693 y,
2694 [
2695 (ar / cnt) as u8,
2696 (ag / cnt) as u8,
2697 (ab / cnt) as u8,
2698 (aa / cnt) as u8,
2699 ],
2700 );
2701 shaded += 1;
2702 }
2703 }
2704 shaded
2705 }
2706
2707 #[must_use]
2717 pub fn text_layout_cache_stats(&self) -> (u64, u64, u64, usize) {
2718 self.get_text_layout_cache().stats()
2719 }
2720
2721 fn resolve_text_run_glyphs(
2737 layout: &TextLayoutResult,
2738 rect: Rect,
2739 style: TextStyle,
2740 clip_dims: (Rect, u32, u32, f32),
2741 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
2742 out_glyphs: &mut Vec<PositionedGlyph>,
2743 line_scratch: &mut Vec<(u32, f32, u16, u16)>,
2744 ) -> (u32, u32) {
2745 let (clip, phys_w, phys_h, scale): (Rect, u32, u32, f32) = clip_dims;
2746 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
2747 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
2748 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).min(phys_h as i32);
2749 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(phys_w as i32);
2750 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).min(phys_h as i32);
2751 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
2752 return (0, 0);
2753 }
2754 let phys_font_size: f32 = style.get_font_size() * scale;
2755 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
2756 let bold: bool = style.get_weight().is_bold();
2757 let monospace: bool = style.get_family() == FontFamily::Monospace;
2758 let italic: bool = style.get_italic();
2759 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
2760 let ascii_table_idx: usize =
2761 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
2762 let line_h_phys: f32 = layout.get_line_height_px() * scale;
2763 let box_w_phys: f32 = rect.get_width() * scale;
2764 let letter_sp: f32 = style.get_letter_spacing() * scale;
2765 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
2766 let base_x_phys: f32 = (rect.get_x() * scale).round();
2767 let base_y_phys: f32 = (rect.get_y() * scale).round();
2768 let clip_x1_f: f32 = clip_x1 as f32;
2769 let clip_y0_f: f32 = clip_y0 as f32;
2770 let clip_y1_f: f32 = clip_y1 as f32;
2771 let align: TextAlign = style.get_align();
2772 let run_start: u32 = out_glyphs.len() as u32;
2773 for (line_idx, line) in layout.get_lines().iter().enumerate() {
2774 let line_off_y: f32 = ((line_idx as f32) * line_h_phys).round();
2775 let pen_y: f32 = base_y_phys + line_off_y;
2776 if (pen_y + line_h_phys) < clip_y0_f || pen_y > clip_y1_f {
2777 continue;
2778 }
2779 let line_str: &str = line.get_text().as_str();
2780 if align == TextAlign::Left {
2781 let mut pen_x: f32 = base_x_phys;
2782 if line_str.is_ascii() {
2783 for &byte in line_str.as_bytes() {
2784 if byte == b' ' {
2785 pen_x += space_step;
2786 continue;
2787 }
2788 if pen_x > clip_x1_f {
2789 break;
2790 }
2791 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
2792 ascii_table_idx,
2793 byte,
2794 key_meta,
2795 font_provider,
2796 );
2797 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
2798 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
2799 let gx0: i32 = pen_x.round() as i32;
2800 let gw: i32 = glyph.get_width() as i32;
2801 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
2802 let gh: u32 = glyph.get_height();
2803 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
2804 let gy0: i32 = (pen_y + glyph_v_off) as i32;
2805 if gy0 < clip_y1 && gy0 + (gh as i32) > clip_y0 {
2806 out_glyphs.push(PositionedGlyph {
2807 glyph_idx: slot,
2808 x: gx0,
2809 y: gy0,
2810 width: (gw as u32).min(u16::MAX as u32) as u16,
2811 height: gh.min(u16::MAX as u32) as u16,
2812 });
2813 }
2814 }
2815 pen_x += adv_phys;
2816 }
2817 } else {
2818 for ch in line_str.chars() {
2819 if ch == ' ' {
2820 pen_x += space_step;
2821 continue;
2822 }
2823 if pen_x > clip_x1_f {
2824 break;
2825 }
2826 let slot: u32 = if ch.is_ascii() {
2827 glyph_atlas.get_or_rasterize_ascii_slot_with(
2828 ascii_table_idx,
2829 ch as u8,
2830 key_meta,
2831 font_provider,
2832 )
2833 } else {
2834 let key: GlyphKey = GlyphKey {
2835 codepoint: ch,
2836 size_tenths,
2837 bold,
2838 monospace,
2839 italic,
2840 };
2841 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
2842 };
2843 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
2844 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
2845 let gx0: i32 = pen_x.round() as i32;
2846 let gw: i32 = glyph.get_width() as i32;
2847 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
2848 let gh: u32 = glyph.get_height();
2849 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
2850 let gy0: i32 = (pen_y + glyph_v_off) as i32;
2851 if gy0 < clip_y1 && gy0 + (gh as i32) > clip_y0 {
2852 out_glyphs.push(PositionedGlyph {
2853 glyph_idx: slot,
2854 x: gx0,
2855 y: gy0,
2856 width: (gw as u32).min(u16::MAX as u32) as u16,
2857 height: gh.min(u16::MAX as u32) as u16,
2858 });
2859 }
2860 }
2861 pen_x += adv_phys;
2862 }
2863 }
2864 } else {
2865 line_scratch.clear();
2866 let mut line_w_phys: f32 = 0.0;
2867 if line_str.is_ascii() {
2868 for &byte in line_str.as_bytes() {
2869 if byte == b' ' {
2870 line_w_phys += space_step;
2871 line_scratch.push((u32::MAX, space_step, 0, 0));
2872 } else {
2873 let slot: u32 = glyph_atlas.get_or_rasterize_ascii_slot_with(
2874 ascii_table_idx,
2875 byte,
2876 key_meta,
2877 font_provider,
2878 );
2879 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
2880 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
2881 line_w_phys += adv_phys;
2882 line_scratch.push((
2883 slot,
2884 adv_phys,
2885 glyph.get_width().min(u16::MAX as u32) as u16,
2886 glyph.get_height().min(u16::MAX as u32) as u16,
2887 ));
2888 }
2889 }
2890 } else {
2891 for ch in line_str.chars() {
2892 if ch == ' ' {
2893 line_w_phys += space_step;
2894 line_scratch.push((u32::MAX, space_step, 0, 0));
2895 } else {
2896 let slot: u32 = if ch.is_ascii() {
2897 glyph_atlas.get_or_rasterize_ascii_slot_with(
2898 ascii_table_idx,
2899 ch as u8,
2900 key_meta,
2901 font_provider,
2902 )
2903 } else {
2904 let key: GlyphKey = GlyphKey {
2905 codepoint: ch,
2906 size_tenths,
2907 bold,
2908 monospace,
2909 italic,
2910 };
2911 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
2912 };
2913 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(slot);
2914 let adv_phys: f32 = (glyph.get_advance() as f32).max(1.0) + letter_sp;
2915 line_w_phys += adv_phys;
2916 line_scratch.push((
2917 slot,
2918 adv_phys,
2919 glyph.get_width().min(u16::MAX as u32) as u16,
2920 glyph.get_height().min(u16::MAX as u32) as u16,
2921 ));
2922 }
2923 }
2924 }
2925 let align_x: f32 = if align == TextAlign::Center {
2926 ((box_w_phys - line_w_phys) * 0.5).max(0.0)
2927 } else {
2928 (box_w_phys - line_w_phys).max(0.0)
2929 };
2930 let mut pen_x: f32 = base_x_phys + align_x.round();
2931 for &(slot, adv_phys, gw_u16, gh_u16) in line_scratch.iter() {
2932 if slot == u32::MAX {
2933 pen_x += adv_phys;
2934 continue;
2935 }
2936 if pen_x > clip_x1_f {
2937 break;
2938 }
2939 let gx0: i32 = pen_x.round() as i32;
2940 let gw: i32 = gw_u16 as i32;
2941 let gh: i32 = gh_u16 as i32;
2942 if gx0 + gw > clip_x0 && gx0 < clip_x1 {
2943 let glyph_v_off: f32 = ((line_h_phys - (gh as f32)) * 0.5).round();
2944 let gy0: i32 = (pen_y + glyph_v_off) as i32;
2945 if gy0 < clip_y1 && gy0 + gh > clip_y0 {
2946 out_glyphs.push(PositionedGlyph {
2947 glyph_idx: slot,
2948 x: gx0,
2949 y: gy0,
2950 width: gw_u16,
2951 height: gh_u16,
2952 });
2953 }
2954 }
2955 pen_x += adv_phys;
2956 }
2957 }
2958 }
2959 let run_len: u32 = (out_glyphs.len() as u32).saturating_sub(run_start);
2960 (run_start, run_len)
2961 }
2962
2963 #[must_use]
2977 fn resolve_text_caret_rect(
2978 layout_opt: Option<&TextLayoutResult>,
2979 rects: (Rect, Rect),
2980 style: TextStyle,
2981 caret_opts: (f32, f32, bool),
2982 atlas_and_font: (&mut GlyphAtlas, &NativeSystemFont),
2983 ) -> Rect {
2984 let (text_rect, content_rect): (Rect, Rect) = rects;
2985 let (caret_height, scale, multiline): (f32, f32, bool) = caret_opts;
2986 let (glyph_atlas, font_provider): (&mut GlyphAtlas, &NativeSystemFont) = atlas_and_font;
2987 let phys_font_size: f32 = style.get_font_size() * scale;
2988 let size_tenths: u16 = (phys_font_size.clamp(6.0, 256.0) * 10.0 + 0.5) as u16;
2989 let bold: bool = style.get_weight().is_bold();
2990 let monospace: bool = style.get_family() == FontFamily::Monospace;
2991 let italic: bool = style.get_italic();
2992 let key_meta: (u16, bool, bool, bool) = (size_tenths, bold, monospace, italic);
2993 let letter_sp: f32 = style.get_letter_spacing() * scale;
2994 let space_step: f32 = measure_char_advance(' ', style) * scale + letter_sp;
2995 let (last_w_phys, line_idx, line_h_phys): (f32, usize, f32) =
2996 if let Some(layout) = layout_opt {
2997 let lh: f32 = layout.get_line_height_px() * scale;
2998 let idx: usize = layout.get_lines().len().saturating_sub(1);
2999 let w_phys: f32 = if let Some(line) = layout.get_lines().last() {
3000 let ascii_table_idx: usize =
3001 glyph_atlas.ascii_table_index(size_tenths, bold, monospace, italic);
3002 let mut acc: f32 = 0.0;
3003 for ch in line.get_text().chars() {
3004 if ch == ' ' {
3005 acc += space_step;
3006 } else {
3007 let slot: u32 = if ch.is_ascii() {
3008 glyph_atlas.get_or_rasterize_ascii_slot_with(
3009 ascii_table_idx,
3010 ch as u8,
3011 key_meta,
3012 font_provider,
3013 )
3014 } else {
3015 let key: GlyphKey = GlyphKey {
3016 codepoint: ch,
3017 size_tenths,
3018 bold,
3019 monospace,
3020 italic,
3021 };
3022 glyph_atlas.get_or_rasterize_slot_with(key, font_provider)
3023 };
3024 let adv: f32 =
3025 (glyph_atlas.glyph_by_slot(slot).get_advance() as f32).max(1.0);
3026 acc += adv + letter_sp;
3027 }
3028 }
3029 acc
3030 } else {
3031 0.0
3032 };
3033 (w_phys, idx, lh)
3034 } else {
3035 (
3036 0.0,
3037 0,
3038 (style.get_font_size() * style.get_line_height()).max(1.0) * scale,
3039 )
3040 };
3041 let caret_h_phys: f32 = (caret_height * scale).max(2.0);
3042 let caret_w_phys: f32 = (1.5 * scale).max(1.5);
3043 let min_x: f32 = content_rect.get_x() * scale;
3044 let max_x: f32 = (content_rect.right() * scale - caret_w_phys - 1.0).max(min_x);
3045 let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.5 * scale } else { 0.0 };
3046 let caret_x_phys: f32 = (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys)
3047 .min(max_x)
3048 .max(min_x);
3049 let caret_y_phys: f32 = if multiline {
3050 let raw_y: f32 = content_rect.get_y() * scale
3051 + (line_idx as f32) * line_h_phys
3052 + ((line_h_phys - caret_h_phys) * 0.5).max(0.0);
3053 raw_y
3054 .min(content_rect.bottom() * scale - caret_h_phys)
3055 .max(content_rect.get_y() * scale)
3056 } else {
3057 content_rect.get_y() * scale
3058 + ((content_rect.get_height() * scale - caret_h_phys) * 0.5).max(0.0)
3059 };
3060 Rect::new(
3061 caret_x_phys.round(),
3062 caret_y_phys.round(),
3063 caret_w_phys.round().max(1.0),
3064 caret_h_phys.round().max(2.0),
3065 )
3066 }
3067
3068 #[must_use]
3080 fn collect_active_rounded(
3081 stack: &[Option<RoundedClipMask>],
3082 out: &mut Vec<RoundedClipMask>,
3083 vis: Rect,
3084 ) -> (u32, u16) {
3085 let start: u32 = out.len() as u32;
3086 for entry in stack.iter().copied().flatten() {
3087 if rect_intersects_rounded_corners(vis, entry.get_rect(), entry.get_radius()) {
3088 out.push(entry);
3089 }
3090 }
3091 let len: u16 = (out.len() as u32)
3092 .saturating_sub(start)
3093 .min(u16::MAX as u32) as u16;
3094 (start, len)
3095 }
3096
3097 #[must_use]
3108 fn resolve_opaque_shadow_cutout(next_cmd: Option<&DrawCommand>, scale: f32) -> (Rect, Rect) {
3109 let Some(DrawCommand::FillRoundedRect {
3110 rect,
3111 color,
3112 radius,
3113 ..
3114 }) = next_cmd
3115 else {
3116 return (Rect::default(), Rect::default());
3117 };
3118 if color.get_a() != 255 {
3119 return (Rect::default(), Rect::default());
3120 }
3121 let phys: Rect = snap_physical_rect(*rect, scale);
3122 let r_max: f32 = Self::scale_radius(*radius, scale)
3123 .max_radius()
3124 .min(phys.get_width() * 0.5)
3125 .min(phys.get_height() * 0.5);
3126 let pad: f32 = 1.5;
3127 let h_w: f32 = (phys.get_width() - pad * 2.0).max(0.0);
3128 let h_h: f32 = (phys.get_height() - (r_max + pad) * 2.0).max(0.0);
3129 let cut_h: Rect = if h_w > 0.0 && h_h > 0.0 {
3130 Rect::new(phys.get_x() + pad, phys.get_y() + r_max + pad, h_w, h_h)
3131 } else {
3132 Rect::default()
3133 };
3134 let v_w: f32 = (phys.get_width() - (r_max + pad) * 2.0).max(0.0);
3135 let v_h: f32 = (phys.get_height() - pad * 2.0).max(0.0);
3136 let cut_v: Rect = if v_w > 0.0 && v_h > 0.0 {
3137 Rect::new(phys.get_x() + r_max + pad, phys.get_y() + pad, v_w, v_h)
3138 } else {
3139 Rect::default()
3140 };
3141 (cut_h, cut_v)
3142 }
3143
3144 fn save_single_cached_rounded_corners(
3159 band: &mut PixelBand<'_>,
3160 mask: RoundedClipMask,
3161 clip: Rect,
3162 band_bounds: (u32, u32, u32),
3163 corner_masks: &[CachedCornerMask],
3164 scratch: &mut BandCornerScratch,
3165 ) -> bool {
3166 let (fb_w, band_y0, band_y1): (u32, u32, u32) = band_bounds;
3167 let clip_x0: i32 = (clip.get_x().floor().max(0.0) as u32).min(fb_w) as i32;
3168 let clip_y0: i32 = (clip.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
3169 let clip_x1: i32 = (clip.right().ceil().max(0.0) as u32).min(fb_w) as i32;
3170 let clip_y1: i32 = (clip.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1) as i32;
3171 if clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
3172 return false;
3173 }
3174 let rect: Rect = mask.get_rect();
3175 let rx0_i: i32 = rect.get_x().round() as i32;
3176 let ry0_i: i32 = rect.get_y().round() as i32;
3177 let rx1_i: i32 = rect.right().round() as i32;
3178 let ry1_i: i32 = rect.bottom().round() as i32;
3179 let mask_ids: [u32; 4] = mask.get_corner_mask_ids();
3180 scratch.saved_bytes.clear();
3181 scratch.saved_rows.clear();
3182 for (q, &mask_id) in mask_ids.iter().enumerate() {
3183 if mask_id == u32::MAX {
3184 continue;
3185 }
3186 let Some(cm) = corner_masks.get(mask_id as usize) else {
3187 continue;
3188 };
3189 let dim_i: i32 = cm.dim as i32;
3190 let origin_x: i32 = if q == 0 || q == 3 {
3191 rx0_i
3192 } else {
3193 rx1_i - dim_i
3194 };
3195 let origin_y: i32 = if q == 0 || q == 1 {
3196 ry0_i
3197 } else {
3198 ry1_i - dim_i
3199 };
3200 let bx0: i32 = origin_x.max(clip_x0);
3201 let bx1: i32 = (origin_x + dim_i).min(clip_x1);
3202 let by0: i32 = origin_y.max(clip_y0);
3203 let by1: i32 = (origin_y + dim_i).min(clip_y1);
3204 if bx0 >= bx1 || by0 >= by1 {
3205 continue;
3206 }
3207 for y_i in by0..by1 {
3208 let my: usize = (y_i - origin_y) as usize;
3209 let span: CornerMaskRowSpan = cm.row_spans[my];
3210 if span.dirty_start >= span.dirty_end {
3211 continue;
3212 }
3213 let sx0_i: i32 = (origin_x + (span.dirty_start as i32)).max(bx0);
3214 let sx1_i: i32 = (origin_x + (span.dirty_end as i32)).min(bx1);
3215 if sx0_i >= sx1_i {
3216 continue;
3217 }
3218 let y: u32 = y_i as u32;
3219 let sx0: u32 = sx0_i as u32;
3220 let sx1: u32 = sx1_i as u32;
3221 if let Some(row) = band.row_slice_mut(y) {
3222 let b0: usize = (sx0 as usize) * 4;
3223 let b1: usize = (sx1 as usize) * 4;
3224 let byte_off: usize = scratch.saved_bytes.len();
3225 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
3226 scratch.saved_rows.push(SavedCornerRow {
3227 y,
3228 sx0,
3229 sx1,
3230 byte_off,
3231 mask_id,
3232 origin_x,
3233 origin_y,
3234 });
3235 }
3236 }
3237 }
3238 !scratch.saved_rows.is_empty()
3239 }
3240
3241 fn restore_single_cached_rounded_corners(
3249 band: &mut PixelBand<'_>,
3250 corner_masks: &[CachedCornerMask],
3251 scratch: &BandCornerScratch,
3252 ) {
3253 let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
3254 for entry in scratch.saved_rows.iter() {
3255 let Some(row) = band.row_slice_mut(entry.y) else {
3256 continue;
3257 };
3258 let cm: &CachedCornerMask = &corner_masks[entry.mask_id as usize];
3259 let dim: usize = cm.dim as usize;
3260 let my: usize = ((entry.y as i32) - entry.origin_y) as usize;
3261 let span: CornerMaskRowSpan = cm.row_spans[my];
3262 let sx0_i: i32 = entry.sx0 as i32;
3263 let sx1_i: i32 = entry.sx1 as i32;
3264 if span.ext_start < span.ext_end {
3265 let ex0: i32 = (entry.origin_x + (span.ext_start as i32)).max(sx0_i);
3266 let ex1: i32 = (entry.origin_x + (span.ext_end as i32)).min(sx1_i);
3267 if ex0 < ex1 {
3268 let dst_b0: usize = (ex0 as usize) * 4;
3269 let dst_b1: usize = (ex1 as usize) * 4;
3270 let src_b0: usize = entry.byte_off + ((ex0 - sx0_i) as usize) * 4;
3271 let src_b1: usize = src_b0 + (dst_b1 - dst_b0);
3272 row[dst_b0..dst_b1].copy_from_slice(&saved_bytes[src_b0..src_b1]);
3273 }
3274 }
3275 if span.aa_start < span.aa_end {
3276 let ax0: i32 = (entry.origin_x + (span.aa_start as i32)).max(sx0_i);
3277 let ax1: i32 = (entry.origin_x + (span.aa_end as i32)).min(sx1_i);
3278 if ax0 < ax1 {
3279 let cov_row: &[u8] = &cm.cov[my * dim..(my + 1) * dim];
3280 for x_i in ax0..ax1 {
3281 let mx: usize = (x_i - entry.origin_x) as usize;
3282 let cov_u8: u8 = cov_row[mx];
3283 if cov_u8 >= 16 {
3284 continue;
3285 }
3286 let dst_off: usize = (x_i as usize) * 4;
3287 let src_off: usize = entry.byte_off + ((x_i - sx0_i) as usize) * 4;
3288 let saved_rgba: [u8; 4] = [
3289 saved_bytes[src_off],
3290 saved_bytes[src_off + 1],
3291 saved_bytes[src_off + 2],
3292 saved_bytes[src_off + 3],
3293 ];
3294 if cov_u8 == 0 {
3295 row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
3296 } else {
3297 let cov: f32 = (cov_u8 as f32) * 0.0625;
3298 lerp_pixel_slice_from_saved_linear(
3299 &mut row[dst_off..dst_off + 4],
3300 saved_rgba,
3301 cov,
3302 );
3303 }
3304 }
3305 }
3306 }
3307 }
3308 }
3309
3310 pub(crate) fn render_band(
3325 band: &mut PixelBand<'_>,
3326 commands: &[DrawCommand],
3327 prepped: &[PreppedCommand],
3328 aux: BandAuxSlices<'_>,
3329 glyph_atlas: &GlyphAtlas,
3330 render_opts: (f32, AntialiasingMode),
3331 ) -> usize {
3332 let (positioned_glyphs, caret_rects, rounded_clips, corner_masks): (
3333 &[PositionedGlyph],
3334 &[Rect],
3335 &[RoundedClipMask],
3336 &[CachedCornerMask],
3337 ) = aux;
3338 let (scale, aa): (f32, AntialiasingMode) = render_opts;
3339 let band_y0: u32 = band.y_offset();
3340 let band_y1: u32 = band.y_end();
3341 let fb_w: u32 = band.width();
3342 let band_rect: Rect =
3343 Rect::new(0.0, band_y0 as f32, fb_w as f32, (band_y1 - band_y0) as f32);
3344 let has_any_rounded: bool = !rounded_clips.is_empty();
3345 let mut scratch: BandCornerScratch = if has_any_rounded {
3346 BAND_CORNER_SCRATCH
3347 .try_with(|cell: &RefCell<BandCornerScratch>| {
3348 cell.try_borrow_mut()
3349 .ok()
3350 .map(|mut guard: RefMut<'_, BandCornerScratch>| take(&mut *guard))
3351 })
3352 .ok()
3353 .flatten()
3354 .unwrap_or_default()
3355 } else {
3356 BandCornerScratch::default()
3357 };
3358 let mut shaded: usize = 0;
3359 let prepped_len: usize = prepped.len();
3360 let mut idx: usize = 0;
3361 while idx < prepped_len {
3362 let item: &PreppedCommand = &prepped[idx];
3363 if item.get_cmd_index() == usize::MAX {
3364 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
3365 idx += (item.get_skip_delta() as usize).max(1);
3366 } else {
3367 idx += 1;
3368 }
3369 continue;
3370 }
3371 idx += 1;
3372 if item.get_y1() <= band_y0 || item.get_y0() >= band_y1 {
3373 continue;
3374 }
3375 let Some(active_clip) = item.get_active_clip().intersect(band_rect) else {
3376 continue;
3377 };
3378 let rc_len: usize = item.get_rounded_clip_len() as usize;
3379 let item_masks: &[RoundedClipMask] = if rc_len > 0 {
3380 let start: usize = item.get_rounded_clip_start() as usize;
3381 let end: usize = start.saturating_add(rc_len).min(rounded_clips.len());
3382 &rounded_clips[start..end]
3383 } else {
3384 &[]
3385 };
3386 let mut corner_mode: u8 = 0;
3387 if item_masks.len() == 1 {
3388 let mask: RoundedClipMask = item_masks[0];
3389 let rect: Rect = mask.get_rect();
3390 let max_r: f32 = (rect.get_width() * 0.5)
3391 .min(rect.get_height() * 0.5)
3392 .max(0.0);
3393 let radius: CornerRadius = mask.get_radius();
3394 let radii: [f32; 4] = [
3395 radius.get_top_left().min(max_r),
3396 radius.get_top_right().min(max_r),
3397 radius.get_bottom_right().min(max_r),
3398 radius.get_bottom_left().min(max_r),
3399 ];
3400 let ids: [u32; 4] = mask.get_corner_mask_ids();
3401 let all_cached: bool = radii
3402 .iter()
3403 .zip(ids.iter())
3404 .all(|(&r, &id): (&f32, &u32)| r <= 0.25 || (id as usize) < corner_masks.len());
3405 if all_cached {
3406 if Self::save_single_cached_rounded_corners(
3407 band,
3408 mask,
3409 active_clip,
3410 (fb_w, band_y0, band_y1),
3411 corner_masks,
3412 &mut scratch,
3413 ) {
3414 corner_mode = 1;
3415 }
3416 } else {
3417 scratch.corner_boxes.clear();
3418 scratch.saved_bytes.clear();
3419 collect_rounded_clip_boxes(
3420 mask,
3421 active_clip,
3422 (fb_w, band_y0, band_y1),
3423 &mut scratch.corner_boxes,
3424 );
3425 if !scratch.corner_boxes.is_empty() {
3426 for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
3427 let b0: usize = (bx0 as usize) * 4;
3428 let b1: usize = (bx1 as usize) * 4;
3429 for y in by0..by1 {
3430 if let Some(row) = band.row_slice_mut(y) {
3431 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
3432 }
3433 }
3434 }
3435 corner_mode = 2;
3436 }
3437 }
3438 } else if !item_masks.is_empty() {
3439 scratch.corner_boxes.clear();
3440 scratch.saved_bytes.clear();
3441 for mask in item_masks.iter().copied() {
3442 collect_rounded_clip_boxes(
3443 mask,
3444 active_clip,
3445 (fb_w, band_y0, band_y1),
3446 &mut scratch.corner_boxes,
3447 );
3448 }
3449 if !scratch.corner_boxes.is_empty() {
3450 for &(bx0, by0, bx1, by1) in scratch.corner_boxes.iter() {
3451 let b0: usize = (bx0 as usize) * 4;
3452 let b1: usize = (bx1 as usize) * 4;
3453 for y in by0..by1 {
3454 if let Some(row) = band.row_slice_mut(y) {
3455 scratch.saved_bytes.extend_from_slice(&row[b0..b1]);
3456 }
3457 }
3458 }
3459 corner_mode = 2;
3460 }
3461 }
3462 let cmd: &DrawCommand = &commands[item.get_cmd_index()];
3463 shaded += match cmd {
3464 DrawCommand::Clear(color) => {
3465 if active_clip.get_x() <= 0.0
3466 && active_clip.get_width() >= (band.width() as f32)
3467 && active_clip.get_y() <= (band_y0 as f32)
3468 && active_clip.bottom() >= (band_y1 as f32)
3469 {
3470 band.clear(*color);
3471 (band.width() as usize) * ((band_y1 - band_y0) as usize)
3472 } else {
3473 Self::fill_rect_clipped(band, active_clip, *color, active_clip)
3474 }
3475 }
3476 DrawCommand::FillRoundedRect {
3477 rect,
3478 color,
3479 radius,
3480 border,
3481 } => {
3482 let phys_rect: Rect = snap_physical_rect(*rect, scale);
3483 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
3484 let bw: f32 = if border.get_width() > 0.0 {
3485 (border.get_width() * scale).max(1.0)
3486 } else {
3487 0.0
3488 };
3489 let phys_border: Border = Border::new(bw, border.get_color());
3490 Self::raster_rounded_rect(
3491 band,
3492 phys_rect,
3493 *color,
3494 phys_radius,
3495 phys_border,
3496 active_clip,
3497 aa,
3498 )
3499 }
3500 DrawCommand::LinearGradientRect {
3501 rect,
3502 gradient,
3503 radius,
3504 } => {
3505 let phys_rect: Rect = snap_physical_rect(*rect, scale);
3506 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
3507 Self::raster_gradient_rect(
3508 band,
3509 phys_rect,
3510 *gradient,
3511 phys_radius,
3512 active_clip,
3513 aa,
3514 )
3515 }
3516 DrawCommand::BoxShadow {
3517 rect,
3518 radius,
3519 shadow,
3520 } => {
3521 let spread: f32 = shadow.get_spread_radius() * scale;
3522 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
3523 let sigma: f32 = (blur * 0.5).max(0.75);
3524 let pad: f32 = (sigma * 3.0).ceil();
3525 let base_rect: Rect = snap_physical_rect(*rect, scale);
3526 let caster_rect: Rect = Rect::new(
3527 base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread,
3528 base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread,
3529 (base_rect.get_width() + spread * 2.0).max(1.0),
3530 (base_rect.get_height() + spread * 2.0).max(1.0),
3531 );
3532 let shadow_rect: Rect = Rect::new(
3533 caster_rect.get_x() - pad,
3534 caster_rect.get_y() - pad,
3535 caster_rect.get_width() + pad * 2.0,
3536 caster_rect.get_height() + pad * 2.0,
3537 );
3538 let raw_r: CornerRadius = Self::scale_radius(*radius, scale);
3539 let phys_radius: CornerRadius = CornerRadius::new(
3540 (raw_r.get_top_left() + spread).max(0.0),
3541 (raw_r.get_top_right() + spread).max(0.0),
3542 (raw_r.get_bottom_right() + spread).max(0.0),
3543 (raw_r.get_bottom_left() + spread).max(0.0),
3544 );
3545 Self::raster_shadow(
3546 band,
3547 (shadow_rect, caster_rect, active_clip),
3548 phys_radius,
3549 sigma,
3550 shadow.get_color(),
3551 (item.get_opaque_cutout_h(), item.get_opaque_cutout_v()),
3552 )
3553 }
3554 DrawCommand::BackdropBlur {
3555 rect,
3556 radius,
3557 blur_radius,
3558 } => {
3559 let phys_rect: Rect = snap_physical_rect(*rect, scale);
3560 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
3561 let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 48.0);
3562 Self::raster_backdrop_blur(band, phys_rect, phys_radius, phys_blur, active_clip)
3563 }
3564 DrawCommand::TextRun { style, .. } => {
3565 let g_start: usize = item.get_glyph_run_start() as usize;
3566 let g_len: usize = item.get_glyph_run_len() as usize;
3567 if let Some(run_slice) = positioned_glyphs.get(g_start..g_start + g_len) {
3568 Self::raster_text_run_band(
3569 band,
3570 run_slice,
3571 style.get_color(),
3572 active_clip,
3573 glyph_atlas,
3574 )
3575 } else {
3576 0
3577 }
3578 }
3579 DrawCommand::TextCaret { color, .. } => {
3580 let cidx: usize = item.get_caret_rect_idx() as usize;
3581 if let Some(&caret_rect) = caret_rects.get(cidx) {
3582 Self::raster_rounded_rect(
3583 band,
3584 caret_rect,
3585 *color,
3586 CornerRadius::all(0.5 * scale),
3587 Border::default(),
3588 active_clip,
3589 aa,
3590 )
3591 } else {
3592 0
3593 }
3594 }
3595 DrawCommand::Image {
3596 rect,
3597 buffer,
3598 radius,
3599 } => {
3600 let phys_rect: Rect = snap_physical_rect(*rect, scale);
3601 let phys_radius: CornerRadius = Self::scale_radius(*radius, scale);
3602 Self::raster_image(band, phys_rect, buffer, phys_radius, active_clip, aa)
3603 }
3604 DrawCommand::Line {
3605 from,
3606 to,
3607 color,
3608 width,
3609 } => {
3610 let p0: Point = Point::new(from.get_x() * scale, from.get_y() * scale);
3611 let p1: Point = Point::new(to.get_x() * scale, to.get_y() * scale);
3612 Self::raster_line(
3613 band,
3614 p0,
3615 p1,
3616 *color,
3617 (width * scale).max(1.0),
3618 active_clip,
3619 aa,
3620 )
3621 }
3622 DrawCommand::Circle {
3623 center,
3624 radius,
3625 color,
3626 } => {
3627 let c: Point = Point::new(center.get_x() * scale, center.get_y() * scale);
3628 Self::raster_circle(band, c, radius * scale, *color, active_clip, aa)
3629 }
3630 DrawCommand::Triangle { p0, p1, p2, color } => {
3631 let v0: Point = Point::new(p0.get_x() * scale, p0.get_y() * scale);
3632 let v1: Point = Point::new(p1.get_x() * scale, p1.get_y() * scale);
3633 let v2: Point = Point::new(p2.get_x() * scale, p2.get_y() * scale);
3634 Self::raster_triangle(band, v0, v1, v2, *color, active_clip, aa)
3635 }
3636 DrawCommand::SpriteRegion {
3637 rect,
3638 buffer,
3639 src_rect,
3640 tint,
3641 } => {
3642 let phys_rect: Rect = snap_physical_rect(*rect, scale);
3643 Self::raster_sprite_region(
3644 band,
3645 phys_rect,
3646 buffer,
3647 *src_rect,
3648 *tint,
3649 active_clip,
3650 aa,
3651 )
3652 }
3653 DrawCommand::PushClip(_)
3654 | DrawCommand::PushRoundedClip { .. }
3655 | DrawCommand::PopClip => 0,
3656 };
3657 if corner_mode == 1 {
3658 Self::restore_single_cached_rounded_corners(band, corner_masks, &scratch);
3659 } else if corner_mode == 2 {
3660 let multi_mask: bool = item_masks.len() > 1;
3661 let saved_bytes: &[u8] = scratch.saved_bytes.as_slice();
3662 let mut byte_cursor: usize = 0;
3663 for (box_idx, &(bx0, by0, bx1, by1)) in scratch.corner_boxes.iter().enumerate() {
3664 for y in by0..by1 {
3665 let Some(row) = band.row_slice_mut(y) else {
3666 byte_cursor += ((bx1 - bx0) as usize) * 4;
3667 continue;
3668 };
3669 for x in bx0..bx1 {
3670 let saved_rgba: [u8; 4] = [
3671 saved_bytes[byte_cursor],
3672 saved_bytes[byte_cursor + 1],
3673 saved_bytes[byte_cursor + 2],
3674 saved_bytes[byte_cursor + 3],
3675 ];
3676 byte_cursor += 4;
3677 if multi_mask
3678 && scratch.corner_boxes[..box_idx].iter().any(
3679 |&(px0, py0, px1, py1): &(u32, u32, u32, u32)| {
3680 x >= px0 && x < px1 && y >= py0 && y < py1
3681 },
3682 )
3683 {
3684 continue;
3685 }
3686 let mut cov: f32 = 1.0;
3687 for mask in item_masks.iter().copied() {
3688 cov *= rounded_clip_coverage_cached(x, y, mask, corner_masks, aa);
3689 if cov <= 0.0005 {
3690 break;
3691 }
3692 }
3693 let dst_off: usize = (x as usize) * 4;
3694 if cov <= 0.0005 {
3695 row[dst_off..dst_off + 4].copy_from_slice(&saved_rgba);
3696 } else if cov < 0.9995 {
3697 lerp_pixel_slice_from_saved_linear(
3698 &mut row[dst_off..dst_off + 4],
3699 saved_rgba,
3700 cov,
3701 );
3702 }
3703 }
3704 }
3705 }
3706 }
3707 }
3708 if has_any_rounded {
3709 let _: bool = BAND_CORNER_SCRATCH
3710 .try_with(|cell: &RefCell<BandCornerScratch>| {
3711 if let Ok(mut guard) = cell.try_borrow_mut() {
3712 *guard = scratch;
3713 }
3714 })
3715 .is_ok();
3716 }
3717 shaded
3718 }
3719
3720 fn scale_rect(rect: Rect, scale: f32) -> Rect {
3731 Rect::new(
3732 rect.get_x() * scale,
3733 rect.get_y() * scale,
3734 rect.get_width() * scale,
3735 rect.get_height() * scale,
3736 )
3737 }
3738
3739 fn scale_radius(radius: CornerRadius, scale: f32) -> CornerRadius {
3750 CornerRadius::new(
3751 radius.get_top_left() * scale,
3752 radius.get_top_right() * scale,
3753 radius.get_bottom_right() * scale,
3754 radius.get_bottom_left() * scale,
3755 )
3756 }
3757
3758 fn fill_rect_clipped(band: &mut PixelBand<'_>, rect: Rect, color: Color, clip: Rect) -> usize {
3771 if color.get_a() == 0 {
3772 return 0;
3773 }
3774 let Some(vis) = rect.intersect(clip) else {
3775 return 0;
3776 };
3777 let fb_w: u32 = band.width();
3778 let band_y0: u32 = band.y_offset();
3779 let band_y1: u32 = band.y_end();
3780 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
3781 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
3782 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
3783 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
3784 if x0 >= x1 || y0 >= y1 {
3785 return 0;
3786 }
3787 let span_len: usize = (x1 - x0) as usize;
3788 let rows: usize = (y1 - y0) as usize;
3789 let sa: u8 = color.get_a();
3790 if sa == 255 {
3791 band.fill_rect_opaque_preclipped(
3792 x0,
3793 x1,
3794 y0,
3795 y1,
3796 [color.get_r(), color.get_g(), color.get_b(), 255],
3797 );
3798 } else if let Some((rows_buf, row_stride)) = band.rows_slice_mut(y0, y1) {
3799 let bx0: usize = (x0 as usize) * 4;
3800 let bx1: usize = (x1 as usize) * 4;
3801 if span_len.saturating_mul(rows) >= 512 {
3802 let luts: ([u8; 256], [u8; 256], [u8; 256], [u8; 256]) =
3803 build_linear_blend_luts(color);
3804 for row in rows_buf.chunks_exact_mut(row_stride) {
3805 fill_span_linear_luts_slice(&mut row[bx0..bx1], &luts);
3806 }
3807 } else {
3808 for row in rows_buf.chunks_exact_mut(row_stride) {
3809 fill_span_linear_slice(&mut row[bx0..bx1], color);
3810 }
3811 }
3812 }
3813 span_len * rows
3814 }
3815
3816 #[must_use]
3831 fn build_vertical_edge_strip(
3832 x_span: (u32, u32),
3833 geom: (f32, f32, f32, f32),
3834 colors: (Color, Border),
3835 lin_colors: ([f32; 4], [f32; 4]),
3836 aa: AntialiasingMode,
3837 out: &mut [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP],
3838 ) -> (usize, usize) {
3839 let (x_start, x_end): (u32, u32) = x_span;
3840 let (cx, half_w, half_h, bw): (f32, f32, f32, f32) = geom;
3841 let (color, border): (Color, Border) = colors;
3842 let (fill_lin, border_lin): ([f32; 4], [f32; 4]) = lin_colors;
3843 let has_border: bool = bw > 0.0 && border.get_color().get_a() > 0;
3844 let inner_hw: f32 = (half_w - bw).max(0.0);
3845 let inner_hh: f32 = (half_h - bw).max(0.0);
3846 let mut len: usize = 0;
3847 let mut shaded: usize = 0;
3848 for x in x_start..x_end {
3849 let px: f32 = (x as f32) + 0.5 - cx;
3850 let dist: f32 = px.abs() - half_w;
3851 if dist > 0.85 {
3852 continue;
3853 }
3854 if !has_border {
3855 if dist < -0.85 {
3856 let sa: u8 = color.get_a();
3857 if sa > 0 {
3858 let a: f32 = (sa as f32) * (1.0 / 255.0);
3859 out[len] = EdgeBlendSample {
3860 x,
3861 rgba: [color.get_r(), color.get_g(), color.get_b(), 255],
3862 sr_a: fill_lin[0] * a,
3863 sg_a: fill_lin[1] * a,
3864 sb_a: fill_lin[2] * a,
3865 inv_a: 1.0 - a,
3866 sa_u32: sa as u32,
3867 is_opaque: sa == 255,
3868 };
3869 len += 1;
3870 shaded += 1;
3871 }
3872 continue;
3873 }
3874 let outer_cov: f32 = sdf_coverage(dist, aa);
3875 if outer_cov > 0.0 && color.get_a() > 0 {
3876 let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * outer_cov;
3877 shaded += 1;
3878 if alpha_f > 0.0002 {
3879 let a: f32 = alpha_f.clamp(0.0, 1.0);
3880 out[len] = EdgeBlendSample {
3881 x,
3882 rgba: [color.get_r(), color.get_g(), color.get_b(), 255],
3883 sr_a: fill_lin[0] * a,
3884 sg_a: fill_lin[1] * a,
3885 sb_a: fill_lin[2] * a,
3886 inv_a: 1.0 - a,
3887 sa_u32: (a * 255.0) as u32,
3888 is_opaque: a >= 0.9995,
3889 };
3890 len += 1;
3891 }
3892 }
3893 continue;
3894 }
3895 if dist < -(bw + 0.85) {
3896 let sa: u8 = color.get_a();
3897 if sa > 0 {
3898 let a: f32 = (sa as f32) * (1.0 / 255.0);
3899 out[len] = EdgeBlendSample {
3900 x,
3901 rgba: [color.get_r(), color.get_g(), color.get_b(), 255],
3902 sr_a: fill_lin[0] * a,
3903 sg_a: fill_lin[1] * a,
3904 sb_a: fill_lin[2] * a,
3905 inv_a: 1.0 - a,
3906 sa_u32: sa as u32,
3907 is_opaque: sa == 255,
3908 };
3909 len += 1;
3910 shaded += 1;
3911 }
3912 continue;
3913 }
3914 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
3915 px.abs() - inner_hw
3916 } else {
3917 2.0
3918 };
3919 if dist < -0.85 && inner_dist > 0.85 {
3920 let bc: Color = border.get_color();
3921 let sa: u8 = bc.get_a();
3922 let a: f32 = (sa as f32) * (1.0 / 255.0);
3923 out[len] = EdgeBlendSample {
3924 x,
3925 rgba: [bc.get_r(), bc.get_g(), bc.get_b(), 255],
3926 sr_a: border_lin[0] * a,
3927 sg_a: border_lin[1] * a,
3928 sb_a: border_lin[2] * a,
3929 inv_a: 1.0 - a,
3930 sa_u32: sa as u32,
3931 is_opaque: sa == 255,
3932 };
3933 len += 1;
3934 shaded += 1;
3935 continue;
3936 }
3937 let outer_cov: f32 = sdf_coverage(dist, aa);
3938 if outer_cov <= 0.0 {
3939 continue;
3940 }
3941 let inner_cov: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
3942 sdf_coverage(inner_dist, aa)
3943 } else {
3944 0.0
3945 };
3946 let mixed: Color =
3947 composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
3948 let sa: u8 = mixed.get_a();
3949 if sa > 0 {
3950 let a: f32 = (sa as f32) * (1.0 / 255.0);
3951 out[len] = EdgeBlendSample {
3952 x,
3953 rgba: [mixed.get_r(), mixed.get_g(), mixed.get_b(), 255],
3954 sr_a: SRGB_TO_LIN_LUT[mixed.get_r() as usize] * a,
3955 sg_a: SRGB_TO_LIN_LUT[mixed.get_g() as usize] * a,
3956 sb_a: SRGB_TO_LIN_LUT[mixed.get_b() as usize] * a,
3957 inv_a: 1.0 - a,
3958 sa_u32: sa as u32,
3959 is_opaque: sa == 255,
3960 };
3961 len += 1;
3962 shaded += 1;
3963 }
3964 }
3965 (len, shaded)
3966 }
3967
3968 fn raster_rounded_rect(
3984 band: &mut PixelBand<'_>,
3985 rect: Rect,
3986 color: Color,
3987 radius: CornerRadius,
3988 border: Border,
3989 clip: Rect,
3990 aa: AntialiasingMode,
3991 ) -> usize {
3992 let Some(vis) = rect.intersect(clip) else {
3993 return 0;
3994 };
3995 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
3996 if radius.max_radius() <= 0.0 && !has_border {
3997 return Self::fill_rect_clipped(band, rect, color, clip);
3998 }
3999 let half_w: f32 = rect.get_width() * 0.5;
4000 let half_h: f32 = rect.get_height() * 0.5;
4001 let cx: f32 = rect.get_x() + half_w;
4002 let cy: f32 = rect.get_y() + half_h;
4003 let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
4004 let fb_w: u32 = band.width();
4005 let band_y0: u32 = band.y_offset();
4006 let band_y1: u32 = band.y_end();
4007 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
4008 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
4009 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
4010 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
4011 if x0 >= x1 || y0 >= y1 {
4012 return 0;
4013 }
4014 let effective_r: f32 = radius.max_radius().min(half_w).min(half_h);
4015 let safe_inset: f32 = effective_r.max(border_w) + 1.5;
4016 let edge_inset: f32 = border_w + 1.5;
4017 let iy0: u32 = ((rect.get_y() + safe_inset).ceil().max(0.0) as u32).clamp(y0, y1);
4018 let iy1: u32 = ((rect.bottom() - safe_inset).floor().max(0.0) as u32).clamp(y0, y1);
4019 let ix0: u32 = ((rect.get_x() + edge_inset).ceil().max(0.0) as u32).clamp(x0, x1);
4020 let ix1: u32 = ((rect.right() - edge_inset).floor().max(0.0) as u32).clamp(x0, x1);
4021 let cx0: u32 = ((rect.get_x() + safe_inset).ceil().max(0.0) as u32).clamp(x0, x1);
4022 let cx1: u32 = ((rect.right() - safe_inset).floor().max(0.0) as u32).clamp(x0, x1);
4023 let has_interior: bool = iy0 < iy1 && ix0 < ix1;
4024 let has_center_band: bool = cx0 < cx1;
4025 let fill_lin: [f32; 4] = [
4026 SRGB_TO_LIN_LUT[color.get_r() as usize],
4027 SRGB_TO_LIN_LUT[color.get_g() as usize],
4028 SRGB_TO_LIN_LUT[color.get_b() as usize],
4029 (color.get_a() as f32) / 255.0,
4030 ];
4031 let bc: Color = border.get_color();
4032 let border_lin: [f32; 4] = [
4033 SRGB_TO_LIN_LUT[bc.get_r() as usize],
4034 SRGB_TO_LIN_LUT[bc.get_g() as usize],
4035 SRGB_TO_LIN_LUT[bc.get_b() as usize],
4036 (bc.get_a() as f32) / 255.0,
4037 ];
4038 let interior_luts: Option<RgbaLutQuad> = if has_interior
4039 && color.get_a() > 0
4040 && color.get_a() < 255
4041 && ((ix1 - ix0) as usize).saturating_mul((iy1 - iy0) as usize) >= 512
4042 {
4043 Some(build_linear_blend_luts(color))
4044 } else {
4045 None
4046 };
4047 let mut shaded: usize = 0;
4048 if has_interior {
4049 for y in y0..iy0 {
4050 let py: f32 = (y as f32) + 0.5 - cy;
4051 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
4052 if has_center_band {
4053 shaded += Self::raster_rounded_corner_band_row(
4054 band,
4055 y,
4056 (x0, cx0, cx1, x1),
4057 box_geom,
4058 radius,
4059 (color, border, fill_lin, border_lin),
4060 (interior_luts.as_ref(), aa),
4061 );
4062 } else if let Some(row) = band.row_slice_mut(y) {
4063 for x in x0..x1 {
4064 shaded += Self::shade_rounded_pixel_row(
4065 row,
4066 x,
4067 box_geom,
4068 radius,
4069 (color, border, fill_lin, border_lin),
4070 aa,
4071 );
4072 }
4073 }
4074 }
4075 let use_1d_strip: bool = ((ix0 - x0) as usize) <= ROUNDED_EDGE_STRIP_CAP
4076 && ((x1 - ix1) as usize) <= ROUNDED_EDGE_STRIP_CAP;
4077 if use_1d_strip {
4078 let mut left_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
4079 [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
4080 let mut right_strip: [EdgeBlendSample; ROUNDED_EDGE_STRIP_CAP] =
4081 [EdgeBlendSample::default(); ROUNDED_EDGE_STRIP_CAP];
4082 let (left_len, left_shaded): (usize, usize) = if x0 < ix0 {
4083 Self::build_vertical_edge_strip(
4084 (x0, ix0),
4085 (cx, half_w, half_h, border_w),
4086 (color, border),
4087 (fill_lin, border_lin),
4088 aa,
4089 &mut left_strip,
4090 )
4091 } else {
4092 (0, 0)
4093 };
4094 let (right_len, right_shaded): (usize, usize) = if ix1 < x1 {
4095 Self::build_vertical_edge_strip(
4096 (ix1, x1),
4097 (cx, half_w, half_h, border_w),
4098 (color, border),
4099 (fill_lin, border_lin),
4100 aa,
4101 &mut right_strip,
4102 )
4103 } else {
4104 (0, 0)
4105 };
4106 let left_slice: &[EdgeBlendSample] = &left_strip[..left_len];
4107 let right_slice: &[EdgeBlendSample] = &right_strip[..right_len];
4108 let edge_shaded: usize = left_shaded + right_shaded;
4109 let has_edges: bool = left_len > 0 || right_len > 0;
4110 let fill_visible: bool = color.get_a() > 0;
4111 let fill_opaque: bool = color.get_a() == 255;
4112 let fill_rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
4113 let interior_span: usize = (ix1 - ix0) as usize;
4114 let ix0_b: usize = (ix0 as usize) * 4;
4115 let ix1_b: usize = (ix1 as usize) * 4;
4116 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
4117 for row in rows_buf.chunks_exact_mut(row_stride) {
4118 if fill_visible {
4119 if fill_opaque {
4120 fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
4121 } else if let Some(ref luts) = interior_luts {
4122 fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
4123 } else {
4124 fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
4125 }
4126 shaded += interior_span;
4127 }
4128 if has_edges {
4129 if left_len > 0 {
4130 apply_edge_strip_row(row, left_slice);
4131 }
4132 if right_len > 0 {
4133 apply_edge_strip_row(row, right_slice);
4134 }
4135 shaded += edge_shaded;
4136 }
4137 }
4138 }
4139 } else {
4140 let fill_visible: bool = color.get_a() > 0;
4141 let fill_opaque: bool = color.get_a() == 255;
4142 let fill_rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
4143 let interior_span: usize = (ix1 - ix0) as usize;
4144 let ix0_b: usize = (ix0 as usize) * 4;
4145 let ix1_b: usize = (ix1 as usize) * 4;
4146 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(iy0, iy1) {
4147 for (y, row) in (iy0..iy1).zip(rows_buf.chunks_exact_mut(row_stride)) {
4148 let py: f32 = (y as f32) + 0.5 - cy;
4149 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
4150 if fill_visible {
4151 if fill_opaque {
4152 fill_rgba_span_32(&mut row[ix0_b..ix1_b], fill_rgba);
4153 } else if let Some(ref luts) = interior_luts {
4154 fill_span_linear_luts_slice(&mut row[ix0_b..ix1_b], luts);
4155 } else {
4156 fill_span_linear_slice(&mut row[ix0_b..ix1_b], color);
4157 }
4158 shaded += interior_span;
4159 }
4160 for x in x0..ix0 {
4161 shaded += Self::shade_rounded_pixel_row(
4162 row,
4163 x,
4164 box_geom,
4165 radius,
4166 (color, border, fill_lin, border_lin),
4167 aa,
4168 );
4169 }
4170 for x in ix1..x1 {
4171 shaded += Self::shade_rounded_pixel_row(
4172 row,
4173 x,
4174 box_geom,
4175 radius,
4176 (color, border, fill_lin, border_lin),
4177 aa,
4178 );
4179 }
4180 }
4181 }
4182 }
4183 for y in iy1..y1 {
4184 let py: f32 = (y as f32) + 0.5 - cy;
4185 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
4186 if has_center_band {
4187 shaded += Self::raster_rounded_corner_band_row(
4188 band,
4189 y,
4190 (x0, cx0, cx1, x1),
4191 box_geom,
4192 radius,
4193 (color, border, fill_lin, border_lin),
4194 (interior_luts.as_ref(), aa),
4195 );
4196 } else if let Some(row) = band.row_slice_mut(y) {
4197 for x in x0..x1 {
4198 shaded += Self::shade_rounded_pixel_row(
4199 row,
4200 x,
4201 box_geom,
4202 radius,
4203 (color, border, fill_lin, border_lin),
4204 aa,
4205 );
4206 }
4207 }
4208 }
4209 return shaded;
4210 }
4211 for y in y0..y1 {
4212 let py: f32 = (y as f32) + 0.5 - cy;
4213 let box_geom: (f32, f32, f32, f32) = (cx, py, half_w, half_h);
4214 if has_center_band {
4215 shaded += Self::raster_rounded_corner_band_row(
4216 band,
4217 y,
4218 (x0, cx0, cx1, x1),
4219 box_geom,
4220 radius,
4221 (color, border, fill_lin, border_lin),
4222 (interior_luts.as_ref(), aa),
4223 );
4224 } else if let Some(row) = band.row_slice_mut(y) {
4225 for x in x0..x1 {
4226 shaded += Self::shade_rounded_pixel_row(
4227 row,
4228 x,
4229 box_geom,
4230 radius,
4231 (color, border, fill_lin, border_lin),
4232 aa,
4233 );
4234 }
4235 }
4236 }
4237 shaded
4238 }
4239
4240 #[inline(always)]
4256 fn raster_rounded_corner_band_row(
4257 band: &mut PixelBand<'_>,
4258 y: u32,
4259 x_bounds: (u32, u32, u32, u32),
4260 geom: (f32, f32, f32, f32),
4261 radius: CornerRadius,
4262 style_colors: (Color, Border, [f32; 4], [f32; 4]),
4263 opts: (Option<&RgbaLutQuad>, AntialiasingMode),
4264 ) -> usize {
4265 let (interior_luts, aa): (Option<&RgbaLutQuad>, AntialiasingMode) = opts;
4266 let Some(row) = band.row_slice_mut(y) else {
4267 return 0;
4268 };
4269 let (x0, cx0, cx1, x1): (u32, u32, u32, u32) = x_bounds;
4270 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
4271 let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
4272 style_colors;
4273 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
4274 let border_w: f32 = if has_border { border.get_width() } else { 0.0 };
4275 let inner_thresh: f32 = if has_border {
4276 -(border_w + 0.85)
4277 } else {
4278 -0.85
4279 };
4280 let py_abs: f32 = py.abs();
4281 let fill_visible: bool = color.get_a() > 0;
4282 let fill_opaque: bool = color.get_a() == 255;
4283 let fill_rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
4284 let mut shaded: usize = 0;
4285 if x0 < cx0 {
4286 let pure_left: bool = ((cx0 - 1) as f32) + 0.5 < cx;
4287 if pure_left {
4288 let r_l: f32 = (if py < 0.0 {
4289 radius.get_top_left()
4290 } else {
4291 radius.get_bottom_left()
4292 })
4293 .min(half_w)
4294 .min(half_h)
4295 .max(0.0);
4296 let qy: f32 = py_abs - half_h + r_l;
4297 let r_out: f32 = r_l + 0.85;
4298 if qy <= r_out + 0.05 {
4299 let vis_l0: u32 = if qy > 0.0 {
4300 let max_vis_abs: f32 =
4301 (half_w - r_l) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
4302 ((cx - max_vis_abs - 0.5).floor().max(0.0) as u32).clamp(x0, cx0)
4303 } else {
4304 x0
4305 };
4306 let r_in: f32 = r_l + inner_thresh;
4307 let max_in_abs: f32 = if qy <= 0.0 {
4308 if qy < r_in - 0.05 {
4309 half_w + inner_thresh - 1.0
4310 } else {
4311 -1.0
4312 }
4313 } else if r_in > 0.0 && qy < r_in - 0.05 {
4314 (half_w - r_l) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
4315 } else {
4316 -1.0
4317 };
4318 let in_l0: u32 = if max_in_abs > 0.0 {
4319 ((cx - max_in_abs - 0.5).ceil().max(0.0) as u32).clamp(vis_l0, cx0)
4320 } else {
4321 cx0
4322 };
4323 for x in vis_l0..in_l0 {
4324 shaded +=
4325 Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
4326 }
4327 if in_l0 < cx0 && fill_visible {
4328 let b0: usize = (in_l0 as usize) * 4;
4329 let b1: usize = (cx0 as usize) * 4;
4330 if fill_opaque {
4331 fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
4332 } else if let Some(luts) = interior_luts {
4333 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
4334 } else {
4335 fill_span_linear_slice(&mut row[b0..b1], color);
4336 }
4337 shaded += (cx0 - in_l0) as usize;
4338 }
4339 }
4340 } else {
4341 for x in x0..cx0 {
4342 shaded += Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
4343 }
4344 }
4345 }
4346 if cx1 < x1 {
4347 let pure_right: bool = (cx1 as f32) + 0.5 >= cx;
4348 if pure_right {
4349 let r_r: f32 = (if py < 0.0 {
4350 radius.get_top_right()
4351 } else {
4352 radius.get_bottom_right()
4353 })
4354 .min(half_w)
4355 .min(half_h)
4356 .max(0.0);
4357 let qy: f32 = py_abs - half_h + r_r;
4358 let r_out: f32 = r_r + 0.85;
4359 if qy <= r_out + 0.05 {
4360 let vis_r1: u32 = if qy > 0.0 {
4361 let max_vis_abs: f32 =
4362 (half_w - r_r) + (r_out * r_out - qy * qy).max(0.0).sqrt() + 1.0;
4363 ((cx + max_vis_abs + 0.5).ceil().max(0.0) as u32).clamp(cx1, x1)
4364 } else {
4365 x1
4366 };
4367 let r_in: f32 = r_r + inner_thresh;
4368 let max_in_abs: f32 = if qy <= 0.0 {
4369 if qy < r_in - 0.05 {
4370 half_w + inner_thresh - 1.0
4371 } else {
4372 -1.0
4373 }
4374 } else if r_in > 0.0 && qy < r_in - 0.05 {
4375 (half_w - r_r) + (r_in * r_in - qy * qy).max(0.0).sqrt() - 1.0
4376 } else {
4377 -1.0
4378 };
4379 let in_r1: u32 = if max_in_abs > 0.0 {
4380 ((cx + max_in_abs - 0.5).floor().max(0.0) as u32).clamp(cx1, vis_r1)
4381 } else {
4382 cx1
4383 };
4384 if cx1 < in_r1 && fill_visible {
4385 let b0: usize = (cx1 as usize) * 4;
4386 let b1: usize = (in_r1 as usize) * 4;
4387 if fill_opaque {
4388 fill_rgba_span_32(&mut row[b0..b1], fill_rgba);
4389 } else if let Some(luts) = interior_luts {
4390 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
4391 } else {
4392 fill_span_linear_slice(&mut row[b0..b1], color);
4393 }
4394 shaded += (in_r1 - cx1) as usize;
4395 }
4396 for x in in_r1..vis_r1 {
4397 shaded +=
4398 Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
4399 }
4400 }
4401 } else {
4402 for x in cx1..x1 {
4403 shaded += Self::shade_rounded_pixel_row(row, x, geom, radius, style_colors, aa);
4404 }
4405 }
4406 }
4407 let dist_y: f32 = py_abs - half_h;
4408 let outer_cov: f32 = sdf_coverage(dist_y, aa);
4409 if outer_cov > 0.0 {
4410 let b0: usize = (cx0 as usize) * 4;
4411 let b1: usize = (cx1 as usize) * 4;
4412 if has_border {
4413 let inner_hh: f32 = (half_h - border_w).max(0.0);
4414 let inner_cov: f32 = if inner_hh > 0.0 && half_w > border_w {
4415 sdf_coverage(py_abs - inner_hh, aa)
4416 } else {
4417 0.0
4418 };
4419 let mixed: Color = composite_fill_and_border_precomputed(
4420 fill_lin, border_lin, outer_cov, inner_cov,
4421 );
4422 if mixed.get_a() > 0 {
4423 fill_span_linear_slice(&mut row[b0..b1], mixed);
4424 }
4425 shaded += (cx1 - cx0) as usize;
4426 } else if fill_visible {
4427 let row_color: Color = color.multiply_alpha(outer_cov);
4428 if row_color == color
4429 && let Some(luts) = interior_luts
4430 {
4431 fill_span_linear_luts_slice(&mut row[b0..b1], luts);
4432 } else {
4433 fill_span_linear_slice(&mut row[b0..b1], row_color);
4434 }
4435 shaded += (cx1 - cx0) as usize;
4436 }
4437 }
4438 shaded
4439 }
4440
4441 #[inline(always)]
4456 fn shade_rounded_pixel_row(
4457 row: &mut [u8],
4458 x: u32,
4459 geom: (f32, f32, f32, f32),
4460 radius: CornerRadius,
4461 style_colors: (Color, Border, [f32; 4], [f32; 4]),
4462 aa: AntialiasingMode,
4463 ) -> usize {
4464 let (cx, py, half_w, half_h): (f32, f32, f32, f32) = geom;
4465 let (color, border, fill_lin, border_lin): (Color, Border, [f32; 4], [f32; 4]) =
4466 style_colors;
4467 let fill_rgb: [f32; 3] = [fill_lin[0], fill_lin[1], fill_lin[2]];
4468 let px: f32 = (x as f32) + 0.5 - cx;
4469 let corner_r: f32 = quadrant_corner_radius(radius, px, py)
4470 .min(half_w)
4471 .min(half_h);
4472 let dist: f32 = rounded_box_sdf(px, py, half_w, half_h, corner_r);
4473 if dist > 0.85 {
4474 return 0;
4475 }
4476 let has_border: bool = border.get_width() > 0.0 && border.get_color().get_a() > 0;
4477 let bw: f32 = if has_border { border.get_width() } else { 0.0 };
4478 if !has_border {
4479 if dist < -0.85 {
4480 if color.get_a() > 0 {
4481 blend_row_pixel_linear_precomputed(row, x, color, fill_rgb);
4482 return 1;
4483 }
4484 return 0;
4485 }
4486 let in_corner_edge: bool = aa != AntialiasingMode::None
4487 && corner_r > 0.5
4488 && px.abs() > (half_w - corner_r - 1.5)
4489 && py.abs() > (half_h - corner_r - 1.5);
4490 let outer_cov: f32 = if in_corner_edge {
4491 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, 0.0).0
4492 } else {
4493 sdf_coverage(dist, aa)
4494 };
4495 if outer_cov > 0.0 && color.get_a() > 0 {
4496 let alpha_f: f32 = ((color.get_a() as f32) * (1.0 / 255.0)) * outer_cov;
4497 blend_row_pixel_f32_precomputed(row, x, color, fill_rgb, alpha_f);
4498 return 1;
4499 }
4500 return 0;
4501 }
4502 if dist < -(bw + 0.85) {
4503 if color.get_a() > 0 {
4504 blend_row_pixel_linear_precomputed(row, x, color, fill_rgb);
4505 return 1;
4506 }
4507 return 0;
4508 }
4509 let inner_hw: f32 = (half_w - bw).max(0.0);
4510 let inner_hh: f32 = (half_h - bw).max(0.0);
4511 let inner_r: f32 = (corner_r - bw).max(0.0);
4512 let inner_dist: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
4513 rounded_box_sdf(px, py, inner_hw, inner_hh, inner_r)
4514 } else {
4515 2.0
4516 };
4517 if dist < -0.85 && inner_dist > 0.85 {
4518 let border_rgb: [f32; 3] = [border_lin[0], border_lin[1], border_lin[2]];
4519 blend_row_pixel_linear_precomputed(row, x, border.get_color(), border_rgb);
4520 return 1;
4521 }
4522 let in_corner_zone: bool = aa != AntialiasingMode::None
4523 && corner_r > 0.5
4524 && px.abs() > (half_w - corner_r - 1.5)
4525 && py.abs() > (half_h - corner_r - 1.5);
4526 let (outer_cov, inner_cov): (f32, f32) = if in_corner_zone {
4527 rounded_box_supersampled_coverage(px, py, half_w, half_h, corner_r, bw)
4528 } else {
4529 let oc: f32 = sdf_coverage(dist, aa);
4530 if oc <= 0.0 {
4531 return 0;
4532 }
4533 let ic: f32 = if inner_hw > 0.0 && inner_hh > 0.0 {
4534 sdf_coverage(inner_dist, aa)
4535 } else {
4536 0.0
4537 };
4538 (oc, ic)
4539 };
4540 if outer_cov <= 0.0 {
4541 return 0;
4542 }
4543 let mixed: Color =
4544 composite_fill_and_border_precomputed(fill_lin, border_lin, outer_cov, inner_cov);
4545 if mixed.get_a() > 0 {
4546 let mixed_rgb: [f32; 3] = [
4547 SRGB_TO_LIN_LUT[mixed.get_r() as usize],
4548 SRGB_TO_LIN_LUT[mixed.get_g() as usize],
4549 SRGB_TO_LIN_LUT[mixed.get_b() as usize],
4550 ];
4551 blend_row_pixel_linear_precomputed(row, x, mixed, mixed_rgb);
4552 return 1;
4553 }
4554 0
4555 }
4556
4557 #[inline(always)]
4570 fn fill_vertical_gradient_span(
4571 band: &mut PixelBand<'_>,
4572 coords: (u32, u32, u32),
4573 sample: Color,
4574 cov: f32,
4575 ) -> usize {
4576 let (sx0, sx1, y): (u32, u32, u32) = coords;
4577 if sx0 >= sx1 || cov <= 0.0 {
4578 return 0;
4579 }
4580 let alpha_f: f32 = ((sample.get_a() as f32) * (1.0 / 255.0)) * cov;
4581 if alpha_f >= 0.9995 {
4582 band.fill_span(
4583 sx0,
4584 sx1,
4585 y,
4586 Color::new(sample.get_r(), sample.get_g(), sample.get_b(), 255),
4587 );
4588 } else if alpha_f > 0.0005 {
4589 band.blend_shadow_span_const_alpha(sx0, sx1, y, sample, alpha_f);
4590 } else if alpha_f > 0.0002
4591 && let Some(row) = band.row_slice_mut(y)
4592 {
4593 let y_term: f32 = (y as f32) * 0.005_837_15;
4594 for x in sx0..sx1 {
4595 blend_gradient_row_pixel(row, x, y_term, sample, cov);
4596 }
4597 }
4598 (sx1 - sx0) as usize
4599 }
4600
4601 #[inline(always)]
4614 fn fill_angled_gradient_span(
4615 row: &mut [u8],
4616 coords: (u32, u32, f32),
4617 step: (f32, f32, f32),
4618 stops: (Color, Color),
4619 ) -> usize {
4620 let (sx0, sx1, y_term): (u32, u32, f32) = coords;
4621 let (t_start, dt_dx, cov): (f32, f32, f32) = step;
4622 let (start_c, end_c): (Color, Color) = stops;
4623 if sx0 >= sx1 || cov <= 0.0 {
4624 return 0;
4625 }
4626 let byte_start: usize = (sx0 as usize) * 4;
4627 let byte_end: usize = (sx1 as usize) * 4;
4628 if byte_end > row.len() {
4629 return 0;
4630 }
4631 let sr_f: f32 = start_c.get_r() as f32;
4632 let sg_f: f32 = start_c.get_g() as f32;
4633 let sb_f: f32 = start_c.get_b() as f32;
4634 let er_f: f32 = end_c.get_r() as f32;
4635 let eg_f: f32 = end_c.get_g() as f32;
4636 let eb_f: f32 = end_c.get_b() as f32;
4637 let both_opaque: bool = start_c.get_a() == 255 && end_c.get_a() == 255;
4638 let mut t_cur: f32 = t_start;
4639 if both_opaque && cov >= 0.9995 {
4640 let chunks: &mut [[u8; 4]] = row[byte_start..byte_end].as_chunks_mut::<4>().0;
4641 for px in chunks.iter_mut() {
4642 let f: f32 = t_cur.clamp(0.0, 1.0);
4643 let inv: f32 = 1.0 - f;
4644 px[0] = (sr_f * inv + er_f * f + 0.5) as u8;
4645 px[1] = (sg_f * inv + eg_f * f + 0.5) as u8;
4646 px[2] = (sb_f * inv + eb_f * f + 0.5) as u8;
4647 px[3] = 255;
4648 t_cur += dt_dx;
4649 }
4650 return (sx1 - sx0) as usize;
4651 }
4652 let sa_f: f32 = start_c.get_a() as f32;
4653 let ea_f: f32 = end_c.get_a() as f32;
4654 for x in sx0..sx1 {
4655 let f: f32 = t_cur.clamp(0.0, 1.0);
4656 let inv: f32 = 1.0 - f;
4657 let sample: Color = Color::new(
4658 (sr_f * inv + er_f * f + 0.5) as u8,
4659 (sg_f * inv + eg_f * f + 0.5) as u8,
4660 (sb_f * inv + eb_f * f + 0.5) as u8,
4661 (sa_f * inv + ea_f * f + 0.5) as u8,
4662 );
4663 blend_gradient_row_pixel(row, x, y_term, sample, cov);
4664 t_cur += dt_dx;
4665 }
4666 (sx1 - sx0) as usize
4667 }
4668
4669 fn raster_gradient_rect(
4684 band: &mut PixelBand<'_>,
4685 rect: Rect,
4686 gradient: LinearGradient,
4687 radius: CornerRadius,
4688 clip: Rect,
4689 aa: AntialiasingMode,
4690 ) -> usize {
4691 let Some(vis) = rect.intersect(clip) else {
4692 return 0;
4693 };
4694 let fb_w: u32 = band.width();
4695 let band_y0: u32 = band.y_offset();
4696 let band_y1: u32 = band.y_end();
4697 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
4698 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
4699 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
4700 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
4701 if x0 >= x1 || y0 >= y1 {
4702 return 0;
4703 }
4704 let rad: f32 = gradient.get_angle_deg().to_radians();
4705 let dir_x: f32 = rad.sin();
4706 let dir_y: f32 = rad.cos();
4707 let start_c: Color = gradient.get_start_color();
4708 let end_c: Color = gradient.get_end_color();
4709 let half_w: f32 = rect.get_width() * 0.5;
4710 let half_h: f32 = rect.get_height() * 0.5;
4711 let cx: f32 = rect.get_x() + half_w;
4712 let cy: f32 = rect.get_y() + half_h;
4713 let inv_w: f32 = if rect.get_width() > 0.0 {
4714 1.0 / rect.get_width()
4715 } else {
4716 0.0
4717 };
4718 let inv_h: f32 = if rect.get_height() > 0.0 {
4719 1.0 / rect.get_height()
4720 } else {
4721 0.0
4722 };
4723 let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
4724 let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
4725 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
4726 let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
4727 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
4728 let cx0: u32 = ((rect.get_x() + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
4729 let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
4730 let is_vertical: bool = dir_x.abs() < 1e-5;
4731 let dt_dx: f32 = inv_w * dir_x;
4732 let rect_x: f32 = rect.get_x();
4733 let rect_y: f32 = rect.get_y();
4734 let mut shaded: usize = 0;
4735 if is_vertical {
4736 for y in y0..iy0 {
4737 let py: f32 = (y as f32) + 0.5 - cy;
4738 let ny: f32 = ((y as f32) - rect_y) * inv_h;
4739 let t: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
4740 let sample: Color = start_c.lerp(end_c, t);
4741 let dist_y: f32 = py.abs() - half_h;
4742 let mid_cov: f32 = if dist_y > 0.85 {
4743 0.0
4744 } else if dist_y < -0.85 {
4745 1.0
4746 } else {
4747 sdf_coverage(dist_y, aa)
4748 };
4749 if cx0 < cx1 && mid_cov > 0.0 {
4750 shaded +=
4751 Self::fill_vertical_gradient_span(band, (cx0, cx1, y), sample, mid_cov);
4752 }
4753 if (x0 < cx0 || cx1 < x1)
4754 && let Some(row) = band.row_slice_mut(y)
4755 {
4756 let y_term: f32 = (y as f32) * 0.005_837_15;
4757 for x in x0..cx0 {
4758 let px: f32 = (x as f32) + 0.5 - cx;
4759 let cov: f32 =
4760 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4761 if cov > 0.0 {
4762 blend_gradient_row_pixel(row, x, y_term, sample, cov);
4763 shaded += 1;
4764 }
4765 }
4766 for x in cx1..x1 {
4767 let px: f32 = (x as f32) + 0.5 - cx;
4768 let cov: f32 =
4769 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4770 if cov > 0.0 {
4771 blend_gradient_row_pixel(row, x, y_term, sample, cov);
4772 shaded += 1;
4773 }
4774 }
4775 }
4776 }
4777 for y in iy0..iy1 {
4778 let ny: f32 = ((y as f32) - rect_y) * inv_h;
4779 let t: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
4780 let sample: Color = start_c.lerp(end_c, t);
4781 if ix0 < ix1 {
4782 shaded += Self::fill_vertical_gradient_span(band, (ix0, ix1, y), sample, 1.0);
4783 }
4784 if (x0 < ix0 || ix1 < x1)
4785 && let Some(row) = band.row_slice_mut(y)
4786 {
4787 let y_term: f32 = (y as f32) * 0.005_837_15;
4788 for x in x0..ix0 {
4789 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
4790 if dist <= 0.85 {
4791 let cov: f32 = if dist < -0.85 {
4792 1.0
4793 } else {
4794 sdf_coverage(dist, aa)
4795 };
4796 if cov > 0.0 {
4797 blend_gradient_row_pixel(row, x, y_term, sample, cov);
4798 shaded += 1;
4799 }
4800 }
4801 }
4802 for x in ix1..x1 {
4803 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
4804 if dist <= 0.85 {
4805 let cov: f32 = if dist < -0.85 {
4806 1.0
4807 } else {
4808 sdf_coverage(dist, aa)
4809 };
4810 if cov > 0.0 {
4811 blend_gradient_row_pixel(row, x, y_term, sample, cov);
4812 shaded += 1;
4813 }
4814 }
4815 }
4816 }
4817 }
4818 for y in iy1..y1 {
4819 let py: f32 = (y as f32) + 0.5 - cy;
4820 let ny: f32 = ((y as f32) - rect_y) * inv_h;
4821 let t: f32 = ((ny - 0.5) * dir_y + 0.5).clamp(0.0, 1.0);
4822 let sample: Color = start_c.lerp(end_c, t);
4823 let dist_y: f32 = py.abs() - half_h;
4824 let mid_cov: f32 = if dist_y > 0.85 {
4825 0.0
4826 } else if dist_y < -0.85 {
4827 1.0
4828 } else {
4829 sdf_coverage(dist_y, aa)
4830 };
4831 if cx0 < cx1 && mid_cov > 0.0 {
4832 shaded +=
4833 Self::fill_vertical_gradient_span(band, (cx0, cx1, y), sample, mid_cov);
4834 }
4835 if (x0 < cx0 || cx1 < x1)
4836 && let Some(row) = band.row_slice_mut(y)
4837 {
4838 let y_term: f32 = (y as f32) * 0.005_837_15;
4839 for x in x0..cx0 {
4840 let px: f32 = (x as f32) + 0.5 - cx;
4841 let cov: f32 =
4842 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4843 if cov > 0.0 {
4844 blend_gradient_row_pixel(row, x, y_term, sample, cov);
4845 shaded += 1;
4846 }
4847 }
4848 for x in cx1..x1 {
4849 let px: f32 = (x as f32) + 0.5 - cx;
4850 let cov: f32 =
4851 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4852 if cov > 0.0 {
4853 blend_gradient_row_pixel(row, x, y_term, sample, cov);
4854 shaded += 1;
4855 }
4856 }
4857 }
4858 }
4859 return shaded;
4860 }
4861 for y in y0..iy0 {
4862 let Some(row) = band.row_slice_mut(y) else {
4863 continue;
4864 };
4865 let py: f32 = (y as f32) + 0.5 - cy;
4866 let ny: f32 = ((y as f32) - rect_y) * inv_h;
4867 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
4868 let y_term: f32 = (y as f32) * 0.005_837_15;
4869 let dist_y: f32 = py.abs() - half_h;
4870 let mid_cov: f32 = if dist_y > 0.85 {
4871 0.0
4872 } else if dist_y < -0.85 {
4873 1.0
4874 } else {
4875 sdf_coverage(dist_y, aa)
4876 };
4877 if cx0 < cx1 && mid_cov > 0.0 {
4878 let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
4879 shaded += Self::fill_angled_gradient_span(
4880 row,
4881 (cx0, cx1, y_term),
4882 (t_start, dt_dx, mid_cov),
4883 (start_c, end_c),
4884 );
4885 }
4886 for x in x0..cx0 {
4887 let px: f32 = (x as f32) + 0.5 - cx;
4888 let cov: f32 =
4889 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4890 if cov > 0.0 {
4891 let nx: f32 = ((x as f32) - rect_x) * inv_w;
4892 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4893 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4894 shaded += 1;
4895 }
4896 }
4897 for x in cx1..x1 {
4898 let px: f32 = (x as f32) + 0.5 - cx;
4899 let cov: f32 =
4900 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4901 if cov > 0.0 {
4902 let nx: f32 = ((x as f32) - rect_x) * inv_w;
4903 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4904 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4905 shaded += 1;
4906 }
4907 }
4908 }
4909 for y in iy0..iy1 {
4910 let Some(row) = band.row_slice_mut(y) else {
4911 continue;
4912 };
4913 let ny: f32 = ((y as f32) - rect_y) * inv_h;
4914 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
4915 let y_term: f32 = (y as f32) * 0.005_837_15;
4916 if ix0 < ix1 {
4917 let t_start: f32 = (((ix0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
4918 shaded += Self::fill_angled_gradient_span(
4919 row,
4920 (ix0, ix1, y_term),
4921 (t_start, dt_dx, 1.0),
4922 (start_c, end_c),
4923 );
4924 }
4925 for x in x0..ix0 {
4926 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
4927 if dist <= 0.85 {
4928 let cov: f32 = if dist < -0.85 {
4929 1.0
4930 } else {
4931 sdf_coverage(dist, aa)
4932 };
4933 if cov > 0.0 {
4934 let nx: f32 = ((x as f32) - rect_x) * inv_w;
4935 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4936 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4937 shaded += 1;
4938 }
4939 }
4940 }
4941 for x in ix1..x1 {
4942 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
4943 if dist <= 0.85 {
4944 let cov: f32 = if dist < -0.85 {
4945 1.0
4946 } else {
4947 sdf_coverage(dist, aa)
4948 };
4949 if cov > 0.0 {
4950 let nx: f32 = ((x as f32) - rect_x) * inv_w;
4951 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4952 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4953 shaded += 1;
4954 }
4955 }
4956 }
4957 }
4958 for y in iy1..y1 {
4959 let Some(row) = band.row_slice_mut(y) else {
4960 continue;
4961 };
4962 let py: f32 = (y as f32) + 0.5 - cy;
4963 let ny: f32 = ((y as f32) - rect_y) * inv_h;
4964 let y_bias: f32 = (ny - 0.5) * dir_y + 0.5;
4965 let y_term: f32 = (y as f32) * 0.005_837_15;
4966 let dist_y: f32 = py.abs() - half_h;
4967 let mid_cov: f32 = if dist_y > 0.85 {
4968 0.0
4969 } else if dist_y < -0.85 {
4970 1.0
4971 } else {
4972 sdf_coverage(dist_y, aa)
4973 };
4974 if cx0 < cx1 && mid_cov > 0.0 {
4975 let t_start: f32 = (((cx0 as f32) - rect_x) * inv_w - 0.5) * dir_x + y_bias;
4976 shaded += Self::fill_angled_gradient_span(
4977 row,
4978 (cx0, cx1, y_term),
4979 (t_start, dt_dx, mid_cov),
4980 (start_c, end_c),
4981 );
4982 }
4983 for x in x0..cx0 {
4984 let px: f32 = (x as f32) + 0.5 - cx;
4985 let cov: f32 =
4986 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4987 if cov > 0.0 {
4988 let nx: f32 = ((x as f32) - rect_x) * inv_w;
4989 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
4990 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
4991 shaded += 1;
4992 }
4993 }
4994 for x in cx1..x1 {
4995 let px: f32 = (x as f32) + 0.5 - cx;
4996 let cov: f32 =
4997 gradient_rounded_pixel_coverage((px, py, half_w, half_h), radius, aa);
4998 if cov > 0.0 {
4999 let nx: f32 = ((x as f32) - rect_x) * inv_w;
5000 let t: f32 = ((nx - 0.5) * dir_x + y_bias).clamp(0.0, 1.0);
5001 blend_gradient_row_pixel(row, x, y_term, start_c.lerp(end_c, t), cov);
5002 shaded += 1;
5003 }
5004 }
5005 }
5006 shaded
5007 }
5008
5009 #[must_use]
5022 fn shadow_row_cutout(y: u32, cutouts: (Rect, Rect), x0: u32, x1: u32) -> (u32, u32) {
5023 let (cut_h, cut_v): (Rect, Rect) = cutouts;
5024 let yf: f32 = (y as f32) + 0.5;
5025 if cut_h.get_width() > 0.0
5026 && cut_h.get_height() > 0.0
5027 && yf >= cut_h.get_y()
5028 && yf < cut_h.bottom()
5029 {
5030 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
5031 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, x1);
5032 return (cx0, cx1);
5033 }
5034 if cut_v.get_width() > 0.0
5035 && cut_v.get_height() > 0.0
5036 && yf >= cut_v.get_y()
5037 && yf < cut_v.bottom()
5038 {
5039 let cx0: u32 = (cut_v.get_x().ceil().max(0.0) as u32).clamp(x0, x1);
5040 let cx1: u32 = (cut_v.right().floor().max(0.0) as u32).clamp(cx0, x1);
5041 return (cx0, cx1);
5042 }
5043 (x1, x1)
5044 }
5045
5046 #[inline(always)]
5060 fn raster_shadow_middle_span(
5061 band: &mut PixelBand<'_>,
5062 ctx: &ShadowRenderCtx,
5063 y: u32,
5064 cutout: (u32, u32),
5065 mid_alpha: f32,
5066 ) -> usize {
5067 if !ctx.has_mid_x || mid_alpha <= 0.0005 {
5068 return 0;
5069 }
5070 let (cut0, cut1): (u32, u32) = cutout;
5071 let sx0: u32 = ctx.lx1;
5072 let sx1: u32 = ctx.rx0;
5073 let mut shaded: usize = 0;
5074 if cut0 < cut1 {
5075 let m0_end: u32 = cut0.min(sx1);
5076 if sx0 < m0_end {
5077 band.blend_shadow_span_const_alpha(sx0, m0_end, y, ctx.color, mid_alpha);
5078 shaded += (m0_end - sx0) as usize;
5079 }
5080 let m1_start: u32 = cut1.max(sx0);
5081 if m1_start < sx1 {
5082 band.blend_shadow_span_const_alpha(m1_start, sx1, y, ctx.color, mid_alpha);
5083 shaded += (sx1 - m1_start) as usize;
5084 }
5085 } else {
5086 band.blend_shadow_span_const_alpha(sx0, sx1, y, ctx.color, mid_alpha);
5087 shaded += (sx1 - sx0) as usize;
5088 }
5089 shaded
5090 }
5091
5092 fn raster_shadow_corner_row_symmetric(
5105 band: &mut PixelBand<'_>,
5106 ctx: &ShadowRenderCtx,
5107 y: u32,
5108 cutouts: (Rect, Rect),
5109 ) -> usize {
5110 let py: f32 = (y as f32) + 0.5 - ctx.cy;
5111 let py_abs: f32 = py.abs();
5112 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1);
5113 let mut shaded: usize = 0;
5114 if ctx.has_mid_x {
5115 let dist_y: f32 = py_abs - ctx.half_h;
5116 let mid_alpha: f32 = if dist_y < ctx.cutoff {
5117 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
5118 } else {
5119 0.0
5120 };
5121 shaded += Self::raster_shadow_middle_span(band, ctx, y, (cut0, cut1), mid_alpha);
5122 }
5123 let (la0, la1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0, cut1);
5124 let (ra0, ra1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0, cut1);
5125 let mut u0: i32 = i32::MAX;
5126 let mut u1: i32 = i32::MIN;
5127 if la0 < la1 {
5128 u0 = u0.min(la0 as i32);
5129 u1 = u1.max(la1 as i32);
5130 }
5131 if ra0 < ra1 {
5132 u0 = u0.min(ctx.mirror_x_sum - (ra1 as i32) + 1);
5133 u1 = u1.max(ctx.mirror_x_sum - (ra0 as i32) + 1);
5134 }
5135 if u0 >= u1 {
5136 return shaded;
5137 }
5138 let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
5139 let qy_pos: f32 = qy.max(0.0);
5140 let qy_pos_sq: f32 = qy_pos * qy_pos;
5141 if qy > 0.0 {
5142 if qy_pos_sq >= ctx.cutoff_r_safe_sq {
5143 return shaded;
5144 }
5145 let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
5146 let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
5147 let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
5148 u0 = u0.max(tight_u0);
5149 if u0 >= u1 {
5150 return shaded;
5151 }
5152 }
5153 let Some(row) = band.row_slice_mut(y) else {
5154 return shaded;
5155 };
5156 let sdf_geom: (f32, f32, f32, f32) =
5157 (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
5158 let y_term: f32 = (y as f32) * 0.005_837_15;
5159 let x0_i: i32 = ctx.x0 as i32;
5160 let lx1_i: i32 = ctx.lx1 as i32;
5161 let rx0_i: i32 = ctx.rx0 as i32;
5162 let x1_i: i32 = ctx.x1 as i32;
5163 let cut0_i: i32 = cut0 as i32;
5164 let cut1_i: i32 = cut1 as i32;
5165 for xl_i in u0..u1 {
5166 let xr_i: i32 = ctx.mirror_x_sum - xl_i;
5167 let do_l: bool = xl_i >= x0_i && xl_i < lx1_i && (xl_i < cut0_i || xl_i >= cut1_i);
5168 let do_r: bool = xr_i >= rx0_i && xr_i < x1_i && (xr_i < cut0_i || xr_i >= cut1_i);
5169 if !do_l && !do_r {
5170 continue;
5171 }
5172 let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
5173 let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
5174 if dist >= ctx.cutoff {
5175 continue;
5176 }
5177 let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5178 if alpha_f <= 0.0005 {
5179 continue;
5180 }
5181 let a: f32 = alpha_f.clamp(0.0, 1.0);
5182 if a >= 0.9995 {
5183 if do_l {
5184 let off: usize = (xl_i as usize) * 4;
5185 row[off] = ctx.color_rgb[0];
5186 row[off + 1] = ctx.color_rgb[1];
5187 row[off + 2] = ctx.color_rgb[2];
5188 row[off + 3] = 255;
5189 shaded += 1;
5190 }
5191 if do_r {
5192 let off: usize = (xr_i as usize) * 4;
5193 row[off] = ctx.color_rgb[0];
5194 row[off + 1] = ctx.color_rgb[1];
5195 row[off + 2] = ctx.color_rgb[2];
5196 row[off + 3] = 255;
5197 shaded += 1;
5198 }
5199 } else {
5200 let inv_a: f32 = 1.0 - a;
5201 let sa_u32: u32 = (a * 255.0) as u32;
5202 let params: ShadowStripParams = ShadowStripParams {
5203 sr_a: ctx.lin_rgb[0] * a,
5204 sg_a: ctx.lin_rgb[1] * a,
5205 sb_a: ctx.lin_rgb[2] * a,
5206 inv_a,
5207 sa_u32,
5208 inv_a_u32: 255 - sa_u32,
5209 };
5210 let mut cache: ShadowPixelCache = ShadowPixelCache::default();
5211 if do_l {
5212 blend_shadow_mirrored_pixel(row, xl_i as u32, y_term, params, &mut cache);
5213 shaded += 1;
5214 }
5215 if do_r {
5216 blend_shadow_mirrored_pixel(row, xr_i as u32, y_term, params, &mut cache);
5217 shaded += 1;
5218 }
5219 }
5220 }
5221 shaded
5222 }
5223
5224 fn raster_shadow_corner_pair_symmetric(
5238 band: &mut PixelBand<'_>,
5239 ctx: &ShadowRenderCtx,
5240 y_t: u32,
5241 y_b: u32,
5242 cutouts: (Rect, Rect),
5243 ) -> usize {
5244 let py: f32 = (y_t as f32) + 0.5 - ctx.cy;
5245 let py_abs: f32 = py.abs();
5246 let (cut0_t, cut1_t): (u32, u32) = Self::shadow_row_cutout(y_t, cutouts, ctx.x0, ctx.x1);
5247 let (cut0_b, cut1_b): (u32, u32) = Self::shadow_row_cutout(y_b, cutouts, ctx.x0, ctx.x1);
5248 let mut shaded: usize = 0;
5249 if ctx.has_mid_x {
5250 let dist_y: f32 = py_abs - ctx.half_h;
5251 let mid_alpha: f32 = if dist_y < ctx.cutoff {
5252 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
5253 } else {
5254 0.0
5255 };
5256 if mid_alpha > 0.0005 {
5257 shaded +=
5258 Self::raster_shadow_middle_span(band, ctx, y_t, (cut0_t, cut1_t), mid_alpha);
5259 shaded +=
5260 Self::raster_shadow_middle_span(band, ctx, y_b, (cut0_b, cut1_b), mid_alpha);
5261 }
5262 }
5263 let (lat0, lat1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_t, cut1_t);
5264 let (rat0, rat1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_t, cut1_t);
5265 let (lab0, lab1): (u32, u32) = active_span_bounds(ctx.x0, ctx.lx1, cut0_b, cut1_b);
5266 let (rab0, rab1): (u32, u32) = active_span_bounds(ctx.rx0, ctx.x1, cut0_b, cut1_b);
5267 let mut u0: i32 = i32::MAX;
5268 let mut u1: i32 = i32::MIN;
5269 if lat0 < lat1 {
5270 u0 = u0.min(lat0 as i32);
5271 u1 = u1.max(lat1 as i32);
5272 }
5273 if rat0 < rat1 {
5274 u0 = u0.min(ctx.mirror_x_sum - (rat1 as i32) + 1);
5275 u1 = u1.max(ctx.mirror_x_sum - (rat0 as i32) + 1);
5276 }
5277 if lab0 < lab1 {
5278 u0 = u0.min(lab0 as i32);
5279 u1 = u1.max(lab1 as i32);
5280 }
5281 if rab0 < rab1 {
5282 u0 = u0.min(ctx.mirror_x_sum - (rab1 as i32) + 1);
5283 u1 = u1.max(ctx.mirror_x_sum - (rab0 as i32) + 1);
5284 }
5285 if u0 >= u1 {
5286 return shaded;
5287 }
5288 let qy: f32 = py_abs - ctx.half_h + ctx.uniform_r;
5289 let qy_pos: f32 = qy.max(0.0);
5290 let qy_pos_sq: f32 = qy_pos * qy_pos;
5291 if qy > 0.0 {
5292 if qy_pos_sq >= ctx.cutoff_r_safe_sq {
5293 return shaded;
5294 }
5295 let max_qx: f32 = (ctx.cutoff_r_safe_sq - qy_pos_sq).sqrt();
5296 let max_px_abs: f32 = ctx.half_w - ctx.uniform_r + max_qx + 0.5;
5297 let tight_u0: i32 = (ctx.cx - max_px_abs - 0.5).floor() as i32;
5298 u0 = u0.max(tight_u0);
5299 if u0 >= u1 {
5300 return shaded;
5301 }
5302 }
5303 let Some((row_t, row_b)) = band.two_row_slices_mut(y_t, y_b) else {
5304 return shaded;
5305 };
5306 let sdf_geom: (f32, f32, f32, f32) =
5307 (ctx.half_w, ctx.uniform_r, ctx.cutoff, ctx.cutoff_r_safe_sq);
5308 let y_term_t: f32 = (y_t as f32) * 0.005_837_15;
5309 let y_term_b: f32 = (y_b as f32) * 0.005_837_15;
5310 let x0_i: i32 = ctx.x0 as i32;
5311 let lx1_i: i32 = ctx.lx1 as i32;
5312 let rx0_i: i32 = ctx.rx0 as i32;
5313 let x1_i: i32 = ctx.x1 as i32;
5314 let cut0_ti: i32 = cut0_t as i32;
5315 let cut1_ti: i32 = cut1_t as i32;
5316 let cut0_bi: i32 = cut0_b as i32;
5317 let cut1_bi: i32 = cut1_b as i32;
5318 for xl_i in u0..u1 {
5319 let xr_i: i32 = ctx.mirror_x_sum - xl_i;
5320 let in_l: bool = xl_i >= x0_i && xl_i < lx1_i;
5321 let in_r: bool = xr_i >= rx0_i && xr_i < x1_i;
5322 let do_lt: bool = in_l && (xl_i < cut0_ti || xl_i >= cut1_ti);
5323 let do_rt: bool = in_r && (xr_i < cut0_ti || xr_i >= cut1_ti);
5324 let do_lb: bool = in_l && (xl_i < cut0_bi || xl_i >= cut1_bi);
5325 let do_rb: bool = in_r && (xr_i < cut0_bi || xr_i >= cut1_bi);
5326 if !do_lt && !do_rt && !do_lb && !do_rb {
5327 continue;
5328 }
5329 let px_abs: f32 = ((xl_i as f32) + 0.5 - ctx.cx).abs();
5330 let dist: f32 = shadow_corner_dist_fast(px_abs, qy, qy_pos_sq, sdf_geom);
5331 if dist >= ctx.cutoff {
5332 continue;
5333 }
5334 let alpha_f: f32 = ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5335 if alpha_f <= 0.0005 {
5336 continue;
5337 }
5338 let a: f32 = alpha_f.clamp(0.0, 1.0);
5339 if a >= 0.9995 {
5340 if do_lt {
5341 let off: usize = (xl_i as usize) * 4;
5342 row_t[off] = ctx.color_rgb[0];
5343 row_t[off + 1] = ctx.color_rgb[1];
5344 row_t[off + 2] = ctx.color_rgb[2];
5345 row_t[off + 3] = 255;
5346 shaded += 1;
5347 }
5348 if do_rt {
5349 let off: usize = (xr_i as usize) * 4;
5350 row_t[off] = ctx.color_rgb[0];
5351 row_t[off + 1] = ctx.color_rgb[1];
5352 row_t[off + 2] = ctx.color_rgb[2];
5353 row_t[off + 3] = 255;
5354 shaded += 1;
5355 }
5356 if do_lb {
5357 let off: usize = (xl_i as usize) * 4;
5358 row_b[off] = ctx.color_rgb[0];
5359 row_b[off + 1] = ctx.color_rgb[1];
5360 row_b[off + 2] = ctx.color_rgb[2];
5361 row_b[off + 3] = 255;
5362 shaded += 1;
5363 }
5364 if do_rb {
5365 let off: usize = (xr_i as usize) * 4;
5366 row_b[off] = ctx.color_rgb[0];
5367 row_b[off + 1] = ctx.color_rgb[1];
5368 row_b[off + 2] = ctx.color_rgb[2];
5369 row_b[off + 3] = 255;
5370 shaded += 1;
5371 }
5372 } else {
5373 let inv_a: f32 = 1.0 - a;
5374 let sa_u32: u32 = (a * 255.0) as u32;
5375 let params: ShadowStripParams = ShadowStripParams {
5376 sr_a: ctx.lin_rgb[0] * a,
5377 sg_a: ctx.lin_rgb[1] * a,
5378 sb_a: ctx.lin_rgb[2] * a,
5379 inv_a,
5380 sa_u32,
5381 inv_a_u32: 255 - sa_u32,
5382 };
5383 let mut cache: ShadowPixelCache = ShadowPixelCache::default();
5384 if do_lt {
5385 blend_shadow_mirrored_pixel(row_t, xl_i as u32, y_term_t, params, &mut cache);
5386 shaded += 1;
5387 }
5388 if do_rt {
5389 blend_shadow_mirrored_pixel(row_t, xr_i as u32, y_term_t, params, &mut cache);
5390 shaded += 1;
5391 }
5392 if do_lb {
5393 blend_shadow_mirrored_pixel(row_b, xl_i as u32, y_term_b, params, &mut cache);
5394 shaded += 1;
5395 }
5396 if do_rb {
5397 blend_shadow_mirrored_pixel(row_b, xr_i as u32, y_term_b, params, &mut cache);
5398 shaded += 1;
5399 }
5400 }
5401 }
5402 shaded
5403 }
5404
5405 fn raster_shadow_corner_row_general(
5419 band: &mut PixelBand<'_>,
5420 ctx: &ShadowRenderCtx,
5421 radius: CornerRadius,
5422 y: u32,
5423 cutouts: (Rect, Rect),
5424 ) -> usize {
5425 let py: f32 = (y as f32) + 0.5 - ctx.cy;
5426 let py_abs: f32 = py.abs();
5427 let (cut0, cut1): (u32, u32) = Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1);
5428 let spans: [(u32, u32); 2] = if cut0 < cut1 {
5429 [(ctx.x0, cut0), (cut1, ctx.x1)]
5430 } else {
5431 [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
5432 };
5433 let mut shaded: usize = 0;
5434 if ctx.has_mid_x {
5435 let dist_y: f32 = py_abs - ctx.half_h;
5436 let mid_alpha: f32 = if dist_y < ctx.cutoff {
5437 ctx.base_alpha * fast_gaussian_shadow_falloff(dist_y, ctx.inv_sigma)
5438 } else {
5439 0.0
5440 };
5441 shaded += Self::raster_shadow_middle_span(band, ctx, y, (cut0, cut1), mid_alpha);
5442 }
5443 let Some(row) = band.row_slice_mut(y) else {
5444 return shaded;
5445 };
5446 let y_term: f32 = (y as f32) * 0.005_837_15;
5447 let r_l: f32 = (if py < 0.0 {
5448 radius.get_top_left()
5449 } else {
5450 radius.get_bottom_left()
5451 })
5452 .min(ctx.half_w)
5453 .min(ctx.half_h)
5454 .max(0.0);
5455 let r_r: f32 = (if py < 0.0 {
5456 radius.get_top_right()
5457 } else {
5458 radius.get_bottom_right()
5459 })
5460 .min(ctx.half_w)
5461 .min(ctx.half_h)
5462 .max(0.0);
5463 let qy_l: f32 = py_abs - ctx.half_h + r_l;
5464 let qy_l_pos: f32 = qy_l.max(0.0);
5465 let qy_l_sq: f32 = qy_l_pos * qy_l_pos;
5466 let cut_l_r: f32 = ctx.cutoff + r_l + 1e-3;
5467 let geom_l: (f32, f32, f32, f32) = (ctx.half_w, r_l, ctx.cutoff, cut_l_r * cut_l_r);
5468 let qy_r: f32 = py_abs - ctx.half_h + r_r;
5469 let qy_r_pos: f32 = qy_r.max(0.0);
5470 let qy_r_sq: f32 = qy_r_pos * qy_r_pos;
5471 let cut_r_r: f32 = ctx.cutoff + r_r + 1e-3;
5472 let geom_r: (f32, f32, f32, f32) = (ctx.half_w, r_r, ctx.cutoff, cut_r_r * cut_r_r);
5473 for (rx0, rx1) in spans.into_iter() {
5474 if rx0 >= rx1 {
5475 continue;
5476 }
5477 if ctx.has_mid_x {
5478 let l_end: u32 = rx1.min(ctx.lx1);
5479 for x in rx0..l_end {
5480 let px: f32 = (x as f32) + 0.5 - ctx.cx;
5481 let dist: f32 = if px < 0.0 {
5482 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
5483 } else {
5484 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
5485 };
5486 if dist < ctx.cutoff {
5487 let alpha_f: f32 =
5488 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5489 if alpha_f > 0.0005 {
5490 blend_shadow_row_pixel(
5491 row,
5492 x,
5493 y_term,
5494 ctx.color_rgb,
5495 ctx.lin_rgb,
5496 alpha_f,
5497 );
5498 shaded += 1;
5499 }
5500 }
5501 }
5502 let r_start: u32 = rx0.max(ctx.rx0);
5503 for x in r_start..rx1 {
5504 let px: f32 = (x as f32) + 0.5 - ctx.cx;
5505 let dist: f32 = if px < 0.0 {
5506 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
5507 } else {
5508 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
5509 };
5510 if dist < ctx.cutoff {
5511 let alpha_f: f32 =
5512 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5513 if alpha_f > 0.0005 {
5514 blend_shadow_row_pixel(
5515 row,
5516 x,
5517 y_term,
5518 ctx.color_rgb,
5519 ctx.lin_rgb,
5520 alpha_f,
5521 );
5522 shaded += 1;
5523 }
5524 }
5525 }
5526 } else {
5527 for x in rx0..rx1 {
5528 let px: f32 = (x as f32) + 0.5 - ctx.cx;
5529 let dist: f32 = if px < 0.0 {
5530 shadow_corner_dist_fast(px.abs(), qy_l, qy_l_sq, geom_l)
5531 } else {
5532 shadow_corner_dist_fast(px.abs(), qy_r, qy_r_sq, geom_r)
5533 };
5534 if dist >= ctx.cutoff {
5535 continue;
5536 }
5537 let alpha_f: f32 =
5538 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5539 if alpha_f > 0.0005 {
5540 blend_shadow_row_pixel(row, x, y_term, ctx.color_rgb, ctx.lin_rgb, alpha_f);
5541 shaded += 1;
5542 }
5543 }
5544 }
5545 }
5546 shaded
5547 }
5548
5549 fn raster_shadow_vertical_strips(
5562 band: &mut PixelBand<'_>,
5563 ctx: &ShadowRenderCtx,
5564 y_span: (u32, u32),
5565 cutouts: (Rect, Rect),
5566 ) -> usize {
5567 let (sy0, sy1): (u32, u32) = y_span;
5568 if sy0 >= sy1 {
5569 return 0;
5570 }
5571 let (cut_h, _): (Rect, Rect) = cutouts;
5572 let sy0_f: f32 = (sy0 as f32) + 0.5;
5573 let sy1_last_f: f32 = ((sy1 - 1) as f32) + 0.5;
5574 let const_cut: Option<(u32, u32)> = if cut_h.get_width() > 0.0
5575 && cut_h.get_height() > 0.0
5576 && sy0_f >= cut_h.get_y()
5577 && sy1_last_f < cut_h.bottom()
5578 {
5579 let cx0: u32 = (cut_h.get_x().ceil().max(0.0) as u32).clamp(ctx.x0, ctx.x1);
5580 let cx1: u32 = (cut_h.right().floor().max(0.0) as u32).clamp(cx0, ctx.x1);
5581 Some((cx0, cx1))
5582 } else {
5583 None
5584 };
5585 let (l_build0, l_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
5586 active_span_bounds(ctx.x0, ctx.lx1, c0, c1)
5587 } else {
5588 (ctx.x0, ctx.lx1)
5589 };
5590 let (r_build0, r_build1): (u32, u32) = if let Some((c0, c1)) = const_cut {
5591 active_span_bounds(ctx.rx0, ctx.x1, c0, c1)
5592 } else {
5593 (ctx.rx0, ctx.x1)
5594 };
5595 let mut shaded: usize = 0;
5596 let ran_tls: bool = BAND_SHADOW_SCRATCH
5597 .try_with(|cell: &RefCell<BandShadowScratch>| {
5598 if let Ok(mut scratch) = cell.try_borrow_mut() {
5599 let BandShadowScratch {
5600 left_hot,
5601 left_params,
5602 right_hot,
5603 right_params,
5604 } = &mut *scratch;
5605 let (l_act0, l_act1): (u32, u32) = build_shadow_vertical_strip(
5606 (l_build0, l_build1),
5607 ctx,
5608 left_hot,
5609 left_params,
5610 );
5611 let (r_act0, r_act1): (u32, u32) = build_shadow_vertical_strip(
5612 (r_build0, r_build1),
5613 ctx,
5614 right_hot,
5615 right_params,
5616 );
5617 if l_act0 >= l_act1 && r_act0 >= r_act1 {
5618 return;
5619 }
5620 let l_hot_s: &mut [ShadowStripHot] = left_hot.as_mut_slice();
5621 let l_par_s: &[ShadowStripParams] = left_params.as_slice();
5622 let r_hot_s: &mut [ShadowStripHot] = right_hot.as_mut_slice();
5623 let r_par_s: &[ShadowStripParams] = right_params.as_slice();
5624 for y in sy0..sy1 {
5625 let Some(row) = band.row_slice_mut(y) else {
5626 continue;
5627 };
5628 let y_term: f32 = (y as f32) * 0.005_837_15;
5629 let (cut0, cut1): (u32, u32) = const_cut
5630 .unwrap_or_else(|| Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1));
5631 if l_act0 < l_act1 {
5632 if cut0 < cut1 {
5633 let a_end: u32 = cut0.min(l_act1);
5634 if l_act0 < a_end {
5635 shaded += apply_shadow_strip_span(
5636 row,
5637 (l_act0, a_end, l_act0),
5638 y_term,
5639 ctx.color_rgb,
5640 l_hot_s,
5641 l_par_s,
5642 );
5643 }
5644 let b_start: u32 = cut1.max(l_act0);
5645 if b_start < l_act1 {
5646 shaded += apply_shadow_strip_span(
5647 row,
5648 (b_start, l_act1, l_act0),
5649 y_term,
5650 ctx.color_rgb,
5651 l_hot_s,
5652 l_par_s,
5653 );
5654 }
5655 } else {
5656 shaded += apply_shadow_strip_span(
5657 row,
5658 (l_act0, l_act1, l_act0),
5659 y_term,
5660 ctx.color_rgb,
5661 l_hot_s,
5662 l_par_s,
5663 );
5664 }
5665 }
5666 if r_act0 < r_act1 {
5667 if cut0 < cut1 {
5668 let a_end: u32 = cut0.min(r_act1);
5669 if r_act0 < a_end {
5670 shaded += apply_shadow_strip_span(
5671 row,
5672 (r_act0, a_end, r_act0),
5673 y_term,
5674 ctx.color_rgb,
5675 r_hot_s,
5676 r_par_s,
5677 );
5678 }
5679 let b_start: u32 = cut1.max(r_act0);
5680 if b_start < r_act1 {
5681 shaded += apply_shadow_strip_span(
5682 row,
5683 (b_start, r_act1, r_act0),
5684 y_term,
5685 ctx.color_rgb,
5686 r_hot_s,
5687 r_par_s,
5688 );
5689 }
5690 } else {
5691 shaded += apply_shadow_strip_span(
5692 row,
5693 (r_act0, r_act1, r_act0),
5694 y_term,
5695 ctx.color_rgb,
5696 r_hot_s,
5697 r_par_s,
5698 );
5699 }
5700 }
5701 }
5702 }
5703 })
5704 .is_ok();
5705 if !ran_tls {
5706 for y in sy0..sy1 {
5707 let Some(row) = band.row_slice_mut(y) else {
5708 continue;
5709 };
5710 let y_term: f32 = (y as f32) * 0.005_837_15;
5711 let (cut0, cut1): (u32, u32) = const_cut
5712 .unwrap_or_else(|| Self::shadow_row_cutout(y, cutouts, ctx.x0, ctx.x1));
5713 let spans: [(u32, u32); 2] = if cut0 < cut1 {
5714 [(ctx.x0, cut0), (cut1, ctx.x1)]
5715 } else {
5716 [(ctx.x0, ctx.x1), (ctx.x1, ctx.x1)]
5717 };
5718 for (rx0, rx1) in spans.into_iter() {
5719 let left_end: u32 = rx1.min(ctx.lx1);
5720 for x in rx0..left_end {
5721 let dist: f32 = ((x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
5722 if dist < ctx.cutoff {
5723 let alpha_f: f32 =
5724 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5725 if alpha_f > 0.0005 {
5726 blend_shadow_row_pixel(
5727 row,
5728 x,
5729 y_term,
5730 ctx.color_rgb,
5731 ctx.lin_rgb,
5732 alpha_f,
5733 );
5734 shaded += 1;
5735 }
5736 }
5737 }
5738 let right_start: u32 = rx0.max(ctx.rx0);
5739 for x in right_start..rx1 {
5740 let dist: f32 = ((x as f32) + 0.5 - ctx.cx).abs() - ctx.half_w;
5741 if dist < ctx.cutoff {
5742 let alpha_f: f32 =
5743 ctx.base_alpha * fast_gaussian_shadow_falloff(dist, ctx.inv_sigma);
5744 if alpha_f > 0.0005 {
5745 blend_shadow_row_pixel(
5746 row,
5747 x,
5748 y_term,
5749 ctx.color_rgb,
5750 ctx.lin_rgb,
5751 alpha_f,
5752 );
5753 shaded += 1;
5754 }
5755 }
5756 }
5757 }
5758 }
5759 }
5760 shaded
5761 }
5762
5763 fn raster_shadow(
5778 band: &mut PixelBand<'_>,
5779 rects: (Rect, Rect, Rect),
5780 radius: CornerRadius,
5781 sigma: f32,
5782 color: Color,
5783 cutouts: (Rect, Rect),
5784 ) -> usize {
5785 let (shadow_rect, caster_rect, clip): (Rect, Rect, Rect) = rects;
5786 if color.get_a() == 0 {
5787 return 0;
5788 }
5789 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
5790 if base_alpha <= 0.0005 {
5791 return 0;
5792 }
5793 let Some(vis) = shadow_rect.intersect(clip) else {
5794 return 0;
5795 };
5796 let fb_w: u32 = band.width();
5797 let band_y0: u32 = band.y_offset();
5798 let band_y1: u32 = band.y_end();
5799 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
5800 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
5801 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
5802 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
5803 if x0 >= x1 || y0 >= y1 {
5804 return 0;
5805 }
5806 let half_w: f32 = (caster_rect.get_width() * 0.5).max(0.5);
5807 let half_h: f32 = (caster_rect.get_height() * 0.5).max(0.5);
5808 let cx: f32 = caster_rect.get_x() + half_w;
5809 let cy: f32 = caster_rect.get_y() + half_h;
5810 let inv_sigma: f32 = 1.0 / sigma.max(0.5);
5811 let cutoff: f32 = sigma * 3.0;
5812 let r_max: f32 = radius.max_radius();
5813 let inner_inset: f32 = cutoff + r_max;
5814 let sy0: u32 = ((caster_rect.get_y() + inner_inset).ceil().max(0.0) as u32).clamp(y0, y1);
5815 let sy1: u32 = ((caster_rect.bottom() - inner_inset).floor().max(0.0) as u32).clamp(y0, y1);
5816 let sx0: u32 = ((caster_rect.get_x() + inner_inset).ceil().max(0.0) as u32).clamp(x0, x1);
5817 let sx1: u32 = ((caster_rect.right() - inner_inset).floor().max(0.0) as u32).clamp(x0, x1);
5818 let has_mid_x: bool = sx0 < sx1;
5819 let has_mid_y: bool = sy0 < sy1;
5820 let r_tl: f32 = radius.get_top_left();
5821 let uniform_radius: bool = r_tl == radius.get_top_right()
5822 && r_tl == radius.get_bottom_right()
5823 && r_tl == radius.get_bottom_left();
5824 let two_cx_f: f32 = 2.0 * cx;
5825 let two_cx_i: i32 = two_cx_f.round() as i32;
5826 let x_symmetric: bool =
5827 uniform_radius && (two_cx_i as f32) == two_cx_f && two_cx_f.abs() < 16_777_216.0;
5828 let two_cy_f: f32 = 2.0 * cy;
5829 let two_cy_i: i32 = two_cy_f.round() as i32;
5830 let y_symmetric: bool =
5831 x_symmetric && (two_cy_i as f32) == two_cy_f && two_cy_f.abs() < 16_777_216.0;
5832 let uniform_r: f32 = r_tl.min(half_w).min(half_h).max(0.0);
5833 let cutoff_r_safe: f32 = cutoff + uniform_r + 1e-3;
5834 let (lx1, rx0): (u32, u32) = if has_mid_x {
5835 (sx0, sx1)
5836 } else if x_symmetric {
5837 let split_x: u32 = ((two_cx_i + 1).div_euclid(2).max(0) as u32).clamp(x0, x1);
5838 (split_x, split_x)
5839 } else {
5840 (x1, x1)
5841 };
5842 let color_rgb: [u8; 3] = [color.get_r(), color.get_g(), color.get_b()];
5843 let lin_rgb: [f32; 3] = [
5844 SRGB_TO_LIN_LUT[color_rgb[0] as usize],
5845 SRGB_TO_LIN_LUT[color_rgb[1] as usize],
5846 SRGB_TO_LIN_LUT[color_rgb[2] as usize],
5847 ];
5848 let ctx: ShadowRenderCtx = ShadowRenderCtx {
5849 color,
5850 color_rgb,
5851 lin_rgb,
5852 cx,
5853 cy,
5854 half_w,
5855 half_h,
5856 base_alpha,
5857 inv_sigma,
5858 cutoff,
5859 uniform_r,
5860 cutoff_r_safe_sq: cutoff_r_safe * cutoff_r_safe,
5861 x0,
5862 x1,
5863 lx1,
5864 rx0,
5865 mirror_x_sum: two_cx_i - 1,
5866 has_mid_x,
5867 };
5868 let mut shaded: usize = 0;
5869 if x_symmetric {
5870 let (top_end, bot_start): (u32, u32) = if has_mid_x && has_mid_y {
5871 (sy0, sy1)
5872 } else if y_symmetric {
5873 let split_y: u32 = ((two_cy_i + 1).div_euclid(2).max(0) as u32).clamp(y0, y1);
5874 (split_y, split_y)
5875 } else {
5876 (y1, y1)
5877 };
5878 let mirror_y_sum: i32 = two_cy_i - 1;
5879 let mut mirrored_b0: u32 = y1;
5880 let mut mirrored_b1: u32 = bot_start;
5881 for y_t in y0..top_end {
5882 let y_b_i: i32 = if y_symmetric {
5883 mirror_y_sum - (y_t as i32)
5884 } else {
5885 -1
5886 };
5887 if y_b_i >= (bot_start as i32) && y_b_i < (y1 as i32) {
5888 let y_b: u32 = y_b_i as u32;
5889 mirrored_b0 = mirrored_b0.min(y_b);
5890 mirrored_b1 = mirrored_b1.max(y_b + 1);
5891 shaded +=
5892 Self::raster_shadow_corner_pair_symmetric(band, &ctx, y_t, y_b, cutouts);
5893 } else {
5894 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_t, cutouts);
5895 }
5896 }
5897 if has_mid_x && has_mid_y {
5898 shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
5899 }
5900 if mirrored_b0 < mirrored_b1 {
5901 for y_b in bot_start..mirrored_b0 {
5902 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
5903 }
5904 for y_b in mirrored_b1..y1 {
5905 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
5906 }
5907 } else {
5908 for y_b in bot_start..y1 {
5909 shaded += Self::raster_shadow_corner_row_symmetric(band, &ctx, y_b, cutouts);
5910 }
5911 }
5912 } else if has_mid_x && has_mid_y {
5913 for y in y0..sy0 {
5914 shaded += Self::raster_shadow_corner_row_general(band, &ctx, radius, y, cutouts);
5915 }
5916 shaded += Self::raster_shadow_vertical_strips(band, &ctx, (sy0, sy1), cutouts);
5917 for y in sy1..y1 {
5918 shaded += Self::raster_shadow_corner_row_general(band, &ctx, radius, y, cutouts);
5919 }
5920 } else {
5921 for y in y0..y1 {
5922 shaded += Self::raster_shadow_corner_row_general(band, &ctx, radius, y, cutouts);
5923 }
5924 }
5925 shaded
5926 }
5927
5928 fn raster_text_run_band(
5942 band: &mut PixelBand<'_>,
5943 positioned_glyphs: &[PositionedGlyph],
5944 color: Color,
5945 clip: Rect,
5946 glyph_atlas: &GlyphAtlas,
5947 ) -> usize {
5948 let fb_w: i32 = band.width() as i32;
5949 let band_y0: i32 = band.y_offset() as i32;
5950 let band_y1: i32 = band.y_end() as i32;
5951 let clip_x0: i32 = clip.get_x().ceil().max(0.0) as i32;
5952 let clip_y0: i32 = (clip.get_y().ceil().max(0.0) as i32).clamp(band_y0, band_y1);
5953 let clip_x1: i32 = (clip.right().floor().max(0.0) as i32).min(fb_w);
5954 let clip_y1: i32 = (clip.bottom().floor().max(0.0) as i32).clamp(band_y0, band_y1);
5955 if color.get_a() == 0 || clip_x0 >= clip_x1 || clip_y0 >= clip_y1 {
5956 return 0;
5957 }
5958 let mut shaded: usize = 0;
5959 for pg in positioned_glyphs.iter() {
5960 let gy0: i32 = pg.y;
5961 let gh: i32 = pg.height as i32;
5962 if gy0 >= clip_y1 || gy0 + gh <= clip_y0 {
5963 continue;
5964 }
5965 let gx0: i32 = pg.x;
5966 let gw: i32 = pg.width as i32;
5967 if gx0 >= clip_x1 || gx0 + gw <= clip_x0 {
5968 continue;
5969 }
5970 let glyph: &RasterizedGlyph = glyph_atlas.glyph_by_slot(pg.glyph_idx);
5971 let py_start: i32 = (clip_y0 - gy0).max(0);
5972 let py_end: i32 = (clip_y1 - gy0).min(gh);
5973 let px_start: i32 = (clip_x0 - gx0).max(0);
5974 let px_end: i32 = (clip_x1 - gx0).min(gw);
5975 if py_start < py_end && px_start < px_end {
5976 let dy0: u32 = (gy0 + py_start) as u32;
5977 let dy1: u32 = (gy0 + py_end) as u32;
5978 if let Some((rows_buf, row_stride)) = band.rows_slice_mut(dy0, dy1) {
5979 let cov_bytes: &[u8] = glyph.get_coverage().as_slice();
5980 let gw_usize: usize = gw as usize;
5981 let bx0: usize = ((gx0 + px_start) as usize) * 4;
5982 let bx1: usize = ((gx0 + px_end) as usize) * 4;
5983 let start_u: usize = px_start as usize;
5984 let end_u: usize = px_end as usize;
5985 let mut cov_off: usize = (py_start as usize) * gw_usize;
5986 for row in rows_buf.chunks_exact_mut(row_stride) {
5987 let row_slice: &[u8] = &cov_bytes[cov_off + start_u..cov_off + end_u];
5988 shaded += blend_glyph_row_span(&mut row[bx0..bx1], row_slice, color);
5989 cov_off += gw_usize;
5990 }
5991 }
5992 }
5993 }
5994 shaded
5995 }
5996
5997 #[inline(always)]
6011 fn blit_bilinear_span_precomputed(
6012 y_params: (usize, usize, u32, u32),
6013 dst_x0: usize,
6014 x_lut: &[(usize, usize, u32)],
6015 src_bytes: &[u8],
6016 dst_row: &mut [u8],
6017 ) -> usize {
6018 let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
6019 let span_bytes_start: usize = dst_x0 * 4;
6020 let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
6021 if span_bytes_end > dst_row.len() {
6022 return 0;
6023 }
6024 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
6025 .as_chunks_mut::<4>()
6026 .0;
6027 let src_len: usize = src_bytes.len();
6028 let mut shaded: usize = 0;
6029 if wy == 0 {
6030 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
6031 let i0: usize = (row0 + sx0) * 4;
6032 let i1: usize = (row0 + sx1) * 4;
6033 if i1 + 4 > src_len {
6034 continue;
6035 }
6036 let iwx: u32 = 256 - wx;
6037 let a0: u32 = src_bytes[i0 + 3] as u32;
6038 let a1: u32 = src_bytes[i1 + 3] as u32;
6039 if (a0 & a1) == 255 {
6040 dp[0] = (((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128)
6041 >> 8) as u8;
6042 dp[1] =
6043 (((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128)
6044 >> 8) as u8;
6045 dp[2] =
6046 (((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128)
6047 >> 8) as u8;
6048 dp[3] = 255;
6049 shaded += 1;
6050 continue;
6051 }
6052 let a_val: u32 = (a0 * iwx + a1 * wx + 128) >> 8;
6053 if a_val == 0 {
6054 continue;
6055 }
6056 let r: u32 =
6057 ((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128) >> 8;
6058 let g: u32 =
6059 ((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128) >> 8;
6060 let b: u32 =
6061 ((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128) >> 8;
6062 let inv_a: u32 = 255 - a_val;
6063 let vr: u32 = r * a_val + (dp[0] as u32) * inv_a + 128;
6064 let vg: u32 = g * a_val + (dp[1] as u32) * inv_a + 128;
6065 let vb: u32 = b * a_val + (dp[2] as u32) * inv_a + 128;
6066 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
6067 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
6068 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
6069 dp[3] = 255;
6070 shaded += 1;
6071 }
6072 return shaded;
6073 }
6074 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
6075 let i00: usize = (row0 + sx0) * 4;
6076 let i10: usize = (row0 + sx1) * 4;
6077 let i01: usize = (row1 + sx0) * 4;
6078 let i11: usize = (row1 + sx1) * 4;
6079 if i11 + 4 > src_len {
6080 continue;
6081 }
6082 let iwx: u32 = 256 - wx;
6083 let w00: u32 = iwx * iwy;
6084 let w10: u32 = wx * iwy;
6085 let w01: u32 = iwx * wy;
6086 let w11: u32 = wx * wy;
6087 let a00: u32 = src_bytes[i00 + 3] as u32;
6088 let a10: u32 = src_bytes[i10 + 3] as u32;
6089 let a01: u32 = src_bytes[i01 + 3] as u32;
6090 let a11: u32 = src_bytes[i11 + 3] as u32;
6091 if (a00 & a10 & a01 & a11) == 255 {
6092 dp[0] = (((src_bytes[i00] as u32) * w00
6093 + (src_bytes[i10] as u32) * w10
6094 + (src_bytes[i01] as u32) * w01
6095 + (src_bytes[i11] as u32) * w11
6096 + 32768)
6097 >> 16) as u8;
6098 dp[1] = (((src_bytes[i00 + 1] as u32) * w00
6099 + (src_bytes[i10 + 1] as u32) * w10
6100 + (src_bytes[i01 + 1] as u32) * w01
6101 + (src_bytes[i11 + 1] as u32) * w11
6102 + 32768)
6103 >> 16) as u8;
6104 dp[2] = (((src_bytes[i00 + 2] as u32) * w00
6105 + (src_bytes[i10 + 2] as u32) * w10
6106 + (src_bytes[i01 + 2] as u32) * w01
6107 + (src_bytes[i11 + 2] as u32) * w11
6108 + 32768)
6109 >> 16) as u8;
6110 dp[3] = 255;
6111 shaded += 1;
6112 continue;
6113 }
6114 let a_val: u32 = (a00 * w00 + a10 * w10 + a01 * w01 + a11 * w11 + 32768) >> 16;
6115 if a_val == 0 {
6116 continue;
6117 }
6118 let r: u32 = ((src_bytes[i00] as u32) * w00
6119 + (src_bytes[i10] as u32) * w10
6120 + (src_bytes[i01] as u32) * w01
6121 + (src_bytes[i11] as u32) * w11
6122 + 32768)
6123 >> 16;
6124 let g: u32 = ((src_bytes[i00 + 1] as u32) * w00
6125 + (src_bytes[i10 + 1] as u32) * w10
6126 + (src_bytes[i01 + 1] as u32) * w01
6127 + (src_bytes[i11 + 1] as u32) * w11
6128 + 32768)
6129 >> 16;
6130 let b: u32 = ((src_bytes[i00 + 2] as u32) * w00
6131 + (src_bytes[i10 + 2] as u32) * w10
6132 + (src_bytes[i01 + 2] as u32) * w01
6133 + (src_bytes[i11 + 2] as u32) * w11
6134 + 32768)
6135 >> 16;
6136 let inv_a: u32 = 255 - a_val;
6137 let vr: u32 = r * a_val + (dp[0] as u32) * inv_a + 128;
6138 let vg: u32 = g * a_val + (dp[1] as u32) * inv_a + 128;
6139 let vb: u32 = b * a_val + (dp[2] as u32) * inv_a + 128;
6140 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
6141 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
6142 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
6143 dp[3] = 255;
6144 shaded += 1;
6145 }
6146 shaded
6147 }
6148
6149 fn raster_image_bilinear_with_lut(
6165 band: &mut PixelBand<'_>,
6166 rect: Rect,
6167 src_info: (u32, u32, &[u8]),
6168 bounds: (u32, u32, u32, u32),
6169 radius: CornerRadius,
6170 aa: AntialiasingMode,
6171 x_lut: &mut Vec<(usize, usize, u32)>,
6172 ) -> usize {
6173 let (src_w, src_h, src_bytes): (u32, u32, &[u8]) = src_info;
6174 let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
6175 let rect_x: f32 = rect.get_x();
6176 let rect_y: f32 = rect.get_y();
6177 let half_w: f32 = rect.get_width() * 0.5;
6178 let half_h: f32 = rect.get_height() * 0.5;
6179 let cx: f32 = rect_x + half_w;
6180 let cy: f32 = rect_y + half_h;
6181 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
6182 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
6183 let src_w_f: f32 = src_w as f32;
6184 let src_h_f: f32 = src_h as f32;
6185 let src_w_usize: usize = src_w as usize;
6186 let max_sx: usize = src_w_usize.saturating_sub(1);
6187 let max_sy: usize = (src_h as usize).saturating_sub(1);
6188 let has_radius: bool = radius.max_radius() > 0.0;
6189 x_lut.clear();
6190 for x in x0..x1 {
6191 let u: f32 = (((x as f32) + 0.5 - rect_x) * inv_dst_w).clamp(0.0, 1.0);
6192 let fx: f32 = (u * src_w_f - 0.5).clamp(0.0, max_sx as f32);
6193 let sx0: usize = (fx.floor() as usize).min(max_sx);
6194 let sx1: usize = (sx0 + 1).min(max_sx);
6195 let wx: u32 = ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
6196 x_lut.push((sx0, sx1, wx));
6197 }
6198 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
6199 if !has_radius {
6200 let x0_u: usize = x0 as usize;
6201 for y in y0..y1 {
6202 let Some(dst_row) = band.row_slice_mut(y) else {
6203 continue;
6204 };
6205 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
6206 let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
6207 let sy0: usize = (fy.floor() as usize).min(max_sy);
6208 let sy1: usize = (sy0 + 1).min(max_sy);
6209 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
6210 let y_params: (usize, usize, u32, u32) =
6211 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
6212 let _: usize = Self::blit_bilinear_span_precomputed(
6213 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
6214 );
6215 }
6216 return ((x1 - x0) as usize) * ((y1 - y0) as usize);
6217 }
6218 let r_max: f32 = radius.max_radius().min(half_w).min(half_h).max(0.0);
6219 let ix0: u32 = ((rect_x + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
6220 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
6221 let iy0: u32 = ((rect_y + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
6222 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
6223 let cx0: u32 = ((rect_x + r_max + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
6224 let cx1: u32 = ((rect.right() - r_max - 1.0).floor().max(0.0) as u32).clamp(cx0, x1);
6225 let mut shaded: usize = 0;
6226 for y in y0..iy0 {
6227 let Some(dst_row) = band.row_slice_mut(y) else {
6228 continue;
6229 };
6230 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
6231 let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
6232 let sy0: usize = (fy.floor() as usize).min(max_sy);
6233 let sy1: usize = (sy0 + 1).min(max_sy);
6234 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
6235 let y_params: (usize, usize, u32, u32) =
6236 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
6237 let py: f32 = (y as f32) + 0.5 - cy;
6238 let dist_y: f32 = py.abs() - half_h;
6239 let mid_cov: f32 = sdf_coverage(dist_y, aa);
6240 if cx0 < cx1 && mid_cov > 0.0 {
6241 let lut_s: usize = (cx0 - x0) as usize;
6242 let lut_e: usize = (cx1 - x0) as usize;
6243 if mid_cov >= 0.9995 {
6244 let _: usize = Self::blit_bilinear_span_precomputed(
6245 y_params,
6246 cx0 as usize,
6247 &x_lut_ref[lut_s..lut_e],
6248 src_bytes,
6249 dst_row,
6250 );
6251 } else {
6252 for x in cx0..cx1 {
6253 let rgba: [u8; 4] = sample_bilinear_fixed(
6254 src_bytes,
6255 y_params,
6256 x_lut_ref[(x - x0) as usize],
6257 );
6258 let off: usize = (x as usize) * 4;
6259 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
6260 }
6261 }
6262 shaded += (cx1 - cx0) as usize;
6263 }
6264 for x in x0..cx0 {
6265 let px: f32 = (x as f32) + 0.5 - cx;
6266 let cr: f32 = quadrant_corner_radius(radius, px, py);
6267 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
6268 if cov > 0.0 {
6269 let rgba: [u8; 4] =
6270 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
6271 let off: usize = (x as usize) * 4;
6272 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
6273 shaded += 1;
6274 }
6275 }
6276 for x in cx1..x1 {
6277 let px: f32 = (x as f32) + 0.5 - cx;
6278 let cr: f32 = quadrant_corner_radius(radius, px, py);
6279 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
6280 if cov > 0.0 {
6281 let rgba: [u8; 4] =
6282 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
6283 let off: usize = (x as usize) * 4;
6284 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
6285 shaded += 1;
6286 }
6287 }
6288 }
6289 for y in iy0..iy1 {
6290 let Some(dst_row) = band.row_slice_mut(y) else {
6291 continue;
6292 };
6293 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
6294 let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
6295 let sy0: usize = (fy.floor() as usize).min(max_sy);
6296 let sy1: usize = (sy0 + 1).min(max_sy);
6297 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
6298 let y_params: (usize, usize, u32, u32) =
6299 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
6300 if ix0 < ix1 {
6301 let lut_s: usize = (ix0 - x0) as usize;
6302 let lut_e: usize = (ix1 - x0) as usize;
6303 let _: usize = Self::blit_bilinear_span_precomputed(
6304 y_params,
6305 ix0 as usize,
6306 &x_lut_ref[lut_s..lut_e],
6307 src_bytes,
6308 dst_row,
6309 );
6310 shaded += (ix1 - ix0) as usize;
6311 }
6312 for x in x0..ix0 {
6313 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
6314 let cov: f32 = sdf_coverage(dist, aa);
6315 if cov > 0.0 {
6316 let rgba: [u8; 4] =
6317 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
6318 let off: usize = (x as usize) * 4;
6319 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
6320 shaded += 1;
6321 }
6322 }
6323 for x in ix1..x1 {
6324 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
6325 let cov: f32 = sdf_coverage(dist, aa);
6326 if cov > 0.0 {
6327 let rgba: [u8; 4] =
6328 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
6329 let off: usize = (x as usize) * 4;
6330 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
6331 shaded += 1;
6332 }
6333 }
6334 }
6335 for y in iy1..y1 {
6336 let Some(dst_row) = band.row_slice_mut(y) else {
6337 continue;
6338 };
6339 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_dst_h).clamp(0.0, 1.0);
6340 let fy: f32 = (v * src_h_f - 0.5).clamp(0.0, max_sy as f32);
6341 let sy0: usize = (fy.floor() as usize).min(max_sy);
6342 let sy1: usize = (sy0 + 1).min(max_sy);
6343 let wy: u32 = ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32;
6344 let y_params: (usize, usize, u32, u32) =
6345 (sy0 * src_w_usize, sy1 * src_w_usize, wy, 256 - wy);
6346 let py: f32 = (y as f32) + 0.5 - cy;
6347 let dist_y: f32 = py.abs() - half_h;
6348 let mid_cov: f32 = sdf_coverage(dist_y, aa);
6349 if cx0 < cx1 && mid_cov > 0.0 {
6350 let lut_s: usize = (cx0 - x0) as usize;
6351 let lut_e: usize = (cx1 - x0) as usize;
6352 if mid_cov >= 0.9995 {
6353 let _: usize = Self::blit_bilinear_span_precomputed(
6354 y_params,
6355 cx0 as usize,
6356 &x_lut_ref[lut_s..lut_e],
6357 src_bytes,
6358 dst_row,
6359 );
6360 } else {
6361 for x in cx0..cx1 {
6362 let rgba: [u8; 4] = sample_bilinear_fixed(
6363 src_bytes,
6364 y_params,
6365 x_lut_ref[(x - x0) as usize],
6366 );
6367 let off: usize = (x as usize) * 4;
6368 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, mid_cov);
6369 }
6370 }
6371 shaded += (cx1 - cx0) as usize;
6372 }
6373 for x in x0..cx0 {
6374 let px: f32 = (x as f32) + 0.5 - cx;
6375 let cr: f32 = quadrant_corner_radius(radius, px, py);
6376 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
6377 if cov > 0.0 {
6378 let rgba: [u8; 4] =
6379 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
6380 let off: usize = (x as usize) * 4;
6381 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
6382 shaded += 1;
6383 }
6384 }
6385 for x in cx1..x1 {
6386 let px: f32 = (x as f32) + 0.5 - cx;
6387 let cr: f32 = quadrant_corner_radius(radius, px, py);
6388 let cov: f32 = sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa);
6389 if cov > 0.0 {
6390 let rgba: [u8; 4] =
6391 sample_bilinear_fixed(src_bytes, y_params, x_lut_ref[(x - x0) as usize]);
6392 let off: usize = (x as usize) * 4;
6393 blend_rgba_pixel_with_cov(&mut dst_row[off..off + 4], rgba, cov);
6394 shaded += 1;
6395 }
6396 }
6397 }
6398 shaded
6399 }
6400
6401 fn raster_image(
6416 band: &mut PixelBand<'_>,
6417 rect: Rect,
6418 buffer: &ImageBuffer,
6419 radius: CornerRadius,
6420 clip: Rect,
6421 aa: AntialiasingMode,
6422 ) -> usize {
6423 if buffer.get_width() == 0 || buffer.get_height() == 0 {
6424 return 0;
6425 }
6426 let Some(vis) = rect.intersect(clip) else {
6427 return 0;
6428 };
6429 let fb_w: u32 = band.width();
6430 let band_y0: u32 = band.y_offset();
6431 let band_y1: u32 = band.y_end();
6432 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6433 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6434 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6435 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6436 if x0 >= x1 || y0 >= y1 {
6437 return 0;
6438 }
6439 let half_w: f32 = rect.get_width() * 0.5;
6440 let half_h: f32 = rect.get_height() * 0.5;
6441 let cx: f32 = rect.get_x() + half_w;
6442 let cy: f32 = rect.get_y() + half_h;
6443 let src_w: u32 = buffer.get_width();
6444 let src_h: u32 = buffer.get_height();
6445 let src_bytes: &[u8] = buffer.get_pixels().as_slice();
6446 let inv_dst_w: f32 = 1.0 / rect.get_width().max(1.0);
6447 let inv_dst_h: f32 = 1.0 / rect.get_height().max(1.0);
6448 let use_bilinear: bool = aa != AntialiasingMode::None
6449 && ((rect.get_width() - (src_w as f32)).abs() > 0.5
6450 || (rect.get_height() - (src_h as f32)).abs() > 0.5);
6451 let has_radius: bool = radius.max_radius() > 0.0;
6452 let max_sx: usize = (src_w as usize).saturating_sub(1);
6453 let max_sy: usize = (src_h as usize).saturating_sub(1);
6454 let src_w_usize: usize = src_w as usize;
6455 let is_exact_1to1: bool = !use_bilinear
6456 && (rect.get_width() - (src_w as f32)).abs() <= 0.01
6457 && (rect.get_height() - (src_h as f32)).abs() <= 0.01
6458 && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
6459 && (rect.get_y() - rect.get_y().round()).abs() <= 0.01;
6460 let rx0_i: i32 = rect.get_x().round() as i32;
6461 let ry0_i: i32 = rect.get_y().round() as i32;
6462 if is_exact_1to1
6463 && !has_radius
6464 && (x0 as i32) >= rx0_i
6465 && (x1 as i32) <= rx0_i + (src_w as i32)
6466 && (y0 as i32) >= ry0_i
6467 && (y1 as i32) <= ry0_i + (src_h as i32)
6468 {
6469 let span_w: usize = (x1 - x0) as usize;
6470 let src_x_off: usize = ((x0 as i32) - rx0_i) as usize;
6471 let dst_byte0: usize = (x0 as usize) * 4;
6472 let dst_byte1: usize = (x1 as usize) * 4;
6473 for y in y0..y1 {
6474 let Some(dst_row) = band.row_slice_mut(y) else {
6475 continue;
6476 };
6477 let sy: usize = ((y as i32) - ry0_i) as usize;
6478 let src_byte0: usize = (sy * src_w_usize + src_x_off) * 4;
6479 let src_byte1: usize = src_byte0 + span_w * 4;
6480 if src_byte1 <= src_bytes.len() && dst_byte1 <= dst_row.len() {
6481 blit_1to1_rgba_span(
6482 &src_bytes[src_byte0..src_byte1],
6483 &mut dst_row[dst_byte0..dst_byte1],
6484 );
6485 }
6486 }
6487 return span_w * ((y1 - y0) as usize);
6488 }
6489 if use_bilinear {
6490 let mut shaded: usize = 0;
6491 let ran_tls: bool = BAND_IMAGE_X_LUT
6492 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
6493 if let Ok(mut guard) = cell.try_borrow_mut() {
6494 shaded = Self::raster_image_bilinear_with_lut(
6495 band,
6496 rect,
6497 (src_w, src_h, src_bytes),
6498 (x0, y0, x1, y1),
6499 radius,
6500 aa,
6501 &mut guard,
6502 );
6503 }
6504 })
6505 .is_ok();
6506 if !ran_tls {
6507 let mut fallback_lut: Vec<(usize, usize, u32)> =
6508 Vec::with_capacity((x1 - x0) as usize);
6509 shaded = Self::raster_image_bilinear_with_lut(
6510 band,
6511 rect,
6512 (src_w, src_h, src_bytes),
6513 (x0, y0, x1, y1),
6514 radius,
6515 aa,
6516 &mut fallback_lut,
6517 );
6518 }
6519 return shaded;
6520 }
6521 let mut shaded: usize = 0;
6522 let r_max: f32 = if has_radius {
6523 radius.max_radius().min(half_w).min(half_h).max(0.0)
6524 } else {
6525 0.0
6526 };
6527 let ix0: u32 = ((rect.get_x() + 1.0).ceil().max(0.0) as u32).clamp(x0, x1);
6528 let ix1: u32 = ((rect.right() - 1.0).floor().max(0.0) as u32).clamp(ix0, x1);
6529 let iy0: u32 = ((rect.get_y() + r_max + 1.0).ceil().max(0.0) as u32).clamp(y0, y1);
6530 let iy1: u32 = ((rect.bottom() - r_max - 1.0).floor().max(0.0) as u32).clamp(iy0, y1);
6531 let can_1to1_interior: bool = is_exact_1to1
6532 && (ix0 as i32) >= rx0_i
6533 && (ix1 as i32) <= rx0_i + (src_w as i32)
6534 && (iy0 as i32) >= ry0_i
6535 && (iy1 as i32) <= ry0_i + (src_h as i32);
6536 for y in y0..y1 {
6537 let Some(dst_row) = band.row_slice_mut(y) else {
6538 continue;
6539 };
6540 let v: f32 = (((y as f32) + 0.5 - rect.get_y()) * inv_dst_h).clamp(0.0, 1.0);
6541 let py: f32 = (y as f32) + 0.5 - cy;
6542 let sy: usize = ((v * (src_h as f32)).floor() as usize).min(max_sy);
6543 let row: usize = sy * src_w_usize;
6544 if has_radius && can_1to1_interior && y >= iy0 && y < iy1 && ix0 < ix1 {
6545 let src_off: usize = (row + (((ix0 as i32) - rx0_i) as usize)) * 4;
6546 let span_bytes: usize = ((ix1 - ix0) as usize) * 4;
6547 let dst_off: usize = (ix0 as usize) * 4;
6548 if src_off + span_bytes <= src_bytes.len() && dst_off + span_bytes <= dst_row.len()
6549 {
6550 blit_1to1_rgba_span(
6551 &src_bytes[src_off..src_off + span_bytes],
6552 &mut dst_row[dst_off..dst_off + span_bytes],
6553 );
6554 }
6555 shaded += (ix1 - ix0) as usize;
6556 for x in x0..ix0 {
6557 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
6558 let cov: f32 = sdf_coverage(dist, aa);
6559 if cov > 0.0 {
6560 let u: f32 =
6561 (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
6562 let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
6563 let idx: usize = (row + sx) * 4;
6564 if idx + 4 <= src_bytes.len() {
6565 let off: usize = (x as usize) * 4;
6566 blend_rgba_pixel_with_cov(
6567 &mut dst_row[off..off + 4],
6568 [
6569 src_bytes[idx],
6570 src_bytes[idx + 1],
6571 src_bytes[idx + 2],
6572 src_bytes[idx + 3],
6573 ],
6574 cov,
6575 );
6576 shaded += 1;
6577 }
6578 }
6579 }
6580 for x in ix1..x1 {
6581 let dist: f32 = ((x as f32) + 0.5 - cx).abs() - half_w;
6582 let cov: f32 = sdf_coverage(dist, aa);
6583 if cov > 0.0 {
6584 let u: f32 =
6585 (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
6586 let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
6587 let idx: usize = (row + sx) * 4;
6588 if idx + 4 <= src_bytes.len() {
6589 let off: usize = (x as usize) * 4;
6590 blend_rgba_pixel_with_cov(
6591 &mut dst_row[off..off + 4],
6592 [
6593 src_bytes[idx],
6594 src_bytes[idx + 1],
6595 src_bytes[idx + 2],
6596 src_bytes[idx + 3],
6597 ],
6598 cov,
6599 );
6600 shaded += 1;
6601 }
6602 }
6603 }
6604 continue;
6605 }
6606 for x in x0..x1 {
6607 let cov: f32 = if has_radius {
6608 let px: f32 = (x as f32) + 0.5 - cx;
6609 let cr: f32 = quadrant_corner_radius(radius, px, py);
6610 sdf_coverage(rounded_box_sdf(px, py, half_w, half_h, cr), aa)
6611 } else {
6612 1.0
6613 };
6614 if cov <= 0.0 {
6615 continue;
6616 }
6617 let u: f32 = (((x as f32) + 0.5 - rect.get_x()) * inv_dst_w).clamp(0.0, 1.0);
6618 let sx: usize = ((u * (src_w as f32)).floor() as usize).min(max_sx);
6619 let idx: usize = (row + sx) * 4;
6620 if idx + 4 <= src_bytes.len() {
6621 let off: usize = (x as usize) * 4;
6622 blend_rgba_pixel_with_cov(
6623 &mut dst_row[off..off + 4],
6624 [
6625 src_bytes[idx],
6626 src_bytes[idx + 1],
6627 src_bytes[idx + 2],
6628 src_bytes[idx + 3],
6629 ],
6630 cov,
6631 );
6632 shaded += 1;
6633 }
6634 }
6635 }
6636 shaded
6637 }
6638
6639 fn raster_line(
6655 band: &mut PixelBand<'_>,
6656 from: Point,
6657 to: Point,
6658 color: Color,
6659 width: f32,
6660 clip: Rect,
6661 aa: AntialiasingMode,
6662 ) -> usize {
6663 if color.get_a() == 0 {
6664 return 0;
6665 }
6666 let half_w: f32 = width * 0.5;
6667 let min_x: f32 = from.get_x().min(to.get_x()) - half_w - 1.0;
6668 let min_y: f32 = from.get_y().min(to.get_y()) - half_w - 1.0;
6669 let max_x: f32 = from.get_x().max(to.get_x()) + half_w + 1.0;
6670 let max_y: f32 = from.get_y().max(to.get_y()) + half_w + 1.0;
6671 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
6672 else {
6673 return 0;
6674 };
6675 let fb_w: u32 = band.width();
6676 let band_y0: u32 = band.y_offset();
6677 let band_y1: u32 = band.y_end();
6678 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6679 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6680 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6681 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6682 if x0 >= x1 || y0 >= y1 {
6683 return 0;
6684 }
6685 let fx0: f32 = from.get_x();
6686 let fy0: f32 = from.get_y();
6687 let dx: f32 = to.get_x() - fx0;
6688 let dy: f32 = to.get_y() - fy0;
6689 let len_sq: f32 = (dx * dx + dy * dy).max(1e-6);
6690 let inv_len_sq: f32 = 1.0 / len_sq;
6691 let outer_r: f32 = half_w + 0.9;
6692 let outer_r_sq: f32 = outer_r * outer_r;
6693 let inner_r: f32 = (half_w - 0.9).max(0.0);
6694 let inner_r_sq: f32 = inner_r * inner_r;
6695 let has_inner: bool = half_w > 0.9;
6696 let use_oriented_x: bool = dy.abs() > 1e-4;
6697 let slope_x_per_y: f32 = if use_oriented_x { dx / dy } else { 0.0 };
6698 let x_pad: f32 = if use_oriented_x {
6699 outer_r * (len_sq.sqrt() / dy.abs()) + 0.5
6700 } else {
6701 0.0
6702 };
6703 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
6704 let lin_rgb: [f32; 3] = [
6705 SRGB_TO_LIN_LUT[color.get_r() as usize],
6706 SRGB_TO_LIN_LUT[color.get_g() as usize],
6707 SRGB_TO_LIN_LUT[color.get_b() as usize],
6708 ];
6709 let mut shaded: usize = 0;
6710 for y in y0..y1 {
6711 let py: f32 = (y as f32) + 0.5;
6712 let py_off: f32 = py - fy0;
6713 let (row_x0, row_x1): (u32, u32) = if use_oriented_x {
6714 let x_center: f32 = fx0 + py_off * slope_x_per_y;
6715 let rx0: u32 = ((x_center - x_pad).floor().max(0.0) as u32).clamp(x0, x1);
6716 let rx1: u32 = ((x_center + x_pad).ceil().max(0.0) as u32).clamp(rx0, x1);
6717 (rx0, rx1)
6718 } else {
6719 (x0, x1)
6720 };
6721 if row_x0 >= row_x1 {
6722 continue;
6723 }
6724 let Some(row) = band.row_slice_mut(y) else {
6725 continue;
6726 };
6727 let py_dy: f32 = py_off * dy;
6728 for x in row_x0..row_x1 {
6729 let px: f32 = (x as f32) + 0.5;
6730 let t: f32 = (((px - fx0) * dx + py_dy) * inv_len_sq).clamp(0.0, 1.0);
6731 let dpx: f32 = px - (fx0 + t * dx);
6732 let dpy: f32 = py - (fy0 + t * dy);
6733 let dist_sq: f32 = dpx * dpx + dpy * dpy;
6734 if dist_sq >= outer_r_sq {
6735 continue;
6736 }
6737 let cov: f32 = if has_inner && dist_sq <= inner_r_sq {
6738 1.0
6739 } else {
6740 sdf_coverage(dist_sq.sqrt() - half_w, aa)
6741 };
6742 if cov > 0.0 {
6743 blend_row_pixel_f32_precomputed(row, x, color, lin_rgb, base_alpha * cov);
6744 shaded += 1;
6745 }
6746 }
6747 }
6748 shaded
6749 }
6750
6751 fn raster_circle(
6766 band: &mut PixelBand<'_>,
6767 center: Point,
6768 radius: f32,
6769 color: Color,
6770 clip: Rect,
6771 aa: AntialiasingMode,
6772 ) -> usize {
6773 if radius <= 0.0 || color.get_a() == 0 {
6774 return 0;
6775 }
6776 let bounds: Rect = Rect::new(
6777 center.get_x() - radius - 1.0,
6778 center.get_y() - radius - 1.0,
6779 (radius + 1.0) * 2.0,
6780 (radius + 1.0) * 2.0,
6781 );
6782 let Some(vis) = bounds.intersect(clip) else {
6783 return 0;
6784 };
6785 let fb_w: u32 = band.width();
6786 let band_y0: u32 = band.y_offset();
6787 let band_y1: u32 = band.y_end();
6788 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6789 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6790 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6791 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6792 if x0 >= x1 || y0 >= y1 {
6793 return 0;
6794 }
6795 let outer_r: f32 = if aa == AntialiasingMode::None {
6796 radius + 0.5
6797 } else {
6798 radius + 0.65
6799 };
6800 let inner_r: f32 = if aa == AntialiasingMode::None {
6801 (radius - 0.5).max(0.0)
6802 } else {
6803 (radius - 0.65).max(0.0)
6804 };
6805 let outer_r2: f32 = outer_r * outer_r;
6806 let inner_r2: f32 = inner_r * inner_r;
6807 let r2: f32 = radius * radius;
6808 let cx: f32 = center.get_x();
6809 let cy: f32 = center.get_y();
6810 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
6811 let lin_rgb: [f32; 3] = [
6812 SRGB_TO_LIN_LUT[color.get_r() as usize],
6813 SRGB_TO_LIN_LUT[color.get_g() as usize],
6814 SRGB_TO_LIN_LUT[color.get_b() as usize],
6815 ];
6816 let interior_luts: Option<RgbaLutQuad> = if color.get_a() < 255 && radius >= 12.0 {
6817 Some(build_linear_blend_luts(color))
6818 } else {
6819 None
6820 };
6821 let mut shaded: usize = 0;
6822 for y in y0..y1 {
6823 let dy: f32 = (y as f32) + 0.5 - cy;
6824 let dy2: f32 = dy * dy;
6825 if dy2 >= outer_r2 {
6826 continue;
6827 }
6828 let out_dx: f32 = (outer_r2 - dy2).sqrt();
6829 let row_x0: u32 = ((cx - out_dx).floor().max(0.0) as u32).clamp(x0, x1);
6830 let row_x1: u32 = ((cx + out_dx).ceil().max(0.0) as u32).clamp(row_x0, x1);
6831 if row_x0 >= row_x1 {
6832 continue;
6833 }
6834 if dy2 < inner_r2 && inner_r > 0.65 {
6835 let in_dx: f32 = (inner_r2 - dy2).sqrt();
6836 let in_x0: u32 = ((cx - in_dx).ceil().max(0.0) as u32).clamp(row_x0, row_x1);
6837 let in_x1: u32 = ((cx + in_dx).floor().max(0.0) as u32).clamp(in_x0, row_x1);
6838 if in_x0 < in_x1 {
6839 if let Some(ref luts) = interior_luts {
6840 band.fill_span_linear_luts(in_x0, in_x1, y, luts);
6841 } else {
6842 band.fill_span_linear(in_x0, in_x1, y, color);
6843 }
6844 shaded += (in_x1 - in_x0) as usize;
6845 }
6846 if (row_x0 < in_x0 || in_x1 < row_x1)
6847 && let Some(row) = band.row_slice_mut(y)
6848 {
6849 for x in row_x0..in_x0 {
6850 let dx: f32 = (x as f32) + 0.5 - cx;
6851 let cov: f32 = if aa == AntialiasingMode::None {
6852 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
6853 } else {
6854 circle_supersampled_coverage(dx, dy, radius)
6855 };
6856 if cov > 0.0 {
6857 blend_row_pixel_f32_precomputed(
6858 row,
6859 x,
6860 color,
6861 lin_rgb,
6862 base_alpha * cov,
6863 );
6864 shaded += 1;
6865 }
6866 }
6867 for x in in_x1..row_x1 {
6868 let dx: f32 = (x as f32) + 0.5 - cx;
6869 let cov: f32 = if aa == AntialiasingMode::None {
6870 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
6871 } else {
6872 circle_supersampled_coverage(dx, dy, radius)
6873 };
6874 if cov > 0.0 {
6875 blend_row_pixel_f32_precomputed(
6876 row,
6877 x,
6878 color,
6879 lin_rgb,
6880 base_alpha * cov,
6881 );
6882 shaded += 1;
6883 }
6884 }
6885 }
6886 } else if let Some(row) = band.row_slice_mut(y) {
6887 for x in row_x0..row_x1 {
6888 let dx: f32 = (x as f32) + 0.5 - cx;
6889 let cov: f32 = if aa == AntialiasingMode::None {
6890 if dx * dx + dy2 <= r2 { 1.0 } else { 0.0 }
6891 } else {
6892 circle_supersampled_coverage(dx, dy, radius)
6893 };
6894 if cov > 0.0 {
6895 blend_row_pixel_f32_precomputed(row, x, color, lin_rgb, base_alpha * cov);
6896 shaded += 1;
6897 }
6898 }
6899 }
6900 }
6901 shaded
6902 }
6903
6904 #[inline(always)]
6917 #[must_use]
6918 fn solve_triangle_scanline_interval(
6919 d_base: [f32; 3],
6920 a_step: [f32; 3],
6921 thresh: f32,
6922 max_s: f32,
6923 ) -> (f32, f32) {
6924 let mut s_min: f32 = 0.0;
6925 let mut s_max: f32 = max_s;
6926 for idx in 0..3usize {
6927 let a: f32 = a_step[idx];
6928 let d: f32 = d_base[idx];
6929 if a > 1e-6 {
6930 let bound: f32 = (thresh - d) / a;
6931 if bound > s_min {
6932 s_min = bound;
6933 }
6934 } else if a < -1e-6 {
6935 let bound: f32 = (thresh - d) / a;
6936 if bound < s_max {
6937 s_max = bound;
6938 }
6939 } else if d < thresh {
6940 return (1.0, 0.0);
6941 }
6942 }
6943 (s_min, s_max)
6944 }
6945
6946 fn raster_triangle(
6962 band: &mut PixelBand<'_>,
6963 p0: Point,
6964 p1: Point,
6965 p2: Point,
6966 color: Color,
6967 clip: Rect,
6968 aa: AntialiasingMode,
6969 ) -> usize {
6970 if color.get_a() == 0 {
6971 return 0;
6972 }
6973 let dx0: f32 = p1.get_x() - p0.get_x();
6974 let dy0: f32 = p1.get_y() - p0.get_y();
6975 let dx1: f32 = p2.get_x() - p1.get_x();
6976 let dy1: f32 = p2.get_y() - p1.get_y();
6977 let dx2: f32 = p0.get_x() - p2.get_x();
6978 let dy2: f32 = p0.get_y() - p2.get_y();
6979 let area: f32 = dx0 * (p2.get_y() - p0.get_y()) - dy0 * (p2.get_x() - p0.get_x());
6980 if area.abs() < 1e-5 {
6981 return 0;
6982 }
6983 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) - 1.0;
6984 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) - 1.0;
6985 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) + 1.0;
6986 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) + 1.0;
6987 let Some(vis) = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y).intersect(clip)
6988 else {
6989 return 0;
6990 };
6991 let fb_w: u32 = band.width();
6992 let band_y0: u32 = band.y_offset();
6993 let band_y1: u32 = band.y_end();
6994 let clip_x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
6995 let clip_x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
6996 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
6997 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
6998 if clip_x0 >= clip_x1 || y0 >= y1 {
6999 return 0;
7000 }
7001 if aa == AntialiasingMode::None {
7002 let edges: [(Point, Point); 3] = [(p0, p1), (p1, p2), (p2, p0)];
7003 let mut shaded: usize = 0;
7004 for y in y0..y1 {
7005 let py: f32 = (y as f32) + 0.5;
7006 let mut min_ix: f32 = f32::INFINITY;
7007 let mut max_ix: f32 = f32::NEG_INFINITY;
7008 for (a, b) in edges.iter() {
7009 let ay: f32 = a.get_y();
7010 let by: f32 = b.get_y();
7011 if (ay <= py && by > py) || (by <= py && ay > py) {
7012 let t: f32 = (py - ay) / (by - ay);
7013 let ix: f32 = a.get_x() + t * (b.get_x() - a.get_x());
7014 min_ix = min_ix.min(ix);
7015 max_ix = max_ix.max(ix);
7016 }
7017 }
7018 if min_ix <= max_ix {
7019 let sx0: u32 = (min_ix.floor().max(0.0) as u32).clamp(clip_x0, clip_x1);
7020 let sx1: u32 = (max_ix.ceil().max(0.0) as u32).clamp(clip_x0, clip_x1);
7021 if sx0 < sx1 {
7022 band.fill_span_linear(sx0, sx1, y, color);
7023 shaded += (sx1 - sx0) as usize;
7024 }
7025 }
7026 }
7027 return shaded;
7028 }
7029 let sign: f32 = if area > 0.0 { 1.0 } else { -1.0 };
7030 let inv_l0: f32 = sign / dx0.hypot(dy0).max(1e-5);
7031 let inv_l1: f32 = sign / dx1.hypot(dy1).max(1e-5);
7032 let inv_l2: f32 = sign / dx2.hypot(dy2).max(1e-5);
7033 let a_step: [f32; 3] = [-dy0 * inv_l0, -dy1 * inv_l1, -dy2 * inv_l2];
7034 let b_step: [f32; 3] = [dx0 * inv_l0, dx1 * inv_l1, dx2 * inv_l2];
7035 let base_alpha: f32 = (color.get_a() as f32) * (1.0 / 255.0);
7036 let lin_rgb: [f32; 3] = [
7037 SRGB_TO_LIN_LUT[color.get_r() as usize],
7038 SRGB_TO_LIN_LUT[color.get_g() as usize],
7039 SRGB_TO_LIN_LUT[color.get_b() as usize],
7040 ];
7041 let interior_luts: Option<RgbaLutQuad> =
7042 if color.get_a() < 255 && (area.abs() * 0.5) >= 256.0 {
7043 Some(build_linear_blend_luts(color))
7044 } else {
7045 None
7046 };
7047 let px_base: f32 = (clip_x0 as f32) + 0.5;
7048 let max_s: f32 = (clip_x1 - clip_x0) as f32;
7049 let py_start: f32 = (y0 as f32) + 0.5;
7050 let mut d_row: [f32; 3] = [
7051 (dx0 * (py_start - p0.get_y()) - dy0 * (px_base - p0.get_x())) * inv_l0,
7052 (dx1 * (py_start - p1.get_y()) - dy1 * (px_base - p1.get_x())) * inv_l1,
7053 (dx2 * (py_start - p2.get_y()) - dy2 * (px_base - p2.get_x())) * inv_l2,
7054 ];
7055 let edge_deltas: [(f32, f32); 3] = [(dx0, dy0), (dx1, dy1), (dx2, dy2)];
7056 let verts: (Point, Point, Point) = (p0, p1, p2);
7057 let mut shaded: usize = 0;
7058 for y in y0..y1 {
7059 let py: f32 = (y as f32) + 0.5;
7060 let (out_min, out_max): (f32, f32) =
7061 Self::solve_triangle_scanline_interval(d_row, a_step, -0.86, max_s);
7062 if out_min <= out_max {
7063 let k_out0: u32 = out_min.floor().max(0.0) as u32;
7064 let k_out1: u32 = (out_max.ceil().max(0.0) as u32).saturating_add(1);
7065 let row_x0: u32 = clip_x0.saturating_add(k_out0).clamp(clip_x0, clip_x1);
7066 let row_x1: u32 = clip_x0.saturating_add(k_out1).clamp(row_x0, clip_x1);
7067 if row_x0 < row_x1 {
7068 let (in_min, in_max): (f32, f32) =
7069 Self::solve_triangle_scanline_interval(d_row, a_step, 0.86, max_s);
7070 let (in_x0, in_x1): (u32, u32) = if in_min <= in_max && in_max >= 0.0 {
7071 let k_in0: u32 = in_min.ceil().max(0.0) as u32;
7072 let k_in1: u32 = (in_max.floor().max(0.0) as u32).saturating_add(1);
7073 let ix0: u32 = clip_x0.saturating_add(k_in0).clamp(row_x0, row_x1);
7074 let ix1: u32 = clip_x0.saturating_add(k_in1).clamp(ix0, row_x1);
7075 (ix0, ix1)
7076 } else {
7077 (row_x1, row_x1)
7078 };
7079 if in_x0 < in_x1 {
7080 if let Some(ref luts) = interior_luts {
7081 band.fill_span_linear_luts(in_x0, in_x1, y, luts);
7082 } else {
7083 band.fill_span_linear(in_x0, in_x1, y, color);
7084 }
7085 shaded += (in_x1 - in_x0) as usize;
7086 }
7087 if (row_x0 < in_x0 || in_x1 < row_x1)
7088 && let Some(row) = band.row_slice_mut(y)
7089 {
7090 let mut rim_spans: [(u32, u32); 2] = [(row_x0, in_x0), (in_x1, row_x1)];
7091 if in_x0 >= in_x1 {
7092 rim_spans = [(row_x0, row_x1), (row_x1, row_x1)];
7093 }
7094 for (sx0, sx1) in rim_spans.into_iter() {
7095 if sx0 >= sx1 {
7096 continue;
7097 }
7098 let s0: f32 = (sx0 - clip_x0) as f32;
7099 let mut d0: f32 = d_row[0] + a_step[0] * s0;
7100 let mut d1: f32 = d_row[1] + a_step[1] * s0;
7101 let mut d2: f32 = d_row[2] + a_step[2] * s0;
7102 for x in sx0..sx1 {
7103 if d0 >= -0.85 && d1 >= -0.85 && d2 >= -0.85 {
7104 if d0 > 0.85 && d1 > 0.85 && d2 > 0.85 {
7105 blend_row_pixel_linear_precomputed(row, x, color, lin_rgb);
7106 shaded += 1;
7107 } else {
7108 let px: f32 = (x as f32) + 0.5;
7109 let cov: f32 = triangle_supersampled_coverage_precomputed(
7110 (px, py),
7111 verts,
7112 edge_deltas,
7113 sign,
7114 );
7115 if cov >= 0.999 {
7116 blend_row_pixel_linear_precomputed(
7117 row, x, color, lin_rgb,
7118 );
7119 shaded += 1;
7120 } else if cov > 0.0 {
7121 blend_row_pixel_f32_precomputed(
7122 row,
7123 x,
7124 color,
7125 lin_rgb,
7126 base_alpha * cov,
7127 );
7128 shaded += 1;
7129 }
7130 }
7131 }
7132 d0 += a_step[0];
7133 d1 += a_step[1];
7134 d2 += a_step[2];
7135 }
7136 }
7137 }
7138 }
7139 }
7140 d_row[0] += b_step[0];
7141 d_row[1] += b_step[1];
7142 d_row[2] += b_step[2];
7143 }
7144 shaded
7145 }
7146
7147 #[inline(always)]
7162 fn blit_sprite_span_tinted(
7163 y_params: (usize, usize, u32, u32),
7164 dst_x0: usize,
7165 x_lut: &[(usize, usize, u32)],
7166 src_bytes: &[u8],
7167 dst_row: &mut [u8],
7168 tint: Color,
7169 ) -> usize {
7170 let (row0, row1, wy, iwy): (usize, usize, u32, u32) = y_params;
7171 let span_bytes_start: usize = dst_x0 * 4;
7172 let span_bytes_end: usize = (dst_x0 + x_lut.len()) * 4;
7173 if span_bytes_end > dst_row.len() {
7174 return 0;
7175 }
7176 let dst_chunks: &mut [[u8; 4]] = dst_row[span_bytes_start..span_bytes_end]
7177 .as_chunks_mut::<4>()
7178 .0;
7179 let src_len: usize = src_bytes.len();
7180 let tr: u32 = tint.get_r() as u32;
7181 let tg: u32 = tint.get_g() as u32;
7182 let tb: u32 = tint.get_b() as u32;
7183 let ta: u32 = tint.get_a() as u32;
7184 let mut shaded: usize = 0;
7185 if wy == 0 {
7186 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
7187 let i0: usize = (row0 + sx0) * 4;
7188 let i1: usize = (row0 + sx1) * 4;
7189 if i1 + 4 > src_len {
7190 continue;
7191 }
7192 let iwx: u32 = 256 - wx;
7193 let sa_raw: u32 =
7194 ((src_bytes[i0 + 3] as u32) * iwx + (src_bytes[i1 + 3] as u32) * wx + 128) >> 8;
7195 if sa_raw == 0 {
7196 continue;
7197 }
7198 let sr_raw: u32 =
7199 ((src_bytes[i0] as u32) * iwx + (src_bytes[i1] as u32) * wx + 128) >> 8;
7200 let sg_raw: u32 =
7201 ((src_bytes[i0 + 1] as u32) * iwx + (src_bytes[i1 + 1] as u32) * wx + 128) >> 8;
7202 let sb_raw: u32 =
7203 ((src_bytes[i0 + 2] as u32) * iwx + (src_bytes[i1 + 2] as u32) * wx + 128) >> 8;
7204 let rr: u32 = sr_raw * tr + 128;
7205 let gg: u32 = sg_raw * tg + 128;
7206 let bb: u32 = sb_raw * tb + 128;
7207 let aa_v: u32 = sa_raw * ta + 128;
7208 let r: u32 = (rr + (rr >> 8)) >> 8;
7209 let g: u32 = (gg + (gg >> 8)) >> 8;
7210 let b: u32 = (bb + (bb >> 8)) >> 8;
7211 let a: u32 = (aa_v + (aa_v >> 8)) >> 8;
7212 if a == 255 {
7213 dp[0] = r as u8;
7214 dp[1] = g as u8;
7215 dp[2] = b as u8;
7216 dp[3] = 255;
7217 } else if a > 0 {
7218 let inv_a: u32 = 255 - a;
7219 let vr: u32 = r * a + (dp[0] as u32) * inv_a + 128;
7220 let vg: u32 = g * a + (dp[1] as u32) * inv_a + 128;
7221 let vb: u32 = b * a + (dp[2] as u32) * inv_a + 128;
7222 let va: u32 = (dp[3] as u32) * inv_a + 128;
7223 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
7224 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
7225 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
7226 dp[3] = (a + ((va + (va >> 8)) >> 8)).min(255) as u8;
7227 }
7228 shaded += 1;
7229 }
7230 return shaded;
7231 }
7232 for (dp, &(sx0, sx1, wx)) in dst_chunks.iter_mut().zip(x_lut.iter()) {
7233 let i00: usize = (row0 + sx0) * 4;
7234 let i10: usize = (row0 + sx1) * 4;
7235 let i01: usize = (row1 + sx0) * 4;
7236 let i11: usize = (row1 + sx1) * 4;
7237 if i11 + 4 > src_len {
7238 continue;
7239 }
7240 let iwx: u32 = 256 - wx;
7241 let w00: u32 = iwx * iwy;
7242 let w10: u32 = wx * iwy;
7243 let w01: u32 = iwx * wy;
7244 let w11: u32 = wx * wy;
7245 let sa_raw: u32 = ((src_bytes[i00 + 3] as u32) * w00
7246 + (src_bytes[i10 + 3] as u32) * w10
7247 + (src_bytes[i01 + 3] as u32) * w01
7248 + (src_bytes[i11 + 3] as u32) * w11
7249 + 32768)
7250 >> 16;
7251 if sa_raw == 0 {
7252 continue;
7253 }
7254 let sr_raw: u32 = ((src_bytes[i00] as u32) * w00
7255 + (src_bytes[i10] as u32) * w10
7256 + (src_bytes[i01] as u32) * w01
7257 + (src_bytes[i11] as u32) * w11
7258 + 32768)
7259 >> 16;
7260 let sg_raw: u32 = ((src_bytes[i00 + 1] as u32) * w00
7261 + (src_bytes[i10 + 1] as u32) * w10
7262 + (src_bytes[i01 + 1] as u32) * w01
7263 + (src_bytes[i11 + 1] as u32) * w11
7264 + 32768)
7265 >> 16;
7266 let sb_raw: u32 = ((src_bytes[i00 + 2] as u32) * w00
7267 + (src_bytes[i10 + 2] as u32) * w10
7268 + (src_bytes[i01 + 2] as u32) * w01
7269 + (src_bytes[i11 + 2] as u32) * w11
7270 + 32768)
7271 >> 16;
7272 let rr: u32 = sr_raw * tr + 128;
7273 let gg: u32 = sg_raw * tg + 128;
7274 let bb: u32 = sb_raw * tb + 128;
7275 let aa_v: u32 = sa_raw * ta + 128;
7276 let r: u32 = (rr + (rr >> 8)) >> 8;
7277 let g: u32 = (gg + (gg >> 8)) >> 8;
7278 let b: u32 = (bb + (bb >> 8)) >> 8;
7279 let a: u32 = (aa_v + (aa_v >> 8)) >> 8;
7280 if a == 255 {
7281 dp[0] = r as u8;
7282 dp[1] = g as u8;
7283 dp[2] = b as u8;
7284 dp[3] = 255;
7285 } else if a > 0 {
7286 let inv_a: u32 = 255 - a;
7287 let vr: u32 = r * a + (dp[0] as u32) * inv_a + 128;
7288 let vg: u32 = g * a + (dp[1] as u32) * inv_a + 128;
7289 let vb: u32 = b * a + (dp[2] as u32) * inv_a + 128;
7290 let va: u32 = (dp[3] as u32) * inv_a + 128;
7291 dp[0] = ((vr + (vr >> 8)) >> 8) as u8;
7292 dp[1] = ((vg + (vg >> 8)) >> 8) as u8;
7293 dp[2] = ((vb + (vb >> 8)) >> 8) as u8;
7294 dp[3] = (a + ((va + (va >> 8)) >> 8)).min(255) as u8;
7295 }
7296 shaded += 1;
7297 }
7298 shaded
7299 }
7300
7301 fn raster_sprite_region_with_lut(
7317 band: &mut PixelBand<'_>,
7318 rects: (Rect, Rect),
7319 src_info: (u32, u32, &[u8]),
7320 bounds: (u32, u32, u32, u32),
7321 tint: Color,
7322 use_bilinear: bool,
7323 x_lut: &mut Vec<(usize, usize, u32)>,
7324 ) -> usize {
7325 let (rect, src_rect): (Rect, Rect) = rects;
7326 let (buf_w, buf_h, src_bytes): (u32, u32, &[u8]) = src_info;
7327 let (x0, y0, x1, y1): (u32, u32, u32, u32) = bounds;
7328 let inv_w: f32 = 1.0 / rect.get_width().max(1.0);
7329 let inv_h: f32 = 1.0 / rect.get_height().max(1.0);
7330 let untinted: bool = tint == COLOR_WHITE;
7331 let max_sx: u32 = ((src_rect.right().ceil() as u32).saturating_sub(1)).min(buf_w - 1);
7332 let max_sy: u32 = ((src_rect.bottom().ceil() as u32).saturating_sub(1)).min(buf_h - 1);
7333 let min_sx: u32 = (src_rect.get_x().floor().max(0.0) as u32).min(max_sx);
7334 let min_sy: u32 = (src_rect.get_y().floor().max(0.0) as u32).min(max_sy);
7335 let buf_w_usize: usize = buf_w as usize;
7336 let rect_x: f32 = rect.get_x();
7337 let rect_y: f32 = rect.get_y();
7338 let src_x: f32 = src_rect.get_x();
7339 let src_y: f32 = src_rect.get_y();
7340 let src_w: f32 = src_rect.get_width();
7341 let src_h: f32 = src_rect.get_height();
7342 let min_sx_f: f32 = min_sx as f32;
7343 let max_sx_f: f32 = max_sx as f32;
7344 let min_sy_f: f32 = min_sy as f32;
7345 let max_sy_f: f32 = max_sy as f32;
7346 x_lut.clear();
7347 for x in x0..x1 {
7348 let u: f32 = (((x as f32) + 0.5 - rect_x) * inv_w).clamp(0.0, 1.0);
7349 let fx: f32 = (src_x + u * src_w - 0.5).clamp(min_sx_f, max_sx_f);
7350 let sx0: u32 = (fx.floor() as u32).clamp(min_sx, max_sx);
7351 let sx1: u32 = if use_bilinear {
7352 (sx0 + 1).min(max_sx)
7353 } else {
7354 sx0
7355 };
7356 let wx: u32 = if use_bilinear {
7357 ((fx - (sx0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
7358 } else {
7359 0
7360 };
7361 x_lut.push((sx0 as usize, sx1 as usize, wx));
7362 }
7363 let x_lut_ref: &[(usize, usize, u32)] = x_lut.as_slice();
7364 let x0_u: usize = x0 as usize;
7365 let mut shaded: usize = 0;
7366 for y in y0..y1 {
7367 let Some(dst_row) = band.row_slice_mut(y) else {
7368 continue;
7369 };
7370 let v: f32 = (((y as f32) + 0.5 - rect_y) * inv_h).clamp(0.0, 1.0);
7371 let fy: f32 = (src_y + v * src_h - 0.5).clamp(min_sy_f, max_sy_f);
7372 let sy0: u32 = (fy.floor() as u32).clamp(min_sy, max_sy);
7373 let sy1: u32 = if use_bilinear {
7374 (sy0 + 1).min(max_sy)
7375 } else {
7376 sy0
7377 };
7378 let wy: u32 = if use_bilinear {
7379 ((fy - (sy0 as f32)) * 256.0).round().clamp(0.0, 256.0) as u32
7380 } else {
7381 0
7382 };
7383 let y_params: (usize, usize, u32, u32) = (
7384 (sy0 as usize) * buf_w_usize,
7385 (sy1 as usize) * buf_w_usize,
7386 wy,
7387 256 - wy,
7388 );
7389 if untinted {
7390 shaded += Self::blit_bilinear_span_precomputed(
7391 y_params, x0_u, x_lut_ref, src_bytes, dst_row,
7392 );
7393 } else {
7394 shaded += Self::blit_sprite_span_tinted(
7395 y_params, x0_u, x_lut_ref, src_bytes, dst_row, tint,
7396 );
7397 }
7398 }
7399 shaded
7400 }
7401
7402 fn raster_sprite_region(
7418 band: &mut PixelBand<'_>,
7419 rect: Rect,
7420 buffer: &ImageBuffer,
7421 src_rect: Rect,
7422 tint: Color,
7423 clip: Rect,
7424 aa: AntialiasingMode,
7425 ) -> usize {
7426 if buffer.get_width() == 0
7427 || buffer.get_height() == 0
7428 || tint.get_a() == 0
7429 || src_rect.get_width() <= 0.0
7430 || src_rect.get_height() <= 0.0
7431 {
7432 return 0;
7433 }
7434 let Some(vis) = rect.intersect(clip) else {
7435 return 0;
7436 };
7437 let fb_w: u32 = band.width();
7438 let band_y0: u32 = band.y_offset();
7439 let band_y1: u32 = band.y_end();
7440 let x0: u32 = (vis.get_x().floor().max(0.0) as u32).min(fb_w);
7441 let y0: u32 = (vis.get_y().floor().max(0.0) as u32).clamp(band_y0, band_y1);
7442 let x1: u32 = (vis.right().ceil().max(0.0) as u32).min(fb_w);
7443 let y1: u32 = (vis.bottom().ceil().max(0.0) as u32).clamp(band_y0, band_y1);
7444 if x0 >= x1 || y0 >= y1 {
7445 return 0;
7446 }
7447 let buf_w: u32 = buffer.get_width();
7448 let buf_h: u32 = buffer.get_height();
7449 let src_bytes: &[u8] = buffer.get_pixels().as_slice();
7450 let use_bilinear: bool = aa != AntialiasingMode::None
7451 && ((rect.get_width() - src_rect.get_width()).abs() > 0.5
7452 || (rect.get_height() - src_rect.get_height()).abs() > 0.5);
7453 if !use_bilinear
7454 && tint == COLOR_WHITE
7455 && (rect.get_width() - src_rect.get_width()).abs() <= 0.01
7456 && (rect.get_height() - src_rect.get_height()).abs() <= 0.01
7457 && (rect.get_x() - rect.get_x().round()).abs() <= 0.01
7458 && (rect.get_y() - rect.get_y().round()).abs() <= 0.01
7459 && (src_rect.get_x() - src_rect.get_x().round()).abs() <= 0.01
7460 && (src_rect.get_y() - src_rect.get_y().round()).abs() <= 0.01
7461 {
7462 let rx0_i: i32 = rect.get_x().round() as i32;
7463 let ry0_i: i32 = rect.get_y().round() as i32;
7464 let sx0_i: i32 = src_rect.get_x().round() as i32;
7465 let sy0_i: i32 = src_rect.get_y().round() as i32;
7466 let span_w: usize = (x1 - x0) as usize;
7467 let src_x0_i: i32 = sx0_i + ((x0 as i32) - rx0_i);
7468 let src_y0_i: i32 = sy0_i + ((y0 as i32) - ry0_i);
7469 let src_y1_i: i32 = sy0_i + ((y1 as i32) - ry0_i);
7470 if src_x0_i >= 0
7471 && src_x0_i + (span_w as i32) <= (buf_w as i32)
7472 && src_y0_i >= 0
7473 && src_y1_i <= (buf_h as i32)
7474 {
7475 let buf_w_u: usize = buf_w as usize;
7476 let dst_b0: usize = (x0 as usize) * 4;
7477 let dst_b1: usize = (x1 as usize) * 4;
7478 let src_x0_u: usize = src_x0_i as usize;
7479 for y in y0..y1 {
7480 let Some(dst_row) = band.row_slice_mut(y) else {
7481 continue;
7482 };
7483 let sy: usize = (sy0_i + ((y as i32) - ry0_i)) as usize;
7484 let src_b0: usize = (sy * buf_w_u + src_x0_u) * 4;
7485 let src_b1: usize = src_b0 + span_w * 4;
7486 if src_b1 <= src_bytes.len() && dst_b1 <= dst_row.len() {
7487 blit_1to1_rgba_span(
7488 &src_bytes[src_b0..src_b1],
7489 &mut dst_row[dst_b0..dst_b1],
7490 );
7491 }
7492 }
7493 return span_w * ((y1 - y0) as usize);
7494 }
7495 }
7496 let mut shaded: usize = 0;
7497 let ran_tls: bool = BAND_IMAGE_X_LUT
7498 .try_with(|cell: &RefCell<Vec<(usize, usize, u32)>>| {
7499 if let Ok(mut guard) = cell.try_borrow_mut() {
7500 shaded = Self::raster_sprite_region_with_lut(
7501 band,
7502 (rect, src_rect),
7503 (buf_w, buf_h, src_bytes),
7504 (x0, y0, x1, y1),
7505 tint,
7506 use_bilinear,
7507 &mut guard,
7508 );
7509 }
7510 })
7511 .is_ok();
7512 if !ran_tls {
7513 let mut fallback_lut: Vec<(usize, usize, u32)> = Vec::with_capacity((x1 - x0) as usize);
7514 shaded = Self::raster_sprite_region_with_lut(
7515 band,
7516 (rect, src_rect),
7517 (buf_w, buf_h, src_bytes),
7518 (x0, y0, x1, y1),
7519 tint,
7520 use_bilinear,
7521 &mut fallback_lut,
7522 );
7523 }
7524 shaded
7525 }
7526}