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
+3 -1
View File
@@ -142,7 +142,9 @@ ScrollBlock.axis is a managed visual attribute: "both" (default), "vertical" or
ContainerBlock.mainAlign accepts "start" (default), "center", "end" or "space-between". Native arrangement uses allocated Bounds after padding/minimum gap, distributes positive remaining main-axis space and keeps child sizes unchanged. Overflow keeps start placement. Explicit source arrange placements remain authoritative; this is alignment, not flex sizing.
Finite box layout: Overlay(padding, gap, children...) stacks children (gap is unused); mainAlign aligns horizontally and crossAlign vertically. Row/Column crossAlign accepts "start", "center", "end" or "stretch". Block.alignSelf defaults to "auto" and can override crossAlign per occurrence. marginTop/Right/Bottom/Left participate in measurement, alignment and flex allocation, without collapsing. paddingTop/Right/Bottom/Left override a side of the container padding; "auto" restores its fallback. borderTop/Right/Bottom/Left reserve inner border space; borderColor controls native border paint. Source paint overrides remain authoritative. boxWidth/boxHeight accept "auto", a nonnegative border-box dimension, or "fill" (finite parent required). Main-axis fill shares remaining space with weight 1 unless flex is set; minWidth/minHeight/maxWidth/maxHeight bound each dimension. Stretch changes only auto cross-axis dimensions. overflow is "visible" or "clip"; clipping affects descendant paint and hits. ScrollBlock handles scrolling independently of its content layout. See examples/box-layout.endor and docs/scene-architecture.md. Scene2D/CanvasViewport/Camera2D and Scene3D/Viewport3D are still pending; Page.mode remains a transitional API.
Finite box layout: Overlay(padding, gap, children...) stacks children (gap is unused); mainAlign aligns horizontally and crossAlign vertically. Row/Column crossAlign accepts "start", "center", "end" or "stretch". Block.alignSelf defaults to "auto" and can override crossAlign per occurrence. marginTop/Right/Bottom/Left participate in measurement, alignment and flex allocation, without collapsing. paddingTop/Right/Bottom/Left override a side of the container padding; "auto" restores its fallback. borderTop/Right/Bottom/Left reserve inner border space; borderColor controls native border paint. Source paint overrides remain authoritative. boxWidth/boxHeight accept "auto", a nonnegative border-box dimension, or "fill" (finite parent required). Main-axis fill shares remaining space with weight 1 unless flex is set; minWidth/minHeight/maxWidth/maxHeight bound each dimension. Stretch changes only auto cross-axis dimensions. overflow is "visible" or "clip"; clipping affects descendant paint and hits. ScrollBlock handles scrolling independently of its content layout. See examples/box-layout.endor and docs/scene-architecture.md. Independent 2D scenes are described below; Scene3D/Viewport3D are still pending. Page.mode remains a compatibility API.
Independent 2D scenes are now implemented: Scene2D(children...) stores world content at child x/y; CanvasViewport(width,height,scene) is a finite layout box with its own Camera2D(). Camera2D(x=0,y=0,zoom=1) fields are ordinary managed attributes; zoom is 0.01–100. Sharing a scene does not share its camera; assigning second.camera=first.camera does. Scene content may contain layout containers and nested finite viewports; Overlay siblings stay fixed. Mount.fitView() fits finite direct scene-child bounds using that occurrence's allocation. Native wheel/pinch/space or middle drag targets the innermost viewport; drag retains its initial target. viewport-pan/viewport-zoom carry the viewport Mount and current frame identities, with signed logical page coordinates. Pan delta is measured before the viewport projection; zoom delta is [factor,0] with an in-content pointer anchor. Worker validation rejects stale/invalid input before invoking the VM. Draw and hit transforms compose consistently while layout geometry and measurement caches remain in world coordinates. ScrollView is a nominal ScrollBlock subtype. The default page uses these APIs; old Page.mode/panX/panY/zoom remain for compatibility. Scene3D/Viewport3D are still pending. See examples/scene-viewports.endor.
Block.flex is a nonnegative weight (default 0). Native containers reserve fixed measured children, padding and gaps, then share remaining allocated main-axis space between positive weights with zero basis. Actual child allocation feeds remeasurement. It does not request parent expansion. Further controls are described below.
+84
View File
@@ -581,3 +581,87 @@ page.render(button)
assert_eq!(response.0, 400);
assert!(namespace.read().unwrap().document.frame.fault.is_none());
}
#[test]
fn explicit_viewport_camera_crosses_http_and_rejects_bad_anchors_without_faulting() {
let server = Arc::new(Server::http("127.0.0.1:0").unwrap());
let namespace = Arc::new(RwLock::new(NamespaceState {
viewport: Some(crate::layout::Size {
width: 600.0,
height: 400.0,
}),
..NamespaceState::default()
}));
let api = start_server(server.clone(), namespace.clone(), Arc::new(|| {})).unwrap();
let client = TestServer {
address: server.server_addr().to_ip().unwrap(),
server,
api: Some(api),
};
let source = r#"
content = Button("inside")
content.x = 40
content.y = 20
scene = Scene2D(content)
view = CanvasViewport(200, 100, scene)
view.borderLeft = 10
page = Page()
page.render(Column(20, 0, view))
"#;
let response = client.request("PUT", "/v1/namespaces/app.main/code", source);
assert_eq!(response.0, 200, "{}", response.2);
let camera = |kind: &str, delta: [f32; 2], point: Option<[f32; 2]>| {
let current = namespace.read().unwrap();
let frame = &current.document.frame;
serde_json::to_string(&crate::events::Input {
window: 1,
session: frame.session,
layout_version: frame.layout_version,
mount: frame
.mounts
.iter()
.find(|mount| mount.canvas_viewport)
.unwrap()
.id,
kind: kind.into(),
delta: Some(delta),
point,
press_point: None,
screen_position: None,
tab_drop: None,
})
.unwrap()
};
let path = "/v1/namespaces/app.main/events";
let pan = camera("viewport-pan", [20.0, -10.0], None);
let response = client.request("POST", path, &pan);
assert_eq!(response.0, 200, "{}", response.2);
assert_eq!(client.request("POST", path, &pan).0, 409);
let response = client.request(
"POST",
path,
&camera("viewport-zoom", [2.0, 0.0], Some([80.0, 60.0])),
);
assert_eq!(response.0, 200, "{}", response.2);
for (expression, expected) in [
("view.camera.x", "45"),
("view.camera.y", "10"),
("view.camera.zoom", "2"),
] {
let response = client.request("POST", "/v1/namespaces/app.main/repl", expression);
assert_eq!(response.0, 200, "{}", response.2);
assert_eq!(
serde_json::from_str::<serde_json::Value>(&response.2).unwrap()["value"],
expected
);
}
for point in [[25.0, 30.0], [220.0, 30.0], [700.0, 700.0]] {
let response = client.request(
"POST",
path,
&camera("viewport-zoom", [2.0, 0.0], Some(point)),
);
assert_eq!(response.0, 400, "{}", response.2);
assert!(namespace.read().unwrap().document.frame.fault.is_none());
}
}
+23
View File
@@ -338,6 +338,8 @@ impl Worker {
| "scroll"
| "page-pan"
| "page-zoom"
| "viewport-pan"
| "viewport-zoom"
| "tab-activate"
| "tab-close"
| "tab-detach"
@@ -438,6 +440,7 @@ impl Worker {
!frame.mounts.iter().any(|mount| {
mount.id == input.mount
&& (mount.interactive
|| input.kind.starts_with("viewport-") && mount.canvas_viewport
|| input.kind == "scroll" && mount.scroll.is_some())
})
}
@@ -460,6 +463,26 @@ impl Worker {
"camera input is unavailable in this Page mode",
));
}
if input.kind == "viewport-zoom"
&& !frame.mounts.iter().any(|mount| {
mount.id == input.mount
&& input.point.is_some_and(|point| {
let point = crate::geometry::Point::new(point[0], point[1]);
mount.contains(point)
&& mount.viewport_clip.is_some_and(|clip| {
point.x >= clip[0]
&& point.y >= clip[1]
&& point.x < clip[0] + clip[2]
&& point.y < clip[1] + clip[3]
})
})
})
{
return RequestProgress::Complete(error_response(
StatusCode(400),
"zoom anchor is outside content viewport",
));
}
Some(input)
} else {
None
+319 -8
View File
@@ -4414,6 +4414,300 @@ fn overlay_stretch_allocates_each_occurrence_without_reflowing_its_siblings() {
);
}
#[test]
fn two_canvas_viewports_share_a_scene_with_independent_explicit_cameras() {
let (mut session, initial) = ReplSession::load(
r#"
hits = ui.state(0)
button = Button("shared")
button.onClick(hits.increment)
button.x = 40
button.y = 20
scene = Scene2D(button)
first = CanvasViewport(200, 100, scene)
second = CanvasViewport(200, 100, scene)
first.camera.x = 20
first.camera.zoom = 2
page = Page()
page.render(Row(0, 20, first, second))
"#,
"app.main",
304,
1,
)
.unwrap();
initial.validate().unwrap();
assert_eq!(
session
.execute("button.mounts().count", "app.main")
.unwrap()
.value,
"2"
);
let buttons: Vec<_> = initial
.frame
.mounts
.iter()
.filter(|mount| mount.interactive)
.collect();
assert_eq!(buttons.len(), 2);
assert_eq!(buttons[0].view.unwrap().zoom, 2.0);
assert!(buttons[1].view.is_none());
assert_eq!(buttons[0].clip, Some([0.0, 0.0, 200.0, 100.0]));
assert_eq!(buttons[1].clip, Some([220.0, 0.0, 200.0, 100.0]));
let first_id = buttons[0].id;
let point = [45.0, 45.0];
assert_eq!(
initial
.frame
.hit_test(crate::geometry::Point::new(point[0], point[1]))
.unwrap()
.id,
first_id
);
session
.dispatch(&crate::events::Input {
window: crate::window::MAIN_WINDOW,
session: initial.frame.session,
layout_version: initial.frame.layout_version,
mount: first_id,
kind: "click".into(),
point: Some(point),
press_point: Some(point),
delta: None,
tab_drop: None,
screen_position: None,
})
.unwrap();
assert_eq!(
session.execute("hits.value", "app.main").unwrap().value,
"1"
);
let changed = session
.execute("first.camera.x = -40\nfirst.camera.zoom = 1", "app.main")
.unwrap()
.document
.unwrap();
changed.validate().unwrap();
let buttons: Vec<_> = changed
.frame
.mounts
.iter()
.filter(|mount| mount.interactive)
.collect();
assert_eq!(buttons[0].id, first_id);
assert_eq!(buttons[0].view.unwrap().x, 40.0);
assert!(buttons[1].view.is_none());
assert_eq!(source_measure_stat(&mut session, "measured"), 0);
let shared = session
.execute(
"second.camera = first.camera\nfirst.camera.zoom = 2",
"app.main",
)
.unwrap()
.document
.unwrap();
shared.validate().unwrap();
assert!(
shared
.frame
.mounts
.iter()
.filter(|mount| mount.interactive)
.all(|mount| mount.view.is_some_and(|view| view.zoom == 2.0))
);
}
#[test]
fn nested_canvas_projects_pixels_and_hits_while_overlay_ui_stays_fixed() {
let (mut session, initial) = ReplSession::load(
r##"
button = Button("nested")
button.boxWidth = 20
button.boxHeight = 20
button.x = 10
button.y = 10
inner = CanvasViewport(80, 60, Scene2D(button))
inner.camera.zoom = 0.5
inner.x = 20
inner.y = 20
outer = CanvasViewport(200, 200, Scene2D(inner))
outer.camera.zoom = 2
hud = RectBlock(10, 10, 0, "#0000FF")
page = Page()
page.render(Overlay(0, 0, outer, hud))
"##,
"app.main",
305,
1,
)
.unwrap();
initial.validate().unwrap();
let button = initial
.frame
.mounts
.iter()
.find(|mount| mount.interactive)
.unwrap();
assert_eq!(
button.view.unwrap(),
crate::viewport::Transform {
zoom: 1.0,
x: 20.0,
y: 20.0
}
);
assert_eq!(button.clip, Some([40.0, 40.0, 160.0, 120.0]));
let point = crate::geometry::Point::new(55.0, 55.0);
assert_eq!(initial.frame.hit_test(point).unwrap().id, button.id);
let inner_id = initial.frame.canvas_at(point).unwrap().id;
let input = crate::events::Input {
window: 1,
session: initial.frame.session,
layout_version: initial.frame.layout_version,
mount: inner_id,
kind: "viewport-pan".into(),
delta: Some([10.0, 0.0]),
point: None,
press_point: None,
tab_drop: None,
screen_position: None,
};
session.dispatch(&input).unwrap();
assert_eq!(
session.execute("inner.camera.x", "app.main").unwrap().value,
"10"
);
assert_eq!(
session.execute("outer.camera.x", "app.main").unwrap().value,
"0"
);
let document = session
.execute("hud.invalidate(\"paint\")", "app.main")
.unwrap()
.document
.unwrap();
let mut pixels = vec![0; 200 * 200];
crate::software_renderer::SoftwareRenderer::render(
&document.display_list(1.0).unwrap(),
&mut pixels,
200,
200,
);
assert_eq!(pixels[5 * 200 + 5], 0x0000FF);
assert_ne!(pixels[55 * 200 + 45], pixels[190 * 200 + 190]);
}
#[test]
fn canvas_world_paint_is_zoomed_and_clipped_in_the_software_renderer() {
let (_, initial) = ReplSession::load(
r##"
rect = RectBlock(20, 20, 0, "#FF0000")
rect.x = -10
rect.y = 10
view = CanvasViewport(50, 50, Scene2D(rect))
view.camera.x = -10
view.camera.zoom = 2
page = Page()
page.render(Overlay(0, 0, view, RectBlock(10, 10, 0, "#0000FF")))
"##,
"app.main",
306,
1,
)
.unwrap();
initial.validate().unwrap();
let mut pixels = vec![0; 80 * 80];
crate::software_renderer::SoftwareRenderer::render(
&initial.display_list(1.0).unwrap(),
&mut pixels,
80,
80,
);
assert_eq!(pixels[5 * 80 + 5], 0x0000FF);
assert_eq!(pixels[25 * 80 + 5], 0xFF0000);
assert_eq!(pixels[55 * 80 + 5], pixels[79 * 80 + 79]);
assert_eq!(pixels[25 * 80 + 45], pixels[79 * 80 + 79]);
}
#[test]
fn scene_viewport_example_and_scroll_view_alias_run_as_real_source() {
let (mut session, initial) = ReplSession::load(
include_str!("../../../examples/scene-viewports.endor"),
"app.main",
307,
1,
)
.unwrap();
initial.validate().unwrap();
assert_eq!(
session
.execute("increment.mounts().count", "app.main")
.unwrap()
.value,
"2"
);
session
.execute(
"testScroll = ScrollView(100, 60, Row(0, 0, TextBlock(\"scroll\")))",
"app.main",
)
.unwrap();
assert_eq!(
session
.execute("ui.isInstance(testScroll, ScrollBlock)", "app.main")
.unwrap()
.value,
"true"
);
}
#[test]
fn fit_view_uses_finite_scene_bounds_and_this_mounts_size() {
let (mut session, initial) = ReplSession::load(
r#"
rect = RectBlock(100, 50)
rect.x = -100
rect.y = -25
view = CanvasViewport(296, 196, Scene2D(rect))
page = Page()
page.render(view)
"#,
"app.main",
308,
1,
)
.unwrap();
initial.validate().unwrap();
let document = session
.execute("view.mounts().at(0).fitView()", "app.main")
.unwrap()
.document
.unwrap();
document.validate().unwrap();
for (expression, expected) in [
("view.camera.zoom", "2"),
("view.camera.x", "-124"),
("view.camera.y", "-49"),
] {
assert_eq!(
session.execute(expression, "app.main").unwrap().value,
expected
);
}
let rect = document
.frame
.mounts
.iter()
.find(|mount| mount.width == 100.0 && mount.height == 50.0)
.unwrap();
let screen = rect
.view
.unwrap()
.point(crate::geometry::Point::new(rect.x, rect.y));
assert_eq!(screen, crate::geometry::Point::new(48.0, 48.0));
}
#[test]
fn scroll_axes_wrap_shared_text_and_clamp_only_the_enabled_offsets() {
let (mut session, initial) = ReplSession::load(
@@ -6211,7 +6505,7 @@ page.zoom=2
}
#[test]
fn bundled_start_page_creates_all_four_real_page_modes() {
fn bundled_start_page_uses_independent_layout_scroll_and_scene_viewports() {
let mut session = ReplSession::new_with_viewport(
302,
Some(crate::layout::Size {
@@ -6225,12 +6519,16 @@ fn bundled_start_page_creates_all_four_real_page_modes() {
.unwrap()
.document
.unwrap();
assert_eq!(document.frame.surface.mode, crate::page::Mode::Canvas);
for (label, mode) in [
("窗口页面", crate::page::Mode::Window),
("纵向延伸", crate::page::Mode::Vertical),
("横向延伸", crate::page::Mode::Horizontal),
] {
assert_eq!(document.frame.surface.mode, crate::page::Mode::Window);
assert!(
document
.frame
.mounts
.iter()
.any(|mount| mount.canvas_viewport)
);
for (label, scrolling) in [("窗口页面", false), ("纵向延伸", true), ("横向延伸", true)]
{
let home_tab = document
.frame
.tabs
@@ -6270,7 +6568,20 @@ fn bundled_start_page_creates_all_four_real_page_modes() {
.unwrap()
.document
.unwrap();
assert_eq!(document.frame.surface.mode, mode, "{label}");
assert_eq!(
document.frame.surface.mode,
crate::page::Mode::Window,
"{label}"
);
assert_eq!(
document
.frame
.mounts
.iter()
.any(|mount| mount.scroll.is_some()),
scrolling,
"{label}"
);
assert!(document.frame.fault.is_none());
let input = crate::events::Input {
window: 1,
+12 -4
View File
@@ -73,7 +73,11 @@ impl Input {
{
return Err("screen_position is only accepted for tab-detach with bounded coordinates");
}
if matches!(self.kind.as_str(), "page-pan" | "page-zoom") {
if matches!(
self.kind.as_str(),
"page-pan" | "page-zoom" | "viewport-pan" | "viewport-zoom"
) {
let viewport = self.kind.starts_with("viewport-");
let valid_delta = self.delta.is_some_and(|delta| {
delta
.iter()
@@ -82,17 +86,21 @@ impl Input {
let valid_point = self.point.is_none_or(|point| {
point
.iter()
.all(|v| v.is_finite() && (0.0..=1_000_000.0).contains(v))
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0 && (viewport || *v >= 0.0))
});
if !valid_delta
|| !valid_point
|| self.mount != 0
|| (if viewport {
self.mount == 0
} else {
self.mount != 0
})
|| self.press_point.is_some()
|| self.screen_position.is_some()
{
return Err("invalid page camera input");
}
if self.kind == "page-zoom"
if self.kind.ends_with("-zoom")
&& (self.point.is_none()
|| self
.delta