Skip to main content

atmos/os_lib/
svg.rs

1// src/svg.rs - ミニ SVG ラスタライザ (Fluent UI System Icons 対応)
2//
3// SVG icons from Fluent UI System Icons
4// Copyright (c) 2020 Microsoft Corporation
5// Licensed under the MIT License
6// https://github.com/microsoft/fluentui-system-icons
7//
8// このモジュールは no_std 環境向けの最小限の SVG パーサ&ラスタライザです。
9// 対応コマンド: M, m, L, l, C, c, Z, z
10// ラスタライズアルゴリズム: Even-Odd (vector_font.rs と同じ方式)
11
12#![allow(dead_code)]
13
14extern crate alloc;
15use alloc::collections::BTreeMap;
16use alloc::vec::Vec;
17use spin::Mutex;
18
19// -------------------------------------------------------------------
20// 内部データ構造
21// -------------------------------------------------------------------
22
23#[derive(Copy, Clone)]
24struct Point {
25    x: f32,
26    y: f32,
27}
28
29#[derive(Clone)]
30struct Segment {
31    p1: Point,
32    p2: Point,
33}
34
35// -------------------------------------------------------------------
36// SVG パスパーサ
37// -------------------------------------------------------------------
38
39/// バイト列から数値トークンを読み取るシンプルなイテレータ
40struct PathParser<'a> {
41    data: &'a [u8],
42    pos: usize,
43}
44
45impl<'a> PathParser<'a> {
46    fn new(data: &'a [u8]) -> Self {
47        Self { data, pos: 0 }
48    }
49
50    fn skip_whitespace_and_comma(&mut self) {
51        while self.pos < self.data.len() {
52            let c = self.data[self.pos];
53            if c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == b',' {
54                self.pos += 1;
55            } else {
56                break;
57            }
58        }
59    }
60
61    fn peek(&self) -> Option<u8> {
62        if self.pos < self.data.len() {
63            Some(self.data[self.pos])
64        } else {
65            None
66        }
67    }
68
69    fn next_char(&mut self) -> Option<u8> {
70        if self.pos < self.data.len() {
71            let c = self.data[self.pos];
72            self.pos += 1;
73            Some(c)
74        } else {
75            None
76        }
77    }
78
79    /// 次の浮動小数点数を読み取る
80    fn next_f32(&mut self) -> Option<f32> {
81        self.skip_whitespace_and_comma();
82        if self.pos >= self.data.len() {
83            return None;
84        }
85
86        let start = self.pos;
87        // 符号
88        if self.pos < self.data.len()
89            && (self.data[self.pos] == b'-' || self.data[self.pos] == b'+')
90        {
91            self.pos += 1;
92        }
93        // 整数部
94        while self.pos < self.data.len() && self.data[self.pos].is_ascii_digit() {
95            self.pos += 1;
96        }
97        // 小数部
98        if self.pos < self.data.len() && self.data[self.pos] == b'.' {
99            self.pos += 1;
100            while self.pos < self.data.len() && self.data[self.pos].is_ascii_digit() {
101                self.pos += 1;
102            }
103        }
104        // 指数部 (e/E)
105        if self.pos < self.data.len()
106            && (self.data[self.pos] == b'e' || self.data[self.pos] == b'E')
107        {
108            self.pos += 1;
109            if self.pos < self.data.len()
110                && (self.data[self.pos] == b'-' || self.data[self.pos] == b'+')
111            {
112                self.pos += 1;
113            }
114            while self.pos < self.data.len() && self.data[self.pos].is_ascii_digit() {
115                self.pos += 1;
116            }
117        }
118
119        if self.pos == start {
120            return None;
121        }
122
123        // バイト列→文字列→f32 変換
124        let s = core::str::from_utf8(&self.data[start..self.pos]).ok()?;
125        parse_f32(s)
126    }
127
128    /// 弧のフラグ(0/1 の 1 文字。`a1 1 0 000 2` のように区切り無しで続けて書ける)。
129    fn next_flag(&mut self) -> Option<bool> {
130        self.skip_whitespace_and_comma();
131        match self.peek() {
132            Some(b'0') => {
133                self.pos += 1;
134                Some(false)
135            }
136            Some(b'1') => {
137                self.pos += 1;
138                Some(true)
139            }
140            _ => None,
141        }
142    }
143
144    /// 次のコマンド文字を読み取る(数値が来たらNone)
145    fn next_cmd(&mut self) -> Option<u8> {
146        self.skip_whitespace_and_comma();
147        match self.peek() {
148            Some(c) if c.is_ascii_alphabetic() => {
149                self.pos += 1;
150                Some(c)
151            }
152            _ => None,
153        }
154    }
155}
156
157/// no_std 環境向けの簡易 f32 パーサ
158fn parse_f32(s: &str) -> Option<f32> {
159    let bytes = s.as_bytes();
160    let mut i = 0;
161    let neg = if i < bytes.len() && bytes[i] == b'-' {
162        i += 1;
163        true
164    } else if i < bytes.len() && bytes[i] == b'+' {
165        i += 1;
166        false
167    } else {
168        false
169    };
170
171    let mut int_part: f32 = 0.0;
172    while i < bytes.len() && bytes[i].is_ascii_digit() {
173        int_part = int_part * 10.0 + (bytes[i] - b'0') as f32;
174        i += 1;
175    }
176
177    let mut frac_part: f32 = 0.0;
178    let mut frac_div: f32 = 1.0;
179    if i < bytes.len() && bytes[i] == b'.' {
180        i += 1;
181        while i < bytes.len() && bytes[i].is_ascii_digit() {
182            frac_part = frac_part * 10.0 + (bytes[i] - b'0') as f32;
183            frac_div *= 10.0;
184            i += 1;
185        }
186    }
187
188    // 指数部の簡易処理
189    let mut exp: i32 = 0;
190    let mut exp_neg = false;
191    if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
192        i += 1;
193        if i < bytes.len() && bytes[i] == b'-' {
194            exp_neg = true;
195            i += 1;
196        } else if i < bytes.len() && bytes[i] == b'+' {
197            i += 1;
198        }
199        while i < bytes.len() && bytes[i].is_ascii_digit() {
200            exp = exp * 10 + (bytes[i] - b'0') as i32;
201            i += 1;
202        }
203    }
204
205    let mut val = int_part + frac_part / frac_div;
206    if exp != 0 {
207        let mut e: f32 = 1.0;
208        for _ in 0..exp {
209            e *= 10.0;
210        }
211        if exp_neg {
212            val /= e;
213        } else {
214            val *= e;
215        }
216    }
217    if neg {
218        val = -val;
219    }
220
221    if i == 0 {
222        None
223    } else {
224        Some(val)
225    }
226}
227
228/// SVG の `d` 属性文字列をパースして線分リストに変換する(塗り用:開いた図形を暗黙に閉じる)
229fn parse_path_d(d: &str) -> Vec<Segment> {
230    parse_path_d_ex(d, true)
231}
232
233/// SVG の `d` 属性文字列をパースして線分リストに変換する。`close_open` が偽なら Z/z 以外の開いた部分パスを閉じない(stroke 用)。
234fn parse_path_d_ex(d: &str, close_open: bool) -> Vec<Segment> {
235    let mut segments: Vec<Segment> = Vec::new();
236    let mut parser = PathParser::new(d.as_bytes());
237
238    let mut cur = Point { x: 0.0, y: 0.0 };
239    let mut start = Point { x: 0.0, y: 0.0 };
240    let mut cmd: u8 = 0;
241    // 直前の曲線の制御点(S は C/S の第 2 制御点、T は Q/T の制御点を鏡映する)。
242    let mut last_cubic_ctrl: Option<Point> = None;
243    let mut last_quad_ctrl: Option<Point> = None;
244
245    loop {
246        if let Some(c) = parser.next_cmd() {
247            cmd = c;
248            if matches!(c, b'Z' | b'z') {
249                if cur.x != start.x || cur.y != start.y {
250                    segments.push(Segment { p1: cur, p2: start });
251                }
252                cur = start;
253                last_cubic_ctrl = None;
254                last_quad_ctrl = None;
255                continue;
256            }
257        } else {
258            if parser.peek().is_none() {
259                break;
260            }
261            // コマンド文字が無い数値は直前のコマンドの繰り返し(M の後は L)。
262            match cmd {
263                b'M' => cmd = b'L',
264                b'm' => cmd = b'l',
265                _ => {}
266            }
267        }
268        let rel = cmd.is_ascii_lowercase();
269        let base = if rel { cur } else { Point { x: 0.0, y: 0.0 } };
270        let at = |x: f32, y: f32| Point { x: base.x + x, y: base.y + y };
271        let mut cubic_ctrl = None;
272        let mut quad_ctrl = None;
273        let ok = match cmd.to_ascii_uppercase() {
274            b'M' => match (parser.next_f32(), parser.next_f32()) {
275                (Some(x), Some(y)) => {
276                    // 塗りでは開いた図形を図形ごとに暗黙に閉じる(次の図形の始まり)。
277                    if close_open {
278                        close_subpath(&mut segments, cur, start);
279                    }
280                    cur = at(x, y);
281                    start = cur;
282                    true
283                }
284                _ => false,
285            },
286            b'L' => match (parser.next_f32(), parser.next_f32()) {
287                (Some(x), Some(y)) => {
288                    let to = at(x, y);
289                    segments.push(Segment { p1: cur, p2: to });
290                    cur = to;
291                    true
292                }
293                _ => false,
294            },
295            b'H' => match parser.next_f32() {
296                Some(x) => {
297                    let to = Point { x: base.x + x, y: cur.y };
298                    segments.push(Segment { p1: cur, p2: to });
299                    cur = to;
300                    true
301                }
302                None => false,
303            },
304            b'V' => match parser.next_f32() {
305                Some(y) => {
306                    let to = Point { x: cur.x, y: base.y + y };
307                    segments.push(Segment { p1: cur, p2: to });
308                    cur = to;
309                    true
310                }
311                None => false,
312            },
313            b'C' => match (
314                parser.next_f32(),
315                parser.next_f32(),
316                parser.next_f32(),
317                parser.next_f32(),
318                parser.next_f32(),
319                parser.next_f32(),
320            ) {
321                (Some(x1), Some(y1), Some(x2), Some(y2), Some(x), Some(y)) => {
322                    let (p1, p2, to) = (at(x1, y1), at(x2, y2), at(x, y));
323                    flatten_cubic(cur, p1, p2, to, &mut segments);
324                    cur = to;
325                    cubic_ctrl = Some(p2);
326                    true
327                }
328                _ => false,
329            },
330            b'S' => match (parser.next_f32(), parser.next_f32(), parser.next_f32(), parser.next_f32()) {
331                (Some(x2), Some(y2), Some(x), Some(y)) => {
332                    let p1 = reflect(last_cubic_ctrl, cur);
333                    let (p2, to) = (at(x2, y2), at(x, y));
334                    flatten_cubic(cur, p1, p2, to, &mut segments);
335                    cur = to;
336                    cubic_ctrl = Some(p2);
337                    true
338                }
339                _ => false,
340            },
341            b'Q' => match (parser.next_f32(), parser.next_f32(), parser.next_f32(), parser.next_f32()) {
342                (Some(x1), Some(y1), Some(x), Some(y)) => {
343                    let (q, to) = (at(x1, y1), at(x, y));
344                    flatten_quad(cur, q, to, &mut segments);
345                    cur = to;
346                    quad_ctrl = Some(q);
347                    true
348                }
349                _ => false,
350            },
351            b'T' => match (parser.next_f32(), parser.next_f32()) {
352                (Some(x), Some(y)) => {
353                    let q = reflect(last_quad_ctrl, cur);
354                    let to = at(x, y);
355                    flatten_quad(cur, q, to, &mut segments);
356                    cur = to;
357                    quad_ctrl = Some(q);
358                    true
359                }
360                _ => false,
361            },
362            b'A' => match (
363                parser.next_f32(),
364                parser.next_f32(),
365                parser.next_f32(),
366                parser.next_flag(),
367                parser.next_flag(),
368                parser.next_f32(),
369                parser.next_f32(),
370            ) {
371                (Some(rx), Some(ry), Some(rot), Some(large), Some(sweep), Some(x), Some(y)) => {
372                    let to = at(x, y);
373                    flatten_arc(cur, rx, ry, rot, large, sweep, to, &mut segments);
374                    cur = to;
375                    true
376                }
377                _ => false,
378            },
379            _ => false,
380        };
381        last_cubic_ctrl = cubic_ctrl;
382        last_quad_ctrl = quad_ctrl;
383        if !ok {
384            // 未対応のコマンドや壊れた数値は 1 文字読み飛ばす(同じ位置で止まらないように)。
385            if parser.peek().is_some_and(|c| !c.is_ascii_alphabetic()) {
386                parser.next_char();
387            }
388        }
389    }
390    if close_open {
391        close_subpath(&mut segments, cur, start);
392    }
393
394    segments
395}
396
397/// 直前の制御点 `ctrl` を現在点 `cur` について鏡映した点(無ければ現在点。S/T 用)。
398fn reflect(ctrl: Option<Point>, cur: Point) -> Point {
399    match ctrl {
400        Some(c) => Point { x: 2.0 * cur.x - c.x, y: 2.0 * cur.y - c.y },
401        None => cur,
402    }
403}
404
405/// 2 次ベジェ曲線を 3 次に直して直線セグメント列に展開する。
406fn flatten_quad(p0: Point, q: Point, p3: Point, out: &mut Vec<Segment>) {
407    let p1 = Point { x: p0.x + 2.0 / 3.0 * (q.x - p0.x), y: p0.y + 2.0 / 3.0 * (q.y - p0.y) };
408    let p2 = Point { x: p3.x + 2.0 / 3.0 * (q.x - p3.x), y: p3.y + 2.0 / 3.0 * (q.y - p3.y) };
409    flatten_cubic(p0, p1, p2, p3, out);
410}
411
412/// 楕円弧(端点パラメータ。SVG 1.1 付録 F.6.5 で中心パラメータへ変換)を直線セグメント列に展開する。
413/// 半径が 0 なら直線(F.6.6)。
414#[allow(clippy::too_many_arguments)]
415fn flatten_arc(p0: Point, rx: f32, ry: f32, rot_deg: f32, large: bool, sweep: bool, p1: Point, out: &mut Vec<Segment>) {
416    if p0.x == p1.x && p0.y == p1.y {
417        return;
418    }
419    let (mut rx, mut ry) = (libm::fabsf(rx), libm::fabsf(ry));
420    if rx < 1e-6 || ry < 1e-6 {
421        out.push(Segment { p1: p0, p2: p1 });
422        return;
423    }
424    let phi = rot_deg * (core::f32::consts::PI / 180.0);
425    let (cos_phi, sin_phi) = (libm::cosf(phi), libm::sinf(phi));
426    let dx = (p0.x - p1.x) / 2.0;
427    let dy = (p0.y - p1.y) / 2.0;
428    let x1p = cos_phi * dx + sin_phi * dy;
429    let y1p = -sin_phi * dx + cos_phi * dy;
430    let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
431    if lambda > 1.0 {
432        let s = libm::sqrtf(lambda);
433        rx *= s;
434        ry *= s;
435    }
436    let num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
437    let den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
438    let sq = if den > 0.0 { libm::fmaxf(0.0, num / den) } else { 0.0 };
439    let coef = if large == sweep { -1.0 } else { 1.0 } * libm::sqrtf(sq);
440    let cxp = coef * (rx * y1p / ry);
441    let cyp = -coef * (ry * x1p / rx);
442    let cx = cos_phi * cxp - sin_phi * cyp + (p0.x + p1.x) / 2.0;
443    let cy = sin_phi * cxp + cos_phi * cyp + (p0.y + p1.y) / 2.0;
444    let angle = |ux: f32, uy: f32| libm::atan2f(uy, ux);
445    let theta1 = angle((x1p - cxp) / rx, (y1p - cyp) / ry);
446    let theta2 = angle((-x1p - cxp) / rx, (-y1p - cyp) / ry);
447    let tau = core::f32::consts::PI * 2.0;
448    let mut dtheta = theta2 - theta1;
449    if sweep && dtheta < 0.0 {
450        dtheta += tau;
451    } else if !sweep && dtheta > 0.0 {
452        dtheta -= tau;
453    }
454    let steps = libm::ceilf(libm::fabsf(dtheta) / (core::f32::consts::PI / 8.0)).max(2.0) as u32;
455    let mut prev = p0;
456    for i in 1..=steps {
457        let t = theta1 + dtheta * i as f32 / steps as f32;
458        let (ct, st) = (libm::cosf(t), libm::sinf(t));
459        let pt = if i == steps {
460            p1
461        } else {
462            Point { x: cx + rx * ct * cos_phi - ry * st * sin_phi, y: cy + rx * ct * sin_phi + ry * st * cos_phi }
463        };
464        out.push(Segment { p1: prev, p2: pt });
465        prev = pt;
466    }
467}
468
469/// 図形(subpath)が開いていれば始点へ閉じる辺を足す(塗りは図形ごとに暗黙に閉じる。SVG 2 §9.3)。
470/// 【2026-10-25】従来は path 全体の最後の点から最初の点へ 1 本足しており、穴のある文字(YouTube の
471/// ロゴの「o」「b」「e」)で図形どうしを結ぶ辺ができ、その行が左端から塗られていた。
472fn close_subpath(segments: &mut Vec<Segment>, cur: Point, start: Point) {
473    if cur.x != start.x || cur.y != start.y {
474        segments.push(Segment { p1: cur, p2: start });
475    }
476}
477
478/// 3次ベジェ曲線を直線セグメント列に展開する(de Casteljau 法)
479fn flatten_cubic(p0: Point, p1: Point, p2: Point, p3: Point, out: &mut Vec<Segment>) {
480    const STEPS: u32 = 8;
481    let mut prev = p0;
482    for i in 1..=STEPS {
483        let t = i as f32 / STEPS as f32;
484        let mt = 1.0 - t;
485        let x = mt * mt * mt * p0.x
486            + 3.0 * mt * mt * t * p1.x
487            + 3.0 * mt * t * t * p2.x
488            + t * t * t * p3.x;
489        let y = mt * mt * mt * p0.y
490            + 3.0 * mt * mt * t * p1.y
491            + 3.0 * mt * t * t * p2.y
492            + t * t * t * p3.y;
493        let cur = Point { x, y };
494        out.push(Segment { p1: prev, p2: cur });
495        prev = cur;
496    }
497}
498
499// -------------------------------------------------------------------
500// ラスタライザ (Even-Odd, 4x4 スーパーサンプリング)
501// -------------------------------------------------------------------
502
503/// パスセグメント群を指定サイズにラスタライズしてアルファマスク(A8)を返す
504fn rasterize(segments: &[Segment], vb_size: f32, out_size: u32) -> Vec<u8> {
505    let scale = out_size as f32 / vb_size;
506    let w = out_size;
507    let h = out_size;
508    let mut data = alloc::vec![0u8; (w * h) as usize];
509
510    for py in 0..h {
511        for px in 0..w {
512            let mut inside = 0u32;
513            for sy in 0..4u32 {
514                let sub_y = py as f32 + (sy as f32 + 0.5) / 4.0;
515                for sx in 0..4u32 {
516                    let sub_x = px as f32 + (sx as f32 + 0.5) / 4.0;
517                    // スケール逆変換: ピクセル座標 → viewBox 座標
518                    let vx = sub_x / scale;
519                    let vy = sub_y / scale;
520                    let mut crossings = 0u32;
521                    for seg in segments {
522                        let y1 = seg.p1.y;
523                        let y2 = seg.p2.y;
524                        let y_min = if y1 < y2 { y1 } else { y2 };
525                        let y_max = if y1 > y2 { y1 } else { y2 };
526                        if vy >= y_min && vy < y_max && y1 != y2 {
527                            let t = (vy - y1) / (y2 - y1);
528                            let ix = seg.p1.x + t * (seg.p2.x - seg.p1.x);
529                            if ix > vx {
530                                crossings += 1;
531                            }
532                        }
533                    }
534                    if !crossings.is_multiple_of(2) {
535                        inside += 1;
536                    }
537                }
538            }
539            data[(py * w + px) as usize] = ((inside * 255) / 16).min(255) as u8;
540        }
541    }
542    data
543}
544
545// -------------------------------------------------------------------
546// SVG 全体パーサ(path d 属性を抽出する)
547// -------------------------------------------------------------------
548
549/// SVG XML から `<path d="...">` の d 属性値を抽出する
550fn extract_path_d(svg: &[u8]) -> Option<alloc::string::String> {
551    let text = core::str::from_utf8(svg).ok()?;
552    // 'd="' を探す
553    let mut search = text;
554    while let Some(pos) = find_substr(search, " d=\"") {
555        let after = search.get(pos + 4..).unwrap_or(""); // `"` の次から
556        if let Some(end) = find_char(after.as_bytes(), b'"') {
557            return Some(alloc::string::String::from(after.get(..end).unwrap_or("")));
558        }
559        search = search.get(pos + 1..).unwrap_or("");
560    }
561    // d=' 形式も試す
562    let mut search2 = text;
563    while let Some(pos) = find_substr(search2, " d='") {
564        let after = search2.get(pos + 4..).unwrap_or("");
565        if let Some(end) = find_char(after.as_bytes(), b'\'') {
566            return Some(alloc::string::String::from(after.get(..end).unwrap_or("")));
567        }
568        search2 = search2.get(pos + 1..).unwrap_or("");
569    }
570    None
571}
572
573/// viewBox の幅を取得する(正方形アイコン前提)
574fn extract_viewbox_size(svg: &[u8]) -> f32 {
575    let text = core::str::from_utf8(svg).unwrap_or("");
576    if let Some(pos) = find_substr(text, "viewBox=\"") {
577        let after = text.get(pos + 9..).unwrap_or("");
578        // "0 0 W H" の形式を想定
579        let mut p = PathParser::new(after.as_bytes());
580        let _ = p.next_f32(); // x_min
581        let _ = p.next_f32(); // y_min
582        if let Some(w) = p.next_f32() {
583            return w;
584        }
585    }
586    20.0 // デフォルト
587}
588
589fn find_substr(haystack: &str, needle: &str) -> Option<usize> {
590    let hb = haystack.as_bytes();
591    let nb = needle.as_bytes();
592    if nb.is_empty() {
593        return Some(0);
594    }
595    hb.windows(nb.len()).position(|w| w == nb)
596}
597
598fn find_char(haystack: &[u8], needle: u8) -> Option<usize> {
599    haystack.iter().position(|&b| b == needle)
600}
601
602// -------------------------------------------------------------------
603// フル SVG 画像デコード(<img src="*.svg"> / インライン SVG)
604// path/rect/circle/ellipse/line/polygon/polyline/<use> を fill/stroke/グラデーションつきで RGBA 合成する
605// -------------------------------------------------------------------
606
607#[derive(Clone, Copy)]
608struct GradientStop {
609    offset: f32, // 0.0..=1.0
610    color: u32,  // 0xAARRGGBB
611}
612
613#[derive(Clone)]
614enum SvgGradient {
615    Linear {
616        x1: f32,
617        y1: f32,
618        x2: f32,
619        y2: f32,
620        user_space: bool,
621        stops: Vec<GradientStop>,
622    },
623    Radial {
624        cx: f32,
625        cy: f32,
626        r: f32,
627        user_space: bool,
628        stops: Vec<GradientStop>,
629    },
630}
631
632#[derive(Clone)]
633enum SvgPaint {
634    None,
635    Solid(u32), // 0xAARRGGBB
636    Gradient(SvgGradient, f32),
637}
638
639impl SvgPaint {
640    fn is_none(&self) -> bool {
641        match self {
642            SvgPaint::None => true,
643            SvgPaint::Solid(c) => ((*c >> 24) & 0xFF) == 0,
644            SvgPaint::Gradient(g, op) => *op <= 0.0 || match g {
645                SvgGradient::Linear { stops, .. } | SvgGradient::Radial { stops, .. } => stops.is_empty(),
646            },
647        }
648    }
649
650    fn sample(&self, vx: f32, vy: f32, bbox: (f32, f32, f32, f32)) -> u32 {
651        match self {
652            SvgPaint::None => 0,
653            SvgPaint::Solid(c) => *c,
654            SvgPaint::Gradient(grad, op) => {
655                let (t, stops) = match grad {
656                    SvgGradient::Linear { x1, y1, x2, y2, user_space, stops } => {
657                        let (nx, ny) = if *user_space {
658                            (vx, vy)
659                        } else {
660                            let bw = (bbox.2 - bbox.0).max(1e-5);
661                            let bh = (bbox.3 - bbox.1).max(1e-5);
662                            ((vx - bbox.0) / bw, (vy - bbox.1) / bh)
663                        };
664                        let dx = *x2 - *x1;
665                        let dy = *y2 - *y1;
666                        let len_sq = dx * dx + dy * dy;
667                        let t = if len_sq > 1e-6 {
668                            (((nx - *x1) * dx + (ny - *y1) * dy) / len_sq).clamp(0.0, 1.0)
669                        } else {
670                            0.0
671                        };
672                        (t, stops)
673                    }
674                    SvgGradient::Radial { cx, cy, r, user_space, stops } => {
675                        let (nx, ny) = if *user_space {
676                            (vx, vy)
677                        } else {
678                            let bw = (bbox.2 - bbox.0).max(1e-5);
679                            let bh = (bbox.3 - bbox.1).max(1e-5);
680                            ((vx - bbox.0) / bw, (vy - bbox.1) / bh)
681                        };
682                        let dx = nx - *cx;
683                        let dy = ny - *cy;
684                        let dist = libm::sqrtf(dx * dx + dy * dy);
685                        let t = if *r > 1e-6 { (dist / *r).clamp(0.0, 1.0) } else { 0.0 };
686                        (t, stops)
687                    }
688                };
689                let c = interpolate_stops(stops, t);
690                let a = (((c >> 24) & 0xFF) as f32 * op.clamp(0.0, 1.0)) as u32;
691                (a << 24) | (c & 0x00FFFFFF)
692            }
693        }
694    }
695}
696
697fn interpolate_stops(stops: &[GradientStop], t: f32) -> u32 {
698    if stops.is_empty() {
699        return 0;
700    }
701    if t <= stops[0].offset || stops.len() == 1 {
702        return stops[0].color;
703    }
704    for w in stops.windows(2) {
705        if t <= w[1].offset {
706            let span = (w[1].offset - w[0].offset).max(1e-5);
707            let u = ((t - w[0].offset) / span).clamp(0.0, 1.0);
708            let c0 = w[0].color;
709            let c1 = w[1].color;
710            let lerp = |s0: u32, s1: u32| -> u32 {
711                (s0 as f32 + (s1 as f32 - s0 as f32) * u).clamp(0.0, 255.0) as u32
712            };
713            let a = lerp((c0 >> 24) & 0xFF, (c1 >> 24) & 0xFF);
714            let r = lerp((c0 >> 16) & 0xFF, (c1 >> 16) & 0xFF);
715            let g = lerp((c0 >> 8) & 0xFF, (c1 >> 8) & 0xFF);
716            let b = lerp(c0 & 0xFF, c1 & 0xFF);
717            return (a << 24) | (r << 16) | (g << 8) | b;
718        }
719    }
720    stops[stops.len() - 1].color
721}
722
723/// 1 つの描画図形(塗りまたはストローク)
724struct SvgShape {
725    segments: Vec<Segment>,
726    paint: SvgPaint,
727    /// `None` なら Even-Odd 塗り、`Some(half_w)` なら線分からの距離 `<= half_w` のストローク描画
728    stroke_half_width: Option<f32>,
729    bbox: (f32, f32, f32, f32),
730}
731
732fn segments_bbox(segs: &[Segment], pad: f32) -> (f32, f32, f32, f32) {
733    let mut min_x = f32::INFINITY;
734    let mut min_y = f32::INFINITY;
735    let mut max_x = f32::NEG_INFINITY;
736    let mut max_y = f32::NEG_INFINITY;
737    for s in segs {
738        for p in [s.p1, s.p2] {
739            if p.x < min_x {
740                min_x = p.x;
741            }
742            if p.y < min_y {
743                min_y = p.y;
744            }
745            if p.x > max_x {
746                max_x = p.x;
747            }
748            if p.y > max_y {
749                max_y = p.y;
750            }
751        }
752    }
753    if !min_x.is_finite() {
754        (0.0, 0.0, 0.0, 0.0)
755    } else {
756        (min_x - pad, min_y - pad, max_x + pad, max_y + pad)
757    }
758}
759
760fn point_seg_dist_sq(px: f32, py: f32, p1: Point, p2: Point) -> f32 {
761    let dx = p2.x - p1.x;
762    let dy = p2.y - p1.y;
763    let len_sq = dx * dx + dy * dy;
764    if len_sq <= 1e-8 {
765        let ex = px - p1.x;
766        let ey = py - p1.y;
767        return ex * ex + ey * ey;
768    }
769    let t = (((px - p1.x) * dx + (py - p1.y) * dy) / len_sq).clamp(0.0, 1.0);
770    let cx = p1.x + t * dx;
771    let cy = p1.y + t * dy;
772    let ex = px - cx;
773    let ey = py - cy;
774    ex * ex + ey * ey
775}
776
777/// SVG バイト列を target_w × target_h の RGBA8888 にラスタライズする。
778/// viewBox に従ってアスペクトを保ちつつスケールする。
779pub fn decode_svg_image(svg: &[u8], target_w: u32, target_h: u32) -> Option<(u32, u32, Vec<u8>)> {
780    let text = core::str::from_utf8(svg).ok()?;
781    if target_w == 0 || target_h == 0 || target_w > 4096 || target_h > 4096 {
782        return None;
783    }
784
785    // viewBox("minx miny w h")を取得。無ければ width/height、無ければ 100。
786    let (vb_x, vb_y, vb_w, vb_h) = extract_viewbox_rect(text);
787
788    // 図形を収集(描画順 = ソース順 = ペインターズアルゴリズム)
789    let shapes = collect_svg_shapes(text);
790    if shapes.is_empty() {
791        return None;
792    }
793
794    let sx = target_w as f32 / vb_w;
795    let sy = target_h as f32 / vb_h;
796    let min_stroke_hw = 0.5 / sx.min(sy).max(1e-4);
797    let mut rgba = alloc::vec![0u8; (target_w * target_h * 4) as usize];
798
799    for shape in &shapes {
800        if shape.paint.is_none() || shape.segments.is_empty() {
801            continue;
802        }
803        let stroke_hw_sq = shape.stroke_half_width.map(|hw| {
804            let h = hw.max(min_stroke_hw);
805            h * h
806        });
807
808        for py in 0..target_h {
809            for px in 0..target_w {
810                let mut inside = 0u32;
811                for sample in 0..4u32 {
812                    let ox = if sample & 1 == 0 { 0.25 } else { 0.75 };
813                    let oy = if sample & 2 == 0 { 0.25 } else { 0.75 };
814                    let vx = (px as f32 + ox) / sx + vb_x;
815                    let vy = (py as f32 + oy) / sy + vb_y;
816                    if let Some(hw_sq) = stroke_hw_sq {
817                        if shape
818                            .segments
819                            .iter()
820                            .any(|seg| point_seg_dist_sq(vx, vy, seg.p1, seg.p2) <= hw_sq)
821                        {
822                            inside += 1;
823                        }
824                    } else {
825                        let mut crossings = 0u32;
826                        for seg in &shape.segments {
827                            let (y1, y2) = (seg.p1.y, seg.p2.y);
828                            let ymin = if y1 < y2 { y1 } else { y2 };
829                            let ymax = if y1 > y2 { y1 } else { y2 };
830                            if vy >= ymin && vy < ymax && y1 != y2 {
831                                let t = (vy - y1) / (y2 - y1);
832                                let ix = seg.p1.x + t * (seg.p2.x - seg.p1.x);
833                                if ix > vx {
834                                    crossings += 1;
835                                }
836                            }
837                        }
838                        if crossings % 2 == 1 {
839                            inside += 1;
840                        }
841                    }
842                }
843                if inside == 0 {
844                    continue;
845                }
846                let vx_center = (px as f32 + 0.5) / sx + vb_x;
847                let vy_center = (py as f32 + 0.5) / sy + vb_y;
848                let color = shape.paint.sample(vx_center, vy_center, shape.bbox);
849                let a = (color >> 24) & 0xFF;
850                if a == 0 {
851                    continue;
852                }
853                let fr = ((color >> 16) & 0xFF) as f32;
854                let fg = ((color >> 8) & 0xFF) as f32;
855                let fb = (color & 0xFF) as f32;
856                let fa = a as f32 / 255.0;
857                let cov = (inside as f32 / 4.0) * fa;
858                let o = ((py * target_w + px) * 4) as usize;
859                // src-over 合成
860                let dr = rgba[o] as f32;
861                let dg = rgba[o + 1] as f32;
862                let db = rgba[o + 2] as f32;
863                let da = rgba[o + 3] as f32 / 255.0;
864                let out_a = cov + da * (1.0 - cov);
865                if out_a <= 0.0 {
866                    continue;
867                }
868                rgba[o] = (((fr * cov + dr * da * (1.0 - cov)) / out_a).min(255.0)) as u8;
869                rgba[o + 1] = (((fg * cov + dg * da * (1.0 - cov)) / out_a).min(255.0)) as u8;
870                rgba[o + 2] = (((fb * cov + db * da * (1.0 - cov)) / out_a).min(255.0)) as u8;
871                rgba[o + 3] = (out_a * 255.0).min(255.0) as u8;
872            }
873        }
874    }
875
876    Some((target_w, target_h, rgba))
877}
878
879/// SVG の自然サイズ(w,h)を返す(ラスタライズ目標解像度の決定用)。
880pub fn natural_size(svg: &[u8]) -> (f32, f32) {
881    if let Ok(text) = core::str::from_utf8(svg) {
882        let (_, _, w, h) = extract_viewbox_rect(text);
883        (w, h)
884    } else {
885        (100.0, 100.0)
886    }
887}
888
889/// viewBox を (x, y, w, h) で返す。無ければ width/height、それも無ければ 100x100。
890fn extract_viewbox_rect(text: &str) -> (f32, f32, f32, f32) {
891    if let Some(pos) = find_substr(text, "viewBox=\"") {
892        let after = text.get(pos + 9..).unwrap_or("");
893        if let Some(end) = find_char(after.as_bytes(), b'"') {
894            let mut p = PathParser::new(&after.as_bytes()[..end]);
895            let x = p.next_f32().unwrap_or(0.0);
896            let y = p.next_f32().unwrap_or(0.0);
897            let w = p.next_f32().unwrap_or(100.0);
898            let h = p.next_f32().unwrap_or(100.0);
899            if w > 0.0 && h > 0.0 {
900                return (x, y, w, h);
901            }
902        }
903    }
904    let w = extract_attr_f32(text, "width").unwrap_or(100.0);
905    let h = extract_attr_f32(text, "height").unwrap_or(100.0);
906    (0.0, 0.0, w.max(1.0), h.max(1.0))
907}
908
909/// タグの属性値を数値で取得("<svg ... width=\"NN\"" の最初の出現)
910fn extract_attr_f32(text: &str, name: &str) -> Option<f32> {
911    let needle = alloc::format!(" {}=\"", name);
912    let pos = find_substr(text, &needle)?;
913    let after = text.get(pos + needle.len()..).unwrap_or("");
914    let end = find_char(after.as_bytes(), b'"')?;
915    let mut p = PathParser::new(&after.as_bytes()[..end]);
916    p.next_f32()
917}
918
919/// 1 つの開始タグ("<tag ...>")から属性値文字列を取得(属性名の前に空白または属性区切りが必要)
920fn tag_attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
921    for q in ['"', '\''] {
922        for prefix in [" ", "\t", "\n", "\r"] {
923            let needle = alloc::format!("{}{}={}", prefix, name, q);
924            if let Some(pos) = find_substr(tag, &needle) {
925                let after = tag.get(pos + needle.len()..).unwrap_or("");
926                if let Some(end) = find_char(after.as_bytes(), q as u8) {
927                    return after.get(..end);
928                }
929            }
930        }
931    }
932    None
933}
934
935fn style_prop<'a>(tag: &'a str, prop: &str) -> Option<&'a str> {
936    let style = tag_attr(tag, "style")?;
937    for part in style.split(';') {
938        if let Some((k, v)) = part.split_once(':') {
939            if k.trim().eq_ignore_ascii_case(prop) {
940                return Some(v.trim());
941            }
942        }
943    }
944    None
945}
946
947fn parse_grad_coord(val: Option<&str>, default: f32) -> f32 {
948    let Some(s) = val else { return default };
949    let s = s.trim();
950    if let Some(pct) = s.strip_suffix('%') {
951        let mut p = PathParser::new(pct.as_bytes());
952        p.next_f32().map(|v| v / 100.0).unwrap_or(default)
953    } else {
954        let mut p = PathParser::new(s.as_bytes());
955        p.next_f32().unwrap_or(default)
956    }
957}
958
959fn collect_svg_gradients(text: &str) -> BTreeMap<alloc::string::String, SvgGradient> {
960    let mut grads = BTreeMap::new();
961    let bytes = text.as_bytes();
962    let mut i = 0;
963    while i < bytes.len() {
964        if bytes[i] != b'<' {
965            i += 1;
966            continue;
967        }
968        let tag_start = i + 1;
969        let mut j = tag_start;
970        while j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'-' || bytes[j] == b':') {
971            j += 1;
972        }
973        let name = text.get(tag_start..j).unwrap_or("");
974        let is_linear = name.eq_ignore_ascii_case("lineargradient");
975        let is_radial = name.eq_ignore_ascii_case("radialgradient");
976        if !is_linear && !is_radial {
977            i += 1;
978            continue;
979        }
980        let Some(end_rel) = find_char(&bytes[i..], b'>') else { break };
981        let end = i + end_rel;
982        let open_tag = text.get(i..=end).unwrap_or("");
983        let Some(id) = tag_attr(open_tag, "id") else {
984            i = end + 1;
985            continue;
986        };
987        let user_space = tag_attr(open_tag, "gradientUnits")
988            .or_else(|| tag_attr(open_tag, "gradientunits"))
989            .is_some_and(|u| u.trim().eq_ignore_ascii_case("userspaceonuse"));
990
991        // 閉じタグを探す
992        let mut body_end = end + 1;
993        if !open_tag.ends_with("/>") {
994            let mut k = end + 1;
995            while k + 2 < bytes.len() {
996                if bytes[k] == b'<' && bytes[k + 1] == b'/' {
997                    let cs = k + 2;
998                    let mut ce = cs;
999                    while ce < bytes.len() && bytes[ce].is_ascii_alphabetic() {
1000                        ce += 1;
1001                    }
1002                    if text.get(cs..ce).unwrap_or("").eq_ignore_ascii_case(name) {
1003                        body_end = k;
1004                        break;
1005                    }
1006                }
1007                k += 1;
1008            }
1009        }
1010        let body = text.get(end + 1..body_end).unwrap_or("");
1011        let mut stops = Vec::new();
1012        let bbytes = body.as_bytes();
1013        let mut bi = 0;
1014        while bi < bbytes.len() {
1015            if bbytes[bi] != b'<' {
1016                bi += 1;
1017                continue;
1018            }
1019            let s_start = bi + 1;
1020            let mut sj = s_start;
1021            while sj < bbytes.len() && bbytes[sj].is_ascii_alphabetic() {
1022                sj += 1;
1023            }
1024            let sname = body.get(s_start..sj).unwrap_or("");
1025            let Some(send_rel) = find_char(&bbytes[bi..], b'>') else { break };
1026            let send = bi + send_rel;
1027            if sname.eq_ignore_ascii_case("stop") {
1028                let stag = body.get(bi..=send).unwrap_or("");
1029                let offset = parse_grad_coord(tag_attr(stag, "offset"), 0.0).clamp(0.0, 1.0);
1030                let sc_str = tag_attr(stag, "stop-color").or_else(|| style_prop(stag, "stop-color")).unwrap_or("#000");
1031                let so_str = tag_attr(stag, "stop-opacity").or_else(|| style_prop(stag, "stop-opacity"));
1032                let so = parse_grad_coord(so_str, 1.0).clamp(0.0, 1.0);
1033                let parsed = crate::os_lib::css::parse_color(sc_str.trim()).unwrap_or(0xFF000000);
1034                let base_a = ((parsed >> 24) & 0xFF) as f32 / 255.0;
1035                let a = ((base_a * so).clamp(0.0, 1.0) * 255.0) as u32;
1036                stops.push(GradientStop {
1037                    offset,
1038                    color: (a << 24) | (parsed & 0x00FFFFFF),
1039                });
1040            }
1041            bi = send + 1;
1042        }
1043        let grad = if is_linear {
1044            SvgGradient::Linear {
1045                x1: parse_grad_coord(tag_attr(open_tag, "x1"), 0.0),
1046                y1: parse_grad_coord(tag_attr(open_tag, "y1"), 0.0),
1047                x2: parse_grad_coord(tag_attr(open_tag, "x2"), 1.0),
1048                y2: parse_grad_coord(tag_attr(open_tag, "y2"), 0.0),
1049                user_space,
1050                stops,
1051            }
1052        } else {
1053            SvgGradient::Radial {
1054                cx: parse_grad_coord(tag_attr(open_tag, "cx"), 0.5),
1055                cy: parse_grad_coord(tag_attr(open_tag, "cy"), 0.5),
1056                r: parse_grad_coord(tag_attr(open_tag, "r"), 0.5),
1057                user_space,
1058                stops,
1059            }
1060        };
1061        grads.insert(alloc::string::String::from(id), grad);
1062        i = body_end.max(end + 1);
1063    }
1064    grads
1065}
1066
1067#[derive(Clone, Default)]
1068struct InheritCtx<'a> {
1069    fill: Option<&'a str>,
1070    stroke: Option<&'a str>,
1071    stroke_width: Option<f32>,
1072    tx: f32,
1073    ty: f32,
1074}
1075
1076fn parse_paint(
1077    raw: Option<&str>,
1078    opacity: f32,
1079    default_black: bool,
1080    grads: &BTreeMap<alloc::string::String, SvgGradient>,
1081) -> SvgPaint {
1082    let op = opacity.clamp(0.0, 1.0);
1083    match raw.map(str::trim) {
1084        Some("none" | "transparent") => SvgPaint::None,
1085        Some(s) if s.starts_with("url(") => {
1086            let inner = s
1087                .strip_prefix("url(")
1088                .and_then(|r| r.strip_suffix(')'))
1089                .unwrap_or("")
1090                .trim()
1091                .trim_matches('"')
1092                .trim_matches('\'');
1093            let id = inner.strip_prefix('#').unwrap_or(inner);
1094            match grads.get(id) {
1095                Some(g) => SvgPaint::Gradient(g.clone(), op),
1096                None => SvgPaint::None,
1097            }
1098        }
1099        Some(s) if !s.is_empty() => {
1100            let parsed = crate::os_lib::css::parse_color(s).unwrap_or(0xFF000000);
1101            let base_a = ((parsed >> 24) & 0xFF) as f32 / 255.0;
1102            let a = ((base_a * op).clamp(0.0, 1.0) * 255.0) as u32;
1103            SvgPaint::Solid((a << 24) | (parsed & 0x00FFFFFF))
1104        }
1105        _ => {
1106            if default_black {
1107                let a = (op * 255.0) as u32;
1108                SvgPaint::Solid(a << 24)
1109            } else {
1110                SvgPaint::None
1111            }
1112        }
1113    }
1114}
1115
1116fn resolve_fill_paint(
1117    tag: &str,
1118    is_line: bool,
1119    ctx: &InheritCtx<'_>,
1120    grads: &BTreeMap<alloc::string::String, SvgGradient>,
1121) -> SvgPaint {
1122    if is_line {
1123        return SvgPaint::None;
1124    }
1125    let fill_str = tag_attr(tag, "fill")
1126        .or_else(|| style_prop(tag, "fill"))
1127        .or(ctx.fill);
1128    let opacity = tag_attr(tag, "fill-opacity")
1129        .or_else(|| style_prop(tag, "fill-opacity"))
1130        .and_then(|s| PathParser::new(s.as_bytes()).next_f32())
1131        .unwrap_or(1.0);
1132    parse_paint(fill_str, opacity, true, grads)
1133}
1134
1135fn resolve_stroke_paint(
1136    tag: &str,
1137    ctx: &InheritCtx<'_>,
1138    grads: &BTreeMap<alloc::string::String, SvgGradient>,
1139) -> (SvgPaint, f32) {
1140    let stroke_str = tag_attr(tag, "stroke")
1141        .or_else(|| style_prop(tag, "stroke"))
1142        .or(ctx.stroke);
1143    let opacity = tag_attr(tag, "stroke-opacity")
1144        .or_else(|| style_prop(tag, "stroke-opacity"))
1145        .and_then(|s| PathParser::new(s.as_bytes()).next_f32())
1146        .unwrap_or(1.0);
1147    let paint = parse_paint(stroke_str, opacity, false, grads);
1148    let width = tag_attr(tag, "stroke-width")
1149        .or_else(|| style_prop(tag, "stroke-width"))
1150        .and_then(|s| PathParser::new(s.as_bytes()).next_f32())
1151        .or(ctx.stroke_width)
1152        .unwrap_or(1.0);
1153    (paint, width)
1154}
1155
1156fn parse_translate(tag: &str) -> (f32, f32) {
1157    let Some(tr) = tag_attr(tag, "transform") else { return (0.0, 0.0) };
1158    if let Some(pos) = find_substr(tr, "translate(") {
1159        let after = tr.get(pos + 10..).unwrap_or("");
1160        let mut p = PathParser::new(after.as_bytes());
1161        let tx = p.next_f32().unwrap_or(0.0);
1162        let ty = p.next_f32().unwrap_or(0.0);
1163        return (tx, ty);
1164    }
1165    (0.0, 0.0)
1166}
1167
1168fn offset_segments(segs: &mut [Segment], tx: f32, ty: f32) {
1169    if tx == 0.0 && ty == 0.0 {
1170        return;
1171    }
1172    for s in segs {
1173        s.p1.x += tx;
1174        s.p1.y += ty;
1175        s.p2.x += tx;
1176        s.p2.y += ty;
1177    }
1178}
1179
1180/// id="..." を持つ要素の範囲(単一タグまたは開始〜終了タグ)を収集する(<use href="#id"> 用)
1181fn collect_id_defs(text: &str) -> BTreeMap<alloc::string::String, &str> {
1182    let mut map = BTreeMap::new();
1183    let bytes = text.as_bytes();
1184    let mut i = 0;
1185    while i < bytes.len() {
1186        if bytes[i] != b'<' || bytes.get(i + 1) == Some(&b'/') {
1187            i += 1;
1188            continue;
1189        }
1190        let tag_start = i + 1;
1191        let mut j = tag_start;
1192        while j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'-' || bytes[j] == b':') {
1193            j += 1;
1194        }
1195        let name = text.get(tag_start..j).unwrap_or("");
1196        let Some(end_rel) = find_char(&bytes[i..], b'>') else { break };
1197        let end = i + end_rel;
1198        let tag = text.get(i..=end).unwrap_or("");
1199        if let Some(id) = tag_attr(tag, "id") {
1200            if tag.ends_with("/>") {
1201                map.insert(alloc::string::String::from(id), tag);
1202            } else {
1203                // 対応する閉じタグ </name> を探す
1204                let mut depth = 1u32;
1205                let mut k = end + 1;
1206                let mut slice_end = end + 1;
1207                while k < bytes.len() {
1208                    if bytes[k] == b'<' {
1209                        let is_close = bytes.get(k + 1) == Some(&b'/');
1210                        let ns = if is_close { k + 2 } else { k + 1 };
1211                        let mut ne = ns;
1212                        while ne < bytes.len() && (bytes[ne].is_ascii_alphanumeric() || bytes[ne] == b'-' || bytes[ne] == b':') {
1213                            ne += 1;
1214                        }
1215                        let cname = text.get(ns..ne).unwrap_or("");
1216                        if let Some(cend_rel) = find_char(&bytes[k..], b'>') {
1217                            let cend = k + cend_rel;
1218                            let ctag = text.get(k..=cend).unwrap_or("");
1219                            if cname.eq_ignore_ascii_case(name) {
1220                                if is_close {
1221                                    depth -= 1;
1222                                    if depth == 0 {
1223                                        slice_end = cend + 1;
1224                                        break;
1225                                    }
1226                                } else if !ctag.ends_with("/>") {
1227                                    depth += 1;
1228                                }
1229                            }
1230                            k = cend + 1;
1231                            continue;
1232                        }
1233                    }
1234                    k += 1;
1235                }
1236                if let Some(s) = text.get(i..slice_end) {
1237                    map.insert(alloc::string::String::from(id), s);
1238                }
1239            }
1240        }
1241        i = end + 1;
1242    }
1243    map
1244}
1245
1246/// SVG 本文から塗りつぶし・ストローク図形を収集する
1247fn collect_svg_shapes(text: &str) -> Vec<SvgShape> {
1248    let grads = collect_svg_gradients(text);
1249    let id_defs = collect_id_defs(text);
1250    let mut shapes = Vec::new();
1251    let root_ctx = InheritCtx::default();
1252    collect_shapes_in_fragment(text, &root_ctx, &id_defs, &grads, 0, &mut shapes);
1253    shapes
1254}
1255
1256fn collect_shapes_in_fragment<'a>(
1257    text: &'a str,
1258    base_ctx: &InheritCtx<'a>,
1259    id_defs: &BTreeMap<alloc::string::String, &'a str>,
1260    grads: &BTreeMap<alloc::string::String, SvgGradient>,
1261    use_depth: u32,
1262    shapes: &mut Vec<SvgShape>,
1263) {
1264    if use_depth > 8 {
1265        return;
1266    }
1267    let bytes = text.as_bytes();
1268    let mut i = 0;
1269    let mut defs_depth = 0u32;
1270    let mut ctx_stack: Vec<InheritCtx<'a>> = alloc::vec![base_ctx.clone()];
1271
1272    while i < bytes.len() {
1273        if bytes[i] != b'<' {
1274            i += 1;
1275            continue;
1276        }
1277        let is_close = bytes.get(i + 1) == Some(&b'/');
1278        let tag_start = if is_close { i + 2 } else { i + 1 };
1279        let mut j = tag_start;
1280        while j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'-' || bytes[j] == b':') {
1281            j += 1;
1282        }
1283        let name = text.get(tag_start..j).unwrap_or("");
1284        let end = match find_char(&bytes[i..], b'>') {
1285            Some(e) => i + e,
1286            None => break,
1287        };
1288        let tag = text.get(i..end + 1).unwrap_or("");
1289        let self_closing = tag.ends_with("/>");
1290
1291        if is_close {
1292            if name.eq_ignore_ascii_case("defs") || (name.eq_ignore_ascii_case("symbol") && use_depth == 0) {
1293                defs_depth = defs_depth.saturating_sub(1);
1294            } else if (name.eq_ignore_ascii_case("g") || name.eq_ignore_ascii_case("svg") || name.eq_ignore_ascii_case("symbol"))
1295                && ctx_stack.len() > 1 {
1296                    ctx_stack.pop();
1297                }
1298            i = end + 1;
1299            continue;
1300        }
1301
1302        if name.eq_ignore_ascii_case("defs") || (name.eq_ignore_ascii_case("symbol") && use_depth == 0) {
1303            if !self_closing {
1304                defs_depth += 1;
1305            }
1306            i = end + 1;
1307            continue;
1308        }
1309
1310        let cur_ctx = ctx_stack.last().cloned().unwrap_or_default();
1311        let (dtx, dty) = parse_translate(tag);
1312        let elem_ctx = InheritCtx {
1313            fill: tag_attr(tag, "fill").or_else(|| style_prop(tag, "fill")).or(cur_ctx.fill),
1314            stroke: tag_attr(tag, "stroke").or_else(|| style_prop(tag, "stroke")).or(cur_ctx.stroke),
1315            stroke_width: tag_attr(tag, "stroke-width")
1316                .or_else(|| style_prop(tag, "stroke-width"))
1317                .and_then(|s| PathParser::new(s.as_bytes()).next_f32())
1318                .or(cur_ctx.stroke_width),
1319            tx: cur_ctx.tx + dtx,
1320            ty: cur_ctx.ty + dty,
1321        };
1322
1323        if name.eq_ignore_ascii_case("g") || name.eq_ignore_ascii_case("svg") || name.eq_ignore_ascii_case("symbol") {
1324            if !self_closing {
1325                ctx_stack.push(elem_ctx);
1326            }
1327            i = end + 1;
1328            continue;
1329        }
1330
1331        if defs_depth > 0 {
1332            i = end + 1;
1333            continue;
1334        }
1335
1336        if name.eq_ignore_ascii_case("use") {
1337            if let Some(href) = tag_attr(tag, "href").or_else(|| tag_attr(tag, "xlink:href")) {
1338                let target_id = href.trim().strip_prefix('#').unwrap_or(href.trim());
1339                if let Some(&target_fragment) = id_defs.get(target_id) {
1340                    let ux = attr_num(tag, "x");
1341                    let uy = attr_num(tag, "y");
1342                    let mut use_ctx = elem_ctx.clone();
1343                    use_ctx.tx += ux;
1344                    use_ctx.ty += uy;
1345                    collect_shapes_in_fragment(target_fragment, &use_ctx, id_defs, grads, use_depth + 1, shapes);
1346                }
1347            }
1348            i = end + 1;
1349            continue;
1350        }
1351
1352        let is_line = name.eq_ignore_ascii_case("line");
1353        let fill_paint = resolve_fill_paint(tag, is_line, &cur_ctx, grads);
1354        let (stroke_paint, stroke_width) = resolve_stroke_paint(tag, &cur_ctx, grads);
1355
1356        let mut push_shape_pair = |mut fill_segs: Vec<Segment>, mut stroke_segs: Vec<Segment>| {
1357            offset_segments(&mut fill_segs, elem_ctx.tx, elem_ctx.ty);
1358            offset_segments(&mut stroke_segs, elem_ctx.tx, elem_ctx.ty);
1359            if !fill_paint.is_none() && !fill_segs.is_empty() {
1360                let bbox = segments_bbox(&fill_segs, 0.0);
1361                shapes.push(SvgShape {
1362                    segments: fill_segs,
1363                    paint: fill_paint.clone(),
1364                    stroke_half_width: None,
1365                    bbox,
1366                });
1367            }
1368            if !stroke_paint.is_none() && stroke_width > 0.0 && !stroke_segs.is_empty() {
1369                let hw = stroke_width * 0.5;
1370                let bbox = segments_bbox(&stroke_segs, hw);
1371                shapes.push(SvgShape {
1372                    segments: stroke_segs,
1373                    paint: stroke_paint.clone(),
1374                    stroke_half_width: Some(hw),
1375                    bbox,
1376                });
1377            }
1378        };
1379
1380        match name {
1381            "path" => {
1382                if let Some(d) = tag_attr(tag, "d") {
1383                    let fill_segs = if fill_paint.is_none() { Vec::new() } else { parse_path_d_ex(d, true) };
1384                    let stroke_segs = if stroke_paint.is_none() { Vec::new() } else { parse_path_d_ex(d, false) };
1385                    push_shape_pair(fill_segs, stroke_segs);
1386                }
1387            }
1388            "rect" => {
1389                let x = attr_num(tag, "x");
1390                let y = attr_num(tag, "y");
1391                let w = attr_num(tag, "width");
1392                let h = attr_num(tag, "height");
1393                if w > 0.0 && h > 0.0 {
1394                    let pts = [
1395                        Point { x, y },
1396                        Point { x: x + w, y },
1397                        Point { x: x + w, y: y + h },
1398                        Point { x, y: y + h },
1399                    ];
1400                    let segs = poly_segments(&pts, true);
1401                    push_shape_pair(segs.clone(), segs);
1402                }
1403            }
1404            "circle" => {
1405                let cx = attr_num(tag, "cx");
1406                let cy = attr_num(tag, "cy");
1407                let r = attr_num(tag, "r");
1408                if r > 0.0 {
1409                    let segs = ellipse_segments(cx, cy, r, r);
1410                    push_shape_pair(segs.clone(), segs);
1411                }
1412            }
1413            "ellipse" => {
1414                let cx = attr_num(tag, "cx");
1415                let cy = attr_num(tag, "cy");
1416                let rx = attr_num(tag, "rx");
1417                let ry = attr_num(tag, "ry");
1418                if rx > 0.0 && ry > 0.0 {
1419                    let segs = ellipse_segments(cx, cy, rx, ry);
1420                    push_shape_pair(segs.clone(), segs);
1421                }
1422            }
1423            "line" => {
1424                let x1 = attr_num(tag, "x1");
1425                let y1 = attr_num(tag, "y1");
1426                let x2 = attr_num(tag, "x2");
1427                let y2 = attr_num(tag, "y2");
1428                let segs = alloc::vec![Segment { p1: Point { x: x1, y: y1 }, p2: Point { x: x2, y: y2 } }];
1429                push_shape_pair(Vec::new(), segs);
1430            }
1431            "polygon" => {
1432                if let Some(pts_str) = tag_attr(tag, "points") {
1433                    let pts = parse_points(pts_str);
1434                    if pts.len() >= 3 {
1435                        let segs = poly_segments(&pts, true);
1436                        push_shape_pair(segs.clone(), segs);
1437                    }
1438                }
1439            }
1440            "polyline" => {
1441                if let Some(pts_str) = tag_attr(tag, "points") {
1442                    let pts = parse_points(pts_str);
1443                    if pts.len() >= 2 {
1444                        let fill_segs = if pts.len() >= 3 { poly_segments(&pts, true) } else { Vec::new() };
1445                        let stroke_segs = poly_segments(&pts, false);
1446                        push_shape_pair(fill_segs, stroke_segs);
1447                    }
1448                }
1449            }
1450            _ => {}
1451        }
1452        i = end + 1;
1453    }
1454}
1455
1456fn attr_num(tag: &str, name: &str) -> f32 {
1457    tag_attr(tag, name)
1458        .and_then(|s| {
1459            let mut p = PathParser::new(s.as_bytes());
1460            p.next_f32()
1461        })
1462        .unwrap_or(0.0)
1463}
1464
1465fn parse_points(s: &str) -> Vec<Point> {
1466    let mut p = PathParser::new(s.as_bytes());
1467    let mut pts = Vec::new();
1468    while let (Some(x), Some(y)) = (p.next_f32(), p.next_f32()) {
1469        pts.push(Point { x, y });
1470    }
1471    pts
1472}
1473
1474/// 点列を閉路セグメントに変換
1475fn poly_segments(pts: &[Point], close: bool) -> Vec<Segment> {
1476    let mut segs = Vec::new();
1477    for w in pts.windows(2) {
1478        segs.push(Segment { p1: w[0], p2: w[1] });
1479    }
1480    if close && pts.len() >= 2 {
1481        segs.push(Segment {
1482            p1: pts[pts.len() - 1],
1483            p2: pts[0],
1484        });
1485    }
1486    segs
1487}
1488
1489/// 楕円を多角形近似してセグメント化
1490fn ellipse_segments(cx: f32, cy: f32, rx: f32, ry: f32) -> Vec<Segment> {
1491    const N: u32 = 32;
1492    let mut pts = Vec::with_capacity(N as usize);
1493    for i in 0..N {
1494        let a = (i as f32) * core::f32::consts::TAU / (N as f32);
1495        pts.push(Point {
1496            x: cx + rx * libm::cosf(a),
1497            y: cy + ry * libm::sinf(a),
1498        });
1499    }
1500    poly_segments(&pts, true)
1501}
1502
1503// -------------------------------------------------------------------
1504// グローバルキャッシュと公開 API
1505// -------------------------------------------------------------------
1506
1507/// SVGラスタライズ結果のキャッシュ
1508pub struct SvgCache {
1509    cache: BTreeMap<usize, Vec<u8>>, // key: svg_data のポインタ値
1510}
1511
1512pub static SVG_CACHE: Mutex<Option<SvgCache>> = Mutex::new(None);
1513
1514pub fn init_cache() {
1515    *SVG_CACHE.lock() = Some(SvgCache {
1516        cache: BTreeMap::new(),
1517    });
1518}
1519
1520/// SVGバイト列を指定サイズにラスタライズしてアルファマスクを返す(キャッシュ付き)
1521/// 戻り値は size×size の A8 バッファ(0-255)
1522pub fn get_or_rasterize(svg_data: &[u8], size: u32) -> Option<&'static [u8]> {
1523    let key = (svg_data.as_ptr() as usize).wrapping_add(size as usize * 0x10000);
1524
1525    {
1526        let guard = SVG_CACHE.lock();
1527        let cache = guard.as_ref()?;
1528        if let Some(v) = cache.cache.get(&key) {
1529            let slice = v.as_slice();
1530            // BTreeMap からの削除は行われず、入れた Vec は置き換えない(下の or_insert)ので、要素の領域は動かない。
1531            return Some(unsafe { core::mem::transmute::<&[u8], &'static [u8]>(slice) });
1532        }
1533    }
1534
1535    // 初回: ラスタライズは**錠を放してから**行う(TODO R4、2026-11-16)。以前は錠を持ったまま描いていたので、
1536    // アプリのスレッド(ブラウザの戻る・進むの絵など)が初めての絵を描いている間、同じ錠を取る OS のメインループ
1537    // (題名の帯のボタン・マウスカーソル)が待たされうる。2 つのスレッドが同時に同じ絵を描いたら、先に入れた方を使う。
1538    let d_str = extract_path_d(svg_data)?;
1539    let vb_size = extract_viewbox_size(svg_data);
1540    let segments = parse_path_d(&d_str);
1541    if segments.is_empty() {
1542        return None;
1543    }
1544    let alpha = rasterize(&segments, vb_size, size);
1545
1546    let mut guard = SVG_CACHE.lock();
1547    let cache = guard.as_mut()?;
1548    let slice = cache.cache.entry(key).or_insert(alpha).as_slice();
1549    // BTreeMap からの削除は行われないため、ポインタをスタティックライフタイムにキャストしても安全
1550    Some(unsafe { core::mem::transmute::<&[u8], &'static [u8]>(slice) })
1551}