Merge latest main into baked map import

Preserve both module and translation additions. Register the baked map tests in the consolidated integration suites.
This commit is contained in:
chasse20 committed 2026-11-08 21:42:24 -05:00
commit c573250601
172 files changed
+9998 -1379

No files matched your search

+2
View File
@@ -25,6 +25,8 @@ jobs:
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
os: '["ubuntu-24.04","windows-latest"]'
toolchain: "1.96.0"
# xtask ci runs cargo test (including doctests), not cargo nextest.
tools: ""
packages: >-
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
libgtk-3-dev
+38 -22
View File
@@ -11,6 +11,7 @@ mod window_frame;
use texturecraft_engine::Session;
use texturecraft_ui_egui::titlebar::TitleBar;
use texturecraft_ui_egui::ui_state_store;
use texturecraft_ui_egui::{TextureCraftApp, UiState};
/// The app name eframe keeps the settings under (`eframe::storage_dir`).
@@ -115,13 +116,16 @@ fn set_taskbar_icon(w: &winit::window::Window) {
}
}
/// Settings › Interface › System title bar, read from the saved settings before the window opens
/// (eframe hands the app its storage only afterwards). Missing or unreadable: off.
fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool {
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron")));
let saved = file.and_then(|f| std::fs::read_to_string(f).ok());
let kv = saved.and_then(|s| ron::from_str::<std::collections::HashMap<String, String>>(&s).ok());
kv.and_then(|kv| ron::from_str::<UiState>(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off
fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool {
if let Some(ui) = ui_file.and_then(ui_state_store::read) {
return ui.prefs.system_title_bar;
}
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron")));
let saved = file.and_then(|file| std::fs::read_to_string(file).ok());
let entries = saved.and_then(|text| ron::from_str::<std::collections::HashMap<String, String>>(&text).ok());
entries.and_then(|entries| ron::from_str::<UiState>(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
}
/// The app with the window chrome that needs the native window: the Windows borderless guard, and
@@ -170,20 +174,24 @@ fn main() {
std::process::exit(2);
}
};
// Errors before the window opens speak the system's language; the app then applies the saved one.
// Errors before the window opens speak the system's language; the app then applies the saved one
texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language());
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
// A message box needs the main thread on macOS; other threads' panics are only logged.
// A message box needs the main thread on macOS; other threads' panics are only logged
fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main"));
prev(info);
}));
let session = initial_session(&args);
// Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS so they neither read nor
// overwrite the user's saved UI layout and settings: state goes to a throwaway folder.
// Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files
let persistence_path =
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref()));
let ui_file =
persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json")));
if let Some(file) = &ui_file {
let _ = ui_state_store::FILE.set(file.clone());
}
let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref()));
let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]);
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
@@ -195,7 +203,7 @@ fn main() {
std::process::exit(2);
}
let control = args.control;
// The start window offers new, open and recent projects, unless a file was given or a script drives the app.
// The start window offers new, open and recent projects, unless a file was given or a script drives the app
let start = args.file.is_none() && control.is_none();
let r = eframe::run_native(
APP_NAME,
@@ -296,19 +304,27 @@ mod tests {
}
#[test]
fn the_system_title_bar_setting_is_read_from_eframes_settings_file() {
let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id()));
fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() {
let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id()));
let json_path = ron_path.with_extension("json");
for on in [false, true] {
let mut ui = UiState::default();
ui.prefs.system_title_bar = on;
// Written as eframe writes it: a pretty RON map of RON strings.
// Written as eframe writes it: a pretty RON map of RON strings
let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]);
std::fs::write(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap();
assert_eq!(saved_system_title_bar(Some(&path)), on);
std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap();
assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on);
ui.prefs.system_title_bar = !on;
std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap();
assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first");
}
std::fs::write(&path, "not ron").unwrap();
assert!(!saved_system_title_bar(Some(&path)));
std::fs::remove_file(&path).unwrap();
assert!(!saved_system_title_bar(Some(&path)));
std::fs::write(&json_path, "not json").unwrap();
std::fs::write(&ron_path, "not ron").unwrap();
assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path)));
std::fs::remove_file(&json_path).unwrap();
std::fs::remove_file(&ron_path).unwrap();
assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path)));
}
}
+15
View File
@@ -0,0 +1,15 @@
//! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws
mod cage_shell;
mod high_poly_reach;
mod ray_frame;
mod ray_start;
mod vertex_reach;
#[cfg(test)]
pub(crate) use cage_shell::CORNERS;
pub use cage_shell::CageShell;
pub use high_poly_reach::HighPolyReach;
pub(crate) use ray_frame::RayFrame;
pub use ray_start::RayStart;
pub use vertex_reach::VertexReach;
+65
View File
@@ -0,0 +1,65 @@
use super::{RayFrame, RayStart};
use crate::{BakeError, BakeRequest, MeshExtent};
use rayon::prelude::*;
use std::collections::{HashMap, HashSet};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::surface_at;
/// Barycentric coordinates of a triangle's three corners
pub(crate) const CORNERS: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
/// The cage of one texture set as the bake sees it: where its transfer rays start at each corner of the set's triangles
#[derive(Clone, Debug, Default)]
pub struct CageShell {
/// Low-poly position of each triangle corner, three per triangle
pub positions: Vec<Vec3>,
pub starts: Vec<RayStart>,
/// Corner pairs along the low poly's polygon edges, for the wireframe
pub edges: Vec<[u32; 2]>,
/// World units per unit of the max frontal distance setting
pub cage_units: f32,
}
impl CageShell {
/// The cage of `request`'s texture set, from the same ray starts the bake uses
pub fn new(request: &BakeRequest) -> Result<CageShell, BakeError> {
let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
let (frame, mesh) = (&ray_frame, request.mesh);
let triangles: Vec<usize> = mesh.triangles_of(request.material).collect();
let (positions, starts): (Vec<Vec3>, Vec<RayStart>) = triangles
.par_iter()
.flat_map_iter(|&triangle| {
CORNERS.into_iter().map(move |barycentric| match surface_at(mesh, triangle as u32, barycentric[0], barycentric[1]) {
Some(surface) => (surface.pos, frame.start(&surface, barycentric)),
None => (Vec3::ZERO, RayStart::Distance { up: Vec3::ZERO, scale: 0.0 }),
})
})
.unzip();
let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
let mut edge_corners = HashMap::new();
for (triangle_index, &triangle) in triangles.iter().enumerate() {
let Some(vertices) = mesh.tri(triangle) else { continue };
for corner in 0..3 {
let next = (corner + 1) % 3;
let (from, to) = (vertices[corner] as u32, vertices[next] as u32);
let key = (from.min(to), from.max(to));
if wire_edges.contains(&key) {
let first_corner = (triangle_index * 3) as u32;
edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]);
}
}
}
let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect();
edges.sort_unstable();
Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units })
}
/// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling
pub fn corners(&self, max_frontal: f32) -> Vec<Vec3> {
let frontal = max_frontal * self.cage_units;
self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect()
}
}
+103
View File
@@ -0,0 +1,103 @@
use super::{RayFrame, VertexReach};
use crate::map::transfer_keys;
use crate::tracing::ANY;
use crate::{BakeError, BakeRequest, MeshExtent};
use rayon::prelude::*;
use texturecraft_core::MeshMatchMode;
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Mesh, surface_at};
/// Where each high-poly vertex sits relative to the transfer rays of one texture set, to show which parts its bake misses
#[derive(Clone, Debug, Default)]
pub struct HighPolyReach {
/// Per high-poly vertex; `None` where another texture set's low poly is nearer or the request has no high poly
pub vertices: Vec<Option<VertexReach>>,
/// World units per unit of the cage distance settings
pub cage_units: f32,
pub ignore_backface: bool,
}
impl HighPolyReach {
/// The reach of `request`'s transfer rays at the high-poly vertices whose nearest low-poly point is on this set, from the same ray starts the bake uses there
pub fn new(request: &BakeRequest) -> Result<HighPolyReach, BakeError> {
let Some(high) = request.high else { return Ok(HighPolyReach::default()) };
let frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
let mut in_set = vec![false; request.mesh.triangle_count()];
for triangle in request.mesh.triangles_of(request.material) {
if let Some(flag) = in_set.get_mut(triangle) {
*flag = true;
}
}
let winding_normals = winding_normals(high.mesh);
let (low_keys, high_vertex_keys) = match request.settings.high_poly.match_mode {
MeshMatchMode::Always => (Vec::new(), Vec::new()),
MeshMatchMode::ByMeshName => {
let (low_keys, high_keys) = transfer_keys(request);
(low_keys, vertex_keys(high.mesh, &high_keys))
}
};
let key = |keys: &[u32], index: usize| keys.get(index).copied().unwrap_or(ANY);
let frame = &frame;
let vertices = high
.mesh
.positions
.par_iter()
.zip(&winding_normals)
.enumerate()
.map(|(vertex, (&high_position, &high_facing))| {
let nearest = request.bvh.nearest(high_position, f32::INFINITY, &|_| true)?;
if !in_set.get(nearest.tri as usize).copied().unwrap_or(false) {
return None;
}
let surface = surface_at(request.mesh, nearest.tri, nearest.u, nearest.v)?;
let ray_key = key(&low_keys, nearest.tri as usize);
Some(VertexReach {
low_position: surface.pos,
start: frame.start(&surface, [nearest.u, nearest.v]),
high_position,
high_facing,
name_matches: ray_key == ANY || key(&high_vertex_keys, vertex) == ray_key,
})
})
.collect();
Ok(HighPolyReach { vertices, cage_units: frame.cage_units, ignore_backface: request.settings.high_poly.ignore_backface })
}
/// Whether the transfer rays miss high-poly vertex `vertex` at the `max_frontal` and `max_rear` settings; `None` when the vertex isn't this set's
pub fn missed(&self, vertex: usize, max_frontal: f32, max_rear: f32) -> Option<bool> {
let reach = self.vertices.get(vertex).copied().flatten()?;
Some(reach.missed(max_frontal * self.cage_units, max_rear * self.cage_units, self.ignore_backface))
}
}
/// Each vertex's mesh-name key, from the first triangle that uses it
fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec<u32> {
let mut keys = vec![ANY; mesh.positions.len()];
for (corners, &triangle_key) in mesh.indices.chunks_exact(3).zip(triangle_keys) {
for &corner in corners {
if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) {
*key = triangle_key;
}
}
}
keys
}
/// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front
fn winding_normals(mesh: &Mesh) -> Vec<Vec3> {
let mut normals = vec![Vec3::ZERO; mesh.positions.len()];
for corners in mesh.indices.chunks_exact(3) {
let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO);
let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0]));
for &corner in corners {
if let Some(normal) = normals.get_mut(corner as usize) {
*normal += winding_normal;
}
}
}
normals
}
+63
View File
@@ -0,0 +1,63 @@
use super::RayStart;
use crate::MeshExtent;
use crate::map::{interpolate, welded};
use crate::skew::PreparedSkew;
use crate::{BakeError, BakePaintMap, BakeRequest};
use texturecraft_core::CageType;
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Mesh, Surface};
/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount
pub(crate) struct RayFrame<'a> {
mesh: &'a Mesh,
ray_normals: Vec<Vec3>,
cage: Option<&'a Mesh>,
skew: Option<PreparedSkew<'a>>,
cage_paint: Option<&'a BakePaintMap>,
/// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead
ray_epsilon: f32,
/// World units per unit of the cage distance settings
pub(crate) cage_units: f32,
}
impl<'a> RayFrame<'a> {
pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result<RayFrame<'a>, BakeError> {
let settings = request.settings;
let ray_normals = match settings.cage.average_normals && request.high.is_some() {
true => {
let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal);
welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect()
}
false => Vec::new(),
};
Ok(RayFrame {
mesh: request.mesh,
ray_normals,
cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None },
skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?,
cage_paint: request.cage_paint,
ray_epsilon: extent.ray_epsilon(),
cage_units: if settings.cage.relative_to_bounding_box { extent.scale } else { 1.0 },
})
}
/// Where the transfer ray of the low-poly point `surface` at `barycentric` starts
pub(crate) fn start(&self, surface: &Surface, barycentric: [f32; 2]) -> RayStart {
let cage_offset = self
.cage
.and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric))
.map(|cage_position| surface.pos - cage_position)
.filter(|offset| offset.length() > self.ray_epsilon);
if let Some(offset) = cage_offset {
return RayStart::CageMesh(offset);
}
let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
let up = match &self.skew {
Some(skew) => skew.correct(self.mesh, surface, averaged_normal),
None => averaged_normal,
};
RayStart::Distance { up, scale: self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)) }
}
}
+20
View File
@@ -0,0 +1,20 @@
use texturecraft_geom::glam::Vec3;
/// Where the bake's transfer ray for one low-poly point starts
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RayStart {
/// On the cage mesh: the offset from the cage to the low-poly point
CageMesh(Vec3),
/// Out along `up` by the frontal distance times `scale` (the painted cage amount)
Distance { up: Vec3, scale: f32 },
}
impl RayStart {
/// The ray origin for the low-poly point `position` at `frontal` world units of max frontal distance
pub fn origin(&self, position: Vec3, frontal: f32) -> Vec3 {
match *self {
RayStart::CageMesh(offset) => position - offset,
RayStart::Distance { up, scale } => position + up * frontal * scale,
}
}
}
+28
View File
@@ -0,0 +1,28 @@
use super::RayStart;
use texturecraft_geom::glam::Vec3;
/// One high-poly vertex seen from the transfer ray through its nearest low-poly point
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VertexReach {
pub low_position: Vec3,
pub start: RayStart,
pub high_position: Vec3,
/// The side the high poly's triangles face at the vertex, by their winding (not normalized)
pub high_facing: Vec3,
/// Whether the bake lets this low-poly point's ray hit the vertex's part (always, unless matching by mesh name)
pub name_matches: bool,
}
impl VertexReach {
/// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray
pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool {
let origin = self.start.origin(self.low_position, frontal);
let (direction, front) = match self.start {
RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()),
RayStart::Distance { up, scale } => (-up, frontal * scale),
};
let along_ray = (self.high_position - origin).dot(direction);
!self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0)
}
}
+4
View File
@@ -6,13 +6,17 @@
mod bake_error;
mod bake_output;
mod bake_request;
mod cage;
mod high_poly;
mod mesh_extent;
mod progress;
pub use bake_error::BakeError;
pub use bake_output::BakeOutput;
pub use bake_request::BakeRequest;
pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach};
pub use high_poly::HighPoly;
pub(crate) use mesh_extent::MeshExtent;
pub use progress::Progress;
mod map;
+3
View File
@@ -15,10 +15,13 @@ mod source;
mod texel_grid;
mod traced;
mod transfer;
mod transfer_keys;
pub(crate) use bake_context::BakeContext;
pub(crate) use normal_curvature::curvature_from_normal;
pub(crate) use sample::Sample;
pub(crate) use sampling::{interpolate, welded};
pub(crate) use texel_grid::TexelGrid;
pub(crate) use traced::Traced;
pub(crate) use transfer::Transfer;
pub(crate) use transfer_keys::transfer_keys;
+21 -65
View File
@@ -1,28 +1,22 @@
use super::curvature::Curvature;
use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded};
use super::sampling::{pack, splitmix64, tangent_normal};
use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer};
use crate::skew::PreparedSkew;
use crate::cage::{RayFrame, RayStart};
use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh};
use crate::{BakeError, BakeRequest};
use crate::{BakeError, BakeRequest, MeshExtent};
use rayon::prelude::*;
use std::collections::HashMap;
use texturecraft_core::{
AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion,
AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion,
};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Hit, Mesh, Surface, surface_at};
use texturecraft_geom::{Hit, Surface, surface_at};
const CURVATURE_CHUNK: usize = 1 << 15;
pub(crate) struct BakeContext<'a> {
low: Source<'a>,
high: Option<Source<'a>>,
cage: Option<&'a Mesh>,
skew: Option<PreparedSkew<'a>>,
cage_paint: Option<&'a crate::BakePaintMap>,
ray_normals: Vec<Vec3>,
ray_frame: RayFrame<'a>,
settings: &'a BakeSettings,
eps: f32,
frontal: f32,
rear: f32,
position: PositionProjection,
@@ -36,36 +30,10 @@ pub(crate) struct BakeContext<'a> {
impl<'a> BakeContext<'a> {
pub(crate) fn new(request: &BakeRequest<'a>) -> Result<BakeContext<'a>, BakeError> {
let settings = request.settings;
let (bounds_min, bounds_max) = request.mesh.bounds();
let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6);
if !mesh_diagonal.is_finite() {
return Err(BakeError::Invalid("mesh bounds are too large".into()));
}
let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6);
let mut name_keys = HashMap::new();
let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys);
let high = request.high.map(|high_mesh| {
Source::new(
high_mesh.mesh,
high_mesh.bvh,
high_mesh.base_color,
high_mesh.file_ids,
&settings.high_poly.high_suffix,
&settings.high_poly,
&mut name_keys,
)
});
let ray_normals = match settings.cage.average_normals && high.is_some() {
true => {
let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal);
welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect()
}
false => Vec::new(),
};
let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?;
let ray_epsilon = 1e-6 * mesh_diagonal;
let extent = MeshExtent::of(request.mesh)?;
let (low, high) = Source::of_request(request);
let ray_frame = RayFrame::new(request, extent)?;
let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon());
let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| {
let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians();
let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 };
@@ -91,27 +59,26 @@ impl<'a> BakeContext<'a> {
pass.ignore_backface = parameters.ignore_backface;
pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName;
pass.attenuation = parameters.attenuation;
pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset);
pass.ground_height = parameters.ground_plane.enabled.then_some(extent.bounds_min.y - parameters.ground_plane.offset);
}
let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion);
if let Some(pass) = &mut bent {
pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface;
pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName;
}
let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness);
if let Some(pass) = &mut thickness {
pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName;
}
let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 };
let cage_units = ray_frame.cage_units;
Ok(BakeContext {
low,
high,
cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None },
skew,
cage_paint: request.cage_paint,
ray_normals,
ray_frame,
settings,
eps: ray_epsilon,
frontal: settings.cage.max_frontal * cage_units,
rear: settings.cage.max_rear * cage_units,
position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters),
@@ -140,22 +107,11 @@ impl<'a> BakeContext<'a> {
}
pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) {
let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
let cage = self
.cage
.and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric))
.map(|cage_position| surface.pos - cage_position)
.filter(|offset| offset.length() > self.eps);
let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv));
let (origin, direction, front) = match cage {
Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()),
None => {
let up = match &self.skew {
Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal),
None => averaged_normal,
};
(surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale)
}
let start = self.ray_frame.start(surface, barycentric);
let origin = start.origin(surface.pos, self.frontal);
let (direction, front) = match start {
RayStart::CageMesh(offset) => (offset.normalize(), offset.length()),
RayStart::Distance { up, scale } => (-up, self.frontal * scale),
};
let key = match self.settings.high_poly.match_mode {
MeshMatchMode::Always => ANY,
+28 -19
View File
@@ -3,34 +3,43 @@ use std::ops::{Add, Mul};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Mesh, Surface};
pub(super) fn interpolate<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option<T> {
let [a, b, c] = mesh.tri(tri as usize)?;
Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2)
/// `values` (one per vertex) at `barycentric` in triangle `triangle`
pub(crate) fn interpolate<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option<T> {
let [first, second, third] = mesh.tri(triangle as usize)?;
let [second_weight, third_weight] = barycentric;
Some(*values.get(first)? * (1.0 - second_weight - third_weight) + *values.get(second)? * second_weight + *values.get(third)? * third_weight)
}
pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec<u32>, Vec<Vec3>, Vec<Vec3>) {
let q = diag * 1e-5;
let mut ids: HashMap<[i64; 3], u32> = HashMap::new();
let (mut pos, mut nrm) = (Vec::new(), Vec::<Vec3>::new());
let weld: Vec<u32> = mesh
/// Vertices closer than this fraction of the mesh diagonal count as one when welding
const WELD_TOLERANCE_PER_DIAGONAL: f32 = 1e-5;
/// Vertices that share a position merged: each vertex's welded index, the welded positions and their averaged normals
pub(crate) fn welded(mesh: &Mesh, diagonal: f32) -> (Vec<u32>, Vec<Vec3>, Vec<Vec3>) {
let tolerance = diagonal * WELD_TOLERANCE_PER_DIAGONAL;
let mut welded_index_of_cell: HashMap<[i64; 3], u32> = HashMap::new();
let (mut positions, mut normal_sums) = (Vec::new(), Vec::<Vec3>::new());
let welded_indices: Vec<u32> = mesh
.positions
.iter()
.zip(&mesh.normals)
.map(|(p, n)| {
let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64);
let id = *ids.entry(key).or_insert_with(|| {
pos.push(*p);
nrm.push(Vec3::ZERO);
(pos.len() - 1) as u32
.map(|(position, normal)| {
let cell = [position.x, position.y, position.z].map(|coordinate| (coordinate / tolerance).round() as i64);
let welded_index = *welded_index_of_cell.entry(cell).or_insert_with(|| {
positions.push(*position);
normal_sums.push(Vec3::ZERO);
(positions.len() - 1) as u32
});
if let Some(acc) = nrm.get_mut(id as usize) {
*acc += *n;
if let Some(normal_sum) = normal_sums.get_mut(welded_index as usize) {
*normal_sum += *normal;
}
id
welded_index
})
.collect();
let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect();
(weld, pos, nrm)
let normals = normal_sums.into_iter().map(|normal_sum| normal_sum.try_normalize().unwrap_or(Vec3::ZERO)).collect();
(welded_indices, positions, normals)
}
pub(super) fn splitmix64(x: u64) -> u64 {
+13
View File
@@ -1,4 +1,5 @@
use super::sampling::{generated_hue, interpolate, splitmix64};
use crate::BakeRequest;
use crate::tracing::{ANY, TraceMesh};
use std::collections::HashMap;
use std::sync::Arc;
@@ -21,6 +22,18 @@ pub(super) struct Source<'a> {
}
impl<'a> Source<'a> {
/// `request`'s low and high poly, their mesh names keyed from one shared table so the bake can match a low-poly part to its high-poly part
pub(super) fn of_request(request: &BakeRequest<'a>) -> (Source<'a>, Option<Source<'a>>) {
let settings = &request.settings.high_poly;
let mut name_keys = HashMap::new();
let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.low_suffix, settings, &mut name_keys);
let high = request.high.map(|high_mesh| {
Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, high_mesh.file_ids, &settings.high_suffix, settings, &mut name_keys)
});
(low, high)
}
pub(super) fn new(
mesh: &'a Mesh,
bvh: &'a Bvh,
+8
View File
@@ -0,0 +1,8 @@
use super::source::Source;
use crate::BakeRequest;
/// The bake's mesh-name key of each low-poly and each high-poly triangle: with By Mesh Name a transfer ray from a low-poly triangle only hits high-poly triangles with its key
pub(crate) fn transfer_keys(request: &BakeRequest) -> (Vec<u32>, Vec<u32>) {
let (low, high) = Source::of_request(request);
(low.key, high.map(|high| high.key).unwrap_or_default())
}
+35
View File
@@ -0,0 +1,35 @@
use crate::BakeError;
use texturecraft_geom::Mesh;
use texturecraft_geom::glam::Vec3;
/// Smallest size a mesh is treated as having, so a flat or empty mesh still gives finite distances
const MIN_MESH_SIZE: f32 = 1e-6;
/// How far a ray starts past the surface it leaves, as a fraction of the mesh diagonal
const RAY_EPSILON_PER_DIAGONAL: f32 = 1e-6;
/// The low-poly mesh's size, which scales the bake's relative distances
#[derive(Clone, Copy, Debug)]
pub(crate) struct MeshExtent {
pub(crate) bounds_min: Vec3,
pub(crate) diagonal: f32,
/// The bounding box's largest side
pub(crate) scale: f32,
}
impl MeshExtent {
pub(crate) fn of(mesh: &Mesh) -> Result<MeshExtent, BakeError> {
let (bounds_min, bounds_max) = mesh.bounds();
let diagonal = (bounds_max - bounds_min).length().max(MIN_MESH_SIZE);
if !diagonal.is_finite() {
return Err(BakeError::Invalid("mesh bounds are too large".into()));
}
Ok(MeshExtent { bounds_min, diagonal, scale: (bounds_max - bounds_min).max_element().max(MIN_MESH_SIZE) })
}
/// How far a ray starts past the surface it leaves, in world units
pub(crate) fn ray_epsilon(&self) -> f32 {
RAY_EPSILON_PER_DIAGONAL * self.diagonal
}
}
+103
View File
@@ -0,0 +1,103 @@
use super::settings;
use crate::cage::CORNERS;
use crate::map::BakeContext;
use crate::{BakePaintMap, BakeRequest, CageShell, HighPoly};
use texturecraft_core::{BakedMap, CageType};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{Bvh, Mesh, primitives, surface_at};
/// A painted map whose values vary over the UV square
fn painted_map() -> BakePaintMap {
let mut map = BakePaintMap::constant(0.25).resized(32, 32).unwrap();
map.paint(&[Vec2::new(0.2, 0.3), Vec2::new(0.7, 0.6)], 0.3, 1.0, 0.5, 1.0).unwrap();
map
}
/// Every corner of `request`'s cage equals the origin of the bake's transfer ray at that corner, bit for bit
fn assert_cage_matches_the_ray_origins(request: &BakeRequest) {
let shell = CageShell::new(request).unwrap();
let corners = shell.corners(request.settings.cage.max_frontal);
let context = BakeContext::new(request).unwrap();
let triangles: Vec<usize> = request.mesh.triangles_of(request.material).collect();
assert_eq!(corners.len(), triangles.len() * 3);
for (corner_index, corner) in corners.iter().enumerate() {
let barycentric = CORNERS[corner_index % 3];
let surface = surface_at(request.mesh, triangles[corner_index / 3] as u32, barycentric[0], barycentric[1]).unwrap();
let (ray, _) = context.transfer_ray(&surface, barycentric);
assert_eq!(*corner, ray.origin, "corner {corner_index}");
}
}
#[test]
fn the_cage_corners_are_the_bake_ray_origins() {
let low = primitives::cube(1.0);
let high_mesh = primitives::sphere(0.8, 16, 8);
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] };
let (skew, cage_paint) = (painted_map(), painted_map());
let mut bake_settings = settings(16, &[BakedMap::Normal]);
bake_settings.cage.max_frontal = 0.03;
bake_settings.skew.edge_protection = true;
let request = |settings| BakeRequest {
low_base_color: &[],
mesh: &low,
bvh: &low_bvh,
material: 0,
settings,
high: Some(high),
cage: None,
skew: Some(&skew),
cage_paint: Some(&cage_paint),
tiles: (1, 1),
};
assert_cage_matches_the_ray_origins(&request(&bake_settings));
let face_normals = {
let mut face_normals = bake_settings.clone();
face_normals.cage.average_normals = false;
face_normals.cage.relative_to_bounding_box = false;
face_normals
};
assert_cage_matches_the_ray_origins(&request(&face_normals));
}
#[test]
fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() {
let low = primitives::cube(1.0);
let low_bvh = Bvh::new(&low);
let high = HighPoly { file_ids: &[], mesh: &low, bvh: &low_bvh, base_color: &[] };
let mut bake_settings = settings(16, &[BakedMap::Normal]);
bake_settings.cage.relative_to_bounding_box = false;
let request = BakeRequest {
low_base_color: &[],
mesh: &low,
bvh: &low_bvh,
material: 0,
settings: &bake_settings,
high: Some(high),
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
let shell = CageShell::new(&request).unwrap();
let distance_from_the_cube = |max_frontal: f32| shell.corners(max_frontal).iter().map(|corner| corner.abs().max_element() - 0.5).fold(0.0, f32::max);
assert!(distance_from_the_cube(0.0).abs() < 1e-6, "at frontal 0 the cage is the low poly");
// Averaged normals point diagonally at the corners, so a corner moves out by at least half the distance along each axis
assert!(distance_from_the_cube(0.2) > 0.1 && distance_from_the_cube(0.2) <= 0.2 + 1e-6, "the cage grows with the frontal distance");
assert_eq!(shell.edges.len(), low.wire_edges()[0].len(), "one wireframe line per polygon edge");
let cage_mesh = Mesh { positions: low.positions.iter().map(|position| *position * 1.5).collect(), ..low.clone() };
let custom_settings = {
let mut custom_settings = bake_settings.clone();
custom_settings.cage.kind = CageType::CustomFile;
custom_settings
};
let custom = BakeRequest { settings: &custom_settings, cage: Some(&cage_mesh), ..request };
assert_cage_matches_the_ray_origins(&custom);
let corners = CageShell::new(&custom).unwrap().corners(0.0);
assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is");
assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO));
}
+222
View File
@@ -0,0 +1,222 @@
use super::settings;
use crate::map::{BakeContext, transfer_keys};
use crate::tracing::ANY;
use crate::{BakeRequest, HighPoly, HighPolyReach, RayStart};
use texturecraft_core::{BakedMap, MeshMatchMode};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Bvh, Mesh, primitives, surface_at};
/// Ray distances closer than this to the end of the ray's range are left out: rounding decides them
const BOUNDARY: f32 = 1e-4;
/// How close the ray's hit must be to the vertex to count as reaching it
const HIT_TOLERANCE: f32 = 1e-4;
/// A bumpy plane over the flat low poly, with the triangles right of `FLIPPED_FROM_X` wound the other way
fn bumpy_high_poly() -> (Mesh, Vec<bool>) {
const FLIPPED_FROM_X: f32 = 0.2;
let mut mesh = primitives::plane(1.0, 40);
for position in &mut mesh.positions {
position.y = 0.04 * (position.x * 9.0).sin() * (position.z * 7.0).cos() + 0.005;
}
let mut flipped = vec![false; mesh.positions.len()];
let mut unflipped = vec![false; mesh.positions.len()];
for corners in mesh.indices.chunks_exact_mut(3) {
let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::<f32>() / 3.0;
if center_x > FLIPPED_FROM_X {
corners.swap(1, 2);
}
for &corner in corners.iter() {
if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true }
}
}
// Vertices on the border face both ways: neither answer is right for them
let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect();
(mesh, mixed)
}
#[test]
fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() {
let low = primitives::plane(1.0, 8);
let (high_mesh, mixed) = bumpy_high_poly();
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] };
let back_facing = |triangle: u32, direction: Vec3| {
let [a, b, c] = high_mesh.tri(triangle as usize).unwrap().map(|corner| high_mesh.positions[corner]);
(b - a).cross(c - a).dot(direction) > 0.0
};
let mut checked = [0usize; 2];
for ignore_backface in [false, true] {
for (max_frontal, max_rear) in [(0.0, 0.01), (0.02, 0.0), (0.02, 0.01), (0.05, 0.05)] {
let mut bake_settings = settings(16, &[BakedMap::Normal]);
bake_settings.cage.relative_to_bounding_box = false;
bake_settings.high_poly.ignore_backface = ignore_backface;
(bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (max_frontal, max_rear);
let request = BakeRequest {
low_base_color: &[],
mesh: &low,
bvh: &low_bvh,
material: 0,
settings: &bake_settings,
high: Some(high),
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
let reach = HighPolyReach::new(&request).unwrap();
let context = BakeContext::new(&request).unwrap();
for (vertex, vertex_reach) in reach.vertices.iter().enumerate() {
let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap());
let RayStart::Distance { scale, .. } = vertex_reach.start else { panic!("a distance-based cage") };
let height = vertex_reach.high_position.y - vertex_reach.low_position.y;
let near_the_range_end = [max_frontal * scale, -max_rear].iter().any(|end| (height - end).abs() < BOUNDARY);
if near_the_range_end || mixed[vertex] {
continue;
}
let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap();
let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap();
let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]);
let hit = high_bvh
.closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| !(ignore_backface && back_facing(triangle, ray.direction)));
let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE);
assert_eq!(
missed, !reaches_the_vertex,
"vertex {vertex}, ignore backface {ignore_backface}, frontal {max_frontal}, rear {max_rear}: height {height}"
);
checked[usize::from(missed)] += 1;
}
}
}
assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}");
}
#[test]
fn a_vertex_belongs_to_the_texture_set_whose_low_poly_is_nearest() {
let mut low = primitives::plane(1.0, 4);
let mut right = primitives::plane(1.0, 4);
for position in &mut right.positions {
position.x += 2.0;
}
low.append(&right);
assert_eq!(low.materials.len(), 2, "each plane is its own texture set");
let mut high_mesh = primitives::plane(3.0, 30);
for position in &mut high_mesh.positions {
position.x += 1.0;
position.y = 0.3;
}
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
let bake_settings = settings(16, &[BakedMap::Normal]);
let request = |material| BakeRequest {
low_base_color: &[],
mesh: &low,
bvh: &low_bvh,
material,
settings: &bake_settings,
high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }),
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
let (left, right) = (HighPolyReach::new(&request(0)).unwrap(), HighPolyReach::new(&request(1)).unwrap());
for (vertex, position) in high_mesh.positions.iter().enumerate() {
let owners = (left.vertices[vertex].is_some(), right.vertices[vertex].is_some());
assert!(owners != (true, true), "vertex {vertex} belongs to one set at most");
if position.x < 0.9 {
assert_eq!(owners, (true, false), "vertex {vertex} at {position} is over the left set");
} else if position.x > 1.1 {
assert_eq!(owners, (false, true), "vertex {vertex} at {position} is over the right set");
}
}
}
#[test]
fn matching_by_mesh_name_misses_the_parts_with_another_name() {
const HEIGHT_INSIDE_THE_CAGE: f32 = 0.01;
let mut low = primitives::plane(1.0, 8);
low.submeshes[0].name = "part_low".into();
let mut high_mesh = primitives::plane(0.5, 10);
let mut other_part = primitives::plane(0.5, 10);
for (mesh, center_x) in [(&mut high_mesh, -0.25), (&mut other_part, 0.25)] {
for position in &mut mesh.positions {
position.x += center_x;
position.y = HEIGHT_INSIDE_THE_CAGE;
}
}
high_mesh.append(&other_part);
high_mesh.submeshes[0].name = "part_high".into();
high_mesh.submeshes[1].name = "other_high".into();
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
let mut bake_settings = settings(16, &[BakedMap::Normal]);
bake_settings.cage.relative_to_bounding_box = false;
bake_settings.cage.max_frontal = 0.02;
bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName;
let request = BakeRequest {
low_base_color: &[],
mesh: &low,
bvh: &low_bvh,
material: 0,
settings: &bake_settings,
high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }),
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
let reach = HighPolyReach::new(&request).unwrap();
let context = BakeContext::new(&request).unwrap();
let (_, high_keys) = transfer_keys(&request);
for (vertex, vertex_reach) in reach.vertices.iter().enumerate() {
let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap());
// On the line where the two parts meet, a ray reaches either part's triangles
if vertex_reach.high_position.x.abs() < BOUNDARY {
continue;
}
let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap();
let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap();
let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]);
let same_name = |triangle: u32| ray.key == ANY || high_keys.get(triangle as usize) == Some(&ray.key);
let hit = high_bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &same_name);
let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE);
assert_eq!(missed, !reaches_the_vertex, "vertex {vertex} at {}", vertex_reach.high_position);
assert_eq!(
missed,
vertex >= high_mesh.positions.len() - other_part.positions.len(),
"only the part named like the low poly is reached: vertex {vertex}"
);
}
}
#[test]
fn without_a_high_poly_no_vertex_has_a_reach() {
let low = primitives::plane(1.0, 4);
let low_bvh = Bvh::new(&low);
let bake_settings = settings(16, &[BakedMap::Normal]);
let request = BakeRequest {
low_base_color: &[],
mesh: &low,
bvh: &low_bvh,
material: 0,
settings: &bake_settings,
high: None,
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
let reach = HighPolyReach::new(&request).unwrap();
assert!(reach.vertices.is_empty());
// Any cage distances: there is no vertex to miss
assert_eq!(reach.missed(0, 0.02, 0.01), None);
}
+51
View File
@@ -0,0 +1,51 @@
use crate::{RayStart, VertexReach};
use texturecraft_geom::glam::Vec3;
/// Cage distances in world units; every case's ray runs down the Y axis from 0.5 to -0.25
const FRONTAL: f32 = 0.5;
const REAR: f32 = 0.25;
/// A frontal distance a cage-mesh start must ignore: its ray starts on the cage
const IGNORED_FRONTAL: f32 = 9.0;
/// How far past an end of the ray's range a vertex counts as outside it
const PAST_THE_END: f32 = 1e-3;
/// A vertex at `height` above the low-poly point at the origin, its triangles facing `facing`
fn vertex(start: RayStart, height: f32, facing: Vec3, name_matches: bool) -> VertexReach {
VertexReach { low_position: Vec3::ZERO, start, high_position: Vec3::new(0.0, height, 0.0), high_facing: facing, name_matches }
}
#[test]
fn a_vertex_is_missed_outside_the_ray_range_on_another_part_or_facing_away() {
// A painted cage amount of 2 doubles the frontal distance
let starts = [
(RayStart::Distance { up: Vec3::Y, scale: 1.0 }, FRONTAL),
(RayStart::Distance { up: Vec3::Y, scale: 2.0 }, FRONTAL / 2.0),
(RayStart::CageMesh(Vec3::new(0.0, -FRONTAL, 0.0)), IGNORED_FRONTAL),
];
let (top, bottom) = (FRONTAL, -REAR);
// Height, facing, name matches, ignore backface: missed
let cases = [
(top, Vec3::Y, true, false, false),
(bottom, Vec3::Y, true, false, false),
(0.0, Vec3::Y, true, false, false),
(top + PAST_THE_END, Vec3::Y, true, false, true),
(bottom - PAST_THE_END, Vec3::Y, true, false, true),
(0.0, Vec3::Y, false, false, true),
(0.0, Vec3::NEG_Y, true, false, false),
(0.0, Vec3::NEG_Y, true, true, true),
(0.0, Vec3::Y, true, true, false),
];
for (start, frontal) in starts {
for (height, facing, name_matches, ignore_backface, missed) in cases {
let reach = vertex(start, height, facing, name_matches);
assert_eq!(
reach.missed(frontal, REAR, ignore_backface),
missed,
"{start:?} at height {height}, facing {facing}, name matches {name_matches}, ignore backface {ignore_backface}"
);
}
}
}
+9
View File
@@ -14,6 +14,12 @@ use texturecraft_geom::primitives;
use super::*;
#[path = "test/cage_shell.rs"]
mod cage_shell;
#[path = "test/high_poly_reach.rs"]
mod high_poly_reach;
#[path = "test/setting.rs"]
mod setting;
@@ -23,6 +29,9 @@ mod normal_map_curvature;
#[path = "test/tile_selection.rs"]
mod tile_selection;
#[path = "test/vertex_reach.rs"]
mod vertex_reach;
fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings {
with_rays(
{
@@ -0,0 +1,50 @@
/// Deviations of ±0.5 (curvature − 0.5) stored as 16-bit integers.
pub const DEVIATION_SCALE: f32 = i16::MAX as f32 * 2.0;
/// Curvature blurred at one detail size: deviations from flat, stored `step` times coarser than the map.
pub struct CurvatureSizeLevel {
pub step: u32,
pub width: u32,
pub height: u32,
/// UV tile dimensions in stored texels; interpolation must stay inside one tile
pub block: (u32, u32),
pub deviation: Vec<i16>,
}
impl CurvatureSizeLevel {
/// The deviation at map texel `(x, y)`, interpolated within its UV tile
pub fn sample(&self, x: u32, y: u32) -> f32 {
if self.width == 0 || self.height == 0 {
return 0.0;
}
let step = self.step.max(1);
let axis = |texel: u32, block: u32, length: u32| {
let block = block.max(1);
let first = if block >= length { 0 } else { (texel / block.saturating_mul(step) * block).min(length - 1) };
let last = first.saturating_add(block - 1).min(length - 1);
let position = ((texel as f32 + 0.5) / step as f32 - 0.5).clamp(first as f32, last as f32);
let lower = position.floor() as u32;
(lower, (lower + 1).min(last), position - lower as f32)
};
let (x0, x1, blend_x) = axis(x, self.block.0, self.width);
let (y0, y1, blend_y) = axis(y, self.block.1, self.height);
let stored = |x: u32, y: u32| self.deviation.get((y * self.width + x) as usize).map_or(0.0, |value| f32::from(*value) / DEVIATION_SCALE);
let top = stored(x0, y0) + (stored(x1, y0) - stored(x0, y0)) * blend_x;
let bottom = stored(x0, y1) + (stored(x1, y1) - stored(x0, y1)) * blend_x;
top + (bottom - top) * blend_y
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn samples_blend_the_stored_texels() {
let level = CurvatureSizeLevel { step: 2, width: 2, height: 1, block: (2, 1), deviation: vec![0, (0.25 * DEVIATION_SCALE) as i16] };
assert!(level.sample(0, 0).abs() < 1e-4, "the first stored texel covers map texels 0 and 1");
assert!((level.sample(3, 0) - 0.25).abs() < 1e-3);
assert!(level.sample(2, 0) > 0.0 && level.sample(2, 0) < 0.25, "between stored texels the value blends");
}
}
+447
View File
@@ -0,0 +1,447 @@
//! The baked curvature map at the detail sizes of curvature generators, built once per map and layout.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};
use rayon::prelude::*;
use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail};
use texturecraft_texel::dilate::{DilationMap, NONE};
use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE};
use crate::eval::{BLUR_BOX_PASSES, Inputs, blur};
/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first.
pub struct CurvatureSizes {
/// One per blurred size, built once a generator gives that size a weight above 0.
pub levels: Vec<Option<Arc<CurvatureSizeLevel>>>,
}
/// The bake map size, its UV tile block and the working texture size a cache entry was built for.
type CacheKey = ((u32, u32), (u32, u32), (u32, u32));
/// Built sizes by the curvature data they come from, their layout and the tiles' scales.
type CacheEntry = (Weak<Vec<f32>>, CacheKey, BlockScales, Arc<CurvatureSizes>);
static CACHE: Mutex<Vec<CacheEntry>> = Mutex::new(Vec::new());
// Undo snapshots keep old maps alive; their derived levels must not grow with the history
const CACHE_BYTES: usize = 256 << 20;
const CACHE_MAPS: usize = 16;
impl CurvatureSizes {
/// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size.
pub fn of(inp: &Inputs, needed: &[bool]) -> Option<Arc<CurvatureSizes>> {
let curvature = inp.baked.maps.get(&BakedMap::Curvature)?;
let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature));
if !needed.contains(&true) || width == 0 || height == 0 {
return None;
}
let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid());
let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1)));
let key = ((width, height), block, (inp.gbuf.width, inp.gbuf.height));
let built = cached(curvature, key, &inp.block_scales);
if let Some(sizes) = built.as_ref().filter(|sizes| sizes.holds(needed)) {
return Some(sizes.clone());
}
// Built without the cache locked: the build runs parallel work, and a thread waiting on it may composite a tile that asks the cache again
let covered = covered_texels(inp, (width, height));
let sizes = CurvatureSizes::build(curvature, (width, height), &covered, block, needed, built.as_deref());
Some(store(curvature, key, &inp.block_scales, sizes))
}
/// Whether every size `needed` marks is built.
fn holds(&self, needed: &[bool]) -> bool {
needed.iter().zip(&self.levels).all(|(needs, level)| !needs || level.is_some())
}
/// Pad and blur each UV tile at the requested sizes, reusing levels already in `built`
fn build(
curvature: &[f32],
(width, height): (u32, u32),
covered: &[bool],
block: (u32, u32),
needed: &[bool],
built: Option<&CurvatureSizes>,
) -> CurvatureSizes {
let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block);
let deviation: Vec<f32> =
padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect();
let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height));
let levels = CurvatureDetail::SIZES
.iter()
.skip(1)
.enumerate()
.map(|(level, size)| {
if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) {
return Some(existing);
}
if !needed.get(level).copied().unwrap_or(false) {
return None;
}
// Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser
let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32;
let mut step = (radius / 2).max(1).next_power_of_two();
// A coarse cell must not average curvature from different UV tiles
while !block_width.is_multiple_of(step) || !block_height.is_multiple_of(step) {
step /= 2;
}
let mut blurred = deviation.clone();
for block_y in (0..height).step_by(block_height as usize) {
for block_x in (0..width).step_by(block_width as usize) {
let region = (block_x, block_y, block_width.min(width - block_x), block_height.min(height - block_y));
blur_block(&mut blurred, width, region, radius);
}
}
Some(Arc::new(coarsen(&blurred, (width, height), step, (block_width, block_height))))
})
.collect();
CurvatureSizes { levels }
}
}
/// The cached sizes of `curvature` for layout `key` and tile `scales`, if any
fn cached(curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales) -> Option<Arc<CurvatureSizes>> {
let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
cache.retain(|(source, ..)| source.strong_count() > 0);
let index = cache.iter().position(|entry| is_entry_for(entry, curvature, key, scales))?;
let entry = cache.remove(index);
let sizes = entry.3.clone();
cache.push(entry);
Some(sizes)
}
/// Cache `sizes`, merging any levels another thread stored meanwhile
fn store(curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc<CurvatureSizes> {
let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let sizes = if let Some((.., cached_sizes)) = cache.iter().find(|entry| is_entry_for(entry, curvature, key, scales)) {
let levels = cached_sizes.levels.iter().zip(sizes.levels).map(|(cached, built)| cached.clone().or(built)).collect();
CurvatureSizes { levels }
} else {
sizes
};
// One layout per curvature map, with the most recently used map at the end
cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature)));
let sizes = Arc::new(sizes);
cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone()));
trim_cache(&mut cache, CACHE_BYTES);
sizes
}
/// Evict the least recently used maps, retaining the newest even if it alone exceeds the budget
fn trim_cache(cache: &mut Vec<CacheEntry>, budget: usize) {
// Keeping the newest prevents a large atlas from rebuilding its levels for every tile
let mut bytes = 0usize;
let mut keep = 0;
for (.., sizes) in cache.iter().rev() {
let size = sizes.levels.iter().flatten().map(|level| level.deviation.len().saturating_mul(size_of::<i16>())).fold(0usize, usize::saturating_add);
bytes = bytes.saturating_add(size);
if keep > 0 && (bytes > budget || keep == CACHE_MAPS) {
break;
}
keep += 1;
}
cache.drain(..cache.len() - keep);
}
/// Whether cache `entry` holds the sizes of `curvature` for layout `key` and tile `scales`.
fn is_entry_for((source, cached_key, cached_scales, _): &CacheEntry, curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales) -> bool {
source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)) && *cached_key == key && cached_scales == scales
}
/// The bake atlas texels (`width × height`) overlapped by covered working texels of `inp`
fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec<bool> {
let working_size = (inp.gbuf.width, inp.gbuf.height);
if working_size == (width, height) && inp.block_scales == BlockScales::default() {
return (0..width * height).into_par_iter().map(|texel| inp.gbuf.covered(texel as usize)).collect();
}
let covered: Vec<AtomicBool> = (0..width * height).map(|_| AtomicBool::new(false)).collect();
(0..working_size.0 * working_size.1).into_par_iter().filter(|texel| inp.gbuf.covered(*texel as usize)).for_each(|texel| {
let (x, y) = (texel % working_size.0, texel / working_size.0);
let uv = [(x as f32 + 0.5) / working_size.0 as f32, (y as f32 + 0.5) / working_size.1 as f32];
if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) {
// A lower-resolution working texel covers a whole rectangle in the bake, not just its center
let scale = inp.block_scales.at(x, y);
let footprint = |center: f32, baked: u32, working: u32| {
let half_width = 0.5 * baked as f32 / (working as f32 * scale);
let center = center * baked as f32;
((center - half_width).floor().max(0.0) as u32)..((center + half_width).ceil() as u32).min(baked)
};
let columns = footprint(baked_uv[0], width, working_size.0);
for baked_y in footprint(baked_uv[1], height, working_size.1) {
for baked_x in columns.clone() {
if let Some(slot) = covered.get((baked_y * width + baked_x) as usize) {
slot.store(true, Ordering::Relaxed);
}
}
}
}
});
covered.into_iter().map(AtomicBool::into_inner).collect()
}
/// Blur the `(left, top, region_width, region_height)` block of `data` (`width` texels per row) in place, reading nothing outside it.
fn blur_block(data: &mut [f32], width: u32, (left, top, region_width, region_height): (u32, u32, u32, u32), radius: u32) {
let rows = top..top + region_height;
let mut block: Vec<f32> =
rows.flat_map(|y| (left..left + region_width).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect();
blur(&mut block, region_width as usize, region_height as usize, radius as usize);
// The blur reads zero past the block's edges; dividing by the share of its window inside the block keeps the edges at full strength
let column_weights = window_inside(region_width as usize, radius as usize);
let row_weights = window_inside(region_height as usize, radius as usize);
for (values, row_weight) in block.chunks_mut(region_width as usize).zip(&row_weights) {
for (value, column_weight) in values.iter_mut().zip(&column_weights) {
*value /= row_weight * column_weight;
}
}
for (row, values) in block.chunks(region_width as usize).enumerate() {
let start = ((top + row as u32) * width + left) as usize;
if let Some(target) = data.get_mut(start..start + values.len()) {
target.copy_from_slice(values);
}
}
}
/// The share of the [`blur`] window at each texel of a line `length` long that falls inside it: 1 from three radii in.
fn window_inside(length: usize, radius: usize) -> Vec<f32> {
let window = (2 * radius + 1) as f64;
let mut weights = vec![1.0f64; length];
for _ in 0..BLUR_BOX_PASSES {
let running_totals: Vec<f64> = std::iter::once(0.0)
.chain(weights.iter().scan(0.0, |total, weight| {
*total += weight;
Some(*total)
}))
.collect();
let total_at = |end: usize| running_totals.get(end.min(length)).copied().unwrap_or(0.0);
weights = (0..length).map(|texel| (total_at(texel + radius + 1) - total_at(texel.saturating_sub(radius))) / window).collect();
}
weights.into_iter().map(|weight| weight as f32).collect()
}
/// `data` averaged over `step × step` squares, clipping the last cells to the map
fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u32)) -> CurvatureSizeLevel {
let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step));
let deviation = (0..coarse_width * coarse_height)
.into_par_iter()
.map(|cell| {
let (cell_x, cell_y) = (cell % coarse_width, cell / coarse_width);
let columns = cell_x * step..((cell_x + 1) * step).min(width);
let rows = cell_y * step..((cell_y + 1) * step).min(height);
let count = (columns.len() * rows.len()).max(1) as f32;
let texels = rows.flat_map(|y| columns.clone().map(move |x| (y * width + x) as usize));
let mean = texels.map(|index| data.get(index).copied().unwrap_or(0.0)).sum::<f32>() / count;
(mean * DEVIATION_SCALE).round().clamp(i16::MIN as f32, i16::MAX as f32) as i16
})
.collect();
CurvatureSizeLevel { step, width: coarse_width, height: coarse_height, block: (block.0.div_ceil(step), block.1.div_ceil(step)), deviation }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn coarse_sizes_do_not_blend_between_uv_tiles() {
let (width, height) = (512, 512);
let block = (256, 256);
let curvature: Vec<f32> = (0..width * height).map(|texel| if (texel % width) / block.0 == (texel / width) / block.1 { 0.8 } else { 0.2 }).collect();
let covered = vec![true; curvature.len()];
let sizes = CurvatureSizes::build(&curvature, (width, height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None);
for level in sizes.levels.iter().flatten() {
for (x, y) in [(255, 128), (256, 128), (128, 255), (128, 256), (255, 255), (256, 256)] {
let expected = curvature[(y * width + x) as usize] - 0.5;
assert!((level.sample(x, y) - expected).abs() < 0.001, "step {} at ({x}, {y}): {} instead of {expected}", level.step, level.sample(x, y));
}
}
}
#[test]
fn coverage_preserves_bake_texels_above_the_working_resolution() {
use texturecraft_core::{Project, TextureSet};
use texturecraft_geom::{UvGBuffer, primitives};
let mesh = primitives::plane(2.0, 1);
let mut project = Project::new("Coverage", "builtin:plane");
project.texture_sets.push(TextureSet::new("Plane", 0, 64));
let gbuf = UvGBuffer::new(&mesh, 0, 64, 64);
let pixels = Default::default();
let images = Default::default();
let baked = Default::default();
let inputs = Inputs {
project: &project,
ts: 0,
mesh: &mesh,
gbuf: &gbuf,
pixels: &pixels,
baked: &baked,
block_scales: BlockScales::default(),
preview: None,
images: &images,
bounds: mesh.bounds(),
};
for size in [(32, 32), (64, 64), (128, 128), (128, 32)] {
let coverage = covered_texels(&inputs, size);
assert!(coverage.iter().all(|covered| *covered), "the plane covers the entire {size:?} bake, including between working texel centers");
}
}
#[test]
fn coverage_expands_scaled_tiles_without_crossing_block_borders() {
use texturecraft_core::{Project, TextureSet};
use texturecraft_geom::{NO_TRI, UvGBuffer, primitives};
let mesh = primitives::plane(2.0, 1);
let mut project = Project::new("Tile coverage", "builtin:plane");
let mut set = TextureSet::new("Tiles", 0, 64);
set.uv_tiles = vec![1001, 1002, 1003];
set.tile_resolutions.insert(1002, 32);
let scales = set.block_scales();
project.texture_sets.push(set);
let mut gbuf = UvGBuffer::new(&mesh, 0, 192, 64);
for (index, triangle) in gbuf.tri.iter_mut().enumerate() {
if !(64..96).contains(&(index % 192)) || index / 192 >= 32 {
*triangle = NO_TRI;
}
}
let pixels = Default::default();
let images = Default::default();
let baked = Default::default();
let inputs = Inputs {
project: &project,
ts: 0,
mesh: &mesh,
gbuf: &gbuf,
pixels: &pixels,
baked: &baked,
block_scales: scales,
preview: None,
images: &images,
bounds: mesh.bounds(),
};
let covered = covered_texels(&inputs, (384, 128));
for (index, covered) in covered.iter().enumerate() {
assert_eq!(*covered, (128..256).contains(&(index % 384)), "bake texel ({}, {})", index % 384, index / 384);
}
}
#[test]
fn unused_maps_are_evicted_even_while_undo_keeps_the_sources_alive() {
let sources: Vec<_> = (0..=CACHE_MAPS).map(|_| Arc::new(vec![0.5; 16])).collect();
let scales = BlockScales::default();
let key = ((4, 4), (4, 4), (4, 4));
let sizes = store(&sources[0], key, &scales, CurvatureSizes { levels: Vec::new() });
let first = Arc::downgrade(&sizes);
drop(sizes);
for source in sources.iter().skip(1) {
store(source, key, &scales, CurvatureSizes { levels: Vec::new() });
}
assert!(first.upgrade().is_none(), "undo history may retain the bake, but not an unlimited number of derived maps");
}
#[test]
fn cache_budget_evicts_old_levels_but_keeps_one_large_map() {
let source = Arc::new(vec![0.5]);
let key = ((1, 1), (1, 1), (1, 1));
let entry = || {
let level = CurvatureSizeLevel { step: 1, width: 4, height: 1, block: (4, 1), deviation: vec![0; 4] };
let sizes = CurvatureSizes { levels: vec![Some(Arc::new(level))] };
(Arc::downgrade(&source), key, BlockScales::default(), Arc::new(sizes))
};
let mut cache = vec![entry(), entry(), entry()];
let oldest = Arc::downgrade(&cache[0].3);
let newest = cache[2].3.clone();
trim_cache(&mut cache, 16);
assert_eq!(cache.len(), 2);
assert!(oldest.upgrade().is_none());
trim_cache(&mut cache, 1);
assert_eq!(cache.len(), 1, "the active map must not rebuild once per composite tile");
assert!(Arc::ptr_eq(&cache[0].3, &newest));
}
#[test]
fn padding_keeps_an_island_border_from_reading_flat() {
let map_size: u32 = 64;
let left_half = |texel: u32| texel % map_size < map_size / 2;
let curvature: Vec<f32> = (0..map_size * map_size).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect();
let covered: Vec<bool> = (0..map_size * map_size).map(left_half).collect();
let shape = (map_size, map_size);
let sizes = CurvatureSizes::build(&curvature, shape, &covered, shape, &[true; CurvatureDetail::BLURRED_SIZES], None);
// The last covered column, halfway down
let (border_x, border_y) = (map_size / 2 - 1, map_size / 2);
for level in sizes.levels.iter().flatten() {
assert!((level.sample(border_x, border_y) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it");
}
}
#[test]
fn uniform_curvature_keeps_its_strength_at_block_borders() {
let (map_width, map_height): (u32, u32) = (256, 256);
// Curvature 0.8 reads 0.3 above the neutral 0.5 at every size
const CURVATURE: f32 = 0.8;
let expected = CURVATURE - 0.5;
let curvature = vec![CURVATURE; (map_width * map_height) as usize];
let covered = vec![true; curvature.len()];
let block = (map_width / 2, map_height);
let sizes = CurvatureSizes::build(&curvature, (map_width, map_height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None);
// The map's corner, then the last texel of the left block and the first of the right one, halfway down
let border_texels = [(0, 0), (block.0 - 1, map_height / 2), (block.0, map_height / 2)];
for level in sizes.levels.iter().flatten() {
for (x, y) in border_texels {
assert!((level.sample(x, y) - expected).abs() < 0.01, "texel ({x}, {y}) reads {} instead of the uniform {expected}", level.sample(x, y));
}
}
}
#[test]
fn a_new_layout_replaces_the_sizes_of_the_old_one() {
let curvature = Arc::new(vec![0.5; 16]);
let scales = BlockScales::default();
let entries_for_curvature = || {
let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count()
};
store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() });
store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() });
assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached");
}
#[test]
fn sizes_built_on_demand_match_a_full_build() {
let map_size: u32 = 64;
let curvature: Vec<f32> =
(0..map_size * map_size).map(|texel| 0.5 + 0.4 * ((texel % map_size) as f32 * 0.3).sin() * ((texel / map_size) as f32 * 0.2).cos()).collect();
let covered = vec![true; (map_size * map_size) as usize];
let shape = (map_size, map_size);
let all = vec![true; CurvatureDetail::BLURRED_SIZES];
let full = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, None);
let even: Vec<bool> = (0..all.len()).map(|level| level % 2 == 0).collect();
let partial = CurvatureSizes::build(&curvature, shape, &covered, shape, &even, None);
assert!(partial.levels.iter().zip(&even).all(|(level, needed)| level.is_some() == *needed), "only the needed sizes are built");
let completed = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, Some(&partial));
for ((built, expected), earlier) in completed.levels.iter().zip(&full.levels).zip(&partial.levels) {
assert_eq!(built.as_ref().map(|level| &level.deviation), expected.as_ref().map(|level| &level.deviation), "the same values either way");
if let (Some(built), Some(earlier)) = (built, earlier) {
assert!(Arc::ptr_eq(built, earlier), "sizes already built are kept, not rebuilt");
}
}
}
}
+265 -91
View File
@@ -4,17 +4,20 @@
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use rayon::prelude::*;
use texturecraft_core::{
BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId,
LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit,
BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator,
GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1,
blend3, lum, mix3, per_unit,
};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer};
use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed};
use crate::below::{Band, BelowCache, Level};
use crate::curvature_sizes::CurvatureSizes;
use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise};
use crate::store::{BakedMaps, ImageStore, PixelStore, decode};
@@ -204,6 +207,8 @@ struct EffectPlan<'a> {
opacity: f32,
data: Option<Cow<'a, [u16]>>,
preview: bool,
/// The curvature detail sizes a generator with detail reads.
curvature_sizes: Option<Arc<CurvatureSizes>>,
}
struct MaskPlan<'a> {
@@ -304,6 +309,12 @@ fn direction(angle: f32) -> [f32; 2] {
[cs, -sn]
}
/// Gain on the curvature map's own deviation from flat (±0.5 reaches black and white).
const MAP_GAIN: f32 = 2.0;
/// Gain per texel of a detail size: blurring spreads an edge over about twice its radius, so wider sizes need proportionally more to reach full strength.
const GAIN_PER_DETAIL_TEXEL: f32 = 2.0 * std::f32::consts::SQRT_2;
/// Samples along a directional or slope blur at most (beyond, samples spread out).
const LINE_SAMPLES: i32 = 24;
@@ -421,17 +432,20 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3
/// the region it is computed in, so tiles composited in any grouping agree exactly.
const FIX: f64 = (1u64 << 24) as f64;
/// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns.
/// Rows (and columns, transposed) blur in parallel.
fn blur(data: &mut [f32], w: usize, h: usize, r: usize) {
let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 };
let mut v: Vec<i64> = data.par_iter().map(fix).collect();
blur_rows(&mut v, w, r);
let mut t = transpose(&v, w, h);
blur_rows(&mut t, h, r);
data.par_iter_mut().zip(transpose(&t, h, w)).for_each(|(d, s)| *d = (s as f64 / FIX) as f32);
/// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel.
pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) {
let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 };
let mut fixed: Vec<i64> = data.par_iter().map(to_fixed).collect();
blur_rows(&mut fixed, width, radius);
let mut columns = transpose(&fixed, width, height);
blur_rows(&mut columns, height, radius);
data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32);
}
/// The box blurs `blur` runs along each axis
pub(crate) const BLUR_BOX_PASSES: usize = 3;
/// Three box blurs of radius `r` along every row (`w` long) of `data`.
fn blur_rows(data: &mut [i64], w: usize, r: usize) {
if w == 0 {
@@ -439,7 +453,7 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) {
}
data.par_chunks_mut(w).for_each(|row| {
let mut tmp = vec![0i64; row.len()];
for _ in 0..3 {
for _ in 0..BLUR_BOX_PASSES {
box_line(row, &mut tmp, r);
row.copy_from_slice(&tmp);
}
@@ -760,28 +774,53 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32
if tiles.is_empty() || inp.gbuf.width == 0 {
return out;
}
let res = inp.gbuf.width;
let working_width = inp.gbuf.width;
let mut order = Vec::new();
draw_order(inp.project, list, 0, &mut order);
prepare_curvature_sizes(inp, &order);
for id in order {
let Some(layer) = inp.project.content_layer(id) else { continue };
if let Some(m) = layer_mask(inp.project, id).filter(|m| m.enabled && neighbourhood(&m.effects, res).is_some())
&& let Some(f) = field(inp, channels, &out, id, Job::Mask(m), tiles)
if let Some(mask) = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some())
&& let Some(filtered) = field(inp, channels, &out, id, Job::Mask(mask), tiles)
{
out.insert(FieldKey::Mask(id), f);
out.insert(FieldKey::Mask(id), filtered);
}
if layer.is_group() || neighbourhood(&layer.content_effects, res).is_none() {
if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() {
continue;
}
for ch in channels.iter().filter(|c| layer.channels.contains_key(c)) {
if let Some(f) = field(inp, channels, &out, id, Job::Content(*ch), tiles) {
out.insert(FieldKey::Content(id, *ch), f);
for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) {
if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) {
out.insert(FieldKey::Content(id, *channel), filtered);
}
}
}
out
}
/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel.
fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) {
let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible));
let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled);
prepare_mask_curvature_sizes(inp, masks);
}
/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel.
fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator<Item = &'a Mask>) {
let mut needed = [false; CurvatureDetail::BLURRED_SIZES];
for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) {
if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind {
for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) {
*slot |= in_use;
}
}
}
CurvatureSizes::of(inp, &needed);
}
struct Node<'a> {
id: LayerId,
content: Content<'a>,
@@ -799,21 +838,26 @@ struct Node<'a> {
/// Plans of the visible effects of a stack: mask effects (`channel` None) or the content
/// effects of one channel (paint effects then read that channel's pixels).
fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option<Channel>) -> Vec<EffectPlan<'a>> {
fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option<Channel>) -> Vec<EffectPlan<'a>> {
effects
.iter()
.filter(|e| e.visible)
.map(|e| {
let (img, target) = match channel {
Some(c) => (inp.pixels.layer(e.id, c), PaintTarget::Layer(e.id)),
None => (inp.pixels.masks.get(&e.id), PaintTarget::Mask(e.id)),
.filter(|effect| effect.visible)
.map(|effect| {
let (image, target) = match channel {
Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)),
None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)),
};
let curvature_sizes = match &effect.kind {
EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()),
_ => None,
};
EffectPlan {
kind: &e.kind,
blend: e.blend,
opacity: e.opacity,
data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None },
kind: &effect.kind,
blend: effect.blend,
opacity: effect.opacity,
data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None },
preview: previews(inp, target),
curvature_sizes,
}
})
.collect()
@@ -1166,94 +1210,142 @@ impl<'a, 'b> Texel<'a, 'b> {
}
}
fn generator(&mut self, g: &Generator) -> f32 {
let c = self.coords();
let s = match g.kind {
GeneratorKind::EdgeWear => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0,
GeneratorKind::Curvature => self.baked(BakedMap::Curvature).unwrap_or(0.5),
GeneratorKind::Dirt => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
GeneratorKind::AmbientOcclusion => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
GeneratorKind::ThinAreas => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0),
GeneratorKind::Position => c.pos.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
GeneratorKind::Direction => c.nrm.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
let coords = self.coords();
let signal = match (generator.kind, &generator.detail) {
(GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes),
(GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0,
(GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5),
(GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
(GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
(GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0),
(GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
(GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
};
let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s };
let th = 1.0 - g.level.clamp(0.0, 1.0);
let soft = g.softness.max(1e-3);
let t = ((s - (th - soft)) / (2.0 * soft)).clamp(0.0, 1.0);
let v = t * t * (3.0 - 2.0 * t);
if g.invert { 1.0 - v } else { v }
let signal = if generator.noise_amount > 0.0 {
let noise = world_noise(coords.pos, generator.noise_scale, generator.seed);
if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) {
// Break up curvature without inventing edges or cavities on a flat surface
let neutral = if detail.mode == CurvatureMode::Raw { 0.5 } else { 0.0 };
neutral + (signal - neutral) * (1.0 - noise * generator.noise_amount).max(0.0)
} else {
signal + (noise - 0.5) * generator.noise_amount
}
} else {
signal
};
// A smooth step from black to white over 2 × softness around 1 − level
let threshold = 1.0 - generator.level.clamp(0.0, 1.0);
let softness = generator.softness.max(1e-3);
let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0);
let value = ramp * ramp * (3.0 - 2.0 * ramp);
if generator.invert { 1.0 - value } else { value }
}
fn mask(&mut self, m: &MaskPlan) -> f32 {
let mut v = m.background;
let mut skip = 0;
if let Some((k, field)) = m.start
&& let Some(f) = field.get(self.x, self.y).and_then(|d| d.first().copied())
{
v = f;
skip = k + 1;
/// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend.
fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
let combine = |edges: f32, cavities: f32| match detail.mode {
CurvatureMode::Edges => edges,
CurvatureMode::Cavities => cavities,
CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities),
CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities),
};
// Without curvature to read the texel is flat: no edges or cavities
let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) };
let working_size = (self.res, self.inp.gbuf.height);
let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32];
let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) };
let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature));
let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32);
let blurred = |index: usize| {
curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y))
};
let (mut edges, mut cavities) = (0.0f32, 0.0f32);
for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() {
let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) };
let response = deviation * if *size == 0.0 { MAP_GAIN } else { GAIN_PER_DETAIL_TEXEL * size };
let weight = weight.clamp(0.0, 1.0);
edges = 1.0 - (1.0 - edges) * (1.0 - weight * response.clamp(0.0, 1.0));
cavities = 1.0 - (1.0 - cavities) * (1.0 - weight * (-response).clamp(0.0, 1.0));
}
for e in m.effects.iter().skip(skip) {
let o = e.opacity.clamp(0.0, 1.0);
match e.kind {
combine(edges, cavities)
}
fn mask(&mut self, plan: &MaskPlan) -> f32 {
let mut value = plan.background;
let mut skip = 0;
if let Some((filtered_index, field)) = plan.start
&& let Some(filtered) = field.get(self.x, self.y).and_then(|texel| texel.first().copied())
{
value = filtered;
skip = filtered_index + 1;
}
for effect in plan.effects.iter().skip(skip) {
let opacity = effect.opacity.clamp(0.0, 1.0);
match effect.kind {
EffectKind::Paint | EffectKind::Path(_) => {
let (mut pv, mut cov) = match e.data.as_deref() {
Some(d) => (from_u16(d.get(self.o * 2).copied().unwrap_or(0)), from_u16(d.get(self.o * 2 + 1).copied().unwrap_or(0))),
let (mut painted, mut cov) = match effect.data.as_deref() {
Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))),
None => (0.0, 0.0),
};
if e.preview
&& let Some(p) = self.inp.preview
if effect.preview
&& let Some(preview) = self.inp.preview
{
let a = (self.stroke * p.opacity).clamp(0.0, 1.0);
if p.erase {
pv *= 1.0 - a;
cov *= 1.0 - a;
let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0);
if preview.erase {
painted *= 1.0 - stroke;
cov *= 1.0 - stroke;
} else {
pv = p.mask_value * a + pv * (1.0 - a);
cov = a + cov * (1.0 - a);
painted = preview.mask_value * stroke + painted * (1.0 - stroke);
cov = stroke + cov * (1.0 - stroke);
}
}
if cov > 0.0 {
let val = pv / cov.max(1e-5);
v += (blend1(e.blend, v, val) - v) * cov * o;
let layer_value = painted / cov.max(1e-5);
value += (blend1(effect.blend, value, layer_value) - value) * cov * opacity;
}
}
EffectKind::Fill { source, projection } => {
let val = self.source(source, projection, ChannelKind::Scalar)[0];
v += (blend1(e.blend, v, val) - v) * o * self.cover(std::iter::once(source), projection);
let fill = self.source(source, projection, ChannelKind::Scalar)[0];
value += (blend1(effect.blend, value, fill) - value) * opacity * self.cover(std::iter::once(source), projection);
}
EffectKind::Generator(g) => {
let val = self.generator(g);
v += (blend1(e.blend, v, val) - v) * o;
EffectKind::Generator(generator) => {
let generated = self.generator(generator, effect.curvature_sizes.as_deref());
value += (blend1(effect.blend, value, generated) - value) * opacity;
}
EffectKind::Levels(l) => v += (l.apply(v) - v) * o,
EffectKind::Filter(f) => {
// A mask is gray (HSL only changes its lightness); neighbourhood filters come
// precomputed through `MaskPlan::start`.
let val = f.point(ChannelKind::Scalar, [v; 3]).map_or(v, |x| x[0]);
v += (val - v) * o;
EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity,
EffectKind::Filter(filter) => {
// A mask is gray (HSL only changes its lightness); neighbourhood filters come precomputed through `MaskPlan::start`
let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]);
value += (filtered - value) * opacity;
}
EffectKind::ColorSelection { colors, tolerance } => {
let id = self.baked_color(BakedMap::Id);
let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance));
let val = if hit { 1.0 } else { 0.0 };
v += (blend1(e.blend, v, val) - v) * o;
let within = |picked: &[f32; 3], color: [f32; 3]| (0..3).all(|component| (picked[component] - color[component]).abs() <= *tolerance);
let selected = if id.is_some_and(|color| colors.iter().any(|picked| within(picked, color))) { 1.0 } else { 0.0 };
value += (blend1(effect.blend, value, selected) - value) * opacity;
}
EffectKind::Compare { op, value, tolerance } => {
EffectKind::Compare { op, value: compared, tolerance } => {
let pass = match op {
CompareOp::LesserThan => v < *value,
CompareOp::GreaterThan => v > *value,
CompareOp::WithinTolerance => (v - value).abs() <= *tolerance,
CompareOp::LesserThan => value < *compared,
CompareOp::GreaterThan => value > *compared,
CompareOp::WithinTolerance => (value - compared).abs() <= *tolerance,
};
let val = if pass { 1.0 } else { 0.0 };
v += (val - v) * o;
let result = if pass { 1.0 } else { 0.0 };
value += (result - value) * opacity;
}
// Content-only effects.
// Content-only effects
EffectKind::Material(_) | EffectKind::Anchor => {}
}
}
v.clamp(0.0, 1.0)
value.clamp(0.0, 1.0)
}
/// Composite `nodes` over `acc`, recording anchors. Returns true when it reached the `stop`
@@ -1898,6 +1990,10 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default();
let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
let coordinates = all_tiles(width, height);
// A hidden layer's mask is left out of the stack's preparation
prepare_mask_curvature_sizes(inputs, std::iter::once(mask));
let fields = neighbourhood_fields(inputs, &channels, &coordinates);
let tiles: HashMap<(u32, u32), Vec<u8>> = coordinates
.par_iter()
@@ -1951,6 +2047,10 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option<Ve
}
let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default();
// A hidden layer's mask is left out of the stack's preparation
prepare_mask_curvature_sizes(inputs, std::iter::once(mask));
// Filters and anchors can depend on texels outside the requested tiles
let fields = neighbourhood_fields(inputs, &channels, &all_tiles(inputs.gbuf.width, inputs.gbuf.height));
let values: Vec<(usize, f32)> = requested
@@ -2455,6 +2555,80 @@ mod tests {
assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs");
}
#[test]
fn larger_curvature_detail_sizes_reach_further_from_an_edge() {
let mut fixture = fixture();
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256);
fixture.project.texture_sets[0].resolution = 256;
let ridge: Vec<f32> = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect();
fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() };
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec<f32> {
let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights };
let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) };
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)));
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
let images = Default::default();
let inputs = Inputs {
project: &fixture.project,
ts: 0,
mesh: &fixture.mesh,
gbuf: &fixture.gbuf,
pixels: &fixture.pixels,
baked: &fixture.baked,
block_scales: BlockScales::default(),
preview: None,
images: &images,
bounds: fixture.mesh.bounds(),
};
mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::<Vec<_>>()).unwrap()
};
// The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth
let (ridge, five_texels_away) = (8, 3);
let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}");
assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}");
}
#[test]
fn curvature_detail_noise_keeps_flat_areas_neutral() {
let mut fixture = fixture();
fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() };
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
let texels: Vec<_> = (0..64).map(|x| (x, 32)).collect();
for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] {
for mode in CurvatureMode::ALL {
let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] };
let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), ..Generator::new(kind) };
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)));
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap();
let expected = if mode == CurvatureMode::Raw { 0.5 } else { 0.0 };
assert!(values.iter().all(|value| (value - expected).abs() < 0.001), "{kind:?} {mode:?} paints noise on flat curvature: {values:?}");
}
}
}
#[test]
fn raw_curvature_reads_mid_gray_without_a_curvature_map() {
let mut fixture = fixture();
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
let detail = CurvatureDetail { mode: CurvatureMode::Raw, ..CurvatureDetail::default() };
let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) };
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)));
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
let values = assert_sparse_mask_matches_image(&fixture, layer, &[(32, 32)]).unwrap();
assert!(values.iter().all(|value| (value - 0.5).abs() < 0.01), "flat curvature is mid gray in raw mode, not black: {values:?}");
}
#[test]
fn blur_filter_softens_mask_edges() {
let mut f = fixture();
+2
View File
@@ -9,6 +9,8 @@
mod baked_maps;
pub mod below;
mod curvature_size_level;
pub mod curvature_sizes;
pub mod display;
pub mod eval;
pub mod pattern;
+28 -2
View File
@@ -6,6 +6,12 @@ use serde::{Deserialize, Serialize};
use crate::{BlendMode, Channel, ChannelKind, lum};
mod curvature_detail;
mod curvature_mode;
pub use curvature_detail::CurvatureDetail;
pub use curvature_mode::CurvatureMode;
/// Id of a layer or effect (one id space per project).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct LayerId(pub u64);
@@ -540,17 +546,26 @@ pub struct Generator {
/// Direction for `Position` / `Direction` generators (world space).
pub direction: [f32; 3],
pub invert: bool,
/// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<CurvatureDetail>,
}
impl Generator {
pub fn new(kind: GeneratorKind) -> Generator {
let (level, softness, noise_amount) = match kind {
GeneratorKind::EdgeWear => (0.6, 0.12, 0.5),
GeneratorKind::EdgeWear => (0.5, 0.25, 0.3),
GeneratorKind::Curvature => (0.5, 0.5, 0.0),
GeneratorKind::Dirt => (0.55, 0.25, 0.35),
GeneratorKind::ThinAreas => (0.3, 0.2, 0.0),
_ => (0.5, 0.25, 0.0),
};
Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false }
let detail = match kind {
GeneratorKind::Curvature => Some(CurvatureDetail::default()),
GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }),
_ => None,
};
Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail }
}
}
@@ -1050,6 +1065,17 @@ impl Effect {
mod tests {
use super::*;
#[test]
fn curvature_generators_saved_before_detail_sizes_load_without_them() {
let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap();
assert!(saved.get("detail").is_some(), "new curvature generators have detail sizes");
saved.as_object_mut().unwrap().remove("detail");
let loaded: Generator = serde_json::from_value(saved).unwrap();
assert_eq!(loaded.detail, None);
assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes");
}
#[test]
fn levels_map_range_and_gamma() {
let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 };
+36
View File
@@ -0,0 +1,36 @@
use serde::{Deserialize, Serialize};
use super::curvature_mode::CurvatureMode;
/// How a curvature generator reads the curvature map: its mode and how much each detail size adds.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CurvatureDetail {
pub mode: CurvatureMode,
/// Weight (0..1) of each size in [`CurvatureDetail::SIZES`], finest first.
pub weights: [f32; CurvatureDetail::SIZES.len()],
}
impl CurvatureDetail {
/// Detail sizes as blur radii in texels at 2K: the map itself, then doubling radii.
pub const SIZES: [f32; 7] = [0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0];
/// Weights falling off with size, tuned by eye on hard-surface bakes: sharp edges first, broad shapes lit faintly.
pub const BROAD_WEIGHTS: [f32; 7] = [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15];
/// Mostly the finer sizes, tuned the same way: worn edges are thin lines.
pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0];
/// How many sizes are blurred copies of the map (all but the first).
pub const BLURRED_SIZES: usize = CurvatureDetail::SIZES.len() - 1;
/// Which blurred sizes this detail reads: those with a weight above 0.
pub fn blurred_sizes_in_use(&self) -> [bool; CurvatureDetail::BLURRED_SIZES] {
std::array::from_fn(|blurred| self.weights.get(blurred + 1).is_some_and(|weight| *weight > 0.0))
}
}
impl Default for CurvatureDetail {
fn default() -> Self {
CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::BROAD_WEIGHTS }
}
}
+34
View File
@@ -0,0 +1,34 @@
use serde::{Deserialize, Serialize};
/// Which side of the curvature map a curvature generator shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CurvatureMode {
/// Convex edges white.
#[default]
Edges,
/// Concave cavities white.
Cavities,
/// Edges and cavities both white.
Both,
/// Signed curvature around mid gray (cavities dark, edges light).
Raw,
}
impl CurvatureMode {
pub const ALL: [CurvatureMode; 4] = [CurvatureMode::Edges, CurvatureMode::Cavities, CurvatureMode::Both, CurvatureMode::Raw];
pub fn label(self) -> &'static str {
match self {
CurvatureMode::Edges => "Edges",
CurvatureMode::Cavities => "Cavities",
CurvatureMode::Both => "Edges and cavities",
CurvatureMode::Raw => "Raw curvature",
}
}
/// The mode named `name` (its variant or label, any case).
pub fn parse(name: &str) -> Option<CurvatureMode> {
let normalized = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], "");
CurvatureMode::ALL.into_iter().find(|mode| normalized(&format!("{mode:?}")) == normalized(name) || normalized(mode.label()) == normalized(name))
}
}
+3 -2
View File
@@ -24,8 +24,9 @@ pub use bake::{
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use layer::{
ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam,
LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit,
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId,
LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient,
hsl_adjust, per_unit,
};
pub use project::{
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project,
@@ -0,0 +1,45 @@
use super::MergedHigh;
use std::sync::Arc;
use texturecraft_bake::{BakeError, BakePaintMap, BakeRequest, CageShell, HighPoly, HighPolyReach};
use texturecraft_core::BakeSettings;
use texturecraft_geom::{Bvh, Mesh};
/// What a texture set's bake reads to place its transfer rays, owned so a worker thread can use it
#[derive(Clone, Debug)]
pub struct BakeCageInputs {
pub(super) mesh: Arc<Mesh>,
pub(super) bvh: Arc<Bvh>,
pub(super) material: usize,
pub(super) settings: BakeSettings,
pub(super) high: MergedHigh,
pub(super) cage: Option<Arc<Mesh>>,
pub(super) skew: Option<Arc<BakePaintMap>>,
pub(super) cage_paint: Option<Arc<BakePaintMap>>,
}
impl BakeCageInputs {
/// The cage the 3D view draws: the bake's ray origins at each triangle corner
pub fn cage_shell(&self) -> Result<CageShell, BakeError> {
CageShell::new(&self.request())
}
/// Where each high-poly vertex sits relative to the bake's transfer rays
pub fn high_poly_reach(&self) -> Result<HighPolyReach, BakeError> {
HighPolyReach::new(&self.request())
}
fn request(&self) -> BakeRequest<'_> {
BakeRequest {
low_base_color: &[],
mesh: &self.mesh,
bvh: &self.bvh,
material: self.material,
settings: &self.settings,
high: Some(HighPoly { file_ids: &self.high.file_ids, mesh: &self.high.mesh, bvh: &self.high.bvh, base_color: &self.high.base_color }),
cage: self.cage.as_deref(),
skew: self.skew.as_deref(),
cage_paint: self.cage_paint.as_deref(),
tiles: (1, 1),
}
}
}
+5
View File
@@ -14,6 +14,11 @@ pub struct BakeMeshes {
}
impl BakeMeshes {
/// Every high poly appended into one mesh, as bakes see it
pub fn merged_high(&self) -> Option<&MergedHigh> {
self.merged.as_ref()
}
pub(crate) fn rebuild(&mut self) {
self.merged = (!self.high.is_empty()).then(|| {
let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new());
@@ -0,0 +1,23 @@
use rayon::prelude::*;
use texturecraft_bake::HighPolyReach;
/// Per high-poly vertex: 1.0 if its owning set's bake misses it, otherwise 0.0
/// Distances are each set's (max frontal, max rear); filtered or unavailable sets leave their vertices unmarked
/// `vertex_count` is the validated high-poly mesh's vertex count
pub fn high_poly_missed(reach: &[Option<HighPolyReach>], distances: &[(f32, f32)], only_set: Option<usize>, vertex_count: usize) -> Vec<f32> {
// Ownership is already assigned by HighPolyReach; other sets must not color the vertex
let sets: Vec<(&HighPolyReach, f32, f32)> = reach
.iter()
.zip(distances)
.enumerate()
.filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set))
.filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear)))
.collect();
(0..vertex_count)
.into_par_iter()
.map(|vertex| {
let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear));
f32::from(u8::from(missed.unwrap_or(false)))
})
.collect()
}
+69 -21
View File
@@ -8,6 +8,7 @@ use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};
use texturecraft_core::BakePaintTarget;
use super::{BakeCageInputs, MergedHigh};
use crate::{BakeMesh, BakeTask};
use serde_json::{Value, json};
use texturecraft_bake::tracing::Tracer;
@@ -15,6 +16,7 @@ use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress};
use texturecraft_core::{
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion,
};
use texturecraft_geom::Mesh;
use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p};
use crate::{EngineError, Result, Session, cmd};
@@ -90,8 +92,8 @@ fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
}
impl Session {
pub fn bake_task(&self, ts: usize) -> Result<BakeTask> {
let set = self.doc.project.texture_set(ts)?;
pub fn bake_task(&self, texture_set: usize) -> Result<BakeTask> {
let set = self.doc.project.texture_set(texture_set)?;
if !set.has_enabled_bake_tiles() {
return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name)));
}
@@ -112,31 +114,22 @@ impl Session {
} else {
Arc::new(Vec::new())
};
let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() };
let cage = if high.is_some() && set.bake.cage.kind == texturecraft_core::CageType::CustomFile {
Some(self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?.mesh.clone())
} else {
None
};
let painted = |target| high.as_ref().and(self.doc.bake_paint.get(&(ts, target))).map(|map| super::layout::paint_for_bake(map, set)).transpose();
let skew = painted(BakePaintTarget::Skew)?;
let cage_paint = painted(BakePaintTarget::Cage)?;
let high = self.bake_high(texture_set)?;
let cage = self.bake_cage(texture_set, high.is_some())?;
let skew = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Skew)?;
let cage_paint = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Cage)?;
let grid = set.tile_grid();
let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows));
let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect();
let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&ts).cloned().unwrap_or_default() };
let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() };
let tracer = GPU_TRACER.get().cloned();
Ok(BakeTask {
low_base_color,
ts,
mesh: match grid.filter(|_| !set.tile_resolutions.is_empty()) {
Some(grid) => {
let mut mesh = (*self.source).clone();
mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array())));
Arc::new(mesh)
}
None => self.mesh.clone(),
},
ts: texture_set,
mesh: self.bake_mesh(texture_set)?,
bvh: self.bvh.clone(),
material: set.material,
settings: set.bake.clone(),
@@ -151,6 +144,61 @@ impl Session {
})
}
/// What texture set `texture_set`'s bake reads to place its transfer rays; `None` when the set bakes without a high poly or misses its cage file
pub fn bake_cage_inputs(&self, texture_set: usize) -> Result<Option<BakeCageInputs>> {
let set = self.doc.project.texture_set(texture_set)?;
let Some(high) = self.bake_high(texture_set)? else { return Ok(None) };
let Ok(cage) = self.bake_cage(texture_set, true) else { return Ok(None) };
Ok(Some(BakeCageInputs {
mesh: self.bake_mesh(texture_set)?,
bvh: self.bvh.clone(),
material: set.material,
settings: set.bake.clone(),
high,
cage,
skew: self.bake_paint(texture_set, true, BakePaintTarget::Skew)?,
cage_paint: self.bake_paint(texture_set, true, BakePaintTarget::Cage)?,
}))
}
/// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly
fn bake_high(&self, texture_set: usize) -> Result<Option<MergedHigh>> {
let set = self.doc.project.texture_set(texture_set)?;
Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() })
}
/// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage
fn bake_cage(&self, texture_set: usize, has_high: bool) -> Result<Option<Arc<Mesh>>> {
let set = self.doc.project.texture_set(texture_set)?;
if !has_high || set.bake.cage.kind != texturecraft_core::CageType::CustomFile {
return Ok(None);
}
let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?;
Ok(Some(cage.mesh.clone()))
}
/// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly
fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result<Option<Arc<BakePaintMap>>> {
let set = self.doc.project.texture_set(texture_set)?;
let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high);
paint.map(|map| super::layout::paint_for_bake(map, set)).transpose()
}
/// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas
fn bake_mesh(&self, texture_set: usize) -> Result<Arc<Mesh>> {
let set = self.doc.project.texture_set(texture_set)?;
Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) {
Some(grid) => {
let mut mesh = (*self.source).clone();
mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array())));
Arc::new(mesh)
}
None => self.mesh.clone(),
})
}
/// Store a finished bake as one undo step
pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
let tracer = output.tracer.clone();
+4
View File
@@ -1,8 +1,10 @@
//! Baking tasks, commands, settings helpers, and the mesh-map baking API
mod bake_cage_inputs;
mod bake_mesh;
mod bake_meshes;
mod bake_task;
mod high_poly_missed;
mod layout;
mod merged_high;
mod mesh_map_command;
@@ -11,9 +13,11 @@ mod paint_command;
mod preserve_tiles;
mod tile_command;
pub use bake_cage_inputs::BakeCageInputs;
pub use bake_mesh::BakeMesh;
pub use bake_meshes::BakeMeshes;
pub use bake_task::BakeTask;
pub use high_poly_missed::high_poly_missed;
pub use merged_high::MergedHigh;
pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params};
pub use model_patch::settings_patch;
+160
View File
@@ -0,0 +1,160 @@
//! Color selection effects: the ID colors they select, picked from the ID mesh map
use serde_json::{Value, json};
use texturecraft_core::{BakedMap, EffectKind, LayerId};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::surface_at;
use crate::commands::{CommandSpec, bad, f32p, has_layer};
use crate::mask_cmds::effect_id;
use crate::tool_cmds::viewport_of;
use crate::{Result, Session, cmd};
/// Most colors one color selection holds; an ID map rarely has more distinct parts
const MAX_SELECTED_COLORS: usize = 256;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"effect.colorSelection.pick",
"Pick ID color",
[],
None,
"{effect?: a color selection (default: the selected effect), x?, y?: viewport pixels, viewport?: [w,h] | uv?: [u,v] texture set atlas UV (the 2D view), index?: replace this color instead of adding one} → {color: [r,g,b] as the ID map stores it, index} — samples the ID mesh map under the point",
has_layer,
pick
)]
}
/// Applies `effect.set`'s `colors` and `tolerance` params to a color selection
pub(crate) fn apply_params(params: &Value, colors: &mut Vec<[f32; 3]>, tolerance: &mut f32) -> Result<()> {
if let Some(list) = params.get("colors") {
*colors = colors_param(list)?;
}
if let Some(value) = f32p(params, "tolerance") {
*tolerance = value.clamp(0.0, 1.0);
}
Ok(())
}
/// A non-empty `[[r, g, b], ...]` list of finite values, clamped to 0..1
fn colors_param(list: &Value) -> Result<Vec<[f32; 3]>> {
const CMD: &str = "effect.set";
let items = list.as_array().ok_or_else(|| bad(CMD, "`colors` must be a list of [r, g, b]"))?;
if items.is_empty() || items.len() > MAX_SELECTED_COLORS {
return Err(bad(CMD, format!("`colors` needs 1 to {MAX_SELECTED_COLORS} colors")));
}
items
.iter()
.map(|item| match finite_numbers::<3>(item) {
Some(color) => Ok(color.map(|value| value.clamp(0.0, 1.0) as f32)),
_ => Err(bad(CMD, "each color must be [r, g, b] with finite numbers")),
})
.collect()
}
/// Samples the ID map under a viewport point or at a UV and adds the color to a color selection
fn pick(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "effect.colorSelection.pick";
let effect = effect_id(session, params, CMD)?;
let (owner, color_count) = match session.doc.project.effect(effect) {
Some((owner, found)) => match &found.kind {
EffectKind::ColorSelection { colors, .. } => (owner, colors.len()),
other => return Err(bad(CMD, format!("{} is not a color selection", other.name()))),
},
None => return Err(bad(CMD, format!("no effect {}", effect.0))),
};
let index = params
.get("index")
.filter(|index| !index.is_null())
.map(|index| index.as_u64().ok_or_else(|| bad(CMD, "`index` must be a non-negative integer")))
.transpose()?;
let index = match index {
Some(index) => Some(usize::try_from(index).ok().filter(|index| *index < color_count).ok_or_else(|| bad(CMD, format!("no color {index} to replace")))?),
None if color_count >= MAX_SELECTED_COLORS => return Err(bad(CMD, format!("a color selection holds at most {MAX_SELECTED_COLORS} colors"))),
None => None,
};
let color = id_color_at(session, params, owner)?;
session.edit("Pick ID color", |session| {
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
if let EffectKind::ColorSelection { colors, .. } = &mut edited.kind {
match index.and_then(|index| colors.get_mut(index)) {
Some(slot) => *slot = color,
None => colors.push(color),
}
}
Ok(())
})?;
Ok(json!({ "color": color, "index": index.unwrap_or(color_count) }))
}
/// The ID map color of the texel a color selection on `owner` reads at the picked point
fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32; 3]> {
const CMD: &str = "effect.colorSelection.pick";
let (set_index, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the effect's layer is not in a texture set"))?;
let set = session.doc.project.texture_set(set_index)?;
let baked = session.baked(set_index).filter(|baked| baked.maps.contains_key(&BakedMap::Id));
let Some(baked) = baked else {
return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name)));
};
let uv = match params.get("uv") {
Some(uv) => uv_param(uv)?,
None => {
let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else {
return Err(bad(CMD, "give `x` and `y` (viewport pixels) or `uv`"));
};
let (uv, material) = visible_surface(session, Vec2::new(x, y), viewport_of(session, params))
.ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?;
if material != set.material {
return Err(bad(CMD, "that surface belongs to another texture set"));
}
uv
}
};
// The same texel the mask evaluates, so a picked color always selects where it was picked
let size = set.size();
let texel = [uv.x * size.0 as f32, uv.y * size.1 as f32];
if !texel.iter().zip([size.0, size.1]).all(|(position, extent)| (0.0..extent as f32).contains(position)) {
return Err(bad(CMD, "that point is outside the texture set's UV space"));
}
baked.sample_working(BakedMap::Id, texel[0] as u32, texel[1] as u32, size, &set.block_scales()).ok_or_else(|| bad(CMD, "no ID color there"))
}
/// The UV and mesh material under viewport pixel `screen`; hidden texture sets don't stop the ray
fn visible_surface(session: &Session, screen: Vec2, viewport: Vec2) -> Option<(Vec2, usize)> {
let viewport = viewport.max(Vec2::ONE);
let device = Vec2::new(screen.x / viewport.x * 2.0 - 1.0, 1.0 - screen.y / viewport.y * 2.0);
let ray = session.camera.ray(device, viewport.x / viewport.y);
let sets = &session.doc.project.texture_sets;
let visible = |triangle: u32| {
let material = session.mesh.material_of(triangle as usize).unwrap_or(0);
sets.iter().find(|set| set.material == material).is_none_or(|set| set.visible)
};
let hit = session.bvh.closest_filtered(ray.origin, ray.dir, f32::MAX, &visible)?;
let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?;
Some((surface.uv, session.mesh.material_of(hit.tri as usize).unwrap_or(0)))
}
/// A `[u, v]` param of finite numbers
fn uv_param(uv: &Value) -> Result<Vec2> {
match finite_numbers::<2>(uv) {
Some([u, v]) => Ok(Vec2::new(u as f32, v as f32)),
_ => Err(bad("effect.colorSelection.pick", "`uv` must be [u, v] with finite numbers")),
}
}
/// Validate the shape before reading components, without allocating for oversized input
fn finite_numbers<const N: usize>(list: &Value) -> Option<[f64; N]> {
let items: &[Value; N] = list.as_array()?.as_slice().try_into().ok()?;
let mut numbers = [0.0; N];
for (number, item) in numbers.iter_mut().zip(items) {
*number = item.as_f64().filter(|value| value.is_finite())?;
}
Some(numbers)
}
+1
View File
@@ -56,6 +56,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::layer_ops::specs());
v.extend(crate::instance_cmds::specs());
v.extend(crate::mask_cmds::specs());
v.extend(crate::color_selection_cmds::specs());
v.extend(crate::effect_clipboard::specs());
v.extend(crate::tool_cmds::specs());
v.extend(crate::brush_preset_cmds::specs());
+83
View File
@@ -0,0 +1,83 @@
//! Which polygons a polygon fill box selects.
use serde::{Deserialize, Serialize};
use texturecraft_geom::glam::Vec2;
/// How a polygon fill box decides whether it selects a polygon
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum FillHitTest {
/// Any part of the polygon inside the box or crossing it
#[default]
Intersection,
/// The polygon's center point inside the box
ContainedCenter,
}
impl FillHitTest {
/// Whether the box from `low` to `high` selects the polygon made of `triangles` (their corners)
pub fn selects(self, triangles: &[[Vec2; 3]], low: Vec2, high: Vec2) -> bool {
match self {
FillHitTest::Intersection => triangles.iter().any(|corners| triangle_overlaps_box(*corners, low, high)),
FillHitTest::ContainedCenter => center(triangles).is_some_and(|point| point.cmpge(low).all() && point.cmple(high).all()),
}
}
}
/// Area-weighted center of the triangles (their corners' mean when they have no area)
fn center(triangles: &[[Vec2; 3]]) -> Option<Vec2> {
if triangles.is_empty() {
return None;
}
// One pass: total area, area-weighted centroids and plain centroids
let (total_area, weighted, centroids) = triangles.iter().fold((0.0, Vec2::ZERO, Vec2::ZERO), |(total_area, weighted, centroids), corners| {
let area = (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs();
let centroid = (corners[0] + corners[1] + corners[2]) / 3.0;
(total_area + area, weighted + centroid * area, centroids + centroid)
});
Some(if total_area > 0.0 { weighted / total_area } else { centroids / triangles.len() as f32 })
}
/// Separating axis test of a triangle against an axis-aligned box
fn triangle_overlaps_box(corners: [Vec2; 3], low: Vec2, high: Vec2) -> bool {
let triangle_low = corners[0].min(corners[1]).min(corners[2]);
let triangle_high = corners[0].max(corners[1]).max(corners[2]);
if triangle_high.cmplt(low).any() || triangle_low.cmpgt(high).any() {
return false;
}
let box_corners = [low, Vec2::new(high.x, low.y), high, Vec2::new(low.x, high.y)];
(0..3).all(|edge| {
let axis = (corners[(edge + 1) % 3] - corners[edge]).perp();
let span = |points: &[Vec2]| points.iter().fold((f32::MAX, f32::MIN), |(min, max), point| (min.min(axis.dot(*point)), max.max(axis.dot(*point))));
let (triangle_min, triangle_max) = span(&corners);
let (box_min, box_max) = span(&box_corners);
triangle_max >= box_min && box_max >= triangle_min
})
}
#[cfg(test)]
mod tests {
use super::*;
const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)];
#[test]
fn intersection_selects_any_overlap() {
assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(6.0)), "a box cutting the triangle");
assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(3.0), Vec2::splat(5.0)), "inside the bounds, past the long edge");
}
#[test]
fn contained_center_selects_only_by_the_center() {
assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(2.0), Vec2::splat(6.0)), "the center (4/3, 4/3) lies outside");
assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0)));
}
#[test]
fn a_polygon_center_weighs_its_triangles_by_area() {
let square = [[Vec2::ZERO, Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0)], [Vec2::ZERO, Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)]];
assert_eq!(center(&square), Some(Vec2::ONE));
assert_eq!(center(&[]), None);
}
}
+17
View File
@@ -0,0 +1,17 @@
//! What one polygon fill target grows to.
use serde::{Deserialize, Serialize};
/// Polygon fill granularity: what a clicked triangle or a boxed polygon grows to
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum FillMode {
/// The triangle itself
#[default]
Triangle,
/// The source polygon (quad or n-gon) the importer split into triangles
Polygon,
/// The UV island: triangles sharing edges in UV space
UvIsland,
/// The connected geometry: triangles sharing edges by position
Mesh,
}
+14
View File
@@ -19,6 +19,20 @@ pub struct FilterDef {
pub mask: bool,
}
impl FilterDef {
/// Whether it builds a filter effect (levels and material finishes are effect types of their own)
pub fn is_filter_effect(&self) -> bool {
matches!(build(self.id, &Value::Null), Ok(EffectKind::Filter(_)))
}
}
/// The library entries that build filter effects, in shelf order, worked out once
pub fn filter_effects() -> &'static [&'static FilterDef] {
static FILTER_EFFECTS: std::sync::LazyLock<Vec<&'static FilterDef>> =
std::sync::LazyLock::new(|| FILTERS.iter().filter(|def| def.is_filter_effect()).collect());
&FILTER_EFFECTS
}
const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef {
FilterDef { id, label, group, mask }
}
+36 -25
View File
@@ -2,7 +2,7 @@
//! without a screenshot.
use serde_json::{Value, json};
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, NormalFormat, Projection, Source};
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Source};
use crate::Session;
use crate::session::StackTarget;
@@ -34,38 +34,49 @@ fn fill_json(f: &Fill) -> Value {
}
/// A mask or content (`content`) effect.
fn effect_json(s: &Session, e: &Effect, content: bool) -> Value {
let mut ej = json!({ "id": e.id.0, "name": e.name, "kind": e.kind.name(), "visible": e.visible, "blend": e.blend.label(), "opacity": e.opacity });
match &e.kind {
EffectKind::Generator(g) => {
ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert })
fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
let mut out = json!({ "id": effect.id.0, "name": effect.name, "kind": effect.kind.name(), "visible": effect.visible, "blend": effect.blend.label(), "opacity": effect.opacity });
let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count());
let content_tiles = || session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == effect.id).map(|(_, image)| image.allocated_count()).sum::<usize>();
match &effect.kind {
EffectKind::Generator(generator) => out["generator"] = generator_json(generator),
EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]),
EffectKind::ColorSelection { colors, tolerance } => {
out["colors"] = json!(colors);
out["tolerance"] = json!(tolerance);
}
EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]),
EffectKind::Path(paths) => {
ej["paths"] = json!(paths.iter().map(|p| json!({ "points": p.points.len(), "uv": p.uv, "closed": p.closed, "fill": p.fill })).collect::<Vec<_>>());
ej["tiles"] = json!(if content {
s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::<usize>()
} else {
s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)
});
out["paths"] = json!(
paths.iter().map(|path| json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill })).collect::<Vec<_>>()
);
out["tiles"] = json!(if content { content_tiles() } else { mask_tiles() });
}
EffectKind::Paint if content => {
ej["tiles"] = json!(s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::<usize>())
}
EffectKind::Paint => ej["tiles"] = json!(s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)),
EffectKind::Fill { source, .. } => ej["source"] = source_json(source),
EffectKind::Material(f) => ej["fill"] = fill_json(f),
EffectKind::Filter(f) => {
ej["filter"] = json!(f);
match f {
Filter::Hsl { hue, saturation, lightness } => ej["hsl"] = json!([hue, saturation, lightness]),
Filter::Blur { radius } => ej["radius"] = json!(radius),
EffectKind::Paint if content => out["tiles"] = json!(content_tiles()),
EffectKind::Paint => out["tiles"] = json!(mask_tiles()),
EffectKind::Fill { source, .. } => out["source"] = source_json(source),
EffectKind::Material(fill) => out["fill"] = fill_json(fill),
EffectKind::Filter(filter) => {
out["filter"] = json!(filter);
match filter {
Filter::Hsl { hue, saturation, lightness } => out["hsl"] = json!([hue, saturation, lightness]),
Filter::Blur { radius } => out["radius"] = json!(radius),
_ => {}
}
}
_ => {}
}
ej
out
}
/// A generator's settings, with its curvature mode and detail size weights when it has them.
fn generator_json(generator: &Generator) -> Value {
let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "invert": generator.invert });
if let Some(detail) = &generator.detail {
out["mode"] = json!(format!("{:?}", detail.mode));
out["sizes"] = json!(detail.weights);
}
out
}
fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value {
+13 -3
View File
@@ -11,10 +11,13 @@
pub mod bake;
pub mod brush_preset_cmds;
pub mod camera_cmds;
pub mod color_selection_cmds;
pub mod commands;
pub mod decal_cmds;
pub mod effect_clipboard;
pub mod file_cmds;
pub mod fill_hit_test;
pub mod fill_mode;
pub mod filter_lib;
pub mod inspect;
pub mod instance_cmds;
@@ -22,17 +25,20 @@ pub mod layer_cmds;
pub mod layer_ops;
pub mod link_cmds;
pub mod mask_cmds;
pub mod mask_preview;
mod mask_preview_camera;
mod mask_preview_pixel;
pub mod material_lib;
mod material_preview_pixel;
pub mod materials;
pub mod materialx_cmds;
pub mod meshmap_cmds;
mod meshmap_file_name;
pub mod meshmap_import_cmds;
mod orb_camera;
pub mod orb_preview;
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;
@@ -47,14 +53,18 @@ pub mod smart_masks;
pub mod template_cmds;
pub mod text_cmds;
pub mod tool_cmds;
mod triangle_partition;
mod uv_stroke_state;
pub mod uv_tile_cmds;
pub mod view_cmds;
pub use bake::{BakeMesh, BakeMeshes, BakeTask};
pub use commands::{CommandSpec, command_specs, execute, find};
pub use fill_hit_test::FillHitTest;
pub use fill_mode::FillMode;
pub use path_tool::PathState;
pub use project_cmds::sample_session;
pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
pub use set_cmds::{ResizeOutput, ResizeTask};
pub use texturecraft_compose as compose;
+149 -56
View File
@@ -2,8 +2,8 @@
use serde_json::{Value, json};
use texturecraft_core::{
BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind,
Project, Source,
BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground,
Procedural, ProceduralKind, Project, Source,
};
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add generator",
["Layers", "Effects"],
None,
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?}",
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}",
has_layer,
add_generator
),
@@ -94,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit effect",
[],
None,
"{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}",
"{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}",
has_layer,
set
),
@@ -314,39 +314,76 @@ fn add_fill(s: &mut Session, p: &Value) -> Result<Value> {
push_effect(s, p, EffectKind::Fill { source, projection }, blend)
}
fn generator_from(p: &Value, g: &mut Generator) {
if let Some(v) = f32p(p, "level") {
g.level = v.clamp(0.0, 1.0);
/// Apply `params` to `generator`, using `command` in errors
fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
if let Some(level) = f32p(params, "level") {
generator.level = level.clamp(0.0, 1.0);
}
if let Some(v) = f32p(p, "softness") {
g.softness = v.clamp(0.0, 1.0);
if let Some(softness) = f32p(params, "softness") {
generator.softness = softness.clamp(0.0, 1.0);
}
if let Some(v) = f32p(p, "noise") {
g.noise_amount = v.clamp(0.0, 2.0);
if let Some(noise) = f32p(params, "noise") {
generator.noise_amount = noise.clamp(0.0, 2.0);
}
if let Some(v) = f32p(p, "noiseScale") {
g.noise_scale = v.clamp(0.01, 1000.0);
if let Some(noise_scale) = f32p(params, "noiseScale") {
generator.noise_scale = noise_scale.clamp(0.01, 1000.0);
}
if let Some(v) = u64p(p, "seed") {
g.seed = v as u32;
if let Some(seed) = u64p(params, "seed") {
generator.seed = seed as u32;
}
if let Some(v) = boolp(p, "invert") {
g.invert = v;
if let Some(invert) = boolp(params, "invert") {
generator.invert = invert;
}
if let Some(d) = color_param(p, "direction") {
g.direction = d;
if let Some(direction) = color_param(params, "direction") {
generator.direction = direction;
}
// A mode or sizes also give a curvature generator saved before detail sizes its detail
let mode = params
.get("mode")
.map(|value| {
let name = value.as_str().ok_or_else(|| bad(command, "`mode` must be a string"))?;
CurvatureMode::parse(name).ok_or_else(|| bad(command, format!("unknown curvature mode `{name}`")))
})
.transpose()?;
let weights = params.get("sizes").map(|value| size_weights(command, value)).transpose()?;
if mode.is_none() && weights.is_none() {
return Ok(());
}
if !matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) {
return Err(bad(command, "only curvature and edge wear generators have a mode and detail sizes"));
}
let detail = generator.detail.get_or_insert_with(CurvatureDetail::default);
if let Some(mode) = mode {
detail.mode = mode;
}
if let Some(weights) = weights {
detail.weights = weights;
}
Ok(())
}
fn add_generator(s: &mut Session, p: &Value) -> Result<Value> {
let kind = match strp(p, "generator") {
Some(k) => GeneratorKind::parse(k).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{k}`")))?,
/// Read one weight (0..1) per size of [`CurvatureDetail::SIZES`], finest first
fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::SIZES.len()]> {
let invalid = || bad(command, format!("`sizes` takes {} numbers, finest first", CurvatureDetail::SIZES.len()));
let items = value.as_array().filter(|items| items.len() == CurvatureDetail::SIZES.len()).ok_or_else(invalid)?;
let mut weights = [0.0; CurvatureDetail::SIZES.len()];
for (weight, item) in weights.iter_mut().zip(items) {
*weight = item.as_f64().ok_or_else(invalid)?.clamp(0.0, 1.0) as f32;
}
Ok(weights)
}
fn add_generator(session: &mut Session, params: &Value) -> Result<Value> {
let kind = match strp(params, "generator") {
Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?,
None => GeneratorKind::EdgeWear,
};
let mut g = Generator::new(kind);
generator_from(p, &mut g);
let blend = blend_param("effect.add.generator", p, "blend")?.unwrap_or(BlendMode::Normal);
push_effect(s, p, EffectKind::Generator(g), blend)
let mut generator = Generator::new(kind);
generator_from("effect.add.generator", params, &mut generator)?;
let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal);
push_effect(session, params, EffectKind::Generator(generator), blend)
}
pub(crate) fn levels_from(p: &Value, l: &mut Levels) {
@@ -413,55 +450,79 @@ fn histogram(s: &mut Session, p: &Value) -> Result<Value> {
Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) })
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
let eid = effect_id(s, p, "effect.set")?;
let blend = blend_param("effect.set", p, "blend")?;
// A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone
// re-targets the current one.
let anchor = match s.doc.project.effect(eid) {
/// Edit visibility, blending, name, effect parameters, or a filter's type
fn set(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "effect.set";
let effect = effect_id(session, params, CMD)?;
let blend = blend_param(CMD, params, "blend")?;
// `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one
let anchor = match session.doc.project.effect(effect) {
Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => {
let (current, channel) = match source {
Source::Anchor { anchor, channel } => (Some(*anchor), *channel),
_ => (None, Channel::Height),
};
let channel_param = channel_param("effect.set", p, "anchorChannel")?;
match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) {
Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?),
let channel_param = channel_param(CMD, params, "anchorChannel")?;
match u64p(params, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) {
Some(anchor) => Some(anchor_source(session, CMD, owner, anchor, channel_param.unwrap_or(channel))?),
None => None,
}
}
_ => None,
};
s.edit("Edit effect", |s| {
let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?;
if let Some(v) = boolp(p, "visible") {
e.visible = v;
// Naming the filter the effect already is edits its parameters like a plain effect.set
let swapped = match strp(params, "filter") {
Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None,
Some(filter) => Some(swapped_filter(session, effect, filter, params)?),
None => None,
};
let swaps_filter = swapped.is_some();
session.edit("Edit effect", |session| {
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
if let Some((kind, label)) = swapped {
if let EffectKind::Filter(old) = &edited.kind
&& edited.name == old.label()
{
edited.name = label.to_string();
}
edited.kind = kind;
}
if let Some(b) = blend {
e.blend = b;
if let Some(visible) = boolp(params, "visible") {
edited.visible = visible;
}
if let Some(o) = f32p(p, "opacity") {
e.opacity = o.clamp(0.0, 1.0);
if let Some(blend) = blend {
edited.blend = blend;
}
if let Some(n) = name_param(p) {
e.name = n.to_string();
if let Some(opacity) = f32p(params, "opacity") {
edited.opacity = opacity.clamp(0.0, 1.0);
}
match &mut e.kind {
EffectKind::Generator(g) => generator_from(p, g),
EffectKind::Levels(l) => levels_from(p, l),
EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?,
if let Some(name) = name_param(params) {
edited.name = name.to_string();
}
match &mut edited.kind {
EffectKind::Generator(generator) => generator_from(CMD, params, generator)?,
EffectKind::Levels(levels) => levels_from(params, levels),
// The swapped filter was built with the parameters already
EffectKind::Filter(_) if swaps_filter => {}
EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?,
EffectKind::Fill { source, .. } => {
if let Some(a) = anchor {
*source = a;
} else if let Some(x) = f32p(p, "value")
if let Some(anchor) = anchor {
*source = anchor;
} else if let Some(value) = f32p(params, "value")
&& matches!(source, Source::Uniform(_) | Source::Anchor { .. })
{
*source = Source::Uniform([x.clamp(0.0, 1.0); 3]);
*source = Source::Uniform([value.clamp(0.0, 1.0); 3]);
}
}
EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => {
if let Some(x) = f32p(p, "tolerance") {
*tolerance = x.clamp(0.0, 1.0);
EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?,
EffectKind::Compare { tolerance, .. } => {
if let Some(value) = f32p(params, "tolerance") {
*tolerance = value.clamp(0.0, 1.0);
}
}
_ => {}
@@ -471,6 +532,38 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// The library id of the filter effect `effect` is, if it is one
fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> {
match &s.doc.project.effect(effect)?.1.kind {
EffectKind::Filter(filter) => crate::filter_lib::find(filter.label()).map(|def| def.id),
_ => None,
}
}
/// Filter `id` built with `p` and its label, to replace filter effect `effect`
fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> {
const CMD: &str = "effect.set";
let (owner, current) = s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
if !matches!(current.kind, EffectKind::Filter(_)) {
return Err(bad(CMD, format!("`filter` changes filter effects only, not {}", current.kind.name().to_ascii_lowercase())));
}
let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?;
let mut kind = crate::filter_lib::build(def.id, &Value::Null)?;
let EffectKind::Filter(filter) = &mut kind else {
return Err(bad(CMD, format!("{} is its own effect type: add it with effect.add.filter", def.label)));
};
let mask = s.doc.project.layer(owner)?.mask.as_ref();
let on_mask = mask.is_some_and(|mask| mask.effects.iter().any(|masked| masked.id == effect));
if on_mask && !def.mask {
return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label)));
}
crate::filter_lib::apply(p, filter, CMD)?;
Ok((kind, def.label))
}
/// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there.
fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec<Effect>, usize)> {
project.layers.values_mut().find_map(|l| {
-161
View File
@@ -1,161 +0,0 @@
//! Smart mask previews share one baked [`primitives::preview_orb`]
//! Presets use `mask.smart.apply` and the compositor, matching document masks
use serde_json::json;
use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::primitives;
use crate::mask_preview_camera::MaskPreviewCamera;
pub use crate::mask_preview_pixel::MaskPreviewPixel;
use crate::{EngineError, Result, Session};
/// Bake resolution in texels; 256 loses the thin edge lines
const TEXTURE_PX: u32 = 512;
/// Camera rays per preview pixel along each axis (anti-aliased outline)
const SUPERSAMPLE: usize = 2;
/// Bound camera samples and output allocations for shelf previews
pub const MAX_PREVIEW_SIZE_PX: usize = 512;
/// AO and thickness rays per texel; thumbnail detail needs fewer than the default
const OCCLUSION_RAYS: u32 = 12;
/// Curvature rays per texel; thumbnail detail needs fewer than the default
const CURVATURE_RAYS: u32 = 12;
/// Radius relative to the bounding box; isolates panel edges from the round body
const CURVATURE_RADIUS: f32 = 0.005;
/// The mesh maps the smart mask generators read
const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness];
/// Keep camera views for the thumbnail and hover preview sizes
const CAMERAS_KEPT: usize = 2;
/// The baked preview shape and, per preview size, what its camera sees
pub struct MaskPreview {
session: Session,
layer: LayerId,
/// Cached camera views, least recently used first
cameras: Vec<MaskPreviewCamera>,
}
impl MaskPreview {
/// Bake the preview shape once (previews of any size reuse it)
pub fn new() -> Result<MaskPreview> {
let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?;
let set = session.doc.project.texture_set_mut(0)?;
set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?;
set.bake.high_poly.use_low_as_high = true;
set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh;
set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS;
set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS;
set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS;
set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS;
for map in BakedMap::ALL {
set.bake.maps.set_enabled(map, MAPS.contains(&map));
}
let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?;
session.bake_now(0, false)?;
Ok(MaskPreview { session, layer, cameras: Vec::new() })
}
/// Row-major `size²` pixels, with None outside the shape
/// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]
pub fn render(&mut self, id: &str, size: usize) -> Option<Vec<Option<MaskPreviewPixel>>> {
if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) {
return None;
}
crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?;
// Previews need no undo history; retaining snapshots grows memory across presets
self.session.undo.clear();
let camera = camera_for(&mut self.cameras, &self.session, size)?;
let values = self.session.mask_at(self.layer, &camera.texels)?;
let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32;
let pixels = (0..size * size)
.map(|i| {
let (x, y) = (i % size, i / size);
let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0);
for sy in 0..SUPERSAMPLE {
for sx in 0..SUPERSAMPLE {
let ray = (y * SUPERSAMPLE + sy) * camera.rays_per_side + x * SUPERSAMPLE + sx;
let Some(&Some((texel, n))) = camera.samples.get(ray) else { continue };
mask += values.get(texel).copied().unwrap_or(0.0);
normal += n;
hits += 1.0;
}
}
(hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels })
})
.collect();
Some(pixels)
}
}
/// Cache one camera per preview size, evicting the least recently used view
fn camera_for<'a>(cameras: &'a mut Vec<MaskPreviewCamera>, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> {
let rays_per_side = size * SUPERSAMPLE;
let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) {
Some(i) => cameras.remove(i),
None => MaskPreviewCamera::new(session, TEXTURE_PX, rays_per_side),
};
if cameras.len() >= CAMERAS_KEPT {
cameras.remove(0);
}
cameras.push(camera);
cameras.last()
}
#[cfg(test)]
mod tests {
use super::*;
/// Mean absolute difference of the masks of two previews over the pixels both see
fn difference(a: &[Option<MaskPreviewPixel>], b: &[Option<MaskPreviewPixel>]) -> f32 {
let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect();
pairs.iter().map(|(a, b)| (a - b).abs()).sum::<f32>() / pairs.len().max(1) as f32
}
#[test]
fn invalid_preview_sizes_are_rejected_before_changing_the_shape() {
let session = Session::new_project("Mask preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
let layer = session.doc.project.texture_set(0).unwrap().stack[0];
let mut preview = MaskPreview { session, layer, cameras: Vec::new() };
for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] {
assert!(preview.render("edges_sharp", size).is_none(), "size {size} should be rejected before rendering");
assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera");
assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask");
}
}
#[test]
fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() {
let size = 24;
let mut preview = MaskPreview::new().unwrap();
for sm in crate::smart_masks::SMART_MASKS {
let px = preview.render(sm.id, size).unwrap_or_else(|| panic!("{}", sm.id));
assert_eq!(px.len(), size * size, "{}", sm.id);
assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id);
let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect();
assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id);
for p in seen {
assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id);
assert!(p.normal.is_finite(), "{}: {p:?}", sm.id);
}
}
let (edges, cavities) = (preview.render("edges_sharp", size).unwrap(), preview.render("dirt_cavities", size).unwrap());
let shows = |px: &[Option<MaskPreviewPixel>]| px.iter().flatten().any(|p| p.mask > 0.5);
assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape");
assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities));
assert!(preview.render("nope", size).is_none());
let big = preview.render("edges_sharp", size * 3).unwrap();
let mean = |px: &[Option<MaskPreviewPixel>]| px.iter().flatten().map(|p| p.mask).sum::<f32>() / px.iter().flatten().count().max(1) as f32;
assert_eq!(big.len(), size * size * 9);
assert!((mean(&big) - mean(&edges)).abs() < 0.05, "{} vs {}", mean(&big), mean(&edges));
preview.render("edges_sharp", size * 2).unwrap();
assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera");
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]).
//! One pixel of a smart mask preview (see [`crate::orb_preview::OrbPreview::mask`])
use texturecraft_geom::glam::Vec3;
@@ -0,0 +1,16 @@
//! One pixel of a smart material preview (see [`crate::orb_preview::OrbPreview::material`])
use texturecraft_geom::glam::Vec3;
use crate::preview::Sample;
/// The material values seen at a preview pixel, with what a display needs to light the shape
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MaterialPreviewPixel {
/// Linear material values, averaged over the pixel
pub sample: Sample,
/// Surface normal in view space (+X right, +Y up, +Z towards the viewer)
pub normal: Vec3,
/// Fraction of the pixel the shape covers (0..=1, anti-aliased outline)
pub coverage: f32,
}
@@ -1,4 +1,4 @@
//! Cached camera rays for one smart mask preview size
//! Cached camera rays for one preview orb size
use std::collections::HashMap;
@@ -11,11 +11,11 @@ use crate::Session;
const CAMERA_PITCH_DEG: f32 = 35.0;
const CAMERA_YAW_DEG: f32 = -34.4;
/// Index into [`MaskPreviewCamera::texels`] and view-space normal; None on a miss
/// Index into [`OrbCamera::texels`] and view-space normal; None on a miss
pub(crate) type CameraSample = Option<(usize, Vec3)>;
/// What each ray of a square orthographic view of the preview shape sees
pub(crate) struct MaskPreviewCamera {
/// What each ray of a square orthographic view of the orb sees
pub(crate) struct OrbCamera {
/// Rays along each side of the view
pub rays_per_side: usize,
/// The texels (x, y) the camera sees, each once
@@ -24,12 +24,12 @@ pub(crate) struct MaskPreviewCamera {
pub samples: Vec<CameraSample>,
}
impl MaskPreviewCamera {
impl OrbCamera {
/// Trace a square orthographic view onto a `texture_px²` texture
pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera {
let (lo, hi) = session.mesh.bounds();
let center = (lo + hi) * 0.5;
let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max);
pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> OrbCamera {
let (min, max) = session.mesh.bounds();
let center = (min + max) * 0.5;
let radius = session.mesh.positions.iter().map(|position| position.distance(center)).fold(0.0f32, f32::max);
let pitch = CAMERA_PITCH_DEG.to_radians();
let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians());
let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos());
@@ -40,9 +40,9 @@ impl MaskPreviewCamera {
let mut texels = Vec::new();
let mut index_of = HashMap::new();
let samples = (0..rays_per_side * rays_per_side)
.map(|i| {
.map(|ray| {
let side = rays_per_side as f32;
let ndc = Vec2::new(((i % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((i / rays_per_side) as f32 + 0.5) / side * 2.0);
let ndc = Vec2::new(((ray % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((ray / rays_per_side) as f32 + 0.5) / side * 2.0);
// Start well outside the shape so every ray enters it from the front
let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0;
let hit = session.bvh.closest(origin, forward, radius * 8.0)?;
@@ -52,10 +52,12 @@ impl MaskPreviewCamera {
texels.push(texel);
texels.len() - 1
});
let n = surface.nrm;
Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward))))
let normal = surface.nrm;
Some((index, Vec3::new(normal.dot(right), normal.dot(up), -normal.dot(forward))))
})
.collect();
MaskPreviewCamera { rays_per_side, texels, samples }
OrbCamera { rays_per_side, texels, samples }
}
}
+297
View File
@@ -0,0 +1,297 @@
//! Smart mask and smart material previews share one baked [`primitives::preview_orb`]
//! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor
use std::collections::{BTreeMap, BTreeSet};
use serde_json::json;
use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::primitives;
use texturecraft_texel::TILE;
pub use crate::mask_preview_pixel::MaskPreviewPixel;
pub use crate::material_preview_pixel::MaterialPreviewPixel;
use crate::orb_camera::OrbCamera;
use crate::preview::Sample;
use crate::session::Document;
use crate::{EngineError, Result, Session, materials};
/// Bake resolution in texels; 256 loses the thin edge lines
const TEXTURE_PX: u32 = 512;
/// Camera rays per preview pixel along each axis (anti-aliased outline)
const SUPERSAMPLE: usize = 2;
/// Bound camera samples and output allocations for shelf previews
pub const MAX_PREVIEW_SIZE_PX: usize = 512;
/// AO and thickness rays per texel; thumbnail detail needs fewer than the default
const OCCLUSION_RAYS: u32 = 12;
/// Curvature rays per texel; thumbnail detail needs fewer than the default
const CURVATURE_RAYS: u32 = 12;
/// Radius relative to the bounding box; isolates panel edges from the round body
const CURVATURE_RADIUS: f32 = 0.005;
/// The mesh maps the smart mask generators read; smart materials build on the same presets
const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness];
/// Keep camera views for the thumbnail and hover preview sizes
const CAMERAS_KEPT: usize = 2;
/// The channels a material preview shows, in [`Sample`] order
const MATERIAL_CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height];
/// The orb's only texture set
const SET: usize = 0;
/// The baked orb and, per preview size, what its camera sees
pub struct OrbPreview {
session: Session,
/// The layer smart masks are applied to
layer: LayerId,
/// The baked document and selection, restored before each material
bare: (Document, BTreeMap<usize, LayerId>),
/// Cached camera views, least recently used first
cameras: Vec<OrbCamera>,
}
impl OrbPreview {
/// Bake the orb once (previews of any size reuse it)
pub fn new() -> Result<OrbPreview> {
let mut session = Session::new_project("Orb preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?;
let set = session.doc.project.texture_set_mut(SET)?;
set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?;
set.bake.high_poly.use_low_as_high = true;
set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh;
set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS;
set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS;
set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS;
set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS;
for map in BakedMap::ALL {
set.bake.maps.set_enabled(map, MAPS.contains(&map));
}
let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?;
session.bake_now(SET, false)?;
let bare = (session.doc.clone(), session.selected.clone());
Ok(OrbPreview { session, layer, bare, cameras: Vec::new() })
}
/// Row-major `size²` pixels of smart mask `id`, with None outside the shape
/// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]
pub fn mask(&mut self, id: &str, size: usize) -> Option<Vec<Option<MaskPreviewPixel>>> {
if !valid_size(size) {
return None;
}
crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?;
// Previews need no undo history; retaining snapshots grows memory across presets
self.session.undo.clear();
let camera = camera_for(&mut self.cameras, &self.session, size)?;
let values = self.session.mask_at(self.layer, &camera.texels)?;
let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32;
let pixels = (0..size * size)
.map(|pixel| {
let (mut mask_sum, mut normal_sum, mut hits) = (0.0, Vec3::ZERO, 0.0);
for (texel, normal) in pixel_hits(camera, size, pixel) {
mask_sum += values.get(texel).copied().unwrap_or(0.0);
normal_sum += normal;
hits += 1.0;
}
(hits > 0.0).then(|| MaskPreviewPixel { mask: mask_sum / hits, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels })
})
.collect();
Some(pixels)
}
/// Row-major `size²` pixels of built-in material `id`, with None outside the shape
/// Returns None for unknown materials or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]
pub fn material(&mut self, id: &str, size: usize) -> Option<Vec<Option<MaterialPreviewPixel>>> {
if !valid_size(size) {
return None;
}
// Each material goes on the bare shape, not over the previous one
(self.session.doc, self.session.selected) = self.bare.clone();
let applied = materials::apply(&mut self.session, id);
// Previews need no undo history; retaining snapshots grows memory across materials
self.session.undo.clear();
applied.ok()?;
let camera = camera_for(&mut self.cameras, &self.session, size)?;
let values = material_at(&self.session, &camera.texels)?;
let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32;
let pixels = (0..size * size)
.map(|pixel| {
let mut sum = Sample { base: [0.0; 3], metallic: 0.0, roughness: 0.0, height: 0.0 };
let (mut normal_sum, mut hits) = (Vec3::ZERO, 0.0);
for (texel, normal) in pixel_hits(camera, size, pixel) {
let Some(value) = values.get(texel) else { continue };
sum.base = [0, 1, 2].map(|component| sum.base[component] + value.base[component]);
sum.metallic += value.metallic;
sum.roughness += value.roughness;
sum.height += value.height;
normal_sum += normal;
hits += 1.0;
}
(hits > 0.0).then(|| {
let mean = Sample {
base: sum.base.map(|component| component / hits),
metallic: sum.metallic / hits,
roughness: sum.roughness / hits,
height: sum.height / hits,
};
MaterialPreviewPixel { sample: mean, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels }
})
})
.collect();
Some(pixels)
}
}
/// Preview sizes the camera may allocate
fn valid_size(size: usize) -> bool {
(1..=MAX_PREVIEW_SIZE_PX).contains(&size)
}
/// The rays through `pixel` of a `size²` preview that hit the shape, as (texel index, view-space normal)
fn pixel_hits(camera: &OrbCamera, size: usize, pixel: usize) -> impl Iterator<Item = (usize, Vec3)> + '_ {
let (x, y) = (pixel % size, pixel / size);
(0..SUPERSAMPLE * SUPERSAMPLE).filter_map(move |sub_pixel| {
let (sub_x, sub_y) = (sub_pixel % SUPERSAMPLE, sub_pixel / SUPERSAMPLE);
let ray = (y * SUPERSAMPLE + sub_y) * camera.rays_per_side + x * SUPERSAMPLE + sub_x;
camera.samples.get(ray).copied().flatten()
})
}
/// The material values at `texels`, compositing only the tiles that hold them
fn material_at(session: &Session, texels: &[(u32, u32)]) -> Option<Vec<Sample>> {
let tiles: BTreeSet<(u32, u32)> = texels.iter().map(|(x, y)| (x / TILE, y / TILE)).collect();
let tiles: Vec<(u32, u32)> = tiles.into_iter().collect();
session.with_inputs(SET, |inputs| {
let mut composite = texturecraft_compose::Composite::new(&MATERIAL_CHANNELS, TEXTURE_PX);
texturecraft_compose::composite_tiles(inputs, &mut composite, &tiles);
let samples = texels
.iter()
.map(|&(x, y)| {
let [base, metallic, roughness, height] = MATERIAL_CHANNELS.map(|channel| composite.value(channel, x, y));
Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] }
})
.collect();
Some(samples)
})
}
/// Cache one camera per preview size, evicting the least recently used view
fn camera_for<'a>(cameras: &'a mut Vec<OrbCamera>, session: &Session, size: usize) -> Option<&'a OrbCamera> {
let rays_per_side = size * SUPERSAMPLE;
let camera = match cameras.iter().position(|camera| camera.rays_per_side == rays_per_side) {
Some(index) => cameras.remove(index),
None => OrbCamera::new(session, TEXTURE_PX, rays_per_side),
};
if cameras.len() >= CAMERAS_KEPT {
cameras.remove(0);
}
cameras.push(camera);
cameras.last()
}
#[cfg(test)]
mod tests {
use super::*;
/// Mean absolute difference of the masks of two previews over the pixels both see
fn difference(a: &[Option<MaskPreviewPixel>], b: &[Option<MaskPreviewPixel>]) -> f32 {
let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect();
pairs.iter().map(|(a, b)| (a - b).abs()).sum::<f32>() / pairs.len().max(1) as f32
}
/// Mean mask value over the pixels a preview sees
fn mean_mask(pixels: &[Option<MaskPreviewPixel>]) -> f32 {
pixels.iter().flatten().map(|pixel| pixel.mask).sum::<f32>() / pixels.iter().flatten().count().max(1) as f32
}
#[test]
fn invalid_preview_sizes_are_rejected_before_changing_the_shape() {
let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
let layer = session.doc.project.texture_set(SET).unwrap().stack[0];
let bare = (session.doc.clone(), session.selected.clone());
let mut preview = OrbPreview { session, layer, bare, cameras: Vec::new() };
let stack_size = preview.session.doc.project.texture_set(SET).unwrap().stack.len();
for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] {
assert!(preview.mask("edges_sharp", size).is_none(), "size {size} should be rejected before rendering");
assert!(preview.material("steel_painted_worn", size).is_none(), "size {size} should be rejected before rendering");
assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera");
assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask");
assert_eq!(preview.session.doc.project.texture_set(SET).unwrap().stack.len(), stack_size, "invalid sizes must not apply a material");
}
}
#[test]
fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() {
let size = 24;
let mut preview = OrbPreview::new().unwrap();
for smart_mask in crate::smart_masks::SMART_MASKS {
let id = smart_mask.id;
let pixels = preview.mask(id, size).unwrap_or_else(|| panic!("{id}"));
assert_eq!(pixels.len(), size * size, "{id}");
assert!(pixels[0].is_none(), "{id}: the corners are outside the shape");
let seen: Vec<&MaskPreviewPixel> = pixels.iter().flatten().collect();
assert!(seen.len() > size * size / 3, "{id}: the shape fills the frame");
for pixel in seen {
assert!((0.0..=1.0).contains(&pixel.mask) && (0.0..=1.0).contains(&pixel.coverage) && pixel.coverage > 0.0, "{id}: {pixel:?}");
assert!(pixel.normal.is_finite(), "{id}: {pixel:?}");
}
}
let (edges, cavities) = (preview.mask("edges_sharp", size).unwrap(), preview.mask("dirt_cavities", size).unwrap());
let shows = |pixels: &[Option<MaskPreviewPixel>]| pixels.iter().flatten().any(|pixel| pixel.mask > 0.5);
assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape");
assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities));
assert!(preview.mask("nope", size).is_none());
// The same bake renders other sizes, showing the same mask
let big = preview.mask("edges_sharp", size * 3).unwrap();
assert_eq!(big.len(), size * size * 9);
assert!((mean_mask(&big) - mean_mask(&edges)).abs() < 0.05, "{} vs {}", mean_mask(&big), mean_mask(&edges));
preview.mask("edges_sharp", size * 2).unwrap();
assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera");
}
#[test]
fn smart_materials_render_on_the_orb_and_show_their_wear() {
let size = 24;
let mut preview = OrbPreview::new().unwrap();
for material in materials::MATERIALS.iter().filter(|material| material.smart) {
let id = material.id;
let pixels = preview.material(id, size).unwrap_or_else(|| panic!("{id}"));
assert_eq!(pixels.len(), size * size, "{id}");
assert!(pixels[0].is_none(), "{id}: the corners are outside the shape");
for pixel in pixels.iter().flatten() {
let sample = pixel.sample;
let values = sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]);
assert!(values.into_iter().all(f32::is_finite), "{id}: {pixel:?}");
assert!(pixel.normal.is_finite() && pixel.coverage > 0.0, "{id}: {pixel:?}");
}
}
assert!(preview.material("nope", size).is_none());
// Paint chipped at the edges shows the steel under it: the smart material is not its base
let (worn, steel) = (preview.material("steel_painted_worn", size).unwrap(), preview.material("steel", size).unwrap());
let metallic_pixels = |pixels: &[Option<MaterialPreviewPixel>]| pixels.iter().flatten().filter(|pixel| pixel.sample.metallic > 0.5).count();
let (worn_metallic, steel_metallic) = (metallic_pixels(&worn), metallic_pixels(&steel));
assert!(worn_metallic > 0 && worn_metallic < steel_metallic / 2, "bare steel only at the worn edges: {worn_metallic} of {steel_metallic}");
let base_colors = |pixels: &[Option<MaterialPreviewPixel>]| pixels.iter().flatten().map(|pixel| pixel.sample.base).collect::<Vec<_>>();
assert_ne!(base_colors(&worn), base_colors(&steel));
// Each material starts from the bare orb: rendering another one in between changes nothing
preview.material("iron_rusted", size).unwrap();
assert_eq!(preview.material("steel_painted_worn", size).unwrap(), worn);
}
}
+82 -136
View File
@@ -7,13 +7,23 @@ 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::uv_stroke_state::UvStrokeState;
use crate::{EngineError, Result};
/// Shortest distance between 2D view stamps, so a stamp with no radius (a pen at zero pressure) can't stall a stroke.
const MIN_UV_STAMP_STEP: f32 = 1e-5;
/// 2D view stamps rasterized together, bounding the memory of one batch.
const UV_STAMP_BATCH: usize = 4096;
/// Covers a UV diagonal at the minimum step (about 142k stamps), including light pen pressure, while bounding hostile coordinates
const MAX_UV_STAMPS_PER_SAMPLE: usize = 150_000;
impl Session {
/// Camera visibility for a stroke at `viewport` (cached until the camera, size or mesh change).
fn eye_depth(&mut self, viewport: Vec2) -> std::sync::Arc<EyeDepth> {
@@ -234,7 +244,7 @@ impl Session {
stroke,
canvas,
depth,
uv: uv_mode.then_some((None, 0.0)),
uv: uv_mode.then(UvStrokeState::default),
camera: self.camera,
viewport,
values,
@@ -301,12 +311,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(())
@@ -314,40 +327,49 @@ impl Session {
/// Add a 2D view sample (texture coordinates). Brush size is relative to the UV square.
pub fn continue_stroke_uv(&mut self, uv: Vec2, pressure: f32) {
let Some(st) = self.stroke.as_mut() else { return };
let Some((last, carry)) = st.uv.as_mut() else { return };
let Some(cache) = self.caches.get_mut(st.ts) else { return };
let b = &st.stroke.settings;
let p = pressure.clamp(0.0, 1.0);
let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 };
let step = (b.spacing * 2.0 * radius).max(1e-5);
let mut points = Vec::new();
match *last {
None => points.push(uv),
Some(prev) => {
let seg = uv - prev;
let len = seg.length();
let mut t = step - *carry;
while t <= len && points.len() < 4096 {
points.push(prev + seg * (t / len.max(1e-9)));
t += step;
}
*carry = len - (t - step);
}
}
// Follow path: turn the stamp with the stroke direction (y up on screen, v grows down).
let angle = match *last {
Some(prev) if b.follow_path && uv != prev => b.angle + (prev.y - uv.y).atan2(uv.x - prev.x).to_degrees() - 90.0,
_ => b.angle,
let Some(active) = self.stroke.as_mut() else { return };
let Some(progress) = active.uv.as_mut() else { return };
let Some(cache) = self.caches.get_mut(active.ts) else { return };
let settings = &active.stroke.settings;
let pressure = pressure.clamp(0.0, 1.0);
let size_scale = if pressure < 1.0 { settings.min_size + (1.0 - settings.min_size) * pressure } else { 1.0 };
let radius = settings.size * 2.0 * size_scale;
let step = (settings.spacing * 2.0 * radius).max(MIN_UV_STAMP_STEP);
// Follow path: turn the stamp with the stroke direction (y up on screen, v grows down)
let angle = match progress.last {
Some(previous) if settings.follow_path && uv != previous => settings.angle + (previous.y - uv.y).atan2(uv.x - previous.x).to_degrees() - 90.0,
_ => settings.angle,
};
*last = Some(uv);
let n0 = st.stroke.stamps.len() as u32;
let stamps: Vec<texturecraft_paint::UvStamp> = points
.iter()
.enumerate()
.map(|(i, c)| texturecraft_paint::UvStamp { center: *c, radius, angle, flow: b.flow, hardness: b.hardness, seed: n0 + i as u32 })
.collect();
texturecraft_paint::rasterize_uv(&mut st.canvas, &cache.gbuf, Self::shape(&self.images, b), &stamps);
// The first sample is one stamp; a later one stamps every `step` along the segment from the previous
let (start, segment, mut distance) = match progress.last.replace(uv) {
None => (uv, Vec2::ZERO, 0.0),
// Pressure can shrink the step below the carry from the preceding sample
Some(previous) => (previous, uv - previous, (step - progress.carry).max(0.0)),
};
let length = segment.length();
let shape = Self::shape(&self.images, settings);
let mut batch = Vec::new();
let mut stamped = 0;
while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE {
let batch_size = UV_STAMP_BATCH.min(MAX_UV_STAMPS_PER_SAMPLE - stamped);
batch.clear();
while distance <= length && batch.len() < batch_size {
let center = start + segment * (distance / length.max(f32::MIN_POSITIVE));
let seed = progress.stamps.wrapping_add((stamped + batch.len()) as u32);
batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed });
distance += step;
}
stamped += batch.len();
texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch);
}
// At most one step, so a segment cut off at the stamp limit can't push the next one's stamps backwards
progress.carry = (length - (distance - step)).min(step);
progress.stamps = progress.stamps.wrapping_add(stamped as u32);
self.stroke_painted();
}
@@ -482,21 +504,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 +517,31 @@ impl Session {
/// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask.
pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
let size = (canvas.alpha.width(), canvas.alpha.height());
let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None };
if self.quick_mask.editing {
self.commit_quick_mask(ts, size, src(self.tool.brush.opacity));
return Ok(());
return self.paint_fill(ts, canvas);
}
self.edit(label, |s| {
let target = s.paint_target()?;
let values = s.stroke_values(target);
match target {
PaintTarget::Layer(id) => commit_layer(&mut s.doc.pixels, id, size, &values, src(s.tool.brush.opacity), &mut Staging::default()),
PaintTarget::Mask(eid) => commit_mask(&mut s.doc.pixels, eid, size, s.tool.mask_value, src(s.tool.brush.opacity), &mut Staging::default()),
}
Ok(())
})
// Each fill is its own step, never merged into a box drag's step of the same label
self.edit_merging(label, false, |session| session.paint_fill(ts, canvas))
}
/// Triangles filled by the current fill mode starting from `tri`.
fn fill_set(&self, tri: u32, material: usize) -> BTreeSet<u32> {
let m = &self.mesh;
match self.tool.fill_mode {
FillMode::Triangle => [tri].into_iter().collect(),
FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(),
FillMode::UvIsland => {
// Triangles sharing an edge in UV space form a UV island: imported meshes often
// split vertices along hard edges (or per face) where the UVs run on, so shared
// vertex indices alone break an island into its polygons.
let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]);
let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) {
Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(),
_ => Vec::new(),
};
let mut by_edge: BTreeMap<_, Vec<u32>> = BTreeMap::new();
for t in m.triangles_of(material) {
for e in edges(t) {
by_edge.entry(e).or_default().push(t as u32);
}
}
let mut seen = BTreeSet::new();
let mut stack = vec![tri];
while let Some(t) = stack.pop() {
if !seen.insert(t) {
continue;
}
for e in edges(t as usize) {
for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) {
if !seen.contains(n) {
stack.push(*n);
}
}
}
}
seen
}
/// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step)
pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
let size = (canvas.alpha.width(), canvas.alpha.height());
let opacity = self.tool.brush.opacity;
let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None };
if self.quick_mask.editing {
self.commit_quick_mask(ts, size, source);
return Ok(());
}
let target = self.paint_target()?;
let values = self.stroke_values(target);
match target {
PaintTarget::Layer(id) => commit_layer(&mut self.doc.pixels, id, size, &values, source, &mut Staging::default()),
PaintTarget::Mask(effect) => commit_mask(&mut self.doc.pixels, effect, size, self.tool.mask_value, source, &mut Staging::default()),
}
Ok(())
}
/// Color picker: copy the material under the cursor into the tool's paint values.
@@ -627,34 +604,3 @@ fn with_commit_source<R>(
let carried = st.canvas.pickup.as_ref().map(|p| &p.values);
f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried })
}
#[cfg(test)]
mod tests {
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::mesh::Mesh;
use texturecraft_geom::primitives;
use crate::session::{FillMode, Session};
#[test]
fn uv_island_fill_follows_uvs_across_split_vertices() {
// Two copies of a plane, each triangle with its own three vertices (as hard edges or
// per-face imports leave a mesh), the second copy apart in UV space.
let plane = primitives::plane(2.0, 4);
let (mut positions, mut uvs) = (Vec::<Vec3>::new(), Vec::<Vec2>::new());
for shift in [0.0, 0.5] {
for i in plane.indices.iter().map(|i| *i as usize) {
positions.push(plane.positions[i] + Vec3::Y * shift);
uvs.push(plane.uvs[i] * 0.5 + shift);
}
}
let indices = (0..positions.len() as u32).collect();
let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap();
let n = plane.triangle_count();
assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared");
let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap();
s.tool.fill_mode = FillMode::UvIsland;
assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island");
assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island");
}
}
+607
View File
@@ -0,0 +1,607 @@
//! Polygon fill: fill the triangles, polygons, UV islands or connected meshes under a click or inside a dragged box, in either view.
use std::borrow::Cow;
use std::collections::{BTreeSet, HashSet};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Mesh, NO_TRI};
use texturecraft_paint::{EyeDepth, fill_triangles, screen_point};
use crate::fill_mode::FillMode;
use crate::polygon_fill_drag::PolygonFillDrag;
use crate::session::Session;
use crate::triangle_partition::TrianglePartition;
use crate::{EngineError, Result};
/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner
const CORNER_GRID_STEPS: f32 = 1e5;
impl Session {
/// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen`
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
if hit.material != self.fill_material()? {
return Err(EngineError::Other("that surface belongs to another texture set".into()));
}
self.fill_group_of(hit.tri)
}
/// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view): the triangle covering that texel's center, so slivers thinner than a texel can't be clicked
pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result<usize> {
let gbuf = self.caches.get(self.ts()).map(|cache| cache.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let size = Vec2::new(gbuf.width as f32, gbuf.height as f32);
let texel = (uv * size).floor();
let triangle = (texel.cmpge(Vec2::ZERO).all() && texel.cmplt(size).all())
.then(|| gbuf.tri.get(texel.y as usize * gbuf.width as usize + texel.x as usize).copied())
.flatten()
.filter(|triangle| *triangle != NO_TRI)
.ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
self.fill_group_of(triangle)
}
/// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step)
pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result<usize> {
// A scripted box stands alone: it finishes any drag under way, and ends even when it fails
self.end_polygon_fill_box();
let shown = self.drag_polygon_fill_box(corner, opposite, viewport);
let filled = self.end_polygon_fill_box();
shown.map(|_| filled)
}
/// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step)
pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result<usize> {
self.end_polygon_fill_box();
let shown = self.drag_polygon_fill_box_uv(corner, opposite);
let filled = self.end_polygon_fill_box();
shown.map(|_| filled)
}
/// Show the fill of a box being dragged between viewport pixels `corner` and `opposite`
pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result<usize> {
// Whole pixels, as the visibility buffer is rendered at
self.drag_polygon_fill(corner, opposite, Some(viewport.round().max(Vec2::ONE)))
}
/// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view)
pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result<usize> {
self.drag_polygon_fill(corner, opposite, None)
}
/// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count
pub fn end_polygon_fill_box(&mut self) -> usize {
let Some(drag) = self.polygon_fill_drag.take() else { return 0 };
let filled = drag.filled.len();
// Quick mask edits keep no history, as with its strokes
if filled > 0 && drag.quick_mask_before.is_none() {
self.push_history("Polygon fill", drag.before);
}
filled
}
/// Show the fill of a box from `corner` to `opposite` in the 3D view of size `viewport`, or in the 2D view when None
fn drag_polygon_fill(&mut self, corner: Vec2, opposite: Vec2, viewport: Option<Vec2>) -> Result<usize> {
if !corner.is_finite() || !opposite.is_finite() {
return Err(EngineError::Other("the box corners must be finite".into()));
}
let (low, high) = (corner.min(opposite), corner.max(opposite));
self.start_polygon_fill_drag(viewport)?;
let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) };
if drag.failed || drag.last_box == Some((low, high)) {
return Ok(drag.filled.len());
}
drag.last_box = Some((low, high));
let selected = self.box_selection(low, high);
self.show_box_fill(selected)
}
/// Continue a box drag only while its view, paint target and quick mask state still match
fn start_polygon_fill_drag(&mut self, viewport: Option<Vec2>) -> Result<()> {
let ts = self.ts();
let target = (self.selected_layer(), self.target);
let quick_mask = self.quick_mask.editing;
// Finish the old target before another preview can restore its earlier document snapshot
if let Some(drag) = &self.polygon_fill_drag {
if drag.ts == ts && drag.target == target && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask {
// A camera move (a wheel zoom mid-drag) keeps the drag, which then sees the mesh from the new camera
if drag.camera != self.camera {
let (points, depth) = self.box_space(viewport);
if let Some(drag) = self.polygon_fill_drag.as_mut() {
(drag.points, drag.depth, drag.camera, drag.last_box) = (points, depth, self.camera, None);
}
}
return Ok(());
}
self.end_polygon_fill_box();
}
let material = self.fill_material()?;
let (points, depth) = self.box_space(viewport);
let polygons = match self.tool.fill_mode {
FillMode::Triangle | FillMode::Polygon => None,
FillMode::UvIsland | FillMode::Mesh => Some(TrianglePartition::new(&self.mesh, material, polygon_edges)),
};
self.polygon_fill_drag = Some(PolygonFillDrag {
ts,
target,
viewport,
camera: self.camera,
before: self.doc.clone(),
quick_mask_before: quick_mask.then(|| self.quick_mask.masks.clone()),
points,
depth,
fill_groups: self.fill_partition(material),
polygons,
filled: BTreeSet::new(),
last_box: None,
failed: false,
});
Ok(())
}
/// Each vertex where a box sees it (viewport pixels for a 3D view of size `viewport`, else texture coordinates) and, for visible polygons only in 3D, what the camera sees
fn box_space(&self, viewport: Option<Vec2>) -> (Vec<Option<Vec2>>, Option<EyeDepth>) {
let Some(size) = viewport else { return (self.mesh.uvs.iter().copied().map(Some).collect(), None) };
let view_proj = self.camera.view_proj(size.x / size.y);
let points = self.mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect();
let depth = self.tool.fill_visible_only.then(|| EyeDepth::render_with_triangles(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32));
(points, depth)
}
/// The mesh material of the texture set being painted
fn fill_material(&self) -> Result<usize> {
Ok(self.doc.project.texture_set(self.ts())?.material)
}
/// The triangles the current fill mode fills together, for `material`
fn fill_partition(&self, material: usize) -> TrianglePartition {
match self.tool.fill_mode {
FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::<u32>::new()),
FillMode::Polygon => TrianglePartition::new(&self.mesh, material, polygon_edges),
FillMode::UvIsland => TrianglePartition::new(&self.mesh, material, uv_edges),
FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges),
}
}
/// Fill the fill-mode group holding `triangle` (one undo step)
fn fill_group_of(&mut self, triangle: u32) -> Result<usize> {
let ts = self.ts();
let groups = self.fill_partition(self.fill_material()?);
let triangles: BTreeSet<u32> = groups.group(triangle).unwrap_or_default().iter().copied().collect();
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
fill_triangles(&mut canvas, &gbuf, &triangles);
self.commit_fill("Polygon fill", ts, &canvas)?;
Ok(triangles.len())
}
/// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden
fn shown_mesh(&self) -> Cow<'_, Mesh> {
let sets = &self.doc.project.texture_sets;
if sets.iter().all(|set| set.visible) {
return Cow::Borrowed(&self.mesh);
}
let mut mesh = (*self.mesh).clone();
for set in sets.iter().filter(|set| !set.visible) {
for triangle in self.mesh.triangles_of(set.material) {
if let Some(corners) = mesh.indices.get_mut(triangle * 3..triangle * 3 + 3) {
let first = corners[0];
corners.fill(first);
}
}
}
Cow::Owned(mesh)
}
/// Triangles the dragged box from `low` to `high` fills: each polygon the hit-test selects, grown by the fill mode
fn box_selection(&self, low: Vec2, high: Vec2) -> BTreeSet<u32> {
let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() };
let visible = drag.depth.as_ref().zip(drag.viewport).map(|(depth, viewport)| visible_triangles(depth, viewport, low, high));
let point = |vertex: usize| drag.points.get(vertex).copied().flatten();
let corners = |triangle: u32| {
let [first, second, third] = self.mesh.tri(triangle as usize)?;
Some([point(first)?, point(second)?, point(third)?])
};
let hit_test = self.tool.fill_hit_test;
let mut polygon_corners = Vec::new();
let mut groups = BTreeSet::new();
for polygon in &drag.polygons.as_ref().unwrap_or(&drag.fill_groups).groups {
let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle)));
if !seen {
continue;
}
polygon_corners.clear();
polygon_corners.extend(polygon.iter().map_while(|triangle| corners(*triangle)));
if polygon_corners.len() == polygon.len() && hit_test.selects(&polygon_corners, low, high) {
groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle)));
}
}
groups.iter().filter_map(|group| drag.fill_groups.groups.get(*group)).flatten().copied().collect()
}
/// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed
fn show_box_fill(&mut self, selected: BTreeSet<u32>) -> Result<usize> {
let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) };
if drag.filled == selected {
return Ok(selected.len());
}
let ts = drag.ts;
let previous = std::mem::replace(&mut self.doc, drag.before.clone());
if let Some(masks) = &drag.quick_mask_before {
self.quick_mask.masks = masks.clone();
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
}
let painted = if selected.is_empty() {
Ok(())
} else {
self.fill_canvas(ts).and_then(|(gbuf, mut canvas)| {
fill_triangles(&mut canvas, &gbuf, &selected);
self.paint_fill(ts, &canvas)
})
};
self.invalidate_changed(&previous);
// A failed fill is reported once and leaves the document as before the drag; the rest of the drag fills nothing
let selected_count = selected.len();
if let Some(drag) = self.polygon_fill_drag.as_mut() {
drag.failed = painted.is_err();
drag.filled = if drag.failed { BTreeSet::new() } else { selected };
}
painted.map(|_| selected_count)
}
}
/// Triangles `depth` (rendered for a `viewport` pixel view) shows in the viewport pixels from `low` to `high`, both edges included
fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet<u32> {
let depth_pixels_per_viewport_pixel = Vec2::new(depth.width as f32, depth.height as f32) / viewport;
let (low, high) = (low * depth_pixels_per_viewport_pixel, high * depth_pixels_per_viewport_pixel);
let columns = pixel_span(low.x, high.x, depth.width);
let rows = pixel_span(low.y, high.y, depth.height);
rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start)))
.copied()
.filter(|triangle| *triangle != NO_TRI)
.collect()
}
/// The pixels `0..count` a span from `low` to `high` covers, both edges included (empty when it lies outside)
fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range<usize> {
let first = low.floor().clamp(0.0, count as f32) as usize;
let end = (high.floor() + 1.0).clamp(0.0, count as f32) as usize;
first..end.max(first)
}
/// Texture coordinates of `triangle`'s corners
fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> {
let [first, second, third] = mesh.tri(triangle)?;
Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?])
}
/// The polygon diagonals of `triangle`: edges the importer added to split a polygon
fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> {
let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0);
let Some(vertices) = mesh.indices.get(triangle * 3..triangle * 3 + 3) else { return Vec::new() };
(0..3)
.filter(|edge| hidden >> edge & 1 == 1)
.map(|edge| {
let (from, to) = (vertices[edge], vertices[(edge + 1) % 3]);
(from.min(to), from.max(to))
})
.collect()
}
/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart
fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> {
let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64);
let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() };
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
}
/// `triangle`'s edges by position: UV seams and hard edges split vertices but leave the geometry connected
fn position_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 3], [i64; 3])> {
let corner = |vertex: usize| mesh.positions.get(vertex).map(|position| (*position * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64));
let Some([first, second, third]) = mesh.tri(triangle) else { return Vec::new() };
let (Some(first), Some(second), Some(third)) = (corner(first), corner(second), corner(third)) else { return Vec::new() };
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
}
#[cfg(test)]
mod tests {
use texturecraft_core::Channel;
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::mesh::Mesh;
use texturecraft_geom::primitives;
use crate::fill_hit_test::FillHitTest;
use crate::fill_mode::FillMode;
use crate::session::{Session, Tool};
/// The roughness the test fills paint, to tell filled texels apart
const FILL_ROUGHNESS: f32 = 0.9;
/// A polygon fill session on `mesh` painting roughness [`FILL_ROUGHNESS`]
fn fill_session(mesh: Mesh) -> Session {
let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap();
session.viewport = Vec2::new(400.0, 400.0);
session.tool.tool = Tool::PolygonFill;
session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]);
session.update();
session
}
/// Whether the texel at texture coordinate `uv` shows the fill's roughness
fn filled_at(session: &Session, uv: Vec2) -> bool {
let (width, height) = session.caches[0].size;
let roughness = session.caches[0].composite.value(Channel::Roughness, (uv.x * width as f32) as u32, (uv.y * height as f32) as u32);
(roughness[0] - FILL_ROUGHNESS).abs() < 0.01
}
/// Two copies of a plane apart in space and in UV space, each triangle with its own three vertices (as hard edges or per-face imports leave a mesh)
fn split_planes() -> (Mesh, usize) {
let plane = primitives::plane(2.0, 4);
let (mut positions, mut uvs) = (Vec::<Vec3>::new(), Vec::<Vec2>::new());
for shift in [0.0, 0.5] {
for vertex in plane.indices.iter().map(|index| *index as usize) {
positions.push(plane.positions[vertex] + Vec3::Y * shift);
uvs.push(plane.uvs[vertex] * 0.5 + shift);
}
}
let indices = (0..positions.len() as u32).collect();
let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap();
assert_eq!(mesh.vertex_count(), 6 * plane.triangle_count(), "no vertex is shared");
(mesh, plane.triangle_count())
}
#[test]
fn uv_island_and_mesh_fills_follow_seams_split_vertices_leave_apart() {
let (mesh, per_plane) = split_planes();
let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap();
for fill_mode in [FillMode::UvIsland, FillMode::Mesh] {
session.tool.fill_mode = fill_mode;
let groups = session.fill_partition(0);
assert_eq!(groups.group(0).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: the whole first plane");
assert_eq!(groups.group(per_plane as u32).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: only the second plane");
}
}
#[test]
fn polygon_mode_groups_the_two_triangles_of_each_quad() {
let mut session = fill_session(primitives::plane(2.0, 2));
session.tool.fill_mode = FillMode::Triangle;
assert_eq!(session.fill_partition(0).group(0), Some(&[0][..]));
session.tool.fill_mode = FillMode::Polygon;
let mut quad = session.fill_partition(0).group(0).unwrap().to_vec();
quad.sort_unstable();
assert_eq!(quad, [0, 1], "the quad's two triangles and no other quad");
}
#[test]
fn a_uv_box_over_half_a_plane_fills_that_half() {
let mut session = fill_session(primitives::plane(2.0, 4));
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
let filled = session.polygon_fill_box_uv(Vec2::new(-0.01, -0.01), Vec2::new(0.5, 1.01)).unwrap();
session.update();
assert_eq!(filled, 16, "the left two columns of quads");
assert!(filled_at(&session, Vec2::new(0.1, 0.5)) && filled_at(&session, Vec2::new(0.45, 0.9)));
assert!(!filled_at(&session, Vec2::new(0.55, 0.5)) && !filled_at(&session, Vec2::new(0.9, 0.1)));
}
#[test]
fn intersection_and_contained_center_differ_on_a_box_missing_a_quads_center() {
let mut session = fill_session(primitives::plane(2.0, 2));
session.tool.fill_mode = FillMode::Polygon;
let (corner, opposite) = (Vec2::new(0.0, 0.0), Vec2::new(0.2, 0.2));
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 0, "the quad's center (0.25, 0.25) is outside");
assert_ne!(session.undo_label(), Some("Polygon fill"), "an empty box records no undo step");
session.tool.fill_hit_test = FillHitTest::Intersection;
assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 2, "the quad the box cuts");
}
#[test]
fn visible_only_skips_the_back_of_a_cube() {
let mut session = fill_session(primitives::cube(1.0));
session.camera.yaw = 0.6;
session.camera.pitch = 0.4;
let (low, high) = (Vec2::ZERO, session.viewport);
let every_triangle = session.mesh.triangle_count();
session.tool.fill_visible_only = true;
assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle / 2, "the three sides the camera sees");
session.tool.fill_visible_only = false;
assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle);
}
#[test]
fn visible_only_sees_through_a_hidden_texture_set() {
let mut session = fill_session(primitives::material_ball());
let base = session.doc.project.texture_sets.iter().position(|set| set.name == "Base").unwrap();
session.active_set = base;
let (low, high) = (Vec2::ZERO, session.viewport);
let behind_the_ball = session.polygon_fill_box(low, high, session.viewport).unwrap();
session.doc.project.texture_sets[0].visible = false;
let ball_hidden = session.polygon_fill_box(low, high, session.viewport).unwrap();
assert!(ball_hidden > behind_the_ball, "hiding the ball shows more of the base: {ball_hidden} vs {behind_the_ball}");
}
#[test]
fn a_dragged_box_fills_live_and_records_one_step_when_it_ends() {
let mut session = fill_session(primitives::plane(2.0, 4));
let history = session.history_labels().len();
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32);
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(), 16, "shrinking the box unfills");
session.update();
assert!(filled_at(&session, Vec2::new(0.2, 0.5)) && !filled_at(&session, Vec2::new(0.8, 0.5)), "the fill shows while dragging");
assert_eq!(session.history_labels().len(), history, "no undo step yet");
assert_eq!(session.end_polygon_fill_box(), 16);
assert_eq!(session.history_labels().len(), history + 1);
session.undo().unwrap();
session.update();
assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag");
}
#[test]
fn a_failed_box_fill_leaves_no_drag_behind() {
let mut session = fill_session(primitives::plane(2.0, 4));
let layer = session.selected.remove(&0).unwrap();
assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).is_err(), "no layer to paint on");
session.selected.insert(0, layer);
assert_eq!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32, "the next box fills again");
}
#[test]
fn undo_and_tool_changes_finish_a_box_drag_first() {
let mut session = fill_session(primitives::plane(2.0, 4));
let history = session.history_labels().len();
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
assert_eq!(session.undo().unwrap(), "Polygon fill", "undo takes back the drag it finished");
assert!(session.polygon_fill_drag.is_none());
assert_eq!(session.history_labels().len(), history);
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
crate::tool_cmds::set_tool(&mut session, Tool::Paint).unwrap();
assert!(session.polygon_fill_drag.is_none());
assert_eq!(session.history_labels().len(), history + 1, "a tool change keeps the fill as one step");
}
#[test]
fn an_unmoved_box_keeps_its_fill() {
let mut session = fill_session(primitives::plane(2.0, 4));
let narrow_box = Vec2::new(0.3, 1.0);
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "intersection: the two columns the box touches");
// Contained center would select one column, so a second selection would show 8
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "the same box selects nothing again");
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box + Vec2::new(0.01, 0.0)).unwrap(), 8, "a moved box selects again");
}
#[test]
fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() {
let mut session = fill_session(primitives::udim_plane());
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]);
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
let every_triangle = session.mesh.triangle_count();
assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002");
}
#[test]
fn a_2d_click_skips_a_triangle_with_collapsed_uvs() {
// A face left unmapped (all corners at UV 0,0) comes first, as imports often leave them
let plane = primitives::plane(2.0, 1);
let mut positions = vec![Vec3::ZERO, Vec3::X, Vec3::Z];
let mut uvs = vec![Vec2::ZERO; 3];
positions.extend(&plane.positions);
uvs.extend(&plane.uvs);
let indices = [0, 1, 2].into_iter().chain(plane.indices.iter().map(|index| index + 3)).collect();
let mut session = fill_session(Mesh::from_parts(positions, None, uvs, indices, "m").unwrap());
assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1);
session.update();
assert!(filled_at(&session, Vec2::new(0.2, 0.7)), "the triangle under the cursor, not the collapsed one");
}
#[test]
fn a_failing_drag_reports_once_and_records_nothing() {
let mut session = fill_session(primitives::plane(2.0, 4));
let history = session.history_labels().len();
session.selected.clear();
assert!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.5, 1.0)).is_err());
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 0, "the rest of the drag fills nothing");
assert_eq!(session.end_polygon_fill_box(), 0);
assert_eq!(session.history_labels().len(), history);
}
#[test]
fn an_edit_during_a_drag_records_the_fill_first() {
let mut session = fill_session(primitives::plane(2.0, 4));
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
let layers = session.doc.project.layers.len();
crate::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap();
assert!(session.polygon_fill_drag.is_none());
let labels = session.history_labels();
assert_eq!(labels.get(labels.len().wrapping_sub(2)).map(String::as_str), Some("Polygon fill"), "{labels:?}");
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap();
assert_eq!(session.doc.project.layers.len(), layers + 1, "a later drag move keeps the added layer");
}
#[test]
fn a_zero_size_box_on_whole_pixels_selects_what_is_under_it() {
let mut session = fill_session(primitives::cube(1.0));
let center = (session.viewport * 0.5).floor();
assert!(session.polygon_fill_box(center, center, session.viewport).unwrap() > 0);
}
#[test]
fn a_camera_move_mid_drag_keeps_one_drag() {
let mut session = fill_session(primitives::cube(1.0));
let viewport = session.viewport;
let history = session.history_labels().len();
let (corner, opposite) = (viewport * 0.4, viewport * 0.6);
let before_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
session.camera.zoom(0.5);
let after_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
session.end_polygon_fill_box();
assert_ne!(before_zoom, after_zoom, "the same box selects again from the new camera");
assert_eq!(session.history_labels().len(), history + 1, "a wheel zoom during the drag doesn't split it");
}
#[test]
fn pixel_spans_include_both_edges_and_nothing_outside() {
assert_eq!(super::pixel_span(2.0, 2.0, 100), 2..3, "a zero-size span on a whole pixel");
assert_eq!(super::pixel_span(-50.0, -10.0, 100), 0..0, "before the first pixel");
assert_eq!(super::pixel_span(120.0, 150.0, 100), 100..100, "past the last pixel");
assert_eq!(super::pixel_span(-5.0, 500.0, 100), 0..100);
}
#[test]
fn a_2d_click_fills_the_triangle_under_it() {
let mut session = fill_session(primitives::plane(2.0, 1));
assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1);
session.update();
assert!(filled_at(&session, Vec2::new(0.2, 0.7)));
assert!(!filled_at(&session, Vec2::new(0.7, 0.2)), "the quad's other triangle stays");
assert!(session.polygon_fill_uv(Vec2::new(1.5, 0.5)).is_err(), "nothing outside the UVs");
}
}
+42
View File
@@ -0,0 +1,42 @@
//! A polygon fill box being dragged: what it filled so far and what it needs to refill each move.
use std::collections::{BTreeMap, BTreeSet};
use texturecraft_core::LayerId;
use texturecraft_geom::OrbitCamera;
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::EyeDepth;
use texturecraft_texel::TileImage;
use crate::session::{Document, StackTarget};
use crate::triangle_partition::TrianglePartition;
/// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends
pub(crate) struct PolygonFillDrag {
/// The texture set it fills
pub ts: usize,
/// The selected layer and content, mask or effect being filled
pub target: (Option<LayerId>, StackTarget),
/// The 3D view's size in pixels, or None for a drag in the 2D view
pub viewport: Option<Vec2>,
/// The camera [`PolygonFillDrag::points`] and [`PolygonFillDrag::depth`] were made with
pub camera: OrbitCamera,
/// The document before the drag, refilled each time the selection changes
pub before: Document,
/// The quick mask's coverage before the drag, when the drag paints the quick mask
pub quick_mask_before: Option<BTreeMap<usize, TileImage>>,
/// Each vertex where the box sees it: viewport pixels in the 3D view (None behind the camera), texture coordinates in the 2D view
pub points: Vec<Option<Vec2>>,
/// What the camera sees (3D view, visible polygons only)
pub depth: Option<EyeDepth>,
/// What the fill mode fills together
pub fill_groups: TrianglePartition,
/// The polygons the box tests, when they differ from the fill groups
pub polygons: Option<TrianglePartition>,
/// The triangles filled so far
pub filled: BTreeSet<u32>,
/// The box last shown, lowest corner first: an unmoved box isn't selected again
pub last_box: Option<(Vec2, Vec2)>,
/// The fill failed (reported once): the rest of the drag fills nothing
pub failed: bool,
}
+44 -71
View File
@@ -1,14 +1,8 @@
//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or
//! baked maps (generators that need mesh maps are approximated with world-space noise), and
//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked
//! preview ([`crate::mask_preview`]).
//! Cheap shelf previews on a unit sphere: plain materials and library filters (smart ones use [`crate::orb_preview`])
use rayon::prelude::*;
use texturecraft_compose::pattern::{Coords, procedural, world_noise};
use texturecraft_core::{
Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project,
Projection, Source, TextureSet, blend1,
};
use texturecraft_compose::pattern::{Coords, procedural};
use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet};
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::materials::{Builder, build};
@@ -50,54 +44,13 @@ fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> {
}
}
/// Approximate generator: mesh-map signals become world noise (a sphere has no edges or cavities).
fn generator(g: &Generator, c: &Coords) -> f32 {
let dir = Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y);
let wear = (world_noise(c.pos, 3.0, 91) - 0.5) * 2.2;
let cavity = (world_noise(c.pos, 3.0, 57) - 0.3).clamp(0.0, 1.0) + (1.0 - c.nrm.y) * 0.1;
let s = match g.kind {
GeneratorKind::Position => c.pos.dot(dir) * 0.5 + 0.5,
GeneratorKind::Direction => c.nrm.dot(dir) * 0.5 + 0.5,
GeneratorKind::EdgeWear => wear,
GeneratorKind::Curvature => 0.5 + wear * 0.5,
GeneratorKind::AmbientOcclusion => 1.0 - cavity,
_ => cavity,
};
// Same thresholding as the compositor.
let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s };
let soft = g.softness.max(1e-3);
let t = ((s - (1.0 - g.level.clamp(0.0, 1.0) - soft)) / (2.0 * soft)).clamp(0.0, 1.0);
let v = t * t * (3.0 - 2.0 * t);
if g.invert { 1.0 - v } else { v }
}
fn mask(m: &Mask, c: &Coords) -> f32 {
if !m.enabled {
return 1.0;
}
let mut v = if m.background == MaskBackground::White { 1.0 } else { 0.0 };
for e in m.effects.iter().filter(|e| e.visible) {
let val = match &e.kind {
EffectKind::Fill { source: s, projection } => source(s, projection, c).map(|x| x[0]),
EffectKind::Generator(g) => Some(generator(g, c)),
EffectKind::Levels(l) => Some(l.apply(v)),
EffectKind::Filter(Filter::Invert) => Some(1.0 - v),
_ => None,
};
if let Some(val) = val {
let blended = if matches!(e.kind, EffectKind::Levels(_) | EffectKind::Filter(_)) { val } else { blend1(e.blend, v, val) };
v += (blended - v) * e.opacity.clamp(0.0, 1.0);
}
}
v.clamp(0.0, 1.0)
}
const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height];
/// Preview of built-in material `id` (None for an unknown id).
/// Preview of plain material `id` (None for an unknown id or a smart material, whose masks need mesh maps)
pub fn material(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
let plain = crate::materials::find(id).filter(|found| !found.smart)?;
let mut project = Project::new("preview", "");
let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).ok()?;
let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, plain.id).ok()?;
// Pixels evaluate independently and big previews take long on one core
let normals: Vec<_> = sphere_normals(size).collect();
@@ -106,23 +59,24 @@ pub fn material(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
.map(|normal| {
let at = coords(normal?);
let mut values = CHANNELS.map(Channel::default_value);
for layer in layers.iter().filter(|l| l.visible) {
for layer in layers.iter().filter(|layer| layer.visible) {
// Plain materials are unmasked fills
let LayerKind::Fill(fill) = &layer.kind else { continue };
let coverage = layer.mask.as_ref().map_or(1.0, |m| mask(m, &at));
for (value, channel) in values.iter_mut().zip(CHANNELS) {
let layer_value = fill.sources.get(&channel).and_then(|s| source(s, &fill.projection, &at));
let layer_value = fill.sources.get(&channel).and_then(|channel_source| source(channel_source, &fill.projection, &at));
if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) {
let weight = coverage * blend.opacity.clamp(0.0, 1.0);
*value = [0, 1, 2].map(|k| value[k] + (layer_value[k] - value[k]) * weight);
let weight = blend.opacity.clamp(0.0, 1.0);
*value = [0, 1, 2].map(|component| value[component] + (layer_value[component] - value[component]) * weight);
}
}
}
let [base, metal, rough, height] = values;
Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] })
let [base, metallic, roughness, height] = values;
Some(Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] })
})
.collect();
Some(samples)
}
@@ -196,21 +150,40 @@ pub fn filter(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
mod tests {
use super::*;
/// Whether every value of `sample` is finite
fn finite(sample: &Sample) -> bool {
sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite)
}
#[test]
fn previews_cover_the_sphere_with_finite_values() {
for m in crate::materials::MATERIALS {
let px = material(m.id, 16).unwrap_or_else(|| panic!("{}", m.id));
let center = px[8 * 16 + 8].unwrap_or_else(|| panic!("{}", m.id));
assert!(center.base.iter().chain([&center.metallic, &center.roughness, &center.height]).all(|v| v.is_finite()), "{}", m.id);
assert!(px[0].is_none(), "corners are outside the sphere");
let size = 16;
for built_in in crate::materials::MATERIALS {
let id = built_in.id;
if built_in.smart {
assert!(material(id, size).is_none(), "{id}: smart materials preview on the orb");
continue;
}
let mut project = Project::new("preview", "");
let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).unwrap();
assert!(layers.iter().all(|layer| layer.mask.is_none()), "{id}: the sphere preview shows no masks");
let pixels = material(id, size).unwrap_or_else(|| panic!("{id}"));
let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}"));
assert!(finite(&center), "{id}");
assert!(pixels[0].is_none(), "corners are outside the sphere");
}
assert!(material("nope", 8).is_none() && filter("nope", 8).is_none());
for f in crate::filter_lib::FILTERS {
let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id));
let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id));
assert!(center.base.iter().chain([&center.roughness, &center.height]).all(|v| v.is_finite()), "{}", f.id);
assert!(material("nope", size).is_none() && filter("nope", size).is_none());
let size = 24;
for library_filter in crate::filter_lib::FILTERS {
let id = library_filter.id;
let pixels = filter(id, size).unwrap_or_else(|| panic!("{id}"));
let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}"));
assert!(finite(&center), "{id}");
}
let (plain, warped) = (filter("levels", 24).unwrap(), filter("warp", 24).unwrap());
let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap());
assert!(plain != warped, "the warp shows in its preview");
}
}
+44 -31
View File
@@ -11,6 +11,7 @@ use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer};
use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas};
use texturecraft_texel::DilationMap;
use crate::fill_mode::FillMode;
use crate::{EngineError, Result};
/// Padding (texels) applied to composites for display.
@@ -160,15 +161,6 @@ impl ViewMode {
}
}
/// Polygon fill granularity.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum FillMode {
#[default]
Triangle,
UvIsland,
Mesh,
}
/// A screen-pinned image for the Projection tool (a stencil).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StencilState {
@@ -210,6 +202,12 @@ pub struct ToolState {
/// Gray painted into masks.
pub mask_value: f32,
pub fill_mode: FillMode,
/// How a polygon fill box decides which polygons it selects
#[serde(default)]
pub fill_hit_test: crate::fill_hit_test::FillHitTest,
/// Polygon fill boxes in the 3D view select only the polygons the camera sees
#[serde(default = "default_fill_visible_only")]
pub fill_visible_only: bool,
/// Stencil used by the Projection tool.
#[serde(default)]
pub stencil: Option<StencilState>,
@@ -231,6 +229,10 @@ fn default_smudge_strength() -> f32 {
0.5
}
fn default_fill_visible_only() -> bool {
true
}
/// What the Clone tool copies (the clone source modes).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum CloneFrom {
@@ -260,6 +262,8 @@ impl Default for ToolState {
enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(),
mask_value: 1.0,
fill_mode: FillMode::Triangle,
fill_hit_test: Default::default(),
fill_visible_only: default_fill_visible_only(),
stencil: None,
smudge_strength: default_smudge_strength(),
clone_source: None,
@@ -291,8 +295,8 @@ pub(crate) struct ActiveStroke {
pub canvas: StrokeCanvas,
/// Camera visibility for 3D strokes (None for strokes in the 2D view).
pub depth: Option<Arc<EyeDepth>>,
/// 2D view strokes: last UV point and the distance carried to the next stamp.
pub uv: Option<(Option<Vec2>, f32)>,
/// 2D view strokes: where the stroke is between samples.
pub uv: Option<crate::uv_stroke_state::UvStrokeState>,
pub camera: OrbitCamera,
pub viewport: Vec2,
pub values: BTreeMap<Channel, [f32; 3]>,
@@ -356,6 +360,8 @@ pub struct Session {
/// The last stroke's camera visibility buffer: reused while the camera, view size and mesh
/// are unchanged, so back-to-back dabs start instantly.
pub(crate) depth_cache: Option<DepthCache>,
/// The polygon fill box being dragged
pub(crate) polygon_fill_drag: Option<crate::polygon_fill_drag::PolygonFillDrag>,
/// The user's export presets (kept when another project opens).
pub export_presets: crate::preset_cmds::UserPresets,
/// The user's project templates (kept when another project opens).
@@ -405,6 +411,7 @@ impl Session {
revision: 1,
log: Vec::new(),
depth_cache: None,
polygon_fill_drag: None,
export_presets: Default::default(),
templates: Default::default(),
})
@@ -489,22 +496,24 @@ impl Session {
self.edit_merging(label, self.merge_edits, f)
}
/// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the
/// same label (a drag in the viewport is one step however many updates it makes).
pub fn edit_merging<T>(&mut self, label: &str, merge: bool, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
/// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the same label (a viewport drag is one step however many updates it makes).
pub fn edit_merging<T>(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
// A box fill under way becomes its own step first, so this edit isn't written over or folded into it
self.end_polygon_fill_box();
let before = self.doc.clone();
let result = f(self).and_then(|v| match self.doc.project.instance_cycle() {
let result = change(self).and_then(|value| match self.doc.project.instance_cycle() {
Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))),
None => Ok(v),
None => Ok(value),
});
match result {
Ok(v) => {
Ok(value) => {
self.record(label, before, merge);
Ok(v)
Ok(value)
}
Err(e) => {
Err(error) => {
self.doc = before;
Err(e)
Err(error)
}
}
}
@@ -530,7 +539,7 @@ impl Session {
/// Mark dirty every texture set whose composite differs between `other` and the current
/// document (after an edit, undo or redo).
fn invalidate_changed(&mut self, other: &Document) {
pub(crate) fn invalidate_changed(&mut self, other: &Document) {
self.follow_uv_layouts(&other.project);
self.sync_caches();
let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::<Vec<_>>();
@@ -625,25 +634,29 @@ impl Session {
}
pub fn undo(&mut self) -> Result<String> {
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
self.cancel_stroke();
// An edited path would otherwise repaint over the restored document.
self.end_polygon_fill_box();
self.stop_path_edit();
let (label, doc) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
let now = std::mem::replace(&mut self.doc, doc);
self.after_history(&now);
self.redo.push((label.clone(), now));
let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
let current = std::mem::replace(&mut self.doc, restored);
self.after_history(&current);
self.redo.push((label.clone(), current));
self.sync_images();
Ok(label)
}
pub fn redo(&mut self) -> Result<String> {
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
self.cancel_stroke();
// An edited path would otherwise repaint over the restored document.
self.end_polygon_fill_box();
self.stop_path_edit();
let (label, doc) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
let now = std::mem::replace(&mut self.doc, doc);
self.after_history(&now);
self.undo.push((label.clone(), now));
let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
let current = std::mem::replace(&mut self.doc, restored);
self.after_history(&current);
self.undo.push((label.clone(), current));
self.sync_images();
Ok(label)
}
+3 -3
View File
@@ -62,14 +62,14 @@ pub fn find(name: &str) -> Option<&'static SmartMask> {
const UP: [f32; 3] = [0.0, 1.0, 0.0];
/// A mesh-map generator with explicit threshold, softness and noise breakup.
/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes).
pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind {
EffectKind::Generator(Generator { level, softness, noise_amount: noise, ..Generator::new(kind) })
EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, ..Generator::new(kind) })
}
/// A direction or position generator (`invert` flips the result).
pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind {
EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, ..Generator::new(kind) })
EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) })
}
/// A triplanar grayscale pattern fill.
+83 -20
View File
@@ -7,7 +7,9 @@ use texturecraft_geom::glam::Vec2;
use texturecraft_paint::{Alignment, BrushAlpha, alphas};
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp};
use crate::session::{CloneFrom, CloneSource, FillMode, Tool};
use crate::fill_hit_test::FillHitTest;
use crate::fill_mode::FillMode;
use crate::session::{CloneFrom, CloneSource, Tool};
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
@@ -69,7 +71,16 @@ pub fn specs() -> Vec<CommandSpec> {
always,
clone_source
),
cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|uvIsland|mesh}", always, fill_mode),
cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|polygon|uvIsland|mesh}", always, fill_mode),
cmd!(
"tool.fillSelection",
"Polygon fill selection",
[],
None,
"{hitTest?: intersection|containedCenter (a box selects polygons it touches, or whose center it holds), visibleOnly?: bool (3D view boxes select only what the camera sees)}",
always,
fill_selection
),
cmd!("tool.stroke", "Paint stroke", [], None, "{points: [[x,y],...] viewport pixels, viewport?: [w,h]} — paints with the current tool", always, stroke),
cmd!(
"tool.strokeUv",
@@ -80,16 +91,26 @@ pub fn specs() -> Vec<CommandSpec> {
always,
stroke_uv
),
cmd!("tool.click", "Tool click", [], None, "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab", always, click),
cmd!(
"tool.click",
"Tool click",
[],
None,
"{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}",
always,
click
),
cmd!("tool.state", "Tool state", [], None, "{}", always, |s, _| Ok(serde_json::to_value(&s.tool).unwrap_or(Value::Null))),
]
}
pub(crate) fn set_tool(s: &mut Session, t: Tool) -> Result<Value> {
s.cancel_stroke();
s.tool.tool = t;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "tool": t.id() }))
pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result<Value> {
session.cancel_stroke();
// A box fill under way keeps what it filled as one undo step
session.end_polygon_fill_box();
session.tool.tool = tool;
session.revision = session.revision.wrapping_add(1);
Ok(json!({ "tool": tool.id() }))
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
@@ -319,13 +340,29 @@ fn clone_source(s: &mut Session, p: &Value) -> Result<Value> {
Ok(serde_json::to_value(s.tool.clone_source).unwrap_or(Value::Null))
}
fn fill_mode(s: &mut Session, p: &Value) -> Result<Value> {
s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") {
fn fill_mode(session: &mut Session, params: &Value) -> Result<Value> {
session.tool.fill_mode = match strp(params, "mode").unwrap_or("triangle") {
"triangle" => FillMode::Triangle,
"polygon" => FillMode::Polygon,
"uvIsland" | "island" => FillMode::UvIsland,
"mesh" => FillMode::Mesh,
other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))),
};
Ok(Value::Null)
}
fn fill_selection(session: &mut Session, params: &Value) -> Result<Value> {
match strp(params, "hitTest") {
None => {}
Some("intersection") => session.tool.fill_hit_test = FillHitTest::Intersection,
Some("containedCenter") => session.tool.fill_hit_test = FillHitTest::ContainedCenter,
Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))),
}
if let Some(visible_only) = boolp(params, "visibleOnly") {
session.tool.fill_visible_only = visible_only;
}
Ok(Value::Null)
}
@@ -369,22 +406,48 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "stamps": stamps }))
}
fn click(s: &mut Session, p: &Value) -> Result<Value> {
let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) };
let vp = viewport_of(s, p);
let out = match s.tool.tool {
Tool::PolygonFill => json!({ "triangles": s.polygon_fill(Vec2::new(x, y), vp)? }),
fn click(session: &mut Session, params: &Value) -> Result<Value> {
if session.tool.tool == Tool::PolygonFill
&& let Some(triangles) = polygon_fill_click(session, params)?
{
session.update();
return Ok(json!({ "triangles": triangles }));
}
let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) };
let point = Vec2::new(x, y);
let viewport = viewport_of(session, params);
let out = match session.tool.tool {
Tool::PolygonFill => json!({ "triangles": session.polygon_fill(point, viewport)? }),
Tool::ColorPicker => {
let v = s.color_pick(Vec2::new(x, y), vp)?;
json!(v.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::<serde_json::Map<_, _>>())
let picked = session.color_pick(point, viewport)?;
json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::<serde_json::Map<_, _>>())
}
Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, Vec2::new(x, y), vp)?,
_ => json!({ "stamps": s.stroke_points(&[Vec2::new(x, y)], vp)? }),
Tool::GeometryMask => crate::instance_cmds::toggle_part_at(session, point, viewport)?,
_ => json!({ "stamps": session.stroke_points(&[point], viewport)? }),
};
s.update();
session.update();
Ok(out)
}
/// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point
fn polygon_fill_click(session: &mut Session, params: &Value) -> Result<Option<usize>> {
let screen_box = (f32p(params, "x0"), f32p(params, "y0"), f32p(params, "x1"), f32p(params, "y1"));
let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some());
let filled = match (pair(params, "uv0"), pair(params, "uv1"), pair(params, "uv"), screen_box) {
(Some(corner), Some(opposite), ..) => session.polygon_fill_box_uv(corner.into(), opposite.into())?,
_ if given(&["uv0", "uv1"]) => return Err(bad("tool.click", "a UV box needs `uv0` and `uv1` as [u, v]")),
(_, _, Some(uv), _) => session.polygon_fill_uv(uv.into())?,
_ if given(&["uv"]) => return Err(bad("tool.click", "a 2D view point needs `uv` as [u, v]")),
(.., (Some(x0), Some(y0), Some(x1), Some(y1))) => session.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(session, params))?,
_ if given(&["x0", "y0", "x1", "y1"]) => return Err(bad("tool.click", "a screen box needs numbers `x0`, `y0`, `x1` and `y1`")),
_ => return Ok(None),
};
Ok(Some(filled))
}
fn stroke_uv(s: &mut Session, p: &Value) -> Result<Value> {
let points = points_param("tool.strokeUv", p, "points")?.ok_or_else(|| bad("tool.strokeUv", "`points` must be an array of [u, v]"))?;
let tiles = s.stroke_uv_points(&points)?;
+123
View File
@@ -0,0 +1,123 @@
//! Triangles of one material grouped into the pieces polygon fill selects and fills.
use std::collections::HashMap;
use std::hash::Hash;
use texturecraft_geom::Mesh;
/// A material's triangles split into groups joined across shared edges
pub struct TrianglePartition {
/// The triangles of each group
pub groups: Vec<Vec<u32>>,
/// The index of each triangle's group
group_of: HashMap<u32, usize>,
}
impl TrianglePartition {
/// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both
pub fn new<K: Eq + Hash + Clone>(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec<K>) -> TrianglePartition {
// Each triangle's edges once, in mesh order so the groups come out the same every time
let triangles: Vec<u32> = mesh.triangles_of(material).map(|triangle| triangle as u32).collect();
let position_of: HashMap<u32, usize> = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect();
let mut edge_lists: Vec<Vec<K>> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect();
let mut by_edge: HashMap<K, Vec<u32>> = HashMap::new();
for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) {
for edge in triangle_edges {
by_edge.entry(edge.clone()).or_default().push(*triangle);
}
}
let mut groups = Vec::new();
let mut group_of = HashMap::with_capacity(triangles.len());
for &start in &triangles {
if group_of.contains_key(&start) {
continue;
}
let mut members = Vec::new();
let mut stack = vec![start];
group_of.insert(start, groups.len());
while let Some(triangle) = stack.pop() {
members.push(triangle);
let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default();
// Visit a shared edge once, including when many collapsed faces share the same key
for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.remove(edge).into_iter().flatten()) {
if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(neighbour) {
entry.insert(groups.len());
stack.push(neighbour);
}
}
}
groups.push(members);
}
TrianglePartition { groups, group_of }
}
/// The index in [`TrianglePartition::groups`] of the group holding `triangle` (None for a triangle of another material)
pub fn index_of(&self, triangle: u32) -> Option<usize> {
self.group_of.get(&triangle).copied()
}
/// The group holding `triangle` (None for a triangle of another material)
pub fn group(&self, triangle: u32) -> Option<&[u32]> {
self.index_of(triangle).and_then(|group| self.groups.get(group)).map(Vec::as_slice)
}
}
#[cfg(test)]
mod tests {
use texturecraft_geom::primitives;
use super::*;
#[test]
fn triangles_sharing_a_key_join_one_group() {
let mesh = primitives::plane(2.0, 2);
let singles = TrianglePartition::new(&mesh, 0, |_, _| Vec::<u32>::new());
let pairs = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 2]);
assert_eq!(singles.groups.len(), mesh.triangle_count());
assert_eq!(pairs.groups.len(), mesh.triangle_count() / 2);
assert_eq!(pairs.group(3).map(<[u32]>::len), Some(2));
assert_eq!(pairs.group(99), None);
}
#[test]
fn shared_edges_keep_transitive_neighbors() {
let mesh = primitives::plane(2.0, 4);
let groups = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 4, (triangle + 1) / 4]);
assert_eq!(groups.groups.len(), 1);
assert_eq!(groups.group(0).unwrap().len(), mesh.triangle_count());
}
#[test]
#[ignore = "release performance measurement"]
fn benchmark_shared_edges() {
use std::hint::black_box;
use std::time::Instant;
for subdivisions in [32, 64] {
let mesh = primitives::plane(2.0, subdivisions);
for collapsed in [false, true] {
let mut times = Vec::new();
for _ in 0..5 {
let start = Instant::now();
let groups = TrianglePartition::new(&mesh, 0, |mesh, triangle| {
if collapsed {
vec![(0, 0); 3]
} else {
let [first, second, third] = mesh.tri(triangle).unwrap();
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
}
});
assert_eq!(groups.groups.len(), 1);
black_box(groups);
times.push(start.elapsed().as_secs_f64() * 1000.0);
}
times.sort_by(f64::total_cmp);
eprintln!("{} triangles, collapsed={collapsed}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[2], times[0], times[4]);
}
}
}
}
+14
View File
@@ -0,0 +1,14 @@
//! Where a stroke in the 2D view is between pointer samples.
use texturecraft_geom::glam::Vec2;
/// A 2D view stroke's progress: its last point, the distance carried to the next stamp and the stamps so far.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct UvStrokeState {
/// The last sample's texture coordinates (None before the first sample).
pub last: Option<Vec2>,
/// Distance from the last stamp to the last sample, at most one stamp step.
pub carry: f32,
/// Stamps so far: the next stamp's seed, so noise alphas don't repeat from sample to sample.
pub stamps: u32,
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
+309
View File
@@ -0,0 +1,309 @@
//! Color selection effects: editing their ID colors and picking them from the ID mesh map
use serde_json::{Value, json};
use texturecraft_engine::core::{EffectKind, LayerId};
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
const TOP_LEFT_ID: [u8; 3] = [200, 30, 10];
const TOP_RIGHT_ID: [u8; 3] = [10, 200, 30];
const BOTTOM_ID: [u8; 3] = [30, 10, 200];
const NO_PART: [f32; 3] = [0.0, 0.0, 0.0];
fn session() -> Session {
let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
session.viewport = Vec2::new(400.0, 400.0);
session.camera.yaw = 0.0;
session.camera.pitch = 0.0;
session.update();
session
}
/// An 8×8 ID map: two parts on the top half, one on the bottom half
fn id_map_png() -> Vec<u8> {
let image = image::RgbaImage::from_fn(8, 8, |x, y| {
let [red, green, blue] = match (x < 4, y < 4) {
(true, true) => TOP_LEFT_ID,
(false, true) => TOP_RIGHT_ID,
_ => BOTTOM_ID,
};
image::Rgba([red, green, blue, 255])
});
let mut bytes = Vec::new();
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
bytes
}
fn stored(id: [u8; 3]) -> [f32; 3] {
id.map(|channel| channel as f32 / 255.0)
}
fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
assert!(actual.iter().zip(expected).all(|(channel, wanted)| (channel - wanted).abs() < 1e-3), "{actual:?} vs {expected:?}");
}
/// A fill layer masked by a color selection that selects no part yet: (layer, effect)
fn masked_layer(session: &mut Session, with_id_map: bool) -> (LayerId, LayerId) {
if with_id_map {
let image = session.import_resource_bytes("id.png", id_map_png()).unwrap();
execute(session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap();
}
let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap()["layer"].as_u64().unwrap());
execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap();
let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id;
(layer, effect)
}
fn colors(session: &Session, effect: LayerId) -> Vec<[f32; 3]> {
match &session.doc.project.effect(effect).unwrap().1.kind {
EffectKind::ColorSelection { colors, .. } => colors.clone(),
other => panic!("not a color selection: {other:?}"),
}
}
#[test]
fn a_color_picked_on_the_mesh_is_selected_where_it_was_picked() {
let mut session = session();
let (layer, effect) = masked_layer(&mut session, true);
let center = Vec2::new(200.0, 200.0);
let hit = session.pick(center, session.viewport).unwrap();
let (width, height) = session.caches[0].size;
let texel = ((hit.uv.x * width as f32) as u32, (hit.uv.y * height as f32) as u32);
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0], "nothing selected before the pick");
let picked = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": center.x, "y": center.y})).unwrap();
assert_eq!(picked["index"], json!(1));
assert_eq!(colors(&session, effect).len(), 2);
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]);
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(colors(&session, effect), vec![NO_PART], "one undo step");
}
#[test]
fn a_uv_pick_adds_the_color_there_or_replaces_one() {
let mut session = session();
let (_, effect) = masked_layer(&mut session, true);
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap();
assert_close(colors(&session, effect)[1], stored(TOP_LEFT_ID));
let replaced = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.75, 0.75], "index": 0})).unwrap();
assert_eq!(replaced["index"], json!(0));
let picked = colors(&session, effect);
assert_eq!(picked.len(), 2);
assert_close(picked[0], stored(BOTTOM_ID));
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(colors(&session, effect)[0], NO_PART, "one undo step");
}
#[test]
fn the_colors_param_replaces_the_list_in_one_undo_step() {
let mut session = session();
let (_, effect) = masked_layer(&mut session, false);
let edited = [stored(TOP_LEFT_ID), stored(TOP_RIGHT_ID)];
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": edited, "tolerance": 0.2})).unwrap();
assert_eq!(colors(&session, effect), edited.to_vec());
let Some((_, found)) = session.doc.project.effect(effect) else { panic!("effect gone") };
assert!(matches!(found.kind, EffectKind::ColorSelection { tolerance, .. } if tolerance == 0.2));
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(colors(&session, effect), vec![NO_PART]);
}
#[test]
fn bad_colors_are_refused_and_change_nothing() {
let mut session = session();
let (_, effect) = masked_layer(&mut session, false);
let refused = [json!([]), json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")];
for colors_param in &refused {
assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors_param})).is_err(), "{colors_param}");
}
assert_eq!(colors(&session, effect), vec![NO_PART]);
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1e300, 0.5, 0.5]]})).unwrap();
assert_eq!(colors(&session, effect), vec![[1.0, 0.5, 0.5]], "out-of-range values clamp to 0..1");
}
#[test]
fn picking_explains_what_is_missing() {
let mut session = session();
let (layer, effect) = masked_layer(&mut session, false);
let pick = |session: &mut Session, params: Value| execute(session, "effect.colorSelection.pick", &params).unwrap_err().to_string();
assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5]})).contains("no ID map"));
let image = session.import_resource_bytes("id.png", id_map_png()).unwrap();
execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap();
assert!(pick(&mut session, json!({"effect": effect.0, "x": 1, "y": 1})).contains("nothing under that point"));
assert!(pick(&mut session, json!({"effect": effect.0, "uv": [1.5, 0.5]})).contains("outside"));
assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5], "index": 7})).contains("no color 7"));
assert!(pick(&mut session, json!({"effect": effect.0})).contains("`x` and `y`"));
let fill = execute(&mut session, "effect.add.fill", &json!({"layer": layer.0})).unwrap()["effect"].as_u64().unwrap();
assert!(pick(&mut session, json!({"effect": fill, "uv": [0.5, 0.5]})).contains("not a color selection"));
assert_eq!(colors(&session, effect), vec![NO_PART]);
}
#[test]
fn hostile_params_never_crash_the_color_selection_commands() {
let mut session = session();
let (_, effect) = masked_layer(&mut session, true);
let hostile = [
json!({"effect": effect.0, "x": f32::MAX, "y": -1e30, "viewport": [0, 0]}),
json!({"effect": effect.0, "uv": [f64::MAX, -1e300], "index": u64::MAX}),
json!({"effect": effect.0, "uv": [0.5], "colors": [[f64::MAX, -f64::MAX, 0.0]]}),
json!({"effect": effect.0, "uv": "x", "colors": {"r": 1}}),
json!({"effect": u64::MAX, "uv": [0.5, 0.5]}),
];
for params in &hostile {
let _ = execute(&mut session, "effect.colorSelection.pick", params);
let _ = execute(&mut session, "effect.set", params);
session.update();
}
}
#[test]
fn a_hidden_texture_set_does_not_block_a_pick_behind_it() {
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
session.viewport = Vec2::new(400.0, 400.0);
session.update();
let set_named = |name: &str| session.doc.project.texture_sets.iter().position(|set| set.name == name).unwrap();
let (base, ball) = (set_named("Base"), set_named("Ball"));
execute(&mut session, "textureSet.select", &json!({"ts": base})).unwrap();
let (_, effect) = masked_layer(&mut session, true);
let pick_at = |session: &mut Session, y: f32| execute(session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": 200, "y": y}));
let ball_in_front = |session: &Session, y: f32| {
session.pick(Vec2::new(200.0, y), session.viewport).is_some_and(|hit| session.texture_set_of_material(hit.material) == Some(ball))
};
// Down the middle until a pixel where the hidden ball covers the base: the pick reads the base
execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": false})).unwrap();
let mut covered = None;
for y in (200..400).map(|y| y as f32) {
if ball_in_front(&session, y) && pick_at(&mut session, y).is_ok() {
covered = Some(y);
break;
}
}
let y = covered.expect("a pixel where the ball covers the base");
assert_eq!(colors(&session, effect).len(), 2);
execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": true})).unwrap();
assert!(pick_at(&mut session, y).unwrap_err().to_string().contains("another texture set"), "a shown ball still blocks it");
}
#[test]
fn malformed_replacement_indices_are_rejected_without_editing() {
let mut session = session();
let (_, effect) = masked_layer(&mut session, true);
let history = session.history_labels();
for index in [json!(-1), json!(0.4), json!("0"), json!(true), json!([])] {
let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": index}));
assert!(result.is_err(), "invalid index {index} was accepted: {result:?}");
assert_eq!(colors(&session, effect), vec![NO_PART]);
assert_eq!(session.history_labels(), history);
}
}
#[test]
fn the_color_limit_rejects_additions_but_allows_replacement() {
let mut session = session();
let (_, effect) = masked_layer(&mut session, true);
let full = vec![NO_PART; 256];
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": full})).unwrap();
let history = session.history_labels();
let project = session.doc.project.clone();
for params in [json!({"effect": effect.0, "uv": [0.25, 0.25]}), json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 256})] {
assert!(execute(&mut session, "effect.colorSelection.pick", &params).is_err());
assert_eq!(colors(&session, effect), full);
assert_eq!(session.history_labels(), history);
}
assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; 257], "name": "Invalid edit"})).is_err());
assert_eq!(session.history_labels(), history);
assert_eq!(session.doc.project, project, "invalid colors also roll back edits to other fields");
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 255})).unwrap();
assert_eq!(colors(&session, effect).len(), 256);
assert_close(colors(&session, effect)[255], stored(TOP_LEFT_ID));
}
#[test]
fn inspect_exposes_the_selected_colors_and_tolerance() {
let mut session = session();
let (layer, effect) = masked_layer(&mut session, true);
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap();
execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.25})).unwrap();
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap();
let layer = inspected["layers"].as_array().unwrap().iter().find(|found| found["id"] == layer.0).unwrap();
let found = &layer["mask"]["effects"][0];
assert_eq!(found["colors"], json!(colors(&session, effect)));
assert_eq!(found["tolerance"], json!(0.25));
}
#[test]
fn picks_use_the_working_texel_on_a_smaller_uv_tile() {
let mut session = Session::new_project("UV tiles", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap();
for tile in [1001, 1002] {
session.import_resource_bytes(&format!("id.{tile}.png"), id_map_png()).unwrap();
}
execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": "id.1001.png"})).unwrap();
let (layer, effect) = masked_layer(&mut session, false);
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.0})).unwrap();
let size = session.doc.project.texture_sets[0].size();
let uv = [0.625, 0.25];
let texel = ((uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32);
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0]);
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": uv})).unwrap();
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]);
let before = colors(&session, effect);
let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.9, 0.8]}));
assert!(result.unwrap_err().to_string().contains("no ID color"), "unused tile space has no sample");
assert_eq!(colors(&session, effect), before);
}
#[test]
#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"]
fn benchmark_color_selection_edits() {
use std::time::{Duration, Instant};
const SAMPLES: u32 = 10;
for resolution in [256, 1024] {
let started = Instant::now();
let mut session = Session::new_project("benchmark", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, resolution).unwrap();
let (_, effect) = masked_layer(&mut session, true);
session.update();
let construction = started.elapsed();
for count in [1, 256] {
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; count]})).unwrap();
session.update();
let params = json!({"effect": effect.0, "uv": [0.25, 0.25], "index": count - 1});
let (mut command_time, mut composite_time) = (Duration::ZERO, Duration::ZERO);
for _ in 0..SAMPLES {
let started = Instant::now();
execute(&mut session, "effect.colorSelection.pick", &params).unwrap();
command_time += started.elapsed();
let started = Instant::now();
session.update();
composite_time += started.elapsed();
execute(&mut session, "edit.undo", &Value::Null).unwrap();
session.update();
}
println!(
"{resolution}x{resolution}, {count} colors, {SAMPLES} samples: construction {construction:.3?}; pick {:.3?}; composite {:.3?}; session memory {} bytes",
command_time / SAMPLES,
composite_time / SAMPLES,
session.memory().total()
);
}
}
}
+172
View File
@@ -0,0 +1,172 @@
//! Swapping a filter effect's type in place through `effect.set {filter}`
use serde_json::{Value, json};
use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, StackTarget, execute};
/// A sphere project with its default layer selected
fn session() -> Session {
Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 256).unwrap()
}
/// Runs effect-adding `command` and returns the new effect, which it selects
fn add(s: &mut Session, command: &str, params: Value) -> LayerId {
execute(s, command, &params).unwrap();
let StackTarget::Effect(added) = s.target else { panic!("adding an effect selects it: {:?}", s.target) };
added
}
/// A copy of effect `id`
fn effect(s: &Session, id: LayerId) -> Effect {
s.doc.project.effect(id).unwrap().1.clone()
}
/// Ids of the selected layer's content effects, bottom first
fn content_order(s: &Session) -> Vec<LayerId> {
let layer = s.selected_layer().unwrap();
s.doc.project.layer(layer).unwrap().content_effects.iter().map(|effect| effect.id).collect()
}
#[test]
fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() {
let mut s = session();
let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
let above = add(&mut s, "effect.add.filter", json!({"filter": "grayscale", "target": "content"}));
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4, "visible": false})).unwrap();
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap();
let blur = effect(&s, swapped);
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind);
assert_eq!(blur.name, "Blur", "a default name follows the new filter");
assert_eq!((blur.blend, blur.opacity, blur.visible), (BlendMode::Multiply, 0.4, false));
assert_eq!(content_order(&s), vec![below, swapped, above]);
}
#[test]
fn swapping_a_filter_keeps_a_name_the_user_chose() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content", "name": "Flip"}));
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold"})).unwrap();
assert_eq!(effect(&s, id).name, "Flip");
}
#[test]
fn one_undo_restores_the_old_filter() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "threshold", "target": "content", "level": 0.3}));
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "sharpen"})).unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
let restored = effect(&s, id);
assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level }) if level == 0.3), "{:?}", restored.kind);
assert_eq!(restored.name, "Threshold");
}
#[test]
fn a_mask_refuses_a_content_only_filter() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "grayscale"})).unwrap_err();
assert!(err.to_string().contains("not on masks"), "{err}");
assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert)));
}
#[test]
fn a_mask_filter_swaps_in_place_on_the_mask() {
let mut s = session();
let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
let above = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4})).unwrap();
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur"})).unwrap();
let blur = effect(&s, swapped);
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind);
assert_eq!((blur.name.as_str(), blur.blend, blur.opacity), ("Blur", BlendMode::Multiply, 0.4));
let layer = s.selected_layer().unwrap();
let mask_order: Vec<LayerId> = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect();
assert_eq!(mask_order, vec![below, swapped, above]);
}
#[test]
fn naming_the_current_filter_edits_it_in_place() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "blur", "target": "content", "radius": 5.0}));
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur", "radius": 9.0})).unwrap();
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).unwrap();
let blur = effect(&s, id);
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind);
}
#[test]
fn a_name_given_with_the_swap_wins() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold", "name": "Edges"})).unwrap();
let swapped = effect(&s, id);
assert!(matches!(swapped.kind, EffectKind::Filter(Filter::Threshold { .. })), "{:?}", swapped.kind);
assert_eq!(swapped.name, "Edges");
}
#[test]
fn a_refused_swap_changes_nothing_and_adds_no_undo_step() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap();
let before = effect(&s, id);
for refused in [
json!({"effect": id.0, "filter": "grayscale"}),
json!({"effect": id.0, "filter": "nope"}),
json!({"effect": id.0, "filter": "levels"}),
json!({"effect": id.0, "filter": "colorBalance", "shadows": "not a color"}),
] {
assert!(execute(&mut s, "effect.set", &refused).is_err(), "{refused}");
}
assert_eq!(effect(&s, id), before);
// The last step is still the blend, opacity and name edit
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(effect(&s, id).name, "Invert");
}
#[test]
fn only_filter_effects_swap_and_only_to_filters() {
let mut s = session();
let levels = add(&mut s, "effect.add.levels", json!({"target": "content"}));
let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect");
assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "nope"})).is_err(), "an unknown filter on levels");
assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill");
assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err());
assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert)));
}
#[test]
fn invalid_swap_parameters_report_effect_set_and_preserve_history() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
let before = effect(&s, id);
let history = s.history_labels();
let error = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "colorBalance", "shadows": "invalid", "name": "Changed"})).unwrap_err();
assert!(matches!(error, texturecraft_engine::EngineError::BadParams { ref cmd, .. } if cmd == "effect.set"), "{error}");
assert_eq!(effect(&s, id), before);
assert_eq!(s.history_labels(), history);
}
File renamed without changes.
@@ -0,0 +1,57 @@
use texturecraft_engine::bake::{HighPolyReach, RayStart, VertexReach, high_poly_missed};
use texturecraft_engine::geom::glam::Vec3;
fn vertex(height: f32) -> Option<VertexReach> {
Some(VertexReach {
low_position: Vec3::ZERO,
start: RayStart::Distance { up: Vec3::Y, scale: 1.0 },
high_position: Vec3::new(0.0, height, 0.0),
high_facing: Vec3::Y,
name_matches: true,
})
}
fn reach(vertices: Vec<Option<VertexReach>>) -> Option<HighPolyReach> {
Some(HighPolyReach { vertices, cage_units: 1.0, ignore_backface: false })
}
fn sets() -> Vec<Option<HighPolyReach>> {
vec![None, reach(vec![vertex(0.5), vertex(-0.25), None, None, None]), reach(vec![None, None, vertex(0.5), vertex(-0.25), None])]
}
const DISTANCES: [(f32, f32); 3] = [(9.0, 9.0), (0.25, 0.25), (0.5, 0.125)];
#[test]
fn each_owning_set_uses_its_own_frontal_and_rear_distances() {
let reaches = sets();
assert_eq!(high_poly_missed(&reaches, &DISTANCES, None, 6), vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
let expanded = [(9.0, 9.0), (0.5, 0.25), (0.5, 0.25)];
assert_eq!(high_poly_missed(&reaches, &expanded, None, 6), vec![0.0; 6]);
}
#[test]
fn selected_set_filter_leaves_other_sets_unmarked() {
let reaches = sets();
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
for only_set in [0, reaches.len(), usize::MAX] {
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![0.0; 6]);
}
}
#[test]
fn missing_reach_or_distances_leave_vertices_unmarked() {
assert_eq!(high_poly_missed(&[], &DISTANCES, None, 6), vec![0.0; 6]);
assert_eq!(high_poly_missed(&sets(), &[], None, 6), vec![0.0; 6]);
assert_eq!(high_poly_missed(&sets(), &DISTANCES[..2], None, 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
assert_eq!(high_poly_missed(&sets(), &DISTANCES, None, 1), vec![1.0]);
assert!(high_poly_missed(&sets(), &DISTANCES, None, 0).is_empty());
}
#[test]
fn a_reached_vertex_is_not_overridden_by_a_later_set() {
let reaches = [reach(vec![vertex(0.5)]), reach(vec![vertex(0.5)])];
let distances = [(0.5, 0.0), (0.25, 0.0)];
assert_eq!(high_poly_missed(&reaches, &distances, None, 1), vec![0.0]);
assert_eq!(high_poly_missed(&reaches, &distances, Some(1), 1), vec![1.0]);
}
File renamed without changes.
+27
View File
@@ -0,0 +1,27 @@
//! One integration-test executable avoids linking the same dependencies for every feature.
//! Keep feature tests in their own modules; the standalone session.rs target remains available.
mod bake;
mod bake_resolution;
mod bake_settings;
mod bake_tiles;
mod color_selection;
mod content_effects;
mod export_colour_space;
mod filter_swap;
mod filters;
mod high_poly_missed;
mod instances;
mod materialcraft_link;
mod materialx;
mod materialx_import;
mod meshmap_import;
mod painter_gaps;
mod path_tool;
mod perf;
mod polygon_fill;
mod project_recovery;
mod sample;
mod tools;
mod udim;
mod uv_strokes;
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+88
View File
@@ -0,0 +1,88 @@
//! Polygon fill drag transitions preserve already painted targets
use serde_json::json;
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::{glam::Vec2, primitives};
use texturecraft_engine::{Session, execute};
#[test]
fn changing_layers_during_a_box_drag_preserves_the_first_fill() {
let mut session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
let first = session.selected_layer().unwrap();
execute(&mut session, "layer.add.paint", &json!({})).unwrap();
let second = session.selected_layer().unwrap();
execute(&mut session, "layer.select", &json!({"layer": first.0})).unwrap();
let history = session.history_labels().len();
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
execute(&mut session, "layer.select", &json!({"layer": second.0})).unwrap();
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.4, 1.0)).unwrap();
session.end_polygon_fill_box();
assert!(session.doc.pixels.layer(first, Channel::BaseColor).is_some(), "the first layer keeps its fill");
assert!(session.doc.pixels.layer(second, Channel::BaseColor).is_some(), "the new target receives the next fill");
assert_eq!(session.history_labels().len(), history + 2, "each target has its own undo step");
session.undo().unwrap();
assert!(session.doc.pixels.layer(first, Channel::BaseColor).is_some());
assert!(session.doc.pixels.layer(second, Channel::BaseColor).is_none());
}
#[test]
fn changing_from_content_to_mask_during_a_box_drag_preserves_content() {
let mut session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
let layer = session.selected_layer().unwrap();
execute(&mut session, "mask.add.black", &json!({})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "content"})).unwrap();
let history = session.history_labels().len();
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap();
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.4, 1.0)).unwrap();
session.end_polygon_fill_box();
assert!(session.doc.pixels.layer(layer, Channel::BaseColor).is_some(), "switching to the mask keeps the content fill");
assert_eq!(session.history_labels().len(), history + 2);
session.undo().unwrap();
assert!(session.doc.pixels.layer(layer, Channel::BaseColor).is_some());
assert!(session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.is_empty());
}
#[test]
#[ignore = "release performance measurement"]
fn benchmark_live_box_fill() {
use std::hint::black_box;
use std::time::Instant;
for (name, mesh) in [("ball", primitives::material_ball()), ("sphere", primitives::sphere(1.0, 512, 256))] {
let triangles = mesh.triangle_count();
let mut session = Session::new_project("benchmark", mesh, "test", None, 1024).unwrap();
let viewport = Vec2::new(1920.0, 1080.0);
let start = Instant::now();
session.drag_polygon_fill_box(viewport * 0.4, viewport * 0.6, viewport).unwrap();
let first_ms = start.elapsed().as_secs_f64() * 1000.0;
let mut times = Vec::new();
for step in 1..=12 {
let radius = 0.1 + step as f32 * 0.02;
let start = Instant::now();
black_box(session.drag_polygon_fill_box(viewport * (0.5 - radius), viewport * (0.5 + radius), viewport).unwrap());
times.push(start.elapsed().as_secs_f64() * 1000.0);
}
let (corner, opposite) = (viewport * 0.16, viewport * 0.84);
session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
let start = Instant::now();
for _ in 0..1000 {
black_box(session.drag_polygon_fill_box(corner, opposite, viewport).unwrap());
}
let unchanged_us = start.elapsed().as_secs_f64() * 1000.0;
session.end_polygon_fill_box();
let start = Instant::now();
session.update();
let composite_ms = start.elapsed().as_secs_f64() * 1000.0;
times.sort_by(f64::total_cmp);
let memory = session.memory();
eprintln!(
"{name}: {triangles} triangles, first={first_ms:.3} ms, growing median={:.3} ms max={:.3} ms, unchanged mean={unchanged_us:.3} us, composite={composite_ms:.3} ms, pixels={} bytes composites={} bytes cache={} bytes",
times[6], times[11], memory.pixels, memory.composites, memory.cache
);
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
+105
View File
@@ -0,0 +1,105 @@
//! Stamping along 2D view strokes: long segments, the carry between samples and per-stamp seeds
use serde_json::json;
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
/// Texture size: 1e-4 UV is 0.0256 texels
const RESOLUTION: u32 = 256;
/// A sphere project painting red with `brush` settings (the UI's 0–100 scales)
fn red_brush_session(brush: serde_json::Value) -> Session {
let mut session = Session::new_project("UV strokes", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap();
execute(&mut session, "tool.paint", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
execute(&mut session, "tool.brush", &brush).unwrap();
session
}
/// The composite base color at texel (`x`, `y`)
fn color_at(session: &Session, x: u32, y: u32) -> [f32; 3] {
session.caches[0].composite.value(Channel::BaseColor, x, y)
}
/// Whether the composite base color at (`u`, `v`) is the painted red
fn red_at(session: &Session, u: f32, v: f32) -> bool {
let color = color_at(session, (u * RESOLUTION as f32) as u32, (v * RESOLUTION as f32) as u32);
color[0] > 0.85 && color[1] < 0.15
}
#[test]
fn a_segment_longer_than_one_stamp_batch_paints_to_its_end() {
// 1e-4 UV between stamps: 0.9 UV is 9000 stamps, past the 4096 of one batch
let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90}));
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.05, 0.5], [0.95, 0.5]]})).unwrap();
for u in [0.1, 0.5, 0.9] {
assert!(red_at(&session, u, 0.5), "painted at u = {u}");
}
}
#[test]
fn a_segment_cut_at_the_stamp_limit_does_not_stamp_the_next_one_backwards() {
// 1e-4 UV between stamps: the 20.5 UV first segment needs 205k stamps and is cut off before reaching the texture
let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90}));
execute(&mut session, "tool.strokeUv", &json!({"points": [[-20.0, 0.5], [0.5, 0.5], [0.6, 0.5]]})).unwrap();
assert!(red_at(&session, 0.55, 0.5), "the last segment is painted");
assert!(!red_at(&session, 0.3, 0.5), "nothing is stamped behind the last segment's start");
}
#[test]
fn each_sample_of_a_stroke_stamps_new_noise() {
// A 32 texel radius at full spacing: one stamp per sample, each centred on a texel at u = 0.25 and 0.5
let mut session = red_brush_session(json!({"size": 25.0, "spacing": 100.0, "alpha": "cloud"}));
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.25, 0.5], [0.5, 0.5]]})).unwrap();
let patch = |centre_x: u32| -> Vec<[f32; 3]> {
(centre_x - 16..centre_x + 16).flat_map(|x| (112..144).map(move |y| (x, y))).map(|(x, y)| color_at(&session, x, y)).collect()
};
let first_stamp = patch(64);
assert!(first_stamp.iter().any(|color| color[0] > 0.5 && color[1] < 0.5), "the first stamp painted");
assert_ne!(first_stamp, patch(128), "the second sample's stamp has its own noise");
}
#[test]
fn a_hostile_segment_stays_bounded() {
// The finest brush the settings allow: 2e-5 UV between stamps
let mut session = red_brush_session(json!({"size": 0.2, "spacing": 1.0}));
let result = execute(&mut session, "tool.strokeUv", &json!({"points": [[0.0, 0.0], [1e9, 1e9]]}));
assert!(result.is_ok(), "{result:?}");
}
#[test]
fn a_light_pressure_diagonal_reaches_the_far_corner() {
let mut session = red_brush_session(json!({"size": 0.2, "minSize": 0.0, "spacing": 1.0, "hardness": 90}));
// Half pressure reaches the minimum stamp step: a diagonal needs about 142k stamps
session.begin_stroke_uv([0.0, 0.0].into(), 0.5).unwrap();
session.continue_stroke_uv([1.0, 1.0].into(), 0.5);
session.end_stroke().unwrap();
session.update();
assert!(red_at(&session, 0.5, 0.5), "the diagonal paints through its midpoint");
assert!(red_at(&session, 0.97, 0.97), "the diagonal reaches the far corner");
}
#[test]
fn decreasing_pressure_does_not_stamp_behind_a_turn() {
let mut session = red_brush_session(json!({"size": 10.0, "minSize": 0.0, "spacing": 100.0, "hardness": 90}));
session.begin_stroke_uv([0.25, 0.5].into(), 1.0).unwrap();
session.continue_stroke_uv([0.33, 0.5].into(), 1.0);
session.continue_stroke_uv([0.33, 0.6].into(), 0.1);
session.end_stroke().unwrap();
session.update();
assert!(red_at(&session, 0.33, 0.55), "the new segment is painted");
assert!(!red_at(&session, 0.33, 0.45), "a smaller step must not stamp behind the turn");
}
+66
View File
@@ -105,6 +105,42 @@ 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();
}
}
}
}
/// A small project still gets the production bake defaults; only panic_hunt overrides them.
#[test]
fn new_project_keeps_full_resolution_bake_defaults() {
let s = session();
assert!(!s.doc.project.texture_sets.is_empty());
for texture_set in &s.doc.project.texture_sets {
assert_eq!(texture_set.resolution, 256);
assert_eq!(texture_set.bake, texturecraft_engine::core::BakeSettings::default());
assert_eq!(texture_set.bake.common.output_size(), (2048, 2048));
assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 64);
}
}
/// Every command must return Ok or Err — never panic — for hostile params.
#[test]
fn panic_hunt() {
@@ -122,6 +158,11 @@ fn panic_hunt() {
}
for p in &hostile {
let mut s = session();
// Match the 256px fixture: otherwise empty/irrelevant bake.run params perform
// repeated 2048px default bakes. Keep every input, ray count and fresh session.
for texture_set in &mut s.doc.project.texture_sets {
texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R256;
}
let _ = execute(&mut s, spec.id, p);
s.update();
}
@@ -380,3 +421,28 @@ fn background_resizes_match_the_command_and_keep_later_edits() {
b.update();
assert_eq!(b.caches[0].size, (512, 512));
}
#[test]
fn curvature_generators_take_a_mode_and_detail_sizes() {
let mut state = session();
execute(&mut state, "layer.add.fill", &json!({})).unwrap();
execute(&mut state, "mask.add.black", &Value::Null).unwrap();
let added = execute(&mut state, "effect.add.generator", &json!({"generator": "curvature", "mode": "cavities"})).unwrap();
let effect = added["effect"].clone();
execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5]})).unwrap();
let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspect.contains(r#""mode":"Cavities""#) && inspect.contains(r#""sizes":[0.0,0.0,0.0,1.0,0.0,0.0,0.5]"#), "{inspect}");
let too_few = execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [1.0, 0.5]}));
assert!(too_few.is_err(), "sizes takes one weight per detail size");
let not_numbers = execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [1.0, "a", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}));
assert!(not_numbers.is_err(), "a size that isn't a number is rejected, not skipped");
let unknown = execute(&mut state, "effect.set", &json!({"effect": effect, "mode": "ridges"}));
assert!(unknown.is_err(), "unknown modes are rejected");
let wrong_type = execute(&mut state, "effect.set", &json!({"effect": effect, "mode": 1, "level": 0.1}));
assert!(wrong_type.is_err(), "a mode must be a string and an invalid edit must be rejected");
let dirt = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "mode": "edges"}));
assert!(dirt.is_err(), "only curvature generators have a mode");
assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged");
}
+93
View File
@@ -4,6 +4,9 @@ use glam::{Vec2, Vec3, Vec4};
use crate::{GeomError, Result};
/// An edge by the bits of its two end positions, the lower one first
type EdgePositions = ([u32; 3], [u32; 3]);
/// A contiguous index range drawn with one material.
#[derive(Clone, Debug, PartialEq)]
pub struct SubMesh {
@@ -107,6 +110,47 @@ impl Mesh {
.collect()
}
/// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`
pub fn uv_seam_edges(&self) -> Vec<Vec<(u32, u32)>> {
// Signed zero denotes the same position on either side of an imported seam
let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() });
let mut seams = vec![Vec::new(); self.materials.len().max(1)];
// Match across materials before grouping the lines for texture-set visibility
let mut sides: std::collections::HashMap<EdgePositions, Vec<(u32, u32, usize)>> = std::collections::HashMap::new();
for material in 0..seams.len() {
for triangle in self.triangles_of(material) {
let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue };
for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] {
let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { continue };
let (from_bits, to_bits) = (bits(*from_position), bits(*to_position));
let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) };
sides.entry(edge).or_default().push((pair.0, pair.1, material));
}
}
}
let uv = |index: u32| self.uvs.get(index as usize).copied();
for pairs in sides.into_values() {
let Some(&(first_from, first_to, _)) = pairs.first() else { continue };
if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) {
for (from, to, material) in pairs {
if let Some(edges) = seams.get_mut(material) {
edges.push((from.min(to), from.max(to)));
}
}
}
}
for edges in &mut seams {
edges.sort_unstable();
edges.dedup();
}
seams
}
/// Material of triangle `t`.
pub fn material_of(&self, t: usize) -> Option<usize> {
let idx = (t * 3) as u32;
@@ -433,6 +477,55 @@ mod tests {
assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges");
}
#[test]
fn uv_seams_are_where_the_uv_layout_splits() {
let mesh = quad();
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam");
// Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut
let mut seam = mesh.clone();
seam.positions.push(seam.positions[0]);
seam.normals.push(seam.normals[0]);
seam.tangents.push(seam.tangents[0]);
seam.uvs.push(Vec2::new(0.9, 0.9));
seam.indices[3] = 4;
assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
// The same split with the same UV is a hard edge, not a seam
let mut hard = seam.clone();
hard.uvs[4] = hard.uvs[0];
assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]);
}
#[test]
fn uv_seams_join_positions_with_opposite_signed_zero() {
let mut mesh = quad();
mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0));
mesh.normals.push(mesh.normals[0]);
mesh.tangents.push(mesh.tangents[0]);
mesh.uvs.push(Vec2::new(0.9, 0.9));
mesh.indices[3] = 4;
assert_eq!(mesh.positions[0], mesh.positions[4]);
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
}
#[test]
fn uv_seams_between_materials_belong_to_both_materials() {
let mut mesh = quad();
mesh.positions.push(mesh.positions[0]);
mesh.normals.push(mesh.normals[0]);
mesh.tangents.push(mesh.tangents[0]);
mesh.uvs.push(Vec2::new(0.9, 0.9));
mesh.indices[3] = 4;
mesh.materials.push("second".into());
mesh.submeshes[0].count = 3;
mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 });
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]);
mesh.uvs[4] = mesh.uvs[0];
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam");
}
#[test]
fn validate_catches_bad_indices() {
let mut m = quad();
+1 -1
View File
@@ -201,7 +201,7 @@ const ORB_CUT: f32 = 0.8;
/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius.
const ORB_PANEL_VALLEY: f32 = 0.88;
/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base.
/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base
/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly
/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys
/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it
+1 -1
View File
@@ -29,4 +29,4 @@ pub use path::{Lasso, spline};
pub use pickup::{Pickup, PickupMode};
pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv};
pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick};
pub use visibility::EyeDepth;
pub use visibility::{EyeDepth, screen_point};
+123 -48
View File
@@ -2,11 +2,26 @@
//! rendered once at the start of a stroke.
use rayon::prelude::*;
use texturecraft_geom::glam::{Mat4, Vec3, Vec4};
use texturecraft_geom::{Mesh, OrbitCamera};
use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4};
use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera};
const BAND: usize = 16;
/// Largest buffer side in pixels.
const MAX_SIZE: u32 = 4096;
/// Clip-space w below which a vertex counts as behind the camera.
pub const MIN_CLIP_W: f32 = 1e-5;
/// Screen area (pixels squared) below which a triangle is skipped as degenerate.
const MIN_SCREEN_AREA: f32 = 1e-9;
/// How far outside a triangle (in barycentric weight) a pixel center may lie and still count, closing seams between neighbours.
const EDGE_TOLERANCE: f32 = 1e-4;
/// [`EyeDepth::bias`] as a fraction of the scene radius.
const BIAS_PER_RADIUS: f32 = 0.004;
/// Distance from the eye to the nearest surface per screen pixel (f32::MAX where empty).
#[derive(Clone, Debug)]
pub struct EyeDepth {
@@ -15,73 +30,133 @@ pub struct EyeDepth {
pub view_proj: Mat4,
pub eye: Vec3,
pub dist: Vec<f32>,
/// The nearest triangle per screen pixel ([`NO_TRI`] where empty); empty unless rendered with [`EyeDepth::render_with_triangles`].
pub triangle: Vec<u32>,
/// Tolerance in world units (≈ 0.4% of the scene radius).
pub bias: f32,
}
/// Where `position` lands in a `size` pixel view through `view_proj` (origin top-left), or None behind the camera.
pub fn screen_point(view_proj: Mat4, position: Vec3, size: Vec2) -> Option<Vec2> {
let clip = view_proj * position.extend(1.0);
(clip.w > MIN_CLIP_W).then(|| Vec2::new(clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5) * size)
}
impl EyeDepth {
/// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at 4096).
/// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]), without [`EyeDepth::triangle`].
pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth {
let (w, h) = (width.clamp(1, 4096), height.clamp(1, 4096));
let aspect = w as f32 / h as f32;
let vp = camera.view_proj(aspect);
Self::rasterize(mesh, camera, width, height, false)
}
/// [`EyeDepth::render`] that also records the nearest triangle per pixel in [`EyeDepth::triangle`].
pub fn render_with_triangles(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth {
Self::rasterize(mesh, camera, width, height, true)
}
/// The eye-distance buffer, plus the nearest triangle per pixel when `record_triangles` is set.
fn rasterize(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool) -> EyeDepth {
// Capping storage dimensions must not change the camera's projection
let projection = camera.proj(width.max(1) as f32 / height.max(1) as f32);
let view = camera.view();
let view_proj = projection * view;
let depth_key = |view_depth: f32| if camera.ortho { view_depth } else { -view_depth.recip() };
let inverse_projection = projection.inverse();
let clip_depth = |z: f32| {
let point = inverse_projection * Vec4::new(0.0, 0.0, z, 1.0);
depth_key(-point.z / point.w)
};
let depth_range = clip_depth(0.0)..=clip_depth(1.0);
let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE));
let size = Vec2::new(width as f32, height as f32);
let eye = camera.eye();
// Project every vertex once.
let clip: Vec<Vec4> = mesh.positions.iter().map(|p| vp * p.extend(1.0)).collect();
let screen: Vec<Option<(f32, f32)>> =
clip.iter().map(|c| (c.w > 1e-5).then(|| ((c.x / c.w * 0.5 + 0.5) * w as f32, (0.5 - c.y / c.w * 0.5) * h as f32))).collect();
let dist_v: Vec<f32> = mesh.positions.iter().map(|p| p.distance(eye)).collect();
let bands = (h as usize).div_ceil(BAND);
let mut bins: Vec<Vec<u32>> = vec![Vec::new(); bands];
for t in 0..mesh.triangle_count() {
let Some([a, b, c]) = mesh.tri(t) else { continue };
let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue };
let y0 = pa.1.min(pb.1).min(pc.1).floor().max(0.0);
let y1 = pa.1.max(pb.1).max(pc.1).ceil().min(h as f32);
if y1 <= y0 || !y0.is_finite() || !y1.is_finite() {
// Brush depth closes seams, but expanding triangle IDs can expose hidden faces at silhouettes
let edge_tolerance = if record_triangles { 0.0 } else { EDGE_TOLERANCE };
let screen: Vec<Option<Vec2>> = mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect();
// Inverse view depth is affine in perspective and avoids the precision loss of normalized clip depth
let vertex_depth: Vec<f32> = mesh.positions.iter().map(|position| depth_key(-(view * position.extend(1.0)).z)).collect();
// Bin each triangle into the bands of rows it covers
let mut bands: Vec<Vec<u32>> = vec![Vec::new(); (height as usize).div_ceil(BAND)];
for triangle in 0..mesh.triangle_count() {
let Some([first, second, third]) = mesh.tri(triangle) else { continue };
let (Some(Some(first)), Some(Some(second)), Some(Some(third))) = (screen.get(first), screen.get(second), screen.get(third)) else { continue };
let top = first.y.min(second.y).min(third.y).floor().max(0.0);
let bottom = first.y.max(second.y).max(third.y).ceil().min(size.y);
if bottom <= top || !top.is_finite() || !bottom.is_finite() {
continue;
}
let (b0, b1) = (y0 as usize / BAND, ((y1 as usize).saturating_sub(1)) / BAND);
for bin in bins.iter_mut().take(b1 + 1).skip(b0) {
bin.push(t as u32);
let (first_band, last_band) = (top as usize / BAND, (bottom as usize).saturating_sub(1) / BAND);
for band in bands.iter_mut().take(last_band + 1).skip(first_band) {
band.push(triangle as u32);
}
}
let mut dist = vec![f32::MAX; (w * h) as usize];
dist.par_chunks_mut(BAND * w as usize).enumerate().for_each(|(bi, rows)| {
let row0 = bi * BAND;
let nrows = rows.len() / w as usize;
for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) {
let Some([a, b, c]) = mesh.tri(t as usize) else { continue };
let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue };
let (da, db, dc) = (dist_v[a], dist_v[b], dist_v[c]);
let area = (pb.0 - pa.0) * (pc.1 - pa.1) - (pb.1 - pa.1) * (pc.0 - pa.0);
if area.abs() < 1e-9 {
let mut dist = vec![f32::MAX; (width * height) as usize];
let mut triangle = if record_triangles { vec![NO_TRI; (width * height) as usize] } else { Vec::new() };
let band_len = BAND * width as usize;
let mut triangle_bands: Vec<Option<&mut [u32]>> = triangle.chunks_mut(band_len).map(Some).collect();
triangle_bands.resize_with(dist.len().div_ceil(band_len), || None);
dist.par_chunks_mut(band_len).zip(triangle_bands.into_par_iter()).enumerate().for_each(|(band, (band_dist, mut band_triangles))| {
let first_row = band * BAND;
let row_count = band_dist.len() / width as usize;
for &candidate in bands.get(band).map(Vec::as_slice).unwrap_or(&[]) {
let Some(corners) = mesh.tri(candidate as usize) else { continue };
let [first, second, third] = corners;
let (Some(Some(first_point)), Some(Some(second_point)), Some(Some(third_point))) = (screen.get(first), screen.get(second), screen.get(third))
else {
continue;
};
let corner_depth = corners.map(|vertex| vertex_depth.get(vertex).copied().unwrap_or(f32::MAX));
let area = (*second_point - *first_point).perp_dot(*third_point - *first_point);
if area.abs() < MIN_SCREEN_AREA {
continue;
}
let x0 = pa.0.min(pb.0).min(pc.0).floor().max(0.0) as usize;
let x1 = (pa.0.max(pb.0).max(pc.0).ceil().min(w as f32)) as usize;
let y0 = (pa.1.min(pb.1).min(pc.1).floor().max(row0 as f32)) as usize;
let y1 = (pa.1.max(pb.1).max(pc.1).ceil().min((row0 + nrows) as f32)) as usize;
for y in y0.max(row0)..y1 {
for x in x0..x1.min(w as usize) {
let (px, py) = (x as f32 + 0.5, y as f32 + 0.5);
let w0 = ((pb.0 - px) * (pc.1 - py) - (pb.1 - py) * (pc.0 - px)) / area;
let w1 = ((pc.0 - px) * (pa.1 - py) - (pc.1 - py) * (pa.0 - px)) / area;
let w2 = 1.0 - w0 - w1;
if w0 < -1e-4 || w1 < -1e-4 || w2 < -1e-4 {
let low = first_point.min(*second_point).min(*third_point).floor();
let high = first_point.max(*second_point).max(*third_point).ceil();
let (left, right) = (low.x.max(0.0) as usize, (high.x.min(size.x) as usize).min(width as usize));
let (top, bottom) = (low.y.max(first_row as f32) as usize, high.y.min((first_row + row_count) as f32) as usize);
for row in top.max(first_row)..bottom {
for column in left..right {
let sample = Vec2::new(column as f32 + 0.5, row as f32 + 0.5);
let first_weight = (*third_point - *second_point).perp_dot(sample - *second_point) / area;
let second_weight = (*first_point - *third_point).perp_dot(sample - *third_point) / area;
let third_weight = 1.0 - first_weight - second_weight;
if first_weight < -edge_tolerance || second_weight < -edge_tolerance || third_weight < -edge_tolerance {
continue;
}
let d = w0 * da + w1 * db + w2 * dc;
if let Some(slot) = rows.get_mut((y - row0) * w as usize + x)
&& d < *slot
let depth = first_weight * corner_depth[0] + second_weight * corner_depth[1] + third_weight * corner_depth[2];
let at = (row - first_row) * width as usize + column;
if let Some(slot) = band_dist.get_mut(at)
&& depth_range.contains(&depth)
&& depth < *slot
{
*slot = d;
*slot = depth;
if let Some(nearest) = band_triangles.as_deref_mut().and_then(|triangles| triangles.get_mut(at)) {
*nearest = candidate;
}
}
}
}
}
// Convert only the winning depths to eye distances for brush visibility queries
for (row, distances) in band_dist.chunks_mut(width as usize).enumerate() {
let view_y = (1.0 - (first_row as f32 + row as f32 + 0.5) / size.y * 2.0) / projection.y_axis.y;
for (column, distance) in distances.iter_mut().enumerate().filter(|(_, distance)| **distance != f32::MAX) {
let view_x = ((column as f32 + 0.5) / size.x * 2.0 - 1.0) / projection.x_axis.x;
let radial_squared = view_x * view_x + view_y * view_y;
*distance = if camera.ortho { (radial_squared + *distance * *distance).sqrt() } else { (radial_squared + 1.0).sqrt() / -*distance };
}
}
});
EyeDepth { width: w, height: h, view_proj: vp, eye, dist, bias: mesh.radius() * 0.004 }
EyeDepth { width, height, view_proj, eye, dist, triangle, bias: mesh.radius() * BIAS_PER_RADIUS }
}
/// Whether world point `p` is visible (not hidden behind other geometry, inside the view).
+99
View File
@@ -0,0 +1,99 @@
//! Visibility agrees with the surface under each pixel
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{Mesh, OrbitCamera};
use texturecraft_paint::EyeDepth;
#[test]
fn a_large_front_triangle_occludes_a_small_rear_triangle() {
let positions = vec![
Vec3::new(-4.0, -4.0, 0.0),
Vec3::new(4.0, -4.0, 0.0),
Vec3::new(0.0, 4.0, 0.0),
Vec3::new(-0.5, -0.5, -1.0),
Vec3::new(0.5, -0.5, -1.0),
Vec3::new(0.0, 0.5, -1.0),
];
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 6], (0..6).collect(), "m").unwrap();
for ortho in [false, true] {
let camera = OrbitCamera { pitch: 0.0, ortho, ..Default::default() };
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 128, 128);
assert_eq!(depth.triangle[64 * 128 + 64], 0, "orthographic: {ortho}");
assert!(!depth.visible(Vec3::new(0.0, 0.0, -1.0)), "the rear face is hidden");
assert!(depth.visible(Vec3::ZERO), "the front face is visible");
}
}
#[test]
#[ignore = "release performance measurement"]
fn benchmark_eye_depth() {
use std::hint::black_box;
use std::time::Instant;
use texturecraft_geom::primitives;
for (name, mesh) in [("ball", primitives::material_ball()), ("sphere", primitives::sphere(1.0, 512, 256))] {
let mut camera = OrbitCamera::default();
let (low, high) = mesh.bounds();
camera.frame(low, high);
for triangles in [false, true] {
let mut times = Vec::new();
for iteration in 0..12 {
let start = Instant::now();
black_box(if triangles { EyeDepth::render_with_triangles(&mesh, &camera, 960, 540) } else { EyeDepth::render(&mesh, &camera, 960, 540) });
if iteration >= 2 {
times.push(start.elapsed().as_secs_f64() * 1000.0);
}
}
times.sort_by(f64::total_cmp);
eprintln!("{name}: {} triangles, record={triangles}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[5], times[0], times[9]);
}
}
}
#[test]
fn perspective_depth_matches_ray_intersections() {
use texturecraft_geom::Bvh;
let positions = vec![Vec3::new(-3.0, -2.0, 2.0), Vec3::new(3.0, -2.0, -2.0), Vec3::new(0.0, 3.0, 0.0)];
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap();
let camera = OrbitCamera { pitch: 0.0, ..Default::default() };
let bvh = Bvh::new(&mesh);
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 128, 128);
for (x, y) in [(40, 60), (64, 64), (88, 60)] {
let ndc = Vec2::new((x as f32 + 0.5) / 64.0 - 1.0, 1.0 - (y as f32 + 0.5) / 64.0);
let ray = camera.ray(ndc, 1.0);
let hit = bvh.closest(ray.origin, ray.dir, f32::MAX).unwrap();
let expected = (ray.origin + ray.dir * hit.t).distance(camera.eye());
assert!((depth.dist[y * 128 + x] - expected).abs() < 0.001, "pixel {x},{y}: {} vs {expected}", depth.dist[y * 128 + x]);
}
}
#[test]
fn capped_buffers_keep_the_requested_viewport_aspect() {
let positions = vec![Vec3::new(4.0, -1.0, 0.0), Vec3::new(7.0, -1.0, 0.0), Vec3::new(5.5, 1.0, 0.0)];
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap();
let camera = OrbitCamera { pitch: 0.0, ..Default::default() };
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 8192, 1024);
let point = camera.project(Vec3::new(5.5, 0.0, 0.0), 8.0).unwrap();
let x = ((point.x * 0.5 + 0.5) * depth.width as f32) as usize;
let y = ((0.5 - point.y * 0.5) * depth.height as f32) as usize;
assert_eq!(depth.triangle[y * depth.width as usize + x], 0, "the triangle stays under its viewport position after the buffer is capped");
}
#[test]
fn triangle_ids_do_not_expand_hidden_cube_faces_past_the_silhouette() {
use std::collections::HashSet;
use texturecraft_geom::{NO_TRI, primitives};
let mesh = primitives::cube(1.0);
let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.4, ..Default::default() };
let (low, high) = mesh.bounds();
camera.frame(low, high);
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 400, 400);
let visible: HashSet<_> = depth.triangle.iter().copied().filter(|triangle| *triangle != NO_TRI).collect();
assert_eq!(visible.len(), mesh.triangle_count() / 2, "only the three front faces own screen pixels");
}
+12
View File
@@ -0,0 +1,12 @@
//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly
/// Which parts of the bake setup the 3D view draws
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BakeVisualization {
pub high_poly: bool,
pub cage: bool,
pub uv_seams: bool,
pub low_poly: bool,
/// Draw the cage, seams and low poly of only this texture set
pub only_set: Option<usize>,
}
+9
View File
@@ -0,0 +1,9 @@
/// One texture set's cage on the GPU: three corners per triangle and the wireframe's corner pairs
pub(crate) struct CageGpu {
/// Identifies the corners' order and the edges: a new distance with the same topology only rewrites `corners`
pub(crate) topology: u64,
pub(crate) corners: wgpu::Buffer,
pub(crate) corner_count: u32,
pub(crate) edges: wgpu::Buffer,
pub(crate) edge_index_count: u32,
}
+11
View File
@@ -0,0 +1,11 @@
/// The high poly bake mode draws over the low poly
pub(crate) struct HighPolyGpu {
/// Which mesh the buffers hold
pub(crate) id: u64,
pub(crate) vertices: wgpu::Buffer,
pub(crate) vertex_count: usize,
pub(crate) indices: wgpu::Buffer,
pub(crate) index_count: u32,
/// One value per vertex: 1 where the bake's rays miss it (drawn red), 0 where they reach it
pub(crate) missed: wgpu::Buffer,
}
+5
View File
@@ -13,12 +13,15 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod bake_visualization;
mod cage_gpu;
pub mod displace;
#[cfg(not(target_arch = "wasm32"))]
pub mod gpu_bake;
pub mod gpu_trace;
#[cfg(not(target_arch = "wasm32"))]
pub mod headless;
mod high_poly_gpu;
pub mod ibl;
pub mod mesh_maps;
pub mod readback;
@@ -26,7 +29,9 @@ pub mod renderer;
pub mod set_highlight;
mod subdivide;
pub mod trace;
mod uv_seam_gpu;
pub use bake_visualization::BakeVisualization;
pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale};
pub use set_highlight::SetHighlight;
pub use wgpu;
+348 -91
View File
@@ -30,10 +30,14 @@ use texturecraft_geom::glam::{Mat4, Vec3};
use texturecraft_geom::{Mesh, OrbitCamera};
use texturecraft_texel::TILE;
use crate::bake_visualization::BakeVisualization;
use crate::cage_gpu::CageGpu;
use crate::gpu_trace::{Checked, checked};
use crate::high_poly_gpu::HighPolyGpu;
use crate::ibl;
use crate::set_highlight::SetHighlight;
use crate::subdivide::{self, Vertex};
use crate::uv_seam_gpu::UvSeamGpu;
pub const MSAA: u32 = 4;
pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
@@ -173,6 +177,8 @@ pub struct Shade {
/// Move the surface by the height channel (3D view): a dense copy of the mesh, displaced in
/// the vertex shader at the height-to-normal strength.
pub displacement: bool,
/// Bake mode's high poly, cage and UV seams over the 3D view
pub bake: Option<BakeVisualization>,
}
/// The viewport's subsurface scattering approximation: the diffuse lighting wraps around the
@@ -259,6 +265,7 @@ impl Default for Shade {
sss_blur: None,
refraction: false,
displacement: false,
bake: None,
}
}
}
@@ -530,6 +537,11 @@ pub struct Renderer {
wire3d_pipeline: wgpu::RenderPipeline,
/// The highlighted set's mesh edges, wider and in the highlight color
highlight_pipeline: wgpu::RenderPipeline,
/// Bake mode: the high poly, the cage's faces and wireframe, the low poly's UV seams
bake_high_pipeline: wgpu::RenderPipeline,
cage_pipeline: wgpu::RenderPipeline,
cage_wire_pipeline: wgpu::RenderPipeline,
uv_seam_pipeline: wgpu::RenderPipeline,
bg_pipeline: wgpu::RenderPipeline,
blit_pipeline: wgpu::RenderPipeline,
post_pipeline: wgpu::RenderPipeline,
@@ -563,6 +575,10 @@ pub struct Renderer {
/// accumulation.
content_rev: u64,
mesh: Option<MeshGpu>,
bake_high: Option<HighPolyGpu>,
/// Each texture set's cage, by set index
cages: Vec<Option<CageGpu>>,
uv_seams: Option<UvSeamGpu>,
sets: Vec<SetGpu>,
/// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least
/// as reduced as the device's texture limit needs).
@@ -808,20 +824,31 @@ fn halton(mut i: u32, base: u32) -> f32 {
const CLEAR: wgpu::LoadOp<wgpu::Color> = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT);
/// Depth bias of the shadow map, per unit of surface slope: keeps lit surfaces from shadowing themselves
const SHADOW_SLOPE_BIAS: f32 = 1.5;
/// Anisotropic filtering of the texture sets' sampler
const MAX_ANISOTROPY: u16 = 8;
/// Size of the environment texture before the first environment loads
const PLACEHOLDER_ENV_SIZE: [u32; 2] = [512, 256];
impl Renderer {
/// `target_format`: the format of the pass [`Renderer::blit`] draws into.
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, target_format: wgpu::TextureFormat) -> Renderer {
let shader = |label: &str, source: &str| {
device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) })
};
let module = shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl")));
let module =
shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"), "\n", include_str!("shaders/bake_view.wgsl")));
let util_module = shader("tc_util", include_str!("shaders/util.wgsl"));
let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl")));
let shadow_module = shader("tc_shadow", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/shadow.wgsl")));
let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| {
let bind_group_layout = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries })
};
let globals_bgl = bgl(
let globals_bind_group_layout = bind_group_layout(
"tc_globals",
&[
uniform_entry(0),
@@ -838,44 +865,47 @@ impl Renderer {
fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)),
],
);
// The display textures, the aux texture, the sampler.
// The display textures, the aux texture, the sampler
let textures = DisplayKind::ALL.len() as u32 + 1;
// Displacement reads the height (and the sampler) in the vertex shader.
let height = DisplayKind::ALL.iter().position(|k| *k == DisplayKind::Height).unwrap_or(0) as u32;
// Displacement reads the height (and the sampler) in the vertex shader
let height = DisplayKind::ALL.iter().position(|kind| *kind == DisplayKind::Height).unwrap_or(0) as u32;
let set_entries: Vec<_> = (0..textures)
.map(tex_entry)
.chain(std::iter::once(sampler_entry(textures)))
.map(|mut e| {
if e.binding == height || e.binding == textures {
e.visibility |= wgpu::ShaderStages::VERTEX;
.map(|mut entry| {
if entry.binding == height || entry.binding == textures {
entry.visibility |= wgpu::ShaderStages::VERTEX;
}
e
entry
})
.collect();
let set_bgl = bgl("tc_set", &set_entries);
let refr_bgl = bgl("tc_refr", &[tex_entry(0)]);
let blit_bgl = bgl("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]);
let mip_bgl = bgl("tc_mip", &[tex_entry(0), sampler_entry(1)]);
let fx_bgl = bgl("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]);
let shadow_bgl = bgl("tc_shadow", &[uniform_entry(0)]);
let pl = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| {
let set_bind_group_layout = bind_group_layout("tc_set", &set_entries);
let refraction_bind_group_layout = bind_group_layout("tc_refr", &[tex_entry(0)]);
let blit_bind_group_layout = bind_group_layout("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]);
let mip_bind_group_layout = bind_group_layout("tc_mip", &[tex_entry(0), sampler_entry(1)]);
let effect_bind_group_layout =
bind_group_layout("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]);
let shadow_bind_group_layout = bind_group_layout("tc_shadow", &[uniform_entry(0)]);
let pipeline_layout = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| {
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: groups, immediate_size: 0 })
};
let layout = pl("tc_uv", &[Some(&globals_bgl), Some(&set_bgl)]);
let mesh_layout = pl("tc_mesh", &[Some(&globals_bgl), Some(&set_bgl), Some(&refr_bgl)]);
let bg_layout = pl("tc_bg", &[Some(&globals_bgl)]);
let blit_layout = pl("tc_blit", &[Some(&blit_bgl)]);
let fx_layout = pl("tc_fx", &[Some(&fx_bgl)]);
let shadow_layout = pl("tc_shadow", &[Some(&shadow_bgl), Some(&set_bgl)]);
let vb = [Some(wgpu::VertexBufferLayout {
let layout = pipeline_layout("tc_uv", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout)]);
let mesh_layout = pipeline_layout("tc_mesh", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout), Some(&refraction_bind_group_layout)]);
let background_layout = pipeline_layout("tc_bg", &[Some(&globals_bind_group_layout)]);
let blit_layout = pipeline_layout("tc_blit", &[Some(&blit_bind_group_layout)]);
let effect_layout = pipeline_layout("tc_fx", &[Some(&effect_bind_group_layout)]);
let shadow_layout = pipeline_layout("tc_shadow", &[Some(&shadow_bind_group_layout), Some(&set_bind_group_layout)]);
let vertex_layout = [Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x4, 3 => Float32x2],
})];
// shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode
// (e.g. RGBM) if WebGL2 without float color buffers turns out to matter.
// shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode (e.g. RGBM) if WebGL2 without float color buffers turns out to matter
let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT };
let hdr = |fs, blend| Some((fs, hdr_format, blend));
let hdr_target = |fragment_entry_point, blend| Some((fragment_entry_point, hdr_format, blend));
let always = || Some(depth_state(false, wgpu::CompareFunction::Always));
let mesh_pipeline = pipeline(
device,
@@ -883,8 +913,8 @@ impl Renderer {
&mesh_layout,
&module,
"vs_mesh",
&vb,
hdr("fs_mesh", None),
&vertex_layout,
hdr_target("fs_mesh", None),
MSAA,
Some(depth_state(true, wgpu::CompareFunction::Less)),
);
@@ -894,31 +924,103 @@ impl Renderer {
&mesh_layout,
&module,
"vs_mesh",
&vb,
hdr("fs_opaque", None),
&vertex_layout,
hdr_target("fs_opaque", None),
MSAA,
Some(depth_state(true, wgpu::CompareFunction::Less)),
);
let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vb, hdr("fs_uv", None), MSAA, always());
let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_uv", None), MSAA, always());
let blend = Some(wgpu::BlendState::ALPHA_BLENDING);
let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always());
let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire", blend), MSAA, always());
let wire3d_depth = Some(depth_state(false, wgpu::CompareFunction::LessEqual));
let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth.clone());
let highlight_pipeline =
pipeline(device, "tc_highlight", &layout, &module, "vs_wire_highlight", &vb, hdr("fs_wire_highlight", blend), MSAA, wire3d_depth);
let bg_pipeline = pipeline(device, "tc_bg", &bg_layout, &module, "vs_bg", &[], hdr("fs_bg", None), MSAA, always());
let wire3d_pipeline =
pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire3d", blend), MSAA, wire3d_depth.clone());
let highlight_pipeline = pipeline(
device,
"tc_highlight",
&layout,
&module,
"vs_wire_highlight",
&vertex_layout,
hdr_target("fs_wire_highlight", blend),
MSAA,
wire3d_depth.clone(),
);
let [mesh_vertex_layout] = vertex_layout.clone();
let high_layout = [
mesh_vertex_layout,
Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<f32>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &wgpu::vertex_attr_array![4 => Float32],
}),
];
let bake_high_pipeline = pipeline(
device,
"tc_bake_high",
&background_layout,
&module,
"vs_bake_high",
&high_layout,
hdr_target("fs_bake_high", None),
MSAA,
Some(depth_state(true, wgpu::CompareFunction::Less)),
);
let corner_layout = [Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<[f32; 3]>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &wgpu::vertex_attr_array![0 => Float32x3],
})];
let cage_pipeline = pipeline(
device,
"tc_cage",
&background_layout,
&module,
"vs_bake_cage",
&corner_layout,
hdr_target("fs_bake_cage", blend),
MSAA,
wire3d_depth.clone(),
);
let cage_wire_pipeline = pipeline(
device,
"tc_cage_wire",
&background_layout,
&module,
"vs_bake_cage_wire",
&corner_layout,
hdr_target("fs_wire_bake_cage", blend),
MSAA,
wire3d_depth.clone(),
);
let uv_seam_pipeline =
pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone());
let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always());
let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None);
let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None);
let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))]
.map(|(fs, blend)| pipeline(device, "tc_bloom", &fx_layout, &post_module, "vs_full", &[], hdr(fs, blend), 1, None));
let gbuf_pipeline =
pipeline(device, "tc_gbuf", &mesh_layout, &module, "vs_mesh", &vb, hdr("fs_gbuf", None), 1, Some(depth_state(true, wgpu::CompareFunction::Less)));
let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fs| pipeline(device, "tc_sss", &fx_layout, &post_module, "vs_full", &[], hdr(fs, None), 1, None));
let dof_pipeline = pipeline(device, "tc_dof", &fx_layout, &post_module, "vs_full", &[], hdr("fs_dof", None), 1, None);
let post_pipeline = pipeline(device, "tc_post", &effect_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None);
let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))].map(|(fragment_entry_point, blend)| {
pipeline(device, "tc_bloom", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, blend), 1, None)
});
let gbuffer_pipeline = pipeline(
device,
"tc_gbuf",
&mesh_layout,
&module,
"vs_mesh",
&vertex_layout,
hdr_target("fs_gbuf", None),
1,
Some(depth_state(true, wgpu::CompareFunction::Less)),
);
let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fragment_entry_point| {
pipeline(device, "tc_sss", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, None), 1, None)
});
let dof_pipeline = pipeline(device, "tc_dof", &effect_layout, &post_module, "vs_full", &[], hdr_target("fs_dof", None), 1, None);
let dof_target = Some(wgpu::ColorTargetState { format: hdr_format, blend: None, write_mask: wgpu::ColorWrites::ALL });
let dof_gather_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("tc_dof_gather"),
layout: Some(&fx_layout),
layout: Some(&effect_layout),
vertex: wgpu::VertexState { module: &post_module, entry_point: Some("vs_full"), buffers: &[], compilation_options: Default::default() },
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
@@ -932,20 +1034,23 @@ impl Renderer {
multiview_mask: None,
cache: None,
});
let shadow_depth = wgpu::DepthStencilState {
bias: wgpu::DepthBiasState { constant: 0, slope_scale: 1.5, clamp: 0.0 },
bias: wgpu::DepthBiasState { constant: 0, slope_scale: SHADOW_SLOPE_BIAS, clamp: 0.0 },
..depth_state(true, wgpu::CompareFunction::Less)
};
let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vb, None, 1, Some(shadow_depth));
// accum = hdr * k + accum * (1 - k) with k = 1 / (sample + 1): a running average.
let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vertex_layout, None, 1, Some(shadow_depth));
// accum = hdr_target * k + accum * (1 - k) with k = 1 / (sample + 1): a running average
let average = wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Constant,
dst_factor: wgpu::BlendFactor::OneMinusConstant,
operation: wgpu::BlendOperation::Add,
};
let accum_layout = pl("tc_accum", &[Some(&mip_bgl)]);
let accum_layout = pipeline_layout("tc_accum", &[Some(&mip_bind_group_layout)]);
let accum_blend = Some(wgpu::BlendState { color: average, alpha: average });
let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr("fs_copy", accum_blend), 1, None);
let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr_target("fs_copy", accum_blend), 1, None);
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("tc_tex"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
@@ -953,7 +1058,7 @@ impl Renderer {
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
anisotropy_clamp: 8,
anisotropy_clamp: MAX_ANISOTROPY,
..Default::default()
});
let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
@@ -972,7 +1077,8 @@ impl Renderer {
compare: Some(wgpu::CompareFunction::LessEqual),
..Default::default()
});
let shadow_buf = device.create_buffer(&wgpu::BufferDescriptor {
let shadow_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("tc_shadow"),
size: std::mem::size_of::<[[f32; 4]; 5]>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
@@ -986,39 +1092,45 @@ impl Renderer {
vp: Mat4::IDENTITY,
bg: device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("tc_shadow"),
layout: &shadow_bgl,
entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buf.as_entire_binding() }],
layout: &shadow_bind_group_layout,
entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buffer.as_entire_binding() }],
}),
buf: shadow_buf,
buf: shadow_buffer,
};
let black = Tex::new(device, "tc_black", 1, 1, COLOR_FORMAT, 1).view;
let refr_black = device.create_bind_group(&wgpu::BindGroupDescriptor {
let refraction_black = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("tc_refr_black"),
layout: &refr_bgl,
layout: &refraction_bind_group_layout,
entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&black) }],
});
let env = Tex::new(device, "tc_env", 512, 256, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS);
let mut r = Renderer {
let env = Tex::new(device, "tc_env", PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1], wgpu::TextureFormat::Rgba16Float, ENV_LEVELS);
let mut renderer = Renderer {
target_format,
hdr_format,
globals_bgl,
set_bgl,
blit_bgl,
mip_bgl,
fx_bgl,
refr_bgl,
refr_black,
globals_bgl: globals_bind_group_layout,
set_bgl: set_bind_group_layout,
blit_bgl: blit_bind_group_layout,
mip_bgl: mip_bind_group_layout,
fx_bgl: effect_bind_group_layout,
refr_bgl: refraction_bind_group_layout,
refr_black: refraction_black,
mesh_pipeline,
opaque_pipeline,
uv_pipeline,
wire_pipeline,
wire3d_pipeline,
highlight_pipeline,
bake_high_pipeline,
cage_pipeline,
cage_wire_pipeline,
uv_seam_pipeline,
bg_pipeline,
blit_pipeline,
post_pipeline,
bloom_pipelines,
gbuf_pipeline,
gbuf_pipeline: gbuffer_pipeline,
sss_pipelines,
dof_gather_pipeline,
dof_pipeline,
@@ -1038,13 +1150,16 @@ impl Renderer {
sh: [[0.0; 4]; 9],
content_rev: 0,
mesh: None,
bake_high: None,
cages: Vec::new(),
uv_seams: None,
sets: Vec::new(),
display_shift: 0,
material_sets: Vec::new(),
views: HashMap::new(),
};
r.set_environment(device, queue, "Studio Soft", None);
r
renderer.set_environment(device, queue, "Studio Soft", None);
renderer
}
pub fn environment_name(&self) -> &str {
@@ -1124,6 +1239,94 @@ impl Renderer {
self.content_rev += 1;
}
/// Upload the high poly when `id` changes; remove it on `None` or when its buffers exceed the device limit
pub fn set_bake_high(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh: Option<&Mesh>, id: u64) -> Result<(), String> {
if self.bake_high.as_ref().map(|high| high.id) == mesh.map(|_| id) {
return Ok(());
}
self.bake_high = None;
self.content_rev += 1;
let Some(mesh) = mesh else { return Ok(()) };
// Imported high polys can outgrow a viewport buffer even when the CPU baker accepts them
let limit = device.limits().max_buffer_size;
let buffers = [
(mesh.positions.len(), std::mem::size_of::<Vertex>()),
(mesh.indices.len(), std::mem::size_of::<u32>()),
(mesh.positions.len(), std::mem::size_of::<f32>()),
];
if mesh.indices.len() > u32::MAX as usize || buffers.iter().any(|&(count, stride)| count.checked_mul(stride).is_none_or(|bytes| bytes as u64 > limit)) {
return Err(format!("High-poly visualization exceeds the GPU buffer limit ({limit} bytes). Use a smaller preview mesh or hide the high poly."));
}
self.bake_high = Some(HighPolyGpu {
id,
vertices: upload_buffer(device, queue, "tc_bake_high_vb", bytemuck::cast_slice(&subdivide::vertices(mesh)), wgpu::BufferUsages::VERTEX),
vertex_count: mesh.positions.len(),
indices: upload_buffer(device, queue, "tc_bake_high_ib", bytemuck::cast_slice(&mesh.indices), wgpu::BufferUsages::INDEX),
index_count: mesh.indices.len() as u32,
missed: upload_buffer(device, queue, "tc_bake_high_missed", bytemuck::cast_slice(&vec![0f32; mesh.positions.len()]), wgpu::BufferUsages::VERTEX),
});
Ok(())
}
/// Which vertices of high poly `id` the bake's rays miss (1) or reach (0); ignored for another mesh or vertex count
pub fn set_bake_high_missed(&mut self, queue: &wgpu::Queue, id: u64, missed: &[f32]) {
let Some(high) = self.bake_high.as_ref().filter(|high| high.id == id && high.vertex_count == missed.len()) else { return };
queue.write_buffer(&high.missed, 0, bytemuck::cast_slice(missed));
self.content_rev += 1;
}
/// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners
pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) {
if self.cages.len() <= texture_set {
self.cages.resize_with(texture_set + 1, || None);
}
let Some(slot) = self.cages.get_mut(texture_set) else { return };
match (cage, slot.as_mut()) {
(None, _) => *slot = None,
(Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => {
queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners));
}
(Some((corners, edges)), _) => {
*slot = Some(CageGpu {
topology,
corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX),
corner_count: corners.len() as u32,
edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX),
edge_index_count: (edges.len() * 2) as u32,
});
}
}
self.content_rev += 1;
}
/// Forget the cages of texture sets from `count` on (sets that were removed)
pub fn truncate_bake_cages(&mut self, count: usize) {
if self.cages.len() > count {
self.cages.truncate(count);
self.content_rev += 1;
}
}
/// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id`
pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) {
let mut line_indices: Vec<u32> = Vec::new();
let mut line_draws = Vec::new();
for (material, edges) in seams.iter().enumerate() {
let start = line_indices.len() as u32;
line_indices.extend(edges.iter().flat_map(|&(from, to)| [from, to]));
line_draws.push((start, line_indices.len() as u32 - start, material));
}
let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX);
self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws });
self.content_rev += 1;
}
/// Build the mesh's dense copy for displacement (once per mesh).
fn ensure_dense(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
let Some(m) = self.mesh.as_mut() else { return };
@@ -1889,30 +2092,30 @@ impl Renderer {
self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr);
}
/// One scene pass: background, then the mesh with `pipe`, the wireframe with `wire` and one set's highlighted edges with `highlight`
/// One scene pass: background, then the mesh with `mesh_pipeline`, the wireframe with `wire` and one set's highlighted edges with `highlight`
#[allow(clippy::too_many_arguments)]
fn draw_scene(
&self,
encoder: &mut wgpu::CommandEncoder,
v: &ViewTargets,
targets: &ViewTargets,
resolve: &wgpu::TextureView,
globals_bg: &wgpu::BindGroup,
globals_bind_group: &wgpu::BindGroup,
frame: &Frame,
pipe: &wgpu::RenderPipeline,
mesh_pipeline: &wgpu::RenderPipeline,
wire: Option<&wgpu::RenderPipeline>,
highlight: Option<(&wgpu::RenderPipeline, usize)>,
refr: &wgpu::BindGroup,
refraction_source: &wgpu::BindGroup,
) {
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("tc_view"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &v.msaa,
view: &targets.msaa,
resolve_target: Some(resolve),
depth_slice: None,
ops: wgpu::Operations { load: CLEAR, store: wgpu::StoreOp::Discard },
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &v.depth,
view: &targets.depth,
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
stencil_ops: None,
}),
@@ -1920,33 +2123,87 @@ impl Renderer {
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_bind_group(0, globals_bg, &[]);
pass.set_bind_group(0, globals_bind_group, &[]);
pass.set_pipeline(&self.bg_pipeline);
pass.draw(0..3, 0..1);
let Some(m) = &self.mesh else { return };
let uv_ts = match frame.kind {
let Some(mesh) = &self.mesh else { return };
let uv_set = match frame.kind {
ViewKind::Scene => None,
ViewKind::Uv { ts, .. } => Some(ts),
};
pass.set_bind_group(2, refr, &[]);
let geo = self.geometry(m, frame);
pass.set_bind_group(2, refraction_source, &[]);
let geometry = self.geometry(mesh, frame);
let bake = frame.shade.bake.filter(|_| uv_set.is_none());
let low_poly_shown = bake.is_none_or(|bake| bake.low_poly);
let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set);
let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && low_poly_set.is_none_or(|only| only == *set)).unzip();
// The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too)
let (highlight, highlight_set) = highlight.unzip();
let passes = [
(Some(pipe), &geo.vb, &geo.ib, &geo.draws, uv_ts, 1),
(wire, &m.geo.vb, &m.lines, &m.line_draws, uv_ts, 1),
(highlight, &m.geo.vb, &m.lines, &m.line_draws, highlight_set, HIGHLIGHT_SHIFTS),
(low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1),
(wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, low_poly_set, 1),
(highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS),
];
for (pipe, vb, ib, ranges, only, instances) in passes {
let Some(pipe) = pipe else { continue };
pass.set_pipeline(pipe);
pass.set_vertex_buffer(0, vb.slice(..));
pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
for (range, set) in self.drawable(ranges, &frame.visible, only) {
for (pipeline, vertices, indices, ranges, only_set, instances) in passes {
let Some(pipeline) = pipeline else { continue };
pass.set_pipeline(pipeline);
pass.set_vertex_buffer(0, vertices.slice(..));
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
for (range, set) in self.drawable(ranges, &frame.visible, only_set) {
pass.set_bind_group(1, &set.bind_group, &[]);
pass.draw_indexed(range, 0, 0..instances);
}
}
if let Some(bake) = bake {
self.draw_bake(&mut pass, mesh, frame, bake);
}
}
/// Bake mode's high poly, UV seams and cages over the low poly `low_poly`
fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) {
if bake.high_poly
&& let Some(high) = &self.bake_high
{
pass.set_pipeline(&self.bake_high_pipeline);
pass.set_vertex_buffer(0, high.vertices.slice(..));
pass.set_vertex_buffer(1, high.missed.slice(..));
pass.set_index_buffer(high.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.draw_indexed(0..high.index_count, 0, 0..1);
}
if bake.uv_seams
&& let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id)
{
pass.set_pipeline(&self.uv_seam_pipeline);
pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..));
pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32);
for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) {
pass.set_bind_group(1, &set.bind_group, &[]);
pass.draw_indexed(range, 0, 0..1);
}
}
if !bake.cage {
return;
}
let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true);
let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref());
// The translucent faces first, then the wireframe over them
pass.set_pipeline(&self.cage_pipeline);
for cage in cages() {
pass.set_vertex_buffer(0, cage.corners.slice(..));
pass.draw(0..cage.corner_count, 0..1);
}
pass.set_pipeline(&self.cage_wire_pipeline);
for cage in cages() {
pass.set_vertex_buffer(0, cage.corners.slice(..));
pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32);
pass.draw_indexed(0..cage.edge_index_count, 0, 0..1);
}
}
/// Draw view `id` into the current pass at `rect` (target pixels: x, y, w, h).
+88
View File
@@ -0,0 +1,88 @@
// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams
struct BakeViewOut {
@builtin(position) clip: vec4<f32>,
@location(0) world_position: vec3<f32>,
@location(1) normal: vec3<f32>,
// 1 where the bake's rays miss the high poly, 0 where they reach it
@location(2) missed: f32,
};
const HIGH_POLY_COLOR: vec3<f32> = vec3<f32>(0.10, 0.36, 0.56);
const MISSED_COLOR: vec3<f32> = vec3<f32>(0.80, 0.01, 0.01);
const CAGE_COLOR: vec3<f32> = vec3<f32>(0.55, 0.42, 0.26);
const CAGE_OPACITY: f32 = 0.16;
const CAGE_WIRE_COLOR: vec4<f32> = vec4<f32>(0.75, 0.62, 0.42, 0.7);
const UV_SEAM_COLOR: vec4<f32> = vec4<f32>(0.20, 0.85, 0.30, 1.0);
// Brightness of surfaces seen edge-on; facing the camera adds the rest
const HEADLIGHT_AMBIENT: f32 = 0.3;
// Fractions of the way to the camera each vertex moves, so near-coincident surfaces and lines draw in a fixed order
const HIGH_POLY_PULL_TOWARD_EYE: f32 = 0.001;
const CAGE_WIRE_PULL_TOWARD_EYE: f32 = 0.002;
// Lit from the camera: surfaces facing it are brightest
fn headlight(color: vec3<f32>, normal: vec3<f32>, world_position: vec3<f32>) -> vec3<f32> {
let facing = abs(dot(normal, normalize(g.eye.xyz - world_position)));
return color * (HEADLIGHT_AMBIENT + (1.0 - HEADLIGHT_AMBIENT) * facing);
}
fn pulled_toward_eye(world_position: vec3<f32>, fraction: f32) -> vec4<f32> {
return g.view_proj * vec4<f32>(world_position + (g.eye.xyz - world_position) * fraction, 1.0);
}
// Pulled slightly toward the camera: where the high poly nearly touches the low poly it shows instead of flickering with it
@vertex
fn vs_bake_high(@location(0) position: vec3<f32>, @location(1) normal: vec3<f32>, @location(4) missed: f32) -> BakeViewOut {
var out: BakeViewOut;
out.clip = pulled_toward_eye(position, HIGH_POLY_PULL_TOWARD_EYE);
out.world_position = position;
out.normal = normal;
out.missed = missed;
return out;
}
@fragment
fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4<f32> {
let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed);
return vec4<f32>(headlight(color, normalize(surface.normal), surface.world_position), 1.0);
}
@vertex
fn vs_bake_cage(@location(0) position: vec3<f32>) -> BakeViewOut {
var out: BakeViewOut;
out.clip = g.view_proj * vec4<f32>(position, 1.0);
out.world_position = position;
out.normal = vec3<f32>(0.0, 1.0, 0.0);
out.missed = 0.0;
return out;
}
// The cage's own faces: their normal comes from the screen-space change of the position
@fragment
fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4<f32> {
let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position)));
return vec4<f32>(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY);
}
// Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces
@vertex
fn vs_bake_cage_wire(@location(0) position: vec3<f32>) -> BakeViewOut {
var out: BakeViewOut;
out.clip = pulled_toward_eye(position, CAGE_WIRE_PULL_TOWARD_EYE);
out.world_position = position;
out.normal = vec3<f32>(0.0, 1.0, 0.0);
out.missed = 0.0;
return out;
}
@fragment
fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4<f32> {
return CAGE_WIRE_COLOR;
}
@fragment
fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4<f32> {
return UV_SEAM_COLOR;
}
+8
View File
@@ -0,0 +1,8 @@
/// The low poly's UV seams as a line list over its vertex buffer
pub(crate) struct UvSeamGpu {
/// The low-poly mesh the lines belong to
pub(crate) mesh_id: u64,
pub(crate) lines: wgpu::Buffer,
/// (first index, count, material) per material
pub(crate) line_draws: Vec<(u32, u32, usize)>,
}
+123 -2
View File
@@ -1,8 +1,9 @@
use texturecraft_compose::{DisplayKind, ImageRes};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{OrbitCamera, primitives};
use texturecraft_render::headless::Headless;
use texturecraft_render::renderer::TAA_SAMPLES;
use texturecraft_render::{Frame, Shade, ViewKind};
use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind};
/// The UI's key light (`viewport::shade`).
const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5];
@@ -42,14 +43,18 @@ impl Img {
}
}
/// The id `setup` uploads the material ball under
const MESH_ID: u64 = 1;
/// A headless renderer with the material ball framed in a 480×360 view (None without a GPU).
fn setup() -> Option<(Headless, Frame)> {
let Ok(mut h) = Headless::new() else {
eprintln!("skipping: no GPU adapter");
return None;
};
eprintln!("headless adapter: {:?}", h.device.adapter_info());
let mesh = primitives::material_ball();
h.renderer.set_mesh(&h.device, &h.queue, &mesh, 1);
h.renderer.set_mesh(&h.device, &h.queue, &mesh, MESH_ID);
h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0), ((256, 256), 1)], 2);
let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() };
let (lo, hi) = mesh.bounds();
@@ -220,6 +225,122 @@ fn wireframe_3d_overlays_the_mesh() {
assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean");
}
#[test]
fn bake_visualization_draws_the_high_poly_and_the_cage() {
// A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color
const HIGH_POLY_RADIUS_PER_SIZE: f32 = 0.3;
const CAGE_SCALE: f32 = 2.5;
const HIGH_POLY_ID: u64 = 7;
const CAGE_TOPOLOGY: u64 = 1;
const CAGE_EDGES: [[u32; 2]; 2] = [[0, 1], [1, 2]];
const COLOR_LEAD: i32 = 30;
let Some((mut h, frame)) = setup() else { return };
let ball = primitives::material_ball();
let (low_min, low_max) = ball.bounds();
let ball_center = (low_min + low_max) * 0.5;
let mut high = primitives::sphere((low_max - low_min).max_element() * HIGH_POLY_RADIUS_PER_SIZE, 32, 16);
for position in &mut high.positions {
*position += ball_center;
}
h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID).unwrap();
let corners: Vec<Vec3> = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect();
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY);
let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None };
let center = (frame.size[0] / 2, frame.size[1] / 2);
let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name);
let low_only = only(&mut h, bake, "bake_low_only");
let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden");
let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly");
let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage");
assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly");
let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background");
assert_same(&hidden, &background, "without the low poly only the background is left");
let [red, green, blue] = high_poly.at(center.0, center.1).map(i32::from);
assert!(blue > red + COLOR_LEAD && blue > green, "the high poly inside the low poly draws blue: {:?}", [red, green, blue]);
let ([low_red, low_green, low_blue], [caged_red, caged_green, caged_blue]) = (low_only.at(center.0, center.1), caged.at(center.0, center.1));
assert!(
caged_blue < low_blue && caged_red >= caged_blue && caged_green >= caged_blue,
"the cage tints the ball tan: {:?} → {:?}",
[low_red, low_green, low_blue],
[caged_red, caged_green, caged_blue]
);
// Vertices the bake's rays miss turn red
h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]);
let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed");
let [red, green, blue] = missed.at(center.0, center.1).map(i32::from);
assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]);
// Show for selected texture set only: the other set's low poly and the cage of set 0 drop out
let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set");
let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set");
assert_ne!(first_set.px, caged.px, "the second set's low poly is left out");
assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out");
assert_ne!(first_set.px, second_set.px);
// UV seams draw over the low poly
h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges());
let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams");
assert_ne!(seams.px, low_only.px, "the seams show");
// A new distance with the same topology only moves the corners
let grown: Vec<Vec3> = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect();
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY);
let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown");
assert_ne!(caged.px, bigger.px, "the cage grew");
}
#[test]
fn oversized_bake_high_poly_leaves_the_view_renderable() {
let Some((mut headless, frame)) = setup() else { return };
let high = primitives::sphere(0.5, 16, 8);
headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 1).unwrap();
let limit = headless.device.limits().max_buffer_size;
// The viewport vertex contains position, normal, tangent and UV: twelve f32 values
let vertex_count = limit as usize / (12 * std::mem::size_of::<f32>()) + 1;
let oversized = texturecraft_geom::Mesh { positions: vec![Vec3::ZERO; vertex_count], ..Default::default() };
let error = headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&oversized), 2).unwrap_err();
assert!(error.contains("GPU buffer limit"), "{error}");
headless.renderer.set_bake_high_missed(&headless.queue, 2, &[]);
let bake = BakeVisualization { high_poly: true, cage: false, uv_seams: false, low_poly: false, only_set: None };
let cleared = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_cleared");
let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_oversized_background");
assert_same(&cleared, &background, "an oversized replacement must not leave the previous high poly visible");
headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 3).unwrap();
let recovered = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_recovered");
assert_ne!(recovered.px, background.px, "a later valid high poly still draws");
}
#[test]
fn bake_low_poly_visibility_also_filters_its_wireframe() {
let Some((mut headless, frame)) = setup() else { return };
let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: false, only_set: None };
let hidden = shaded(&frame, |shade| {
shade.bake = Some(bake);
shade.wireframe_3d = true;
shade.highlight = Some(texturecraft_render::SetHighlight { set: 0, color: [1.0, 0.5, 0.0] });
});
let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_wire_background");
let hidden_wire = render(&mut headless, &hidden, "bake_wire_hidden");
assert_same(&hidden_wire, &background, "hiding the project mesh also hides its wireframe and highlight");
for texture_set in [0, 1] {
let selected = shaded(&hidden, |shade| {
shade.bake = Some(BakeVisualization { low_poly: true, only_set: Some(texture_set), ..bake });
shade.highlight = Some(texturecraft_render::SetHighlight { set: 1 - texture_set, color: [1.0, 0.5, 0.0] });
});
let expected = Frame { visible: vec![texture_set == 0, texture_set == 1], ..selected.clone() };
let actual = render(&mut headless, &selected, &format!("bake_wire_selected_{texture_set}"));
let expected = render(&mut headless, &expected, &format!("bake_wire_expected_{texture_set}"));
assert_same(&actual, &expected, "the wireframe and highlight respect the selected texture set");
}
}
#[test]
fn ortho_background_matches_perspective() {
let Some((mut h, frame)) = setup() else { return };
@@ -0,0 +1,61 @@
use egui::collapsing_header::CollapsingState;
use egui::{Rect, Ui, vec2};
use egui_phosphor::regular as icon;
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
use crate::widgets::{icon_button_without_tooltip, section_chevron};
/// The panel's width and its gap from the 3D view's top-left corner
const PANEL_WIDTH: f32 = 280.0;
const PANEL_MARGIN: f32 = 12.0;
/// Size of the panel's eye buttons
const EYE_BUTTON_SIZE: f32 = 22.0;
/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view`
pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) {
let toggles = &mut app.ui.bake_visualization;
egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show(
ui.ctx(),
|ui| {
ui.set_width(PANEL_WIDTH);
let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true);
let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open()));
if header.clicked() {
collapsing_state.toggle(ui);
}
collapsing_state.show_body_unindented(ui, |ui| {
ui.add_enabled_ui(toggles.on, |ui| {
ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only"));
eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None);
eye_row(ui, &mut toggles.cage, tr("Cage"), None);
eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None);
eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None);
});
});
},
);
}
/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response
fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option<bool>) -> egui::Response {
let tokens = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.set_min_height(EYE_BUTTON_SIZE);
let text = match open {
Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())),
None => egui::RichText::new(label),
};
let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click()));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() {
*shown = !*shown;
}
});
response
})
.inner
}
@@ -0,0 +1,34 @@
use serde::{Deserialize, Serialize};
use texturecraft_render::BakeVisualization;
/// The Baking Visualization panel's switches in bake mode's 3D view
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct BakeVisualizationToggles {
/// The panel's eye: the whole visualization on or off
pub on: bool,
pub selected_set_only: bool,
pub high_poly: bool,
pub cage: bool,
pub uv_seams: bool,
pub low_poly: bool,
}
impl Default for BakeVisualizationToggles {
fn default() -> Self {
Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true }
}
}
impl BakeVisualizationToggles {
/// What the renderer draws with these switches while texture set `selected_set` is selected
pub fn visualization(&self, selected_set: usize) -> Option<BakeVisualization> {
self.on.then_some(BakeVisualization {
high_poly: self.high_poly,
cage: self.cage,
uv_seams: self.uv_seams,
low_poly: self.low_poly,
only_set: self.selected_set_only.then_some(selected_set),
})
}
}
+4
View File
@@ -1,9 +1,13 @@
//! Bake Mode presentation; persisted settings live in core and edits use engine commands
mod bake_paint_brush;
mod bake_visualization_panel;
mod bake_visualization_toggles;
mod breadcrumb;
mod common_settings;
pub use bake_paint_brush::BakePaintBrush;
pub(crate) use bake_visualization_panel::bake_visualization_panel;
pub use bake_visualization_toggles::BakeVisualizationToggles;
mod controls;
mod map_settings;
mod mesh_map_bakers;
+11
View File
@@ -0,0 +1,11 @@
//! Keeps the GPU's copy of bake mode's visualization (high poly, cages, UV seams) in step with the session
mod bake_scene_link;
mod cage_link;
mod cage_shell_key;
mod cage_upload;
mod reach_link;
mod shared_handle;
pub use bake_scene_link::BakeSceneLink;
pub use cage_upload::CageUpload;
@@ -0,0 +1,239 @@
use std::sync::Arc;
use texturecraft_engine::Session;
use texturecraft_engine::geom::Mesh;
use texturecraft_render::BakeVisualization;
use super::CageUpload;
use super::cage_link::CageLink;
use super::cage_shell_key::CageShellKey;
use super::reach_link::ReachLink;
use super::shared_handle::SharedHandle;
use crate::gpu::SceneSync;
/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams
#[derive(Default)]
pub struct BakeSceneLink {
/// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one)
high: SharedHandle<Mesh>,
high_id: u64,
/// Whether the GPU has the high poly (a lost frame sends it again under the same id)
high_sent: bool,
cages: Vec<Option<CageLink>>,
/// How many texture sets' cages the GPU was last told to keep
sent_cage_count: Option<usize>,
/// The low-poly mesh whose seams are uploaded
seams_mesh_id: Option<u64>,
next_topology: u64,
reach: ReachLink,
}
impl BakeSceneLink {
/// Send everything again (the GPU lost what it was sent); the cage shells and the reach worked out on the CPU stay
pub fn resend(&mut self) {
self.high_sent = false;
self.sent_cage_count = None;
self.seams_mesh_id = None;
for link in self.cages.iter_mut().flatten() {
link.max_frontal = f32::NAN;
}
self.reach.resend();
}
/// Whether something is still being worked out off the UI thread
pub fn busy(&self) -> bool {
self.reach.busy()
}
/// Add to `out` what the GPU needs to draw `visualization` this frame
pub fn sync(&mut self, session: &Session, visualization: Option<BakeVisualization>, out: &mut SceneSync) {
self.reach.poll();
let Some(visualization) = visualization else { return };
if visualization.high_poly {
let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone());
let handle = SharedHandle::of(high.as_ref());
if handle != self.high {
self.high = handle;
self.high_id += 1;
self.high_sent = false;
}
if !self.high_sent {
out.bake_high = Some((high, self.high_id));
self.high_sent = true;
}
self.reach.sync(session, self.high_id, visualization.only_set, out);
}
if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) {
self.seams_mesh_id = Some(session.mesh_id);
out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges()));
}
if visualization.cage {
self.sync_cages(session, out);
}
}
/// Rebuild the cages whose inputs changed and move the corners of those whose distance changed
fn sync_cages(&mut self, session: &Session, out: &mut SceneSync) {
let set_count = session.doc.project.texture_sets.len();
if self.sent_cage_count != Some(set_count) {
out.bake_cage_count = Some(set_count);
self.sent_cage_count = Some(set_count);
}
self.cages.truncate(set_count);
self.cages.resize_with(set_count, || None);
for (texture_set, link) in self.cages.iter_mut().enumerate() {
let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue };
let max_frontal = set.bake.cage.max_frontal;
match link {
Some(link) if link.key == key => {
if link.max_frontal == max_frontal {
continue;
}
link.max_frontal = max_frontal;
}
_ => {
self.next_topology += 1;
let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new);
*link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal });
}
}
let Some(link) = link.as_ref() else { continue };
let upload = link.shell.as_ref().map(|shell| CageUpload { corners: shell.corners(max_frontal), shell: shell.clone() });
out.bake_cages.push((texture_set, upload, link.topology));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None };
/// How long a test waits for the reach worker: frames, and the pause between them
const WAIT_FRAMES: usize = 2000;
const WAIT_FRAME_PAUSE: std::time::Duration = std::time::Duration::from_millis(5);
/// The sample project with a high poly a little outside its low poly
fn session() -> Session {
const HIGH_POLY_OFFSET: f32 = 0.02;
let mut session = texturecraft_engine::sample_session(128, 128).unwrap();
let low = session.mesh.clone();
let mut obj = String::new();
for (position, normal) in low.positions.iter().zip(&low.normals) {
let raised = *position + *normal * HIGH_POLY_OFFSET;
obj += &format!("v {} {} {}\n", raised.x, raised.y, raised.z);
}
for corners in low.indices.chunks(3) {
obj += &format!("f {} {} {}\n", corners[0] + 1, corners[1] + 1, corners[2] + 1);
}
session.add_high_poly_bytes("high.obj", obj.into_bytes()).unwrap();
session
}
fn sync(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> SceneSync {
let mut out = SceneSync::default();
link.sync(session, Some(visualization), &mut out);
out
}
/// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red
fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 {
for _ in 0..WAIT_FRAMES {
if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed {
return missed.iter().sum::<f32>() / missed.len().max(1) as f32;
}
std::thread::sleep(WAIT_FRAME_PAUSE);
}
panic!("the reach never arrived");
}
fn set_distances(session: &mut Session, max_frontal: f32) {
texturecraft_engine::execute(session, "bake.settings", &json!({"ts": "all", "maxFrontal": max_frontal})).unwrap();
}
#[test]
fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() {
let (mut session, mut link) = (session(), BakeSceneLink::default());
let first = sync(&mut link, &session, EVERYTHING);
assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len()));
let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") };
let unchanged = sync(&mut link, &session, EVERYTHING);
assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent");
set_distances(&mut session, 0.03);
let moved = sync(&mut link, &session, EVERYTHING);
let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") };
assert_eq!(moved_topology, topology, "a distance only moves the corners");
assert_ne!(moved_cage.corners, cage.corners);
texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap();
let rebuilt = sync(&mut link, &session, EVERYTHING);
assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage");
// The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts
red_share(&mut link, &session, EVERYTHING);
link.resend();
let resent = sync(&mut link, &session, EVERYTHING);
assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again");
assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len());
assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame");
assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id");
assert!(!link.busy(), "a lost frame doesn't work out the reach again");
}
#[test]
fn a_reach_finishes_while_nothing_is_drawn() {
let session = session();
let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING };
for hidden in [None, Some(no_high_poly)] {
let mut link = BakeSceneLink::default();
sync(&mut link, &session, EVERYTHING);
assert!(link.busy(), "the first frame starts working out the reach");
let finished = (0..WAIT_FRAMES).any(|_| {
std::thread::sleep(WAIT_FRAME_PAUSE);
link.sync(&session, hidden, &mut SceneSync::default());
!link.busy()
});
assert!(finished, "the view stops redrawing for a reach once it is done: {hidden:?}");
}
}
#[test]
fn the_red_follows_the_distances_and_the_selected_set() {
let (mut session, mut link) = (session(), BakeSceneLink::default());
set_distances(&mut session, 0.0);
let at_zero = red_share(&mut link, &session, EVERYTHING);
assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}");
set_distances(&mut session, 0.05);
let covered = red_share(&mut link, &session, EVERYTHING);
assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}");
set_distances(&mut session, 0.0);
let by_name = |session: &mut Session, low_suffix: &str| {
for set in &mut session.doc.project.texture_sets {
set.bake.high_poly.match_mode = texturecraft_engine::core::MeshMatchMode::ByMeshName;
set.bake.high_poly.low_suffix = low_suffix.into();
}
};
by_name(&mut session, "_no_such_suffix");
let by_name_red = red_share(&mut link, &session, EVERYTHING);
assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}");
let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING };
assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing");
}
}
@@ -0,0 +1,16 @@
use std::sync::Arc;
use texturecraft_engine::bake::CageShell;
use super::cage_shell_key::CageShellKey;
/// A texture set's cage as the GPU has it
pub(super) struct CageLink {
pub(super) key: CageShellKey,
/// `None`: the set bakes without a high poly or its cage can't be built
pub(super) shell: Option<Arc<CageShell>>,
/// The renderer's name for the shell's corner order and edges
pub(super) topology: u64,
/// The max frontal distance the GPU's corners are at
pub(super) max_frontal: f32,
}
@@ -0,0 +1,47 @@
use std::collections::BTreeMap;
use texturecraft_engine::Session;
use texturecraft_engine::bake::BakePaintMap;
use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings};
use texturecraft_engine::geom::Mesh;
use super::shared_handle::SharedHandle;
/// Everything a texture set's cage shell is built from except the distances, which only move its corners
#[derive(Clone, Debug, PartialEq)]
pub(super) struct CageShellKey {
mesh_id: u64,
high: SharedHandle<Mesh>,
cage_file: SharedHandle<Mesh>,
material: usize,
uv_tiles: Vec<u32>,
tile_resolutions: BTreeMap<u32, u32>,
cage_kind: CageType,
relative_to_bounding_box: bool,
average_normals: bool,
use_low_as_high: bool,
skew: SkewSettings,
/// The painted skew and cage maps
paint: [SharedHandle<BakePaintMap>; 2],
}
impl CageShellKey {
pub(super) fn of(session: &Session, texture_set: usize) -> Option<CageShellKey> {
let set = session.doc.project.texture_sets.get(texture_set)?;
let paint = |target| SharedHandle::of(session.doc.bake_paint.get(&(texture_set, target)));
Some(CageShellKey {
mesh_id: session.mesh_id,
high: SharedHandle::of(session.bake_meshes.merged_high().map(|high| &high.mesh)),
cage_file: SharedHandle::of(session.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)),
material: set.material,
uv_tiles: set.uv_tiles.clone(),
tile_resolutions: set.tile_resolutions.clone(),
cage_kind: set.bake.cage.kind,
relative_to_bounding_box: set.bake.cage.relative_to_bounding_box,
average_normals: set.bake.cage.average_normals,
use_low_as_high: set.bake.high_poly.use_low_as_high,
skew: set.bake.skew,
paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)],
})
}
}
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more