velox-engine 0.2.0

Velox core UI engine: arena, pod state, 1D fixed-point layout solver, damage tracker, SDF scanline rasterizer, and cross-platform GPU/software backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! `#![no_std]` 兼容的轻量浮点数学原语与 SVG 2D 仿射变换矩阵(`Transform2D`)。

/// 圆周率 $\pi$。
pub const PI: f32 = core::f32::consts::PI;
/// $2\pi$。
pub const TAU: f32 = core::f32::consts::TAU;

/// 绝对值(零 `std` 依赖)。
#[inline(always)]
pub fn abs_f32(x: f32) -> f32 {
    f32::from_bits(x.to_bits() & 0x7FFF_FFFF)
}

/// 向下取整。
#[inline]
pub fn floor_f32(x: f32) -> f32 {
    {
        x.floor()
    }
}

/// 向上取整。
#[inline]
pub fn ceil_f32(x: f32) -> f32 {
    {
        x.ceil()
    }
}

/// 四舍五入。
#[inline]
pub fn round_f32(x: f32) -> f32 {
    {
        x.round()
    }
}

/// 平方根。
#[inline]
pub fn sqrt_f32(x: f32) -> f32 {
    {
        if x <= 0.0 {
            0.0
        } else {
            x.sqrt()
        }
    }
}

/// 立方根(支持负数,供 OKLab 色彩空间转换使用)。
#[inline]
pub fn cbrt_f32(x: f32) -> f32 {
    {
        x.cbrt()
    }
}

/// sRGB 通道值 `[0.0, 1.0]` 转线性光强 `[0.0, 1.0]`(IEC 61966-2-1)。
#[inline]
pub fn srgb_to_linear_f32(c: f32) -> f32 {
    let x = c.clamp(0.0, 1.0);
    if x <= 0.04045 {
        return x / 12.92;
    }
    {
        ((x + 0.055) / 1.055).powf(2.4)
    }
}

/// 线性光强 `[0.0, 1.0]` 转 sRGB 通道值 `[0.0, 1.0]`(IEC 61966-2-1)。
#[inline]
pub fn linear_to_srgb_f32(c: f32) -> f32 {
    let x = c.clamp(0.0, 1.0);
    if x <= 0.003_130_8 {
        return x * 12.92;
    }
    {
        1.055 * x.powf(1.0 / 2.4) - 0.055
    }
}

/// 同时计算 `(sin(rad), cos(rad))`。
#[inline]
pub fn sin_cos_f32(rad: f32) -> (f32, f32) {
    {
        rad.sin_cos()
    }
}

/// 正切 `tan(rad)`。
#[inline]
pub fn tan_f32(rad: f32) -> f32 {
    let (s, c) = sin_cos_f32(rad);
    if abs_f32(c) < 1e-6 {
        if s >= 0.0 {
            1e6
        } else {
            -1e6
        }
    } else {
        s / c
    }
}

/// 反正切 `atan2(y, x)`。
#[inline]
pub fn atan2_f32(y: f32, x: f32) -> f32 {
    {
        y.atan2(x)
    }
}

/// 2D 仿射变换矩阵,按 SVG 规范表示:
///
/// $$
/// \begin{bmatrix} x' \\ y' \\ 1 \end{bmatrix}
/// =
/// \begin{bmatrix} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{bmatrix}
/// \begin{bmatrix} x \\ y \\ 1 \end{bmatrix}
/// $$
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Transform2D {
    pub a: f32,
    pub b: f32,
    pub c: f32,
    pub d: f32,
    pub e: f32,
    pub f: f32,
}

impl Default for Transform2D {
    #[inline(always)]
    fn default() -> Self {
        Self::IDENTITY
    }
}

impl Transform2D {
    /// 单位矩阵。
    pub const IDENTITY: Self = Self {
        a: 1.0,
        b: 0.0,
        c: 0.0,
        d: 1.0,
        e: 0.0,
        f: 0.0,
    };

    /// 构造任意 2D 仿射矩阵 `[a, b, c, d, e, f]`。
    #[inline(always)]
    pub const fn new(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Self {
        Self { a, b, c, d, e, f }
    }

    /// 平移变换。
    #[inline(always)]
    pub const fn translate(tx: f32, ty: f32) -> Self {
        Self {
            a: 1.0,
            b: 0.0,
            c: 0.0,
            d: 1.0,
            e: tx,
            f: ty,
        }
    }

    /// 缩放变换。
    #[inline(always)]
    pub const fn scale(sx: f32, sy: f32) -> Self {
        Self {
            a: sx,
            b: 0.0,
            c: 0.0,
            d: sy,
            e: 0.0,
            f: 0.0,
        }
    }

    /// 绕原点顺时针旋转(角度制 `deg`)。
    #[inline]
    pub fn rotate(deg: f32) -> Self {
        let (s, c) = sin_cos_f32(deg * (PI / 180.0));
        Self {
            a: c,
            b: s,
            c: -s,
            d: c,
            e: 0.0,
            f: 0.0,
        }
    }

    /// 绕指定中心 `(cx, cy)` 顺时针旋转(角度制 `deg`)。
    #[inline]
    pub fn rotate_around(deg: f32, cx: f32, cy: f32) -> Self {
        Self::translate(cx, cy)
            .concat(Self::rotate(deg))
            .concat(Self::translate(-cx, -cy))
    }

    /// 沿 X 轴错切(角度制 `deg`)。
    #[inline]
    pub fn skew_x(deg: f32) -> Self {
        Self {
            a: 1.0,
            b: 0.0,
            c: tan_f32(deg * (PI / 180.0)),
            d: 1.0,
            e: 0.0,
            f: 0.0,
        }
    }

    /// 沿 Y 轴错切(角度制 `deg`)。
    #[inline]
    pub fn skew_y(deg: f32) -> Self {
        Self {
            a: 1.0,
            b: tan_f32(deg * (PI / 180.0)),
            c: 0.0,
            d: 1.0,
            e: 0.0,
            f: 0.0,
        }
    }

    /// 矩阵右乘 `self * rhs`(先应用 `rhs`,再应用 `self`,符合 SVG 父子嵌套顺序)。
    #[inline]
    pub fn concat(self, rhs: Self) -> Self {
        Self {
            a: self.a * rhs.a + self.c * rhs.b,
            b: self.b * rhs.a + self.d * rhs.b,
            c: self.a * rhs.c + self.c * rhs.d,
            d: self.b * rhs.c + self.d * rhs.d,
            e: self.a * rhs.e + self.c * rhs.f + self.e,
            f: self.b * rhs.e + self.d * rhs.f + self.f,
        }
    }

    /// 将点 `(x, y)` 变换至目标坐标系。
    #[inline(always)]
    pub fn apply(self, x: f32, y: f32) -> (f32, f32) {
        (
            self.a * x + self.c * y + self.e,
            self.b * x + self.d * y + self.f,
        )
    }

    /// 判断是否为单位变换矩阵。
    #[inline(always)]
    pub fn is_identity(self) -> bool {
        abs_f32(self.a - 1.0) < 1e-6
            && abs_f32(self.b) < 1e-6
            && abs_f32(self.c) < 1e-6
            && abs_f32(self.d - 1.0) < 1e-6
            && abs_f32(self.e) < 1e-6
            && abs_f32(self.f) < 1e-6
    }

    /// 绕指定中心 `(cx, cy)` 缩放 `(sx, sy)`。
    #[inline]
    pub fn scale_around(sx: f32, sy: f32, cx: f32, cy: f32) -> Self {
        Self::translate(cx, cy)
            .concat(Self::scale(sx, sy))
            .concat(Self::translate(-cx, -cy))
    }

    /// 求 2D 仿射变换的逆矩阵(奇异矩阵返回 `None`)。
    #[inline]
    pub fn invert(self) -> Option<Self> {
        let det = self.a * self.d - self.b * self.c;
        if abs_f32(det) < 1e-8 || !det.is_finite() {
            return None;
        }
        let inv = 1.0 / det;
        let a = self.d * inv;
        let b = -self.b * inv;
        let c = -self.c * inv;
        let d = self.a * inv;
        let e = -(a * self.e + c * self.f);
        let f = -(b * self.e + d * self.f);
        Some(Self { a, b, c, d, e, f })
    }

    /// 计算逻辑矩形经当前仿射变换后的轴对齐外接包围盒(像素向外取整)。
    #[inline]
    pub fn transform_region(self, r: crate::solver::Region) -> crate::solver::Region {
        if r.is_empty() {
            return crate::solver::Region::EMPTY;
        }
        let x0 = r.x as f32;
        let y0 = r.y as f32;
        let x1 = r.right() as f32;
        let y1 = r.bottom() as f32;
        let p0 = self.apply(x0, y0);
        let p1 = self.apply(x1, y0);
        let p2 = self.apply(x0, y1);
        let p3 = self.apply(x1, y1);
        let min_x = p0.0.min(p1.0).min(p2.0).min(p3.0);
        let max_x = p0.0.max(p1.0).max(p2.0).max(p3.0);
        let min_y = p0.1.min(p1.1).min(p2.1).min(p3.1);
        let max_y = p0.1.max(p1.1).max(p2.1).max(p3.1);
        let rx0 = (floor_f32(min_x) as i32).clamp(i16::MIN as i32, i16::MAX as i32) as i16;
        let ry0 = (floor_f32(min_y) as i32).clamp(i16::MIN as i32, i16::MAX as i32) as i16;
        let rx1 = (ceil_f32(max_x) as i32).clamp(i16::MIN as i32, i16::MAX as i32) as i16;
        let ry1 = (ceil_f32(max_y) as i32).clamp(i16::MIN as i32, i16::MAX as i32) as i16;
        crate::solver::Region::new(rx0, ry0, rx1.saturating_sub(rx0), ry1.saturating_sub(ry0))
    }

    /// 将当前绕局部中心 `(cx, cy)` 表达的变换转换到屏幕空间(`T(cx,cy) * self * T(-cx,-cy)`)。
    #[inline]
    pub fn centered_at(self, cx: f32, cy: f32) -> Self {
        Self::translate(cx, cy)
            .concat(self)
            .concat(Self::translate(-cx, -cy))
    }

    /// 估算该仿射变换对应的平均各向同性缩放系数(用于缩放 `stroke-width`)。
    #[inline]
    pub fn approx_scale(self) -> f32 {
        let sx = sqrt_f32(self.a * self.a + self.b * self.b);
        let sy = sqrt_f32(self.c * self.c + self.d * self.d);
        let avg = 0.5 * (sx + sy);
        if avg > 1e-5 {
            avg
        } else {
            1.0
        }
    }

    /// 解析 SVG `transform` 属性字符串(支持 `translate`/`scale`/`rotate`/`skewX`/`skewY`/`matrix` 任意组合)。
    pub fn parse_svg_attr(input: &str) -> Self {
        let bytes = input.as_bytes();
        let mut pos = 0usize;
        let mut acc = Self::IDENTITY;

        while pos < bytes.len() {
            while pos < bytes.len() && is_sep(bytes[pos]) {
                pos += 1;
            }
            if pos >= bytes.len() {
                break;
            }
            let name_start = pos;
            while pos < bytes.len() && bytes[pos].is_ascii_alphabetic() {
                pos += 1;
            }
            let name = &input[name_start..pos];
            while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
                pos += 1;
            }
            if pos >= bytes.len() || bytes[pos] != b'(' {
                // 跳过非预期字符避免死循环
                pos += 1;
                continue;
            }
            pos += 1; // skip '('
            let args_start = pos;
            while pos < bytes.len() && bytes[pos] != b')' {
                pos += 1;
            }
            let args_str = &input[args_start..pos];
            if pos < bytes.len() && bytes[pos] == b')' {
                pos += 1;
            }

            let mut nums = [0.0f32; 6];
            let count = parse_number_list(args_str, &mut nums);
            let step = if name.eq_ignore_ascii_case("translate") {
                if count >= 2 {
                    Self::translate(nums[0], nums[1])
                } else if count == 1 {
                    Self::translate(nums[0], 0.0)
                } else {
                    Self::IDENTITY
                }
            } else if name.eq_ignore_ascii_case("scale") {
                if count >= 2 {
                    Self::scale(nums[0], nums[1])
                } else if count == 1 {
                    Self::scale(nums[0], nums[0])
                } else {
                    Self::IDENTITY
                }
            } else if name.eq_ignore_ascii_case("rotate") {
                if count >= 3 {
                    Self::rotate_around(nums[0], nums[1], nums[2])
                } else if count >= 1 {
                    Self::rotate(nums[0])
                } else {
                    Self::IDENTITY
                }
            } else if name.eq_ignore_ascii_case("skewX") {
                if count >= 1 {
                    Self::skew_x(nums[0])
                } else {
                    Self::IDENTITY
                }
            } else if name.eq_ignore_ascii_case("skewY") {
                if count >= 1 {
                    Self::skew_y(nums[0])
                } else {
                    Self::IDENTITY
                }
            } else if name.eq_ignore_ascii_case("matrix") && count >= 6 {
                Self::new(nums[0], nums[1], nums[2], nums[3], nums[4], nums[5])
            } else {
                Self::IDENTITY
            };

            acc = acc.concat(step);
        }

        acc
    }
}

#[inline(always)]
fn is_sep(b: u8) -> bool {
    b == b' ' || b == b'\t' || b == b'\r' || b == b'\n' || b == b','
}

/// 从字符串中顺序提取最多 `out.len()` 个浮点数(供 `transform`、`viewBox` 等共用)。
pub(crate) fn parse_number_list(s: &str, out: &mut [f32]) -> usize {
    let mut count = 0usize;
    let mut cur = s;
    while count < out.len() {
        let Some((val, rest)) = parse_next_f32(cur) else {
            break;
        };
        out[count] = val;
        count += 1;
        cur = rest;
    }
    count
}

/// 跳过空白与逗号后解析下一个 SVG 浮点数(支持科学计数法与省略前导零如 `.5`、`-0.25`、`1e-3`)。
pub(crate) fn parse_next_f32(s: &str) -> Option<(f32, &str)> {
    let bytes = s.as_bytes();
    let mut i = 0usize;
    while i < bytes.len() && is_sep(bytes[i]) {
        i += 1;
    }
    if i >= bytes.len() {
        return None;
    }
    let start = i;
    if bytes[i] == b'+' || bytes[i] == b'-' {
        i += 1;
    }
    let mut has_digits = false;
    while i < bytes.len() && bytes[i].is_ascii_digit() {
        has_digits = true;
        i += 1;
    }
    if i < bytes.len() && bytes[i] == b'.' {
        i += 1;
        while i < bytes.len() && bytes[i].is_ascii_digit() {
            has_digits = true;
            i += 1;
        }
    }
    if !has_digits {
        return None;
    }
    if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
        let exp_pos = i;
        i += 1;
        if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
            i += 1;
        }
        let mut exp_digits = false;
        while i < bytes.len() && bytes[i].is_ascii_digit() {
            exp_digits = true;
            i += 1;
        }
        if !exp_digits {
            i = exp_pos;
        }
    }
    let token = &s[start..i];
    let val = token.parse::<f32>().ok()?;
    Some((val, &s[i..]))
}

/// 解析单个 SVG 长度值(忽略 `px`/`pt`/`%` 等常见单位后缀,提取数值部分)。
pub(crate) fn parse_svg_length(s: &str) -> Option<f32> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return None;
    }
    parse_next_f32(trimmed).map(|(v, _)| v)
}