Skip to main content

strata_render/
rasterizer.rs

1//! Analytical Signed Distance Field (SDF) 2D Rasterizer & Headless Software FrameBuffer.
2
3use crate::compositor::{DisplayList, DrawCommand};
4use std::fs::File;
5use std::io::Write;
6use std::path::Path;
7use strata_layout::Rect;
8use strata_style::effects::ClipPath;
9use strata_style::types::{BlendMode, BoxShadow, Color, ColorStop};
10
11/// Analytical Signed Distance Field for a rounded rectangle.
12///
13/// Mathematical formula:
14/// Given point `p` relative to center of box with half-extents `b` and corner radius `r`:
15/// `q = |p| - b + r`
16/// `d = length(max(q, 0)) + min(max(q.x, q.y), 0) - r`
17#[inline(always)]
18pub fn sd_rounded_rect(px: f32, py: f32, half_w: f32, half_h: f32, r: f32) -> f32 {
19    let r = r.min(half_w).min(half_h).max(0.0);
20    let qx = px.abs() - half_w + r;
21    let qy = py.abs() - half_h + r;
22
23    let len = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
24    let inside = qx.max(qy).min(0.0);
25    len + inside - r
26}
27
28/// Computes pixel coverage weight [0.0, 1.0] from signed distance.
29#[inline(always)]
30pub fn sdf_coverage(distance: f32) -> f32 {
31    (0.5 - distance).clamp(0.0, 1.0)
32}
33
34/// Standard sRGB gamma exponent for perceptual linearity compensation.
35pub const SRGB_GAMMA: f32 = 2.2;
36
37/// Converts an 8-bit sRGB value [0..255] to linear luminance [0.0..1.0].
38#[inline]
39pub fn srgb_to_linear(v: u8) -> f32 {
40    let s = v as f32 / 255.0;
41    s.powf(SRGB_GAMMA)
42}
43
44/// Converts linear luminance [0.0..1.0] to an 8-bit sRGB value [0..255].
45#[inline]
46pub fn linear_to_srgb(l: f32) -> u8 {
47    let l_clamped = l.clamp(0.0, 1.0);
48    let s = l_clamped.powf(1.0 / SRGB_GAMMA);
49    (s * 255.0).round().clamp(0.0, 255.0) as u8
50}
51
52/// Authentic analytical software rasterizer alias matching FrameBuffer.
53pub type Rasterizer = FrameBuffer;
54
55/// Headless in-memory RGBA pixel canvas for software rasterization and automated testing.
56#[derive(Debug, Clone, PartialEq)]
57pub struct FrameBuffer {
58    pub width: usize,
59    pub height: usize,
60    pub pixels: Vec<u8>, // 4 bytes per pixel: [R, G, B, A]
61    pub clip_mask_stack: Vec<Vec<u8>>,
62}
63
64impl FrameBuffer {
65    /// Creates a new frame buffer initialized to transparent black.
66    pub fn new(width: usize, height: usize) -> Self {
67        Self {
68            width,
69            height,
70            pixels: vec![0; width * height * 4],
71            clip_mask_stack: Vec::new(),
72        }
73    }
74
75    /// Clears the entire buffer with a solid color.
76    pub fn clear(&mut self, color: Color) {
77        let (r, g, b, a) = color.to_rgba8();
78        for chunk in self.pixels.chunks_exact_mut(4) {
79            chunk[0] = r;
80            chunk[1] = g;
81            chunk[2] = b;
82            chunk[3] = a;
83        }
84    }
85
86    /// Clears an axis-aligned rectangular region with a solid color.
87    pub fn clear_rect(&mut self, rect: Rect, color: Color) {
88        let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(rect, None);
89        let (r, g, b, a) = color.to_rgba8();
90        for y in min_y..max_y {
91            let row_start = (y * self.width + min_x) * 4;
92            let row_end = (y * self.width + max_x) * 4;
93            for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
94                chunk[0] = r;
95                chunk[1] = g;
96                chunk[2] = b;
97                chunk[3] = a;
98            }
99        }
100    }
101
102    /// Reads a pixel at (x, y).
103    #[inline]
104    pub fn get_pixel(&self, x: usize, y: usize) -> Color {
105        if x >= self.width || y >= self.height {
106            return Color::TRANSPARENT;
107        }
108        let idx = (y * self.width + x) * 4;
109        Color::rgba(
110            self.pixels[idx],
111            self.pixels[idx + 1],
112            self.pixels[idx + 2],
113            self.pixels[idx + 3],
114        )
115    }
116
117    /// Safe zero-copy byte slice view of raw RGBA pixel data.
118    #[inline]
119    pub fn as_raw_bytes(&self) -> &[u8] {
120        &self.pixels
121    }
122
123    /// Writes a pixel at (x, y) with standard alpha blending (Porter-Duff Over).
124    #[inline]
125    pub fn set_pixel(&mut self, x: usize, y: usize, mut src: Color) {
126        if x >= self.width || y >= self.height {
127            return;
128        }
129        if let Some(mask) = self.clip_mask_stack.last() {
130            let mask_val = mask[y * self.width + x];
131            if mask_val == 0 {
132                return;
133            }
134            if mask_val < 255 {
135                let cov = mask_val as f32 / 255.0;
136                src = Color::from_f32(src.r(), src.g(), src.b(), src.a() * cov);
137            }
138        }
139        let src_a = src.a();
140        if src_a <= 0.001 {
141            return;
142        }
143
144        let idx = (y * self.width + x) * 4;
145        let dst_r = self.pixels[idx] as f32 / 255.0;
146        let dst_g = self.pixels[idx + 1] as f32 / 255.0;
147        let dst_b = self.pixels[idx + 2] as f32 / 255.0;
148        let dst_a = self.pixels[idx + 3] as f32 / 255.0;
149
150        let out_a = src_a + dst_a * (1.0 - src_a);
151        if out_a > 1e-5 {
152            let out_r = (src.r() * src_a + dst_r * dst_a * (1.0 - src_a)) / out_a;
153            let out_g = (src.g() * src_a + dst_g * dst_a * (1.0 - src_a)) / out_a;
154            let out_b = (src.b() * src_a + dst_b * dst_a * (1.0 - src_a)) / out_a;
155
156            self.pixels[idx] = (out_r * 255.0).round() as u8;
157            self.pixels[idx + 1] = (out_g * 255.0).round() as u8;
158            self.pixels[idx + 2] = (out_b * 255.0).round() as u8;
159            self.pixels[idx + 3] = (out_a * 255.0).round() as u8;
160        }
161    }
162
163    /// Blends glyph coverage into the framebuffer at (x, y) with non-linear sRGB gamma compensation (gamma = 2.2).
164    ///
165    /// Prevents optical thinning and dark halos when rendering light text on dark backgrounds
166    /// by performing alpha compositing in physically linear luminance space.
167    pub fn blend_glyph_coverage(&mut self, x: usize, y: usize, color: Color, mut coverage: f32) {
168        if x >= self.width || y >= self.height || coverage <= 0.001 {
169            return;
170        }
171
172        if let Some(mask) = self.clip_mask_stack.last() {
173            let mask_val = mask[y * self.width + x];
174            if mask_val == 0 {
175                return;
176            }
177            if mask_val < 255 {
178                coverage *= mask_val as f32 / 255.0;
179            }
180        }
181
182        let src_a = (color.a() * coverage).clamp(0.0, 1.0);
183        if src_a <= 0.001 {
184            return;
185        }
186
187        let idx = (y * self.width + x) * 4;
188        let dst_r_byte = self.pixels[idx];
189        let dst_g_byte = self.pixels[idx + 1];
190        let dst_b_byte = self.pixels[idx + 2];
191        let dst_a = self.pixels[idx + 3] as f32 / 255.0;
192
193        // Convert destination sRGB values to linear luminance
194        let dst_r_lin = srgb_to_linear(dst_r_byte);
195        let dst_g_lin = srgb_to_linear(dst_g_byte);
196        let dst_b_lin = srgb_to_linear(dst_b_byte);
197
198        // Convert source sRGB values to linear luminance
199        let (sr, sg, sb, _) = color.to_rgba8();
200        let src_r_lin = srgb_to_linear(sr);
201        let src_g_lin = srgb_to_linear(sg);
202        let src_b_lin = srgb_to_linear(sb);
203
204        // Porter-Duff Over in linear space
205        let out_a = src_a + dst_a * (1.0 - src_a);
206        if out_a > 1e-5 {
207            let out_r_lin = (src_r_lin * src_a + dst_r_lin * dst_a * (1.0 - src_a)) / out_a;
208            let out_g_lin = (src_g_lin * src_a + dst_g_lin * dst_a * (1.0 - src_a)) / out_a;
209            let out_b_lin = (src_b_lin * src_a + dst_b_lin * dst_a * (1.0 - src_a)) / out_a;
210
211            self.pixels[idx] = linear_to_srgb(out_r_lin);
212            self.pixels[idx + 1] = linear_to_srgb(out_g_lin);
213            self.pixels[idx + 2] = linear_to_srgb(out_b_lin);
214            self.pixels[idx + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
215        }
216    }
217
218    /// Renders an axis-aligned solid rectangle.
219    pub fn draw_rect(&mut self, bounds: Rect, color: Color, clip: Option<Rect>) {
220        let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
221
222        for y in min_y..max_y {
223            for x in min_x..max_x {
224                self.set_pixel(x, y, color);
225            }
226        }
227    }
228
229    /// Renders an anti-aliased rounded rectangle via Signed Distance Fields.
230    pub fn draw_rounded_rect(
231        &mut self,
232        bounds: Rect,
233        color: Color,
234        radius: f32,
235        border_width: f32,
236        border_color: Option<Color>,
237        clip: Option<Rect>,
238    ) {
239        let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
240        let center_x = bounds.x + bounds.width * 0.5;
241        let center_y = bounds.y + bounds.height * 0.5;
242        let half_w = bounds.width * 0.5;
243        let half_h = bounds.height * 0.5;
244
245        for y in min_y..max_y {
246            let py = y as f32 + 0.5 - center_y;
247            for x in min_x..max_x {
248                let px = x as f32 + 0.5 - center_x;
249
250                let d = sd_rounded_rect(px, py, half_w, half_h, radius);
251                let alpha = sdf_coverage(d);
252
253                if alpha > 0.0 {
254                    if let Some(b_color) = border_color.filter(|_| border_width > 0.0) {
255                        let inner_d = d + border_width;
256                        let inner_alpha = sdf_coverage(inner_d);
257
258                        // Blend border with inner fill
259                        let effective_color = Color::rgba(
260                            (b_color.r() * 255.0) as u8,
261                            (b_color.g() * 255.0) as u8,
262                            (b_color.b() * 255.0) as u8,
263                            (b_color.a() * alpha * (1.0 - inner_alpha) * 255.0) as u8,
264                        );
265                        self.set_pixel(x, y, effective_color);
266
267                        let fill_color = Color::rgba(
268                            (color.r() * 255.0) as u8,
269                            (color.g() * 255.0) as u8,
270                            (color.b() * 255.0) as u8,
271                            (color.a() * inner_alpha * 255.0) as u8,
272                        );
273                        self.set_pixel(x, y, fill_color);
274                    } else {
275                        let blended = Color::rgba(
276                            (color.r() * 255.0) as u8,
277                            (color.g() * 255.0) as u8,
278                            (color.b() * 255.0) as u8,
279                            (color.a() * alpha * 255.0) as u8,
280                        );
281                        self.set_pixel(x, y, blended);
282                    }
283                }
284            }
285        }
286    }
287
288    /// Renders a CSS box-shadow using smoothed SDF drop shadow approximation.
289    pub fn draw_shadow(&mut self, bounds: Rect, shadow: &BoxShadow, clip: Option<Rect>) {
290        if shadow.color.a() <= 0.001 {
291            return;
292        }
293
294        let shadow_bounds = Rect::new(
295            bounds.x + shadow.offset_x - shadow.spread_radius - shadow.blur_radius,
296            bounds.y + shadow.offset_y - shadow.spread_radius - shadow.blur_radius,
297            bounds.width + (shadow.spread_radius + shadow.blur_radius) * 2.0,
298            bounds.height + (shadow.spread_radius + shadow.blur_radius) * 2.0,
299        );
300
301        let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(shadow_bounds, clip);
302        let center_x = bounds.x + shadow.offset_x + bounds.width * 0.5;
303        let center_y = bounds.y + shadow.offset_y + bounds.height * 0.5;
304        let half_w = bounds.width * 0.5 + shadow.spread_radius;
305        let half_h = bounds.height * 0.5 + shadow.spread_radius;
306
307        let blur = shadow.blur_radius.max(1.0);
308
309        for y in min_y..max_y {
310            let py = y as f32 + 0.5 - center_y;
311            for x in min_x..max_x {
312                let px = x as f32 + 0.5 - center_x;
313
314                let d = sd_rounded_rect(px, py, half_w, half_h, 0.0);
315                // Gaussian blur roll-off approximation:
316                let alpha = (-d / blur).exp().clamp(0.0, 1.0) * shadow.color.a();
317
318                if alpha > 0.005 {
319                    let c = Color::rgba(
320                        (shadow.color.r() * 255.0) as u8,
321                        (shadow.color.g() * 255.0) as u8,
322                        (shadow.color.b() * 255.0) as u8,
323                        (alpha * 255.0) as u8,
324                    );
325                    self.set_pixel(x, y, c);
326                }
327            }
328        }
329    }
330
331    /// Renders text using the embedded 8x16 bitmap font.
332    pub fn draw_text(
333        &mut self,
334        origin: (f32, f32),
335        text: &str,
336        font_size: f32,
337        color: Color,
338        clip: Option<Rect>,
339    ) {
340        if color.a() <= 0.001 {
341            return;
342        }
343
344        let scale = (font_size / 16.0).max(0.65);
345        let char_w = 8.0 * scale;
346        let char_h = 16.0 * scale;
347
348        let mut cursor_x = origin.0;
349        let mut cursor_y = origin.1;
350
351        for ch in text.chars() {
352            if ch == '\n' {
353                cursor_y += char_h * 1.25;
354                cursor_x = origin.0;
355                continue;
356            }
357
358            let glyph = crate::font::get_glyph_or_fallback(ch);
359            if (scale - 1.0).abs() < 1e-4
360                && cursor_x.fract().abs() < 1e-4
361                && cursor_y.fract().abs() < 1e-4
362            {
363                let base_x = cursor_x.round() as usize;
364                let base_y = cursor_y.round() as usize;
365                for (row_idx, &row) in glyph.iter().enumerate() {
366                    if row == 0 {
367                        continue;
368                    }
369                    let y = base_y + row_idx;
370                    if y >= self.height {
371                        continue;
372                    }
373                    for col_idx in 0..8 {
374                        if (row & (1 << (7 - col_idx))) != 0 {
375                            let x = base_x + col_idx;
376                            if x >= self.width {
377                                continue;
378                            }
379                            if let Some(c) = clip {
380                                if !c.contains_point(x as f32 + 0.5, y as f32 + 0.5) {
381                                    continue;
382                                }
383                            }
384                            self.blend_glyph_coverage(x, y, color, 1.0);
385                        }
386                    }
387                }
388            } else {
389                let min_x = (cursor_x.floor() as isize).max(0).min(self.width as isize) as usize;
390                let max_x = ((cursor_x + char_w).ceil() as isize)
391                    .max(0)
392                    .min(self.width as isize) as usize;
393                let min_y = (cursor_y.floor() as isize).max(0).min(self.height as isize) as usize;
394                let max_y = ((cursor_y + char_h).ceil() as isize)
395                    .max(0)
396                    .min(self.height as isize) as usize;
397
398                for y in min_y..max_y {
399                    let py = y as f32 + 0.5;
400                    let gy = (py - cursor_y) / scale;
401                    if gy < 0.0 || gy >= 16.0 {
402                        continue;
403                    }
404                    let row_f = gy.clamp(0.0, 15.99);
405                    let r0 = row_f.floor() as usize;
406                    let r1 = (r0 + 1).min(15);
407                    let fr = row_f - r0 as f32;
408
409                    for x in min_x..max_x {
410                        let px = x as f32 + 0.5;
411                        let gx = (px - cursor_x) / scale;
412                        if gx < 0.0 || gx >= 8.0 {
413                            continue;
414                        }
415                        if let Some(c) = clip {
416                            if !c.contains_point(px, py) {
417                                continue;
418                            }
419                        }
420
421                        let col_f = gx.clamp(0.0, 7.99);
422                        let c0 = col_f.floor() as usize;
423                        let c1 = (c0 + 1).min(7);
424                        let fc = col_f - c0 as f32;
425
426                        let b00 = if (glyph[r0] & (1 << (7 - c0))) != 0 {
427                            1.0f32
428                        } else {
429                            0.0f32
430                        };
431                        let b10 = if (glyph[r0] & (1 << (7 - c1))) != 0 {
432                            1.0f32
433                        } else {
434                            0.0f32
435                        };
436                        let b01 = if (glyph[r1] & (1 << (7 - c0))) != 0 {
437                            1.0f32
438                        } else {
439                            0.0f32
440                        };
441                        let b11 = if (glyph[r1] & (1 << (7 - c1))) != 0 {
442                            1.0f32
443                        } else {
444                            0.0f32
445                        };
446
447                        let top = b00 * (1.0 - fc) + b10 * fc;
448                        let bot = b01 * (1.0 - fc) + b11 * fc;
449                        let cov = top * (1.0 - fr) + bot * fr;
450
451                        if cov > 0.01 {
452                            self.blend_glyph_coverage(x, y, color, cov);
453                        }
454                    }
455                }
456            }
457            cursor_x += char_w;
458        }
459    }
460
461    /// Applies CSS filter operations to the specified rectangle in the FrameBuffer.
462    pub fn apply_filter(&mut self, bounds: Rect, filter: &strata_style::effects::BackdropFilter) {
463        if filter.is_empty() {
464            return;
465        }
466        let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, None);
467        if min_x >= max_x || min_y >= max_y {
468            return;
469        }
470
471        for op in &filter.operations {
472            match *op {
473                strata_style::effects::FilterOp::Brightness(factor) => {
474                    for y in min_y..max_y {
475                        let row_start = (y * self.width + min_x) * 4;
476                        let row_end = (y * self.width + max_x) * 4;
477                        for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
478                            chunk[0] = ((chunk[0] as f32 * factor).round() as u32).min(255) as u8;
479                            chunk[1] = ((chunk[1] as f32 * factor).round() as u32).min(255) as u8;
480                            chunk[2] = ((chunk[2] as f32 * factor).round() as u32).min(255) as u8;
481                        }
482                    }
483                }
484                strata_style::effects::FilterOp::Contrast(factor) => {
485                    for y in min_y..max_y {
486                        let row_start = (y * self.width + min_x) * 4;
487                        let row_end = (y * self.width + max_x) * 4;
488                        for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
489                            for ch in &mut chunk[..3] {
490                                let norm = *ch as f32 / 255.0;
491                                let adjusted = ((norm - 0.5) * factor + 0.5).clamp(0.0, 1.0);
492                                *ch = (adjusted * 255.0).round() as u8;
493                            }
494                        }
495                    }
496                }
497                strata_style::effects::FilterOp::Grayscale(amt) => {
498                    let amt = amt.clamp(0.0, 1.0);
499                    let inv = 1.0 - amt;
500                    for y in min_y..max_y {
501                        let row_start = (y * self.width + min_x) * 4;
502                        let row_end = (y * self.width + max_x) * 4;
503                        for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
504                            let r = chunk[0] as f32;
505                            let g = chunk[1] as f32;
506                            let b = chunk[2] as f32;
507                            let gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
508                            chunk[0] = (r * inv + gray * amt).round() as u8;
509                            chunk[1] = (g * inv + gray * amt).round() as u8;
510                            chunk[2] = (b * inv + gray * amt).round() as u8;
511                        }
512                    }
513                }
514                strata_style::effects::FilterOp::Invert(amt) => {
515                    let amt = amt.clamp(0.0, 1.0);
516                    let inv = 1.0 - amt;
517                    for y in min_y..max_y {
518                        let row_start = (y * self.width + min_x) * 4;
519                        let row_end = (y * self.width + max_x) * 4;
520                        for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
521                            chunk[0] = (chunk[0] as f32 * inv + (255 - chunk[0]) as f32 * amt)
522                                .round() as u8;
523                            chunk[1] = (chunk[1] as f32 * inv + (255 - chunk[1]) as f32 * amt)
524                                .round() as u8;
525                            chunk[2] = (chunk[2] as f32 * inv + (255 - chunk[2]) as f32 * amt)
526                                .round() as u8;
527                        }
528                    }
529                }
530                strata_style::effects::FilterOp::Sepia(amt) => {
531                    let amt = amt.clamp(0.0, 1.0);
532                    let inv = 1.0 - amt;
533                    for y in min_y..max_y {
534                        let row_start = (y * self.width + min_x) * 4;
535                        let row_end = (y * self.width + max_x) * 4;
536                        for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
537                            let r = chunk[0] as f32;
538                            let g = chunk[1] as f32;
539                            let b = chunk[2] as f32;
540                            let sr = (0.393 * r + 0.769 * g + 0.189 * b).min(255.0);
541                            let sg = (0.349 * r + 0.686 * g + 0.168 * b).min(255.0);
542                            let sb = (0.272 * r + 0.534 * g + 0.131 * b).min(255.0);
543                            chunk[0] = (r * inv + sr * amt).round() as u8;
544                            chunk[1] = (g * inv + sg * amt).round() as u8;
545                            chunk[2] = (b * inv + sb * amt).round() as u8;
546                        }
547                    }
548                }
549                strata_style::effects::FilterOp::Opacity(amt) => {
550                    let amt = amt.clamp(0.0, 1.0);
551                    for y in min_y..max_y {
552                        let row_start = (y * self.width + min_x) * 4;
553                        let row_end = (y * self.width + max_x) * 4;
554                        for chunk in self.pixels[row_start..row_end].chunks_exact_mut(4) {
555                            chunk[3] = (chunk[3] as f32 * amt).round() as u8;
556                        }
557                    }
558                }
559                _ => {}
560            }
561        }
562    }
563
564    /// Renders an anti-aliased circle.
565    pub fn draw_circle(&mut self, cx: f32, cy: f32, radius: f32, color: Color, clip: Option<Rect>) {
566        if radius <= 0.0 || color.a() <= 0.001 {
567            return;
568        }
569        let bounds = Rect::new(cx - radius, cy - radius, radius * 2.0, radius * 2.0);
570        let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
571
572        for y in min_y..max_y {
573            let py = y as f32 + 0.5 - cy;
574            for x in min_x..max_x {
575                let px = x as f32 + 0.5 - cx;
576                let d = (px * px + py * py).sqrt() - radius;
577                let cov = sdf_coverage(d);
578                if cov > 0.001 {
579                    let mut blended = color;
580                    let out_a = blended.a() * cov;
581                    blended = Color::from_f32(blended.r(), blended.g(), blended.b(), out_a);
582                    self.set_pixel(x, y, blended);
583                }
584            }
585        }
586    }
587
588    /// Renders a multi-stop linear gradient with analytical corner clipping.
589    pub fn draw_linear_gradient(
590        &mut self,
591        bounds: Rect,
592        angle_deg: f32,
593        stops: &[ColorStop],
594        radius: f32,
595        clip: Option<Rect>,
596    ) {
597        if stops.is_empty() || bounds.width <= 0.0 || bounds.height <= 0.0 {
598            return;
599        }
600        let norm_stops = normalize_color_stops(stops);
601        let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
602        let center_x = bounds.x + bounds.width * 0.5;
603        let center_y = bounds.y + bounds.height * 0.5;
604        let half_w = bounds.width * 0.5;
605        let half_h = bounds.height * 0.5;
606
607        let rad = angle_deg.to_radians();
608        let dx = rad.sin();
609        let dy = -rad.cos();
610        let length = (bounds.width * dx.abs() + bounds.height * dy.abs()).max(1e-4);
611
612        for y in min_y..max_y {
613            let py = y as f32 + 0.5 - center_y;
614            for x in min_x..max_x {
615                let px = x as f32 + 0.5 - center_x;
616
617                let d = sd_rounded_rect(px, py, half_w, half_h, radius);
618                let cov = sdf_coverage(d);
619                if cov <= 0.001 {
620                    continue;
621                }
622
623                let proj = px * dx + py * dy;
624                let t = (proj + length * 0.5) / length;
625                let col = sample_gradient(&norm_stops, t);
626
627                if cov >= 0.999 {
628                    self.set_pixel(x, y, col);
629                } else {
630                    let mut blended = col;
631                    let out_a = blended.a() * cov;
632                    blended = Color::from_f32(blended.r(), blended.g(), blended.b(), out_a);
633                    self.set_pixel(x, y, blended);
634                }
635            }
636        }
637    }
638
639    /// Renders a multi-stop radial gradient with analytical corner clipping.
640    pub fn draw_radial_gradient(
641        &mut self,
642        bounds: Rect,
643        center: (f32, f32),
644        stops: &[ColorStop],
645        radius: f32,
646        clip: Option<Rect>,
647    ) {
648        if stops.is_empty() || bounds.width <= 0.0 || bounds.height <= 0.0 {
649            return;
650        }
651        let norm_stops = normalize_color_stops(stops);
652        let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
653        let center_x = bounds.x + bounds.width * 0.5;
654        let center_y = bounds.y + bounds.height * 0.5;
655        let half_w = bounds.width * 0.5;
656        let half_h = bounds.height * 0.5;
657
658        let focal_x = if center.0 <= 1.0 {
659            bounds.x + bounds.width * center.0
660        } else {
661            center.0
662        };
663        let focal_y = if center.1 <= 1.0 {
664            bounds.y + bounds.height * center.1
665        } else {
666            center.1
667        };
668        let rx = half_w.max(1e-4);
669        let ry = half_h.max(1e-4);
670
671        for y in min_y..max_y {
672            let py = y as f32 + 0.5 - center_y;
673            let actual_y = y as f32 + 0.5;
674            for x in min_x..max_x {
675                let px = x as f32 + 0.5 - center_x;
676                let actual_x = x as f32 + 0.5;
677
678                let d = sd_rounded_rect(px, py, half_w, half_h, radius);
679                let cov = sdf_coverage(d);
680                if cov <= 0.001 {
681                    continue;
682                }
683
684                let ndx = (actual_x - focal_x) / rx;
685                let ndy = (actual_y - focal_y) / ry;
686                let t = (ndx * ndx + ndy * ndy).sqrt();
687                let col = sample_gradient(&norm_stops, t);
688
689                if cov >= 0.999 {
690                    self.set_pixel(x, y, col);
691                } else {
692                    let mut blended = col;
693                    let out_a = blended.a() * cov;
694                    blended = Color::from_f32(blended.r(), blended.g(), blended.b(), out_a);
695                    self.set_pixel(x, y, blended);
696                }
697            }
698        }
699    }
700
701    /// Renders an image with bilinear scaling and alpha blending.
702    pub fn draw_image(
703        &mut self,
704        bounds: Rect,
705        image: &strata_layout::ImageResource,
706        clip: Option<Rect>,
707    ) {
708        if bounds.width <= 0.0 || bounds.height <= 0.0 || image.width == 0 || image.height == 0 {
709            return;
710        }
711
712        let raw_pixels =
713            decode_or_get_rgba(&image.data, image.width as usize, image.height as usize);
714        let src_w = image.width as usize;
715        let src_h = image.height as usize;
716        if raw_pixels.len() < src_w * src_h * 4 {
717            return;
718        }
719
720        let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(bounds, clip);
721
722        for y in min_y..max_y {
723            let v = ((y as f32 + 0.5 - bounds.y) / bounds.height * src_h as f32 - 0.5)
724                .clamp(0.0, (src_h - 1) as f32);
725            let y_low = v.floor() as usize;
726            let y_high = (y_low + 1).min(src_h - 1);
727            let fy = v - v.floor();
728
729            for x in min_x..max_x {
730                let u = ((x as f32 + 0.5 - bounds.x) / bounds.width * src_w as f32 - 0.5)
731                    .clamp(0.0, (src_w - 1) as f32);
732                let x_low = u.floor() as usize;
733                let x_high = (x_low + 1).min(src_w - 1);
734                let fx = u - u.floor();
735
736                let idx_tl = (y_low * src_w + x_low) * 4;
737                let idx_tr = (y_low * src_w + x_high) * 4;
738                let idx_bl = (y_high * src_w + x_low) * 4;
739                let idx_br = (y_high * src_w + x_high) * 4;
740
741                let r_t = (raw_pixels[idx_tl] as f32 * (1.0 - fx) + raw_pixels[idx_tr] as f32 * fx)
742                    / 255.0;
743                let g_t = (raw_pixels[idx_tl + 1] as f32 * (1.0 - fx)
744                    + raw_pixels[idx_tr + 1] as f32 * fx)
745                    / 255.0;
746                let b_t = (raw_pixels[idx_tl + 2] as f32 * (1.0 - fx)
747                    + raw_pixels[idx_tr + 2] as f32 * fx)
748                    / 255.0;
749                let a_t = (raw_pixels[idx_tl + 3] as f32 * (1.0 - fx)
750                    + raw_pixels[idx_tr + 3] as f32 * fx)
751                    / 255.0;
752
753                let r_b = (raw_pixels[idx_bl] as f32 * (1.0 - fx) + raw_pixels[idx_br] as f32 * fx)
754                    / 255.0;
755                let g_b = (raw_pixels[idx_bl + 1] as f32 * (1.0 - fx)
756                    + raw_pixels[idx_br + 1] as f32 * fx)
757                    / 255.0;
758                let b_b = (raw_pixels[idx_bl + 2] as f32 * (1.0 - fx)
759                    + raw_pixels[idx_br + 2] as f32 * fx)
760                    / 255.0;
761                let a_b = (raw_pixels[idx_bl + 3] as f32 * (1.0 - fx)
762                    + raw_pixels[idx_br + 3] as f32 * fx)
763                    / 255.0;
764
765                let r = r_t * (1.0 - fy) + r_b * fy;
766                let g = g_t * (1.0 - fy) + g_b * fy;
767                let b = b_t * (1.0 - fy) + b_b * fy;
768                let a = a_t * (1.0 - fy) + a_b * fy;
769
770                self.set_pixel(x, y, Color::from_f32(r, g, b, a));
771            }
772        }
773    }
774
775    /// Renders an SVG vector path with fill and stroke.
776    pub fn draw_svg_path(
777        &mut self,
778        bounds: Rect,
779        path_data: &str,
780        stroke_color: Option<Color>,
781        fill_color: Option<Color>,
782        stroke_width: f32,
783        stroke_linecap: strata_layout::StrokeLineCap,
784        stroke_linejoin: strata_layout::StrokeLineJoin,
785        stroke_dasharray: &[f32],
786        fill_rule: strata_layout::FillRule,
787        view_box: (f32, f32),
788        clip: Option<Rect>,
789    ) {
790        let path = strata_gpu_path::PathBuilder::from_svg(path_data);
791        let scale_x = if view_box.0 > 0.0 {
792            bounds.width / view_box.0
793        } else {
794            1.0
795        };
796        let scale_y = if view_box.1 > 0.0 {
797            bounds.height / view_box.1
798        } else {
799            1.0
800        };
801
802        let quads = path.to_quadratics(0.25);
803        if quads.is_empty() {
804            return;
805        }
806
807        let transformed_quads: Vec<strata_gpu_path::QuadraticBezier> = quads
808            .into_iter()
809            .map(|q| {
810                strata_gpu_path::QuadraticBezier::new(
811                    strata_gpu_path::Point2D::new(
812                        bounds.x + q.p0.x * scale_x,
813                        bounds.y + q.p0.y * scale_y,
814                    ),
815                    strata_gpu_path::Point2D::new(
816                        bounds.x + q.p1.x * scale_x,
817                        bounds.y + q.p1.y * scale_y,
818                    ),
819                    strata_gpu_path::Point2D::new(
820                        bounds.x + q.p2.x * scale_x,
821                        bounds.y + q.p2.y * scale_y,
822                    ),
823                )
824            })
825            .collect();
826
827        let gpu_fill_rule = match fill_rule {
828            strata_layout::FillRule::NonZero => strata_gpu_path::FillRule::NonZero,
829            strata_layout::FillRule::EvenOdd => strata_gpu_path::FillRule::EvenOdd,
830        };
831
832        if let Some(fc) = fill_color {
833            if fc.a() > 0.001 {
834                self.rasterize_curves_fill(&transformed_quads, bounds, fc, gpu_fill_rule, clip);
835            }
836        }
837
838        if let Some(sc) = stroke_color {
839            if sc.a() > 0.001 && stroke_width > 0.0 {
840                let cap = match stroke_linecap {
841                    strata_layout::StrokeLineCap::Round => strata_gpu_path::LineCap::Round,
842                    strata_layout::StrokeLineCap::Square => strata_gpu_path::LineCap::Square,
843                    _ => strata_gpu_path::LineCap::Butt,
844                };
845                let join = match stroke_linejoin {
846                    strata_layout::StrokeLineJoin::Round => strata_gpu_path::LineJoin::Round,
847                    strata_layout::StrokeLineJoin::Bevel => strata_gpu_path::LineJoin::Bevel,
848                    _ => strata_gpu_path::LineJoin::Miter,
849                };
850                let avg_scale = ((scale_x + scale_y) * 0.5).max(0.001);
851                let stroke_opts = strata_gpu_path::StrokeOptions {
852                    width: stroke_width * avg_scale,
853                    miter_limit: 4.0,
854                    cap,
855                    join,
856                };
857                let inflated = Rect::new(
858                    bounds.x - stroke_width * avg_scale,
859                    bounds.y - stroke_width * avg_scale,
860                    bounds.width + stroke_width * avg_scale * 2.0,
861                    bounds.height + stroke_width * avg_scale * 2.0,
862                );
863                let has_dashes = stroke_dasharray.iter().any(|&d| d > 0.0);
864                if has_dashes {
865                    let scaled_dashes: Vec<f32> =
866                        stroke_dasharray.iter().map(|&d| d * avg_scale).collect();
867                    for dash_subpath in
868                        strata_gpu_path::dash_quadratics(&transformed_quads, &scaled_dashes)
869                    {
870                        let stroked_quads = strata_gpu_path::expand_stroke_quadratics(
871                            &dash_subpath,
872                            &stroke_opts,
873                        );
874                        self.rasterize_curves_fill(
875                            &stroked_quads,
876                            inflated,
877                            sc,
878                            strata_gpu_path::FillRule::NonZero,
879                            clip,
880                        );
881                    }
882                } else {
883                    let stroked_quads = strata_gpu_path::expand_stroke_quadratics(
884                        &transformed_quads,
885                        &stroke_opts,
886                    );
887                    self.rasterize_curves_fill(
888                        &stroked_quads,
889                        inflated,
890                        sc,
891                        strata_gpu_path::FillRule::NonZero,
892                        clip,
893                    );
894                }
895            }
896        }
897    }
898
899    /// Renders a GPU vector path with fill and stroke.
900    pub fn draw_gpu_path(
901        &mut self,
902        bounds: Rect,
903        path: &strata_gpu_path::Path,
904        stroke: Option<strata_gpu_path::StrokeOptions>,
905        fill_color: Option<Color>,
906        stroke_color: Option<Color>,
907        transform: Option<strata_primitives::geom::Matrix4x4>,
908        clip: Option<Rect>,
909    ) {
910        let quads = path.to_quadratics(0.25);
911        if quads.is_empty() {
912            return;
913        }
914
915        let transformed_quads: Vec<strata_gpu_path::QuadraticBezier> = quads
916            .into_iter()
917            .map(|q| {
918                let p0 = if let Some(ref m) = transform {
919                    let (tx, ty) = m.transform_point(q.p0.x, q.p0.y);
920                    strata_gpu_path::Point2D::new(bounds.x + tx, bounds.y + ty)
921                } else {
922                    strata_gpu_path::Point2D::new(bounds.x + q.p0.x, bounds.y + q.p0.y)
923                };
924                let p1 = if let Some(ref m) = transform {
925                    let (tx, ty) = m.transform_point(q.p1.x, q.p1.y);
926                    strata_gpu_path::Point2D::new(bounds.x + tx, bounds.y + ty)
927                } else {
928                    strata_gpu_path::Point2D::new(bounds.x + q.p1.x, bounds.y + q.p1.y)
929                };
930                let p2 = if let Some(ref m) = transform {
931                    let (tx, ty) = m.transform_point(q.p2.x, q.p2.y);
932                    strata_gpu_path::Point2D::new(bounds.x + tx, bounds.y + ty)
933                } else {
934                    strata_gpu_path::Point2D::new(bounds.x + q.p2.x, bounds.y + q.p2.y)
935                };
936                strata_gpu_path::QuadraticBezier::new(p0, p1, p2)
937            })
938            .collect();
939
940        let path_fill_rule = path.fill_rule.unwrap_or(strata_gpu_path::FillRule::NonZero);
941        if let Some(fc) = fill_color {
942            if fc.a() > 0.001 {
943                self.rasterize_curves_fill(&transformed_quads, bounds, fc, path_fill_rule, clip);
944            }
945        }
946
947        if let Some(sc) = stroke_color {
948            if sc.a() > 0.001 {
949                let opts = stroke.unwrap_or_else(|| strata_gpu_path::StrokeOptions::new(1.0));
950                let stroked_quads =
951                    strata_gpu_path::expand_stroke_quadratics(&transformed_quads, &opts);
952                let inflated = Rect::new(
953                    bounds.x - opts.width,
954                    bounds.y - opts.width,
955                    bounds.width + opts.width * 2.0,
956                    bounds.height + opts.width * 2.0,
957                );
958                self.rasterize_curves_fill(
959                    &stroked_quads,
960                    inflated,
961                    sc,
962                    strata_gpu_path::FillRule::NonZero,
963                    clip,
964                );
965            }
966        }
967    }
968
969    fn rasterize_curves_fill(
970        &mut self,
971        curves: &[strata_gpu_path::QuadraticBezier],
972        bounds: Rect,
973        color: Color,
974        fill_rule: strata_gpu_path::FillRule,
975        clip: Option<Rect>,
976    ) {
977        if curves.is_empty() || color.a() <= 0.001 {
978            return;
979        }
980
981        let mut min_x_f = bounds.x;
982        let mut min_y_f = bounds.y;
983        let mut max_x_f = bounds.max_x();
984        let mut max_y_f = bounds.max_y();
985
986        for q in curves {
987            let bb = q.bounding_box();
988            min_x_f = min_x_f.min(bb.min_x);
989            min_y_f = min_y_f.min(bb.min_y);
990            max_x_f = max_x_f.max(bb.max_x);
991            max_y_f = max_y_f.max(bb.max_y);
992        }
993
994        let effective_bounds = Rect::new(min_x_f, min_y_f, max_x_f - min_x_f, max_y_f - min_y_f);
995        let (min_x, max_x, min_y, max_y) = self.compute_clamped_bounds(effective_bounds, clip);
996
997        for y in min_y..max_y {
998            let py = y as f32;
999            for x in min_x..max_x {
1000                let px = x as f32;
1001                let mut hits = 0;
1002                let sub_offsets = [(0.25, 0.25), (0.75, 0.25), (0.25, 0.75), (0.75, 0.75)];
1003                for (ox, oy) in sub_offsets {
1004                    let pt = strata_gpu_path::Point2D::new(px + ox, py + oy);
1005                    if strata_gpu_path::is_point_inside_closed_path_rule(pt, curves, fill_rule) {
1006                        hits += 1;
1007                    }
1008                }
1009                if hits > 0 {
1010                    let cov = hits as f32 / 4.0;
1011                    let mut blended = color;
1012                    let out_a = blended.a() * cov;
1013                    blended = Color::from_f32(blended.r(), blended.g(), blended.b(), out_a);
1014                    self.set_pixel(x, y, blended);
1015                }
1016            }
1017        }
1018    }
1019
1020    /// Pushes an arbitrary geometric clip mask.
1021    pub fn push_clip_path(&mut self, bounds: Rect, clip_path: &ClipPath) {
1022        let mut mask = vec![0u8; self.width * self.height];
1023
1024        match clip_path {
1025            ClipPath::None => {
1026                mask.fill(255);
1027            }
1028            ClipPath::Circle {
1029                radius,
1030                center_x,
1031                center_y,
1032            } => {
1033                let cx = bounds.x + center_x;
1034                let cy = bounds.y + center_y;
1035                let r = *radius;
1036                for y in 0..self.height {
1037                    let py = y as f32 + 0.5 - cy;
1038                    for x in 0..self.width {
1039                        let px = x as f32 + 0.5 - cx;
1040                        let d = (px * px + py * py).sqrt() - r;
1041                        let cov = sdf_coverage(d);
1042                        mask[y * self.width + x] = (cov * 255.0).round() as u8;
1043                    }
1044                }
1045            }
1046            ClipPath::Ellipse {
1047                radius_x,
1048                radius_y,
1049                center_x,
1050                center_y,
1051            } => {
1052                let cx = bounds.x + center_x;
1053                let cy = bounds.y + center_y;
1054                let rx = (*radius_x).max(1e-4);
1055                let ry = (*radius_y).max(1e-4);
1056                for y in 0..self.height {
1057                    let py = (y as f32 + 0.5 - cy) / ry;
1058                    for x in 0..self.width {
1059                        let px = (x as f32 + 0.5 - cx) / rx;
1060                        let d = (px * px + py * py).sqrt() - 1.0;
1061                        let cov = (0.5 - d * rx.min(ry)).clamp(0.0, 1.0);
1062                        mask[y * self.width + x] = (cov * 255.0).round() as u8;
1063                    }
1064                }
1065            }
1066            ClipPath::Inset {
1067                top,
1068                right,
1069                bottom,
1070                left,
1071                border_radius,
1072            } => {
1073                let ix = bounds.x + left;
1074                let iy = bounds.y + top;
1075                let iw = (bounds.width - left - right).max(0.0);
1076                let ih = (bounds.height - top - bottom).max(0.0);
1077                let half_w = iw * 0.5;
1078                let half_h = ih * 0.5;
1079                let cx = ix + half_w;
1080                let cy = iy + half_h;
1081                for y in 0..self.height {
1082                    let py = y as f32 + 0.5 - cy;
1083                    for x in 0..self.width {
1084                        let px = x as f32 + 0.5 - cx;
1085                        let d = sd_rounded_rect(px, py, half_w, half_h, *border_radius);
1086                        let cov = sdf_coverage(d);
1087                        mask[y * self.width + x] = (cov * 255.0).round() as u8;
1088                    }
1089                }
1090            }
1091            ClipPath::Polygon(pts) => {
1092                if pts.len() >= 3 {
1093                    let poly_pts: Vec<(f32, f32)> = pts
1094                        .iter()
1095                        .map(|p| (bounds.x + p.x, bounds.y + p.y))
1096                        .collect();
1097                    for y in 0..self.height {
1098                        let py = y as f32 + 0.5;
1099                        for x in 0..self.width {
1100                            let px = x as f32 + 0.5;
1101                            let mut inside = false;
1102                            let n = poly_pts.len();
1103                            let mut j = n - 1;
1104                            for i in 0..n {
1105                                let (xi, yi) = poly_pts[i];
1106                                let (xj, yj) = poly_pts[j];
1107                                if ((yi > py) != (yj > py))
1108                                    && (px < (xj - xi) * (py - yi) / (yj - yi) + xi)
1109                                {
1110                                    inside = !inside;
1111                                }
1112                                j = i;
1113                            }
1114                            if inside {
1115                                mask[y * self.width + x] = 255;
1116                            }
1117                        }
1118                    }
1119                }
1120            }
1121            ClipPath::Path(svg_data) => {
1122                let path = strata_gpu_path::PathBuilder::from_svg(svg_data);
1123                let curves = path.to_quadratics(0.2);
1124                let offset_curves: Vec<strata_gpu_path::QuadraticBezier> = curves
1125                    .into_iter()
1126                    .map(|q| {
1127                        strata_gpu_path::QuadraticBezier::new(
1128                            strata_gpu_path::Point2D::new(q.p0.x + bounds.x, q.p0.y + bounds.y),
1129                            strata_gpu_path::Point2D::new(q.p1.x + bounds.x, q.p1.y + bounds.y),
1130                            strata_gpu_path::Point2D::new(q.p2.x + bounds.x, q.p2.y + bounds.y),
1131                        )
1132                    })
1133                    .collect();
1134
1135                for y in 0..self.height {
1136                    let py = y as f32 + 0.5;
1137                    for x in 0..self.width {
1138                        let pt = strata_gpu_path::Point2D::new(x as f32 + 0.5, py);
1139                        if strata_gpu_path::is_point_inside_closed_path(pt, &offset_curves) {
1140                            mask[y * self.width + x] = 255;
1141                        }
1142                    }
1143                }
1144            }
1145        }
1146
1147        if let Some(parent) = self.clip_mask_stack.last() {
1148            for i in 0..mask.len() {
1149                mask[i] = ((mask[i] as u16 * parent[i] as u16) / 255) as u8;
1150            }
1151        }
1152
1153        self.clip_mask_stack.push(mask);
1154    }
1155
1156    /// Pops the active geometric clip mask.
1157    pub fn pop_clip_path(&mut self) {
1158        self.clip_mask_stack.pop();
1159    }
1160
1161    /// Convenience alias for execute_display_list.
1162    pub fn render_display_list(&mut self, list: &DisplayList) {
1163        self.execute_display_list(list);
1164    }
1165
1166    /// Executes an entire DisplayList onto this FrameBuffer.
1167    pub fn execute_display_list(&mut self, list: &DisplayList) {
1168        let full_bounds = Rect::new(0.0, 0.0, self.width as f32, self.height as f32);
1169        self.execute_display_list_damaged(list, full_bounds);
1170    }
1171
1172    /// Executes a display list scissored strictly to the clustered damage regions tracked by the DamageTracker.
1173    pub fn rasterize_damaged(
1174        &mut self,
1175        list: &DisplayList,
1176        damage: &crate::compositor::DamageTracker,
1177    ) {
1178        let clusters = damage.cluster_damage_rects();
1179        if clusters.is_empty() {
1180            return;
1181        }
1182
1183        for damage_rect in clusters {
1184            self.execute_display_list_damaged(list, damage_rect);
1185        }
1186    }
1187
1188    /// Executes drawing commands strictly scissored to the specified damage rectangle.
1189    /// Commands that do not intersect damage are skipped in O(1).
1190    pub fn execute_display_list_damaged(&mut self, list: &DisplayList, damage: Rect) {
1191        if damage.width <= 0.0 || damage.height <= 0.0 {
1192            return;
1193        }
1194
1195        let mut clip_stack: Vec<Rect> = Vec::new();
1196        let mut transform_stack: Vec<strata_primitives::geom::Matrix4x4> = Vec::new();
1197        let mut filter_stack: Vec<(Rect, strata_style::effects::BackdropFilter)> = Vec::new();
1198        let mut layer_stack: Vec<LayerState> = Vec::new();
1199
1200        for cmd in list.commands() {
1201            // 1. Process state stack push/pop operations
1202            match cmd {
1203                DrawCommand::PushClip { bounds, .. } => {
1204                    let combined = match clip_stack.last() {
1205                        Some(prev) => prev
1206                            .intersect(*bounds)
1207                            .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0)),
1208                        None => *bounds,
1209                    };
1210                    clip_stack.push(combined);
1211                    continue;
1212                }
1213                DrawCommand::PopClip => {
1214                    clip_stack.pop();
1215                    continue;
1216                }
1217                DrawCommand::PushTransform { matrix } => {
1218                    let combined = match transform_stack.last() {
1219                        Some(prev) => prev.multiply(matrix),
1220                        None => *matrix,
1221                    };
1222                    transform_stack.push(combined);
1223                    continue;
1224                }
1225                DrawCommand::PopTransform => {
1226                    transform_stack.pop();
1227                    continue;
1228                }
1229                DrawCommand::PushFilter { bounds, filter } => {
1230                    filter_stack.push((*bounds, filter.clone()));
1231                    continue;
1232                }
1233                DrawCommand::PopFilter => {
1234                    if let Some((bounds, filter)) = filter_stack.pop() {
1235                        let active_matrix = transform_stack.last();
1236                        let tb = if let Some(mat) = active_matrix {
1237                            if !mat.is_identity() {
1238                                let (x, y, w, h) = mat.transform_bounds(
1239                                    bounds.x,
1240                                    bounds.y,
1241                                    bounds.width,
1242                                    bounds.height,
1243                                );
1244                                Rect::new(x, y, w, h)
1245                            } else {
1246                                bounds
1247                            }
1248                        } else {
1249                            bounds
1250                        };
1251                        let target = if let Some(top) = layer_stack.last_mut() {
1252                            &mut top.buffer
1253                        } else {
1254                            &mut *self
1255                        };
1256                        target.apply_filter(tb, &filter);
1257                    }
1258                    continue;
1259                }
1260                DrawCommand::PushBackdropFilter { .. } => {
1261                    continue;
1262                }
1263                DrawCommand::PopBackdropFilter => {
1264                    continue;
1265                }
1266                DrawCommand::PushOpacity { alpha } => {
1267                    layer_stack.push(LayerState {
1268                        buffer: FrameBuffer::new(self.width, self.height),
1269                        opacity: *alpha,
1270                        blend_mode: BlendMode::Normal,
1271                    });
1272                    continue;
1273                }
1274                DrawCommand::PopOpacity => {
1275                    if let Some(popped) = layer_stack.pop() {
1276                        let effective_clip = match clip_stack.last() {
1277                            Some(prev) => prev.intersect(damage),
1278                            None => Some(damage),
1279                        };
1280                        let target = if let Some(top) = layer_stack.last_mut() {
1281                            &mut top.buffer
1282                        } else {
1283                            &mut *self
1284                        };
1285                        composite_layer(
1286                            target,
1287                            &popped.buffer,
1288                            popped.opacity,
1289                            popped.blend_mode,
1290                            effective_clip,
1291                        );
1292                    }
1293                    continue;
1294                }
1295                DrawCommand::PushBlendMode { mode } => {
1296                    layer_stack.push(LayerState {
1297                        buffer: FrameBuffer::new(self.width, self.height),
1298                        opacity: 1.0,
1299                        blend_mode: *mode,
1300                    });
1301                    continue;
1302                }
1303                DrawCommand::PopBlendMode => {
1304                    if let Some(popped) = layer_stack.pop() {
1305                        let effective_clip = match clip_stack.last() {
1306                            Some(prev) => prev.intersect(damage),
1307                            None => Some(damage),
1308                        };
1309                        let target = if let Some(top) = layer_stack.last_mut() {
1310                            &mut top.buffer
1311                        } else {
1312                            &mut *self
1313                        };
1314                        composite_layer(
1315                            target,
1316                            &popped.buffer,
1317                            popped.opacity,
1318                            popped.blend_mode,
1319                            effective_clip,
1320                        );
1321                    }
1322                    continue;
1323                }
1324                DrawCommand::PushIsolation { .. } => {
1325                    layer_stack.push(LayerState {
1326                        buffer: FrameBuffer::new(self.width, self.height),
1327                        opacity: 1.0,
1328                        blend_mode: BlendMode::Normal,
1329                    });
1330                    continue;
1331                }
1332                DrawCommand::PopIsolation => {
1333                    if let Some(popped) = layer_stack.pop() {
1334                        let effective_clip = match clip_stack.last() {
1335                            Some(prev) => prev.intersect(damage),
1336                            None => Some(damage),
1337                        };
1338                        let target = if let Some(top) = layer_stack.last_mut() {
1339                            &mut top.buffer
1340                        } else {
1341                            &mut *self
1342                        };
1343                        composite_layer(
1344                            target,
1345                            &popped.buffer,
1346                            popped.opacity,
1347                            popped.blend_mode,
1348                            effective_clip,
1349                        );
1350                    }
1351                    continue;
1352                }
1353                DrawCommand::PushClipPath { bounds, clip_path } => {
1354                    let active_matrix = transform_stack.last();
1355                    let tb = if let Some(mat) = active_matrix {
1356                        if !mat.is_identity() {
1357                            let (x, y, w, h) = mat.transform_bounds(
1358                                bounds.x,
1359                                bounds.y,
1360                                bounds.width,
1361                                bounds.height,
1362                            );
1363                            Rect::new(x, y, w, h)
1364                        } else {
1365                            *bounds
1366                        }
1367                    } else {
1368                        *bounds
1369                    };
1370                    let target = if let Some(top) = layer_stack.last_mut() {
1371                        &mut top.buffer
1372                    } else {
1373                        &mut *self
1374                    };
1375                    target.push_clip_path(tb, clip_path);
1376                    continue;
1377                }
1378                DrawCommand::PopClipPath => {
1379                    let target = if let Some(top) = layer_stack.last_mut() {
1380                        &mut top.buffer
1381                    } else {
1382                        &mut *self
1383                    };
1384                    target.pop_clip_path();
1385                    continue;
1386                }
1387                _ => {}
1388            }
1389
1390            // 2. Compute effective damage / clip rectangle
1391            let effective_clip = match clip_stack.last() {
1392                Some(prev) => match prev.intersect(damage) {
1393                    Some(c) => c,
1394                    None => continue,
1395                },
1396                None => damage,
1397            };
1398
1399            let active_matrix = transform_stack.last();
1400            let transform_rect_fn = |r: Rect| -> Rect {
1401                if let Some(mat) = active_matrix {
1402                    if !mat.is_identity() {
1403                        let (x, y, w, h) = mat.transform_bounds(r.x, r.y, r.width, r.height);
1404                        return Rect::new(x, y, w, h);
1405                    }
1406                }
1407                r
1408            };
1409
1410            // 3. Skip drawing commands whose bounds do not intersect effective clip
1411            let transformed_cmd_bounds = cmd.bounds().map(transform_rect_fn);
1412            if let Some(cmd_bounds) = transformed_cmd_bounds {
1413                if cmd_bounds.intersect(effective_clip).is_none() {
1414                    continue;
1415                }
1416            }
1417
1418            // 4. Dispatch drawing commands to target
1419            let target = if let Some(top) = layer_stack.last_mut() {
1420                &mut top.buffer
1421            } else {
1422                &mut *self
1423            };
1424
1425            match cmd {
1426                DrawCommand::DrawRect { bounds, color } => {
1427                    target.draw_rect(transform_rect_fn(*bounds), *color, Some(effective_clip));
1428                }
1429                DrawCommand::DrawRoundedRect {
1430                    bounds,
1431                    color,
1432                    border_radius,
1433                    border_width,
1434                    border_color,
1435                } => {
1436                    target.draw_rounded_rect(
1437                        transform_rect_fn(*bounds),
1438                        *color,
1439                        border_radius.top_left,
1440                        border_width.top,
1441                        *border_color,
1442                        Some(effective_clip),
1443                    );
1444                }
1445                DrawCommand::DrawShadow { bounds, shadow, .. } => {
1446                    target.draw_shadow(transform_rect_fn(*bounds), shadow, Some(effective_clip));
1447                }
1448                DrawCommand::DrawBorder {
1449                    bounds,
1450                    widths,
1451                    color,
1452                    border_radius,
1453                    ..
1454                } => {
1455                    target.draw_rounded_rect(
1456                        transform_rect_fn(*bounds),
1457                        Color::TRANSPARENT,
1458                        border_radius.top_left,
1459                        widths.top,
1460                        Some(*color),
1461                        Some(effective_clip),
1462                    );
1463                }
1464                DrawCommand::DrawText {
1465                    origin,
1466                    text,
1467                    font_size,
1468                    color,
1469                    ..
1470                } => {
1471                    let (ox, oy) = if let Some(m) = active_matrix {
1472                        m.transform_point(origin.0, origin.1)
1473                    } else {
1474                        *origin
1475                    };
1476                    target.draw_text((ox, oy), text, *font_size, *color, Some(effective_clip));
1477                }
1478                DrawCommand::DrawViewport3D { bounds, scene } => {
1479                    crate::rasterizer3d::render_scene_3d_with_textures(
1480                        target,
1481                        transform_rect_fn(*bounds),
1482                        scene,
1483                        Some(effective_clip),
1484                        scene.textures_deref(),
1485                    );
1486                }
1487                DrawCommand::DrawCanvas2D { bounds, commands } => {
1488                    let tb = transform_rect_fn(*bounds);
1489                    crate::canvas2d::rasterize_canvas_commands(
1490                        target,
1491                        commands,
1492                        tb.x,
1493                        tb.y,
1494                        Some(effective_clip),
1495                    );
1496                }
1497                DrawCommand::DrawTextFragments { fragments } => {
1498                    for frag in fragments {
1499                        if !frag.text.is_empty() {
1500                            let fb = transform_rect_fn(frag.bounds);
1501                            target.draw_text(
1502                                (fb.x, fb.y),
1503                                &frag.text,
1504                                frag.style.font_size,
1505                                frag.style.color,
1506                                Some(effective_clip),
1507                            );
1508                        }
1509                    }
1510                }
1511                DrawCommand::DrawInsetShadow { bounds, shadow, .. } => {
1512                    target.draw_shadow(transform_rect_fn(*bounds), shadow, Some(effective_clip));
1513                }
1514                DrawCommand::DrawLinearGradient {
1515                    bounds,
1516                    angle_deg,
1517                    stops,
1518                    border_radius,
1519                } => {
1520                    target.draw_linear_gradient(
1521                        transform_rect_fn(*bounds),
1522                        *angle_deg,
1523                        stops,
1524                        border_radius.top_left,
1525                        Some(effective_clip),
1526                    );
1527                }
1528                DrawCommand::DrawRadialGradient {
1529                    bounds,
1530                    center,
1531                    stops,
1532                    border_radius,
1533                } => {
1534                    target.draw_radial_gradient(
1535                        transform_rect_fn(*bounds),
1536                        *center,
1537                        stops,
1538                        border_radius.top_left,
1539                        Some(effective_clip),
1540                    );
1541                }
1542                DrawCommand::DrawImage { bounds, image } => {
1543                    target.draw_image(transform_rect_fn(*bounds), image, Some(effective_clip));
1544                }
1545                DrawCommand::DrawSvgPath {
1546                    bounds,
1547                    path_data,
1548                    stroke_color,
1549                    fill_color,
1550                    stroke_width,
1551                    stroke_linecap,
1552                    stroke_linejoin,
1553                    stroke_dasharray,
1554                    fill_rule,
1555                    view_box,
1556                } => {
1557                    target.draw_svg_path(
1558                        transform_rect_fn(*bounds),
1559                        path_data,
1560                        *stroke_color,
1561                        *fill_color,
1562                        *stroke_width,
1563                        *stroke_linecap,
1564                        *stroke_linejoin,
1565                        stroke_dasharray,
1566                        *fill_rule,
1567                        *view_box,
1568                        Some(effective_clip),
1569                    );
1570                }
1571                DrawCommand::DrawGpuPath {
1572                    bounds,
1573                    path,
1574                    stroke,
1575                    fill_color,
1576                    stroke_color,
1577                    transform,
1578                } => {
1579                    let mut combined_transform = *transform;
1580                    if let Some(m) = active_matrix {
1581                        combined_transform = Some(match combined_transform {
1582                            Some(t) => m.multiply(&t),
1583                            None => *m,
1584                        });
1585                    }
1586                    target.draw_gpu_path(
1587                        transform_rect_fn(*bounds),
1588                        path,
1589                        *stroke,
1590                        *fill_color,
1591                        *stroke_color,
1592                        combined_transform,
1593                        Some(effective_clip),
1594                    );
1595                }
1596                _ => {}
1597            }
1598        }
1599
1600        // Flush any remaining active layers
1601        while let Some(popped) = layer_stack.pop() {
1602            let target = if let Some(top) = layer_stack.last_mut() {
1603                &mut top.buffer
1604            } else {
1605                &mut *self
1606            };
1607            composite_layer(
1608                target,
1609                &popped.buffer,
1610                popped.opacity,
1611                popped.blend_mode,
1612                None,
1613            );
1614        }
1615    }
1616
1617    fn compute_clamped_bounds(
1618        &self,
1619        bounds: Rect,
1620        clip: Option<Rect>,
1621    ) -> (usize, usize, usize, usize) {
1622        let rect = match clip {
1623            Some(c) => bounds.intersect(c).unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0)),
1624            None => bounds,
1625        };
1626
1627        let min_x = (rect.x.floor() as isize).max(0).min(self.width as isize) as usize;
1628        let max_x = (rect.max_x().ceil() as isize)
1629            .max(0)
1630            .min(self.width as isize) as usize;
1631        let min_y = (rect.y.floor() as isize).max(0).min(self.height as isize) as usize;
1632        let max_y = (rect.max_y().ceil() as isize)
1633            .max(0)
1634            .min(self.height as isize) as usize;
1635
1636        (min_x, max_x, min_y, max_y)
1637    }
1638
1639    /// Encodes the current RGBA framebuffer into a standard, spec-compliant PNG byte buffer.
1640    pub fn to_png_bytes(&self) -> Result<Vec<u8>, String> {
1641        if self.width == 0 || self.height == 0 {
1642            return Err("FrameBuffer dimensions must be non-zero to encode PNG".to_string());
1643        }
1644
1645        let mut out = Vec::new();
1646        // 1. PNG 8-byte signature
1647        out.extend_from_slice(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]);
1648
1649        // 2. IHDR Chunk (13 bytes)
1650        let mut ihdr_data = Vec::with_capacity(13);
1651        ihdr_data.extend_from_slice(&(self.width as u32).to_be_bytes());
1652        ihdr_data.extend_from_slice(&(self.height as u32).to_be_bytes());
1653        ihdr_data.push(8); // Bit depth: 8 bits per channel
1654        ihdr_data.push(6); // Color type: 6 = RGBA
1655        ihdr_data.push(0); // Compression method: 0 = Deflate
1656        ihdr_data.push(0); // Filter method: 0 = Standard
1657        ihdr_data.push(0); // Interlace method: 0 = None
1658        write_png_chunk(&mut out, b"IHDR", &ihdr_data);
1659
1660        // 3. Raw Scanlines with Filter None (0)
1661        let row_stride = self.width * 4;
1662        let mut raw_scanlines = Vec::with_capacity(self.height * (1 + row_stride));
1663        for y in 0..self.height {
1664            raw_scanlines.push(0); // Filter type: None
1665            let row_start = y * row_stride;
1666            raw_scanlines.extend_from_slice(&self.pixels[row_start..row_start + row_stride]);
1667        }
1668
1669        // 4. Deflate zlib stream (RFC 1950 & RFC 1951)
1670        let mut deflate_stream = Vec::new();
1671        deflate_stream.push(0x78); // CMF: Deflate, 32K window
1672        deflate_stream.push(0x01); // FLG: No preset dict, check bits
1673
1674        const CHUNK_SIZE: usize = 65535;
1675        let total = raw_scanlines.len();
1676        let mut offset = 0;
1677        while offset < total {
1678            let chunk_len = (total - offset).min(CHUNK_SIZE);
1679            let is_last = (offset + chunk_len) >= total;
1680            let bfinal_btype: u8 = if is_last { 0x01 } else { 0x00 };
1681            deflate_stream.push(bfinal_btype);
1682
1683            let len_u16 = chunk_len as u16;
1684            let nlen_u16 = !len_u16;
1685            deflate_stream.extend_from_slice(&len_u16.to_le_bytes());
1686            deflate_stream.extend_from_slice(&nlen_u16.to_le_bytes());
1687            deflate_stream.extend_from_slice(&raw_scanlines[offset..offset + chunk_len]);
1688            offset += chunk_len;
1689        }
1690
1691        let adler = adler32(&raw_scanlines);
1692        deflate_stream.extend_from_slice(&adler.to_be_bytes());
1693
1694        // 5. IDAT Chunk
1695        write_png_chunk(&mut out, b"IDAT", &deflate_stream);
1696
1697        // 6. IEND Chunk
1698        write_png_chunk(&mut out, b"IEND", &[]);
1699
1700        Ok(out)
1701    }
1702
1703    /// Exports the current framebuffer to a PNG image file at the specified path.
1704    pub fn export_png<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> {
1705        let bytes = self.to_png_bytes().map_err(std::io::Error::other)?;
1706        let mut file = File::create(path)?;
1707        file.write_all(&bytes)?;
1708        file.flush()?;
1709        Ok(())
1710    }
1711
1712    /// Computes a 64-bit difference hash (dHash) for visual regression testing and perceptual diffing.
1713    #[allow(clippy::needless_range_loop)]
1714    pub fn compute_phash(&self) -> u64 {
1715        if self.width == 0 || self.height == 0 {
1716            return 0;
1717        }
1718
1719        let mut grid = [[0.0f32; 9]; 8];
1720        for y in 0..8 {
1721            for x in 0..9 {
1722                let px = (((x as f32 + 0.5) * self.width as f32 / 9.0).floor() as usize)
1723                    .min(self.width - 1);
1724                let py = (((y as f32 + 0.5) * self.height as f32 / 8.0).floor() as usize)
1725                    .min(self.height - 1);
1726                let idx = (py * self.width + px) * 4;
1727                let r = self.pixels[idx] as f32;
1728                let g = self.pixels[idx + 1] as f32;
1729                let b = self.pixels[idx + 2] as f32;
1730                grid[y][x] = 0.299 * r + 0.587 * g + 0.114 * b;
1731            }
1732        }
1733
1734        let mut hash = 0u64;
1735        for y in 0..8 {
1736            for x in 0..8 {
1737                if grid[y][x] > grid[y][x + 1] {
1738                    hash |= 1u64 << (y * 8 + x);
1739                }
1740            }
1741        }
1742        hash
1743    }
1744
1745    /// Computes the Hamming distance (number of differing bits) between two perceptual hashes.
1746    pub fn phash_distance(hash_a: u64, hash_b: u64) -> u32 {
1747        (hash_a ^ hash_b).count_ones()
1748    }
1749}
1750
1751const CRC_TABLE: [u32; 256] = {
1752    let mut table = [0u32; 256];
1753    let mut i = 0;
1754    while i < 256 {
1755        let mut crc = i as u32;
1756        let mut j = 0;
1757        while j < 8 {
1758            if crc & 1 != 0 {
1759                crc = (crc >> 1) ^ 0xEDB8_8320;
1760            } else {
1761                crc >>= 1;
1762            }
1763            j += 1;
1764        }
1765        table[i] = crc;
1766        i += 1;
1767    }
1768    table
1769};
1770
1771fn adler32(data: &[u8]) -> u32 {
1772    let mut s1 = 1u32;
1773    let mut s2 = 0u32;
1774    for &b in data {
1775        s1 = (s1 + b as u32) % 65521;
1776        s2 = (s2 + s1) % 65521;
1777    }
1778    (s2 << 16) | s1
1779}
1780
1781fn write_png_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) {
1782    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
1783    out.extend_from_slice(chunk_type);
1784    out.extend_from_slice(data);
1785
1786    let mut crc = 0xFFFF_FFFFu32;
1787    for &byte in chunk_type {
1788        let idx = ((crc ^ (byte as u32)) & 0xFF) as usize;
1789        crc = (crc >> 8) ^ CRC_TABLE[idx];
1790    }
1791    for &byte in data {
1792        let idx = ((crc ^ (byte as u32)) & 0xFF) as usize;
1793        crc = (crc >> 8) ^ CRC_TABLE[idx];
1794    }
1795    let final_crc = !crc;
1796    out.extend_from_slice(&final_crc.to_be_bytes());
1797}
1798
1799struct LayerState {
1800    buffer: FrameBuffer,
1801    opacity: f32,
1802    blend_mode: BlendMode,
1803}
1804
1805fn composite_layer(
1806    dst: &mut FrameBuffer,
1807    src: &FrameBuffer,
1808    opacity: f32,
1809    blend_mode: BlendMode,
1810    clip: Option<Rect>,
1811) {
1812    if opacity <= 0.0 {
1813        return;
1814    }
1815    let opacity = opacity.clamp(0.0, 1.0);
1816    let (min_x, max_x, min_y, max_y) = if let Some(c) = clip {
1817        dst.compute_clamped_bounds(c, None)
1818    } else {
1819        (0, dst.width.min(src.width), 0, dst.height.min(src.height))
1820    };
1821
1822    for y in min_y..max_y {
1823        for x in min_x..max_x {
1824            let src_idx = (y * src.width + x) * 4;
1825            let src_raw_a = src.pixels[src_idx + 3] as f32 / 255.0;
1826            if src_raw_a <= 0.001 {
1827                continue;
1828            }
1829
1830            let clip_cov = if let Some(mask) = dst.clip_mask_stack.last() {
1831                mask[y * dst.width + x] as f32 / 255.0
1832            } else {
1833                1.0
1834            };
1835            if clip_cov <= 0.001 {
1836                continue;
1837            }
1838
1839            let cs_r = src.pixels[src_idx] as f32 / 255.0;
1840            let cs_g = src.pixels[src_idx + 1] as f32 / 255.0;
1841            let cs_b = src.pixels[src_idx + 2] as f32 / 255.0;
1842            let alpha_s = (src_raw_a * opacity * clip_cov).clamp(0.0, 1.0);
1843
1844            let dst_idx = (y * dst.width + x) * 4;
1845            let cb_r = dst.pixels[dst_idx] as f32 / 255.0;
1846            let cb_g = dst.pixels[dst_idx + 1] as f32 / 255.0;
1847            let cb_b = dst.pixels[dst_idx + 2] as f32 / 255.0;
1848            let alpha_b = dst.pixels[dst_idx + 3] as f32 / 255.0;
1849
1850            let b_r = blend_channel(cb_r, cs_r, blend_mode);
1851            let b_g = blend_channel(cb_g, cs_g, blend_mode);
1852            let b_b = blend_channel(cb_b, cs_b, blend_mode);
1853
1854            let alpha_o = alpha_s + alpha_b * (1.0 - alpha_s);
1855            if alpha_o > 1e-5 {
1856                let out_r = ((1.0 - alpha_b) * alpha_s * cs_r
1857                    + (1.0 - alpha_s) * alpha_b * cb_r
1858                    + alpha_b * alpha_s * b_r)
1859                    / alpha_o;
1860                let out_g = ((1.0 - alpha_b) * alpha_s * cs_g
1861                    + (1.0 - alpha_s) * alpha_b * cb_g
1862                    + alpha_b * alpha_s * b_g)
1863                    / alpha_o;
1864                let out_b = ((1.0 - alpha_b) * alpha_s * cs_b
1865                    + (1.0 - alpha_s) * alpha_b * cb_b
1866                    + alpha_b * alpha_s * b_b)
1867                    / alpha_o;
1868
1869                dst.pixels[dst_idx] = (out_r.clamp(0.0, 1.0) * 255.0).round() as u8;
1870                dst.pixels[dst_idx + 1] = (out_g.clamp(0.0, 1.0) * 255.0).round() as u8;
1871                dst.pixels[dst_idx + 2] = (out_b.clamp(0.0, 1.0) * 255.0).round() as u8;
1872                dst.pixels[dst_idx + 3] = (alpha_o.clamp(0.0, 1.0) * 255.0).round() as u8;
1873            }
1874        }
1875    }
1876}
1877
1878fn blend_channel(cb: f32, cs: f32, mode: BlendMode) -> f32 {
1879    match mode {
1880        BlendMode::Normal => cs,
1881        BlendMode::Multiply => cb * cs,
1882        BlendMode::Screen => cb + cs - cb * cs,
1883        BlendMode::Darken => cb.min(cs),
1884        BlendMode::Lighten => cb.max(cs),
1885        BlendMode::Difference => (cb - cs).abs(),
1886        BlendMode::Exclusion => cb + cs - 2.0 * cb * cs,
1887        BlendMode::Overlay => {
1888            if cb <= 0.5 {
1889                2.0 * cb * cs
1890            } else {
1891                1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)
1892            }
1893        }
1894        BlendMode::HardLight => {
1895            if cs <= 0.5 {
1896                2.0 * cb * cs
1897            } else {
1898                1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)
1899            }
1900        }
1901        BlendMode::SoftLight => {
1902            if cs <= 0.5 {
1903                cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb)
1904            } else {
1905                let d = if cb <= 0.25 {
1906                    ((16.0 * cb - 12.0) * cb + 4.0) * cb
1907                } else {
1908                    cb.sqrt()
1909                };
1910                cb + (2.0 * cs - 1.0) * (d - cb)
1911            }
1912        }
1913        BlendMode::ColorDodge => {
1914            if cb == 0.0 {
1915                0.0
1916            } else if cs >= 1.0 {
1917                1.0
1918            } else {
1919                (cb / (1.0 - cs)).min(1.0)
1920            }
1921        }
1922        BlendMode::ColorBurn => {
1923            if cb >= 1.0 {
1924                1.0
1925            } else if cs <= 0.0 {
1926                0.0
1927            } else {
1928                1.0 - ((1.0 - cb) / cs).min(1.0)
1929            }
1930        }
1931        _ => cs,
1932    }
1933}
1934
1935fn normalize_color_stops(stops: &[ColorStop]) -> Vec<(f32, Color)> {
1936    if stops.is_empty() {
1937        return Vec::new();
1938    }
1939    if stops.len() == 1 {
1940        return vec![(0.0, stops[0].color), (1.0, stops[0].color)];
1941    }
1942
1943    let mut result: Vec<(f32, Color)> = stops
1944        .iter()
1945        .map(|s| (s.position.unwrap_or(-1.0), s.color))
1946        .collect();
1947
1948    // 1. First stop default is 0.0
1949    if result[0].0 < 0.0 {
1950        result[0].0 = 0.0;
1951    }
1952    // 2. Last stop default is 1.0
1953    let last_idx = result.len() - 1;
1954    if result[last_idx].0 < 0.0 {
1955        result[last_idx].0 = 1.0;
1956    }
1957
1958    // 3. Interpolate missing intermediate positions
1959    let mut i = 0;
1960    while i < result.len() {
1961        if result[i].0 < 0.0 {
1962            let start_idx = i - 1;
1963            let start_pos = result[start_idx].0;
1964            let mut end_idx = i;
1965            while end_idx < result.len() && result[end_idx].0 < 0.0 {
1966                end_idx += 1;
1967            }
1968            let end_pos = if end_idx < result.len() {
1969                result[end_idx].0
1970            } else {
1971                1.0
1972            };
1973            let count = (end_idx - start_idx) as f32;
1974            let step = (end_pos - start_pos) / count;
1975            for (k, entry) in result[(start_idx + 1)..end_idx].iter_mut().enumerate() {
1976                entry.0 = start_pos + step * (k + 1) as f32;
1977            }
1978            i = end_idx;
1979        } else {
1980            i += 1;
1981        }
1982    }
1983
1984    // 4. Ensure monotonicity
1985    let mut current_max = 0.0f32;
1986    for entry in &mut result {
1987        if entry.0 < current_max {
1988            entry.0 = current_max;
1989        } else {
1990            current_max = entry.0;
1991        }
1992    }
1993
1994    result
1995}
1996
1997fn sample_gradient(stops: &[(f32, Color)], t: f32) -> Color {
1998    if stops.is_empty() {
1999        return Color::TRANSPARENT;
2000    }
2001    let t = t.clamp(0.0, 1.0);
2002    if t <= stops[0].0 {
2003        return stops[0].1;
2004    }
2005    if t >= stops.last().unwrap().0 {
2006        return stops.last().unwrap().1;
2007    }
2008
2009    for i in 0..stops.len() - 1 {
2010        let (p0, c0) = stops[i];
2011        let (p1, c1) = stops[i + 1];
2012        if t >= p0 && t <= p1 {
2013            let factor = if p1 > p0 { (t - p0) / (p1 - p0) } else { 0.0 };
2014            let r = c0.r() + (c1.r() - c0.r()) * factor;
2015            let g = c0.g() + (c1.g() - c0.g()) * factor;
2016            let b = c0.b() + (c1.b() - c0.b()) * factor;
2017            let a = c0.a() + (c1.a() - c0.a()) * factor;
2018            return Color::from_f32(r, g, b, a);
2019        }
2020    }
2021
2022    stops.last().unwrap().1
2023}
2024
2025fn decode_or_get_rgba(data: &[u8], width: usize, height: usize) -> Vec<u8> {
2026    if data.len() == width * height * 4 {
2027        return data.to_vec();
2028    }
2029    if data.len() >= 8 && data[0..8] == [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A] {
2030        if let Ok(decoded) = decode_png_to_rgba(data, width, height) {
2031            return decoded;
2032        }
2033    }
2034    if data.len() == width * height * 3 {
2035        let mut out = Vec::with_capacity(width * height * 4);
2036        for chunk in data.chunks_exact(3) {
2037            out.push(chunk[0]);
2038            out.push(chunk[1]);
2039            out.push(chunk[2]);
2040            out.push(255);
2041        }
2042        return out;
2043    }
2044
2045    vec![0u8; width * height * 4]
2046}
2047
2048fn decode_png_to_rgba(
2049    data: &[u8],
2050    expected_w: usize,
2051    expected_h: usize,
2052) -> Result<Vec<u8>, String> {
2053    if data.len() < 8 || data[0..8] != [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A] {
2054        return Err("Invalid PNG signature".to_string());
2055    }
2056
2057    let mut cursor = 8;
2058    let mut width = 0usize;
2059    let mut height = 0usize;
2060    let mut color_type = 6u8;
2061    let mut idat_data = Vec::new();
2062
2063    while cursor + 12 <= data.len() {
2064        let chunk_len = u32::from_be_bytes(data[cursor..cursor + 4].try_into().unwrap()) as usize;
2065        let chunk_type = &data[cursor + 4..cursor + 8];
2066        let chunk_payload = &data[cursor + 8..cursor + 8 + chunk_len];
2067        cursor += 12 + chunk_len;
2068
2069        if chunk_type == b"IHDR" {
2070            if chunk_len < 13 {
2071                return Err("IHDR chunk too short".to_string());
2072            }
2073            width = u32::from_be_bytes(chunk_payload[0..4].try_into().unwrap()) as usize;
2074            height = u32::from_be_bytes(chunk_payload[4..8].try_into().unwrap()) as usize;
2075            color_type = chunk_payload[9];
2076        } else if chunk_type == b"IDAT" {
2077            idat_data.extend_from_slice(chunk_payload);
2078        } else if chunk_type == b"IEND" {
2079            break;
2080        }
2081    }
2082
2083    if width == 0 || height == 0 {
2084        width = expected_w;
2085        height = expected_h;
2086    }
2087
2088    let decompressed = miniz_oxide::inflate::decompress_to_vec_zlib(&idat_data)
2089        .map_err(|e| format!("PNG zlib inflation failed: {e:?}"))?;
2090
2091    let bpp: usize = match color_type {
2092        0 => 1,
2093        2 => 3,
2094        3 => 1,
2095        4 => 2,
2096        6 => 4,
2097        _ => 4,
2098    };
2099
2100    let stride = 1 + width * bpp;
2101    if decompressed.len() < height * stride {
2102        return Err("Decompressed PNG data truncated".to_string());
2103    }
2104
2105    let mut uncompressed_rows: Vec<u8> = vec![0u8; height * width * bpp];
2106    let mut prev_row: Vec<u8> = vec![0u8; width * bpp];
2107
2108    for y in 0..height {
2109        let filter_type = decompressed[y * stride];
2110        let raw_row = &decompressed[y * stride + 1..y * stride + stride];
2111        let row_out_start = y * width * bpp;
2112        let row_out = &mut uncompressed_rows[row_out_start..row_out_start + width * bpp];
2113
2114        match filter_type {
2115            0 => {
2116                row_out.copy_from_slice(raw_row);
2117            }
2118            1 => {
2119                for x in 0..raw_row.len() {
2120                    let a = if x >= bpp { row_out[x - bpp] } else { 0 };
2121                    row_out[x] = raw_row[x].wrapping_add(a);
2122                }
2123            }
2124            2 => {
2125                for x in 0..raw_row.len() {
2126                    let b = prev_row[x];
2127                    row_out[x] = raw_row[x].wrapping_add(b);
2128                }
2129            }
2130            3 => {
2131                for x in 0..raw_row.len() {
2132                    let a = if x >= bpp { row_out[x - bpp] as u16 } else { 0 };
2133                    let b = prev_row[x] as u16;
2134                    row_out[x] = raw_row[x].wrapping_add(((a + b) / 2) as u8);
2135                }
2136            }
2137            4 => {
2138                for x in 0..raw_row.len() {
2139                    let a = if x >= bpp { row_out[x - bpp] as i32 } else { 0 };
2140                    let b = prev_row[x] as i32;
2141                    let c = if x >= bpp {
2142                        prev_row[x - bpp] as i32
2143                    } else {
2144                        0
2145                    };
2146                    let p = a + b - c;
2147                    let pa = (p - a).abs();
2148                    let pb = (p - b).abs();
2149                    let pc = (p - c).abs();
2150                    let pr = if pa <= pb && pa <= pc {
2151                        a
2152                    } else if pb <= pc {
2153                        b
2154                    } else {
2155                        c
2156                    };
2157                    row_out[x] = raw_row[x].wrapping_add(pr as u8);
2158                }
2159            }
2160            _ => {
2161                row_out.copy_from_slice(raw_row);
2162            }
2163        }
2164
2165        prev_row.copy_from_slice(row_out);
2166    }
2167
2168    let mut rgba_out = Vec::with_capacity(width * height * 4);
2169    for y in 0..height {
2170        let row_start = y * width * bpp;
2171        for x in 0..width {
2172            let px_start = row_start + x * bpp;
2173            match color_type {
2174                6 => {
2175                    rgba_out.extend_from_slice(&uncompressed_rows[px_start..px_start + 4]);
2176                }
2177                2 => {
2178                    rgba_out.push(uncompressed_rows[px_start]);
2179                    rgba_out.push(uncompressed_rows[px_start + 1]);
2180                    rgba_out.push(uncompressed_rows[px_start + 2]);
2181                    rgba_out.push(255);
2182                }
2183                0 => {
2184                    let g = uncompressed_rows[px_start];
2185                    rgba_out.push(g);
2186                    rgba_out.push(g);
2187                    rgba_out.push(g);
2188                    rgba_out.push(255);
2189                }
2190                4 => {
2191                    let g = uncompressed_rows[px_start];
2192                    let a = uncompressed_rows[px_start + 1];
2193                    rgba_out.push(g);
2194                    rgba_out.push(g);
2195                    rgba_out.push(g);
2196                    rgba_out.push(a);
2197                }
2198                _ => {
2199                    rgba_out.extend_from_slice(&[255, 255, 255, 255]);
2200                }
2201            }
2202        }
2203    }
2204
2205    Ok(rgba_out)
2206}