Polygon fill: review fixes

- A box drag always finishes: on release (even after a failed move), before
  any edit, undo, redo or tool change, and when a scripted box fails or
  starts while another drag is open. A camera move mid-drag (wheel zoom)
  keeps the drag and selects again from the new camera.
- A drag projects the mesh once, skips repaints whose box hasn't moved,
  and builds each grouping once; triangle edges are computed once.
- 2D clicks read the triangle from the set's UV G-buffer at the clicked
  texel, so collapsed UV faces can't take the click.
- Brush strokes no longer record the nearest-triangle buffer; only polygon
  fill asks for it (EyeDepth::render_with_triangles). Screen projection is
  shared through paint::screen_point.
- A box touching the view's edge or zero-size on whole pixels selects
  exactly the pixels it covers.
- Click fills never merge into a box drag's undo step; FillMode moves to
  its own file; partial box parameters get their own error.
This commit is contained in:
Rebornim committed 2026-11-07 07:52:40 +00:00
1 parent 3b302b88dc
commit 49bd4a1273
13 files changed
+439 -246

No files matched your search

+18 -15
View File
@@ -25,17 +25,17 @@ impl FillHitTest {
/// 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),
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
@@ -63,11 +63,14 @@ mod tests {
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");
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)));
}
+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,
}
+3 -1
View File
@@ -16,6 +16,7 @@ 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;
@@ -55,9 +56,10 @@ 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;
+2 -1
View File
@@ -502,7 +502,8 @@ impl Session {
return self.paint_fill(ts, canvas);
}
self.edit(label, |session| session.paint_fill(ts, canvas))
// 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))
}
/// 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)
+250 -117
View File
@@ -3,21 +3,19 @@
use std::borrow::Cow;
use std::collections::{BTreeSet, HashSet};
use texturecraft_geom::glam::{Vec2, Vec4Swizzles};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Mesh, NO_TRI};
use texturecraft_paint::{EyeDepth, fill_triangles};
use texturecraft_paint::{EyeDepth, fill_triangles, screen_point};
use crate::fill_mode::FillMode;
use crate::polygon_fill_drag::PolygonFillDrag;
use crate::session::{FillMode, Session};
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;
/// 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> {
@@ -29,73 +27,131 @@ impl Session {
self.fill_group_of(hit.tri)
}
/// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view)
/// 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 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)))
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 as u32)
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> {
self.drag_polygon_fill_box(corner, opposite, viewport)?;
Ok(self.end_polygon_fill_box())
// 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.drag_polygon_fill_box_uv(corner, opposite)?;
Ok(self.end_polygon_fill_box())
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> {
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)
// 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> {
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)
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 };
// Quick mask edits keep no history, as with its strokes
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)
}
/// Begin a box drag unless one is under way in the same view, texture set and quick mask state; a drag from another one ends first
fn start_polygon_fill_drag(&mut self, viewport: Option<Vec2>) -> Result<()> {
let ts = self.ts();
let quick_mask = self.quick_mask.editing;
// A different view size, set or quick mask state starts a new drag; the old one keeps its fill as one step
if let Some(drag) = &self.polygon_fill_drag {
if drag.ts == ts && 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,
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)
@@ -123,32 +179,6 @@ impl Session {
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;
@@ -168,17 +198,28 @@ impl Session {
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> {
/// 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().map(|(depth, viewport)| visible_triangles(depth, *viewport, low, high));
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.groups {
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)));
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)) {
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)));
}
}
@@ -189,17 +230,17 @@ impl Session {
/// 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());
if drag.filled == selected {
return Ok(selected.len());
}
drag.filled = selected.clone();
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 ts = self.ts();
let painted = if selected.is_empty() {
Ok(())
} else {
@@ -209,37 +250,23 @@ impl Session {
})
};
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);
// 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.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);
painted.map(|_| selected_count)
}
}
/// Triangles `depth` (rendered for `viewport`) shows in the viewport pixels from `low` to `high`
/// 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 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);
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()
@@ -247,13 +274,11 @@ fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) ->
.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)))
/// 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
@@ -262,13 +287,6 @@ fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> {
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);
@@ -308,7 +326,8 @@ mod tests {
use texturecraft_geom::primitives;
use crate::fill_hit_test::FillHitTest;
use crate::session::{FillMode, Session, Tool};
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;
@@ -446,6 +465,44 @@ mod tests {
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());
@@ -456,6 +513,82 @@ mod tests {
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));
+17 -6
View File
@@ -2,6 +2,7 @@
use std::collections::{BTreeMap, BTreeSet};
use texturecraft_geom::OrbitCamera;
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::EyeDepth;
use texturecraft_texel::TileImage;
@@ -11,18 +12,28 @@ 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 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>>,
/// 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,
/// 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,
}
+26 -30
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,17 +161,6 @@ impl ViewMode {
}
}
/// Polygon fill granularity.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum FillMode {
#[default]
Triangle,
/// The source polygon (quad or n-gon) the importer split into triangles
Polygon,
UvIsland,
Mesh,
}
/// A screen-pinned image for the Projection tool (a stencil).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StencilState {
@@ -506,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)
}
}
}
@@ -642,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)
}
+40 -32
View File
@@ -8,7 +8,8 @@ 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::fill_mode::FillMode;
use crate::session::{CloneFrom, CloneSource, Tool};
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
@@ -103,11 +104,13 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
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> {
@@ -337,26 +340,27 @@ 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(s: &mut Session, p: &Value) -> Result<Value> {
match strp(p, "hitTest") {
fn fill_selection(session: &mut Session, params: &Value) -> Result<Value> {
match strp(params, "hitTest") {
None => {}
Some("intersection") => s.tool.fill_hit_test = FillHitTest::Intersection,
Some("containedCenter") => s.tool.fill_hit_test = FillHitTest::ContainedCenter,
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(p, "visibleOnly") {
s.tool.fill_visible_only = visible_only;
if let Some(visible_only) = boolp(params, "visibleOnly") {
session.tool.fill_visible_only = visible_only;
}
Ok(Value::Null)
@@ -402,38 +406,42 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "stamps": stamps }))
}
fn click(s: &mut Session, p: &Value) -> Result<Value> {
if s.tool.tool == Tool::PolygonFill
&& let Some(triangles) = polygon_fill_click(s, p)?
fn click(session: &mut Session, params: &Value) -> Result<Value> {
if session.tool.tool == Tool::PolygonFill
&& let Some(triangles) = polygon_fill_click(session, params)?
{
s.update();
session.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 (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(s, p);
let out = match s.tool.tool {
Tool::PolygonFill => json!({ "triangles": s.polygon_fill(point, viewport)? }),
let viewport = viewport_of(session, params);
let out = match session.tool.tool {
Tool::PolygonFill => json!({ "triangles": session.polygon_fill(point, viewport)? }),
Tool::ColorPicker => {
let picked = s.color_pick(point, viewport)?;
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, point, viewport)?,
_ => json!({ "stamps": s.stroke_points(&[point], viewport)? }),
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(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))?,
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),
};
+13 -7
View File
@@ -1,6 +1,7 @@
//! Triangles of one material grouped into the pieces polygon fill selects and fills.
use std::collections::{BTreeMap, HashMap};
use std::collections::HashMap;
use std::hash::Hash;
use texturecraft_geom::Mesh;
@@ -14,12 +15,15 @@ pub struct TrianglePartition {
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 {
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 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 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);
}
}
@@ -29,12 +33,14 @@ impl TrianglePartition {
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()) {
let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default();
for neighbour in triangle_edges.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);
+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};
+41 -31
View File
@@ -2,7 +2,7 @@
//! rendered once at the start of a stroke.
use rayon::prelude::*;
use texturecraft_geom::glam::{Mat4, Vec3, Vec4};
use texturecraft_geom::glam::{Mat4, Vec2, Vec3};
use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera};
const BAND: usize = 16;
@@ -11,7 +11,7 @@ const BAND: usize = 16;
const MAX_SIZE: u32 = 4096;
/// Clip-space w below which a vertex counts as behind the camera.
const MIN_CLIP_W: f32 = 1e-5;
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;
@@ -30,28 +30,38 @@ pub struct EyeDepth {
pub view_proj: Mat4,
pub eye: Vec3,
pub dist: Vec<f32>,
/// The nearest triangle per screen pixel ([`NO_TRI`] where empty).
/// 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 [`MAX_SIZE`]).
/// 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 {
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 {
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 size = Vec2::new(width as f32, height as f32);
let view_proj = camera.view_proj(size.x / size.y);
let eye = camera.eye();
// 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 screen: Vec<Option<Vec2>> = mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).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
@@ -60,8 +70,8 @@ impl EyeDepth {
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);
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;
}
@@ -72,9 +82,11 @@ impl EyeDepth {
}
let mut dist = vec![f32::MAX; (width * height) as usize];
let mut triangle = vec![NO_TRI; (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;
dist.par_chunks_mut(band_len).zip(triangle.par_chunks_mut(band_len)).enumerate().for_each(|(band, (band_dist, band_triangles))| {
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(&[]) {
@@ -84,24 +96,22 @@ impl EyeDepth {
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);
let corner_distance = corners.map(|vertex| vertex_distance.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 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;
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.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;
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;
@@ -113,7 +123,7 @@ impl EyeDepth {
&& distance < *slot
{
*slot = distance;
if let Some(nearest) = band_triangles.get_mut(at) {
if let Some(nearest) = band_triangles.as_deref_mut().and_then(|triangles| triangles.get_mut(at)) {
*nearest = candidate;
}
}
+9 -4
View File
@@ -214,13 +214,13 @@ 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;
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 || polygon_fill,
wireframe_3d: app.ui.wireframe_3d || polygon_fill,
wireframe: app.ui.uv_wireframe || polygon_fill_tool,
wireframe_3d: app.ui.wireframe_3d || polygon_fill_tool,
..Shade::from_project(&app.session.doc.project)
}
}
@@ -1040,7 +1040,12 @@ fn polygon_fill_input(
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)) 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)
}
(Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))),
_ => (None, None),
};
+2 -1
View File
@@ -27,8 +27,9 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) {
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(3);
harness.run_steps(1);
}
/// Press and release the primary button at `at`