feat: separate 2d scenes viewports and explicit cameras

This commit is contained in:
2026-11-10 22:42:56 +08:00
parent 32d7ada3ab
commit 040b779f5f
29 changed files with 1309 additions and 70 deletions
+44
View File
@@ -33,6 +33,11 @@ pub enum Kind {
Row,
Column,
Overlay,
Scene2D,
CanvasViewport {
width: f32,
height: f32,
},
Button,
Page,
}
@@ -129,6 +134,7 @@ pub struct Data {
pub border: crate::layout::Insets,
pub border_color: String,
pub clip_children: bool,
pub camera: Option<ObjectRef>,
pub scroll_axis: crate::scroll::Axis,
pub position: [f32; 2],
pub surface: crate::page::Surface,
@@ -168,6 +174,7 @@ impl Data {
border: crate::layout::Insets::default(),
border_color: "#D8DCE2".into(),
clip_children: false,
camera: None,
scroll_axis: crate::scroll::Axis::Both,
position: [0.0, 0.0],
surface: crate::page::Surface::new(crate::page::Mode::Window),
@@ -187,6 +194,8 @@ impl Data {
Kind::Row
| Kind::Column
| Kind::Overlay
| Kind::Scene2D
| Kind::CanvasViewport { .. }
| Kind::Button
| Kind::Page
| Kind::Scroll { .. }
@@ -205,6 +214,9 @@ impl ObjectPayload for Data {
"tessera-block-data"
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
if let Some(camera) = self.camera {
visit(camera);
}
if let Some(properties) = self.properties {
visit(properties);
}
@@ -403,6 +415,11 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
));
}
match &data.kind {
Kind::CanvasViewport { width, height } => fields.extend([
("width", number(*width)),
("height", number(*height)),
("camera", data.camera.map_or(Value::Nil, Value::Object)),
]),
Kind::Page => fields.extend([
("mode", Value::Text(data.surface.mode.name().into())),
("panX", number(data.surface.pan.x)),
@@ -461,6 +478,24 @@ pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
{
return Err(VmError::InvalidArgument("box minimum exceeds maximum"));
}
if matches!(data.kind, Kind::CanvasViewport { .. }) {
crate::viewport::camera(
store,
data.camera.ok_or(VmError::InvalidArgument(
"CanvasViewport requires a Camera2D",
))?,
)?;
if data.children.len() != 1
|| !matches!(
resolve(store, data.children[0].block)?.1.kind,
Kind::Scene2D
)
{
return Err(VmError::InvalidArgument(
"CanvasViewport requires exactly one Scene2D",
));
}
}
Ok(data)
}
@@ -501,6 +536,13 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
return Ok(());
}
match name {
"camera" if matches!(data.kind, Kind::CanvasViewport { .. }) => {
let Value::Object(camera) = value else {
return Err(bad());
};
data.camera = Some(*camera);
return Ok(());
}
"paddingTop" | "paddingRight" | "paddingBottom" | "paddingLeft" => {
let index = match name {
"paddingTop" => 0,
@@ -646,6 +688,8 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
return Ok(());
}
match (&mut data.kind, name) {
(Kind::CanvasViewport { width, .. }, "width") => *width = number()?,
(Kind::CanvasViewport { height, .. }, "height") => *height = number()?,
(Kind::Text { value: text, .. }, "text") => {
let Value::Text(value) = value else {
return Err(bad());
+62 -6
View File
@@ -156,6 +156,16 @@ impl RenderDocument {
for clip in self.frame.command_clips.iter().flatten() {
validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?;
}
if !self.frame.command_views.is_empty()
&& self.frame.command_views.len() != self.frame.commands.len()
{
bail!("invalid command view table");
}
for view in self.frame.command_views.iter().flatten() {
if !view.valid() {
bail!("invalid command view transform");
}
}
for command in &self.frame.commands {
command.validate()?;
}
@@ -175,6 +185,9 @@ impl RenderDocument {
}
let mut mount_ids = HashSet::new();
for mount in &self.frame.mounts {
if mount.view.is_some_and(|view| !view.valid()) {
bail!("invalid Mount view transform");
}
if mount.id == 0 || mount.block_id.is_empty() || !mount_ids.insert(mount.id) {
bail!("invalid or duplicate mount identity");
}
@@ -182,6 +195,9 @@ impl RenderDocument {
if let Some(clip) = mount.clip {
validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?;
}
if let Some(clip) = mount.viewport_clip {
validate_rect(clip[0], clip[1], clip[2], clip[3], 0.0)?;
}
if let Some(scroll) = mount.scroll
&& (!scroll.iter().all(|n| {
n.is_finite() && (0.0..=crate::ui_bridge::MAX_DIMENSION as f32).contains(n)
@@ -229,7 +245,17 @@ impl RenderDocument {
clip[0], clip[1], clip[2], clip[3], scale,
)));
}
list.push(command.to_draw_command(scale)?);
let view = frame
.command_views
.get(index)
.copied()
.flatten()
.unwrap_or_default();
list.push(
command
.to_draw_command(scale * view.zoom)?
.translated(Point::new(view.x * scale, view.y * scale)),
);
if clip.is_some() {
list.push(DrawCommand::PopClip);
}
@@ -245,10 +271,18 @@ impl RenderDocument {
}
list.push(
RenderCommand::StrokeRoundedRect {
x: focus.x,
y: focus.y,
width: focus.width,
height: focus.height,
x: focus
.view
.unwrap_or_default()
.rect(Rect::new(focus.x, focus.y, focus.width, focus.height))
.x,
y: focus
.view
.unwrap_or_default()
.rect(Rect::new(focus.x, focus.y, focus.width, focus.height))
.y,
width: focus.width * focus.view.unwrap_or_default().zoom,
height: focus.height * focus.view.unwrap_or_default().zoom,
radius: 7.0,
stroke_width: 2.0,
color: "#4F6FDB".into(),
@@ -345,6 +379,10 @@ pub struct Frame {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub command_clips: Vec<Option<[f32; 4]>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub command_views: Vec<Option<crate::viewport::Transform>>,
#[serde(skip)]
pub command_mounts: Vec<u64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mounts: Vec<MountGeometry>,
#[serde(default)]
pub layout_version: u64,
@@ -366,6 +404,8 @@ impl Default for Frame {
background: default_background(),
commands: Vec::new(),
command_clips: Vec::new(),
command_views: Vec::new(),
command_mounts: Vec::new(),
mounts: Vec::new(),
layout_version: 0,
session: 0,
@@ -379,6 +419,12 @@ impl Default for Frame {
/// A position in a published frame. Identifiers are opaque data, never VM handles.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct MountGeometry {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub canvas_viewport: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub viewport_clip: Option<[f32; 4]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<crate::viewport::Transform>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub clip: Option<[f32; 4]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -397,7 +443,8 @@ pub struct MountGeometry {
impl MountGeometry {
pub fn contains(&self, point: Point) -> bool {
Rect::new(self.x, self.y, self.width, self.height).contains(point)
let local = self.view.map_or(point, |view| view.inverse(point));
Rect::new(self.x, self.y, self.width, self.height).contains(local)
&& self.clip.is_none_or(|c| {
c[2] > 0.0 && c[3] > 0.0 && Rect::new(c[0], c[1], c[2], c[3]).contains(point)
})
@@ -405,6 +452,15 @@ impl MountGeometry {
}
impl Frame {
pub fn canvas_at(&self, point: Point) -> Option<&MountGeometry> {
self.mounts.iter().rev().find(|mount| {
mount.canvas_viewport
&& mount.contains(point)
&& mount.viewport_clip.is_some_and(|clip| {
Rect::new(clip[0], clip[1], clip[2], clip[3]).contains(point)
})
})
}
pub fn hit_test(&self, point: Point) -> Option<&MountGeometry> {
if self.fault.is_some() {
return None;
+8 -1
View File
@@ -55,6 +55,7 @@ enum Query {
ScrollBy,
ScrollPosition,
ScrollIntoView,
FitView,
Parent,
FirstChild,
NextSibling,
@@ -99,6 +100,7 @@ impl NativeCallable for Method {
| Query::ScrollTo
| Query::ScrollBy
| Query::ScrollIntoView
| Query::FitView
| Query::ScrollPosition
)
{
@@ -133,6 +135,10 @@ impl NativeCallable for Method {
crate::scroll::into_view(cx, self.owner, self.desktop)?;
Value::Nil
}
Query::FitView => {
crate::viewport::fit(cx, &mount)?;
Value::Nil
}
Query::ScrollPosition => {
let p = mount
.geometry
@@ -263,7 +269,7 @@ fn mount_signature(
};
let effect = if matches!(
query,
Query::ScrollTo | Query::ScrollBy | Query::ScrollIntoView | Query::Focus
Query::ScrollTo | Query::ScrollBy | Query::ScrollIntoView | Query::FitView | Query::Focus
) {
CallEffect::Mutating
} else {
@@ -405,6 +411,7 @@ impl NativeCallable for Sync {
("scrollBy", Query::ScrollBy),
("scrollPosition", Query::ScrollPosition),
("scrollIntoView", Query::ScrollIntoView),
("fitView", Query::FitView),
("parent", Query::Parent),
("firstChild", Query::FirstChild),
("nextSibling", Query::NextSibling),
+29
View File
@@ -154,6 +154,14 @@ impl RenderCache {
});
}
}
if let Some(camera) = data.camera {
for name in ["x", "y", "zoom"] {
dependencies.push(Dependency {
object: camera,
property: Some(name.into()),
});
}
}
if !finish {
if !path.insert(data_ref) {
return Err(VmError::InvalidArgument("cyclic Block composition"));
@@ -259,6 +267,27 @@ impl RenderCache {
children,
},
Kind::Spacer(size) => UiKind::Spacer(*size),
Kind::CanvasViewport { width, height } => UiKind::CanvasViewport {
width: *width,
height: *height,
camera: crate::viewport::camera(
store,
data.camera
.ok_or(VmError::InvalidArgument("missing camera"))?,
)?,
children,
},
Kind::Scene2D => UiKind::Scene2D {
positions: data
.children
.iter()
.map(|child| {
let (_, child) = block::resolve(store, child.block)?;
Ok(block::visual_data(store, child)?.position)
})
.collect::<Result<Vec<_>, VmError>>()?,
children,
},
Kind::Overlay => UiKind::Overlay {
padding: data.padding,
children,