Skip to main content

euv_core/render/buffer/
impl.rs

1use super::*;
2
3/// Pixel access, blitting, BGRA conversion, and deterministic hashing for `Framebuffer`.
4impl Framebuffer {
5    /// Allocates a new zero-initialized RGBA8 framebuffer of `(width, height)`.
6    ///
7    /// # Arguments
8    ///
9    /// - `u32` - Physical width in pixels.
10    /// - `u32` - Physical height in pixels.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Allocated framebuffer.
15    #[must_use]
16    pub fn allocate(width: u32, height: u32) -> Self {
17        let w: u32 = width.max(1);
18        let h: u32 = height.max(1);
19        let byte_len: usize = (w as usize).saturating_mul(h as usize).saturating_mul(4);
20        Self {
21            width: w,
22            height: h,
23            pixels: vec![0; byte_len],
24        }
25    }
26
27    /// Returns the number of allocated RGBA8 pixel bytes currently resident in this framebuffer.
28    ///
29    /// # Arguments
30    ///
31    /// - `&Self` - Framebuffer reference.
32    ///
33    /// # Returns
34    ///
35    /// - `usize` - Resident RGBA8 pixel byte count (`0` when unallocated).
36    #[must_use]
37    pub fn allocated_bytes(&self) -> usize {
38        self.get_pixels().len()
39    }
40
41    /// Resizes the framebuffer only when dimensions changed, avoiding per-frame reallocation.
42    ///
43    /// # Arguments
44    ///
45    /// - `&Self` - Mutable framebuffer.
46    /// - `u32` - Target width.
47    /// - `u32` - Target height.
48    ///
49    /// # Returns
50    ///
51    /// - `bool` - True if dimensions changed and buffer was resized.
52    pub fn resize(&mut self, width: u32, height: u32) -> bool {
53        let w: u32 = width.max(1);
54        let h: u32 = height.max(1);
55        if self.get_width() == w && self.get_height() == h {
56            return false;
57        }
58        self.set_width(w);
59        self.set_height(h);
60        let byte_len: usize = (w as usize).saturating_mul(h as usize).saturating_mul(4);
61        self.get_mut_pixels().resize(byte_len, 0);
62        true
63    }
64
65    /// Fills the entire framebuffer with solid `color` using 32-byte wide auto-vectorized stores.
66    ///
67    /// # Arguments
68    ///
69    /// - `&Self` - Mutable framebuffer.
70    /// - `Color` - Clear color.
71    pub fn clear(&mut self, color: Color) {
72        fill_rgba_span_32(self.get_mut_pixels().as_mut_slice(), color.to_rgba_bytes());
73    }
74
75    /// Fills or composites a contiguous horizontal pixel span `[x0, x1)` on row `y`.
76    ///
77    /// # Arguments
78    ///
79    /// - `&Self` - Mutable framebuffer.
80    /// - `u32` - Inclusive start X pixel coordinate.
81    /// - `u32` - Exclusive end X pixel coordinate.
82    /// - `u32` - Row Y pixel coordinate.
83    /// - `Color` - Foreground color to write or alpha-blend.
84    pub fn fill_span(&mut self, x0: u32, x1: u32, y: u32, color: Color) {
85        let sa: u8 = color.get_a();
86        let width: u32 = self.get_width();
87        let height: u32 = self.get_height();
88        if sa == 0 || y >= height || x0 >= x1 || x0 >= width {
89            return;
90        }
91        let end_x: u32 = x1.min(width);
92        let row_base: usize = (y as usize) * (width as usize);
93        let start_byte: usize = (row_base + (x0 as usize)) * 4;
94        let end_byte: usize = (row_base + (end_x as usize)) * 4;
95        let Some(span) = self.get_mut_pixels().get_mut(start_byte..end_byte) else {
96            return;
97        };
98        if sa == 255 {
99            fill_rgba_span_32(span, [color.get_r(), color.get_g(), color.get_b(), 255]);
100            return;
101        }
102        let sr: u32 = color.get_r() as u32;
103        let sg: u32 = color.get_g() as u32;
104        let sb: u32 = color.get_b() as u32;
105        let sa_u32: u32 = sa as u32;
106        let inv_a: u32 = 255 - sa_u32;
107        for px in span.as_chunks_mut::<4>().0.iter_mut() {
108            let dr: u32 = px[0] as u32;
109            let dg: u32 = px[1] as u32;
110            let db: u32 = px[2] as u32;
111            let da: u32 = px[3] as u32;
112            let vr: u32 = sr * sa_u32 + dr * inv_a + 128;
113            let vg: u32 = sg * sa_u32 + dg * inv_a + 128;
114            let vb: u32 = sb * sa_u32 + db * inv_a + 128;
115            let va: u32 = da * inv_a + 128;
116            px[0] = ((vr + (vr >> 8)) >> 8) as u8;
117            px[1] = ((vg + (vg >> 8)) >> 8) as u8;
118            px[2] = ((vb + (vb >> 8)) >> 8) as u8;
119            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
120        }
121    }
122
123    /// Fills or composites a contiguous horizontal pixel span `[x0, x1)` on row `y` using gamma-correct linear-light blending.
124    ///
125    /// # Arguments
126    ///
127    /// - `&Self` - Mutable framebuffer.
128    /// - `u32` - Inclusive start X pixel coordinate.
129    /// - `u32` - Exclusive end X pixel coordinate.
130    /// - `u32` - Row Y pixel coordinate.
131    /// - `Color` - Foreground color to write or linear-light blend.
132    pub fn fill_span_linear(&mut self, x0: u32, x1: u32, y: u32, color: Color) {
133        let sa: u8 = color.get_a();
134        let width: u32 = self.get_width();
135        let height: u32 = self.get_height();
136        if sa == 0 || y >= height || x0 >= x1 || x0 >= width {
137            return;
138        }
139        if sa == 255 {
140            self.fill_span(x0, x1, y, color);
141            return;
142        }
143        let end_x: u32 = x1.min(width);
144        let row_base: usize = (y as usize) * (width as usize);
145        let start_byte: usize = (row_base + (x0 as usize)) * 4;
146        let end_byte: usize = (row_base + (end_x as usize)) * 4;
147        let Some(span) = self.get_mut_pixels().get_mut(start_byte..end_byte) else {
148            return;
149        };
150        let a: f32 = (sa as f32) * (1.0 / 255.0);
151        let inv_a: f32 = 1.0 - a;
152        let sr_a: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize] * a;
153        let sg_a: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize] * a;
154        let sb_a: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize] * a;
155        let sa_u32: u32 = sa as u32;
156        let inv_a_u32: u32 = 255 - sa_u32;
157        for px in span.as_chunks_mut::<4>().0.iter_mut() {
158            let dr: f32 = SRGB_TO_LIN_LUT[px[0] as usize];
159            let dg: f32 = SRGB_TO_LIN_LUT[px[1] as usize];
160            let db: f32 = SRGB_TO_LIN_LUT[px[2] as usize];
161            let ir: usize = ((sr_a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
162            let ig: usize = ((sg_a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
163            let ib: usize = ((sb_a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
164            let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
165            px[0] = ((LIN_TO_SRGB_Q4_LUT[ir] + 8) >> 4).min(255) as u8;
166            px[1] = ((LIN_TO_SRGB_Q4_LUT[ig] + 8) >> 4).min(255) as u8;
167            px[2] = ((LIN_TO_SRGB_Q4_LUT[ib] + 8) >> 4).min(255) as u8;
168            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
169        }
170    }
171
172    /// Blends a contiguous glyph alpha coverage row directly onto framebuffer row `dy` starting at `dx`.
173    ///
174    /// # Arguments
175    ///
176    /// - `&Self` - Mutable framebuffer.
177    /// - `u32` - Destination starting X pixel coordinate.
178    /// - `u32` - Destination Y pixel coordinate.
179    /// - `&[u8]` - Glyph coverage alpha bytes for the clipped horizontal slice.
180    /// - `Color` - Foreground text color.
181    ///
182    /// # Returns
183    ///
184    /// - `usize` - Number of non-zero coverage pixels shaded.
185    pub fn blend_glyph_row(&mut self, dx: u32, dy: u32, coverage: &[u8], color: Color) -> usize {
186        let width: u32 = self.get_width();
187        let height: u32 = self.get_height();
188        if color.get_a() == 0 || dy >= height || dx >= width || coverage.is_empty() {
189            return 0;
190        }
191        let max_len: usize = ((width - dx) as usize).min(coverage.len());
192        let start_byte: usize = ((dy as usize) * (width as usize) + (dx as usize)) * 4;
193        let end_byte: usize = start_byte + max_len * 4;
194        let Some(dst_span) = self.get_mut_pixels().get_mut(start_byte..end_byte) else {
195            return 0;
196        };
197        blend_glyph_row_span(dst_span, &coverage[..max_len], color)
198    }
199
200    /// Reads the RGBA `Color` at pixel coordinates `(x, y)`.
201    ///
202    /// # Arguments
203    ///
204    /// - `&Self` - Framebuffer reference.
205    /// - `u32` - X pixel coordinate.
206    /// - `u32` - Y pixel coordinate.
207    ///
208    /// # Returns
209    ///
210    /// - `Option<Color>` - Pixel color if within bounds.
211    #[must_use]
212    pub fn get_pixel(&self, x: u32, y: u32) -> Option<Color> {
213        if x >= self.get_width() || y >= self.get_height() {
214            return None;
215        }
216        let offset: usize = ((y as usize) * (self.get_width() as usize) + (x as usize)) * 4;
217        let slice: &[u8] = self.get_pixels().get(offset..offset + 4)?;
218        Some(Color::new(slice[0], slice[1], slice[2], slice[3]))
219    }
220
221    /// Blends `color` over the pixel at `(x, y)` using gamma-correct linear-light compositing with optional sub-LSB dithering.
222    ///
223    /// # Arguments
224    ///
225    /// - `&Self` - Mutable framebuffer.
226    /// - `u32` - X pixel coordinate.
227    /// - `u32` - Y pixel coordinate.
228    /// - `Color` - Foreground color to composite.
229    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]` to eliminate 8-bit banding.
230    pub fn blend_pixel_linear_dithered(&mut self, x: u32, y: u32, color: Color, dither: f32) {
231        let sa: u8 = color.get_a();
232        if sa == 0 || x >= self.get_width() || y >= self.get_height() {
233            return;
234        }
235        let offset: usize = ((y as usize) * (self.get_width() as usize) + (x as usize)) * 4;
236        let pixels: &mut [u8] = self.get_mut_pixels().as_mut_slice();
237        if offset + 4 > pixels.len() {
238            return;
239        }
240        if sa == 255 {
241            pixels[offset] = color.get_r();
242            pixels[offset + 1] = color.get_g();
243            pixels[offset + 2] = color.get_b();
244            pixels[offset + 3] = 255;
245            return;
246        }
247        let a: f32 = (sa as f32) * (1.0 / 255.0);
248        let inv_a: f32 = 1.0 - a;
249        let sr: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize];
250        let sg: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize];
251        let sb: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize];
252        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
253        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
254        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
255        let ir: usize = ((sr * a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
256        let ig: usize = ((sg * a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
257        let ib: usize = ((sb * a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
258        let dq: i32 = (dither * 16.0) as i32 + 8;
259        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
260        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
261        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
262        let sa_u32: u32 = sa as u32;
263        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
264        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
265    }
266
267    /// Blends a foreground RGBA color with continuous floating-point alpha `alpha_f` in `[0.0, 1.0]` using linear-light compositing and IGN dithering.
268    ///
269    /// # Arguments
270    ///
271    /// - `&Self` - Mutable framebuffer.
272    /// - `u32` - X pixel coordinate.
273    /// - `u32` - Y pixel coordinate.
274    /// - `Color` - Foreground RGB tint (its own alpha is already folded into `alpha_f`).
275    /// - `f32` - Continuous opacity in `[0.0, 1.0]`.
276    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]`.
277    pub fn blend_pixel_f32_dithered(
278        &mut self,
279        x: u32,
280        y: u32,
281        color: Color,
282        alpha_f: f32,
283        dither: f32,
284    ) {
285        if alpha_f <= 0.0002 || x >= self.get_width() || y >= self.get_height() {
286            return;
287        }
288        let offset: usize = ((y as usize) * (self.get_width() as usize) + (x as usize)) * 4;
289        let pixels: &mut [u8] = self.get_mut_pixels().as_mut_slice();
290        if offset + 4 > pixels.len() {
291            return;
292        }
293        let a: f32 = alpha_f.clamp(0.0, 1.0);
294        if a >= 0.9995 {
295            pixels[offset] = color.get_r();
296            pixels[offset + 1] = color.get_g();
297            pixels[offset + 2] = color.get_b();
298            pixels[offset + 3] = 255;
299            return;
300        }
301        let inv_a: f32 = 1.0 - a;
302        let sr: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize];
303        let sg: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize];
304        let sb: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize];
305        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
306        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
307        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
308        let ir: usize = ((sr * a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
309        let ig: usize = ((sg * a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
310        let ib: usize = ((sb * a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
311        let dq: i32 = (dither * 16.0) as i32 + 8;
312        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
313        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
314        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
315        let sa_u32: u32 = (a * 255.0) as u32;
316        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
317        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
318    }
319
320    /// Blends `color` over the pixel at `(x, y)` using fast integer Porter-Duff source-over.
321    ///
322    /// # Arguments
323    ///
324    /// - `&Self` - Mutable framebuffer.
325    /// - `u32` - X pixel coordinate.
326    /// - `u32` - Y pixel coordinate.
327    /// - `Color` - Foreground color to composite.
328    pub fn blend_pixel(&mut self, x: u32, y: u32, color: Color) {
329        let sa: u8 = color.get_a();
330        if sa == 0 || x >= self.get_width() || y >= self.get_height() {
331            return;
332        }
333        let offset: usize = ((y as usize) * (self.get_width() as usize) + (x as usize)) * 4;
334        let pixels: &mut [u8] = self.get_mut_pixels().as_mut_slice();
335        if offset + 4 > pixels.len() {
336            return;
337        }
338        if sa == 255 {
339            pixels[offset] = color.get_r();
340            pixels[offset + 1] = color.get_g();
341            pixels[offset + 2] = color.get_b();
342            pixels[offset + 3] = 255;
343            return;
344        }
345        let dst: Color = Color::new(
346            pixels[offset],
347            pixels[offset + 1],
348            pixels[offset + 2],
349            pixels[offset + 3],
350        );
351        let blended: Color = color.blend_over(dst);
352        pixels[offset] = blended.get_r();
353        pixels[offset + 1] = blended.get_g();
354        pixels[offset + 2] = blended.get_b();
355        pixels[offset + 3] = blended.get_a();
356    }
357
358    /// Converts RGBA8 pixels into BGRA8 byte order required by Win32 GDI, X11, and Cocoa/Metal.
359    ///
360    /// # Arguments
361    ///
362    /// - `&Self` - Source RGBA8 framebuffer.
363    ///
364    /// # Returns
365    ///
366    /// - `Vec<u8>` - Packed BGRA8 pixel buffer.
367    #[must_use]
368    pub fn to_bgra_bytes(&self) -> Vec<u8> {
369        let src: &[u8] = self.get_pixels().as_slice();
370        let len: usize = src.len() & !3usize;
371        let mut out: Vec<u8> = vec![0u8; len];
372        let (src_wide, src_tail): (&[[u8; 16]], &[u8]) = src[..len].as_chunks::<16>();
373        let (dst_wide, dst_tail): (&mut [[u8; 16]], &mut [u8]) = out.as_chunks_mut::<16>();
374        for (s, d) in src_wide.iter().zip(dst_wide.iter_mut()) {
375            *d = [
376                s[2], s[1], s[0], s[3], s[6], s[5], s[4], s[7], s[10], s[9], s[8], s[11], s[14],
377                s[13], s[12], s[15],
378            ];
379        }
380        for (s, d) in src_tail
381            .as_chunks::<4>()
382            .0
383            .iter()
384            .zip(dst_tail.as_chunks_mut::<4>().0.iter_mut())
385        {
386            *d = [s[2], s[1], s[0], s[3]];
387        }
388        out
389    }
390
391    /// Computes a deterministic 64-bit 4-lane word-folded FNV-1a hash of one `128x16` pixel tile `(tx, ty)`.
392    ///
393    /// # Arguments
394    ///
395    /// - `&Self` - Framebuffer reference.
396    /// - `u32` - Tile column index (`0..width.div_ceil(128)`).
397    /// - `u32` - Tile row index (`0..height.div_ceil(16)`).
398    ///
399    /// # Returns
400    ///
401    /// - `u64` - Deterministic endian-independent hash for tile `(tx, ty)`.
402    #[must_use]
403    pub(crate) fn hash_tile_fnv1a(&self, tx: u32, ty: u32) -> u64 {
404        let w: u32 = self.get_width();
405        let h: u32 = self.get_height();
406        let x0: usize = (tx.saturating_mul(FB_HASH_TILE_W) as usize).min(w as usize);
407        let x1: usize = (x0.saturating_add(FB_HASH_TILE_W as usize)).min(w as usize);
408        let y0: usize = (ty.saturating_mul(FB_HASH_TILE_H) as usize).min(h as usize);
409        let y1: usize = (y0.saturating_add(FB_HASH_TILE_H as usize)).min(h as usize);
410        let bytes: &[u8] = self.get_pixels().as_slice();
411        let row_stride: usize = (w as usize).saturating_mul(4);
412        let mut lanes: [u64; 8] = [
413            FNV1A_OFFSET_BASIS,
414            FNV1A_OFFSET_BASIS ^ 0x9E37_79B9_7F4A_7C15,
415            FNV1A_OFFSET_BASIS ^ 0xBF58_476D_1CE4_E5B9,
416            FNV1A_OFFSET_BASIS ^ 0x94D0_49BB_1331_11EB,
417            FNV1A_OFFSET_BASIS ^ 0xD6E8_FEB8_6659_FD93,
418            FNV1A_OFFSET_BASIS ^ 0xA076_1D64_78BD_642F,
419            FNV1A_OFFSET_BASIS ^ 0xE703_7ED1_A0B4_28DB,
420            FNV1A_OFFSET_BASIS ^ 0x8EBC_6AF0_9C88_C6E3,
421        ];
422        let mut tail_hash: u64 = FNV1A_OFFSET_BASIS;
423        let x0_b: usize = x0.saturating_mul(4);
424        let x1_b: usize = x1.saturating_mul(4);
425        for y in y0..y1 {
426            let base: usize = y.saturating_mul(row_stride);
427            let start: usize = base.saturating_add(x0_b);
428            let end: usize = base.saturating_add(x1_b);
429            if end > bytes.len() {
430                break;
431            }
432            let row_slice: &[u8] = &bytes[start..end];
433            let (blocks64, rem): (&[[u8; 64]], &[u8]) = row_slice.as_chunks::<64>();
434            for blk in blocks64.iter() {
435                fold_fnv1a_64(&mut lanes, blk);
436            }
437            if !rem.is_empty() {
438                let (words8, tail): (&[[u8; 8]], &[u8]) = rem.as_chunks::<8>();
439                for word in words8.iter() {
440                    tail_hash = (tail_hash ^ u64::from_le_bytes(*word)).wrapping_mul(FNV1A_PRIME);
441                }
442                for byte in tail.iter().copied() {
443                    tail_hash = (tail_hash ^ (byte as u64)).wrapping_mul(FNV1A_PRIME);
444                }
445            }
446        }
447        let lo: u64 = lanes[0]
448            ^ lanes[1].rotate_left(13)
449            ^ lanes[2].rotate_left(29)
450            ^ lanes[3].rotate_left(47);
451        let hi: u64 = lanes[4]
452            ^ lanes[5].rotate_left(17)
453            ^ lanes[6].rotate_left(31)
454            ^ lanes[7].rotate_left(53);
455        let mut hash: u64 = lo ^ hi.rotate_left(7) ^ tail_hash.rotate_left(11);
456        hash = hash.wrapping_mul(FNV1A_PRIME);
457        hash
458    }
459
460    /// Combines per-tile hashes in canonical row-major order into the exact framebuffer digest.
461    ///
462    /// # Arguments
463    ///
464    /// - `u32` - Framebuffer width in pixels.
465    /// - `u32` - Framebuffer height in pixels.
466    /// - `&[u64]` - Row-major slice of `128x16` tile hashes.
467    ///
468    /// # Returns
469    ///
470    /// - `u64` - Deterministic framebuffer hash identical to `Framebuffer::fnv1a_hash`.
471    #[inline]
472    #[must_use]
473    pub(crate) fn fold_tile_hashes(width: u32, height: u32, tile_hashes: &[u64]) -> u64 {
474        let mut acc: u64 = FNV1A_OFFSET_BASIS;
475        acc = (acc ^ (width as u64)).wrapping_mul(FNV1A_PRIME);
476        acc = (acc ^ (height as u64)).wrapping_mul(FNV1A_PRIME);
477        for &tile_h in tile_hashes.iter() {
478            acc = (acc ^ tile_h).wrapping_mul(FNV1A_PRIME);
479        }
480        acc
481    }
482
483    /// Computes a deterministic 64-bit tile-folded FNV-1a hash of the framebuffer pixels.
484    ///
485    /// # Arguments
486    ///
487    /// - `&Self` - Framebuffer to hash.
488    ///
489    /// # Returns
490    ///
491    /// - `u64` - Deterministic endian-independent pixel hash.
492    #[must_use]
493    pub fn fnv1a_hash(&self) -> u64 {
494        let w: u32 = self.get_width();
495        let h: u32 = self.get_height();
496        let mut acc: u64 = FNV1A_OFFSET_BASIS;
497        acc = (acc ^ (w as u64)).wrapping_mul(FNV1A_PRIME);
498        acc = (acc ^ (h as u64)).wrapping_mul(FNV1A_PRIME);
499        if w == 0 || h == 0 || self.get_pixels().is_empty() {
500            return acc;
501        }
502        let tiles_x: u32 = w.div_ceil(FB_HASH_TILE_W);
503        let tiles_y: u32 = h.div_ceil(FB_HASH_TILE_H);
504        for ty in 0..tiles_y {
505            for tx in 0..tiles_x {
506                let tile_h: u64 = self.hash_tile_fnv1a(tx, ty);
507                acc = (acc ^ tile_h).wrapping_mul(FNV1A_PRIME);
508            }
509        }
510        acc
511    }
512
513    /// Borrows the entire framebuffer as a single zero-copy mutable `PixelBand`.
514    ///
515    /// # Arguments
516    ///
517    /// - `&Self` - Mutable framebuffer.
518    ///
519    /// # Returns
520    ///
521    /// - `PixelBand<'_>` - Full-surface mutable pixel band.
522    pub fn as_band_mut(&mut self) -> PixelBand<'_> {
523        let Self {
524            width,
525            height,
526            pixels,
527        } = self;
528        PixelBand {
529            width: *width,
530            y_offset: 0,
531            height: *height,
532            pixels: pixels.as_mut_slice(),
533        }
534    }
535
536    /// Splits rows `[y0, y1)` of this framebuffer into `band_count` disjoint mutable `PixelBand` slices for safe parallel rasterization.
537    ///
538    /// # Arguments
539    ///
540    /// - `&Self` - Mutable framebuffer.
541    /// - `u32` - Inclusive starting physical Y row.
542    /// - `u32` - Exclusive ending physical Y row.
543    /// - `usize` - Requested number of parallel bands.
544    ///
545    /// # Returns
546    ///
547    /// - `Vec<PixelBand<'_>>` - Non-overlapping mutable horizontal bands covering `[y0, y1)`.
548    pub fn split_bands_mut(&mut self, y0: u32, y1: u32, band_count: usize) -> Vec<PixelBand<'_>> {
549        let Self {
550            width,
551            height,
552            pixels,
553        } = self;
554        let fb_w: u32 = *width;
555        let fb_h: u32 = *height;
556        let start_y: u32 = y0.min(fb_h);
557        let end_y: u32 = y1.clamp(start_y, fb_h);
558        let total_rows: u32 = end_y - start_y;
559        if total_rows == 0 || fb_w == 0 {
560            return Vec::new();
561        }
562        let count: usize = band_count.max(1).min(total_rows as usize);
563        let rows_per: usize = (total_rows as usize).div_ceil(count);
564        let row_stride: usize = (fb_w as usize) * 4;
565        let start_byte: usize = (start_y as usize) * row_stride;
566        let end_byte: usize = (end_y as usize) * row_stride;
567        let Some(slice) = pixels.get_mut(start_byte..end_byte) else {
568            return Vec::new();
569        };
570        let mut bands: Vec<PixelBand<'_>> = Vec::with_capacity(count);
571        let mut cur_y: u32 = start_y;
572        for chunk in slice.chunks_mut(rows_per * row_stride) {
573            let chunk_rows: u32 = (chunk.len() / row_stride) as u32;
574            bands.push(PixelBand {
575                width: fb_w,
576                y_offset: cur_y,
577                height: chunk_rows,
578                pixels: chunk,
579            });
580            cur_y += chunk_rows;
581        }
582        bands
583    }
584}
585
586/// Zero-copy band rasterization primitives for `PixelBand`.
587impl<'a> PixelBand<'a> {
588    /// Returns the full framebuffer width in physical pixels.
589    ///
590    /// # Arguments
591    ///
592    /// - `&Self` - Pixel band reference.
593    ///
594    /// # Returns
595    ///
596    /// - `u32` - Width in physical pixels.
597    #[must_use]
598    pub fn width(&self) -> u32 {
599        let Self { width, .. } = self;
600        *width
601    }
602
603    /// Returns the inclusive top physical Y row owned by this band.
604    ///
605    /// # Arguments
606    ///
607    /// - `&Self` - Pixel band reference.
608    ///
609    /// # Returns
610    ///
611    /// - `u32` - Starting physical Y row.
612    #[must_use]
613    pub fn y_offset(&self) -> u32 {
614        let Self { y_offset, .. } = self;
615        *y_offset
616    }
617
618    /// Returns the exclusive bottom physical Y row owned by this band.
619    ///
620    /// # Arguments
621    ///
622    /// - `&Self` - Pixel band reference.
623    ///
624    /// # Returns
625    ///
626    /// - `u32` - Ending physical Y row.
627    #[must_use]
628    pub fn y_end(&self) -> u32 {
629        let Self {
630            y_offset, height, ..
631        } = self;
632        *y_offset + *height
633    }
634
635    /// Returns the mutable byte slice for global physical row `y` if owned by this band.
636    ///
637    /// # Arguments
638    ///
639    /// - `&Self` - Mutable pixel band.
640    /// - `u32` - Global physical Y row coordinate.
641    ///
642    /// # Returns
643    ///
644    /// - `Option<&mut [u8]>` - Mutable row byte slice (`width * 4` bytes).
645    pub fn row_slice_mut(&mut self, y: u32) -> Option<&mut [u8]> {
646        let Self {
647            width,
648            y_offset,
649            height,
650            pixels,
651        } = self;
652        if y < *y_offset || y >= *y_offset + *height {
653            return None;
654        }
655        let local_y: usize = (y - *y_offset) as usize;
656        let stride: usize = (*width as usize) * 4;
657        let start: usize = local_y * stride;
658        pixels.get_mut(start..start + stride)
659    }
660
661    /// Returns two disjoint mutable row slices for global physical rows `y_a < y_b` owned by this band.
662    ///
663    /// # Arguments
664    ///
665    /// - `&Self` - Mutable pixel band.
666    /// - `u32` - Upper global physical Y row coordinate (`y_a < y_b`).
667    /// - `u32` - Lower global physical Y row coordinate (`y_b > y_a`).
668    ///
669    /// # Returns
670    ///
671    /// - `Option<(&mut [u8], &mut [u8])>` - Pair of disjoint mutable row slices `(row_a, row_b)`.
672    pub fn two_row_slices_mut(&mut self, y_a: u32, y_b: u32) -> Option<(&mut [u8], &mut [u8])> {
673        let Self {
674            width,
675            y_offset,
676            height,
677            pixels,
678        } = self;
679        let y_end: u32 = *y_offset + *height;
680        if y_a >= y_b || y_a < *y_offset || y_b >= y_end {
681            return None;
682        }
683        let stride: usize = (*width as usize) * 4;
684        let start_a: usize = ((y_a - *y_offset) as usize) * stride;
685        let start_b: usize = ((y_b - *y_offset) as usize) * stride;
686        if start_b + stride > pixels.len() {
687            return None;
688        }
689        let (head, tail): (&mut [u8], &mut [u8]) = pixels.split_at_mut(start_b);
690        Some((&mut head[start_a..start_a + stride], &mut tail[..stride]))
691    }
692
693    /// Returns a contiguous mutable byte slice for global physical rows `[y0, y1)` along with the row byte stride.
694    ///
695    /// # Arguments
696    ///
697    /// - `&Self` - Mutable pixel band.
698    /// - `u32` - Inclusive starting global physical Y row.
699    /// - `u32` - Exclusive ending global physical Y row.
700    ///
701    /// # Returns
702    ///
703    /// - `Option<(&mut [u8], usize)>` - Contiguous byte slice covering rows `[y0, y1)` and byte stride `width * 4`.
704    #[inline(always)]
705    pub(crate) fn rows_slice_mut(&mut self, y0: u32, y1: u32) -> Option<(&mut [u8], usize)> {
706        let Self {
707            width,
708            y_offset,
709            height,
710            pixels,
711        } = self;
712        let y_end: u32 = *y_offset + *height;
713        if y0 >= y1 || y0 < *y_offset || y1 > y_end {
714            return None;
715        }
716        let stride: usize = (*width as usize) * 4;
717        let start: usize = ((y0 - *y_offset) as usize) * stride;
718        let end: usize = ((y1 - *y_offset) as usize) * stride;
719        pixels.get_mut(start..end).map(|s: &mut [u8]| (s, stride))
720    }
721
722    /// Fills a pre-clipped opaque rectangle `[x0, x1) x [y0, y1)` using 32-byte wide stores with zero per-row bounds checks.
723    ///
724    /// # Arguments
725    ///
726    /// - `&Self` - Mutable pixel band.
727    /// - `u32` - Pre-clipped inclusive start X coordinate.
728    /// - `u32` - Pre-clipped exclusive end X coordinate.
729    /// - `u32` - Pre-clipped inclusive start global Y coordinate.
730    /// - `u32` - Pre-clipped exclusive end global Y coordinate.
731    /// - `[u8; 4]` - Solid opaque RGBA8 pixel bytes.
732    #[inline(always)]
733    pub(crate) fn fill_rect_opaque_preclipped(
734        &mut self,
735        x0: u32,
736        x1: u32,
737        y0: u32,
738        y1: u32,
739        rgba: [u8; 4],
740    ) {
741        let Self {
742            width,
743            y_offset,
744            height,
745            pixels,
746        } = self;
747        let fb_w: u32 = *width;
748        let y_end: u32 = *y_offset + *height;
749        let valid_x: bool = x0 < x1 && x1 <= fb_w;
750        let valid_y: bool = y0 < y1 && y0 >= *y_offset && y1 <= y_end;
751        if !valid_x || !valid_y {
752            return;
753        }
754        let stride: usize = (fb_w as usize) * 4;
755        let start: usize = ((y0 - *y_offset) as usize) * stride;
756        let end: usize = ((y1 - *y_offset) as usize) * stride;
757        let Some(rows_buf) = pixels.get_mut(start..end) else {
758            return;
759        };
760        if x0 == 0 && x1 == fb_w {
761            fill_rgba_span_32(rows_buf, rgba);
762            return;
763        }
764        let bx0: usize = (x0 as usize) * 4;
765        let bx1: usize = (x1 as usize) * 4;
766        for row in rows_buf.chunks_exact_mut(stride) {
767            fill_rgba_span_32(&mut row[bx0..bx1], rgba);
768        }
769    }
770
771    /// Fills the entire band with solid `color` using 32-byte wide auto-vectorized stores.
772    ///
773    /// # Arguments
774    ///
775    /// - `&Self` - Mutable pixel band.
776    /// - `Color` - Clear color.
777    pub fn clear(&mut self, color: Color) {
778        let Self { pixels, .. } = self;
779        fill_rgba_span_32(pixels, color.to_rgba_bytes());
780    }
781
782    /// Fills or Porter-Duff blends horizontal span `[x0, x1)` on global row `y`.
783    ///
784    /// # Arguments
785    ///
786    /// - `&Self` - Mutable pixel band.
787    /// - `u32` - Inclusive start X coordinate.
788    /// - `u32` - Exclusive end X coordinate.
789    /// - `u32` - Global physical Y coordinate.
790    /// - `Color` - Foreground RGBA color.
791    pub fn fill_span(&mut self, x0: u32, x1: u32, y: u32, color: Color) {
792        let sa: u8 = color.get_a();
793        let Self {
794            width,
795            y_offset,
796            height,
797            pixels,
798        } = self;
799        if sa == 0 || y < *y_offset || y >= *y_offset + *height || x0 >= x1 || x0 >= *width {
800            return;
801        }
802        let end_x: u32 = x1.min(*width);
803        let row_base: usize = ((y - *y_offset) as usize) * (*width as usize);
804        let start_byte: usize = (row_base + (x0 as usize)) * 4;
805        let end_byte: usize = (row_base + (end_x as usize)) * 4;
806        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
807            return;
808        };
809        if sa == 255 {
810            fill_rgba_span_32(span, [color.get_r(), color.get_g(), color.get_b(), 255]);
811            return;
812        }
813        let sr: u32 = color.get_r() as u32;
814        let sg: u32 = color.get_g() as u32;
815        let sb: u32 = color.get_b() as u32;
816        let sa_u32: u32 = sa as u32;
817        let inv_a: u32 = 255 - sa_u32;
818        for px in span.as_chunks_mut::<4>().0.iter_mut() {
819            let dr: u32 = px[0] as u32;
820            let dg: u32 = px[1] as u32;
821            let db: u32 = px[2] as u32;
822            let da: u32 = px[3] as u32;
823            let vr: u32 = sr * sa_u32 + dr * inv_a + 128;
824            let vg: u32 = sg * sa_u32 + dg * inv_a + 128;
825            let vb: u32 = sb * sa_u32 + db * inv_a + 128;
826            let va: u32 = da * inv_a + 128;
827            px[0] = ((vr + (vr >> 8)) >> 8) as u8;
828            px[1] = ((vg + (vg >> 8)) >> 8) as u8;
829            px[2] = ((vb + (vb >> 8)) >> 8) as u8;
830            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
831        }
832    }
833
834    /// Fills or LUT linear-light blends horizontal span `[x0, x1)` on global row `y`.
835    ///
836    /// # Arguments
837    ///
838    /// - `&Self` - Mutable pixel band.
839    /// - `u32` - Inclusive start X coordinate.
840    /// - `u32` - Exclusive end X coordinate.
841    /// - `u32` - Global physical Y coordinate.
842    /// - `Color` - Foreground RGBA color.
843    pub fn fill_span_linear(&mut self, x0: u32, x1: u32, y: u32, color: Color) {
844        let sa: u8 = color.get_a();
845        if sa == 255 {
846            self.fill_span(x0, x1, y, color);
847            return;
848        }
849        let Self {
850            width,
851            y_offset,
852            height,
853            pixels,
854        } = self;
855        if sa == 0 || y < *y_offset || y >= *y_offset + *height || x0 >= x1 || x0 >= *width {
856            return;
857        }
858        let end_x: u32 = x1.min(*width);
859        let row_base: usize = ((y - *y_offset) as usize) * (*width as usize);
860        let start_byte: usize = (row_base + (x0 as usize)) * 4;
861        let end_byte: usize = (row_base + (end_x as usize)) * 4;
862        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
863            return;
864        };
865        fill_span_linear_slice(span, color);
866    }
867
868    /// Composites horizontal span `[x0, x1)` on global row `y` using precomputed bit-exact 256-entry linear-light channel LUTs.
869    ///
870    /// # Arguments
871    ///
872    /// - `&Self` - Mutable pixel band.
873    /// - `u32` - Inclusive start X coordinate.
874    /// - `u32` - Exclusive end X coordinate.
875    /// - `u32` - Global physical Y coordinate.
876    /// - `&[[u8; 256]; 4]` - Precomputed per-channel lookup tables.
877    pub fn fill_span_linear_luts(&mut self, x0: u32, x1: u32, y: u32, luts: &[[u8; 256]; 4]) {
878        let Self {
879            width,
880            y_offset,
881            height,
882            pixels,
883        } = self;
884        if y < *y_offset || y >= *y_offset + *height || x0 >= x1 || x0 >= *width {
885            return;
886        }
887        let end_x: u32 = x1.min(*width);
888        let row_base: usize = ((y - *y_offset) as usize) * (*width as usize);
889        let start_byte: usize = (row_base + (x0 as usize)) * 4;
890        let end_byte: usize = (row_base + (end_x as usize)) * 4;
891        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
892            return;
893        };
894        fill_span_linear_luts_slice(span, luts);
895    }
896
897    /// Composites a constant-opacity horizontal shadow span `[x0, x1)` on global row `y` with L1 LUT linear light and IGN dithering.
898    ///
899    /// # Arguments
900    ///
901    /// - `&Self` - Mutable pixel band.
902    /// - `u32` - Inclusive start X coordinate.
903    /// - `u32` - Exclusive end X coordinate.
904    /// - `u32` - Global physical Y coordinate.
905    /// - `Color` - Shadow tint RGB.
906    /// - `f32` - Continuous shadow opacity in `[0.0, 1.0]`.
907    pub fn blend_shadow_span_const_alpha(
908        &mut self,
909        x0: u32,
910        x1: u32,
911        y: u32,
912        color: Color,
913        alpha_f: f32,
914    ) {
915        if alpha_f <= 0.0005 {
916            return;
917        }
918        let Self {
919            width,
920            y_offset,
921            height,
922            pixels,
923        } = self;
924        if y < *y_offset || y >= *y_offset + *height || x0 >= x1 || x0 >= *width {
925            return;
926        }
927        let end_x: u32 = x1.min(*width);
928        let row_base: usize = ((y - *y_offset) as usize) * (*width as usize);
929        let start_byte: usize = (row_base + (x0 as usize)) * 4;
930        let end_byte: usize = (row_base + (end_x as usize)) * 4;
931        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
932            return;
933        };
934        let a: f32 = alpha_f.clamp(0.0, 1.0);
935        let cr: u8 = color.get_r();
936        let cg: u8 = color.get_g();
937        let cb: u8 = color.get_b();
938        let (chunks, _): (&mut [[u8; 4]], &mut [u8]) = span.as_chunks_mut::<4>();
939        if a >= 0.9995 {
940            let opaque: [u8; 4] = [cr, cg, cb, 255];
941            for px in chunks.iter_mut() {
942                *px = opaque;
943            }
944            return;
945        }
946        let Some(first_px) = chunks.first().copied() else {
947            return;
948        };
949        let inv_a: f32 = 1.0 - a;
950        let sr_a: f32 = SRGB_TO_LIN_LUT[cr as usize] * a;
951        let sg_a: f32 = SRGB_TO_LIN_LUT[cg as usize] * a;
952        let sb_a: f32 = SRGB_TO_LIN_LUT[cb as usize] * a;
953        let sa_u32: u32 = (a * 255.0) as u32;
954        let inv_a_u32: u32 = 255 - sa_u32;
955        let mut phase_u32: u32 = x0
956            .wrapping_mul(IGN_X_STEP_U32)
957            .wrapping_add(y.wrapping_mul(IGN_Y_STEP_U32));
958        let mut prev_px: [u8; 4] = first_px;
959        let dr0: f32 = SRGB_TO_LIN_LUT[first_px[0] as usize];
960        let dg0: f32 = SRGB_TO_LIN_LUT[first_px[1] as usize];
961        let db0: f32 = SRGB_TO_LIN_LUT[first_px[2] as usize];
962        let ir0: usize = ((sr_a + dr0 * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
963        let ig0: usize = ((sg_a + dg0 * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
964        let ib0: usize = ((sb_a + db0 * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
965        let mut q4_r: u16 = LIN_TO_SRGB_Q4_LUT[ir0];
966        let mut q4_g: u16 = LIN_TO_SRGB_Q4_LUT[ig0];
967        let mut q4_b: u16 = LIN_TO_SRGB_Q4_LUT[ib0];
968        let va0: u32 = (first_px[3] as u32) * inv_a_u32 + 128;
969        let mut out_a: u8 = (sa_u32 + ((va0 + (va0 >> 8)) >> 8)).min(255) as u8;
970        let total_len: usize = chunks.len();
971        let mut miss_count: u32 = 0;
972        let mut split_idx: usize = total_len;
973        for (idx, px) in chunks.iter_mut().enumerate() {
974            if *px != prev_px {
975                miss_count += 1;
976                if miss_count >= 10 && total_len.saturating_sub(idx) >= 64 {
977                    split_idx = idx;
978                    break;
979                }
980                prev_px = *px;
981                let dr: f32 = SRGB_TO_LIN_LUT[px[0] as usize];
982                let dg: f32 = SRGB_TO_LIN_LUT[px[1] as usize];
983                let db: f32 = SRGB_TO_LIN_LUT[px[2] as usize];
984                let ir: usize = ((sr_a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
985                let ig: usize = ((sg_a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
986                let ib: usize = ((sb_a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
987                q4_r = LIN_TO_SRGB_Q4_LUT[ir];
988                q4_g = LIN_TO_SRGB_Q4_LUT[ig];
989                q4_b = LIN_TO_SRGB_Q4_LUT[ib];
990                if px[3] == 255 {
991                    out_a = 255;
992                } else {
993                    let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
994                    out_a = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
995                }
996            }
997            let dq: u16 = (((phase_u32 as u64).wrapping_mul(IGN_MUL_Q26) >> 54) & 15) as u16;
998            phase_u32 = phase_u32.wrapping_add(IGN_X_STEP_U32);
999            px[0] = ((q4_r + dq) >> 4) as u8;
1000            px[1] = ((q4_g + dq) >> 4) as u8;
1001            px[2] = ((q4_b + dq) >> 4) as u8;
1002            px[3] = out_a;
1003        }
1004        if split_idx < total_len {
1005            let tail: &mut [[u8; 4]] = &mut chunks[split_idx..];
1006            let same_rg: bool = cr == cg;
1007            let same_rb: bool = cr == cb;
1008            let lut_r: [u16; 256] = build_shadow_q4_lut_channel(cr, a);
1009            if same_rg && same_rb {
1010                for px in tail.iter_mut() {
1011                    let dq: u16 =
1012                        (((phase_u32 as u64).wrapping_mul(IGN_MUL_Q26) >> 54) & 15) as u16;
1013                    phase_u32 = phase_u32.wrapping_add(IGN_X_STEP_U32);
1014                    px[0] = ((lut_r[px[0] as usize] + dq) >> 4) as u8;
1015                    px[1] = ((lut_r[px[1] as usize] + dq) >> 4) as u8;
1016                    px[2] = ((lut_r[px[2] as usize] + dq) >> 4) as u8;
1017                    if px[3] != 255 {
1018                        let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
1019                        px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1020                    }
1021                }
1022            } else {
1023                let lut_g: [u16; 256] = if same_rg {
1024                    lut_r
1025                } else {
1026                    build_shadow_q4_lut_channel(cg, a)
1027                };
1028                let lut_b: [u16; 256] = if same_rb {
1029                    lut_r
1030                } else {
1031                    build_shadow_q4_lut_channel(cb, a)
1032                };
1033                for px in tail.iter_mut() {
1034                    let dq: u16 =
1035                        (((phase_u32 as u64).wrapping_mul(IGN_MUL_Q26) >> 54) & 15) as u16;
1036                    phase_u32 = phase_u32.wrapping_add(IGN_X_STEP_U32);
1037                    px[0] = ((lut_r[px[0] as usize] + dq) >> 4) as u8;
1038                    px[1] = ((lut_g[px[1] as usize] + dq) >> 4) as u8;
1039                    px[2] = ((lut_b[px[2] as usize] + dq) >> 4) as u8;
1040                    if px[3] != 255 {
1041                        let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
1042                        px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1043                    }
1044                }
1045            }
1046        }
1047    }
1048
1049    /// Blends a contiguous glyph alpha coverage row onto global row `dy` starting at `dx`.
1050    ///
1051    /// # Arguments
1052    ///
1053    /// - `&Self` - Mutable pixel band.
1054    /// - `u32` - Destination starting X coordinate.
1055    /// - `u32` - Global destination Y coordinate.
1056    /// - `&[u8]` - Glyph alpha coverage slice.
1057    /// - `Color` - Foreground text color.
1058    ///
1059    /// # Returns
1060    ///
1061    /// - `usize` - Number of non-zero coverage pixels shaded.
1062    pub fn blend_glyph_row(&mut self, dx: u32, dy: u32, coverage: &[u8], color: Color) -> usize {
1063        let Self {
1064            width,
1065            y_offset,
1066            height,
1067            pixels,
1068        } = self;
1069        if color.get_a() == 0
1070            || dy < *y_offset
1071            || dy >= *y_offset + *height
1072            || dx >= *width
1073            || coverage.is_empty()
1074        {
1075            return 0;
1076        }
1077        let max_len: usize = ((*width - dx) as usize).min(coverage.len());
1078        let start_byte: usize =
1079            (((dy - *y_offset) as usize) * (*width as usize) + (dx as usize)) * 4;
1080        let end_byte: usize = start_byte + max_len * 4;
1081        let Some(dst_span) = pixels.get_mut(start_byte..end_byte) else {
1082            return 0;
1083        };
1084        blend_glyph_row_span(dst_span, &coverage[..max_len], color)
1085    }
1086
1087    /// Blends `color` over global pixel `(x, y)` using fast integer Porter-Duff source-over.
1088    ///
1089    /// # Arguments
1090    ///
1091    /// - `&Self` - Mutable pixel band.
1092    /// - `u32` - X pixel coordinate.
1093    /// - `u32` - Global Y pixel coordinate.
1094    /// - `Color` - Foreground color.
1095    pub fn blend_pixel(&mut self, x: u32, y: u32, color: Color) {
1096        let sa: u8 = color.get_a();
1097        let Self {
1098            width,
1099            y_offset,
1100            height,
1101            pixels,
1102        } = self;
1103        if sa == 0 || x >= *width || y < *y_offset || y >= *y_offset + *height {
1104            return;
1105        }
1106        let offset: usize = (((y - *y_offset) as usize) * (*width as usize) + (x as usize)) * 4;
1107        if offset + 4 > pixels.len() {
1108            return;
1109        }
1110        if sa == 255 {
1111            pixels[offset] = color.get_r();
1112            pixels[offset + 1] = color.get_g();
1113            pixels[offset + 2] = color.get_b();
1114            pixels[offset + 3] = 255;
1115            return;
1116        }
1117        let dst: Color = Color::new(
1118            pixels[offset],
1119            pixels[offset + 1],
1120            pixels[offset + 2],
1121            pixels[offset + 3],
1122        );
1123        let blended: Color = color.blend_over(dst);
1124        pixels[offset] = blended.get_r();
1125        pixels[offset + 1] = blended.get_g();
1126        pixels[offset + 2] = blended.get_b();
1127        pixels[offset + 3] = blended.get_a();
1128    }
1129
1130    /// Blends `color` over global pixel `(x, y)` using L1 LUT linear-light compositing with optional sub-LSB dithering.
1131    ///
1132    /// # Arguments
1133    ///
1134    /// - `&Self` - Mutable pixel band.
1135    /// - `u32` - X pixel coordinate.
1136    /// - `u32` - Global Y pixel coordinate.
1137    /// - `Color` - Foreground color.
1138    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]`.
1139    pub fn blend_pixel_linear_dithered(&mut self, x: u32, y: u32, color: Color, dither: f32) {
1140        let sa: u8 = color.get_a();
1141        let Self {
1142            width,
1143            y_offset,
1144            height,
1145            pixels,
1146        } = self;
1147        if sa == 0 || x >= *width || y < *y_offset || y >= *y_offset + *height {
1148            return;
1149        }
1150        let offset: usize = (((y - *y_offset) as usize) * (*width as usize) + (x as usize)) * 4;
1151        if offset + 4 > pixels.len() {
1152            return;
1153        }
1154        if sa == 255 {
1155            pixels[offset] = color.get_r();
1156            pixels[offset + 1] = color.get_g();
1157            pixels[offset + 2] = color.get_b();
1158            pixels[offset + 3] = 255;
1159            return;
1160        }
1161        let a: f32 = (sa as f32) * (1.0 / 255.0);
1162        let inv_a: f32 = 1.0 - a;
1163        let sr: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize];
1164        let sg: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize];
1165        let sb: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize];
1166        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
1167        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
1168        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
1169        let ir: usize = ((sr * a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1170        let ig: usize = ((sg * a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1171        let ib: usize = ((sb * a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1172        let dq: i32 = (dither * 16.0) as i32 + 8;
1173        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
1174        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
1175        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
1176        let sa_u32: u32 = sa as u32;
1177        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
1178        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1179    }
1180
1181    /// Blends a foreground RGB color with continuous floating-point opacity `alpha_f` onto global pixel `(x, y)` via L1 LUT linear light.
1182    ///
1183    /// # Arguments
1184    ///
1185    /// - `&Self` - Mutable pixel band.
1186    /// - `u32` - X pixel coordinate.
1187    /// - `u32` - Global Y pixel coordinate.
1188    /// - `Color` - Foreground RGB tint.
1189    /// - `f32` - Continuous opacity in `[0.0, 1.0]`.
1190    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]`.
1191    pub fn blend_pixel_f32_dithered(
1192        &mut self,
1193        x: u32,
1194        y: u32,
1195        color: Color,
1196        alpha_f: f32,
1197        dither: f32,
1198    ) {
1199        let Self {
1200            width,
1201            y_offset,
1202            height,
1203            pixels,
1204        } = self;
1205        if alpha_f <= 0.0002 || x >= *width || y < *y_offset || y >= *y_offset + *height {
1206            return;
1207        }
1208        let offset: usize = (((y - *y_offset) as usize) * (*width as usize) + (x as usize)) * 4;
1209        if offset + 4 > pixels.len() {
1210            return;
1211        }
1212        let a: f32 = alpha_f.clamp(0.0, 1.0);
1213        if a >= 0.9995 {
1214            pixels[offset] = color.get_r();
1215            pixels[offset + 1] = color.get_g();
1216            pixels[offset + 2] = color.get_b();
1217            pixels[offset + 3] = 255;
1218            return;
1219        }
1220        let inv_a: f32 = 1.0 - a;
1221        let sr: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize];
1222        let sg: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize];
1223        let sb: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize];
1224        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
1225        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
1226        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
1227        let ir: usize = ((sr * a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1228        let ig: usize = ((sg * a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1229        let ib: usize = ((sb * a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1230        let dq: i32 = (dither * 16.0) as i32 + 8;
1231        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
1232        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
1233        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
1234        let sa_u32: u32 = (a * 255.0) as u32;
1235        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
1236        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1237    }
1238
1239    /// Reads the raw RGBA8 bytes at global pixel `(x, y)` if owned by this band.
1240    ///
1241    /// # Arguments
1242    ///
1243    /// - `&Self` - Pixel band reference.
1244    /// - `u32` - X pixel coordinate.
1245    /// - `u32` - Global Y pixel coordinate.
1246    ///
1247    /// # Returns
1248    ///
1249    /// - `[u8; 4]` - Pixel RGBA8 bytes (`[0, 0, 0, 0]` when out of bounds).
1250    #[must_use]
1251    pub fn get_pixel_rgba(&self, x: u32, y: u32) -> [u8; 4] {
1252        let Self {
1253            width,
1254            y_offset,
1255            height,
1256            pixels,
1257        } = self;
1258        if x >= *width || y < *y_offset || y >= *y_offset + *height {
1259            return [0, 0, 0, 0];
1260        }
1261        let offset: usize = (((y - *y_offset) as usize) * (*width as usize) + (x as usize)) * 4;
1262        if offset + 4 > pixels.len() {
1263            return [0, 0, 0, 0];
1264        }
1265        [
1266            pixels[offset],
1267            pixels[offset + 1],
1268            pixels[offset + 2],
1269            pixels[offset + 3],
1270        ]
1271    }
1272
1273    /// Writes raw RGBA8 bytes directly to global pixel `(x, y)` when owned by this band.
1274    ///
1275    /// # Arguments
1276    ///
1277    /// - `&Self` - Mutable pixel band.
1278    /// - `u32` - X pixel coordinate.
1279    /// - `u32` - Global Y pixel coordinate.
1280    /// - `[u8; 4]` - Target RGBA8 pixel bytes.
1281    pub fn set_pixel_rgba(&mut self, x: u32, y: u32, rgba: [u8; 4]) {
1282        let Self {
1283            width,
1284            y_offset,
1285            height,
1286            pixels,
1287        } = self;
1288        if x >= *width || y < *y_offset || y >= *y_offset + *height {
1289            return;
1290        }
1291        let offset: usize = (((y - *y_offset) as usize) * (*width as usize) + (x as usize)) * 4;
1292        if offset + 4 > pixels.len() {
1293            return;
1294        }
1295        pixels[offset] = rgba[0];
1296        pixels[offset + 1] = rgba[1];
1297        pixels[offset + 2] = rgba[2];
1298        pixels[offset + 3] = rgba[3];
1299    }
1300
1301    /// Blends the current rasterized pixel at `(x, y)` back toward `saved_rgba` using linear-light clip coverage `cov`.
1302    ///
1303    /// # Arguments
1304    ///
1305    /// - `&Self` - Mutable pixel band.
1306    /// - `u32` - X pixel coordinate.
1307    /// - `u32` - Global Y pixel coordinate.
1308    /// - `[u8; 4]` - Pre-command saved RGBA8 pixel bytes.
1309    /// - `f32` - Clip mask coverage in `[0.0, 1.0]` (`1.0` keeps current pixel, `0.0` restores `saved_rgba`).
1310    pub fn lerp_pixel_from_saved_linear(&mut self, x: u32, y: u32, saved_rgba: [u8; 4], cov: f32) {
1311        let Self {
1312            width,
1313            y_offset,
1314            height,
1315            pixels,
1316        } = self;
1317        if x >= *width || y < *y_offset || y >= *y_offset + *height {
1318            return;
1319        }
1320        let offset: usize = (((y - *y_offset) as usize) * (*width as usize) + (x as usize)) * 4;
1321        if offset + 4 > pixels.len() {
1322            return;
1323        }
1324        let cur: [u8; 4] = [
1325            pixels[offset],
1326            pixels[offset + 1],
1327            pixels[offset + 2],
1328            pixels[offset + 3],
1329        ];
1330        if cur == saved_rgba {
1331            return;
1332        }
1333        let c: f32 = cov.clamp(0.0, 1.0);
1334        let inv_c: f32 = 1.0 - c;
1335        let nr: f32 = SRGB_TO_LIN_LUT[cur[0] as usize];
1336        let ng: f32 = SRGB_TO_LIN_LUT[cur[1] as usize];
1337        let nb: f32 = SRGB_TO_LIN_LUT[cur[2] as usize];
1338        let or: f32 = SRGB_TO_LIN_LUT[saved_rgba[0] as usize];
1339        let og: f32 = SRGB_TO_LIN_LUT[saved_rgba[1] as usize];
1340        let ob: f32 = SRGB_TO_LIN_LUT[saved_rgba[2] as usize];
1341        let ir: usize = ((nr * c + or * inv_c) * 4095.0).clamp(0.0, 4095.0) as usize;
1342        let ig: usize = ((ng * c + og * inv_c) * 4095.0).clamp(0.0, 4095.0) as usize;
1343        let ib: usize = ((nb * c + ob * inv_c) * 4095.0).clamp(0.0, 4095.0) as usize;
1344        pixels[offset] = ((LIN_TO_SRGB_Q4_LUT[ir] + 8) >> 4).min(255) as u8;
1345        pixels[offset + 1] = ((LIN_TO_SRGB_Q4_LUT[ig] + 8) >> 4).min(255) as u8;
1346        pixels[offset + 2] = ((LIN_TO_SRGB_Q4_LUT[ib] + 8) >> 4).min(255) as u8;
1347        let na: f32 = (cur[3] as f32) * c + (saved_rgba[3] as f32) * inv_c;
1348        pixels[offset + 3] = na.round().clamp(0.0, 255.0) as u8;
1349    }
1350}
1351
1352/// Damage accumulation helpers for `DamageRegion`.
1353impl DamageRegion {
1354    /// Marks the entire surface damaged.
1355    ///
1356    /// # Returns
1357    ///
1358    /// - `Self` - Full-surface damage region.
1359    #[must_use]
1360    pub fn full() -> Self {
1361        Self {
1362            full_damage: true,
1363            rect: None,
1364            rects: [Rect::default(); 8],
1365            rect_count: 0,
1366        }
1367    }
1368
1369    /// Expands the damaged region to include `rect`, normalizing disjoint regions inline on the stack.
1370    ///
1371    /// # Arguments
1372    ///
1373    /// - `&Self` - Mutable damage region.
1374    /// - `Rect` - Newly damaged rectangle.
1375    pub fn add_rect(&mut self, rect: Rect) {
1376        let Self {
1377            full_damage,
1378            rect: bounds,
1379            rects,
1380            rect_count,
1381        } = self;
1382        if *full_damage {
1383            return;
1384        }
1385        let next_bounds: Rect = match *bounds {
1386            Some(existing) => existing.union(rect),
1387            None => rect,
1388        };
1389        *bounds = Some(next_bounds);
1390        if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
1391            return;
1392        }
1393        let mut merged: Rect = rect;
1394        let mut count: usize = (*rect_count as usize).min(rects.len());
1395        let mut changed: bool = true;
1396        while changed {
1397            changed = false;
1398            let mut i: usize = 0;
1399            while i < count {
1400                let cur: Rect = rects[i];
1401                let touches: bool = merged.get_x() - 2.0 <= cur.right()
1402                    && cur.get_x() - 2.0 <= merged.right()
1403                    && merged.get_y() - 2.0 <= cur.bottom()
1404                    && cur.get_y() - 2.0 <= merged.bottom();
1405                let stacked_column: bool = !touches
1406                    && (merged.get_x() - cur.get_x()).abs() <= 4.0
1407                    && (merged.right() - cur.right()).abs() <= 4.0
1408                    && merged.get_y() - 14.0 <= cur.bottom()
1409                    && cur.get_y() - 14.0 <= merged.bottom();
1410                if touches || stacked_column {
1411                    merged = merged.union(cur);
1412                    count -= 1;
1413                    let mut j: usize = i;
1414                    while j < count {
1415                        rects[j] = rects[j + 1];
1416                        j += 1;
1417                    }
1418                    rects[count] = Rect::default();
1419                    changed = true;
1420                } else {
1421                    i += 1;
1422                }
1423            }
1424        }
1425        if count < rects.len() {
1426            let mut insert_at: usize = count;
1427            while insert_at > 0 {
1428                let prev: Rect = rects[insert_at - 1];
1429                let goes_before: bool = merged.get_y() < prev.get_y()
1430                    || (merged.get_y() == prev.get_y() && merged.get_x() < prev.get_x());
1431                if goes_before {
1432                    rects[insert_at] = prev;
1433                    insert_at -= 1;
1434                } else {
1435                    break;
1436                }
1437            }
1438            rects[insert_at] = merged;
1439            *rect_count = (count + 1) as u8;
1440        } else {
1441            let mut candidates: [Rect; 9] = [Rect::default(); 9];
1442            candidates[..8].copy_from_slice(rects);
1443            candidates[8] = merged;
1444            let mut best_a: usize = 0;
1445            let mut best_b: usize = 1;
1446            let mut best_waste: f32 = f32::INFINITY;
1447            for a in 0..9usize {
1448                let area_a: f32 = candidates[a].get_width() * candidates[a].get_height();
1449                for b in (a + 1)..9usize {
1450                    let area_b: f32 = candidates[b].get_width() * candidates[b].get_height();
1451                    let u: Rect = candidates[a].union(candidates[b]);
1452                    let waste: f32 = (u.get_width() * u.get_height()) - area_a - area_b;
1453                    if waste < best_waste {
1454                        best_waste = waste;
1455                        best_a = a;
1456                        best_b = b;
1457                    }
1458                }
1459            }
1460            candidates[best_a] = candidates[best_a].union(candidates[best_b]);
1461            let mut out_len: usize = 0;
1462            for (idx, item) in candidates.iter().copied().enumerate() {
1463                if idx == best_b {
1464                    continue;
1465                }
1466                let mut pos: usize = out_len;
1467                while pos > 0 {
1468                    let prev: Rect = rects[pos - 1];
1469                    let goes_before: bool = item.get_y() < prev.get_y()
1470                        || (item.get_y() == prev.get_y() && item.get_x() < prev.get_x());
1471                    if goes_before {
1472                        rects[pos] = prev;
1473                        pos -= 1;
1474                    } else {
1475                        break;
1476                    }
1477                }
1478                rects[pos] = item;
1479                out_len += 1;
1480            }
1481            *rect_count = out_len as u8;
1482        }
1483    }
1484
1485    /// Returns viewport-clamped non-overlapping damage rectangles normalized into a stack array without heap allocation.
1486    ///
1487    /// # Arguments
1488    ///
1489    /// - `&Self` - Damage region.
1490    /// - `u32` - Surface physical width.
1491    /// - `u32` - Surface physical height.
1492    ///
1493    /// # Returns
1494    ///
1495    /// - `([Rect; 8], usize)` - Stack array of clamped disjoint damage rectangles and active count `0..=8`.
1496    #[must_use]
1497    pub(crate) fn normalized_rects(&self, width: u32, height: u32) -> ([Rect; 8], usize) {
1498        let Self {
1499            full_damage,
1500            rect: bounds,
1501            rects,
1502            rect_count,
1503        } = *self;
1504        let mut out: [Rect; 8] = [Rect::default(); 8];
1505        if width == 0 || height == 0 {
1506            return (out, 0);
1507        }
1508        let viewport: Rect = Rect::new(0.0, 0.0, width as f32, height as f32);
1509        if full_damage {
1510            out[0] = viewport;
1511            return (out, 1);
1512        }
1513        let Some(bound_rect) = bounds else {
1514            return (out, 0);
1515        };
1516        let active: usize = (rect_count as usize).min(out.len());
1517        if active == 0 {
1518            if let Some(clamped) = bound_rect.intersect(viewport)
1519                && clamped.get_width() > 0.0
1520                && clamped.get_height() > 0.0
1521            {
1522                out[0] = clamped;
1523                return (out, 1);
1524            }
1525            return (out, 0);
1526        }
1527        let mut out_len: usize = 0;
1528        for item in rects.iter().take(active) {
1529            if let Some(clamped) = item.intersect(viewport)
1530                && clamped.get_width() > 0.0
1531                && clamped.get_height() > 0.0
1532            {
1533                out[out_len] = clamped;
1534                out_len += 1;
1535            }
1536        }
1537        (out, out_len)
1538    }
1539
1540    /// Returns the damaged bounding rectangle, or full viewport when `full_damage` is true.
1541    ///
1542    /// # Arguments
1543    ///
1544    /// - `&Self` - Damage region.
1545    /// - `u32` - Surface width.
1546    /// - `u32` - Surface height.
1547    ///
1548    /// # Returns
1549    ///
1550    /// - `Option<Rect>` - Effective clip rect to rasterize, or `None` if undamaged.
1551    #[must_use]
1552    pub fn resolve(&self, width: u32, height: u32) -> Option<Rect> {
1553        if self.get_full_damage() {
1554            return Some(Rect::new(0.0, 0.0, width as f32, height as f32));
1555        }
1556        self.bounds_rect()
1557    }
1558
1559    /// Returns the optional accumulated damage rectangle.
1560    ///
1561    /// # Arguments
1562    ///
1563    /// - `&Self` - Damage region.
1564    ///
1565    /// # Returns
1566    ///
1567    /// - `Option<Rect>` - Accumulated rectangle if any.
1568    #[must_use]
1569    pub fn bounds_rect(&self) -> Option<Rect> {
1570        let Self { rect, .. } = *self;
1571        rect
1572    }
1573
1574    /// Optimizes multi-rect damage by merging low-waste adjacent pairs and promoting to full-viewport damage when covered area exceeds `full_fallback_ratio`.
1575    ///
1576    /// # Arguments
1577    ///
1578    /// - `&Self` - Mutable damage region.
1579    /// - `u32` - Surface physical width in pixels.
1580    /// - `u32` - Surface physical height in pixels.
1581    /// - `f32` - Area coverage threshold in `(0.1..=1.0]` above which full-frame fallback triggers.
1582    ///
1583    /// # Returns
1584    ///
1585    /// - `bool` - `true` if the damage region was promoted to `full_damage`.
1586    pub fn optimize_for_viewport(
1587        &mut self,
1588        width: u32,
1589        height: u32,
1590        full_fallback_ratio: f32,
1591    ) -> bool {
1592        if self.get_full_damage() {
1593            return true;
1594        }
1595        let total_area: f32 = (width as f32) * (height as f32);
1596        if total_area <= 0.0 {
1597            return false;
1598        }
1599        let threshold: f32 = full_fallback_ratio.clamp(0.1, 1.0);
1600        let (mut list, mut count): ([Rect; 8], usize) = self.normalized_rects(width, height);
1601        if count == 0 {
1602            return false;
1603        }
1604        let mut dirty_area: f32 = 0.0;
1605        for item in list.iter().take(count) {
1606            dirty_area += item.get_width().max(0.0) * item.get_height().max(0.0);
1607        }
1608        if dirty_area / total_area >= threshold {
1609            *self = Self::full();
1610            return true;
1611        }
1612        let mut merged_any: bool = true;
1613        while merged_any && count > 1 {
1614            merged_any = false;
1615            let mut best_pair: Option<(usize, usize, Rect, f32)> = None;
1616            for i in 0..count {
1617                let area_i: f32 = list[i].get_width().max(0.0) * list[i].get_height().max(0.0);
1618                for j in (i + 1)..count {
1619                    let area_j: f32 = list[j].get_width().max(0.0) * list[j].get_height().max(0.0);
1620                    let u: Rect = list[i].union(list[j]);
1621                    let union_area: f32 = u.get_width().max(0.0) * u.get_height().max(0.0);
1622                    let waste: f32 = (union_area - (area_i + area_j)).max(0.0);
1623                    let acceptable: bool = waste <= (area_i + area_j) * 0.25 || count > 4;
1624                    if acceptable {
1625                        let better: bool = match best_pair {
1626                            Some((_, _, _, best_w)) => waste < best_w,
1627                            None => true,
1628                        };
1629                        if better {
1630                            best_pair = Some((i, j, u, waste));
1631                        }
1632                    }
1633                }
1634            }
1635            if let Some((i, j, u, _)) = best_pair {
1636                list[i] = u;
1637                let mut k: usize = j;
1638                while k + 1 < count {
1639                    list[k] = list[k + 1];
1640                    k += 1;
1641                }
1642                list[count - 1] = Rect::default();
1643                count -= 1;
1644                merged_any = true;
1645            }
1646        }
1647        let mut post_area: f32 = 0.0;
1648        let mut union_all: Rect = list[0];
1649        for item in list.iter().take(count) {
1650            post_area += item.get_width().max(0.0) * item.get_height().max(0.0);
1651            union_all = union_all.union(*item);
1652        }
1653        if post_area / total_area >= threshold {
1654            *self = Self::full();
1655            return true;
1656        }
1657        let Self {
1658            rect,
1659            rects,
1660            rect_count,
1661            ..
1662        } = self;
1663        *rect = Some(union_all);
1664        *rects = list;
1665        *rect_count = count as u8;
1666        false
1667    }
1668
1669    /// Returns the number of active normalized disjoint damage rectangles.
1670    ///
1671    /// # Arguments
1672    ///
1673    /// - `&Self` - Damage region reference.
1674    ///
1675    /// # Returns
1676    ///
1677    /// - `usize` - Count of disjoint damage rectangles (`1` when `full_damage` is set).
1678    #[must_use]
1679    pub fn active_rect_count(&self) -> usize {
1680        if self.get_full_damage() {
1681            1
1682        } else {
1683            let Self { rect_count, .. } = *self;
1684            rect_count as usize
1685        }
1686    }
1687
1688    /// Resets the damage region to clean.
1689    ///
1690    /// # Arguments
1691    ///
1692    /// - `&Self` - Mutable damage region.
1693    pub fn clear(&mut self) {
1694        let Self {
1695            full_damage,
1696            rect,
1697            rects,
1698            rect_count,
1699        } = self;
1700        *full_damage = false;
1701        *rect = None;
1702        *rects = [Rect::default(); 8];
1703        *rect_count = 0;
1704    }
1705}