Polygon fill: box selection, polygon mode, hit-test, visible polygons only and the 2D view

A drag in the 3D or 2D view draws a rectangle and fills what it selects
live; releasing it records one undo step. A click still fills one target,
now also in the 2D view. Fill modes gain Polygon (the source quad or n-gon,
from the importer's diagonals), and Mesh fills connected geometry. The
hit-test picks polygons the rectangle touches or whose center it holds;
visible polygons only uses a nearest-triangle buffer next to the eye-depth
raster, leaving hidden texture sets out.

Polygon fill's properties show its own settings and, by selection, the
material, the mask gray, or why it can't fill. Wireframes show while the
tool is active without changing the saved toggles.

Commands: tool.fillMode takes polygon, tool.fillSelection sets hitTest and
visibleOnly, and tool.click takes a screen box, a UV point or a UV box.
This commit is contained in:
Rebornim committed 2026-11-07 07:00:12 +00:00
1 parent eb9b736520
commit 3b302b88dc
23 files changed
+1414 -210

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
//! 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> {
let area = |corners: &[Vec2; 3]| (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs();
let centroid = |corners: &[Vec2; 3]| (corners[0] + corners[1] + corners[2]) / 3.0;
let total: f32 = triangles.iter().map(area).sum();
let weighted: Vec2 = triangles.iter().map(|corners| centroid(corners) * area(corners)).sum();
let centroids: Vec2 = triangles.iter().map(centroid).sum();
match triangles.len() {
0 => None,
count if total <= f32::EPSILON => Some(centroids / count as f32),
_ => Some(weighted / total),
}
}
/// 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_needs_any_overlap_and_contained_center_the_center() {
let (low, high) = (Vec2::new(2.0, 2.0), Vec2::new(6.0, 6.0));
assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(1.0, 1.0), high), "a box cutting the triangle");
assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(3.0, 3.0), Vec2::new(5.0, 5.0)), "inside the bounds, past the long edge");
assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], low, high), "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);
}
}
+5
View File
@@ -15,6 +15,7 @@ pub mod commands;
pub mod decal_cmds;
pub mod effect_clipboard;
pub mod file_cmds;
pub mod fill_hit_test;
pub mod filter_lib;
pub mod inspect;
pub mod instance_cmds;
@@ -31,6 +32,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,11 +48,13 @@ 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 path_tool::PathState;
pub use project_cmds::sample_session;
pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
+28 -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,30 @@ 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(())
})
self.edit(label, |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 +584,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");
}
}
+470
View File
@@ -0,0 +1,470 @@
//! 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, Vec4Swizzles};
use texturecraft_geom::{Mesh, NO_TRI};
use texturecraft_paint::{EyeDepth, fill_triangles};
use crate::polygon_fill_drag::PolygonFillDrag;
use crate::session::{FillMode, 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;
/// Clip-space w below which a vertex counts as behind the camera
const MIN_CLIP_W: f32 = 1e-5;
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)
pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result<usize> {
let material = self.fill_material()?;
let mesh = &self.mesh;
let triangle = mesh
.triangles_of(material)
.find(|triangle| uv_corners(mesh, *triangle).is_some_and(|corners| contains(corners, uv)))
.ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
self.fill_group_of(triangle as u32)
}
/// 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> {
self.drag_polygon_fill_box(corner, opposite, viewport)?;
Ok(self.end_polygon_fill_box())
}
/// 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.drag_polygon_fill_box_uv(corner, opposite)?;
Ok(self.end_polygon_fill_box())
}
/// 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> {
let (low, high) = box_bounds(corner, opposite)?;
let viewport = viewport.max(Vec2::ONE);
self.start_polygon_fill_drag(Some(viewport))?;
let view_proj = self.camera.view_proj(viewport.x / viewport.y);
let mesh = self.mesh.clone();
let to_screen = |vertex: usize| {
let clip = view_proj * mesh.positions.get(vertex)?.extend(1.0);
let ndc = (clip.w > MIN_CLIP_W).then(|| clip.xy() / clip.w)?;
Some(Vec2::new(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * viewport)
};
let screen_corners = |triangle: usize| {
let [first, second, third] = mesh.tri(triangle)?;
Some([to_screen(first)?, to_screen(second)?, to_screen(third)?])
};
let selected = self.box_selection(&screen_corners, low, high);
self.show_box_fill(selected)
}
/// 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> {
let (low, high) = box_bounds(corner, opposite)?;
self.start_polygon_fill_drag(None)?;
let mesh = self.mesh.clone();
let selected = self.box_selection(&|triangle| uv_corners(&mesh, triangle), low, high);
self.show_box_fill(selected)
}
/// 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 };
// Quick mask edits keep no history, as with its strokes
let filled = drag.filled.len();
if filled > 0 && drag.quick_mask_before.is_none() {
self.push_history("Polygon fill", drag.before);
}
filled
}
/// 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())
}
/// Begin a box drag unless one is under way; `viewport` is the 3D view's size (None in the 2D view)
fn start_polygon_fill_drag(&mut self, viewport: Option<Vec2>) -> Result<()> {
if self.polygon_fill_drag.is_some() {
return Ok(());
}
let material = self.fill_material()?;
let polygons = match self.tool.fill_mode {
FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::<u32>::new()),
_ => TrianglePartition::new(&self.mesh, material, polygon_edges),
};
let depth = viewport
.filter(|_| self.tool.fill_visible_only)
.map(|size| (EyeDepth::render(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32), size));
self.polygon_fill_drag = Some(PolygonFillDrag {
before: self.doc.clone(),
quick_mask_before: self.quick_mask.editing.then(|| self.quick_mask.masks.clone()),
filled: BTreeSet::new(),
depth,
polygons,
fill_groups: self.fill_partition(material),
failed: false,
});
Ok(())
}
/// 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, given each triangle's `corners` in the box's space
fn box_selection(&self, corners: &dyn Fn(usize) -> Option<[Vec2; 3]>, low: Vec2, high: Vec2) -> BTreeSet<u32> {
let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() };
let visible = drag.depth.as_ref().map(|(depth, viewport)| visible_triangles(depth, *viewport, low, high));
let hit_test = self.tool.fill_hit_test;
let mut groups = BTreeSet::new();
for polygon in &drag.polygons.groups {
let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle)));
let triangles: Option<Vec<[Vec2; 3]>> = polygon.iter().map(|triangle| corners(*triangle as usize)).collect();
if seen && triangles.is_some_and(|triangles| hit_test.selects(&triangles, 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.failed || drag.filled == selected {
return Ok(drag.filled.len());
}
drag.filled = selected.clone();
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();
}
let ts = self.ts();
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);
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
// A failed fill is reported once; the rest of the drag fills nothing
if painted.is_err()
&& let Some(mut drag) = self.polygon_fill_drag.take()
{
self.restore_before_box(&drag);
drag.failed = true;
drag.filled.clear();
self.polygon_fill_drag = Some(drag);
}
painted.map(|_| selected.len())
}
/// Put back the document and quick mask from before the box `drag`
fn restore_before_box(&mut self, drag: &PolygonFillDrag) {
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);
}
self.invalidate_changed(&previous);
}
}
/// Triangles `depth` (rendered for `viewport`) shows in the viewport pixels from `low` to `high`
fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet<u32> {
let pixels_per_point = Vec2::new(depth.width as f32, depth.height as f32) / viewport;
let (first, last) = ((low * pixels_per_point).floor(), (high * pixels_per_point).ceil());
let columns = first.x.max(0.0) as usize..(last.x as usize).min(depth.width as usize);
let rows = first.y.max(0.0) as usize..(last.y as usize).min(depth.height as usize);
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 two corners spanning a box, lowest first
fn box_bounds(corner: Vec2, opposite: Vec2) -> Result<(Vec2, Vec2)> {
if !corner.is_finite() || !opposite.is_finite() {
return Err(EngineError::Other("the box corners must be finite".into()));
}
Ok((corner.min(opposite), corner.max(opposite)))
}
/// 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)?])
}
/// Whether `point` lies in the triangle with `corners` (either winding)
fn contains(corners: [Vec2; 3], point: Vec2) -> bool {
let side = |edge: usize| (corners[(edge + 1) % 3] - corners[edge]).perp_dot(point - corners[edge]);
let sides = [side(0), side(1), side(2)];
sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0)
}
/// 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::session::{FillMode, 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_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_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");
}
}
+28
View File
@@ -0,0 +1,28 @@
//! 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_geom::glam::Vec2;
use texturecraft_paint::EyeDepth;
use texturecraft_texel::TileImage;
use crate::session::Document;
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 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>>,
/// The triangles filled so far
pub filled: BTreeSet<u32>,
/// What the camera sees and the viewport size it was rendered for (3D view, visible polygons only)
pub depth: Option<(EyeDepth, Vec2)>,
/// The polygons the box tests
pub polygons: TrianglePartition,
/// What the fill mode fills together
pub fill_groups: TrianglePartition,
/// The fill failed (reported once): the rest of the drag fills nothing
pub failed: bool,
}
+18 -1
View File
@@ -165,6 +165,8 @@ impl ViewMode {
pub enum FillMode {
#[default]
Triangle,
/// The source polygon (quad or n-gon) the importer split into triangles
Polygon,
UvIsland,
Mesh,
}
@@ -210,6 +212,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 +239,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 +272,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 +370,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 +421,7 @@ impl Session {
revision: 1,
log: Vec::new(),
depth_cache: None,
polygon_fill_drag: None,
export_presets: Default::default(),
templates: Default::default(),
})
@@ -530,7 +547,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<_>>();
+63 -8
View File
@@ -7,6 +7,7 @@ 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::fill_hit_test::FillHitTest;
use crate::session::{CloneFrom, CloneSource, FillMode, Tool};
use crate::{Result, Session, cmd};
@@ -69,7 +70,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,7 +90,15 @@ 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))),
]
}
@@ -322,6 +340,7 @@ fn clone_source(s: &mut Session, p: &Value) -> Result<Value> {
fn fill_mode(s: &mut Session, p: &Value) -> Result<Value> {
s.tool.fill_mode = match strp(p, "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}`"))),
@@ -329,6 +348,20 @@ fn fill_mode(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
fn fill_selection(s: &mut Session, p: &Value) -> Result<Value> {
match strp(p, "hitTest") {
None => {}
Some("intersection") => s.tool.fill_hit_test = FillHitTest::Intersection,
Some("containedCenter") => s.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(p, "visibleOnly") {
s.tool.fill_visible_only = visible_only;
}
Ok(Value::Null)
}
pub(crate) fn viewport_of(s: &Session, p: &Value) -> Vec2 {
match p.get("viewport").and_then(Value::as_array) {
Some(a) if a.len() == 2 => {
@@ -370,21 +403,43 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
}
fn click(s: &mut Session, p: &Value) -> Result<Value> {
if s.tool.tool == Tool::PolygonFill
&& let Some(triangles) = polygon_fill_click(s, p)?
{
s.update();
return Ok(json!({ "triangles": triangles }));
}
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 point = Vec2::new(x, y);
let viewport = viewport_of(s, p);
let out = match s.tool.tool {
Tool::PolygonFill => json!({ "triangles": s.polygon_fill(Vec2::new(x, y), vp)? }),
Tool::PolygonFill => json!({ "triangles": s.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 = s.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(s, point, viewport)?,
_ => json!({ "stamps": s.stroke_points(&[point], viewport)? }),
};
s.update();
Ok(out)
}
/// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point
fn polygon_fill_click(s: &mut Session, p: &Value) -> Result<Option<usize>> {
let screen_box = (f32p(p, "x0"), f32p(p, "y0"), f32p(p, "x1"), f32p(p, "y1"));
let filled = match (pair(p, "uv0"), pair(p, "uv1"), pair(p, "uv"), screen_box) {
(Some(corner), Some(opposite), ..) => s.polygon_fill_box_uv(corner.into(), opposite.into())?,
(_, _, Some(uv), _) => s.polygon_fill_uv(uv.into())?,
(.., (Some(x0), Some(y0), Some(x1), Some(y1))) => s.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(s, p))?,
_ => 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)?;
+77
View File
@@ -0,0 +1,77 @@
//! Triangles of one material grouped into the pieces polygon fill selects and fills.
use std::collections::{BTreeMap, HashMap};
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: Ord>(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec<K>) -> TrianglePartition {
let triangles: Vec<u32> = mesh.triangles_of(material).map(|triangle| triangle as u32).collect();
let mut by_edge: BTreeMap<K, Vec<u32>> = BTreeMap::new();
for &triangle in &triangles {
for edge in edges(mesh, triangle as usize) {
by_edge.entry(edge).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);
for neighbour in edges(mesh, triangle as usize).iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) {
if !group_of.contains_key(neighbour) {
group_of.insert(*neighbour, 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);
}
}
+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() {
+88 -47
View File
@@ -3,10 +3,25 @@
use rayon::prelude::*;
use texturecraft_geom::glam::{Mat4, Vec3, Vec4};
use texturecraft_geom::{Mesh, OrbitCamera};
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.
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,99 @@ pub struct EyeDepth {
pub view_proj: Mat4,
pub eye: Vec3,
pub dist: Vec<f32>,
/// The nearest triangle per screen pixel ([`NO_TRI`] where empty).
pub triangle: Vec<u32>,
/// Tolerance in world units (≈ 0.4% of the scene radius).
pub bias: f32,
}
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`]).
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);
let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE));
let view_proj = camera.view_proj(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() {
// Project every vertex once
let screen: Vec<Option<(f32, f32)>> = mesh
.positions
.iter()
.map(|position| {
let clip: Vec4 = view_proj * position.extend(1.0);
(clip.w > MIN_CLIP_W).then(|| ((clip.x / clip.w * 0.5 + 0.5) * width as f32, (0.5 - clip.y / clip.w * 0.5) * height as f32))
})
.collect();
let vertex_distance: Vec<f32> = mesh.positions.iter().map(|position| position.distance(eye)).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.1.min(second.1).min(third.1).floor().max(0.0);
let bottom = first.1.max(second.1).max(third.1).ceil().min(height as f32);
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 = vec![NO_TRI; (width * height) as usize];
let band_len = BAND * width as usize;
dist.par_chunks_mut(band_len).zip(triangle.par_chunks_mut(band_len)).enumerate().for_each(|(band, (band_dist, 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_distance = corners.map(|vertex| vertex_distance[vertex]);
let area =
(second_point.0 - first_point.0) * (third_point.1 - first_point.1) - (second_point.1 - first_point.1) * (third_point.0 - first_point.0);
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 left = first_point.0.min(second_point.0).min(third_point.0).floor().max(0.0) as usize;
let right = (first_point.0.max(second_point.0).max(third_point.0).ceil().min(width as f32)) as usize;
let top = (first_point.1.min(second_point.1).min(third_point.1).floor().max(first_row as f32)) as usize;
let bottom = (first_point.1.max(second_point.1).max(third_point.1).ceil().min((first_row + row_count) as f32)) as usize;
for row in top.max(first_row)..bottom {
for column in left..right.min(width as usize) {
let (sample_x, sample_y) = (column as f32 + 0.5, row as f32 + 0.5);
let first_weight =
((second_point.0 - sample_x) * (third_point.1 - sample_y) - (second_point.1 - sample_y) * (third_point.0 - sample_x)) / area;
let second_weight =
((third_point.0 - sample_x) * (first_point.1 - sample_y) - (third_point.1 - sample_y) * (first_point.0 - sample_x)) / 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 distance = first_weight * corner_distance[0] + second_weight * corner_distance[1] + third_weight * corner_distance[2];
let at = (row - first_row) * width as usize + column;
if let Some(slot) = band_dist.get_mut(at)
&& distance < *slot
{
*slot = d;
*slot = distance;
if let Some(nearest) = band_triangles.get_mut(at) {
*nearest = candidate;
}
}
}
}
}
});
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).
+147 -36
View File
@@ -912,12 +912,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"))
@@ -927,12 +929,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() => {
@@ -1144,6 +1148,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")));
@@ -1365,59 +1467,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
@@ -1035,4 +1035,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
@@ -1078,4 +1078,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
@@ -1063,4 +1063,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
@@ -1087,4 +1087,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
@@ -1072,4 +1072,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
@@ -1057,4 +1057,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
@@ -1045,4 +1045,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
@@ -1060,4 +1060,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
@@ -1003,4 +1003,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;
+71 -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 = 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,
wireframe_3d: app.ui.wireframe_3d || polygon_fill,
..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,52 @@ 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));
}
let origin = 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 => (Some(drag_box(&mut app.session, origin, pointer).map(|_| app.session.end_polygon_fill_box())), 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 +1271,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 +1321,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
+85
View File
@@ -0,0 +1,85 @@
//! 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);
}
harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
harness.run_steps(3);
}
/// 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"));
}