Skip to main content

strata_render/
canvas2d.rs

1//! W3C-Compatible Immediate-Mode 2D Canvas Engine (`CanvasRenderingContext2D`).
2//!
3//! Provides immediate-mode vector drawing, affine 2D transformations, cubic & quadratic Bézier
4//! curves, dashed strokes, path clipping, text rendering, and analytical anti-aliased CPU/GPU
5//! rasterization.
6
7use crate::rasterizer::FrameBuffer;
8use strata_layout::Rect;
9pub use strata_primitives::geom::Transform2D;
10use strata_style::types::Color;
11
12/// Horizontal text alignment for [`Canvas2DContext::fill_text`] and [`Canvas2DContext::stroke_text`].
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum CanvasTextAlign {
15    #[default]
16    Left,
17    Center,
18    Right,
19    Start,
20    End,
21}
22
23/// Vertical text baseline for [`Canvas2DContext::fill_text`] and [`Canvas2DContext::stroke_text`].
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub enum CanvasTextBaseline {
26    #[default]
27    Alphabetic,
28    Top,
29    Middle,
30    Bottom,
31    Hanging,
32    Ideographic,
33}
34
35/// Canvas path primitive verbs in transformed coordinates.
36#[derive(Debug, Clone, PartialEq)]
37pub enum CanvasPathVerb {
38    MoveTo(f32, f32),
39    LineTo(f32, f32),
40    QuadraticCurveTo {
41        cpx: f32,
42        cpy: f32,
43        x: f32,
44        y: f32,
45    },
46    BezierCurveTo {
47        cp1x: f32,
48        cp1y: f32,
49        cp2x: f32,
50        cp2y: f32,
51        x: f32,
52        y: f32,
53    },
54    Arc {
55        cx: f32,
56        cy: f32,
57        radius: f32,
58        start_angle: f32,
59        end_angle: f32,
60        counter_clockwise: bool,
61    },
62    Close,
63}
64
65/// Renderable 2D canvas drawing instruction.
66#[derive(Debug, Clone, PartialEq)]
67pub enum CanvasCommand {
68    FillRect {
69        bounds: Rect,
70        color: Color,
71    },
72    StrokeRect {
73        bounds: Rect,
74        color: Color,
75        line_width: f32,
76    },
77    ClearRect {
78        bounds: Rect,
79    },
80    DrawLine {
81        p0: (f32, f32),
82        p1: (f32, f32),
83        color: Color,
84        line_width: f32,
85    },
86    DrawCircle {
87        center: (f32, f32),
88        radius: f32,
89        fill_color: Option<Color>,
90        stroke_color: Option<Color>,
91        line_width: f32,
92    },
93    DrawPath {
94        verbs: Vec<CanvasPathVerb>,
95        fill_color: Option<Color>,
96        stroke_color: Option<Color>,
97        line_width: f32,
98    },
99    /// Pushes the active backend graphics state (clip region and dash state).
100    Save,
101    /// Pops the most recently pushed backend graphics state.
102    Restore,
103    /// Sets the stroke dash pattern (empty clears dashing) and phase offset.
104    SetLineDash {
105        segments: Vec<f32>,
106        offset: f32,
107    },
108    /// Intersects the active clip region with the given path until the matching `Restore`.
109    ClipPath {
110        verbs: Vec<CanvasPathVerb>,
111    },
112    /// Renders filled text at `(x, y)` in transformed canvas coordinates.
113    FillText {
114        text: String,
115        x: f32,
116        y: f32,
117        color: Color,
118        font: String,
119        font_size: f32,
120        font_family: String,
121        font_weight: u16,
122        italic: bool,
123        text_align: CanvasTextAlign,
124        text_baseline: CanvasTextBaseline,
125        max_width: Option<f32>,
126    },
127    /// Renders outlined/stroked text at `(x, y)` in transformed canvas coordinates.
128    StrokeText {
129        text: String,
130        x: f32,
131        y: f32,
132        color: Color,
133        line_width: f32,
134        font: String,
135        font_size: f32,
136        font_family: String,
137        font_weight: u16,
138        italic: bool,
139        text_align: CanvasTextAlign,
140        text_baseline: CanvasTextBaseline,
141        max_width: Option<f32>,
142    },
143}
144
145/// Parses a CSS/HTML5 Canvas `font` shorthand string (e.g. `"bold 12px monospace"`,
146/// `"italic 600 11px/1.4 'JetBrains Mono', monospace"`, `"10pt sans-serif"`) into
147/// `(font_size_px, font_family, font_weight, italic)`.
148pub fn parse_canvas_font(font: &str) -> (f32, String, u16, bool) {
149    let mut font_size = 12.0_f32;
150    let mut font_weight = 400_u16;
151    let mut italic = false;
152    let mut family_start: Option<usize> = None;
153
154    let bytes = font.as_bytes();
155    let mut i = 0usize;
156    while i < bytes.len() {
157        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
158            i += 1;
159        }
160        if i >= bytes.len() {
161            break;
162        }
163        let start = i;
164        while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
165            i += 1;
166        }
167        let token = &font[start..i];
168        let lower = token.to_ascii_lowercase();
169
170        if lower == "italic" || lower == "oblique" {
171            italic = true;
172            continue;
173        }
174        if lower == "bold" || lower == "bolder" {
175            font_weight = 700;
176            continue;
177        }
178        if lower == "lighter" {
179            font_weight = 300;
180            continue;
181        }
182        if lower == "normal" || lower == "small-caps" {
183            continue;
184        }
185        if let Ok(w) = lower.parse::<u16>() {
186            if (100..=900).contains(&w) {
187                font_weight = w;
188                continue;
189            }
190        }
191
192        // Size token: `12px`, `12.5px/1.4`, `10pt`, `1rem`, `1em`
193        let size_part = lower.split('/').next().unwrap_or("");
194        let parsed_px = if let Some(num) = size_part.strip_suffix("px") {
195            num.parse::<f32>().ok()
196        } else if let Some(num) = size_part.strip_suffix("pt") {
197            num.parse::<f32>().ok().map(|pt| pt * (4.0 / 3.0))
198        } else if let Some(num) = size_part.strip_suffix("rem") {
199            num.parse::<f32>().ok().map(|r| r * 16.0)
200        } else if let Some(num) = size_part.strip_suffix("em") {
201            num.parse::<f32>().ok().map(|e| e * 16.0)
202        } else {
203            None
204        };
205
206        if let Some(px) = parsed_px {
207            if px.is_finite() && px > 0.0 {
208                font_size = px;
209                family_start = Some(i);
210                break;
211            }
212        }
213    }
214
215    let raw_family = family_start.map(|idx| font[idx..].trim()).unwrap_or("");
216    let cleaned_family = raw_family
217        .split(',')
218        .map(|s| s.trim().trim_matches('\'').trim_matches('"').trim())
219        .filter(|s| !s.is_empty())
220        .collect::<Vec<_>>()
221        .join(", ");
222
223    let font_family = if cleaned_family.is_empty() {
224        "sans-serif".to_string()
225    } else {
226        cleaned_family
227    };
228
229    (font_size, font_family, font_weight, italic)
230}
231
232#[derive(Debug, Clone, PartialEq)]
233struct CanvasState {
234    transform: Transform2D,
235    fill_style: Color,
236    stroke_style: Color,
237    line_width: f32,
238    global_alpha: f32,
239    line_dash: Vec<f32>,
240    line_dash_offset: f32,
241    font: String,
242    font_size: f32,
243    font_family: String,
244    font_weight: u16,
245    font_italic: bool,
246    text_align: CanvasTextAlign,
247    text_baseline: CanvasTextBaseline,
248}
249
250impl Default for CanvasState {
251    fn default() -> Self {
252        Self {
253            transform: Transform2D::IDENTITY,
254            fill_style: Color::BLACK,
255            stroke_style: Color::BLACK,
256            line_width: 1.0,
257            global_alpha: 1.0,
258            line_dash: Vec::new(),
259            line_dash_offset: 0.0,
260            font: "12px sans-serif".to_string(),
261            font_size: 12.0,
262            font_family: "sans-serif".to_string(),
263            font_weight: 400,
264            font_italic: false,
265            text_align: CanvasTextAlign::Left,
266            text_baseline: CanvasTextBaseline::Alphabetic,
267        }
268    }
269}
270
271/// W3C-Compatible 2D Immediate-Mode Canvas Rendering Context.
272#[derive(Debug, Clone)]
273pub struct Canvas2DContext {
274    pub width: f32,
275    pub height: f32,
276    current_state: CanvasState,
277    state_stack: Vec<CanvasState>,
278    current_path: Vec<CanvasPathVerb>,
279    commands: Vec<CanvasCommand>,
280}
281
282impl Canvas2DContext {
283    pub fn new(width: f32, height: f32) -> Self {
284        Self {
285            width,
286            height,
287            current_state: CanvasState::default(),
288            state_stack: Vec::new(),
289            current_path: Vec::new(),
290            commands: Vec::new(),
291        }
292    }
293
294    // --- State Stack ---
295
296    pub fn save(&mut self) {
297        self.state_stack.push(self.current_state.clone());
298        self.commands.push(CanvasCommand::Save);
299    }
300
301    pub fn restore(&mut self) {
302        if let Some(state) = self.state_stack.pop() {
303            self.current_state = state;
304            self.commands.push(CanvasCommand::Restore);
305        }
306    }
307
308    // --- Transformations ---
309
310    pub fn translate(&mut self, dx: f32, dy: f32) {
311        self.current_state.transform.translate(dx, dy);
312    }
313
314    pub fn scale(&mut self, sx: f32, sy: f32) {
315        self.current_state.transform.scale_mut(sx, sy);
316    }
317
318    pub fn rotate(&mut self, radians: f32) {
319        self.current_state.transform.rotate_mut(radians);
320    }
321
322    pub fn transform(&mut self, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) {
323        let other = Transform2D::from_w3c(a, b, c, d, e, f);
324        self.current_state.transform = self.current_state.transform.multiply(other);
325    }
326
327    pub fn set_transform(&mut self, transform: Transform2D) {
328        self.current_state.transform = transform;
329    }
330
331    pub fn get_transform(&self) -> Transform2D {
332        self.current_state.transform
333    }
334
335    pub fn reset_transform(&mut self) {
336        self.current_state.transform = Transform2D::IDENTITY;
337    }
338
339    // --- Styles ---
340
341    pub fn set_fill_style(&mut self, color: Color) {
342        self.current_state.fill_style = color;
343    }
344
345    pub fn set_stroke_style(&mut self, color: Color) {
346        self.current_state.stroke_style = color;
347    }
348
349    pub fn set_line_width(&mut self, width: f32) {
350        self.current_state.line_width = width.max(0.1);
351    }
352
353    pub fn set_global_alpha(&mut self, alpha: f32) {
354        self.current_state.global_alpha = alpha.clamp(0.0, 1.0);
355    }
356
357    /// Sets the stroke dash pattern (HTML5 `ctx.setLineDash(segments)`).
358    ///
359    /// Negative or non-finite values cause the call to be ignored per the HTML5 Canvas 2D spec;
360    /// an odd-length pattern is automatically concatenated with itself so dash/gap pairs repeat
361    /// cleanly; an empty slice restores solid strokes.
362    pub fn set_line_dash(&mut self, segments: &[f32]) {
363        if segments.iter().any(|&v| !v.is_finite() || v < 0.0) {
364            return;
365        }
366        let mut normalized = Vec::with_capacity(if segments.len() % 2 == 1 {
367            segments.len() * 2
368        } else {
369            segments.len()
370        });
371        normalized.extend_from_slice(segments);
372        if segments.len() % 2 == 1 {
373            normalized.extend_from_slice(segments);
374        }
375        self.current_state.line_dash = normalized.clone();
376        self.commands.push(CanvasCommand::SetLineDash {
377            segments: normalized,
378            offset: self.current_state.line_dash_offset,
379        });
380    }
381
382    /// Returns the currently active stroke dash pattern.
383    pub fn get_line_dash(&self) -> &[f32] {
384        &self.current_state.line_dash
385    }
386
387    /// Sets the stroke dash phase offset (`ctx.lineDashOffset`).
388    pub fn set_line_dash_offset(&mut self, offset: f32) {
389        if !offset.is_finite() {
390            return;
391        }
392        self.current_state.line_dash_offset = offset;
393        self.commands.push(CanvasCommand::SetLineDash {
394            segments: self.current_state.line_dash.clone(),
395            offset,
396        });
397    }
398
399    /// Returns the current stroke dash phase offset.
400    pub fn line_dash_offset(&self) -> f32 {
401        self.current_state.line_dash_offset
402    }
403
404    /// Sets the active CSS font shorthand (e.g. `"bold 12px monospace"`).
405    pub fn set_font(&mut self, font: impl Into<String>) {
406        let raw = font.into();
407        let (size, family, weight, italic) = parse_canvas_font(&raw);
408        self.current_state.font = raw;
409        self.current_state.font_size = size;
410        self.current_state.font_family = family;
411        self.current_state.font_weight = weight;
412        self.current_state.font_italic = italic;
413    }
414
415    /// Returns the active CSS font string.
416    pub fn font(&self) -> &str {
417        &self.current_state.font
418    }
419
420    /// Sets horizontal text alignment (`Left`, `Center`, `Right`, `Start`, `End`).
421    pub fn set_text_align(&mut self, align: CanvasTextAlign) {
422        self.current_state.text_align = align;
423    }
424
425    /// Sets vertical text baseline (`Alphabetic`, `Top`, `Middle`, `Bottom`, `Hanging`, `Ideographic`).
426    pub fn set_text_baseline(&mut self, baseline: CanvasTextBaseline) {
427        self.current_state.text_baseline = baseline;
428    }
429
430    fn apply_alpha(&self, color: Color) -> Color {
431        if (self.current_state.global_alpha - 1.0).abs() < 1e-4 {
432            color
433        } else {
434            let (r, g, b, a) = color.to_f32();
435            Color::from_f32(r, g, b, a * self.current_state.global_alpha)
436        }
437    }
438
439    fn transform_scale(&self) -> f32 {
440        (self.current_state.transform.a.powi(2) + self.current_state.transform.b.powi(2)).sqrt()
441    }
442
443    // --- Path Construction ---
444
445    pub fn begin_path(&mut self) {
446        self.current_path.clear();
447    }
448
449    pub fn move_to(&mut self, x: f32, y: f32) {
450        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
451        self.current_path.push(CanvasPathVerb::MoveTo(tx, ty));
452    }
453
454    pub fn line_to(&mut self, x: f32, y: f32) {
455        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
456        self.current_path.push(CanvasPathVerb::LineTo(tx, ty));
457    }
458
459    /// Appends a quadratic Bézier curve from the current point to `(x, y)` using control point `(cpx, cpy)`.
460    pub fn quadratic_curve_to(&mut self, cpx: f32, cpy: f32, x: f32, y: f32) {
461        let (tcpx, tcpy) = self.current_state.transform.transform_xy(cpx, cpy);
462        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
463        self.current_path.push(CanvasPathVerb::QuadraticCurveTo {
464            cpx: tcpx,
465            cpy: tcpy,
466            x: tx,
467            y: ty,
468        });
469    }
470
471    /// Appends a cubic Bézier curve from the current point to `(x, y)` using control points
472    /// `(cp1x, cp1y)` and `(cp2x, cp2y)`.
473    pub fn bezier_curve_to(
474        &mut self,
475        cp1x: f32,
476        cp1y: f32,
477        cp2x: f32,
478        cp2y: f32,
479        x: f32,
480        y: f32,
481    ) {
482        let (tcp1x, tcp1y) = self.current_state.transform.transform_xy(cp1x, cp1y);
483        let (tcp2x, tcp2y) = self.current_state.transform.transform_xy(cp2x, cp2y);
484        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
485        self.current_path.push(CanvasPathVerb::BezierCurveTo {
486            cp1x: tcp1x,
487            cp1y: tcp1y,
488            cp2x: tcp2x,
489            cp2y: tcp2y,
490            x: tx,
491            y: ty,
492        });
493    }
494
495    pub fn arc(
496        &mut self,
497        cx: f32,
498        cy: f32,
499        radius: f32,
500        start_angle: f32,
501        end_angle: f32,
502        ccw: bool,
503    ) {
504        let (tcx, tcy) = self.current_state.transform.transform_xy(cx, cy);
505        let scale_x = self.transform_scale();
506        self.current_path.push(CanvasPathVerb::Arc {
507            cx: tcx,
508            cy: tcy,
509            radius: radius * scale_x,
510            start_angle,
511            end_angle,
512            counter_clockwise: ccw,
513        });
514    }
515
516    pub fn rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
517        self.move_to(x, y);
518        self.line_to(x + w, y);
519        self.line_to(x + w, y + h);
520        self.line_to(x, y + h);
521        self.close_path();
522    }
523
524    pub fn close_path(&mut self) {
525        self.current_path.push(CanvasPathVerb::Close);
526    }
527
528    /// Intersects the current clipping region with the current path.
529    ///
530    /// Wrap with [`Self::save`] and [`Self::restore`] to scope the clip region.
531    pub fn clip(&mut self) {
532        if self.current_path.is_empty() {
533            return;
534        }
535        self.commands.push(CanvasCommand::ClipPath {
536            verbs: self.current_path.clone(),
537        });
538    }
539
540    // --- Drawing Operations ---
541
542    pub fn fill_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
543        let (x0, y0) = self.current_state.transform.transform_xy(x, y);
544        let (x1, y1) = self.current_state.transform.transform_xy(x + w, y + h);
545        let min_x = x0.min(x1);
546        let max_x = x0.max(x1);
547        let min_y = y0.min(y1);
548        let max_y = y0.max(y1);
549
550        let color = self.apply_alpha(self.current_state.fill_style);
551        self.commands.push(CanvasCommand::FillRect {
552            bounds: Rect::new(min_x, min_y, max_x - min_x, max_y - min_y),
553            color,
554        });
555    }
556
557    pub fn stroke_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
558        let (x0, y0) = self.current_state.transform.transform_xy(x, y);
559        let (x1, y1) = self.current_state.transform.transform_xy(x + w, y + h);
560        let min_x = x0.min(x1);
561        let max_x = x0.max(x1);
562        let min_y = y0.min(y1);
563        let max_y = y0.max(y1);
564
565        let color = self.apply_alpha(self.current_state.stroke_style);
566        self.commands.push(CanvasCommand::StrokeRect {
567            bounds: Rect::new(min_x, min_y, max_x - min_x, max_y - min_y),
568            color,
569            line_width: self.current_state.line_width,
570        });
571    }
572
573    pub fn clear_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
574        let (x0, y0) = self.current_state.transform.transform_xy(x, y);
575        let (x1, y1) = self.current_state.transform.transform_xy(x + w, y + h);
576        let min_x = x0.min(x1);
577        let max_x = x0.max(x1);
578        let min_y = y0.min(y1);
579        let max_y = y0.max(y1);
580
581        self.commands.push(CanvasCommand::ClearRect {
582            bounds: Rect::new(min_x, min_y, max_x - min_x, max_y - min_y),
583        });
584    }
585
586    pub fn stroke(&mut self) {
587        if self.current_path.is_empty() {
588            return;
589        }
590        let color = self.apply_alpha(self.current_state.stroke_style);
591        self.commands.push(CanvasCommand::DrawPath {
592            verbs: self.current_path.clone(),
593            fill_color: None,
594            stroke_color: Some(color),
595            line_width: self.current_state.line_width,
596        });
597    }
598
599    pub fn fill(&mut self) {
600        if self.current_path.is_empty() {
601            return;
602        }
603        let color = self.apply_alpha(self.current_state.fill_style);
604        self.commands.push(CanvasCommand::DrawPath {
605            verbs: self.current_path.clone(),
606            fill_color: Some(color),
607            stroke_color: None,
608            line_width: self.current_state.line_width,
609        });
610    }
611
612    /// Renders filled text at `(x, y)` using the active `font`, `fill_style`, `text_align`, and `text_baseline`.
613    pub fn fill_text(&mut self, text: impl Into<String>, x: f32, y: f32) {
614        self.push_fill_text(text.into(), x, y, None);
615    }
616
617    /// Renders filled text at `(x, y)`, horizontally constrained to `max_width` pixels.
618    pub fn fill_text_with_max_width(
619        &mut self,
620        text: impl Into<String>,
621        x: f32,
622        y: f32,
623        max_width: f32,
624    ) {
625        self.push_fill_text(text.into(), x, y, Some(max_width.max(1.0)));
626    }
627
628    fn push_fill_text(&mut self, text: String, x: f32, y: f32, max_width: Option<f32>) {
629        if text.is_empty() {
630            return;
631        }
632        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
633        let scale = self.transform_scale().max(1e-3);
634        let color = self.apply_alpha(self.current_state.fill_style);
635        self.commands.push(CanvasCommand::FillText {
636            text,
637            x: tx,
638            y: ty,
639            color,
640            font: self.current_state.font.clone(),
641            font_size: self.current_state.font_size * scale,
642            font_family: self.current_state.font_family.clone(),
643            font_weight: self.current_state.font_weight,
644            italic: self.current_state.font_italic,
645            text_align: self.current_state.text_align,
646            text_baseline: self.current_state.text_baseline,
647            max_width: max_width.map(|mw| mw * scale),
648        });
649    }
650
651    /// Renders stroked/outlined text at `(x, y)` using the active `font`, `stroke_style`, and `line_width`.
652    pub fn stroke_text(&mut self, text: impl Into<String>, x: f32, y: f32) {
653        self.push_stroke_text(text.into(), x, y, None);
654    }
655
656    /// Renders stroked/outlined text at `(x, y)`, horizontally constrained to `max_width` pixels.
657    pub fn stroke_text_with_max_width(
658        &mut self,
659        text: impl Into<String>,
660        x: f32,
661        y: f32,
662        max_width: f32,
663    ) {
664        self.push_stroke_text(text.into(), x, y, Some(max_width.max(1.0)));
665    }
666
667    fn push_stroke_text(&mut self, text: String, x: f32, y: f32, max_width: Option<f32>) {
668        if text.is_empty() {
669            return;
670        }
671        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
672        let scale = self.transform_scale().max(1e-3);
673        let color = self.apply_alpha(self.current_state.stroke_style);
674        self.commands.push(CanvasCommand::StrokeText {
675            text,
676            x: tx,
677            y: ty,
678            color,
679            line_width: self.current_state.line_width,
680            font: self.current_state.font.clone(),
681            font_size: self.current_state.font_size * scale,
682            font_family: self.current_state.font_family.clone(),
683            font_weight: self.current_state.font_weight,
684            italic: self.current_state.font_italic,
685            text_align: self.current_state.text_align,
686            text_baseline: self.current_state.text_baseline,
687            max_width: max_width.map(|mw| mw * scale),
688        });
689    }
690
691    /// Emits all recorded canvas commands.
692    pub fn finish(self) -> Vec<CanvasCommand> {
693        self.commands
694    }
695
696    pub fn commands(&self) -> &[CanvasCommand] {
697        &self.commands
698    }
699
700    /// Software analytical anti-aliased rasterization directly onto a FrameBuffer.
701    pub fn rasterize(
702        &self,
703        fb: &mut FrameBuffer,
704        origin_x: f32,
705        origin_y: f32,
706        clip: Option<Rect>,
707    ) {
708        rasterize_canvas_commands(fb, &self.commands, origin_x, origin_y, clip);
709    }
710}
711
712/// Flattens a slice of [`CanvasPathVerb`]s (including cubic/quadratic Bézier curves and arcs)
713/// into translated polyline subpaths `Vec<Vec<(f32, f32)>>`.
714pub fn flatten_canvas_verbs(
715    verbs: &[CanvasPathVerb],
716    origin_x: f32,
717    origin_y: f32,
718) -> Vec<Vec<(f32, f32)>> {
719    let mut subpaths: Vec<Vec<(f32, f32)>> = Vec::new();
720    let mut cur_sub: Vec<(f32, f32)> = Vec::new();
721    let mut current = (origin_x, origin_y);
722    let mut start = (origin_x, origin_y);
723
724    for verb in verbs {
725        match *verb {
726            CanvasPathVerb::MoveTo(x, y) => {
727                if cur_sub.len() >= 2 {
728                    subpaths.push(std::mem::take(&mut cur_sub));
729                } else {
730                    cur_sub.clear();
731                }
732                current = (x + origin_x, y + origin_y);
733                start = current;
734                cur_sub.push(current);
735            }
736            CanvasPathVerb::LineTo(x, y) => {
737                let next = (x + origin_x, y + origin_y);
738                if cur_sub.is_empty() {
739                    cur_sub.push(current);
740                }
741                cur_sub.push(next);
742                current = next;
743            }
744            CanvasPathVerb::QuadraticCurveTo { cpx, cpy, x, y } => {
745                let p0 = current;
746                let p1 = (cpx + origin_x, cpy + origin_y);
747                let p2 = (x + origin_x, y + origin_y);
748                if cur_sub.is_empty() {
749                    cur_sub.push(p0);
750                }
751                let approx_len = ((p1.0 - p0.0).hypot(p1.1 - p0.1)
752                    + (p2.0 - p1.0).hypot(p2.1 - p1.1))
753                .max(1.0);
754                let steps = ((approx_len / 4.0).ceil() as usize).clamp(12, 64);
755                for i in 1..=steps {
756                    let t = i as f32 / steps as f32;
757                    let mt = 1.0 - t;
758                    let px = mt * mt * p0.0 + 2.0 * mt * t * p1.0 + t * t * p2.0;
759                    let py = mt * mt * p0.1 + 2.0 * mt * t * p1.1 + t * t * p2.1;
760                    cur_sub.push((px, py));
761                }
762                current = p2;
763            }
764            CanvasPathVerb::BezierCurveTo {
765                cp1x,
766                cp1y,
767                cp2x,
768                cp2y,
769                x,
770                y,
771            } => {
772                let p0 = current;
773                let p1 = (cp1x + origin_x, cp1y + origin_y);
774                let p2 = (cp2x + origin_x, cp2y + origin_y);
775                let p3 = (x + origin_x, y + origin_y);
776                if cur_sub.is_empty() {
777                    cur_sub.push(p0);
778                }
779                let approx_len = ((p1.0 - p0.0).hypot(p1.1 - p0.1)
780                    + (p2.0 - p1.0).hypot(p2.1 - p1.1)
781                    + (p3.0 - p2.0).hypot(p3.1 - p2.1))
782                .max(1.0);
783                let steps = ((approx_len / 4.0).ceil() as usize).clamp(16, 80);
784                for i in 1..=steps {
785                    let t = i as f32 / steps as f32;
786                    let mt = 1.0 - t;
787                    let mt2 = mt * mt;
788                    let t2 = t * t;
789                    let px = mt2 * mt * p0.0
790                        + 3.0 * mt2 * t * p1.0
791                        + 3.0 * mt * t2 * p2.0
792                        + t2 * t * p3.0;
793                    let py = mt2 * mt * p0.1
794                        + 3.0 * mt2 * t * p1.1
795                        + 3.0 * mt * t2 * p2.1
796                        + t2 * t * p3.1;
797                    cur_sub.push((px, py));
798                }
799                current = p3;
800            }
801            CanvasPathVerb::Arc {
802                cx,
803                cy,
804                radius,
805                start_angle,
806                end_angle,
807                counter_clockwise,
808            } => {
809                let acx = cx + origin_x;
810                let acy = cy + origin_y;
811                let mut sweep = end_angle - start_angle;
812                if counter_clockwise {
813                    if sweep >= 0.0 {
814                        sweep -= std::f32::consts::TAU;
815                    }
816                } else if sweep <= 0.0 && (end_angle - start_angle).abs() > 1e-5 {
817                    sweep += std::f32::consts::TAU;
818                }
819                let steps = ((radius.abs() * sweep.abs() / 3.0).ceil() as usize).clamp(16, 96);
820                for i in 0..=steps {
821                    let a = start_angle + sweep * (i as f32 / steps as f32);
822                    let pt = (acx + radius * a.cos(), acy + radius * a.sin());
823                    if i == 0 && cur_sub.is_empty() {
824                        start = pt;
825                    }
826                    cur_sub.push(pt);
827                    current = pt;
828                }
829            }
830            CanvasPathVerb::Close => {
831                if !cur_sub.is_empty() && current != start {
832                    cur_sub.push(start);
833                    current = start;
834                }
835                if cur_sub.len() >= 2 {
836                    subpaths.push(std::mem::take(&mut cur_sub));
837                } else {
838                    cur_sub.clear();
839                }
840            }
841        }
842    }
843
844    if cur_sub.len() >= 2 {
845        subpaths.push(cur_sub);
846    }
847    subpaths
848}
849
850/// Computes the axis-aligned bounding box of `verbs` shifted by `(origin_x, origin_y)`.
851pub fn canvas_verbs_bounds(verbs: &[CanvasPathVerb], origin_x: f32, origin_y: f32) -> Option<Rect> {
852    let subpaths = flatten_canvas_verbs(verbs, origin_x, origin_y);
853    let mut min_x = f32::INFINITY;
854    let mut min_y = f32::INFINITY;
855    let mut max_x = f32::NEG_INFINITY;
856    let mut max_y = f32::NEG_INFINITY;
857    for sub in &subpaths {
858        for &(x, y) in sub {
859            min_x = min_x.min(x);
860            min_y = min_y.min(y);
861            max_x = max_x.max(x);
862            max_y = max_y.max(y);
863        }
864    }
865    if min_x.is_finite() && min_y.is_finite() && max_x >= min_x && max_y >= min_y {
866        Some(Rect::new(min_x, min_y, max_x - min_x, max_y - min_y))
867    } else {
868        None
869    }
870}
871
872#[derive(Clone)]
873struct RasterState {
874    clip: Option<Rect>,
875    clip_polys: Vec<Vec<Vec<(f32, f32)>>>,
876    line_dash: Vec<f32>,
877    dash_offset: f32,
878}
879
880fn point_in_subpaths_even_odd(subpaths: &[Vec<(f32, f32)>], px: f32, py: f32) -> bool {
881    let mut inside = false;
882    for sub in subpaths {
883        if sub.len() < 3 {
884            continue;
885        }
886        let mut j = sub.len() - 1;
887        for i in 0..sub.len() {
888            let (xi, yi) = sub[i];
889            let (xj, yj) = sub[j];
890            let intersects =
891                ((yi > py) != (yj > py)) && (px < (xj - xi) * (py - yi) / (yj - yi) + xi);
892            if intersects {
893                inside = !inside;
894            }
895            j = i;
896        }
897    }
898    inside
899}
900
901fn point_passes_clip(state: &RasterState, x: f32, y: f32) -> bool {
902    if let Some(c) = state.clip {
903        if x < c.x || x >= c.max_x() || y < c.y || y >= c.max_y() {
904            return false;
905        }
906    }
907    for poly in &state.clip_polys {
908        if !point_in_subpaths_even_odd(poly, x, y) {
909            return false;
910        }
911    }
912    true
913}
914
915fn rasterize_fill_subpaths(
916    fb: &mut FrameBuffer,
917    subpaths: &[Vec<(f32, f32)>],
918    color: Color,
919    state: &RasterState,
920) {
921    let mut min_x = f32::INFINITY;
922    let mut min_y = f32::INFINITY;
923    let mut max_x = f32::NEG_INFINITY;
924    let mut max_y = f32::NEG_INFINITY;
925    for sub in subpaths {
926        for &(x, y) in sub {
927            min_x = min_x.min(x);
928            min_y = min_y.min(y);
929            max_x = max_x.max(x);
930            max_y = max_y.max(y);
931        }
932    }
933    if !min_x.is_finite() || max_x <= min_x || max_y <= min_y {
934        return;
935    }
936
937    let x0 = (min_x.floor() as isize).max(0) as usize;
938    let x1 = (max_x.ceil() as usize).min(fb.width);
939    let y0 = (min_y.floor() as isize).max(0) as usize;
940    let y1 = (max_y.ceil() as usize).min(fb.height);
941
942    for y in y0..y1 {
943        let py = y as f32 + 0.5;
944        for x in x0..x1 {
945            let px = x as f32 + 0.5;
946            if !point_passes_clip(state, px, py) {
947                continue;
948            }
949            if point_in_subpaths_even_odd(subpaths, px, py) {
950                fb.set_pixel(x, y, color);
951            }
952        }
953    }
954}
955
956fn rasterize_polyline(
957    fb: &mut FrameBuffer,
958    pts: &[(f32, f32)],
959    color: Color,
960    line_width: f32,
961    state: &RasterState,
962) {
963    if pts.len() < 2 {
964        return;
965    }
966
967    let period: f32 = state.line_dash.iter().copied().sum();
968    if state.line_dash.is_empty() || period <= 1e-4 {
969        for seg in pts.windows(2) {
970            rasterize_line(
971                fb,
972                seg[0].0,
973                seg[0].1,
974                seg[1].0,
975                seg[1].1,
976                color,
977                line_width,
978                state,
979            );
980        }
981        return;
982    }
983
984    let mut phase = state.dash_offset.rem_euclid(period);
985    let mut dash_idx = 0usize;
986    while dash_idx < state.line_dash.len() && phase >= state.line_dash[dash_idx] {
987        phase -= state.line_dash[dash_idx];
988        dash_idx = (dash_idx + 1) % state.line_dash.len();
989    }
990    let mut rem = (state.line_dash[dash_idx] - phase).max(0.0);
991
992    for seg in pts.windows(2) {
993        let (x0, y0) = seg[0];
994        let (x1, y1) = seg[1];
995        let dx = x1 - x0;
996        let dy = y1 - y0;
997        let seg_len = dx.hypot(dy);
998        if seg_len <= 1e-4 {
999            continue;
1000        }
1001        let mut cursor = 0.0_f32;
1002        while cursor < seg_len {
1003            if rem <= 1e-4 {
1004                dash_idx = (dash_idx + 1) % state.line_dash.len();
1005                rem = state.line_dash[dash_idx];
1006                if rem <= 1e-4 {
1007                    break;
1008                }
1009            }
1010            let step = rem.min(seg_len - cursor);
1011            let t0 = cursor / seg_len;
1012            let t1 = (cursor + step) / seg_len;
1013            if dash_idx.is_multiple_of(2) {
1014                rasterize_line(
1015                    fb,
1016                    x0 + dx * t0,
1017                    y0 + dy * t0,
1018                    x0 + dx * t1,
1019                    y0 + dy * t1,
1020                    color,
1021                    line_width,
1022                    state,
1023                );
1024            }
1025            cursor += step;
1026            rem -= step;
1027        }
1028    }
1029}
1030
1031/// Software analytical anti-aliased rasterization of canvas commands directly onto a FrameBuffer.
1032pub fn rasterize_canvas_commands(
1033    fb: &mut FrameBuffer,
1034    commands: &[CanvasCommand],
1035    origin_x: f32,
1036    origin_y: f32,
1037    clip: Option<Rect>,
1038) {
1039    let mut state = RasterState {
1040        clip,
1041        clip_polys: Vec::new(),
1042        line_dash: Vec::new(),
1043        dash_offset: 0.0,
1044    };
1045    let mut stack: Vec<RasterState> = Vec::new();
1046
1047    for cmd in commands {
1048        match cmd {
1049            CanvasCommand::Save => {
1050                stack.push(state.clone());
1051            }
1052            CanvasCommand::Restore => {
1053                if let Some(prev) = stack.pop() {
1054                    state = prev;
1055                }
1056            }
1057            CanvasCommand::SetLineDash { segments, offset } => {
1058                state.line_dash = segments.clone();
1059                state.dash_offset = *offset;
1060            }
1061            CanvasCommand::ClipPath { verbs } => {
1062                let subpaths = flatten_canvas_verbs(verbs, origin_x, origin_y);
1063                if let Some(bbox) = canvas_verbs_bounds(verbs, origin_x, origin_y) {
1064                    state.clip = match state.clip {
1065                        Some(existing) => existing.intersect(bbox).or(Some(Rect::zero())),
1066                        None => Some(bbox),
1067                    };
1068                }
1069                if !subpaths.is_empty() {
1070                    state.clip_polys.push(subpaths);
1071                }
1072            }
1073            CanvasCommand::FillRect { bounds, color } => {
1074                let translated = Rect::new(
1075                    bounds.x + origin_x,
1076                    bounds.y + origin_y,
1077                    bounds.width,
1078                    bounds.height,
1079                );
1080                if state.clip_polys.is_empty() {
1081                    fb.draw_rect(translated, *color, state.clip);
1082                } else {
1083                    let poly = vec![vec![
1084                        (translated.x, translated.y),
1085                        (translated.max_x(), translated.y),
1086                        (translated.max_x(), translated.max_y()),
1087                        (translated.x, translated.max_y()),
1088                        (translated.x, translated.y),
1089                    ]];
1090                    rasterize_fill_subpaths(fb, &poly, *color, &state);
1091                }
1092            }
1093            CanvasCommand::ClearRect { bounds } => {
1094                let translated = Rect::new(
1095                    bounds.x + origin_x,
1096                    bounds.y + origin_y,
1097                    bounds.width,
1098                    bounds.height,
1099                );
1100                fb.clear_rect(translated, Color::TRANSPARENT);
1101            }
1102            CanvasCommand::StrokeRect {
1103                bounds,
1104                color,
1105                line_width,
1106            } => {
1107                let translated = Rect::new(
1108                    bounds.x + origin_x,
1109                    bounds.y + origin_y,
1110                    bounds.width,
1111                    bounds.height,
1112                );
1113                if state.line_dash.is_empty() && state.clip_polys.is_empty() {
1114                    let lw = *line_width;
1115                    fb.draw_rect(
1116                        Rect::new(translated.x, translated.y, translated.width, lw),
1117                        *color,
1118                        state.clip,
1119                    );
1120                    fb.draw_rect(
1121                        Rect::new(translated.x, translated.max_y() - lw, translated.width, lw),
1122                        *color,
1123                        state.clip,
1124                    );
1125                    fb.draw_rect(
1126                        Rect::new(translated.x, translated.y, lw, translated.height),
1127                        *color,
1128                        state.clip,
1129                    );
1130                    fb.draw_rect(
1131                        Rect::new(translated.max_x() - lw, translated.y, lw, translated.height),
1132                        *color,
1133                        state.clip,
1134                    );
1135                } else {
1136                    let pts = [
1137                        (translated.x, translated.y),
1138                        (translated.max_x(), translated.y),
1139                        (translated.max_x(), translated.max_y()),
1140                        (translated.x, translated.max_y()),
1141                        (translated.x, translated.y),
1142                    ];
1143                    rasterize_polyline(fb, &pts, *color, *line_width, &state);
1144                }
1145            }
1146            CanvasCommand::DrawLine {
1147                p0,
1148                p1,
1149                color,
1150                line_width,
1151            } => {
1152                let pts = [(p0.0 + origin_x, p0.1 + origin_y), (p1.0 + origin_x, p1.1 + origin_y)];
1153                rasterize_polyline(fb, &pts, *color, *line_width, &state);
1154            }
1155            CanvasCommand::DrawCircle {
1156                center,
1157                radius,
1158                fill_color,
1159                stroke_color,
1160                line_width,
1161            } => {
1162                let cx = center.0 + origin_x;
1163                let cy = center.1 + origin_y;
1164                let r = *radius;
1165                let lw = *line_width;
1166
1167                if let Some(fc) = fill_color {
1168                    let min_x = ((cx - r - lw).floor() as isize).max(0) as usize;
1169                    let max_x = ((cx + r + lw).ceil() as usize).min(fb.width);
1170                    let min_y = ((cy - r - lw).floor() as isize).max(0) as usize;
1171                    let max_y = ((cy + r + lw).ceil() as usize).min(fb.height);
1172
1173                    for y in min_y..max_y {
1174                        let py = y as f32 + 0.5;
1175                        let dy = py - cy;
1176                        for x in min_x..max_x {
1177                            let px = x as f32 + 0.5;
1178                            if !point_passes_clip(&state, px, py) {
1179                                continue;
1180                            }
1181                            let dx = px - cx;
1182                            let dist = (dx * dx + dy * dy).sqrt();
1183                            let coverage = (0.5 + r - dist).clamp(0.0, 1.0);
1184                            if coverage > 0.005 {
1185                                fb.set_pixel(
1186                                    x,
1187                                    y,
1188                                    Color::rgba(
1189                                        fc.r,
1190                                        fc.g,
1191                                        fc.b,
1192                                        (fc.a() * coverage * 255.0) as u8,
1193                                    ),
1194                                );
1195                            }
1196                        }
1197                    }
1198                }
1199
1200                if let Some(sc) = stroke_color {
1201                    if !state.line_dash.is_empty() {
1202                        let steps = ((r * std::f32::consts::TAU / 3.0).ceil() as usize).clamp(24, 128);
1203                        let pts: Vec<(f32, f32)> = (0..=steps)
1204                            .map(|i| {
1205                                let a = (i as f32 / steps as f32) * std::f32::consts::TAU;
1206                                (cx + r * a.cos(), cy + r * a.sin())
1207                            })
1208                            .collect();
1209                        rasterize_polyline(fb, &pts, *sc, lw, &state);
1210                    } else {
1211                        let min_x = ((cx - r - lw).floor() as isize).max(0) as usize;
1212                        let max_x = ((cx + r + lw).ceil() as usize).min(fb.width);
1213                        let min_y = ((cy - r - lw).floor() as isize).max(0) as usize;
1214                        let max_y = ((cy + r + lw).ceil() as usize).min(fb.height);
1215                        for y in min_y..max_y {
1216                            let py = y as f32 + 0.5;
1217                            let dy = py - cy;
1218                            for x in min_x..max_x {
1219                                let px = x as f32 + 0.5;
1220                                if !point_passes_clip(&state, px, py) {
1221                                    continue;
1222                                }
1223                                let dx = px - cx;
1224                                let dist = (dx * dx + dy * dy).sqrt();
1225                                let stroke_dist = (dist - r).abs();
1226                                let coverage = (0.5 + lw * 0.5 - stroke_dist).clamp(0.0, 1.0);
1227                                if coverage > 0.005 {
1228                                    fb.set_pixel(
1229                                        x,
1230                                        y,
1231                                        Color::rgba(
1232                                            sc.r,
1233                                            sc.g,
1234                                            sc.b,
1235                                            (sc.a() * coverage * 255.0) as u8,
1236                                        ),
1237                                    );
1238                                }
1239                            }
1240                        }
1241                    }
1242                }
1243            }
1244            CanvasCommand::DrawPath {
1245                verbs,
1246                fill_color,
1247                stroke_color,
1248                line_width,
1249            } => {
1250                let subpaths = flatten_canvas_verbs(verbs, origin_x, origin_y);
1251                if let Some(fc) = fill_color {
1252                    rasterize_fill_subpaths(fb, &subpaths, *fc, &state);
1253                }
1254                if let Some(sc) = stroke_color {
1255                    for sub in &subpaths {
1256                        rasterize_polyline(fb, sub, *sc, *line_width, &state);
1257                    }
1258                }
1259            }
1260            CanvasCommand::FillText {
1261                text,
1262                x,
1263                y,
1264                color,
1265                font_size,
1266                text_align,
1267                text_baseline,
1268                ..
1269            }
1270            | CanvasCommand::StrokeText {
1271                text,
1272                x,
1273                y,
1274                color,
1275                font_size,
1276                text_align,
1277                text_baseline,
1278                ..
1279            } => {
1280                let est_w = text.chars().count() as f32 * (*font_size) * 0.6;
1281                let est_h = *font_size;
1282                let tx = origin_x
1283                    + match text_align {
1284                        CanvasTextAlign::Left | CanvasTextAlign::Start => *x,
1285                        CanvasTextAlign::Center => *x - est_w * 0.5,
1286                        CanvasTextAlign::Right | CanvasTextAlign::End => *x - est_w,
1287                    };
1288                let ty = origin_y
1289                    + match text_baseline {
1290                        CanvasTextBaseline::Top | CanvasTextBaseline::Hanging => *y,
1291                        CanvasTextBaseline::Middle => *y - est_h * 0.5,
1292                        CanvasTextBaseline::Bottom | CanvasTextBaseline::Ideographic => *y - est_h,
1293                        CanvasTextBaseline::Alphabetic => *y - est_h * 0.8,
1294                    };
1295                fb.draw_text((tx, ty), text, *font_size, *color, state.clip);
1296            }
1297        }
1298    }
1299}
1300
1301/// Analytical Signed Distance Field 2D Line Segment Rasterizer with subpixel anti-aliasing.
1302#[allow(clippy::too_many_arguments)]
1303fn rasterize_line(
1304    fb: &mut FrameBuffer,
1305    x0: f32,
1306    y0: f32,
1307    x1: f32,
1308    y1: f32,
1309    color: Color,
1310    line_width: f32,
1311    state: &RasterState,
1312) {
1313    let min_x = (x0.min(x1) - line_width - 1.0).max(0.0).floor() as usize;
1314    let max_x = ((x0.max(x1) + line_width + 1.0).ceil() as usize).min(fb.width);
1315    let min_y = (y0.min(y1) - line_width - 1.0).max(0.0).floor() as usize;
1316    let max_y = ((y0.max(y1) + line_width + 1.0).ceil() as usize).min(fb.height);
1317
1318    let vx = x1 - x0;
1319    let vy = y1 - y0;
1320    let v_len_sq = vx * vx + vy * vy;
1321    let half_lw = line_width * 0.5;
1322
1323    for y in min_y..max_y {
1324        let py = y as f32 + 0.5;
1325        if let Some(c) = state.clip {
1326            if py < c.y || py >= c.max_y() {
1327                continue;
1328            }
1329        }
1330
1331        for x in min_x..max_x {
1332            let px = x as f32 + 0.5;
1333            if !point_passes_clip(state, px, py) {
1334                continue;
1335            }
1336
1337            // Project point onto line segment: t = clamp(dot(p - p0, v) / |v|^2, 0.0, 1.0)
1338            let wx = px - x0;
1339            let wy = py - y0;
1340
1341            let t = if v_len_sq > 1e-6 {
1342                ((wx * vx + wy * vy) / v_len_sq).clamp(0.0, 1.0)
1343            } else {
1344                0.0
1345            };
1346
1347            let proj_x = x0 + t * vx;
1348            let proj_y = y0 + t * vy;
1349
1350            let dist = ((px - proj_x).powi(2) + (py - proj_y).powi(2)).sqrt();
1351            let coverage = (0.5 + half_lw - dist).clamp(0.0, 1.0);
1352
1353            if coverage > 0.005 {
1354                let effective_color = Color::rgba(
1355                    color.r,
1356                    color.g,
1357                    color.b,
1358                    (color.a() * coverage * 255.0) as u8,
1359                );
1360                fb.set_pixel(x, y, effective_color);
1361            }
1362        }
1363    }
1364}
1365
1366#[cfg(test)]
1367mod tests {
1368    use super::*;
1369
1370    #[test]
1371    fn test_transform2d_operations() {
1372        let mut t = Transform2D::IDENTITY;
1373        t.translate(100.0, 50.0);
1374        let p = t.transform_xy(10.0, 20.0);
1375        assert_eq!(p, (110.0, 70.0));
1376
1377        let mut s = Transform2D::IDENTITY;
1378        s.scale_mut(2.0, 3.0);
1379        let p2 = s.transform_xy(10.0, 10.0);
1380        assert_eq!(p2, (20.0, 30.0));
1381    }
1382
1383    #[test]
1384    fn test_canvas_context_recording() {
1385        let mut ctx = Canvas2DContext::new(400.0, 300.0);
1386
1387        ctx.set_fill_style(Color::rgb(255, 0, 0));
1388        ctx.fill_rect(10.0, 10.0, 80.0, 50.0);
1389
1390        ctx.set_stroke_style(Color::rgb(0, 0, 255));
1391        ctx.set_line_width(2.0);
1392        ctx.begin_path();
1393        ctx.move_to(0.0, 0.0);
1394        ctx.line_to(100.0, 100.0);
1395        ctx.stroke();
1396
1397        assert_eq!(ctx.commands().len(), 2);
1398    }
1399
1400    #[test]
1401    fn test_canvas_rasterize_to_framebuffer() {
1402        let mut fb = FrameBuffer::new(200, 200);
1403        let mut ctx = Canvas2DContext::new(200.0, 200.0);
1404
1405        ctx.set_fill_style(Color::rgb(0, 255, 0));
1406        ctx.fill_rect(20.0, 20.0, 40.0, 40.0);
1407
1408        ctx.rasterize(&mut fb, 0.0, 0.0, None);
1409
1410        // Center of rect (40, 40) must be green
1411        let pixel = fb.get_pixel(40, 40);
1412        assert_eq!(pixel, Color::rgb(0, 255, 0));
1413
1414        // Outside rect (5, 5) must be transparent
1415        assert_eq!(fb.get_pixel(5, 5), Color::TRANSPARENT);
1416    }
1417
1418    #[test]
1419    fn test_canvas_bezier_dash_clip_and_text() {
1420        let (size, family, weight, italic) =
1421            parse_canvas_font("italic bold 14px/1.2 'JetBrains Mono', monospace");
1422        assert!((size - 14.0).abs() < 0.01);
1423        assert_eq!(family, "JetBrains Mono, monospace");
1424        assert_eq!(weight, 700);
1425        assert!(italic);
1426
1427        // Dashed horizontal line leaves transparent gaps
1428        let mut fb = FrameBuffer::new(200, 100);
1429        let mut ctx = Canvas2DContext::new(200.0, 100.0);
1430        ctx.set_stroke_style(Color::rgb(255, 0, 0));
1431        ctx.set_line_width(2.0);
1432        ctx.set_line_dash(&[10.0, 10.0]);
1433        ctx.begin_path();
1434        ctx.move_to(0.0, 20.0);
1435        ctx.line_to(100.0, 20.0);
1436        ctx.stroke();
1437        ctx.rasterize(&mut fb, 0.0, 0.0, None);
1438        assert!(fb.get_pixel(5, 20).r > 200, "dash on-segment must be drawn");
1439        assert_eq!(fb.get_pixel(15, 20), Color::TRANSPARENT, "dash gap must stay empty");
1440
1441        // Clip restricts fill_rect, and restore removes clip
1442        let mut fb_clip = FrameBuffer::new(100, 100);
1443        let mut c2 = Canvas2DContext::new(100.0, 100.0);
1444        c2.save();
1445        c2.begin_path();
1446        c2.rect(10.0, 10.0, 30.0, 30.0);
1447        c2.clip();
1448        c2.set_fill_style(Color::rgb(0, 200, 255));
1449        c2.fill_rect(0.0, 0.0, 100.0, 100.0);
1450        c2.restore();
1451        c2.set_fill_style(Color::rgb(255, 255, 0));
1452        c2.fill_rect(60.0, 60.0, 20.0, 20.0);
1453        c2.rasterize(&mut fb_clip, 0.0, 0.0, None);
1454        assert_eq!(fb_clip.get_pixel(25, 25), Color::rgb(0, 200, 255));
1455        assert_eq!(fb_clip.get_pixel(5, 5), Color::TRANSPARENT);
1456        assert_eq!(fb_clip.get_pixel(70, 70), Color::rgb(255, 255, 0));
1457
1458        // Cubic & quadratic bezier + fill_text + stroke_text
1459        let mut fb_curve = FrameBuffer::new(160, 120);
1460        let mut c3 = Canvas2DContext::new(160.0, 120.0);
1461        c3.set_stroke_style(Color::rgb(50, 255, 50));
1462        c3.set_line_width(2.0);
1463        c3.begin_path();
1464        c3.move_to(10.0, 60.0);
1465        c3.quadratic_curve_to(50.0, 10.0, 90.0, 60.0);
1466        c3.bezier_curve_to(110.0, 90.0, 130.0, 90.0, 150.0, 60.0);
1467        c3.stroke();
1468        c3.set_font("bold 12px monospace");
1469        c3.set_text_align(CanvasTextAlign::Left);
1470        c3.set_text_baseline(CanvasTextBaseline::Top);
1471        c3.set_fill_style(Color::rgb(255, 255, 255));
1472        c3.fill_text("CLK_0", 10.0, 5.0);
1473        c3.stroke_text("OUT", 80.0, 5.0);
1474        c3.rasterize(&mut fb_curve, 0.0, 0.0, None);
1475
1476        // Quadratic curve midpoint at t=0.5 is (50, 35)
1477        assert!(
1478            fb_curve.get_pixel(50, 35).g > 150,
1479            "quadratic curve midpoint should be lit"
1480        );
1481        // Text region (10..60, 5..20) should have non-transparent white pixels
1482        let mut lit_text = 0usize;
1483        for y in 5..22 {
1484            for x in 10..60 {
1485                if fb_curve.get_pixel(x, y).a > 0 {
1486                    lit_text += 1;
1487                }
1488            }
1489        }
1490        assert!(lit_text > 5, "fill_text should rasterize visible glyph pixels");
1491    }
1492}