Skip to main content

velox_engine/element/
image.rs

1//! 位图、RLE 压缩掩码、旋转精灵、过程化 SDF、原生矢量 SVG 与 GPU 原生解析圆弧图像节点 `Img<'a>`。
2
3use crate::arena::StrRef;
4use crate::display::SpriteFormat;
5use crate::pod::FrameScope;
6use crate::sdf::SurfacePainter;
7use crate::style::Color;
8
9use super::{Element, IntoElement};
10
11impl<'a> IntoElement<'a> for Img<'a> {
12    #[inline(always)]
13    fn into_element(self, _cx: &'a FrameScope) -> Element<'a> {
14        Element::Img(self)
15    }
16}
17
18
19/// `Sprite` 贴图数据源(支持静态/帧池预烘焙位图掩码,或过程化 SDF 精灵贴图)。
20#[derive(Copy, Clone)]
21pub enum SpriteSource<'a> {
22    /// 预烘焙 `A4`/`A8` Alpha 掩码或 `Rgb565` 位图切片。
23    Bitmap {
24        bytes: &'a [u8],
25        format: SpriteFormat,
26        tint: Color,
27    },
28    /// 过程化矢量精灵(分配于 `ScratchArena`,如旋转表针或动态仪表盘层)。
29    Shader {
30        state_hash: u32,
31        painter: &'a dyn Fn(&mut dyn SurfacePainter),
32    },
33    /// 原生矢量 SVG 文档或单路径 `d` 字符串(纯 POD,支持软件多核条带并行与 GPU `SpriteAtlas` HiDPI 跨帧缓存)。
34    Svg {
35        /// SVG XML 文本或单条 `d` 路径数据(静态字面量或帧级 `ScratchArena` 字符串)。
36        source: StrRef<'a>,
37        /// `true` 表示 `source` 为 24×24 标准 SVG Path `d` 字符串;`false` 表示完整 `<svg>` XML 文档。
38        is_path_only: bool,
39        /// 前景着色颜色(对应 XML 中的 `currentColor` 及整体 Alpha 透明度;纯路径模式下作为绘制颜色)。
40        tint: Color,
41        /// 0.1px 精度描边宽度(纯路径模式下 `0` 表示实心填充,`>0` 如 `20` 表示 `2.0px` 圆头描边线条图标;XML 模式下 `0` 遵循内置 `stroke-width`)。
42        stroke_width_x10: u8,
43    },
44    /// 原生解析圆弧/圆环 SDF 图元(纯 POD,GPU 端单 Draw Call 片元直算零上传,软件端支持多线程并行光栅)。
45    Arc {
46        /// 圆弧线宽(逻辑像素)。
47        thickness: u8,
48        /// 起始顺时针角度(单位 `0.1°`,`0` 为 12 点钟方向)。
49        start_deg10: u16,
50        /// 背景轨道总跨度(单位 `0.1°`)。
51        sweep_deg10: u16,
52        /// 前景填充进度跨度(单位 `0.1°`)。
53        fill_sweep_deg10: u16,
54        /// 背景轨道颜色。
55        track_color: Color,
56        /// 前景填充颜色。
57        fill_color: Color,
58    },
59}
60
61impl<'a> PartialEq for SpriteSource<'a> {
62    fn eq(&self, other: &Self) -> bool {
63        match (*self, *other) {
64            (
65                Self::Bitmap {
66                    bytes: b1,
67                    format: f1,
68                    tint: t1,
69                },
70                Self::Bitmap {
71                    bytes: b2,
72                    format: f2,
73                    tint: t2,
74                },
75            ) => f1 == f2 && t1 == t2 && b1 == b2,
76            (
77                Self::Shader {
78                    state_hash: h1, ..
79                },
80                Self::Shader {
81                    state_hash: h2, ..
82                },
83            ) => h1 == h2,
84            (
85                Self::Svg {
86                    source: s1,
87                    is_path_only: p1,
88                    tint: t1,
89                    stroke_width_x10: sw1,
90                },
91                Self::Svg {
92                    source: s2,
93                    is_path_only: p2,
94                    tint: t2,
95                    stroke_width_x10: sw2,
96                },
97            ) => p1 == p2 && t1 == t2 && sw1 == sw2 && s1 == s2,
98            (
99                Self::Arc {
100                    thickness: t1,
101                    start_deg10: s1,
102                    sweep_deg10: sw1,
103                    fill_sweep_deg10: f1,
104                    track_color: tc1,
105                    fill_color: fc1,
106                },
107                Self::Arc {
108                    thickness: t2,
109                    start_deg10: s2,
110                    sweep_deg10: sw2,
111                    fill_sweep_deg10: f2,
112                    track_color: tc2,
113                    fill_color: fc2,
114                },
115            ) => t1 == t2 && s1 == s2 && sw1 == sw2 && f1 == f2 && tc1 == tc2 && fc1 == fc2,
116            _ => false,
117        }
118    }
119}
120
121impl<'a> Eq for SpriteSource<'a> {}
122
123impl<'a> core::fmt::Debug for SpriteSource<'a> {
124    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
125        match *self {
126            Self::Bitmap {
127                bytes,
128                format,
129                tint,
130            } => f
131                .debug_struct("Bitmap")
132                .field("byte_len", &bytes.len())
133                .field("format", &format)
134                .field("tint", &tint)
135                .finish(),
136            Self::Shader { state_hash, .. } => f
137                .debug_struct("Shader")
138                .field("state_hash", &state_hash)
139                .finish(),
140            Self::Svg {
141                source,
142                is_path_only,
143                tint,
144                stroke_width_x10,
145            } => f
146                .debug_struct("Svg")
147                .field("len", &source.as_str().len())
148                .field("is_path_only", &is_path_only)
149                .field("tint", &tint)
150                .field("stroke_width_x10", &stroke_width_x10)
151                .finish(),
152            Self::Arc {
153                thickness,
154                start_deg10,
155                sweep_deg10,
156                fill_sweep_deg10,
157                track_color,
158                fill_color,
159            } => f
160                .debug_struct("Arc")
161                .field("thickness", &thickness)
162                .field("start_deg10", &start_deg10)
163                .field("sweep_deg10", &sweep_deg10)
164                .field("fill_sweep_deg10", &fill_sweep_deg10)
165                .field("track_color", &track_color)
166                .field("fill_color", &fill_color)
167                .finish(),
168        }
169    }
170}
171
172/// 贴图与图标掩码原语节点(最终编译为 `DrawPayload::Sprite`)。
173#[derive(Copy, Clone)]
174pub struct Img<'a> {
175    pub width: i16,
176    pub height: i16,
177    pub source: SpriteSource<'a>,
178}
179
180/// 构造一个位图贴图节点(支持 `&'static [u8]` 或 `ScratchArena` 切片 `&'a [u8]`)。
181#[inline(always)]
182pub const fn img<'a>(
183    width: i16,
184    height: i16,
185    bytes: &'a [u8],
186    format: SpriteFormat,
187) -> Img<'a> {
188    Img {
189        width,
190        height,
191        source: SpriteSource::Bitmap {
192            bytes,
193            format,
194            tint: Color::WHITE,
195        },
196    }
197}
198
199/// 构造一个 A8 Alpha 掩码图标节点(等价于编译期预烘焙的 SVG 图标)。
200#[inline(always)]
201pub const fn svg<'a>(width: i16, height: i16, alpha_mask: &'a [u8]) -> Img<'a> {
202    img(width, height, alpha_mask, SpriteFormat::A8)
203}
204
205/// 构造一个 A4 (4-bit Alpha) 紧凑掩码图标节点(体积比 A8 减半)。
206#[inline(always)]
207pub const fn svg_a4<'a>(width: i16, height: i16, alpha_mask_a4: &'a [u8]) -> Img<'a> {
208    img(width, height, alpha_mask_a4, SpriteFormat::A4)
209}
210
211/// 构造一个完整原生矢量 SVG XML 图像节点(支持 `<svg viewBox>`、`<g>` 嵌套、`transform`、多色填充/描边与 `currentColor`)。
212#[inline(always)]
213pub fn svg_str<'a>(width: i16, height: i16, xml: impl Into<StrRef<'a>>) -> Img<'a> {
214    Img {
215        width,
216        height,
217        source: SpriteSource::Svg {
218            source: xml.into(),
219            is_path_only: false,
220            tint: Color::WHITE,
221            stroke_width_x10: 0,
222        },
223    }
224}
225
226/// 构造一个实心填充的 24×24 标准 SVG Path `d` 矢量图形节点(配合 `.tint(color)` 着色)。
227#[inline(always)]
228pub fn svg_path<'a>(width: i16, height: i16, d: impl Into<StrRef<'a>>) -> Img<'a> {
229    Img {
230        width,
231        height,
232        source: SpriteSource::Svg {
233            source: d.into(),
234            is_path_only: true,
235            tint: Color::WHITE,
236            stroke_width_x10: 0,
237        },
238    }
239}
240
241/// 构造一个 Lucide 风格 24×24 圆头圆角描边(默认 `stroke-width = 2.0`)矢量线条图标节点(配合 `.tint(color)` 与 `.stroke_width(...)` 定制)。
242#[inline(always)]
243pub fn svg_icon<'a>(width: i16, height: i16, d: impl Into<StrRef<'a>>) -> Img<'a> {
244    Img {
245        width,
246        height,
247        source: SpriteSource::Svg {
248            source: d.into(),
249            is_path_only: true,
250            tint: Color::WHITE,
251            stroke_width_x10: 20,
252        },
253    }
254}
255
256
257/// 构造一个支持任意角度旋转(`angle_deg10` 单位为 `0.1°`)与定点缩放(`scale_q8` 基准为 `256 = 1.0x`)的 `Rgb565` 仿射变换精灵节点。
258pub fn img_rotated_rgb565<'a>(
259    cx: &'a FrameScope,
260    width: i16,
261    height: i16,
262    src_w: i16,
263    src_h: i16,
264    rgb565_le_bytes: &'a [u8],
265    angle_deg10: u16,
266    scale_q8: u16,
267) -> Img<'a> {
268    let state_hash = (rgb565_le_bytes.as_ptr() as usize as u32)
269        ^ ((angle_deg10 as u32) << 16)
270        ^ (scale_q8 as u32);
271    img_shader(cx, width, height, state_hash, move |surface| {
272        let b = surface.bounds();
273        let c = surface.clip();
274        if c.is_empty() || src_w <= 0 || src_h <= 0 || scale_q8 == 0 {
275            return;
276        }
277        let (sin_q10, cos_q10) = crate::sdf::sin_cos_deg10((angle_deg10 % 3600) as i32);
278        let dst_cx = b.x as i32 + (b.w as i32) / 2;
279        let dst_cy = b.y as i32 + (b.h as i32) / 2;
280        let src_cx_q8 = (src_w as i32) * 128;
281        let src_cy_q8 = (src_h as i32) * 128;
282        let inv_scale_q8 = (65536 / (scale_q8 as i32)).max(1);
283
284        for py in c.y..c.bottom() {
285            let dy = (py as i32) - dst_cy;
286            for px in c.x..c.right() {
287                let dx = (px as i32) - dst_cx;
288                // 反向旋转映射回源贴图坐标 (Q8,使用 i64 杜绝小 scale_q8 时乘法溢出)
289                let rx_q10 = (dx * cos_q10 + dy * sin_q10) as i64;
290                let ry_q10 = (-dx * sin_q10 + dy * cos_q10) as i64;
291                let sx = ((((rx_q10 * inv_scale_q8 as i64) >> 10) + src_cx_q8 as i64) >> 8) as i32;
292                let sy = ((((ry_q10 * inv_scale_q8 as i64) >> 10) + src_cy_q8 as i64) >> 8) as i32;
293                if sx >= 0 && sx < src_w as i32 && sy >= 0 && sy < src_h as i32 {
294                    let idx = ((sy as usize) * (src_w as usize) + (sx as usize)) * 2;
295                    if let Some(pair) = rgb565_le_bytes.get(idx..idx + 2) {
296                        let raw = u16::from_le_bytes([pair[0], pair[1]]);
297                        if raw != 0 {
298                            let col = <crate::display::Rgb565 as crate::display::PixelFormat>::to_color(
299                                crate::display::Rgb565(raw),
300                            );
301                            surface.blend_pixel(px, py, col, 255);
302                        }
303                    }
304                }
305            }
306        }
307    })
308}
309
310/// 构造一个原生解析圆弧/圆环 SDF 图元节点(GPU 端单 Draw Call 直算零纹理上传,软件端多线程并行光栅)。
311#[inline(always)]
312pub const fn img_arc(
313    width: i16,
314    height: i16,
315    thickness: u8,
316    start_deg10: u16,
317    sweep_deg10: u16,
318    fill_sweep_deg10: u16,
319    track_color: Color,
320    fill_color: Color,
321) -> Img<'static> {
322    Img {
323        width,
324        height,
325        source: SpriteSource::Arc {
326            thickness,
327            start_deg10,
328            sweep_deg10,
329            fill_sweep_deg10,
330            track_color,
331            fill_color,
332        },
333    }
334}
335
336/// 构造一个过程化 SDF 矢量精灵节点(作为 `DrawPayload::Sprite` 渲染,闭包分配在 `ScratchArena` 中)。
337#[inline(always)]
338pub fn img_shader<'a, F>(
339    cx: &'a FrameScope,
340    width: i16,
341    height: i16,
342    state_hash: u32,
343    painter: F,
344) -> Img<'a>
345where
346    F: Fn(&mut dyn SurfacePainter) + 'a,
347{
348    Img {
349        width,
350        height,
351        source: SpriteSource::Shader {
352            state_hash,
353            painter: cx.arena().alloc(painter),
354        },
355    }
356}
357
358impl<'a> Img<'a> {
359    /// 设置位图掩码或矢量 SVG 的着色颜色(对完整 XML SVG 映射为 `currentColor` 及整体不透明度)。
360    #[inline(always)]
361    pub const fn tint(mut self, color: Color) -> Self {
362        match self.source {
363            SpriteSource::Bitmap {
364                bytes, format, ..
365            } => {
366                self.source = SpriteSource::Bitmap {
367                    bytes,
368                    format,
369                    tint: color,
370                };
371            }
372            SpriteSource::Svg {
373                source,
374                is_path_only,
375                stroke_width_x10,
376                ..
377            } => {
378                self.source = SpriteSource::Svg {
379                    source,
380                    is_path_only,
381                    tint: color,
382                    stroke_width_x10,
383                };
384            }
385            _ => {}
386        }
387        self
388    }
389
390    /// 设置矢量 SVG 的描边宽度(单位 `0.1px`,如 `20` 表示 `2.0px`;对 `svg_path` 设为 `0` 表示实心填充)。
391    #[inline(always)]
392    pub const fn stroke_width(mut self, width_x10: u8) -> Self {
393        if let SpriteSource::Svg {
394            source,
395            is_path_only,
396            tint,
397            ..
398        } = self.source
399        {
400            self.source = SpriteSource::Svg {
401                source,
402                is_path_only,
403                tint,
404                stroke_width_x10: width_x10,
405            };
406        }
407        self
408    }
409}