mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-20 22:40:44 +01:00
Merge pull request #351 from Rebornim/feat/path-tool-parity
Path tool: live preview while placing points, edit points in the views
This commit is contained in:
33 files changed
+2143
-198
No files matched your search
@@ -126,7 +126,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// A decal dropped on another texture set goes there and selects it, as a dropped material does
|
||||
if ts != s.ts() {
|
||||
crate::set_cmds::select_set(s, ts);
|
||||
crate::set_cmds::select_set(s, ts)?;
|
||||
}
|
||||
|
||||
let base = strp(p, "name")
|
||||
|
||||
@@ -168,6 +168,12 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = layer_param(s, "layer.select", p)?;
|
||||
let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad("layer.select", "layer not in a stack"))?;
|
||||
|
||||
// Paths paint into the active set
|
||||
if ts != s.ts() {
|
||||
s.finish_path()?;
|
||||
}
|
||||
|
||||
s.active_set = ts;
|
||||
s.selected.insert(ts, id);
|
||||
s.target = match p.get("target") {
|
||||
@@ -184,6 +190,7 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
},
|
||||
None => StackTarget::Content,
|
||||
};
|
||||
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(json!({ "layer": id.0, "textureSet": ts }))
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ pub mod meshmap_import_cmds;
|
||||
mod orb_camera;
|
||||
pub mod orb_preview;
|
||||
pub mod painting;
|
||||
mod path_draft;
|
||||
pub mod path_tool;
|
||||
mod polygon_fill;
|
||||
mod polygon_fill_drag;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
//! A new Path tool path previewed in the document before it is applied
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::Document;
|
||||
|
||||
/// A new path previewed in the document before it is applied
|
||||
pub(crate) struct PathDraft {
|
||||
/// The document before the preview
|
||||
pub(crate) base: Document,
|
||||
/// What painting the preview last reported (the commit's report when nothing changed since)
|
||||
pub(crate) painted: Value,
|
||||
}
|
||||
+587
-55
@@ -7,58 +7,108 @@
|
||||
//! (`path.edit`, live while the points, brush or material change) or removed (`path.remove`).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::{PaintTarget, PixelStore};
|
||||
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape};
|
||||
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
|
||||
use texturecraft_geom::{OrbitCamera, surface_at};
|
||||
use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline};
|
||||
use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments};
|
||||
use texturecraft_texel::TileImage;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p};
|
||||
use crate::path_draft::PathDraft;
|
||||
use crate::session::{StackTarget, Tool};
|
||||
use crate::tool_cmds::{points_param, set_tool, viewport_of};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
use crate::{Document, EngineError, Result, Session, cmd};
|
||||
|
||||
/// Control points kept at most.
|
||||
pub const MAX_PATH_POINTS: usize = 4096;
|
||||
/// The undo step that adds a new path
|
||||
pub(crate) const NEW_PATH_LABEL: &str = "Path";
|
||||
/// Curve sampling step in viewport pixels (3D view) and texture units (2D view).
|
||||
const STEP_PX: f32 = 2.0;
|
||||
const STEP_UV: f32 = 0.001;
|
||||
/// A stored path's viewport is clamped to this range (pixels per side) before painting from it
|
||||
const MIN_PAINT_VIEWPORT_PX: f32 = 16.0;
|
||||
const MAX_PAINT_VIEWPORT_PX: f32 = 16384.0;
|
||||
/// Sampling step of a 3D path's curve on the mesh for the views, in its paint viewport pixels
|
||||
const SURFACE_STEP_PX: f32 = 4.0;
|
||||
const MIN_PROJECTIVE_W: f32 = 1e-6;
|
||||
// Match the minimum world-space scale used by brush stamps
|
||||
const MIN_BRUSH_SCALE: f32 = 1e-4;
|
||||
// Allow ray hits to differ slightly from transformed texel positions
|
||||
const RAY_HIT_RELATIVE_TOLERANCE: f32 = 0.001;
|
||||
|
||||
/// The curve being edited with the Path tool.
|
||||
/// The curve being edited with the Path tool
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PathState {
|
||||
/// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view).
|
||||
/// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view)
|
||||
pub points: Vec<Vec3>,
|
||||
/// The points are texture coordinates (placed in the 2D view).
|
||||
/// The points are texture coordinates (placed in the 2D view)
|
||||
pub uv: bool,
|
||||
/// The curve loops back to its first point.
|
||||
/// The curve loops back to its first point
|
||||
pub closed: bool,
|
||||
/// A closed path fills its interior instead of stroking the curve.
|
||||
/// A closed path fills its interior instead of stroking the curve
|
||||
pub fill: bool,
|
||||
/// The stored path being edited: (path sublayer, index). Changes repaint it live.
|
||||
/// The stored path being edited: (path sublayer, index). Changes repaint it live
|
||||
#[serde(default)]
|
||||
pub editing: Option<(LayerId, usize)>,
|
||||
/// This edit has already repainted: later changes join its undo step, not an earlier edit's.
|
||||
/// This edit has already repainted: later changes join its undo step, not an earlier edit's
|
||||
#[serde(default)]
|
||||
pub edited: bool,
|
||||
/// The selected control point (drawn in the accent color; Backspace or Remove point removes it)
|
||||
#[serde(default)]
|
||||
pub selected: Option<usize>,
|
||||
}
|
||||
|
||||
impl PathState {
|
||||
/// Append a control point; a point placed in the other view starts a new path.
|
||||
pub fn push(&mut self, p: Vec3, uv: bool) {
|
||||
pub fn push(&mut self, point: Vec3, uv: bool) {
|
||||
if uv != self.uv {
|
||||
self.points.clear();
|
||||
self.uv = uv;
|
||||
}
|
||||
if self.points.len() < MAX_PATH_POINTS {
|
||||
self.points.push(p);
|
||||
self.points.push(point);
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert a control point before point `at` (on the segment ending there) and select it; None when it can't
|
||||
pub fn insert(&mut self, at: usize, point: Vec3) -> Option<usize> {
|
||||
if at > self.points.len() || self.points.len() >= MAX_PATH_POINTS {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.points.insert(at, point);
|
||||
self.selected = Some(at);
|
||||
self.selected
|
||||
}
|
||||
|
||||
/// The same curve (points, open or closed, filled, view) as `other`
|
||||
fn same_curve(&self, other: &PathState) -> bool {
|
||||
(&self.points, self.closed, self.fill, self.uv) == (&other.points, other.closed, other.fill, other.uv)
|
||||
}
|
||||
|
||||
/// Empty the tool for the next path: no points, open, nothing selected or edited
|
||||
pub fn clear(&mut self) {
|
||||
self.points.clear();
|
||||
self.closed = false;
|
||||
self.selected = None;
|
||||
self.editing = None;
|
||||
self.edited = false;
|
||||
}
|
||||
|
||||
/// Remove the selected control point, or the last one when none is selected
|
||||
pub fn remove_selected(&mut self) {
|
||||
let at = self.selected.take().filter(|i| *i < self.points.len()).or(self.points.len().checked_sub(1));
|
||||
if let Some(i) = at {
|
||||
self.points.remove(i);
|
||||
}
|
||||
if self.closed && self.points.len() < 3 {
|
||||
self.closed = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,31 +168,35 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Set the curve from command parameters, then preview or commit it in the supplied viewport
|
||||
fn path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "tool.path";
|
||||
if s.tool.tool != Tool::Path {
|
||||
set_tool(s, Tool::Path)?;
|
||||
}
|
||||
let vp = viewport_of(s, p);
|
||||
|
||||
let viewport = viewport_of(s, p);
|
||||
if boolp(p, "clear") == Some(true) {
|
||||
s.tool.path.points.clear();
|
||||
s.tool.path.editing = None;
|
||||
s.cancel_path();
|
||||
}
|
||||
|
||||
let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) {
|
||||
(Some(pts), _) => Some((
|
||||
pts.iter()
|
||||
(Some(pixels), _) => Some((
|
||||
pixels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, q)| s.pick(*q, vp).map(|h| h.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh"))))
|
||||
.map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh"))))
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
false,
|
||||
)),
|
||||
(None, Some(pts)) => Some((pts.iter().map(|q| q.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)),
|
||||
(None, Some(uvs)) => Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)),
|
||||
(None, None) => None,
|
||||
};
|
||||
if let Some((points, uv)) = placed {
|
||||
if points.len() > MAX_PATH_POINTS {
|
||||
return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points")));
|
||||
}
|
||||
|
||||
s.tool.path.points = points;
|
||||
s.tool.path.uv = uv;
|
||||
}
|
||||
@@ -153,19 +207,21 @@ fn path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.tool.path.fill = v;
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
|
||||
let committed = if boolp(p, "commit") == Some(true) {
|
||||
let r = s.commit_path(vp)?;
|
||||
let report = s.commit_path(viewport)?;
|
||||
s.update();
|
||||
r
|
||||
report
|
||||
} else {
|
||||
if s.path_live()? {
|
||||
if s.path_live_in_view(viewport)? {
|
||||
s.update();
|
||||
}
|
||||
Value::Null
|
||||
};
|
||||
let st = &s.tool.path;
|
||||
let editing = st.editing.map(|(e, i)| json!({ "effect": e.0, "index": i }));
|
||||
Ok(json!({ "points": st.points.len(), "uv": st.uv, "closed": st.closed, "fill": st.fill, "editing": editing, "committed": committed }))
|
||||
|
||||
let path = &s.tool.path;
|
||||
let editing = path.editing.map(|(e, i)| json!({ "effect": e.0, "index": i }));
|
||||
Ok(json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill, "editing": editing, "committed": committed }))
|
||||
}
|
||||
|
||||
/// The `effect` and `index` params naming a stored path, with the path.
|
||||
@@ -179,20 +235,25 @@ fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathSh
|
||||
Ok((eid, i, shape))
|
||||
}
|
||||
|
||||
/// Finish any draft and load a stored path's geometry and paint settings for live editing
|
||||
fn edit_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "path.edit";
|
||||
let (eid, index, shape) = path_ref(s, CMD, p)?;
|
||||
let paint = read_paint(&shape)?;
|
||||
|
||||
s.finish_path()?;
|
||||
set_tool(s, Tool::Path)?;
|
||||
s.tool.brush = paint.brush;
|
||||
s.tool.values = paint.values;
|
||||
s.tool.enabled = paint.enabled;
|
||||
s.tool.mask_value = paint.mask_value;
|
||||
s.tool.path = PathState { editing: Some((eid, index)), ..state_of(&shape) };
|
||||
s.path_steps = Default::default();
|
||||
s.target = StackTarget::Effect(eid);
|
||||
Ok(json!({ "effect": eid.0, "index": index, "points": s.tool.path.points.len() }))
|
||||
}
|
||||
|
||||
/// Remove one stored curve and repaint its sublayer as an atomic document edit
|
||||
fn remove_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "path.remove";
|
||||
let (eid, index, _) = path_ref(s, CMD, p)?;
|
||||
@@ -218,10 +279,46 @@ fn read_paint(shape: &PathShape) -> Result<PathPaint> {
|
||||
Ok(paint)
|
||||
}
|
||||
|
||||
/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]).
|
||||
/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`])
|
||||
fn state_of(shape: &PathShape) -> PathState {
|
||||
let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect();
|
||||
PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, editing: None, edited: false }
|
||||
PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() }
|
||||
}
|
||||
|
||||
/// Tiles (x, y) where sublayer `eid`'s pixels differ between `before` and `after` (copy-on-write: an unchanged tile is the same allocation)
|
||||
fn changed_tiles(before: &PixelStore, after: &PixelStore, eid: LayerId) -> BTreeSet<(u32, u32)> {
|
||||
let (before_images, after_images) = (sublayer_images(before, eid), sublayer_images(after, eid));
|
||||
let channels: BTreeSet<Option<Channel>> = before_images.keys().chain(after_images.keys()).copied().collect();
|
||||
|
||||
let mut tiles = BTreeSet::new();
|
||||
for channel in channels {
|
||||
let (before_image, after_image) = (before_images.get(&channel), after_images.get(&channel));
|
||||
let Some(image) = before_image.or(after_image) else { continue };
|
||||
for ty in 0..image.tiles_y() {
|
||||
for tx in 0..image.tiles_x() {
|
||||
let same = match (before_image.and_then(|i| i.tile_handle(tx, ty)), after_image.and_then(|i| i.tile_handle(tx, ty))) {
|
||||
(None, None) => true,
|
||||
(Some(before_tile), Some(after_tile)) => Arc::ptr_eq(before_tile, after_tile),
|
||||
_ => false,
|
||||
};
|
||||
if !same {
|
||||
tiles.insert((tx, ty));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tiles
|
||||
}
|
||||
|
||||
/// Sublayer `eid`'s images by channel (None: its mask image)
|
||||
fn sublayer_images(pixels: &PixelStore, eid: LayerId) -> BTreeMap<Option<Channel>, &TileImage> {
|
||||
let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, channel), image)| (Some(*channel), image));
|
||||
layers.chain(pixels.masks.get(&eid).map(|mask| (None, mask))).collect()
|
||||
}
|
||||
|
||||
/// The camera and viewport a stored path paints through (the views draw its curve the same way)
|
||||
fn paint_view(shape: &PathShape, paint: &PathPaint) -> (OrbitCamera, Vec2) {
|
||||
(paint.camera, Vec2::from_array(shape.viewport).max(Vec2::splat(MIN_PAINT_VIEWPORT_PX)).min(Vec2::splat(MAX_PAINT_VIEWPORT_PX)))
|
||||
}
|
||||
|
||||
/// NDC (y up) to viewport pixels (origin top-left).
|
||||
@@ -237,10 +334,16 @@ impl Session {
|
||||
if path.uv {
|
||||
return path.points.iter().map(|p| Some(p.truncate())).collect();
|
||||
}
|
||||
|
||||
let aspect = viewport.x.max(1.0) / viewport.y.max(1.0);
|
||||
path.points.iter().map(|p| self.camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect()
|
||||
}
|
||||
|
||||
/// The stored paths of path sublayer `eid` as Path tool states, for the views to draw
|
||||
pub fn stored_path_states(&self, eid: LayerId) -> Vec<PathState> {
|
||||
self.paths(eid).unwrap_or_default().iter().map(state_of).collect()
|
||||
}
|
||||
|
||||
/// The stored paths of path sublayer `eid` (None if it isn't one).
|
||||
pub fn paths(&self, eid: LayerId) -> Option<&[PathShape]> {
|
||||
match self.doc.project.effect(eid) {
|
||||
@@ -263,12 +366,36 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Store the Path tool's curve (a new path in the selected path sublayer, or in a new one;
|
||||
/// or the path being edited) and repaint the sublayer, as one undo step. Clears the tool.
|
||||
/// Store the Path tool's curve (new, or the path being edited) and repaint its sublayer as one undo step, then clear the tool
|
||||
pub fn commit_path(&mut self, viewport: Vec2) -> Result<Value> {
|
||||
if let Some((effect, index)) = self.tool.path.editing
|
||||
&& self.paths(effect).and_then(|paths| paths.get(index)).is_some_and(|stored| self.same_as_stored(stored))
|
||||
{
|
||||
// Camera navigation alone must not replace the pixels the user just previewed
|
||||
let mut report = match self.path_draft.take() {
|
||||
Some(draft) => {
|
||||
self.push_step(NEW_PATH_LABEL, draft.base, false);
|
||||
draft.painted
|
||||
}
|
||||
None => json!({}),
|
||||
};
|
||||
report["effect"] = json!(effect.0);
|
||||
report["index"] = json!(index);
|
||||
self.target = StackTarget::Effect(effect);
|
||||
self.cancel_path();
|
||||
return Ok(report);
|
||||
}
|
||||
|
||||
if let Some(draft) = self.path_draft.take() {
|
||||
// Changed settings paint again from the document before the preview
|
||||
let preview = std::mem::replace(&mut self.doc, draft.base);
|
||||
self.changed_without_history(&preview);
|
||||
self.tool.path.editing = None;
|
||||
}
|
||||
|
||||
let shape = self.path_shape(self.camera, viewport);
|
||||
let editing = self.tool.path.editing;
|
||||
let label = editing.map_or("Path".to_string(), |(_, i)| format!("Edit path {}", i + 1));
|
||||
let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1));
|
||||
let out = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |s| {
|
||||
let (eid, index) = match editing {
|
||||
Some(at) => at,
|
||||
@@ -276,49 +403,309 @@ impl Session {
|
||||
};
|
||||
s.put_path(eid, index, shape)
|
||||
})?;
|
||||
|
||||
if let Some(eid) = out.get("effect").and_then(Value::as_u64) {
|
||||
self.target = StackTarget::Effect(LayerId(eid));
|
||||
}
|
||||
self.tool.path.points.clear();
|
||||
self.tool.path.editing = None;
|
||||
self.tool.path.clear();
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// While a stored path is edited, repaint its sublayer when the tool's points, brush or
|
||||
/// material changed (orbiting or resizing the view alone doesn't), merged into one undo
|
||||
/// step. Cheap when nothing changed; the UI calls it every frame. Returns whether it
|
||||
/// repainted.
|
||||
/// Repaint the edited path (one merged undo step) or a new path's preview (no step) when its points, brush or material changed; called every frame
|
||||
pub fn path_live(&mut self) -> Result<bool> {
|
||||
let Some((eid, index)) = self.tool.path.editing else { return Ok(false) };
|
||||
let Some(stored) = self.paths(eid).and_then(|v| v.get(index)).cloned() else {
|
||||
self.stop_path_edit();
|
||||
return Ok(false);
|
||||
self.path_live_in_view(self.viewport)
|
||||
}
|
||||
|
||||
/// Compare curve and typed paint settings through the stored camera and viewport
|
||||
fn same_as_stored(&self, stored: &PathShape) -> bool {
|
||||
// JSON round trips can change float representation without changing the paint settings
|
||||
read_paint(stored).is_ok_and(|paint| {
|
||||
let current = self.path_shape(paint.camera, Vec2::from_array(stored.viewport));
|
||||
(¤t.points, current.uv, current.closed, current.fill) == (&stored.points, stored.uv, stored.closed, stored.fill)
|
||||
&& read_paint(¤t).is_ok_and(|current_paint| current_paint == paint)
|
||||
})
|
||||
}
|
||||
|
||||
/// Preview a command's points in its supplied viewport, or the UI's current viewport
|
||||
fn path_live_in_view(&mut self, viewport: Vec2) -> Result<bool> {
|
||||
let stored = match self.tool.path.editing {
|
||||
Some((eid, index)) => match self.paths(eid).and_then(|v| v.get(index)).cloned() {
|
||||
Some(shape) => Some((eid, index, shape)),
|
||||
None => {
|
||||
self.stop_path_edit();
|
||||
return Ok(false);
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
|
||||
if self.tool.tool != Tool::Path || self.stroke.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
if self.tool.path.points.is_empty() {
|
||||
if let Some((effect, index, _)) = stored {
|
||||
if self.path_draft.is_some() {
|
||||
self.cancel_path();
|
||||
} else {
|
||||
self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |session| {
|
||||
if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) {
|
||||
paths.remove(index);
|
||||
}
|
||||
session.render_paths(effect, index)
|
||||
})?;
|
||||
self.cancel_path();
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let path = &self.tool.path;
|
||||
if self.tool.tool != Tool::Path || self.stroke.is_some() || path.points.is_empty() || (path.closed && path.fill && path.points.len() < 3) {
|
||||
if path.closed && path.fill && path.points.len() < 3 {
|
||||
return Ok(false);
|
||||
}
|
||||
// Typed comparison: the stored settings went through JSON (f64), maybe a save and load.
|
||||
let unchanged = read_paint(&stored).is_ok_and(|p| {
|
||||
let now = self.path_shape(p.camera, Vec2::from_array(stored.viewport));
|
||||
(&now.points, now.uv, now.closed, now.fill) == (&stored.points, stored.uv, stored.closed, stored.fill) && read_paint(&now).is_ok_and(|n| n == p)
|
||||
});
|
||||
if unchanged {
|
||||
|
||||
let Some((eid, index, stored)) = stored else { return self.start_path_draft(viewport) };
|
||||
|
||||
if self.same_as_stored(&stored) {
|
||||
return Ok(false);
|
||||
}
|
||||
let shape = self.path_shape(self.camera, self.viewport);
|
||||
self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |s| s.put_path(eid, index, shape))?;
|
||||
self.tool.path.edited = true;
|
||||
|
||||
let shape = self.path_shape(self.camera, viewport);
|
||||
let (painted, before) = self.repaint_path(eid, index, shape)?;
|
||||
match &mut self.path_draft {
|
||||
Some(draft) => draft.painted = painted,
|
||||
None => {
|
||||
// The path's own repaint keeps its point changes undoable, unlike other steps
|
||||
let steps = std::mem::take(&mut self.path_steps);
|
||||
self.push_step(&format!("Edit path {}", index + 1), before, self.tool.path.edited);
|
||||
self.path_steps = steps;
|
||||
self.tool.path.edited = true;
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Stop editing a stored path (its changes are already applied) and clear the tool.
|
||||
pub fn stop_path_edit(&mut self) {
|
||||
if self.tool.path.editing.take().is_some() {
|
||||
self.tool.path.points.clear();
|
||||
/// Paint a new path's first preview where [`Session::commit_path`] would add it, keeping the document before it for apply and cancel
|
||||
fn start_path_draft(&mut self, viewport: Vec2) -> Result<bool> {
|
||||
let base = self.doc.clone();
|
||||
let shape = self.path_shape(self.camera, viewport);
|
||||
let placed = self.path_effect().and_then(|eid| {
|
||||
let index = self.paths(eid).map_or(0, <[_]>::len);
|
||||
self.put_path(eid, index, shape).map(|painted| ((eid, index), painted))
|
||||
});
|
||||
match placed {
|
||||
Ok((at, painted)) => {
|
||||
// Placing a path is a new action: what was undone before can't be redone over it
|
||||
self.redo.clear();
|
||||
self.tool.path.editing = Some(at);
|
||||
self.changed_without_history(&base);
|
||||
self.path_draft = Some(PathDraft { base, painted });
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
self.doc = base;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remember the curve before a point change from a view, so undo steps back through those changes while the path is edited
|
||||
pub fn path_checkpoint(&mut self) {
|
||||
if !self.path_steps.0.last().is_some_and(|s| s.same_curve(&self.tool.path)) {
|
||||
self.path_steps.0.push(self.tool.path.clone());
|
||||
// Each snapshot can contain thousands of points; bound point history like document history
|
||||
let excess = self.path_steps.0.len().saturating_sub(crate::session::MAX_HISTORY);
|
||||
self.path_steps.0.drain(..excess);
|
||||
self.path_steps.1.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Select a point without changing its geometry or clearing redo
|
||||
pub fn select_path_point(&mut self, index: usize) {
|
||||
self.tool.path.selected = (index < self.tool.path.points.len()).then_some(index);
|
||||
}
|
||||
|
||||
/// Append and select a point, checkpointing the curve before it changes
|
||||
pub fn append_path_point(&mut self, point: Vec3, uv: bool) -> Option<usize> {
|
||||
if !point.is_finite() || (self.tool.path.uv == uv && self.tool.path.points.len() >= MAX_PATH_POINTS) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// A click in the other view must not replace a committed path's coordinate space
|
||||
if self.tool.path.editing.is_some() && self.path_draft.is_none() && self.tool.path.uv != uv {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.path_checkpoint();
|
||||
self.tool.path.push(point, uv);
|
||||
self.tool.path.selected = self.tool.path.points.len().checked_sub(1);
|
||||
self.tool.path.selected
|
||||
}
|
||||
|
||||
/// Insert and select a point as one undoable point edit
|
||||
pub fn insert_path_point(&mut self, index: usize, point: Vec3) -> Option<usize> {
|
||||
if !point.is_finite() || index > self.tool.path.points.len() || self.tool.path.points.len() >= MAX_PATH_POINTS {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.path_checkpoint();
|
||||
self.tool.path.insert(index, point)
|
||||
}
|
||||
|
||||
/// Move a point, checkpointing only the first actual movement in a drag
|
||||
pub fn move_path_point(&mut self, index: usize, point: Vec3, begin_drag: bool) -> bool {
|
||||
if !point.is_finite() || self.tool.path.points.get(index).is_none_or(|current| *current == point) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if begin_drag {
|
||||
self.path_checkpoint();
|
||||
}
|
||||
if let Some(current) = self.tool.path.points.get_mut(index) {
|
||||
*current = point;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Remove the selected point, or the last one, as one undoable point edit
|
||||
pub fn remove_selected_path_point(&mut self) {
|
||||
if self.tool.path.points.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.path_checkpoint();
|
||||
self.tool.path.remove_selected();
|
||||
}
|
||||
|
||||
/// Change whether the path loops back to its first point, with point undo
|
||||
pub fn set_path_closed(&mut self, closed: bool) {
|
||||
if self.tool.path.closed != closed {
|
||||
self.path_checkpoint();
|
||||
self.tool.path.closed = closed;
|
||||
}
|
||||
}
|
||||
|
||||
/// Change whether a closed path fills its interior, with point undo
|
||||
pub fn set_path_fill(&mut self, fill: bool) {
|
||||
if self.tool.path.fill != fill {
|
||||
self.path_checkpoint();
|
||||
self.tool.path.fill = fill;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether [`Session::step_path`] would undo (`back`) or redo a point change
|
||||
pub(crate) fn path_step_pending(&self, back: bool) -> bool {
|
||||
let steps = if back { &self.path_steps.0 } else { &self.path_steps.1 };
|
||||
self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path))
|
||||
}
|
||||
|
||||
/// Undo calls needed to move back through document history, including pending path operations.
|
||||
/// With zero document steps, only an uncommitted draft is canceled; stored edits stay applied.
|
||||
pub fn history_undo_steps(&self, document_steps: usize) -> usize {
|
||||
if document_steps == 0 && self.path_draft.is_none() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let (point_steps, clears_path) = self.path_steps_before_document(true);
|
||||
let cancel_draft = self.path_draft.is_some() && !clears_path;
|
||||
document_steps.saturating_add(point_steps).saturating_add(usize::from(cancel_draft))
|
||||
}
|
||||
|
||||
/// Redo calls needed to move forward through document history, including pending point edits.
|
||||
/// Unlike undo, document redo cancels any remaining draft in the same call.
|
||||
pub fn history_redo_steps(&self, document_steps: usize) -> usize {
|
||||
if document_steps == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
document_steps.saturating_add(self.path_steps_before_document(false).0)
|
||||
}
|
||||
|
||||
/// Count pending point steps and whether their last step clears the path
|
||||
fn path_steps_before_document(&self, back: bool) -> (usize, bool) {
|
||||
if self.tool.tool != Tool::Path {
|
||||
return (0, false);
|
||||
}
|
||||
|
||||
let states = if back { &self.path_steps.0 } else { &self.path_steps.1 };
|
||||
let mut steps = 0usize;
|
||||
let mut current = &self.tool.path;
|
||||
for state in states.iter().rev() {
|
||||
if state.same_curve(current) {
|
||||
continue;
|
||||
}
|
||||
|
||||
steps = steps.saturating_add(1);
|
||||
|
||||
// Restoring an empty curve cancels the draft and clears point history in the same step
|
||||
if state.points.is_empty() {
|
||||
return (steps, true);
|
||||
}
|
||||
|
||||
current = state;
|
||||
}
|
||||
|
||||
(steps, false)
|
||||
}
|
||||
|
||||
/// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history
|
||||
pub(crate) fn step_path(&mut self, back: bool) -> Result<bool> {
|
||||
if self.tool.tool != Tool::Path {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// Skip no-change checkpoints without consuming history until the repaint succeeds
|
||||
let from = if back { &self.path_steps.0 } else { &self.path_steps.1 };
|
||||
let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) };
|
||||
|
||||
let path = &mut self.tool.path;
|
||||
let previous = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state.clone() });
|
||||
if let Err(error) = self.path_live() {
|
||||
self.tool.path = previous;
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
if self.tool.path.points.is_empty() {
|
||||
self.stop_path_edit();
|
||||
} else {
|
||||
let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) };
|
||||
from.truncate(index);
|
||||
to.push(previous);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Apply a new path being placed (as Enter would) and end the edit of a stored one, e.g. before the active texture set changes
|
||||
pub fn finish_path(&mut self) -> Result<()> {
|
||||
if self.path_draft.is_some() {
|
||||
let viewport = self.viewport;
|
||||
self.commit_path(viewport)?;
|
||||
}
|
||||
self.stop_path_edit();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cancel the Path tool's path: a new one's preview is removed, a stored one keeps its applied changes
|
||||
pub fn cancel_path(&mut self) {
|
||||
self.stop_path_edit();
|
||||
self.tool.path.clear();
|
||||
}
|
||||
|
||||
/// Stop editing a stored path (its changes are already applied) and clear the tool; a new path's preview is removed
|
||||
pub fn stop_path_edit(&mut self) {
|
||||
if let Some(draft) = self.path_draft.take() {
|
||||
let preview = std::mem::replace(&mut self.doc, draft.base);
|
||||
self.changed_without_history(&preview);
|
||||
}
|
||||
if self.tool.path.editing.is_some() {
|
||||
self.tool.path.clear();
|
||||
}
|
||||
self.path_steps = Default::default();
|
||||
}
|
||||
|
||||
/// The selected path sublayer, or a new one on the selected layer's content or mask
|
||||
/// (whichever is selected).
|
||||
fn path_effect(&mut self) -> Result<LayerId> {
|
||||
@@ -348,6 +735,32 @@ impl Session {
|
||||
Ok(eid)
|
||||
}
|
||||
|
||||
/// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before
|
||||
fn repaint_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> {
|
||||
let before = self.doc.clone();
|
||||
let painted = match self.put_path(eid, index, shape) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
self.doc = before;
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
// Paths paint into the active set; a sublayer in another set recomposites in full
|
||||
let project = &self.doc.project;
|
||||
let set = project.effect(eid).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts);
|
||||
if set == Some(self.ts()) {
|
||||
// Content or mask, the sublayer's owner decides which sets redraw
|
||||
let tiles = changed_tiles(&before.pixels, &self.doc.pixels, eid);
|
||||
self.mark_painted(self.ts(), Some(PaintTarget::Layer(eid)), tiles);
|
||||
} else {
|
||||
self.invalidate_changed(&before);
|
||||
}
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.modified = true;
|
||||
Ok((painted, before))
|
||||
}
|
||||
|
||||
/// Replace path `index` of sublayer `eid` (append when out of range) and repaint the
|
||||
/// sublayer. Returns what painting that path reported, with the sublayer and index.
|
||||
fn put_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<Value> {
|
||||
@@ -423,13 +836,41 @@ impl Session {
|
||||
|
||||
fn paint_shape(&mut self, shape: &PathShape) -> Result<Value> {
|
||||
let paint = read_paint(shape)?;
|
||||
let (camera, viewport) = paint_view(shape, &paint);
|
||||
self.tool.brush = paint.brush;
|
||||
self.tool.values = paint.values;
|
||||
self.tool.enabled = paint.enabled;
|
||||
self.tool.mask_value = paint.mask_value;
|
||||
self.camera = paint.camera;
|
||||
self.camera = camera;
|
||||
self.tool.path = state_of(shape);
|
||||
self.paint_path(Vec2::from_array(shape.viewport).max(Vec2::splat(16.0)).min(Vec2::splat(16384.0)))
|
||||
self.paint_path(viewport)
|
||||
}
|
||||
|
||||
/// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`spline_segments`] (None off the mesh)
|
||||
pub fn path_surface(&self, points: &[Vec3], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec<Vec<Option<Vec3>>> {
|
||||
let aspect = viewport.x.max(1.0) / viewport.y.max(1.0);
|
||||
let Some(screen) = points.iter().map(|p| camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect::<Option<Vec<_>>>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &camera, viewport };
|
||||
spline_segments(&screen, closed, SURFACE_STEP_PX)
|
||||
.into_iter()
|
||||
.zip(&screen)
|
||||
.map(|(samples, first)| std::iter::once(*first).chain(samples).map(|q| pick(&ctx, q).map(|hit| hit.pos)).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// [`Session::path_surface`] of a stored 3D path through the camera and viewport it paints with
|
||||
pub fn stored_path_surface(&self, eid: LayerId, index: usize) -> Option<Vec<Vec<Option<Vec3>>>> {
|
||||
let shape = self.paths(eid)?.get(index)?;
|
||||
if shape.uv {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (camera, viewport) = paint_view(shape, &read_paint(shape).ok()?);
|
||||
let path = state_of(shape);
|
||||
Some(self.path_surface(&path.points, path.closed, camera, viewport))
|
||||
}
|
||||
|
||||
/// Paint the Path tool's curve with the current brush (or fill it when closed and filled)
|
||||
@@ -548,6 +989,7 @@ impl Session {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{Session, execute};
|
||||
@@ -584,4 +1026,94 @@ mod tests {
|
||||
assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path");
|
||||
assert!(!cached.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_insertion_and_removal_respect_boundaries() {
|
||||
let mut path = PathState { points: vec![Vec3::ZERO, Vec3::X], ..Default::default() };
|
||||
|
||||
assert_eq!(path.insert(2, Vec3::Y), Some(2));
|
||||
assert_eq!(path.points, vec![Vec3::ZERO, Vec3::X, Vec3::Y]);
|
||||
assert_eq!(path.insert(4, Vec3::Z), None);
|
||||
path.closed = true;
|
||||
path.selected = Some(usize::MAX);
|
||||
path.remove_selected();
|
||||
assert_eq!(path.points, vec![Vec3::ZERO, Vec3::X]);
|
||||
assert!(!path.closed);
|
||||
path.remove_selected();
|
||||
path.remove_selected();
|
||||
path.remove_selected();
|
||||
assert!(path.points.is_empty());
|
||||
assert_eq!(path.selected, None);
|
||||
|
||||
path.points = vec![Vec3::ZERO; MAX_PATH_POINTS];
|
||||
assert_eq!(path.insert(MAX_PATH_POINTS, Vec3::X), None);
|
||||
assert_eq!(path.points.len(), MAX_PATH_POINTS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_tiles_include_mask_and_channel_creation_and_deletion() {
|
||||
let effect = LayerId(7);
|
||||
let mut before = PixelStore::default();
|
||||
let mut image = TileImage::new(192, 128, 1);
|
||||
image.tile_mut(0, 0, &[1]).unwrap();
|
||||
before.masks.insert(effect, image.clone());
|
||||
before.layers.insert((effect, Channel::Roughness), image.clone());
|
||||
let mut after = before.clone();
|
||||
after.masks.get_mut(&effect).unwrap().set_tile(0, 0, None);
|
||||
after.masks.get_mut(&effect).unwrap().tile_mut(2, 1, &[1]).unwrap();
|
||||
after.layers.remove(&(effect, Channel::Roughness));
|
||||
image.set_tile(0, 0, None);
|
||||
image.tile_mut(1, 0, &[1]).unwrap();
|
||||
after.layers.insert((effect, Channel::Metallic), image);
|
||||
|
||||
assert_eq!(changed_tiles(&before, &before.clone(), effect), BTreeSet::new());
|
||||
assert_eq!(changed_tiles(&before, &after, effect), BTreeSet::from([(0, 0), (1, 0), (2, 1)]));
|
||||
assert_eq!(changed_tiles(&before, &after, LayerId(8)), BTreeSet::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_checkpoints_skip_noops_and_bound_retained_points() {
|
||||
let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap();
|
||||
session.tool.tool = Tool::Path;
|
||||
session.tool.path.points = vec![Vec3::ZERO; MAX_PATH_POINTS];
|
||||
session.path_checkpoint();
|
||||
assert!(!session.path_step_pending(true));
|
||||
assert!(!session.step_path(true).unwrap());
|
||||
|
||||
for index in 0..crate::session::MAX_HISTORY + 10 {
|
||||
session.path_checkpoint();
|
||||
session.tool.path.points[0].x = index as f32 + 1.0;
|
||||
}
|
||||
|
||||
assert_eq!(session.path_steps.0.len(), crate::session::MAX_HISTORY);
|
||||
assert_eq!(session.path_steps.0.iter().map(|state| state.points.len()).sum::<usize>(), crate::session::MAX_HISTORY * MAX_PATH_POINTS);
|
||||
session.path_checkpoint();
|
||||
assert!(session.step_path(true).unwrap(), "a no-change checkpoint does not consume an undo");
|
||||
assert_eq!(session.tool.path.points[0].x, (crate::session::MAX_HISTORY + 9) as f32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_surface_uses_bounded_viewports_and_skips_uv_paths() {
|
||||
let mut session = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap();
|
||||
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap();
|
||||
let StackTarget::Effect(effect) = session.target else { panic!("path sublayer") };
|
||||
assert!(session.stored_path_surface(effect, 0).is_none());
|
||||
let shape = session.paths(effect).unwrap()[0].clone();
|
||||
let paint = read_paint(&shape).unwrap();
|
||||
let mut shape = shape;
|
||||
shape.viewport = [-1.0, f32::MAX];
|
||||
assert_eq!(paint_view(&shape, &paint).1, Vec2::new(MIN_PAINT_VIEWPORT_PX, MAX_PAINT_VIEWPORT_PX));
|
||||
|
||||
let points = [Vec3::new(-0.2, 0.0, 1.0), Vec3::new(0.0, 0.2, 1.0), Vec3::new(0.2, 0.0, 1.0)];
|
||||
session.camera.yaw = 0.0;
|
||||
session.camera.pitch = 0.0;
|
||||
let surface = session.path_surface(&points, true, session.camera, Vec2::splat(400.0));
|
||||
assert_eq!(surface.len(), 3);
|
||||
let first = surface.first().unwrap().first().unwrap().unwrap();
|
||||
let last = surface.last().unwrap().last().unwrap().unwrap();
|
||||
assert!(first.distance(last) < 1e-5, "the closed curve returns to its starting surface point");
|
||||
let off_mesh = session.path_surface(&[Vec3::new(10.0, 0.0, 0.0), Vec3::new(11.0, 0.0, 0.0)], false, session.camera, Vec2::splat(400.0));
|
||||
assert!(!off_mesh.is_empty());
|
||||
assert!(off_mesh.iter().flatten().all(Option::is_none));
|
||||
}
|
||||
}
|
||||
@@ -356,6 +356,10 @@ pub struct Session {
|
||||
pub(crate) painting_paths: bool,
|
||||
/// Pixels of the paths below the one being edited, so live edits skip repainting them.
|
||||
pub(crate) path_cache: Option<crate::path_tool::PathCache>,
|
||||
/// A new path's live preview: the path becomes an undo step only when it is applied
|
||||
pub(crate) path_draft: Option<crate::path_draft::PathDraft>,
|
||||
/// Point changes of the path being edited: (earlier states for undo, undone states for redo)
|
||||
pub(crate) path_steps: (Vec<crate::path_tool::PathState>, Vec<crate::path_tool::PathState>),
|
||||
pub path: Option<String>,
|
||||
pub modified: bool,
|
||||
/// Bumps on every document change.
|
||||
@@ -374,8 +378,7 @@ pub struct Session {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// A session for `project` on `mesh` (texture sets must reference mesh materials). The
|
||||
/// UVs of UV-tiled sets are mapped into their tile atlas (see [`Session::source_mesh`]).
|
||||
/// A session for `project` on `mesh` (its sets must reference mesh materials), with UV-tiled sets' UVs mapped into their atlas ([`Session::source_mesh`])
|
||||
pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec<u8>)>) -> Result<Session> {
|
||||
mesh.validate().map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let source = Arc::new(mesh);
|
||||
@@ -413,6 +416,8 @@ impl Session {
|
||||
quick_mask: Default::default(),
|
||||
painting_paths: false,
|
||||
path_cache: None,
|
||||
path_draft: None,
|
||||
path_steps: Default::default(),
|
||||
path: None,
|
||||
modified: false,
|
||||
revision: 1,
|
||||
@@ -529,21 +534,43 @@ impl Session {
|
||||
self.record(label, before, false);
|
||||
}
|
||||
|
||||
/// A change from `before` to the current document: a new undo step `label`, or with
|
||||
/// `merge` part of the previous one when it has the same label.
|
||||
/// A change from `before`: a new undo step `label`, or with `merge` part of the previous one when it has the same label
|
||||
fn record(&mut self, label: &str, before: Document, merge: bool) {
|
||||
self.invalidate_changed(&before);
|
||||
self.push_step(label, before, merge);
|
||||
}
|
||||
|
||||
/// [`Session::record`] for a change whose tiles the caller already marked for recompositing
|
||||
pub(crate) fn push_step(&mut self, label: &str, before: Document, merge: bool) {
|
||||
// Another change during a new path's preview makes the path its own step first
|
||||
if !self.painting_paths
|
||||
&& let Some(draft) = self.path_draft.take()
|
||||
{
|
||||
self.undo.push((crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base));
|
||||
}
|
||||
|
||||
// Point changes of an edited path undo only until another step lands
|
||||
if !self.painting_paths {
|
||||
self.path_steps = Default::default();
|
||||
}
|
||||
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.invalidate_changed(&before);
|
||||
if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) {
|
||||
self.undo.push((label.to_string(), before));
|
||||
if self.undo.len() > MAX_HISTORY {
|
||||
self.undo.remove(0);
|
||||
}
|
||||
}
|
||||
let over = self.undo.len().saturating_sub(MAX_HISTORY);
|
||||
self.undo.drain(..over);
|
||||
self.redo.clear();
|
||||
}
|
||||
|
||||
/// A change from `other` to the current document that is not an undo step (a path preview)
|
||||
pub(crate) fn changed_without_history(&mut self, other: &Document) {
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.invalidate_changed(other);
|
||||
}
|
||||
|
||||
/// Mark dirty every texture set whose composite differs between `other` and the current
|
||||
/// document (after an edit, undo or redo).
|
||||
pub(crate) fn invalidate_changed(&mut self, other: &Document) {
|
||||
@@ -620,18 +647,32 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a point edit, an uncommitted path preview, or a document edit can be undone
|
||||
pub fn can_undo(&self) -> bool {
|
||||
!self.undo.is_empty()
|
||||
!self.undo.is_empty() || self.path_draft.is_some() || self.path_step_pending(true)
|
||||
}
|
||||
|
||||
/// Whether a point edit or document edit can be restored
|
||||
pub fn can_redo(&self) -> bool {
|
||||
!self.redo.is_empty()
|
||||
!self.redo.is_empty() || self.path_step_pending(false)
|
||||
}
|
||||
|
||||
/// Label of the next undo action, giving an active path's point edits and preview priority
|
||||
pub fn undo_label(&self) -> Option<&str> {
|
||||
if self.path_draft.is_some() || self.path_step_pending(true) {
|
||||
return Some(crate::path_tool::NEW_PATH_LABEL);
|
||||
}
|
||||
self.undo.last().map(|(l, _)| l.as_str())
|
||||
}
|
||||
|
||||
/// Label of the next redo action, giving an active path's point history priority
|
||||
pub fn redo_label(&self) -> Option<&str> {
|
||||
if self.path_step_pending(false) {
|
||||
return Some(crate::path_tool::NEW_PATH_LABEL);
|
||||
}
|
||||
self.redo.last().map(|(l, _)| l.as_str())
|
||||
}
|
||||
|
||||
/// The undone steps, the next one to redo first.
|
||||
pub fn redo_labels(&self) -> Vec<String> {
|
||||
self.redo.iter().rev().map(|(l, _)| l.clone()).collect()
|
||||
@@ -640,10 +681,23 @@ impl Session {
|
||||
self.undo.iter().map(|(l, _)| l.clone()).collect()
|
||||
}
|
||||
|
||||
/// Undo a point edit, cancel an uncommitted path, or restore a document snapshot, in that order
|
||||
pub fn undo(&mut self) -> Result<String> {
|
||||
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
|
||||
self.cancel_stroke();
|
||||
self.end_polygon_fill_box();
|
||||
|
||||
// While a path is edited, undo steps back through its point changes first
|
||||
if self.step_path(true)? {
|
||||
return Ok(crate::path_tool::NEW_PATH_LABEL.to_string());
|
||||
}
|
||||
|
||||
// A path being placed isn't a step yet: undo removes it
|
||||
if self.path_draft.is_some() {
|
||||
self.stop_path_edit();
|
||||
return Ok(crate::path_tool::NEW_PATH_LABEL.to_string());
|
||||
}
|
||||
|
||||
self.stop_path_edit();
|
||||
|
||||
let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
|
||||
@@ -654,10 +708,16 @@ impl Session {
|
||||
Ok(label)
|
||||
}
|
||||
|
||||
/// Restore a point edit and its pixels before considering document redo
|
||||
pub fn redo(&mut self) -> Result<String> {
|
||||
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
|
||||
self.cancel_stroke();
|
||||
self.end_polygon_fill_box();
|
||||
|
||||
if self.step_path(false)? {
|
||||
return Ok(crate::path_tool::NEW_PATH_LABEL.to_string());
|
||||
}
|
||||
|
||||
self.stop_path_edit();
|
||||
|
||||
let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
|
||||
|
||||
@@ -79,16 +79,23 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|index| index as usize)
|
||||
.filter(|index| *index < s.set_count())
|
||||
.ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?;
|
||||
select_set(s, ts);
|
||||
select_set(s, ts)?;
|
||||
Ok(json!({ "ts": ts }))
|
||||
}
|
||||
|
||||
/// Make texture set `ts` the active one, on its content stack
|
||||
pub(crate) fn select_set(s: &mut Session, ts: usize) {
|
||||
pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> {
|
||||
s.cancel_stroke();
|
||||
|
||||
// Paths paint into the active set
|
||||
if ts != s.ts() {
|
||||
s.finish_path()?;
|
||||
}
|
||||
|
||||
s.active_set = ts;
|
||||
s.target = StackTarget::Content;
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -17,6 +17,7 @@ mod materialx;
|
||||
mod materialx_import;
|
||||
mod meshmap_import;
|
||||
mod painter_gaps;
|
||||
mod path_perf;
|
||||
mod path_tool;
|
||||
mod perf;
|
||||
mod polygon_fill;
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Path preview timings and a repeatable memory soak (release, --ignored --nocapture).
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::execute;
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
|
||||
/// Sort a nonempty timing sample in place and report its middle value in milliseconds
|
||||
fn median_ms(samples: &mut [Duration]) -> f64 {
|
||||
samples.sort_unstable();
|
||||
samples[samples.len() / 2].as_secs_f64() * 1_000.0
|
||||
}
|
||||
|
||||
/// Separate repaint cost from dirty-tile and full-set compositing across representative brush sizes
|
||||
#[test]
|
||||
#[ignore = "release benchmark: two texture resolutions and brush sizes"]
|
||||
fn path_preview_timings() {
|
||||
for resolution in [2048, 4096] {
|
||||
let mut session = texturecraft_engine::sample_session(resolution, 64).unwrap();
|
||||
session.viewport = Vec2::splat(400.0);
|
||||
session.camera.yaw = 0.0;
|
||||
session.camera.pitch = 0.0;
|
||||
session.update();
|
||||
for size in [4, 20] {
|
||||
execute(&mut session, "tool.brush", &json!({"size": size})).unwrap();
|
||||
execute(&mut session, "tool.path", &json!({"points": [[150, 210], [175, 180], [200, 210], [225, 180], [250, 210]]})).unwrap();
|
||||
session.update();
|
||||
let original = session.tool.path.points[2];
|
||||
let (mut paint, mut composite, mut full) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let mut dirty_tiles = Vec::new();
|
||||
|
||||
for step in 0..20 {
|
||||
let point = original + texturecraft_engine::geom::glam::Vec3::Y * (step as f32 + 1.0) * 0.001;
|
||||
assert!(session.move_path_point(2, point, step == 0));
|
||||
let started = Instant::now();
|
||||
assert!(session.path_live().unwrap());
|
||||
paint.push(started.elapsed());
|
||||
dirty_tiles.push(session.pending_tiles());
|
||||
let started = Instant::now();
|
||||
session.update();
|
||||
composite.push(started.elapsed());
|
||||
// The same document with full invalidation isolates the compositor saving
|
||||
if step < 3 {
|
||||
for cache in &mut session.caches {
|
||||
cache.invalidate_all();
|
||||
}
|
||||
let started = Instant::now();
|
||||
session.update();
|
||||
full.push(started.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
println!(
|
||||
"path {resolution}px brush={size}: paint {:.2} ms, dirty composite {:.2} ms, full composite {:.2} ms; dirty tiles {:?}",
|
||||
median_ms(&mut paint),
|
||||
median_ms(&mut composite),
|
||||
median_ms(&mut full),
|
||||
dirty_tiles
|
||||
);
|
||||
session.cancel_path();
|
||||
session.update();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observe resident memory without treating allocator-retained pages as a leak
|
||||
#[cfg(target_os = "linux")]
|
||||
fn resident_kib() -> usize {
|
||||
let status = std::fs::read_to_string("/proc/self/status").unwrap();
|
||||
status.lines().find_map(|line| line.strip_prefix("VmRSS:").and_then(|rest| rest.split_whitespace().next()).and_then(|n| n.parse().ok())).unwrap()
|
||||
}
|
||||
|
||||
/// Check that repeated canceled previews release tile buffers and leave no document history
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
#[ignore = "release memory soak: 1,000 edits across 100 canceled previews"]
|
||||
fn path_preview_memory_soak() {
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
|
||||
let mut session = Session::new_project("Path soak", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 512).unwrap();
|
||||
session.viewport = Vec2::splat(400.0);
|
||||
session.update();
|
||||
let history = session.history_labels().len();
|
||||
let mut resident = Vec::new();
|
||||
|
||||
for cycle in 0..100 {
|
||||
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.35, 0.45], [0.5, 0.5], [0.65, 0.45], [0.8, 0.5]]})).unwrap();
|
||||
for step in 0..10 {
|
||||
let point = texturecraft_engine::geom::glam::Vec3::new(0.5, 0.5 + (step as f32 + 1.0) * 0.002, 0.0);
|
||||
session.move_path_point(2, point, true);
|
||||
assert!(session.path_live().unwrap());
|
||||
session.update();
|
||||
}
|
||||
let preview_tiles: Vec<_> = session
|
||||
.doc
|
||||
.pixels
|
||||
.layers
|
||||
.values()
|
||||
.flat_map(|image| image.allocated().map(|(x, y)| std::sync::Arc::downgrade(image.tile_handle(x, y).unwrap())))
|
||||
.collect();
|
||||
assert!(!preview_tiles.is_empty());
|
||||
session.cancel_path();
|
||||
session.update();
|
||||
assert!(preview_tiles.iter().all(|tile| tile.upgrade().is_none()), "canceled previews release their painted tile buffers");
|
||||
assert_eq!(session.history_labels().len(), history, "canceled previews retain no document history");
|
||||
if (cycle + 1) % 10 == 0 {
|
||||
resident.push(resident_kib());
|
||||
}
|
||||
}
|
||||
|
||||
println!("path soak VmRSS KiB after each 100 edits: {resident:?}");
|
||||
// RSS is an observation, not a portable leak assertion: allocators can retain freed pages
|
||||
}
|
||||
@@ -37,7 +37,7 @@ fn path_stroke_paints_along_the_curve() {
|
||||
let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap();
|
||||
assert_eq!(r["points"], 3);
|
||||
assert_eq!(s.tool.tool, texturecraft_engine::Tool::Path);
|
||||
assert!(!red_at(&s, 200.0, 180.0), "nothing painted before commit");
|
||||
assert!(red_at(&s, 200.0, 180.0), "the path is previewed before it is applied");
|
||||
let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap();
|
||||
assert!(r["committed"]["stamps"].as_u64().unwrap() > 10, "{r}");
|
||||
assert_eq!(r["points"], 0, "commit clears the path");
|
||||
@@ -46,11 +46,11 @@ fn path_stroke_paints_along_the_curve() {
|
||||
}
|
||||
assert!(!red_at(&s, 200.0, 240.0), "below the curve");
|
||||
assert!(!red_at(&s, 200.0, 130.0), "above the curve");
|
||||
// One undo step.
|
||||
// One undo step
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
s.update();
|
||||
assert!(!red_at(&s, 200.0, 180.0));
|
||||
// Errors: no points, points off the mesh.
|
||||
// Errors: no points, points off the mesh
|
||||
assert!(execute(&mut s, "tool.path", &json!({"commit": true})).is_err());
|
||||
assert!(execute(&mut s, "tool.path", &json!({"points": [[2, 2]]})).is_err());
|
||||
}
|
||||
@@ -278,3 +278,434 @@ fn each_path_and_each_edit_of_one_is_its_own_undo_step() {
|
||||
s.update();
|
||||
assert!(red_at(&s, 200.0, 230.0), "undo brings back the first edit");
|
||||
}
|
||||
|
||||
/// The pixels of every path sublayer of the selected layer, comparable
|
||||
fn path_pixels(s: &Session) -> Vec<String> {
|
||||
let ids: Vec<u64> = path_sublayers(s).into_iter().map(|(id, _)| id).collect();
|
||||
let mut v: Vec<String> = s.doc.pixels.layers.iter().filter(|((id, _), _)| ids.contains(&id.0)).map(|(k, img)| format!("{k:?}{img:?}")).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_points_previews_the_path_with_no_undo_step_until_it_is_applied() {
|
||||
let points = json!([[140, 210], [200, 180], [260, 210]]);
|
||||
let mut direct = session(primitives::sphere(1.0, 48, 24));
|
||||
execute(&mut direct, "tool.path", &json!({"points": points, "commit": true})).unwrap();
|
||||
|
||||
let mut s = session(primitives::sphere(1.0, 48, 24));
|
||||
let start = s.history_labels();
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 280], [260, 280]]})).unwrap();
|
||||
assert!(red_at(&s, 200.0, 280.0));
|
||||
execute(&mut s, "tool.path", &json!({"points": points})).unwrap();
|
||||
assert!(red_at(&s, 200.0, 180.0) && !red_at(&s, 200.0, 280.0), "the preview follows the points");
|
||||
assert_eq!(s.history_labels(), start, "no undo step while placing");
|
||||
execute(&mut s, "tool.path", &json!({"commit": true})).unwrap();
|
||||
assert_eq!(s.history_labels().len(), start.len() + 1, "applying is one undo step");
|
||||
assert_eq!(s.undo_label(), Some("Path"));
|
||||
assert_eq!(path_pixels(&s), path_pixels(&direct), "the same pixels as applying without a preview");
|
||||
|
||||
// Cancelling removes the preview
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap();
|
||||
assert!(red_at(&s, 200.0, 250.0));
|
||||
execute(&mut s, "tool.path", &json!({"clear": true})).unwrap();
|
||||
s.update();
|
||||
assert!(!red_at(&s, 200.0, 250.0) && red_at(&s, 200.0, 180.0));
|
||||
assert_eq!(s.history_labels().len(), start.len() + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_while_placing_removes_the_preview_only() {
|
||||
let mut s = session(primitives::sphere(1.0, 48, 24));
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
|
||||
let steps = s.history_labels().len();
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap();
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
s.update();
|
||||
assert!(!red_at(&s, 200.0, 250.0), "the preview is gone");
|
||||
assert!(red_at(&s, 200.0, 180.0), "the applied path stays");
|
||||
assert_eq!(s.history_labels().len(), steps);
|
||||
assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_change_while_placing_makes_the_path_its_own_step_first() {
|
||||
let mut s = session(primitives::sphere(1.0, 48, 24));
|
||||
let steps = s.history_labels().len();
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap();
|
||||
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
|
||||
let labels = s.history_labels();
|
||||
assert_eq!(labels.len(), steps + 2);
|
||||
assert_eq!(labels.get(steps).map(String::as_str), Some("Path"));
|
||||
// Undoing the other change keeps the path; undoing again removes it
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
s.update();
|
||||
assert!(red_at(&s, 200.0, 180.0));
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
s.update();
|
||||
assert!(!red_at(&s, 200.0, 180.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_another_path_while_placing_applies_the_new_one() {
|
||||
let mut s = session(primitives::sphere(1.0, 48, 24));
|
||||
let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
|
||||
let eid = r["committed"]["effect"].as_u64().unwrap();
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap();
|
||||
execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap();
|
||||
assert_eq!(path_sublayers(&s), vec![(eid, 2)], "the new path was applied");
|
||||
assert_eq!(s.undo_label(), Some("Path"));
|
||||
assert_eq!(s.tool.path.editing, Some((texturecraft_engine::core::LayerId(eid), 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_next_path_starts_open_after_a_closed_one() {
|
||||
let mut s = session(primitives::sphere(1.0, 48, 24));
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "closed": true, "commit": true})).unwrap();
|
||||
assert!(!s.tool.path.closed, "applying a closed path leaves the tool open for the next one");
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]], "closed": true})).unwrap();
|
||||
execute(&mut s, "tool.path", &json!({"clear": true})).unwrap();
|
||||
assert!(!s.tool.path.closed, "cancelling does too");
|
||||
}
|
||||
|
||||
/// A short path's repaint marks under 1/N of a 1024-texel set's 256 tiles
|
||||
const SHORT_PATH_TILE_SHARE_DIVISOR: usize = 4;
|
||||
|
||||
/// Move the middle point of the Path tool's curve down to viewport row `y` and repaint, returning the (dirty, all) tile counts
|
||||
fn move_middle_point(s: &mut Session, y: f32) -> (usize, usize) {
|
||||
s.tool.path.points[1] = s.pick(Vec2::new(200.0, y), s.viewport).unwrap().pos;
|
||||
assert!(s.path_live().unwrap());
|
||||
(s.caches[0].dirty.len(), s.caches[0].covered_tiles.len())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_a_point_recomposites_only_the_paths_tiles() {
|
||||
// 1024 texels: 256 tiles, so a short path covers few of them
|
||||
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:test", None, 1024).unwrap();
|
||||
s.viewport = Vec2::new(400.0, 400.0);
|
||||
(s.camera.yaw, s.camera.pitch) = (0.0, 0.0);
|
||||
execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap();
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap();
|
||||
s.update();
|
||||
|
||||
let (dirty, all) = move_middle_point(&mut s, 190.0);
|
||||
assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "a new path: {dirty} of {all} tiles to recomposite");
|
||||
s.update();
|
||||
|
||||
let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap();
|
||||
execute(&mut s, "path.edit", &json!({"effect": r["committed"]["effect"], "index": 0})).unwrap();
|
||||
s.update();
|
||||
// Another row than the applied one, so the edit changes the path
|
||||
let (dirty, all) = move_middle_point(&mut s, 200.0);
|
||||
assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "an applied path being edited: {dirty} of {all} tiles to recomposite");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_change_ends_the_point_undo_of_an_edited_path() {
|
||||
let mut s = session(primitives::sphere(1.0, 48, 24));
|
||||
let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
|
||||
let eid = texturecraft_engine::core::LayerId(r["committed"]["effect"].as_u64().unwrap());
|
||||
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 0})).unwrap();
|
||||
s.path_checkpoint();
|
||||
s.tool.path.points[1] = s.pick(Vec2::new(200.0, 230.0), s.viewport).unwrap().pos;
|
||||
assert!(s.path_live().unwrap());
|
||||
let moved: Vec<[f32; 3]> = s.tool.path.points.iter().map(|p| p.to_array()).collect();
|
||||
let layers = s.doc.project.layers.len();
|
||||
|
||||
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(s.doc.project.layers.len(), layers, "undo removes the new layer");
|
||||
assert_eq!(s.paths(eid).unwrap()[0].points, moved, "the path keeps its moved point");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_a_path_ends_redo() {
|
||||
let mut s = session(primitives::sphere(1.0, 48, 24));
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert!(s.can_redo());
|
||||
execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap();
|
||||
assert!(!s.can_redo(), "redo would throw the path being placed away");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_texture_sets_applies_the_path_being_placed() {
|
||||
let mut s = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
|
||||
let steps = s.history_labels().len();
|
||||
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.45], [0.8, 0.5]]})).unwrap();
|
||||
|
||||
execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap();
|
||||
assert_eq!(s.history_labels().len(), steps + 1);
|
||||
assert_eq!(s.undo_label(), Some("Path"));
|
||||
assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none(), "the path no longer paints into the other set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applying_after_orbit_preserves_preview_pixels_and_storage() {
|
||||
let mut session = session(primitives::sphere(1.0, 48, 24));
|
||||
execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap();
|
||||
let preview = session.doc.clone();
|
||||
let steps = session.history_labels().len();
|
||||
session.camera.yaw += 0.6;
|
||||
session.viewport = Vec2::new(600.0, 400.0);
|
||||
assert!(!session.path_live().unwrap());
|
||||
|
||||
execute(&mut session, "tool.path", &json!({"commit": true})).unwrap();
|
||||
|
||||
assert_eq!(session.doc.project, preview.project, "apply must keep the preview's camera and viewport");
|
||||
assert_eq!(session.doc.pixels.layers, preview.pixels.layers, "apply must keep the preview pixels");
|
||||
for (key, image) in &preview.pixels.layers {
|
||||
for (x, y) in image.allocated() {
|
||||
assert!(std::sync::Arc::ptr_eq(image.tile_handle(x, y).unwrap(), session.doc.pixels.layers[key].tile_handle(x, y).unwrap()));
|
||||
}
|
||||
}
|
||||
assert_eq!(session.history_labels().len(), steps + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applying_an_unchanged_stored_path_after_orbit_adds_no_history() {
|
||||
let mut session = session(primitives::sphere(1.0, 48, 24));
|
||||
let report = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
|
||||
execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap();
|
||||
let before = session.doc.clone();
|
||||
let history = session.history_labels();
|
||||
session.camera.yaw += 0.6;
|
||||
assert!(!session.path_live().unwrap());
|
||||
|
||||
execute(&mut session, "tool.path", &json!({"commit": true})).unwrap();
|
||||
|
||||
assert_eq!(session.history_labels(), history, "accepting an unchanged path is not an edit");
|
||||
assert_eq!(session.doc.project, before.project);
|
||||
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
|
||||
assert!(session.tool.path.editing.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_final_preview_point_removes_its_pixels() {
|
||||
let mut session = session(wall());
|
||||
let before = session.doc.clone();
|
||||
let history = session.history_labels();
|
||||
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.5, 0.5]]})).unwrap();
|
||||
assert!(!path_sublayers(&session).is_empty());
|
||||
|
||||
session.path_checkpoint();
|
||||
session.tool.path.remove_selected();
|
||||
assert!(session.path_live().unwrap());
|
||||
session.update();
|
||||
|
||||
assert_eq!(session.doc.project, before.project);
|
||||
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
assert!(session.tool.path.editing.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_uses_the_commands_explicit_viewport() {
|
||||
let mut session = session(primitives::sphere(1.0, 48, 24));
|
||||
let params = json!({"points": [[170, 210], [200, 180], [230, 210]], "viewport": [400, 600]});
|
||||
execute(&mut session, "tool.path", ¶ms).unwrap();
|
||||
let preview = path_pixels(&session);
|
||||
let (effect, index) = session.tool.path.editing.unwrap();
|
||||
|
||||
let mut direct = self::session(primitives::sphere(1.0, 48, 24));
|
||||
let mut params = params;
|
||||
params["commit"] = json!(true);
|
||||
execute(&mut direct, "tool.path", ¶ms).unwrap();
|
||||
|
||||
assert_eq!(session.paths(effect).unwrap()[index].viewport, [400.0, 600.0]);
|
||||
assert_eq!(preview, path_pixels(&direct));
|
||||
}
|
||||
|
||||
/// An opposite-view placement must preserve the stored curve, painted pixels and point redo
|
||||
#[test]
|
||||
fn stored_paths_ignore_point_placement_from_the_other_view() {
|
||||
for uv in [false, true] {
|
||||
let mut session = session(wall());
|
||||
let params =
|
||||
if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true}) } else { json!({"points": [[140, 210], [260, 210]], "commit": true}) };
|
||||
let report = execute(&mut session, "tool.path", ¶ms).unwrap();
|
||||
execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap();
|
||||
let (effect, index) = session.tool.path.editing.unwrap();
|
||||
let uv_point = Vec3::new(0.5, 0.6, 0.0);
|
||||
let world_point = session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos;
|
||||
assert_eq!(session.append_path_point(if uv { uv_point } else { world_point }, uv), Some(2));
|
||||
session.path_live().unwrap();
|
||||
let extended = session.tool.path.points.clone();
|
||||
session.undo().unwrap();
|
||||
let before = session.doc.clone();
|
||||
let path = session.tool.path.clone();
|
||||
let history = session.history_labels();
|
||||
|
||||
let placed = session.append_path_point(if uv { world_point } else { uv_point }, !uv);
|
||||
session.path_live().unwrap();
|
||||
|
||||
assert_eq!(session.paths(effect).unwrap()[index].uv, uv, "the stored path must keep its coordinate space");
|
||||
assert_eq!(placed, None);
|
||||
assert_eq!(session.tool.path, path);
|
||||
assert_eq!(session.doc.project, before.project);
|
||||
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
|
||||
assert_eq!(session.doc.pixels.masks, before.pixels.masks);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
assert!(session.can_redo(), "ignored placement must preserve point redo");
|
||||
|
||||
session.redo().unwrap();
|
||||
assert_eq!(session.tool.path.points, extended);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new, uncommitted curve can still switch views and cancel without changing the document
|
||||
#[test]
|
||||
fn draft_paths_can_switch_to_the_other_view() {
|
||||
for uv in [false, true] {
|
||||
let mut session = session(wall());
|
||||
let before = session.doc.clone();
|
||||
let history = session.history_labels();
|
||||
let params = if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]}) } else { json!({"points": [[140, 210], [260, 210]]}) };
|
||||
execute(&mut session, "tool.path", ¶ms).unwrap();
|
||||
let point = if uv { session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos } else { Vec3::new(0.5, 0.6, 0.0) };
|
||||
|
||||
assert_eq!(session.append_path_point(point, !uv), Some(0));
|
||||
session.path_live().unwrap();
|
||||
|
||||
assert_eq!(session.tool.path.points, vec![point]);
|
||||
assert_eq!(session.tool.path.uv, !uv);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
session.cancel_path();
|
||||
assert_eq!(session.doc.project, before.project);
|
||||
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
|
||||
}
|
||||
}
|
||||
|
||||
/// Headless history commands must restore geometry and pixels before any frame or subsequent edit
|
||||
#[test]
|
||||
fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() {
|
||||
let mut session = session(wall());
|
||||
let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap();
|
||||
let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap());
|
||||
execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
|
||||
let original = session.tool.path.points.clone();
|
||||
let original_pixels = session.doc.pixels.clone();
|
||||
let history = session.history_labels().len();
|
||||
session.insert_path_point(1, Vec3::new(0.5, 0.5, 0.0));
|
||||
session.path_live().unwrap();
|
||||
let inserted = session.tool.path.points.clone();
|
||||
let inserted_pixels = session.doc.pixels.clone();
|
||||
session.move_path_point(1, Vec3::new(0.5, 0.6, 0.0), true);
|
||||
session.move_path_point(1, Vec3::new(0.5, 0.7, 0.0), false);
|
||||
session.path_live().unwrap();
|
||||
let moved = session.tool.path.points.clone();
|
||||
let moved_pixels = session.doc.pixels.clone();
|
||||
session.remove_selected_path_point();
|
||||
session.path_live().unwrap();
|
||||
let removed = session.tool.path.points.clone();
|
||||
let removed_pixels = session.doc.pixels.clone();
|
||||
|
||||
for (expected, pixels) in [(&moved, &moved_pixels), (&inserted, &inserted_pixels), (&original, &original_pixels)] {
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(&session.tool.path.points, expected);
|
||||
assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::<Vec<_>>());
|
||||
assert_eq!(session.doc.pixels.layers, pixels.layers);
|
||||
assert_eq!(session.doc.pixels.masks, pixels.masks);
|
||||
}
|
||||
|
||||
session.select_path_point(0);
|
||||
assert!(session.can_redo(), "selection must preserve point redo");
|
||||
for (expected, pixels) in [(&inserted, &inserted_pixels), (&moved, &moved_pixels), (&removed, &removed_pixels)] {
|
||||
execute(&mut session, "edit.redo", &Value::Null).unwrap();
|
||||
assert_eq!(&session.tool.path.points, expected);
|
||||
assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::<Vec<_>>());
|
||||
assert_eq!(session.doc.pixels.layers, pixels.layers);
|
||||
assert_eq!(session.doc.pixels.masks, pixels.masks);
|
||||
}
|
||||
assert_eq!(session.history_labels().len(), history + 1, "all point edits share one document step");
|
||||
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(session.paths(effect).unwrap()[0].points, moved.iter().map(|point| point.to_array()).collect::<Vec<_>>());
|
||||
assert_eq!(session.doc.pixels.layers, moved_pixels.layers, "a subsequent command keeps the undone path pixels");
|
||||
}
|
||||
|
||||
/// A bad path above the edited one must not consume undo or redo when repainting fails
|
||||
#[test]
|
||||
fn point_history_repaint_errors_preserve_the_edit_and_can_be_retried() {
|
||||
use texturecraft_engine::core::{EffectKind, LayerId};
|
||||
|
||||
let mut session = session(wall());
|
||||
let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap();
|
||||
let effect = LayerId(report["committed"]["effect"].as_u64().unwrap());
|
||||
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap();
|
||||
let paint = session.paths(effect).unwrap()[1].paint.clone();
|
||||
execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
|
||||
let original = session.tool.path.points.clone();
|
||||
session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true);
|
||||
session.path_live().unwrap();
|
||||
let moved = session.tool.path.points.clone();
|
||||
|
||||
for (command, expected) in [("edit.undo", &original), ("edit.redo", &moved)] {
|
||||
let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") };
|
||||
paths[1].paint = Value::Null;
|
||||
let before = session.doc.clone();
|
||||
let path = session.tool.path.clone();
|
||||
let history = (session.history_labels(), session.redo_labels());
|
||||
|
||||
let error = execute(&mut session, command, &Value::Null).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("unreadable path settings"), "{error}");
|
||||
assert_eq!(session.tool.path, path);
|
||||
assert_eq!(session.doc.project, before.project);
|
||||
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
|
||||
assert_eq!((session.history_labels(), session.redo_labels()), history);
|
||||
|
||||
let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") };
|
||||
paths[1].paint = paint.clone();
|
||||
execute(&mut session, command, &Value::Null).unwrap();
|
||||
assert_eq!(&session.tool.path.points, expected, "the failed step remains available");
|
||||
assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
|
||||
/// Point history repaints an uncommitted preview without creating document undo steps
|
||||
#[test]
|
||||
fn draft_point_history_repaints_immediately_and_undoing_all_points_cancels() {
|
||||
let mut session = session(wall());
|
||||
execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap();
|
||||
let before = session.doc.clone();
|
||||
let history = session.history_labels();
|
||||
session.append_path_point(Vec3::new(0.2, 0.5, 0.0), true);
|
||||
session.path_live().unwrap();
|
||||
let one_point = session.doc.clone();
|
||||
session.append_path_point(Vec3::new(0.8, 0.5, 0.0), true);
|
||||
session.path_live().unwrap();
|
||||
let two_points = session.doc.clone();
|
||||
|
||||
for (command, expected) in [("edit.undo", &one_point), ("edit.redo", &two_points), ("edit.undo", &one_point), ("edit.undo", &before)] {
|
||||
execute(&mut session, command, &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(session.doc.project, expected.project);
|
||||
assert_eq!(session.doc.pixels.layers, expected.pixels.layers);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
}
|
||||
assert!(session.tool.path.points.is_empty());
|
||||
assert!(session.tool.path.editing.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_final_stored_point_removes_the_path_and_undo_restores_it() {
|
||||
let mut session = session(wall());
|
||||
let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.5, 0.5]], "commit": true})).unwrap();
|
||||
let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap());
|
||||
execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
|
||||
let before = session.doc.clone();
|
||||
|
||||
session.remove_selected_path_point();
|
||||
assert!(session.path_live().unwrap());
|
||||
|
||||
assert!(session.paths(effect).unwrap().is_empty());
|
||||
assert!(session.doc.pixels.layers.keys().all(|(id, _)| *id != effect));
|
||||
assert!(session.tool.path.editing.is_none());
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.doc.project, before.project);
|
||||
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
|
||||
}
|
||||
@@ -26,7 +26,7 @@ pub mod visibility;
|
||||
|
||||
pub use brush::{Alignment, BrushAlpha, BrushSettings, FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Particles, Shape, Symmetry, image_alpha};
|
||||
pub use commit::{CommitSource, Staging, TexelFn, commit_coverage, commit_layer, commit_mask};
|
||||
pub use path::{Lasso, spline};
|
||||
pub use path::{Lasso, spline, spline_segments};
|
||||
pub use pickup::{Pickup, PickupMode};
|
||||
pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv};
|
||||
pub use stamp_source::StampSource;
|
||||
|
||||
+28
-14
@@ -6,30 +6,44 @@ use texturecraft_geom::glam::Vec2;
|
||||
/// Most samples per curve segment.
|
||||
const MAX_SEGMENT_SAMPLES: f32 = 1024.0;
|
||||
|
||||
/// A Catmull-Rom spline through `points`, sampled about every `step` units. Closed curves wrap
|
||||
/// back to the first point; the result starts at the first point.
|
||||
/// A Catmull-Rom spline through `points`, sampled about every `step` units, starting on the first point (closed curves end there too)
|
||||
pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec<Vec2> {
|
||||
let n = points.len();
|
||||
if n < 2 {
|
||||
return points.to_vec();
|
||||
let mut out: Vec<Vec2> = points.first().copied().into_iter().collect();
|
||||
for segment in segment_samples(points, closed, step) {
|
||||
out.extend(segment);
|
||||
}
|
||||
let at = |i: isize| {
|
||||
out
|
||||
}
|
||||
|
||||
/// [`spline`]'s samples per segment: segment `s` holds those after point `s`, up to and including the next point
|
||||
pub fn spline_segments(points: &[Vec2], closed: bool, step: f32) -> Vec<Vec<Vec2>> {
|
||||
segment_samples(points, closed, step).map(Iterator::collect).collect()
|
||||
}
|
||||
|
||||
/// Stream samples so a flat curve does not allocate and retain every segment alongside its output
|
||||
fn segment_samples(points: &[Vec2], closed: bool, step: f32) -> impl Iterator<Item = impl Iterator<Item = Vec2>> + '_ {
|
||||
let n = points.len();
|
||||
let at = move |i: isize| {
|
||||
let i = if closed { i.rem_euclid(n as isize) } else { i.clamp(0, n as isize - 1) };
|
||||
points.get(i as usize).copied().unwrap_or_default()
|
||||
};
|
||||
let step = if step.is_finite() && step > 1e-6 { step } else { 1.0 };
|
||||
let segments = if closed { n } else { n - 1 } as isize;
|
||||
let mut out = vec![at(0)];
|
||||
for s in 0..segments {
|
||||
let segments = if n < 2 {
|
||||
0
|
||||
} else if closed {
|
||||
n
|
||||
} else {
|
||||
n - 1
|
||||
} as isize;
|
||||
(0..segments).map(move |s| {
|
||||
let (p0, p1, p2, p3) = (at(s - 1), at(s), at(s + 1), at(s + 2));
|
||||
let k = ((p2 - p1).length() / step).ceil().clamp(1.0, MAX_SEGMENT_SAMPLES) as usize;
|
||||
for j in 1..=k {
|
||||
(1..=k).map(move |j| {
|
||||
let t = j as f32 / k as f32;
|
||||
let (t2, t3) = (t * t, t * t * t);
|
||||
out.push(0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3));
|
||||
}
|
||||
}
|
||||
out
|
||||
0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// A closed polygon's coverage: 1 inside, 0 outside, a one-unit ramp across the edge.
|
||||
|
||||
@@ -578,7 +578,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.",
|
||||
"ارسم على المجسم لتعديل هذا القناع. استخدم قيمة القناع في لسان تبويب المادة للتدرج الرمادي.",
|
||||
),
|
||||
("Paint the path with the brush (Enter)", "رسم المسار بالفرشاة (Enter)"),
|
||||
("Paint with the current tool", "الرسم بالأداة الحالية"),
|
||||
(
|
||||
"Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB",
|
||||
@@ -597,7 +596,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Paste layer(s)", "لصق الطبقة (الطبقات)"),
|
||||
("Path", "مسار"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "تتبع المسار على المعالج بدلاً من بطاقة الرسوميات (أبطأ)"),
|
||||
("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "المسار: النقر يضيف نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي"),
|
||||
(
|
||||
"Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels",
|
||||
"المسار: النقر يضيف نقطة، والنقر على المنحنى يُدرج نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي",
|
||||
),
|
||||
("Pattern scale", "مقياس النمط"),
|
||||
("Perlin noise", "ضوضاء بيرلن (Perlin)"),
|
||||
("Pick focus in the viewport", "اختر نقطة التركيز في منفذ العرض"),
|
||||
@@ -642,8 +644,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove layer", "إزالة الطبقة"),
|
||||
("Remove layer(s)", "إزالة الطبقة (الطبقات)"),
|
||||
("Remove mask", "إزالة القناع"),
|
||||
("Remove point", "إزالة النقطة"),
|
||||
("Remove resource", "إزالة المورد"),
|
||||
("Remove the path (Esc)", "إزالة المسار (Esc)"),
|
||||
("Remove the shortcut", "إزالة الاختصار"),
|
||||
("Remove this output", "إزالة هذا المخرج"),
|
||||
("Remove unused resources...", "إزالة الموارد غير المستخدمة..."),
|
||||
|
||||
@@ -611,7 +611,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.",
|
||||
"Auf das Mesh malen, um diese Maske zu bearbeiten. Für Grau den Maskenwert im Tab Material verwenden.",
|
||||
),
|
||||
("Paint the path with the brush (Enter)", "Pfad mit dem Pinsel malen (Eingabe)"),
|
||||
("Paint with the current tool", "Mit dem aktuellen Werkzeug malen"),
|
||||
(
|
||||
"Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB",
|
||||
@@ -634,8 +633,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Path", "Pfad"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "Path Tracing auf dem Prozessor statt auf der Grafikkarte (langsamer)"),
|
||||
(
|
||||
"Path: click adds a point, drag moves it, Enter applies, Esc cancels",
|
||||
"Pfad: Klicken fügt einen Punkt hinzu, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab",
|
||||
"Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels",
|
||||
"Pfad: Klicken fügt einen Punkt hinzu, Klicken auf die Kurve fügt einen ein, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab",
|
||||
),
|
||||
("Pattern scale", "Musterskalierung"),
|
||||
("Perlin noise", "Perlin-Rauschen"),
|
||||
@@ -681,8 +680,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove layer", "Ebene entfernen"),
|
||||
("Remove layer(s)", "Ebene(n) entfernen"),
|
||||
("Remove mask", "Maske entfernen"),
|
||||
("Remove point", "Punkt entfernen"),
|
||||
("Remove resource", "Ressource entfernen"),
|
||||
("Remove the path (Esc)", "Pfad entfernen (Esc)"),
|
||||
("Remove the shortcut", "Tastenkürzel entfernen"),
|
||||
("Remove this output", "Diese Ausgabe entfernen"),
|
||||
("Remove unused resources...", "Unbenutzte Ressourcen entfernen..."),
|
||||
|
||||
@@ -602,7 +602,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.",
|
||||
"Pinta sobre la malla para editar esta máscara. Usa el valor de máscara de la pestaña Material para el gris.",
|
||||
),
|
||||
("Paint the path with the brush (Enter)", "Pintar el trazado con el pincel (Intro)"),
|
||||
("Paint with the current tool", "Pintar con la herramienta actual"),
|
||||
(
|
||||
"Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB",
|
||||
@@ -624,7 +623,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Paste layer(s)", "Pegar capa(s)"),
|
||||
("Path", "Trazado"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "Trazar trayectorias en el procesador en lugar de la tarjeta gráfica (más lento)"),
|
||||
("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Trazado: clic añade un punto, arrastrar lo mueve, Intro aplica, Esc cancela"),
|
||||
(
|
||||
"Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels",
|
||||
"Trazado: clic añade un punto, clic en la curva inserta uno, arrastrar lo mueve, Intro aplica, Esc cancela",
|
||||
),
|
||||
("Pattern scale", "Escala del patrón"),
|
||||
("Perlin noise", "Ruido Perlin"),
|
||||
("Pick focus in the viewport", "Elegir el enfoque en la ventana gráfica"),
|
||||
@@ -669,8 +671,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove layer", "Eliminar capa"),
|
||||
("Remove layer(s)", "Eliminar capa(s)"),
|
||||
("Remove mask", "Quitar máscara"),
|
||||
("Remove point", "Quitar punto"),
|
||||
("Remove resource", "Quitar recurso"),
|
||||
("Remove the path (Esc)", "Quitar el trazado (Esc)"),
|
||||
("Remove the shortcut", "Quitar el atajo"),
|
||||
("Remove this output", "Quitar esta salida"),
|
||||
("Remove unused resources...", "Quitar recursos no usados..."),
|
||||
|
||||
@@ -617,7 +617,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.",
|
||||
"Peignez sur le maillage pour modifier ce masque. Utilisez la valeur de masque de l'onglet Matériau pour le gris.",
|
||||
),
|
||||
("Paint the path with the brush (Enter)", "Peindre le tracé avec le pinceau (Enter)"),
|
||||
("Paint with the current tool", "Peindre avec l'outil actuel"),
|
||||
(
|
||||
"Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB",
|
||||
@@ -639,7 +638,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Paste layer(s)", "Coller le(s) calque(s)"),
|
||||
("Path", "Tracé"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "Tracé de chemins sur le processeur au lieu de la carte graphique (plus lent)"),
|
||||
("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Tracé : cliquer ajoute un point, glisser le déplace, Enter applique, Esc annule"),
|
||||
(
|
||||
"Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels",
|
||||
"Tracé : cliquer ajoute un point, cliquer sur la courbe en insère un, glisser le déplace, Enter applique, Esc annule",
|
||||
),
|
||||
("Pattern scale", "Échelle du motif"),
|
||||
("Perlin noise", "Bruit de Perlin"),
|
||||
("Pick focus in the viewport", "Choisir la mise au point dans la fenêtre d'affichage"),
|
||||
@@ -684,8 +686,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove layer", "Supprimer le calque"),
|
||||
("Remove layer(s)", "Supprimer le(s) calque(s)"),
|
||||
("Remove mask", "Supprimer le masque"),
|
||||
("Remove point", "Retirer le point"),
|
||||
("Remove resource", "Supprimer la ressource"),
|
||||
("Remove the path (Esc)", "Supprimer le tracé (Esc)"),
|
||||
("Remove the shortcut", "Supprimer le raccourci"),
|
||||
("Remove this output", "Supprimer cette sortie"),
|
||||
("Remove unused resources...", "Supprimer les ressources inutilisées..."),
|
||||
|
||||
@@ -608,7 +608,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.",
|
||||
"Dipingi sulla mesh per modificare questa maschera. Usa il valore maschera della scheda Materiale per il grigio.",
|
||||
),
|
||||
("Paint the path with the brush (Enter)", "Dipingi il tracciato con il pennello (Invio)"),
|
||||
("Paint with the current tool", "Dipingi con lo strumento corrente"),
|
||||
(
|
||||
"Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB",
|
||||
@@ -631,8 +630,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Path", "Tracciato"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "Esegui il path tracing sul processore anziché sulla scheda grafica (più lento)"),
|
||||
(
|
||||
"Path: click adds a point, drag moves it, Enter applies, Esc cancels",
|
||||
"Tracciato: clic aggiunge un punto, trascina lo sposta, Invio applica, Esc annulla",
|
||||
"Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels",
|
||||
"Tracciato: clic aggiunge un punto, clic sulla curva ne inserisce uno, trascina lo sposta, Invio applica, Esc annulla",
|
||||
),
|
||||
("Pattern scale", "Scala motivo"),
|
||||
("Perlin noise", "Rumore Perlin"),
|
||||
@@ -678,8 +677,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove layer", "Rimuovi livello"),
|
||||
("Remove layer(s)", "Rimuovi livello/i"),
|
||||
("Remove mask", "Rimuovi maschera"),
|
||||
("Remove point", "Rimuovi punto"),
|
||||
("Remove resource", "Rimuovi risorsa"),
|
||||
("Remove the path (Esc)", "Rimuovi il tracciato (Esc)"),
|
||||
("Remove the shortcut", "Rimuovi la scorciatoia"),
|
||||
("Remove this output", "Rimuovi questo output"),
|
||||
("Remove unused resources...", "Rimuovi risorse inutilizzate..."),
|
||||
|
||||
@@ -596,7 +596,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.",
|
||||
"メッシュにペイントしてこのマスクを編集します。グレーには「マテリアル」タブのマスク値を使用します。",
|
||||
),
|
||||
("Paint the path with the brush (Enter)", "ブラシでパスをペイント (Enter)"),
|
||||
("Paint with the current tool", "現在のツールでペイント"),
|
||||
(
|
||||
"Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB",
|
||||
@@ -615,7 +614,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Paste layer(s)", "レイヤーを貼り付け"),
|
||||
("Path", "パス"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "グラフィックカードではなくプロセッサーでパストレース (低速)"),
|
||||
("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "パス: クリックでポイントを追加、ドラッグで移動、Enterで適用、Escでキャンセル"),
|
||||
(
|
||||
"Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels",
|
||||
"パス: クリックでポイントを追加、カーブをクリックで挿入、ドラッグで移動、Enterで適用、Escでキャンセル",
|
||||
),
|
||||
("Pattern scale", "パターンのスケール"),
|
||||
("Perlin noise", "パーリンノイズ"),
|
||||
("Pick focus in the viewport", "ビューポートでフォーカスを指定"),
|
||||
@@ -660,8 +662,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove layer", "レイヤーを削除"),
|
||||
("Remove layer(s)", "レイヤーを削除"),
|
||||
("Remove mask", "マスクを削除"),
|
||||
("Remove point", "ポイントを削除"),
|
||||
("Remove resource", "リソースを削除"),
|
||||
("Remove the path (Esc)", "パスを削除 (Esc)"),
|
||||
("Remove the shortcut", "ショートカットを削除"),
|
||||
("Remove this output", "この出力を削除"),
|
||||
("Remove unused resources...", "未使用のリソースを削除..."),
|
||||
|
||||
@@ -587,7 +587,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.",
|
||||
"메시에 칠하여 이 마스크를 편집합니다. 회색은 머티리얼 탭의 마스크 값을 사용하세요.",
|
||||
),
|
||||
("Paint the path with the brush (Enter)", "브러시로 패스를 칠합니다 (Enter)"),
|
||||
("Paint with the current tool", "현재 도구로 페인팅"),
|
||||
(
|
||||
"Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB",
|
||||
@@ -606,7 +605,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Paste layer(s)", "레이어 붙여넣기"),
|
||||
("Path", "패스"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "그래픽 카드 대신 프로세서에서 패스 트레이싱합니다 (더 느림)"),
|
||||
("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "패스: 클릭으로 점 추가, 드래그로 이동, Enter로 적용, Esc로 취소"),
|
||||
(
|
||||
"Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels",
|
||||
"패스: 클릭으로 점 추가, 곡선 클릭으로 점 삽입, 드래그로 이동, Enter로 적용, Esc로 취소",
|
||||
),
|
||||
("Pattern scale", "패턴 스케일"),
|
||||
("Perlin noise", "펄린 노이즈"),
|
||||
("Pick focus in the viewport", "뷰포트에서 초점 선택"),
|
||||
@@ -651,8 +653,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove layer", "레이어 제거"),
|
||||
("Remove layer(s)", "레이어 제거"),
|
||||
("Remove mask", "마스크 제거"),
|
||||
("Remove point", "점 제거"),
|
||||
("Remove resource", "리소스 제거"),
|
||||
("Remove the path (Esc)", "패스를 제거합니다 (Esc)"),
|
||||
("Remove the shortcut", "단축키를 제거합니다"),
|
||||
("Remove this output", "이 출력을 제거합니다"),
|
||||
("Remove unused resources...", "사용하지 않는 리소스 제거..."),
|
||||
|
||||
@@ -599,7 +599,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.",
|
||||
"Pinte na malha para editar esta máscara. Use o valor de máscara da aba Material para cinza.",
|
||||
),
|
||||
("Paint the path with the brush (Enter)", "Pintar o caminho com o pincel (Enter)"),
|
||||
("Paint with the current tool", "Pintar com a ferramenta atual"),
|
||||
(
|
||||
"Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB",
|
||||
@@ -621,7 +620,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Paste layer(s)", "Colar camada(s)"),
|
||||
("Path", "Caminho"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "Fazer path tracing no processador em vez da placa de vídeo (mais lento)"),
|
||||
("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Caminho: clicar adiciona um ponto, arrastar o move, Enter aplica, Esc cancela"),
|
||||
(
|
||||
"Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels",
|
||||
"Caminho: clicar adiciona um ponto, clicar na curva insere um, arrastar o move, Enter aplica, Esc cancela",
|
||||
),
|
||||
("Pattern scale", "Escala do padrão"),
|
||||
("Perlin noise", "Ruído Perlin"),
|
||||
("Pick focus in the viewport", "Escolher o foco na viewport"),
|
||||
@@ -666,8 +668,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove layer", "Remover camada"),
|
||||
("Remove layer(s)", "Remover camada(s)"),
|
||||
("Remove mask", "Remover máscara"),
|
||||
("Remove point", "Remover ponto"),
|
||||
("Remove resource", "Remover recurso"),
|
||||
("Remove the path (Esc)", "Remover o caminho (Esc)"),
|
||||
("Remove the shortcut", "Remover o atalho"),
|
||||
("Remove this output", "Remover esta saída"),
|
||||
("Remove unused resources...", "Remover recursos não usados..."),
|
||||
|
||||
@@ -545,7 +545,6 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Paint chips", "掉漆"),
|
||||
("Paint on the mesh to edit the layer content.", "在网格上绘画以编辑图层内容。"),
|
||||
("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "在网格上绘画以编辑此遮罩。灰度请使用“材质”选项卡中的遮罩值。"),
|
||||
("Paint the path with the brush (Enter)", "用笔刷绘制路径(Enter)"),
|
||||
("Paint with the current tool", "使用当前工具绘画"),
|
||||
(
|
||||
"Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB",
|
||||
@@ -564,7 +563,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Paste layer(s)", "粘贴图层"),
|
||||
("Path", "路径"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "在处理器而非显卡上进行路径追踪(较慢)"),
|
||||
("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "路径:单击添加点,拖动移动点,Enter 应用,Esc 取消"),
|
||||
(
|
||||
"Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels",
|
||||
"路径:单击添加点,单击曲线插入点,拖动移动点,Enter 应用,Esc 取消",
|
||||
),
|
||||
("Pattern scale", "图案缩放"),
|
||||
("Perlin noise", "柏林噪波"),
|
||||
("Pick focus in the viewport", "在视口中拾取焦点"),
|
||||
@@ -609,8 +611,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Remove layer", "移除图层"),
|
||||
("Remove layer(s)", "移除图层"),
|
||||
("Remove mask", "移除遮罩"),
|
||||
("Remove point", "移除点"),
|
||||
("Remove resource", "移除资源"),
|
||||
("Remove the path (Esc)", "移除路径(Esc)"),
|
||||
("Remove the shortcut", "移除快捷键"),
|
||||
("Remove this output", "移除此输出"),
|
||||
("Remove unused resources...", "移除未使用的资源..."),
|
||||
|
||||
@@ -34,6 +34,8 @@ pub mod menus;
|
||||
pub mod new_project_advanced;
|
||||
mod orb_shape;
|
||||
pub mod parity;
|
||||
mod path_hit;
|
||||
mod path_surface_cache;
|
||||
mod preview_image;
|
||||
mod preview_request;
|
||||
mod preview_worker;
|
||||
@@ -667,7 +669,7 @@ impl eframe::App for TextureCraftApp {
|
||||
self.poll_bake(ctx);
|
||||
self.poll_resize(ctx);
|
||||
self.poll_link_cooks(ctx);
|
||||
// The library shelf rescans when the window comes back (MaterialCraft may have sent a material).
|
||||
// The library shelf rescans when the window comes back (MaterialCraft may have sent a material)
|
||||
let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true);
|
||||
if focused && !self.focused {
|
||||
self.library = None;
|
||||
@@ -690,9 +692,9 @@ impl eframe::App for TextureCraftApp {
|
||||
updates_ui::tick(self, ctx);
|
||||
self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx));
|
||||
menus::shortcuts(self, ctx);
|
||||
// A stored path being edited repaints its sublayer as its points, brush or material change.
|
||||
// The Path tool's curve repaints (a preview while placed) as its points, brush or material change
|
||||
if let Err(e) = self.session.path_live() {
|
||||
self.session.stop_path_edit();
|
||||
self.session.cancel_path();
|
||||
self.toast(e.to_string(), true);
|
||||
}
|
||||
profile::drive(self, ctx);
|
||||
@@ -718,7 +720,7 @@ impl eframe::App for TextureCraftApp {
|
||||
}
|
||||
let hide = self.ui.hide_ui;
|
||||
let tk = theme::Tokens::get(&ctx);
|
||||
// The dock keeps the cards' gutter from the bars and rails around it.
|
||||
// The dock keeps the cards' gutter from the bars and rails around it
|
||||
let panel_frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) };
|
||||
egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) });
|
||||
windows::show(self, &ctx);
|
||||
|
||||
@@ -371,8 +371,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
crate::id_color_pick::IdColorPick::end(app);
|
||||
} else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
app.session.cancel_stroke();
|
||||
app.session.tool.path.points.clear();
|
||||
app.session.tool.path.editing = None;
|
||||
app.session.cancel_path();
|
||||
}
|
||||
commands
|
||||
});
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
//! What a pointer position in a view is over, for the Path tool
|
||||
|
||||
use egui::Pos2;
|
||||
use texturecraft_engine::core::LayerId;
|
||||
|
||||
/// What a pointer position in a view is over, for the Path tool
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum PathHit {
|
||||
/// A control point of the path being edited
|
||||
Point(usize),
|
||||
/// The edited path's curve: the segment starting at this point, and the nearest screen position on it
|
||||
Curve(usize, Pos2),
|
||||
/// Another stored path of the selected layer: (path sublayer, index)
|
||||
Stored(LayerId, usize),
|
||||
/// Nothing of a path
|
||||
Miss,
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Sampled path curves retained only while the viewport uses them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::cache::CacheTrait;
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::core::{LayerId, PathShape};
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
|
||||
pub(crate) type SurfaceCurve = Arc<Vec<Vec<Option<Vec3>>>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PathSurfaceCache {
|
||||
// Mesh, effect and path index identify entries; the flag records use during this pass
|
||||
curves: HashMap<(u64, LayerId, usize), (PathShape, SurfaceCurve, bool)>,
|
||||
}
|
||||
|
||||
impl PathSurfaceCache {
|
||||
/// Reuse an unchanged curve and retain it for this pass; UV or missing paths have no surface curve
|
||||
pub(crate) fn get(&mut self, session: &Session, effect: LayerId, index: usize) -> Option<SurfaceCurve> {
|
||||
let shape = session.paths(effect)?.get(index)?;
|
||||
let key = (session.mesh_id, effect, index);
|
||||
if let Some((cached_shape, surface, used)) = self.curves.get_mut(&key)
|
||||
&& cached_shape == shape
|
||||
{
|
||||
*used = true;
|
||||
return Some(Arc::clone(surface));
|
||||
}
|
||||
|
||||
let surface = Arc::new(session.stored_path_surface(effect, index)?);
|
||||
self.curves.insert(key, (shape.clone(), Arc::clone(&surface), true));
|
||||
Some(surface)
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheTrait for PathSurfaceCache {
|
||||
fn update(&mut self) {
|
||||
// egui calls this even when paths stop drawing, so hidden or deleted paths release their buffers
|
||||
self.curves.retain(|_, (_, _, used)| std::mem::take(used));
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.curves.len()
|
||||
}
|
||||
}
|
||||
@@ -322,25 +322,25 @@ pub fn fill_mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
/// Path tool options and actions (top bar and properties)
|
||||
pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
let button_size = ui.spacing().interact_size.y;
|
||||
let path = &mut app.session.tool.path;
|
||||
if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, button_size).clicked() {
|
||||
path.closed = !path.closed;
|
||||
}
|
||||
let fill_tip = if path.closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") };
|
||||
if icon_button(ui, ic::PAINT_BUCKET, fill_tip, path.fill, button_size).clicked() {
|
||||
path.fill = !path.fill;
|
||||
let path = &app.session.tool.path;
|
||||
let (closed, fill) = (path.closed, path.fill);
|
||||
let selected = path.selected.is_some_and(|i| i < path.points.len());
|
||||
let has_points = !path.points.is_empty();
|
||||
if icon_button(ui, ic::POLYGON, tr("Closed path"), closed, button_size).clicked() {
|
||||
app.session.set_path_closed(!closed);
|
||||
}
|
||||
|
||||
let has_points = !path.points.is_empty();
|
||||
if ui
|
||||
.add_enabled(has_points, egui::Button::new(format!("{} {}", ic::CHECK, tr("Apply"))))
|
||||
.on_hover_text(tr("Paint the path with the brush (Enter)"))
|
||||
.clicked()
|
||||
{
|
||||
app.run("tool.path", json!({"commit": true}));
|
||||
let fill_tip = if closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") };
|
||||
if icon_button(ui, ic::PAINT_BUCKET, fill_tip, fill, button_size).clicked() {
|
||||
app.session.set_path_fill(!fill);
|
||||
}
|
||||
if ui.add_enabled(has_points, egui::Button::new(format!("{} {}", ic::X, tr("Cancel")))).on_hover_text(tr("Remove the path (Esc)")).clicked() {
|
||||
app.run("tool.path", json!({"clear": true}));
|
||||
|
||||
if ui.add_enabled_ui(selected, |ui| icon_button(ui, ic::BACKSPACE, tr("Remove point"), false, button_size)).inner.clicked() {
|
||||
app.session.remove_selected_path_point();
|
||||
}
|
||||
|
||||
if ui.add_enabled_ui(has_points, |ui| icon_button(ui, ic::CHECK, tr("Apply"), false, button_size)).inner.clicked() {
|
||||
app.run("tool.path", json!({"commit": true}));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+357
-59
@@ -1,7 +1,7 @@
|
||||
//! The 3D viewport and the 2D UV view: navigation, painting input, brush cursor and the GPU
|
||||
//! callbacks that render them.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use egui::emath::GuiRounding as _;
|
||||
use egui::{Color32, PointerButton, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2};
|
||||
@@ -16,6 +16,8 @@ use crate::TextureCraftApp;
|
||||
use crate::decal_drop::DecalDrop;
|
||||
use crate::gpu::ViewCallback;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::path_hit::PathHit;
|
||||
use crate::path_surface_cache::{PathSurfaceCache, SurfaceCurve};
|
||||
use crate::state::ViewLayout;
|
||||
use crate::theme::Tokens;
|
||||
use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE};
|
||||
@@ -653,7 +655,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point);
|
||||
let mut fill_box = None;
|
||||
if painting && path_tool {
|
||||
path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show);
|
||||
path_input(app, ui, &response, (rect, false), |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show);
|
||||
} else if painting && app.session.tool.tool == Tool::PolygonFill {
|
||||
fill_box = polygon_fill_input(
|
||||
app,
|
||||
@@ -718,6 +720,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
&& !navigating
|
||||
&& response.hovered()
|
||||
&& brush_tool(app.session.tool.tool)
|
||||
&& (app.session.tool.tool != Tool::Path || adjusting)
|
||||
&& !crate::symmetry::manipulator_hovered(app, ui, rect)
|
||||
&& app.picking_id_color.is_none()
|
||||
&& let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() }
|
||||
@@ -739,7 +742,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
&& !path_tool
|
||||
&& let Some(from) = app.last_paint_point
|
||||
{
|
||||
rubber_band(ui, rect, pos2(rect.left() + from.x, rect.top() + from.y), hover_pos);
|
||||
rubber_band(ui, rect, &[pos2(rect.left() + from.x, rect.top() + from.y), hover_pos]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1038,16 +1041,45 @@ pub(crate) fn project(app: &TextureCraftApp, rect: Rect, point: Vec3) -> Option<
|
||||
Some(pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height()))
|
||||
}
|
||||
|
||||
/// Control point grab radius (points).
|
||||
/// Control point and curve grab radius (points)
|
||||
const HANDLE_GRAB: f32 = 8.0;
|
||||
/// Opacity of the selected layer's other stored paths
|
||||
const PATH_STORED_OPACITY: f32 = 0.55;
|
||||
/// Opacity of a curve where the mesh hides it
|
||||
const PATH_HIDDEN_OPACITY: f32 = 0.5;
|
||||
/// A control point counts as hidden when the surface under it is this much closer (relative)
|
||||
const PATH_HIDDEN_DEPTH: f32 = 0.01;
|
||||
/// The Path tool's pointer glyph size (points)
|
||||
const PATH_CURSOR_SIZE: f32 = 18.0;
|
||||
/// A path's line and the dark outline under it (points)
|
||||
const PATH_LINE_WIDTH: f32 = 1.4;
|
||||
const PATH_OUTLINE_WIDTH: f32 = 3.0;
|
||||
/// Where the view hint sits from the view's bottom left corner, and its text size (points)
|
||||
const PATH_HINT_OFFSET: egui::Vec2 = vec2(56.0, -12.0);
|
||||
const PATH_HINT_FONT_SIZE: f32 = 12.0;
|
||||
/// The pen pointer's drop shadow, and the space before its insert plus (points)
|
||||
const PATH_CURSOR_SHADOW_OFFSET: egui::Vec2 = vec2(1.0, 1.0);
|
||||
const PATH_CURSOR_PLUS_GAP: f32 = 1.0;
|
||||
/// The insert plus beside the pen pointer, relative to the pen's size
|
||||
const PATH_CURSOR_PLUS_SCALE: f32 = 0.6;
|
||||
/// Space kept right of the view hint, and its narrowest wrap width (points)
|
||||
const PATH_HINT_MARGIN: f32 = 8.0;
|
||||
const PATH_HINT_MIN_WIDTH: f32 = 80.0;
|
||||
/// How much a control point marker grows under the pointer, and when selected (points)
|
||||
const PATH_POINT_HOVER_GROWTH: f32 = 1.5;
|
||||
const PATH_POINT_SELECTED_GROWTH: f32 = 0.5;
|
||||
/// Control point marker radius (points)
|
||||
const PATH_POINT_RADIUS: f32 = 3.0;
|
||||
/// Curve sampling step on screen (points)
|
||||
const PATH_SCREEN_STEP: f32 = 3.0;
|
||||
|
||||
/// Path tool keys: Enter applies the path, Backspace removes its last point (Esc, handled with
|
||||
/// the global shortcuts, cancels it).
|
||||
/// Path tool keys: Enter applies the path, Backspace removes the selected (or last) point; Esc is a global shortcut
|
||||
fn path_keys(app: &mut TextureCraftApp, ui: &Ui) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if crate::updates_ui::blocks_input(app) {
|
||||
return;
|
||||
}
|
||||
|
||||
if app.ui.mode != crate::state::Mode::Painting
|
||||
|| app.session.tool.tool != Tool::Path
|
||||
|| app.session.tool.path.points.is_empty()
|
||||
@@ -1055,24 +1087,116 @@ fn path_keys(app: &mut TextureCraftApp, ui: &Ui) {
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let (enter, back) = ui.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::Enter), i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)));
|
||||
if enter {
|
||||
app.run("tool.path", json!({"commit": true}));
|
||||
}
|
||||
if back {
|
||||
app.session.tool.path.points.pop();
|
||||
app.session.remove_selected_path_point();
|
||||
}
|
||||
}
|
||||
|
||||
/// Path tool input in a view (`uv`: the 2D view). Pressing on a control point drags it,
|
||||
/// elsewhere adds a point (and drags it); clicking the first point of an open path closes it.
|
||||
/// `place` maps a pointer position to a path point (None off the surface), `show` a path point
|
||||
/// to the screen.
|
||||
/// The selected layer's stored paths except the edited one: (path sublayer, index, path)
|
||||
fn other_paths(app: &TextureCraftApp) -> Vec<(texturecraft_engine::core::LayerId, usize, texturecraft_engine::PathState)> {
|
||||
let s = &app.session;
|
||||
let Some(layer) = s.selected_layer().and_then(|id| s.doc.project.layer(id).ok()) else { return Vec::new() };
|
||||
let effects = layer.content_effects.iter().chain(layer.mask.iter().flat_map(|m| m.effects.iter()));
|
||||
effects
|
||||
.flat_map(|e| s.stored_path_states(e.id).into_iter().enumerate().map(move |(i, path)| (e.id, i, path)))
|
||||
.filter(|(e, i, _)| s.tool.path.editing != Some((*e, *i)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The screen curve through `points` per segment, each starting on its first point
|
||||
fn screen_segments(points: &[Pos2], closed: bool) -> Vec<Vec<Pos2>> {
|
||||
let pts: Vec<Vec2> = points.iter().map(|p| Vec2::new(p.x, p.y)).collect();
|
||||
texturecraft_engine::paint::spline_segments(&pts, closed, PATH_SCREEN_STEP)
|
||||
.into_iter()
|
||||
.zip(points)
|
||||
.map(|(samples, first)| std::iter::once(*first).chain(samples.into_iter().map(|v| pos2(v.x, v.y))).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A path's curve in a view per segment: screen position and whether the mesh leaves it visible (None off the mesh or screen)
|
||||
type ScreenCurve = Vec<Vec<Option<(Pos2, bool)>>>;
|
||||
|
||||
/// The nearest segment of `curve` within grab distance of `at`, with the nearest position on it
|
||||
fn segment_near(curve: &ScreenCurve, at: Pos2) -> Option<(usize, Pos2)> {
|
||||
let nearest = |segment: &Vec<Option<(Pos2, bool)>>| {
|
||||
segment.windows(2).filter_map(|w| Some(closest_on_line(w[0]?.0, w[1]?.0, at))).min_by(|a, b| a.distance(at).total_cmp(&b.distance(at)))
|
||||
};
|
||||
curve
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, segment)| nearest(segment).map(|p| (i, p)))
|
||||
.filter(|(_, p)| p.distance(at) < HANDLE_GRAB)
|
||||
.min_by(|a, b| a.1.distance(at).total_cmp(&b.1.distance(at)))
|
||||
}
|
||||
|
||||
/// `path`'s curve in a view; a 3D curve lies where its paint lands, and without `depth_test` (hit tests) every sample counts as visible
|
||||
fn curve_on_screen(
|
||||
app: &TextureCraftApp,
|
||||
ui: &Ui,
|
||||
(rect, uv, depth_test): (Rect, bool, bool),
|
||||
path: &texturecraft_engine::PathState,
|
||||
stored: Option<(texturecraft_engine::core::LayerId, usize)>,
|
||||
show: &impl Fn(&TextureCraftApp, Vec3) -> Option<Pos2>,
|
||||
) -> ScreenCurve {
|
||||
if uv {
|
||||
let Some(points) = path.points.iter().map(|p| show(app, *p)).collect::<Option<Vec<_>>>() else { return Vec::new() };
|
||||
return screen_segments(&points, path.closed).into_iter().map(|segment| segment.into_iter().map(|at| Some((at, true))).collect()).collect();
|
||||
}
|
||||
let s = &app.session;
|
||||
let surface = stored
|
||||
.and_then(|(eid, index)| stored_surface(app, ui, eid, index))
|
||||
.unwrap_or_else(|| Arc::new(s.path_surface(&path.points, path.closed, s.camera, s.viewport)));
|
||||
surface
|
||||
.iter()
|
||||
.map(|segment| segment.iter().map(|p| p.and_then(|p| show(app, p).map(|at| (at, !depth_test || path_point_visible(app, rect, p, at))))).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Sample the stored curve once while visible, invalidating it when the path or mesh changes
|
||||
fn stored_surface(app: &TextureCraftApp, ui: &Ui, eid: texturecraft_engine::core::LayerId, index: usize) -> Option<SurfaceCurve> {
|
||||
ui.memory_mut(|memory| memory.caches.cache::<PathSurfaceCache>().get(&app.session, eid, index))
|
||||
}
|
||||
|
||||
/// The point of the segment `a`–`b` nearest to `p`
|
||||
fn closest_on_line(a: Pos2, b: Pos2, p: Pos2) -> Pos2 {
|
||||
let ab = b - a;
|
||||
let t = if ab.length_sq() > 0.0 { ((p - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 };
|
||||
a + ab * t
|
||||
}
|
||||
|
||||
/// What `at` is over in a view (`uv`: the 2D view); `show` maps a path point to the screen
|
||||
fn path_hit(app: &TextureCraftApp, ui: &Ui, (rect, uv): (Rect, bool), at: Pos2, show: &impl Fn(&TextureCraftApp, Vec3) -> Option<Pos2>) -> PathHit {
|
||||
let path = &app.session.tool.path;
|
||||
if path.uv == uv {
|
||||
if let Some(i) = path.points.iter().position(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) {
|
||||
return PathHit::Point(i);
|
||||
}
|
||||
if let Some((i, on)) = segment_near(&curve_on_screen(app, ui, (rect, uv, false), path, path.editing, show), at) {
|
||||
return PathHit::Curve(i, on);
|
||||
}
|
||||
}
|
||||
for (eid, i, other) in other_paths(app) {
|
||||
if other.uv == uv
|
||||
&& (other.points.iter().any(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB))
|
||||
|| segment_near(&curve_on_screen(app, ui, (rect, uv, false), &other, Some((eid, i)), show), at).is_some())
|
||||
{
|
||||
return PathHit::Stored(eid, i);
|
||||
}
|
||||
}
|
||||
PathHit::Miss
|
||||
}
|
||||
|
||||
/// Path tool presses in a view: select and drag a point, insert on the curve, open another path, close on the first point, or add a point
|
||||
fn path_input(
|
||||
app: &mut TextureCraftApp,
|
||||
ui: &Ui,
|
||||
resp: &egui::Response,
|
||||
uv: bool,
|
||||
(rect, uv): (Rect, bool),
|
||||
place: impl Fn(&TextureCraftApp, Pos2) -> Option<Vec3>,
|
||||
show: impl Fn(&TextureCraftApp, Vec3) -> Option<Pos2>,
|
||||
) {
|
||||
@@ -1082,71 +1206,191 @@ fn path_input(
|
||||
&& let Some(at) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
|
||||
{
|
||||
let path = &app.session.tool.path;
|
||||
let near = if path.uv == uv { path.points.iter().position(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) } else { None };
|
||||
match near {
|
||||
Some(0) if clicked && !path.closed && path.points.len() >= 3 => app.session.tool.path.closed = true,
|
||||
Some(i) => ui.data_mut(|d| {
|
||||
d.insert_temp(drag_id, i);
|
||||
}),
|
||||
None => match place(app, at) {
|
||||
Some(p) => {
|
||||
app.session.tool.path.push(p, uv);
|
||||
let last = app.session.tool.path.points.len().saturating_sub(1);
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(drag_id, last);
|
||||
});
|
||||
let (closed, len) = (path.closed, path.points.len());
|
||||
let hit = path_hit(app, ui, (rect, uv), at, &show);
|
||||
|
||||
let grab = match hit {
|
||||
PathHit::Point(0) if clicked && !closed && len >= 3 => {
|
||||
app.session.set_path_closed(true);
|
||||
None
|
||||
}
|
||||
PathHit::Point(i) => {
|
||||
app.session.select_path_point(i);
|
||||
Some(i)
|
||||
}
|
||||
PathHit::Stored(eid, index) => {
|
||||
app.run("path.edit", json!({"effect": eid.0, "index": index}));
|
||||
None
|
||||
}
|
||||
hit => match place(app, if let PathHit::Curve(_, on) = hit { on } else { at }) {
|
||||
Some(p) => match hit {
|
||||
PathHit::Curve(i, _) => app.session.insert_path_point(i + 1, p),
|
||||
_ => app.session.append_path_point(p, uv),
|
||||
},
|
||||
None => {
|
||||
app.toast(tr("Place path points on the mesh"), false);
|
||||
None
|
||||
}
|
||||
None => app.toast(tr("Place path points on the mesh"), false),
|
||||
},
|
||||
};
|
||||
if let Some(i) = grab {
|
||||
ui.data_mut(|d| d.insert_temp(drag_id, (i, true)));
|
||||
}
|
||||
}
|
||||
|
||||
if resp.dragged_by(PointerButton::Primary)
|
||||
&& let Some(i) = ui.data(|d| d.get_temp::<usize>(drag_id))
|
||||
&& let Some((index, begin_drag)) = ui.data(|data| data.get_temp::<(usize, bool)>(drag_id))
|
||||
&& let Some(p) = resp.interact_pointer_pos().and_then(|pos| place(app, pos))
|
||||
&& let Some(q) = app.session.tool.path.points.get_mut(i)
|
||||
&& app.session.move_path_point(index, p, begin_drag)
|
||||
{
|
||||
*q = p;
|
||||
ui.data_mut(|data| data.insert_temp(drag_id, (index, false)));
|
||||
}
|
||||
|
||||
if !resp.is_pointer_button_down_on() {
|
||||
ui.data_mut(|d| d.remove::<usize>(drag_id));
|
||||
ui.data_mut(|data| data.remove::<(usize, bool)>(drag_id));
|
||||
}
|
||||
}
|
||||
|
||||
/// The path being edited: its curve, control points (the first one in the accent color) and,
|
||||
/// while open, a dashed preview of the next segment.
|
||||
/// Is path point `p` (on screen at `at`) in front of the mesh in the 3D view `rect`?
|
||||
fn path_point_visible(app: &TextureCraftApp, rect: Rect, p: Vec3, at: Pos2) -> bool {
|
||||
let eye = app.session.camera.eye();
|
||||
let local = Vec2::new(at.x - rect.left(), at.y - rect.top());
|
||||
app.session.pick(local, app.session.viewport).is_none_or(|hit| hit.pos.distance(eye) >= p.distance(eye) * (1.0 - PATH_HIDDEN_DEPTH))
|
||||
}
|
||||
|
||||
/// Draw `curve` in `color` over a dark outline, as a faint line where the mesh hides it
|
||||
fn draw_path_curve(painter: &egui::Painter, curve: &ScreenCurve, color: Color32) {
|
||||
let draw = |run: &mut Vec<Pos2>, shown: bool| {
|
||||
if run.len() > 1 {
|
||||
// Hidden parts are a ghost line: no outline, half strength
|
||||
if shown {
|
||||
painter.add(egui::Shape::line(run.clone(), Stroke::new(PATH_OUTLINE_WIDTH, Color32::from_black_alpha(140))));
|
||||
}
|
||||
painter.add(egui::Shape::line(
|
||||
std::mem::take(run),
|
||||
Stroke::new(PATH_LINE_WIDTH, if shown { color } else { color.gamma_multiply(PATH_HIDDEN_OPACITY) }),
|
||||
));
|
||||
}
|
||||
run.clear();
|
||||
};
|
||||
for segment in curve {
|
||||
// Runs of samples the view shows (or hides) alike, joined at the sample where that changes
|
||||
let (mut run, mut shown) = (Vec::new(), true);
|
||||
for sample in segment {
|
||||
match *sample {
|
||||
Some((at, visible)) => {
|
||||
if visible != shown && !run.is_empty() {
|
||||
run.push(at);
|
||||
draw(&mut run, shown);
|
||||
}
|
||||
shown = visible;
|
||||
run.push(at);
|
||||
}
|
||||
None => draw(&mut run, shown),
|
||||
}
|
||||
}
|
||||
draw(&mut run, shown);
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer's other paths (lit under the pointer), then the edited path with its points, the next segment's preview and the pen cursor
|
||||
fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Response, uv: bool, show: impl Fn(&TextureCraftApp, Vec3) -> Option<Pos2>) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let p = ui.painter_at(rect);
|
||||
let path = &app.session.tool.path;
|
||||
let hint = tr("Path: click adds a point, drag moves it, Enter applies, Esc cancels");
|
||||
p.text(rect.left_bottom() + vec2(56.0, -12.0), egui::Align2::LEFT_BOTTOM, hint, egui::FontId::proportional(12.0), tk.viewport_text);
|
||||
if path.uv != uv {
|
||||
return;
|
||||
}
|
||||
let handles: Vec<Pos2> = path.points.iter().filter_map(|q| show(app, *q)).collect();
|
||||
let pts: Vec<Vec2> = handles.iter().map(|h| Vec2::new(h.x, h.y)).collect();
|
||||
let curve: Vec<Pos2> = texturecraft_engine::paint::spline(&pts, path.closed, 3.0).into_iter().map(|v| pos2(v.x, v.y)).collect();
|
||||
let color = if path.closed && path.fill { tk.viewport_accent } else { Color32::from_white_alpha(230) };
|
||||
p.add(egui::Shape::line(curve.clone(), Stroke::new(3.0, Color32::from_black_alpha(140))));
|
||||
p.add(egui::Shape::line(curve, Stroke::new(1.4, color)));
|
||||
let painter = ui.painter_at(rect);
|
||||
let hint = tr("Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels");
|
||||
// Wrapped to the view: the hint is longer than a narrow split view
|
||||
let at = rect.left_bottom() + PATH_HINT_OFFSET;
|
||||
let wrap = (rect.right() - at.x - PATH_HINT_MARGIN).max(PATH_HINT_MIN_WIDTH);
|
||||
let hint = painter.layout(hint.to_string(), egui::FontId::proportional(PATH_HINT_FONT_SIZE), tk.viewport_text, wrap);
|
||||
painter.galley(at - vec2(0.0, hint.size().y), hint, tk.viewport_text);
|
||||
|
||||
let hover = resp.hover_pos();
|
||||
if !path.closed
|
||||
&& let (Some(last), Some(to)) = (handles.last(), hover)
|
||||
{
|
||||
rubber_band(ui, rect, *last, to);
|
||||
let hit = hover.map(|at| (at, path_hit(app, ui, (rect, uv), at, &show)));
|
||||
for (eid, i, other) in other_paths(app).iter().filter(|(_, _, other)| other.uv == uv) {
|
||||
let curve = curve_on_screen(app, ui, (rect, uv, true), other, Some((*eid, *i)), &show);
|
||||
// The path a click opens lights up
|
||||
let opened = matches!(hit, Some((_, PathHit::Stored(e, n))) if (e, n) == (*eid, *i));
|
||||
draw_path_curve(&painter, &curve, if opened { Color32::WHITE } else { Color32::WHITE.gamma_multiply(PATH_STORED_OPACITY) });
|
||||
}
|
||||
for (i, h) in handles.iter().enumerate() {
|
||||
let r = if hover.is_some_and(|m| m.distance(*h) < HANDLE_GRAB) { 5.5 } else { 4.0 };
|
||||
p.circle(*h, r, if i == 0 { tk.viewport_accent } else { Color32::WHITE }, Stroke::new(1.5, Color32::from_black_alpha(180)));
|
||||
|
||||
let path = &app.session.tool.path;
|
||||
if path.uv == uv {
|
||||
draw_path_curve(&painter, &curve_on_screen(app, ui, (rect, uv, true), path, path.editing, &show), tk.viewport_accent);
|
||||
let handles: Vec<Pos2> = path.points.iter().filter_map(|q| show(app, *q)).collect();
|
||||
if !path.closed
|
||||
&& !handles.is_empty()
|
||||
&& let Some((to, PathHit::Miss)) = hit
|
||||
{
|
||||
let mut next = handles.clone();
|
||||
next.push(to);
|
||||
if let Some(segment) = screen_segments(&next, false).last() {
|
||||
rubber_band(ui, rect, segment);
|
||||
}
|
||||
}
|
||||
|
||||
for (index, point) in path.points.iter().enumerate() {
|
||||
let Some(handle) = show(app, *point) else { continue };
|
||||
|
||||
// Keep the point's original index when earlier points project behind the camera
|
||||
let hovered = hover.is_some_and(|m| m.distance(handle) < HANDLE_GRAB);
|
||||
let radius = if hovered { PATH_POINT_RADIUS + PATH_POINT_HOVER_GROWTH } else { PATH_POINT_RADIUS };
|
||||
if path.selected == Some(index) {
|
||||
painter.circle(handle, radius + PATH_POINT_SELECTED_GROWTH, tk.viewport_accent, Stroke::new(1.0, Color32::from_black_alpha(160)));
|
||||
} else {
|
||||
painter.circle(handle, radius, Color32::from_black_alpha(110), Stroke::new(1.0, Color32::from_white_alpha(if hovered { 230 } else { 150 })));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((at, hit)) = hit
|
||||
&& !ui.input(|i| i.modifiers.command)
|
||||
{
|
||||
if let PathHit::Curve(_, on) = hit {
|
||||
// Where the click inserts its point
|
||||
painter.circle(on, PATH_POINT_RADIUS, Color32::from_black_alpha(60), Stroke::new(1.0, Color32::from_white_alpha(110)));
|
||||
}
|
||||
path_cursor(ui, &painter, at, matches!(hit, PathHit::Curve(..)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Dashed preview of a straight segment, clipped to `rect` so an end far off screen adds no dashes.
|
||||
fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) {
|
||||
let Some(visible) = visible_dashes(rect, from, to) else { return };
|
||||
/// The Path tool's pointer: a pen with its nib at `at`, and a plus when a click inserts a point
|
||||
fn path_cursor(ui: &Ui, painter: &egui::Painter, at: Pos2, insert: bool) {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
|
||||
let glyph = |icon: &str, size: f32, color: Color32| painter.layout_no_wrap(icon.to_string(), egui::FontId::proportional(size), color);
|
||||
for (offset, color) in [(PATH_CURSOR_SHADOW_OFFSET, Color32::from_black_alpha(200)), (egui::Vec2::ZERO, Color32::WHITE)] {
|
||||
// The pen's nib is the bottom left corner of the drawn glyph
|
||||
let pen = glyph(egui_phosphor::regular::PEN_NIB, PATH_CURSOR_SIZE, color);
|
||||
let origin = at + offset - pen.mesh_bounds.left_bottom().to_vec2();
|
||||
let right = origin + pen.mesh_bounds.right_bottom().to_vec2();
|
||||
painter.galley(origin, pen, color);
|
||||
if insert {
|
||||
let plus = glyph(egui_phosphor::regular::PLUS, PATH_CURSOR_SIZE * PATH_CURSOR_PLUS_SCALE, color);
|
||||
painter.galley(right + vec2(PATH_CURSOR_PLUS_GAP, 0.0) - plus.mesh_bounds.left_top().to_vec2(), plus, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dashed curve preview clipped segment by segment to bound offscreen dash allocation
|
||||
fn rubber_band(ui: &Ui, rect: Rect, line: &[Pos2]) {
|
||||
let painter = ui.painter_at(rect);
|
||||
for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] {
|
||||
painter.add(egui::Shape::dashed_line(&visible, stroke, RUBBER_BAND_DASH, RUBBER_BAND_GAP));
|
||||
let period = RUBBER_BAND_DASH + RUBBER_BAND_GAP;
|
||||
let mut distance = 0.0;
|
||||
for pair in line.windows(2) {
|
||||
if let Some(visible) = visible_dashes(rect, pair[0], pair[1]) {
|
||||
// Continue the dash pattern across sampled curve segments and clipped portions
|
||||
let phase = (distance + pair[0].distance(visible[0])) % period;
|
||||
for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] {
|
||||
// Draw any dash already in progress without extending behind this curve segment
|
||||
if phase > 0.0 && phase < RUBBER_BAND_DASH {
|
||||
let direction = visible[1] - visible[0];
|
||||
let end = visible[0] + direction.normalized() * (RUBBER_BAND_DASH - phase).min(direction.length());
|
||||
painter.line_segment([visible[0], end], stroke);
|
||||
}
|
||||
let offset = if phase == 0.0 { 0.0 } else { period - phase };
|
||||
painter.add(egui::Shape::dashed_line_with_offset(&visible, stroke, &[RUBBER_BAND_DASH], &[RUBBER_BAND_GAP], offset));
|
||||
}
|
||||
}
|
||||
distance = (distance + pair[0].distance(pair[1])) % period;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1474,7 +1718,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
&& !DecalDrop::blocks_input(ui.ctx());
|
||||
let mut fill_box = None;
|
||||
if painting && path_tool {
|
||||
path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show);
|
||||
path_input(app, ui, &response, (rect, true), |_, pointer| Some(to_uv(pointer).extend(0.0)), show);
|
||||
} else if painting && app.session.tool.tool == Tool::PolygonFill {
|
||||
fill_box = polygon_fill_input(
|
||||
app,
|
||||
@@ -1541,7 +1785,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
&& let Some(from) = app.last_paint_uv.and_then(|point| point.uv_for(&app.session))
|
||||
&& let Some(hover) = response.hover_pos()
|
||||
{
|
||||
rubber_band(ui, rect, to_screen(from.x, from.y), hover);
|
||||
rubber_band(ui, rect, &[to_screen(from.x, from.y), hover]);
|
||||
}
|
||||
|
||||
if app.ui.mode == crate::state::Mode::Baking {
|
||||
@@ -1656,6 +1900,60 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stored_surfaces_release_after_a_frame_without_paths() {
|
||||
use texturecraft_engine::{core::EffectKind, execute, geom::primitives};
|
||||
|
||||
let mut session = Session::new_project("Path cache", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
|
||||
session.viewport = Vec2::splat(400.0);
|
||||
session.camera.yaw = 0.0;
|
||||
session.camera.pitch = 0.0;
|
||||
let result = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap();
|
||||
let effect = texturecraft_engine::core::LayerId(result["committed"]["effect"].as_u64().unwrap());
|
||||
let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") };
|
||||
paths.resize(8, paths[0].clone());
|
||||
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let context = egui::Context::default();
|
||||
let mut previous = Vec::<std::sync::Weak<Vec<Vec<Option<Vec3>>>>>::new();
|
||||
|
||||
// Every path in the selection stays warm, and leaving it releases every sampled buffer
|
||||
for _ in 0..4 {
|
||||
let output = context.run_ui(Default::default(), |ui| {
|
||||
for index in 0..8 {
|
||||
let surface = stored_surface(harness.state(), ui, effect, index).unwrap();
|
||||
assert!(surface.iter().map(Vec::len).sum::<usize>() > 10);
|
||||
if let Some(cached) = previous.get(index) {
|
||||
assert!(Arc::ptr_eq(&cached.upgrade().unwrap(), &surface), "unchanged paths must not be resampled");
|
||||
} else {
|
||||
previous.push(Arc::downgrade(&surface));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// This cache lifecycle test has no renderer to consume texture updates
|
||||
output.drop_without_applying_deltas();
|
||||
}
|
||||
|
||||
let EffectKind::Path(paths) = &mut harness.state_mut().session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") };
|
||||
for path in paths {
|
||||
path.viewport = [800.0, 800.0];
|
||||
}
|
||||
let output = context.run_ui(Default::default(), |ui| {
|
||||
for (index, previous) in previous.iter_mut().enumerate() {
|
||||
let surface = stored_surface(harness.state(), ui, effect, index).unwrap();
|
||||
assert!(previous.upgrade().is_none(), "editing a path releases its obsolete samples");
|
||||
*previous = Arc::downgrade(&surface);
|
||||
}
|
||||
});
|
||||
output.drop_without_applying_deltas();
|
||||
|
||||
for _ in 0..2 {
|
||||
context.run_pass(Default::default(), |_| {}).drop_without_applying_deltas();
|
||||
}
|
||||
|
||||
assert!(previous.iter().all(|surface| surface.upgrade().is_none()), "unused path surfaces must be freed while the window stays open");
|
||||
}
|
||||
|
||||
/// A selected mask decal on the ball, with another texture set available for selection tests
|
||||
fn decal_frame_app(render: bool) -> egui_kittest::Harness<'static, TextureCraftApp> {
|
||||
let session =
|
||||
|
||||
@@ -367,7 +367,12 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
// Each row is the state after that many steps
|
||||
let steps = done_count - row as i64;
|
||||
if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() {
|
||||
jump = steps;
|
||||
// Point history is consumed before the document rows shown here
|
||||
jump = if steps >= 0 {
|
||||
app.session.history_undo_steps(steps as usize) as i64
|
||||
} else {
|
||||
-(app.session.history_redo_steps((-steps) as usize) as i64)
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3,9 +3,162 @@
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::docking::Panel;
|
||||
|
||||
/// Show document history so row clicks exercise the same command dispatch as the application
|
||||
fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> {
|
||||
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
harness.state_mut().ui.dock.focus(Panel::History);
|
||||
harness.run_steps(4);
|
||||
harness
|
||||
}
|
||||
|
||||
/// Three document rows provide an intermediate target that detects both short and excessive jumps
|
||||
fn renamed_session() -> Session {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
for name in ["Step A", "Step B", "Step C"] {
|
||||
execute(&mut session, "layer.rename", &json!({"name": name})).unwrap();
|
||||
}
|
||||
session
|
||||
}
|
||||
|
||||
/// Canceling a preview can be its own undo or part of undoing the first placed point
|
||||
#[test]
|
||||
fn history_jump_accounts_for_drafts_with_and_without_an_empty_checkpoint() {
|
||||
for placed in [false, true] {
|
||||
let mut session = renamed_session();
|
||||
let layer = session.selected_layer().unwrap();
|
||||
let effect_count = session.doc.project.layer(layer).unwrap().content_effects.len();
|
||||
if placed {
|
||||
execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap();
|
||||
for point in [Vec3::new(0.2, 0.5, 0.0), Vec3::new(0.5, 0.3, 0.0), Vec3::new(0.8, 0.5, 0.0)] {
|
||||
session.append_path_point(point, true);
|
||||
session.path_live().unwrap();
|
||||
}
|
||||
} else {
|
||||
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap();
|
||||
session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true);
|
||||
session.path_live().unwrap();
|
||||
}
|
||||
session.path_checkpoint();
|
||||
let mut harness = history_harness(session);
|
||||
|
||||
harness.get_all_by_label("Rename layer").next().unwrap().click();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step A");
|
||||
assert_eq!(harness.state().session.history_labels().len(), 1);
|
||||
assert_eq!(harness.state().session.redo_labels().len(), 2);
|
||||
assert!(harness.state().session.tool.path.points.is_empty());
|
||||
assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().content_effects.len(), effect_count);
|
||||
}
|
||||
}
|
||||
|
||||
/// A row jump traverses point history, while the Undo and Redo buttons still take one point step
|
||||
#[test]
|
||||
fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() {
|
||||
let mut session = renamed_session();
|
||||
let layer = session.selected_layer().unwrap();
|
||||
let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap();
|
||||
execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap();
|
||||
let original = session.tool.path.points.clone();
|
||||
session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true);
|
||||
session.path_live().unwrap();
|
||||
let moved = session.tool.path.points.clone();
|
||||
session.move_path_point(0, original[0], true);
|
||||
session.path_live().unwrap();
|
||||
session.path_checkpoint();
|
||||
let done = session.history_labels().len();
|
||||
let mut harness = history_harness(session);
|
||||
|
||||
harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click();
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.state().session.tool.path.points, moved);
|
||||
assert_eq!(harness.state().session.history_labels().len(), done);
|
||||
harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click();
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.state().session.tool.path.points, original);
|
||||
assert_eq!(harness.state().session.history_labels().len(), done);
|
||||
|
||||
harness.get_by_label("Edit path 1").click();
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.state().session.tool.path.points, original);
|
||||
assert_eq!(harness.state().session.history_labels().len(), done);
|
||||
|
||||
harness.get_all_by_label("Rename layer").next().unwrap().click();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step A");
|
||||
assert_eq!(harness.state().session.history_labels().len(), 1);
|
||||
assert_eq!(harness.state().session.redo_labels().len(), done - 1);
|
||||
assert!(harness.state().session.tool.path.points.is_empty());
|
||||
}
|
||||
|
||||
/// Incomplete filled curves keep point redo separate from the document redo rows
|
||||
#[test]
|
||||
fn history_redo_jump_accounts_for_point_steps_without_changing_single_steps() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let layer = session.selected_layer().unwrap();
|
||||
let report =
|
||||
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.3], [0.8, 0.5]], "closed": true, "fill": true, "commit": true})).unwrap();
|
||||
for name in ["Step A", "Step B", "Step C"] {
|
||||
execute(&mut session, "layer.rename", &json!({"name": name})).unwrap();
|
||||
}
|
||||
let done = session.history_labels().len();
|
||||
execute(&mut session, "edit.undo", &json!({"steps": 3})).unwrap();
|
||||
execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap();
|
||||
let original = session.tool.path.points.clone();
|
||||
|
||||
// Partial filled shapes do not repaint; their undo/redo leaves document redo available
|
||||
for points in [json!([[0.2, 0.5], [0.8, 0.5]]), json!([[0.2, 0.5]]), json!([[0.2, 0.5], [0.8, 0.5]])] {
|
||||
session.path_checkpoint();
|
||||
execute(&mut session, "tool.path", &json!({"uvPoints": points})).unwrap();
|
||||
}
|
||||
for _ in 0..3 {
|
||||
session.undo().unwrap();
|
||||
}
|
||||
assert_eq!(session.redo_labels().len(), 3);
|
||||
let mut harness = history_harness(session);
|
||||
|
||||
harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click();
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.state().session.tool.path.points.len(), 2);
|
||||
assert_eq!(harness.state().session.history_labels().len(), done - 3);
|
||||
harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click();
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.state().session.tool.path.points, original);
|
||||
assert_eq!(harness.state().session.history_labels().len(), done - 3);
|
||||
|
||||
harness.get_all_by_label("Rename layer (undone)").last().unwrap().click();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step C");
|
||||
assert_eq!(harness.state().session.history_labels().len(), done);
|
||||
assert!(harness.state().session.redo_labels().is_empty());
|
||||
assert!(harness.state().session.tool.path.points.is_empty());
|
||||
}
|
||||
|
||||
/// Returning to the current document row cancels a draft without undoing a document step
|
||||
#[test]
|
||||
fn clicking_the_current_history_row_cancels_a_draft() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let layer = session.selected_layer().unwrap();
|
||||
let effect_count = session.doc.project.layer(layer).unwrap().content_effects.len();
|
||||
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap();
|
||||
let mut harness = history_harness(session);
|
||||
|
||||
harness.get_by_label("Project opened").click();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert!(harness.state().session.tool.path.points.is_empty());
|
||||
assert!(harness.state().session.history_labels().is_empty());
|
||||
assert!(harness.state().session.redo_labels().is_empty());
|
||||
assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().content_effects.len(), effect_count);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_a_history_step_returns_to_it() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
|
||||
@@ -21,6 +21,7 @@ mod layers_panel;
|
||||
mod levels_editor;
|
||||
mod mask_value_swap;
|
||||
mod new_project_baked_maps;
|
||||
mod path_in_view;
|
||||
mod path_list;
|
||||
mod pen_pressure;
|
||||
mod polygon_fill;
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
//! The Path tool in the 2D view: placing previews the path, and points are edited where they are drawn
|
||||
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::LayerId;
|
||||
use texturecraft_engine::execute;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::state::ViewLayout;
|
||||
|
||||
type AppHarness<'a> = Harness<'a, TextureCraftApp>;
|
||||
|
||||
// Three points left to right across the middle of the 2D view's texture
|
||||
const A: Pos2 = pos2(600.0, 500.0);
|
||||
const B: Pos2 = pos2(700.0, 500.0);
|
||||
const C: Pos2 = pos2(800.0, 500.0);
|
||||
|
||||
/// A Path tool session whose texture fills the test pointer coordinates in the 2D view
|
||||
fn harness() -> AppHarness<'static> {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap();
|
||||
execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap();
|
||||
// Tall enough that the 2D view's texture square takes A, B and C
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.layout = ViewLayout::Only2D;
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
/// Advance one input frame, optionally changing the primary button's state
|
||||
fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option<bool>) {
|
||||
let events = &mut h.input_mut().events;
|
||||
events.push(Event::PointerMoved(pos));
|
||||
if let Some(pressed) = pressed {
|
||||
events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
}
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// Send a complete pointer click and allow the resulting preview to update
|
||||
fn click(h: &mut AppHarness<'_>, at: Pos2) {
|
||||
pointer(h, at, Some(true));
|
||||
pointer(h, at, Some(false));
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
/// Move through several frames so the test exercises drag grouping as well as its final position
|
||||
fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) {
|
||||
pointer(h, from, Some(true));
|
||||
for k in 1..=6 {
|
||||
pointer(h, from + (to - from) * (k as f32 / 6.0), None);
|
||||
}
|
||||
pointer(h, to, Some(false));
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
/// Dispatch an unmodified tool key and settle the resulting UI state
|
||||
fn key(h: &mut AppHarness<'_>, key: Key) {
|
||||
h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
/// The path sublayers of the selected layer: (id, stored paths)
|
||||
fn path_sublayers(h: &AppHarness<'_>) -> Vec<(LayerId, usize)> {
|
||||
let s = &h.state().session;
|
||||
let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap();
|
||||
layer.content_effects.iter().filter_map(|e| s.paths(e.id).map(|p| (e.id, p.len()))).collect()
|
||||
}
|
||||
|
||||
/// Channel images painted in path sublayer `eid`
|
||||
fn painted_channels(h: &AppHarness<'_>, eid: LayerId) -> usize {
|
||||
h.state().session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == eid).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_points_previews_the_path_and_enter_applies_it_as_one_step() {
|
||||
let mut h = harness();
|
||||
let steps = h.state().session.history_labels().len();
|
||||
for at in [A, B, C] {
|
||||
click(&mut h, at);
|
||||
}
|
||||
assert_eq!(h.state().session.tool.path.points.len(), 3);
|
||||
let [(eid, 1)] = path_sublayers(&h)[..] else { panic!("the preview is a path in a path sublayer: {:?}", path_sublayers(&h)) };
|
||||
assert!(painted_channels(&h, eid) > 0, "the preview painted");
|
||||
assert_eq!(h.state().session.history_labels().len(), steps, "no undo step while placing");
|
||||
key(&mut h, Key::Enter);
|
||||
assert_eq!(h.state().session.history_labels().len(), steps + 1);
|
||||
assert_eq!(h.state().session.undo_label(), Some("Path"));
|
||||
assert!(h.state().session.tool.path.points.is_empty());
|
||||
assert_eq!(path_sublayers(&h), vec![(eid, 1)]);
|
||||
}
|
||||
|
||||
/// Applying with the pointer commits the preview without leaving the current texture set
|
||||
#[test]
|
||||
fn apply_button_commits_the_path_in_the_current_texture_set() {
|
||||
let mut h = harness();
|
||||
assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled());
|
||||
let steps = h.state().session.history_labels().len();
|
||||
let texture_set = h.state().session.ts();
|
||||
for at in [A, B, C] {
|
||||
click(&mut h, at);
|
||||
}
|
||||
let paths = path_sublayers(&h);
|
||||
let preview = h.state().session.doc.pixels.layers.clone();
|
||||
|
||||
// Path controls share the horizontally scrolling brush toolbar
|
||||
h.get_all_by_label("Apply").next().unwrap().scroll_to_me();
|
||||
h.run_steps(30);
|
||||
assert!(!h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled());
|
||||
h.get_all_by_label("Apply").next().unwrap().click();
|
||||
h.run_steps(2);
|
||||
|
||||
assert_eq!(h.state().session.ts(), texture_set);
|
||||
assert_eq!(h.state().session.history_labels().len(), steps + 1);
|
||||
assert!(h.state().session.tool.path.points.is_empty());
|
||||
assert_eq!(path_sublayers(&h), paths);
|
||||
assert_eq!(h.state().session.doc.pixels.layers, preview);
|
||||
assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_an_applied_path_edits_it_and_dragging_a_point_changes_it() {
|
||||
let mut h = harness();
|
||||
for at in [A, B, C] {
|
||||
click(&mut h, at);
|
||||
}
|
||||
key(&mut h, Key::Enter);
|
||||
let [(eid, 1)] = path_sublayers(&h)[..] else { panic!("one path") };
|
||||
let stored = |h: &AppHarness<'_>| h.state().session.paths(eid).unwrap()[0].points.clone();
|
||||
let before = stored(&h);
|
||||
let steps = h.state().session.history_labels().len();
|
||||
|
||||
// A click on the path's curve opens it for editing without repainting it
|
||||
click(&mut h, A.lerp(B, 0.5));
|
||||
assert_eq!(h.state().session.tool.path.editing, Some((eid, 0)));
|
||||
assert_eq!(h.state().session.history_labels().len(), steps, "opening a path repaints nothing");
|
||||
|
||||
drag(&mut h, B, B + egui::vec2(0.0, 60.0));
|
||||
let after = stored(&h);
|
||||
assert_eq!(after.len(), 3);
|
||||
assert_eq!((after[0], after[2]), (before[0], before[2]));
|
||||
assert!(after[1][1] > before[1][1], "the dragged point moved down: {:?} -> {:?}", before[1], after[1]);
|
||||
assert_eq!(h.state().session.history_labels().len(), steps + 1, "the edit is one step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_the_2d_view_preserves_a_stored_3d_path_being_edited() {
|
||||
let mut session =
|
||||
texturecraft_engine::Session::new_project("t", texturecraft_engine::geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap();
|
||||
session.camera.yaw = 0.0;
|
||||
session.camera.pitch = 0.0;
|
||||
session.update();
|
||||
let report = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [260, 210]], "viewport": [400, 400], "commit": true})).unwrap();
|
||||
execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap();
|
||||
let before = session.doc.clone();
|
||||
let path = session.tool.path.clone();
|
||||
let history = session.history_labels();
|
||||
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
harness.state_mut().ui.layout = ViewLayout::Split;
|
||||
harness.run_steps(4);
|
||||
let view_3d = harness.state().viewport_rect;
|
||||
let view_2d_center = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y);
|
||||
|
||||
click(&mut harness, view_2d_center);
|
||||
|
||||
assert_eq!(harness.state().session.tool.path, path);
|
||||
assert_eq!(harness.state().session.doc.project, before.project);
|
||||
assert_eq!(harness.state().session.doc.pixels.layers, before.pixels.layers);
|
||||
assert_eq!(harness.state().session.history_labels(), history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_the_curve_inserts_a_point_and_backspace_removes_the_selected_one() {
|
||||
let mut h = harness();
|
||||
for at in [A, B, C] {
|
||||
click(&mut h, at);
|
||||
}
|
||||
let path = |h: &AppHarness<'_>| h.state().session.tool.path.clone();
|
||||
let before = path(&h).points;
|
||||
click(&mut h, B.lerp(C, 0.5));
|
||||
let after = path(&h);
|
||||
assert_eq!(after.points.len(), 4, "inserted, not appended");
|
||||
assert_eq!(after.selected, Some(2));
|
||||
assert_eq!((after.points[1], after.points[3]), (before[1], before[2]));
|
||||
assert!(after.points[2].x > before[1].x && after.points[2].x < before[2].x);
|
||||
|
||||
// B, not A: clicking the first point closes the path
|
||||
click(&mut h, B);
|
||||
assert_eq!(path(&h).selected, Some(1));
|
||||
key(&mut h, Key::Backspace);
|
||||
assert_eq!(path(&h).points, vec![after.points[0], after.points[2], after.points[3]]);
|
||||
|
||||
// Undo brings the point back and keeps the path; again, the inserted point goes
|
||||
let undo = |h: &mut AppHarness<'_>| {
|
||||
h.input_mut().events.push(Event::Key { key: Key::Z, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND });
|
||||
h.run_steps(2);
|
||||
};
|
||||
undo(&mut h);
|
||||
assert_eq!(path(&h).points, after.points);
|
||||
undo(&mut h);
|
||||
assert_eq!(path(&h).points, before);
|
||||
assert!(!path_sublayers(&h).is_empty(), "the path is still there");
|
||||
}
|
||||
@@ -419,7 +419,9 @@ fn escape_cancels_a_path_with_a_hidden_rail_popup() {
|
||||
assert!(harness.state().ui.hide_ui);
|
||||
assert!(popup_closed(&harness));
|
||||
assert_eq!(harness.state().session.tool.path.points.len(), 2);
|
||||
assert_eq!(harness.state().session.tool.path.editing.is_some(), stored_path);
|
||||
|
||||
// Drafts and committed paths both have a live preview target while edited
|
||||
let (effect, index) = harness.state().session.tool.path.editing.unwrap();
|
||||
let history = harness.state().session.history_labels();
|
||||
|
||||
harness.key_press(egui::Key::Escape);
|
||||
@@ -428,6 +430,11 @@ fn escape_cancels_a_path_with_a_hidden_rail_popup() {
|
||||
assert!(harness.state().session.tool.path.points.is_empty(), "one Escape clears the path despite the hidden popup");
|
||||
assert!(harness.state().session.tool.path.editing.is_none());
|
||||
assert_eq!(harness.state().session.history_labels(), history);
|
||||
assert_eq!(
|
||||
harness.state().session.paths(effect).and_then(|paths| paths.get(index)).is_some(),
|
||||
stored_path,
|
||||
"Escape removes a draft but keeps a committed path"
|
||||
);
|
||||
|
||||
harness.key_press(egui::Key::Tab);
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
|
||||
@@ -406,6 +406,26 @@ fn nested_layers_snapshot() {
|
||||
save(&mut harness, &output_dir, "panel-layers-narrow-nested");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn path_tool_snapshots() {
|
||||
let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return };
|
||||
|
||||
std::fs::create_dir_all(&output_dir).unwrap();
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
texturecraft_engine::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap();
|
||||
texturecraft_engine::execute(&mut session, "tool.path", &serde_json::json!({"uvPoints": [[0.25, 0.5], [0.5, 0.3], [0.75, 0.5]]})).unwrap();
|
||||
let mut harness =
|
||||
Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Only2D;
|
||||
harness.state_mut().session.select_path_point(1);
|
||||
harness.hover_at(egui::pos2(800.0, 600.0));
|
||||
save(&mut harness, &output_dir, "path-preview-2d");
|
||||
|
||||
harness.state_mut().session.commit_path(texturecraft_engine::geom::glam::Vec2::splat(400.0)).unwrap();
|
||||
save(&mut harness, &output_dir, "path-stored-2d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn rail_window_snapshots() {
|
||||
|
||||
Reference in new issue
Block a user