docs: explain box sizing, device drawing and image preparation
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
//! 有限布局盒子的尺寸策略。区分 auto、固定值和 fill,并处理 min/max 对约束与最终尺寸的限制。
|
||||
//! margin、border、padding 的空间分配由布局层结合本模块完成;场景世界范围不被当成无限布局盒子。
|
||||
//!
|
||||
//! 调用路径:Block 属性解码使用 Dimension.parse,native_properties 用 value 公开当前策略。
|
||||
//! layout 的测量/分配入口调用 available 收窄内容约束,再用 resolve 结合自然尺寸求边框盒大小。
|
||||
//! 本模块只处理数值策略,不读 VM 或安排 Mount 生命周期;min/max 一致性由模型提取预先检查。
|
||||
//!
|
||||
//! Native border-box sizing. An unbounded axis cannot resolve `fill`.
|
||||
use crate::{layout::Size, ui_bridge::MAX_DIMENSION};
|
||||
use anyhow::Result;
|
||||
@@ -10,14 +14,18 @@ use endor_core::{Value, VmError};
|
||||
/// 一个布局轴的尺寸策略:随内容、固定值或占用有限可用空间。
|
||||
pub enum Dimension {
|
||||
#[default]
|
||||
// 从自然内容尺寸求候选值;不是占满父轴的同义词。
|
||||
Auto,
|
||||
// 显式边框盒长度,最终仍会受自身 min/max 与父可用上限限制。
|
||||
Fixed(f32),
|
||||
// 使用父级有限分配上限,父轴无界时必须报错,不能生成无限几何。
|
||||
Fill,
|
||||
}
|
||||
|
||||
impl Dimension {
|
||||
/// 把内部尺寸策略投影为相应的源属性表示。
|
||||
pub fn value(self) -> Value {
|
||||
// 把内部枚举编码为源字段值,保留 auto/fill 字符串与固定数值的可区分性。
|
||||
match self {
|
||||
Self::Auto => Value::Text("auto".into()),
|
||||
Self::Fill => Value::Text("fill".into()),
|
||||
@@ -27,11 +35,13 @@ impl Dimension {
|
||||
|
||||
/// 把外部源码或属性表示转换为内部枚举/结构,并反馈不支持的输入。
|
||||
pub fn parse(value: &Value) -> Result<Self, VmError> {
|
||||
// 仅接受约定文本或真实 Number,错误类型/未知字符串不做隐式转换。
|
||||
match value {
|
||||
Value::Text(text) if text == "auto" => Ok(Self::Auto),
|
||||
Value::Text(text) if text == "fill" => Ok(Self::Fill),
|
||||
Value::Number(_) => Ok(Self::Fixed(crate::scroll::coordinate(value).and_then(
|
||||
|n| {
|
||||
// coordinate 已检查有限性与绝对值预算,盒尺寸再额外排除负数。
|
||||
if n >= 0.0 {
|
||||
Ok(n)
|
||||
} else {
|
||||
@@ -51,17 +61,24 @@ impl Dimension {
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
/// border-box 尺寸策略与双轴上下限,实际求解仍要结合父级约束。
|
||||
pub struct Sizing {
|
||||
// 横轴 auto/fixed/fill 策略,按边框盒而非内容盒解释。
|
||||
pub width: Dimension,
|
||||
// 纵轴独立尺寸策略,不能沿用横轴是否有限的判断。
|
||||
pub height: Dimension,
|
||||
// 横轴自身下限,父可用宽更小时仍以父上限优先。
|
||||
pub min_width: f32,
|
||||
// 纵轴自身下限,单位为逻辑长度。
|
||||
pub min_height: f32,
|
||||
// 横轴自身上限,available 在内容测量前应用以产生正确文字换行。
|
||||
pub max_width: f32,
|
||||
// 纵轴自身上限,默认 MAX_DIMENSION 同时作为无界分配哨兵。
|
||||
pub max_height: f32,
|
||||
}
|
||||
|
||||
impl Default for Sizing {
|
||||
/// 建立类型约定的初始值,供尚未发布或尚未交互的状态使用。
|
||||
fn default() -> Self {
|
||||
// 默认跟随内容,零下限与全局最大值不提前冻结自然尺寸;构造器可随后覆盖。
|
||||
Self {
|
||||
width: Dimension::Auto,
|
||||
height: Dimension::Auto,
|
||||
@@ -81,9 +98,11 @@ impl Sizing {
|
||||
// 先套自身 max,再应用 Fixed;Auto/Fill 在测量阶段保留父级允许的空间。
|
||||
constraints[2] = constraints[2].min(self.max_width);
|
||||
constraints[3] = constraints[3].min(self.max_height);
|
||||
// 固定宽先抬到自身 min_width,再收紧父最大宽,保证文本按实际可用盒宽测量。
|
||||
if let Dimension::Fixed(width) = self.width {
|
||||
constraints[2] = constraints[2].min(width.max(self.min_width));
|
||||
}
|
||||
// 纵轴独立应用同一规则;不改变另一轴策略,也不在此填充 Fill。
|
||||
if let Dimension::Fixed(height) = self.height {
|
||||
constraints[3] = constraints[3].min(height.max(self.min_height));
|
||||
}
|
||||
@@ -120,6 +139,7 @@ impl Sizing {
|
||||
// 先满足自身 min/max,再服从父级上限;父级空间比 min 小时,父级上限优先。
|
||||
Ok(value.clamp(min, max).min(available))
|
||||
}
|
||||
// 横纵轴分别求解,只取父最大分配 constraints[2/3];输入的最小约束不在此额外强加。
|
||||
Ok(Size {
|
||||
width: axis(
|
||||
self.width,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! 面向设备像素的绘制指令集合。它承载矩形、文字、裁剪与 3D 表面等原语,不直接操作 VM。
|
||||
//! 平移和缩放统一作用于命令几何;文字样式和裁剪也要使用一致的设备比例。
|
||||
//! 调用路径:RenderDocument.display_list 将已验证逻辑命令转为这些设备原语;shell/system_ui 也可直接组装。
|
||||
//! SoftwareRenderer 顺序消费 commands;合成页面/工具面板时用 translate/extend,不能把共享场景数据本身平移。
|
||||
//!
|
||||
use crate::geometry::{Point, Rect};
|
||||
use crate::text::TextStyle;
|
||||
@@ -7,9 +9,13 @@ use crate::text::TextStyle;
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
/// 设备绘制使用的 RGBA 字节通道,区别于源代码的颜色文本。
|
||||
pub struct Color {
|
||||
// 红通道字节;源十六进制颜色由 document.parse_color 解码。
|
||||
pub red: u8,
|
||||
// 绿通道字节,颜色本身不带坐标或设备比例。
|
||||
pub green: u8,
|
||||
// 蓝通道字节,与输出软件像素通道组合。
|
||||
pub blue: u8,
|
||||
// 透明度 0..255,混合方式由具体原语渲染器解释。
|
||||
pub alpha: u8,
|
||||
}
|
||||
|
||||
@@ -40,11 +46,17 @@ impl Color {
|
||||
pub enum DrawCommand {
|
||||
/// Immutable RGBA image mapped from its local rectangle by rotation.
|
||||
Image {
|
||||
// 不可变 RGBA 资源 Arc,窗口渲染无需访问源对象或重新解码 PNG。
|
||||
image: std::sync::Arc<crate::render::image::Image>,
|
||||
// 设备坐标旋转原点,平移只移动它,不改局部 rect 的偏移。
|
||||
origin: Point,
|
||||
// 相对 origin 的局部采样矩形,旋转时绕 origin 映射。
|
||||
rect: Rect,
|
||||
// 旋转角参数,平移/同比缩放不改变它。
|
||||
angle: f32,
|
||||
// 整体不透明度系数,与资源像素 alpha 在采样时组合。
|
||||
opacity: f32,
|
||||
// 可选染色通道值,不属于位置/尺寸变换。
|
||||
tint: Option<Color>,
|
||||
},
|
||||
// 在 rect 内绘制不可变 3D 视图;平移/缩放改变视口矩形,不改写共享场景或相机。
|
||||
@@ -92,6 +104,7 @@ impl DrawCommand {
|
||||
pub fn translated(mut self, delta: Point) -> Self {
|
||||
// 平移只改变位置,保留尺寸、圆角、文字样式和颜色;消费 self 后返回修改后的命令。
|
||||
match &mut self {
|
||||
// 这些原语的定位直接在 rect 上,移动矩形原点即可,尺寸保持不变。
|
||||
Self::WrappedText { rect, .. }
|
||||
| Self::Scene3D { rect, .. }
|
||||
| Self::PushClip(rect)
|
||||
@@ -100,10 +113,12 @@ impl DrawCommand {
|
||||
rect.x += delta.x;
|
||||
rect.y += delta.y;
|
||||
}
|
||||
// 文字与图片使用 origin 定位;图片 rect 是局部偏移,不能在此跟着重复平移。
|
||||
Self::Text { origin, .. } | Self::Image { origin, .. } => {
|
||||
origin.x += delta.x;
|
||||
origin.y += delta.y;
|
||||
}
|
||||
// Clear/PopClip 无定位几何,平移不产生任何变化。
|
||||
_ => {}
|
||||
}
|
||||
self
|
||||
@@ -113,6 +128,7 @@ impl DrawCommand {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// 有序绘制原语容器;命令顺序同时约束叠放和裁剪栈行为。
|
||||
pub struct DisplayList {
|
||||
// 拥有按执行顺序排列的原语、字符串与原生资源 Arc,列表本身不引用 VM。
|
||||
commands: Vec<DrawCommand>,
|
||||
}
|
||||
|
||||
@@ -123,16 +139,21 @@ impl DisplayList {
|
||||
for command in &mut self.commands {
|
||||
// 先处理各变体独有的长度(字体、圆角、描边),再把公共矩形交给下方统一缩放。
|
||||
let rect = match command {
|
||||
// 有限文字框交给公共矩形缩放,样式先同步乘比例,避免换行框与字形不一致。
|
||||
DrawCommand::WrappedText { rect, style, .. } => {
|
||||
*style = style.scaled(scale);
|
||||
Some(rect)
|
||||
}
|
||||
// 裁剪属于设备几何,和所裁内容使用相同比例。
|
||||
DrawCommand::PushClip(rect) => Some(rect),
|
||||
// 只改三维显示区域,不缩放共享世界网格和相机数值。
|
||||
DrawCommand::Scene3D { rect, .. } => Some(rect),
|
||||
// 圆角作为长度先缩放,再返回矩形供统一处理。
|
||||
DrawCommand::FillRoundedRect { rect, radius, .. } => {
|
||||
*radius *= scale;
|
||||
Some(rect)
|
||||
}
|
||||
// 半径与描边宽也要缩放,不能只改外框而保留旧粗细。
|
||||
DrawCommand::StrokeRoundedRect {
|
||||
rect,
|
||||
radius,
|
||||
@@ -143,6 +164,7 @@ impl DisplayList {
|
||||
*width *= scale;
|
||||
Some(rect)
|
||||
}
|
||||
// 图片 origin 和局部 rect 均在设备单位,分别缩放后返回 None,防止公共分支再缩放一次。
|
||||
DrawCommand::Image { origin, rect, .. } => {
|
||||
origin.x *= scale;
|
||||
origin.y *= scale;
|
||||
@@ -152,12 +174,14 @@ impl DisplayList {
|
||||
rect.height *= scale;
|
||||
None
|
||||
}
|
||||
// 无框文字单独缩放原点和样式,没有矩形需要返回公共路径。
|
||||
DrawCommand::Text { origin, style, .. } => {
|
||||
origin.x *= scale;
|
||||
origin.y *= scale;
|
||||
*style = style.scaled(scale);
|
||||
None
|
||||
}
|
||||
// Clear/PopClip 不含长度数据,保持原样。
|
||||
_ => None,
|
||||
};
|
||||
// 矩形的原点和宽高一起缩放,保证裁剪范围、文本框与实际绘制内容对齐。
|
||||
@@ -177,7 +201,9 @@ impl DisplayList {
|
||||
/// 平移当前显示列表中的命令,供整块页面或管理面板放入窗口坐标。
|
||||
// 与单条 translated 相同,但直接修改整个列表;Clear/PopClip 没有位置需要移动。
|
||||
pub fn translate(&mut self, delta: Point) {
|
||||
// 保持原语顺序逐项移动,不能按种类分组而打乱覆盖关系和裁剪栈。
|
||||
for command in &mut self.commands {
|
||||
// 与单条 translated 保持同一空间规则:rect 型移原点,图片只移旋转 origin。
|
||||
match command {
|
||||
DrawCommand::WrappedText { rect, .. }
|
||||
| DrawCommand::Scene3D { rect, .. }
|
||||
@@ -191,6 +217,7 @@ impl DisplayList {
|
||||
origin.x += delta.x;
|
||||
origin.y += delta.y;
|
||||
}
|
||||
// 无几何的状态原语保留顺序但不做坐标更新。
|
||||
DrawCommand::Clear(_) | DrawCommand::PopClip => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
//! 共享的二维点和矩形值。命中判断在调用方完成坐标系转换后使用,矩形本身不隐式处理相机。
|
||||
//! 调用路径:布局与 viewport 生成点/矩形,文档命中先做坐标逆变换再调用 contains;软件渲染也用它们表达设备区域。
|
||||
//! 这里只是数值容器,不隐式校验/夹取/做相机变换;有限性和尺寸合法性在各协议入口检查。
|
||||
//!
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
/// 二维坐标值;具体处于逻辑、局部还是设备空间由调用上下文决定。
|
||||
pub struct Point {
|
||||
// 横坐标原值,单位与空间由构造方约定。
|
||||
pub x: f32,
|
||||
// 纵坐标原值,不假定一定是世界向上或屏幕向下。
|
||||
pub y: f32,
|
||||
}
|
||||
|
||||
@@ -17,9 +21,13 @@ impl Point {
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
/// 轴对齐矩形,保存原点和宽高,用于布局、裁剪与命中。
|
||||
pub struct Rect {
|
||||
// 左侧原点,在同一坐标系中与 point.x 比较。
|
||||
pub x: f32,
|
||||
// 顶部原点,在同一坐标系中与 point.y 比较。
|
||||
pub y: f32,
|
||||
// 横向长度,不存储右端点;contains 使用 x+width。
|
||||
pub width: f32,
|
||||
// 纵向长度,不存储下端点;调用方负责非负尺寸约定。
|
||||
pub height: f32,
|
||||
}
|
||||
|
||||
@@ -36,6 +44,7 @@ impl Rect {
|
||||
|
||||
/// 用闭区间比较判断点是否命中,左右上下边缘都计入;调用前需将点转换到矩形所在空间。
|
||||
pub fn contains(self, point: Point) -> bool {
|
||||
// 闭区间四边比较;自身不处理裁剪叠加、圆角或世界面板遮挡,这些属于更上层命中流程。
|
||||
point.x >= self.x
|
||||
&& point.x <= self.x + self.width
|
||||
&& point.y >= self.y
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
//! 有界不可变 RGBA 图片资源,由原生 Arc 共享,准备阶段解码/排字,逐帧软件渲染只采样像素。
|
||||
//! 调用路径:graphics 的图像加载入口调用 png,text_flow 调用 text 缓存设备分辨率字词。
|
||||
//! SoftwareRenderer.draw_image 逆映射目标像素后调用 sample;graphics 使用 outline 取得排版避让轮廓。
|
||||
//! id 只用于原生缓存身份比较,不是 VM 句柄,也不表示两个相同像素资源必有相同 ID。
|
||||
//!
|
||||
//! Immutable, bounded RGBA images shared by display lists. Decoding and text
|
||||
//! preparation happen outside the frame loop; the CPU backend samples them.
|
||||
use crate::{
|
||||
@@ -8,21 +13,32 @@ use crate::{
|
||||
use std::{io::Cursor, sync::Arc};
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
// 像素、尺寸和轮廓在构造完成后由 Arc 只读共享;序列化省略原始像素与轮廓。
|
||||
pub struct Image {
|
||||
// 资源实际像素宽,png/text 构造保证至少为一。
|
||||
pub width: u32,
|
||||
// 资源实际像素高,与绘制局部逻辑 rect 可按 scale 不同。
|
||||
pub height: u32,
|
||||
// 每次准备新资源取得的进程内数值身份,PartialEq 只比较它以便快速判断缓存复用。
|
||||
pub id: u64,
|
||||
#[serde(skip)]
|
||||
// 行优先 RGBA 字节数组,保存 straight alpha;采样时临时转预乘权重避免透明边黑晕。
|
||||
pixels: Vec<u8>,
|
||||
#[serde(skip)]
|
||||
// PNG 的 alpha 保守凸包,用于图形排版避让;预渲染文字目前返回空轮廓。
|
||||
pub outline: Vec<crate::geometry::Point>,
|
||||
}
|
||||
|
||||
impl Image {
|
||||
// 将受预算约束的 PNG 解码为 RGBA,并一次性生成透明轮廓;格式/解码错误直接交给加载调用方。
|
||||
pub fn png(bytes: &[u8]) -> anyhow::Result<Arc<Self>> {
|
||||
// 借用输入字节建立内存解码器,不在帧循环执行文件 I/O。
|
||||
let mut decoder = png::Decoder::new(Cursor::new(bytes));
|
||||
// 展开调色板/低位深并去掉 16 位低字节,使后面每个颜色样本可按 8 位通道读取。
|
||||
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
// 先读取 PNG 头,像素预算在分配输出缓冲前检查。
|
||||
let mut reader = decoder.read_info()?;
|
||||
// 头部尺寸非零且总像素不超过 4194304,使用 u64 乘法避免 u32 乘积溢出。
|
||||
let info = reader.info();
|
||||
anyhow::ensure!(
|
||||
info.width > 0
|
||||
@@ -30,24 +46,35 @@ impl Image {
|
||||
&& u64::from(info.width) * u64::from(info.height) <= 4_194_304,
|
||||
"image exceeds pixel budget"
|
||||
);
|
||||
// 按解码器计算的输出字节数分配,计算溢出时拒绝而非猜测缓冲长度。
|
||||
let mut buffer = vec![
|
||||
0;
|
||||
reader
|
||||
.output_buffer_size()
|
||||
.ok_or_else(|| anyhow::anyhow!("image size overflow"))?
|
||||
];
|
||||
// 解码一帧并取得实际输出布局,只消费 buffer_size 范围,不读取未写尾部。
|
||||
let info = reader.next_frame(&mut buffer)?;
|
||||
// 预留统一四通道容量,原 PNG 可以是灰度、RGB 或 RGBA。
|
||||
let mut pixels = Vec::with_capacity(info.width as usize * info.height as usize * 4);
|
||||
// 按解码后的每像素样本数遍历,所有格式归并成同一 RGBA 存储。
|
||||
for chunk in buffer[..info.buffer_size()].chunks_exact(info.color_type.samples()) {
|
||||
// 灰度复制到 RGB,缺 alpha 填 255;若 Indexed 未展开则报错,不能把索引当颜色通道。
|
||||
let rgba = match info.color_type {
|
||||
// 原生四通道直接复制,保留源 alpha。
|
||||
// 三通道图片默认全不透明,不从相邻像素误读 alpha。
|
||||
png::ColorType::Rgba => [chunk[0], chunk[1], chunk[2], chunk[3]],
|
||||
png::ColorType::Rgb => [chunk[0], chunk[1], chunk[2], 255],
|
||||
// 单灰度通道复制到三色,完全不透明。
|
||||
png::ColorType::Grayscale => [chunk[0], chunk[0], chunk[0], 255],
|
||||
// 灰度/alpha 双通道保留透明度,前三色仍同值。
|
||||
png::ColorType::GrayscaleAlpha => [chunk[0], chunk[0], chunk[0], chunk[1]],
|
||||
// EXPAND 后正常不应残留索引图,若仍存在就拒绝不支持的输出布局。
|
||||
png::ColorType::Indexed => anyhow::bail!("unexpanded indexed PNG"),
|
||||
};
|
||||
pixels.extend_from_slice(&rgba);
|
||||
}
|
||||
// 资源准备阶段扫描 alpha 生成保守轮廓,后续排版不必每帧重新遍历图片像素。
|
||||
let outline = alpha_hull(&pixels, info.width, info.height);
|
||||
Ok(Arc::new(Self {
|
||||
width: info.width,
|
||||
@@ -60,20 +87,28 @@ impl Image {
|
||||
|
||||
/// Cache a shaped word at the actual device resolution. Padding preserves
|
||||
/// italic/serif overhangs. Returns its logical image rectangle and advance.
|
||||
// 按实际设备 scale 预渲染一段已排字文本,返回共享资源、逻辑图片框和不含 padding 的文字 advance。
|
||||
pub fn text(
|
||||
value: &str,
|
||||
style: TextStyle,
|
||||
scale: f32,
|
||||
color: Color,
|
||||
) -> Result<(Arc<Self>, Rect, f32), &'static str> {
|
||||
// 用逻辑 TextStyle 测量自然字形 advance/行高;返回 advance 不随设备 DPI 改变。
|
||||
let size = text::measure(value, style);
|
||||
// 按字号预留约 30% 整数逻辑边距,容纳斜体/衬线伸出而不裁掉字形。
|
||||
let pad = (style.font_size * 0.3).ceil();
|
||||
// 两侧 padding 后乘设备比例再向上取整,实际资源至少一像素宽。
|
||||
let width = ((size.width + pad * 2.) * scale).ceil().max(1.) as u32;
|
||||
// 高度也含两侧留白并按设备比例取整,与 width 分别计算。
|
||||
let height = ((size.height + pad * 2.) * scale).ceil().max(1.) as u32;
|
||||
// 准备文字资源另限 1048576 像素,避免单段文本缓冲无限增长。
|
||||
if u64::from(width) * u64::from(height) > 1_048_576 {
|
||||
return Err("prepared text image exceeds pixel budget");
|
||||
}
|
||||
// 零初始化 RGBA 即透明背景,字形回调只修改实际覆盖的像素。
|
||||
let mut pixels = vec![0; width as usize * height as usize * 4];
|
||||
// 以设备字号绘制,负 padding 框与下面回调偏移共同把逻辑文字原点放在资源留白之后。
|
||||
text::draw_clipped(
|
||||
value,
|
||||
style.scaled(scale),
|
||||
@@ -81,11 +116,15 @@ impl Image {
|
||||
None,
|
||||
Rect::new(-pad * scale, -pad * scale, width as f32, height as f32),
|
||||
|x, y, c| {
|
||||
// 把绘制回调坐标移到含左 padding 的缓冲位置,按设备像素舍入。
|
||||
let x = x + (pad * scale).round() as i32;
|
||||
// 纵向也加 top padding,保持字形基线与返回的逻辑图片框一致。
|
||||
let y = y + (pad * scale).round() as i32;
|
||||
// 排除所有缓冲外像素,防止字形 overhang 或舍入造成越界写入。
|
||||
if x < 0 || y < 0 || x >= width as i32 || y >= height as i32 {
|
||||
return;
|
||||
}
|
||||
// 行优先像素索引乘四得到 RGBA 字节起点,先通过上面坐标范围检查。
|
||||
let i = (y as usize * width as usize + x as usize) * 4;
|
||||
// All glyphs have the same ink color; alpha-over preserves overlaps.
|
||||
pixels[i..i + 3].copy_from_slice(&[c.red, c.green, c.blue]);
|
||||
@@ -94,6 +133,7 @@ impl Image {
|
||||
as u8;
|
||||
},
|
||||
);
|
||||
// 返回的新图有独立 id;逻辑 rect 左上为负 padding,绘图能保持原文字基线与 advance 对齐。
|
||||
Ok((
|
||||
Arc::new(Self {
|
||||
width,
|
||||
@@ -107,30 +147,44 @@ impl Image {
|
||||
))
|
||||
}
|
||||
|
||||
// 软件渲染器传入逆映射的归一化纹理点和已夹取 opacity;预乘 alpha 双线性插值后返回 straight RGBA。
|
||||
pub fn sample(&self, u: f32, v: f32, opacity: f32) -> Color {
|
||||
// 归一化 u 映射到像素中心索引,减 0.5 使 texel 中心落在整数坐标。
|
||||
let x = u * self.width as f32 - 0.5;
|
||||
// v 使用同样中心约定,不把资源边缘当作像素中心。
|
||||
let y = v * self.height as f32 - 0.5;
|
||||
// 取左上采样格的整数基点,四个邻居随后夹在资源边界。
|
||||
let (ix, iy) = (x.floor() as i32, y.floor() as i32);
|
||||
// 小数部分作为双线性权重,四项权重之和为一。
|
||||
let (fx, fy) = (x - x.floor(), y - y.floor());
|
||||
// 前三项累计 RGB×alpha×权重,第四项累计 alpha×权重,避免透明像素 RGB 污染边缘。
|
||||
let mut sum = [0.; 4];
|
||||
// 四邻像素按二维线性乘积权重采样,边缘通过 clamping 复制最近 texel。
|
||||
for (dx, dy, w) in [
|
||||
(0, 0, (1. - fx) * (1. - fy)),
|
||||
(1, 0, fx * (1. - fy)),
|
||||
(0, 1, (1. - fx) * fy),
|
||||
(1, 1, fx * fy),
|
||||
] {
|
||||
// 横轴邻居夹到有效像素列,不在透明边缘之外读越界数据。
|
||||
let px = (ix + dx).clamp(0, self.width as i32 - 1) as usize;
|
||||
// 纵轴独立夹取,图片宽高不同也不能复用同一边界。
|
||||
let py = (iy + dy).clamp(0, self.height as i32 - 1) as usize;
|
||||
// 转换资源像素位置为四通道字节偏移。
|
||||
let i = (py * self.width as usize + px) * 4;
|
||||
// alpha 保留 0..255 数值再乘权重,前三色同用该权重以实现预乘插值。
|
||||
let a = f32::from(self.pixels[i + 3]) * w;
|
||||
// 只累计 RGB 三通道,最终 alpha 单独累加,避免重复乘整体 opacity。
|
||||
for (j, s) in sum.iter_mut().enumerate().take(3) {
|
||||
*s += f32::from(self.pixels[i + j]) * a;
|
||||
}
|
||||
sum[3] += a;
|
||||
}
|
||||
// 完全透明时直接返回透明黑,避免除以零且不泄露透明像素的无意义 RGB。
|
||||
if sum[3] <= 0. {
|
||||
return Color::rgba(0, 0, 0, 0);
|
||||
}
|
||||
// RGB 除累计 alpha 恢复 straight 通道,整体 opacity 只作用最终 alpha。
|
||||
Color::rgba(
|
||||
(sum[0] / sum[3]).round() as u8,
|
||||
(sum[1] / sum[3]).round() as u8,
|
||||
@@ -144,49 +198,68 @@ impl Image {
|
||||
/// rectangle, this excludes empty transparent margins. Generated once per PNG.
|
||||
fn alpha_hull(pixels: &[u8], width: u32, height: u32) -> Vec<crate::geometry::Point> {
|
||||
use crate::geometry::Point;
|
||||
// 先收集各有效行左右端像素的四角点,后面求整体凸包,而非逐像素精确边界。
|
||||
let mut points = Vec::new();
|
||||
// 按行扫描 alpha,阈值 16 去掉几乎透明的外围像素。
|
||||
for y in 0..height {
|
||||
// 只保留 alpha>=16 的列号,颜色通道不影响避让轮廓。
|
||||
let xs: Vec<_> = (0..width)
|
||||
.filter(|&x| pixels[((y * width + x) * 4 + 3) as usize] >= 16)
|
||||
.collect();
|
||||
// 该行有有效像素才生成候选角点,空透明行不参与外形。
|
||||
if let (Some(&left), Some(&right)) = (xs.first(), xs.last()) {
|
||||
// 右端取 right+1 表达像素外边界,不把末列中心当作轮廓右缘。
|
||||
for x in [left as f32, right as f32 + 1.] {
|
||||
// 上下各取像素行边界,保守覆盖整个端点像素单元。
|
||||
for yy in [y as f32, y as f32 + 1.] {
|
||||
points.push(Point::new(x, yy));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 按 x/y 全序排序,后面单调链要求稳定几何次序;随后去掉重复角点。
|
||||
points.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
|
||||
points.dedup();
|
||||
// 不足三点直接返回,无法构成面积凸多边形,不补造图片矩形。
|
||||
if points.len() < 3 {
|
||||
return points;
|
||||
}
|
||||
// 二维叉积符号判断转向,单调链移除非凸与共线中间点。
|
||||
let cross =
|
||||
|a: Point, b: Point, c: Point| (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
|
||||
// 结果栈先构造下链,再逆序追加上链。
|
||||
let mut hull: Vec<Point> = Vec::new();
|
||||
// 按升序构造第一条凸包链,每个候选最多入栈/出栈一次。
|
||||
for &p in &points {
|
||||
// 新点使末两点不构成严格左转时弹出中间点,保留外侧端点。
|
||||
while hull.len() >= 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0. {
|
||||
hull.pop();
|
||||
}
|
||||
hull.push(p);
|
||||
}
|
||||
// 记录下链末端位置,构造上链时不能越过这条边界。
|
||||
let lower = hull.len();
|
||||
// 反向跳过已在下链末端的最右点,继续构造上链并闭合。
|
||||
for &p in points.iter().rev().skip(1) {
|
||||
// 与下链相同转向规则,但保留已完成下链;最后会去掉重复闭合首点。
|
||||
while hull.len() > lower && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0. {
|
||||
hull.pop();
|
||||
}
|
||||
hull.push(p);
|
||||
}
|
||||
// 首点在上下链闭合时出现两次,移除末尾重复点,返回不含闭合副本的凸包。
|
||||
hull.pop();
|
||||
hull
|
||||
}
|
||||
|
||||
// 为每个准备完成的原生资源分配进程内身份;只需要原子递增取号,不承担读写像素的跨线程发布屏障。
|
||||
fn next_id() -> u64 {
|
||||
// 计数器从一开始,Relaxed 只用于取号;资源的安全共享由不可变 Arc 实现。
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
impl PartialEq for Image {
|
||||
// 原生缓存比较资源身份而非扫描像素;两次解码相同文件也会是不同资源 ID。
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user