Merge pull request #837 from vangel76/feat/warp-toolbar-805

Warp tool bar in the top bar: gizmo modes, place on surface, snapping, mirrors and resets
This commit is contained in:
Chris Hassebrook authored and GitHub committed 2026-11-26 01:00:38 -05:00
commit 6b01f32eab
17 files changed
+892 -101

No files matched your search

+28 -15
View File
@@ -1,7 +1,7 @@
//! Warp projections: the frame a new warp starts from, and Reset frame, which puts a warp's frame and corners back there
use serde_json::Value;
use texturecraft_core::{Decal, Projection};
use texturecraft_core::{Decal, Projection, Projector};
use texturecraft_geom::Mesh;
use crate::commands::{CommandSpec, bad, has_layer};
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset frame",
[],
None,
"{layer? | effect?: content or mask fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)",
"{layer? | effect?: content or mask fill effect id, keepCorners?: bool} — refit the warp's frame around the mesh. With `keepCorners: true`, also reset the projector's rotation and scale and keep the corners; otherwise reset the corners. Projection Depth, crop, and culling stay",
has_layer,
reset_frame
)]
@@ -44,26 +44,39 @@ pub(crate) fn fitted_frame(mesh: &Mesh) -> Decal {
/// A fitted frame's smallest side, relative to the mesh diagonal (a flat mesh still gets a frame)
const SMALLEST_SIDE: f32 = 1e-3;
fn reset_frame(s: &mut Session, p: &Value) -> Result<Value> {
let target = fill_target(s, p, RESET_FRAME)?;
let fitted = fitted_frame(&s.mesh);
let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else {
fn reset_frame(session: &mut Session, params: &Value) -> Result<Value> {
let target = fill_target(session, params, RESET_FRAME)?;
let keep_corners = match params.get("keepCorners") {
Some(value) => value.as_bool().ok_or_else(|| bad(RESET_FRAME, "`keepCorners` must be a boolean"))?,
None => false,
};
let fitted = fitted_frame(&session.mesh);
let (projection, _) = placement_mut(session, target)?;
let mut reset = projection.clone();
let Projection::Warp { frame, corners, projector, .. } = &mut reset else {
return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection"));
};
// A frame already fitted with unpulled corners adds no undo step
if *frame == fitted && *corners == Projection::FRAME_CORNERS {
*frame = fitted;
if keep_corners {
// Older warps may still carry a transform separate from the frame
let defaults = Projector::default();
projector.rotation = defaults.rotation;
projector.scale = defaults.scale;
} else {
*corners = Projection::FRAME_CORNERS;
}
// An unchanged projection adds no undo step
if reset == *projection {
return Ok(Value::Null);
}
s.edit("Reset frame", |s| {
let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else {
return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection"));
};
*frame = fitted;
*corners = Projection::FRAME_CORNERS;
let label = if keep_corners { "Reset warp transform" } else { "Reset frame" };
session.edit(label, |session| {
*placement_mut(session, target)?.0 = reset;
Ok(())
})?;
Ok(Value::Null)
}
@@ -337,6 +337,67 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame()
assert!(execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).is_err(), "only a warp has a frame to reset");
}
/// Restore the global transformation refits a warp's frame and keeps its pulled corners, in one undo step, none when the frame is fitted
#[test]
fn a_warps_frame_resets_apart_from_its_corners() {
let mut s = session();
let layer = checker_fill(&mut s);
set(&mut s, layer, json!({"projection": "warp"}));
let Projection::Warp { frame: fitted, .. } = projection(&s, layer) else { panic!("a warp") };
let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]];
set(&mut s, layer, json!({"warpCorners": pulled}));
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).unwrap();
let steps = s.history_labels().len();
execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap();
let Projection::Warp { frame, corners, .. } = projection(&s, layer) else { panic!("a warp") };
assert_eq!(frame, fitted, "the frame goes back around the mesh");
assert_eq!(corners, pulled, "the pulled corners stay");
assert_eq!(s.history_labels().len(), steps + 1);
execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap();
assert_eq!(s.history_labels().len(), steps + 1, "a fitted frame adds no undo step");
}
#[test]
fn a_warps_global_reset_clears_the_projector_transform() {
let mut session = session();
let layer = checker_fill(&mut session);
let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]];
set(&mut session, layer, json!({"projection": "warp", "warpCorners": pulled, "depthCulling": false, "projectionDepth": 0.2}));
let fitted = projection(&session, layer);
set(&mut session, layer, json!({"projectorRotation": [12, 0, 20], "projectorScale": [2, 2, 1]}));
let edited = projection(&session, layer);
let steps = session.history_labels().len();
execute(&mut session, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap();
assert_eq!(projection(&session, layer), fitted, "restore the displayed frame and keep its corners and projection settings");
assert_eq!(session.history_labels().len(), steps + 1);
session.undo().unwrap();
assert_eq!(projection(&session, layer), edited);
}
#[test]
fn invalid_keep_corners_cannot_reset_the_warp() {
let mut session = session();
let layer = checker_fill(&mut session);
let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]];
set(&mut session, layer, json!({"projection": "warp", "warpCorners": pulled}));
let before = projection(&session, layer);
let steps = session.history_labels().len();
let result = execute(&mut session, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": "true"}));
assert!(result.is_err());
assert_eq!(projection(&session, layer), before);
assert_eq!(session.history_labels().len(), steps);
}
/// Depth culling keeps planar and warp projections off surfaces hidden behind others from the projector; new ones start with it on, older saves without it
#[test]
fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() {
+213 -69
View File
@@ -6,7 +6,7 @@ use texturecraft_engine::compose::axis_frame::{placed_from_axis, placing_moves_p
use texturecraft_engine::compose::frame_placement::folded;
use texturecraft_engine::compose::pattern::{decal_axes, decal_corners};
use texturecraft_engine::core::{Decal, EffectKind, Fill, LayerId, LayerKind, Projection, Source};
use texturecraft_engine::geom::glam::Vec3;
use texturecraft_engine::geom::glam::{Vec2, Vec3};
use crate::TextureCraftApp;
use crate::projection_gizmo::{Gizmo, dragging};
@@ -14,8 +14,10 @@ use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH,
use crate::viewport::{project, view_ray};
mod frame_grab;
pub(crate) mod warp_toolbar;
pub(crate) use frame_grab::FrameGrab;
use warp_toolbar::{GizmoMode, GizmoSpace, WarpToolbarSettings, to_step};
/// The selected fill's frame as the 3D view shows it
#[derive(Clone, Copy, Debug)]
@@ -35,11 +37,16 @@ pub(crate) struct FrameGizmo {
pub arrows: [Option<Pos2>; 3],
/// On screen, the turn ring round the centre in the frame's plane (None when it is edge on)
pub ring: Option<[Pos2; TURN_RING_POINTS]>,
/// A warp's tool bar settings: which handles show, their size and snapping, and the space the arrows move in
pub tools: Option<WarpToolbarSettings>,
/// In the world: the frame's centre, and its across, up and out directions
origin: Vec3,
axes: [Vec3; 3],
/// Screen movement per world unit along each direction at the centre
steps: [Option<egui::Vec2>; 3],
/// The directions the arrows move along (the frame's own, or the world's in World space) and their screen movement per world unit
move_axes: [Vec3; 3],
move_steps: [Option<egui::Vec2>; 3],
}
/// Screen length of the axis arrows, and their heads (points): long enough to grab each one apart from the others
@@ -74,33 +81,7 @@ fn placeable_projection<'a>(projection: &'a Projection, sources: impl Iterator<I
impl FrameGizmo {
/// The frame of the selected fill layer, or of the selected mask fill effect, with a planar or warp projection
pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option<FrameGizmo> {
use texturecraft_engine::StackTarget;
if app.ui.mode != crate::state::Mode::Painting {
return None;
}
let layers = &app.session.doc.project;
let selected = app.session.selected_layer()?;
let (layer, effect, projection) = match app.session.target {
StackTarget::Content => {
let layer = layers.content_layer(selected)?;
let LayerKind::Fill(Fill { projection, sources, .. }) = &layer.kind else { return None };
(layer.id, None, placeable_projection(projection, sources.values())?)
}
StackTarget::Effect(effect) => {
// An instance can show a frame from its inherited mask
let owner = layers.mask_owner(selected);
let mask = layers.layer(owner).ok()?.mask.as_ref()?;
let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?;
let EffectKind::Fill { projection, source, .. } = &mask_effect.kind else { return None };
(owner, Some(effect), placeable_projection(projection, std::iter::once(source))?)
}
StackTarget::Mask => return None,
};
let (layer, effect, projection) = selected_fill_projection(app)?;
let placed = placed_from_axis(projection, app.viewport_mesh_bounds.get(&app.session.mesh));
// Match the panel by folding the projector transform into the frame first
@@ -125,16 +106,35 @@ impl FrameGizmo {
let sides = [0, 1, 2, 3].map(|side| corners[side].lerp(corners[(side + 1) % 4], 0.5));
let center = project(app, rect, origin)?;
let tools = warp.map(|_| app.ui.warp_toolbar);
let manipulator_scale = tools.map_or(1.0, |tools| tools.gizmo_scale());
let show_move = tools.is_none_or(|tools| tools.mode == GizmoMode::Move);
let show_ring = tools.is_none_or(|tools| tools.mode == GizmoMode::Rotate);
// Arrows use the same screen steps as the drag
let reach = decal.size[0].max(decal.size[1]);
let axes = [across, up, out];
let steps = axes.map(|axis| Some((project(app, rect, origin + axis * reach)? - center) / reach.max(f32::MIN_POSITIVE)));
let arrows = steps.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW));
let step_along = |axis: Vec3| Some((project(app, rect, origin + axis * reach)? - center) / reach.max(f32::MIN_POSITIVE));
let steps = axes.map(step_along);
let (move_axes, move_steps) = if show_move && tools.is_some_and(|tools| tools.space == GizmoSpace::World) {
let world_axes = [Vec3::X, Vec3::Y, Vec3::Z];
(world_axes, world_axes.map(step_along))
} else {
(axes, steps)
};
let arrows = if show_move {
move_steps
.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW * manipulator_scale))
} else {
[None; 3]
};
// The ring can still project when an arrow's endpoint is behind the camera
let ring = if ring_open(app, rect, center, out) { turn_ring(app, rect, center, origin, across, up) } else { None };
let ring_radius = TURN_RING * manipulator_scale;
let ring =
if show_ring && ring_open(app, rect, center, out, ring_radius) { turn_ring(app, rect, center, origin, across, up, ring_radius) } else { None };
Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, origin, axes, steps })
Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, tools, origin, axes, steps, move_axes, move_steps })
}
/// The frame's offset after sliding it across its plane by screen movement `delta` (None when the frame is edge-on)
@@ -143,6 +143,16 @@ impl FrameGizmo {
Some(self.slid(across, up))
}
/// The tool bar's grid step and angle step (0: no snapping) while a drag snaps
fn snap_steps(&self, snapping: bool) -> (f32, f32) {
self.tools.filter(|_| snapping).map_or((0.0, 0.0), |tools| (tools.grid_step(), tools.angle_step()))
}
/// Whether the tool bar's mode offers `grab` (a planar's frame, with no tool bar, offers every handle but Place on surface's)
fn offers(&self, grab: FrameGrab) -> bool {
self.tools.map_or(grab != FrameGrab::Place, |tools| grab.offered_in(tools.mode))
}
/// Where screen point `p` meets the frame's plane, across and up in frame sizes from its centre
fn on_plane(&self, app: &TextureCraftApp, rect: Rect, p: Pos2) -> Option<[f32; 2]> {
let ray = view_ray(app, rect, p);
@@ -164,6 +174,36 @@ impl FrameGizmo {
}
}
/// The selected fill layer or mask effect and its projection, if eligible to show a frame in Painting mode
fn selected_fill_projection(app: &TextureCraftApp) -> Option<(LayerId, Option<LayerId>, &Projection)> {
use texturecraft_engine::StackTarget;
if app.ui.mode != crate::state::Mode::Painting {
return None;
}
let layers = &app.session.doc.project;
let selected = app.session.selected_layer()?;
match app.session.target {
StackTarget::Content => {
let layer = layers.content_layer(selected)?;
let LayerKind::Fill(Fill { projection, sources, .. }) = &layer.kind else { return None };
Some((layer.id, None, placeable_projection(projection, sources.values())?))
}
StackTarget::Effect(effect) => {
// Only the selected layer's effective mask may supply a frame, including an instance's inherited mask
let owner = layers.mask_owner(selected);
let mask = layers.layer(owner).ok()?.mask.as_ref()?;
let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?;
let EffectKind::Fill { projection, source, .. } = &mask_effect.kind else { return None };
Some((owner, Some(effect), placeable_projection(projection, std::iter::once(source))?))
}
StackTarget::Mask => None,
}
}
/// Half a turn in degrees: a ring drag's sweep is kept within one either way
const HALF_TURN: f32 = 180.0;
@@ -176,16 +216,13 @@ pub(crate) const EDGE_ON_FACING: f32 = 1e-4;
/// The smallest length a direction spans on screen to point somewhere (points): shorter, it points at the camera
pub(crate) const MIN_SCREEN_SPAN: f32 = 1.0;
/// The smallest cosine between the view ray and a turn ring's axis for the ring to show: flatter, its half height on screen is under its drawn line's width, it reads as a line and a drag along it turns half a turn at once across the centre
const MIN_RING_FACING: f32 = (SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) / TURN_RING;
/// Whether a turn ring round `axis`, centred on screen at `center`, is seen open enough to show and grab
pub(crate) fn ring_open(app: &TextureCraftApp, rect: Rect, center: Pos2, axis: Vec3) -> bool {
view_ray(app, rect, center).dir.dot(axis).abs() >= MIN_RING_FACING
/// A ring seen edge-on reads as a line until its foreshortened radius clears its stroke.
pub(crate) fn ring_open(app: &TextureCraftApp, rect: Rect, center: Pos2, axis: Vec3, radius_points: f32) -> bool {
view_ray(app, rect, center).dir.dot(axis).abs() >= (SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) / radius_points
}
/// Project a circle in the frame's plane whose longest screen reach is `TURN_RING` points.
fn turn_ring(app: &TextureCraftApp, rect: Rect, center: Pos2, origin: Vec3, across: Vec3, up: Vec3) -> Option<[Pos2; TURN_RING_POINTS]> {
/// Project a circle in the frame's plane with the requested screen reach in points
fn turn_ring(app: &TextureCraftApp, rect: Rect, center: Pos2, origin: Vec3, across: Vec3, up: Vec3, radius_points: f32) -> Option<[Pos2; TURN_RING_POINTS]> {
const RING_SEGMENTS: usize = TURN_RING_POINTS - 1;
let view_projection = app.session.camera.view_proj(rect.width() / rect.height().max(1.0));
@@ -206,13 +243,13 @@ fn turn_ring(app: &TextureCraftApp, rect: Rect, center: Pos2, origin: Vec3, acro
across_step * cos + up_step * sin
});
// Solve radius * length(xy) / (1 + radius * z) <= TURN_RING for every sample
let limiting_growth = ring_steps.iter().map(|step| step.truncate().length() - TURN_RING * step.z).fold(0.0, f32::max);
// Solve radius * length(xy) / (1 + radius * z) <= radius_points for every sample
let limiting_growth = ring_steps.iter().map(|step| step.truncate().length() - radius_points * step.z).fold(0.0, f32::max);
if !limiting_growth.is_finite() || limiting_growth <= f32::EPSILON {
return None;
}
let radius = TURN_RING / limiting_growth;
let radius = radius_points / limiting_growth;
let mut ring = [center; TURN_RING_POINTS];
for (point, step) in ring.iter_mut().zip(ring_steps) {
let depth = 1.0 + radius * step.z;
@@ -222,6 +259,7 @@ fn turn_ring(app: &TextureCraftApp, rect: Rect, center: Pos2, origin: Vec3, acro
*point += vec2(step.x, step.y) * (radius / depth);
}
ring[RING_SEGMENTS] = ring[0];
Some(ring)
@@ -255,6 +293,7 @@ pub(crate) fn nearest<T: Copy>(handles: impl IntoIterator<Item = (T, f32)>) -> O
best = Some((handle, distance));
}
}
best.map(|(handle, _)| handle)
}
@@ -273,37 +312,54 @@ impl Gizmo for FrameGizmo {
/// The handle under screen point `p`: the nearest one within reach, so a small frame's corners stay grabbable beside its arrows
fn grab(&self, at: Pos2) -> Option<FrameGrab> {
let mut handles = vec![(FrameGrab::Slide, center_distance(self.center, at))];
handles.extend((0..3).filter_map(|axis| Some((FrameGrab::Axis(axis), arrow_distance(at, self.center, self.arrows[axis]?)))));
let near = |points: [Pos2; 4], grab: fn(usize) -> FrameGrab| (0..4).map(move |index| (grab(index), points[index].distance(at)));
match self.warp {
Some(_) => handles.extend(near(self.corners, FrameGrab::Corner)),
None => handles.extend(near(self.corners, |_| FrameGrab::Scale)),
}
handles.extend(near(self.sides, FrameGrab::Side));
if let Some(ring) = &self.ring {
handles.push((FrameGrab::Turn, ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min)));
}
nearest(handles)
let slide = self.offers(FrameGrab::Slide).then(|| (FrameGrab::Slide, center_distance(self.center, at)));
let arrows = self.arrows.into_iter().enumerate().filter_map(|(axis, tip)| Some((FrameGrab::Axis(axis), arrow_distance(at, self.center, tip?))));
let corners = self.corners.into_iter().enumerate().map(|(index, corner)| {
let grab = if self.warp.is_some() { FrameGrab::Corner(index) } else { FrameGrab::Scale };
(grab, corner.distance(at))
});
let sides = self.sides.into_iter().enumerate().filter_map(|(index, side)| {
let grab = FrameGrab::Side(index);
self.offers(grab).then(|| (grab, side.distance(at)))
});
let turn = self.ring.as_ref().map(|ring| {
let distance = ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min);
(FrameGrab::Turn, distance)
});
// Place on surface takes any press the handles do not: just within reach, so a nearer corner wins
let place = self.offers(FrameGrab::Place).then_some((FrameGrab::Place, GRAB));
nearest(slide.into_iter().chain(arrows).chain(corners).chain(sides).chain(turn).chain(place))
}
fn same_projection(&self, other: &FrameGizmo) -> bool {
self.layer == other.layer && self.effect == other.effect
self.layer == other.layer && self.effect == other.effect && self.warp.is_some() == other.warp.is_some()
}
/// The command and params a drag of `grab` from `from` to `to` runs
fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: FrameGrab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)> {
self.edit_with_snap(app, rect, grab, from, to, false)
}
/// As [`Gizmo::edit`]; with `snapping` a warp's moves and turns jump by the tool bar's grid and angle steps
fn edit_with_snap(&self, app: &TextureCraftApp, rect: Rect, grab: FrameGrab, from: Pos2, to: Pos2, snapping: bool) -> Option<(&'static str, Value)> {
let delta = to - from;
let center = self.center;
let (grid_step, angle_step) = self.snap_steps(snapping);
let world = self.tools.is_some_and(|tools| tools.space == GizmoSpace::World);
let mut params = match grab {
FrameGrab::Slide => json!({"offset": self.slid_on_screen(delta)?}),
FrameGrab::Slide => {
let [across, up] = solve(self.steps[0]?, self.steps[1]?, delta)?;
json!({"offset": self.slid(to_step(across, grid_step), to_step(up, grid_step))})
}
FrameGrab::Axis(axis) => {
let step = (*self.steps.get(axis)?)?;
let distance = delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE);
let step = (*self.move_steps.get(axis)?)?;
let distance_world = to_step(delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE), grid_step);
match axis {
0 => json!({"offset": self.slid(distance, 0.0)}),
1 => json!({"offset": self.slid(0.0, distance)}),
_ => json!({"position": (self.origin + self.axes[2] * distance).to_array(), "normal": self.axes[2].to_array()}),
0 if !world => json!({"offset": self.slid(distance_world, 0.0)}),
1 if !world => json!({"offset": self.slid(0.0, distance_world)}),
_ => json!({"position": (self.origin + self.move_axes[axis] * distance_world).to_array(), "normal": self.axes[2].to_array()}),
}
}
FrameGrab::Scale => {
@@ -317,12 +373,25 @@ impl Gizmo for FrameGizmo {
size[1 - side % 2] *= stretch;
json!({"size": size})
}
FrameGrab::Place => {
let on_view = to - rect.min;
let hit = app.session.pick(Vec2::new(on_view.x, on_view.y), app.session.viewport)?;
let project = &app.session.doc.project;
let (owner_set, _, _) = project.locate(self.layer)?;
// A world-space placement must belong to the edited fill's texture set
if hit.material != project.texture_set(owner_set).ok()?.material {
return None;
}
json!({"position": hit.pos.to_array(), "normal": hit.nrm.to_array()})
}
FrameGrab::Turn => {
// Measure the turn in the frame's own plane so a tilted frame follows the pointer
let angle = |p: Pos2| self.on_plane(app, rect, p).map(|[across, up]| (up * self.decal.size[1]).atan2(across * self.decal.size[0]).to_degrees());
let swept = angle(to)? - angle(from)?;
let swept = (swept + HALF_TURN).rem_euclid(2.0 * HALF_TURN) - HALF_TURN;
json!({"rotation": self.decal.rotation + swept})
json!({"rotation": self.decal.rotation + to_step(swept, angle_step)})
}
FrameGrab::Corner(corner) => {
let mut corners = self.warp?;
@@ -332,10 +401,12 @@ impl Gizmo for FrameGizmo {
json!({"warpCorners": corners})
}
};
params["layer"] = json!(self.layer.0);
if let Some(effect) = self.effect {
params["effect"] = json!(effect.0);
}
let command = if matches!(grab, FrameGrab::Corner(_)) { "layer.fill.projection" } else { "layer.decal.set" };
Some((command, params))
}
@@ -354,14 +425,16 @@ pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) {
let lit = |grab: FrameGrab| active == Some(grab) || (active.is_none() && hovered == Some(grab));
let dot_fill = |grab: FrameGrab| if lit(grab) { tokens.viewport_accent } else { Color32::WHITE };
let mut outline = gizmo.corners.to_vec();
outline.push(gizmo.corners[0]);
let [first, second, third, fourth] = gizmo.corners;
let outline = [first, second, third, fourth, first];
dashed_outline(&painter, &outline);
if let Some(ring) = &gizmo.ring {
let color = if lit(FrameGrab::Turn) { tokens.viewport_accent } else { AXIS_COLORS[2] };
painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO)));
painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH, color)));
}
match gizmo.warp {
Some(_) => {
for (index, corner) in gizmo.corners.into_iter().enumerate() {
@@ -374,12 +447,15 @@ pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) {
}
}
}
for (index, side) in gizmo.sides.into_iter().enumerate() {
for (index, side) in gizmo.sides.into_iter().enumerate().filter(|(index, _)| gizmo.offers(FrameGrab::Side(*index))) {
handle_dot(&painter, side, SIDE_DOT, dot_fill(FrameGrab::Side(index)));
}
let arrow_color = |axis: usize| if lit(FrameGrab::Axis(axis)) { tokens.viewport_accent } else { AXIS_COLORS[axis] };
move_handles(&painter, gizmo.center, gizmo.arrows, arrow_color, dot_fill(FrameGrab::Slide));
if gizmo.offers(FrameGrab::Slide) {
move_handles(&painter, gizmo.center, gizmo.arrows, arrow_color, dot_fill(FrameGrab::Slide));
}
}
/// The centre square (filled `square`) with its X/Y/Z arrows to `arrows`, coloured by `arrow_color`; shafts and heads over a dark halo like the symmetry manipulator's
@@ -452,6 +528,12 @@ pub(crate) mod tests {
harness
}
/// A warp's gizmo in `mode`, as the tool bar's buttons set it (a planar's has no modes)
pub(crate) fn show_handles(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, mode: GizmoMode) {
harness.state_mut().ui.warp_toolbar.mode = mode;
harness.run_steps(2);
}
/// The ball with a selected fill layer projecting `projection`
pub(crate) fn fill_app(projection: &str) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) {
fill_app_with(json!({"projection": projection}))
@@ -548,7 +630,7 @@ pub(crate) mod tests {
["X", "Y", "Z"].map(|tag| harness.get_by_label(&format!("{row} {tag}")).accesskit_node().numeric_value().unwrap() as f32)
}
fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> FrameGizmo {
pub(crate) fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> FrameGizmo {
FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap()
}
@@ -674,6 +756,7 @@ pub(crate) mod tests {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for kind in ["warp", "planar"] {
let (mut harness, _) = fill_app(kind);
show_handles(&mut harness, GizmoMode::Rotate);
let start = gizmo(&harness);
let ring = start.ring.unwrap_or_else(|| panic!("{kind}: a frame facing the camera shows its ring"));
let on_ring = *ring
@@ -696,6 +779,7 @@ pub(crate) mod tests {
}
let (mut harness, layer) = fill_app("warp");
show_handles(&mut harness, GizmoMode::Scale);
let warp = gizmo(&harness);
assert_eq!(warp.grab(warp.sides[1]), Some(FrameGrab::Side(1)));
@@ -717,6 +801,7 @@ pub(crate) mod tests {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for kind in ["planar", "warp"] {
let (mut harness, _) = fill_app(kind);
show_handles(&mut harness, GizmoMode::Rotate);
let mut foreshortened_shown = false;
// A distant view isolates the foreshortening
@@ -743,6 +828,26 @@ pub(crate) mod tests {
}
}
#[test]
fn an_oblique_warp_ring_opens_when_its_scaled_height_clears_the_stroke() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, _) = fill_app("warp");
show_handles(&mut harness, GizmoMode::Rotate);
let camera = &mut harness.state_mut().session.camera;
camera.ortho = true;
camera.set_angles(87.0_f32.to_radians(), 0.0);
let base_size = harness.state().ui.warp_toolbar.manipulator_size;
harness.state_mut().ui.warp_toolbar.manipulator_size = base_size * 0.5;
let small = gizmo(&harness);
harness.state_mut().ui.warp_toolbar.manipulator_size = base_size * 2.0;
let large = gizmo(&harness);
assert!(small.ring.is_none(), "a ring narrower than its stroke stays hidden");
let ring = large.ring.expect("the enlarged ring clears its stroke at the same angle");
assert!(ring.iter().any(|point| large.grab(*point) == Some(FrameGrab::Turn)));
}
#[test]
fn the_ring_keeps_its_screen_size_when_the_oblique_frame_is_turning_near_the_camera() {
const FRAME_SIDE: f32 = 4.0;
@@ -756,6 +861,13 @@ pub(crate) mod tests {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for kind in ["planar", "warp"] {
let (mut harness, layer) = fill_app(kind);
show_handles(&mut harness, GizmoMode::Rotate);
let expected_radius = if kind == "warp" {
harness.state_mut().ui.warp_toolbar.manipulator_size *= 2.0;
TURN_RING * 2.0
} else {
TURN_RING
};
let camera = &mut harness.state_mut().session.camera;
camera.distance = CAMERA_DISTANCE;
camera.set_angles(ORBIT_DEGREES.to_radians(), 0.0);
@@ -771,7 +883,7 @@ pub(crate) mod tests {
let reach = ring.iter().map(|point| point.distance(shown.center)).fold(0.0, f32::max);
assert!(
(TURN_RING * MIN_RING_SHARE..=TURN_RING * MAX_RING_SHARE).contains(&reach),
(expected_radius * MIN_RING_SHARE..=expected_radius * MAX_RING_SHARE).contains(&reach),
"{kind} turned {rotation_degrees} degrees: the ring reaches {reach} points"
);
}
@@ -855,6 +967,38 @@ pub(crate) mod tests {
harness.run_steps(2);
}
#[test]
fn a_place_drag_ends_if_the_project_or_projection_is_replaced() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for replace_project in [true, false] {
let (mut harness, layer) = fill_app("warp");
show_handles(&mut harness, GizmoMode::PlaceOnSurface);
let center = gizmo(&harness).center;
let held = center + vec2(24.0, 8.0);
press_and_move(&mut harness, center, held, Modifiers::NONE);
let start = std::sync::Arc::downgrade(&dragging::<FrameGizmo>(&harness.ctx).unwrap().start);
let next_kind = if replace_project {
harness.state_mut().run("project.new", json!({"mesh": "sphere", "resolution": 128})).unwrap();
let new_layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap();
assert_eq!(new_layer["layer"], layer.0, "the new project reuses the local layer ID");
"warp"
} else {
"planar"
};
harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": next_kind})).unwrap();
let before = projection(&harness, layer);
let steps = harness.state().session.history_labels().len();
harness.event(egui::Event::PointerMoved(held + vec2(8.0, 8.0)));
harness.run_steps(2);
assert_eq!(projection(&harness, layer), before, "the old drag must not move the replacement {next_kind}");
assert_eq!(harness.state().session.history_labels().len(), steps);
assert!(start.upgrade().is_none(), "release the captured geometry while the pointer is still held");
}
}
/// A drag whose first edit changes nothing (its arrow pulled further past the offset limit) makes no undo step, so its later edits make the drag's own step instead of joining the edit before it
#[test]
fn a_drag_that_first_changes_nothing_keeps_its_own_undo_step() {
@@ -1,3 +1,5 @@
use super::warp_toolbar::GizmoMode;
/// What a drag on the frame does
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum FrameGrab {
@@ -13,15 +15,29 @@ pub(crate) enum FrameGrab {
Corner(usize),
/// The ring: turn it round its normal
Turn,
/// Place on surface: anywhere over the model puts the frame where the pointer touches it
Place,
}
impl FrameGrab {
/// Whether a warp's gizmo in `mode` offers this handle: its corners stay in every mode
pub(super) fn offered_in(self, mode: GizmoMode) -> bool {
match self {
FrameGrab::Slide | FrameGrab::Axis(_) => mode == GizmoMode::Move,
FrameGrab::Turn => mode == GizmoMode::Rotate,
FrameGrab::Side(_) => mode == GizmoMode::Scale,
FrameGrab::Place => mode == GizmoMode::PlaceOnSurface,
FrameGrab::Scale | FrameGrab::Corner(_) => true,
}
}
pub(super) fn cursor(self, dragging: bool) -> egui::CursorIcon {
match self {
FrameGrab::Slide if dragging => egui::CursorIcon::Grabbing,
FrameGrab::Slide => egui::CursorIcon::Grab,
FrameGrab::Axis(_) | FrameGrab::Corner(_) | FrameGrab::Turn => egui::CursorIcon::Move,
FrameGrab::Scale => egui::CursorIcon::ResizeNwSe,
FrameGrab::Place => egui::CursorIcon::Crosshair,
FrameGrab::Side(side) if side % 2 == 0 => egui::CursorIcon::ResizeVertical,
FrameGrab::Side(_) => egui::CursorIcon::ResizeHorizontal,
}
@@ -0,0 +1,11 @@
use serde::{Deserialize, Serialize};
/// What a warp's frame gizmo does: Move shows the arrows and centre square, Rotate the turn ring, Scale the edge dots that size the frame; Place on surface puts the frame where a drag over the model touches it
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum GizmoMode {
#[default]
Move,
Rotate,
Scale,
PlaceOnSurface,
}
@@ -0,0 +1,9 @@
use serde::{Deserialize, Serialize};
/// The directions a warp's move arrows follow: the frame's own, or the world's
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum GizmoSpace {
#[default]
Object,
World,
}
@@ -0,0 +1,380 @@
//! The warp controls of the top tool bar while the selected fill projects through a warp, in place of the tool's own: the transform tool's settings, the warp mode, the gizmo's mode and space, the mirrors and the resets
mod gizmo_mode;
mod gizmo_space;
mod snap;
mod warp_target;
mod warp_toolbar_settings;
use egui::Ui;
use egui_phosphor::regular as ic;
use serde_json::json;
pub use gizmo_mode::GizmoMode;
pub use gizmo_space::GizmoSpace;
pub(crate) use snap::to_step;
pub use warp_toolbar_settings::WarpToolbarSettings;
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::toolbar::icon_dropdown;
use crate::widgets::{icon_button, icon_dropdown_button};
use texturecraft_engine::core::Projection;
pub(crate) use warp_target::WarpTarget;
use warp_toolbar_settings::{ANGLE_STEPS, GRID_STEPS, MANIPULATOR_SIZES};
/// The width of the settings popup (points)
const POPUP_WIDTH: f32 = 220.0;
/// The gizmo mode buttons: mode, icon, label
const MODES: [(GizmoMode, &str, &str); 4] = [
(GizmoMode::Move, ic::ARROWS_OUT_CARDINAL, "Move"),
(GizmoMode::Rotate, ic::ARROWS_CLOCKWISE, "Rotate"),
(GizmoMode::Scale, ic::CORNERS_OUT, "Scale"),
(GizmoMode::PlaceOnSurface, ic::ARROW_LINE_DOWN, "Place on surface"),
];
/// The warp modes the bar lists; only the first works until the warp has a grid of vertices
const WARP_MODES: [&str; 5] = ["Transform warp", "Edit vertices", "Split both directions", "Split horizontally", "Split vertically"];
/// Why the warp modes past the first and the vertex reset are greyed out
const NEEDS_GRID: &str = "Needs the warp grid, which is not available yet";
/// The warp controls of the top tool bar, left to right
pub(crate) fn controls(app: &mut TextureCraftApp, ui: &mut Ui, target: WarpTarget) {
let size = ui.spacing().interact_size.y;
// The only tool there is, so it stays on
icon_button(ui, ic::BOUNDING_BOX, tr("Transform tool"), true, size);
manipulator_settings(app, ui, size);
warp_mode(ui);
ui.separator();
let current = app.ui.warp_toolbar.mode;
for (mode, icon, label) in MODES {
if icon_button(ui, icon, tr(label), current == mode, size).clicked() {
app.ui.warp_toolbar.mode = mode;
}
}
gizmo_space(app, ui);
ui.separator();
for (axis, icon, label, field) in [(0, ic::FLIP_HORIZONTAL, "Mirror horizontally", "flipU"), (1, ic::FLIP_VERTICAL, "Mirror vertically", "flipV")] {
if icon_button(ui, icon, tr(label), target.flip[axis], size).clicked() {
let mut fields = json!({});
fields[field] = json!(!target.flip[axis]);
app.run("layer.decal.set", target.params(fields));
}
}
resets(app, ui, &target);
}
/// The settings popup of the transform tool: the gizmo's size and the steps its drags snap to
fn manipulator_settings(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) {
let popup_id = ui.make_persistent_id("warp_manipulator_settings");
let open = egui::Popup::is_id_open(ui.ctx(), popup_id);
let response = icon_dropdown_button(ui, ic::GEAR, tr("Manipulator settings"), open, size);
let response = if open { response } else { response.on_hover_text(tr("Manipulator settings")) };
// Sliders sit in the popup, so a click inside must not close it
egui::Popup::menu(&response).id(popup_id).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
ui.set_width(POPUP_WIDTH);
ui.label(egui::RichText::new(tr("MANIPULATOR SETTINGS")).strong());
let settings = &mut app.ui.warp_toolbar;
ui.add(egui::Slider::new(&mut settings.manipulator_size, MANIPULATOR_SIZES).text(tr("Manipulator size")).fixed_decimals(2));
ui.add(egui::Slider::new(&mut settings.grid_steps, GRID_STEPS).text(tr("Grid steps")).fixed_decimals(2))
.on_hover_text(tr("Hold Ctrl while dragging to move in these steps"));
ui.add(egui::Slider::new(&mut settings.angle_steps, ANGLE_STEPS).text(tr("Angle steps")).fixed_decimals(0))
.on_hover_text(tr("Hold Ctrl while dragging to turn in these steps"));
});
}
/// The warp mode list: Transform warp works; the others wait for the warp grid
fn warp_mode(ui: &mut Ui) {
icon_dropdown(ui, "warp_mode", ic::FRAME_CORNERS, tr(WARP_MODES[0]), |ui| {
for (index, label) in WARP_MODES.into_iter().enumerate() {
let unavailable = (index > 0).then(|| tr(NEEDS_GRID));
menu_row(ui, tr(label), index == 0, unavailable);
}
});
}
/// Object space or World space: the directions the move arrows follow
fn gizmo_space(app: &mut TextureCraftApp, ui: &mut Ui) {
let spaces = [(GizmoSpace::Object, ic::CUBE, "Object space"), (GizmoSpace::World, ic::GLOBE, "World space")];
let current = app.ui.warp_toolbar.space;
let (_, icon, label) = spaces.iter().find(|(space, ..)| *space == current).unwrap_or(&spaces[0]);
let mut chosen = None;
icon_dropdown(ui, "warp_space", icon, tr(label), |ui| {
for (space, _, label) in spaces {
if menu_row(ui, tr(label), current == space, None) {
chosen = Some(space);
}
}
});
if let Some(space) = chosen {
app.ui.warp_toolbar.space = space;
}
}
/// The reset list: the frame back around the mesh, or the corners back on the frame
fn resets(app: &mut TextureCraftApp, ui: &mut Ui, target: &WarpTarget) {
let mut command = None;
icon_dropdown(ui, "warp_reset", ic::ARROW_COUNTER_CLOCKWISE, tr("Reset"), |ui| {
if menu_row(ui, tr("Reset warp transform"), false, None) {
command = Some(("layer.fill.resetFrame", json!({"keepCorners": true})));
}
if menu_row(ui, tr("Reset all vertices"), false, None) {
command = Some(("layer.fill.projection", json!({"warpCorners": Projection::FRAME_CORNERS})));
}
// Vertices cannot be selected before the warp has a grid
menu_row(ui, tr("Reset selected vertices"), false, Some(tr(NEEDS_GRID)));
});
if let Some((id, fields)) = command {
app.run(id, target.params(fields));
}
}
/// One list entry; `unavailable` greys it out and says why on hover. Returns true when clicked
fn menu_row(ui: &mut Ui, label: &str, selected: bool, unavailable: Option<&str>) -> bool {
let response = ui.add_enabled(unavailable.is_none(), egui::Button::new(label).selected(selected));
if let Some(reason) = unavailable {
response.on_disabled_hover_text(reason);
return false;
}
response.clicked()
}
#[cfg(test)]
mod tests {
use egui::accesskit::Role;
use egui::{Modifiers, Pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use texturecraft_engine::core::Projection;
use texturecraft_engine::geom::glam::{Vec2, Vec3};
use super::*;
use crate::frame_gizmo::FrameGrab;
use crate::frame_gizmo::tests::{drag, fill_app, gizmo, projection};
use crate::projection_gizmo::Gizmo;
fn click_label(harness: &mut Harness<'_, TextureCraftApp>, label: &str) {
harness.get_by_label(label).click();
harness.run_steps(2);
}
/// The warp's frame and corners
fn warp_parts(harness: &Harness<'_, TextureCraftApp>, layer: texturecraft_engine::core::LayerId) -> (texturecraft_engine::core::Decal, [[f32; 2]; 4]) {
let Projection::Warp { frame, corners, .. } = projection(harness, layer) else { panic!("a warp") };
(frame, corners)
}
#[test]
fn the_bar_shows_for_a_warp_fill_only() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, layer) = fill_app("warp");
assert!(harness.query_by_label("Transform tool").is_some());
harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": "planar"}));
harness.run_steps(2);
assert!(harness.query_by_label("Transform tool").is_none(), "a planar frame has no warp tools");
let away = harness.state().viewport_rect.left_bottom() + vec2(10.0, -10.0);
assert_eq!(gizmo(&harness).grab(away), None, "a planar frame has no Place on surface");
}
#[test]
fn each_mode_offers_only_its_handles() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, _) = fill_app("warp");
let start = gizmo(&harness);
click_label(&mut harness, "Rotate");
let ring = gizmo(&harness).ring.expect("a frame facing the camera shows its ring");
let ring_point = *ring.iter().max_by(|first, second| first.y.total_cmp(&second.y)).unwrap();
let handles: [(FrameGrab, Pos2, GizmoMode); 4] = [
(FrameGrab::Slide, start.center, GizmoMode::Move),
(FrameGrab::Axis(0), start.arrows[0].unwrap(), GizmoMode::Move),
(FrameGrab::Turn, ring_point, GizmoMode::Rotate),
(FrameGrab::Side(1), start.sides[1], GizmoMode::Scale),
];
for (_, _, label) in MODES {
click_label(&mut harness, label);
let shown = gizmo(&harness);
let mode = shown.tools.unwrap().mode;
for (grab, at, offered_in) in handles {
assert_eq!(shown.grab(at) == Some(grab), mode == offered_in, "{grab:?} in {mode:?}");
}
assert_eq!(shown.grab(shown.corners[1]), Some(FrameGrab::Corner(1)), "a warp's corners stay in {mode:?}");
}
}
#[test]
fn place_on_surface_puts_the_frame_where_the_pointer_touches_the_model() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, layer) = fill_app("warp");
let rect = harness.state().viewport_rect;
let middle = crate::viewport::project(harness.state(), rect, Vec3::ZERO).unwrap();
let (from, onto) = (middle + vec2(30.0, 20.0), middle + vec2(-60.0, -40.0));
let steps = harness.state().session.history_labels().len();
let (before, corners_before) = warp_parts(&harness, layer);
click_label(&mut harness, "Place on surface");
drag(&mut harness, from, onto, Modifiers::NONE);
let (placed, corners) = warp_parts(&harness, layer);
let on_view = onto - rect.min;
let hit = harness.state().session.pick(Vec2::new(on_view.x, on_view.y), harness.state().session.viewport).expect("the model is under the pointer");
assert!(Vec3::from(placed.center).distance(hit.pos) < 1e-2, "the frame centre sits at the surface hit: {:?} {:?}", placed.center, hit.pos);
assert!(Vec3::from(placed.normal).dot(hit.nrm) > 0.99, "the frame faces along the surface normal");
assert_eq!((placed.size, placed.rotation, corners), (before.size, before.rotation, corners_before), "its size, rotation and corners stay");
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step per drag");
// Past the model's edge the frame waits where it last touched it
drag(&mut harness, onto, rect.left_bottom() + vec2(10.0, -10.0), Modifiers::NONE);
let (waiting, _) = warp_parts(&harness, layer);
assert!((Vec3::from(waiting.center).length() - 1.0).abs() < 0.05, "still on the ball: {:?}", waiting.center);
}
#[test]
fn place_on_surface_keeps_a_warp_on_its_own_texture_set() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mesh = texturecraft_engine::geom::primitives::material_ball();
let session = texturecraft_engine::Session::new_project("Warp placement", mesh, "builtin:material_ball", None, 128).unwrap();
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
let layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap();
harness.state_mut().run("layer.fill.projection", json!({"layer": layer, "projection": "warp"})).unwrap();
harness.run_steps(2);
click_label(&mut harness, "Place on surface");
let app = harness.state();
let rect = app.viewport_rect;
let frame = gizmo(&harness);
let on_other_set = |point: Pos2| {
let local = point - rect.min;
app.session.texture_set_at(Vec2::new(local.x, local.y), app.session.viewport).is_some_and(|set| set != app.session.ts())
};
let movement = vec2(12.0, 0.0);
let rows = (0..rect.height() as usize).step_by(8);
let columns = (0..rect.width() as usize).step_by(8);
let mut candidates = rows.flat_map(|y| columns.clone().map(move |x| rect.min + vec2(x as f32, y as f32)));
let from = candidates
.find(|point| frame.grab(*point) == Some(FrameGrab::Place) && (0..=4).all(|step| on_other_set(*point + movement * (step as f32 / 4.0))))
.expect("a drag entirely on the material ball's other set");
let layer = frame.layer;
let before = projection(&harness, layer);
let steps = app.session.history_labels().len();
drag(&mut harness, from, from + movement, Modifiers::NONE);
assert_eq!(projection(&harness, layer), before, "the foreign surface must not take the warp");
assert_eq!(harness.state().session.history_labels().len(), steps);
}
#[test]
fn world_space_arrows_ignore_the_frames_turn() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, layer) = fill_app("warp");
let turn = |harness: &mut Harness<'_, TextureCraftApp>| {
harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30}));
harness.run_steps(2);
};
let arrow = |harness: &Harness<'_, TextureCraftApp>| {
let shown = gizmo(harness);
(shown.arrows[0].unwrap() - shown.center).normalized()
};
let frame_arrow = arrow(&harness);
turn(&mut harness);
assert!(arrow(&harness).dot(frame_arrow) < 0.95, "an object space arrow turns with the frame");
harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 0}));
click_label(&mut harness, "Object space");
click_label(&mut harness, "World space");
let world_arrow = arrow(&harness);
turn(&mut harness);
assert!(arrow(&harness).dot(world_arrow) > 0.999, "a world space arrow stays on its world axis");
}
#[test]
fn holding_ctrl_moves_in_whole_grid_steps() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, layer) = fill_app("warp");
let grid_step = harness.state().ui.warp_toolbar.grid_step();
let start = gizmo(&harness);
let tip = start.arrows[0].unwrap();
let along = (tip - start.center).normalized();
// On macOS Ctrl is independent of the platform Command modifier
drag(&mut harness, tip, tip + along * 37.0, Modifiers::CTRL);
let (frame, _) = warp_parts(&harness, layer);
let steps = frame.offset[0] / grid_step;
assert!(frame.offset[0].abs() > 1e-3 && (steps - steps.round()).abs() < 1e-3, "moved by whole steps of {grid_step}: {:?}", frame.offset);
}
#[test]
fn keyboard_changes_the_warp_drag_steps() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, _) = fill_app("warp");
let before = harness.state().ui.warp_toolbar.grid_step();
click_label(&mut harness, "Manipulator settings");
harness.get_by_role_and_label(Role::Slider, "Grid steps").focus();
harness.run_steps(2);
harness.key_press(egui::Key::ArrowRight);
harness.run_steps(2);
assert!(harness.get_by_role_and_label(Role::Slider, "Grid steps").is_focused());
assert!(harness.state().ui.warp_toolbar.grid_step() > before);
assert!(harness.query_by_role_and_label(Role::Slider, "Angle steps").is_some());
}
#[test]
fn the_mirror_and_reset_buttons_edit_the_warp_in_one_undo_step_each() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, layer) = fill_app("warp");
let (fitted, _) = warp_parts(&harness, layer);
let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]];
harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "warpCorners": pulled}));
harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30}));
harness.run_steps(2);
let steps = harness.state().session.history_labels().len();
click_label(&mut harness, "Mirror horizontally");
assert_eq!(warp_parts(&harness, layer).0.flip, [true, false]);
click_label(&mut harness, "Mirror vertically");
click_label(&mut harness, "Mirror horizontally");
assert_eq!(warp_parts(&harness, layer).0.flip, [false, true], "each button toggles its own direction");
assert_eq!(harness.state().session.history_labels().len(), steps + 3);
click_label(&mut harness, "Reset");
click_label(&mut harness, "Reset warp transform");
let (frame, corners) = warp_parts(&harness, layer);
assert_eq!((frame, corners), (fitted, pulled), "the frame goes back and the corners stay");
click_label(&mut harness, "Reset");
click_label(&mut harness, "Reset all vertices");
assert_eq!(warp_parts(&harness, layer).1, Projection::FRAME_CORNERS);
assert_eq!(harness.state().session.history_labels().len(), steps + 5);
}
}
@@ -0,0 +1,24 @@
/// `value` rounded to the nearest multiple of `step`; no step (0, negative or not a number) leaves it as it is
pub(crate) fn to_step(value: f32, step: f32) -> f32 {
if step.is_finite() && step > 0.0 { (value / step).round() * step } else { value }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_value_snaps_to_the_nearest_multiple_of_the_step() {
assert!((to_step(0.29, 0.2) - 0.2).abs() < 1e-6);
assert!((to_step(0.31, 0.2) - 0.4).abs() < 1e-6);
assert!((to_step(-0.31, 0.2) + 0.4).abs() < 1e-6, "negative moves snap the same way");
assert_eq!(to_step(100.0, 45.0), 90.0);
}
#[test]
fn no_step_leaves_the_value_alone() {
for step in [0.0, -1.0, f32::NAN, f32::INFINITY] {
assert_eq!(to_step(0.37, step), 0.37, "{step}");
}
}
}
@@ -0,0 +1,34 @@
use serde_json::{Value, json};
use texturecraft_engine::core::{LayerId, Projection};
use crate::TextureCraftApp;
use crate::frame_gizmo::selected_fill_projection;
/// The selected fill with a warp projection that the tool bar edits: a fill layer, or a fill effect in its mask
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct WarpTarget {
pub layer: LayerId,
pub effect: Option<LayerId>,
/// The image mirrored left to right and top to bottom inside the frame
pub flip: [bool; 2],
}
impl WarpTarget {
/// The selected fill when it projects through a warp, in the modes where the frame gizmo shows
pub(crate) fn of(app: &TextureCraftApp) -> Option<WarpTarget> {
let (layer, effect, projection) = selected_fill_projection(app)?;
let Projection::Warp { frame, .. } = projection else { return None };
Some(WarpTarget { layer, effect, flip: frame.flip })
}
/// `fields` addressed to this fill, as every command that edits a fill's projection takes it
pub(super) fn params(&self, mut params: Value) -> Value {
params["layer"] = json!(self.layer.0);
if let Some(effect) = self.effect {
params["effect"] = json!(effect.0);
}
params
}
}
@@ -0,0 +1,63 @@
use std::ops::RangeInclusive;
use serde::{Deserialize, Serialize};
use super::{GizmoMode, GizmoSpace};
/// The manipulator size the gizmo's measurements are given at
pub(super) const DEFAULT_MANIPULATOR_SIZE: f32 = 0.2;
pub(super) const MANIPULATOR_SIZES: RangeInclusive<f32> = 0.1..=0.5;
/// The default and range of the move step (world units) and of the turn step (degrees)
pub(super) const DEFAULT_GRID_STEP: f32 = 0.2;
pub(super) const GRID_STEPS: RangeInclusive<f32> = 0.01..=1.0;
pub(super) const DEFAULT_ANGLE_STEP: f32 = 45.0;
pub(super) const ANGLE_STEPS: RangeInclusive<f32> = 1.0..=90.0;
/// The warp tool bar's settings: the gizmo's mode, space and size, and the steps its drags snap to while Ctrl is held
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct WarpToolbarSettings {
pub mode: GizmoMode,
pub space: GizmoSpace,
/// Manipulator size: [`DEFAULT_MANIPULATOR_SIZE`] draws the gizmo at its base size
pub manipulator_size: f32,
/// Move step in world units
pub grid_steps: f32,
/// Turn step in degrees
pub angle_steps: f32,
}
impl Default for WarpToolbarSettings {
fn default() -> Self {
WarpToolbarSettings {
mode: GizmoMode::default(),
space: GizmoSpace::default(),
manipulator_size: DEFAULT_MANIPULATOR_SIZE,
grid_steps: DEFAULT_GRID_STEP,
angle_steps: DEFAULT_ANGLE_STEP,
}
}
}
impl WarpToolbarSettings {
/// How many times its base size the gizmo's arrows and ring are drawn
pub(crate) fn gizmo_scale(&self) -> f32 {
within(self.manipulator_size, MANIPULATOR_SIZES, DEFAULT_MANIPULATOR_SIZE) / DEFAULT_MANIPULATOR_SIZE
}
/// The move step in world units
pub(crate) fn grid_step(&self) -> f32 {
within(self.grid_steps, GRID_STEPS, DEFAULT_GRID_STEP)
}
/// The turn step in degrees
pub(crate) fn angle_step(&self) -> f32 {
within(self.angle_steps, ANGLE_STEPS, DEFAULT_ANGLE_STEP)
}
}
/// `value` held to `range`; `fallback` for a saved value that is not a number
fn within(value: f32, range: RangeInclusive<f32>, fallback: f32) -> f32 {
if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { fallback }
}
+10 -4
View File
@@ -29,12 +29,14 @@ pub(crate) fn let_go<G: Gizmo>(ctx: &egui::Context) {
/// Drags on `gizmo`'s handles (one undo step per drag, the projection updates live); returns whether a drag owns the pointer. The cursor shows what the handle under it, or the one dragged, does (only while the gizmo takes input: an Alt orbit or a held Move on model keeps its own)
pub(crate) fn input<G: Gizmo>(app: &mut TextureCraftApp, ctx: &egui::Context, response: &egui::Response, rect: Rect, gizmo: Option<&G>) -> bool {
let mut drag = dragging::<G>(ctx).filter(|drag| gizmo.is_some_and(|gizmo| gizmo.same_projection(&drag.start)));
let mesh_id = app.session.mesh_id;
let mut drag = dragging::<G>(ctx).filter(|drag| drag.mesh_id == mesh_id && gizmo.is_some_and(|gizmo| gizmo.same_projection(&drag.start)));
if response.drag_started_by(PointerButton::Primary)
&& let (Some(gizmo), Some(from)) = (gizmo, ctx.input(|input| input.pointer.press_origin()))
&& let Some(grab) = gizmo.grab(from)
{
drag = Some(GizmoDrag { grab, from, start: Arc::new(gizmo.clone()), edited_revision: None });
drag = Some(GizmoDrag { grab, from, mesh_id, start: Arc::new(gizmo.clone()), edited_revision: None });
}
// Apply a final move on release and let focus loss end a drag without one
@@ -51,19 +53,23 @@ pub(crate) fn input<G: Gizmo>(app: &mut TextureCraftApp, ctx: &egui::Context, re
// A drag lives only while its gizmo shows, so the gizmo drawn this frame names the cursor
ctx.set_cursor_icon(gizmo.unwrap_or(&drag.start).cursor(drag.grab, true));
if let Some(pointer) = response.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO))
&& let Some((command, params)) = drag.start.edit(app, rect, drag.grab, drag.from, pointer)
let (moved, snapping) = ctx.input(|input| (input.pointer.delta() != egui::Vec2::ZERO, input.modifiers.ctrl || input.modifiers.command));
if moved
&& let Some(pointer) = response.interact_pointer_pos()
&& let Some((command, params)) = drag.start.edit_with_snap(app, rect, drag.grab, drag.from, pointer, snapping)
{
edit_in_one_step(&mut app.session, command, params, &mut drag.edited_revision);
// The panel drew before this edit: one more frame shows its fields and preview where the projection is now
ctx.request_repaint();
}
if released {
let_go::<G>(ctx);
} else {
ctx.data_mut(|data| data.insert_temp(G::drag_id(), drag));
}
true
}
@@ -20,6 +20,11 @@ pub(crate) trait Gizmo: Clone + Send + Sync + 'static {
/// The command and params a drag of `grab` from `from` to `to` runs
fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: Self::Grab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)>;
/// As [`Gizmo::edit`], the drag snapping to the tool bar's steps while `snapping` (a gizmo with none ignores it)
fn edit_with_snap(&self, app: &TextureCraftApp, rect: Rect, grab: Self::Grab, from: Pos2, to: Pos2, _snapping: bool) -> Option<(&'static str, Value)> {
self.edit(app, rect, grab, from, to)
}
/// The cursor over `grab`, or dragging it
fn cursor(&self, grab: Self::Grab, dragging: bool) -> egui::CursorIcon;
}
@@ -10,6 +10,8 @@ pub(crate) struct GizmoDrag<G: Gizmo> {
pub(crate) grab: G::Grab,
/// Where the drag started
pub(crate) from: Pos2,
/// The loaded mesh at press time, including its UV layout
pub(crate) mesh_id: u64,
/// The starting gizmo shared by the pointer, edit and overlay paths
pub(crate) start: Arc<G>,
/// The session revision the drag's last edit left: later updates merge into its undo step while the history is still there
+1 -1
View File
@@ -148,7 +148,7 @@ impl RoundGizmo {
let pixels = (project(app, rect, origin + right * reach)? - center).length() / reach;
let ring = TURN_RING / pixels.max(f32::MIN_POSITIVE);
self.rings = directions.map(|direction| {
if !ring_open(app, rect, center, direction) {
if !ring_open(app, rect, center, direction, TURN_RING) {
return Vec::new();
}
+11 -1
View File
@@ -631,6 +631,9 @@ pub struct UiState {
/// How the 3D view shows symmetry
#[serde(default)]
pub symmetry: crate::symmetry::SymmetryDisplay,
/// The warp tool bar: the gizmo's mode and space, its size, and the steps its drags snap to
#[serde(default)]
pub warp_toolbar: crate::frame_gizmo::warp_toolbar::WarpToolbarSettings,
/// The brush, symmetry and other tool settings of the last session, which the next one starts with
#[serde(default)]
pub tool_settings: texturecraft_engine::ToolSettings,
@@ -738,6 +741,7 @@ impl UiState {
self.nav_buttons = keep.nav_buttons;
self.keymap = keep.keymap;
self.tool_settings = keep.tool_settings;
self.warp_toolbar = keep.warp_toolbar;
self.named_layouts = keep.named_layouts;
self.bake_presets = keep.bake_presets;
self.layout_dialog = None;
@@ -798,6 +802,7 @@ impl Default for UiState {
keymap: Keymap::new(),
bake_paint_brush: crate::bake_mode::BakePaintBrush::default(),
symmetry: crate::symmetry::SymmetryDisplay::default(),
warp_toolbar: crate::frame_gizmo::warp_toolbar::WarpToolbarSettings::default(),
tool_settings: Default::default(),
bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(),
named_layouts: Vec::new(),
@@ -852,8 +857,12 @@ mod tests {
}
#[test]
fn adopting_a_layout_keeps_recent_files_export_settings_and_shortcuts() {
fn adopting_a_layout_keeps_recent_files_and_user_settings() {
use crate::frame_gizmo::warp_toolbar::{GizmoMode, GizmoSpace, WarpToolbarSettings};
let warp_toolbar = WarpToolbarSettings { mode: GizmoMode::Rotate, space: GizmoSpace::World, manipulator_size: 0.4, grid_steps: 0.5, angle_steps: 30.0 };
let mut ui = UiState { recent: vec!["a.tcraft".into()], ..UiState::default() };
ui.warp_toolbar = warp_toolbar;
ui.export.preset = "Mine".into();
ui.keymap.insert("file.save".into(), "F5".into());
let mut layout = UiState::default();
@@ -865,6 +874,7 @@ mod tests {
assert_eq!(ui.recent, vec!["a.tcraft".to_string()]);
assert_eq!(ui.export.preset, "Mine");
assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5"));
assert_eq!(ui.warp_toolbar, warp_toolbar, "loading a layout keeps the user's warp settings");
}
#[test]
+19 -8
View File
@@ -7,6 +7,7 @@ use texturecraft_engine::Tool;
use crate::TextureCraftApp;
use crate::drawn_icon::DrawnIcon;
use crate::frame_gizmo::warp_toolbar::{self, WarpTarget};
use crate::i18n::{tr, trf};
use crate::keymap::{shortcut_of, tip};
use crate::state::{Mode, ViewLayout};
@@ -58,16 +59,18 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
return;
}
let warp_target = WarpTarget::of(app);
let tool_usable = warp_target.is_none() && app.session.tool_usable(app.session.tool.tool);
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
if !scroll_views {
view_buttons(app, ui);
if app.session.tool_usable(app.session.tool.tool) {
if warp_target.is_some() || tool_usable {
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
}
}
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
scrolling_tool_controls(app, ui, &tokens, scroll_views);
scrolling_tool_controls(app, ui, &tokens, scroll_views, warp_target, tool_usable);
});
});
});
@@ -175,7 +178,7 @@ fn rotation_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
}
/// An icon button with a caret that opens `menu` below it, highlighted while open
fn icon_dropdown(ui: &mut egui::Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut egui::Ui)) {
pub(crate) fn icon_dropdown(ui: &mut egui::Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut egui::Ui)) {
let button_size = ui.spacing().interact_size.y;
let popup_id = ui.make_persistent_id(id_salt);
let open = egui::Popup::is_id_open(ui.ctx(), popup_id);
@@ -198,7 +201,14 @@ fn dropdown_row(ui: &mut egui::Ui, icon: &str, label: &str, shortcut: Option<&st
}
/// Scroll tool controls and, in narrow viewports, the view buttons
fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, scroll_views: bool) {
fn scrolling_tool_controls(
app: &mut TextureCraftApp,
ui: &mut egui::Ui,
tokens: &Tokens,
scroll_views: bool,
warp_target: Option<WarpTarget>,
tool_usable: bool,
) {
let button_size = ui.spacing().interact_size.y;
let strip_width = ui.available_width();
let overflow_id = egui::Id::unique("tool_controls_overflow");
@@ -224,13 +234,14 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens:
scroll_area.show(ui, |ui| {
ui.scroll_with_delta(vec2(scroll_delta, 0.0));
ui.horizontal_centered(|ui| {
// A tool that can't act on the selection leaves the bar, as the shelf greys it
let tool_usable = app.session.tool_usable(app.session.tool.tool);
if tool_usable {
if let Some(target) = warp_target {
warp_toolbar::controls(app, ui, target);
} else if tool_usable {
tool_controls(app, ui, tokens);
}
if scroll_views {
if tool_usable {
if warp_target.is_some() || tool_usable {
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
}
let size = vec2(view_buttons_width(button_size, ui.spacing().item_spacing.x), ui.available_height());
+5 -3
View File
@@ -677,9 +677,11 @@ with `material.apply` instead. The command rejects linked MaterialCraft fills. T
- `effect.filter.restoreDefaults {effect?}` puts a filter's parameters back to its defaults (name,
channels and blending stay) and returns `{changed}`.
- `layer.fill.resetProjection {layer? | effect?}` puts the Fill section back to a new fill's (same
projection kind; a placed frame, the symmetry and the sources stay); `layer.fill.resetFrame` puts a
warp's frame back around the mesh with its corners unpulled. Each is one undo step, or none when
nothing changes.
projection kind; a placed frame, the symmetry and the sources stay). `layer.fill.resetFrame
{layer? | effect?, keepCorners?: bool}` puts a warp's frame back around the mesh. By default it
resets the corners. With `keepCorners: true` it preserves the corners and also resets projector
rotation and scale. Projection Depth, crop and culling stay. Each reset is one undo step, or none
when nothing changes.
## MaterialCraft materials