Skip to main content

atmos/os_lib/
canvas2d.rs

1//! Canvas 2D の変換行列とパス幾何(純粋モジュール)。
2//!
3//! `<canvas>` の 2D コンテキストは、現状 API 表面だけが存在し
4//! 全メソッドが `dom_noop` へ接続されている(=一切描画されない)。
5//! 実描画を入れる前提として、ラスタライズに依存しない部分——
6//! **アフィン変換の合成**と**パスの折れ線化**——をここへ集約する。
7//!
8//! ハードウェアにもグローバル状態にも依存しないので、ホスト側で検証できる。
9//!
10//! # 座標系
11//!
12//! 変換行列は CSS/Canvas と同じ `[a b c d e f]` の並びで、点 (x, y) は
13//!
14//! ```text
15//! x' = a*x + c*y + e
16//! y' = b*x + d*y + f
17//! ```
18//!
19//! へ移る。`transform()` は**現在の行列へ右から掛ける**(後から積んだ変換が
20//! 点に対して先に効く)。この順序を取り違えると `translate` してから
21//! `rotate` した図形が原点回りに回ってしまうので、試験で固定する。
22
23extern crate alloc;
24use alloc::vec::Vec;
25
26/// アフィン変換行列 `[a b c d e f]`。
27#[derive(Debug, Clone, Copy, PartialEq)]
28pub struct Matrix {
29    pub a: f32,
30    pub b: f32,
31    pub c: f32,
32    pub d: f32,
33    pub e: f32,
34    pub f: f32,
35}
36
37impl Default for Matrix {
38    fn default() -> Self {
39        Self::identity()
40    }
41}
42
43impl Matrix {
44    pub fn identity() -> Self {
45        Matrix { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 }
46    }
47
48    pub fn translate(tx: f32, ty: f32) -> Self {
49        Matrix { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: tx, f: ty }
50    }
51
52    pub fn scale(sx: f32, sy: f32) -> Self {
53        Matrix { a: sx, b: 0.0, c: 0.0, d: sy, e: 0.0, f: 0.0 }
54    }
55
56    /// 角度はラジアン。正の角度で「x 軸から y 軸へ」回る(Canvas の既定は
57    /// y 軸が下向きなので、画面上は時計回りに見える)。
58    pub fn rotate(rad: f32) -> Self {
59        let (s, c) = (libm::sinf(rad), libm::cosf(rad));
60        Matrix { a: c, b: s, c: -s, d: c, e: 0.0, f: 0.0 }
61    }
62
63    /// `self` に `m` を**右から**掛ける(`self * m`)。
64    ///
65    /// Canvas の `ctx.transform(...)` の意味論。後から積んだ変換ほど
66    /// 点に対して先に効く。
67    pub fn multiply(&self, m: &Matrix) -> Matrix {
68        Matrix {
69            a: self.a * m.a + self.c * m.b,
70            b: self.b * m.a + self.d * m.b,
71            c: self.a * m.c + self.c * m.d,
72            d: self.b * m.c + self.d * m.d,
73            e: self.a * m.e + self.c * m.f + self.e,
74            f: self.b * m.e + self.d * m.f + self.f,
75        }
76    }
77
78    /// 点を変換する。
79    pub fn apply(&self, x: f32, y: f32) -> (f32, f32) {
80        (
81            self.a * x + self.c * y + self.e,
82            self.b * x + self.d * y + self.f,
83        )
84    }
85
86    /// 行列式。0 なら退化(逆行列を持たない)。
87    pub fn determinant(&self) -> f32 {
88        self.a * self.d - self.b * self.c
89    }
90
91    /// 逆行列。退化していれば `None`(呼び出し側は変換を諦める)。
92    ///
93    /// `isPointInPath` のようにデバイス座標をユーザー座標へ戻す用途で要る。
94    pub fn invert(&self) -> Option<Matrix> {
95        let det = self.determinant();
96        if !det.is_finite() || libm::fabsf(det) < 1e-12 {
97            return None;
98        }
99        let inv = 1.0 / det;
100        Some(Matrix {
101            a: self.d * inv,
102            b: -self.b * inv,
103            c: -self.c * inv,
104            d: self.a * inv,
105            e: (self.c * self.f - self.d * self.e) * inv,
106            f: (self.b * self.e - self.a * self.f) * inv,
107        })
108    }
109}
110
111/// パスを構成する副パス(連続した折れ線)。
112#[derive(Debug, Clone, PartialEq)]
113pub struct SubPath {
114    /// 折れ線の頂点(変換適用済みのデバイス座標)。
115    pub points: Vec<(f32, f32)>,
116    /// `closePath()` で閉じられたか。
117    pub closed: bool,
118}
119
120/// パスを (dx, dy) だけ平行移動した新しい副パス列を生成する(Canvas 2D Shadow用)。
121pub(crate) fn offset_subpaths(paths: &[SubPath], dx: f32, dy: f32) -> Vec<SubPath> {
122    paths
123        .iter()
124        .map(|sp| SubPath {
125            points: sp.points.iter().map(|&(x, y)| (x + dx, y + dy)).collect(),
126            closed: sp.closed,
127        })
128        .collect()
129}
130
131/// パス構築器。曲線は折れ線へ分割して保持する。
132///
133/// ラスタライザは「折れ線の集まり」だけを相手にすればよくなるので、
134/// 曲線の分割規則をここへ閉じ込めて試験できる。
135#[derive(Debug, Clone, Default)]
136pub struct PathBuilder {
137    subpaths: Vec<SubPath>,
138    current: Option<SubPath>,
139    /// 直近の点(**変換前**のユーザー座標)。曲線の始点に使う。
140    last_user: Option<(f32, f32)>,
141}
142
143/// 円弧を折れ線化するときの、90 度あたりの分割数。
144const ARC_SEGMENTS_PER_QUARTER: usize = 8;
145/// ベジェ 1 本あたりの分割数。
146const BEZIER_SEGMENTS: usize = 16;
147
148impl PathBuilder {
149    pub fn new() -> Self {
150        Self::default()
151    }
152
153    /// 現在の副パスを確定して次へ移る。
154    ///
155    /// 点が 1 個以下の副パスは描画に寄与しないので捨てる
156    /// (`moveTo` だけして何も引かなかった場合など)。
157    fn flush(&mut self) {
158        if let Some(sp) = self.current.take() {
159            if sp.points.len() >= 2 {
160                self.subpaths.push(sp);
161            }
162        }
163    }
164
165    pub fn begin_path(&mut self) {
166        self.subpaths.clear();
167        self.current = None;
168        self.last_user = None;
169    }
170
171    pub fn move_to(&mut self, m: &Matrix, x: f32, y: f32) {
172        self.flush();
173        self.current = Some(SubPath {
174            points: alloc::vec![m.apply(x, y)],
175            closed: false,
176        });
177        self.last_user = Some((x, y));
178    }
179
180    pub fn line_to(&mut self, m: &Matrix, x: f32, y: f32) {
181        // `moveTo` 無しの `lineTo` は、仕様上その点への `moveTo` と同じ扱い。
182        if self.current.is_none() {
183            self.move_to(m, x, y);
184            return;
185        }
186        if let Some(sp) = self.current.as_mut() {
187            sp.points.push(m.apply(x, y));
188        }
189        self.last_user = Some((x, y));
190    }
191
192    pub fn close_path(&mut self) {
193        if let Some(sp) = self.current.as_mut() {
194            sp.closed = true;
195        }
196        self.flush();
197    }
198
199    pub fn add_path(&mut self, other: &PathBuilder, transform: Option<&Matrix>) {
200        self.flush();
201        let id_mat = Matrix::identity();
202        let m = transform.unwrap_or(&id_mat);
203        for sp in &other.subpaths {
204            let pts = sp.points.iter().map(|p| m.apply(p.0, p.1)).collect();
205            self.subpaths.push(SubPath {
206                points: pts,
207                closed: sp.closed,
208            });
209        }
210        if let Some(ref sp) = other.current {
211            if sp.points.len() >= 2 {
212                let pts = sp.points.iter().map(|p| m.apply(p.0, p.1)).collect();
213                self.subpaths.push(SubPath {
214                    points: pts,
215                    closed: sp.closed,
216                });
217            }
218        }
219        if let Some((lx, ly)) = other.last_user {
220            let lp = m.apply(lx, ly);
221            self.last_user = Some((lp.0, lp.1));
222        }
223    }
224
225    /// 3 次ベジェ。始点は直近の点。
226    pub fn bezier_curve_to(
227        &mut self,
228        m: &Matrix,
229        c1x: f32,
230        c1y: f32,
231        c2x: f32,
232        c2y: f32,
233        x: f32,
234        y: f32,
235    ) {
236        let (x0, y0) = match self.last_user {
237            Some(p) => p,
238            None => {
239                self.move_to(m, c1x, c1y);
240                (c1x, c1y)
241            }
242        };
243        for i in 1..=BEZIER_SEGMENTS {
244            let t = i as f32 / BEZIER_SEGMENTS as f32;
245            let mt = 1.0 - t;
246            let px = mt * mt * mt * x0
247                + 3.0 * mt * mt * t * c1x
248                + 3.0 * mt * t * t * c2x
249                + t * t * t * x;
250            let py = mt * mt * mt * y0
251                + 3.0 * mt * mt * t * c1y
252                + 3.0 * mt * t * t * c2y
253                + t * t * t * y;
254            self.line_to(m, px, py);
255        }
256        self.last_user = Some((x, y));
257    }
258
259    /// 2 次ベジェ。3 次へ昇格させて処理する。
260    pub fn quadratic_curve_to(&mut self, m: &Matrix, cx: f32, cy: f32, x: f32, y: f32) {
261        let (x0, y0) = match self.last_user {
262            Some(p) => p,
263            None => {
264                self.move_to(m, cx, cy);
265                (cx, cy)
266            }
267        };
268        // 2 次 → 3 次の標準的な昇格。
269        let c1x = x0 + 2.0 / 3.0 * (cx - x0);
270        let c1y = y0 + 2.0 / 3.0 * (cy - y0);
271        let c2x = x + 2.0 / 3.0 * (cx - x);
272        let c2y = y + 2.0 / 3.0 * (cy - y);
273        self.bezier_curve_to(m, c1x, c1y, c2x, c2y, x, y);
274    }
275
276    /// 円弧。`anticlockwise` が真なら反時計回り。
277    pub fn arc(
278        &mut self,
279        m: &Matrix,
280        cx: f32,
281        cy: f32,
282        r: f32,
283        start: f32,
284        end: f32,
285        anticlockwise: bool,
286    ) {
287        // 負の半径・非有限値は仕様上エラーだが、ここでは黙って無視する
288        // (描画系でパニックさせない方が安全)。
289        if !r.is_finite() || r < 0.0 || !start.is_finite() || !end.is_finite() {
290            return;
291        }
292        let sweep = normalize_sweep(start, end, anticlockwise);
293        let steps = arc_steps(sweep);
294        for i in 0..=steps {
295            let t = i as f32 / steps as f32;
296            let ang = start + sweep * t;
297            let px = cx + r * libm::cosf(ang);
298            let py = cy + r * libm::sinf(ang);
299            if i == 0 && self.current.is_none() {
300                self.move_to(m, px, py);
301            } else {
302                self.line_to(m, px, py);
303            }
304        }
305    }
306
307    /// 2本の接線((x0,y0)-(x1,y1) と (x1,y1)-(x2,y2))に接する半径 `radius` の円弧を追加する。
308    pub fn arc_to(&mut self, m: &Matrix, x1: f32, y1: f32, x2: f32, y2: f32, radius: f32) {
309        if !x1.is_finite() || !y1.is_finite() || !x2.is_finite() || !y2.is_finite() || !radius.is_finite() {
310            return;
311        }
312        if radius < 0.0 {
313            return;
314        }
315        let (x0, y0) = match self.last_user {
316            Some(p) => p,
317            None => {
318                self.move_to(m, x1, y1);
319                (x1, y1)
320            }
321        };
322
323        // 半径0、またはP0とP1が一致する場合、P1への直線
324        if radius == 0.0 || (x0 == x1 && y0 == y1) {
325            self.line_to(m, x1, y1);
326            return;
327        }
328
329        let v1x = x0 - x1;
330        let v1y = y0 - y1;
331        let v2x = x2 - x1;
332        let v2y = y2 - y1;
333
334        let len1 = libm::hypotf(v1x, v1y);
335        let len2 = libm::hypotf(v2x, v2y);
336
337        if len1 == 0.0 || len2 == 0.0 {
338            self.line_to(m, x1, y1);
339            return;
340        }
341
342        let u1x = v1x / len1;
343        let u1y = v1y / len1;
344        let u2x = v2x / len2;
345        let u2y = v2y / len2;
346
347        let cross = u1x * u2y - u1y * u2x;
348        let dot = u1x * u2x + u1y * u2y;
349
350        // 同一直線上(crossが極小)なら P1 への直線
351        if libm::fabsf(cross) < 1e-6 {
352            self.line_to(m, x1, y1);
353            return;
354        }
355
356        // 接点までの距離: dist = radius * (1.0 + dot) / |cross|
357        let dist = radius * (1.0 + dot) / libm::fabsf(cross);
358
359        let t1x = x1 + dist * u1x;
360        let t1y = y1 + dist * u1y;
361        let t2x = x1 + dist * u2x;
362        let t2y = y1 + dist * u2y;
363
364        // 円の中心 C: T1 から u1 に直交するベクトルへ radius 進む
365        let (cx, cy) = if cross > 0.0 {
366            (t1x - radius * u1y, t1y + radius * u1x)
367        } else {
368            (t1x + radius * u1y, t1y - radius * u1x)
369        };
370
371        let start_ang = libm::atan2f(t1y - cy, t1x - cx);
372        let end_ang = libm::atan2f(t2y - cy, t2x - cx);
373        let anticlockwise = cross > 0.0;
374
375        self.line_to(m, t1x, t1y);
376        self.arc(m, cx, cy, radius, start_ang, end_ang, anticlockwise);
377        self.last_user = Some((t2x, t2y));
378    }
379
380    /// 矩形。独立した閉じた副パスになる。
381    pub fn rect(&mut self, m: &Matrix, x: f32, y: f32, w: f32, h: f32) {
382        self.flush();
383        self.current = Some(SubPath {
384            points: alloc::vec![
385                m.apply(x, y),
386                m.apply(x + w, y),
387                m.apply(x + w, y + h),
388                m.apply(x, y + h),
389            ],
390            closed: true,
391        });
392        self.flush();
393        self.last_user = Some((x, y));
394    }
395
396    /// 構築済みの副パス一覧を返す(未確定の副パスも含める)。
397    pub fn finish(&self) -> Vec<SubPath> {
398        let mut out = self.subpaths.clone();
399        if let Some(sp) = &self.current {
400            if sp.points.len() >= 2 {
401                out.push(sp.clone());
402            }
403        }
404        out
405    }
406}
407
408/// 円弧の掃引角を求める。
409///
410/// Canvas の仕様では、時計回り指定で `end < start` のときは 2π を足し、
411/// 反時計回り指定で `end > start` のときは 2π を引く。
412/// 差が 2π を超える場合は 1 周に丸める(分割数が発散しないように)。
413pub fn normalize_sweep(start: f32, end: f32, anticlockwise: bool) -> f32 {
414    let tau = core::f32::consts::PI * 2.0;
415    let mut sweep = end - start;
416    if anticlockwise {
417        if sweep > 0.0 {
418            sweep -= tau;
419        }
420        if sweep < -tau {
421            sweep = -tau;
422        }
423    } else {
424        if sweep < 0.0 {
425            sweep += tau;
426        }
427        if sweep > tau {
428            sweep = tau;
429        }
430    }
431    sweep
432}
433
434/// 掃引角に応じた分割数(最低 1)。
435pub fn arc_steps(sweep: f32) -> usize {
436    let quarters = libm::fabsf(sweep) / (core::f32::consts::PI / 2.0);
437    let n = (quarters * ARC_SEGMENTS_PER_QUARTER as f32) as usize;
438    n.max(1)
439}
440
441// ───────────── ラスタライズ(走査線) ─────────────
442
443/// 塗りつぶし規則。
444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
445pub enum FillRule {
446    /// `nonzero`(既定)。巻き数が 0 でなければ内側。
447    NonZero,
448    /// `evenodd`。交差回数が奇数なら内側。
449    EvenOdd,
450}
451
452/// 走査線 `y` とパスの交点を求め、塗るべき x 区間を返す(純粋関数)。
453///
454/// 返り値は `(x_start, x_end)` の並びで、いずれも**昇順・非重複**。
455/// 閉じていない副パスも、塗りのときは仕様上「閉じているものとして」扱う。
456///
457/// # なぜ純粋関数にするか
458///
459/// 巻き数の数え方(`nonzero` と `evenodd` の違い)と、頂点をちょうど
460/// 走査線が通るときの二重計上は、目視では気づけない典型的なバグ源。
461/// ここを試験で固定しておけば、実際のピクセル書き込み側は
462/// 「区間を塗るだけ」の単純な処理に保てる。
463///
464/// 計算量: **O(辺の数 log 辺の数)**(交点の整列ぶん)。
465pub fn scanline_spans(subpaths: &[SubPath], y: f32, rule: FillRule) -> Vec<(f32, f32)> {
466    // (x, 巻き方向) の組を集める。
467    let mut hits: Vec<(f32, i32)> = Vec::new();
468    for sp in subpaths {
469        let n = sp.points.len();
470        if n < 2 {
471            continue;
472        }
473        // 塗りでは常に閉じたものとして扱う(最後の点と最初の点を結ぶ)。
474        for i in 0..n {
475            let (x0, y0) = sp.points[i];
476            let (x1, y1) = sp.points[(i + 1) % n];
477            if !y0.is_finite() || !y1.is_finite() || !x0.is_finite() || !x1.is_finite() {
478                continue;
479            }
480            // 水平な辺は交差を作らない。
481            if (y0 - y1).abs() < f32::EPSILON {
482                continue;
483            }
484            // 半開区間 [min, max) で判定する。
485            //
486            // これをしないと、頂点をちょうど走査線が通るときに
487            // 上下 2 本の辺が同じ交点を二重に数え、`evenodd` で
488            // 内外が反転する(塗り残し・塗り過ぎの典型的な原因)。
489            let (ylo, yhi) = if y0 < y1 { (y0, y1) } else { (y1, y0) };
490            if y < ylo || y >= yhi {
491                continue;
492            }
493            let t = (y - y0) / (y1 - y0);
494            let x = x0 + t * (x1 - x0);
495            // 下向きの辺を +1、上向きを -1 とする。
496            let dir = if y1 > y0 { 1 } else { -1 };
497            hits.push((x, dir));
498        }
499    }
500    if hits.is_empty() {
501        return Vec::new();
502    }
503    // x 昇順に並べる(NaN は上で除外済み)。
504    hits.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(core::cmp::Ordering::Equal));
505
506    let mut spans = Vec::new();
507    match rule {
508        FillRule::EvenOdd => {
509            let mut i = 0;
510            while i + 1 < hits.len() {
511                spans.push((hits[i].0, hits[i + 1].0));
512                i += 2;
513            }
514        }
515        FillRule::NonZero => {
516            let mut winding = 0i32;
517            let mut start = 0.0f32;
518            for &(x, dir) in &hits {
519                let was_inside = winding != 0;
520                winding += dir;
521                let now_inside = winding != 0;
522                if !was_inside && now_inside {
523                    start = x;
524                } else if was_inside && !now_inside {
525                    spans.push((start, x));
526                }
527            }
528        }
529    }
530    spans
531}
532
533/// 指定した座標 (x, y) がパス(subpaths)の内部に含まれるかを判定する(W3C isPointInPath 準拠)。
534pub fn is_point_in_path(subpaths: &[SubPath], x: f32, y: f32, rule: FillRule) -> bool {
535    if !x.is_finite() || !y.is_finite() || subpaths.is_empty() {
536        return false;
537    }
538    let spans = scanline_spans(subpaths, y, rule);
539    for (sx, ex) in spans {
540        if x >= sx - 1e-4 && x <= ex + 1e-4 {
541            return true;
542        }
543    }
544    false
545}
546
547/// 指定した座標 (x, y) がストローク線(subpaths, line_width)の範囲内にあるかを判定する(W3C isPointInStroke 準拠)。
548pub fn is_point_in_stroke(subpaths: &[SubPath], x: f32, y: f32, line_width: f32) -> bool {
549    if !x.is_finite() || !y.is_finite() || subpaths.is_empty() || line_width <= 0.0 {
550        return false;
551    }
552    let max_dist = line_width * 0.5;
553    let max_dist_sq = max_dist * max_dist;
554
555    for sp in subpaths {
556        let n = sp.points.len();
557        if n < 2 {
558            continue;
559        }
560        for i in 0..n - 1 {
561            let (x0, y0) = sp.points[i];
562            let (x1, y1) = sp.points[i + 1];
563            if !x0.is_finite() || !y0.is_finite() || !x1.is_finite() || !y1.is_finite() {
564                continue;
565            }
566            let dx = x1 - x0;
567            let dy = y1 - y0;
568            let len_sq = dx * dx + dy * dy;
569            let dist_sq = if len_sq < 1e-6 {
570                let px = x - x0;
571                let py = y - y0;
572                px * px + py * py
573            } else {
574                let t = (((x - x0) * dx + (y - y0) * dy) / len_sq).clamp(0.0, 1.0);
575                let qx = x0 + t * dx;
576                let qy = y0 + t * dy;
577                let px = x - qx;
578                let py = y - qy;
579                px * px + py * py
580            };
581            if dist_sq <= max_dist_sq {
582                return true;
583            }
584        }
585        if sp.closed && n >= 3 {
586            let (x0, y0) = sp.points[n - 1];
587            let (x1, y1) = sp.points[0];
588            let dx = x1 - x0;
589            let dy = y1 - y0;
590            let len_sq = dx * dx + dy * dy;
591            let dist_sq = if len_sq < 1e-6 {
592                let px = x - x0;
593                let py = y - y0;
594                px * px + py * py
595            } else {
596                let t = (((x - x0) * dx + (y - y0) * dy) / len_sq).clamp(0.0, 1.0);
597                let qx = x0 + t * dx;
598                let qy = y0 + t * dy;
599                let px = x - qx;
600                let py = y - qy;
601                px * px + py * py
602            };
603            if dist_sq <= max_dist_sq {
604                return true;
605            }
606        }
607    }
608    false
609}
610
611/// 指定した座標 (x, y) が、線幅・端点・結合・破線パターンを反映したストローク範囲内にあるかを判定する(W3C isPointInStroke 準拠)。
612pub fn is_point_in_stroke_styled(
613    subpaths: &[SubPath],
614    x: f32,
615    y: f32,
616    line_width: f32,
617    cap: LineCap,
618    join: LineJoin,
619    miter_limit: f32,
620    dash: &[f32],
621    dash_offset: f32,
622) -> bool {
623    if !x.is_finite() || !y.is_finite() || subpaths.is_empty() || line_width <= 0.0 {
624        return false;
625    }
626    let dashed = if dash.is_empty() {
627        subpaths.to_vec()
628    } else {
629        dash_subpaths(subpaths, dash, dash_offset)
630    };
631    let outline = stroke_to_outline(&dashed, line_width, cap, join, miter_limit);
632    if outline.is_empty() {
633        return false;
634    }
635    is_point_in_path(&outline, x, y, FillRule::NonZero)
636}
637
638
639// ───────────── グラデーション ─────────────
640
641/// グラデーションのカラーストップ。
642#[derive(Debug, Clone, Copy, PartialEq)]
643pub struct ColorStop {
644    pub offset: f32, // 0.0 ..= 1.0
645    pub color: u32,  // ARGB8888
646}
647
648/// グラデーションの種別と幾何パラメータ。
649#[derive(Debug, Clone, PartialEq)]
650pub enum GradientKind {
651    Linear {
652        x0: f32,
653        y0: f32,
654        x1: f32,
655        y1: f32,
656    },
657    Radial {
658        x0: f32,
659        y0: f32,
660        r0: f32,
661        x1: f32,
662        y1: f32,
663        r1: f32,
664    },
665    Conic {
666        start_angle: f32,
667        cx: f32,
668        cy: f32,
669    },
670}
671
672/// カラーストップ配列から位置 `t`(0.0..=1.0)に対応する ARGB8888 色を線形補間する。
673pub fn sample_gradient_stops(stops: &[ColorStop], t: f32) -> u32 {
674    if stops.is_empty() {
675        return 0; // 透明
676    }
677    let t = t.clamp(0.0, 1.0);
678    if t <= stops[0].offset {
679        return stops[0].color;
680    }
681    let last = &stops[stops.len() - 1];
682    if t >= last.offset {
683        return last.color;
684    }
685    for i in 0..stops.len() - 1 {
686        let s0 = &stops[i];
687        let s1 = &stops[i + 1];
688        if t >= s0.offset && t <= s1.offset {
689            let span = s1.offset - s0.offset;
690            let ratio = if span > 1e-6 { (t - s0.offset) / span } else { 0.0 };
691            let a0 = ((s0.color >> 24) & 0xFF) as f32;
692            let r0 = ((s0.color >> 16) & 0xFF) as f32;
693            let g0 = ((s0.color >> 8) & 0xFF) as f32;
694            let b0 = (s0.color & 0xFF) as f32;
695
696            let a1 = ((s1.color >> 24) & 0xFF) as f32;
697            let r1 = ((s1.color >> 16) & 0xFF) as f32;
698            let g1 = ((s1.color >> 8) & 0xFF) as f32;
699            let b1 = (s1.color & 0xFF) as f32;
700
701            let a = ((1.0 - ratio) * a0 + ratio * a1 + 0.5) as u32;
702            let r = ((1.0 - ratio) * r0 + ratio * r1 + 0.5) as u32;
703            let g = ((1.0 - ratio) * g0 + ratio * g1 + 0.5) as u32;
704            let b = ((1.0 - ratio) * b0 + ratio * b1 + 0.5) as u32;
705
706            return (a.min(255) << 24) | (r.min(255) << 16) | (g.min(255) << 8) | b.min(255);
707        }
708    }
709    last.color
710}
711
712/// Canvas 2D のグラデーションオブジェクト。
713#[derive(Debug, Clone, PartialEq)]
714pub struct CanvasGradient {
715    pub kind: GradientKind,
716    pub stops: Vec<ColorStop>,
717}
718
719impl CanvasGradient {
720    pub fn new_linear(x0: f32, y0: f32, x1: f32, y1: f32) -> Self {
721        CanvasGradient {
722            kind: GradientKind::Linear { x0, y0, x1, y1 },
723            stops: Vec::new(),
724        }
725    }
726
727    pub fn new_radial(x0: f32, y0: f32, r0: f32, x1: f32, y1: f32, r1: f32) -> Self {
728        CanvasGradient {
729            kind: GradientKind::Radial { x0, y0, r0, x1, y1, r1 },
730            stops: Vec::new(),
731        }
732    }
733
734    pub fn new_conic(start_angle: f32, cx: f32, cy: f32) -> Self {
735        CanvasGradient {
736            kind: GradientKind::Conic { start_angle, cx, cy },
737            stops: Vec::new(),
738        }
739    }
740
741    pub fn add_color_stop(&mut self, offset: f32, color: u32) {
742        let offset = offset.clamp(0.0, 1.0);
743        let stop = ColorStop { offset, color };
744        let idx = self.stops.partition_point(|s| s.offset <= offset);
745        self.stops.insert(idx, stop);
746    }
747
748    /// 256段の高速ルックアップテーブル(LUT)を生成する。
749    pub fn build_lut(&self) -> [u32; 256] {
750        let mut lut = [0u32; 256];
751        if self.stops.is_empty() {
752            return lut;
753        }
754        for i in 0..256 {
755            let t = i as f32 / 255.0;
756            lut[i] = sample_gradient_stops(&self.stops, t);
757        }
758        lut
759    }
760
761    /// 座標 (x, y) における射影パラメータ t (0.0..=1.0) を計算する。
762    pub fn calculate_t(&self, x: f32, y: f32) -> f32 {
763        match self.kind {
764            GradientKind::Linear { x0, y0, x1, y1 } => {
765                let dx = x1 - x0;
766                let dy = y1 - y0;
767                let len_sq = dx * dx + dy * dy;
768                if len_sq < 1e-6 {
769                    return 0.0;
770                }
771                let proj = (x - x0) * dx + (y - y0) * dy;
772                (proj / len_sq).clamp(0.0, 1.0)
773            }
774            GradientKind::Radial { x0: _, y0: _, r0, x1, y1, r1 } => {
775                let dx = x - x1;
776                let dy = y - y1;
777                let dist = libm::sqrtf(dx * dx + dy * dy);
778                let r_span = r1 - r0;
779                if libm::fabsf(r_span) < 1e-6 {
780                    return 0.0;
781                }
782                ((dist - r0) / r_span).clamp(0.0, 1.0)
783            }
784            GradientKind::Conic { start_angle, cx, cy } => {
785                let dx = x - cx;
786                let dy = y - cy;
787                if dx == 0.0 && dy == 0.0 {
788                    return 0.0;
789                }
790                let angle = libm::atan2f(dy, dx);
791                let mut diff = angle - start_angle;
792                let two_pi = core::f32::consts::PI * 2.0;
793                while diff < 0.0 {
794                    diff += two_pi;
795                }
796                while diff >= two_pi {
797                    diff -= two_pi;
798                }
799                (diff / two_pi).clamp(0.0, 1.0)
800            }
801        }
802    }
803}
804
805
806// ───────────── パターン ─────────────
807
808/// `createPattern` のリピート方式。
809#[derive(Debug, Clone, Copy, PartialEq, Eq)]
810pub enum Repetition {
811    Repeat,
812    RepeatX,
813    RepeatY,
814    NoRepeat,
815}
816
817/// 文字列から `Repetition` を判定する(仕様上、大文字小文字無視、空文字や未知の値は Repeat)。
818pub fn parse_repetition(s: &str) -> Repetition {
819    let s = s.trim();
820    if s.is_empty() {
821        return Repetition::Repeat;
822    }
823    if s.eq_ignore_ascii_case("repeat") {
824        Repetition::Repeat
825    } else if s.eq_ignore_ascii_case("repeat-x") {
826        Repetition::RepeatX
827    } else if s.eq_ignore_ascii_case("repeat-y") {
828        Repetition::RepeatY
829    } else if s.eq_ignore_ascii_case("no-repeat") {
830        Repetition::NoRepeat
831    } else {
832        Repetition::Repeat
833    }
834}
835
836/// Canvas 2D のパターンオブジェクト。
837#[derive(Debug, Clone, PartialEq)]
838pub struct CanvasPattern {
839    pub width: u32,
840    pub height: u32,
841    pub pixels: Vec<u32>,
842    pub repetition: Repetition,
843    pub transform: Matrix,
844}
845
846impl CanvasPattern {
847    pub fn new(width: u32, height: u32, pixels: Vec<u32>, repetition: Repetition) -> Self {
848        CanvasPattern {
849            width,
850            height,
851            pixels,
852            repetition,
853            transform: Matrix::identity(),
854        }
855    }
856
857    pub fn set_transform(&mut self, m: Matrix) {
858        self.transform = m;
859    }
860
861    /// 座標 (x, y) におけるピクセル色 (ARGB8888) をサンプリングする。
862    /// 範囲外(no-repeat等)は 0(透明)を返す。
863    pub fn sample(&self, x: f32, y: f32) -> u32 {
864        if self.width == 0 || self.height == 0 || self.pixels.is_empty() {
865            return 0;
866        }
867        let (u, v) = if let Some(inv) = self.transform.invert() {
868            inv.apply(x, y)
869        } else {
870            (x, y)
871        };
872        let w = self.width as i32;
873        let h = self.height as i32;
874
875        let (ix, iy) = match self.repetition {
876            Repetition::Repeat => (
877                (libm::floorf(u) as i32).rem_euclid(w),
878                (libm::floorf(v) as i32).rem_euclid(h),
879            ),
880            Repetition::RepeatX => {
881                let y_int = libm::floorf(v) as i32;
882                if y_int < 0 || y_int >= h {
883                    return 0;
884                }
885                ((libm::floorf(u) as i32).rem_euclid(w), y_int)
886            }
887            Repetition::RepeatY => {
888                let x_int = libm::floorf(u) as i32;
889                if x_int < 0 || x_int >= w {
890                    return 0;
891                }
892                (x_int, (libm::floorf(v) as i32).rem_euclid(h))
893            }
894            Repetition::NoRepeat => {
895                let x_int = libm::floorf(u) as i32;
896                let y_int = libm::floorf(v) as i32;
897                if x_int < 0 || x_int >= w || y_int < 0 || y_int >= h {
898                    return 0;
899                }
900                (x_int, y_int)
901            }
902        };
903
904        let idx = (iy as usize) * (self.width as usize) + (ix as usize);
905        self.pixels.get(idx).copied().unwrap_or(0)
906    }
907}
908
909
910// ───────────── バッキングストアへの描画 ─────────────
911
912/// Canvas のバッキングストア(ARGB8888 のピクセル配列)。
913///
914/// 画面へ直接描かず、まずここへ描く。`<canvas>` は
915/// 「レイアウトで決まった矩形へ、自分のピクセルを貼る」要素なので、
916/// 画面座標ではなく**キャンバス内座標**で完結させる必要がある。
917#[derive(Debug, Clone)]
918pub struct Surface {
919    pub width: u32,
920    pub height: u32,
921    /// 長さは `width * height`。各要素は 0xAARRGGBB。
922    pub pixels: Vec<u32>,
923    /// 有効なクリップ領域。`None` なら全面に描ける。
924    ///
925    /// 状態側(`DrawState`)が持ち主で、描画の直前に `sync_clip` で写す。
926    /// 塗りの実装すべてが最後は `blend_pixel` を通るので、
927    /// ここで一度だけ見れば経路の取りこぼしが起きない。
928    pub clip: Option<alloc::sync::Arc<ClipMask>>,
929    /// 合成モード(既定 `SourceOver`)。
930    pub composite_op: CompositeOperation,
931}
932
933impl Surface {
934    /// 透明で初期化した面を作る。
935    ///
936    /// 面積が過大な場合は `None`(ヒープを食い潰さないための上限)。
937    /// 実サイトの canvas は大きくても数千×数千なので、
938    /// 4096×4096(約 64MB)を上限とする。
939    pub fn new(width: u32, height: u32) -> Option<Self> {
940        const MAX_SIDE: u32 = 4096;
941        if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE {
942            return None;
943        }
944        let n = (width as usize).checked_mul(height as usize)?;
945        Some(Surface {
946            width,
947            height,
948            pixels: alloc::vec![0u32; n],
949            clip: None,
950            composite_op: CompositeOperation::SourceOver,
951        })
952    }
953
954    /// 指定座標のピクセル(0xAARRGGBB)を返す。範囲外は 0(透明)。
955    pub fn get_pixel(&self, x: i32, y: i32) -> u32 {
956        if x < 0 || y < 0 || x as u32 >= self.width || y as u32 >= self.height {
957            return 0;
958        }
959        let idx = y as usize * self.width as usize + x as usize;
960        self.pixels[idx]
961    }
962
963    /// 指定座標にピクセル(0xAARRGGBB)を直接書き込む。範囲外は無視する。
964    pub fn set_pixel(&mut self, x: i32, y: i32, argb: u32) {
965        if x < 0 || y < 0 || x as u32 >= self.width || y as u32 >= self.height {
966            return;
967        }
968        let idx = y as usize * self.width as usize + x as usize;
969        self.pixels[idx] = argb;
970    }
971
972    /// 1 ピクセルを現在の合成モード(`self.composite_op`)で描画する。範囲外は黙って無視する。
973    pub fn blend_pixel(&mut self, x: i32, y: i32, argb: u32) {
974        self.blend_pixel_with_op(x, y, argb, self.composite_op);
975    }
976
977    /// 1 ピクセルを指定した合成モード(Porter-Duff)で描画する。
978    #[allow(clippy::manual_checked_ops)] // 結果 0 のとき別の値を返す分岐で、既に `out_a == 0` を明示的に確認している
979    pub fn blend_pixel_with_op(&mut self, x: i32, y: i32, argb: u32, op: CompositeOperation) {
980        if x < 0 || y < 0 || x as u32 >= self.width || y as u32 >= self.height {
981            return;
982        }
983        if let Some(c) = &self.clip {
984            if !c.allows(x, y) {
985                return;
986            }
987        }
988        let idx = y as usize * self.width as usize + x as usize;
989        let sa = (argb >> 24) & 0xFF;
990        let sr = (argb >> 16) & 0xFF;
991        let sg = (argb >> 8) & 0xFF;
992        let sb = argb & 0xFF;
993
994        let dst = self.pixels[idx];
995        let da = (dst >> 24) & 0xFF;
996        let dr = (dst >> 16) & 0xFF;
997        let dg = (dst >> 8) & 0xFF;
998        let db = dst & 0xFF;
999
1000        let (out_a, out_r, out_g, out_b) = match op {
1001            CompositeOperation::Copy => (sa, sr, sg, sb),
1002            CompositeOperation::SourceOver => {
1003                if sa == 0 {
1004                    return;
1005                }
1006                if sa == 255 {
1007                    self.pixels[idx] = argb;
1008                    return;
1009                }
1010                let inv = 255 - sa;
1011                let out_a = sa + da * inv / 255;
1012                if out_a == 0 {
1013                    (0, 0, 0, 0)
1014                } else {
1015                    let r = (sr * sa + dr * da * inv / 255) / out_a;
1016                    let g = (sg * sa + dg * da * inv / 255) / out_a;
1017                    let b = (sb * sa + db * da * inv / 255) / out_a;
1018                    (out_a, r.min(255), g.min(255), b.min(255))
1019                }
1020            }
1021            CompositeOperation::DestinationOver => {
1022                if da == 255 {
1023                    return;
1024                }
1025                let inv = 255 - da;
1026                let out_a = da + sa * inv / 255;
1027                if out_a == 0 {
1028                    (0, 0, 0, 0)
1029                } else {
1030                    let r = (dr * da + sr * sa * inv / 255) / out_a;
1031                    let g = (dg * da + sg * sa * inv / 255) / out_a;
1032                    let b = (db * da + sb * sa * inv / 255) / out_a;
1033                    (out_a, r.min(255), g.min(255), b.min(255))
1034                }
1035            }
1036            CompositeOperation::SourceIn => {
1037                let out_a = (sa * da) / 255;
1038                (out_a, sr, sg, sb)
1039            }
1040            CompositeOperation::SourceOut => {
1041                let out_a = (sa * (255 - da)) / 255;
1042                (out_a, sr, sg, sb)
1043            }
1044            CompositeOperation::SourceAtop => {
1045                let out_a = da;
1046                let r = (sr * sa + dr * (255 - sa)) / 255;
1047                let g = (sg * sa + dg * (255 - sa)) / 255;
1048                let b = (sb * sa + db * (255 - sa)) / 255;
1049                (out_a, r.min(255), g.min(255), b.min(255))
1050            }
1051            CompositeOperation::DestinationIn => {
1052                let out_a = (da * sa) / 255;
1053                (out_a, dr, dg, db)
1054            }
1055            CompositeOperation::DestinationOut => {
1056                let out_a = (da * (255 - sa)) / 255;
1057                (out_a, dr, dg, db)
1058            }
1059            CompositeOperation::DestinationAtop => {
1060                let out_a = sa;
1061                let r = (dr * da + sr * (255 - da)) / 255;
1062                let g = (dg * da + sg * (255 - da)) / 255;
1063                let b = (db * da + sb * (255 - da)) / 255;
1064                (out_a, r.min(255), g.min(255), b.min(255))
1065            }
1066            CompositeOperation::Lighter => {
1067                let out_a = (sa + da).min(255);
1068                let r = (sr + dr).min(255);
1069                let g = (sg + dg).min(255);
1070                let b = (sb + db).min(255);
1071                (out_a, r, g, b)
1072            }
1073            CompositeOperation::Xor => {
1074                let inv_d = 255 - da;
1075                let inv_s = 255 - sa;
1076                let out_a = (sa * inv_d + da * inv_s) / 255;
1077                if out_a == 0 {
1078                    (0, 0, 0, 0)
1079                } else {
1080                    let r = (sr * sa * inv_d + dr * da * inv_s) / (out_a * 255);
1081                    let g = (sg * sa * inv_d + dg * da * inv_s) / (out_a * 255);
1082                    let b = (sb * sa * inv_d + db * da * inv_s) / (out_a * 255);
1083                    (out_a.min(255), r.min(255), g.min(255), b.min(255))
1084                }
1085            }
1086        };
1087
1088        self.pixels[idx] = (out_a.min(255) << 24) | (out_r.min(255) << 16) | (out_g.min(255) << 8) | out_b.min(255);
1089    }
1090
1091    /// 矩形を塗りつぶす(`clearRect` は `argb=0` かつ `replace=true` で使う)。
1092    ///
1093    /// `replace` が真なら合成せず上書きする(`clearRect` の意味論)。
1094    pub fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, argb: u32, replace: bool) {
1095        mark_canvas_dirty();
1096        if w <= 0 || h <= 0 {
1097            return;
1098        }
1099        let x0 = x.max(0);
1100        let y0 = y.max(0);
1101        let x1 = (x.saturating_add(w)).min(self.width as i32);
1102        let y1 = (y.saturating_add(h)).min(self.height as i32);
1103        for py in y0..y1 {
1104            for px in x0..x1 {
1105                if replace {
1106                    // `clearRect` も合成を飛ばすだけで、クリップは効く(仕様)。
1107                    // ここは `blend_pixel` を通らないので個別に見る。
1108                    if let Some(c) = &self.clip {
1109                        if !c.allows(px, py) {
1110                            continue;
1111                        }
1112                    }
1113                    let idx = py as usize * self.width as usize + px as usize;
1114                    self.pixels[idx] = argb;
1115                } else {
1116                    self.blend_pixel(px, py, argb);
1117                }
1118            }
1119        }
1120    }
1121
1122    /// パスを塗りつぶす。
1123    ///
1124    /// 走査線はピクセル中心(`y + 0.5`)で判定する。境界ちょうどの
1125    /// 走査線を使うと、隣り合う図形の継ぎ目に隙間や二重塗りが出る。
1126    pub fn fill_path(&mut self, subpaths: &[SubPath], rule: FillRule, argb: u32) {
1127        mark_canvas_dirty();
1128        if subpaths.is_empty() {
1129            return;
1130        }
1131        // 走査する y 範囲をパスの境界から絞る(全面走査を避ける)。
1132        let (mut ymin, mut ymax) = (f32::MAX, f32::MIN);
1133        for sp in subpaths {
1134            for &(_, py) in &sp.points {
1135                if py.is_finite() {
1136                    ymin = ymin.min(py);
1137                    ymax = ymax.max(py);
1138                }
1139            }
1140        }
1141        if ymin > ymax {
1142            return;
1143        }
1144        let y_start = (libm::floorf(ymin) as i32).max(0);
1145        let y_end = (libm::ceilf(ymax) as i32).min(self.height as i32);
1146        for py in y_start..y_end {
1147            let spans = scanline_spans(subpaths, py as f32 + 0.5, rule);
1148            for (sx, ex) in spans {
1149                // 区間の両端はピクセル境界へ丸める。
1150                let x0 = (libm::roundf(sx) as i32).max(0);
1151                let x1 = (libm::roundf(ex) as i32).min(self.width as i32);
1152                for px in x0..x1 {
1153                    self.blend_pixel(px, py, argb);
1154                }
1155            }
1156        }
1157    }
1158
1159    /// パスをグラデーション(線形または円形)で塗りつぶす。
1160    pub fn fill_path_gradient(
1161        &mut self,
1162        subpaths: &[SubPath],
1163        rule: FillRule,
1164        gradient: &CanvasGradient,
1165        alpha_multiplier: f32,
1166    ) {
1167        mark_canvas_dirty();
1168        if subpaths.is_empty() || gradient.stops.is_empty() {
1169            return;
1170        }
1171        let lut = gradient.build_lut();
1172        let (mut ymin, mut ymax) = (f32::MAX, f32::MIN);
1173        for sp in subpaths {
1174            for &(_, py) in &sp.points {
1175                if py.is_finite() {
1176                    ymin = ymin.min(py);
1177                    ymax = ymax.max(py);
1178                }
1179            }
1180        }
1181        if ymin > ymax {
1182            return;
1183        }
1184        let y_start = (libm::floorf(ymin) as i32).max(0);
1185        let y_end = (libm::ceilf(ymax) as i32).min(self.height as i32);
1186
1187        match gradient.kind {
1188            GradientKind::Linear { x0, y0, x1, y1 } => {
1189                let dx = x1 - x0;
1190                let dy = y1 - y0;
1191                let len_sq = dx * dx + dy * dy;
1192                let (cx, cy, c_base) = if len_sq >= 1e-6 {
1193                    let inv = 1.0 / len_sq;
1194                    (dx * inv, dy * inv, -(x0 * dx + y0 * dy) * inv)
1195                } else {
1196                    (0.0, 0.0, 0.0)
1197                };
1198
1199                for py in y_start..y_end {
1200                    let y_mid = py as f32 + 0.5;
1201                    let t_row_base = c_base + cy * y_mid;
1202                    let spans = scanline_spans(subpaths, y_mid, rule);
1203                    for (sx, ex) in spans {
1204                        let px0 = (libm::roundf(sx) as i32).max(0);
1205                        let px1 = (libm::roundf(ex) as i32).min(self.width as i32);
1206                        for px in px0..px1 {
1207                            let x_mid = px as f32 + 0.5;
1208                            let t = (t_row_base + cx * x_mid).clamp(0.0, 1.0);
1209                            let lut_idx = (t * 255.0 + 0.5) as usize;
1210                            let mut color = lut[lut_idx.min(255)];
1211                            if alpha_multiplier < 1.0 {
1212                                let a = (((color >> 24) & 0xFF) as f32 * alpha_multiplier + 0.5) as u32;
1213                                color = (a.min(255) << 24) | (color & 0x00FF_FFFF);
1214                            }
1215                            self.blend_pixel(px, py, color);
1216                        }
1217                    }
1218                }
1219            }
1220            GradientKind::Radial { .. } | GradientKind::Conic { .. } => {
1221                for py in y_start..y_end {
1222                    let y_mid = py as f32 + 0.5;
1223                    let spans = scanline_spans(subpaths, y_mid, rule);
1224                    for (sx, ex) in spans {
1225                        let px0 = (libm::roundf(sx) as i32).max(0);
1226                        let px1 = (libm::roundf(ex) as i32).min(self.width as i32);
1227                        for px in px0..px1 {
1228                            let x_mid = px as f32 + 0.5;
1229                            let t = gradient.calculate_t(x_mid, y_mid);
1230                            let lut_idx = (t * 255.0 + 0.5) as usize;
1231                            let mut color = lut[lut_idx.min(255)];
1232                            if alpha_multiplier < 1.0 {
1233                                let a = (((color >> 24) & 0xFF) as f32 * alpha_multiplier + 0.5) as u32;
1234                                color = (a.min(255) << 24) | (color & 0x00FF_FFFF);
1235                            }
1236                            self.blend_pixel(px, py, color);
1237                        }
1238                    }
1239                }
1240            }
1241        }
1242    }
1243
1244    /// パスをパターン(タイリング画像)で塗りつぶす。
1245    pub fn fill_path_pattern(
1246        &mut self,
1247        subpaths: &[SubPath],
1248        rule: FillRule,
1249        pattern: &CanvasPattern,
1250        alpha_multiplier: f32,
1251    ) {
1252        mark_canvas_dirty();
1253        if subpaths.is_empty() || pattern.width == 0 || pattern.height == 0 || pattern.pixels.is_empty() {
1254            return;
1255        }
1256        let (mut ymin, mut ymax) = (f32::MAX, f32::MIN);
1257        for sp in subpaths {
1258            for &(_, py) in &sp.points {
1259                if py.is_finite() {
1260                    ymin = ymin.min(py);
1261                    ymax = ymax.max(py);
1262                }
1263            }
1264        }
1265        if ymin > ymax {
1266            return;
1267        }
1268        let y_start = (libm::floorf(ymin) as i32).max(0);
1269        let y_end = (libm::ceilf(ymax) as i32).min(self.height as i32);
1270
1271        for py in y_start..y_end {
1272            let y_mid = py as f32 + 0.5;
1273            let spans = scanline_spans(subpaths, y_mid, rule);
1274            for (sx, ex) in spans {
1275                let px0 = (libm::roundf(sx) as i32).max(0);
1276                let px1 = (libm::roundf(ex) as i32).min(self.width as i32);
1277                for px in px0..px1 {
1278                    let x_mid = px as f32 + 0.5;
1279                    let color = pattern.sample(x_mid, y_mid);
1280                    let a = (color >> 24) & 0xFF;
1281                    if a == 0 {
1282                        continue;
1283                    }
1284                    let final_color = if alpha_multiplier < 1.0 {
1285                        let final_a = libm::roundf(a as f32 * alpha_multiplier).clamp(0.0, 255.0) as u32;
1286                        (final_a << 24) | (color & 0x00FF_FFFF)
1287                    } else {
1288                        color
1289                    };
1290                    self.blend_pixel(px, py, final_color);
1291                }
1292            }
1293        }
1294    }
1295
1296    /// 折れ線を線幅 1 で描く(`stroke` の最小実装)。
1297    ///
1298    /// 線幅・線端・線結合は未対応。まず「線が見える」ところまでを担保する。
1299    pub fn stroke_path(&mut self, subpaths: &[SubPath], argb: u32) {
1300        mark_canvas_dirty();
1301        for sp in subpaths {
1302            let n = sp.points.len();
1303            if n < 2 {
1304                continue;
1305            }
1306            let last = if sp.closed { n } else { n - 1 };
1307            for i in 0..last {
1308                let (x0, y0) = sp.points[i];
1309                let (x1, y1) = sp.points[(i + 1) % n];
1310                self.draw_line(x0, y0, x1, y1, argb);
1311            }
1312        }
1313    }
1314
1315    /// Bresenham で線分を引く。非有限座標は無視する。
1316    fn draw_line(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, argb: u32) {
1317        if !x0.is_finite() || !y0.is_finite() || !x1.is_finite() || !y1.is_finite() {
1318            return;
1319        }
1320        let mut x = libm::roundf(x0) as i32;
1321        let mut y = libm::roundf(y0) as i32;
1322        let xe = libm::roundf(x1) as i32;
1323        let ye = libm::roundf(y1) as i32;
1324        let dx = (xe - x).abs();
1325        let dy = -(ye - y).abs();
1326        let sx = if x < xe { 1 } else { -1 };
1327        let sy = if y < ye { 1 } else { -1 };
1328        let mut err = dx + dy;
1329        // 上限を設けて、万一の座標異常でも無限ループにしない。
1330        let mut guard = 0i32;
1331        let limit = (self.width as i32 + self.height as i32) * 4 + 16;
1332        loop {
1333            self.blend_pixel(x, y, argb);
1334            if (x == xe && y == ye) || guard > limit {
1335                break;
1336            }
1337            guard += 1;
1338            let e2 = err * 2;
1339            if e2 >= dy {
1340                err += dy;
1341                x += sx;
1342            }
1343            if e2 <= dx {
1344                err += dx;
1345                y += sy;
1346            }
1347        }
1348    }
1349}
1350
1351
1352// ───────────── 2D コンテキストの状態 ─────────────
1353
1354/// `save()`/`restore()` で退避・復帰する描画状態。
1355#[derive(Debug, Clone)]
1356pub struct DrawState {
1357    pub transform: Matrix,
1358    /// 塗り色(ARGB8888)。
1359    pub fill: u32,
1360    /// 塗り色の文字列表現(例: "#000000", "red")。
1361    pub fill_str: alloc::string::String,
1362    /// 線色(ARGB8888)。
1363    pub stroke: u32,
1364    /// 線色の文字列表現。
1365    pub stroke_str: alloc::string::String,
1366    pub line_width: f32,
1367    /// `lineCap`。
1368    pub line_cap: LineCap,
1369    /// `lineJoin`。
1370    pub line_join: LineJoin,
1371    /// `miterLimit`。
1372    pub miter_limit: f32,
1373    /// `setLineDash` のパターン。空なら実線。
1374    pub line_dash: Vec<f32>,
1375    /// `lineDashOffset`。
1376    pub line_dash_offset: f32,
1377    /// クリップ領域。`None` なら全面。
1378    pub clip: Option<alloc::sync::Arc<ClipMask>>,
1379    /// `globalAlpha`(0.0〜1.0)。
1380    pub global_alpha: f32,
1381    /// フォント指定文字列(例: "10px sans-serif")。
1382    pub font_str: alloc::string::String,
1383    /// 水平揃え文字列(例: "start")。
1384    pub text_align_str: alloc::string::String,
1385    /// 垂直ベースライン文字列(例: "alphabetic")。
1386    pub text_baseline_str: alloc::string::String,
1387    /// 画像平滑化有効フラグ(imageSmoothingEnabled)。
1388    pub image_smoothing_enabled: bool,
1389    /// 塗りグラデーション(指定時は単色 fill より優先)。
1390    pub fill_gradient: Option<CanvasGradient>,
1391    /// 線グラデーション。
1392    pub stroke_gradient: Option<CanvasGradient>,
1393    /// 塗りパターン(指定時は単色 fill より優先)。
1394    pub fill_pattern: Option<CanvasPattern>,
1395    /// 線パターン。
1396    pub stroke_pattern: Option<CanvasPattern>,
1397    /// shadowBlur(非負の float。既定 0.0)。
1398    pub shadow_blur: f32,
1399    /// shadowColor(ARGB8888。既定 0x0000_0000 完全透明)。
1400    pub shadow_color: u32,
1401    /// shadowColor の文字列表現(既定 "rgba(0, 0, 0, 0)")。
1402    pub shadow_color_str: alloc::string::String,
1403    /// shadowOffsetX(既定 0.0)。
1404    pub shadow_offset_x: f32,
1405    /// shadowOffsetY(既定 0.0)。
1406    pub shadow_offset_y: f32,
1407    /// CSS filter 文字列(既定 "none")。
1408    pub filter: alloc::string::String,
1409    /// 合成モード(既定 `SourceOver`)。
1410    pub global_composite_operation: CompositeOperation,
1411    /// 合成モードの文字列表現(既定 `"source-over"`)。
1412    pub global_composite_operation_str: alloc::string::String,
1413    /// 書字方向(既定 `Inherit`)。
1414    pub direction: CanvasDirection,
1415    /// 書字方向の文字列表現(既定 `"inherit"`)。
1416    pub direction_str: alloc::string::String,
1417}
1418
1419impl DrawState {
1420    /// 影描画が有効か(アルファ > 0 かつ オフセットまたはぼかしが存在する)。
1421    pub fn has_shadow(&self) -> bool {
1422        let a = (self.shadow_color >> 24) & 0xFF;
1423        a > 0 && (self.shadow_offset_x != 0.0 || self.shadow_offset_y != 0.0 || self.shadow_blur > 0.0)
1424    }
1425
1426    /// 実効的な書字方向を返す(`Inherit` は `Ltr` にフォールバック)。
1427    pub fn effective_direction(&self) -> CanvasDirection {
1428        match self.direction {
1429            CanvasDirection::Rtl => CanvasDirection::Rtl,
1430            _ => CanvasDirection::Ltr,
1431        }
1432    }
1433}
1434
1435impl Default for DrawState {
1436    fn default() -> Self {
1437        DrawState {
1438            transform: Matrix::identity(),
1439            // Canvas の既定は不透明な黒。
1440            fill: 0xFF00_0000,
1441            fill_str: alloc::string::String::from("#000000"),
1442            stroke: 0xFF00_0000,
1443            stroke_str: alloc::string::String::from("#000000"),
1444            line_width: 1.0,
1445            line_cap: LineCap::Butt,
1446            line_join: LineJoin::Miter,
1447            miter_limit: DEFAULT_MITER_LIMIT,
1448            line_dash: Vec::new(),
1449            line_dash_offset: 0.0,
1450            clip: None,
1451            global_alpha: 1.0,
1452            font_str: alloc::string::String::from("10px sans-serif"),
1453            text_align_str: alloc::string::String::from("start"),
1454            text_baseline_str: alloc::string::String::from("alphabetic"),
1455            image_smoothing_enabled: true,
1456            fill_gradient: None,
1457            stroke_gradient: None,
1458            fill_pattern: None,
1459            stroke_pattern: None,
1460            shadow_blur: 0.0,
1461            shadow_color: 0x0000_0000,
1462            shadow_color_str: alloc::string::String::from("rgba(0, 0, 0, 0)"),
1463            shadow_offset_x: 0.0,
1464            shadow_offset_y: 0.0,
1465            filter: alloc::string::String::from("none"),
1466            global_composite_operation: CompositeOperation::SourceOver,
1467            global_composite_operation_str: alloc::string::String::from("source-over"),
1468            direction: CanvasDirection::Inherit,
1469            direction_str: alloc::string::String::from("inherit"),
1470        }
1471    }
1472}
1473
1474/// 1 つの `<canvas>` に対する 2D コンテキストの全状態。
1475///
1476/// JS 側のオブジェクトは軽いハンドルだけを持ち、実体はこれを指す。
1477/// パスと面はどちらもここに持たせて、描画の途中経過が
1478/// JS オブジェクトの寿命に左右されないようにする。
1479#[derive(Debug)]
1480pub struct Canvas2dContext {
1481    pub surface: Surface,
1482    pub path: PathBuilder,
1483    pub state: DrawState,
1484    /// `save()` の退避スタック。
1485    stack: Vec<DrawState>,
1486}
1487
1488/// `save()` の入れ子上限。
1489///
1490/// 際限なく積むと、壊れた(`restore` を呼ばない)スクリプトで
1491/// ヒープを食い潰す。実用上 32 段もあれば足りる。
1492const MAX_SAVE_DEPTH: usize = 32;
1493
1494impl Canvas2dContext {
1495    pub fn new(width: u32, height: u32) -> Option<Self> {
1496        Some(Canvas2dContext {
1497            surface: Surface::new(width, height)?,
1498            path: PathBuilder::new(),
1499            state: DrawState::default(),
1500            stack: Vec::new(),
1501        })
1502    }
1503
1504    /// 現在の状態を退避する。上限を超えたら黙って無視する
1505    /// (`restore` との対応が崩れるが、落ちるよりはよい)。
1506    pub fn save(&mut self) {
1507        if self.stack.len() >= MAX_SAVE_DEPTH {
1508            return;
1509        }
1510        self.stack.push(self.state.clone());
1511    }
1512
1513    /// 直近の退避状態へ戻す。スタックが空なら何もしない
1514    /// (仕様どおり。`restore` の呼び過ぎはエラーではない)。
1515    pub fn restore(&mut self) {
1516        if let Some(s) = self.stack.pop() {
1517            self.state = s;
1518        }
1519    }
1520
1521    /// `globalAlpha` を適用した色を返す。
1522    ///
1523    /// アルファは掛け算で合成する。`globalAlpha=0.5` の半透明色は
1524    /// さらに薄くなる(仕様どおり)。
1525    pub fn apply_alpha(&self, argb: u32) -> u32 {
1526        let ga = self.state.global_alpha.clamp(0.0, 1.0);
1527        if ga >= 1.0 {
1528            return argb;
1529        }
1530        let a = ((argb >> 24) & 0xFF) as f32 * ga;
1531        let a = libm::roundf(a).clamp(0.0, 255.0) as u32;
1532        (a << 24) | (argb & 0x00FF_FFFF)
1533    }
1534
1535    /// `globalAlpha` を適用した影の色(ARGB8888)を返す。
1536    pub fn shadow_color_argb(&self) -> u32 {
1537        self.apply_alpha(self.state.shadow_color)
1538    }
1539
1540    /// 現在の変換を適用して矩形を塗る。
1541    ///
1542    /// 変換が平行移動と拡大だけなら矩形のまま塗れるが、回転が入ると
1543    /// 軸平行でなくなる。判定を分けず、常にパス経由で塗ることで
1544    /// 回転時も正しくなるようにしている。
1545    pub fn fill_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
1546        self.sync_clip();
1547        let mut p = PathBuilder::new();
1548        p.rect(&self.state.transform, x, y, w, h);
1549        let sub = p.finish();
1550        if self.state.has_shadow() {
1551            let shadow_sub = offset_subpaths(&sub, self.state.shadow_offset_x, self.state.shadow_offset_y);
1552            let s_color = self.shadow_color_argb();
1553            self.surface.fill_path(&shadow_sub, FillRule::NonZero, s_color);
1554        }
1555        if let Some(ref grad) = self.state.fill_gradient {
1556            self.surface.fill_path_gradient(&sub, FillRule::NonZero, grad, self.state.global_alpha.clamp(0.0, 1.0));
1557        } else if let Some(ref pat) = self.state.fill_pattern {
1558            self.surface.fill_path_pattern(&sub, FillRule::NonZero, pat, self.state.global_alpha.clamp(0.0, 1.0));
1559        } else {
1560            let color = self.apply_alpha(self.state.fill);
1561            self.surface.fill_path(&sub, FillRule::NonZero, color);
1562        }
1563    }
1564
1565    /// 矩形を透明で消す。`globalAlpha` の影響は受けない(仕様どおり)。
1566    ///
1567    /// 回転が入っていると軸平行に消せないため、パスの外接矩形を消す。
1568    /// 厳密ではないが、`clearRect` に回転を掛ける使い方は稀。
1569    pub fn clear_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
1570        self.sync_clip();
1571        let m = &self.state.transform;
1572        let pts = [
1573            m.apply(x, y),
1574            m.apply(x + w, y),
1575            m.apply(x + w, y + h),
1576            m.apply(x, y + h),
1577        ];
1578        let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
1579        for (px, py) in pts {
1580            if !px.is_finite() || !py.is_finite() {
1581                return;
1582            }
1583            x0 = x0.min(px);
1584            y0 = y0.min(py);
1585            x1 = x1.max(px);
1586            y1 = y1.max(py);
1587        }
1588        self.surface.fill_rect(
1589            libm::floorf(x0) as i32,
1590            libm::floorf(y0) as i32,
1591            libm::ceilf(x1 - x0) as i32,
1592            libm::ceilf(y1 - y0) as i32,
1593            0,
1594            true,
1595        );
1596    }
1597
1598    /// 現在のパスを塗る。
1599    pub fn fill(&mut self, rule: FillRule) {
1600        self.sync_clip();
1601        let sub = self.path.finish();
1602        if self.state.has_shadow() {
1603            let shadow_sub = offset_subpaths(&sub, self.state.shadow_offset_x, self.state.shadow_offset_y);
1604            let s_color = self.shadow_color_argb();
1605            self.surface.fill_path(&shadow_sub, rule, s_color);
1606        }
1607        if let Some(ref grad) = self.state.fill_gradient {
1608            self.surface.fill_path_gradient(&sub, rule, grad, self.state.global_alpha.clamp(0.0, 1.0));
1609        } else if let Some(ref pat) = self.state.fill_pattern {
1610            self.surface.fill_path_pattern(&sub, rule, pat, self.state.global_alpha.clamp(0.0, 1.0));
1611        } else {
1612            let color = self.apply_alpha(self.state.fill);
1613            self.surface.fill_path(&sub, rule, color);
1614        }
1615    }
1616
1617    /// サブパス群を指定された描画状態(線幅、キャップ、ジョイント、ダッシュ、影、グラデーション、パターン)に従って線描する内部ヘルパー。
1618    fn stroke_subpaths_internal(&mut self, subpaths: &[SubPath]) {
1619        self.sync_clip();
1620        let dashed = self.apply_dash(subpaths);
1621        let lw = self.state.line_width;
1622        if !lw.is_finite() || lw <= 0.0 {
1623            return;
1624        }
1625        let (cap, join, limit) = (self.state.line_cap, self.state.line_join, self.state.miter_limit);
1626        let has_shadow = self.state.has_shadow();
1627        let shadow_offset_x = self.state.shadow_offset_x;
1628        let shadow_offset_y = self.state.shadow_offset_y;
1629        let s_color = if has_shadow { self.shadow_color_argb() } else { 0 };
1630        let alpha = self.state.global_alpha.clamp(0.0, 1.0);
1631        let stroke_color = self.apply_alpha(self.state.stroke);
1632        let stroke_grad = self.state.stroke_gradient.clone();
1633        let stroke_pat = self.state.stroke_pattern.clone();
1634
1635        if has_shadow {
1636            let shadow_sub = offset_subpaths(&dashed, shadow_offset_x, shadow_offset_y);
1637            self.surface.stroke_path_styled(&shadow_sub, s_color, lw, cap, join, limit);
1638        }
1639        if let Some(ref grad) = stroke_grad {
1640            let outline = stroke_to_outline(&dashed, lw, cap, join, limit);
1641            self.surface.fill_path_gradient(&outline, FillRule::NonZero, grad, alpha);
1642        } else if let Some(ref pat) = stroke_pat {
1643            let outline = stroke_to_outline(&dashed, lw, cap, join, limit);
1644            self.surface.fill_path_pattern(&outline, FillRule::NonZero, pat, alpha);
1645        } else {
1646            self.surface.stroke_path_styled(&dashed, stroke_color, lw, cap, join, limit);
1647        }
1648    }
1649
1650    /// 現在のパスを線描する。
1651    pub fn stroke(&mut self) {
1652        let sub = self.path.finish();
1653        self.stroke_subpaths_internal(&sub);
1654    }
1655
1656    /// 矩形を線描する(現在のパスは変更しない)。
1657    pub fn stroke_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
1658        let mut p = PathBuilder::new();
1659        p.rect(&self.state.transform, x, y, w, h);
1660        let sub = p.finish();
1661        self.stroke_subpaths_internal(&sub);
1662    }
1663
1664    /// 現在の変換へ平行移動を積む。
1665    pub fn translate(&mut self, tx: f32, ty: f32) {
1666        self.state.transform = self.state.transform.multiply(&Matrix::translate(tx, ty));
1667    }
1668
1669    /// 現在の変換へ拡大縮小を積む。
1670    pub fn scale(&mut self, sx: f32, sy: f32) {
1671        self.state.transform = self.state.transform.multiply(&Matrix::scale(sx, sy));
1672    }
1673
1674    /// 現在の変換へ回転を積む。
1675    pub fn rotate(&mut self, rad: f32) {
1676        self.state.transform = self.state.transform.multiply(&Matrix::rotate(rad));
1677    }
1678
1679    /// 変換行列を直接置き換える(`setTransform`)。
1680    pub fn set_transform(&mut self, m: Matrix) {
1681        self.state.transform = m;
1682    }
1683
1684    /// 変換を単位行列へ戻す(`resetTransform`)。
1685    pub fn reset_transform(&mut self) {
1686        self.state.transform = Matrix::identity();
1687    }
1688
1689    pub fn begin_path(&mut self) {
1690        self.path.begin_path();
1691    }
1692
1693    pub fn close_path(&mut self) {
1694        self.path.close_path();
1695    }
1696
1697    pub fn move_to(&mut self, x: f32, y: f32) {
1698        let m = self.state.transform;
1699        self.path.move_to(&m, x, y);
1700    }
1701
1702    pub fn line_to(&mut self, x: f32, y: f32) {
1703        let m = self.state.transform;
1704        self.path.line_to(&m, x, y);
1705    }
1706
1707    pub fn arc_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, radius: f32) {
1708        let m = self.state.transform;
1709        self.path.arc_to(&m, x1, y1, x2, y2, radius);
1710    }
1711}
1712
1713
1714// ───────────── コンテキスト登録表 ─────────────
1715
1716/// `<canvas>` ごとの 2D コンテキストを id で保持する表。
1717///
1718/// JS 側のオブジェクトは `HostRef { class: HOST_CANVAS2D, id }`(`id` はこの表の id。
1719/// JS 側への配線は未着手)という識別子だけを持ち、実体はここにある。JS の値へ Rust の可変状態を
1720/// 直接埋めると借用と寿命の扱いが複雑になるため、既存の DOM プロキシ(style/classList)と同じ
1721/// 「識別子で引く」流儀に合わせた(2026-11-19 手順 7 で、文字列のタグから `HostRef` へ替える方針にした)。
1722static CONTEXTS: spin::Mutex<alloc::collections::BTreeMap<u32, Canvas2dContext>> =
1723    spin::Mutex::new(alloc::collections::BTreeMap::new());
1724
1725/// 次に払い出す id。
1726static NEXT_ID: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(1);
1727
1728/// 同時に保持するコンテキスト数の上限。
1729///
1730/// ページ遷移のたびに増え続けると、面(最大 64MB)が積み上がって
1731/// ヒープを食い潰す。上限を超えたら最も古い id から捨てる。
1732const MAX_CONTEXTS: usize = 8;
1733
1734/// 新しいコンテキストを作り、その id を返す。
1735///
1736/// 面が確保できない(サイズが不正・過大)場合は `None`。
1737pub fn create_context(width: u32, height: u32) -> Option<u32> {
1738    let ctx = Canvas2dContext::new(width, height)?;
1739    let id = NEXT_ID.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
1740    let mut map = CONTEXTS.lock();
1741    // 上限を超えたら最も古い(id が小さい)ものから捨てる。
1742    while map.len() >= MAX_CONTEXTS {
1743        let Some(&oldest) = map.keys().next() else {
1744            break;
1745        };
1746        map.remove(&oldest);
1747    }
1748    map.insert(id, ctx);
1749    Some(id)
1750}
1751
1752/// id のコンテキストへ可変アクセスする。
1753///
1754/// 見つからなければ `f` を呼ばず `None` を返す(ページ遷移で
1755/// 破棄された後の呼び出しは黙って無視する)。
1756pub fn with_context<R>(id: u32, f: impl FnOnce(&mut Canvas2dContext) -> R) -> Option<R> {
1757    let mut map = CONTEXTS.lock();
1758    map.get_mut(&id).map(f)
1759}
1760
1761/// 保持している全コンテキストを破棄する(ページ遷移時に呼ぶ)。
1762pub fn clear_contexts() {
1763    CONTEXTS.lock().clear();
1764}
1765
1766impl PathBuilder {
1767    /// 楕円弧(`ellipse`)。
1768    ///
1769    /// `arc` の一般形で、x/y に別々の半径と、楕円自体の回転を持つ。
1770    /// 単位円上の点を「半径で伸ばす → 回転する → 中心へ移す」順で写す。
1771    /// この順序を取り違えると、回転した楕円が歪む。
1772    #[allow(clippy::too_many_arguments)]
1773    pub fn ellipse(
1774        &mut self,
1775        m: &Matrix,
1776        cx: f32,
1777        cy: f32,
1778        rx: f32,
1779        ry: f32,
1780        rotation: f32,
1781        start: f32,
1782        end: f32,
1783        anticlockwise: bool,
1784    ) {
1785        if !rx.is_finite()
1786            || !ry.is_finite()
1787            || rx < 0.0
1788            || ry < 0.0
1789            || !start.is_finite()
1790            || !end.is_finite()
1791            || !rotation.is_finite()
1792        {
1793            return;
1794        }
1795        let sweep = normalize_sweep(start, end, anticlockwise);
1796        let steps = arc_steps(sweep);
1797        let (rs, rc) = (libm::sinf(rotation), libm::cosf(rotation));
1798        for i in 0..=steps {
1799            let t = i as f32 / steps as f32;
1800            let ang = start + sweep * t;
1801            // 単位円 → 半径で伸ばす
1802            let ux = rx * libm::cosf(ang);
1803            let uy = ry * libm::sinf(ang);
1804            // → 楕円の回転 → 中心へ移す
1805            let px = cx + ux * rc - uy * rs;
1806            let py = cy + ux * rs + uy * rc;
1807            if i == 0 && self.current.is_none() {
1808                self.move_to(m, px, py);
1809            } else {
1810                self.line_to(m, px, py);
1811            }
1812        }
1813    }
1814
1815    /// 角丸矩形(`roundRect`)。
1816    ///
1817    /// 半径は 4 隅ぶん(左上・右上・右下・左下)。
1818    /// 半径の合計が辺の長さを超える場合は、仕様どおり**比率を保ったまま
1819    /// 縮小**する。しないと角が重なって図形が破綻する。
1820    #[allow(clippy::too_many_arguments)]
1821    pub fn round_rect(
1822        &mut self,
1823        m: &Matrix,
1824        x: f32,
1825        y: f32,
1826        w: f32,
1827        h: f32,
1828        radii: [f32; 4],
1829    ) {
1830        if !w.is_finite() || !h.is_finite() || w == 0.0 || h == 0.0 {
1831            return;
1832        }
1833        // 負の幅・高さは反対側から描く(仕様)。
1834        let (x, w) = if w < 0.0 { (x + w, -w) } else { (x, w) };
1835        let (y, h) = if h < 0.0 { (y + h, -h) } else { (y, h) };
1836
1837        let mut r = [0.0f32; 4];
1838        for (i, v) in radii.iter().enumerate() {
1839            r[i] = if v.is_finite() && *v > 0.0 { *v } else { 0.0 };
1840        }
1841        // 辺ごとに「両端の半径の和」が辺長を超えないよう縮小率を求める。
1842        let mut scale = 1.0f32;
1843        let pairs = [
1844            (r[0] + r[1], w), // 上辺: 左上 + 右上
1845            (r[2] + r[3], w), // 下辺: 右下 + 左下
1846            (r[1] + r[2], h), // 右辺: 右上 + 右下
1847            (r[3] + r[0], h), // 左辺: 左下 + 左上
1848        ];
1849        for (sum, len) in pairs {
1850            if sum > 0.0 && sum > len {
1851                scale = scale.min(len / sum);
1852            }
1853        }
1854        for v in r.iter_mut() {
1855            *v *= scale;
1856        }
1857
1858        let half_pi = core::f32::consts::PI / 2.0;
1859        let pi = core::f32::consts::PI;
1860        self.flush();
1861        // 左上から時計回りに、直線 → 角の 1/4 円 を繰り返す。
1862        self.move_to(m, x + r[0], y);
1863        self.line_to(m, x + w - r[1], y);
1864        if r[1] > 0.0 {
1865            self.arc(m, x + w - r[1], y + r[1], r[1], -half_pi, 0.0, false);
1866        }
1867        self.line_to(m, x + w, y + h - r[2]);
1868        if r[2] > 0.0 {
1869            self.arc(m, x + w - r[2], y + h - r[2], r[2], 0.0, half_pi, false);
1870        }
1871        self.line_to(m, x + r[3], y + h);
1872        if r[3] > 0.0 {
1873            self.arc(m, x + r[3], y + h - r[3], r[3], half_pi, pi, false);
1874        }
1875        self.line_to(m, x, y + r[0]);
1876        if r[0] > 0.0 {
1877            self.arc(m, x + r[0], y + r[0], r[0], pi, pi + half_pi, false);
1878        }
1879        self.close_path();
1880    }
1881}
1882
1883impl Surface {
1884    /// 線幅つきで折れ線を描く。
1885    ///
1886    /// 各線分を「線幅ぶんの太さを持つ四角形」に展開して塗る。
1887    /// 線端・線結合(`lineCap`/`lineJoin`)は未対応で、
1888    /// 結合部には円を置いて隙間を埋める(`round` 相当の近似)。
1889    ///
1890    /// # なぜ四角形へ展開するか
1891    ///
1892    /// Bresenham を平行にずらして何本も引く方法は、斜線で
1893    /// 太さが不均一になる(見た目が痩せる)。線分に垂直な方向へ
1894    /// 幅の半分ずつ広げた四角形を塗れば、角度によらず一定の太さになる。
1895    /// 線幅つきで折れ線を描く(線端 `Butt`・結合 `Round`)。
1896    ///
1897    /// 線端・結合を選ぶ場合は `stroke_path_styled` を使う。
1898    pub fn stroke_path_width(&mut self, subpaths: &[SubPath], argb: u32, width: f32) {
1899        self.stroke_path_styled(
1900            subpaths,
1901            argb,
1902            width,
1903            LineCap::Butt,
1904            LineJoin::Round,
1905            DEFAULT_MITER_LIMIT,
1906        );
1907    }
1908
1909    /// 中心 (cx, cy)・半径 r の円を塗る(線の結合部を埋めるのに使う)。
1910    fn fill_disc(&mut self, cx: f32, cy: f32, r: f32, argb: u32) {
1911        if !cx.is_finite() || !cy.is_finite() || !r.is_finite() || r <= 0.0 {
1912            return;
1913        }
1914        let y0 = (libm::floorf(cy - r) as i32).max(0);
1915        let y1 = (libm::ceilf(cy + r) as i32).min(self.height as i32);
1916        let r2 = r * r;
1917        for py in y0..y1 {
1918            let dy = py as f32 + 0.5 - cy;
1919            let d = r2 - dy * dy;
1920            if d < 0.0 {
1921                continue;
1922            }
1923            let dx = libm::sqrtf(d);
1924            let x0 = (libm::roundf(cx - dx) as i32).max(0);
1925            let x1 = (libm::roundf(cx + dx) as i32).min(self.width as i32);
1926            for px in x0..x1 {
1927                self.blend_pixel(px, py, argb);
1928            }
1929        }
1930    }
1931}
1932
1933impl Canvas2dContext {
1934    /// 現在のパスを、`lineWidth` を反映して線描する。
1935    pub fn stroke_with_width(&mut self) {
1936        self.stroke();
1937    }
1938}
1939
1940/// 線端の形状(`lineCap`)。
1941#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1942pub enum LineCap {
1943    /// 端点で切り落とす(既定)。
1944    Butt,
1945    /// 端点に半円を付ける。
1946    Round,
1947    /// 端点から線幅の半分だけ四角く伸ばす。
1948    Square,
1949}
1950
1951/// 線の結合形状(`lineJoin`)。
1952#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1953pub enum LineJoin {
1954    /// 外側の辺を延長して尖らせる(既定)。
1955    Miter,
1956    /// 結合点に円を置く。
1957    Round,
1958    /// 外側を直線で切り落とす。
1959    Bevel,
1960}
1961
1962/// `miterLimit` の既定値。仕様どおり 10。
1963pub const DEFAULT_MITER_LIMIT: f32 = 10.0;
1964
1965pub fn parse_line_cap(s: &str) -> Option<LineCap> {
1966    match s.trim() {
1967        "butt" => Some(LineCap::Butt),
1968        "round" => Some(LineCap::Round),
1969        "square" => Some(LineCap::Square),
1970        _ => None,
1971    }
1972}
1973
1974pub fn parse_line_join(s: &str) -> Option<LineJoin> {
1975    match s.trim() {
1976        "miter" => Some(LineJoin::Miter),
1977        "round" => Some(LineJoin::Round),
1978        "bevel" => Some(LineJoin::Bevel),
1979        _ => None,
1980    }
1981}
1982
1983/// 合成モード(`globalCompositeOperation` / Porter-Duff)。
1984#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1985pub enum CompositeOperation {
1986    SourceOver,
1987    SourceIn,
1988    SourceOut,
1989    SourceAtop,
1990    DestinationOver,
1991    DestinationIn,
1992    DestinationOut,
1993    DestinationAtop,
1994    Lighter,
1995    Copy,
1996    Xor,
1997}
1998
1999pub fn parse_composite_operation(s: &str) -> Option<CompositeOperation> {
2000    let t = s.trim();
2001    if t.eq_ignore_ascii_case("source-over") {
2002        Some(CompositeOperation::SourceOver)
2003    } else if t.eq_ignore_ascii_case("source-in") {
2004        Some(CompositeOperation::SourceIn)
2005    } else if t.eq_ignore_ascii_case("source-out") {
2006        Some(CompositeOperation::SourceOut)
2007    } else if t.eq_ignore_ascii_case("source-atop") {
2008        Some(CompositeOperation::SourceAtop)
2009    } else if t.eq_ignore_ascii_case("destination-over") {
2010        Some(CompositeOperation::DestinationOver)
2011    } else if t.eq_ignore_ascii_case("destination-in") {
2012        Some(CompositeOperation::DestinationIn)
2013    } else if t.eq_ignore_ascii_case("destination-out") {
2014        Some(CompositeOperation::DestinationOut)
2015    } else if t.eq_ignore_ascii_case("destination-atop") {
2016        Some(CompositeOperation::DestinationAtop)
2017    } else if t.eq_ignore_ascii_case("lighter") || t.eq_ignore_ascii_case("plus-lighter") {
2018        Some(CompositeOperation::Lighter)
2019    } else if t.eq_ignore_ascii_case("copy") {
2020        Some(CompositeOperation::Copy)
2021    } else if t.eq_ignore_ascii_case("xor") {
2022        Some(CompositeOperation::Xor)
2023    } else {
2024        None
2025    }
2026}
2027
2028/// 2 直線の交点。`p1` を通り向き `d1` の直線と、`p2` を通り向き `d2` の直線。
2029///
2030/// 平行(または反転)なら交点は無いので `None`。miter を延ばす先を
2031/// 求めるのに使い、`None` のときは bevel へ落とす。
2032pub fn line_intersection(
2033    p1: (f32, f32),
2034    d1: (f32, f32),
2035    p2: (f32, f32),
2036    d2: (f32, f32),
2037) -> Option<(f32, f32)> {
2038    let den = d1.0 * d2.1 - d1.1 * d2.0;
2039    // ほぼ平行なら交点が無限遠へ飛ぶ。閾値は目視で差が出ない範囲。
2040    if libm::fabsf(den) < 1e-6 {
2041        return None;
2042    }
2043    let t = ((p2.0 - p1.0) * d2.1 - (p2.1 - p1.1) * d2.0) / den;
2044    let x = p1.0 + d1.0 * t;
2045    let y = p1.1 + d1.1 * t;
2046    if !x.is_finite() || !y.is_finite() {
2047        return None;
2048    }
2049    Some((x, y))
2050}
2051
2052impl Surface {
2053    /// 線端・結合を指定して折れ線を描く。
2054    ///
2055    /// `stroke_path_width` は端 `Butt`・結合 `Round` でこれを呼ぶ。
2056    pub fn stroke_path_styled(
2057        &mut self,
2058        subpaths: &[SubPath],
2059        argb: u32,
2060        width: f32,
2061        cap: LineCap,
2062        join: LineJoin,
2063        miter_limit: f32,
2064    ) {
2065        mark_canvas_dirty();
2066        // 1 以下は従来の 1px 線で足りる(見た目も速度も有利)。
2067        if !width.is_finite() || width <= 1.0 {
2068            self.stroke_path(subpaths, argb);
2069            return;
2070        }
2071        let half = width / 2.0;
2072        let limit = if miter_limit.is_finite() && miter_limit > 0.0 {
2073            miter_limit
2074        } else {
2075            DEFAULT_MITER_LIMIT
2076        };
2077        for sp in subpaths {
2078            let n = sp.points.len();
2079            if n < 2 {
2080                continue;
2081            }
2082            let seg_end = if sp.closed { n } else { n - 1 };
2083
2084            // 各線分を、線分に垂直な方向へ half ずつ広げた四角形へ展開。
2085            for i in 0..seg_end {
2086                let a = sp.points[i];
2087                let b = sp.points[(i + 1) % n];
2088                let Some((dx, dy, len)) = unit_delta(a, b) else {
2089                    continue;
2090                };
2091                // 端が Square のときは、線分の外側へ half だけ伸ばす。
2092                let (mut ax, mut ay) = a;
2093                let (mut bx, mut by) = b;
2094                if cap == LineCap::Square && !sp.closed {
2095                    if i == 0 {
2096                        ax -= dx * half;
2097                        ay -= dy * half;
2098                    }
2099                    if i == seg_end - 1 {
2100                        bx += dx * half;
2101                        by += dy * half;
2102                    }
2103                }
2104                let _ = len;
2105                let (nx, ny) = (-dy * half, dx * half);
2106                self.fill_quad(
2107                    (ax + nx, ay + ny),
2108                    (bx + nx, by + ny),
2109                    (bx - nx, by - ny),
2110                    (ax - nx, ay - ny),
2111                    argb,
2112                );
2113            }
2114
2115            // 結合部を埋める。線分の四角形だけでは外側の角が欠ける。
2116            let joint_from = if sp.closed { 0 } else { 1 };
2117            let joint_to = if sp.closed { n } else { n - 1 };
2118            for j in joint_from..joint_to {
2119                let prev = sp.points[(j + n - 1) % n];
2120                let cur = sp.points[j];
2121                let next = sp.points[(j + 1) % n];
2122                self.fill_joint(prev, cur, next, half, argb, join, limit);
2123            }
2124
2125            // 端が Round なら両端に半円(円で近似)を置く。
2126            if cap == LineCap::Round && !sp.closed {
2127                let first = sp.points[0];
2128                let last = sp.points[n - 1];
2129                self.fill_disc(first.0, first.1, half, argb);
2130                self.fill_disc(last.0, last.1, half, argb);
2131            }
2132        }
2133    }
2134
2135    /// 結合部 1 箇所を埋める。
2136    #[allow(clippy::too_many_arguments)]
2137    fn fill_joint(
2138        &mut self,
2139        prev: (f32, f32),
2140        cur: (f32, f32),
2141        next: (f32, f32),
2142        half: f32,
2143        argb: u32,
2144        join: LineJoin,
2145        limit: f32,
2146    ) {
2147        if join == LineJoin::Round {
2148            self.fill_disc(cur.0, cur.1, half, argb);
2149            return;
2150        }
2151        let (Some((d1x, d1y, _)), Some((d2x, d2y, _))) =
2152            (unit_delta(prev, cur), unit_delta(cur, next))
2153        else {
2154            return;
2155        };
2156        // 曲がる向き。外側だけを埋めれば足りる(内側は線分の四角形が覆う)。
2157        let cross = d1x * d2y - d1y * d2x;
2158        if libm::fabsf(cross) < 1e-6 {
2159            // まっすぐ、または折り返し。角は生じないので何もしない。
2160            return;
2161        }
2162        // 左法線を (-dy, dx) とすると、左折(cross>0)では外側は右。
2163        let s = if cross > 0.0 { -1.0f32 } else { 1.0f32 };
2164        let p1 = (cur.0 + s * -d1y * half, cur.1 + s * d1x * half);
2165        let p2 = (cur.0 + s * -d2y * half, cur.1 + s * d2x * half);
2166
2167        if join == LineJoin::Miter {
2168            if let Some(mp) = line_intersection(p1, (d1x, d1y), p2, (d2x, d2y)) {
2169                let (mx, my) = (mp.0 - cur.0, mp.1 - cur.1);
2170                let miter_len = libm::sqrtf(mx * mx + my * my);
2171                // 鋭角では尖りが際限なく伸びる。仕様どおり
2172                // miterLength/halfWidth が上限を超えたら bevel へ落とす。
2173                if miter_len / half <= limit {
2174                    self.fill_quad(cur, p1, mp, p2, argb);
2175                    return;
2176                }
2177            }
2178        }
2179        // Bevel(および miter の打ち切り)。外側を直線で結ぶ三角形。
2180        self.fill_tri(cur, p1, p2, argb);
2181    }
2182
2183    fn fill_quad(
2184        &mut self,
2185        a: (f32, f32),
2186        b: (f32, f32),
2187        c: (f32, f32),
2188        d: (f32, f32),
2189        argb: u32,
2190    ) {
2191        for p in [a, b, c, d] {
2192            if !p.0.is_finite() || !p.1.is_finite() {
2193                return;
2194            }
2195        }
2196        let poly = alloc::vec![SubPath {
2197            points: alloc::vec![a, b, c, d],
2198            closed: true,
2199        }];
2200        self.fill_path(&poly, FillRule::NonZero, argb);
2201    }
2202
2203    fn fill_tri(&mut self, a: (f32, f32), b: (f32, f32), c: (f32, f32), argb: u32) {
2204        for p in [a, b, c] {
2205            if !p.0.is_finite() || !p.1.is_finite() {
2206                return;
2207            }
2208        }
2209        let poly = alloc::vec![SubPath {
2210            points: alloc::vec![a, b, c],
2211            closed: true,
2212        }];
2213        self.fill_path(&poly, FillRule::NonZero, argb);
2214    }
2215}
2216
2217/// 多角形の符号付き面積を計算する(画面座標系: Y下向き)。
2218pub fn polygon_signed_area(pts: &[(f32, f32)]) -> f32 {
2219    let n = pts.len();
2220    if n < 3 {
2221        return 0.0;
2222    }
2223    let mut area = 0.0f32;
2224    for i in 0..n {
2225        let (x0, y0) = pts[i];
2226        let (x1, y1) = pts[(i + 1) % n];
2227        area += x0 * y1 - x1 * y0;
2228    }
2229    area * 0.5
2230}
2231
2232fn normalize_convex_poly(mut pts: Vec<(f32, f32)>) -> Option<SubPath> {
2233    for p in &pts {
2234        if !p.0.is_finite() || !p.1.is_finite() {
2235            return None;
2236        }
2237    }
2238    if pts.len() < 3 {
2239        return None;
2240    }
2241    let area = polygon_signed_area(&pts);
2242    if libm::fabsf(area) < 1e-5 {
2243        return None;
2244    }
2245    if area < 0.0 {
2246        pts.reverse();
2247    }
2248    Some(SubPath {
2249        points: pts,
2250        closed: true,
2251    })
2252}
2253
2254fn circle_poly(cx: f32, cy: f32, r: f32) -> Option<SubPath> {
2255    if !cx.is_finite() || !cy.is_finite() || !r.is_finite() || r <= 0.0 {
2256        return None;
2257    }
2258    const SEGMENTS: usize = 16;
2259    let mut pts = Vec::with_capacity(SEGMENTS);
2260    for k in 0..SEGMENTS {
2261        let theta = (k as f32) * (2.0 * core::f32::consts::PI / (SEGMENTS as f32));
2262        let px = cx + r * libm::cosf(theta);
2263        let py = cy + r * libm::sinf(theta);
2264        pts.push((px, py));
2265    }
2266    normalize_convex_poly(pts)
2267}
2268
2269/// パス(折れ線群)を、指定された線幅・端点形状・結合形状に従って
2270/// 閉じたポリゴン(アウトライン)のサブパス群に変換する純粋幾何関数。
2271///
2272/// 全ての出力ポリゴンは同一の巻き方向(正の符号付き面積)に揃えられ、
2273/// `FillRule::NonZero` によるラスタライズ(グラデーション/パターン)で
2274/// 穴や打ち消し合いが生じないように正規化される。
2275pub fn stroke_to_outline(
2276    subpaths: &[SubPath],
2277    width: f32,
2278    cap: LineCap,
2279    join: LineJoin,
2280    miter_limit: f32,
2281) -> Vec<SubPath> {
2282    if !width.is_finite() || width <= 0.0 || subpaths.is_empty() {
2283        return Vec::new();
2284    }
2285    let half = width / 2.0;
2286    let limit = if miter_limit.is_finite() && miter_limit > 0.0 {
2287        miter_limit
2288    } else {
2289        DEFAULT_MITER_LIMIT
2290    };
2291
2292    let mut result = Vec::new();
2293
2294    for sp in subpaths {
2295        let n = sp.points.len();
2296        if n < 2 {
2297            continue;
2298        }
2299        let seg_end = if sp.closed { n } else { n - 1 };
2300
2301        // 各線分の Quad
2302        for i in 0..seg_end {
2303            let a = sp.points[i];
2304            let b = sp.points[(i + 1) % n];
2305            let Some((dx, dy, _)) = unit_delta(a, b) else {
2306                continue;
2307            };
2308            let (mut ax, mut ay) = a;
2309            let (mut bx, mut by) = b;
2310            if cap == LineCap::Square && !sp.closed {
2311                if i == 0 {
2312                    ax -= dx * half;
2313                    ay -= dy * half;
2314                }
2315                if i == seg_end - 1 {
2316                    bx += dx * half;
2317                    by += dy * half;
2318                }
2319            }
2320            let (nx, ny) = (-dy * half, dx * half);
2321            let p0 = (ax + nx, ay + ny);
2322            let p1 = (bx + nx, by + ny);
2323            let p2 = (bx - nx, by - ny);
2324            let p3 = (ax - nx, ay - ny);
2325            if let Some(poly) = normalize_convex_poly(alloc::vec![p0, p1, p2, p3]) {
2326                result.push(poly);
2327            }
2328        }
2329
2330        // 結合部
2331        let joint_from = if sp.closed { 0 } else { 1 };
2332        let joint_to = if sp.closed { n } else { n - 1 };
2333        for j in joint_from..joint_to {
2334            let prev = sp.points[(j + n - 1) % n];
2335            let cur = sp.points[j];
2336            let next = sp.points[(j + 1) % n];
2337
2338            if join == LineJoin::Round {
2339                if let Some(circle) = circle_poly(cur.0, cur.1, half) {
2340                    result.push(circle);
2341                }
2342                continue;
2343            }
2344
2345            let (Some((d1x, d1y, _)), Some((d2x, d2y, _))) =
2346                (unit_delta(prev, cur), unit_delta(cur, next))
2347            else {
2348                continue;
2349            };
2350
2351            let cross = d1x * d2y - d1y * d2x;
2352            if libm::fabsf(cross) < 1e-6 {
2353                continue;
2354            }
2355            let s = if cross > 0.0 { -1.0f32 } else { 1.0f32 };
2356            let p1 = (cur.0 + s * -d1y * half, cur.1 + s * d1x * half);
2357            let p2 = (cur.0 + s * -d2y * half, cur.1 + s * d2x * half);
2358
2359            if join == LineJoin::Miter {
2360                if let Some(mp) = line_intersection(p1, (d1x, d1y), p2, (d2x, d2y)) {
2361                    let (mx, my) = (mp.0 - cur.0, mp.1 - cur.1);
2362                    let miter_len = libm::sqrtf(mx * mx + my * my);
2363                    if miter_len / half <= limit {
2364                        if let Some(poly) = normalize_convex_poly(alloc::vec![cur, p1, mp, p2]) {
2365                            result.push(poly);
2366                            continue;
2367                        }
2368                    }
2369                }
2370            }
2371            // Bevel(または miter limit 超過時)
2372            if let Some(poly) = normalize_convex_poly(alloc::vec![cur, p1, p2]) {
2373                result.push(poly);
2374            }
2375        }
2376
2377        // Round 端点
2378        if cap == LineCap::Round && !sp.closed {
2379            let first = sp.points[0];
2380            let last = sp.points[n - 1];
2381            if let Some(circle) = circle_poly(first.0, first.1, half) {
2382                result.push(circle);
2383            }
2384            if let Some(circle) = circle_poly(last.0, last.1, half) {
2385                result.push(circle);
2386            }
2387        }
2388    }
2389
2390    result
2391}
2392
2393/// `a` から `b` への単位ベクトルと距離。長さが 0 なら `None`。
2394pub fn unit_delta(a: (f32, f32), b: (f32, f32)) -> Option<(f32, f32, f32)> {
2395    let (dx, dy) = (b.0 - a.0, b.1 - a.1);
2396    if !dx.is_finite() || !dy.is_finite() {
2397        return None;
2398    }
2399    let len = libm::sqrtf(dx * dx + dy * dy);
2400    if len < 1e-6 {
2401        return None;
2402    }
2403    Some((dx / len, dy / len, len))
2404}
2405
2406/// JS が canvas へ描いたことを示す旗(エッジトリガ再描画用)。
2407///
2408/// canvas への描画はバッキングストア(`Surface`)を書き換えるだけで、
2409/// 画面には出ない。以前は「他の理由で再描画が起きたとき」にだけ
2410/// ついでに反映されていたため、JS が描いても画面が変わらないことがあった。
2411///
2412/// 立てっぱなしにすると毎フレーム全画面を描き直して画面が波打つので、
2413/// 画像完了(`image_results_ready`)と同じく**変化があった一度だけ**
2414/// 再描画させる。描画側が `take_canvas_dirty` で降ろす。
2415static CANVAS_DIRTY: core::sync::atomic::AtomicBool =
2416    core::sync::atomic::AtomicBool::new(false);
2417
2418/// 画素が変わったことを記録する。`Surface` の塗り口から呼ぶ。
2419pub fn mark_canvas_dirty() {
2420    CANVAS_DIRTY.store(true, core::sync::atomic::Ordering::Relaxed);
2421}
2422
2423/// 変化があったかを見る(降ろさない)。再描画するかの判断に使う。
2424pub fn canvas_dirty() -> bool {
2425    CANVAS_DIRTY.load(core::sync::atomic::Ordering::Relaxed)
2426}
2427
2428/// 変化があったかを見て、同時に降ろす。描画を始める側から呼ぶ。
2429pub fn take_canvas_dirty() -> bool {
2430    CANVAS_DIRTY.swap(false, core::sync::atomic::Ordering::Relaxed)
2431}
2432
2433/// 破線のパターンを正規化する(`setLineDash` の引数検査)。
2434///
2435/// 仕様では、負の値や非有限が混じるパターンは**まるごと捨てる**
2436/// (一部だけ直すのではない)。奇数個なら 2 周ぶんに複製して偶数個にする。
2437/// 全部 0 のパターンは「破線なし」と同じ扱い。
2438pub fn normalize_dash(pattern: &[f32]) -> Option<Vec<f32>> {
2439    if pattern.is_empty() {
2440        return None;
2441    }
2442    for v in pattern {
2443        if !v.is_finite() || *v < 0.0 {
2444            return None;
2445        }
2446    }
2447    if pattern.iter().all(|v| *v == 0.0) {
2448        return None;
2449    }
2450    let mut out: Vec<f32> = pattern.to_vec();
2451    // 奇数個なら繰り返して偶数個にする(仕様)。
2452    if out.len() % 2 == 1 {
2453        let dup = out.clone();
2454        out.extend(dup);
2455    }
2456    Some(out)
2457}
2458
2459/// 折れ線を破線に切り分ける。
2460///
2461/// `pattern` は「描く長さ・空ける長さ」の交互。`offset` はパターンの
2462/// 開始位置をずらす量(`lineDashOffset`)。戻り値は描く区間だけを集めた
2463/// 開いた折れ線の並びで、そのまま `stroke_path_styled` へ渡せる。
2464///
2465/// 線分の途中でパターンが切り替わるので、線分を長さで分割しながら進む。
2466pub fn dash_subpaths(subpaths: &[SubPath], pattern: &[f32], offset: f32) -> Vec<SubPath> {
2467    let Some(pat) = normalize_dash(pattern) else {
2468        return subpaths.to_vec();
2469    };
2470    let total: f32 = pat.iter().sum();
2471    if total <= 0.0 {
2472        return subpaths.to_vec();
2473    }
2474    let mut out: Vec<SubPath> = Vec::new();
2475    for sp in subpaths {
2476        let n = sp.points.len();
2477        if n < 2 {
2478            continue;
2479        }
2480        // パターン内の位置。offset は仕様どおり周期で巻き戻す。
2481        let mut phase = if offset.is_finite() {
2482            let m = libm::fmodf(offset, total);
2483            if m < 0.0 {
2484                m + total
2485            } else {
2486                m
2487            }
2488        } else {
2489            0.0
2490        };
2491        // phase がどの区間にいるか(偶数番が「描く」)。
2492        let mut idx = 0usize;
2493        while phase >= pat[idx] {
2494            phase -= pat[idx];
2495            idx = (idx + 1) % pat.len();
2496        }
2497        let mut drawing = idx.is_multiple_of(2);
2498        let mut cur: Vec<(f32, f32)> = Vec::new();
2499        if drawing {
2500            cur.push(sp.points[0]);
2501        }
2502
2503        let seg_end = if sp.closed { n } else { n - 1 };
2504        for i in 0..seg_end {
2505            let a = sp.points[i];
2506            let b = sp.points[(i + 1) % n];
2507            let Some((dx, dy, len)) = unit_delta(a, b) else {
2508                continue;
2509            };
2510            let mut travelled = 0.0f32;
2511            while travelled < len {
2512                // この区間の残り長。
2513                let remain = pat[idx] - phase;
2514                let step = remain.min(len - travelled);
2515                travelled += step;
2516                phase += step;
2517                let p = (a.0 + dx * travelled, a.1 + dy * travelled);
2518                if phase >= pat[idx] - 1e-6 {
2519                    // 区間の切り替わり。描いていたなら、ここで区切る。
2520                    if drawing {
2521                        cur.push(p);
2522                        if cur.len() >= 2 {
2523                            out.push(SubPath {
2524                                points: core::mem::take(&mut cur),
2525                                closed: false,
2526                            });
2527                        } else {
2528                            cur.clear();
2529                        }
2530                    } else {
2531                        cur.clear();
2532                        cur.push(p);
2533                    }
2534                    phase = 0.0;
2535                    idx = (idx + 1) % pat.len();
2536                    drawing = !drawing;
2537                } else if drawing {
2538                    // 線分の終わりで、まだ同じ区間の途中。
2539                    cur.push(p);
2540                }
2541            }
2542        }
2543        if drawing && cur.len() >= 2 {
2544            out.push(SubPath {
2545                points: cur,
2546                closed: false,
2547            });
2548        }
2549    }
2550    out
2551}
2552
2553impl Canvas2dContext {
2554    /// 現在の破線設定をパスへ適用する。実線ならそのまま返す。
2555    pub fn apply_dash(&self, subpaths: &[SubPath]) -> Vec<SubPath> {
2556        if self.state.line_dash.is_empty() {
2557            return subpaths.to_vec();
2558        }
2559        dash_subpaths(subpaths, &self.state.line_dash, self.state.line_dash_offset)
2560    }
2561
2562    /// 現在のコンテキストの線描状態(lineWidth, lineCap, lineJoin, miterLimit, lineDash)を
2563    /// 反映して、指定された座標 (x, y) がストローク領域内にあるかを判定する。
2564    pub fn is_point_in_stroke(&self, subpaths: &[SubPath], x: f32, y: f32) -> bool {
2565        let dashed = self.apply_dash(subpaths);
2566        let outline = stroke_to_outline(
2567            &dashed,
2568            self.state.line_width,
2569            self.state.line_cap,
2570            self.state.line_join,
2571            self.state.miter_limit,
2572        );
2573        is_point_in_path(&outline, x, y, FillRule::NonZero)
2574    }
2575}
2576
2577// ───────────── クリップ領域 ─────────────
2578
2579/// クリップ領域(`clip()`)。画素ごとに「描いてよいか」を持つ。
2580///
2581/// 走査線ベースの塗りに合わせて、パスをその場でラスタライズして持つ。
2582/// 領域を式のまま持つと、交差のたびに判定が複雑になっていく。
2583#[derive(Debug, Clone)]
2584pub struct ClipMask {
2585    pub width: u32,
2586    pub height: u32,
2587    /// `true` の画素だけ描ける。長さは `width * height`。
2588    pub bits: Vec<bool>,
2589}
2590
2591impl ClipMask {
2592    /// パスからクリップ領域を作る。塗りと同じ走査線・同じ巻き数規則を使う。
2593    ///
2594    /// 塗りとずれた判定をすると、クリップの縁に 1px の隙間や food が出る。
2595    pub fn from_path(width: u32, height: u32, subpaths: &[SubPath], rule: FillRule) -> ClipMask {
2596        let mut bits = alloc::vec![false; (width as usize) * (height as usize)];
2597        for y in 0..height {
2598            // 塗りと同じくピクセル中心で判定する。
2599            let spans = scanline_spans(subpaths, y as f32 + 0.5, rule);
2600            for (x0, x1) in spans {
2601                let a = (libm::ceilf(x0 - 0.5) as i32).max(0);
2602                let b = (libm::ceilf(x1 - 0.5) as i32).min(width as i32);
2603                for x in a..b {
2604                    bits[y as usize * width as usize + x as usize] = true;
2605                }
2606            }
2607        }
2608        ClipMask {
2609            width,
2610            height,
2611            bits,
2612        }
2613    }
2614
2615    /// 2 つのクリップ領域の交わり。`clip()` は既存の領域を**狭める**だけで、
2616    /// 広げることはできない(仕様)。
2617    pub fn intersect(&self, other: &ClipMask) -> ClipMask {
2618        if self.width != other.width || self.height != other.height {
2619            // 大きさが食い違うことは無い想定。安全側(狭い方)へ倒す。
2620            return self.clone();
2621        }
2622        let bits = self
2623            .bits
2624            .iter()
2625            .zip(other.bits.iter())
2626            .map(|(a, b)| *a && *b)
2627            .collect();
2628        ClipMask {
2629            width: self.width,
2630            height: self.height,
2631            bits,
2632        }
2633    }
2634
2635    /// その画素に描いてよいか。範囲外は描けない。
2636    pub fn allows(&self, x: i32, y: i32) -> bool {
2637        if x < 0 || y < 0 || x as u32 >= self.width || y as u32 >= self.height {
2638            return false;
2639        }
2640        self.bits[y as usize * self.width as usize + x as usize]
2641    }
2642}
2643
2644impl Canvas2dContext {
2645    /// 現在のパスでクリップ領域を狭める(`clip()`)。
2646    ///
2647    /// `save`/`restore` で元に戻る。状態を複製するだけで復帰できるよう
2648    /// `Rc` で共有しており、色と違って**正しく戻せる**。
2649    pub fn clip(&mut self, rule: FillRule) {
2650        let sub = self.path.finish();
2651        if sub.is_empty() {
2652            return;
2653        }
2654        let mask = ClipMask::from_path(self.surface.width, self.surface.height, &sub, rule);
2655        let merged = match &self.state.clip {
2656            Some(prev) => prev.intersect(&mask),
2657            None => mask,
2658        };
2659        self.state.clip = Some(alloc::sync::Arc::new(merged));
2660    }
2661
2662    /// 描画前に、現在のクリップ領域および合成モードを `Surface` へ渡す。
2663    pub fn sync_clip(&mut self) {
2664        self.surface.clip = self.state.clip.clone();
2665        self.surface.composite_op = self.state.global_composite_operation;
2666    }
2667}
2668
2669// ───────────── ImageData ─────────────
2670
2671/// `Surface` の一部を `ImageData` のバイト列(RGBA8・行優先)へ取り出す。
2672///
2673/// 面の外にはみ出した部分は**透明**として埋める(仕様)。
2674/// はみ出しを切り詰めると、返る配列の大きさが要求と食い違ってしまう。
2675pub fn get_image_data(s: &Surface, x: i32, y: i32, w: i32, h: i32) -> Vec<u8> {
2676    if w <= 0 || h <= 0 {
2677        return Vec::new();
2678    }
2679    let mut out = alloc::vec![0u8; (w as usize) * (h as usize) * 4];
2680    for row in 0..h {
2681        for col in 0..w {
2682            let (sx, sy) = (x + col, y + row);
2683            if sx < 0 || sy < 0 || sx as u32 >= s.width || sy as u32 >= s.height {
2684                continue;
2685            }
2686            let argb = s.pixels[sy as usize * s.width as usize + sx as usize];
2687            let o = ((row as usize) * (w as usize) + col as usize) * 4;
2688            out[o] = ((argb >> 16) & 0xFF) as u8;
2689            out[o + 1] = ((argb >> 8) & 0xFF) as u8;
2690            out[o + 2] = (argb & 0xFF) as u8;
2691            out[o + 3] = ((argb >> 24) & 0xFF) as u8;
2692        }
2693    }
2694    out
2695}
2696
2697/// `ImageData` のバイト列を `Surface` へ書き戻す。
2698///
2699/// `putImageData` は**合成しない**(上書きする)。クリップも無視する。
2700/// これは仕様で、`fill` 系とは意味論が違う。
2701pub fn put_image_data(s: &mut Surface, data: &[u8], w: i32, h: i32, x: i32, y: i32) {
2702    if w <= 0 || h <= 0 {
2703        return;
2704    }
2705    // 長さが足りない配列は、足りるぶんだけ書く(途中で落とさない)。
2706    mark_canvas_dirty();
2707    for row in 0..h {
2708        for col in 0..w {
2709            let o = ((row as usize) * (w as usize) + col as usize) * 4;
2710            if o + 3 >= data.len() {
2711                return;
2712            }
2713            let (dx, dy) = (x + col, y + row);
2714            if dx < 0 || dy < 0 || dx as u32 >= s.width || dy as u32 >= s.height {
2715                continue;
2716            }
2717            let argb = ((data[o + 3] as u32) << 24)
2718                | ((data[o] as u32) << 16)
2719                | ((data[o + 1] as u32) << 8)
2720                | (data[o + 2] as u32);
2721            s.pixels[dy as usize * s.width as usize + dx as usize] = argb;
2722        }
2723    }
2724}
2725
2726/// canvas の大きさ変更。`<canvas width>`/`height` への代入で呼ぶ。
2727///
2728/// 仕様では、大きさを代入すると**同じ値でも**内容と描画状態が
2729/// まるごと初期化される。これを省くと、大きさを設定し直す定型句
2730/// (`canvas.width = canvas.width` による消去)が効かなくなる。
2731///
2732/// 大きさが上限を超える等で面が作れなければ何もしない(元の面を残す)。
2733pub fn resize_context(id: u32, width: u32, height: u32) -> bool {
2734    let Some(fresh) = Surface::new(width, height) else {
2735        return false;
2736    };
2737    mark_canvas_dirty();
2738    with_context(id, |c| {
2739        c.surface = fresh;
2740        c.state = DrawState::default();
2741        c.path = PathBuilder::new();
2742        c.stack.clear();
2743    })
2744    .is_some()
2745}
2746
2747// ───────────── 画像の転送 ─────────────
2748
2749/// 転送元の画素(RGBA8・行優先)。
2750pub struct ImageSource<'a> {
2751    pub width: u32,
2752    pub height: u32,
2753    pub rgba: &'a [u8],
2754}
2755
2756impl ImageSource<'_> {
2757    /// 最近傍で 1 画素を読む。範囲外は透明。
2758    pub fn sample(&self, x: i32, y: i32) -> u32 {
2759        if x < 0 || y < 0 || x as u32 >= self.width || y as u32 >= self.height {
2760            return 0;
2761        }
2762        let o = (y as usize * self.width as usize + x as usize) * 4;
2763        if o + 3 >= self.rgba.len() {
2764            return 0;
2765        }
2766        ((self.rgba[o + 3] as u32) << 24)
2767            | ((self.rgba[o] as u32) << 16)
2768            | ((self.rgba[o + 1] as u32) << 8)
2769            | (self.rgba[o + 2] as u32)
2770    }
2771
2772    /// バイリニア補間で 1 画素を読む(imageSmoothingEnabled 用)。
2773    pub fn sample_bilinear(&self, sxf: f32, syf: f32) -> u32 {
2774        let u = sxf - 0.5;
2775        let v = syf - 0.5;
2776        let x0 = libm::floorf(u) as i32;
2777        let y0 = libm::floorf(v) as i32;
2778        let x1 = x0 + 1;
2779        let y1 = y0 + 1;
2780
2781        let fx = ((u - x0 as f32) * 256.0).clamp(0.0, 256.0) as u32;
2782        let fy = ((v - y0 as f32) * 256.0).clamp(0.0, 256.0) as u32;
2783
2784        let c00 = self.sample(x0, y0);
2785        let c10 = self.sample(x1, y0);
2786        let c01 = self.sample(x0, y1);
2787        let c11 = self.sample(x1, y1);
2788
2789        if c00 == c10 && c10 == c01 && c01 == c11 {
2790            return c00;
2791        }
2792
2793        let w00 = (256 - fx) * (256 - fy);
2794        let w10 = fx * (256 - fy);
2795        let w01 = (256 - fx) * fy;
2796        let w11 = fx * fy;
2797
2798        let a = (((c00 >> 24) & 0xFF) * w00
2799            + ((c10 >> 24) & 0xFF) * w10
2800            + ((c01 >> 24) & 0xFF) * w01
2801            + ((c11 >> 24) & 0xFF) * w11 + 32768) >> 16;
2802
2803        let r = (((c00 >> 16) & 0xFF) * w00
2804            + ((c10 >> 16) & 0xFF) * w10
2805            + ((c01 >> 16) & 0xFF) * w01
2806            + ((c11 >> 16) & 0xFF) * w11 + 32768) >> 16;
2807
2808        let g = (((c00 >> 8) & 0xFF) * w00
2809            + ((c10 >> 8) & 0xFF) * w10
2810            + ((c01 >> 8) & 0xFF) * w01
2811            + ((c11 >> 8) & 0xFF) * w11 + 32768) >> 16;
2812
2813        let b = ((c00 & 0xFF) * w00
2814            + (c10 & 0xFF) * w10
2815            + (c01 & 0xFF) * w01
2816            + (c11 & 0xFF) * w11 + 32768) >> 16;
2817
2818        (a.min(255) << 24) | (r.min(255) << 16) | (g.min(255) << 8) | b.min(255)
2819    }
2820}
2821
2822/// 転送の指定(`drawImage` の 9 引数形に対応)。
2823#[derive(Debug, Clone, Copy)]
2824pub struct BlitSpec {
2825    /// 転送元の矩形。
2826    pub sx: f32,
2827    pub sy: f32,
2828    pub sw: f32,
2829    pub sh: f32,
2830    /// 転送先の矩形(変換前の canvas 座標)。
2831    pub dx: f32,
2832    pub dy: f32,
2833    pub dw: f32,
2834    pub dh: f32,
2835}
2836
2837impl Surface {
2838    /// 画像を現在の変換のもとで転送する(`drawImage`)。
2839    ///
2840    /// # なぜ逆変換で引くか
2841    ///
2842    /// 転送元を 1 画素ずつ変換先へ「押し出す」と、拡大時に隙間が空き
2843    /// 回転時には縞が出る。転送先の画素ごとに**逆変換で元を引く**と、
2844    /// どの倍率・角度でも穴が空かない。
2845    ///
2846    /// 変換が退化している(面積 0 に潰れる)場合は何もしない。
2847    pub fn draw_image(&mut self, src: &ImageSource, spec: &BlitSpec, m: &Matrix, alpha: f32, smooth: bool) {
2848        self.draw_image_with_filter(src, spec, m, alpha, smooth, "none");
2849    }
2850
2851    /// 画像を描画する(CSS filter 対応)。
2852    pub fn draw_image_with_filter(
2853        &mut self,
2854        src: &ImageSource,
2855        spec: &BlitSpec,
2856        m: &Matrix,
2857        alpha: f32,
2858        smooth: bool,
2859        filter: &str,
2860    ) {
2861        if spec.dw == 0.0 || spec.dh == 0.0 || spec.sw == 0.0 || spec.sh == 0.0 {
2862            return;
2863        }
2864        for v in [
2865            spec.sx, spec.sy, spec.sw, spec.sh, spec.dx, spec.dy, spec.dw, spec.dh,
2866        ] {
2867            if !v.is_finite() {
2868                return;
2869            }
2870        }
2871        let Some(inv) = m.invert() else {
2872            return;
2873        };
2874        mark_canvas_dirty();
2875
2876        // 転送先の 4 隅を変換して、走査すべき範囲を求める。
2877        let corners = [
2878            m.apply(spec.dx, spec.dy),
2879            m.apply(spec.dx + spec.dw, spec.dy),
2880            m.apply(spec.dx + spec.dw, spec.dy + spec.dh),
2881            m.apply(spec.dx, spec.dy + spec.dh),
2882        ];
2883        let mut x0 = corners[0].0;
2884        let mut x1 = corners[0].0;
2885        let mut y0 = corners[0].1;
2886        let mut y1 = corners[0].1;
2887        for (cx, cy) in corners.iter().skip(1) {
2888            x0 = x0.min(*cx);
2889            x1 = x1.max(*cx);
2890            y0 = y0.min(*cy);
2891            y1 = y1.max(*cy);
2892        }
2893        let px0 = (libm::floorf(x0) as i32).max(0);
2894        let px1 = (libm::ceilf(x1) as i32).min(self.width as i32);
2895        let py0 = (libm::floorf(y0) as i32).max(0);
2896        let py1 = (libm::ceilf(y1) as i32).min(self.height as i32);
2897
2898        let a = alpha.clamp(0.0, 1.0);
2899        let has_filter = filter != "none" && !filter.is_empty();
2900        for py in py0..py1 {
2901            for px in px0..px1 {
2902                // 画素中心を逆変換して、変換前の canvas 座標へ戻す。
2903                let (ux, uy) = inv.apply(px as f32 + 0.5, py as f32 + 0.5);
2904                // 転送先の矩形の中だけを描く。
2905                let tx = (ux - spec.dx) / spec.dw;
2906                let ty = (uy - spec.dy) / spec.dh;
2907                if !(0.0..1.0).contains(&tx) || !(0.0..1.0).contains(&ty) {
2908                    continue;
2909                }
2910                // 転送元の対応位置(smooth に応じてバイリニア / 最近傍)。
2911                let sxf = spec.sx + tx * spec.sw;
2912                let syf = spec.sy + ty * spec.sh;
2913                let mut argb = if smooth {
2914                    src.sample_bilinear(sxf, syf)
2915                } else {
2916                    src.sample(libm::floorf(sxf) as i32, libm::floorf(syf) as i32)
2917                };
2918                if argb >> 24 == 0 {
2919                    continue;
2920                }
2921                if has_filter {
2922                    argb = crate::os_lib::css::filters::apply_css_filters_argb(filter, argb);
2923                }
2924                let argb = if a >= 1.0 {
2925                    argb
2926                } else {
2927                    let na = (((argb >> 24) & 0xFF) as f32 * a) as u32;
2928                    (na << 24) | (argb & 0x00FF_FFFF)
2929                };
2930                self.blend_pixel(px, py, argb);
2931            }
2932        }
2933    }
2934}
2935
2936// ───────────── テキスト ─────────────
2937
2938/// `textAlign`。
2939#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2940pub enum TextAlign {
2941    Start,
2942    End,
2943    Left,
2944    Right,
2945    Center,
2946}
2947
2948/// `textBaseline`。
2949#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2950pub enum TextBaseline {
2951    Top,
2952    Hanging,
2953    Middle,
2954    Alphabetic,
2955    Ideographic,
2956    Bottom,
2957}
2958
2959pub fn parse_text_align(s: &str) -> Option<TextAlign> {
2960    match s.trim() {
2961        "start" => Some(TextAlign::Start),
2962        "end" => Some(TextAlign::End),
2963        "left" => Some(TextAlign::Left),
2964        "right" => Some(TextAlign::Right),
2965        "center" => Some(TextAlign::Center),
2966        _ => None,
2967    }
2968}
2969
2970pub fn parse_text_baseline(s: &str) -> Option<TextBaseline> {
2971    match s.trim() {
2972        "top" => Some(TextBaseline::Top),
2973        "hanging" => Some(TextBaseline::Hanging),
2974        "middle" => Some(TextBaseline::Middle),
2975        "alphabetic" => Some(TextBaseline::Alphabetic),
2976        "ideographic" => Some(TextBaseline::Ideographic),
2977        "bottom" => Some(TextBaseline::Bottom),
2978        _ => None,
2979    }
2980}
2981
2982/// Canvas 2D の書字方向(`ctx.direction`)。
2983#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2984#[derive(Default)]
2985pub enum CanvasDirection {
2986    Ltr,
2987    Rtl,
2988    #[default]
2989    Inherit,
2990}
2991
2992
2993/// 文字列から `CanvasDirection` を判定する(大文字小文字無視)。
2994pub fn parse_canvas_direction(s: &str) -> Option<CanvasDirection> {
2995    let s = s.trim();
2996    if s.eq_ignore_ascii_case("ltr") {
2997        Some(CanvasDirection::Ltr)
2998    } else if s.eq_ignore_ascii_case("rtl") {
2999        Some(CanvasDirection::Rtl)
3000    } else if s.eq_ignore_ascii_case("inherit") {
3001        Some(CanvasDirection::Inherit)
3002    } else {
3003        None
3004    }
3005}
3006
3007/// 指定位置から見た、描き始めの x のずれ(書字方向対応)。
3008///
3009/// `start`/`end` は書字方向(`direction`)で決まる:
3010/// - LTR: `start` = 0.0 (左揃え), `end` = -total_advance (右揃え)
3011/// - RTL: `start` = -total_advance (右揃え), `end` = 0.0 (左揃え)
3012/// - `left` / `right` / `center` は書字方向に左右されず物理配置を維持。
3013pub fn align_offset_with_direction(
3014    align: TextAlign,
3015    total_advance: f32,
3016    direction: CanvasDirection,
3017) -> f32 {
3018    let is_rtl = matches!(direction, CanvasDirection::Rtl);
3019    match align {
3020        TextAlign::Start => {
3021            if is_rtl {
3022                -total_advance
3023            } else {
3024                0.0
3025            }
3026        }
3027        TextAlign::End => {
3028            if is_rtl {
3029                0.0
3030            } else {
3031                -total_advance
3032            }
3033        }
3034        TextAlign::Left => 0.0,
3035        TextAlign::Right => -total_advance,
3036        TextAlign::Center => -total_advance / 2.0,
3037    }
3038}
3039
3040/// 指定位置から見た、描き始めの x のずれ(後方互換: 既定 LTR)。
3041pub fn align_offset(align: TextAlign, total_advance: f32) -> f32 {
3042    align_offset_with_direction(align, total_advance, CanvasDirection::Ltr)
3043}
3044
3045/// 指定位置から見た、ベースラインの y のずれ。
3046///
3047/// 字形はベースライン基準で置かれるので、`top` 指定なら
3048/// ベースラインを下げる(正の向きへずらす)。
3049/// 比率はこの処理系の字形配置(アセンダ 0.85)に合わせた近似で、
3050/// フォントごとの実測値ではない。
3051pub fn baseline_offset(baseline: TextBaseline, size_px: f32) -> f32 {
3052    match baseline {
3053        TextBaseline::Alphabetic => 0.0,
3054        TextBaseline::Top => size_px * 0.85,
3055        TextBaseline::Hanging => size_px * 0.8,
3056        TextBaseline::Middle => size_px * 0.35,
3057        TextBaseline::Ideographic | TextBaseline::Bottom => -size_px * 0.15,
3058    }
3059}
3060
3061/// `font` から文字の大きさ(px)を取り出す。
3062///
3063/// CSS の `font` 一括指定は語順が自由なので、**`px` で終わる数値**を
3064/// 探す。`pt`/`em` 等は換算せず、見つからなければ `None`
3065/// (呼び出し側が既定の 10px を使う)。
3066pub fn parse_font_size(font: &str) -> Option<f32> {
3067    for tok in font.split(|c: char| c.is_whitespace() || c == '/') {
3068        let t = tok.trim();
3069        let Some(num) = t.strip_suffix("px") else {
3070            continue;
3071        };
3072        if let Ok(v) = num.parse::<f32>() {
3073            if v.is_finite() && v > 0.0 {
3074                return Some(v);
3075            }
3076        }
3077    }
3078    None
3079}
3080
3081/// 1 文字ぶんの字形(アルファ値のビットマップ)。
3082///
3083/// フォントの実装(`kernel::vector_font`)に依存しないよう、
3084/// ここでは**値として受け取る**。canvas 側を純粋に保つため。
3085pub struct GlyphBitmap<'a> {
3086    pub width: u32,
3087    pub height: u32,
3088    /// 字形の左上を、ペン位置(ベースライン左端)から見たずれ。
3089    pub x_offset: i32,
3090    pub y_offset: i32,
3091    /// 次の文字までの送り幅。
3092    pub advance: f32,
3093    /// 長さは `width * height`。0 は透明。
3094    pub alpha: &'a [u8],
3095}
3096
3097impl Surface {
3098    /// 字形を 1 つ描く。
3099    ///
3100    /// 字形は軸に沿ったビットマップだが、**現在の変換の下で**置きたい。
3101    /// アルファを色に載せた画像として `draw_image` に通すことで、
3102    /// 回転・拡大も転送と同じ経路で扱える(別実装を増やさない)。
3103    pub fn draw_glyph(&mut self, g: &GlyphBitmap, pen_x: f32, pen_y: f32, argb: u32, m: &Matrix) {
3104        if g.width == 0 || g.height == 0 {
3105            return;
3106        }
3107        let n = (g.width as usize) * (g.height as usize);
3108        if g.alpha.len() < n {
3109            return;
3110        }
3111        let (r, gg, b) = ((argb >> 16) & 0xFF, (argb >> 8) & 0xFF, argb & 0xFF);
3112        let base_a = (argb >> 24) & 0xFF;
3113        let mut rgba = alloc::vec![0u8; n * 4];
3114        for i in 0..n {
3115            let a = (g.alpha[i] as u32 * base_a / 255) as u8;
3116            rgba[i * 4] = r as u8;
3117            rgba[i * 4 + 1] = gg as u8;
3118            rgba[i * 4 + 2] = b as u8;
3119            rgba[i * 4 + 3] = a;
3120        }
3121        let src = ImageSource {
3122            width: g.width,
3123            height: g.height,
3124            rgba: &rgba,
3125        };
3126        let spec = BlitSpec {
3127            sx: 0.0,
3128            sy: 0.0,
3129            sw: g.width as f32,
3130            sh: g.height as f32,
3131            dx: pen_x + g.x_offset as f32,
3132            dy: pen_y + g.y_offset as f32,
3133            dw: g.width as f32,
3134            dh: g.height as f32,
3135        };
3136        self.draw_image(&src, &spec, m, 1.0, false);
3137    }
3138
3139    /// 字形の輪郭(ストローク)を描く。
3140    ///
3141    /// 線幅 `line_width` に応じて近傍へ輪郭マスクを膨張(dilation)させて描画する。
3142    pub fn draw_glyph_stroke(
3143        &mut self,
3144        g: &GlyphBitmap,
3145        pen_x: f32,
3146        pen_y: f32,
3147        stroke_argb: u32,
3148        line_width: f32,
3149        m: &Matrix,
3150    ) {
3151        if g.width == 0 || g.height == 0 || line_width <= 0.0 {
3152            return;
3153        }
3154        let n = (g.width as usize) * (g.height as usize);
3155        if g.alpha.len() < n {
3156            return;
3157        }
3158        let r = (line_width / 2.0).clamp(0.5, 4.0);
3159        let ir = libm::ceilf(r) as i32;
3160        let w = g.width as i32;
3161        let h = g.height as i32;
3162
3163        let mut stroke_alpha = alloc::vec![0u8; n];
3164        for y in 0..h {
3165            for x in 0..w {
3166                let idx = (y * w + x) as usize;
3167                let a = g.alpha[idx];
3168                if a > 0 {
3169                    for dy in -ir..=ir {
3170                        for dx in -ir..=ir {
3171                            let dist = libm::sqrtf((dx * dx + dy * dy) as f32);
3172                            if dist <= r {
3173                                let nx = x + dx;
3174                                let ny = y + dy;
3175                                if nx >= 0 && nx < w && ny >= 0 && ny < h {
3176                                    let nidx = (ny * w + nx) as usize;
3177                                    let falloff = if r > 0.0 {
3178                                        (1.0 - (dist / (r + 0.5))).clamp(0.0, 1.0)
3179                                    } else {
3180                                        1.0
3181                                    };
3182                                    let strk_val = (a as f32 * falloff) as u8;
3183                                    if strk_val > stroke_alpha[nidx] {
3184                                        stroke_alpha[nidx] = strk_val;
3185                                    }
3186                                }
3187                            }
3188                        }
3189                    }
3190                }
3191            }
3192        }
3193        let (r_col, g_col, b_col) = (
3194            (stroke_argb >> 16) & 0xFF,
3195            (stroke_argb >> 8) & 0xFF,
3196            stroke_argb & 0xFF,
3197        );
3198        let base_a = (stroke_argb >> 24) & 0xFF;
3199        let mut rgba = alloc::vec![0u8; n * 4];
3200        for i in 0..n {
3201            let a = (stroke_alpha[i] as u32 * base_a / 255) as u8;
3202            rgba[i * 4] = r_col as u8;
3203            rgba[i * 4 + 1] = g_col as u8;
3204            rgba[i * 4 + 2] = b_col as u8;
3205            rgba[i * 4 + 3] = a;
3206        }
3207        let src = ImageSource {
3208            width: g.width,
3209            height: g.height,
3210            rgba: &rgba,
3211        };
3212        let spec = BlitSpec {
3213            sx: 0.0,
3214            sy: 0.0,
3215            sw: g.width as f32,
3216            sh: g.height as f32,
3217            dx: pen_x + g.x_offset as f32,
3218            dy: pen_y + g.y_offset as f32,
3219            dw: g.width as f32,
3220            dh: g.height as f32,
3221        };
3222        self.draw_image(&src, &spec, m, 1.0, false);
3223    }
3224}
3225
3226
3227// ───────────── SVG パス文字列のパース ─────────────
3228
3229/// SVG パス文字列から浮動小数点数を順次読み取るトークナイザ。
3230struct SvgPathTokenizer<'a> {
3231    data: &'a [u8],
3232    pos: usize,
3233}
3234
3235impl<'a> SvgPathTokenizer<'a> {
3236    fn new(data: &'a str) -> Self {
3237        Self {
3238            data: data.as_bytes(),
3239            pos: 0,
3240        }
3241    }
3242
3243    fn skip_whitespace_and_comma(&mut self) {
3244        while self.pos < self.data.len() {
3245            let c = self.data[self.pos];
3246            if c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == b',' {
3247                self.pos += 1;
3248            } else {
3249                break;
3250            }
3251        }
3252    }
3253
3254    fn next_cmd(&mut self) -> Option<char> {
3255        self.skip_whitespace_and_comma();
3256        if self.pos >= self.data.len() {
3257            return None;
3258        }
3259        let c = self.data[self.pos] as char;
3260        if c.is_ascii_alphabetic() {
3261            self.pos += 1;
3262            Some(c)
3263        } else {
3264            None
3265        }
3266    }
3267
3268    fn next_f32(&mut self) -> Option<f32> {
3269        self.skip_whitespace_and_comma();
3270        if self.pos >= self.data.len() {
3271            return None;
3272        }
3273        let start = self.pos;
3274        if self.pos < self.data.len() && (self.data[self.pos] == b'-' || self.data[self.pos] == b'+') {
3275            self.pos += 1;
3276        }
3277        let mut has_digit = false;
3278        while self.pos < self.data.len() && self.data[self.pos].is_ascii_digit() {
3279            self.pos += 1;
3280            has_digit = true;
3281        }
3282        if self.pos < self.data.len() && self.data[self.pos] == b'.' {
3283            self.pos += 1;
3284            while self.pos < self.data.len() && self.data[self.pos].is_ascii_digit() {
3285                self.pos += 1;
3286                has_digit = true;
3287            }
3288        }
3289        if has_digit && self.pos < self.data.len() && (self.data[self.pos] == b'e' || self.data[self.pos] == b'E') {
3290            self.pos += 1;
3291            if self.pos < self.data.len() && (self.data[self.pos] == b'-' || self.data[self.pos] == b'+') {
3292                self.pos += 1;
3293            }
3294            while self.pos < self.data.len() && self.data[self.pos].is_ascii_digit() {
3295                self.pos += 1;
3296            }
3297        }
3298        if !has_digit {
3299            self.pos = start;
3300            return None;
3301        }
3302        let s = core::str::from_utf8(&self.data[start..self.pos]).ok()?;
3303        s.parse::<f32>().ok()
3304    }
3305
3306    fn next_flag(&mut self) -> Option<bool> {
3307        self.skip_whitespace_and_comma();
3308        if self.pos >= self.data.len() {
3309            return None;
3310        }
3311        let b = self.data[self.pos];
3312        if b == b'0' {
3313            self.pos += 1;
3314            Some(false)
3315        } else if b == b'1' {
3316            self.pos += 1;
3317            Some(true)
3318        } else {
3319            None
3320        }
3321    }
3322}
3323
3324/// W3C SVG 1.1 Appendix F.6.5: 端点パラメータ (x1, y1, rx, ry, phi, large_arc, sweep, x2, y2)
3325/// を中心パラメータ (cx, cy, rx, ry, phi, theta1, theta2, anticlockwise) に変換する。
3326#[allow(clippy::too_many_arguments)]
3327fn svg_arc_to_center(
3328    x1: f32,
3329    y1: f32,
3330    mut rx: f32,
3331    mut ry: f32,
3332    angle_deg: f32,
3333    large_arc: bool,
3334    sweep: bool,
3335    x2: f32,
3336    y2: f32,
3337) -> Option<(f32, f32, f32, f32, f32, f32, f32, bool)> {
3338    if libm::fabsf(x1 - x2) < 1e-6 && libm::fabsf(y1 - y2) < 1e-6 {
3339        return None;
3340    }
3341    rx = libm::fabsf(rx);
3342    ry = libm::fabsf(ry);
3343    if rx < 1e-6 || ry < 1e-6 {
3344        return None;
3345    }
3346
3347    let phi = angle_deg * (core::f32::consts::PI / 180.0);
3348    let cos_phi = libm::cosf(phi);
3349    let sin_phi = libm::sinf(phi);
3350
3351    // Step 1: (x1', y1') の計算
3352    let dx = (x1 - x2) / 2.0;
3353    let dy = (y1 - y2) / 2.0;
3354    let x1_prime = cos_phi * dx + sin_phi * dy;
3355    let y1_prime = -sin_phi * dx + cos_phi * dy;
3356
3357    // Step 2: 半径の拡大調整
3358    let lambda = (x1_prime * x1_prime) / (rx * rx) + (y1_prime * y1_prime) / (ry * ry);
3359    if lambda > 1.0 {
3360        let sqrt_lambda = libm::sqrtf(lambda);
3361        rx *= sqrt_lambda;
3362        ry *= sqrt_lambda;
3363    }
3364
3365    // Step 3: (cx', cy') の計算
3366    let rx_sq = rx * rx;
3367    let ry_sq = ry * ry;
3368    let x1_p_sq = x1_prime * x1_prime;
3369    let y1_p_sq = y1_prime * y1_prime;
3370
3371    let num = rx_sq * ry_sq - rx_sq * y1_p_sq - ry_sq * x1_p_sq;
3372    let den = rx_sq * y1_p_sq + ry_sq * x1_p_sq;
3373    let sq = if den > 0.0 { libm::fmaxf(0.0, num / den) } else { 0.0 };
3374    let sign = if large_arc == sweep { -1.0 } else { 1.0 };
3375    let coef = sign * libm::sqrtf(sq);
3376
3377    let cx_prime = coef * ((rx * y1_prime) / ry);
3378    let cy_prime = coef * -((ry * x1_prime) / rx);
3379
3380    // Step 4: (cx, cy) の復元
3381    let cx = cos_phi * cx_prime - sin_phi * cy_prime + (x1 + x2) / 2.0;
3382    let cy = sin_phi * cx_prime + cos_phi * cy_prime + (y1 + y2) / 2.0;
3383
3384    // Step 5: 開始角と掃引角の計算
3385    let ux = (x1_prime - cx_prime) / rx;
3386    let uy = (y1_prime - cy_prime) / ry;
3387    let vx = (-x1_prime - cx_prime) / rx;
3388    let vy = (-y1_prime - cy_prime) / ry;
3389
3390    let u_len = libm::sqrtf(ux * ux + uy * uy);
3391    let cos_theta1 = if u_len > 0.0 { (ux / u_len).clamp(-1.0, 1.0) } else { 1.0 };
3392    let mut theta1 = libm::acosf(cos_theta1);
3393    if uy < 0.0 {
3394        theta1 = -theta1;
3395    }
3396
3397    let dot = ux * vx + uy * vy;
3398    let v_len = libm::sqrtf(vx * vx + vy * vy);
3399    let uv_len = u_len * v_len;
3400    let cos_dtheta = if uv_len > 0.0 { (dot / uv_len).clamp(-1.0, 1.0) } else { 1.0 };
3401    let mut dtheta = libm::acosf(cos_dtheta);
3402    if (ux * vy - uy * vx) < 0.0 {
3403        dtheta = -dtheta;
3404    }
3405
3406    let tau = core::f32::consts::PI * 2.0;
3407    if !sweep && dtheta > 0.0 {
3408        dtheta -= tau;
3409    } else if sweep && dtheta < 0.0 {
3410        dtheta += tau;
3411    }
3412
3413    let anticlockwise = !sweep;
3414    let theta2 = theta1 + dtheta;
3415    Some((cx, cy, rx, ry, phi, theta1, theta2, anticlockwise))
3416}
3417
3418/// SVG パス文字列 `d` を解析し、`PathBuilder` へ追加する。
3419pub fn parse_svg_path_into(d: &str, p: &mut PathBuilder, m: &Matrix) {
3420    let mut tok = SvgPathTokenizer::new(d);
3421    let mut curr_x = 0.0f32;
3422    let mut curr_y = 0.0f32;
3423    let mut start_x = 0.0f32;
3424    let mut start_y = 0.0f32;
3425    let mut last_cmd = ' ';
3426    let mut last_cubic_ctrl: Option<(f32, f32)> = None;
3427    let mut last_quad_ctrl: Option<(f32, f32)> = None;
3428
3429    while tok.pos < tok.data.len() {
3430        tok.skip_whitespace_and_comma();
3431        if tok.pos >= tok.data.len() {
3432            break;
3433        }
3434        let cmd = if let Some(c) = tok.next_cmd() {
3435            last_cmd = c;
3436            c
3437        } else if last_cmd != ' ' {
3438            if last_cmd == 'M' {
3439                'L'
3440            } else if last_cmd == 'm' {
3441                'l'
3442            } else {
3443                last_cmd
3444            }
3445        } else {
3446            break;
3447        };
3448
3449        match cmd {
3450            'M' => {
3451                if let (Some(x), Some(y)) = (tok.next_f32(), tok.next_f32()) {
3452                    curr_x = x;
3453                    curr_y = y;
3454                    start_x = x;
3455                    start_y = y;
3456                    p.move_to(m, x, y);
3457                    last_cubic_ctrl = None;
3458                    last_quad_ctrl = None;
3459                }
3460            }
3461            'm' => {
3462                if let (Some(dx), Some(dy)) = (tok.next_f32(), tok.next_f32()) {
3463                    curr_x += dx;
3464                    curr_y += dy;
3465                    start_x = curr_x;
3466                    start_y = curr_y;
3467                    p.move_to(m, curr_x, curr_y);
3468                    last_cubic_ctrl = None;
3469                    last_quad_ctrl = None;
3470                }
3471            }
3472            'L' => {
3473                if let (Some(x), Some(y)) = (tok.next_f32(), tok.next_f32()) {
3474                    curr_x = x;
3475                    curr_y = y;
3476                    p.line_to(m, x, y);
3477                    last_cubic_ctrl = None;
3478                    last_quad_ctrl = None;
3479                }
3480            }
3481            'l' => {
3482                if let (Some(dx), Some(dy)) = (tok.next_f32(), tok.next_f32()) {
3483                    curr_x += dx;
3484                    curr_y += dy;
3485                    p.line_to(m, curr_x, curr_y);
3486                    last_cubic_ctrl = None;
3487                    last_quad_ctrl = None;
3488                }
3489            }
3490            'H' => {
3491                if let Some(x) = tok.next_f32() {
3492                    curr_x = x;
3493                    p.line_to(m, curr_x, curr_y);
3494                    last_cubic_ctrl = None;
3495                    last_quad_ctrl = None;
3496                }
3497            }
3498            'h' => {
3499                if let Some(dx) = tok.next_f32() {
3500                    curr_x += dx;
3501                    p.line_to(m, curr_x, curr_y);
3502                    last_cubic_ctrl = None;
3503                    last_quad_ctrl = None;
3504                }
3505            }
3506            'V' => {
3507                if let Some(y) = tok.next_f32() {
3508                    curr_y = y;
3509                    p.line_to(m, curr_x, curr_y);
3510                    last_cubic_ctrl = None;
3511                    last_quad_ctrl = None;
3512                }
3513            }
3514            'v' => {
3515                if let Some(dy) = tok.next_f32() {
3516                    curr_y += dy;
3517                    p.line_to(m, curr_x, curr_y);
3518                    last_cubic_ctrl = None;
3519                    last_quad_ctrl = None;
3520                }
3521            }
3522            'C' => {
3523                if let (Some(x1), Some(y1), Some(x2), Some(y2), Some(x), Some(y)) = (
3524                    tok.next_f32(), tok.next_f32(), tok.next_f32(), tok.next_f32(), tok.next_f32(), tok.next_f32()
3525                ) {
3526                    p.bezier_curve_to(m, x1, y1, x2, y2, x, y);
3527                    last_cubic_ctrl = Some((x2, y2));
3528                    last_quad_ctrl = None;
3529                    curr_x = x;
3530                    curr_y = y;
3531                }
3532            }
3533            'c' => {
3534                if let (Some(dx1), Some(dy1), Some(dx2), Some(dy2), Some(dx), Some(dy)) = (
3535                    tok.next_f32(), tok.next_f32(), tok.next_f32(), tok.next_f32(), tok.next_f32(), tok.next_f32()
3536                ) {
3537                    let (x1, y1) = (curr_x + dx1, curr_y + dy1);
3538                    let (x2, y2) = (curr_x + dx2, curr_y + dy2);
3539                    let (x, y) = (curr_x + dx, curr_y + dy);
3540                    p.bezier_curve_to(m, x1, y1, x2, y2, x, y);
3541                    last_cubic_ctrl = Some((x2, y2));
3542                    last_quad_ctrl = None;
3543                    curr_x = x;
3544                    curr_y = y;
3545                }
3546            }
3547            'S' => {
3548                if let (Some(x2), Some(y2), Some(x), Some(y)) = (
3549                    tok.next_f32(), tok.next_f32(), tok.next_f32(), tok.next_f32()
3550                ) {
3551                    let (x1, y1) = if let Some((prev_x2, prev_y2)) = last_cubic_ctrl {
3552                        (2.0 * curr_x - prev_x2, 2.0 * curr_y - prev_y2)
3553                    } else {
3554                        (curr_x, curr_y)
3555                    };
3556                    p.bezier_curve_to(m, x1, y1, x2, y2, x, y);
3557                    last_cubic_ctrl = Some((x2, y2));
3558                    last_quad_ctrl = None;
3559                    curr_x = x;
3560                    curr_y = y;
3561                }
3562            }
3563            's' => {
3564                if let (Some(dx2), Some(dy2), Some(dx), Some(dy)) = (
3565                    tok.next_f32(), tok.next_f32(), tok.next_f32(), tok.next_f32()
3566                ) {
3567                    let (x1, y1) = if let Some((prev_x2, prev_y2)) = last_cubic_ctrl {
3568                        (2.0 * curr_x - prev_x2, 2.0 * curr_y - prev_y2)
3569                    } else {
3570                        (curr_x, curr_y)
3571                    };
3572                    let (x2, y2) = (curr_x + dx2, curr_y + dy2);
3573                    let (x, y) = (curr_x + dx, curr_y + dy);
3574                    p.bezier_curve_to(m, x1, y1, x2, y2, x, y);
3575                    last_cubic_ctrl = Some((x2, y2));
3576                    last_quad_ctrl = None;
3577                    curr_x = x;
3578                    curr_y = y;
3579                }
3580            }
3581            'Q' => {
3582                if let (Some(x1), Some(y1), Some(x), Some(y)) = (
3583                    tok.next_f32(), tok.next_f32(), tok.next_f32(), tok.next_f32()
3584                ) {
3585                    p.quadratic_curve_to(m, x1, y1, x, y);
3586                    last_quad_ctrl = Some((x1, y1));
3587                    last_cubic_ctrl = None;
3588                    curr_x = x;
3589                    curr_y = y;
3590                }
3591            }
3592            'q' => {
3593                if let (Some(dx1), Some(dy1), Some(dx), Some(dy)) = (
3594                    tok.next_f32(), tok.next_f32(), tok.next_f32(), tok.next_f32()
3595                ) {
3596                    let (x1, y1) = (curr_x + dx1, curr_y + dy1);
3597                    let (x, y) = (curr_x + dx, curr_y + dy);
3598                    p.quadratic_curve_to(m, x1, y1, x, y);
3599                    last_quad_ctrl = Some((x1, y1));
3600                    last_cubic_ctrl = None;
3601                    curr_x = x;
3602                    curr_y = y;
3603                }
3604            }
3605            'T' => {
3606                if let (Some(x), Some(y)) = (tok.next_f32(), tok.next_f32()) {
3607                    let (cx, cy) = if let Some((prev_cx, prev_cy)) = last_quad_ctrl {
3608                        (2.0 * curr_x - prev_cx, 2.0 * curr_y - prev_cy)
3609                    } else {
3610                        (curr_x, curr_y)
3611                    };
3612                    p.quadratic_curve_to(m, cx, cy, x, y);
3613                    last_quad_ctrl = Some((cx, cy));
3614                    last_cubic_ctrl = None;
3615                    curr_x = x;
3616                    curr_y = y;
3617                }
3618            }
3619            't' => {
3620                if let (Some(dx), Some(dy)) = (tok.next_f32(), tok.next_f32()) {
3621                    let (cx, cy) = if let Some((prev_cx, prev_cy)) = last_quad_ctrl {
3622                        (2.0 * curr_x - prev_cx, 2.0 * curr_y - prev_cy)
3623                    } else {
3624                        (curr_x, curr_y)
3625                    };
3626                    let (x, y) = (curr_x + dx, curr_y + dy);
3627                    p.quadratic_curve_to(m, cx, cy, x, y);
3628                    last_quad_ctrl = Some((cx, cy));
3629                    last_cubic_ctrl = None;
3630                    curr_x = x;
3631                    curr_y = y;
3632                }
3633            }
3634            'A' | 'a' => {
3635                let rx_opt = tok.next_f32();
3636                let ry_opt = tok.next_f32();
3637                let angle_opt = tok.next_f32();
3638                let large_arc_opt = tok.next_flag();
3639                let sweep_opt = tok.next_flag();
3640                let x_opt = tok.next_f32();
3641                let y_opt = tok.next_f32();
3642
3643                if let (Some(rx), Some(ry), Some(angle), Some(large_arc), Some(sweep), Some(x), Some(y)) =
3644                    (rx_opt, ry_opt, angle_opt, large_arc_opt, sweep_opt, x_opt, y_opt)
3645                {
3646                    let (target_x, target_y) = if cmd == 'a' {
3647                        (curr_x + x, curr_y + y)
3648                    } else {
3649                        (x, y)
3650                    };
3651
3652                    if let Some((cx, cy, r_x, r_y, phi, theta1, theta2, anticlockwise)) =
3653                        svg_arc_to_center(curr_x, curr_y, rx, ry, angle, large_arc, sweep, target_x, target_y)
3654                    {
3655                        p.ellipse(m, cx, cy, r_x, r_y, phi, theta1, theta2, anticlockwise);
3656                    } else {
3657                        p.line_to(m, target_x, target_y);
3658                    }
3659                    curr_x = target_x;
3660                    curr_y = target_y;
3661                    last_cubic_ctrl = None;
3662                    last_quad_ctrl = None;
3663                }
3664            }
3665            'Z' | 'z' => {
3666                p.close_path();
3667                curr_x = start_x;
3668                curr_y = start_y;
3669                last_cubic_ctrl = None;
3670                last_quad_ctrl = None;
3671            }
3672            _ => {
3673                tok.pos += 1;
3674            }
3675        }
3676    }
3677}
3678
3679// ───────────── Path2D 登録表 ─────────────
3680
3681static PATH2D_MAP: spin::Mutex<alloc::collections::BTreeMap<u32, PathBuilder>> =
3682    spin::Mutex::new(alloc::collections::BTreeMap::new());
3683static NEXT_PATH2D_ID: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(1);
3684const MAX_PATH2D: usize = 64;
3685
3686pub fn create_path2d(init_svg: Option<&str>) -> u32 {
3687    let id = NEXT_PATH2D_ID.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
3688    let mut builder = PathBuilder::new();
3689    if let Some(svg) = init_svg {
3690        parse_svg_path_into(svg, &mut builder, &Matrix::identity());
3691    }
3692    let mut map = PATH2D_MAP.lock();
3693    while map.len() >= MAX_PATH2D {
3694        if let Some(&oldest) = map.keys().next() {
3695            map.remove(&oldest);
3696        } else {
3697            break;
3698        }
3699    }
3700    map.insert(id, builder);
3701    id
3702}
3703
3704pub fn clone_path2d(src_id: u32) -> u32 {
3705    let new_id = NEXT_PATH2D_ID.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
3706    let mut map = PATH2D_MAP.lock();
3707    while map.len() >= MAX_PATH2D {
3708        if let Some(&oldest) = map.keys().next() {
3709            map.remove(&oldest);
3710        } else {
3711            break;
3712        }
3713    }
3714    let cloned = map.get(&src_id).cloned().unwrap_or_else(PathBuilder::new);
3715    map.insert(new_id, cloned);
3716    new_id
3717}
3718
3719pub fn with_path2d<R>(id: u32, f: impl FnOnce(&mut PathBuilder) -> R) -> Option<R> {
3720    let mut map = PATH2D_MAP.lock();
3721    map.get_mut(&id).map(f)
3722}
3723
3724pub fn get_path2d_subpaths(id: u32) -> Option<Vec<SubPath>> {
3725    let map = PATH2D_MAP.lock();
3726    map.get(&id).map(|p| p.finish())
3727}
3728
3729pub fn add_path_to_path2d(dst_id: u32, src_id: u32, transform: Option<&Matrix>) {
3730    let mut map = PATH2D_MAP.lock();
3731    if let Some(src) = map.get(&src_id).cloned() {
3732        if let Some(dst) = map.get_mut(&dst_id) {
3733            dst.add_path(&src, transform);
3734        }
3735    }
3736}
3737
3738impl Canvas2dContext {
3739    /// 外部のパス(Path2D 等)を指定して塗る。
3740    pub fn fill_subpaths(&mut self, subpaths: &[SubPath], rule: FillRule) {
3741        self.sync_clip();
3742        if let Some(ref grad) = self.state.fill_gradient {
3743            self.surface.fill_path_gradient(subpaths, rule, grad, self.state.global_alpha.clamp(0.0, 1.0));
3744        } else if let Some(ref pat) = self.state.fill_pattern {
3745            self.surface.fill_path_pattern(subpaths, rule, pat, self.state.global_alpha.clamp(0.0, 1.0));
3746        } else {
3747            let color = self.apply_alpha(self.state.fill);
3748            self.surface.fill_path(subpaths, rule, color);
3749        }
3750    }
3751
3752    /// 外部のパス(Path2D 等)を指定して線を描く。
3753    pub fn stroke_subpaths(&mut self, subpaths: &[SubPath]) {
3754        self.stroke_subpaths_internal(subpaths);
3755    }
3756
3757    /// 外部のパス(Path2D 等)を指定してクリップする。
3758    pub fn clip_subpaths(&mut self, subpaths: &[SubPath], rule: FillRule) {
3759        if subpaths.is_empty() {
3760            return;
3761        }
3762        let mask = ClipMask::from_path(self.surface.width, self.surface.height, subpaths, rule);
3763        let merged = match &self.state.clip {
3764            Some(prev) => prev.intersect(&mask),
3765            None => mask,
3766        };
3767        self.state.clip = Some(alloc::sync::Arc::new(merged));
3768    }
3769}
3770
3771
3772// ───────────── CanvasGradient 登録表 ─────────────
3773
3774static GRADIENT_MAP: spin::Mutex<alloc::collections::BTreeMap<u32, CanvasGradient>> =
3775    spin::Mutex::new(alloc::collections::BTreeMap::new());
3776static NEXT_GRADIENT_ID: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(1);
3777const MAX_GRADIENTS: usize = 64;
3778
3779pub fn create_linear_gradient(x0: f32, y0: f32, x1: f32, y1: f32) -> u32 {
3780    let id = NEXT_GRADIENT_ID.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
3781    let grad = CanvasGradient::new_linear(x0, y0, x1, y1);
3782    let mut map = GRADIENT_MAP.lock();
3783    while map.len() >= MAX_GRADIENTS {
3784        if let Some(&oldest) = map.keys().next() {
3785            map.remove(&oldest);
3786        } else {
3787            break;
3788        }
3789    }
3790    map.insert(id, grad);
3791    id
3792}
3793
3794pub fn create_radial_gradient(x0: f32, y0: f32, r0: f32, x1: f32, y1: f32, r1: f32) -> u32 {
3795    let id = NEXT_GRADIENT_ID.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
3796    let grad = CanvasGradient::new_radial(x0, y0, r0, x1, y1, r1);
3797    let mut map = GRADIENT_MAP.lock();
3798    while map.len() >= MAX_GRADIENTS {
3799        if let Some(&oldest) = map.keys().next() {
3800            map.remove(&oldest);
3801        } else {
3802            break;
3803        }
3804    }
3805    map.insert(id, grad);
3806    id
3807}
3808
3809pub fn create_conic_gradient(start_angle: f32, cx: f32, cy: f32) -> u32 {
3810    let id = NEXT_GRADIENT_ID.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
3811    let grad = CanvasGradient::new_conic(start_angle, cx, cy);
3812    let mut map = GRADIENT_MAP.lock();
3813    while map.len() >= MAX_GRADIENTS {
3814        if let Some(&oldest) = map.keys().next() {
3815            map.remove(&oldest);
3816        } else {
3817            break;
3818        }
3819    }
3820    map.insert(id, grad);
3821    id
3822}
3823
3824pub fn add_color_stop_to_gradient(id: u32, offset: f32, color: u32) {
3825    let mut map = GRADIENT_MAP.lock();
3826    if let Some(grad) = map.get_mut(&id) {
3827        grad.add_color_stop(offset, color);
3828    }
3829}
3830
3831pub fn get_gradient(id: u32) -> Option<CanvasGradient> {
3832    let map = GRADIENT_MAP.lock();
3833    map.get(&id).cloned()
3834}
3835
3836
3837// ───────────── CanvasPattern 登録表 ─────────────
3838
3839static PATTERN_MAP: spin::Mutex<alloc::collections::BTreeMap<u32, CanvasPattern>> =
3840    spin::Mutex::new(alloc::collections::BTreeMap::new());
3841static NEXT_PATTERN_ID: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(1);
3842const MAX_PATTERNS: usize = 64;
3843
3844pub fn create_pattern(width: u32, height: u32, pixels: Vec<u32>, repetition: Repetition) -> u32 {
3845    let id = NEXT_PATTERN_ID.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
3846    let pat = CanvasPattern::new(width, height, pixels, repetition);
3847    let mut map = PATTERN_MAP.lock();
3848    while map.len() >= MAX_PATTERNS {
3849        if let Some(&oldest) = map.keys().next() {
3850            map.remove(&oldest);
3851        } else {
3852            break;
3853        }
3854    }
3855    map.insert(id, pat);
3856    id
3857}
3858
3859pub fn get_pattern(id: u32) -> Option<CanvasPattern> {
3860    let map = PATTERN_MAP.lock();
3861    map.get(&id).cloned()
3862}
3863
3864pub fn set_pattern_transform(id: u32, transform: Matrix) {
3865    let mut map = PATTERN_MAP.lock();
3866    if let Some(pat) = map.get_mut(&id) {
3867        pat.set_transform(transform);
3868    }
3869}