mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 03:17:43 +00:00
Keep transform preview geometry aligned during edits
This commit is contained in:
@@ -351,6 +351,24 @@ fn drag(h: &mut Harness, from: Point, to: Point) {
|
||||
frame(h, Vec::new());
|
||||
}
|
||||
|
||||
/// A handle's accessible location follows the box in the same frame as its painted preview.
|
||||
#[trial]
|
||||
fn a_dragged_corner_reports_its_current_location() {
|
||||
let mut h = harness(BoxState::from_rect(RECT), |config| config.rules = free_rules());
|
||||
let start = h.screen(Point::new(RECT.x1, RECT.y0));
|
||||
let end = start + Vec2::new(-40.0, 20.0);
|
||||
frame(&mut h, vec![pointer::moved(start)]);
|
||||
frame(&mut h, vec![pointer::press(start)]);
|
||||
frame(&mut h, vec![pointer::moved(end)]);
|
||||
let first_move_passes = h.fixture.passes();
|
||||
frame(&mut h, vec![pointer::moved(end + Vec2::new(-10.0, 5.0))]);
|
||||
assert!(h.fixture.passes() <= first_move_passes, "a continued drag needs no extra pass");
|
||||
let shown = h.host.borrow().shown.unwrap();
|
||||
let painted_corner = h.screen(shown.quad[1]);
|
||||
let accessible_corner = h.fixture.by_label("Top right corner").unwrap().rect.center();
|
||||
assert!((accessible_corner - painted_corner).length() < 0.5, "accessible {accessible_corner:?}, painted {painted_corner:?}");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn an_edge_takes_a_press_along_its_side_and_a_corner_wins_where_both_reach() {
|
||||
let mut h = harness(BoxState::from_rect(RECT), |config| config.rules = free_rules());
|
||||
|
||||
@@ -128,6 +128,12 @@ pub struct PreviewMesh {
|
||||
}
|
||||
|
||||
impl PreviewMesh {
|
||||
/// Clips the preview to a convex quadrilateral in document space.
|
||||
#[must_use]
|
||||
pub fn clipped_to_quad(self, quad: [Point; 4]) -> PreviewMesh {
|
||||
clip_to_quad(self, quad)
|
||||
}
|
||||
|
||||
/// The mesh clipped to a document of `canvas` pixels: triangles past its edges are cut in
|
||||
/// document space, also under a turned view.
|
||||
#[must_use]
|
||||
@@ -325,9 +331,18 @@ pub(super) fn front_vertices(h: &Homography, n: usize) -> Vec<bool> {
|
||||
/// `mesh` with every triangle cut to the document `canvas` (0, 0)–(width, height) in document
|
||||
/// space, so the cut follows a turned view.
|
||||
pub(super) fn clip_to_canvas(mesh: PreviewMesh, canvas: [u32; 2]) -> PreviewMesh {
|
||||
// pc: crates/ui-egui/src/tools/transform_tool/draw.rs:395 (`clip_to_canvas`).
|
||||
let size = (f64::from(canvas[0]), f64::from(canvas[1]));
|
||||
let inside = |p: &Point| p.x >= 0.0 && p.y >= 0.0 && p.x <= size.0 && p.y <= size.1;
|
||||
let (w, h) = (f64::from(canvas[0]), f64::from(canvas[1]));
|
||||
clip_to_quad(mesh, [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)])
|
||||
}
|
||||
|
||||
fn clip_to_quad(mesh: PreviewMesh, quad: [Point; 4]) -> PreviewMesh {
|
||||
let cross = |a: Point, b: Point, p: Point| (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
|
||||
let area: f64 = (0..4).map(|i| quad[i].x * quad[(i + 1) % 4].y - quad[(i + 1) % 4].x * quad[i].y).sum();
|
||||
if !area.is_finite() || area.abs() < 1e-12 || (0..4).any(|i| cross(quad[i], quad[(i + 1) % 4], quad[(i + 2) % 4]) * area < 0.0) {
|
||||
return PreviewMesh::default();
|
||||
}
|
||||
let distance = |edge: usize, p: Point| cross(quad[edge], quad[(edge + 1) % 4], p) * area.signum();
|
||||
let inside = |p: &Point| (0..4).all(|edge| distance(edge, *p) >= 0.0);
|
||||
if mesh.points.iter().all(inside) {
|
||||
return mesh;
|
||||
}
|
||||
@@ -344,14 +359,9 @@ pub(super) fn clip_to_canvas(mesh: PreviewMesh, canvas: [u32; 2]) -> PreviewMesh
|
||||
let mut out = PreviewMesh::default();
|
||||
for tri in mesh.indices.as_chunks::<3>().0 {
|
||||
let Some(mut poly) = tri.iter().map(|&k| vertex(k)).collect::<Option<Vec<_>>>() else { continue };
|
||||
// Sutherland–Hodgman against the four canvas edges (`dist` >= 0 is the canvas side).
|
||||
// Clip each triangle against the four edges, interpolating its texture coordinates.
|
||||
for edge in 0..4 {
|
||||
let dist = |v: &Vertex| match edge {
|
||||
0 => v.point.x,
|
||||
1 => size.0 - v.point.x,
|
||||
2 => v.point.y,
|
||||
_ => size.1 - v.point.y,
|
||||
};
|
||||
let dist = |v: &Vertex| distance(edge, v.point);
|
||||
let mut next = Vec::with_capacity(poly.len() + 2);
|
||||
for (k, a) in poly.iter().enumerate() {
|
||||
let Some(b) = poly.get((k + 1) % poly.len()) else { continue };
|
||||
|
||||
@@ -115,6 +115,9 @@ pub struct TransformPreview<'a> {
|
||||
/// The document's size in pixels: nothing is drawn past its edges.
|
||||
#[prop]
|
||||
clip: Option<[u32; 2]>,
|
||||
/// A convex quadrilateral in document space limiting the visible preview.
|
||||
#[prop]
|
||||
clip_quad: Option<[Point; 4]>,
|
||||
/// The monitor conversion of the displayed upload; the mip levels stay raw.
|
||||
#[prop]
|
||||
display: Option<&'a PreviewDisplay>,
|
||||
@@ -141,6 +144,7 @@ impl<'a> TransformPreview<'a> {
|
||||
opacity: 1.0,
|
||||
nearest: false,
|
||||
clip: None,
|
||||
clip_quad: None,
|
||||
display: None,
|
||||
styled: None,
|
||||
dragging: false,
|
||||
@@ -210,12 +214,12 @@ impl Component for TransformPreview<'_> {
|
||||
uv: corners.iter().map(|c| [c.2, c.3]).collect(),
|
||||
indices: vec![0, 1, 2, 0, 2, 3],
|
||||
};
|
||||
add_mesh(&painter, mesh, texture, Color32::from_gray(u8::MAX), self.clip, &view);
|
||||
add_mesh(&painter, mesh, texture, Color32::from_gray(u8::MAX), self.clip, self.clip_quad, &view);
|
||||
} else {
|
||||
let choice = PreviewTextures::choose(zoom, scale, self.nearest);
|
||||
let Some((texture, uv)) = self.textures.pick(&ctx, choice, self.display) else { return };
|
||||
let mesh = map.build(view.zoom * f64::from(device), uv);
|
||||
add_mesh(&painter, mesh, texture, tint, self.clip, &view);
|
||||
add_mesh(&painter, mesh, texture, tint, self.clip, self.clip_quad, &view);
|
||||
}
|
||||
if let Some(first) = first {
|
||||
space.paint_picture(&ctx, first.take_after(&ctx));
|
||||
@@ -232,11 +236,23 @@ impl Component for TransformPreview<'_> {
|
||||
}
|
||||
|
||||
/// `mesh` clipped to the canvas in document space, mapped through `view` and added to the painter.
|
||||
fn add_mesh(painter: &ContentPainterCx<'_>, mesh: PreviewMesh, texture: TextureId, tint: Color32, canvas: Option<[u32; 2]>, view: &CanvasView) {
|
||||
fn add_mesh(
|
||||
painter: &ContentPainterCx<'_>,
|
||||
mesh: PreviewMesh,
|
||||
texture: TextureId,
|
||||
tint: Color32,
|
||||
canvas: Option<[u32; 2]>,
|
||||
quad: Option<[Point; 4]>,
|
||||
view: &CanvasView,
|
||||
) {
|
||||
let mesh = match canvas {
|
||||
Some(canvas) => clip_to_canvas(mesh, canvas),
|
||||
None => mesh,
|
||||
};
|
||||
let mesh = match quad {
|
||||
Some(quad) => mesh.clipped_to_quad(quad),
|
||||
None => mesh,
|
||||
};
|
||||
let mut out = Mesh::with_texture(texture);
|
||||
out.vertices =
|
||||
mesh.points.iter().zip(&mesh.uv).map(|(p, uv)| Vertex { pos: view.to_screen(*p), uv: egui::pos2(uv[0], uv[1]), color: tint }).collect();
|
||||
|
||||
@@ -66,6 +66,18 @@ fn unit_quad() -> [Point; 4] {
|
||||
[pt(0.0, 0.0), pt(100.0, 0.0), pt(100.0, 100.0), pt(0.0, 100.0)]
|
||||
}
|
||||
|
||||
/// A clipped preview retains texture coordinates where its frame cuts the image.
|
||||
#[trial]
|
||||
fn a_preview_clipped_to_a_frame_keeps_its_texture_coordinates() {
|
||||
let quad = [pt(25.0, 20.0), pt(75.0, 20.0), pt(75.0, 80.0), pt(25.0, 80.0)];
|
||||
let mesh = PreviewMap::quad(unit_quad()).build(1.0, [1.0, 1.0]).clipped_to_quad(quad);
|
||||
assert!(!mesh.indices.is_empty());
|
||||
for (p, uv) in mesh.points.iter().zip(&mesh.uv) {
|
||||
assert!(p.x >= 24.999 && p.x <= 75.001 && p.y >= 19.999 && p.y <= 80.001, "{p:?}");
|
||||
assert!((f64::from(uv[0]) - p.x / 100.0).abs() < 1e-5 && (f64::from(uv[1]) - p.y / 100.0).abs() < 1e-5);
|
||||
}
|
||||
}
|
||||
|
||||
// A Distort dragged past the horizon leaves the cells with a corner on the far side out of the mesh; the cells in
|
||||
// front stay.
|
||||
#[trial]
|
||||
|
||||
@@ -537,6 +537,7 @@ pub(crate) trait ErasedPass<'a> {
|
||||
fn padding(&self, rect: Rect) -> craft_behavior::Insets;
|
||||
/// Step 7: the component's parts, then the shape's.
|
||||
fn parts(&mut self, rect: Rect, flow: Flow, content_rect: Rect, parts: &mut PartsStep, input: &MeasureIn<'_>, rtl: bool);
|
||||
fn parts_value_changed(&self) -> bool;
|
||||
/// Step 8b for a text part.
|
||||
fn text(&mut self, ui: &mut Ui, step: &mut super::text::TextStep, keys: focus::KeyUse, rtl: bool, ink: egui::Color32, underline: f32);
|
||||
/// Step 8b for an editor part.
|
||||
@@ -1157,6 +1158,17 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option<ShowAt>, h
|
||||
e.settle();
|
||||
let edit = e.settle_values();
|
||||
steps::rerun_after_edit(e, style, edit, &MeasureIn { ui: &*ui, env: p.env, proposal: Proposal::Ideal, room: p.room }, resolved, leaf);
|
||||
// Sensing used the parts before the edit. Report their new bounds alongside the value painted in this pass.
|
||||
if !inert && declares_parts && e.parts_value_changed() {
|
||||
let mut current = PartsStep { decls: Default::default(), rovings: Vec::new(), scrolls: Vec::new(), text: super::text::TextStep::default() };
|
||||
let input = MeasureIn { ui: &*ui, env, proposal: Proposal::Ideal, room: p.room };
|
||||
e.parts(rect, flow, content_rect, &mut current, &input, rtl);
|
||||
for decl in current.decls.parts() {
|
||||
if let Some(result) = e.core().results.get_mut(&(decl.key, decl.index)) {
|
||||
result.rect = decl.shape.bounds();
|
||||
}
|
||||
}
|
||||
}
|
||||
// 16 report, then the tooltip.
|
||||
p.trace.mark(Step::Report);
|
||||
let message = steps::report(
|
||||
|
||||
@@ -157,7 +157,7 @@ impl<C: Component> Erased for Typed<'_, '_, C> {
|
||||
let applied = if events.iter().any(|event| matches!(event, EditEvent::Cancel { before: Some(_), .. })) { 0 } else { events.len() };
|
||||
let mut cx = Cx::<C> { core, style, shown: self.shown.take(), mixed: self.mixed, events, applied, validity: Validity::Ok };
|
||||
let mut comp = self.comp.take();
|
||||
let real = rest(&mut TypedPass { comp: &mut comp, hooks: &mut *self.hooks, cx: &mut cx });
|
||||
let real = rest(&mut TypedPass { comp: &mut comp, hooks: &mut *self.hooks, cx: &mut cx, parts_value: None });
|
||||
let id = cx.core.id;
|
||||
let output = comp.finish(cx);
|
||||
debug_assert!(!real || crate::contract::Outcome::response(&output).id == id, "an output's Response is the component's own");
|
||||
@@ -226,6 +226,7 @@ struct TypedPass<'r, 'a, C: Component> {
|
||||
comp: &'r mut C,
|
||||
hooks: &'r mut dyn ShapeHooks<C>,
|
||||
cx: &'r mut Cx<'a, C>,
|
||||
parts_value: Option<Arc<ValueOf<C>>>,
|
||||
}
|
||||
|
||||
impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> {
|
||||
@@ -275,6 +276,7 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> {
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, flow: Flow, content_rect: Rect, parts: &mut PartsStep, input: &MeasureIn<'_>, rtl: bool) {
|
||||
self.parts_value = self.cx.shown.clone();
|
||||
let id = self.cx.core.id;
|
||||
let last = self.cx.core.memory.shown::<steps::Shown<ValueOf<C>>>(id).state.last_state;
|
||||
let measure = steps::measure_cx::<C>(input, self.cx.style, self.cx.core.resolved, self.cx.shown.as_deref());
|
||||
@@ -296,6 +298,10 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> {
|
||||
self.hooks.parts(self.comp, rect, &mut pcx);
|
||||
}
|
||||
|
||||
fn parts_value_changed(&self) -> bool {
|
||||
self.parts_value.as_deref() != self.cx.shown.as_deref()
|
||||
}
|
||||
|
||||
fn text(&mut self, ui: &mut Ui, step: &mut crate::contract::text::TextStep, keys: focus::KeyUse, rtl: bool, ink: egui::Color32, underline: f32) {
|
||||
crate::contract::text::run(self.cx, ui, step, keys, rtl, ink, underline);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user