Merge pull request #323 from Rebornim/feat/polygon-fill-parity

Polygon fill: box selection, polygon mode, hit-test, visible polygons only and the 2D view
This commit is contained in:
Chris Hassebrook authored and GitHub committed 2026-11-08 02:49:29 -05:00
commit b177ecc912
27 files changed
+1972 -253

No files matched your search

+83
View File
@@ -0,0 +1,83 @@
//! Which polygons a polygon fill box selects.
use serde::{Deserialize, Serialize};
use texturecraft_geom::glam::Vec2;
/// How a polygon fill box decides whether it selects a polygon
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum FillHitTest {
/// Any part of the polygon inside the box or crossing it
#[default]
Intersection,
/// The polygon's center point inside the box
ContainedCenter,
}
impl FillHitTest {
/// Whether the box from `low` to `high` selects the polygon made of `triangles` (their corners)
pub fn selects(self, triangles: &[[Vec2; 3]], low: Vec2, high: Vec2) -> bool {
match self {
FillHitTest::Intersection => triangles.iter().any(|corners| triangle_overlaps_box(*corners, low, high)),
FillHitTest::ContainedCenter => center(triangles).is_some_and(|point| point.cmpge(low).all() && point.cmple(high).all()),
}
}
}
/// Area-weighted center of the triangles (their corners' mean when they have no area)
fn center(triangles: &[[Vec2; 3]]) -> Option<Vec2> {
if triangles.is_empty() {
return None;
}
// One pass: total area, area-weighted centroids and plain centroids
let (total_area, weighted, centroids) = triangles.iter().fold((0.0, Vec2::ZERO, Vec2::ZERO), |(total_area, weighted, centroids), corners| {
let area = (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs();
let centroid = (corners[0] + corners[1] + corners[2]) / 3.0;
(total_area + area, weighted + centroid * area, centroids + centroid)
});
Some(if total_area > 0.0 { weighted / total_area } else { centroids / triangles.len() as f32 })
}
/// Separating axis test of a triangle against an axis-aligned box
fn triangle_overlaps_box(corners: [Vec2; 3], low: Vec2, high: Vec2) -> bool {
let triangle_low = corners[0].min(corners[1]).min(corners[2]);
let triangle_high = corners[0].max(corners[1]).max(corners[2]);
if triangle_high.cmplt(low).any() || triangle_low.cmpgt(high).any() {
return false;
}
let box_corners = [low, Vec2::new(high.x, low.y), high, Vec2::new(low.x, high.y)];
(0..3).all(|edge| {
let axis = (corners[(edge + 1) % 3] - corners[edge]).perp();
let span = |points: &[Vec2]| points.iter().fold((f32::MAX, f32::MIN), |(min, max), point| (min.min(axis.dot(*point)), max.max(axis.dot(*point))));
let (triangle_min, triangle_max) = span(&corners);
let (box_min, box_max) = span(&box_corners);
triangle_max >= box_min && box_max >= triangle_min
})
}
#[cfg(test)]
mod tests {
use super::*;
const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)];
#[test]
fn intersection_selects_any_overlap() {
assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(6.0)), "a box cutting the triangle");
assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(3.0), Vec2::splat(5.0)), "inside the bounds, past the long edge");
}
#[test]
fn contained_center_selects_only_by_the_center() {
assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(2.0), Vec2::splat(6.0)), "the center (4/3, 4/3) lies outside");
assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0)));
}
#[test]
fn a_polygon_center_weighs_its_triangles_by_area() {
let square = [[Vec2::ZERO, Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0)], [Vec2::ZERO, Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)]];
assert_eq!(center(&square), Some(Vec2::ONE));
assert_eq!(center(&[]), None);
}
}
+17
View File
@@ -0,0 +1,17 @@
//! What one polygon fill target grows to.
use serde::{Deserialize, Serialize};
/// Polygon fill granularity: what a clicked triangle or a boxed polygon grows to
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum FillMode {
/// The triangle itself
#[default]
Triangle,
/// The source polygon (quad or n-gon) the importer split into triangles
Polygon,
/// The UV island: triangles sharing edges in UV space
UvIsland,
/// The connected geometry: triangles sharing edges by position
Mesh,
}
+8 -1
View File
@@ -15,6 +15,8 @@ pub mod commands;
pub mod decal_cmds;
pub mod effect_clipboard;
pub mod file_cmds;
pub mod fill_hit_test;
pub mod fill_mode;
pub mod filter_lib;
pub mod inspect;
pub mod instance_cmds;
@@ -31,6 +33,8 @@ pub mod materialx_cmds;
pub mod meshmap_cmds;
pub mod painting;
pub mod path_tool;
mod polygon_fill;
mod polygon_fill_drag;
// Mesh reimport reads files: native only.
#[cfg(not(target_arch = "wasm32"))]
mod preserve;
@@ -45,14 +49,17 @@ pub mod smart_masks;
pub mod template_cmds;
pub mod text_cmds;
pub mod tool_cmds;
mod triangle_partition;
pub mod uv_tile_cmds;
pub mod view_cmds;
pub use bake::{BakeMesh, BakeMeshes, BakeTask};
pub use commands::{CommandSpec, command_specs, execute, find};
pub use fill_hit_test::FillHitTest;
pub use fill_mode::FillMode;
pub use path_tool::PathState;
pub use project_cmds::sample_session;
pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
pub use set_cmds::{ResizeOutput, ResizeTask};
pub use texturecraft_compose as compose;
+29 -102
View File
@@ -7,11 +7,11 @@ use texturecraft_compose::PaintTarget;
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground};
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::{
CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask,
fill_triangles, pick, rasterize,
CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick,
rasterize,
};
use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool};
use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool};
use crate::{EngineError, Result};
impl Session {
@@ -301,12 +301,15 @@ impl Session {
Ok(self.continue_stroke(screen, pressure))
}
/// Start a stroke in the 2D view at texture coordinate `uv`.
/// Start a stroke in the 2D view at texture coordinate `uv` (polygon fill fills there).
pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> {
self.cancel_stroke();
if matches!(self.tool.tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask) {
return Err(EngineError::Other("use this tool in the 3D view".into()));
match self.tool.tool {
Tool::PolygonFill => return self.polygon_fill_uv(uv).map(|_| ()),
Tool::ColorPicker | Tool::GeometryMask => return Err(EngineError::Other("use this tool in the 3D view".into())),
_ => {}
}
self.start_stroke(self.viewport, true, Some(uv))?;
self.continue_stroke_uv(uv, pressure);
Ok(())
@@ -482,21 +485,6 @@ impl Session {
Ok(tiles)
}
/// Polygon fill: fill the triangle / UV island / whole mesh under `screen`.
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
let ts = self.ts();
let material = self.doc.project.texture_set(ts)?.material;
if hit.material != material {
return Err(EngineError::Other("that surface belongs to another texture set".into()));
}
let tris = self.fill_set(hit.tri, material);
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
fill_triangles(&mut canvas, &gbuf, &tris);
self.commit_fill("Polygon fill", ts, &canvas)?;
Ok(tris.len())
}
/// The G-buffer of texture set `ts` and an empty canvas for a one-shot fill, limited by the
/// quick mask unless the fill edits it.
pub(crate) fn fill_canvas(&self, ts: usize) -> Result<(std::sync::Arc<texturecraft_geom::UvGBuffer>, StrokeCanvas)> {
@@ -510,61 +498,31 @@ impl Session {
/// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask.
pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
let size = (canvas.alpha.width(), canvas.alpha.height());
let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None };
if self.quick_mask.editing {
self.commit_quick_mask(ts, size, src(self.tool.brush.opacity));
return Ok(());
return self.paint_fill(ts, canvas);
}
self.edit(label, |s| {
let target = s.paint_target()?;
let values = s.stroke_values(target);
match target {
PaintTarget::Layer(id) => commit_layer(&mut s.doc.pixels, id, size, &values, src(s.tool.brush.opacity), &mut Staging::default()),
PaintTarget::Mask(eid) => commit_mask(&mut s.doc.pixels, eid, size, s.tool.mask_value, src(s.tool.brush.opacity), &mut Staging::default()),
}
Ok(())
})
// Each fill is its own step, never merged into a box drag's step of the same label
self.edit_merging(label, false, |session| session.paint_fill(ts, canvas))
}
/// Triangles filled by the current fill mode starting from `tri`.
fn fill_set(&self, tri: u32, material: usize) -> BTreeSet<u32> {
let m = &self.mesh;
match self.tool.fill_mode {
FillMode::Triangle => [tri].into_iter().collect(),
FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(),
FillMode::UvIsland => {
// Triangles sharing an edge in UV space form a UV island: imported meshes often
// split vertices along hard edges (or per face) where the UVs run on, so shared
// vertex indices alone break an island into its polygons.
let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]);
let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) {
Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(),
_ => Vec::new(),
};
let mut by_edge: BTreeMap<_, Vec<u32>> = BTreeMap::new();
for t in m.triangles_of(material) {
for e in edges(t) {
by_edge.entry(e).or_default().push(t as u32);
}
}
let mut seen = BTreeSet::new();
let mut stack = vec![tri];
while let Some(t) = stack.pop() {
if !seen.insert(t) {
continue;
}
for e in edges(t as usize) {
for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) {
if !seen.contains(n) {
stack.push(*n);
}
}
}
}
seen
}
/// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step)
pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
let size = (canvas.alpha.width(), canvas.alpha.height());
let opacity = self.tool.brush.opacity;
let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None };
if self.quick_mask.editing {
self.commit_quick_mask(ts, size, source);
return Ok(());
}
let target = self.paint_target()?;
let values = self.stroke_values(target);
match target {
PaintTarget::Layer(id) => commit_layer(&mut self.doc.pixels, id, size, &values, source, &mut Staging::default()),
PaintTarget::Mask(effect) => commit_mask(&mut self.doc.pixels, effect, size, self.tool.mask_value, source, &mut Staging::default()),
}
Ok(())
}
/// Color picker: copy the material under the cursor into the tool's paint values.
@@ -627,34 +585,3 @@ fn with_commit_source<R>(
let carried = st.canvas.pickup.as_ref().map(|p| &p.values);
f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried })
}
#[cfg(test)]
mod tests {
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::mesh::Mesh;
use texturecraft_geom::primitives;
use crate::session::{FillMode, Session};
#[test]
fn uv_island_fill_follows_uvs_across_split_vertices() {
// Two copies of a plane, each triangle with its own three vertices (as hard edges or
// per-face imports leave a mesh), the second copy apart in UV space.
let plane = primitives::plane(2.0, 4);
let (mut positions, mut uvs) = (Vec::<Vec3>::new(), Vec::<Vec2>::new());
for shift in [0.0, 0.5] {
for i in plane.indices.iter().map(|i| *i as usize) {
positions.push(plane.positions[i] + Vec3::Y * shift);
uvs.push(plane.uvs[i] * 0.5 + shift);
}
}
let indices = (0..positions.len() as u32).collect();
let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap();
let n = plane.triangle_count();
assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared");
let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap();
s.tool.fill_mode = FillMode::UvIsland;
assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island");
assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island");
}
}
+607
View File
@@ -0,0 +1,607 @@
//! Polygon fill: fill the triangles, polygons, UV islands or connected meshes under a click or inside a dragged box, in either view.
use std::borrow::Cow;
use std::collections::{BTreeSet, HashSet};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Mesh, NO_TRI};
use texturecraft_paint::{EyeDepth, fill_triangles, screen_point};
use crate::fill_mode::FillMode;
use crate::polygon_fill_drag::PolygonFillDrag;
use crate::session::Session;
use crate::triangle_partition::TrianglePartition;
use crate::{EngineError, Result};
/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner
const CORNER_GRID_STEPS: f32 = 1e5;
impl Session {
/// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen`
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
if hit.material != self.fill_material()? {
return Err(EngineError::Other("that surface belongs to another texture set".into()));
}
self.fill_group_of(hit.tri)
}
/// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view): the triangle covering that texel's center, so slivers thinner than a texel can't be clicked
pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result<usize> {
let gbuf = self.caches.get(self.ts()).map(|cache| cache.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let size = Vec2::new(gbuf.width as f32, gbuf.height as f32);
let texel = (uv * size).floor();
let triangle = (texel.cmpge(Vec2::ZERO).all() && texel.cmplt(size).all())
.then(|| gbuf.tri.get(texel.y as usize * gbuf.width as usize + texel.x as usize).copied())
.flatten()
.filter(|triangle| *triangle != NO_TRI)
.ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
self.fill_group_of(triangle)
}
/// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step)
pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result<usize> {
// A scripted box stands alone: it finishes any drag under way, and ends even when it fails
self.end_polygon_fill_box();
let shown = self.drag_polygon_fill_box(corner, opposite, viewport);
let filled = self.end_polygon_fill_box();
shown.map(|_| filled)
}
/// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step)
pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result<usize> {
self.end_polygon_fill_box();
let shown = self.drag_polygon_fill_box_uv(corner, opposite);
let filled = self.end_polygon_fill_box();
shown.map(|_| filled)
}
/// Show the fill of a box being dragged between viewport pixels `corner` and `opposite`
pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result<usize> {
// Whole pixels, as the visibility buffer is rendered at
self.drag_polygon_fill(corner, opposite, Some(viewport.round().max(Vec2::ONE)))
}
/// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view)
pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result<usize> {
self.drag_polygon_fill(corner, opposite, None)
}
/// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count
pub fn end_polygon_fill_box(&mut self) -> usize {
let Some(drag) = self.polygon_fill_drag.take() else { return 0 };
let filled = drag.filled.len();
// Quick mask edits keep no history, as with its strokes
if filled > 0 && drag.quick_mask_before.is_none() {
self.push_history("Polygon fill", drag.before);
}
filled
}
/// Show the fill of a box from `corner` to `opposite` in the 3D view of size `viewport`, or in the 2D view when None
fn drag_polygon_fill(&mut self, corner: Vec2, opposite: Vec2, viewport: Option<Vec2>) -> Result<usize> {
if !corner.is_finite() || !opposite.is_finite() {
return Err(EngineError::Other("the box corners must be finite".into()));
}
let (low, high) = (corner.min(opposite), corner.max(opposite));
self.start_polygon_fill_drag(viewport)?;
let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) };
if drag.failed || drag.last_box == Some((low, high)) {
return Ok(drag.filled.len());
}
drag.last_box = Some((low, high));
let selected = self.box_selection(low, high);
self.show_box_fill(selected)
}
/// Continue a box drag only while its view, paint target and quick mask state still match
fn start_polygon_fill_drag(&mut self, viewport: Option<Vec2>) -> Result<()> {
let ts = self.ts();
let target = (self.selected_layer(), self.target);
let quick_mask = self.quick_mask.editing;
// Finish the old target before another preview can restore its earlier document snapshot
if let Some(drag) = &self.polygon_fill_drag {
if drag.ts == ts && drag.target == target && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask {
// A camera move (a wheel zoom mid-drag) keeps the drag, which then sees the mesh from the new camera
if drag.camera != self.camera {
let (points, depth) = self.box_space(viewport);
if let Some(drag) = self.polygon_fill_drag.as_mut() {
(drag.points, drag.depth, drag.camera, drag.last_box) = (points, depth, self.camera, None);
}
}
return Ok(());
}
self.end_polygon_fill_box();
}
let material = self.fill_material()?;
let (points, depth) = self.box_space(viewport);
let polygons = match self.tool.fill_mode {
FillMode::Triangle | FillMode::Polygon => None,
FillMode::UvIsland | FillMode::Mesh => Some(TrianglePartition::new(&self.mesh, material, polygon_edges)),
};
self.polygon_fill_drag = Some(PolygonFillDrag {
ts,
target,
viewport,
camera: self.camera,
before: self.doc.clone(),
quick_mask_before: quick_mask.then(|| self.quick_mask.masks.clone()),
points,
depth,
fill_groups: self.fill_partition(material),
polygons,
filled: BTreeSet::new(),
last_box: None,
failed: false,
});
Ok(())
}
/// Each vertex where a box sees it (viewport pixels for a 3D view of size `viewport`, else texture coordinates) and, for visible polygons only in 3D, what the camera sees
fn box_space(&self, viewport: Option<Vec2>) -> (Vec<Option<Vec2>>, Option<EyeDepth>) {
let Some(size) = viewport else { return (self.mesh.uvs.iter().copied().map(Some).collect(), None) };
let view_proj = self.camera.view_proj(size.x / size.y);
let points = self.mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect();
let depth = self.tool.fill_visible_only.then(|| EyeDepth::render_with_triangles(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32));
(points, depth)
}
/// The mesh material of the texture set being painted
fn fill_material(&self) -> Result<usize> {
Ok(self.doc.project.texture_set(self.ts())?.material)
}
/// The triangles the current fill mode fills together, for `material`
fn fill_partition(&self, material: usize) -> TrianglePartition {
match self.tool.fill_mode {
FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::<u32>::new()),
FillMode::Polygon => TrianglePartition::new(&self.mesh, material, polygon_edges),
FillMode::UvIsland => TrianglePartition::new(&self.mesh, material, uv_edges),
FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges),
}
}
/// Fill the fill-mode group holding `triangle` (one undo step)
fn fill_group_of(&mut self, triangle: u32) -> Result<usize> {
let ts = self.ts();
let groups = self.fill_partition(self.fill_material()?);
let triangles: BTreeSet<u32> = groups.group(triangle).unwrap_or_default().iter().copied().collect();
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
fill_triangles(&mut canvas, &gbuf, &triangles);
self.commit_fill("Polygon fill", ts, &canvas)?;
Ok(triangles.len())
}
/// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden
fn shown_mesh(&self) -> Cow<'_, Mesh> {
let sets = &self.doc.project.texture_sets;
if sets.iter().all(|set| set.visible) {
return Cow::Borrowed(&self.mesh);
}
let mut mesh = (*self.mesh).clone();
for set in sets.iter().filter(|set| !set.visible) {
for triangle in self.mesh.triangles_of(set.material) {
if let Some(corners) = mesh.indices.get_mut(triangle * 3..triangle * 3 + 3) {
let first = corners[0];
corners.fill(first);
}
}
}
Cow::Owned(mesh)
}
/// Triangles the dragged box from `low` to `high` fills: each polygon the hit-test selects, grown by the fill mode
fn box_selection(&self, low: Vec2, high: Vec2) -> BTreeSet<u32> {
let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() };
let visible = drag.depth.as_ref().zip(drag.viewport).map(|(depth, viewport)| visible_triangles(depth, viewport, low, high));
let point = |vertex: usize| drag.points.get(vertex).copied().flatten();
let corners = |triangle: u32| {
let [first, second, third] = self.mesh.tri(triangle as usize)?;
Some([point(first)?, point(second)?, point(third)?])
};
let hit_test = self.tool.fill_hit_test;
let mut polygon_corners = Vec::new();
let mut groups = BTreeSet::new();
for polygon in &drag.polygons.as_ref().unwrap_or(&drag.fill_groups).groups {
let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle)));
if !seen {
continue;
}
polygon_corners.clear();
polygon_corners.extend(polygon.iter().map_while(|triangle| corners(*triangle)));
if polygon_corners.len() == polygon.len() && hit_test.selects(&polygon_corners, low, high) {
groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle)));
}
}
groups.iter().filter_map(|group| drag.fill_groups.groups.get(*group)).flatten().copied().collect()
}
/// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed
fn show_box_fill(&mut self, selected: BTreeSet<u32>) -> Result<usize> {
let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) };
if drag.filled == selected {
return Ok(selected.len());
}
let ts = drag.ts;
let previous = std::mem::replace(&mut self.doc, drag.before.clone());
if let Some(masks) = &drag.quick_mask_before {
self.quick_mask.masks = masks.clone();
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
}
let painted = if selected.is_empty() {
Ok(())
} else {
self.fill_canvas(ts).and_then(|(gbuf, mut canvas)| {
fill_triangles(&mut canvas, &gbuf, &selected);
self.paint_fill(ts, &canvas)
})
};
self.invalidate_changed(&previous);
// A failed fill is reported once and leaves the document as before the drag; the rest of the drag fills nothing
let selected_count = selected.len();
if let Some(drag) = self.polygon_fill_drag.as_mut() {
drag.failed = painted.is_err();
drag.filled = if drag.failed { BTreeSet::new() } else { selected };
}
painted.map(|_| selected_count)
}
}
/// Triangles `depth` (rendered for a `viewport` pixel view) shows in the viewport pixels from `low` to `high`, both edges included
fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet<u32> {
let depth_pixels_per_viewport_pixel = Vec2::new(depth.width as f32, depth.height as f32) / viewport;
let (low, high) = (low * depth_pixels_per_viewport_pixel, high * depth_pixels_per_viewport_pixel);
let columns = pixel_span(low.x, high.x, depth.width);
let rows = pixel_span(low.y, high.y, depth.height);
rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start)))
.copied()
.filter(|triangle| *triangle != NO_TRI)
.collect()
}
/// The pixels `0..count` a span from `low` to `high` covers, both edges included (empty when it lies outside)
fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range<usize> {
let first = low.floor().clamp(0.0, count as f32) as usize;
let end = (high.floor() + 1.0).clamp(0.0, count as f32) as usize;
first..end.max(first)
}
/// Texture coordinates of `triangle`'s corners
fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> {
let [first, second, third] = mesh.tri(triangle)?;
Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?])
}
/// The polygon diagonals of `triangle`: edges the importer added to split a polygon
fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> {
let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0);
let Some(vertices) = mesh.indices.get(triangle * 3..triangle * 3 + 3) else { return Vec::new() };
(0..3)
.filter(|edge| hidden >> edge & 1 == 1)
.map(|edge| {
let (from, to) = (vertices[edge], vertices[(edge + 1) % 3]);
(from.min(to), from.max(to))
})
.collect()
}
/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart
fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> {
let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64);
let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() };
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
}
/// `triangle`'s edges by position: UV seams and hard edges split vertices but leave the geometry connected
fn position_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 3], [i64; 3])> {
let corner = |vertex: usize| mesh.positions.get(vertex).map(|position| (*position * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64));
let Some([first, second, third]) = mesh.tri(triangle) else { return Vec::new() };
let (Some(first), Some(second), Some(third)) = (corner(first), corner(second), corner(third)) else { return Vec::new() };
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
}
#[cfg(test)]
mod tests {
use texturecraft_core::Channel;
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::mesh::Mesh;
use texturecraft_geom::primitives;
use crate::fill_hit_test::FillHitTest;
use crate::fill_mode::FillMode;
use crate::session::{Session, Tool};
/// The roughness the test fills paint, to tell filled texels apart
const FILL_ROUGHNESS: f32 = 0.9;
/// A polygon fill session on `mesh` painting roughness [`FILL_ROUGHNESS`]
fn fill_session(mesh: Mesh) -> Session {
let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap();
session.viewport = Vec2::new(400.0, 400.0);
session.tool.tool = Tool::PolygonFill;
session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]);
session.update();
session
}
/// Whether the texel at texture coordinate `uv` shows the fill's roughness
fn filled_at(session: &Session, uv: Vec2) -> bool {
let (width, height) = session.caches[0].size;
let roughness = session.caches[0].composite.value(Channel::Roughness, (uv.x * width as f32) as u32, (uv.y * height as f32) as u32);
(roughness[0] - FILL_ROUGHNESS).abs() < 0.01
}
/// Two copies of a plane apart in space and in UV space, each triangle with its own three vertices (as hard edges or per-face imports leave a mesh)
fn split_planes() -> (Mesh, usize) {
let plane = primitives::plane(2.0, 4);
let (mut positions, mut uvs) = (Vec::<Vec3>::new(), Vec::<Vec2>::new());
for shift in [0.0, 0.5] {
for vertex in plane.indices.iter().map(|index| *index as usize) {
positions.push(plane.positions[vertex] + Vec3::Y * shift);
uvs.push(plane.uvs[vertex] * 0.5 + shift);
}
}
let indices = (0..positions.len() as u32).collect();
let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap();
assert_eq!(mesh.vertex_count(), 6 * plane.triangle_count(), "no vertex is shared");
(mesh, plane.triangle_count())
}
#[test]
fn uv_island_and_mesh_fills_follow_seams_split_vertices_leave_apart() {
let (mesh, per_plane) = split_planes();
let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap();
for fill_mode in [FillMode::UvIsland, FillMode::Mesh] {
session.tool.fill_mode = fill_mode;
let groups = session.fill_partition(0);
assert_eq!(groups.group(0).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: the whole first plane");
assert_eq!(groups.group(per_plane as u32).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: only the second plane");
}
}
#[test]
fn polygon_mode_groups_the_two_triangles_of_each_quad() {
let mut session = fill_session(primitives::plane(2.0, 2));
session.tool.fill_mode = FillMode::Triangle;
assert_eq!(session.fill_partition(0).group(0), Some(&[0][..]));
session.tool.fill_mode = FillMode::Polygon;
let mut quad = session.fill_partition(0).group(0).unwrap().to_vec();
quad.sort_unstable();
assert_eq!(quad, [0, 1], "the quad's two triangles and no other quad");
}
#[test]
fn a_uv_box_over_half_a_plane_fills_that_half() {
let mut session = fill_session(primitives::plane(2.0, 4));
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
let filled = session.polygon_fill_box_uv(Vec2::new(-0.01, -0.01), Vec2::new(0.5, 1.01)).unwrap();
session.update();
assert_eq!(filled, 16, "the left two columns of quads");
assert!(filled_at(&session, Vec2::new(0.1, 0.5)) && filled_at(&session, Vec2::new(0.45, 0.9)));
assert!(!filled_at(&session, Vec2::new(0.55, 0.5)) && !filled_at(&session, Vec2::new(0.9, 0.1)));
}
#[test]
fn intersection_and_contained_center_differ_on_a_box_missing_a_quads_center() {
let mut session = fill_session(primitives::plane(2.0, 2));
session.tool.fill_mode = FillMode::Polygon;
let (corner, opposite) = (Vec2::new(0.0, 0.0), Vec2::new(0.2, 0.2));
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 0, "the quad's center (0.25, 0.25) is outside");
assert_ne!(session.undo_label(), Some("Polygon fill"), "an empty box records no undo step");
session.tool.fill_hit_test = FillHitTest::Intersection;
assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 2, "the quad the box cuts");
}
#[test]
fn visible_only_skips_the_back_of_a_cube() {
let mut session = fill_session(primitives::cube(1.0));
session.camera.yaw = 0.6;
session.camera.pitch = 0.4;
let (low, high) = (Vec2::ZERO, session.viewport);
let every_triangle = session.mesh.triangle_count();
session.tool.fill_visible_only = true;
assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle / 2, "the three sides the camera sees");
session.tool.fill_visible_only = false;
assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle);
}
#[test]
fn visible_only_sees_through_a_hidden_texture_set() {
let mut session = fill_session(primitives::material_ball());
let base = session.doc.project.texture_sets.iter().position(|set| set.name == "Base").unwrap();
session.active_set = base;
let (low, high) = (Vec2::ZERO, session.viewport);
let behind_the_ball = session.polygon_fill_box(low, high, session.viewport).unwrap();
session.doc.project.texture_sets[0].visible = false;
let ball_hidden = session.polygon_fill_box(low, high, session.viewport).unwrap();
assert!(ball_hidden > behind_the_ball, "hiding the ball shows more of the base: {ball_hidden} vs {behind_the_ball}");
}
#[test]
fn a_dragged_box_fills_live_and_records_one_step_when_it_ends() {
let mut session = fill_session(primitives::plane(2.0, 4));
let history = session.history_labels().len();
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32);
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(), 16, "shrinking the box unfills");
session.update();
assert!(filled_at(&session, Vec2::new(0.2, 0.5)) && !filled_at(&session, Vec2::new(0.8, 0.5)), "the fill shows while dragging");
assert_eq!(session.history_labels().len(), history, "no undo step yet");
assert_eq!(session.end_polygon_fill_box(), 16);
assert_eq!(session.history_labels().len(), history + 1);
session.undo().unwrap();
session.update();
assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag");
}
#[test]
fn a_failed_box_fill_leaves_no_drag_behind() {
let mut session = fill_session(primitives::plane(2.0, 4));
let layer = session.selected.remove(&0).unwrap();
assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).is_err(), "no layer to paint on");
session.selected.insert(0, layer);
assert_eq!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32, "the next box fills again");
}
#[test]
fn undo_and_tool_changes_finish_a_box_drag_first() {
let mut session = fill_session(primitives::plane(2.0, 4));
let history = session.history_labels().len();
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
assert_eq!(session.undo().unwrap(), "Polygon fill", "undo takes back the drag it finished");
assert!(session.polygon_fill_drag.is_none());
assert_eq!(session.history_labels().len(), history);
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
crate::tool_cmds::set_tool(&mut session, Tool::Paint).unwrap();
assert!(session.polygon_fill_drag.is_none());
assert_eq!(session.history_labels().len(), history + 1, "a tool change keeps the fill as one step");
}
#[test]
fn an_unmoved_box_keeps_its_fill() {
let mut session = fill_session(primitives::plane(2.0, 4));
let narrow_box = Vec2::new(0.3, 1.0);
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "intersection: the two columns the box touches");
// Contained center would select one column, so a second selection would show 8
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "the same box selects nothing again");
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box + Vec2::new(0.01, 0.0)).unwrap(), 8, "a moved box selects again");
}
#[test]
fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() {
let mut session = fill_session(primitives::udim_plane());
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]);
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
let every_triangle = session.mesh.triangle_count();
assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002");
}
#[test]
fn a_2d_click_skips_a_triangle_with_collapsed_uvs() {
// A face left unmapped (all corners at UV 0,0) comes first, as imports often leave them
let plane = primitives::plane(2.0, 1);
let mut positions = vec![Vec3::ZERO, Vec3::X, Vec3::Z];
let mut uvs = vec![Vec2::ZERO; 3];
positions.extend(&plane.positions);
uvs.extend(&plane.uvs);
let indices = [0, 1, 2].into_iter().chain(plane.indices.iter().map(|index| index + 3)).collect();
let mut session = fill_session(Mesh::from_parts(positions, None, uvs, indices, "m").unwrap());
assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1);
session.update();
assert!(filled_at(&session, Vec2::new(0.2, 0.7)), "the triangle under the cursor, not the collapsed one");
}
#[test]
fn a_failing_drag_reports_once_and_records_nothing() {
let mut session = fill_session(primitives::plane(2.0, 4));
let history = session.history_labels().len();
session.selected.clear();
assert!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.5, 1.0)).is_err());
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 0, "the rest of the drag fills nothing");
assert_eq!(session.end_polygon_fill_box(), 0);
assert_eq!(session.history_labels().len(), history);
}
#[test]
fn an_edit_during_a_drag_records_the_fill_first() {
let mut session = fill_session(primitives::plane(2.0, 4));
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
let layers = session.doc.project.layers.len();
crate::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap();
assert!(session.polygon_fill_drag.is_none());
let labels = session.history_labels();
assert_eq!(labels.get(labels.len().wrapping_sub(2)).map(String::as_str), Some("Polygon fill"), "{labels:?}");
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap();
assert_eq!(session.doc.project.layers.len(), layers + 1, "a later drag move keeps the added layer");
}
#[test]
fn a_zero_size_box_on_whole_pixels_selects_what_is_under_it() {
let mut session = fill_session(primitives::cube(1.0));
let center = (session.viewport * 0.5).floor();
assert!(session.polygon_fill_box(center, center, session.viewport).unwrap() > 0);
}
#[test]
fn a_camera_move_mid_drag_keeps_one_drag() {
let mut session = fill_session(primitives::cube(1.0));
let viewport = session.viewport;
let history = session.history_labels().len();
let (corner, opposite) = (viewport * 0.4, viewport * 0.6);
let before_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
session.camera.zoom(0.5);
let after_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
session.end_polygon_fill_box();
assert_ne!(before_zoom, after_zoom, "the same box selects again from the new camera");
assert_eq!(session.history_labels().len(), history + 1, "a wheel zoom during the drag doesn't split it");
}
#[test]
fn pixel_spans_include_both_edges_and_nothing_outside() {
assert_eq!(super::pixel_span(2.0, 2.0, 100), 2..3, "a zero-size span on a whole pixel");
assert_eq!(super::pixel_span(-50.0, -10.0, 100), 0..0, "before the first pixel");
assert_eq!(super::pixel_span(120.0, 150.0, 100), 100..100, "past the last pixel");
assert_eq!(super::pixel_span(-5.0, 500.0, 100), 0..100);
}
#[test]
fn a_2d_click_fills_the_triangle_under_it() {
let mut session = fill_session(primitives::plane(2.0, 1));
assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1);
session.update();
assert!(filled_at(&session, Vec2::new(0.2, 0.7)));
assert!(!filled_at(&session, Vec2::new(0.7, 0.2)), "the quad's other triangle stays");
assert!(session.polygon_fill_uv(Vec2::new(1.5, 0.5)).is_err(), "nothing outside the UVs");
}
}
+42
View File
@@ -0,0 +1,42 @@
//! A polygon fill box being dragged: what it filled so far and what it needs to refill each move.
use std::collections::{BTreeMap, BTreeSet};
use texturecraft_core::LayerId;
use texturecraft_geom::OrbitCamera;
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::EyeDepth;
use texturecraft_texel::TileImage;
use crate::session::{Document, StackTarget};
use crate::triangle_partition::TrianglePartition;
/// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends
pub(crate) struct PolygonFillDrag {
/// The texture set it fills
pub ts: usize,
/// The selected layer and content, mask or effect being filled
pub target: (Option<LayerId>, StackTarget),
/// The 3D view's size in pixels, or None for a drag in the 2D view
pub viewport: Option<Vec2>,
/// The camera [`PolygonFillDrag::points`] and [`PolygonFillDrag::depth`] were made with
pub camera: OrbitCamera,
/// The document before the drag, refilled each time the selection changes
pub before: Document,
/// The quick mask's coverage before the drag, when the drag paints the quick mask
pub quick_mask_before: Option<BTreeMap<usize, TileImage>>,
/// Each vertex where the box sees it: viewport pixels in the 3D view (None behind the camera), texture coordinates in the 2D view
pub points: Vec<Option<Vec2>>,
/// What the camera sees (3D view, visible polygons only)
pub depth: Option<EyeDepth>,
/// What the fill mode fills together
pub fill_groups: TrianglePartition,
/// The polygons the box tests, when they differ from the fill groups
pub polygons: Option<TrianglePartition>,
/// The triangles filled so far
pub filled: BTreeSet<u32>,
/// The box last shown, lowest corner first: an unmoved box isn't selected again
pub last_box: Option<(Vec2, Vec2)>,
/// The fill failed (reported once): the rest of the drag fills nothing
pub failed: bool,
}
+42 -29
View File
@@ -11,6 +11,7 @@ use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer};
use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas};
use texturecraft_texel::DilationMap;
use crate::fill_mode::FillMode;
use crate::{EngineError, Result};
/// Padding (texels) applied to composites for display.
@@ -160,15 +161,6 @@ impl ViewMode {
}
}
/// Polygon fill granularity.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum FillMode {
#[default]
Triangle,
UvIsland,
Mesh,
}
/// A screen-pinned image for the Projection tool (a stencil).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StencilState {
@@ -210,6 +202,12 @@ pub struct ToolState {
/// Gray painted into masks.
pub mask_value: f32,
pub fill_mode: FillMode,
/// How a polygon fill box decides which polygons it selects
#[serde(default)]
pub fill_hit_test: crate::fill_hit_test::FillHitTest,
/// Polygon fill boxes in the 3D view select only the polygons the camera sees
#[serde(default = "default_fill_visible_only")]
pub fill_visible_only: bool,
/// Stencil used by the Projection tool.
#[serde(default)]
pub stencil: Option<StencilState>,
@@ -231,6 +229,10 @@ fn default_smudge_strength() -> f32 {
0.5
}
fn default_fill_visible_only() -> bool {
true
}
/// What the Clone tool copies (the clone source modes).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum CloneFrom {
@@ -260,6 +262,8 @@ impl Default for ToolState {
enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(),
mask_value: 1.0,
fill_mode: FillMode::Triangle,
fill_hit_test: Default::default(),
fill_visible_only: default_fill_visible_only(),
stencil: None,
smudge_strength: default_smudge_strength(),
clone_source: None,
@@ -356,6 +360,8 @@ pub struct Session {
/// The last stroke's camera visibility buffer: reused while the camera, view size and mesh
/// are unchanged, so back-to-back dabs start instantly.
pub(crate) depth_cache: Option<DepthCache>,
/// The polygon fill box being dragged
pub(crate) polygon_fill_drag: Option<crate::polygon_fill_drag::PolygonFillDrag>,
/// The user's export presets (kept when another project opens).
pub export_presets: crate::preset_cmds::UserPresets,
/// The user's project templates (kept when another project opens).
@@ -405,6 +411,7 @@ impl Session {
revision: 1,
log: Vec::new(),
depth_cache: None,
polygon_fill_drag: None,
export_presets: Default::default(),
templates: Default::default(),
})
@@ -489,22 +496,24 @@ impl Session {
self.edit_merging(label, self.merge_edits, f)
}
/// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the
/// same label (a drag in the viewport is one step however many updates it makes).
pub fn edit_merging<T>(&mut self, label: &str, merge: bool, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
/// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the same label (a viewport drag is one step however many updates it makes).
pub fn edit_merging<T>(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
// A box fill under way becomes its own step first, so this edit isn't written over or folded into it
self.end_polygon_fill_box();
let before = self.doc.clone();
let result = f(self).and_then(|v| match self.doc.project.instance_cycle() {
let result = change(self).and_then(|value| match self.doc.project.instance_cycle() {
Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))),
None => Ok(v),
None => Ok(value),
});
match result {
Ok(v) => {
Ok(value) => {
self.record(label, before, merge);
Ok(v)
Ok(value)
}
Err(e) => {
Err(error) => {
self.doc = before;
Err(e)
Err(error)
}
}
}
@@ -530,7 +539,7 @@ impl Session {
/// Mark dirty every texture set whose composite differs between `other` and the current
/// document (after an edit, undo or redo).
fn invalidate_changed(&mut self, other: &Document) {
pub(crate) fn invalidate_changed(&mut self, other: &Document) {
self.follow_uv_layouts(&other.project);
self.sync_caches();
let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::<Vec<_>>();
@@ -625,25 +634,29 @@ impl Session {
}
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();
// An edited path would otherwise repaint over the restored document.
self.end_polygon_fill_box();
self.stop_path_edit();
let (label, doc) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
let now = std::mem::replace(&mut self.doc, doc);
self.after_history(&now);
self.redo.push((label.clone(), now));
let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
let current = std::mem::replace(&mut self.doc, restored);
self.after_history(&current);
self.redo.push((label.clone(), current));
self.sync_images();
Ok(label)
}
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();
// An edited path would otherwise repaint over the restored document.
self.end_polygon_fill_box();
self.stop_path_edit();
let (label, doc) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
let now = std::mem::replace(&mut self.doc, doc);
self.after_history(&now);
self.undo.push((label.clone(), now));
let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
let current = std::mem::replace(&mut self.doc, restored);
self.after_history(&current);
self.undo.push((label.clone(), current));
self.sync_images();
Ok(label)
}
+83 -20
View File
@@ -7,7 +7,9 @@ use texturecraft_geom::glam::Vec2;
use texturecraft_paint::{Alignment, BrushAlpha, alphas};
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp};
use crate::session::{CloneFrom, CloneSource, FillMode, Tool};
use crate::fill_hit_test::FillHitTest;
use crate::fill_mode::FillMode;
use crate::session::{CloneFrom, CloneSource, Tool};
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
@@ -69,7 +71,16 @@ pub fn specs() -> Vec<CommandSpec> {
always,
clone_source
),
cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|uvIsland|mesh}", always, fill_mode),
cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|polygon|uvIsland|mesh}", always, fill_mode),
cmd!(
"tool.fillSelection",
"Polygon fill selection",
[],
None,
"{hitTest?: intersection|containedCenter (a box selects polygons it touches, or whose center it holds), visibleOnly?: bool (3D view boxes select only what the camera sees)}",
always,
fill_selection
),
cmd!("tool.stroke", "Paint stroke", [], None, "{points: [[x,y],...] viewport pixels, viewport?: [w,h]} — paints with the current tool", always, stroke),
cmd!(
"tool.strokeUv",
@@ -80,16 +91,26 @@ pub fn specs() -> Vec<CommandSpec> {
always,
stroke_uv
),
cmd!("tool.click", "Tool click", [], None, "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab", always, click),
cmd!(
"tool.click",
"Tool click",
[],
None,
"{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}",
always,
click
),
cmd!("tool.state", "Tool state", [], None, "{}", always, |s, _| Ok(serde_json::to_value(&s.tool).unwrap_or(Value::Null))),
]
}
pub(crate) fn set_tool(s: &mut Session, t: Tool) -> Result<Value> {
s.cancel_stroke();
s.tool.tool = t;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "tool": t.id() }))
pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result<Value> {
session.cancel_stroke();
// A box fill under way keeps what it filled as one undo step
session.end_polygon_fill_box();
session.tool.tool = tool;
session.revision = session.revision.wrapping_add(1);
Ok(json!({ "tool": tool.id() }))
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
@@ -319,13 +340,29 @@ fn clone_source(s: &mut Session, p: &Value) -> Result<Value> {
Ok(serde_json::to_value(s.tool.clone_source).unwrap_or(Value::Null))
}
fn fill_mode(s: &mut Session, p: &Value) -> Result<Value> {
s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") {
fn fill_mode(session: &mut Session, params: &Value) -> Result<Value> {
session.tool.fill_mode = match strp(params, "mode").unwrap_or("triangle") {
"triangle" => FillMode::Triangle,
"polygon" => FillMode::Polygon,
"uvIsland" | "island" => FillMode::UvIsland,
"mesh" => FillMode::Mesh,
other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))),
};
Ok(Value::Null)
}
fn fill_selection(session: &mut Session, params: &Value) -> Result<Value> {
match strp(params, "hitTest") {
None => {}
Some("intersection") => session.tool.fill_hit_test = FillHitTest::Intersection,
Some("containedCenter") => session.tool.fill_hit_test = FillHitTest::ContainedCenter,
Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))),
}
if let Some(visible_only) = boolp(params, "visibleOnly") {
session.tool.fill_visible_only = visible_only;
}
Ok(Value::Null)
}
@@ -369,22 +406,48 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "stamps": stamps }))
}
fn click(s: &mut Session, p: &Value) -> Result<Value> {
let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) };
let vp = viewport_of(s, p);
let out = match s.tool.tool {
Tool::PolygonFill => json!({ "triangles": s.polygon_fill(Vec2::new(x, y), vp)? }),
fn click(session: &mut Session, params: &Value) -> Result<Value> {
if session.tool.tool == Tool::PolygonFill
&& let Some(triangles) = polygon_fill_click(session, params)?
{
session.update();
return Ok(json!({ "triangles": triangles }));
}
let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) };
let point = Vec2::new(x, y);
let viewport = viewport_of(session, params);
let out = match session.tool.tool {
Tool::PolygonFill => json!({ "triangles": session.polygon_fill(point, viewport)? }),
Tool::ColorPicker => {
let v = s.color_pick(Vec2::new(x, y), vp)?;
json!(v.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::<serde_json::Map<_, _>>())
let picked = session.color_pick(point, viewport)?;
json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::<serde_json::Map<_, _>>())
}
Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, Vec2::new(x, y), vp)?,
_ => json!({ "stamps": s.stroke_points(&[Vec2::new(x, y)], vp)? }),
Tool::GeometryMask => crate::instance_cmds::toggle_part_at(session, point, viewport)?,
_ => json!({ "stamps": session.stroke_points(&[point], viewport)? }),
};
s.update();
session.update();
Ok(out)
}
/// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point
fn polygon_fill_click(session: &mut Session, params: &Value) -> Result<Option<usize>> {
let screen_box = (f32p(params, "x0"), f32p(params, "y0"), f32p(params, "x1"), f32p(params, "y1"));
let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some());
let filled = match (pair(params, "uv0"), pair(params, "uv1"), pair(params, "uv"), screen_box) {
(Some(corner), Some(opposite), ..) => session.polygon_fill_box_uv(corner.into(), opposite.into())?,
_ if given(&["uv0", "uv1"]) => return Err(bad("tool.click", "a UV box needs `uv0` and `uv1` as [u, v]")),
(_, _, Some(uv), _) => session.polygon_fill_uv(uv.into())?,
_ if given(&["uv"]) => return Err(bad("tool.click", "a 2D view point needs `uv` as [u, v]")),
(.., (Some(x0), Some(y0), Some(x1), Some(y1))) => session.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(session, params))?,
_ if given(&["x0", "y0", "x1", "y1"]) => return Err(bad("tool.click", "a screen box needs numbers `x0`, `y0`, `x1` and `y1`")),
_ => return Ok(None),
};
Ok(Some(filled))
}
fn stroke_uv(s: &mut Session, p: &Value) -> Result<Value> {
let points = points_param("tool.strokeUv", p, "points")?.ok_or_else(|| bad("tool.strokeUv", "`points` must be an array of [u, v]"))?;
let tiles = s.stroke_uv_points(&points)?;
+123
View File
@@ -0,0 +1,123 @@
//! Triangles of one material grouped into the pieces polygon fill selects and fills.
use std::collections::HashMap;
use std::hash::Hash;
use texturecraft_geom::Mesh;
/// A material's triangles split into groups joined across shared edges
pub struct TrianglePartition {
/// The triangles of each group
pub groups: Vec<Vec<u32>>,
/// The index of each triangle's group
group_of: HashMap<u32, usize>,
}
impl TrianglePartition {
/// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both
pub fn new<K: Eq + Hash + Clone>(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec<K>) -> TrianglePartition {
// Each triangle's edges once, in mesh order so the groups come out the same every time
let triangles: Vec<u32> = mesh.triangles_of(material).map(|triangle| triangle as u32).collect();
let position_of: HashMap<u32, usize> = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect();
let mut edge_lists: Vec<Vec<K>> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect();
let mut by_edge: HashMap<K, Vec<u32>> = HashMap::new();
for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) {
for edge in triangle_edges {
by_edge.entry(edge.clone()).or_default().push(*triangle);
}
}
let mut groups = Vec::new();
let mut group_of = HashMap::with_capacity(triangles.len());
for &start in &triangles {
if group_of.contains_key(&start) {
continue;
}
let mut members = Vec::new();
let mut stack = vec![start];
group_of.insert(start, groups.len());
while let Some(triangle) = stack.pop() {
members.push(triangle);
let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default();
// Visit a shared edge once, including when many collapsed faces share the same key
for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.remove(edge).into_iter().flatten()) {
if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(neighbour) {
entry.insert(groups.len());
stack.push(neighbour);
}
}
}
groups.push(members);
}
TrianglePartition { groups, group_of }
}
/// The index in [`TrianglePartition::groups`] of the group holding `triangle` (None for a triangle of another material)
pub fn index_of(&self, triangle: u32) -> Option<usize> {
self.group_of.get(&triangle).copied()
}
/// The group holding `triangle` (None for a triangle of another material)
pub fn group(&self, triangle: u32) -> Option<&[u32]> {
self.index_of(triangle).and_then(|group| self.groups.get(group)).map(Vec::as_slice)
}
}
#[cfg(test)]
mod tests {
use texturecraft_geom::primitives;
use super::*;
#[test]
fn triangles_sharing_a_key_join_one_group() {
let mesh = primitives::plane(2.0, 2);
let singles = TrianglePartition::new(&mesh, 0, |_, _| Vec::<u32>::new());
let pairs = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 2]);
assert_eq!(singles.groups.len(), mesh.triangle_count());
assert_eq!(pairs.groups.len(), mesh.triangle_count() / 2);
assert_eq!(pairs.group(3).map(<[u32]>::len), Some(2));
assert_eq!(pairs.group(99), None);
}
#[test]
fn shared_edges_keep_transitive_neighbors() {
let mesh = primitives::plane(2.0, 4);
let groups = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 4, (triangle + 1) / 4]);
assert_eq!(groups.groups.len(), 1);
assert_eq!(groups.group(0).unwrap().len(), mesh.triangle_count());
}
#[test]
#[ignore = "release performance measurement"]
fn benchmark_shared_edges() {
use std::hint::black_box;
use std::time::Instant;
for subdivisions in [32, 64] {
let mesh = primitives::plane(2.0, subdivisions);
for collapsed in [false, true] {
let mut times = Vec::new();
for _ in 0..5 {
let start = Instant::now();
let groups = TrianglePartition::new(&mesh, 0, |mesh, triangle| {
if collapsed {
vec![(0, 0); 3]
} else {
let [first, second, third] = mesh.tri(triangle).unwrap();
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
}
});
assert_eq!(groups.groups.len(), 1);
black_box(groups);
times.push(start.elapsed().as_secs_f64() * 1000.0);
}
times.sort_by(f64::total_cmp);
eprintln!("{} triangles, collapsed={collapsed}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[2], times[0], times[4]);
}
}
}
}
+88
View File
@@ -0,0 +1,88 @@
//! Polygon fill drag transitions preserve already painted targets
use serde_json::json;
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::{glam::Vec2, primitives};
use texturecraft_engine::{Session, execute};
#[test]
fn changing_layers_during_a_box_drag_preserves_the_first_fill() {
let mut session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
let first = session.selected_layer().unwrap();
execute(&mut session, "layer.add.paint", &json!({})).unwrap();
let second = session.selected_layer().unwrap();
execute(&mut session, "layer.select", &json!({"layer": first.0})).unwrap();
let history = session.history_labels().len();
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
execute(&mut session, "layer.select", &json!({"layer": second.0})).unwrap();
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.4, 1.0)).unwrap();
session.end_polygon_fill_box();
assert!(session.doc.pixels.layer(first, Channel::BaseColor).is_some(), "the first layer keeps its fill");
assert!(session.doc.pixels.layer(second, Channel::BaseColor).is_some(), "the new target receives the next fill");
assert_eq!(session.history_labels().len(), history + 2, "each target has its own undo step");
session.undo().unwrap();
assert!(session.doc.pixels.layer(first, Channel::BaseColor).is_some());
assert!(session.doc.pixels.layer(second, Channel::BaseColor).is_none());
}
#[test]
fn changing_from_content_to_mask_during_a_box_drag_preserves_content() {
let mut session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
let layer = session.selected_layer().unwrap();
execute(&mut session, "mask.add.black", &json!({})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "content"})).unwrap();
let history = session.history_labels().len();
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap();
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.4, 1.0)).unwrap();
session.end_polygon_fill_box();
assert!(session.doc.pixels.layer(layer, Channel::BaseColor).is_some(), "switching to the mask keeps the content fill");
assert_eq!(session.history_labels().len(), history + 2);
session.undo().unwrap();
assert!(session.doc.pixels.layer(layer, Channel::BaseColor).is_some());
assert!(session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.is_empty());
}
#[test]
#[ignore = "release performance measurement"]
fn benchmark_live_box_fill() {
use std::hint::black_box;
use std::time::Instant;
for (name, mesh) in [("ball", primitives::material_ball()), ("sphere", primitives::sphere(1.0, 512, 256))] {
let triangles = mesh.triangle_count();
let mut session = Session::new_project("benchmark", mesh, "test", None, 1024).unwrap();
let viewport = Vec2::new(1920.0, 1080.0);
let start = Instant::now();
session.drag_polygon_fill_box(viewport * 0.4, viewport * 0.6, viewport).unwrap();
let first_ms = start.elapsed().as_secs_f64() * 1000.0;
let mut times = Vec::new();
for step in 1..=12 {
let radius = 0.1 + step as f32 * 0.02;
let start = Instant::now();
black_box(session.drag_polygon_fill_box(viewport * (0.5 - radius), viewport * (0.5 + radius), viewport).unwrap());
times.push(start.elapsed().as_secs_f64() * 1000.0);
}
let (corner, opposite) = (viewport * 0.16, viewport * 0.84);
session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
let start = Instant::now();
for _ in 0..1000 {
black_box(session.drag_polygon_fill_box(corner, opposite, viewport).unwrap());
}
let unchanged_us = start.elapsed().as_secs_f64() * 1000.0;
session.end_polygon_fill_box();
let start = Instant::now();
session.update();
let composite_ms = start.elapsed().as_secs_f64() * 1000.0;
times.sort_by(f64::total_cmp);
let memory = session.memory();
eprintln!(
"{name}: {triangles} triangles, first={first_ms:.3} ms, growing median={:.3} ms max={:.3} ms, unchanged mean={unchanged_us:.3} us, composite={composite_ms:.3} ms, pixels={} bytes composites={} bytes cache={} bytes",
times[6], times[11], memory.pixels, memory.composites, memory.cache
);
}
}
+23
View File
@@ -105,6 +105,29 @@ fn polygon_fill_and_color_picker() {
assert!((r["roughness"][0].as_f64().unwrap() - 0.9).abs() < 0.01, "{r}");
}
#[test]
fn polygon_fill_boxes_survive_hostile_params() {
let hostile = [
json!({"x0": 1e30, "y0": -1e30, "x1": f64::MAX, "y1": 0, "viewport": [1e9, 1e9]}),
json!({"x0": 0, "y0": 0, "x1": 0, "y1": 0, "viewport": [16, 16]}),
json!({"uv0": [1e30, -1e30], "uv1": [0, 0]}),
json!({"uv0": [0.5], "uv1": "x", "uv": [f64::MIN, 2]}),
json!({"hitTest": "nope", "visibleOnly": "yes", "mode": 7}),
];
for visible_only in [true, false] {
for hit_test in ["intersection", "containedCenter"] {
let mut session = session();
execute(&mut session, "tool.polygonFill", &Value::Null).unwrap();
execute(&mut session, "tool.fillSelection", &json!({"hitTest": hit_test, "visibleOnly": visible_only})).unwrap();
for params in &hostile {
let _ = execute(&mut session, "tool.click", params);
let _ = execute(&mut session, "tool.fillSelection", params);
session.update();
}
}
}
}
/// Every command must return Ok or Err — never panic — for hostile params.
#[test]
fn panic_hunt() {
+1 -1
View File
@@ -29,4 +29,4 @@ pub use path::{Lasso, spline};
pub use pickup::{Pickup, PickupMode};
pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv};
pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick};
pub use visibility::EyeDepth;
pub use visibility::{EyeDepth, screen_point};
+123 -48
View File
@@ -2,11 +2,26 @@
//! rendered once at the start of a stroke.
use rayon::prelude::*;
use texturecraft_geom::glam::{Mat4, Vec3, Vec4};
use texturecraft_geom::{Mesh, OrbitCamera};
use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4};
use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera};
const BAND: usize = 16;
/// Largest buffer side in pixels.
const MAX_SIZE: u32 = 4096;
/// Clip-space w below which a vertex counts as behind the camera.
pub const MIN_CLIP_W: f32 = 1e-5;
/// Screen area (pixels squared) below which a triangle is skipped as degenerate.
const MIN_SCREEN_AREA: f32 = 1e-9;
/// How far outside a triangle (in barycentric weight) a pixel center may lie and still count, closing seams between neighbours.
const EDGE_TOLERANCE: f32 = 1e-4;
/// [`EyeDepth::bias`] as a fraction of the scene radius.
const BIAS_PER_RADIUS: f32 = 0.004;
/// Distance from the eye to the nearest surface per screen pixel (f32::MAX where empty).
#[derive(Clone, Debug)]
pub struct EyeDepth {
@@ -15,73 +30,133 @@ pub struct EyeDepth {
pub view_proj: Mat4,
pub eye: Vec3,
pub dist: Vec<f32>,
/// The nearest triangle per screen pixel ([`NO_TRI`] where empty); empty unless rendered with [`EyeDepth::render_with_triangles`].
pub triangle: Vec<u32>,
/// Tolerance in world units (≈ 0.4% of the scene radius).
pub bias: f32,
}
/// Where `position` lands in a `size` pixel view through `view_proj` (origin top-left), or None behind the camera.
pub fn screen_point(view_proj: Mat4, position: Vec3, size: Vec2) -> Option<Vec2> {
let clip = view_proj * position.extend(1.0);
(clip.w > MIN_CLIP_W).then(|| Vec2::new(clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5) * size)
}
impl EyeDepth {
/// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at 4096).
/// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]), without [`EyeDepth::triangle`].
pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth {
let (w, h) = (width.clamp(1, 4096), height.clamp(1, 4096));
let aspect = w as f32 / h as f32;
let vp = camera.view_proj(aspect);
Self::rasterize(mesh, camera, width, height, false)
}
/// [`EyeDepth::render`] that also records the nearest triangle per pixel in [`EyeDepth::triangle`].
pub fn render_with_triangles(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth {
Self::rasterize(mesh, camera, width, height, true)
}
/// The eye-distance buffer, plus the nearest triangle per pixel when `record_triangles` is set.
fn rasterize(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool) -> EyeDepth {
// Capping storage dimensions must not change the camera's projection
let projection = camera.proj(width.max(1) as f32 / height.max(1) as f32);
let view = camera.view();
let view_proj = projection * view;
let depth_key = |view_depth: f32| if camera.ortho { view_depth } else { -view_depth.recip() };
let inverse_projection = projection.inverse();
let clip_depth = |z: f32| {
let point = inverse_projection * Vec4::new(0.0, 0.0, z, 1.0);
depth_key(-point.z / point.w)
};
let depth_range = clip_depth(0.0)..=clip_depth(1.0);
let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE));
let size = Vec2::new(width as f32, height as f32);
let eye = camera.eye();
// Project every vertex once.
let clip: Vec<Vec4> = mesh.positions.iter().map(|p| vp * p.extend(1.0)).collect();
let screen: Vec<Option<(f32, f32)>> =
clip.iter().map(|c| (c.w > 1e-5).then(|| ((c.x / c.w * 0.5 + 0.5) * w as f32, (0.5 - c.y / c.w * 0.5) * h as f32))).collect();
let dist_v: Vec<f32> = mesh.positions.iter().map(|p| p.distance(eye)).collect();
let bands = (h as usize).div_ceil(BAND);
let mut bins: Vec<Vec<u32>> = vec![Vec::new(); bands];
for t in 0..mesh.triangle_count() {
let Some([a, b, c]) = mesh.tri(t) else { continue };
let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue };
let y0 = pa.1.min(pb.1).min(pc.1).floor().max(0.0);
let y1 = pa.1.max(pb.1).max(pc.1).ceil().min(h as f32);
if y1 <= y0 || !y0.is_finite() || !y1.is_finite() {
// Brush depth closes seams, but expanding triangle IDs can expose hidden faces at silhouettes
let edge_tolerance = if record_triangles { 0.0 } else { EDGE_TOLERANCE };
let screen: Vec<Option<Vec2>> = mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect();
// Inverse view depth is affine in perspective and avoids the precision loss of normalized clip depth
let vertex_depth: Vec<f32> = mesh.positions.iter().map(|position| depth_key(-(view * position.extend(1.0)).z)).collect();
// Bin each triangle into the bands of rows it covers
let mut bands: Vec<Vec<u32>> = vec![Vec::new(); (height as usize).div_ceil(BAND)];
for triangle in 0..mesh.triangle_count() {
let Some([first, second, third]) = mesh.tri(triangle) else { continue };
let (Some(Some(first)), Some(Some(second)), Some(Some(third))) = (screen.get(first), screen.get(second), screen.get(third)) else { continue };
let top = first.y.min(second.y).min(third.y).floor().max(0.0);
let bottom = first.y.max(second.y).max(third.y).ceil().min(size.y);
if bottom <= top || !top.is_finite() || !bottom.is_finite() {
continue;
}
let (b0, b1) = (y0 as usize / BAND, ((y1 as usize).saturating_sub(1)) / BAND);
for bin in bins.iter_mut().take(b1 + 1).skip(b0) {
bin.push(t as u32);
let (first_band, last_band) = (top as usize / BAND, (bottom as usize).saturating_sub(1) / BAND);
for band in bands.iter_mut().take(last_band + 1).skip(first_band) {
band.push(triangle as u32);
}
}
let mut dist = vec![f32::MAX; (w * h) as usize];
dist.par_chunks_mut(BAND * w as usize).enumerate().for_each(|(bi, rows)| {
let row0 = bi * BAND;
let nrows = rows.len() / w as usize;
for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) {
let Some([a, b, c]) = mesh.tri(t as usize) else { continue };
let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue };
let (da, db, dc) = (dist_v[a], dist_v[b], dist_v[c]);
let area = (pb.0 - pa.0) * (pc.1 - pa.1) - (pb.1 - pa.1) * (pc.0 - pa.0);
if area.abs() < 1e-9 {
let mut dist = vec![f32::MAX; (width * height) as usize];
let mut triangle = if record_triangles { vec![NO_TRI; (width * height) as usize] } else { Vec::new() };
let band_len = BAND * width as usize;
let mut triangle_bands: Vec<Option<&mut [u32]>> = triangle.chunks_mut(band_len).map(Some).collect();
triangle_bands.resize_with(dist.len().div_ceil(band_len), || None);
dist.par_chunks_mut(band_len).zip(triangle_bands.into_par_iter()).enumerate().for_each(|(band, (band_dist, mut band_triangles))| {
let first_row = band * BAND;
let row_count = band_dist.len() / width as usize;
for &candidate in bands.get(band).map(Vec::as_slice).unwrap_or(&[]) {
let Some(corners) = mesh.tri(candidate as usize) else { continue };
let [first, second, third] = corners;
let (Some(Some(first_point)), Some(Some(second_point)), Some(Some(third_point))) = (screen.get(first), screen.get(second), screen.get(third))
else {
continue;
};
let corner_depth = corners.map(|vertex| vertex_depth.get(vertex).copied().unwrap_or(f32::MAX));
let area = (*second_point - *first_point).perp_dot(*third_point - *first_point);
if area.abs() < MIN_SCREEN_AREA {
continue;
}
let x0 = pa.0.min(pb.0).min(pc.0).floor().max(0.0) as usize;
let x1 = (pa.0.max(pb.0).max(pc.0).ceil().min(w as f32)) as usize;
let y0 = (pa.1.min(pb.1).min(pc.1).floor().max(row0 as f32)) as usize;
let y1 = (pa.1.max(pb.1).max(pc.1).ceil().min((row0 + nrows) as f32)) as usize;
for y in y0.max(row0)..y1 {
for x in x0..x1.min(w as usize) {
let (px, py) = (x as f32 + 0.5, y as f32 + 0.5);
let w0 = ((pb.0 - px) * (pc.1 - py) - (pb.1 - py) * (pc.0 - px)) / area;
let w1 = ((pc.0 - px) * (pa.1 - py) - (pc.1 - py) * (pa.0 - px)) / area;
let w2 = 1.0 - w0 - w1;
if w0 < -1e-4 || w1 < -1e-4 || w2 < -1e-4 {
let low = first_point.min(*second_point).min(*third_point).floor();
let high = first_point.max(*second_point).max(*third_point).ceil();
let (left, right) = (low.x.max(0.0) as usize, (high.x.min(size.x) as usize).min(width as usize));
let (top, bottom) = (low.y.max(first_row as f32) as usize, high.y.min((first_row + row_count) as f32) as usize);
for row in top.max(first_row)..bottom {
for column in left..right {
let sample = Vec2::new(column as f32 + 0.5, row as f32 + 0.5);
let first_weight = (*third_point - *second_point).perp_dot(sample - *second_point) / area;
let second_weight = (*first_point - *third_point).perp_dot(sample - *third_point) / area;
let third_weight = 1.0 - first_weight - second_weight;
if first_weight < -edge_tolerance || second_weight < -edge_tolerance || third_weight < -edge_tolerance {
continue;
}
let d = w0 * da + w1 * db + w2 * dc;
if let Some(slot) = rows.get_mut((y - row0) * w as usize + x)
&& d < *slot
let depth = first_weight * corner_depth[0] + second_weight * corner_depth[1] + third_weight * corner_depth[2];
let at = (row - first_row) * width as usize + column;
if let Some(slot) = band_dist.get_mut(at)
&& depth_range.contains(&depth)
&& depth < *slot
{
*slot = d;
*slot = depth;
if let Some(nearest) = band_triangles.as_deref_mut().and_then(|triangles| triangles.get_mut(at)) {
*nearest = candidate;
}
}
}
}
}
// Convert only the winning depths to eye distances for brush visibility queries
for (row, distances) in band_dist.chunks_mut(width as usize).enumerate() {
let view_y = (1.0 - (first_row as f32 + row as f32 + 0.5) / size.y * 2.0) / projection.y_axis.y;
for (column, distance) in distances.iter_mut().enumerate().filter(|(_, distance)| **distance != f32::MAX) {
let view_x = ((column as f32 + 0.5) / size.x * 2.0 - 1.0) / projection.x_axis.x;
let radial_squared = view_x * view_x + view_y * view_y;
*distance = if camera.ortho { (radial_squared + *distance * *distance).sqrt() } else { (radial_squared + 1.0).sqrt() / -*distance };
}
}
});
EyeDepth { width: w, height: h, view_proj: vp, eye, dist, bias: mesh.radius() * 0.004 }
EyeDepth { width, height, view_proj, eye, dist, triangle, bias: mesh.radius() * BIAS_PER_RADIUS }
}
/// Whether world point `p` is visible (not hidden behind other geometry, inside the view).
+99
View File
@@ -0,0 +1,99 @@
//! Visibility agrees with the surface under each pixel
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{Mesh, OrbitCamera};
use texturecraft_paint::EyeDepth;
#[test]
fn a_large_front_triangle_occludes_a_small_rear_triangle() {
let positions = vec![
Vec3::new(-4.0, -4.0, 0.0),
Vec3::new(4.0, -4.0, 0.0),
Vec3::new(0.0, 4.0, 0.0),
Vec3::new(-0.5, -0.5, -1.0),
Vec3::new(0.5, -0.5, -1.0),
Vec3::new(0.0, 0.5, -1.0),
];
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 6], (0..6).collect(), "m").unwrap();
for ortho in [false, true] {
let camera = OrbitCamera { pitch: 0.0, ortho, ..Default::default() };
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 128, 128);
assert_eq!(depth.triangle[64 * 128 + 64], 0, "orthographic: {ortho}");
assert!(!depth.visible(Vec3::new(0.0, 0.0, -1.0)), "the rear face is hidden");
assert!(depth.visible(Vec3::ZERO), "the front face is visible");
}
}
#[test]
#[ignore = "release performance measurement"]
fn benchmark_eye_depth() {
use std::hint::black_box;
use std::time::Instant;
use texturecraft_geom::primitives;
for (name, mesh) in [("ball", primitives::material_ball()), ("sphere", primitives::sphere(1.0, 512, 256))] {
let mut camera = OrbitCamera::default();
let (low, high) = mesh.bounds();
camera.frame(low, high);
for triangles in [false, true] {
let mut times = Vec::new();
for iteration in 0..12 {
let start = Instant::now();
black_box(if triangles { EyeDepth::render_with_triangles(&mesh, &camera, 960, 540) } else { EyeDepth::render(&mesh, &camera, 960, 540) });
if iteration >= 2 {
times.push(start.elapsed().as_secs_f64() * 1000.0);
}
}
times.sort_by(f64::total_cmp);
eprintln!("{name}: {} triangles, record={triangles}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[5], times[0], times[9]);
}
}
}
#[test]
fn perspective_depth_matches_ray_intersections() {
use texturecraft_geom::Bvh;
let positions = vec![Vec3::new(-3.0, -2.0, 2.0), Vec3::new(3.0, -2.0, -2.0), Vec3::new(0.0, 3.0, 0.0)];
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap();
let camera = OrbitCamera { pitch: 0.0, ..Default::default() };
let bvh = Bvh::new(&mesh);
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 128, 128);
for (x, y) in [(40, 60), (64, 64), (88, 60)] {
let ndc = Vec2::new((x as f32 + 0.5) / 64.0 - 1.0, 1.0 - (y as f32 + 0.5) / 64.0);
let ray = camera.ray(ndc, 1.0);
let hit = bvh.closest(ray.origin, ray.dir, f32::MAX).unwrap();
let expected = (ray.origin + ray.dir * hit.t).distance(camera.eye());
assert!((depth.dist[y * 128 + x] - expected).abs() < 0.001, "pixel {x},{y}: {} vs {expected}", depth.dist[y * 128 + x]);
}
}
#[test]
fn capped_buffers_keep_the_requested_viewport_aspect() {
let positions = vec![Vec3::new(4.0, -1.0, 0.0), Vec3::new(7.0, -1.0, 0.0), Vec3::new(5.5, 1.0, 0.0)];
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap();
let camera = OrbitCamera { pitch: 0.0, ..Default::default() };
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 8192, 1024);
let point = camera.project(Vec3::new(5.5, 0.0, 0.0), 8.0).unwrap();
let x = ((point.x * 0.5 + 0.5) * depth.width as f32) as usize;
let y = ((0.5 - point.y * 0.5) * depth.height as f32) as usize;
assert_eq!(depth.triangle[y * depth.width as usize + x], 0, "the triangle stays under its viewport position after the buffer is capped");
}
#[test]
fn triangle_ids_do_not_expand_hidden_cube_faces_past_the_silhouette() {
use std::collections::HashSet;
use texturecraft_geom::{NO_TRI, primitives};
let mesh = primitives::cube(1.0);
let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.4, ..Default::default() };
let (low, high) = mesh.bounds();
camera.frame(low, high);
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 400, 400);
let visible: HashSet<_> = depth.triangle.iter().copied().filter(|triangle| *triangle != NO_TRI).collect();
assert_eq!(visible.len(), mesh.triangle_count() / 2, "only the three front faces own screen pixels");
}
+147 -36
View File
@@ -914,12 +914,14 @@ fn mesh_map_color(map: BakedMap) -> Color32 {
/// The Properties tab title: what the panel edits.
pub(crate) fn properties_title(app: &TextureCraftApp) -> String {
let p = &app.session.doc.project;
let what = match (app.session.selected_layer().and_then(|id| p.layers.get(&id)), app.session.target) {
(Some(_), StackTarget::Effect(e)) => p.effect(e).map(|(_, x)| x.name.clone()).unwrap_or_default(),
(Some(l), StackTarget::Content) if matches!(l.kind, LayerKind::Fill(_)) => tr("Fill").to_string(),
(Some(l), StackTarget::Content) if l.is_group() => tr("Folder").to_string(),
(Some(l), StackTarget::Content) if l.instance_source().is_some() => tr("Instance").to_string(),
let project = &app.session.doc.project;
let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) {
// Polygon fill keeps its own properties whatever is selected
_ if app.session.tool.tool == Tool::PolygonFill => tr(app.session.tool.tool.label()).to_string(),
(Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| found.name.clone()).unwrap_or_default(),
(Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(),
(Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(),
(Some(layer), StackTarget::Content) if layer.instance_source().is_some() => tr("Instance").to_string(),
_ => tr(app.session.tool.tool.label()).to_string(),
};
format!("{} - {what}", tr("Properties"))
@@ -929,12 +931,14 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) {
egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui));
}
/// What the Properties panel edits: the selected effect, fill, folder or instance, else the tool
/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder or instance, else the tool
pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned());
match (&selected, app.session.target) {
// Polygon fill shows its own settings and says what it fills into, whatever is selected
_ if app.session.tool.tool == Tool::PolygonFill => polygon_fill_properties(app, ui),
(Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect),
(Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer),
(Some(layer), StackTarget::Content) if layer.is_group() => {
@@ -1146,6 +1150,104 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) {
ui.label(RichText::new(hint).size(10.5).color(tk.text_dim));
}
/// Width of the label column in polygon fill's properties
const POLYGON_FILL_LABEL_WIDTH: f32 = 108.0;
/// Polygon fill's properties: how it selects and fills, its blending, then what it fills with (material, mask gray, or why it can't fill)
fn polygon_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui) {
use texturecraft_engine::FillHitTest;
let button_size = ui.spacing().interact_size.y;
ui.label(caption(&tr("Polygon fill").to_uppercase()));
property_row(ui, tr("Selection mode"), tr("A click fills what is under it; a dragged rectangle fills what it selects as it grows"), |ui| {
icon_button(ui, ic::SELECTION, tr("Rectangle fill"), true, button_size);
});
property_row(
ui,
tr("Fill mode"),
tr("Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands"),
|ui| crate::toolbar::fill_mode_buttons(app, ui),
);
property_row(ui, tr("Hit-test"), tr("How a rectangle selects polygons"), |ui| {
for (hit_test, icon, tooltip) in [
(FillHitTest::Intersection, ic::INTERSECT_SQUARE, tr("Intersection: fill polygons the rectangle touches")),
(FillHitTest::ContainedCenter, ic::SELECTION_FOREGROUND, tr("Contained center: fill polygons whose center is in the rectangle")),
] {
if icon_button(ui, icon, tooltip, app.session.tool.fill_hit_test == hit_test, button_size).clicked() {
app.session.tool.fill_hit_test = hit_test;
}
}
});
ui.horizontal(|ui| {
ui.checkbox(&mut app.session.tool.fill_visible_only, tr("Visible polygons only"));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, tr("Fill only polygons the camera sees (3D view)")));
});
section(ui, "sec_polygon_fill_blending", tr("Blending"), false, |ui| {
let mut opacity = app.session.tool.brush.opacity * 100.0;
if slider(ui, tr("Opacity"), &mut opacity, 0.0..=100.0, 0).changed() {
app.session.tool.brush.opacity = (opacity / 100.0).clamp(0.0, 1.0);
}
});
ui.separator();
match polygon_fill_paints_mask(app) {
Ok(false) => {
ui.label(caption(&tr("Material").to_uppercase()));
material_controls(app, ui);
}
Ok(true) => {
ui.label(caption(&tr("Grayscale").to_uppercase()));
let mut gray = app.session.tool.mask_value;
if slider(ui, tr("Value"), &mut gray, 0.0..=1.0, 2).changed() {
app.session.tool.mask_value = gray;
}
}
Err(note) => {
ui.label(RichText::new(note).color(Tokens::get(ui.ctx()).text_dim));
}
}
}
/// One polygon fill setting: its label in a fixed column, its `controls`, and an info icon with `info` at the right edge
fn property_row(ui: &mut Ui, label: &str, info: &str, controls: impl FnOnce(&mut Ui)) {
ui.horizontal(|ui| {
let label_width = ui.label(label).rect.width();
ui.add_space((POLYGON_FILL_LABEL_WIDTH - label_width - ui.spacing().item_spacing.x).max(0.0));
controls(ui);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, info));
});
}
/// A dim info icon explaining a setting on hover
fn info_icon(ui: &mut Ui, text: &str) {
ui.label(RichText::new(ic::INFO).color(Tokens::get(ui.ctx()).text_dim)).on_hover_text(text);
}
/// What a polygon fill paints into now: Ok(true) a mask (gray), Ok(false) layer content (material), or a note on why it can't fill
fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result<bool, String> {
if app.session.quick_mask.editing {
return Err(tr("Editing the quick mask: fills paint where painting is allowed. Press U to finish.").to_string());
}
let project = &app.session.doc.project;
let Some(layer) = app.session.selected_layer().and_then(|id| project.layers.get(&id)) else {
return Err(tr("Select a paint layer or a layer's mask to fill").to_string());
};
match app.session.target {
StackTarget::Mask => Ok(true),
StackTarget::Effect(_) => Ok(!targets_content(app)),
StackTarget::Content => {
let content = project.content_layer(layer.id).unwrap_or(layer);
if matches!(content.kind, LayerKind::Paint) {
Ok(false)
} else {
Err(trf("\"{layer}\" can't be filled: select a paint layer or a layer's mask", &[("layer", &layer.name)]))
}
}
}
}
fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) {
let b = &mut app.session.tool.brush;
ui.label(caption(tr("Brush")));
@@ -1367,59 +1469,68 @@ fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) {
/// Tooltip of the material channel chips.
pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only";
/// The tool's material under a "Material" heading
fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
ui.label(caption(tr("Material")));
let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default();
material_controls(app, ui);
}
/// The tool's material: channel chips, then each enabled channel's value (or the mask gray while painting a mask)
fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) {
use texturecraft_engine::core::ChannelKind;
let tokens = Tokens::get(ui.ctx());
let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default();
ui.horizontal_wrapped(|ui| {
for c in &chans {
let on = app.session.tool.enabled.contains(c);
if chip(ui, tr(c.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() {
let solo = ui.input(|i| i.modifiers.alt);
app.run("tool.material", json!({"channel": c.id(), "enabled": solo || !on, "solo": solo}));
for channel in &channels {
let on = app.session.tool.enabled.contains(channel);
if chip(ui, tr(channel.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() {
let solo = ui.input(|input| input.modifiers.alt);
app.run("tool.material", json!({"channel": channel.id(), "enabled": solo || !on, "solo": solo}));
}
}
});
ui.add_space(4.0);
let mask_mode = !targets_content(app);
if mask_mode {
let mut v = app.session.tool.mask_value;
if slider(ui, tr("Mask value (gray)"), &mut v, 0.0..=1.0, 2).changed() {
app.session.tool.mask_value = v;
if !targets_content(app) {
let mut gray = app.session.tool.mask_value;
if slider(ui, tr("Mask value (gray)"), &mut gray, 0.0..=1.0, 2).changed() {
app.session.tool.mask_value = gray;
}
return;
}
for c in chans {
if !app.session.tool.enabled.contains(&c) {
for channel in channels {
if !app.session.tool.enabled.contains(&channel) {
continue;
}
let mut v = app.session.tool.values.get(&c).copied().unwrap_or(c.default_value());
match c.kind() {
texturecraft_engine::core::ChannelKind::Color => {
let mut value = app.session.tool.values.get(&channel).copied().unwrap_or(channel.default_value());
match channel.kind() {
ChannelKind::Color => {
ui.horizontal(|ui| {
ui.label(tr(c.label()));
if color_swatch(ui, &format!("tool_{}", c.id()), &mut v, ui.available_width() - 4.0) {
app.session.tool.values.insert(c, v);
ui.label(tr(channel.label()));
if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - 4.0) {
app.session.tool.values.insert(channel, value);
}
});
}
texturecraft_engine::core::ChannelKind::NormalMap => {
ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tk.text_dim));
ChannelKind::NormalMap => {
ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tokens.text_dim));
}
texturecraft_engine::core::ChannelKind::Signed => {
if slider(ui, tr(c.label()), &mut v[0], -1.0..=1.0, 2).changed() {
app.session.tool.values.insert(c, [v[0]; 3]);
ChannelKind::Signed => {
if slider(ui, tr(channel.label()), &mut value[0], -1.0..=1.0, 2).changed() {
app.session.tool.values.insert(channel, [value[0]; 3]);
}
}
texturecraft_engine::core::ChannelKind::Scalar => {
if slider(ui, tr(c.label()), &mut v[0], 0.0..=1.0, 2).changed() {
app.session.tool.values.insert(c, [v[0]; 3]);
ChannelKind::Scalar => {
if slider(ui, tr(channel.label()), &mut value[0], 0.0..=1.0, 2).changed() {
app.session.tool.values.insert(channel, [value[0]; 3]);
}
}
}
}
if app.session.tool.tool == Tool::Eraser {
ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tk.text_dim));
ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tokens.text_dim));
}
}
+20
View File
@@ -1037,4 +1037,24 @@ pub const TABLE: &[(&str, &str)] = &[
("Remove resolution override", "إزالة تجاوز الدقة"),
("Texture set resolution", "دقة مجموعة الخامات"),
("UV tile {tile} resolution", "دقة بلاطة UV {tile}"),
(
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
"النقرة تملأ ما تحتها، والمستطيل المسحوب يملأ ما يحدده أثناء اتساعه",
),
("Contained center: fill polygons whose center is in the rectangle", "المركز المحتوى: تعبئة المضلعات التي يقع مركزها داخل المستطيل"),
("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "تحرير القناع السريع: ترسم التعبئات حيث يُسمح بالرسم. اضغط U للإنهاء."),
("Fill mode", "وضع التعبئة"),
("Fill only polygons the camera sees (3D view)", "تعبئة المضلعات التي تراها الكاميرا فقط (العرض ثلاثي الأبعاد)"),
("Hit-test", "اختبار الإصابة"),
("How a rectangle selects polygons", "كيف يحدد المستطيل المضلعات"),
("Intersection: fill polygons the rectangle touches", "التقاطع: تعبئة المضلعات التي يلمسها المستطيل"),
("Rectangle fill", "تعبئة مستطيلة"),
("Select a paint layer or a layer's mask to fill", "حدد طبقة رسم أو قناع طبقة للتعبئة"),
("Selection mode", "وضع التحديد"),
(
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
"المثلث يملأ مثلثات منفردة، والمضلع رباعيات ومضلعات كاملة، والمجسم الهندسة المتصلة، وجزيرة UV جزر UV",
),
("Visible polygons only", "المضلعات المرئية فقط"),
("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"),
];
+23
View File
@@ -1080,4 +1080,27 @@ pub const TABLE: &[(&str, &str)] = &[
("Remove resolution override", "Auflösungsüberschreibung entfernen"),
("Texture set resolution", "Auflösung des Textursets"),
("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"),
(
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
"Ein Klick füllt, was darunter liegt; ein aufgezogenes Rechteck füllt, was es beim Aufziehen erfasst",
),
("Contained center: fill polygons whose center is in the rectangle", "Enthaltener Mittelpunkt: Polygone füllen, deren Mittelpunkt im Rechteck liegt"),
(
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
"Schnellmaske wird bearbeitet: Füllungen markieren, wo Malen erlaubt ist. Zum Beenden U drücken.",
),
("Fill mode", "Füllmodus"),
("Fill only polygons the camera sees (3D view)", "Nur Polygone füllen, die die Kamera sieht (3D-Ansicht)"),
("Hit-test", "Treffertest"),
("How a rectangle selects polygons", "Wie ein Rechteck Polygone auswählt"),
("Intersection: fill polygons the rectangle touches", "Schnittmenge: Polygone füllen, die das Rechteck berührt"),
("Rectangle fill", "Rechteckfüllung"),
("Select a paint layer or a layer's mask to fill", "Wähle zum Füllen eine Malebene oder eine Ebenenmaske"),
("Selection mode", "Auswahlmodus"),
(
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
"Dreieck füllt einzelne Dreiecke, Polygon ganze Vierecke und N-Ecke, Mesh die zusammenhängende Geometrie, UV-Insel die UV-Inseln",
),
("Visible polygons only", "Nur sichtbare Polygone"),
("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" kann nicht gefüllt werden: Wähle eine Malebene oder eine Ebenenmaske"),
];
+26
View File
@@ -1065,4 +1065,30 @@ pub const TABLE: &[(&str, &str)] = &[
("Remove resolution override", "Quitar resolución personalizada"),
("Texture set resolution", "Resolución del conjunto de texturas"),
("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"),
(
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
"Un clic rellena lo que hay debajo; un rectángulo arrastrado rellena lo que selecciona mientras crece",
),
("Contained center: fill polygons whose center is in the rectangle", "Centro contenido: rellenar los polígonos cuyo centro está en el rectángulo"),
(
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
"Editando la máscara rápida: los rellenos pintan donde se permite pintar. Pulsa U para terminar.",
),
("Fill mode", "Modo de relleno"),
("Fill only polygons the camera sees (3D view)", "Rellenar solo los polígonos que ve la cámara (vista 3D)"),
("Hit-test", "Prueba de selección"),
("How a rectangle selects polygons", "Cómo selecciona polígonos un rectángulo"),
("Intersection: fill polygons the rectangle touches", "Intersección: rellenar los polígonos que toca el rectángulo"),
("Rectangle fill", "Relleno rectangular"),
("Select a paint layer or a layer's mask to fill", "Selecciona una capa de pintura o una máscara de capa para rellenar"),
("Selection mode", "Modo de selección"),
(
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
"Triángulo rellena triángulos sueltos, Polígono cuadriláteros y n-gonos enteros, Malla la geometría conectada, Isla UV las islas UV",
),
("Visible polygons only", "Solo polígonos visibles"),
(
"\"{layer}\" can't be filled: select a paint layer or a layer's mask",
"\"{layer}\" no se puede rellenar: selecciona una capa de pintura o una máscara de capa",
),
];
+26
View File
@@ -1089,4 +1089,30 @@ pub const TABLE: &[(&str, &str)] = &[
("Remove resolution override", "Supprimer la résolution personnalisée"),
("Texture set resolution", "Résolution de l'ensemble de textures"),
("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"),
(
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
"Un clic remplit ce qui est dessous ; un rectangle tracé remplit ce qu'il sélectionne à mesure qu'il grandit",
),
("Contained center: fill polygons whose center is in the rectangle", "Centre contenu : remplir les polygones dont le centre est dans le rectangle"),
(
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
"Modification du masque rapide : les remplissages peignent là où la peinture est autorisée. Appuyez sur U pour terminer.",
),
("Fill mode", "Mode de remplissage"),
("Fill only polygons the camera sees (3D view)", "Remplir uniquement les polygones que voit la caméra (vue 3D)"),
("Hit-test", "Test de sélection"),
("How a rectangle selects polygons", "Comment un rectangle sélectionne les polygones"),
("Intersection: fill polygons the rectangle touches", "Intersection : remplir les polygones que touche le rectangle"),
("Rectangle fill", "Remplissage rectangulaire"),
("Select a paint layer or a layer's mask to fill", "Sélectionnez un calque de peinture ou un masque de calque à remplir"),
("Selection mode", "Mode de sélection"),
(
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
"Triangle remplit des triangles seuls, Polygone des quads et n-gones entiers, Maillage la géométrie connectée, Îlot UV les îlots UV",
),
("Visible polygons only", "Polygones visibles uniquement"),
(
"\"{layer}\" can't be filled: select a paint layer or a layer's mask",
"« {layer} » ne peut pas être rempli : sélectionnez un calque de peinture ou un masque de calque",
),
];
+26
View File
@@ -1074,4 +1074,30 @@ pub const TABLE: &[(&str, &str)] = &[
("Remove resolution override", "Rimuovi risoluzione personalizzata"),
("Texture set resolution", "Risoluzione del set di texture"),
("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"),
(
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
"Un clic riempie ciò che c'è sotto; un rettangolo trascinato riempie ciò che seleziona mentre si allarga",
),
("Contained center: fill polygons whose center is in the rectangle", "Centro contenuto: riempi i poligoni il cui centro è nel rettangolo"),
(
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
"Modifica della maschera rapida: i riempimenti dipingono le aree in cui è consentito dipingere. Premi U per terminare.",
),
("Fill mode", "Modalità di riempimento"),
("Fill only polygons the camera sees (3D view)", "Riempi solo i poligoni visti dalla camera (vista 3D)"),
("Hit-test", "Test di selezione"),
("How a rectangle selects polygons", "Come un rettangolo seleziona i poligoni"),
("Intersection: fill polygons the rectangle touches", "Intersezione: riempi i poligoni toccati dal rettangolo"),
("Rectangle fill", "Riempimento rettangolare"),
("Select a paint layer or a layer's mask to fill", "Seleziona un livello di pittura o una maschera di livello da riempire"),
("Selection mode", "Modalità di selezione"),
(
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
"Triangolo riempie singoli triangoli, Poligono quad e n-goni interi, Mesh la geometria connessa, Isola UV le isole UV",
),
("Visible polygons only", "Solo poligoni visibili"),
(
"\"{layer}\" can't be filled: select a paint layer or a layer's mask",
"\"{layer}\" non può essere riempito: seleziona un livello di pittura o una maschera di livello",
),
];
+26
View File
@@ -1059,4 +1059,30 @@ pub const TABLE: &[(&str, &str)] = &[
("Remove resolution override", "解像度の上書きを解除"),
("Texture set resolution", "テクスチャセットの解像度"),
("UV tile {tile} resolution", "UVタイル {tile} の解像度"),
(
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
"クリックでその下を塗りつぶし、ドラッグした矩形は広げるにつれて選択した範囲を塗りつぶします",
),
("Contained center: fill polygons whose center is in the rectangle", "中心を含む: 中心が矩形内にあるポリゴンを塗りつぶします"),
(
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
"クイックマスク編集中: 塗りつぶしでペイントを許可する範囲を塗ります。Uキーで終了します。",
),
("Fill mode", "塗りつぶしモード"),
("Fill only polygons the camera sees (3D view)", "カメラから見えるポリゴンだけを塗りつぶします (3Dビュー)"),
("Hit-test", "ヒットテスト"),
("How a rectangle selects polygons", "矩形がポリゴンを選択する方法"),
("Intersection: fill polygons the rectangle touches", "交差: 矩形が触れるポリゴンを塗りつぶします"),
("Rectangle fill", "矩形塗りつぶし"),
("Select a paint layer or a layer's mask to fill", "塗りつぶすペイントレイヤーまたはレイヤーマスクを選択してください"),
("Selection mode", "選択モード"),
(
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
"三角形は個々の三角形、ポリゴンは四角形やNゴン全体、メッシュはつながったジオメトリ、UVアイランドはUVアイランドを塗りつぶします",
),
("Visible polygons only", "表示されているポリゴンのみ"),
(
"\"{layer}\" can't be filled: select a paint layer or a layer's mask",
"「{layer}」は塗りつぶせません: ペイントレイヤーまたはレイヤーマスクを選択してください",
),
];
+23
View File
@@ -1047,4 +1047,27 @@ pub const TABLE: &[(&str, &str)] = &[
("Remove resolution override", "해상도 재정의 제거"),
("Texture set resolution", "텍스처 세트 해상도"),
("UV tile {tile} resolution", "UV 타일 {tile} 해상도"),
(
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
"클릭하면 아래에 있는 것을 채우고, 드래그한 사각형은 커지면서 선택한 것을 채웁니다",
),
("Contained center: fill polygons whose center is in the rectangle", "중심 포함: 중심이 사각형 안에 있는 폴리곤을 채웁니다"),
(
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
"퀵 마스크 편집 중: 채우기로 페인팅을 허용할 영역을 칠합니다. U를 눌러 완료하세요.",
),
("Fill mode", "채우기 모드"),
("Fill only polygons the camera sees (3D view)", "카메라에 보이는 폴리곤만 채웁니다 (3D 뷰)"),
("Hit-test", "히트 테스트"),
("How a rectangle selects polygons", "사각형이 폴리곤을 선택하는 방식"),
("Intersection: fill polygons the rectangle touches", "교차: 사각형에 닿는 폴리곤을 채웁니다"),
("Rectangle fill", "사각형 채우기"),
("Select a paint layer or a layer's mask to fill", "채울 페인트 레이어나 레이어 마스크를 선택하세요"),
("Selection mode", "선택 모드"),
(
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
"삼각형은 개별 삼각형, 폴리곤은 사각형과 N각형 전체, 메시는 연결된 지오메트리, UV 아일랜드는 UV 아일랜드를 채웁니다",
),
("Visible polygons only", "보이는 폴리곤만"),
("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"),
];
+26
View File
@@ -1062,4 +1062,30 @@ pub const TABLE: &[(&str, &str)] = &[
("Remove resolution override", "Remover resolução personalizada"),
("Texture set resolution", "Resolução do conjunto de texturas"),
("UV tile {tile} resolution", "Resolução do tile UV {tile}"),
(
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
"Um clique preenche o que está embaixo; um retângulo arrastado preenche o que seleciona enquanto cresce",
),
("Contained center: fill polygons whose center is in the rectangle", "Centro contido: preencher os polígonos cujo centro está no retângulo"),
(
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
"Editando a máscara rápida: os preenchimentos pintam onde a pintura é permitida. Pressione U para concluir.",
),
("Fill mode", "Modo de preenchimento"),
("Fill only polygons the camera sees (3D view)", "Preencher apenas os polígonos que a câmera vê (vista 3D)"),
("Hit-test", "Teste de seleção"),
("How a rectangle selects polygons", "Como um retângulo seleciona polígonos"),
("Intersection: fill polygons the rectangle touches", "Interseção: preencher os polígonos que o retângulo toca"),
("Rectangle fill", "Preenchimento retangular"),
("Select a paint layer or a layer's mask to fill", "Selecione uma camada de pintura ou uma máscara de camada para preencher"),
("Selection mode", "Modo de seleção"),
(
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
"Triângulo preenche triângulos isolados, Polígono quads e n-gons inteiros, Malha a geometria conectada, Ilha UV as ilhas UV",
),
("Visible polygons only", "Apenas polígonos visíveis"),
(
"\"{layer}\" can't be filled: select a paint layer or a layer's mask",
"\"{layer}\" não pode ser preenchida: selecione uma camada de pintura ou uma máscara de camada",
),
];
+17
View File
@@ -1005,4 +1005,21 @@ pub const TABLE: &[(&str, &str)] = &[
("Remove resolution override", "移除分辨率覆盖"),
("Texture set resolution", "纹理集分辨率"),
("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"),
("A click fills what is under it; a dragged rectangle fills what it selects as it grows", "单击填充其下方的内容;拖出的矩形在扩大时填充其选中的内容"),
("Contained center: fill polygons whose center is in the rectangle", "包含中心:填充中心位于矩形内的多边形"),
("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "正在编辑快速遮罩:填充绘制在允许绘画的区域。按 U 完成。"),
("Fill mode", "填充模式"),
("Fill only polygons the camera sees (3D view)", "仅填充相机可见的多边形(3D 视图)"),
("Hit-test", "命中测试"),
("How a rectangle selects polygons", "矩形选择多边形的方式"),
("Intersection: fill polygons the rectangle touches", "相交:填充矩形触及的多边形"),
("Rectangle fill", "矩形填充"),
("Select a paint layer or a layer's mask to fill", "选择要填充的绘画图层或图层遮罩"),
("Selection mode", "选择模式"),
(
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
"三角形填充单个三角形,多边形填充整个四边形和 n 边形,网格填充相连的几何体,UV 岛填充 UV 岛",
),
("Visible polygons only", "仅可见多边形"),
("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"),
];
+18 -13
View File
@@ -281,19 +281,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens)
path_controls(app, ui);
}
}
Tool::PolygonFill => {
use texturecraft_engine::FillMode;
for (fill_mode, icon, tooltip) in [
(FillMode::Triangle, ic::POLYGON, tr("Triangle fill")),
(FillMode::UvIsland, ic::SHAPES, tr("UV island fill")),
(FillMode::Mesh, ic::CUBE, tr("Mesh fill")),
] {
if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() {
app.session.tool.fill_mode = fill_mode;
}
}
}
Tool::PolygonFill => fill_mode_buttons(app, ui),
Tool::ColorPicker => {
ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim));
}
@@ -317,6 +305,23 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
}
}
/// Polygon fill's fill modes (top bar and properties)
pub fn fill_mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
use texturecraft_engine::FillMode;
let button_size = ui.spacing().interact_size.y;
for (fill_mode, icon, tooltip) in [
(FillMode::Triangle, ic::TRIANGLE, tr("Triangle fill")),
(FillMode::Polygon, ic::PARALLELOGRAM, tr("Polygon fill")),
(FillMode::Mesh, ic::CUBE, tr("Mesh fill")),
(FillMode::UvIsland, ic::CHECKERBOARD, tr("UV island fill")),
] {
if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() {
app.session.tool.fill_mode = fill_mode;
}
}
}
/// 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;
+83 -3
View File
@@ -9,7 +9,7 @@ use serde_json::json;
use texturecraft_engine::camera_cmds::DEFAULT_CAMERA;
use texturecraft_engine::core::BakedMap;
use texturecraft_engine::geom::glam::{Vec2, Vec3};
use texturecraft_engine::{Tool, ViewMode};
use texturecraft_engine::{Session, Tool, ViewMode};
use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind};
use crate::TextureCraftApp;
@@ -213,12 +213,14 @@ fn shade(app: &TextureCraftApp) -> Shade {
};
let set_index = app.session.ts();
let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0);
// Polygon fill shows the polygons it fills without changing the saved wireframe toggles
let polygon_fill_tool = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill;
Shade {
height_strength,
view_mode,
channel,
wireframe: app.ui.uv_wireframe,
wireframe_3d: app.ui.wireframe_3d,
wireframe: app.ui.uv_wireframe || polygon_fill_tool,
wireframe_3d: app.ui.wireframe_3d || polygon_fill_tool,
..Shade::from_project(&app.session.doc.project)
}
}
@@ -575,8 +577,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
let path_tool = app.session.tool.tool == Tool::Path;
let viewport = app.session.viewport;
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);
} else if painting && app.session.tool.tool == Tool::PolygonFill {
fill_box = polygon_fill_input(
app,
ui,
&response,
|session, point| session.polygon_fill(local(point), viewport),
|session, corner, opposite| session.drag_polygon_fill_box(local(corner), local(opposite), viewport),
);
} else if painting {
let pressure = pen_pressure(ui);
if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) {
@@ -621,6 +632,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(),
};
add_callback(app, ui, rect, frame, sync);
polygon_fill_box_overlay(ui, rect, fill_box);
// Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush
crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d);
@@ -1003,6 +1015,64 @@ fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) {
p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0));
}
/// Polygon fill in a view: a click fills one target, a drag fills its box live (one undo step); returns the box to draw over the view image
fn polygon_fill_input(
app: &mut TextureCraftApp,
ui: &Ui,
response: &egui::Response,
fill_at: impl Fn(&mut Session, Pos2) -> texturecraft_engine::Result<usize>,
drag_box: impl Fn(&mut Session, Pos2, Pos2) -> texturecraft_engine::Result<usize>,
) -> Option<Rect> {
let origin_id = response.id.with("polygon_fill_box");
let dragging = response.dragged_by(PointerButton::Primary);
let released = response.drag_stopped_by(PointerButton::Primary);
let held = ui.input(|input| input.pointer.primary_down());
if !held && !released {
// A drag this view started and cut short (Alt, a second finger) keeps what it filled as one step
if ui.data_mut(|data| data.remove_temp::<Pos2>(origin_id)).is_some() {
app.session.end_polygon_fill_box();
}
} else if dragging && let Some(press) = ui.input(|input| input.pointer.press_origin()) {
ui.data_mut(|data| data.insert_temp(origin_id, press));
}
// Consume the origin on release so a new press cannot resume the previous rectangle
let origin = if released { ui.data_mut(|data| data.remove_temp::<Pos2>(origin_id)) } else { ui.data(|data| data.get_temp::<Pos2>(origin_id)) };
let pointer = ui.input(|input| input.pointer.latest_pos());
let (filled, dragged_box) = match (origin, pointer) {
_ if response.clicked_by(PointerButton::Primary) => (response.interact_pointer_pos().map(|point| fill_at(&mut app.session, point)), None),
(Some(origin), Some(pointer)) if released => {
// The drag ends on release even when its last move failed
let shown = drag_box(&mut app.session, origin, pointer);
let filled = app.session.end_polygon_fill_box();
(Some(shown.map(|_| filled)), None)
}
_ if released => {
app.session.end_polygon_fill_box();
(None, None)
}
(Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))),
_ => (None, None),
};
if let Some(Err(error)) = filled {
app.toast(error.to_string(), true);
}
dragged_box
}
/// How strongly the polygon fill box tints what it covers (0..1)
const FILL_BOX_TINT: f32 = 0.15;
/// The polygon fill box being dragged, over view `rect`
fn polygon_fill_box_overlay(ui: &Ui, rect: Rect, fill_box: Option<Rect>) {
let Some(fill_box) = fill_box else { return };
let accent = Tokens::get(ui.ctx()).viewport_accent;
ui.painter_at(rect).rect(fill_box, 0.0, accent.gamma_multiply(FILL_BOX_TINT), Stroke::new(1.0, accent), egui::StrokeKind::Inside);
}
/// V held with the Clone tool in painting mode: clicks set the clone source.
fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool {
app.ui.mode == crate::state::Mode::Painting
@@ -1213,8 +1283,17 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
// Painting in UV space
let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held;
let mut fill_box = None;
if painting && path_tool {
path_input(app, ui, &response, 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,
ui,
&response,
|session, point| session.polygon_fill_uv(to_uv(point)),
|session, corner, opposite| session.drag_polygon_fill_box_uv(to_uv(corner), to_uv(opposite)),
);
} else if painting {
let pressure = pen_pressure(ui);
if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) {
@@ -1254,6 +1333,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(),
};
add_callback(app, ui, rect, frame, sync);
polygon_fill_box_overlay(ui, rect, fill_box);
crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View2d);
// The UV tile outlines (numbered for UDIM sets) and the path being edited
+143
View File
@@ -0,0 +1,143 @@
//! Polygon fill in the views: a click fills one target and a box drag fills what the box selects, each as one undo step
use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2};
use egui_kittest::Harness;
use texturecraft_engine::Tool;
use texturecraft_engine::core::Channel;
use texturecraft_ui_egui::TextureCraftApp;
/// The sample project in the default split layout at 1600 x 960 with the polygon fill tool
fn polygon_fill_app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().session.tool.tool = Tool::PolygonFill;
harness.run_steps(4);
harness
}
/// Drag the primary button from `from` to `to` in a few moves
fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) {
harness.hover_at(from);
harness.run_steps(1);
harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
harness.run_steps(2);
for step in 1..=4 {
harness.hover_at(from + (to - from) * (step as f32 / 4.0));
harness.run_steps(1);
}
// Only the release frame runs, so the release itself must finish the drag
harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
harness.run_steps(1);
}
/// Press and release the primary button at `at`
fn click(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) {
harness.hover_at(at);
harness.run_steps(1);
harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
harness.run_steps(3);
}
/// Allocated tiles in the selected layer's base color
fn painted_tiles(harness: &Harness<'_, TextureCraftApp>) -> usize {
let session = &harness.state().session;
let layer = session.selected_layer().expect("a selected layer");
session.doc.pixels.layer(layer, Channel::BaseColor).map_or(0, |image| image.allocated_count())
}
/// The undo steps recorded so far
fn history(harness: &Harness<'_, TextureCraftApp>) -> Vec<String> {
harness.state().session.history_labels()
}
#[test]
fn a_box_drag_in_the_3d_view_is_one_fill_over_more_than_a_click() {
let mut clicked = polygon_fill_app();
let center = clicked.state().viewport_rect.center();
let before = history(&clicked).len();
click(&mut clicked, center);
assert_eq!(history(&clicked).len(), before + 1, "a click fills one triangle");
let mut boxed = polygon_fill_app();
drag(&mut boxed, center - vec2(120.0, 120.0), center + vec2(120.0, 120.0));
assert_eq!(history(&boxed).len(), before + 1);
assert_eq!(history(&boxed).last().map(String::as_str), Some("Polygon fill"));
assert!(
painted_tiles(&boxed) > painted_tiles(&clicked),
"the box fills every triangle in it: {} tiles vs {}",
painted_tiles(&boxed),
painted_tiles(&clicked)
);
}
#[test]
fn a_box_drag_in_the_2d_view_is_one_fill() {
let mut harness = polygon_fill_app();
let view_3d = harness.state().viewport_rect;
let center = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y);
let before = history(&harness).len();
drag(&mut harness, center - vec2(80.0, 20.0), center + vec2(80.0, 20.0));
assert_eq!(history(&harness).len(), before + 1);
assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill"));
}
#[test]
fn a_new_press_after_release_does_not_resume_the_previous_box() {
let mut harness = polygon_fill_app();
let center = harness.state().viewport_rect.center();
drag(&mut harness, center - vec2(40.0, 40.0), center + vec2(40.0, 40.0));
let history_after_drag = history(&harness);
let tiles_after_drag = painted_tiles(&harness);
// Start the next gesture on the frame immediately after release
let point = center - vec2(80.0, 80.0);
harness
.input_mut()
.events
.extend([Event::PointerMoved(point), Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]);
harness.run_steps(1);
assert_eq!(painted_tiles(&harness), tiles_after_drag, "a press alone must not refill the old rectangle");
harness.event(Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
harness.run_steps(1);
assert_eq!(history(&harness).len(), history_after_drag.len() + 1, "only the new click records a step");
}
#[test]
#[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"]
fn polygon_fill_snapshots() {
let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return };
std::fs::create_dir_all(&directory).unwrap();
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session));
let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info();
eprintln!("Offscreen adapter: {} ({:?}), driver {} {}", adapter.name, adapter.backend, adapter.driver, adapter.driver_info);
harness.state_mut().session.tool.tool = Tool::PolygonFill;
harness.run_steps(6);
harness.render().unwrap().save(directory.join("polygon-fill-properties.png")).unwrap();
let center = harness.state().viewport_rect.center();
let origin = center - vec2(85.0, 70.0);
let opposite = center + vec2(85.0, 70.0);
harness.hover_at(origin);
harness.event(Event::PointerButton { pos: origin, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
harness.run_steps(1);
harness.hover_at(opposite);
harness.run_steps(6);
harness.render().unwrap().save(directory.join("polygon-fill-drag-3d.png")).unwrap();
harness.event(Event::PointerButton { pos: opposite, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
harness.run_steps(6);
harness.render().unwrap().save(directory.join("polygon-fill-complete-3d.png")).unwrap();
texturecraft_engine::execute(&mut harness.state_mut().session, "mask.add.black", &serde_json::Value::Null).unwrap();
let view = harness.state().viewport_rect;
let center = pos2(view.right() + view.width() * 0.5, view.center().y);
drag(&mut harness, center - vec2(80.0, 20.0), center + vec2(80.0, 20.0));
harness.run_steps(6);
harness.render().unwrap().save(directory.join("polygon-fill-mask-2d.png")).unwrap();
}