mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-30 18:14:00 +01:00
Merge main and fix symmetry review issues
This commit is contained in:
commit
ca08fb7c3d
269 files changed
+21475
-3068
No files matched your search
@@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use super::MergedHigh;
|
||||
use super::{MergedHigh, StreamedBake, StreamedMap};
|
||||
use crate::{EngineError, Result};
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::BakeSettings;
|
||||
use texturecraft_core::{BakeSettings, BakedMap};
|
||||
use texturecraft_geom::{Bvh, Mesh};
|
||||
|
||||
/// A self-contained bake task that can run on another thread.
|
||||
@@ -29,7 +29,69 @@ pub struct BakeTask {
|
||||
}
|
||||
|
||||
impl BakeTask {
|
||||
/// The maps this task makes, in the order [`BakeTask::run_streaming`] finishes them
|
||||
pub fn maps(&self) -> Vec<BakedMap> {
|
||||
self.settings.maps.enabled().collect()
|
||||
}
|
||||
|
||||
/// Bake the maps one after another, handing each one to `on_map` as soon as it is padded,
|
||||
/// and return all of them together. Each map is a bake of its own, so with a high poly
|
||||
/// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several
|
||||
/// maps, in exchange for showing them as they land. The pixels are the same as `run`'s.
|
||||
/// The handed-over buffers are the returned ones too (no copy is made), so a preview that
|
||||
/// keeps them costs no second set of maps. A cancel or an error leaves the maps already
|
||||
/// handed over whole.
|
||||
pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result<StreamedBake> {
|
||||
let maps = self.maps();
|
||||
let total = maps.len();
|
||||
let mut combined: Option<StreamedBake> = None;
|
||||
|
||||
for (index, map) in maps.iter().copied().enumerate() {
|
||||
let mut settings = self.settings.clone();
|
||||
settings.maps.select([map]);
|
||||
let mut output = self.run_with(&settings, progress)?;
|
||||
let Some(data) = output.maps.remove(&map) else { continue };
|
||||
if combined.is_none() {
|
||||
// Retain unchecked maps once, using the full selection rather than this one-map pass.
|
||||
super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &maps)?;
|
||||
}
|
||||
|
||||
let data = Arc::new(data);
|
||||
on_map(StreamedMap { map, index, total, resolution: output.resolution, height: output.height, data: data.clone() });
|
||||
match &mut combined {
|
||||
Some(combined) => {
|
||||
combined.maps.insert(map, data);
|
||||
}
|
||||
None => {
|
||||
// A resized partial bake also returns unchecked maps that must survive application
|
||||
let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
|
||||
retained.insert(map, data);
|
||||
combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match combined {
|
||||
Some(output) => Ok(output),
|
||||
None => {
|
||||
let output = self.run(progress)?;
|
||||
Ok(StreamedBake {
|
||||
resolution: output.resolution,
|
||||
height: output.height,
|
||||
maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(),
|
||||
tracer: output.tracer,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&self, progress: &Progress) -> Result<BakeOutput> {
|
||||
let mut output = self.run_with(&self.settings, progress)?;
|
||||
super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn run_with(&self, settings: &BakeSettings, progress: &Progress) -> Result<BakeOutput> {
|
||||
let high =
|
||||
self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color });
|
||||
let request = BakeRequest {
|
||||
@@ -37,16 +99,118 @@ impl BakeTask {
|
||||
mesh: &self.mesh,
|
||||
bvh: &self.bvh,
|
||||
material: self.material,
|
||||
settings: &self.settings,
|
||||
settings,
|
||||
high,
|
||||
cage: self.cage.as_deref(),
|
||||
skew: self.skew.as_deref(),
|
||||
cage_paint: self.cage_paint.as_deref(),
|
||||
tiles: self.tiles,
|
||||
};
|
||||
|
||||
let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref())
|
||||
.map_err(|error| EngineError::Other(format!("bake failed: {error}")))?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Session, execute};
|
||||
use serde_json::json;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
const PREVIOUS_MAPS: [BakedMap; 3] = [BakedMap::Normal, BakedMap::AmbientOcclusion, BakedMap::Height];
|
||||
const SELECTED_MAPS: [BakedMap; 2] = [BakedMap::AmbientOcclusion, BakedMap::Height];
|
||||
|
||||
fn partial_task(selected: &[BakedMap], resized: bool, excluded: bool) -> BakeTask {
|
||||
let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({"resolution": 64, "rays": 2})).unwrap();
|
||||
if excluded {
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
|
||||
}
|
||||
let mut task = session.bake_task(0).unwrap();
|
||||
task.tracer = None;
|
||||
task.settings.maps.select(selected.iter().copied());
|
||||
let (width, height) = if resized { (64, 32) } else { (128, 64) };
|
||||
task.previous_maps = BakedMaps {
|
||||
resolution: width,
|
||||
maps: PREVIOUS_MAPS.into_iter().map(|map| (map, Arc::new(vec![0.25; width as usize * height * map.components()]))).collect(),
|
||||
};
|
||||
task
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_allocates_only_truly_unchecked_resized_maps_once() {
|
||||
for (selected, resized, excluded) in [
|
||||
(SELECTED_MAPS.as_slice(), true, true),
|
||||
(PREVIOUS_MAPS.as_slice(), true, true),
|
||||
(SELECTED_MAPS.as_slice(), false, true),
|
||||
(SELECTED_MAPS.as_slice(), true, false),
|
||||
] {
|
||||
let task = partial_task(selected, resized, excluded);
|
||||
let whole = task.run(&Progress::new()).unwrap();
|
||||
super::super::preserve_tiles::take_retained_allocations();
|
||||
let mut allocations = Vec::new();
|
||||
let mut handed_over = Vec::new();
|
||||
let output = task
|
||||
.run_streaming(&Progress::new(), &mut |map| {
|
||||
allocations.extend(super::super::preserve_tiles::take_retained_allocations());
|
||||
assert!(allocations.iter().all(|map| !selected.contains(map)), "maps scheduled to bake must never allocate retained buffers");
|
||||
handed_over.push(map);
|
||||
})
|
||||
.unwrap();
|
||||
allocations.extend(super::super::preserve_tiles::take_retained_allocations());
|
||||
let expected: Vec<_> = PREVIOUS_MAPS.into_iter().filter(|map| resized && excluded && !selected.contains(map)).collect();
|
||||
assert_eq!(allocations, expected, "each truly unchecked resized map must allocate exactly once");
|
||||
assert_eq!(output.maps.keys().collect::<Vec<_>>(), whole.maps.keys().collect::<Vec<_>>());
|
||||
for (map, pixels) in &whole.maps {
|
||||
assert_eq!(*output.maps[map], *pixels, "{map:?} must preserve the ordinary bake's pixels");
|
||||
}
|
||||
for map in handed_over {
|
||||
assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map]), "streaming must keep sharing the baked buffer");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_a_partial_stream_does_not_resample_future_maps() {
|
||||
let task = partial_task(&SELECTED_MAPS, true, true);
|
||||
let whole = task.run(&Progress::new()).unwrap();
|
||||
super::super::preserve_tiles::take_retained_allocations();
|
||||
let progress = Progress::new();
|
||||
let mut handed_over = Vec::new();
|
||||
let result = task.run_streaming(&progress, &mut |map| {
|
||||
handed_over.push(map);
|
||||
progress.cancel();
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(handed_over.len(), 1);
|
||||
for map in handed_over {
|
||||
assert_eq!(*map.data, whole.maps[&map.map], "cancellation leaves the handed-over map whole");
|
||||
}
|
||||
assert_eq!(super::super::preserve_tiles::take_retained_allocations(), [BakedMap::Normal]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_streaming_selection_keeps_the_ordinary_bake_behavior() {
|
||||
let task = partial_task(&[], true, true);
|
||||
super::super::preserve_tiles::take_retained_allocations();
|
||||
let whole = task.run(&Progress::new());
|
||||
let expected_allocations = super::super::preserve_tiles::take_retained_allocations();
|
||||
let output = task.run_streaming(&Progress::new(), &mut |_| panic!("an empty selection must not stream a map"));
|
||||
assert_eq!(super::super::preserve_tiles::take_retained_allocations(), expected_allocations);
|
||||
match (whole, output) {
|
||||
(Ok(whole), Ok(output)) => {
|
||||
assert_eq!((output.resolution, output.height), (whole.resolution, whole.height));
|
||||
assert_eq!(output.maps.keys().collect::<Vec<_>>(), whole.maps.keys().collect::<Vec<_>>());
|
||||
for (map, pixels) in whole.maps {
|
||||
assert_eq!(*output.maps[&map], pixels);
|
||||
}
|
||||
}
|
||||
(Err(whole), Err(output)) => assert_eq!(whole.to_string(), output.to_string()),
|
||||
_ => panic!("empty streaming and ordinary bakes must agree"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -8,13 +8,15 @@ use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use texturecraft_core::BakePaintTarget;
|
||||
|
||||
use crate::{BakeMesh, BakeTask};
|
||||
use super::{BakeCageInputs, MergedHigh};
|
||||
use crate::{BakeMesh, BakeTask, StreamedBake};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_bake::tracing::Tracer;
|
||||
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();
|
||||
@@ -159,15 +207,28 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the
|
||||
/// preview that showed them holds the same ones)
|
||||
pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> {
|
||||
let tracer = output.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps))?;
|
||||
self.log.push(format!("Baked texture set {texture_set} ({tracer})"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
|
||||
let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
|
||||
self.store_bake_maps(texture_set, output.resolution, output.height, maps)
|
||||
}
|
||||
|
||||
fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap<BakedMap, Arc<Vec<f32>>>) -> Result<()> {
|
||||
let entry = self.doc.baked.entry(texture_set).or_default();
|
||||
if entry.resolution != output.resolution || entry.maps.keys().any(|map| entry.height(*map) != output.height) {
|
||||
if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) {
|
||||
entry.maps.clear();
|
||||
}
|
||||
entry.resolution = output.resolution;
|
||||
for (map, pixels) in output.maps {
|
||||
entry.maps.insert(map, Arc::new(pixels));
|
||||
}
|
||||
|
||||
entry.resolution = resolution;
|
||||
entry.maps.extend(maps);
|
||||
self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
//! 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;
|
||||
mod model_patch;
|
||||
mod paint_command;
|
||||
mod preserve_tiles;
|
||||
mod streamed_bake;
|
||||
mod streamed_map;
|
||||
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;
|
||||
pub use streamed_bake::StreamedBake;
|
||||
pub use streamed_map::StreamedMap;
|
||||
pub use texturecraft_bake::*;
|
||||
|
||||
use crate::CommandSpec;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use texturecraft_bake::BakeOutput;
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
@@ -29,9 +30,18 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti
|
||||
}
|
||||
}
|
||||
|
||||
// Keep unchecked map outputs too when a partial bake changes the atlas dimensions
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retain only maps outside the full task selection, once per completed atlas.
|
||||
/// A one-map streaming pass must not resample maps that are still scheduled to bake.
|
||||
pub(super) fn restore_unchecked(output: &mut BakeOutput, previous: &BakedMaps, excluded_tiles: &[(u32, u32)], selected: &[BakedMap]) -> Result<()> {
|
||||
if excluded_tiles.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let size = (output.resolution, output.height);
|
||||
for map in previous.maps.keys() {
|
||||
if output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) {
|
||||
if selected.contains(map) || output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -42,6 +52,8 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti
|
||||
.ok_or_else(|| EngineError::Other("resized bake map exceeds the addressable size".into()))?;
|
||||
let mut pixels = Vec::new();
|
||||
pixels.try_reserve_exact(count).map_err(|error| EngineError::Other(format!("cannot retain mesh map {}: {error}", map.id())))?;
|
||||
#[cfg(test)]
|
||||
RETAINED_ALLOCATIONS.with(|allocations| allocations.borrow_mut().push(*map));
|
||||
for y in 0..size.1 {
|
||||
for x in 0..size.0 {
|
||||
let value = previous.sample(*map, x, y, size).unwrap_or_else(|| map.neutral());
|
||||
@@ -52,3 +64,15 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Restoration is sequential on the calling thread. Record successful retained-buffer allocations
|
||||
// only in unit tests, without a global allocator or interference from parallel test threads.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static RETAINED_ALLOCATIONS: std::cell::RefCell<Vec<texturecraft_core::BakedMap>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn take_retained_allocations() -> Vec<texturecraft_core::BakedMap> {
|
||||
RETAINED_ALLOCATIONS.with(|allocations| std::mem::take(&mut *allocations.borrow_mut()))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// The result of a streamed bake: the finished maps stay shared (`Arc`) with whoever was shown them,
|
||||
/// so the preview and the document hold one buffer per map, never two
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StreamedBake {
|
||||
pub resolution: u32,
|
||||
pub height: u32,
|
||||
pub maps: BTreeMap<BakedMap, Arc<Vec<f32>>>,
|
||||
pub tracer: String,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// One finished map of a streamed bake (see [`crate::BakeTask::run_streaming`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StreamedMap {
|
||||
pub map: BakedMap,
|
||||
/// Position among the maps this bake makes, from 0, and how many there are.
|
||||
pub index: usize,
|
||||
pub total: usize,
|
||||
/// Width and height in texels.
|
||||
pub resolution: u32,
|
||||
pub height: u32,
|
||||
/// Row-major, `map.components()` floats per texel, padded.
|
||||
pub data: Arc<Vec<f32>>,
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
//! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon
|
||||
//! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in
|
||||
//! the document: nothing enters the undo history until a texture set's bake is applied
|
||||
//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already
|
||||
//! applied keep their results and undo steps. The preview shows one map at a time, raw on the
|
||||
//! model; maps and texture sets not baked yet show their neutral value.
|
||||
|
||||
mod preview_set;
|
||||
mod preview_show;
|
||||
mod stage;
|
||||
|
||||
pub use preview_set::PreviewSet;
|
||||
pub use preview_show::PreviewShow;
|
||||
pub use stage::Stage;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use crate::bake::StreamedMap;
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::session::ViewMode;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// What painting says while a bake preview shows (the app translates it).
|
||||
pub const PAINTING_PAUSED: &str = "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"bake.preview",
|
||||
"Bake preview",
|
||||
[],
|
||||
None,
|
||||
"{show?: \"follow\" (the newest finished map) | \"material\" | \"map:<id>\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)",
|
||||
always,
|
||||
preview
|
||||
)]
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BakePreview {
|
||||
/// The view mode to put back when the preview ends.
|
||||
pub restore: ViewMode,
|
||||
pub show: PreviewShow,
|
||||
pub sets: BTreeMap<usize, PreviewSet>,
|
||||
/// The texture set being baked.
|
||||
pub current: Option<usize>,
|
||||
/// The last map that finished.
|
||||
pub newest: Option<BakedMap>,
|
||||
}
|
||||
|
||||
impl BakePreview {
|
||||
/// The map the view shows, None for the material.
|
||||
pub fn shown(&self) -> Option<BakedMap> {
|
||||
match self.show {
|
||||
PreviewShow::Material => None,
|
||||
PreviewShow::Pin(map) => Some(map),
|
||||
PreviewShow::Follow => self
|
||||
.newest
|
||||
.or_else(|| self.current_set().and_then(|set| set.order.first().copied()))
|
||||
.or_else(|| self.sets.values().find_map(|set| set.order.first().copied())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn current_set(&self) -> Option<&PreviewSet> {
|
||||
self.sets.get(&self.current?)
|
||||
}
|
||||
|
||||
/// The map being baked now (None between sets and once the set's maps are all in).
|
||||
pub fn stage(&self) -> Option<Stage> {
|
||||
let texture_set = self.current?;
|
||||
let set = self.sets.get(&texture_set)?;
|
||||
let done = set.baked.maps.len();
|
||||
Some(Stage { texture_set, map: *set.order.get(done)?, position: done + 1, total: set.order.len() })
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Start a preview from each selected texture set's enabled maps, in the same order as
|
||||
/// [`crate::BakeTask::maps`]. Invalid indices return the project's texture-set error before
|
||||
/// changing the preview or view mode. This reads settings without preparing bake geometry.
|
||||
pub fn bake_preview_begin_for(&mut self, sets: &[usize]) -> Result<()> {
|
||||
let orders = sets
|
||||
.iter()
|
||||
.map(|&texture_set| {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok((texture_set, set.bake.maps.enabled().collect()))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
|
||||
self.bake_preview_begin(orders);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view
|
||||
/// follows the newest map and every set shows neutral values until its maps arrive. The
|
||||
/// view mode in use comes back with [`Session::bake_preview_end`]. An active stroke is
|
||||
/// discarded so a later pointer release cannot commit paint during the preview.
|
||||
pub fn bake_preview_begin(&mut self, sets: Vec<(usize, Vec<BakedMap>)>) {
|
||||
self.cancel_stroke();
|
||||
|
||||
let restore = self.bake_preview.as_ref().map_or(self.view, |preview| preview.restore);
|
||||
let sets = sets.into_iter().map(|(texture_set, order)| (texture_set, PreviewSet { baked: BakedMaps::default(), order })).collect();
|
||||
|
||||
self.bake_preview = Some(BakePreview { restore, show: PreviewShow::Follow, sets, current: None, newest: None });
|
||||
self.bake_preview_refresh();
|
||||
}
|
||||
|
||||
/// The texture set whose maps stream in now.
|
||||
pub fn bake_preview_set_current(&mut self, texture_set: usize) {
|
||||
if let Some(preview) = &mut self.bake_preview {
|
||||
preview.current = Some(texture_set);
|
||||
}
|
||||
|
||||
self.bake_preview_refresh();
|
||||
}
|
||||
|
||||
/// Install one finished map of set `texture_set`. Returns false when no preview shows.
|
||||
pub fn bake_preview_map(&mut self, texture_set: usize, streamed: StreamedMap) -> bool {
|
||||
let Some(preview) = &mut self.bake_preview else { return false };
|
||||
|
||||
let set = preview.sets.entry(texture_set).or_default();
|
||||
|
||||
// A new bake of the set starts from nothing (the baker never repeats a map)
|
||||
if streamed.index == 0 {
|
||||
set.baked = BakedMaps::default();
|
||||
}
|
||||
|
||||
set.baked.resolution = streamed.resolution;
|
||||
set.baked.maps.insert(streamed.map, streamed.data);
|
||||
preview.newest = Some(streamed.map);
|
||||
self.bake_preview_refresh();
|
||||
true
|
||||
}
|
||||
|
||||
/// Choose what the view shows (Follow, a pinned map or the material).
|
||||
pub fn bake_preview_show(&mut self, show: PreviewShow) -> Result<()> {
|
||||
let Some(preview) = &mut self.bake_preview else { return Err(bad("bake.preview", "no bake is running")) };
|
||||
|
||||
preview.show = show;
|
||||
self.bake_preview_refresh();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The user picked a view mode during a bake: a mesh map pins it, any other mode shows
|
||||
/// the material and is what comes back when the bake ends.
|
||||
pub(crate) fn bake_preview_user_view(&mut self, view: ViewMode) {
|
||||
let Some(preview) = &mut self.bake_preview else { return };
|
||||
|
||||
match view {
|
||||
ViewMode::MeshMap(map) => preview.show = PreviewShow::Pin(map),
|
||||
other => {
|
||||
preview.show = PreviewShow::Material;
|
||||
preview.restore = other;
|
||||
}
|
||||
}
|
||||
|
||||
self.bake_preview_refresh();
|
||||
if !matches!(view, ViewMode::MeshMap(_)) {
|
||||
self.view = view;
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop the displayed maps and restore the previous view mode. This does not stop a
|
||||
/// worker or undo any applied results; the UI also uses it when leaving Bake mode.
|
||||
pub fn bake_preview_end(&mut self) {
|
||||
if let Some(preview) = self.bake_preview.take() {
|
||||
self.view = preview.restore;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bake_preview_active(&self) -> bool {
|
||||
self.bake_preview.is_some()
|
||||
}
|
||||
|
||||
/// The streamed maps of set `texture_set` while a preview shows (empty for a set not baked
|
||||
/// yet: neutral values), None when the document's baked maps are what shows.
|
||||
pub fn bake_preview_baked(&self, texture_set: usize) -> Option<&BakedMaps> {
|
||||
self.bake_preview.as_ref()?.sets.get(&texture_set).map(|set| &set.baked)
|
||||
}
|
||||
|
||||
/// Why painting is not possible now, when a bake preview shows.
|
||||
pub fn painting_blocked(&self) -> Option<&'static str> {
|
||||
self.bake_preview.as_ref().map(|_| PAINTING_PAUSED)
|
||||
}
|
||||
|
||||
fn bake_preview_refresh(&mut self) {
|
||||
let Some(preview) = &self.bake_preview else { return };
|
||||
|
||||
self.view = match preview.shown() {
|
||||
Some(map) => ViewMode::MeshMap(map),
|
||||
None => ViewMode::Material,
|
||||
};
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// The preview as JSON, for `bake.preview`, `session.inspect` and `ui.inspect`.
|
||||
pub fn preview_json(session: &Session) -> Value {
|
||||
let Some(preview) = &session.bake_preview else { return json!({ "active": false }) };
|
||||
|
||||
let stage = preview.stage().map(|stage| json!({ "set": stage.texture_set, "map": stage.map.id(), "n": stage.position, "total": stage.total }));
|
||||
let sets: Vec<Value> = preview
|
||||
.sets
|
||||
.iter()
|
||||
.map(|(texture_set, set)| {
|
||||
json!({
|
||||
"set": texture_set,
|
||||
"order": set.order.iter().map(|map| map.id()).collect::<Vec<_>>(),
|
||||
"done": set.baked.maps.keys().map(|map| map.id()).collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
json!({
|
||||
"active": true,
|
||||
"show": preview.show.id(),
|
||||
"shown": preview.shown().map(|map| map.id()),
|
||||
"newest": preview.newest.map(|map| map.id()),
|
||||
"restore": preview.restore.label(),
|
||||
"stage": stage,
|
||||
"sets": sets,
|
||||
})
|
||||
}
|
||||
|
||||
fn preview(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if let Some(show) = strp(params, "show") {
|
||||
let show = PreviewShow::parse(show).ok_or_else(|| bad("bake.preview", format!("unknown `show` {show:?}: follow, material or map:<id>")))?;
|
||||
session.bake_preview_show(show)?;
|
||||
}
|
||||
|
||||
Ok(preview_json(session))
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// The maps of one texture set streamed so far.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PreviewSet {
|
||||
pub baked: BakedMaps,
|
||||
/// The maps this set's bake makes, in the order they arrive.
|
||||
pub order: Vec<BakedMap>,
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// What the 3D view shows while a bake runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PreviewShow {
|
||||
/// The newest finished map (the first one, still neutral, before any is done).
|
||||
Follow,
|
||||
/// One map, pinned: neutral until it is baked.
|
||||
Pin(BakedMap),
|
||||
/// The lit material.
|
||||
Material,
|
||||
}
|
||||
|
||||
impl PreviewShow {
|
||||
pub fn id(self) -> String {
|
||||
match self {
|
||||
PreviewShow::Follow => "follow".into(),
|
||||
PreviewShow::Pin(map) => format!("map:{}", map.id()),
|
||||
PreviewShow::Material => "material".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Option<PreviewShow> {
|
||||
match text {
|
||||
"follow" => Some(PreviewShow::Follow),
|
||||
"material" => Some(PreviewShow::Material),
|
||||
_ => text.strip_prefix("map:").and_then(BakedMap::parse).map(PreviewShow::Pin),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// The map a bake is working on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Stage {
|
||||
pub texture_set: usize,
|
||||
pub map: BakedMap,
|
||||
/// 1-based position among the set's maps, and how many there are.
|
||||
pub position: usize,
|
||||
pub total: usize,
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -57,6 +57,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());
|
||||
@@ -66,10 +67,12 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::quick_mask::specs());
|
||||
v.extend(crate::set_cmds::specs());
|
||||
v.extend(crate::meshmap_cmds::specs());
|
||||
v.extend(crate::meshmap_import_cmds::specs());
|
||||
v.extend(crate::uv_tile_cmds::specs());
|
||||
v.extend(crate::template_cmds::specs());
|
||||
v.extend(crate::project_cmds::specs());
|
||||
v.extend(crate::bake::specs());
|
||||
v.extend(crate::bake_preview::specs());
|
||||
v.extend(crate::materialx_cmds::specs());
|
||||
v.extend(crate::file_cmds::specs());
|
||||
v.extend(crate::preset_cmds::specs());
|
||||
@@ -134,13 +137,11 @@ pub(crate) fn u64p(p: &Value, key: &str) -> Option<u64> {
|
||||
}
|
||||
|
||||
/// A `[x, y, z]` param of finite numbers
|
||||
pub(crate) fn vec3(p: &Value, key: &str) -> Option<Vec3> {
|
||||
let items = p.get(key)?.as_array()?;
|
||||
let numbers: Vec<f32> = items.iter().filter_map(Value::as_f64).map(|number| number as f32).filter(|number| number.is_finite()).collect();
|
||||
match numbers.as_slice() {
|
||||
[x, y, z] => Some(Vec3::new(*x, *y, *z)),
|
||||
_ => None,
|
||||
}
|
||||
pub(crate) fn vec3(params: &Value, key: &str) -> Option<Vec3> {
|
||||
let [x, y, z] = params.get(key)?.as_array()?.as_slice() else { return None };
|
||||
let vector = Vec3::new(x.as_f64()? as f32, y.as_f64()? as f32, z.as_f64()? as f32);
|
||||
|
||||
vector.is_finite().then_some(vector)
|
||||
}
|
||||
|
||||
pub(crate) fn boolp(p: &Value, key: &str) -> Option<bool> {
|
||||
|
||||
+171
-78
@@ -2,12 +2,12 @@
|
||||
//! (a decal fill with a planar projection), as a fill layer with a decal projection.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Channel, Decal, Fill, Layer, LayerId, LayerKind, Projection, Source};
|
||||
use texturecraft_core::{Channel, Decal, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, f32p, has_layer, layer_param, strp, vec3};
|
||||
use crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p, vec3};
|
||||
use crate::tool_cmds::viewport_of;
|
||||
use crate::{Result, Session, cmd};
|
||||
use crate::{Result, Session, StackTarget, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add decal",
|
||||
[],
|
||||
None,
|
||||
"{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round",
|
||||
"{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round",
|
||||
always,
|
||||
add
|
||||
),
|
||||
@@ -25,50 +25,58 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit decal",
|
||||
[],
|
||||
None,
|
||||
"{layer?, x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}",
|
||||
"{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}",
|
||||
has_layer,
|
||||
set
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Where a decal goes: a surface point and its normal, from `x`/`y` (viewport pixels, the view
|
||||
/// center by default) or `position` + `normal`. None when `optional` and neither is given.
|
||||
fn placement(s: &Session, cmd: &str, p: &Value, optional: bool) -> Result<Option<(Vec3, Vec3)>> {
|
||||
if let Some(pos) = vec3(p, "position") {
|
||||
let n = vec3(p, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(cmd, "`position` needs a non-zero `normal`"))?;
|
||||
return Ok(Some((pos, n)));
|
||||
/// Resolve a viewport hit or explicit world position, using `texture_set` for explicit positions.
|
||||
/// Returns None when placement is optional and no position or viewport point is given.
|
||||
fn placement(session: &Session, command: &str, params: &Value, texture_set: usize, optional: bool) -> Result<Option<(Vec3, Vec3, usize)>> {
|
||||
if let Some(position) = vec3(params, "position") {
|
||||
let normal = vec3(params, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(command, "`position` needs a non-zero `normal`"))?;
|
||||
return Ok(Some((position, normal, texture_set)));
|
||||
}
|
||||
let vp = viewport_of(s, p);
|
||||
let at = match (f32p(p, "x"), f32p(p, "y")) {
|
||||
|
||||
let viewport = viewport_of(session, params);
|
||||
let point = match (f32p(params, "x"), f32p(params, "y")) {
|
||||
(Some(x), Some(y)) => Vec2::new(x, y),
|
||||
_ if optional => return Ok(None),
|
||||
_ => vp * 0.5,
|
||||
_ => viewport * 0.5,
|
||||
};
|
||||
let hit = s.pick(at, vp).ok_or_else(|| bad(cmd, "nothing under that point: place the decal on the mesh"))?;
|
||||
if s.doc.project.texture_set(s.ts()).ok().map(|t| t.material) != Some(hit.material) {
|
||||
return Err(bad(cmd, "that surface belongs to another texture set"));
|
||||
}
|
||||
Ok(Some((hit.pos, hit.nrm)))
|
||||
let hit = session.pick(point, viewport).ok_or_else(|| bad(command, "nothing under that point: place the decal on the mesh"))?;
|
||||
let hit_set = session.texture_set_of_material(hit.material).ok_or_else(|| bad(command, "that surface has no texture set"))?;
|
||||
Ok(Some((hit.pos, hit.nrm, hit_set)))
|
||||
}
|
||||
|
||||
/// A new decal's height, relative to the mesh diagonal
|
||||
const DEFAULT_HEIGHT: f32 = 0.25;
|
||||
|
||||
/// The smallest decal side or depth, relative to the mesh diagonal
|
||||
const MIN_SIZE: f32 = 1e-4;
|
||||
|
||||
/// The largest decal side or depth, relative to the mesh diagonal
|
||||
const MAX_SIZE: f32 = 10.0;
|
||||
|
||||
/// The mesh's diagonal (decal sizes are relative to it).
|
||||
fn mesh_size(s: &Session) -> f32 {
|
||||
let (lo, hi) = s.mesh.bounds();
|
||||
(hi - lo).length().max(1e-3)
|
||||
}
|
||||
|
||||
/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`).
|
||||
fn size_param(p: &Value, aspect: f32, diag: f32) -> Option<[f32; 2]> {
|
||||
let v = p.get("size")?;
|
||||
let size = match v.as_array() {
|
||||
Some(a) => [a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32],
|
||||
/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`), within the decal size limits
|
||||
fn size_param(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> {
|
||||
let value = p.get("size")?;
|
||||
let size = match value.as_array() {
|
||||
Some(pair) => [pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32],
|
||||
None => {
|
||||
let h = v.as_f64()? as f32;
|
||||
[h * aspect, h]
|
||||
let height = value.as_f64()? as f32;
|
||||
[height * aspect, height]
|
||||
}
|
||||
};
|
||||
size.iter().all(|x| x.is_finite()).then(|| size.map(|x| x.clamp(diag * 1e-4, diag * 10.0)))
|
||||
size.iter().all(|side| side.is_finite()).then(|| size.map(|side| side.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)))
|
||||
}
|
||||
|
||||
/// The decal's up direction: `up` when given, else the camera's (decals are placed upright on
|
||||
@@ -86,11 +94,25 @@ fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result<Vec3> {
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "layer.add.decal";
|
||||
let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string();
|
||||
let img = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?;
|
||||
let aspect = img.width as f32 / img.height.max(1) as f32;
|
||||
let (center, normal) = placement(s, cmd, p, false)?.ok_or_else(|| bad(cmd, "no placement"))?;
|
||||
let diag = mesh_size(s);
|
||||
let size = size_param(p, aspect, diag).unwrap_or([diag * 0.25 * aspect, diag * 0.25]);
|
||||
let resource = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?;
|
||||
let aspect = resource.width as f32 / resource.height.max(1) as f32;
|
||||
let (center, normal, ts) = placement(s, cmd, p, s.ts(), false)?.ok_or_else(|| bad(cmd, "no placement"))?;
|
||||
|
||||
// None: the image masks a new fill layer
|
||||
let target = match strp(p, "channel") {
|
||||
Some("mask") => None,
|
||||
_ => Some(channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor)),
|
||||
};
|
||||
let set_channels = s.doc.project.texture_set(ts)?.channel_list();
|
||||
if let Some(channel) = target
|
||||
&& !set_channels.contains(&channel)
|
||||
{
|
||||
return Err(bad(cmd, format!("the texture set has no {} channel", channel.label())));
|
||||
}
|
||||
|
||||
let mesh_diagonal = mesh_size(s);
|
||||
let default_height = mesh_diagonal * DEFAULT_HEIGHT;
|
||||
let size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]);
|
||||
let decal = Decal {
|
||||
center: center.to_array(),
|
||||
normal: normal.to_array(),
|
||||
@@ -98,68 +120,139 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
size,
|
||||
rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0),
|
||||
offset: [0.0; 2],
|
||||
depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |d| d.clamp(diag * 1e-4, diag * 10.0)),
|
||||
// By default it reaches half its larger side into the surface
|
||||
depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)),
|
||||
};
|
||||
let ts = s.ts();
|
||||
let base =
|
||||
strp(p, "name").map(str::to_string).unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|n| n.to_str()).unwrap_or("Decal").to_string());
|
||||
|
||||
// A decal dropped on another texture set goes there and selects it, as a dropped material does
|
||||
if ts != s.ts() {
|
||||
crate::set_cmds::select_set(s, ts);
|
||||
}
|
||||
|
||||
let base = strp(p, "name")
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Decal").to_string());
|
||||
let name = s.doc.project.next_layer_name(ts, &base);
|
||||
let id = s.edit("Add decal", |s| {
|
||||
let (id, mask_effect) = s.edit("Add decal", |s| {
|
||||
let id = s.doc.project.alloc_id();
|
||||
let Some(channel) = target else {
|
||||
let effect_id = s.doc.project.alloc_id();
|
||||
let mut layer = Layer::new(id, name, LayerKind::Fill(Fill::default()), &set_channels);
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(Effect::new(effect_id, EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::Decal(decal) }));
|
||||
layer.mask = Some(mask);
|
||||
crate::layer_cmds::insert_selected(s, layer)?;
|
||||
s.target = StackTarget::Effect(effect_id);
|
||||
return Ok((id, Some(effect_id)));
|
||||
};
|
||||
|
||||
let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() };
|
||||
fill.sources.insert(Channel::BaseColor, Source::image(image.clone()));
|
||||
crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[Channel::BaseColor]))
|
||||
fill.sources.insert(channel, Source::image(image.clone()));
|
||||
crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?;
|
||||
Ok((id, None))
|
||||
})?;
|
||||
Ok(json!({ "layer": id.0, "decal": decal }))
|
||||
Ok(json!({ "layer": id.0, "decal": decal, "maskEffect": mask_effect.map(|effect| effect.0) }))
|
||||
}
|
||||
|
||||
/// The decal of fill layer `id`.
|
||||
fn decal_of(s: &Session, cmd: &str, id: LayerId) -> Result<Decal> {
|
||||
/// The decal of fill layer `id`, or of mask fill effect `effect` when given
|
||||
fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option<LayerId>) -> Result<Decal> {
|
||||
if let Some(effect) = effect {
|
||||
return match s.doc.project.effect(effect).map(|(_, effect)| &effect.kind) {
|
||||
Some(EffectKind::Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal),
|
||||
_ => Err(bad(cmd, "the effect is not a decal (layer.add.decal with channel mask)")),
|
||||
};
|
||||
}
|
||||
|
||||
match &s.doc.project.layer(id)?.kind {
|
||||
LayerKind::Fill(Fill { projection: Projection::Decal(d), .. }) => Ok(*d),
|
||||
LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal),
|
||||
_ => Err(bad(cmd, "the layer is not a decal (layer.add.decal)")),
|
||||
}
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "layer.decal.set";
|
||||
let id = s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|l| l.id).ok_or_else(|| bad(cmd, "no layer"))?;
|
||||
let mut d = decal_of(s, cmd, id)?;
|
||||
let diag = mesh_size(s);
|
||||
if let Some((center, normal)) = placement(s, cmd, p, true)? {
|
||||
(d.center, d.normal, d.offset) = (center.to_array(), normal.to_array(), [0.0; 2]);
|
||||
}
|
||||
if p.get("up").is_some() {
|
||||
d.up = decal_up(s, cmd, p, Vec3::from(d.normal))?.to_array();
|
||||
}
|
||||
if let Some(size) = size_param(p, d.size[0] / d.size[1].max(1e-6), diag) {
|
||||
d.size = size;
|
||||
}
|
||||
if let Some(r) = f32p(p, "rotation") {
|
||||
d.rotation = r.rem_euclid(360.0);
|
||||
}
|
||||
if let Some(o) = p.get("offset").and_then(Value::as_array) {
|
||||
let v: Vec<f32> = o.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect();
|
||||
let [x, y] = v.as_slice() else { return Err(bad(cmd, "`offset` must be [right, up]")) };
|
||||
d.offset = [x.clamp(-diag, diag), y.clamp(-diag, diag)];
|
||||
}
|
||||
if let Some(v) = f32p(p, "depth") {
|
||||
d.depth = v.clamp(diag * 1e-4, diag * 10.0);
|
||||
}
|
||||
let image = strp(p, "image").map(str::to_string);
|
||||
if let Some(name) = &image
|
||||
&& !s.doc.resources.contains_key(name)
|
||||
fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let command = "layer.decal.set";
|
||||
let effect = u64p(params, "effect").map(LayerId);
|
||||
let layer_id = match effect {
|
||||
Some(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner).ok_or_else(|| bad(command, format!("no effect {}", effect.0)))?,
|
||||
None => session.doc.project.content_layer(layer_param(session, command, params)?).map(|layer| layer.id).ok_or_else(|| bad(command, "no layer"))?,
|
||||
};
|
||||
if let (Some(effect), Some(layer)) = (effect, u64p(params, "layer"))
|
||||
&& layer != layer_id.0
|
||||
{
|
||||
return Err(bad(cmd, format!("no image resource `{name}`")));
|
||||
return Err(bad(command, format!("effect {} is not in layer {layer}", effect.0)));
|
||||
}
|
||||
s.edit("Edit decal", |s| {
|
||||
if let LayerKind::Fill(f) = &mut s.doc.project.layer_mut(id)?.kind {
|
||||
f.projection = Projection::Decal(d);
|
||||
if let Some(name) = image {
|
||||
f.sources.insert(Channel::BaseColor, Source::image(name));
|
||||
|
||||
let mut decal = decal_of(session, command, layer_id, effect)?;
|
||||
let texture_set =
|
||||
session.doc.project.locate(layer_id).map(|(texture_set, _, _)| texture_set).ok_or_else(|| bad(command, "the decal has no texture set"))?;
|
||||
let mesh_diagonal = mesh_size(session);
|
||||
if let Some((center, normal, hit_set)) = placement(session, command, params, texture_set, true)? {
|
||||
// Selecting another set must not let this decal leave its layer's stack
|
||||
if hit_set != texture_set {
|
||||
return Err(bad(command, "that surface belongs to another texture set"));
|
||||
}
|
||||
|
||||
(decal.center, decal.normal, decal.offset) = (center.to_array(), normal.to_array(), [0.0; 2]);
|
||||
}
|
||||
if params.get("up").is_some() {
|
||||
decal.up = decal_up(session, command, params, Vec3::from(decal.normal))?.to_array();
|
||||
}
|
||||
if let Some(size) = size_param(params, decal.size[0] / decal.size[1].max(1e-6), mesh_diagonal) {
|
||||
decal.size = size;
|
||||
}
|
||||
if let Some(rotation) = f32p(params, "rotation") {
|
||||
decal.rotation = rotation.rem_euclid(360.0);
|
||||
}
|
||||
if let Some(offset) = params.get("offset").and_then(Value::as_array) {
|
||||
let values: Vec<f32> = offset.iter().filter_map(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()).collect();
|
||||
let [right, up] = values.as_slice() else { return Err(bad(command, "`offset` must be [right, up]")) };
|
||||
|
||||
decal.offset = [right.clamp(-mesh_diagonal, mesh_diagonal), up.clamp(-mesh_diagonal, mesh_diagonal)];
|
||||
}
|
||||
if let Some(depth) = f32p(params, "depth") {
|
||||
decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
|
||||
}
|
||||
|
||||
let image = strp(params, "image").map(str::to_string);
|
||||
if let Some(name) = &image
|
||||
&& !session.doc.resources.contains_key(name)
|
||||
{
|
||||
return Err(bad(command, format!("no image resource `{name}`")));
|
||||
}
|
||||
|
||||
session.edit("Edit decal", |session| {
|
||||
if let Some(effect) = effect {
|
||||
if let Some(EffectKind::Fill { source, projection }) = session.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) {
|
||||
*projection = Projection::Decal(decal);
|
||||
if let Some(image) = image {
|
||||
*source = Source::image(image);
|
||||
}
|
||||
}
|
||||
} else if let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer_id)?.kind {
|
||||
fill.projection = Projection::Decal(decal);
|
||||
|
||||
// The new image goes where the decal's image is (the channel it was placed in)
|
||||
let placed = fill.sources.values().find_map(|source| match source {
|
||||
Source::Image { name, .. } => Some(name.clone()),
|
||||
_ => None,
|
||||
});
|
||||
match (image, placed) {
|
||||
(Some(image), Some(placed)) => {
|
||||
for source in fill.sources.values_mut() {
|
||||
if let Source::Image { name, .. } = source
|
||||
&& *name == placed
|
||||
{
|
||||
name.clone_from(&image);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(image), None) => {
|
||||
fill.sources.insert(Channel::BaseColor, Source::image(image));
|
||||
}
|
||||
(None, _) => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "layer": id.0, "decal": d }))
|
||||
Ok(json!({ "layer": layer_id.0, "decal": decal }))
|
||||
}
|
||||
@@ -331,6 +331,11 @@ mod native {
|
||||
strp(p, key).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required")))
|
||||
}
|
||||
|
||||
/// `path` made absolute (as given when that fails), for [`Project::mesh_path`].
|
||||
pub fn absolute(path: &str) -> String {
|
||||
std::path::absolute(Path::new(path)).map_or_else(|_| path.to_string(), |p| p.display().to_string())
|
||||
}
|
||||
|
||||
/// Mesh file `path` with the files it references next to it folded in (a `.gltf`'s buffers
|
||||
/// and images, a loose USD layer's textures), ready to import and store in the project.
|
||||
pub fn read_mesh(cmd: &str, path: &str) -> Result<texturecraft_formats::MeshFile> {
|
||||
@@ -349,6 +354,7 @@ mod native {
|
||||
} else {
|
||||
let f = read_mesh("file.open", path)?;
|
||||
let mut s = Session::from_mesh_bytes(&f.name, &f.bytes, 2048, &stem_of(path))?;
|
||||
s.doc.project.mesh_path = absolute(path);
|
||||
s.log.extend(f.warnings);
|
||||
Ok(s)
|
||||
}
|
||||
@@ -367,8 +373,10 @@ mod native {
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use native::{open_path, read_mesh};
|
||||
pub use native::{absolute, open_path, read_mesh};
|
||||
|
||||
/// `file.new {mesh, name?, resolution?, uvTiles?, template?}`: a new project from the mesh file `mesh`,
|
||||
/// remembering its path for Reimport mesh.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn new_from_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = native::path_param(p, "mesh", "file.new")?;
|
||||
@@ -377,6 +385,7 @@ fn new_from_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let res = u64p(p, "resolution").or(template.as_ref().map(|t| u64::from(t.resolution))).unwrap_or(2048);
|
||||
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
|
||||
let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?;
|
||||
next.doc.project.mesh_path = native::absolute(path);
|
||||
next.log.extend(f.warnings);
|
||||
if let Some(t) = &template {
|
||||
next.apply_template(t);
|
||||
@@ -414,14 +423,28 @@ fn save_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
native::save_to(s, &path, false)
|
||||
}
|
||||
|
||||
/// `file.reimportMesh {path?, preserveStrokes?}`: reimport from `path`, or from the project's own
|
||||
/// copy of the mesh when there is none. A path given is remembered as the project's mesh path.
|
||||
/// The remembered path is never read implicitly (a project file could point it anywhere on the
|
||||
/// host); callers that may read host files pass [`Session::remembered_mesh_path`] as `path`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let file = strp(p, "path").map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?;
|
||||
s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))
|
||||
let path = strp(p, "path");
|
||||
let file = path.map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?;
|
||||
let reply = s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))?;
|
||||
if let Some(path) = path {
|
||||
s.doc.project.mesh_path = native::absolute(path);
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Session {
|
||||
/// The file the mesh was imported from, when it is still there: what Reimport mesh reads again.
|
||||
pub fn remembered_mesh_path(&self) -> Option<&str> {
|
||||
Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file())
|
||||
}
|
||||
|
||||
/// Replace the mesh with `file` (or re-read the project's own copy) and keep the project:
|
||||
/// texture sets map by material index. Nothing changes unless the new mesh fits the project.
|
||||
/// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies
|
||||
@@ -449,6 +472,7 @@ impl Session {
|
||||
next.log.extend(warnings);
|
||||
next.path = self.path.clone();
|
||||
next.modified = true;
|
||||
next.project_id = self.project_id;
|
||||
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
|
||||
self.switch_to(next);
|
||||
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
|
||||
@@ -611,14 +635,57 @@ fn close(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Reimport mesh reads the mesh file again from where it was imported, so a change saved to
|
||||
/// the file since shows up (it used to re-read the project's own copy and change nothing).
|
||||
#[test]
|
||||
fn reimport_picks_up_changes_saved_to_the_mesh_file() {
|
||||
let dir = std::env::temp_dir().join(format!("tc_reimport_disk_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("tri.obj");
|
||||
let obj = |z: f32| {
|
||||
format!(
|
||||
"v -1 -1 {z}
|
||||
v 1 -1 0
|
||||
v 1 1 0
|
||||
vt 0 0
|
||||
vt 1 0
|
||||
vt 1 1
|
||||
f 1/1 2/2 3/3
|
||||
"
|
||||
)
|
||||
};
|
||||
std::fs::write(&file, obj(0.0)).unwrap();
|
||||
let path = file.display().to_string();
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128})).unwrap();
|
||||
let low = |s: &Session| s.mesh.positions.iter().map(|p| p.z.abs()).fold(0.0_f32, f32::max);
|
||||
assert_eq!(low(&s), 0.0);
|
||||
// Edit the file, save the project, reopen it, then reimport with no path.
|
||||
std::fs::write(&file, obj(0.5)).unwrap();
|
||||
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(low(&reopened), 0.0, "the project still holds the old copy");
|
||||
// A command without a path never reads the remembered host path (automation allows it).
|
||||
crate::execute(&mut reopened, "file.reimportMesh", &Value::Null).unwrap();
|
||||
assert_eq!(low(&reopened), 0.0, "no path: the project's own copy");
|
||||
let remembered = reopened.remembered_mesh_path().map(str::to_string).expect("the imported file is remembered");
|
||||
crate::execute(&mut reopened, "file.reimportMesh", &json!({ "path": remembered })).unwrap();
|
||||
assert!(low(&reopened) > 0.0, "the edited file must be read again");
|
||||
// The file gone: nothing is remembered, so the UI asks for one.
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
assert!(reopened.remembered_mesh_path().is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reimporting_a_saved_project_marks_it_modified() {
|
||||
let obj = b"v -1 -1 0\nv 1 -1 0\nv 1 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nf 1/1 2/2 3/3\n";
|
||||
let original = Session::from_mesh_bytes("mesh.obj", obj, 128, "mesh").unwrap();
|
||||
let mut saved = Session::from_project_bytes(&original.to_project_bytes().unwrap()).unwrap();
|
||||
assert!(!saved.modified);
|
||||
let project = saved.project_id;
|
||||
crate::execute(&mut saved, "file.reimportMesh", &Value::Null).unwrap();
|
||||
assert!(saved.modified, "reimport must trigger the unsaved-changes prompt");
|
||||
assert_eq!(saved.project_id, project, "a reimport stays the same project");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -176,6 +187,7 @@ pub fn session(s: &Session) -> Value {
|
||||
"layers": stack(s, ts),
|
||||
"tool": { "tool": s.tool.tool.id(), "brush": crate::tool_cmds::brush_json(s) },
|
||||
"view": s.view.label(),
|
||||
"bakePreview": crate::bake_preview::preview_json(s),
|
||||
"camera": crate::view_cmds::camera_json(s),
|
||||
"display": s.doc.project.display,
|
||||
"history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() },
|
||||
|
||||
@@ -9,12 +9,16 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod bake;
|
||||
pub mod bake_preview;
|
||||
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,15 +26,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;
|
||||
@@ -44,15 +53,21 @@ pub mod set_cmds;
|
||||
pub mod smart_masks;
|
||||
pub mod template_cmds;
|
||||
pub mod text_cmds;
|
||||
pub mod thumbs;
|
||||
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 bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap};
|
||||
pub use bake_preview::{BakePreview, PreviewShow};
|
||||
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
@@ -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| {
|
||||
|
||||
@@ -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,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,
|
||||
}
|
||||
@@ -38,55 +38,91 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let map = map_param(p, CMD)?;
|
||||
let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?;
|
||||
let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
|
||||
let set = s.doc.project.texture_set(ts)?.clone();
|
||||
let tiles = set.tile_grid().map(|grid| tile_images(&s.images, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?;
|
||||
// Every mesh map of a set shares one size: the other maps', or what a bake would make (a
|
||||
// block of the bake resolution per tile of the atlas).
|
||||
let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows));
|
||||
let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) {
|
||||
Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))),
|
||||
None => {
|
||||
let (width, height) = set.bake.common.output_size();
|
||||
(width.saturating_mul(cols), height.saturating_mul(rows))
|
||||
}
|
||||
let image = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
|
||||
let texture_set = s.doc.project.texture_set(ts)?;
|
||||
let images = match texture_set.tile_grid() {
|
||||
Some(_) => tile_images(&s.images, CMD, name, &texture_set.uv_tiles)?,
|
||||
None => BTreeMap::from([(FIRST_TILE, image)]),
|
||||
};
|
||||
if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) {
|
||||
return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty")));
|
||||
}
|
||||
let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX;
|
||||
let data = match &tiles {
|
||||
None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)),
|
||||
// An atlas texel reads the image of the tile its mesh UV falls in.
|
||||
Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| {
|
||||
let uv = grid.from_atlas([u, v]);
|
||||
udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
|
||||
}),
|
||||
};
|
||||
s.edit("Use image as mesh map", |s| {
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
entry.resolution = res;
|
||||
entry.maps.insert(map, Arc::new(data));
|
||||
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "map": map.id(), "resolution": res }))
|
||||
|
||||
let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?;
|
||||
Ok(json!({ "map": map.id(), "resolution": resolution }))
|
||||
}
|
||||
|
||||
/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for
|
||||
/// each tile's.
|
||||
fn tile_images(images: &ImageStore, name: &str, tiles: &[u32]) -> Result<BTreeMap<u32, Arc<ImageRes>>> {
|
||||
const CMD: &str = "textureSet.meshMap.set";
|
||||
let at = udim_in(name).ok_or_else(|| bad(CMD, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?;
|
||||
/// The tile number a set without UV tiles keys its one image by
|
||||
pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start();
|
||||
|
||||
/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width
|
||||
pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap<u32, Arc<ImageRes>>) -> Result<u32> {
|
||||
let texture_set = s.doc.project.texture_set(ts)?;
|
||||
let grid = texture_set.tile_grid();
|
||||
if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) {
|
||||
return Err(bad(cmd, format!("no image for UV tile {tile}")));
|
||||
}
|
||||
|
||||
let (width, height) = image_map_size(s, cmd, ts)?;
|
||||
|
||||
let flip_green = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX;
|
||||
let data = match (grid, images.values().next()) {
|
||||
(_, None) => return Err(bad(cmd, "no image to use")),
|
||||
(None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)),
|
||||
// An atlas texel reads the image of the tile its mesh UV falls in
|
||||
(Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| {
|
||||
let uv = grid.from_atlas([u, v]);
|
||||
udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
|
||||
}),
|
||||
};
|
||||
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
entry.resolution = width;
|
||||
entry.maps.insert(map, Arc::new(data));
|
||||
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
|
||||
Ok(width)
|
||||
}
|
||||
|
||||
/// Dimensions shared by imported mesh maps, checked before allocating the resampled pixels
|
||||
pub(crate) fn image_map_size(s: &Session, cmd: &str, ts: usize) -> Result<(u32, u32)> {
|
||||
let texture_set = s.doc.project.texture_set(ts)?;
|
||||
let grid = texture_set.tile_grid();
|
||||
|
||||
// Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile)
|
||||
let (columns, rows) = grid.map_or((1, 1), |grid| (grid.cols, grid.rows));
|
||||
let (width, height) = match s.doc.baked.get(&ts).filter(|baked| !baked.maps.is_empty()) {
|
||||
Some(baked) => (baked.resolution, baked.maps.keys().next().map_or(baked.resolution, |other| baked.height(*other))),
|
||||
None => {
|
||||
let (width, height) = texture_set.bake.common.output_size();
|
||||
(width.saturating_mul(columns), height.saturating_mul(rows))
|
||||
}
|
||||
};
|
||||
let empty = width == 0 || height == 0;
|
||||
let too_many_texels = u64::from(width) * u64::from(height) > texturecraft_bake::MAX_TEXELS;
|
||||
let too_wide = grid.is_none() && width > MAX_RESOLUTION;
|
||||
if empty || too_many_texels || too_wide {
|
||||
return Err(bad(cmd, format!("mesh map size {width} × {height} is too large or empty")));
|
||||
}
|
||||
|
||||
Ok((width, height))
|
||||
}
|
||||
|
||||
/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's
|
||||
fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result<BTreeMap<u32, Arc<ImageRes>>> {
|
||||
let tile_at =
|
||||
udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?;
|
||||
let (before_tile, after_tile) = (name.get(..tile_at).unwrap_or_default(), name.get(tile_at + 4..).unwrap_or_default());
|
||||
tiles
|
||||
.iter()
|
||||
.map(|&t| {
|
||||
let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default());
|
||||
images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(CMD, format!("no image `{tile_name}` for UV tile {t}")))
|
||||
.map(|&tile| {
|
||||
let tile_name = format!("{before_tile}{tile}{after_tile}");
|
||||
images.get(&tile_name).cloned().map(|image| (tile, image)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {tile}")))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The UV tile number in a file name (`Body_ao.1002.png` → 1002)
|
||||
pub(crate) fn tile_number(file_name: &str) -> Option<u32> {
|
||||
udim_in(file_name).and_then(|at| file_name.get(at..at + 4)).and_then(|digits| digits.parse().ok())
|
||||
}
|
||||
|
||||
/// Where the last UDIM tile number (four digits alone, in [`UDIM_RANGE`]) in `name` starts.
|
||||
fn udim_in(name: &str) -> Option<usize> {
|
||||
let b = name.as_bytes();
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Which texture set and mesh map a baked map file is for, by file name (`Body_ao.1001.png` = Body's ambient occlusion)
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use texturecraft_core::{BakedMap, UDIM_RANGE};
|
||||
|
||||
/// Mesh maps named by two words anywhere in the file name; they win over the one-word names
|
||||
const TWO_WORD_NAMES: &[(&str, &[&str], BakedMap)] = &[
|
||||
("world", &["normal", "normals"], BakedMap::WorldNormal),
|
||||
("bent", &["normal", "normals"], BakedMap::BentNormal),
|
||||
("ambient", &["occlusion"], BakedMap::AmbientOcclusion),
|
||||
];
|
||||
|
||||
/// Mesh maps named by one word, including the two-word names written as one
|
||||
const ONE_WORD_NAMES: &[(&str, BakedMap)] = &[
|
||||
("worldnormal", BakedMap::WorldNormal),
|
||||
("worldnormals", BakedMap::WorldNormal),
|
||||
("bentnormal", BakedMap::BentNormal),
|
||||
("bentnormals", BakedMap::BentNormal),
|
||||
("ambientocclusion", BakedMap::AmbientOcclusion),
|
||||
("normal", BakedMap::Normal),
|
||||
("normals", BakedMap::Normal),
|
||||
("nrm", BakedMap::Normal),
|
||||
("occlusion", BakedMap::AmbientOcclusion),
|
||||
("ao", BakedMap::AmbientOcclusion),
|
||||
("curvature", BakedMap::Curvature),
|
||||
("curv", BakedMap::Curvature),
|
||||
("id", BakedMap::Id),
|
||||
("position", BakedMap::Position),
|
||||
("pos", BakedMap::Position),
|
||||
("thickness", BakedMap::Thickness),
|
||||
("height", BakedMap::Height),
|
||||
("displacement", BakedMap::Height),
|
||||
("opacity", BakedMap::Opacity),
|
||||
("alpha", BakedMap::Opacity),
|
||||
];
|
||||
|
||||
fn is_separator(c: char) -> bool {
|
||||
matches!(c, '_' | '-' | '.' | ' ')
|
||||
}
|
||||
|
||||
/// The lowercase file name without its folder and extension
|
||||
fn lowercase_stem(path: &str) -> String {
|
||||
Path::new(path).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_lowercase()
|
||||
}
|
||||
|
||||
/// What follows `set_name` at the start of a lowercase stem, when a separator follows it
|
||||
fn after_set_name<'a>(stem: &'a str, set_name: &str) -> Option<&'a str> {
|
||||
if set_name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
stem.strip_prefix(&set_name.to_lowercase()).filter(|rest| rest.starts_with(is_separator))
|
||||
}
|
||||
|
||||
/// The mesh map a file holds, from the words of its name after `set_name`; the last recognised word wins
|
||||
pub(crate) fn baked_map_from_file_name(path: &str, set_name: &str) -> Option<BakedMap> {
|
||||
let stem = lowercase_stem(path);
|
||||
let rest = after_set_name(&stem, set_name).unwrap_or(&stem);
|
||||
let is_tile_number = |word: &str| word.len() == 4 && word.parse::<u32>().is_ok_and(|number| UDIM_RANGE.contains(&number));
|
||||
let words: Vec<&str> = rest.split(is_separator).filter(|word| !word.is_empty() && !is_tile_number(word)).collect();
|
||||
|
||||
let has = |name: &str| words.contains(&name);
|
||||
TWO_WORD_NAMES
|
||||
.iter()
|
||||
.find(|(first, seconds, _)| has(first) && seconds.iter().any(|second| has(second)))
|
||||
.map(|(_, _, map)| *map)
|
||||
.or_else(|| words.iter().rev().find_map(|word| ONE_WORD_NAMES.iter().find(|(name, _)| name == word).map(|(_, map)| *map)))
|
||||
}
|
||||
|
||||
/// The set a file is for: the longest set name its name starts with before a separator (any name with one set)
|
||||
pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Option<usize> {
|
||||
if set_names.len() == 1 {
|
||||
return Some(0);
|
||||
}
|
||||
|
||||
let stem = lowercase_stem(path);
|
||||
set_names.iter().enumerate().filter(|(_, name)| after_set_name(&stem, name).is_some()).max_by_key(|(_, name)| name.chars().count()).map(|(ts, _)| ts)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_word_names_its_map() {
|
||||
let cases = [
|
||||
("Body_normal.png", BakedMap::Normal),
|
||||
("Body_normals.png", BakedMap::Normal),
|
||||
("Body_nrm.png", BakedMap::Normal),
|
||||
("Body_world_normal.png", BakedMap::WorldNormal),
|
||||
("Body_normals_world.png", BakedMap::WorldNormal),
|
||||
("Body_WorldNormal.png", BakedMap::WorldNormal),
|
||||
("Body_bent_normals.png", BakedMap::BentNormal),
|
||||
("Body-ambient-occlusion.png", BakedMap::AmbientOcclusion),
|
||||
("Body_AmbientOcclusion.png", BakedMap::AmbientOcclusion),
|
||||
("Body_occlusion.png", BakedMap::AmbientOcclusion),
|
||||
("Body AO.png", BakedMap::AmbientOcclusion),
|
||||
("Body_curvature.png", BakedMap::Curvature),
|
||||
("Body_curv.png", BakedMap::Curvature),
|
||||
("Body_ID.png", BakedMap::Id),
|
||||
("Body_position.png", BakedMap::Position),
|
||||
("Body_pos.png", BakedMap::Position),
|
||||
("Body_thickness.png", BakedMap::Thickness),
|
||||
("Body_height.png", BakedMap::Height),
|
||||
("Body_displacement.png", BakedMap::Height),
|
||||
("Body_opacity.png", BakedMap::Opacity),
|
||||
("Body_alpha.png", BakedMap::Opacity),
|
||||
];
|
||||
for (file, map) in cases {
|
||||
assert_eq!(baked_map_from_file_name(file, "Body"), Some(map), "{file}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_numbers_and_folders_are_ignored() {
|
||||
assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png", "Body"), Some(BakedMap::AmbientOcclusion));
|
||||
assert_eq!(baked_map_from_file_name("Body_normal_1002.tga", "Body"), Some(BakedMap::Normal));
|
||||
assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_words_match_no_map() {
|
||||
assert_eq!(baked_map_from_file_name("Body_diffuse.png", "Body"), None);
|
||||
assert_eq!(baked_map_from_file_name("Body_1001.png", "Body"), None);
|
||||
assert_eq!(baked_map_from_file_name("ambient.png", "Body"), None);
|
||||
assert_eq!(baked_map_from_file_name("", "Body"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_set_name_is_not_read_as_a_map() {
|
||||
assert_eq!(baked_map_from_file_name("World_normal.png", "World"), Some(BakedMap::Normal));
|
||||
assert_eq!(baked_map_from_file_name("ID_diffuse.png", "ID"), None);
|
||||
assert_eq!(baked_map_from_file_name("Body_ao.png", ""), Some(BakedMap::AmbientOcclusion));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_longest_set_name_wins() {
|
||||
let sets = ["Body", "Body_Upper", "Head"];
|
||||
assert_eq!(texture_set_from_file_name("Body_Upper_ao.png", &sets), Some(1));
|
||||
assert_eq!(texture_set_from_file_name("body_ao.png", &sets), Some(0));
|
||||
assert_eq!(texture_set_from_file_name("HEAD-normal.png", &sets), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_name_must_end_at_a_separator() {
|
||||
let sets = ["Body", "Head"];
|
||||
assert_eq!(texture_set_from_file_name("Bodywork_ao.png", &sets), None);
|
||||
assert_eq!(texture_set_from_file_name("Arm_ao.png", &sets), None);
|
||||
assert_eq!(texture_set_from_file_name("Body.png", &sets), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_set_takes_every_file() {
|
||||
assert_eq!(texture_set_from_file_name("ao.png", &["Body"]), Some(0));
|
||||
assert_eq!(texture_set_from_file_name("Head_ao.png", &["Body"]), Some(0));
|
||||
assert_eq!(texture_set_from_file_name("ao.png", &[]), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images};
|
||||
use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name};
|
||||
use crate::resource_cmds::read_image_file;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
const CMD: &str = "textureSet.meshMap.import";
|
||||
|
||||
/// Most files one import takes: every mesh map of dozens of sets, each split over a few UV tiles
|
||||
const MAX_FILES: usize = 512;
|
||||
|
||||
/// Bound retained file bytes, decoded RGBA floats and resampled maps together, before allocating pixels
|
||||
const MAX_TOTAL_BYTES: u64 = 2 << 30;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"textureSet.meshMap.import",
|
||||
"Import baked maps",
|
||||
[],
|
||||
None,
|
||||
"{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set. A UV-tiled set takes one file per tile, named with the tile number (`Body_ao.1001.png`, `Body_ao.1002.png`). Left out and listed in `unmatched`: files matching no set or map, a second file for one slot or tile, files of a UV-tiled set without one of its tile numbers, and every file of a map missing a tile. One undo step (none when nothing matches); at most 512 files and 2 GiB of file bytes, decoded images and mesh maps; desktop only",
|
||||
always,
|
||||
import
|
||||
)]
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
import_with_budget(s, p, MAX_TOTAL_BYTES)
|
||||
}
|
||||
|
||||
fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result<Value> {
|
||||
let files = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(CMD, "`files` (a list of {path, map?}) is required"))?;
|
||||
if files.len() > MAX_FILES {
|
||||
return Err(bad(CMD, format!("at most {MAX_FILES} files at once")));
|
||||
}
|
||||
|
||||
let set_names: Vec<&str> = s.doc.project.texture_sets.iter().map(|set| set.name.as_str()).collect();
|
||||
let mut slots: BTreeMap<(usize, BakedMap), BTreeMap<u32, &str>> = BTreeMap::new();
|
||||
let mut unmatched = Vec::new();
|
||||
for file in files {
|
||||
let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?;
|
||||
let given_map = match file.get("map") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(id)) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?),
|
||||
Some(_) => return Err(bad(CMD, "`map` must be a mesh map id string")),
|
||||
};
|
||||
|
||||
match slot_of(s, &set_names, path, given_map) {
|
||||
Some((slot, tile)) if !slots.get(&slot).is_some_and(|tiles| tiles.contains_key(&tile)) => {
|
||||
slots.entry(slot).or_default().insert(tile, path);
|
||||
}
|
||||
_ => unmatched.push(path),
|
||||
}
|
||||
}
|
||||
|
||||
// A UV-tiled map needs a file for every tile of its set
|
||||
slots.retain(|(ts, _), tiles| {
|
||||
let complete =
|
||||
s.doc.project.texture_sets.get(*ts).is_some_and(|set| set.tile_grid().is_none() || set.uv_tiles.iter().all(|tile| tiles.contains_key(tile)));
|
||||
if !complete {
|
||||
unmatched.extend(tiles.values());
|
||||
}
|
||||
complete
|
||||
});
|
||||
if slots.is_empty() {
|
||||
return Ok(json!({ "assigned": [], "unmatched": unmatched }));
|
||||
}
|
||||
|
||||
let result = s.edit("Import baked maps", |s| {
|
||||
let mut assigned = Vec::new();
|
||||
let mut remaining_bytes = max_bytes;
|
||||
for ((ts, map), tiles) in &slots {
|
||||
let (width, height) = image_map_size(s, CMD, *ts)?;
|
||||
let map_bytes = u64::from(width) * u64::from(height) * map.components() as u64 * size_of::<f32>() as u64;
|
||||
reserve_bytes(&mut remaining_bytes, map_bytes)?;
|
||||
|
||||
let mut images = BTreeMap::new();
|
||||
for (tile, path) in tiles {
|
||||
let bytes = read_image_file(CMD, path, remaining_bytes)?;
|
||||
reserve_bytes(&mut remaining_bytes, bytes.len() as u64)?;
|
||||
|
||||
let bytes_per_texel = size_of::<[f32; 4]>() as u64;
|
||||
let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?;
|
||||
let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?;
|
||||
reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?;
|
||||
images.insert(*tile, image.clone());
|
||||
assigned.push(json!({"path": path, "ts": ts, "map": map.id()}));
|
||||
}
|
||||
use_images(s, CMD, *ts, *map, &images)?;
|
||||
}
|
||||
Ok(assigned)
|
||||
});
|
||||
// A failed edit leaves the document as it was; forget the images it decoded
|
||||
if result.is_err() {
|
||||
s.sync_images();
|
||||
}
|
||||
|
||||
Ok(json!({ "assigned": result?, "unmatched": unmatched }))
|
||||
}
|
||||
|
||||
fn reserve_bytes(remaining_bytes: &mut u64, bytes: u64) -> Result<()> {
|
||||
*remaining_bytes = remaining_bytes.checked_sub(bytes).ok_or_else(|| bad(CMD, "the files, decoded images and mesh maps exceed the import memory budget"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The texture set and mesh map a file is for, and its UV tile ([`FIRST_TILE`] on a set without UV tiles)
|
||||
fn slot_of(s: &Session, set_names: &[&str], path: &str, given_map: Option<BakedMap>) -> Option<((usize, BakedMap), u32)> {
|
||||
let ts = texture_set_from_file_name(path, set_names)?;
|
||||
let map = given_map.or_else(|| baked_map_from_file_name(path, set_names.get(ts).copied().unwrap_or_default()))?;
|
||||
let texture_set = s.doc.project.texture_sets.get(ts)?;
|
||||
let tile = match texture_set.tile_grid() {
|
||||
Some(_) => tile_number(Path::new(path).file_name()?.to_str()?).filter(|tile| texture_set.uv_tiles.contains(tile))?,
|
||||
None => FIRST_TILE,
|
||||
};
|
||||
Some(((ts, map), tile))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_core::BakeResolution;
|
||||
|
||||
#[test]
|
||||
fn import_budget_counts_decoded_images_and_resampled_maps() {
|
||||
let dir = std::env::temp_dir().join(format!("texturecraft-import-budget-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let paths = [dir.join("ao.png"), dir.join("height.png")];
|
||||
for path in &paths {
|
||||
image::RgbaImage::from_pixel(16, 16, image::Rgba([128, 128, 128, 255])).save(path).unwrap();
|
||||
}
|
||||
let file_bytes: u64 = paths.iter().map(|path| std::fs::metadata(path).unwrap().len()).sum();
|
||||
let decoded_bytes = 2 * 16 * 16 * 16;
|
||||
let map_bytes = 2 * 16 * 16 * 4;
|
||||
let required_bytes = file_bytes + decoded_bytes + map_bytes;
|
||||
let params = json!({"files": paths.map(|path| json!({"path": path}))});
|
||||
let mut session = Session::new_project("budget", texturecraft_geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
|
||||
session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R16;
|
||||
let revision = session.revision;
|
||||
|
||||
for budget in [file_bytes, file_bytes + decoded_bytes, required_bytes - 1] {
|
||||
let result = import_with_budget(&mut session, ¶ms, budget);
|
||||
assert!(result.is_err(), "budget {budget} must cover decoded pixels and mesh maps: {result:?}");
|
||||
assert!(session.doc.resources.is_empty() && session.images.is_empty());
|
||||
assert!(session.doc.baked.values().all(|baked| baked.maps.is_empty()));
|
||||
assert_eq!(session.revision, revision);
|
||||
assert!(!session.modified);
|
||||
assert!(session.undo_label().is_none());
|
||||
}
|
||||
|
||||
let result = import_with_budget(&mut session, ¶ms, required_bytes).unwrap();
|
||||
assert_eq!(result["assigned"].as_array().unwrap().len(), 2);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+93
-136
@@ -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> {
|
||||
@@ -145,6 +155,7 @@ impl Session {
|
||||
/// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh
|
||||
/// (the Clone tool's destination anchor).
|
||||
fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option<Vec2>) -> Result<()> {
|
||||
self.refuse_while_baking()?;
|
||||
let tool = self.tool.tool;
|
||||
let erase = tool == Tool::Eraser;
|
||||
let quick_mask = self.quick_mask.editing;
|
||||
@@ -234,7 +245,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,
|
||||
@@ -286,9 +297,18 @@ impl Session {
|
||||
Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile })
|
||||
}
|
||||
|
||||
/// Painting is paused while a bake preview shows the baked maps instead of the material.
|
||||
pub(crate) fn refuse_while_baking(&self) -> Result<()> {
|
||||
match self.painting_blocked() {
|
||||
Some(why) => Err(EngineError::Other(why.into())),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a stroke at `screen` (viewport pixels). Returns false when the cursor misses the
|
||||
/// mesh (the stroke starts anyway and resumes when the cursor enters the mesh).
|
||||
pub fn begin_stroke(&mut self, screen: Vec2, viewport: Vec2, pressure: f32) -> Result<bool> {
|
||||
self.refuse_while_baking()?;
|
||||
self.cancel_stroke();
|
||||
match self.tool.tool {
|
||||
Tool::PolygonFill => return self.polygon_fill(screen, viewport).map(|_| true),
|
||||
@@ -301,12 +321,16 @@ 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.refuse_while_baking()?;
|
||||
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 +338,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 +515,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 +528,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 +615,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");
|
||||
}
|
||||
}
|
||||
@@ -452,69 +452,72 @@ impl Session {
|
||||
})
|
||||
}
|
||||
|
||||
/// Fill the inside of `poly` (viewport pixels over the visible surface, or texture coordinates); returns the touched tiles
|
||||
fn lasso_fill(&mut self, poly: Vec<Vec2>, uv: bool, viewport: Vec2) -> Result<usize> {
|
||||
let ts = self.ts();
|
||||
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
|
||||
let w = gbuf.width.max(1);
|
||||
/// Fill the inside of `polygon` (viewport pixels over the visible surface, or texture coordinates); returns the touched tiles
|
||||
fn lasso_fill(&mut self, polygon: Vec<Vec2>, uv: bool, viewport: Vec2) -> Result<usize> {
|
||||
let texture_set = self.ts();
|
||||
let (gbuf, mut canvas) = self.fill_canvas(texture_set)?;
|
||||
let width = gbuf.width.max(1);
|
||||
|
||||
if uv {
|
||||
let lasso = Lasso::new(poly.iter().map(|p| *p * Vec2::new(w as f32, gbuf.height as f32)).collect());
|
||||
fill_coverage(&mut canvas, &gbuf, |i, _| lasso.coverage(Vec2::new((i as u32 % w) as f32 + 0.5, (i as u32 / w) as f32 + 0.5)));
|
||||
let lasso = Lasso::new(polygon.iter().map(|point| *point * Vec2::new(width as f32, gbuf.height as f32)).collect());
|
||||
fill_coverage(&mut canvas, &gbuf, |texel, _| lasso.coverage(Vec2::new((texel as u32 % width) as f32 + 0.5, (texel as u32 / width) as f32 + 0.5)));
|
||||
} else {
|
||||
let lasso = Lasso::new(poly);
|
||||
let lasso = Lasso::new(polygon);
|
||||
let view_proj = self.camera.view_proj(viewport.x.max(1.0) / viewport.y.max(1.0));
|
||||
let inv = view_proj.inverse();
|
||||
let (cull, mesh, bvh) = (self.tool.brush.backface_culling, &self.mesh, &self.bvh);
|
||||
let inverse_view_proj = view_proj.inverse();
|
||||
let (backface_culling, mesh, bvh) = (self.tool.brush.backface_culling, &self.mesh, &self.bvh);
|
||||
|
||||
// A visible source inside the lasso can paint each symmetry copy
|
||||
let (lo, hi) = mesh.bounds();
|
||||
let (bounds_min, bounds_max) = mesh.bounds();
|
||||
let symmetry = self.tool.brush.sanitized().symmetry;
|
||||
let symmetry_origin = symmetry.origin((lo + hi) * 0.5);
|
||||
let inverses: Vec<_> = symmetry.transforms().iter().map(|m| m.inverse()).collect();
|
||||
let symmetry_origin = symmetry.origin((bounds_min + bounds_max) * 0.5);
|
||||
let inverses: Vec<_> = symmetry.transforms().iter().map(|transform| transform.inverse()).collect();
|
||||
|
||||
fill_coverage(&mut canvas, &gbuf, |i, _| {
|
||||
let Some(s) = gbuf.surface(mesh, i) else { return 0.0 };
|
||||
fill_coverage(&mut canvas, &gbuf, |texel, _| {
|
||||
let Some(surface) = gbuf.surface(mesh, texel) else { return 0.0 };
|
||||
let mut best = 0.0f32;
|
||||
|
||||
for m in &inverses {
|
||||
let pos = symmetry_origin + *m * (s.pos - symmetry_origin);
|
||||
let c = view_proj * pos.extend(1.0);
|
||||
if c.w <= MIN_PROJECTIVE_W {
|
||||
for inverse in &inverses {
|
||||
let position = symmetry_origin + *inverse * (surface.pos - symmetry_origin);
|
||||
let clip = view_proj * position.extend(1.0);
|
||||
if clip.w <= MIN_PROJECTIVE_W {
|
||||
continue;
|
||||
}
|
||||
let ndc = Vec2::new(c.x, c.y) / c.w;
|
||||
let a = lasso.coverage(to_pixels(ndc, viewport));
|
||||
if a <= best {
|
||||
|
||||
let ndc = Vec2::new(clip.x, clip.y) / clip.w;
|
||||
let coverage = lasso.coverage(to_pixels(ndc, viewport));
|
||||
if coverage <= best {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Use the source surface normal; a copy may face away from the camera
|
||||
let o = inv * ndc.extend(0.0).extend(1.0);
|
||||
let origin = o.truncate() / o.w;
|
||||
let to = pos - origin;
|
||||
let d = to.length();
|
||||
let Some(dir) = to.try_normalize() else { continue };
|
||||
let Some(hit) =
|
||||
bvh.closest(origin, dir, d * (1.0 + RAY_HIT_RELATIVE_TOLERANCE)).filter(|hit| hit.t >= d * (1.0 - RAY_HIT_RELATIVE_TOLERANCE))
|
||||
let near_clip = inverse_view_proj * ndc.extend(0.0).extend(1.0);
|
||||
let origin = near_clip.truncate() / near_clip.w;
|
||||
let to_surface = position - origin;
|
||||
let distance = to_surface.length();
|
||||
let Some(direction) = to_surface.try_normalize() else { continue };
|
||||
let Some(hit) = bvh
|
||||
.closest(origin, direction, distance * (1.0 + RAY_HIT_RELATIVE_TOLERANCE))
|
||||
.filter(|hit| hit.t >= distance * (1.0 - RAY_HIT_RELATIVE_TOLERANCE))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let Some(source) = surface_at(mesh, hit.tri, hit.u, hit.v) else { continue };
|
||||
|
||||
if cull && source.nrm.dot(dir) >= 0.0 {
|
||||
if backface_culling && source.nrm.dot(direction) >= 0.0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
best = a;
|
||||
best = coverage;
|
||||
}
|
||||
|
||||
best
|
||||
});
|
||||
}
|
||||
|
||||
let tiles = canvas.dirty.len();
|
||||
self.commit_fill("Path fill", ts, &canvas)?;
|
||||
self.commit_fill("Path fill", texture_set, &canvas)?;
|
||||
Ok(tiles)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,614 @@
|
||||
//! 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> {
|
||||
self.refuse_while_baking()?;
|
||||
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> {
|
||||
self.refuse_while_baking()?;
|
||||
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> {
|
||||
self.refuse_while_baking()?;
|
||||
|
||||
// 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.refuse_while_baking()?;
|
||||
|
||||
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> {
|
||||
self.refuse_while_baking()?;
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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([¢er.metallic, ¢er.roughness, ¢er.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(¢er), "{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([¢er.roughness, ¢er.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(¢er), "{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");
|
||||
}
|
||||
}
|
||||
@@ -105,34 +105,37 @@ impl Session {
|
||||
/// Includes the stroke in progress.
|
||||
pub fn quick_mask_rgba(&self, ts: usize, size: u32) -> Option<Vec<u8>> {
|
||||
let cache = self.caches.get(ts)?;
|
||||
let (w, h) = cache.size;
|
||||
let size = size.clamp(1, w.max(h));
|
||||
let (width, height) = cache.size;
|
||||
let size = size.clamp(1, width.max(height));
|
||||
let mask = self.quick_mask_image(ts, cache.size);
|
||||
let live = self.stroke.as_ref().filter(|s| s.ts == ts && s.target.is_none()).map(|s| (&s.canvas.alpha, s.stroke.settings.opacity, s.erase));
|
||||
let base = cache.composite.channels.get(&Channel::BaseColor);
|
||||
let lut = srgb_lut();
|
||||
let srgb = srgb_lut();
|
||||
let inverted = self.quick_mask.inverted;
|
||||
let mut out = vec![255u8; size as usize * size as usize * 4];
|
||||
|
||||
out.par_chunks_mut(size as usize * 4).enumerate().for_each(|(y, row)| {
|
||||
let ty = (y as u64 * u64::from(h) / u64::from(size)) as u32;
|
||||
for (x, px) in row.chunks_exact_mut(4).enumerate() {
|
||||
let tx = (x as u64 * u64::from(w) / u64::from(size)) as u32;
|
||||
let mut m = from_u16(mask.get(tx, ty)[0]);
|
||||
let ty = (y as u64 * u64::from(height) / u64::from(size)) as u32;
|
||||
for (x, pixel) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
let tx = (x as u64 * u64::from(width) / u64::from(size)) as u32;
|
||||
let mut coverage = from_u16(mask.get(tx, ty)[0]);
|
||||
if let Some((alpha, opacity, erase)) = live {
|
||||
let a = from_u16(alpha.get(tx, ty)[0]) * opacity;
|
||||
m = if erase { m * (1.0 - a) } else { a + m * (1.0 - a) };
|
||||
let stroke_coverage = from_u16(alpha.get(tx, ty)[0]) * opacity;
|
||||
coverage = if erase { coverage * (1.0 - stroke_coverage) } else { stroke_coverage + coverage * (1.0 - stroke_coverage) };
|
||||
}
|
||||
let blocked = if inverted { m } else { 1.0 - m };
|
||||
|
||||
let blocked = if inverted { coverage } else { 1.0 - coverage };
|
||||
let raw = base.map(|b| b.get(tx, ty)).unwrap_or([32768; 4]);
|
||||
let t = 0.55 * blocked;
|
||||
let tint_amount = 0.55 * blocked;
|
||||
for (k, tint) in [0.9, 0.1, 0.15].into_iter().enumerate() {
|
||||
let c = f32::from(lut.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0;
|
||||
if let Some(slot) = px.get_mut(k) {
|
||||
*slot = ((c + (tint - c) * t).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
let color = f32::from(srgb.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0;
|
||||
if let Some(slot) = pixel.get_mut(k) {
|
||||
*slot = ((color + (tint - color) * tint_amount).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
@@ -36,12 +36,18 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name.
|
||||
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name
|
||||
pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
|
||||
self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX))
|
||||
}
|
||||
|
||||
/// Add an image within a decoded texel budget, inside the caller's edit
|
||||
pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec<u8>, max_texels: u64) -> Result<String> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
|
||||
}
|
||||
let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
|
||||
|
||||
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
|
||||
let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image");
|
||||
let base = texturecraft_formats::sanitize_resource_name(leaf);
|
||||
let mut name = base.clone();
|
||||
@@ -50,11 +56,8 @@ impl Session {
|
||||
name = format!("{n}_{base}");
|
||||
n += 1;
|
||||
}
|
||||
let key = name.clone();
|
||||
self.edit("Import resource", |s| {
|
||||
s.doc.resources.insert(key, Arc::new(bytes));
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
self.doc.resources.insert(name.clone(), Arc::new(bytes));
|
||||
self.images.insert(name.clone(), decoded(image));
|
||||
Ok(name)
|
||||
}
|
||||
@@ -98,15 +101,44 @@ fn list(s: &Session) -> Value {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?;
|
||||
let meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?;
|
||||
if meta.len() > MAX_BYTES as u64 {
|
||||
return Err(bad("resource.import", format!("{path} is too large")));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?;
|
||||
let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?;
|
||||
let name = s.import_resource_bytes(path, bytes)?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// Read a regular image file within both the per-file cap and the caller's remaining byte budget
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_image_file(cmd: &str, path: &str, max_bytes: u64) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
|
||||
let max_bytes = max_bytes.min(MAX_BYTES as u64);
|
||||
let read_error = |error| bad(cmd, format!("cannot read {path}: {error}"));
|
||||
let too_large = || bad(cmd, format!("{path} is too large (limit {max_bytes} bytes)"));
|
||||
let metadata = std::fs::metadata(path).map_err(read_error)?;
|
||||
// Pipes can block on open, and devices may never reach EOF
|
||||
if !metadata.is_file() {
|
||||
return Err(bad(cmd, format!("{path} is not a regular file")));
|
||||
}
|
||||
if metadata.len() > max_bytes {
|
||||
return Err(too_large());
|
||||
}
|
||||
|
||||
// Bound the read even if the file grows after the metadata check
|
||||
let file = std::fs::File::open(path).map_err(read_error)?;
|
||||
let mut bytes = Vec::with_capacity(metadata.len() as usize);
|
||||
file.take(max_bytes + 1).read_to_end(&mut bytes).map_err(read_error)?;
|
||||
if bytes.len() as u64 > max_bytes {
|
||||
return Err(too_large());
|
||||
}
|
||||
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn read_image_file(cmd: &str, _: &str, _: u64) -> Result<Vec<u8>> {
|
||||
Err(bad(cmd, "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn import(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into()))
|
||||
@@ -165,3 +197,24 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
Ok(json!({ "layer": id.0 }))
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn file_reads_obey_the_remaining_byte_budget() {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id()));
|
||||
std::fs::write(&path, b"1234").unwrap();
|
||||
let name = path.to_str().unwrap();
|
||||
assert!(read_image_file("test", name, 3).unwrap_err().to_string().contains("too large"));
|
||||
assert_eq!(read_image_file("test", name, 4).unwrap(), b"1234");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn devices_are_rejected_before_reading() {
|
||||
assert!(read_image_file("test", "/dev/null", 16).unwrap_err().to_string().contains("not a regular 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]>,
|
||||
@@ -314,6 +318,9 @@ pub struct Session {
|
||||
pub mesh: Arc<Mesh>,
|
||||
/// Unique per loaded mesh and UV layout (GPU caches compare it).
|
||||
pub mesh_id: u64,
|
||||
/// Unique per open project: a mesh reimport or UV layout change keeps it, and opening, closing
|
||||
/// or creating a project replaces it.
|
||||
pub project_id: u64,
|
||||
/// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas).
|
||||
pub(crate) source: Arc<Mesh>,
|
||||
pub bvh: Arc<Bvh>,
|
||||
@@ -334,6 +341,8 @@ pub struct Session {
|
||||
pub target: StackTarget,
|
||||
pub camera: OrbitCamera,
|
||||
pub view: ViewMode,
|
||||
/// The live bake preview while the app bakes (see [`crate::bake_preview`]).
|
||||
pub bake_preview: Option<crate::bake_preview::BakePreview>,
|
||||
/// Viewport size (pixels) used by scripted strokes.
|
||||
pub viewport: Vec2,
|
||||
pub(crate) stroke: Option<ActiveStroke>,
|
||||
@@ -356,6 +365,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).
|
||||
@@ -378,6 +389,7 @@ impl Session {
|
||||
Ok(Session {
|
||||
doc,
|
||||
mesh_id: next_mesh_id(),
|
||||
project_id: next_mesh_id(),
|
||||
source,
|
||||
mesh,
|
||||
bvh: Arc::new(bvh),
|
||||
@@ -393,6 +405,7 @@ impl Session {
|
||||
target: StackTarget::Content,
|
||||
camera,
|
||||
view: ViewMode::Material,
|
||||
bake_preview: None,
|
||||
viewport: Vec2::new(1280.0, 800.0),
|
||||
stroke: None,
|
||||
clipboard: None,
|
||||
@@ -405,6 +418,7 @@ impl Session {
|
||||
revision: 1,
|
||||
log: Vec::new(),
|
||||
depth_cache: None,
|
||||
polygon_fill_drag: None,
|
||||
export_presets: Default::default(),
|
||||
templates: Default::default(),
|
||||
})
|
||||
@@ -489,22 +503,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 +546,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 +641,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(¤t);
|
||||
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(¤t);
|
||||
self.undo.push((label.clone(), current));
|
||||
self.sync_images();
|
||||
Ok(label)
|
||||
}
|
||||
|
||||
@@ -75,12 +75,20 @@ pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ts = u64p(p, "ts").map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?;
|
||||
let ts = u64p(p, "ts")
|
||||
.map(|index| index as usize)
|
||||
.filter(|index| *index < s.set_count())
|
||||
.ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?;
|
||||
select_set(s, ts);
|
||||
Ok(json!({ "ts": ts }))
|
||||
}
|
||||
|
||||
/// Make texture set `ts` the active one, on its content stack
|
||||
pub(crate) fn select_set(s: &mut Session, ts: usize) {
|
||||
s.cancel_stroke();
|
||||
s.active_set = ts;
|
||||
s.target = StackTarget::Content;
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(json!({ "ts": ts }))
|
||||
}
|
||||
|
||||
fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
//! Asynchronous layer-panel thumbnails.
|
||||
//!
|
||||
//! The panel asks for small previews of layer contents, masks and effect stages
|
||||
//! ([`ThumbTarget`]). The work never runs on the UI thread and never touches the main composite:
|
||||
//!
|
||||
//! * A **snapshot** ([`ThumbSnapshot`]) is an immutable copy of what the compositor reads (the
|
||||
//! project, copy-on-write pixel tiles, baked maps, images and the mesh) plus a 64 px G-buffer.
|
||||
//! It is rebuilt only when the document really changed, at most every [`DEBOUNCE`] seconds
|
||||
//! (a slider drag renders at that pace, not once per frame).
|
||||
//! * A **worker thread** evaluates one target at a time from a snapshot with
|
||||
//! [`texturecraft_compose::thumb::render`]. On wasm32 (no threads) one job runs per
|
||||
//! [`ThumbService::poll`] instead.
|
||||
//! * Results are kept in a small LRU **cache** ([`CACHE_ENTRIES`]). A result computed from an
|
||||
//! older snapshot than the current one is dropped, so a slow job can never overwrite a newer
|
||||
//! thumbnail. An entry that is out of date keeps showing until its replacement arrives.
|
||||
//! * Only targets requested during the current frame are rendered: a row that scrolled away
|
||||
//! before its turn is dropped from the queue.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PixelStore, THUMB_TEXELS, ThumbImage, ThumbTarget, thumb};
|
||||
use texturecraft_core::Project;
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Mesh, UvGBuffer};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// Thumbnails kept.
|
||||
pub const CACHE_ENTRIES: usize = 96;
|
||||
/// Seconds between checks for a changed document while it keeps changing.
|
||||
pub const DEBOUNCE: f64 = 0.12;
|
||||
/// Jobs handed to the worker at once (the rest wait here, where they can still be dropped).
|
||||
const IN_FLIGHT: usize = 2;
|
||||
|
||||
/// An immutable copy of everything the thumbnails of one texture set read.
|
||||
pub struct ThumbSnapshot {
|
||||
ts: usize,
|
||||
mesh_id: u64,
|
||||
project: Project,
|
||||
pixels: PixelStore,
|
||||
baked: BakedMaps,
|
||||
images: ImageStore,
|
||||
mesh: Arc<Mesh>,
|
||||
gbuf: Arc<UvGBuffer>,
|
||||
bounds: (Vec3, Vec3),
|
||||
}
|
||||
|
||||
impl ThumbSnapshot {
|
||||
/// Snapshot texture set `ts` of `s`, with the G-buffer from `gbufs` (built on a miss).
|
||||
pub fn new(s: &Session, ts: usize, gbufs: &mut GbufCache) -> Option<ThumbSnapshot> {
|
||||
let material = s.doc.project.texture_set(ts).ok()?.material;
|
||||
let gbuf = gbufs.get(&s.mesh, s.mesh_id, material);
|
||||
Some(ThumbSnapshot {
|
||||
ts,
|
||||
mesh_id: s.mesh_id,
|
||||
project: s.doc.project.clone(),
|
||||
pixels: s.doc.pixels.clone(),
|
||||
baked: s.doc.baked.get(&ts).cloned().unwrap_or_default(),
|
||||
images: s.images.clone(),
|
||||
mesh: s.mesh.clone(),
|
||||
gbuf,
|
||||
bounds: s.mesh.bounds(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `session` would give the same thumbnails as this snapshot.
|
||||
fn matches(&self, session: &Session, texture_set: usize) -> bool {
|
||||
let same_pixels = self.pixels.layers.len() == session.doc.pixels.layers.len()
|
||||
&& self.pixels.masks.len() == session.doc.pixels.masks.len()
|
||||
&& self.pixels.layers.iter().all(|(key, pixels)| session.doc.pixels.layers.get(key) == Some(pixels))
|
||||
&& self.pixels.masks.iter().all(|(key, pixels)| session.doc.pixels.masks.get(key) == Some(pixels));
|
||||
let empty = BakedMaps::default();
|
||||
let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty);
|
||||
|
||||
// Copy-on-write maps change handles on edits; float equality would scan entire bakes
|
||||
let same_baked = self.baked.resolution == baked.resolution
|
||||
&& self.baked.maps.len() == baked.maps.len()
|
||||
&& self.baked.maps.iter().all(|(map, pixels)| baked.maps.get(map).is_some_and(|current| Arc::ptr_eq(pixels, current)));
|
||||
|
||||
self.ts == texture_set
|
||||
&& self.mesh_id == session.mesh_id
|
||||
&& self.project == session.doc.project
|
||||
&& same_pixels
|
||||
&& same_baked
|
||||
&& self.images.len() == session.images.len()
|
||||
&& self.images.iter().all(|(key, image)| session.images.get(key).is_some_and(|current| Arc::ptr_eq(current, image)))
|
||||
}
|
||||
|
||||
/// Render `target`: the work of one job.
|
||||
pub fn render(&self, target: ThumbTarget) -> Option<ThumbImage> {
|
||||
let inp = Inputs {
|
||||
project: &self.project,
|
||||
ts: self.ts,
|
||||
mesh: &self.mesh,
|
||||
gbuf: &self.gbuf,
|
||||
pixels: &self.pixels,
|
||||
baked: &self.baked,
|
||||
block_scales: self.project.texture_set(self.ts).map(|set| set.block_scales()).unwrap_or_default(),
|
||||
preview: None,
|
||||
images: &self.images,
|
||||
bounds: self.bounds,
|
||||
};
|
||||
thumb::render(&inp, target)
|
||||
}
|
||||
|
||||
/// Whether the layer or effect `target` shows still exists in the snapshot's project.
|
||||
fn has(&self, target: ThumbTarget) -> bool {
|
||||
has_target(&self.project, target)
|
||||
}
|
||||
}
|
||||
|
||||
fn has_target(p: &Project, target: ThumbTarget) -> bool {
|
||||
match target {
|
||||
ThumbTarget::Content { layer, .. } | ThumbTarget::Mask { layer } => p.layers.contains_key(&layer),
|
||||
ThumbTarget::Stage { effect, .. } => p.effect(effect).is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The 64 px G-buffers built so far, per mesh and material (rasterizing is the one part of a
|
||||
/// snapshot that is not just copying handles).
|
||||
#[derive(Default)]
|
||||
pub struct GbufCache {
|
||||
map: HashMap<(u64, usize), Arc<UvGBuffer>>,
|
||||
}
|
||||
|
||||
impl GbufCache {
|
||||
fn get(&mut self, mesh: &Mesh, mesh_id: u64, material: usize) -> Arc<UvGBuffer> {
|
||||
if self.map.len() > 16 {
|
||||
self.map.clear();
|
||||
}
|
||||
self.map.entry((mesh_id, material)).or_insert_with(|| Arc::new(UvGBuffer::new(mesh, material, THUMB_TEXELS, THUMB_TEXELS))).clone()
|
||||
}
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
/// None: the target has nothing to show (a layer without that channel).
|
||||
image: Option<Arc<ThumbImage>>,
|
||||
/// Snapshot generation it was rendered from.
|
||||
generation: u64,
|
||||
/// Changes whenever `image` does (views key their GPU textures on it).
|
||||
version: u64,
|
||||
used: u64,
|
||||
}
|
||||
|
||||
/// What the panel draws for one target.
|
||||
#[derive(Clone)]
|
||||
pub struct ThumbView {
|
||||
pub image: Option<Arc<ThumbImage>>,
|
||||
/// Identifies `image`; changes when a new picture arrives.
|
||||
pub version: u64,
|
||||
/// A newer picture is on its way.
|
||||
pub pending: bool,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
snapshot: Arc<ThumbSnapshot>,
|
||||
generation: u64,
|
||||
target: ThumbTarget,
|
||||
}
|
||||
|
||||
struct Done {
|
||||
generation: u64,
|
||||
target: ThumbTarget,
|
||||
image: Option<ThumbImage>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct Worker {
|
||||
tx: std::sync::mpsc::Sender<Job>,
|
||||
rx: std::sync::mpsc::Receiver<Done>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn spawn_worker() -> Option<Worker> {
|
||||
let (tx, jobs) = std::sync::mpsc::channel::<Job>();
|
||||
let (done_tx, rx) = std::sync::mpsc::channel::<Done>();
|
||||
std::thread::Builder::new()
|
||||
.name("layer-thumbs".into())
|
||||
.spawn(move || {
|
||||
while let Ok(job) = jobs.recv() {
|
||||
let image = job.snapshot.render(job.target);
|
||||
if done_tx.send(Done { generation: job.generation, target: job.target, image }).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.ok()?;
|
||||
Some(Worker { tx, rx })
|
||||
}
|
||||
|
||||
/// The thumbnail cache and its worker. One lives in the UI; see the module documentation.
|
||||
pub struct ThumbService {
|
||||
snapshot: Option<Arc<ThumbSnapshot>>,
|
||||
/// Bumps whenever the snapshot's content changes; entries and jobs carry it.
|
||||
generation: u64,
|
||||
/// The session revision the snapshot was last compared with.
|
||||
seen: Option<u64>,
|
||||
last_check: f64,
|
||||
cache: HashMap<ThumbTarget, Entry>,
|
||||
tick: u64,
|
||||
versions: u64,
|
||||
queue: VecDeque<ThumbTarget>,
|
||||
in_flight: HashSet<(u64, ThumbTarget)>,
|
||||
wanted: HashSet<ThumbTarget>,
|
||||
gbufs: GbufCache,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
worker: Option<Worker>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
spawned: bool,
|
||||
/// Jobs run inline (wasm32, or no worker thread could start).
|
||||
inline: VecDeque<Job>,
|
||||
/// Pictures computed (tests, benchmarks).
|
||||
pub rendered: u64,
|
||||
}
|
||||
|
||||
impl Default for ThumbService {
|
||||
fn default() -> Self {
|
||||
ThumbService {
|
||||
snapshot: None,
|
||||
generation: 0,
|
||||
seen: None,
|
||||
last_check: f64::NEG_INFINITY,
|
||||
cache: HashMap::new(),
|
||||
tick: 0,
|
||||
versions: 0,
|
||||
queue: VecDeque::new(),
|
||||
in_flight: HashSet::new(),
|
||||
wanted: HashSet::new(),
|
||||
gbufs: GbufCache::default(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
worker: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
spawned: false,
|
||||
inline: VecDeque::new(),
|
||||
rendered: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ThumbService {
|
||||
pub fn new() -> ThumbService {
|
||||
ThumbService::default()
|
||||
}
|
||||
|
||||
/// Start of a frame: forget what the last frame asked for and notice document changes.
|
||||
pub fn begin_frame(&mut self, session: &Session, now: f64) {
|
||||
self.wanted.clear();
|
||||
let texture_set = session.ts();
|
||||
if self.seen == Some(session.revision)
|
||||
&& self.snapshot.as_ref().is_some_and(|snapshot| snapshot.ts == texture_set && snapshot.mesh_id == session.mesh_id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Compare at the debounce pace while the document keeps changing
|
||||
if self.snapshot.is_some() && now - self.last_check < DEBOUNCE {
|
||||
return;
|
||||
}
|
||||
|
||||
self.last_check = now;
|
||||
if self.snapshot.as_ref().is_some_and(|snapshot| snapshot.matches(session, texture_set)) {
|
||||
self.seen = Some(session.revision);
|
||||
return;
|
||||
}
|
||||
|
||||
self.snapshot = ThumbSnapshot::new(session, texture_set, &mut self.gbufs).map(Arc::new);
|
||||
self.seen = Some(session.revision);
|
||||
self.generation = self.generation.wrapping_add(1);
|
||||
|
||||
// Keep dispatched jobs counted until they finish, even when their snapshot is stale
|
||||
self.queue.clear();
|
||||
for job in self.inline.drain(..) {
|
||||
self.in_flight.remove(&(job.generation, job.target));
|
||||
}
|
||||
|
||||
if let Some(snapshot) = &self.snapshot {
|
||||
self.cache.retain(|target, _| snapshot.has(*target));
|
||||
} else {
|
||||
self.cache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the displayed pictures wait for a document comparison that is still debounced.
|
||||
fn checked(&self, session: &Session) -> bool {
|
||||
self.seen == Some(session.revision)
|
||||
}
|
||||
|
||||
/// The picture for `target` (call for the rows on screen only). Queues work when the
|
||||
/// picture is missing or out of date.
|
||||
pub fn get(&mut self, session: &Session, target: ThumbTarget) -> ThumbView {
|
||||
self.wanted.insert(target);
|
||||
self.tick = self.tick.wrapping_add(1);
|
||||
let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation);
|
||||
let checked = self.checked(session);
|
||||
if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&(self.generation, target)) && !self.queue.contains(&target) {
|
||||
self.queue.push_back(target);
|
||||
}
|
||||
|
||||
match self.cache.get_mut(&target) {
|
||||
Some(entry) => {
|
||||
entry.used = self.tick;
|
||||
ThumbView { image: entry.image.clone(), version: entry.version, pending: !(fresh && checked) }
|
||||
}
|
||||
None => ThumbView { image: None, version: 0, pending: true },
|
||||
}
|
||||
}
|
||||
|
||||
/// End of a frame: collect results, discard unrequested rows, and dispatch new work.
|
||||
/// Returns whether another frame is needed, including to display newly collected pictures.
|
||||
pub fn poll(&mut self, session: &Session) -> bool {
|
||||
let changed = self.collect();
|
||||
self.queue.retain(|target| self.wanted.contains(target));
|
||||
self.dispatch();
|
||||
self.trim();
|
||||
|
||||
changed || !self.queue.is_empty() || !self.in_flight.is_empty() || !self.checked(session)
|
||||
}
|
||||
|
||||
fn dispatch(&mut self) {
|
||||
let Some(snapshot) = self.snapshot.clone() else { return };
|
||||
|
||||
while self.in_flight.len() < IN_FLIGHT {
|
||||
let Some(target) = self.queue.pop_front() else { break };
|
||||
let job = Job { snapshot: snapshot.clone(), generation: self.generation, target };
|
||||
self.in_flight.insert((job.generation, target));
|
||||
self.send(job);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn send(&mut self, job: Job) {
|
||||
if !self.spawned {
|
||||
self.spawned = true;
|
||||
self.worker = spawn_worker();
|
||||
}
|
||||
|
||||
match &self.worker {
|
||||
Some(worker) => {
|
||||
if let Err(error) = worker.tx.send(job) {
|
||||
// A stopped worker cannot complete any of its outstanding jobs
|
||||
self.worker = None;
|
||||
self.in_flight.clear();
|
||||
self.in_flight.insert((error.0.generation, error.0.target));
|
||||
self.inline.push_back(error.0);
|
||||
}
|
||||
}
|
||||
None => self.inline.push_back(job),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn send(&mut self, job: Job) {
|
||||
self.inline.push_back(job);
|
||||
}
|
||||
|
||||
fn collect(&mut self) -> bool {
|
||||
let mut completed = Vec::new();
|
||||
let mut changed = false;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(worker) = &self.worker {
|
||||
loop {
|
||||
match worker.rx.try_recv() {
|
||||
Ok(result) => completed.push(result),
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => break,
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||||
// Request another frame so wanted targets retry on the inline fallback
|
||||
self.worker = None;
|
||||
self.in_flight.clear();
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Without a thread, bound each poll to one render
|
||||
if let Some(job) = self.inline.pop_front() {
|
||||
let image = job.snapshot.render(job.target);
|
||||
completed.push(Done { generation: job.generation, target: job.target, image });
|
||||
}
|
||||
|
||||
for result in completed {
|
||||
self.rendered = self.rendered.wrapping_add(1);
|
||||
self.in_flight.remove(&(result.generation, result.target));
|
||||
|
||||
// A picture of an older snapshot never replaces a newer one
|
||||
if result.generation != self.generation {
|
||||
continue;
|
||||
}
|
||||
|
||||
if !self.snapshot.as_ref().is_some_and(|snapshot| snapshot.has(result.target)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
self.versions = self.versions.wrapping_add(1);
|
||||
let entry = Entry { image: result.image.map(Arc::new), generation: result.generation, version: self.versions, used: self.tick };
|
||||
self.cache.insert(result.target, entry);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
fn trim(&mut self) {
|
||||
while self.cache.len() > CACHE_ENTRIES {
|
||||
let Some(oldest) = self.cache.iter().filter(|(t, _)| !self.wanted.contains(t)).min_by_key(|(_, e)| e.used).map(|(t, _)| *t) else { break };
|
||||
self.cache.remove(&oldest);
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries held (tests).
|
||||
pub fn cached(&self) -> usize {
|
||||
self.cache.len()
|
||||
}
|
||||
|
||||
/// Whether `target` has a picture of the current snapshot (tests).
|
||||
pub fn is_fresh(&self, target: ThumbTarget) -> bool {
|
||||
self.cache.get(&target).is_some_and(|e| e.generation == self.generation)
|
||||
}
|
||||
|
||||
/// Whether any work is queued or running (tests).
|
||||
pub fn busy(&self) -> bool {
|
||||
!self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_core::Channel;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
fn test_session() -> crate::Result<Session> {
|
||||
Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128)
|
||||
}
|
||||
|
||||
fn held_worker() -> (ThumbService, std::sync::mpsc::Receiver<Job>, std::sync::mpsc::Sender<Done>) {
|
||||
let (sender, jobs) = std::sync::mpsc::channel();
|
||||
let (results, receiver) = std::sync::mpsc::channel();
|
||||
let service = ThumbService { worker: Some(Worker { tx: sender, rx: receiver }), spawned: true, ..Default::default() };
|
||||
(service, jobs, results)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_baked_handles_match_even_with_non_finite_samples() {
|
||||
let mut session = test_session().unwrap();
|
||||
let baked = session.doc.baked.entry(0).or_default();
|
||||
baked.resolution = 1;
|
||||
baked.maps.insert(texturecraft_core::BakedMap::Height, Arc::new(vec![f32::NAN]));
|
||||
let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap();
|
||||
|
||||
assert!(snapshot.matches(&session, 0), "unchanged shared data must not invalidate every frame");
|
||||
|
||||
let map = session.doc.baked.get_mut(&0).unwrap().maps.get_mut(&texturecraft_core::BakedMap::Height).unwrap();
|
||||
Arc::make_mut(map)[0] = 0.5;
|
||||
assert!(!snapshot.matches(&session, 0), "a copy-on-write edit must invalidate the snapshot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn benchmark_unchanged_4k_baked_snapshot() {
|
||||
let mut session = test_session().unwrap();
|
||||
let baked = session.doc.baked.entry(0).or_default();
|
||||
baked.resolution = 4096;
|
||||
baked.maps.insert(texturecraft_core::BakedMap::Normal, Arc::new(vec![0.5; 4096 * 4096 * 3]));
|
||||
baked.maps.insert(texturecraft_core::BakedMap::AmbientOcclusion, Arc::new(vec![0.5; 4096 * 4096]));
|
||||
let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
for _ in 0..20 {
|
||||
assert!(std::hint::black_box(&snapshot).matches(std::hint::black_box(&session), 0));
|
||||
}
|
||||
|
||||
eprintln!("20 unchanged snapshot comparisons, 4K normal + AO (256 MiB): {:?}", start.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collecting_the_last_result_requests_a_frame_to_display_it() {
|
||||
let session = test_session().unwrap();
|
||||
let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor };
|
||||
let (mut service, jobs, results) = held_worker();
|
||||
service.begin_frame(&session, 0.0);
|
||||
service.get(&session, target);
|
||||
assert!(service.poll(&session));
|
||||
let job = jobs.try_recv().unwrap();
|
||||
results.send(Done { generation: job.generation, target, image: job.snapshot.render(target) }).unwrap();
|
||||
|
||||
service.begin_frame(&session, 0.1);
|
||||
assert!(service.get(&session, target).image.is_none());
|
||||
let repaint = service.poll(&session);
|
||||
|
||||
assert!(service.is_fresh(target));
|
||||
assert!(repaint, "the frame drew before collecting the final thumbnail");
|
||||
service.begin_frame(&session, 0.2);
|
||||
assert!(service.get(&session, target).image.is_some());
|
||||
assert!(!service.poll(&session), "an idle cache must stop repainting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stopped_worker_retries_visible_targets_inline() {
|
||||
let session = test_session().unwrap();
|
||||
let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor };
|
||||
let (mut service, jobs, results) = held_worker();
|
||||
service.begin_frame(&session, 0.0);
|
||||
service.get(&session, target);
|
||||
service.poll(&session);
|
||||
|
||||
// Simulate a worker that stops with a dispatched request still outstanding
|
||||
drop(jobs);
|
||||
drop(results);
|
||||
for frame in 1..=4 {
|
||||
service.begin_frame(&session, f64::from(frame));
|
||||
service.get(&session, target);
|
||||
service.poll(&session);
|
||||
}
|
||||
|
||||
assert!(service.get(&session, target).image.is_some());
|
||||
assert!(!service.busy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_keep_worker_jobs_and_retained_snapshots_bounded() {
|
||||
let mut session = test_session().unwrap();
|
||||
let layer = session.selected_layer().unwrap();
|
||||
let target = ThumbTarget::Content { layer, channel: Channel::BaseColor };
|
||||
let (mut service, jobs, results) = held_worker();
|
||||
let mut snapshots = Vec::new();
|
||||
|
||||
// Hold the worker's receiver still while repeated edits each produce a new snapshot
|
||||
for revision in 0..2_000 {
|
||||
session.doc.pixels.layer_mut(layer, Channel::BaseColor, (128, 128)).set(0, 0, &[revision, 0, 0, u16::MAX]);
|
||||
session.revision += 1;
|
||||
service.begin_frame(&session, f64::from(revision));
|
||||
snapshots.push(Arc::downgrade(service.snapshot.as_ref().unwrap()));
|
||||
service.get(&session, target);
|
||||
service.poll(&session);
|
||||
}
|
||||
|
||||
let queued: Vec<_> = jobs.try_iter().collect();
|
||||
let retained = snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count();
|
||||
let retained_pixel_bytes: usize = snapshots.iter().filter_map(std::sync::Weak::upgrade).map(|snapshot| snapshot.pixels.bytes()).sum();
|
||||
eprintln!("2,000 edits: {} queued jobs, {retained} live snapshots, {retained_pixel_bytes} retained pixel bytes", queued.len());
|
||||
assert!(queued.len() <= IN_FLIGHT, "{} queued jobs bypassed the worker limit", queued.len());
|
||||
assert!(retained <= IN_FLIGHT + 1, "{retained} document snapshots retained across edits");
|
||||
assert!(retained_pixel_bytes <= (IN_FLIGHT + 1) * texturecraft_texel::TILE_AREA * 4 * std::mem::size_of::<u16>());
|
||||
|
||||
// Finishing stale work frees a slot for the newest document, without caching old results
|
||||
for job in queued {
|
||||
results.send(Done { generation: job.generation, target: job.target, image: None }).unwrap();
|
||||
}
|
||||
|
||||
assert_eq!(snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count(), 1, "completed jobs release stale snapshots");
|
||||
assert!(service.poll(&session));
|
||||
assert!(!service.is_fresh(target));
|
||||
let latest = jobs.try_recv().unwrap();
|
||||
assert_eq!(latest.generation, service.generation);
|
||||
results.send(Done { generation: latest.generation, target, image: latest.snapshot.render(target) }).unwrap();
|
||||
drop(latest);
|
||||
assert!(service.poll(&session));
|
||||
assert!(service.is_fresh(target));
|
||||
|
||||
let image = Arc::downgrade(service.cache.get(&target).unwrap().image.as_ref().unwrap());
|
||||
drop(service);
|
||||
|
||||
assert!(snapshots.iter().all(|snapshot| snapshot.upgrade().is_none()), "dropping the cache releases its last snapshot");
|
||||
assert!(image.upgrade().is_none(), "dropping the cache releases the rendered image");
|
||||
assert!(jobs.try_recv().is_err());
|
||||
}
|
||||
}
|
||||
+223
-104
@@ -7,7 +7,9 @@ use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_paint::{Alignment, BrushAlpha, MAX_RADIAL_COPIES, alphas};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp, vec3};
|
||||
use crate::session::{CloneFrom, CloneSource, FillMode, Tool};
|
||||
use crate::fill_hit_test::FillHitTest;
|
||||
use crate::fill_mode::FillMode;
|
||||
use crate::session::{CloneFrom, CloneSource, StackTarget, Tool};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -51,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
material
|
||||
),
|
||||
cmd!(
|
||||
"tool.swapMaskValue",
|
||||
"Invert mask value",
|
||||
["Tools"],
|
||||
Some("X"),
|
||||
"{} — mask value becomes 1 − value: switch the brush between adding to and removing from the mask",
|
||||
paints_mask,
|
||||
swap_mask_value
|
||||
),
|
||||
cmd!(
|
||||
"tool.stencil",
|
||||
"Projection stencil",
|
||||
@@ -69,7 +80,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 +100,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> {
|
||||
@@ -99,135 +129,158 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers
|
||||
fn brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let b = &mut s.tool.brush;
|
||||
let pct = |k: &str| f32p(p, k).map(|v| v / 100.0);
|
||||
if let Some(v) = pct("size") {
|
||||
b.size = v * 0.25;
|
||||
fn brush(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let mut settings = session.tool.brush.clone();
|
||||
let percent = |key: &str| f32p(params, key).map(|value| value / 100.0);
|
||||
|
||||
if let Some(value) = percent("size") {
|
||||
settings.size = value * 0.25;
|
||||
}
|
||||
if let Some(v) = pct("minSize") {
|
||||
b.min_size = v;
|
||||
if let Some(value) = percent("minSize") {
|
||||
settings.min_size = value;
|
||||
}
|
||||
if let Some(v) = pct("flow") {
|
||||
b.flow = v;
|
||||
|
||||
if let Some(value) = percent("flow") {
|
||||
settings.flow = value;
|
||||
}
|
||||
if let Some(v) = pct("opacity") {
|
||||
b.opacity = v;
|
||||
if let Some(value) = percent("opacity") {
|
||||
settings.opacity = value;
|
||||
}
|
||||
if let Some(v) = pct("spacing") {
|
||||
b.spacing = v;
|
||||
if let Some(value) = percent("spacing") {
|
||||
settings.spacing = value;
|
||||
}
|
||||
if let Some(v) = pct("hardness") {
|
||||
b.hardness = v;
|
||||
if let Some(value) = percent("hardness") {
|
||||
settings.hardness = value;
|
||||
}
|
||||
if let Some(v) = f32p(p, "angle") {
|
||||
b.angle = v;
|
||||
|
||||
if let Some(value) = f32p(params, "angle") {
|
||||
settings.angle = value;
|
||||
}
|
||||
if let Some(v) = boolp(p, "followPath") {
|
||||
b.follow_path = v;
|
||||
if let Some(value) = boolp(params, "followPath") {
|
||||
settings.follow_path = value;
|
||||
}
|
||||
if let Some(a) = strp(p, "alignment") {
|
||||
b.alignment = match a {
|
||||
if let Some(alignment) = strp(params, "alignment") {
|
||||
settings.alignment = match alignment {
|
||||
"camera" => Alignment::Camera,
|
||||
"tangent" | "uv" => Alignment::Tangent,
|
||||
other => return Err(bad("tool.brush", format!("unknown alignment `{other}`"))),
|
||||
};
|
||||
}
|
||||
if let Some(v) = f32p(p, "lazy") {
|
||||
b.lazy = v;
|
||||
|
||||
if let Some(value) = f32p(params, "lazy") {
|
||||
settings.lazy = value;
|
||||
}
|
||||
for (k, slot) in [("jitterSize", &mut b.jitter_size), ("jitterAngle", &mut b.jitter_angle), ("jitterFlow", &mut b.jitter_flow)] {
|
||||
if let Some(v) = f32p(p, k) {
|
||||
*slot = v / 100.0;
|
||||
|
||||
for (key, slot) in [("jitterSize", &mut settings.jitter_size), ("jitterAngle", &mut settings.jitter_angle), ("jitterFlow", &mut settings.jitter_flow)] {
|
||||
if let Some(value) = f32p(params, key) {
|
||||
*slot = value / 100.0;
|
||||
}
|
||||
}
|
||||
if let Some(v) = f32p(p, "jitterPosition") {
|
||||
b.jitter_position = v / 100.0;
|
||||
if let Some(value) = f32p(params, "jitterPosition") {
|
||||
settings.jitter_position = value / 100.0;
|
||||
}
|
||||
let alpha = p.get("alpha");
|
||||
if let Some(a) = strp(p, "alpha") {
|
||||
b.alpha = BrushAlpha::parse(a).ok_or_else(|| bad("tool.brush", format!("unknown alpha `{a}`")))?;
|
||||
(b.alpha_image, b.alpha_library) = (None, None);
|
||||
} else if let Some(name) = alpha.and_then(|a| a.get("image")).and_then(Value::as_str) {
|
||||
if !s.images.contains_key(name) {
|
||||
|
||||
let alpha = params.get("alpha");
|
||||
if let Some(alpha_name) = strp(params, "alpha") {
|
||||
settings.alpha = BrushAlpha::parse(alpha_name).ok_or_else(|| bad("tool.brush", format!("unknown alpha `{alpha_name}`")))?;
|
||||
(settings.alpha_image, settings.alpha_library) = (None, None);
|
||||
} else if let Some(name) = alpha.and_then(|alpha| alpha.get("image")).and_then(Value::as_str) {
|
||||
if !session.images.contains_key(name) {
|
||||
return Err(bad("tool.brush", format!("no image resource `{name}` (import it first)")));
|
||||
}
|
||||
(b.alpha_image, b.alpha_library) = (Some(name.to_string()), None);
|
||||
} else if let Some(id) = alpha.and_then(|a| a.get("library")).and_then(Value::as_str) {
|
||||
let a = alphas::find(id).ok_or_else(|| bad("tool.brush", format!("unknown library alpha `{id}` (see alpha.list)")))?;
|
||||
|
||||
(settings.alpha_image, settings.alpha_library) = (Some(name.to_string()), None);
|
||||
} else if let Some(id) = alpha.and_then(|alpha| alpha.get("library")).and_then(Value::as_str) {
|
||||
let alpha = alphas::find(id).ok_or_else(|| bad("tool.brush", format!("unknown library alpha `{id}` (see alpha.list)")))?;
|
||||
|
||||
// Render it now rather than on the first stamp
|
||||
a.image();
|
||||
(b.alpha_image, b.alpha_library) = (None, Some(a.id.clone()));
|
||||
alpha.image();
|
||||
(settings.alpha_image, settings.alpha_library) = (None, Some(alpha.id.clone()));
|
||||
}
|
||||
if let Some(v) = boolp(p, "backfaceCulling") {
|
||||
b.backface_culling = v;
|
||||
|
||||
if let Some(value) = boolp(params, "backfaceCulling") {
|
||||
settings.backface_culling = value;
|
||||
}
|
||||
if let Some(v) = boolp(p, "symmetryOn") {
|
||||
b.symmetry.enabled = v;
|
||||
|
||||
if let Some(value) = boolp(params, "symmetryOn") {
|
||||
settings.symmetry.enabled = value;
|
||||
}
|
||||
for (k, slot) in [("symmetryX", &mut b.symmetry.x), ("symmetryY", &mut b.symmetry.y), ("symmetryZ", &mut b.symmetry.z)] {
|
||||
if let Some(v) = boolp(p, k) {
|
||||
*slot = v;
|
||||
|
||||
for (key, slot) in [("symmetryX", &mut settings.symmetry.x), ("symmetryY", &mut settings.symmetry.y), ("symmetryZ", &mut settings.symmetry.z)] {
|
||||
if let Some(value) = boolp(params, key) {
|
||||
*slot = value;
|
||||
}
|
||||
}
|
||||
if let Some(v) = f32p(p, "symmetryRadial") {
|
||||
b.symmetry.radial = v.clamp(0.0, f32::from(MAX_RADIAL_COPIES)) as u8;
|
||||
|
||||
if let Some(value) = f32p(params, "symmetryRadial") {
|
||||
settings.symmetry.radial = value.clamp(0.0, f32::from(MAX_RADIAL_COPIES)) as u8;
|
||||
}
|
||||
if let Some(a) = strp(p, "symmetryAxis") {
|
||||
b.symmetry.axis = match a.to_ascii_lowercase().as_str() {
|
||||
|
||||
if let Some(axis) = strp(params, "symmetryAxis") {
|
||||
settings.symmetry.axis = match axis.to_ascii_lowercase().as_str() {
|
||||
"x" => 0,
|
||||
"y" => 1,
|
||||
"z" => 2,
|
||||
_ => return Err(bad("tool.brush", format!("unknown symmetry axis `{a}` (x, y or z)"))),
|
||||
_ => return Err(bad("tool.brush", format!("unknown symmetry axis `{axis}` (x, y or z)"))),
|
||||
};
|
||||
}
|
||||
if let Some(v) = f32p(p, "symmetryAngleSpan") {
|
||||
b.symmetry.angle_span = v;
|
||||
|
||||
if let Some(value) = f32p(params, "symmetryAngleSpan") {
|
||||
settings.symmetry.angle_span = value;
|
||||
}
|
||||
if p.get("symmetryOffset").is_some() {
|
||||
b.symmetry.offset = vec3(p, "symmetryOffset").ok_or_else(|| bad("tool.brush", "`symmetryOffset` must be [x, y, z]"))?.to_array();
|
||||
|
||||
if params.get("symmetryOffset").is_some() {
|
||||
settings.symmetry.offset = vec3(params, "symmetryOffset").ok_or_else(|| bad("tool.brush", "`symmetryOffset` must be [x, y, z]"))?.to_array();
|
||||
}
|
||||
if let Some(v) = boolp(p, "screenSpace") {
|
||||
b.screen_space = v;
|
||||
|
||||
if let Some(value) = boolp(params, "screenSpace") {
|
||||
settings.screen_space = value;
|
||||
}
|
||||
if let Some(q) = p.get("particles") {
|
||||
let pt = &mut b.particles;
|
||||
pt.enabled = boolp(q, "enabled").unwrap_or(pt.enabled);
|
||||
pt.count = f32p(q, "count").map_or(pt.count, |v| v as u32);
|
||||
pt.lifetime = f32p(q, "lifetime").map_or(pt.lifetime, |v| v as u32);
|
||||
pt.gravity = f32p(q, "gravity").unwrap_or(pt.gravity);
|
||||
|
||||
if let Some(particle_params) = params.get("particles") {
|
||||
let particles = &mut settings.particles;
|
||||
particles.enabled = boolp(particle_params, "enabled").unwrap_or(particles.enabled);
|
||||
particles.count = f32p(particle_params, "count").map_or(particles.count, |value| value as u32);
|
||||
particles.lifetime = f32p(particle_params, "lifetime").map_or(particles.lifetime, |value| value as u32);
|
||||
particles.gravity = f32p(particle_params, "gravity").unwrap_or(particles.gravity);
|
||||
}
|
||||
*b = b.sanitized();
|
||||
if let Some(v) = f32p(p, "smudgeStrength") {
|
||||
s.tool.smudge_strength = (v / 100.0).clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(v) = strp(p, "cloneSource") {
|
||||
s.tool.clone_from = match v {
|
||||
|
||||
let clone_from = if let Some(value) = strp(params, "cloneSource") {
|
||||
match value {
|
||||
"composite" => CloneFrom::Composite,
|
||||
"layer" => CloneFrom::Layer,
|
||||
other => return Err(bad("tool.brush", format!("unknown clone source `{other}`: use composite or layer"))),
|
||||
};
|
||||
}
|
||||
} else {
|
||||
session.tool.clone_from
|
||||
};
|
||||
|
||||
session.tool.brush = settings.sanitized();
|
||||
session.tool.clone_from = clone_from;
|
||||
if let Some(value) = f32p(params, "smudgeStrength") {
|
||||
session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0);
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(brush_json(s))
|
||||
|
||||
session.revision = session.revision.wrapping_add(1);
|
||||
Ok(brush_json(session))
|
||||
}
|
||||
|
||||
pub(crate) fn brush_json(s: &Session) -> Value {
|
||||
let b = &s.tool.brush;
|
||||
pub(crate) fn brush_json(session: &Session) -> Value {
|
||||
let settings = &session.tool.brush;
|
||||
json!({
|
||||
"size": b.size / 0.25 * 100.0, "minSize": b.min_size * 100.0, "flow": b.flow * 100.0, "opacity": b.opacity * 100.0,
|
||||
"spacing": b.spacing * 100.0, "hardness": b.hardness * 100.0, "angle": b.angle, "followPath": b.follow_path,
|
||||
"alignment": format!("{:?}", b.alignment).to_lowercase(), "lazy": b.lazy,
|
||||
"alpha": match (&b.alpha_image, &b.alpha_library) {
|
||||
"size": settings.size / 0.25 * 100.0, "minSize": settings.min_size * 100.0, "flow": settings.flow * 100.0, "opacity": settings.opacity * 100.0,
|
||||
"spacing": settings.spacing * 100.0, "hardness": settings.hardness * 100.0, "angle": settings.angle, "followPath": settings.follow_path,
|
||||
"alignment": format!("{:?}", settings.alignment).to_lowercase(), "lazy": settings.lazy,
|
||||
"alpha": match (&settings.alpha_image, &settings.alpha_library) {
|
||||
(Some(name), _) => json!({ "image": name }),
|
||||
(None, Some(id)) => json!({ "library": id }),
|
||||
(None, None) => json!(b.alpha.label()),
|
||||
(None, None) => json!(settings.alpha.label()),
|
||||
},
|
||||
"backfaceCulling": b.backface_culling, "symmetry": [b.symmetry.x, b.symmetry.y, b.symmetry.z],
|
||||
"radialSymmetry": { "copies": b.symmetry.radial, "axis": (["x", "y", "z"].get(b.symmetry.axis as usize)) },
|
||||
"symmetryOffset": b.symmetry.offset, "symmetryOn": b.symmetry.enabled, "symmetryAngleSpan": b.symmetry.angle_span,
|
||||
"smudgeStrength": s.tool.smudge_strength * 100.0, "particles": b.particles,
|
||||
"cloneSource": if s.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" },
|
||||
"backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z],
|
||||
"radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) },
|
||||
"symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span,
|
||||
"smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles,
|
||||
"cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -262,6 +315,30 @@ fn material(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Whether strokes paint the selected layer's mask: the mask itself or one of its effects
|
||||
fn paints_mask(session: &Session) -> std::result::Result<(), String> {
|
||||
session.selected_layer().ok_or("no layer selected")?;
|
||||
|
||||
let project = &session.doc.project;
|
||||
let targets_mask = match session.target {
|
||||
StackTarget::Content => false,
|
||||
StackTarget::Mask => true,
|
||||
StackTarget::Effect(effect_id) => project
|
||||
.effect(effect_id)
|
||||
.and_then(|(owner, _)| project.layers.get(&owner))
|
||||
.is_some_and(|owner_layer| !owner_layer.content_effects.iter().any(|effect| effect.id == effect_id)),
|
||||
};
|
||||
|
||||
if targets_mask { Ok(()) } else { Err("select a mask to paint on".into()) }
|
||||
}
|
||||
|
||||
fn swap_mask_value(session: &mut Session, _: &Value) -> Result<Value> {
|
||||
session.tool.mask_value = 1.0 - session.tool.mask_value;
|
||||
session.revision = session.revision.wrapping_add(1);
|
||||
|
||||
Ok(json!({ "maskValue": session.tool.mask_value }))
|
||||
}
|
||||
|
||||
fn stencil(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if boolp(p, "clear") == Some(true) {
|
||||
s.tool.stencil = None;
|
||||
@@ -329,13 +406,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)
|
||||
}
|
||||
|
||||
@@ -379,22 +472,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)?;
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -88,7 +88,13 @@ fn frame(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn set_view(s: &mut Session, v: ViewMode) -> Result<Value> {
|
||||
s.view = v;
|
||||
if s.bake_preview.is_some() {
|
||||
// During a bake the view follows the preview: a mesh map pins it, another mode comes back afterwards
|
||||
s.bake_preview_user_view(v);
|
||||
} else {
|
||||
s.view = v;
|
||||
}
|
||||
let v = s.view;
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(json!({ "view": v.label() }))
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user