feat: separate 2d scenes viewports and explicit cameras
This commit is contained in:
@@ -59,6 +59,26 @@ pub enum DrawCommand {
|
||||
},
|
||||
}
|
||||
|
||||
impl DrawCommand {
|
||||
pub fn translated(mut self, delta: Point) -> Self {
|
||||
match &mut self {
|
||||
Self::WrappedText { rect, .. }
|
||||
| Self::PushClip(rect)
|
||||
| Self::FillRoundedRect { rect, .. }
|
||||
| Self::StrokeRoundedRect { rect, .. } => {
|
||||
rect.x += delta.x;
|
||||
rect.y += delta.y;
|
||||
}
|
||||
Self::Text { origin, .. } => {
|
||||
origin.x += delta.x;
|
||||
origin.y += delta.y;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DisplayList {
|
||||
commands: Vec<DrawCommand>,
|
||||
|
||||
+18
-3
@@ -209,7 +209,10 @@ pub fn child_constraints(node: &UiNode, parent: [f32; 4]) -> [f32; 4] {
|
||||
content_limit(parent[3], padding.vertical()),
|
||||
];
|
||||
}
|
||||
if matches!(node.kind, UiKind::Canvas { .. }) {
|
||||
if matches!(
|
||||
node.kind,
|
||||
UiKind::Canvas { .. } | UiKind::Scene2D { .. } | UiKind::CanvasViewport { .. }
|
||||
) {
|
||||
return root_constraints(None);
|
||||
}
|
||||
if let UiKind::Scroll { width, height, .. } = node.kind {
|
||||
@@ -429,7 +432,8 @@ fn shape(node: &UiNode, children: Vec<Size>, constraints: [f32; 4]) -> Result<Sh
|
||||
size.height + padding.vertical(),
|
||||
)
|
||||
}
|
||||
UiKind::Canvas { positions, .. } => {
|
||||
UiKind::CanvasViewport { width, height, .. } => Shape::Rect(*width, *height),
|
||||
UiKind::Canvas { positions, .. } | UiKind::Scene2D { positions, .. } => {
|
||||
let mut size = Size::default();
|
||||
for (position, child) in positions.iter().zip(children) {
|
||||
size.width = size.width.max(position[0] + child.width);
|
||||
@@ -770,7 +774,15 @@ pub fn arrange_native(
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
if let UiKind::Canvas { positions, .. } = &node.kind {
|
||||
if matches!(node.kind, UiKind::CanvasViewport { .. }) {
|
||||
let inset = insets(node);
|
||||
return Ok(node
|
||||
.children()
|
||||
.iter()
|
||||
.map(|_| (x + inset.left, y + inset.top))
|
||||
.collect());
|
||||
}
|
||||
if let UiKind::Canvas { positions, .. } | UiKind::Scene2D { positions, .. } = &node.kind {
|
||||
return Ok(positions
|
||||
.iter()
|
||||
.map(|point| (x + point[0], y + point[1]))
|
||||
@@ -996,6 +1008,9 @@ impl LayoutRuntime {
|
||||
coordinate(x + size.width)?;
|
||||
coordinate(y + size.height)?;
|
||||
mounts.push(MountGeometry {
|
||||
canvas_viewport: matches!(item.node.kind, UiKind::CanvasViewport { .. }),
|
||||
viewport_clip: None,
|
||||
view: None,
|
||||
id: item.id,
|
||||
clip: None,
|
||||
scroll: None,
|
||||
|
||||
@@ -12,3 +12,4 @@ pub(crate) mod source_hit;
|
||||
pub(crate) mod source_layout;
|
||||
pub(crate) mod source_paint;
|
||||
pub(crate) mod text;
|
||||
pub(crate) mod viewport;
|
||||
|
||||
@@ -96,6 +96,8 @@ pub fn project(vm: &mut Vm, table: &MountTable, root: &UiNode, frame: &mut Frame
|
||||
let mut contexts = HashMap::<u64, (f32, f32, Option<[f32; 4]>)>::new();
|
||||
frame.commands.clear();
|
||||
frame.command_clips.clear();
|
||||
frame.command_mounts.clear();
|
||||
frame.command_views.clear();
|
||||
for (i, m) in frame.mounts.iter_mut().enumerate() {
|
||||
let (dx, dy, clip) = m
|
||||
.parent
|
||||
@@ -176,6 +178,7 @@ pub fn project(vm: &mut Vm, table: &MountTable, root: &UiNode, frame: &mut Frame
|
||||
) {
|
||||
frame.commands.push(command);
|
||||
frame.command_clips.push(m.clip);
|
||||
frame.command_mounts.push(m.id);
|
||||
}
|
||||
}
|
||||
if frame.commands.len() > 10_000 {
|
||||
@@ -256,6 +259,14 @@ pub fn into_view(
|
||||
};
|
||||
let mount = cx.store().payload::<Mount>(owner, "Mount")?.clone();
|
||||
parent = mount.parent;
|
||||
if mount.geometry.canvas_viewport {
|
||||
rect = [
|
||||
mount.geometry.x,
|
||||
mount.geometry.y,
|
||||
mount.geometry.width,
|
||||
mount.geometry.height,
|
||||
];
|
||||
}
|
||||
if let Some(offset) = mount.geometry.scroll {
|
||||
let delta = |start: f32, length: f32, viewport: f32, size: f32| {
|
||||
if start < viewport {
|
||||
|
||||
@@ -79,8 +79,10 @@ fn selector(
|
||||
continue;
|
||||
}
|
||||
let geometry = &target.geometry;
|
||||
let x = point[0] - geometry.x;
|
||||
let y = point[1] - geometry.y;
|
||||
let point = crate::geometry::Point::new(point[0], point[1]);
|
||||
let point = geometry.view.map_or(point, |view| view.inverse(point));
|
||||
let x = point.x - geometry.x;
|
||||
let y = point.y - geometry.y;
|
||||
if x < 0.0 || y < 0.0 || x > geometry.width || y > geometry.height {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -417,6 +417,8 @@ fn finish(vm: &mut Vm, mut work: Work, reads: Vec<endor_core::ReadDependency>) -
|
||||
}
|
||||
let mut commands = Vec::new();
|
||||
let mut clips = Vec::new();
|
||||
let mut views = Vec::new();
|
||||
let mut owners = Vec::new();
|
||||
for mount in &frame.mounts {
|
||||
let before = commands.len();
|
||||
if let Some(custom) = output.commands.get(&mount.id) {
|
||||
@@ -436,12 +438,16 @@ fn finish(vm: &mut Vm, mut work: Work, reads: Vec<endor_core::ReadDependency>) -
|
||||
));
|
||||
}
|
||||
clips.extend(std::iter::repeat_n(mount.clip, commands.len() - before));
|
||||
views.extend(std::iter::repeat_n(mount.view, commands.len() - before));
|
||||
owners.extend(std::iter::repeat_n(mount.id, commands.len() - before));
|
||||
if commands.len() > 10_000 {
|
||||
bail!("paint command budget exceeded");
|
||||
}
|
||||
}
|
||||
frame.commands = commands;
|
||||
frame.command_clips = clips;
|
||||
frame.command_views = views;
|
||||
frame.command_mounts = owners;
|
||||
let registry = object(vm.get_attr(desktop, "types")?)?;
|
||||
let reads = reads
|
||||
.into_iter()
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
//! Reversible projections keep camera movement independent of layout.
|
||||
use crate::geometry::{Point, Rect};
|
||||
use endor_core::{ObjectPayload, ObjectRef, ObjectStore, VmError};
|
||||
|
||||
/// Marker payload gives cameras a native nominal identity while their fields
|
||||
/// remain ordinary traced, bindable VM attributes.
|
||||
#[derive(Debug)]
|
||||
pub struct Camera2D;
|
||||
impl ObjectPayload for Camera2D {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"camera-2d"
|
||||
}
|
||||
fn allows_attributes(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn trace(&self, _: &mut dyn FnMut(ObjectRef)) {}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CameraView {
|
||||
pub identity: String,
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub zoom: f32,
|
||||
}
|
||||
|
||||
pub fn camera(store: &ObjectStore, object: ObjectRef) -> Result<CameraView, VmError> {
|
||||
store.payload::<Camera2D>(object, "Camera2D")?;
|
||||
let x = crate::scroll::coordinate(&store.get_attr(object, "x")?)?;
|
||||
let y = crate::scroll::coordinate(&store.get_attr(object, "y")?)?;
|
||||
let zoom = crate::scroll::coordinate(&store.get_attr(object, "zoom")?)?;
|
||||
if !(0.01..=100.0).contains(&zoom) {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"Camera2D.zoom expects 0.01 through 100",
|
||||
));
|
||||
}
|
||||
Ok(CameraView {
|
||||
identity: object.to_string(),
|
||||
x,
|
||||
y,
|
||||
zoom,
|
||||
})
|
||||
}
|
||||
|
||||
/// Fit finite scene bounds using this occurrence's allocation. Sharing a camera
|
||||
/// is explicit, so fitting one view then intentionally affects all its users.
|
||||
pub fn fit(
|
||||
cx: &mut endor_core::NativeContext<'_>,
|
||||
mount: &crate::mount::Mount,
|
||||
) -> Result<(), VmError> {
|
||||
if !mount.geometry.canvas_viewport || mount.layout.is_some() {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"fitView requires a committed CanvasViewport Mount",
|
||||
));
|
||||
}
|
||||
let (_, data) = crate::block::resolve(cx.store(), mount.block)?;
|
||||
let data = crate::block::visual_data(cx.store(), data)?;
|
||||
let camera = data
|
||||
.camera
|
||||
.ok_or(VmError::InvalidArgument("missing viewport camera"))?;
|
||||
let root = mount
|
||||
.first_child
|
||||
.map(|weak| cx.upgrade(weak))
|
||||
.transpose()?
|
||||
.flatten()
|
||||
.ok_or(VmError::InvalidArgument("missing scene occurrence"))?;
|
||||
let scene = cx
|
||||
.store()
|
||||
.payload::<crate::mount::Mount>(root, "Mount")?
|
||||
.clone();
|
||||
let mut next = scene.first_child;
|
||||
let mut bounds: Option<[f32; 4]> = None;
|
||||
let mut count = 0;
|
||||
while let Some(weak) = next {
|
||||
count += 1;
|
||||
if count > 10_000 {
|
||||
return Err(VmError::ExecutionLimit("fitView scene bounds"));
|
||||
}
|
||||
let object = cx
|
||||
.upgrade(weak)?
|
||||
.ok_or(VmError::InvalidArgument("expired scene child"))?;
|
||||
let child = cx.store().payload::<crate::mount::Mount>(object, "Mount")?;
|
||||
let rect = [
|
||||
child.geometry.x - scene.geometry.x,
|
||||
child.geometry.y - scene.geometry.y,
|
||||
child.geometry.x - scene.geometry.x + child.geometry.width,
|
||||
child.geometry.y - scene.geometry.y + child.geometry.height,
|
||||
];
|
||||
bounds = Some(bounds.map_or(rect, |b| {
|
||||
[
|
||||
b[0].min(rect[0]),
|
||||
b[1].min(rect[1]),
|
||||
b[2].max(rect[2]),
|
||||
b[3].max(rect[3]),
|
||||
]
|
||||
}));
|
||||
next = child.next_sibling;
|
||||
}
|
||||
let node = crate::block::snapshot(cx.store(), mount.block)?;
|
||||
let inset = crate::layout::insets(&node);
|
||||
let width = (mount.geometry.width - inset.horizontal()).max(0.0);
|
||||
let height = (mount.geometry.height - inset.vertical()).max(0.0);
|
||||
let (x, y, zoom) = if let Some(bounds) = bounds {
|
||||
let zoom = (width / (bounds[2] - bounds[0] + 48.0))
|
||||
.min(height / (bounds[3] - bounds[1] + 48.0))
|
||||
.clamp(0.01, 100.0);
|
||||
(
|
||||
(bounds[0] + bounds[2]) / 2.0 - width / (2.0 * zoom),
|
||||
(bounds[1] + bounds[3]) / 2.0 - height / (2.0 * zoom),
|
||||
zoom,
|
||||
)
|
||||
} else {
|
||||
(0.0, 0.0, 1.0)
|
||||
};
|
||||
for (name, value) in [("x", x), ("y", y), ("zoom", zoom)] {
|
||||
cx.set_attr(
|
||||
camera,
|
||||
name,
|
||||
crate::native_visual::value(value.clamp(-1_000_000.0, 1_000_000.0)),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Transform {
|
||||
pub zoom: f32,
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
}
|
||||
impl Default for Transform {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
zoom: 1.0,
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Transform {
|
||||
pub fn point(self, point: Point) -> Point {
|
||||
Point::new(point.x * self.zoom + self.x, point.y * self.zoom + self.y)
|
||||
}
|
||||
pub fn inverse(self, point: Point) -> Point {
|
||||
Point::new(
|
||||
(point.x - self.x) / self.zoom,
|
||||
(point.y - self.y) / self.zoom,
|
||||
)
|
||||
}
|
||||
pub fn rect(self, rect: Rect) -> Rect {
|
||||
let point = self.point(Point::new(rect.x, rect.y));
|
||||
Rect::new(
|
||||
point.x,
|
||||
point.y,
|
||||
rect.width * self.zoom,
|
||||
rect.height * self.zoom,
|
||||
)
|
||||
}
|
||||
pub fn then(self, outer: Self) -> Self {
|
||||
Self {
|
||||
zoom: self.zoom * outer.zoom,
|
||||
x: self.x * outer.zoom + outer.x,
|
||||
y: self.y * outer.zoom + outer.y,
|
||||
}
|
||||
}
|
||||
pub fn valid(self) -> bool {
|
||||
self.zoom.is_finite()
|
||||
&& self.zoom > 0.0
|
||||
&& self.zoom <= 1_000_000.0
|
||||
&& self.x.is_finite()
|
||||
&& self.y.is_finite()
|
||||
&& self.x.abs() <= 1_000_000.0
|
||||
&& self.y.abs() <= 1_000_000.0
|
||||
}
|
||||
}
|
||||
|
||||
fn intersect(a: [f32; 4], b: [f32; 4]) -> [f32; 4] {
|
||||
let x = a[0].max(b[0]);
|
||||
let y = a[1].max(b[1]);
|
||||
[
|
||||
x,
|
||||
y,
|
||||
((a[0] + a[2]).min(b[0] + b[2]) - x).max(0.0),
|
||||
((a[1] + a[3]).min(b[1] + b[3]) - y).max(0.0),
|
||||
]
|
||||
}
|
||||
|
||||
pub fn project(
|
||||
root: &crate::ui_bridge::UiNode,
|
||||
frame: &mut crate::document::Frame,
|
||||
) -> anyhow::Result<()> {
|
||||
use crate::ui_bridge::UiKind;
|
||||
use std::collections::HashMap;
|
||||
let mut nodes = HashMap::new();
|
||||
let mut work = vec![root];
|
||||
while let Some(node) = work.pop() {
|
||||
nodes.insert(node.block_id.as_str(), node);
|
||||
work.extend(node.children().iter().map(|node| node.as_ref()));
|
||||
}
|
||||
let mut contexts = HashMap::<u64, (Transform, Option<[f32; 4]>)>::new();
|
||||
for mount in &mut frame.mounts {
|
||||
let node = nodes[mount.block_id.as_str()];
|
||||
let (view, clip) = mount
|
||||
.parent
|
||||
.and_then(|parent| contexts.get(&parent).copied())
|
||||
.unwrap_or_default();
|
||||
anyhow::ensure!(
|
||||
view.valid(),
|
||||
"nested viewport transform exceeds numeric budget"
|
||||
);
|
||||
mount.view = (view != Transform::default()).then_some(view);
|
||||
mount.clip = clip;
|
||||
mount.viewport_clip = None;
|
||||
let mut child_view = view;
|
||||
let mut child_clip = clip;
|
||||
let inset = crate::layout::insets(node);
|
||||
let viewport = if let UiKind::CanvasViewport { camera, .. } = &node.kind {
|
||||
let x = mount.x + inset.left;
|
||||
let y = mount.y + inset.top;
|
||||
child_view = Transform {
|
||||
zoom: camera.zoom,
|
||||
x: x * (1.0 - camera.zoom) - camera.x * camera.zoom,
|
||||
y: y * (1.0 - camera.zoom) - camera.y * camera.zoom,
|
||||
}
|
||||
.then(view);
|
||||
Some(Rect::new(
|
||||
x,
|
||||
y,
|
||||
(mount.width - inset.horizontal()).max(0.0),
|
||||
(mount.height - inset.vertical()).max(0.0),
|
||||
))
|
||||
} else if node.clip_children {
|
||||
let border = node.border;
|
||||
Some(Rect::new(
|
||||
mount.x + border.left.min(mount.width),
|
||||
mount.y + border.top.min(mount.height),
|
||||
(mount.width - border.horizontal()).max(0.0),
|
||||
(mount.height - border.vertical()).max(0.0),
|
||||
))
|
||||
} else if matches!(node.kind, UiKind::Scroll { .. }) {
|
||||
Some(Rect::new(mount.x, mount.y, mount.width, mount.height))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(rect) = viewport {
|
||||
let rect = view.rect(rect);
|
||||
let rect = [rect.x, rect.y, rect.width, rect.height];
|
||||
child_clip = Some(clip.map_or(rect, |clip| intersect(clip, rect)));
|
||||
if mount.canvas_viewport {
|
||||
mount.viewport_clip = child_clip;
|
||||
}
|
||||
}
|
||||
contexts.insert(mount.id, (child_view, child_clip));
|
||||
}
|
||||
let mounts: HashMap<_, _> = frame.mounts.iter().map(|mount| (mount.id, mount)).collect();
|
||||
frame.command_views.clear();
|
||||
frame.command_clips.clear();
|
||||
anyhow::ensure!(
|
||||
frame.command_mounts.len() == frame.commands.len(),
|
||||
"missing command occurrence table"
|
||||
);
|
||||
for owner in &frame.command_mounts {
|
||||
let mount = mounts
|
||||
.get(owner)
|
||||
.ok_or_else(|| anyhow::anyhow!("paint owner is unavailable"))?;
|
||||
frame.command_views.push(mount.view);
|
||||
frame.command_clips.push(mount.clip);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn nested_views_compose_and_invert_without_changing_layout_coordinates() {
|
||||
let inner = Transform {
|
||||
zoom: 2.0,
|
||||
x: 12.0,
|
||||
y: -40.0,
|
||||
};
|
||||
let outer = Transform {
|
||||
zoom: 0.5,
|
||||
x: 80.0,
|
||||
y: 20.0,
|
||||
};
|
||||
let point = Point::new(-5.0, 100.0);
|
||||
let composed = inner.then(outer);
|
||||
assert_eq!(composed.point(point), outer.point(inner.point(point)));
|
||||
assert_eq!(composed.inverse(composed.point(point)), point);
|
||||
assert_eq!(
|
||||
composed.rect(Rect::new(-5.0, 100.0, 20.0, 30.0)),
|
||||
Rect::new(81.0, 100.0, 20.0, 30.0)
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user