feat: compose interactive world ui across nested 3d viewports

This commit is contained in:
2026-11-11 00:08:23 +08:00
parent ad2c01bc29
commit 15fc01542c
27 changed files with 1412 additions and 84 deletions
+113 -13
View File
@@ -23,6 +23,7 @@ pub enum Constructor {
Perspective,
Orthographic,
Orbit,
Panel,
}
impl Constructor {
pub fn name(self) -> &'static str {
@@ -38,6 +39,7 @@ impl Constructor {
Self::Perspective => "PerspectiveCamera",
Self::Orthographic => "OrthographicCamera",
Self::Orbit => "OrbitController",
Self::Panel => "Panel3D",
}
}
pub fn function(self) -> &'static str {
@@ -53,6 +55,7 @@ impl Constructor {
Self::Perspective => "perspectiveCamera",
Self::Orthographic => "orthographicCamera",
Self::Orbit => "orbitController",
Self::Panel => "panel3D",
}
}
pub fn from_function(name: &str) -> Option<Self> {
@@ -68,6 +71,7 @@ impl Constructor {
Self::Perspective,
Self::Orthographic,
Self::Orbit,
Self::Panel,
]
.into_iter()
.find(|kind| kind.function() == name)
@@ -79,6 +83,7 @@ impl Constructor {
Self::Box => (4, 4),
Self::Group | Self::Scene => (0, 4096),
Self::Light => (5, 5),
Self::Panel => (3, 3),
_ => (0, 0),
}
}
@@ -89,6 +94,7 @@ impl Constructor {
Self::Mesh => &["Geometry3D", "String"],
Self::Box => &["Number", "Number", "Number", "String"],
Self::Light => &["Number", "Number", "Number", "String", "Number"],
Self::Panel => &["Number", "Number", "Block"],
_ => &[],
}
}
@@ -108,6 +114,7 @@ pub enum NodeKind {
Perspective,
Orthographic,
Orbit,
Panel,
}
#[derive(Debug)]
pub struct Node(pub NodeKind);
@@ -198,6 +205,7 @@ pub fn allocate(
Constructor::Perspective => NodeKind::Perspective,
Constructor::Orthographic => NodeKind::Orthographic,
Constructor::Orbit => NodeKind::Orbit,
Constructor::Panel => NodeKind::Panel,
Constructor::Geometry => {
let vertices = object_list::items(cx.store(), object_ref(&args[0])?)?
.iter()
@@ -233,6 +241,7 @@ pub fn allocate(
let geometry = scene3d::Geometry {
vertices,
triangles,
uv: vec![],
};
if !geometry.valid() {
return Err(invalid(
@@ -282,7 +291,7 @@ pub fn allocate(
for child in &children {
if !matches!(
cx.store().payload::<Node>(*child, "3D node")?.0,
NodeKind::Mesh | NodeKind::Group | NodeKind::Light
NodeKind::Mesh | NodeKind::Group | NodeKind::Light | NodeKind::Panel
) {
return Err(invalid(
"Scene3D/Group3D children require meshes, groups or lights",
@@ -307,6 +316,16 @@ pub fn allocate(
cx.set_attr(instance, "color", args[3].clone())?;
set_number(cx, instance, "intensity", number(&args[4])?)?;
}
NodeKind::Panel => {
let content = object_ref(&args[2])?;
crate::block::validate(cx.store(), content, None)?;
set_number(cx, instance, "width", number(&args[0])?)?;
set_number(cx, instance, "height", number(&args[1])?)?;
set_number(cx, instance, "uiWidth", 512.)?;
set_number(cx, instance, "uiHeight", 320.)?;
cx.set_attr(instance, "content", Value::Object(content))?;
cx.set_attr(instance, "background", Value::Text("#FFFFFF".into()))?;
}
NodeKind::Perspective | NodeKind::Orthographic => {
for (name, value) in [
("x", 0.),
@@ -331,7 +350,7 @@ pub fn allocate(
set_number(cx, instance, "panSpeed", 1.)?;
}
}
if matches!(kind, NodeKind::Mesh | NodeKind::Group) {
if matches!(kind, NodeKind::Mesh | NodeKind::Group | NodeKind::Panel) {
for (name, value) in [
("x", 0.),
("y", 0.),
@@ -397,7 +416,16 @@ impl Reader<'_> {
}
}
pub type Snapshot = (Arc<scene3d::View>, Vec<(ObjectRef, String)>);
pub struct PanelMount {
pub key: u64,
pub content: ObjectRef,
pub size: crate::layout::Size,
}
pub type Snapshot = (
Arc<scene3d::View>,
Vec<(ObjectRef, String)>,
Vec<PanelMount>,
);
pub fn snapshot(
store: &ObjectStore,
scene: ObjectRef,
@@ -422,11 +450,12 @@ pub fn snapshot(
ambient,
background,
};
let mut work = vec![(scene, Matrix::default(), false)];
let mut work = vec![(scene, Matrix::default(), false, 0u64)];
let mut panels = Vec::new();
let mut path = HashSet::new();
let mut visits = 0;
let mut triangles = 0;
while let Some((object, parent, finish)) = work.pop() {
while let Some((object, parent, finish, key)) = work.pop() {
if finish {
path.remove(&object);
continue;
@@ -438,9 +467,9 @@ pub fn snapshot(
if !path.insert(object) {
return Err(invalid("cyclic 3D scene graph"));
}
work.push((object, parent, true));
work.push((object, parent, true, key));
let kind = store.payload::<Node>(object, "3D node")?.0;
let world = if matches!(kind, NodeKind::Mesh | NodeKind::Group) {
let world = if matches!(kind, NodeKind::Mesh | NodeKind::Group | NodeKind::Panel) {
parent.compose(Matrix::trs(
reader.vector(object, ["x", "y", "z"])?,
reader.vector(object, ["rotationX", "rotationY", "rotationZ"])?,
@@ -452,8 +481,13 @@ pub fn snapshot(
match kind {
NodeKind::Scene | NodeKind::Group => {
let list = object_ref(&reader.value(object, "children")?)?;
for child in object_list::items(store, list)?.iter().rev() {
work.push((*child, world, false));
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.hash(&mut hasher);
index.hash(&mut hasher);
child.hash(&mut hasher);
work.push((*child, world, false, hasher.finish()));
}
}
NodeKind::Mesh => {
@@ -469,6 +503,60 @@ pub fn snapshot(
geometry,
world,
color: material,
panel: None,
});
}
NodeKind::Panel => {
if panels.len() >= 64 {
return Err(VmError::ExecutionLimit("3D UI panels"));
}
let width = reader.number(object, "width")?;
let height = reader.number(object, "height")?;
let ui_width = reader.number(object, "uiWidth")?;
let ui_height = reader.number(object, "uiHeight")?;
if width <= 0.
|| height <= 0.
|| ![ui_width, ui_height]
.iter()
.all(|size| (1.0..=2048.0).contains(size) && size.fract() == 0.)
{
return Err(invalid(
"Panel3D requires positive world dimensions and integer UI dimensions from 1 through 2048",
));
}
let content = object_ref(&reader.value(object, "content")?)?;
crate::block::resolve(store, content)?;
let background = color(&text(&reader.value(object, "background")?)?)?;
let geometry = Arc::new(scene3d::Geometry {
vertices: vec![
Vec3::new(-width / 2., height / 2., 0.),
Vec3::new(width / 2., height / 2., 0.),
Vec3::new(width / 2., -height / 2., 0.),
Vec3::new(-width / 2., -height / 2., 0.),
],
triangles: vec![[0, 1, 2], [0, 2, 3]],
uv: vec![[0., 0.], [1., 0.], [1., 1.], [0., 1.]],
});
output.meshes.push(scene3d::Mesh {
identity: object.to_string(),
geometry,
world,
color: [1., 1., 1.],
panel: Some(scene3d::Panel {
key,
width: ui_width as u32,
height: ui_height as u32,
background,
surface: None,
}),
});
panels.push(PanelMount {
key,
content,
size: crate::layout::Size {
width: ui_width,
height: ui_height,
},
});
}
NodeKind::Light => {
@@ -501,7 +589,7 @@ pub fn snapshot(
if !view.valid() {
return Err(invalid("invalid 3D scene snapshot"));
}
Ok((view, reader.reads.into_iter().collect()))
Ok((view, reader.reads.into_iter().collect(), panels))
}
pub fn pick(
@@ -523,7 +611,9 @@ pub fn pick(
}
let node = crate::block::snapshot(cx.store(), mount.block)?;
let inset = crate::layout::insets(&node);
let point = mount.geometry.view.unwrap_or_default().inverse(point);
let Some(point) = mount.geometry.logical_point(point) else {
return Ok(Value::Nil);
};
let (width, height) = (
(mount.geometry.width - inset.horizontal()).max(0.),
(mount.geometry.height - inset.vertical()).max(0.),
@@ -531,7 +621,7 @@ pub fn pick(
if width <= 0. || height <= 0. {
return Ok(Value::Nil);
}
let (view, reads) = snapshot(
let (view, reads, _) = snapshot(
cx.store(),
data.scene3d.ok_or(invalid("missing Scene3D"))?,
data.camera.ok_or(invalid("missing 3D camera"))?,
@@ -551,6 +641,12 @@ pub fn pick(
let result = cx.new_object()?;
crate::ui_bridge::attach_desktop_type(cx, result, "RayHit3D", desktop)?;
cx.set_attr(result, "mesh", Value::Object(mesh))?;
cx.set_attr(result, "node", Value::Object(mesh))?;
cx.set_attr(
result,
"instance",
Value::Number((hit.instance as i64).into()),
)?;
cx.set_attr(
result,
"distance",
@@ -700,7 +796,11 @@ pub fn transform(
let camera = matches!(kind, NodeKind::Perspective | NodeKind::Orthographic);
if !matches!(
kind,
NodeKind::Mesh | NodeKind::Group | NodeKind::Perspective | NodeKind::Orthographic
NodeKind::Mesh
| NodeKind::Group
| NodeKind::Panel
| NodeKind::Perspective
| NodeKind::Orthographic
) || rotate && camera
{
return Err(invalid("unsupported 3D transform target"));