docs: 逐模块细化中文逻辑注释并覆盖测试与示例
This commit is contained in:
+48
-5
@@ -84,8 +84,9 @@ impl Constructor {
|
||||
.into_iter()
|
||||
.find(|kind| kind.function() == name)
|
||||
}
|
||||
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
|
||||
/// 返回三维原生构造的显式最小/最大参数数,不含请求 Type;Group/Scene 支持最多4096子节点。
|
||||
pub fn arity(self) -> (usize, usize) {
|
||||
// 构造器 arity 不含 NativeTyped 的类型首参,Group/Scene 允许零到 4096 个孩子,其他零参对象使用默认属性。
|
||||
match self {
|
||||
Self::Vec3 | Self::Triangle => (3, 3),
|
||||
Self::Geometry | Self::Mesh => (2, 2),
|
||||
@@ -205,6 +206,7 @@ fn set_number(
|
||||
}
|
||||
/// 解析颜色值并检查其满足当前原生绘制约定。
|
||||
fn color(value: &str) -> Result<[f32; 3], VmError> {
|
||||
// 3D 不透明材质拒绝半透明颜色,转换为 [0,1] RGB 数值;普通二维 UI 的 alpha 不受这里限制。
|
||||
let color = crate::document::parse_color(value).map_err(|_| invalid("invalid 3D color"))?;
|
||||
if color.alpha != 255 {
|
||||
return Err(invalid("3D opaque material color requires full alpha"));
|
||||
@@ -224,6 +226,7 @@ pub fn allocate(
|
||||
constructor: Constructor,
|
||||
args: &[Value],
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 入口假设桥接工厂已按 arity/类型检查 args;Geometry 特殊地复制缓冲并提前返回,其余创建可编辑标记节点。
|
||||
let kind = match constructor {
|
||||
Constructor::Vec3 => NodeKind::Vector,
|
||||
Constructor::Triangle => NodeKind::Triangle,
|
||||
@@ -236,6 +239,7 @@ pub fn allocate(
|
||||
Constructor::Orbit => NodeKind::Orbit,
|
||||
Constructor::Panel => NodeKind::Panel,
|
||||
Constructor::Geometry => {
|
||||
// Geometry 构造只接受受控 ObjectList,逐成员验证 Vec3 payload 并复制数值;以后改源 Vec3 不会改已建几何。
|
||||
let vertices = object_list::items(cx.store(), object_ref(&args[0])?)?
|
||||
.iter()
|
||||
.map(|&item| {
|
||||
@@ -257,6 +261,7 @@ pub fn allocate(
|
||||
return Err(invalid("geometry indices require Triangle3D"));
|
||||
}
|
||||
let mut triangle = [0; 3];
|
||||
// 索引先从 Number 检查非负整数,再转 u32;是否越出顶点范围在整份 geometry.valid 校验。
|
||||
for (index, name) in ["a", "b", "c"].into_iter().enumerate() {
|
||||
let value = number(&cx.store().get_attr(item, name)?)?;
|
||||
if value < 0. || value.fract() != 0. {
|
||||
@@ -272,6 +277,7 @@ pub fn allocate(
|
||||
triangles,
|
||||
uv: vec![],
|
||||
};
|
||||
// 缓存为原生 Arc 前统一验证顶点/三角形预算与下标范围,避免渲染线程再接触源缓冲对象。
|
||||
if !geometry.valid() {
|
||||
return Err(invalid(
|
||||
"invalid Geometry3D buffers or geometry budget exceeded",
|
||||
@@ -300,6 +306,7 @@ pub fn allocate(
|
||||
NodeKind::Mesh => {
|
||||
let (geometry, material) = if matches!(constructor, Constructor::Box) {
|
||||
let (w, h, d) = (number(&args[0])?, number(&args[1])?, number(&args[2])?);
|
||||
// Box 允许零尺寸产生退化面,后续光栅/拾取跳过退化三角形;负尺寸在构造入口拒绝。
|
||||
if w < 0. || h < 0. || d < 0. {
|
||||
return Err(invalid("Box3D dimensions must be nonnegative"));
|
||||
}
|
||||
@@ -315,6 +322,7 @@ pub fn allocate(
|
||||
cx.set_attr(instance, "geometry", Value::Object(geometry))?;
|
||||
cx.set_attr(instance, "color", Value::Text(material))?;
|
||||
}
|
||||
// 孩子只接受 Mesh/Group/Light/Panel 标记,不允许把相机、控制器或任意 Object 放进场景组成。
|
||||
NodeKind::Group | NodeKind::Scene => {
|
||||
let children = args.iter().map(object_ref).collect::<Result<Vec<_>, _>>()?;
|
||||
for child in &children {
|
||||
@@ -327,6 +335,7 @@ pub fn allocate(
|
||||
));
|
||||
}
|
||||
}
|
||||
// 托管 children 列表拥有子节点;Node payload 自身只是标记,属性拥有边由 VM 正常追踪。
|
||||
let children = object_list::collection(cx, children, desktop)?;
|
||||
cx.set_attr(instance, "children", Value::Object(children))?;
|
||||
if kind == NodeKind::Scene {
|
||||
@@ -345,6 +354,7 @@ pub fn allocate(
|
||||
cx.set_attr(instance, "color", args[3].clone())?;
|
||||
set_number(cx, instance, "intensity", number(&args[4])?)?;
|
||||
}
|
||||
// 世界宽高与 UI 像素分辨率独立:初始纹理 512×320,content 是普通 Block 图,稍后参与独立有限布局。
|
||||
NodeKind::Panel => {
|
||||
let content = object_ref(&args[2])?;
|
||||
crate::block::validate(cx.store(), content, None)?;
|
||||
@@ -379,6 +389,7 @@ pub fn allocate(
|
||||
set_number(cx, instance, "panSpeed", 1.)?;
|
||||
}
|
||||
}
|
||||
// 只有可放置节点安装 TRS;相机用 position/target/up,方向光用方向向量,不复用网格欧拉角字段。
|
||||
if matches!(kind, NodeKind::Mesh | NodeKind::Group | NodeKind::Panel) {
|
||||
for (name, value) in [
|
||||
("x", 0.),
|
||||
@@ -405,6 +416,7 @@ struct Reader<'a> {
|
||||
impl Reader<'_> {
|
||||
/// 读取字段并登记依赖,使后续字段变更能够使 3D 快照失效。
|
||||
fn value(&mut self, object: ObjectRef, name: &str) -> Result<Value, VmError> {
|
||||
// 读取前登记精确对象/属性依赖,HashSet 去重;返回给视觉缓存后,相关字段变化才能驱动重建。
|
||||
self.reads.insert((object, name.into()));
|
||||
self.store.get_attr(object, name)
|
||||
}
|
||||
@@ -422,6 +434,7 @@ impl Reader<'_> {
|
||||
}
|
||||
/// 读取并校验透视或正交摄像机字段,生成不持有 VM 引用的投影描述。
|
||||
fn camera(&mut self, object: ObjectRef) -> Result<Camera, VmError> {
|
||||
// 先验证宿主相机种类,再按投影策略读取 fov 或 height;不把有同名字段的对象当相机。
|
||||
let projection = match self.store.payload::<Node>(object, "3D camera")?.0 {
|
||||
NodeKind::Perspective => Projection::Perspective {
|
||||
fov: self.number(object, "fov")?,
|
||||
@@ -456,6 +469,7 @@ pub struct PanelMount {
|
||||
pub content: ObjectRef,
|
||||
pub size: crate::layout::Size,
|
||||
}
|
||||
// 三部分分别是可跨线程的不可变 View、VM 内缓存用的属性依赖、仍由 VM 驱动布局的面板 Block 根。
|
||||
pub type Snapshot = (
|
||||
Arc<scene3d::View>,
|
||||
Vec<(ObjectRef, String)>,
|
||||
@@ -496,6 +510,7 @@ pub fn snapshot_reusing(
|
||||
background,
|
||||
acceleration: Arc::default(),
|
||||
};
|
||||
// 显式进入/退出栈保存节点、父世界矩阵、退出标记与路径 key;path 仅追踪祖先,因此允许共享子树多次出现。
|
||||
let mut work = vec![(scene, Matrix::default(), false, 0u64)];
|
||||
let mut panels = Vec::new();
|
||||
let mut path = HashSet::new();
|
||||
@@ -508,6 +523,7 @@ pub fn snapshot_reusing(
|
||||
continue;
|
||||
}
|
||||
visits += 1;
|
||||
// 预算按展开出现次数,重复共享同一网格也消耗实例/顶点/三角形工作,不能只数不同对象身份。
|
||||
if visits > 4096 {
|
||||
return Err(VmError::ExecutionLimit("3D scene occurrences"));
|
||||
}
|
||||
@@ -517,6 +533,7 @@ pub fn snapshot_reusing(
|
||||
work.push((object, parent, true, key));
|
||||
let kind = store.payload::<Node>(object, "3D node")?.0;
|
||||
let world = if matches!(kind, NodeKind::Mesh | NodeKind::Group | NodeKind::Panel) {
|
||||
// 局部先缩放、旋转、平移,再乘父 world;Scene/Light 不新增 TRS,方向光仍受祖先 Group 变换。
|
||||
parent.compose(Matrix::trs(
|
||||
reader.vector(object, ["x", "y", "z"])?,
|
||||
reader.vector(object, ["rotationX", "rotationY", "rotationZ"])?,
|
||||
@@ -531,6 +548,8 @@ pub fn snapshot_reusing(
|
||||
for (index, child) in object_list::items(store, list)?.iter().enumerate().rev() {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
// 路径 key 包含父 key、当前孩子索引和托管身份,区分同一 Panel 节点在不同路径的出现。
|
||||
// 此 key 与普通 Block slot 不同,场景列表重排会改变路径身份。
|
||||
key.hash(&mut hasher);
|
||||
index.hash(&mut hasher);
|
||||
child.hash(&mut hasher);
|
||||
@@ -540,6 +559,7 @@ pub fn snapshot_reusing(
|
||||
NodeKind::Mesh => {
|
||||
let geometry = object_ref(&reader.value(object, "geometry")?)?;
|
||||
let geometry = store.payload::<Geometry>(geometry, "Geometry3D")?.0.clone();
|
||||
// 每次 mesh 出现都累计完整几何,Arc 共享只节约存储,不减少本帧实例绘制工作预算。
|
||||
triangles += geometry.triangles.len();
|
||||
vertices += geometry.vertices.len();
|
||||
if vertices > 262_144 {
|
||||
@@ -560,10 +580,12 @@ pub fn snapshot_reusing(
|
||||
NodeKind::Panel => {
|
||||
// Arrangement slots cross Endor's signed integer API. A raw
|
||||
// u64 hash can turn negative when native Bounds are created.
|
||||
// Bounds.slot 经有符号整数 API 传递,清最高位避免变负;仍显式检测碰撞,不能假设哈希必然唯一。
|
||||
let key = key & i64::MAX as u64;
|
||||
if panels.iter().any(|panel: &PanelMount| panel.key == key) {
|
||||
return Err(invalid("colliding 3D UI occurrence identities"));
|
||||
}
|
||||
// 有限面板根数量另限 64;每个面板还有独立像素分辨率限制和递归纹理总预算。
|
||||
if panels.len() >= 64 {
|
||||
return Err(VmError::ExecutionLimit("3D UI panels"));
|
||||
}
|
||||
@@ -584,6 +606,7 @@ pub fn snapshot_reusing(
|
||||
let content = object_ref(&reader.value(object, "content")?)?;
|
||||
crate::block::resolve(store, content)?;
|
||||
let background = color(&text(&reader.value(object, "background")?)?)?;
|
||||
// 面板平面以中心为原点,顶点 y 向上,UV 左上为 (0,0);两三角形共用四个角点。
|
||||
let geometry = Arc::new(scene3d::Geometry {
|
||||
vertices: vec![
|
||||
Vec3::new(-width / 2., height / 2., 0.),
|
||||
@@ -607,6 +630,7 @@ pub fn snapshot_reusing(
|
||||
surface: None,
|
||||
}),
|
||||
});
|
||||
// 同时把普通 UI 根交给宿主布局,scene Mesh 先只带分辨率/背景,surface 由后续 panel::compose 装配。
|
||||
panels.push(PanelMount {
|
||||
key,
|
||||
content,
|
||||
@@ -622,6 +646,7 @@ pub fn snapshot_reusing(
|
||||
}
|
||||
let direction =
|
||||
reader.vector(object, ["directionX", "directionY", "directionZ"])?;
|
||||
// 用两点之差撤销父矩阵平移,仅保留线性部分对方向的影响,再归一化;零方向拒绝。
|
||||
let direction = (world.point(direction) - world.point(Vec3::default()))
|
||||
.normalized()
|
||||
.ok_or(invalid("light direction cannot be zero"))?;
|
||||
@@ -639,6 +664,7 @@ pub fn snapshot_reusing(
|
||||
_ => return Err(invalid("invalid node in 3D scene graph")),
|
||||
}
|
||||
}
|
||||
// 完整世界值相等时复用旧 Scene/BVH,单独换 camera 生成新 View;不相等才重建世界空间索引。
|
||||
let scene = if let Some(scene) = reuse.filter(|scene| **scene == output) {
|
||||
scene
|
||||
} else {
|
||||
@@ -646,6 +672,7 @@ pub fn snapshot_reusing(
|
||||
Arc::new(output)
|
||||
};
|
||||
let view = Arc::new(scene3d::View { scene, camera });
|
||||
// 提取各项之后仍做完整视图校验,覆盖累计世界变换、光照、面板及整体资源不变量。
|
||||
if !view.valid() {
|
||||
return Err(invalid("invalid 3D scene snapshot"));
|
||||
}
|
||||
@@ -667,6 +694,7 @@ pub fn pick(
|
||||
if !matches!(data.kind, crate::block::Kind::Viewport3D { .. }) {
|
||||
return Err(invalid("pick3D requires a Viewport3D"));
|
||||
}
|
||||
// 先做出现/面板遮挡和裁剪命中,未命中直接 Nil;即使场景射线有交点也不能点穿外层遮挡。
|
||||
if !mount.geometry.contains(point) {
|
||||
return Ok(Value::Nil);
|
||||
}
|
||||
@@ -675,6 +703,7 @@ pub fn pick(
|
||||
let Some(point) = mount.geometry.logical_point(point) else {
|
||||
return Ok(Value::Nil);
|
||||
};
|
||||
// 从布局盒扣 inset 得到实际内容视口,再把逻辑点归一化;零面积视口没有有效投影。
|
||||
let (width, height) = (
|
||||
(mount.geometry.width - inset.horizontal()).max(0.),
|
||||
(mount.geometry.height - inset.vertical()).max(0.),
|
||||
@@ -695,6 +724,7 @@ pub fn pick(
|
||||
let Some(hit) = hit else {
|
||||
return Ok(Value::Nil);
|
||||
};
|
||||
// 原生 Hit.identity 只带文本,通过本次实际读取的托管身份重新关联节点;渲染器本身从不解引用 VM 对象。
|
||||
let mesh = reads
|
||||
.iter()
|
||||
.find_map(|(object, _)| (object.to_string() == hit.identity).then_some(*object))
|
||||
@@ -718,6 +748,7 @@ pub fn pick(
|
||||
"triangle",
|
||||
Value::Number((hit.triangle as i64).into()),
|
||||
)?;
|
||||
// 交点、法线、重心权重都包装为名义 Vec3,结果对象通过普通属性强持有它们。
|
||||
for (name, vector) in [
|
||||
("point", hit.point),
|
||||
("normal", hit.normal),
|
||||
@@ -752,7 +783,7 @@ pub struct PointerPick {
|
||||
}
|
||||
|
||||
/// The default controller is replaceable; camera data has no dependency on it.
|
||||
/// 为指定出现解码相机手势并调用控制器;嵌套面板输入先转换到所属视口坐标。
|
||||
/// 默认 OrbitController 根据已解码的 CameraGesture 更新相机,处理轨道、平移和缩放;可由源控制器替换。
|
||||
pub fn control(
|
||||
cx: &mut NativeContext<'_>,
|
||||
controller: ObjectRef,
|
||||
@@ -770,6 +801,7 @@ pub fn control(
|
||||
let dx = reader.number(gesture, "dx")?;
|
||||
let dy = reader.number(gesture, "dy")?;
|
||||
let kind = text(&reader.value(gesture, "kind")?)?;
|
||||
// 默认轨道控制围绕 target 使用 position-target 偏移和半径;相机有效性保证观察方向不退化。
|
||||
let offset = camera.position - camera.target;
|
||||
let radius = offset.length();
|
||||
let mut position = camera.position;
|
||||
@@ -784,12 +816,14 @@ pub fn control(
|
||||
.up
|
||||
.normalized()
|
||||
.ok_or(invalid("camera up cannot be zero"))?;
|
||||
// 将偏移分解为 up 方向和水平面方向,用水平旋转更新 yaw、asin(vertical) 更新 pitch。
|
||||
let vertical = (offset.dot(up) / radius).clamp(-1., 1.);
|
||||
let horizontal = (offset - up * offset.dot(up))
|
||||
.normalized()
|
||||
.ok_or(invalid("orbit at pole requires a different up vector"))?;
|
||||
let (sine, cosine) = (dx * speed).sin_cos();
|
||||
let horizontal = horizontal * cosine + up.cross(horizontal) * sine;
|
||||
// 俯仰限制在两极内侧 0.01 弧度,避免绕极点时水平基退化并导致轨道跳变。
|
||||
let pitch = (vertical.asin() + dy * speed).clamp(
|
||||
-std::f32::consts::FRAC_PI_2 + 0.01,
|
||||
std::f32::consts::FRAC_PI_2 - 0.01,
|
||||
@@ -802,6 +836,7 @@ pub fn control(
|
||||
return Err(invalid("panSpeed expects 0 through 100"));
|
||||
}
|
||||
let height = reader.number(gesture, "height")?.max(1.);
|
||||
// 把逻辑像素位移换成世界单位:透视按 target 距离处的可见高度,正交按固定投影高度。
|
||||
let units = match camera.projection {
|
||||
Projection::Perspective { fov } => {
|
||||
2. * radius * (fov.to_radians() / 2.).tan() / height
|
||||
@@ -810,6 +845,7 @@ pub fn control(
|
||||
};
|
||||
let basis = camera.basis().ok_or(invalid("invalid camera basis"))?;
|
||||
let delta = basis.right * (dx * units * speed) + basis.up * (-dy * units * speed);
|
||||
// 平移同时移动 position 和 target,保留观察方向与轨道半径;屏幕 y 向下所以 up 分量取负。
|
||||
position = position + delta;
|
||||
target = target + delta;
|
||||
}
|
||||
@@ -818,6 +854,7 @@ pub fn control(
|
||||
if !(0.1..=10.0).contains(&factor) {
|
||||
return Err(invalid("zoom factor expects 0.1 through 10"));
|
||||
}
|
||||
// 正交缩放只改投影高度,透视缩放改变到 target 的距离;倍率大于一均表现为拉近。
|
||||
if let Projection::Orthographic { height } = camera.projection {
|
||||
set_number(
|
||||
cx,
|
||||
@@ -833,6 +870,7 @@ pub fn control(
|
||||
}
|
||||
_ => return Err(invalid("unsupported 3D camera gesture")),
|
||||
}
|
||||
// 写回前校验整个计算结果,拒绝超世界范围;控制器通过普通属性更新让后续快照依赖观察变化。
|
||||
if !position.valid() || !target.valid() {
|
||||
return Err(invalid("camera movement exceeds world budget"));
|
||||
}
|
||||
@@ -849,7 +887,7 @@ pub fn control(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 执行托管 3D 节点的原生平移/旋转操作,供尚不支持普通数值算术表达式的源程序调用。
|
||||
/// 对允许的 3D 节点累计平移或角度旋转;相机平移同时更新 target,旋转值归一到 [0,360)。
|
||||
pub fn transform(
|
||||
cx: &mut NativeContext<'_>,
|
||||
owner: ObjectRef,
|
||||
@@ -869,11 +907,13 @@ pub fn transform(
|
||||
{
|
||||
return Err(invalid("unsupported 3D transform target"));
|
||||
}
|
||||
// 旋转增量作用欧拉角,平移增量作用位置;相机不接受本接口的欧拉角旋转。
|
||||
let names = if rotate {
|
||||
["rotationX", "rotationY", "rotationZ"]
|
||||
} else {
|
||||
["x", "y", "z"]
|
||||
};
|
||||
// 先收集并验证全部轴再写入,避免验证到第二/三轴才发现越界时已修改前面轴。
|
||||
let mut updates = Vec::new();
|
||||
for (index, name) in names.into_iter().enumerate() {
|
||||
let delta = number(&args[index])?;
|
||||
@@ -884,11 +924,13 @@ pub fn transform(
|
||||
updates.push((
|
||||
name,
|
||||
if rotate {
|
||||
// 角度归一到 [0,360),支持负增量而不使用产生负余数的普通取模。
|
||||
value.rem_euclid(360.)
|
||||
} else {
|
||||
value
|
||||
},
|
||||
));
|
||||
// 相机平移同步改 target,保留朝向;不把“移动摄像机”意外变成绕固定目标转动。
|
||||
if camera {
|
||||
let name = ["targetX", "targetY", "targetZ"][index];
|
||||
let value = number(&cx.store().get_attr(owner, name)?)? + delta;
|
||||
@@ -904,11 +946,11 @@ pub fn transform(
|
||||
Ok(())
|
||||
}
|
||||
impl endor_core::NativeCallable for PointerPick {
|
||||
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
|
||||
/// 输入 Mount 与点击点已捕获,拾取/分发准备步骤不再接受实参。
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
|
||||
/// 在当前 Mount 中重新射线拾取,构造含真实 mesh 命中的 click Event,再交托管事件系统分发。
|
||||
fn invoke(
|
||||
&self,
|
||||
cx: &mut NativeContext<'_>,
|
||||
@@ -921,6 +963,7 @@ impl endor_core::NativeCallable for PointerPick {
|
||||
let hit = pick(cx, self.desktop, &mount, self.point)?;
|
||||
let definition = crate::ui_bridge::desktop_type(cx.store(), "Event", self.desktop)?;
|
||||
let event = crate::event_dispatch::new_event(cx, definition, "click")?;
|
||||
// 点击事件把精确拾取值放到 hit(未击中则 Nil),仍以 Viewport 的 Block/Mount 作为事件传播目标。
|
||||
cx.set_attr(event, "hit", hit)?;
|
||||
crate::event_dispatch::dispatch(cx, mount.block, event, Some(self.mount), self.desktop)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user