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    /// Resizes the framebuffer only when dimensions changed, avoiding per-frame reallocation.
28    ///
29    /// # Arguments
30    ///
31    /// - `&Self` - Mutable framebuffer.
32    /// - `u32` - Target width.
33    /// - `u32` - Target height.
34    ///
35    /// # Returns
36    ///
37    /// - `bool` - True if dimensions changed and buffer was resized.
38    pub fn resize(&mut self, width: u32, height: u32) -> bool {
39        let w: u32 = width.max(1);
40        let h: u32 = height.max(1);
41        if self.get_width() == w && self.get_height() == h {
42            return false;
43        }
44        self.set_width(w);
45        self.set_height(h);
46        let byte_len: usize = (w as usize).saturating_mul(h as usize).saturating_mul(4);
47        self.get_mut_pixels().resize(byte_len, 0);
48        true
49    }
50
51    /// Fills the entire framebuffer with solid `color` using 64-bit wide stores.
52    ///
53    /// # Arguments
54    ///
55    /// - `&Self` - Mutable framebuffer.
56    /// - `Color` - Clear color.
57    pub fn clear(&mut self, color: Color) {
58        let rgba: [u8; 4] = color.to_rgba_bytes();
59        let pair: [u8; 8] = [
60            rgba[0], rgba[1], rgba[2], rgba[3], rgba[0], rgba[1], rgba[2], rgba[3],
61        ];
62        let (wide, tail): (&mut [[u8; 8]], &mut [u8]) = self.get_mut_pixels().as_chunks_mut::<8>();
63        for chunk in wide.iter_mut() {
64            *chunk = pair;
65        }
66        for chunk in tail.as_chunks_mut::<4>().0.iter_mut() {
67            *chunk = rgba;
68        }
69    }
70
71    /// Fills or composites a contiguous horizontal pixel span `[x0, x1)` on row `y`.
72    ///
73    /// # Arguments
74    ///
75    /// - `&Self` - Mutable framebuffer.
76    /// - `u32` - Inclusive start X pixel coordinate.
77    /// - `u32` - Exclusive end X pixel coordinate.
78    /// - `u32` - Row Y pixel coordinate.
79    /// - `Color` - Foreground color to write or alpha-blend.
80    pub fn fill_span(&mut self, x0: u32, x1: u32, y: u32, color: Color) {
81        let sa: u8 = color.get_a();
82        let width: u32 = self.get_width();
83        let height: u32 = self.get_height();
84        if sa == 0 || y >= height || x0 >= x1 || x0 >= width {
85            return;
86        }
87        let end_x: u32 = x1.min(width);
88        let row_base: usize = (y as usize) * (width as usize);
89        let start_byte: usize = (row_base + (x0 as usize)) * 4;
90        let end_byte: usize = (row_base + (end_x as usize)) * 4;
91        let Some(span) = self.get_mut_pixels().get_mut(start_byte..end_byte) else {
92            return;
93        };
94        if sa == 255 {
95            let rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
96            let pair: [u8; 8] = [
97                rgba[0], rgba[1], rgba[2], rgba[3], rgba[0], rgba[1], rgba[2], rgba[3],
98            ];
99            let (wide, tail): (&mut [[u8; 8]], &mut [u8]) = span.as_chunks_mut::<8>();
100            for chunk in wide.iter_mut() {
101                *chunk = pair;
102            }
103            for chunk in tail.as_chunks_mut::<4>().0.iter_mut() {
104                *chunk = rgba;
105            }
106            return;
107        }
108        let sr: u32 = color.get_r() as u32;
109        let sg: u32 = color.get_g() as u32;
110        let sb: u32 = color.get_b() as u32;
111        let sa_u32: u32 = sa as u32;
112        let inv_a: u32 = 255 - sa_u32;
113        for px in span.as_chunks_mut::<4>().0.iter_mut() {
114            let dr: u32 = px[0] as u32;
115            let dg: u32 = px[1] as u32;
116            let db: u32 = px[2] as u32;
117            let da: u32 = px[3] as u32;
118            let vr: u32 = sr * sa_u32 + dr * inv_a + 128;
119            let vg: u32 = sg * sa_u32 + dg * inv_a + 128;
120            let vb: u32 = sb * sa_u32 + db * inv_a + 128;
121            let va: u32 = da * inv_a + 128;
122            px[0] = ((vr + (vr >> 8)) >> 8) as u8;
123            px[1] = ((vg + (vg >> 8)) >> 8) as u8;
124            px[2] = ((vb + (vb >> 8)) >> 8) as u8;
125            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
126        }
127    }
128
129    /// Fills or composites a contiguous horizontal pixel span `[x0, x1)` on row `y` using gamma-correct linear-light blending.
130    ///
131    /// # Arguments
132    ///
133    /// - `&Self` - Mutable framebuffer.
134    /// - `u32` - Inclusive start X pixel coordinate.
135    /// - `u32` - Exclusive end X pixel coordinate.
136    /// - `u32` - Row Y pixel coordinate.
137    /// - `Color` - Foreground color to write or linear-light blend.
138    pub fn fill_span_linear(&mut self, x0: u32, x1: u32, y: u32, color: Color) {
139        let sa: u8 = color.get_a();
140        let width: u32 = self.get_width();
141        let height: u32 = self.get_height();
142        if sa == 0 || y >= height || x0 >= x1 || x0 >= width {
143            return;
144        }
145        if sa == 255 {
146            self.fill_span(x0, x1, y, color);
147            return;
148        }
149        let end_x: u32 = x1.min(width);
150        let row_base: usize = (y as usize) * (width as usize);
151        let start_byte: usize = (row_base + (x0 as usize)) * 4;
152        let end_byte: usize = (row_base + (end_x as usize)) * 4;
153        let Some(span) = self.get_mut_pixels().get_mut(start_byte..end_byte) else {
154            return;
155        };
156        let a: f32 = (sa as f32) * (1.0 / 255.0);
157        let inv_a: f32 = 1.0 - a;
158        let sr_a: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize] * a;
159        let sg_a: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize] * a;
160        let sb_a: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize] * a;
161        let sa_u32: u32 = sa as u32;
162        let inv_a_u32: u32 = 255 - sa_u32;
163        for px in span.as_chunks_mut::<4>().0.iter_mut() {
164            let dr: f32 = SRGB_TO_LIN_LUT[px[0] as usize];
165            let dg: f32 = SRGB_TO_LIN_LUT[px[1] as usize];
166            let db: f32 = SRGB_TO_LIN_LUT[px[2] as usize];
167            let ir: usize = ((sr_a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
168            let ig: usize = ((sg_a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
169            let ib: usize = ((sb_a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
170            let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
171            px[0] = ((LIN_TO_SRGB_Q4_LUT[ir] + 8) >> 4).min(255) as u8;
172            px[1] = ((LIN_TO_SRGB_Q4_LUT[ig] + 8) >> 4).min(255) as u8;
173            px[2] = ((LIN_TO_SRGB_Q4_LUT[ib] + 8) >> 4).min(255) as u8;
174            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
175        }
176    }
177
178    /// Blends a contiguous glyph alpha coverage row directly onto framebuffer row `dy` starting at `dx`.
179    ///
180    /// # Arguments
181    ///
182    /// - `&Self` - Mutable framebuffer.
183    /// - `u32` - Destination starting X pixel coordinate.
184    /// - `u32` - Destination Y pixel coordinate.
185    /// - `&[u8]` - Glyph coverage alpha bytes for the clipped horizontal slice.
186    /// - `Color` - Foreground text color.
187    ///
188    /// # Returns
189    ///
190    /// - `usize` - Number of non-zero coverage pixels shaded.
191    pub fn blend_glyph_row(&mut self, dx: u32, dy: u32, coverage: &[u8], color: Color) -> usize {
192        let width: u32 = self.get_width();
193        let height: u32 = self.get_height();
194        let color_a: u32 = color.get_a() as u32;
195        if color_a == 0 || dy >= height || dx >= width || coverage.is_empty() {
196            return 0;
197        }
198        let max_len: usize = ((width - dx) as usize).min(coverage.len());
199        let start_byte: usize = ((dy as usize) * (width as usize) + (dx as usize)) * 4;
200        let end_byte: usize = start_byte + max_len * 4;
201        let Some(dst_span) = self.get_mut_pixels().get_mut(start_byte..end_byte) else {
202            return 0;
203        };
204        let sr: u32 = color.get_r() as u32;
205        let sg: u32 = color.get_g() as u32;
206        let sb: u32 = color.get_b() as u32;
207        let mut shaded: usize = 0;
208        for (px, alpha_byte) in dst_span
209            .as_chunks_mut::<4>()
210            .0
211            .iter_mut()
212            .zip(coverage[..max_len].iter().copied())
213        {
214            if alpha_byte == 0 {
215                continue;
216            }
217            let sa_u32: u32 = if color_a == 255 {
218                alpha_byte as u32
219            } else {
220                let prod: u32 = color_a * (alpha_byte as u32) + 128;
221                (prod + (prod >> 8)) >> 8
222            };
223            if sa_u32 == 255 {
224                px[0] = sr as u8;
225                px[1] = sg as u8;
226                px[2] = sb as u8;
227                px[3] = 255;
228            } else if sa_u32 > 0 {
229                let inv_a: u32 = 255 - sa_u32;
230                let vr: u32 = sr * sa_u32 + (px[0] as u32) * inv_a + 128;
231                let vg: u32 = sg * sa_u32 + (px[1] as u32) * inv_a + 128;
232                let vb: u32 = sb * sa_u32 + (px[2] as u32) * inv_a + 128;
233                let va: u32 = (px[3] as u32) * inv_a + 128;
234                px[0] = ((vr + (vr >> 8)) >> 8) as u8;
235                px[1] = ((vg + (vg >> 8)) >> 8) as u8;
236                px[2] = ((vb + (vb >> 8)) >> 8) as u8;
237                px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
238            }
239            shaded += 1;
240        }
241        shaded
242    }
243
244    /// Reads the RGBA `Color` at pixel coordinates `(x, y)`.
245    ///
246    /// # Arguments
247    ///
248    /// - `&Self` - Framebuffer reference.
249    /// - `u32` - X pixel coordinate.
250    /// - `u32` - Y pixel coordinate.
251    ///
252    /// # Returns
253    ///
254    /// - `Option<Color>` - Pixel color if within bounds.
255    #[must_use]
256    pub fn get_pixel(&self, x: u32, y: u32) -> Option<Color> {
257        if x >= self.get_width() || y >= self.get_height() {
258            return None;
259        }
260        let offset: usize = ((y as usize) * (self.get_width() as usize) + (x as usize)) * 4;
261        let slice: &[u8] = self.get_pixels().get(offset..offset + 4)?;
262        Some(Color::new(slice[0], slice[1], slice[2], slice[3]))
263    }
264
265    /// Blends `color` over the pixel at `(x, y)` using gamma-correct linear-light compositing with optional sub-LSB dithering.
266    ///
267    /// # Arguments
268    ///
269    /// - `&Self` - Mutable framebuffer.
270    /// - `u32` - X pixel coordinate.
271    /// - `u32` - Y pixel coordinate.
272    /// - `Color` - Foreground color to composite.
273    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]` to eliminate 8-bit banding.
274    pub fn blend_pixel_linear_dithered(&mut self, x: u32, y: u32, color: Color, dither: f32) {
275        let sa: u8 = color.get_a();
276        if sa == 0 || x >= self.get_width() || y >= self.get_height() {
277            return;
278        }
279        let offset: usize = ((y as usize) * (self.get_width() as usize) + (x as usize)) * 4;
280        let pixels: &mut [u8] = self.get_mut_pixels().as_mut_slice();
281        if offset + 4 > pixels.len() {
282            return;
283        }
284        if sa == 255 {
285            pixels[offset] = color.get_r();
286            pixels[offset + 1] = color.get_g();
287            pixels[offset + 2] = color.get_b();
288            pixels[offset + 3] = 255;
289            return;
290        }
291        let a: f32 = (sa as f32) * (1.0 / 255.0);
292        let inv_a: f32 = 1.0 - a;
293        let sr: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize];
294        let sg: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize];
295        let sb: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize];
296        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
297        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
298        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
299        let ir: usize = ((sr * a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
300        let ig: usize = ((sg * a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
301        let ib: usize = ((sb * a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
302        let dq: i32 = (dither * 16.0) as i32 + 8;
303        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
304        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
305        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
306        let sa_u32: u32 = sa as u32;
307        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
308        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
309    }
310
311    /// Blends a foreground RGBA color with continuous floating-point alpha `alpha_f` in `[0.0, 1.0]` using linear-light compositing and IGN dithering.
312    ///
313    /// # Arguments
314    ///
315    /// - `&Self` - Mutable framebuffer.
316    /// - `u32` - X pixel coordinate.
317    /// - `u32` - Y pixel coordinate.
318    /// - `Color` - Foreground RGB tint (its own alpha is already folded into `alpha_f`).
319    /// - `f32` - Continuous opacity in `[0.0, 1.0]`.
320    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]`.
321    pub fn blend_pixel_f32_dithered(
322        &mut self,
323        x: u32,
324        y: u32,
325        color: Color,
326        alpha_f: f32,
327        dither: f32,
328    ) {
329        if alpha_f <= 0.0002 || x >= self.get_width() || y >= self.get_height() {
330            return;
331        }
332        let offset: usize = ((y as usize) * (self.get_width() as usize) + (x as usize)) * 4;
333        let pixels: &mut [u8] = self.get_mut_pixels().as_mut_slice();
334        if offset + 4 > pixels.len() {
335            return;
336        }
337        let a: f32 = alpha_f.clamp(0.0, 1.0);
338        if a >= 0.9995 {
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 inv_a: f32 = 1.0 - a;
346        let sr: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize];
347        let sg: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize];
348        let sb: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize];
349        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
350        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
351        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
352        let ir: usize = ((sr * a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
353        let ig: usize = ((sg * a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
354        let ib: usize = ((sb * a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
355        let dq: i32 = (dither * 16.0) as i32 + 8;
356        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
357        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
358        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
359        let sa_u32: u32 = (a * 255.0) as u32;
360        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
361        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
362    }
363
364    /// Blends `color` over the pixel at `(x, y)` using fast integer Porter-Duff source-over.
365    ///
366    /// # Arguments
367    ///
368    /// - `&Self` - Mutable framebuffer.
369    /// - `u32` - X pixel coordinate.
370    /// - `u32` - Y pixel coordinate.
371    /// - `Color` - Foreground color to composite.
372    pub fn blend_pixel(&mut self, x: u32, y: u32, color: Color) {
373        let sa: u8 = color.get_a();
374        if sa == 0 || x >= self.get_width() || y >= self.get_height() {
375            return;
376        }
377        let offset: usize = ((y as usize) * (self.get_width() as usize) + (x as usize)) * 4;
378        let pixels: &mut [u8] = self.get_mut_pixels().as_mut_slice();
379        if offset + 4 > pixels.len() {
380            return;
381        }
382        if sa == 255 {
383            pixels[offset] = color.get_r();
384            pixels[offset + 1] = color.get_g();
385            pixels[offset + 2] = color.get_b();
386            pixels[offset + 3] = 255;
387            return;
388        }
389        let dst: Color = Color::new(
390            pixels[offset],
391            pixels[offset + 1],
392            pixels[offset + 2],
393            pixels[offset + 3],
394        );
395        let blended: Color = color.blend_over(dst);
396        pixels[offset] = blended.get_r();
397        pixels[offset + 1] = blended.get_g();
398        pixels[offset + 2] = blended.get_b();
399        pixels[offset + 3] = blended.get_a();
400    }
401
402    /// Converts RGBA8 pixels into BGRA8 byte order required by Win32 GDI, X11, and Cocoa/Metal.
403    ///
404    /// # Arguments
405    ///
406    /// - `&Self` - Source RGBA8 framebuffer.
407    ///
408    /// # Returns
409    ///
410    /// - `Vec<u8>` - Packed BGRA8 pixel buffer.
411    #[must_use]
412    pub fn to_bgra_bytes(&self) -> Vec<u8> {
413        let mut out: Vec<u8> = Vec::with_capacity(self.get_pixels().len());
414        for chunk in self.get_pixels().as_chunks::<4>().0.iter() {
415            out.push(chunk[2]);
416            out.push(chunk[1]);
417            out.push(chunk[0]);
418            out.push(chunk[3]);
419        }
420        out
421    }
422
423    /// Computes a deterministic 64-bit 4-lane word-folded FNV-1a hash of the framebuffer pixels.
424    ///
425    /// # Arguments
426    ///
427    /// - `&Self` - Framebuffer to hash.
428    ///
429    /// # Returns
430    ///
431    /// - `u64` - Deterministic endian-independent pixel hash.
432    #[must_use]
433    pub fn fnv1a_hash(&self) -> u64 {
434        let bytes: &[u8] = self.get_pixels().as_slice();
435        let mut h0: u64 = FNV1A_OFFSET_BASIS;
436        let mut h1: u64 = FNV1A_OFFSET_BASIS ^ 0x9E37_79B9_7F4A_7C15;
437        let mut h2: u64 = FNV1A_OFFSET_BASIS ^ 0xBF58_476D_1CE4_E5B9;
438        let mut h3: u64 = FNV1A_OFFSET_BASIS ^ 0x94D0_49BB_1331_11EB;
439        let (blocks, tail): (&[[u8; 32]], &[u8]) = bytes.as_chunks::<32>();
440        for blk in blocks.iter() {
441            let w0: u64 = u64::from_le_bytes([
442                blk[0], blk[1], blk[2], blk[3], blk[4], blk[5], blk[6], blk[7],
443            ]);
444            let w1: u64 = u64::from_le_bytes([
445                blk[8], blk[9], blk[10], blk[11], blk[12], blk[13], blk[14], blk[15],
446            ]);
447            let w2: u64 = u64::from_le_bytes([
448                blk[16], blk[17], blk[18], blk[19], blk[20], blk[21], blk[22], blk[23],
449            ]);
450            let w3: u64 = u64::from_le_bytes([
451                blk[24], blk[25], blk[26], blk[27], blk[28], blk[29], blk[30], blk[31],
452            ]);
453            h0 = (h0 ^ w0).wrapping_mul(FNV1A_PRIME);
454            h1 = (h1 ^ w1).wrapping_mul(FNV1A_PRIME);
455            h2 = (h2 ^ w2).wrapping_mul(FNV1A_PRIME);
456            h3 = (h3 ^ w3).wrapping_mul(FNV1A_PRIME);
457        }
458        let mut hash: u64 = h0 ^ h1.rotate_left(13) ^ h2.rotate_left(29) ^ h3.rotate_left(47);
459        hash = hash.wrapping_mul(FNV1A_PRIME);
460        for byte in tail.iter().copied() {
461            hash ^= byte as u64;
462            hash = hash.wrapping_mul(FNV1A_PRIME);
463        }
464        hash
465    }
466
467    /// Borrows the entire framebuffer as a single zero-copy mutable `PixelBand`.
468    ///
469    /// # Arguments
470    ///
471    /// - `&Self` - Mutable framebuffer.
472    ///
473    /// # Returns
474    ///
475    /// - `PixelBand<'_>` - Full-surface mutable pixel band.
476    pub fn as_band_mut(&mut self) -> PixelBand<'_> {
477        let Self {
478            width,
479            height,
480            pixels,
481        } = self;
482        PixelBand {
483            width: *width,
484            y_offset: 0,
485            height: *height,
486            pixels: pixels.as_mut_slice(),
487        }
488    }
489
490    /// Splits rows `[y0, y1)` of this framebuffer into `band_count` disjoint mutable `PixelBand` slices for safe parallel rasterization.
491    ///
492    /// # Arguments
493    ///
494    /// - `&Self` - Mutable framebuffer.
495    /// - `u32` - Inclusive starting physical Y row.
496    /// - `u32` - Exclusive ending physical Y row.
497    /// - `usize` - Requested number of parallel bands.
498    ///
499    /// # Returns
500    ///
501    /// - `Vec<PixelBand<'_>>` - Non-overlapping mutable horizontal bands covering `[y0, y1)`.
502    pub fn split_bands_mut(&mut self, y0: u32, y1: u32, band_count: usize) -> Vec<PixelBand<'_>> {
503        let Self {
504            width,
505            height,
506            pixels,
507        } = self;
508        let fb_w: u32 = *width;
509        let fb_h: u32 = *height;
510        let start_y: u32 = y0.min(fb_h);
511        let end_y: u32 = y1.clamp(start_y, fb_h);
512        let total_rows: u32 = end_y - start_y;
513        if total_rows == 0 || fb_w == 0 {
514            return Vec::new();
515        }
516        let count: usize = band_count.max(1).min(total_rows as usize);
517        let rows_per: usize = (total_rows as usize).div_ceil(count);
518        let row_stride: usize = (fb_w as usize) * 4;
519        let start_byte: usize = (start_y as usize) * row_stride;
520        let end_byte: usize = (end_y as usize) * row_stride;
521        let Some(slice) = pixels.get_mut(start_byte..end_byte) else {
522            return Vec::new();
523        };
524        let mut bands: Vec<PixelBand<'_>> = Vec::with_capacity(count);
525        let mut cur_y: u32 = start_y;
526        for chunk in slice.chunks_mut(rows_per * row_stride) {
527            let chunk_rows: u32 = (chunk.len() / row_stride) as u32;
528            bands.push(PixelBand {
529                width: fb_w,
530                y_offset: cur_y,
531                height: chunk_rows,
532                pixels: chunk,
533            });
534            cur_y += chunk_rows;
535        }
536        bands
537    }
538}
539
540/// Zero-copy band rasterization primitives for `PixelBand`.
541impl<'a> PixelBand<'a> {
542    /// Returns the full framebuffer width in physical pixels.
543    ///
544    /// # Arguments
545    ///
546    /// - `&Self` - Pixel band reference.
547    ///
548    /// # Returns
549    ///
550    /// - `u32` - Width in physical pixels.
551    #[must_use]
552    pub fn width(&self) -> u32 {
553        let Self { width, .. } = self;
554        *width
555    }
556
557    /// Returns the inclusive top physical Y row owned by this band.
558    ///
559    /// # Arguments
560    ///
561    /// - `&Self` - Pixel band reference.
562    ///
563    /// # Returns
564    ///
565    /// - `u32` - Starting physical Y row.
566    #[must_use]
567    pub fn y_offset(&self) -> u32 {
568        let Self { y_offset, .. } = self;
569        *y_offset
570    }
571
572    /// Returns the exclusive bottom physical Y row owned by this band.
573    ///
574    /// # Arguments
575    ///
576    /// - `&Self` - Pixel band reference.
577    ///
578    /// # Returns
579    ///
580    /// - `u32` - Ending physical Y row.
581    #[must_use]
582    pub fn y_end(&self) -> u32 {
583        let Self {
584            y_offset, height, ..
585        } = self;
586        *y_offset + *height
587    }
588
589    /// Returns the mutable byte slice for global physical row `y` if owned by this band.
590    ///
591    /// # Arguments
592    ///
593    /// - `&Self` - Mutable pixel band.
594    /// - `u32` - Global physical Y row coordinate.
595    ///
596    /// # Returns
597    ///
598    /// - `Option<&mut [u8]>` - Mutable row byte slice (`width * 4` bytes).
599    pub fn row_slice_mut(&mut self, y: u32) -> Option<&mut [u8]> {
600        let Self {
601            width,
602            y_offset,
603            height,
604            pixels,
605        } = self;
606        if y < *y_offset || y >= *y_offset + *height {
607            return None;
608        }
609        let local_y: usize = (y - *y_offset) as usize;
610        let stride: usize = (*width as usize) * 4;
611        let start: usize = local_y * stride;
612        pixels.get_mut(start..start + stride)
613    }
614
615    /// Fills the entire band with solid `color` using 64-bit wide stores.
616    ///
617    /// # Arguments
618    ///
619    /// - `&Self` - Mutable pixel band.
620    /// - `Color` - Clear color.
621    pub fn clear(&mut self, color: Color) {
622        let Self { pixels, .. } = self;
623        let rgba: [u8; 4] = color.to_rgba_bytes();
624        let pair: [u8; 8] = [
625            rgba[0], rgba[1], rgba[2], rgba[3], rgba[0], rgba[1], rgba[2], rgba[3],
626        ];
627        let (wide, tail): (&mut [[u8; 8]], &mut [u8]) = pixels.as_chunks_mut::<8>();
628        for chunk in wide.iter_mut() {
629            *chunk = pair;
630        }
631        for chunk in tail.as_chunks_mut::<4>().0.iter_mut() {
632            *chunk = rgba;
633        }
634    }
635
636    /// Fills or Porter-Duff blends horizontal span `[x0, x1)` on global row `y`.
637    ///
638    /// # Arguments
639    ///
640    /// - `&Self` - Mutable pixel band.
641    /// - `u32` - Inclusive start X coordinate.
642    /// - `u32` - Exclusive end X coordinate.
643    /// - `u32` - Global physical Y coordinate.
644    /// - `Color` - Foreground RGBA color.
645    pub fn fill_span(&mut self, x0: u32, x1: u32, y: u32, color: Color) {
646        let sa: u8 = color.get_a();
647        let Self {
648            width,
649            y_offset,
650            height,
651            pixels,
652        } = self;
653        if sa == 0 || y < *y_offset || y >= *y_offset + *height || x0 >= x1 || x0 >= *width {
654            return;
655        }
656        let end_x: u32 = x1.min(*width);
657        let row_base: usize = ((y - *y_offset) as usize) * (*width as usize);
658        let start_byte: usize = (row_base + (x0 as usize)) * 4;
659        let end_byte: usize = (row_base + (end_x as usize)) * 4;
660        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
661            return;
662        };
663        if sa == 255 {
664            let rgba: [u8; 4] = [color.get_r(), color.get_g(), color.get_b(), 255];
665            let pair: [u8; 8] = [
666                rgba[0], rgba[1], rgba[2], rgba[3], rgba[0], rgba[1], rgba[2], rgba[3],
667            ];
668            let (wide, tail): (&mut [[u8; 8]], &mut [u8]) = span.as_chunks_mut::<8>();
669            for chunk in wide.iter_mut() {
670                *chunk = pair;
671            }
672            for chunk in tail.as_chunks_mut::<4>().0.iter_mut() {
673                *chunk = rgba;
674            }
675            return;
676        }
677        let sr: u32 = color.get_r() as u32;
678        let sg: u32 = color.get_g() as u32;
679        let sb: u32 = color.get_b() as u32;
680        let sa_u32: u32 = sa as u32;
681        let inv_a: u32 = 255 - sa_u32;
682        for px in span.as_chunks_mut::<4>().0.iter_mut() {
683            let dr: u32 = px[0] as u32;
684            let dg: u32 = px[1] as u32;
685            let db: u32 = px[2] as u32;
686            let da: u32 = px[3] as u32;
687            let vr: u32 = sr * sa_u32 + dr * inv_a + 128;
688            let vg: u32 = sg * sa_u32 + dg * inv_a + 128;
689            let vb: u32 = sb * sa_u32 + db * inv_a + 128;
690            let va: u32 = da * inv_a + 128;
691            px[0] = ((vr + (vr >> 8)) >> 8) as u8;
692            px[1] = ((vg + (vg >> 8)) >> 8) as u8;
693            px[2] = ((vb + (vb >> 8)) >> 8) as u8;
694            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
695        }
696    }
697
698    /// Fills or LUT linear-light blends horizontal span `[x0, x1)` on global row `y`.
699    ///
700    /// # Arguments
701    ///
702    /// - `&Self` - Mutable pixel band.
703    /// - `u32` - Inclusive start X coordinate.
704    /// - `u32` - Exclusive end X coordinate.
705    /// - `u32` - Global physical Y coordinate.
706    /// - `Color` - Foreground RGBA color.
707    pub fn fill_span_linear(&mut self, x0: u32, x1: u32, y: u32, color: Color) {
708        let sa: u8 = color.get_a();
709        if sa == 255 {
710            self.fill_span(x0, x1, y, color);
711            return;
712        }
713        let Self {
714            width,
715            y_offset,
716            height,
717            pixels,
718        } = self;
719        if sa == 0 || y < *y_offset || y >= *y_offset + *height || x0 >= x1 || x0 >= *width {
720            return;
721        }
722        let end_x: u32 = x1.min(*width);
723        let row_base: usize = ((y - *y_offset) as usize) * (*width as usize);
724        let start_byte: usize = (row_base + (x0 as usize)) * 4;
725        let end_byte: usize = (row_base + (end_x as usize)) * 4;
726        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
727            return;
728        };
729        if end_x - x0 >= 128 {
730            let (lut_r, lut_g, lut_b, lut_a): ([u8; 256], [u8; 256], [u8; 256], [u8; 256]) =
731                build_linear_blend_luts(color);
732            for px in span.as_chunks_mut::<4>().0.iter_mut() {
733                px[0] = lut_r[px[0] as usize];
734                px[1] = lut_g[px[1] as usize];
735                px[2] = lut_b[px[2] as usize];
736                px[3] = lut_a[px[3] as usize];
737            }
738            return;
739        }
740        let a: f32 = (sa as f32) * (1.0 / 255.0);
741        let inv_a: f32 = 1.0 - a;
742        let sr_a: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize] * a;
743        let sg_a: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize] * a;
744        let sb_a: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize] * a;
745        let sa_u32: u32 = sa as u32;
746        let inv_a_u32: u32 = 255 - sa_u32;
747        for px in span.as_chunks_mut::<4>().0.iter_mut() {
748            let dr: f32 = SRGB_TO_LIN_LUT[px[0] as usize];
749            let dg: f32 = SRGB_TO_LIN_LUT[px[1] as usize];
750            let db: f32 = SRGB_TO_LIN_LUT[px[2] as usize];
751            let ir: usize = ((sr_a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
752            let ig: usize = ((sg_a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
753            let ib: usize = ((sb_a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
754            let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
755            px[0] = ((LIN_TO_SRGB_Q4_LUT[ir] + 8) >> 4).min(255) as u8;
756            px[1] = ((LIN_TO_SRGB_Q4_LUT[ig] + 8) >> 4).min(255) as u8;
757            px[2] = ((LIN_TO_SRGB_Q4_LUT[ib] + 8) >> 4).min(255) as u8;
758            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
759        }
760    }
761
762    /// Composites horizontal span `[x0, x1)` on global row `y` using precomputed bit-exact 256-entry linear-light channel LUTs.
763    ///
764    /// # Arguments
765    ///
766    /// - `&Self` - Mutable pixel band.
767    /// - `u32` - Inclusive start X coordinate.
768    /// - `u32` - Exclusive end X coordinate.
769    /// - `u32` - Global physical Y coordinate.
770    /// - `&([u8; 256], [u8; 256], [u8; 256], [u8; 256])` - Precomputed per-channel lookup tables.
771    pub fn fill_span_linear_luts(
772        &mut self,
773        x0: u32,
774        x1: u32,
775        y: u32,
776        luts: &([u8; 256], [u8; 256], [u8; 256], [u8; 256]),
777    ) {
778        let Self {
779            width,
780            y_offset,
781            height,
782            pixels,
783        } = self;
784        if y < *y_offset || y >= *y_offset + *height || x0 >= x1 || x0 >= *width {
785            return;
786        }
787        let end_x: u32 = x1.min(*width);
788        let row_base: usize = ((y - *y_offset) as usize) * (*width as usize);
789        let start_byte: usize = (row_base + (x0 as usize)) * 4;
790        let end_byte: usize = (row_base + (end_x as usize)) * 4;
791        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
792            return;
793        };
794        let (lut_r, lut_g, lut_b, lut_a): &([u8; 256], [u8; 256], [u8; 256], [u8; 256]) = luts;
795        for px in span.as_chunks_mut::<4>().0.iter_mut() {
796            px[0] = lut_r[px[0] as usize];
797            px[1] = lut_g[px[1] as usize];
798            px[2] = lut_b[px[2] as usize];
799            px[3] = lut_a[px[3] as usize];
800        }
801    }
802
803    /// Composites a constant-opacity horizontal shadow span `[x0, x1)` on global row `y` with L1 LUT linear light and IGN dithering.
804    ///
805    /// # Arguments
806    ///
807    /// - `&Self` - Mutable pixel band.
808    /// - `u32` - Inclusive start X coordinate.
809    /// - `u32` - Exclusive end X coordinate.
810    /// - `u32` - Global physical Y coordinate.
811    /// - `Color` - Shadow tint RGB.
812    /// - `f32` - Continuous shadow opacity in `[0.0, 1.0]`.
813    pub fn blend_shadow_span_const_alpha(
814        &mut self,
815        x0: u32,
816        x1: u32,
817        y: u32,
818        color: Color,
819        alpha_f: f32,
820    ) {
821        if alpha_f <= 0.0005 {
822            return;
823        }
824        let Self {
825            width,
826            y_offset,
827            height,
828            pixels,
829        } = self;
830        if y < *y_offset || y >= *y_offset + *height || x0 >= x1 || x0 >= *width {
831            return;
832        }
833        let end_x: u32 = x1.min(*width);
834        let row_base: usize = ((y - *y_offset) as usize) * (*width as usize);
835        let start_byte: usize = (row_base + (x0 as usize)) * 4;
836        let end_byte: usize = (row_base + (end_x as usize)) * 4;
837        let Some(span) = pixels.get_mut(start_byte..end_byte) else {
838            return;
839        };
840        let a: f32 = alpha_f.clamp(0.0, 1.0);
841        let inv_a: f32 = 1.0 - a;
842        let sr_a: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize] * a;
843        let sg_a: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize] * a;
844        let sb_a: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize] * a;
845        let sa_u32: u32 = (a * 255.0) as u32;
846        let inv_a_u32: u32 = 255 - sa_u32;
847        let y_term: f32 = (y as f32) * 0.005_837_15;
848        for (cur_x, px) in (x0..).zip(span.as_chunks_mut::<4>().0.iter_mut()) {
849            let n: f32 = (52.982_918 * ((cur_x as f32) * 0.067_110_56 + y_term).fract()).fract();
850            let dq: i32 = ((n - 0.5) * 16.0) as i32 + 8;
851            let dr: f32 = SRGB_TO_LIN_LUT[px[0] as usize];
852            let dg: f32 = SRGB_TO_LIN_LUT[px[1] as usize];
853            let db: f32 = SRGB_TO_LIN_LUT[px[2] as usize];
854            let ir: usize = ((sr_a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
855            let ig: usize = ((sg_a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
856            let ib: usize = ((sb_a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
857            let va: u32 = (px[3] as u32) * inv_a_u32 + 128;
858            px[0] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
859            px[1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
860            px[2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
861            px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
862        }
863    }
864
865    /// Blends a contiguous glyph alpha coverage row onto global row `dy` starting at `dx`.
866    ///
867    /// # Arguments
868    ///
869    /// - `&Self` - Mutable pixel band.
870    /// - `u32` - Destination starting X coordinate.
871    /// - `u32` - Global destination Y coordinate.
872    /// - `&[u8]` - Glyph alpha coverage slice.
873    /// - `Color` - Foreground text color.
874    ///
875    /// # Returns
876    ///
877    /// - `usize` - Number of non-zero coverage pixels shaded.
878    pub fn blend_glyph_row(&mut self, dx: u32, dy: u32, coverage: &[u8], color: Color) -> usize {
879        let color_a: u32 = color.get_a() as u32;
880        let Self {
881            width,
882            y_offset,
883            height,
884            pixels,
885        } = self;
886        if color_a == 0
887            || dy < *y_offset
888            || dy >= *y_offset + *height
889            || dx >= *width
890            || coverage.is_empty()
891        {
892            return 0;
893        }
894        let max_len: usize = ((*width - dx) as usize).min(coverage.len());
895        let start_byte: usize =
896            (((dy - *y_offset) as usize) * (*width as usize) + (dx as usize)) * 4;
897        let end_byte: usize = start_byte + max_len * 4;
898        let Some(dst_span) = pixels.get_mut(start_byte..end_byte) else {
899            return 0;
900        };
901        let sr: u32 = color.get_r() as u32;
902        let sg: u32 = color.get_g() as u32;
903        let sb: u32 = color.get_b() as u32;
904        let mut shaded: usize = 0;
905        for (px, alpha_byte) in dst_span
906            .as_chunks_mut::<4>()
907            .0
908            .iter_mut()
909            .zip(coverage[..max_len].iter().copied())
910        {
911            if alpha_byte == 0 {
912                continue;
913            }
914            let sa_u32: u32 = if color_a == 255 {
915                alpha_byte as u32
916            } else {
917                let prod: u32 = color_a * (alpha_byte as u32) + 128;
918                (prod + (prod >> 8)) >> 8
919            };
920            if sa_u32 == 255 {
921                px[0] = sr as u8;
922                px[1] = sg as u8;
923                px[2] = sb as u8;
924                px[3] = 255;
925            } else if sa_u32 > 0 {
926                let inv_a: u32 = 255 - sa_u32;
927                let vr: u32 = sr * sa_u32 + (px[0] as u32) * inv_a + 128;
928                let vg: u32 = sg * sa_u32 + (px[1] as u32) * inv_a + 128;
929                let vb: u32 = sb * sa_u32 + (px[2] as u32) * inv_a + 128;
930                let va: u32 = (px[3] as u32) * inv_a + 128;
931                px[0] = ((vr + (vr >> 8)) >> 8) as u8;
932                px[1] = ((vg + (vg >> 8)) >> 8) as u8;
933                px[2] = ((vb + (vb >> 8)) >> 8) as u8;
934                px[3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
935            }
936            shaded += 1;
937        }
938        shaded
939    }
940
941    /// Blends `color` over global pixel `(x, y)` using fast integer Porter-Duff source-over.
942    ///
943    /// # Arguments
944    ///
945    /// - `&Self` - Mutable pixel band.
946    /// - `u32` - X pixel coordinate.
947    /// - `u32` - Global Y pixel coordinate.
948    /// - `Color` - Foreground color.
949    pub fn blend_pixel(&mut self, x: u32, y: u32, color: Color) {
950        let sa: u8 = color.get_a();
951        let Self {
952            width,
953            y_offset,
954            height,
955            pixels,
956        } = self;
957        if sa == 0 || x >= *width || y < *y_offset || y >= *y_offset + *height {
958            return;
959        }
960        let offset: usize = (((y - *y_offset) as usize) * (*width as usize) + (x as usize)) * 4;
961        if offset + 4 > pixels.len() {
962            return;
963        }
964        if sa == 255 {
965            pixels[offset] = color.get_r();
966            pixels[offset + 1] = color.get_g();
967            pixels[offset + 2] = color.get_b();
968            pixels[offset + 3] = 255;
969            return;
970        }
971        let dst: Color = Color::new(
972            pixels[offset],
973            pixels[offset + 1],
974            pixels[offset + 2],
975            pixels[offset + 3],
976        );
977        let blended: Color = color.blend_over(dst);
978        pixels[offset] = blended.get_r();
979        pixels[offset + 1] = blended.get_g();
980        pixels[offset + 2] = blended.get_b();
981        pixels[offset + 3] = blended.get_a();
982    }
983
984    /// Blends `color` over global pixel `(x, y)` using L1 LUT linear-light compositing with optional sub-LSB dithering.
985    ///
986    /// # Arguments
987    ///
988    /// - `&Self` - Mutable pixel band.
989    /// - `u32` - X pixel coordinate.
990    /// - `u32` - Global Y pixel coordinate.
991    /// - `Color` - Foreground color.
992    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]`.
993    pub fn blend_pixel_linear_dithered(&mut self, x: u32, y: u32, color: Color, dither: f32) {
994        let sa: u8 = color.get_a();
995        let Self {
996            width,
997            y_offset,
998            height,
999            pixels,
1000        } = self;
1001        if sa == 0 || x >= *width || y < *y_offset || y >= *y_offset + *height {
1002            return;
1003        }
1004        let offset: usize = (((y - *y_offset) as usize) * (*width as usize) + (x as usize)) * 4;
1005        if offset + 4 > pixels.len() {
1006            return;
1007        }
1008        if sa == 255 {
1009            pixels[offset] = color.get_r();
1010            pixels[offset + 1] = color.get_g();
1011            pixels[offset + 2] = color.get_b();
1012            pixels[offset + 3] = 255;
1013            return;
1014        }
1015        let a: f32 = (sa as f32) * (1.0 / 255.0);
1016        let inv_a: f32 = 1.0 - a;
1017        let sr: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize];
1018        let sg: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize];
1019        let sb: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize];
1020        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
1021        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
1022        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
1023        let ir: usize = ((sr * a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1024        let ig: usize = ((sg * a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1025        let ib: usize = ((sb * a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1026        let dq: i32 = (dither * 16.0) as i32 + 8;
1027        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
1028        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
1029        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
1030        let sa_u32: u32 = sa as u32;
1031        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
1032        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1033    }
1034
1035    /// Blends a foreground RGB color with continuous floating-point opacity `alpha_f` onto global pixel `(x, y)` via L1 LUT linear light.
1036    ///
1037    /// # Arguments
1038    ///
1039    /// - `&Self` - Mutable pixel band.
1040    /// - `u32` - X pixel coordinate.
1041    /// - `u32` - Global Y pixel coordinate.
1042    /// - `Color` - Foreground RGB tint.
1043    /// - `f32` - Continuous opacity in `[0.0, 1.0]`.
1044    /// - `f32` - Normalized dither offset in `[-0.5, 0.5]`.
1045    pub fn blend_pixel_f32_dithered(
1046        &mut self,
1047        x: u32,
1048        y: u32,
1049        color: Color,
1050        alpha_f: f32,
1051        dither: f32,
1052    ) {
1053        let Self {
1054            width,
1055            y_offset,
1056            height,
1057            pixels,
1058        } = self;
1059        if alpha_f <= 0.0002 || x >= *width || y < *y_offset || y >= *y_offset + *height {
1060            return;
1061        }
1062        let offset: usize = (((y - *y_offset) as usize) * (*width as usize) + (x as usize)) * 4;
1063        if offset + 4 > pixels.len() {
1064            return;
1065        }
1066        let a: f32 = alpha_f.clamp(0.0, 1.0);
1067        if a >= 0.9995 {
1068            pixels[offset] = color.get_r();
1069            pixels[offset + 1] = color.get_g();
1070            pixels[offset + 2] = color.get_b();
1071            pixels[offset + 3] = 255;
1072            return;
1073        }
1074        let inv_a: f32 = 1.0 - a;
1075        let sr: f32 = SRGB_TO_LIN_LUT[color.get_r() as usize];
1076        let sg: f32 = SRGB_TO_LIN_LUT[color.get_g() as usize];
1077        let sb: f32 = SRGB_TO_LIN_LUT[color.get_b() as usize];
1078        let dr: f32 = SRGB_TO_LIN_LUT[pixels[offset] as usize];
1079        let dg: f32 = SRGB_TO_LIN_LUT[pixels[offset + 1] as usize];
1080        let db: f32 = SRGB_TO_LIN_LUT[pixels[offset + 2] as usize];
1081        let ir: usize = ((sr * a + dr * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1082        let ig: usize = ((sg * a + dg * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1083        let ib: usize = ((sb * a + db * inv_a) * 4095.0).clamp(0.0, 4095.0) as usize;
1084        let dq: i32 = (dither * 16.0) as i32 + 8;
1085        pixels[offset] = (((LIN_TO_SRGB_Q4_LUT[ir] as i32) + dq) >> 4).clamp(0, 255) as u8;
1086        pixels[offset + 1] = (((LIN_TO_SRGB_Q4_LUT[ig] as i32) + dq) >> 4).clamp(0, 255) as u8;
1087        pixels[offset + 2] = (((LIN_TO_SRGB_Q4_LUT[ib] as i32) + dq) >> 4).clamp(0, 255) as u8;
1088        let sa_u32: u32 = (a * 255.0) as u32;
1089        let va: u32 = (pixels[offset + 3] as u32) * (255 - sa_u32) + 128;
1090        pixels[offset + 3] = (sa_u32 + ((va + (va >> 8)) >> 8)).min(255) as u8;
1091    }
1092}
1093
1094/// Damage accumulation helpers for `DamageRegion`.
1095impl DamageRegion {
1096    /// Marks the entire surface damaged.
1097    ///
1098    /// # Returns
1099    ///
1100    /// - `Self` - Full-surface damage region.
1101    #[must_use]
1102    pub fn full() -> Self {
1103        Self {
1104            full_damage: true,
1105            rect: None,
1106        }
1107    }
1108
1109    /// Expands the damaged region to include `rect`.
1110    ///
1111    /// # Arguments
1112    ///
1113    /// - `&Self` - Mutable damage region.
1114    /// - `Rect` - Newly damaged rectangle.
1115    pub fn add_rect(&mut self, rect: Rect) {
1116        if self.get_full_damage() {
1117            return;
1118        }
1119        let next: Rect = match self.bounds_rect() {
1120            Some(existing) => existing.union(rect),
1121            None => rect,
1122        };
1123        self.set_rect(Some(next));
1124    }
1125
1126    /// Returns the damaged bounding rectangle, or full viewport when `full_damage` is true.
1127    ///
1128    /// # Arguments
1129    ///
1130    /// - `&Self` - Damage region.
1131    /// - `u32` - Surface width.
1132    /// - `u32` - Surface height.
1133    ///
1134    /// # Returns
1135    ///
1136    /// - `Option<Rect>` - Effective clip rect to rasterize, or `None` if undamaged.
1137    #[must_use]
1138    pub fn resolve(&self, width: u32, height: u32) -> Option<Rect> {
1139        if self.get_full_damage() {
1140            return Some(Rect::new(0.0, 0.0, width as f32, height as f32));
1141        }
1142        self.bounds_rect()
1143    }
1144
1145    /// Returns the optional accumulated damage rectangle.
1146    ///
1147    /// # Arguments
1148    ///
1149    /// - `&Self` - Damage region.
1150    ///
1151    /// # Returns
1152    ///
1153    /// - `Option<Rect>` - Accumulated rectangle if any.
1154    #[must_use]
1155    pub fn bounds_rect(&self) -> Option<Rect> {
1156        let Self { rect, .. } = *self;
1157        rect
1158    }
1159
1160    /// Resets the damage region to clean.
1161    ///
1162    /// # Arguments
1163    ///
1164    /// - `&Self` - Mutable damage region.
1165    pub fn clear(&mut self) {
1166        self.set_full_damage(false);
1167        self.set_rect(None);
1168    }
1169}