Skip to main content

velox_engine/svg/
math.rs

1//! `#![no_std]` 兼容的轻量浮点数学原语与 SVG 2D 仿射变换矩阵(`Transform2D`)。
2
3/// 圆周率 $\pi$。
4pub const PI: f32 = core::f32::consts::PI;
5/// $2\pi$。
6pub const TAU: f32 = core::f32::consts::TAU;
7
8/// 绝对值(零 `std` 依赖)。
9#[inline(always)]
10pub fn abs_f32(x: f32) -> f32 {
11    f32::from_bits(x.to_bits() & 0x7FFF_FFFF)
12}
13
14/// 向下取整。
15#[inline]
16pub fn floor_f32(x: f32) -> f32 {
17    {
18        x.floor()
19    }
20}
21
22/// 向上取整。
23#[inline]
24pub fn ceil_f32(x: f32) -> f32 {
25    {
26        x.ceil()
27    }
28}
29
30/// 四舍五入。
31#[inline]
32pub fn round_f32(x: f32) -> f32 {
33    {
34        x.round()
35    }
36}
37
38/// 平方根。
39#[inline]
40pub fn sqrt_f32(x: f32) -> f32 {
41    {
42        if x <= 0.0 {
43            0.0
44        } else {
45            x.sqrt()
46        }
47    }
48}
49
50/// 立方根(支持负数,供 OKLab 色彩空间转换使用)。
51#[inline]
52pub fn cbrt_f32(x: f32) -> f32 {
53    {
54        x.cbrt()
55    }
56}
57
58/// sRGB 通道值 `[0.0, 1.0]` 转线性光强 `[0.0, 1.0]`(IEC 61966-2-1)。
59#[inline]
60pub fn srgb_to_linear_f32(c: f32) -> f32 {
61    let x = c.clamp(0.0, 1.0);
62    if x <= 0.04045 {
63        return x / 12.92;
64    }
65    {
66        ((x + 0.055) / 1.055).powf(2.4)
67    }
68}
69
70/// 线性光强 `[0.0, 1.0]` 转 sRGB 通道值 `[0.0, 1.0]`(IEC 61966-2-1)。
71#[inline]
72pub fn linear_to_srgb_f32(c: f32) -> f32 {
73    let x = c.clamp(0.0, 1.0);
74    if x <= 0.003_130_8 {
75        return x * 12.92;
76    }
77    {
78        1.055 * x.powf(1.0 / 2.4) - 0.055
79    }
80}
81
82/// 同时计算 `(sin(rad), cos(rad))`。
83#[inline]
84pub fn sin_cos_f32(rad: f32) -> (f32, f32) {
85    {
86        rad.sin_cos()
87    }
88}
89
90/// 正切 `tan(rad)`。
91#[inline]
92pub fn tan_f32(rad: f32) -> f32 {
93    let (s, c) = sin_cos_f32(rad);
94    if abs_f32(c) < 1e-6 {
95        if s >= 0.0 {
96            1e6
97        } else {
98            -1e6
99        }
100    } else {
101        s / c
102    }
103}
104
105/// 反正切 `atan2(y, x)`。
106#[inline]
107pub fn atan2_f32(y: f32, x: f32) -> f32 {
108    {
109        y.atan2(x)
110    }
111}
112
113/// 2D 仿射变换矩阵,按 SVG 规范表示:
114///
115/// $$
116/// \begin{bmatrix} x' \\ y' \\ 1 \end{bmatrix}
117/// =
118/// \begin{bmatrix} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{bmatrix}
119/// \begin{bmatrix} x \\ y \\ 1 \end{bmatrix}
120/// $$
121#[derive(Copy, Clone, Debug, PartialEq)]
122pub struct Transform2D {
123    pub a: f32,
124    pub b: f32,
125    pub c: f32,
126    pub d: f32,
127    pub e: f32,
128    pub f: f32,
129}
130
131impl Default for Transform2D {
132    #[inline(always)]
133    fn default() -> Self {
134        Self::IDENTITY
135    }
136}
137
138impl Transform2D {
139    /// 单位矩阵。
140    pub const IDENTITY: Self = Self {
141        a: 1.0,
142        b: 0.0,
143        c: 0.0,
144        d: 1.0,
145        e: 0.0,
146        f: 0.0,
147    };
148
149    /// 构造任意 2D 仿射矩阵 `[a, b, c, d, e, f]`。
150    #[inline(always)]
151    pub const fn new(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Self {
152        Self { a, b, c, d, e, f }
153    }
154
155    /// 平移变换。
156    #[inline(always)]
157    pub const fn translate(tx: f32, ty: f32) -> Self {
158        Self {
159            a: 1.0,
160            b: 0.0,
161            c: 0.0,
162            d: 1.0,
163            e: tx,
164            f: ty,
165        }
166    }
167
168    /// 缩放变换。
169    #[inline(always)]
170    pub const fn scale(sx: f32, sy: f32) -> Self {
171        Self {
172            a: sx,
173            b: 0.0,
174            c: 0.0,
175            d: sy,
176            e: 0.0,
177            f: 0.0,
178        }
179    }
180
181    /// 绕原点顺时针旋转(角度制 `deg`)。
182    #[inline]
183    pub fn rotate(deg: f32) -> Self {
184        let (s, c) = sin_cos_f32(deg * (PI / 180.0));
185        Self {
186            a: c,
187            b: s,
188            c: -s,
189            d: c,
190            e: 0.0,
191            f: 0.0,
192        }
193    }
194
195    /// 绕指定中心 `(cx, cy)` 顺时针旋转(角度制 `deg`)。
196    #[inline]
197    pub fn rotate_around(deg: f32, cx: f32, cy: f32) -> Self {
198        Self::translate(cx, cy)
199            .concat(Self::rotate(deg))
200            .concat(Self::translate(-cx, -cy))
201    }
202
203    /// 沿 X 轴错切(角度制 `deg`)。
204    #[inline]
205    pub fn skew_x(deg: f32) -> Self {
206        Self {
207            a: 1.0,
208            b: 0.0,
209            c: tan_f32(deg * (PI / 180.0)),
210            d: 1.0,
211            e: 0.0,
212            f: 0.0,
213        }
214    }
215
216    /// 沿 Y 轴错切(角度制 `deg`)。
217    #[inline]
218    pub fn skew_y(deg: f32) -> Self {
219        Self {
220            a: 1.0,
221            b: tan_f32(deg * (PI / 180.0)),
222            c: 0.0,
223            d: 1.0,
224            e: 0.0,
225            f: 0.0,
226        }
227    }
228
229    /// 矩阵右乘 `self * rhs`(先应用 `rhs`,再应用 `self`,符合 SVG 父子嵌套顺序)。
230    #[inline]
231    pub fn concat(self, rhs: Self) -> Self {
232        Self {
233            a: self.a * rhs.a + self.c * rhs.b,
234            b: self.b * rhs.a + self.d * rhs.b,
235            c: self.a * rhs.c + self.c * rhs.d,
236            d: self.b * rhs.c + self.d * rhs.d,
237            e: self.a * rhs.e + self.c * rhs.f + self.e,
238            f: self.b * rhs.e + self.d * rhs.f + self.f,
239        }
240    }
241
242    /// 将点 `(x, y)` 变换至目标坐标系。
243    #[inline(always)]
244    pub fn apply(self, x: f32, y: f32) -> (f32, f32) {
245        (
246            self.a * x + self.c * y + self.e,
247            self.b * x + self.d * y + self.f,
248        )
249    }
250
251    /// 判断是否为单位变换矩阵。
252    #[inline(always)]
253    pub fn is_identity(self) -> bool {
254        abs_f32(self.a - 1.0) < 1e-6
255            && abs_f32(self.b) < 1e-6
256            && abs_f32(self.c) < 1e-6
257            && abs_f32(self.d - 1.0) < 1e-6
258            && abs_f32(self.e) < 1e-6
259            && abs_f32(self.f) < 1e-6
260    }
261
262    /// 绕指定中心 `(cx, cy)` 缩放 `(sx, sy)`。
263    #[inline]
264    pub fn scale_around(sx: f32, sy: f32, cx: f32, cy: f32) -> Self {
265        Self::translate(cx, cy)
266            .concat(Self::scale(sx, sy))
267            .concat(Self::translate(-cx, -cy))
268    }
269
270    /// 求 2D 仿射变换的逆矩阵(奇异矩阵返回 `None`)。
271    #[inline]
272    pub fn invert(self) -> Option<Self> {
273        let det = self.a * self.d - self.b * self.c;
274        if abs_f32(det) < 1e-8 || !det.is_finite() {
275            return None;
276        }
277        let inv = 1.0 / det;
278        let a = self.d * inv;
279        let b = -self.b * inv;
280        let c = -self.c * inv;
281        let d = self.a * inv;
282        let e = -(a * self.e + c * self.f);
283        let f = -(b * self.e + d * self.f);
284        Some(Self { a, b, c, d, e, f })
285    }
286
287    /// 计算逻辑矩形经当前仿射变换后的轴对齐外接包围盒(像素向外取整)。
288    #[inline]
289    pub fn transform_region(self, r: crate::solver::Region) -> crate::solver::Region {
290        if r.is_empty() {
291            return crate::solver::Region::EMPTY;
292        }
293        let x0 = r.x as f32;
294        let y0 = r.y as f32;
295        let x1 = r.right() as f32;
296        let y1 = r.bottom() as f32;
297        let p0 = self.apply(x0, y0);
298        let p1 = self.apply(x1, y0);
299        let p2 = self.apply(x0, y1);
300        let p3 = self.apply(x1, y1);
301        let min_x = p0.0.min(p1.0).min(p2.0).min(p3.0);
302        let max_x = p0.0.max(p1.0).max(p2.0).max(p3.0);
303        let min_y = p0.1.min(p1.1).min(p2.1).min(p3.1);
304        let max_y = p0.1.max(p1.1).max(p2.1).max(p3.1);
305        let rx0 = (floor_f32(min_x) as i32).clamp(i16::MIN as i32, i16::MAX as i32) as i16;
306        let ry0 = (floor_f32(min_y) as i32).clamp(i16::MIN as i32, i16::MAX as i32) as i16;
307        let rx1 = (ceil_f32(max_x) as i32).clamp(i16::MIN as i32, i16::MAX as i32) as i16;
308        let ry1 = (ceil_f32(max_y) as i32).clamp(i16::MIN as i32, i16::MAX as i32) as i16;
309        crate::solver::Region::new(rx0, ry0, rx1.saturating_sub(rx0), ry1.saturating_sub(ry0))
310    }
311
312    /// 将当前绕局部中心 `(cx, cy)` 表达的变换转换到屏幕空间(`T(cx,cy) * self * T(-cx,-cy)`)。
313    #[inline]
314    pub fn centered_at(self, cx: f32, cy: f32) -> Self {
315        Self::translate(cx, cy)
316            .concat(self)
317            .concat(Self::translate(-cx, -cy))
318    }
319
320    /// 估算该仿射变换对应的平均各向同性缩放系数(用于缩放 `stroke-width`)。
321    #[inline]
322    pub fn approx_scale(self) -> f32 {
323        let sx = sqrt_f32(self.a * self.a + self.b * self.b);
324        let sy = sqrt_f32(self.c * self.c + self.d * self.d);
325        let avg = 0.5 * (sx + sy);
326        if avg > 1e-5 {
327            avg
328        } else {
329            1.0
330        }
331    }
332
333    /// 解析 SVG `transform` 属性字符串(支持 `translate`/`scale`/`rotate`/`skewX`/`skewY`/`matrix` 任意组合)。
334    pub fn parse_svg_attr(input: &str) -> Self {
335        let bytes = input.as_bytes();
336        let mut pos = 0usize;
337        let mut acc = Self::IDENTITY;
338
339        while pos < bytes.len() {
340            while pos < bytes.len() && is_sep(bytes[pos]) {
341                pos += 1;
342            }
343            if pos >= bytes.len() {
344                break;
345            }
346            let name_start = pos;
347            while pos < bytes.len() && bytes[pos].is_ascii_alphabetic() {
348                pos += 1;
349            }
350            let name = &input[name_start..pos];
351            while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
352                pos += 1;
353            }
354            if pos >= bytes.len() || bytes[pos] != b'(' {
355                // 跳过非预期字符避免死循环
356                pos += 1;
357                continue;
358            }
359            pos += 1; // skip '('
360            let args_start = pos;
361            while pos < bytes.len() && bytes[pos] != b')' {
362                pos += 1;
363            }
364            let args_str = &input[args_start..pos];
365            if pos < bytes.len() && bytes[pos] == b')' {
366                pos += 1;
367            }
368
369            let mut nums = [0.0f32; 6];
370            let count = parse_number_list(args_str, &mut nums);
371            let step = if name.eq_ignore_ascii_case("translate") {
372                if count >= 2 {
373                    Self::translate(nums[0], nums[1])
374                } else if count == 1 {
375                    Self::translate(nums[0], 0.0)
376                } else {
377                    Self::IDENTITY
378                }
379            } else if name.eq_ignore_ascii_case("scale") {
380                if count >= 2 {
381                    Self::scale(nums[0], nums[1])
382                } else if count == 1 {
383                    Self::scale(nums[0], nums[0])
384                } else {
385                    Self::IDENTITY
386                }
387            } else if name.eq_ignore_ascii_case("rotate") {
388                if count >= 3 {
389                    Self::rotate_around(nums[0], nums[1], nums[2])
390                } else if count >= 1 {
391                    Self::rotate(nums[0])
392                } else {
393                    Self::IDENTITY
394                }
395            } else if name.eq_ignore_ascii_case("skewX") {
396                if count >= 1 {
397                    Self::skew_x(nums[0])
398                } else {
399                    Self::IDENTITY
400                }
401            } else if name.eq_ignore_ascii_case("skewY") {
402                if count >= 1 {
403                    Self::skew_y(nums[0])
404                } else {
405                    Self::IDENTITY
406                }
407            } else if name.eq_ignore_ascii_case("matrix") && count >= 6 {
408                Self::new(nums[0], nums[1], nums[2], nums[3], nums[4], nums[5])
409            } else {
410                Self::IDENTITY
411            };
412
413            acc = acc.concat(step);
414        }
415
416        acc
417    }
418}
419
420#[inline(always)]
421fn is_sep(b: u8) -> bool {
422    b == b' ' || b == b'\t' || b == b'\r' || b == b'\n' || b == b','
423}
424
425/// 从字符串中顺序提取最多 `out.len()` 个浮点数(供 `transform`、`viewBox` 等共用)。
426pub(crate) fn parse_number_list(s: &str, out: &mut [f32]) -> usize {
427    let mut count = 0usize;
428    let mut cur = s;
429    while count < out.len() {
430        let Some((val, rest)) = parse_next_f32(cur) else {
431            break;
432        };
433        out[count] = val;
434        count += 1;
435        cur = rest;
436    }
437    count
438}
439
440/// 跳过空白与逗号后解析下一个 SVG 浮点数(支持科学计数法与省略前导零如 `.5`、`-0.25`、`1e-3`)。
441pub(crate) fn parse_next_f32(s: &str) -> Option<(f32, &str)> {
442    let bytes = s.as_bytes();
443    let mut i = 0usize;
444    while i < bytes.len() && is_sep(bytes[i]) {
445        i += 1;
446    }
447    if i >= bytes.len() {
448        return None;
449    }
450    let start = i;
451    if bytes[i] == b'+' || bytes[i] == b'-' {
452        i += 1;
453    }
454    let mut has_digits = false;
455    while i < bytes.len() && bytes[i].is_ascii_digit() {
456        has_digits = true;
457        i += 1;
458    }
459    if i < bytes.len() && bytes[i] == b'.' {
460        i += 1;
461        while i < bytes.len() && bytes[i].is_ascii_digit() {
462            has_digits = true;
463            i += 1;
464        }
465    }
466    if !has_digits {
467        return None;
468    }
469    if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
470        let exp_pos = i;
471        i += 1;
472        if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
473            i += 1;
474        }
475        let mut exp_digits = false;
476        while i < bytes.len() && bytes[i].is_ascii_digit() {
477            exp_digits = true;
478            i += 1;
479        }
480        if !exp_digits {
481            i = exp_pos;
482        }
483    }
484    let token = &s[start..i];
485    let val = token.parse::<f32>().ok()?;
486    Some((val, &s[i..]))
487}
488
489/// 解析单个 SVG 长度值(忽略 `px`/`pt`/`%` 等常见单位后缀,提取数值部分)。
490pub(crate) fn parse_svg_length(s: &str) -> Option<f32> {
491    let trimmed = s.trim();
492    if trimmed.is_empty() {
493        return None;
494    }
495    parse_next_f32(trimmed).map(|(v, _)| v)
496}