mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-24 08:20:46 +01:00
Bake mode: the Baking Visualization panel and neutral material, as in the reference
Every overlay gets the reference's colour swatch and eyedropper: the high poly, its matching error, the cage's surface and wireframe (separate, each with an opacity), the missing seams and the project mesh. The panel opens as the reference's does at first launch; its eye hides the baking meshes and greys their rows. Show for selected texture set only filters the cage and the high poly; a hidden high poly leaves the GPU. The UV seam overlay now marks the hard edges the UV layout does not split, on the low poly and the cage, in the 3D and 2D views. The project mesh can show the neutral material, picked in the 3D view's view menu: colour, roughness, metallic, baked AO, an optional baked bent normal, and Quality as importance-sampled reflections per pixel.
This commit is contained in:
1 parent
42c8ea5b3c
commit
dafbdf3ec7
30 files changed
+1300
-233
No files matched your search
Generated
+1
@@ -4425,6 +4425,7 @@ dependencies = [
|
||||
"log",
|
||||
"pollster 0.4.0",
|
||||
"rayon",
|
||||
"serde",
|
||||
"texturecraft-bake",
|
||||
"texturecraft-compose",
|
||||
"texturecraft-core",
|
||||
|
||||
@@ -16,6 +16,8 @@ pub struct CageShell {
|
||||
pub starts: Vec<RayStart>,
|
||||
/// Corner pairs along the low poly's polygon edges, for the wireframe
|
||||
pub edges: Vec<[u32; 2]>,
|
||||
/// Corner pairs along the low poly's hard edges without a UV seam
|
||||
pub missing_seams: Vec<[u32; 2]>,
|
||||
/// World units per unit of the max frontal distance setting
|
||||
pub cage_units: f32,
|
||||
}
|
||||
@@ -37,7 +39,8 @@ impl CageShell {
|
||||
.unzip();
|
||||
|
||||
let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
|
||||
let mut edge_corners = HashMap::new();
|
||||
let missing_seam_edges: HashSet<(u32, u32)> = mesh.missing_seam_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
|
||||
let (mut edge_corners, mut seam_corners) = (HashMap::new(), HashMap::new());
|
||||
for (triangle_index, &triangle) in triangles.iter().enumerate() {
|
||||
let Some(vertices) = mesh.tri(triangle) else { continue };
|
||||
|
||||
@@ -45,16 +48,23 @@ impl CageShell {
|
||||
let next = (corner + 1) % 3;
|
||||
let (from, to) = (vertices[corner] as u32, vertices[next] as u32);
|
||||
let key = (from.min(to), from.max(to));
|
||||
let first_corner = (triangle_index * 3) as u32;
|
||||
let corners = [first_corner + corner as u32, first_corner + next as u32];
|
||||
if wire_edges.contains(&key) {
|
||||
let first_corner = (triangle_index * 3) as u32;
|
||||
edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]);
|
||||
edge_corners.entry(key).or_insert(corners);
|
||||
}
|
||||
if missing_seam_edges.contains(&key) {
|
||||
seam_corners.entry(key).or_insert(corners);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect();
|
||||
edges.sort_unstable();
|
||||
let sorted = |corners: HashMap<(u32, u32), [u32; 2]>| {
|
||||
let mut pairs: Vec<[u32; 2]> = corners.into_values().collect();
|
||||
pairs.sort_unstable();
|
||||
pairs
|
||||
};
|
||||
|
||||
Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units })
|
||||
Ok(CageShell { positions, starts, edges: sorted(edge_corners), missing_seams: sorted(seam_corners), cage_units: ray_frame.cage_units })
|
||||
}
|
||||
|
||||
/// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling
|
||||
|
||||
@@ -101,3 +101,54 @@ fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() {
|
||||
assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is");
|
||||
assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cage_lists_its_hard_edges_without_a_uv_seam() {
|
||||
// A quad whose diagonal is split into two vertices with the same UV, smooth or hard by the copy's normal
|
||||
let quad_with_diagonal_normal = |normal: Vec3| {
|
||||
let mut mesh = Mesh::from_parts(
|
||||
vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y],
|
||||
None,
|
||||
vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)],
|
||||
vec![0, 1, 2, 0, 2, 3],
|
||||
"Default",
|
||||
)
|
||||
.unwrap();
|
||||
mesh.positions.push(mesh.positions[0]);
|
||||
mesh.normals.push(normal);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(mesh.uvs[0]);
|
||||
mesh.indices[3] = 4;
|
||||
mesh
|
||||
};
|
||||
let shell_of = |low: &Mesh| {
|
||||
let bvh = Bvh::new(low);
|
||||
let bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: low,
|
||||
bvh: &bvh,
|
||||
material: 0,
|
||||
settings: &bake_settings,
|
||||
high: Some(HighPoly { file_ids: &[], mesh: low, bvh: &bvh, base_color: &[] }),
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
CageShell::new(&request).unwrap()
|
||||
};
|
||||
|
||||
let smooth = quad_with_diagonal_normal(Vec3::Z);
|
||||
assert!(shell_of(&smooth).missing_seams.is_empty(), "the same normal on both sides is a smooth edge");
|
||||
|
||||
let hard = quad_with_diagonal_normal(Vec3::new(1.0, 0.0, 1.0).normalize());
|
||||
let shell = shell_of(&hard);
|
||||
let diagonal = [Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0)];
|
||||
assert_eq!(shell.missing_seams.len(), 2, "the diagonal, once per triangle");
|
||||
for [from, to] in &shell.missing_seams {
|
||||
let mut ends = [shell.positions[*from as usize], shell.positions[*to as usize]];
|
||||
ends.sort_by(|a, b| a.x.total_cmp(&b.x));
|
||||
assert_eq!(ends, diagonal, "the line runs along the hard diagonal");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
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
|
||||
/// The value [`high_poly_missed`] gives a vertex that `only_set` doesn't own, which the 3D view leaves out
|
||||
pub const HIDDEN_HIGH_POLY_VERTEX: f32 = -1.0;
|
||||
|
||||
/// Per vertex of the validated high poly: 1.0 if its owning set's bake misses it at that set's (max frontal, max rear), 0.0 if reached or unknown, [`HIDDEN_HIGH_POLY_VERTEX`] if `only_set` doesn't own it
|
||||
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
|
||||
@@ -13,11 +14,21 @@ pub fn high_poly_missed(reach: &[Option<HighPolyReach>], distances: &[(f32, f32)
|
||||
.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| {
|
||||
if only_set.is_some_and(|only| !owns(reach, only, vertex)) {
|
||||
return HIDDEN_HIGH_POLY_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()
|
||||
}
|
||||
|
||||
/// Whether texture set `texture_set`'s reach claims high-poly vertex `vertex`
|
||||
fn owns(reach: &[Option<HighPolyReach>], texture_set: usize, vertex: usize) -> bool {
|
||||
reach.get(texture_set).and_then(Option::as_ref).and_then(|set| set.vertices.get(vertex)).is_some_and(Option::is_some)
|
||||
}
|
||||
@@ -19,7 +19,7 @@ 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 high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, 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;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use texturecraft_engine::bake::{HighPolyReach, RayStart, VertexReach, high_poly_missed};
|
||||
use texturecraft_engine::bake::{HIDDEN_HIGH_POLY_VERTEX, HighPolyReach, RayStart, VertexReach, high_poly_missed};
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
|
||||
fn vertex(height: f32) -> Option<VertexReach> {
|
||||
@@ -30,12 +30,13 @@ fn each_owning_set_uses_its_own_frontal_and_rear_distances() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_set_filter_leaves_other_sets_unmarked() {
|
||||
fn selected_set_filter_hides_other_sets_vertices() {
|
||||
const H: f32 = HIDDEN_HIGH_POLY_VERTEX;
|
||||
let reaches = sets();
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, H, H, H, H]);
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![H, H, 0.0, 1.0, H, H]);
|
||||
for only_set in [0, reaches.len(), usize::MAX] {
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![0.0; 6]);
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![H; 6], "a set without a reach shows none of the high poly");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+60
-42
@@ -7,6 +7,9 @@ use crate::{GeomError, Result};
|
||||
/// An edge by the bits of its two end positions, the lower one first
|
||||
type EdgePositions = ([u32; 3], [u32; 3]);
|
||||
|
||||
/// Normals closer than about one degree are the same normal: the edge between them is smooth
|
||||
const SAME_NORMAL_MIN_COSINE: f32 = 0.9998;
|
||||
|
||||
/// A contiguous index range drawn with one material.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SubMesh {
|
||||
@@ -110,8 +113,8 @@ impl Mesh {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`
|
||||
pub fn uv_seam_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
/// Hard edges the UV layout does not split, which bake visible lines into the normal map: two triangles meet there with different normals but the same UVs, per material in `0..materials.len().max(1)`
|
||||
pub fn missing_seam_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
// Signed zero denotes the same position on either side of an imported seam
|
||||
let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() });
|
||||
let mut seams = vec![Vec::new(); self.materials.len().max(1)];
|
||||
@@ -132,10 +135,18 @@ impl Mesh {
|
||||
}
|
||||
|
||||
let uv = |index: u32| self.uvs.get(index as usize).copied();
|
||||
// Directions only: imported normals need not be unit length, and two missing normals agree
|
||||
let direction = |index: u32| self.normals.get(index as usize).map_or(Vec3::ZERO, |normal| normal.normalize_or_zero());
|
||||
let same_normal = |a: u32, b: u32| {
|
||||
let (a, b) = (direction(a), direction(b));
|
||||
a == b || a.dot(b) >= SAME_NORMAL_MIN_COSINE
|
||||
};
|
||||
for pairs in sides.into_values() {
|
||||
let Some(&(first_from, first_to, _)) = pairs.first() else { continue };
|
||||
|
||||
if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) {
|
||||
let uv_split = pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to)));
|
||||
let hard = pairs.iter().any(|&(from, to, _)| !same_normal(from, first_from) || !same_normal(to, first_to));
|
||||
if hard && !uv_split {
|
||||
for (from, to, material) in pairs {
|
||||
if let Some(edges) = seams.get_mut(material) {
|
||||
edges.push((from.min(to), from.max(to)));
|
||||
@@ -485,53 +496,60 @@ mod tests {
|
||||
assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_are_where_the_uv_layout_splits() {
|
||||
let mesh = quad();
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam");
|
||||
|
||||
// Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut
|
||||
let mut seam = mesh.clone();
|
||||
seam.positions.push(seam.positions[0]);
|
||||
seam.normals.push(seam.normals[0]);
|
||||
seam.tangents.push(seam.tangents[0]);
|
||||
seam.uvs.push(Vec2::new(0.9, 0.9));
|
||||
seam.indices[3] = 4;
|
||||
assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
|
||||
// The same split with the same UV is a hard edge, not a seam
|
||||
let mut hard = seam.clone();
|
||||
hard.uvs[4] = hard.uvs[0];
|
||||
assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_join_positions_with_opposite_signed_zero() {
|
||||
let mut mesh = quad();
|
||||
mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0));
|
||||
mesh.normals.push(mesh.normals[0]);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(Vec2::new(0.9, 0.9));
|
||||
mesh.indices[3] = 4;
|
||||
assert_eq!(mesh.positions[0], mesh.positions[4]);
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_between_materials_belong_to_both_materials() {
|
||||
/// `quad` with vertex 4 a copy of vertex 0 at `uv` with `normal`, used by the second triangle: the diagonal (0, 2) / (4, 2) has two sides
|
||||
fn split_quad(uv: Vec2, normal: Vec3) -> Mesh {
|
||||
let mut mesh = quad();
|
||||
mesh.positions.push(mesh.positions[0]);
|
||||
mesh.normals.push(mesh.normals[0]);
|
||||
mesh.normals.push(normal);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(Vec2::new(0.9, 0.9));
|
||||
mesh.uvs.push(uv);
|
||||
mesh.indices[3] = 4;
|
||||
mesh
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_seams_are_hard_edges_the_uv_layout_does_not_split() {
|
||||
let none = vec![Vec::<(u32, u32)>::new()];
|
||||
assert_eq!(quad().missing_seam_edges(), none, "a smooth quad has no hard edge");
|
||||
|
||||
let shared_uv = quad().uvs[0];
|
||||
let smooth_split = split_quad(shared_uv, Vec3::Z);
|
||||
assert_eq!(smooth_split.missing_seam_edges(), none, "the same normal on both sides is a smooth edge");
|
||||
|
||||
let hard = split_quad(shared_uv, Vec3::new(1.0, 0.0, 1.0).normalize());
|
||||
assert_eq!(hard.missing_seam_edges(), vec![vec![(0, 2), (2, 4)]], "a hard edge inside one UV island");
|
||||
|
||||
let seamed = split_quad(Vec2::new(0.9, 0.9), hard.normals[4]);
|
||||
assert_eq!(seamed.missing_seam_edges(), none, "a hard edge on a UV seam is fine");
|
||||
|
||||
let mut short_normals = quad();
|
||||
short_normals.normals.iter_mut().for_each(|normal| *normal *= 0.5);
|
||||
assert_eq!(short_normals.missing_seam_edges(), none, "normals shorter than unit length point the same way");
|
||||
assert_eq!(split_quad(shared_uv, Vec3::Z * 0.5).missing_seam_edges(), none, "normals of different lengths point the same way");
|
||||
|
||||
let mut no_normals = quad();
|
||||
no_normals.normals.fill(Vec3::ZERO);
|
||||
assert_eq!(no_normals.missing_seam_edges(), none, "two missing normals agree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_seams_join_positions_with_opposite_signed_zero() {
|
||||
let mut mesh = split_quad(quad().uvs[0], Vec3::X);
|
||||
mesh.positions[4] = Vec3::new(-0.0, 0.0, 0.0);
|
||||
assert_eq!(mesh.positions[0], mesh.positions[4]);
|
||||
assert_eq!(mesh.missing_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_seams_between_materials_belong_to_both_materials() {
|
||||
let mut mesh = split_quad(quad().uvs[0], Vec3::X);
|
||||
mesh.materials.push("second".into());
|
||||
mesh.submeshes[0].count = 3;
|
||||
mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 });
|
||||
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]);
|
||||
mesh.uvs[4] = mesh.uvs[0];
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam");
|
||||
assert_eq!(mesh.missing_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]);
|
||||
mesh.normals[4] = mesh.normals[0];
|
||||
assert_eq!(mesh.missing_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a hard edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -19,6 +19,7 @@ bytemuck = { workspace = true }
|
||||
half = { workspace = true }
|
||||
log = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
pollster = "0.4"
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
//! One overlay of bake mode's 3D view: whether it shows, its color and its opacity
|
||||
|
||||
/// Whether a part of the bake setup shows in the 3D view, and in which color and opacity
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct BakeOverlay {
|
||||
pub shown: bool,
|
||||
/// Linear RGB
|
||||
pub color: [f32; 3],
|
||||
/// 0 transparent, 1 opaque; the matching error mixes into the high poly by it
|
||||
pub opacity: f32,
|
||||
}
|
||||
|
||||
impl BakeOverlay {
|
||||
/// A hidden overlay in `color`, fully opaque
|
||||
pub const fn hidden(color: [f32; 3]) -> Self {
|
||||
Self { shown: false, color, opacity: 1.0 }
|
||||
}
|
||||
|
||||
/// The overlay's shader globals: rgb its color, a its opacity (0 while hidden)
|
||||
pub(crate) fn globals(&self) -> [f32; 4] {
|
||||
let [red, green, blue] = self.color;
|
||||
[red, green, blue, if self.shown { self.opacity.clamp(0.0, 1.0) } else { 0.0 }]
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,58 @@
|
||||
//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly
|
||||
//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the missing seams and the low poly
|
||||
|
||||
/// Which parts of the bake setup the 3D view draws
|
||||
use crate::bake_overlay::BakeOverlay;
|
||||
use crate::neutral_material::NeutralMaterial;
|
||||
|
||||
/// Default overlay colors, linear RGB
|
||||
const HIGH_POLY_COLOR: [f32; 3] = [0.0, 0.216, 0.521];
|
||||
const MATCHING_ERROR_COLOR: [f32; 3] = [1.0, 0.0, 0.0];
|
||||
const CAGE_SURFACE_COLOR: [f32; 3] = [0.604, 0.451, 0.216];
|
||||
const CAGE_WIRE_COLOR: [f32; 3] = [0.604, 0.604, 0.604];
|
||||
const MISSING_SEAM_COLOR: [f32; 3] = [0.451, 0.0, 0.451];
|
||||
const LOW_POLY_COLOR: [f32; 3] = [0.216, 0.216, 0.216];
|
||||
|
||||
/// Which parts of the bake setup the 3D view draws, and how
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct BakeVisualization {
|
||||
pub high_poly: bool,
|
||||
pub cage: bool,
|
||||
pub uv_seams: bool,
|
||||
pub low_poly: bool,
|
||||
/// Draw the cage, seams and low poly of only this texture set
|
||||
pub high_poly: BakeOverlay,
|
||||
/// Tints the high poly where the bake's rays miss it
|
||||
pub matching_error: BakeOverlay,
|
||||
pub cage_surface: BakeOverlay,
|
||||
pub cage_wire: BakeOverlay,
|
||||
/// The low poly's hard edges that are not UV seams
|
||||
pub missing_seams: BakeOverlay,
|
||||
/// The low poly; its color is the neutral material's color
|
||||
pub low_poly: BakeOverlay,
|
||||
/// Shade the low poly with this plain material instead of its painted one
|
||||
pub neutral: Option<NeutralMaterial>,
|
||||
/// Draw the cage and high poly of only this texture set (the high poly's vertices of other sets come marked hidden)
|
||||
pub only_set: Option<usize>,
|
||||
}
|
||||
|
||||
impl Default for BakeVisualization {
|
||||
/// Every part hidden, in its default color, the low poly with its painted material
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
high_poly: BakeOverlay::hidden(HIGH_POLY_COLOR),
|
||||
matching_error: BakeOverlay::hidden(MATCHING_ERROR_COLOR),
|
||||
cage_surface: BakeOverlay::hidden(CAGE_SURFACE_COLOR),
|
||||
cage_wire: BakeOverlay::hidden(CAGE_WIRE_COLOR),
|
||||
missing_seams: BakeOverlay::hidden(MISSING_SEAM_COLOR),
|
||||
low_poly: BakeOverlay::hidden(LOW_POLY_COLOR),
|
||||
neutral: None,
|
||||
only_set: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BakeVisualization {
|
||||
/// Whether any part of the cage shows
|
||||
pub fn cage_shown(&self) -> bool {
|
||||
self.cage_surface.shown || self.cage_wire.shown
|
||||
}
|
||||
|
||||
/// The neutral material while the low poly shows with it
|
||||
pub fn shown_neutral(&self) -> Option<NeutralMaterial> {
|
||||
self.neutral.filter(|_| self.low_poly.shown)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! A texture set's cage as the renderer takes it
|
||||
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// A cage for [`crate::Renderer::set_bake_cage`]: three corners per low-poly triangle, and lines as corner pairs
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CageGeometry<'a> {
|
||||
pub corners: &'a [Vec3],
|
||||
/// The low poly's polygon edges, for the wireframe
|
||||
pub edges: &'a [[u32; 2]],
|
||||
/// The low poly's hard edges without a UV seam
|
||||
pub missing_seams: &'a [[u32; 2]],
|
||||
}
|
||||
@@ -6,4 +6,7 @@ pub(crate) struct CageGpu {
|
||||
pub(crate) corner_count: u32,
|
||||
pub(crate) edges: wgpu::Buffer,
|
||||
pub(crate) edge_index_count: u32,
|
||||
/// Corner pairs along the low poly's hard edges without a UV seam
|
||||
pub(crate) missing_seams: wgpu::Buffer,
|
||||
pub(crate) missing_seam_index_count: u32,
|
||||
}
|
||||
@@ -13,7 +13,9 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod bake_overlay;
|
||||
pub mod bake_visualization;
|
||||
pub mod cage_geometry;
|
||||
mod cage_gpu;
|
||||
pub mod displace;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -24,15 +26,19 @@ pub mod headless;
|
||||
mod high_poly_gpu;
|
||||
pub mod ibl;
|
||||
pub mod mesh_maps;
|
||||
mod missing_seam_gpu;
|
||||
pub mod neutral_material;
|
||||
pub mod overlay_quad;
|
||||
pub mod readback;
|
||||
pub mod renderer;
|
||||
pub mod set_highlight;
|
||||
mod subdivide;
|
||||
pub mod trace;
|
||||
mod uv_seam_gpu;
|
||||
|
||||
pub use bake_overlay::BakeOverlay;
|
||||
pub use bake_visualization::BakeVisualization;
|
||||
pub use cage_geometry::CageGeometry;
|
||||
pub use neutral_material::NeutralMaterial;
|
||||
pub use overlay_quad::OverlayQuad;
|
||||
pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale};
|
||||
pub use set_highlight::SetHighlight;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// The low poly's UV seams as a line list over its vertex buffer
|
||||
pub(crate) struct UvSeamGpu {
|
||||
/// The low poly's hard edges without a UV seam, as a line list over its vertex buffer
|
||||
pub(crate) struct MissingSeamGpu {
|
||||
/// The low-poly mesh the lines belong to
|
||||
pub(crate) mesh_id: u64,
|
||||
pub(crate) lines: wgpu::Buffer,
|
||||
@@ -0,0 +1,75 @@
|
||||
//! The plain material bake mode can show the low poly with, so the bake reads without the painted colours
|
||||
|
||||
/// The highest Quality: reflection samples per pixel
|
||||
pub const MAX_SAMPLES_PER_PIXEL: u32 = 256;
|
||||
|
||||
/// A plain material for the low poly in bake mode: its color comes from the low poly's overlay; its normal and occlusion are the texture set's as shown (the bake under any painted normal, height or AO)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct NeutralMaterial {
|
||||
pub roughness: f32,
|
||||
pub metallic: f32,
|
||||
/// How much the texture set's ambient occlusion (baked × painted) darkens the material (0 none, 1 fully)
|
||||
pub ao_intensity: f32,
|
||||
/// Environment reflection samples per pixel, taken by every frame so a moving view looks like a still one
|
||||
pub samples_per_pixel: u32,
|
||||
/// Light the material along the baked bent normal: the open direction above each point
|
||||
pub bent_normal: bool,
|
||||
/// How far the diffuse light turns to the bent normal, and how much reflections facing away from it dim (0..1)
|
||||
pub bent_normal_diffuse: f32,
|
||||
pub bent_normal_specular: f32,
|
||||
}
|
||||
|
||||
impl Default for NeutralMaterial {
|
||||
/// Low quality (16 samples per pixel), a slightly rough half metal, most of the baked occlusion, no bent normal
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
roughness: 0.3,
|
||||
metallic: 0.6,
|
||||
ao_intensity: 0.75,
|
||||
samples_per_pixel: 16,
|
||||
bent_normal: false,
|
||||
bent_normal_diffuse: 1.0,
|
||||
bent_normal_specular: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NeutralMaterial {
|
||||
/// The material's shader globals: x roughness, y metallic, z AO intensity, w 1 (on)
|
||||
pub(crate) fn globals(&self) -> [f32; 4] {
|
||||
[self.roughness, self.metallic, self.ao_intensity, 1.0]
|
||||
}
|
||||
|
||||
/// Reflection samples each frame takes: the whole quality, from 1 to [`MAX_SAMPLES_PER_PIXEL`] (a damaged settings file can't stall the GPU)
|
||||
pub(crate) fn samples_per_frame(&self) -> u32 {
|
||||
self.samples_per_pixel.clamp(1, MAX_SAMPLES_PER_PIXEL)
|
||||
}
|
||||
|
||||
/// The bent normal's shader globals: x diffuse amount, y specular amount (both 0 while off), zw -
|
||||
pub(crate) fn bent_normal_globals(&self) -> [f32; 4] {
|
||||
if self.bent_normal { [self.bent_normal_diffuse, self.bent_normal_specular, 0.0, 0.0] } else { [0.0; 4] }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_frame_takes_the_whole_quality() {
|
||||
let quality = |samples_per_pixel| NeutralMaterial { samples_per_pixel, ..NeutralMaterial::default() };
|
||||
assert_eq!(quality(16).samples_per_frame(), 16);
|
||||
assert_eq!(quality(256).samples_per_frame(), 256);
|
||||
assert_eq!(quality(u32::MAX).samples_per_frame(), MAX_SAMPLES_PER_PIXEL, "a damaged file is held to the highest quality");
|
||||
assert_eq!(quality(0).samples_per_frame(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bent_normal_reaches_the_shader_only_when_on() {
|
||||
let off = NeutralMaterial::default();
|
||||
assert_eq!(off.bent_normal_globals(), [0.0; 4]);
|
||||
let on = NeutralMaterial { bent_normal: true, bent_normal_diffuse: 0.5, bent_normal_specular: 0.25, ..off };
|
||||
assert_eq!(on.bent_normal_globals(), [0.5, 0.25, 0.0, 0.0]);
|
||||
}
|
||||
}
|
||||
+124
-44
@@ -31,14 +31,15 @@ use texturecraft_geom::{Mesh, OrbitCamera};
|
||||
use texturecraft_texel::TILE;
|
||||
|
||||
use crate::bake_visualization::BakeVisualization;
|
||||
use crate::cage_geometry::CageGeometry;
|
||||
use crate::cage_gpu::CageGpu;
|
||||
use crate::gpu_trace::{Checked, checked};
|
||||
use crate::high_poly_gpu::HighPolyGpu;
|
||||
use crate::ibl;
|
||||
use crate::missing_seam_gpu::MissingSeamGpu;
|
||||
use crate::overlay_quad::OverlayQuad;
|
||||
use crate::set_highlight::SetHighlight;
|
||||
use crate::subdivide::{self, Vertex};
|
||||
use crate::uv_seam_gpu::UvSeamGpu;
|
||||
|
||||
pub const MSAA: u32 = 4;
|
||||
pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
|
||||
@@ -84,6 +85,14 @@ struct GlobalsRaw {
|
||||
refr: [f32; 4],
|
||||
highlight: [f32; 4],
|
||||
highlight_shift: [f32; 4],
|
||||
bake_high: [f32; 4],
|
||||
bake_matching_error: [f32; 4],
|
||||
bake_cage: [f32; 4],
|
||||
bake_cage_wire: [f32; 4],
|
||||
bake_missing_seam: [f32; 4],
|
||||
bake_neutral_color: [f32; 4],
|
||||
bake_neutral: [f32; 4],
|
||||
bake_bent_normal: [f32; 4],
|
||||
}
|
||||
|
||||
/// The post pass uniform (see `Post` in post.wgsl).
|
||||
@@ -548,7 +557,10 @@ pub struct Renderer {
|
||||
bake_high_pipeline: wgpu::RenderPipeline,
|
||||
cage_pipeline: wgpu::RenderPipeline,
|
||||
cage_wire_pipeline: wgpu::RenderPipeline,
|
||||
uv_seam_pipeline: wgpu::RenderPipeline,
|
||||
missing_seam_pipeline: wgpu::RenderPipeline,
|
||||
/// The missing seams along the cage, and in the 2D view
|
||||
cage_missing_seam_pipeline: wgpu::RenderPipeline,
|
||||
uv_missing_seam_pipeline: wgpu::RenderPipeline,
|
||||
bg_pipeline: wgpu::RenderPipeline,
|
||||
blit_pipeline: wgpu::RenderPipeline,
|
||||
post_pipeline: wgpu::RenderPipeline,
|
||||
@@ -585,7 +597,7 @@ pub struct Renderer {
|
||||
bake_high: Option<HighPolyGpu>,
|
||||
/// Each texture set's cage, by set index
|
||||
cages: Vec<Option<CageGpu>>,
|
||||
uv_seams: Option<UvSeamGpu>,
|
||||
missing_seams: Option<MissingSeamGpu>,
|
||||
sets: Vec<SetGpu>,
|
||||
/// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least
|
||||
/// as reduced as the device's texture limit needs).
|
||||
@@ -1001,8 +1013,30 @@ impl Renderer {
|
||||
MSAA,
|
||||
wire3d_depth.clone(),
|
||||
);
|
||||
let uv_seam_pipeline =
|
||||
pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone());
|
||||
let cage_missing_seam_pipeline = pipeline(
|
||||
device,
|
||||
"tc_cage_missing_seam",
|
||||
&background_layout,
|
||||
&module,
|
||||
"vs_bake_cage_wire",
|
||||
&corner_layout,
|
||||
hdr_target("fs_wire_cage_missing_seam", blend),
|
||||
MSAA,
|
||||
wire3d_depth.clone(),
|
||||
);
|
||||
let uv_missing_seam_pipeline =
|
||||
pipeline(device, "tc_uv_missing_seam", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire_missing_seam", blend), MSAA, always());
|
||||
let missing_seam_pipeline = pipeline(
|
||||
device,
|
||||
"tc_missing_seam",
|
||||
&layout,
|
||||
&module,
|
||||
"vs_wire3d",
|
||||
&vertex_layout,
|
||||
hdr_target("fs_wire_missing_seam", blend),
|
||||
MSAA,
|
||||
wire3d_depth.clone(),
|
||||
);
|
||||
let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always());
|
||||
let overlay_pipeline =
|
||||
pipeline(device, "tc_overlay", &background_layout, &module, "vs_overlay", &vertex_layout, hdr_target("fs_overlay", blend), MSAA, wire3d_depth);
|
||||
@@ -1135,7 +1169,9 @@ impl Renderer {
|
||||
bake_high_pipeline,
|
||||
cage_pipeline,
|
||||
cage_wire_pipeline,
|
||||
uv_seam_pipeline,
|
||||
missing_seam_pipeline,
|
||||
cage_missing_seam_pipeline,
|
||||
uv_missing_seam_pipeline,
|
||||
bg_pipeline,
|
||||
blit_pipeline,
|
||||
post_pipeline,
|
||||
@@ -1162,7 +1198,7 @@ impl Renderer {
|
||||
mesh: None,
|
||||
bake_high: None,
|
||||
cages: Vec::new(),
|
||||
uv_seams: None,
|
||||
missing_seams: None,
|
||||
sets: Vec::new(),
|
||||
display_shift: 0,
|
||||
material_sets: Vec::new(),
|
||||
@@ -1289,8 +1325,8 @@ impl Renderer {
|
||||
self.content_rev += 1;
|
||||
}
|
||||
|
||||
/// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners
|
||||
pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) {
|
||||
/// Texture set `texture_set`'s cage; `None` removes it. The same `topology` as before only rewrites the corners
|
||||
pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<CageGeometry<'_>>, topology: u64) {
|
||||
if self.cages.len() <= texture_set {
|
||||
self.cages.resize_with(texture_set + 1, || None);
|
||||
}
|
||||
@@ -1298,16 +1334,18 @@ impl Renderer {
|
||||
|
||||
match (cage, slot.as_mut()) {
|
||||
(None, _) => *slot = None,
|
||||
(Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => {
|
||||
queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners));
|
||||
(Some(cage), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == cage.corners.len() => {
|
||||
queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(cage.corners));
|
||||
}
|
||||
(Some((corners, edges)), _) => {
|
||||
(Some(cage), _) => {
|
||||
*slot = Some(CageGpu {
|
||||
topology,
|
||||
corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX),
|
||||
corner_count: corners.len() as u32,
|
||||
edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX),
|
||||
edge_index_count: (edges.len() * 2) as u32,
|
||||
corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(cage.corners), wgpu::BufferUsages::VERTEX),
|
||||
corner_count: cage.corners.len() as u32,
|
||||
edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(cage.edges), wgpu::BufferUsages::INDEX),
|
||||
edge_index_count: (cage.edges.len() * 2) as u32,
|
||||
missing_seams: upload_buffer(device, queue, "tc_cage_seam_ib", bytemuck::cast_slice(cage.missing_seams), wgpu::BufferUsages::INDEX),
|
||||
missing_seam_index_count: (cage.missing_seams.len() * 2) as u32,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1322,8 +1360,8 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id`
|
||||
pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) {
|
||||
/// The low poly's hard edges without a UV seam as vertex pairs per material ([`Mesh::missing_seam_edges`]) for mesh `mesh_id`
|
||||
pub fn set_missing_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) {
|
||||
let mut line_indices: Vec<u32> = Vec::new();
|
||||
let mut line_draws = Vec::new();
|
||||
for (material, edges) in seams.iter().enumerate() {
|
||||
@@ -1332,8 +1370,8 @@ impl Renderer {
|
||||
line_draws.push((start, line_indices.len() as u32 - start, material));
|
||||
}
|
||||
|
||||
let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX);
|
||||
self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws });
|
||||
let lines = upload_buffer(device, queue, "tc_missing_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX);
|
||||
self.missing_seams = Some(MissingSeamGpu { mesh_id, lines, line_draws });
|
||||
self.content_rev += 1;
|
||||
}
|
||||
|
||||
@@ -1938,6 +1976,7 @@ impl Renderer {
|
||||
refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0],
|
||||
highlight: highlight_globals(s, data),
|
||||
highlight_shift: highlight_shift(frame.size),
|
||||
..bake_globals(s.bake)
|
||||
};
|
||||
let flag = |b: bool| if b { 1.0 } else { 0.0 };
|
||||
let post = PostRaw {
|
||||
@@ -2148,14 +2187,13 @@ impl Renderer {
|
||||
pass.set_bind_group(2, refraction_source, &[]);
|
||||
let geometry = self.geometry(mesh, frame);
|
||||
let bake = frame.shade.bake.filter(|_| uv_set.is_none());
|
||||
let low_poly_shown = bake.is_none_or(|bake| bake.low_poly);
|
||||
let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set);
|
||||
let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && low_poly_set.is_none_or(|only| only == *set)).unzip();
|
||||
let low_poly_shown = bake.is_none_or(|bake| bake.low_poly.shown);
|
||||
let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && uv_set.is_none_or(|only| only == *set)).unzip();
|
||||
|
||||
// The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too)
|
||||
let passes = [
|
||||
(low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1),
|
||||
(wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, low_poly_set, 1),
|
||||
(low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, uv_set, 1),
|
||||
(wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1),
|
||||
(highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS),
|
||||
];
|
||||
for (pipeline, vertices, indices, ranges, only_set, instances) in passes {
|
||||
@@ -2173,6 +2211,18 @@ impl Renderer {
|
||||
if let Some(bake) = bake {
|
||||
self.draw_bake(&mut pass, mesh, frame, bake);
|
||||
}
|
||||
if let Some(texture_set) = uv_set
|
||||
&& frame.shade.bake.is_some_and(|bake| bake.missing_seams.shown)
|
||||
&& let Some(seams) = self.missing_seams.as_ref().filter(|seams| seams.mesh_id == mesh.id)
|
||||
{
|
||||
pass.set_pipeline(&self.uv_missing_seam_pipeline);
|
||||
pass.set_vertex_buffer(0, mesh.geo.vb.slice(..));
|
||||
pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (range, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) {
|
||||
pass.set_bind_group(1, &set.bind_group, &[]);
|
||||
pass.draw_indexed(range, 0, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
// Overlay quads last, so the mesh's depth hides what is behind it
|
||||
if uv_set.is_none()
|
||||
@@ -2184,9 +2234,9 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bake mode's high poly, UV seams and cages over the low poly `low_poly`
|
||||
/// Bake mode's high poly, missing seams and cages over the low poly `low_poly`
|
||||
fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) {
|
||||
if bake.high_poly
|
||||
if bake.high_poly.shown
|
||||
&& let Some(high) = &self.bake_high
|
||||
{
|
||||
pass.set_pipeline(&self.bake_high_pipeline);
|
||||
@@ -2196,35 +2246,45 @@ impl Renderer {
|
||||
pass.draw_indexed(0..high.index_count, 0, 0..1);
|
||||
}
|
||||
|
||||
if bake.uv_seams
|
||||
&& let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id)
|
||||
if bake.missing_seams.shown
|
||||
&& let Some(seams) = self.missing_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id)
|
||||
{
|
||||
pass.set_pipeline(&self.uv_seam_pipeline);
|
||||
pass.set_pipeline(&self.missing_seam_pipeline);
|
||||
pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..));
|
||||
pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) {
|
||||
for (range, set) in self.drawable(&seams.line_draws, &frame.visible, None) {
|
||||
pass.set_bind_group(1, &set.bind_group, &[]);
|
||||
pass.draw_indexed(range, 0, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
if !bake.cage {
|
||||
return;
|
||||
}
|
||||
|
||||
let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true);
|
||||
let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref());
|
||||
// The translucent faces first, then the wireframe over them
|
||||
pass.set_pipeline(&self.cage_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.draw(0..cage.corner_count, 0..1);
|
||||
if bake.cage_surface.shown {
|
||||
pass.set_pipeline(&self.cage_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.draw(0..cage.corner_count, 0..1);
|
||||
}
|
||||
}
|
||||
pass.set_pipeline(&self.cage_wire_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..cage.edge_index_count, 0, 0..1);
|
||||
|
||||
if bake.cage_wire.shown {
|
||||
pass.set_pipeline(&self.cage_wire_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..cage.edge_index_count, 0, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
if bake.missing_seams.shown && bake.cage_shown() {
|
||||
pass.set_pipeline(&self.cage_missing_seam_pipeline);
|
||||
for cage in cages() {
|
||||
pass.set_vertex_buffer(0, cage.corners.slice(..));
|
||||
pass.set_index_buffer(cage.missing_seams.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..cage.missing_seam_index_count, 0, 0..1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2336,6 +2396,26 @@ fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] {
|
||||
[r, g, b, HIGHLIGHT_OPACITY]
|
||||
}
|
||||
|
||||
/// The globals of bake mode's overlays and neutral material for `bake` (all zero without it)
|
||||
fn bake_globals(bake: Option<BakeVisualization>) -> GlobalsRaw {
|
||||
let Some(bake) = bake else { return GlobalsRaw::zeroed() };
|
||||
|
||||
let [red, green, blue] = bake.low_poly.color;
|
||||
let neutral = bake.shown_neutral();
|
||||
let samples_per_frame = neutral.map_or(0, |neutral| neutral.samples_per_frame());
|
||||
GlobalsRaw {
|
||||
bake_high: bake.high_poly.globals(),
|
||||
bake_matching_error: bake.matching_error.globals(),
|
||||
bake_cage: bake.cage_surface.globals(),
|
||||
bake_cage_wire: bake.cage_wire.globals(),
|
||||
bake_missing_seam: bake.missing_seams.globals(),
|
||||
bake_neutral_color: [red, green, blue, samples_per_frame as f32],
|
||||
bake_neutral: neutral.map_or([0.0; 4], |neutral| neutral.globals()),
|
||||
bake_bent_normal: neutral.map_or([0.0; 4], |neutral| neutral.bent_normal_globals()),
|
||||
..GlobalsRaw::zeroed()
|
||||
}
|
||||
}
|
||||
|
||||
/// Globals `highlight_shift`: how far each of the highlight's line copies moves sideways, in clip units of a `size` pixel target
|
||||
fn highlight_shift(size: [u32; 2]) -> [f32; 4] {
|
||||
let half_extra_width = (HIGHLIGHT_WIDTH_PX - 1.0) * 0.5;
|
||||
|
||||
@@ -1,19 +1,46 @@
|
||||
// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams
|
||||
// Bake mode's 3D view: the high poly, the cage around the low poly, the missing seams and the neutral material
|
||||
|
||||
struct BakeViewOut {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) world_position: vec3<f32>,
|
||||
@location(1) normal: vec3<f32>,
|
||||
// 1 where the bake's rays miss the high poly, 0 where they reach it
|
||||
// 1 where the bake's rays miss the high poly, 0 where they reach it, negative where another texture set owns it (hidden)
|
||||
@location(2) missed: f32,
|
||||
};
|
||||
|
||||
const HIGH_POLY_COLOR: vec3<f32> = vec3<f32>(0.10, 0.36, 0.56);
|
||||
const MISSED_COLOR: vec3<f32> = vec3<f32>(0.80, 0.01, 0.01);
|
||||
const CAGE_COLOR: vec3<f32> = vec3<f32>(0.55, 0.42, 0.26);
|
||||
const CAGE_OPACITY: f32 = 0.16;
|
||||
const CAGE_WIRE_COLOR: vec4<f32> = vec4<f32>(0.75, 0.62, 0.42, 0.7);
|
||||
const UV_SEAM_COLOR: vec4<f32> = vec4<f32>(0.20, 0.85, 0.30, 1.0);
|
||||
// Reflectance of the neutral material's dielectric part facing the camera
|
||||
const NEUTRAL_F0: f32 = 0.04;
|
||||
|
||||
// Lowest roughness the neutral material shades with: below it the GGX lobe is too narrow for its samples
|
||||
const MIN_NEUTRAL_ROUGHNESS: f32 = 0.045;
|
||||
|
||||
// How fast reflections fade as they dip below the mesh surface (larger = sooner)
|
||||
const HORIZON_FADE: f32 = 1.3;
|
||||
|
||||
// Floor of the cosines that divide the reflection terms, so grazing angles stay finite
|
||||
const MIN_COSINE: f32 = 1e-4;
|
||||
|
||||
// A normal closer than this to +-Z builds its tangent frame from X, where the cross product with Z would vanish
|
||||
const TANGENT_HELPER_MAX_Z: f32 = 0.999;
|
||||
|
||||
// One mip coarser than each sample's share of the lobe: hides the gaps between few samples (filtered importance sampling)
|
||||
const FILTERED_SAMPLING_LOD_BIAS: f32 = 1.0;
|
||||
|
||||
// A packed bent normal shorter than this is the unbaked gray, not a direction
|
||||
const BENT_NORMAL_MIN_LENGTH: f32 = 0.5;
|
||||
|
||||
// Cosines between a reflection and the bent normal over which the reflection goes from occluded to open
|
||||
const BENT_OCCLUSION_START: f32 = -0.25;
|
||||
const BENT_OCCLUSION_END: f32 = 0.75;
|
||||
|
||||
// Floor of the GGX distribution's denominator, which reaches 0 at the peak of a mirror-like lobe
|
||||
const MIN_GGX_DENOMINATOR: f32 = 1e-6;
|
||||
|
||||
// Fractional part of the golden ratio: shifts each accumulated frame's samples around the lobe
|
||||
const GOLDEN_RATIO_FRACTION: f32 = 0.618034;
|
||||
|
||||
// High-poly surface where the interpolated `missed` falls below this belongs to a hidden texture set
|
||||
const HIDDEN_BELOW: f32 = -0.5;
|
||||
|
||||
// Brightness of surfaces seen edge-on; facing the camera adds the rest
|
||||
const HEADLIGHT_AMBIENT: f32 = 0.3;
|
||||
@@ -45,7 +72,11 @@ fn vs_bake_high(@location(0) position: vec3<f32>, @location(1) normal: vec3<f32>
|
||||
|
||||
@fragment
|
||||
fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed);
|
||||
if (surface.missed < HIDDEN_BELOW) {
|
||||
discard;
|
||||
}
|
||||
|
||||
let color = mix(g.bake_high.rgb, g.bake_matching_error.rgb, max(surface.missed, 0.0) * g.bake_matching_error.a);
|
||||
return vec4<f32>(headlight(color, normalize(surface.normal), surface.world_position), 1.0);
|
||||
}
|
||||
|
||||
@@ -63,7 +94,7 @@ fn vs_bake_cage(@location(0) position: vec3<f32>) -> BakeViewOut {
|
||||
@fragment
|
||||
fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position)));
|
||||
return vec4<f32>(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY);
|
||||
return vec4<f32>(headlight(g.bake_cage.rgb, face_normal, surface.world_position), g.bake_cage.a);
|
||||
}
|
||||
|
||||
// Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces
|
||||
@@ -79,10 +110,107 @@ fn vs_bake_cage_wire(@location(0) position: vec3<f32>) -> BakeViewOut {
|
||||
|
||||
@fragment
|
||||
fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
return CAGE_WIRE_COLOR;
|
||||
return g.bake_cage_wire;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4<f32> {
|
||||
return UV_SEAM_COLOR;
|
||||
fn fs_wire_missing_seam(surface: VOut) -> @location(0) vec4<f32> {
|
||||
return g.bake_missing_seam;
|
||||
}
|
||||
|
||||
// The missing seams along the cage, whose vertices carry the bake view's outputs
|
||||
@fragment
|
||||
fn fs_wire_cage_missing_seam(surface: BakeViewOut) -> @location(0) vec4<f32> {
|
||||
return g.bake_missing_seam;
|
||||
}
|
||||
|
||||
// The neutral material at the texture set's normal `n` (over the mesh normal `n_geo`) seen from direction `v`, darkened by its occlusion `ao_channel`, lit along the packed bent normal `packed_bent` when it is on
|
||||
fn neutral_color(n: vec3<f32>, n_geo: vec3<f32>, v: vec3<f32>, world_position: vec3<f32>, ao_channel: f32, packed_bent: vec3<f32>) -> vec4<f32> {
|
||||
let albedo = g.bake_neutral_color.rgb;
|
||||
let rough = clamp(g.bake_neutral.x, MIN_NEUTRAL_ROUGHNESS, 1.0);
|
||||
let metal = g.bake_neutral.y;
|
||||
let ao = mix(1.0, ao_channel, g.bake_neutral.z);
|
||||
let f0 = mix(vec3<f32>(NEUTRAL_F0), albedo, metal);
|
||||
let diffuse_col = albedo * (1.0 - metal);
|
||||
let nov = clamp(abs(dot(n, v)), MIN_COSINE, 1.0);
|
||||
|
||||
// An unbaked bent normal reads as the neutral gray (length 0): the surface normal stands in
|
||||
var bent = packed_bent * 2.0 - 1.0;
|
||||
bent = select(n, normalize(bent), dot(bent, bent) > BENT_NORMAL_MIN_LENGTH * BENT_NORMAL_MIN_LENGTH);
|
||||
let diffuse = sh_irradiance(normalize(mix(n, bent, g.bake_bent_normal.x)), vec3<f32>(0.0)) * diffuse_col * ao;
|
||||
let r = reflect(-v, n);
|
||||
let horizon = clamp(1.0 + HORIZON_FADE * dot(r, n_geo), 0.0, 1.0);
|
||||
// Reflections pointing away from the open direction are occluded
|
||||
let bent_occlusion = mix(1.0, smoothstep(BENT_OCCLUSION_START, BENT_OCCLUSION_END, dot(bent, r)), g.bake_bent_normal.y);
|
||||
let spec = sampled_reflection(n, v, rough, f0, nov) * ao * bent_occlusion * horizon * horizon;
|
||||
|
||||
var direct = vec3<f32>(0.0);
|
||||
if (g.light.w > 0.0) {
|
||||
let l = normalize(g.light.xyz);
|
||||
let h = normalize(l + v);
|
||||
let nol = clamp(dot(n, l), 0.0, 1.0);
|
||||
let f = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - clamp(dot(v, h), 0.0, 1.0), 5.0);
|
||||
direct = ((vec3<f32>(1.0) - f) * diffuse_col / PI + ggx_dv(rough * rough, nov, nol, clamp(dot(n, h), 0.0, 1.0)) * f) * nol * g.light.w;
|
||||
if (g.shadow.x > 0.5 && nol > 0.0) {
|
||||
direct *= shadow_factor(world_position, n_geo);
|
||||
}
|
||||
}
|
||||
let color = diffuse + spec + direct;
|
||||
return vec4<f32>(select(color, vec3<f32>(0.0), any(color != color)), 1.0);
|
||||
}
|
||||
|
||||
// The environment's GGX reflection at normal `n`, importance sampled with this frame's share of the neutral material's quality; each accumulated frame takes other samples
|
||||
fn sampled_reflection(n: vec3<f32>, v: vec3<f32>, rough: f32, f0: vec3<f32>, nov: f32) -> vec3<f32> {
|
||||
let count = max(u32(g.bake_neutral_color.w), 1u);
|
||||
let a = rough * rough;
|
||||
let a2 = a * a;
|
||||
let env_size = vec2<f32>(textureDimensions(env_tex));
|
||||
let texel_solid_angle = 4.0 * PI / (env_size.x * env_size.y);
|
||||
let side = select(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 0.0, 1.0), abs(n.z) < TANGENT_HELPER_MAX_Z);
|
||||
let tangent = normalize(cross(side, n));
|
||||
let bitangent = cross(n, tangent);
|
||||
let frame_offset = u32(g.material.z) * count;
|
||||
// Schlick-GGX geometry term at k = a / 2
|
||||
let k = a * 0.5;
|
||||
let view_visibility = nov / (nov * (1.0 - k) + k);
|
||||
|
||||
var sum = vec3<f32>(0.0);
|
||||
for (var index = 0u; index < count; index++) {
|
||||
let xi = vec2<f32>(fract((f32(index) + 0.5) / f32(count) + f32(g.material.z) * GOLDEN_RATIO_FRACTION), radical_inverse(index + frame_offset));
|
||||
let phi = 2.0 * PI * xi.x;
|
||||
// Clamped: near roughness 0 the ratio rounds a hair past 1, and the sine's square root would be NaN (a black pixel once frames accumulate)
|
||||
let cos_theta = clamp(sqrt((1.0 - xi.y) / (1.0 + (a2 - 1.0) * xi.y)), 0.0, 1.0);
|
||||
let sin_theta = sqrt(1.0 - cos_theta * cos_theta);
|
||||
let h = normalize(tangent * (cos(phi) * sin_theta) + bitangent * (sin(phi) * sin_theta) + n * cos_theta);
|
||||
let l = reflect(-v, h);
|
||||
let nol = min(dot(n, l), 1.0);
|
||||
if (nol <= 0.0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Capped at 1: a dot product rounding past it makes pow(1 - voh, 5) NaN on GPUs that compute pow through log2
|
||||
let noh = clamp(dot(n, h), MIN_COSINE, 1.0);
|
||||
let voh = clamp(dot(v, h), MIN_COSINE, 1.0);
|
||||
let denominator = max(noh * noh * (a2 - 1.0) + 1.0, MIN_GGX_DENOMINATOR);
|
||||
let pdf = a2 / (PI * denominator * denominator) * noh / (4.0 * voh);
|
||||
// Filtered importance sampling: each sample reads the mip that covers its share of the lobe
|
||||
let lod = clamp(0.5 * log2(1.0 / (f32(count) * pdf * texel_solid_angle)) + FILTERED_SAMPLING_LOD_BIAS, 0.0, g.env.y);
|
||||
let light = textureSampleLevel(env_tex, env_samp, env_uv(l), lod).rgb;
|
||||
let fresnel = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - voh, 5.0);
|
||||
let visibility = view_visibility * nol / (nol * (1.0 - k) + k);
|
||||
let contribution = light * fresnel * (visibility * voh / (noh * nov));
|
||||
// A sample that still came out NaN (x != x) is dropped: the frame average would carry it, and post effects spread it over the image
|
||||
sum += select(contribution, vec3<f32>(0.0), any(contribution != contribution));
|
||||
}
|
||||
return sum / f32(count);
|
||||
}
|
||||
|
||||
// Van der Corput: the bits of `index` mirrored behind the binary point (swapped by hand: WebGL2 lacks a bit reverse)
|
||||
fn radical_inverse(index: u32) -> f32 {
|
||||
var bits = (index << 16u) | (index >> 16u);
|
||||
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
|
||||
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
|
||||
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
|
||||
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
|
||||
return f32(bits) / 4294967296.0;
|
||||
}
|
||||
@@ -26,6 +26,14 @@ struct Globals {
|
||||
refr: vec4<f32>, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w -
|
||||
highlight: vec4<f32>, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity
|
||||
highlight_shift: vec4<f32>, // xy sideways shift of each highlight line copy (clip units), zw -
|
||||
bake_high: vec4<f32>, // bake mode: rgb high poly color, a -
|
||||
bake_matching_error: vec4<f32>, // rgb color where the bake's rays miss the high poly, a its strength (0 hidden)
|
||||
bake_cage: vec4<f32>, // rgb cage surface color, a opacity
|
||||
bake_cage_wire: vec4<f32>, // rgb cage wireframe color, a opacity
|
||||
bake_missing_seam: vec4<f32>, // rgb color of hard edges without a UV seam, a opacity
|
||||
bake_neutral_color: vec4<f32>, // rgb the neutral material's color, a its reflection samples this frame
|
||||
bake_neutral: vec4<f32>, // x roughness, y metallic, z AO intensity of the neutral material, w on (1)
|
||||
bake_bent_normal: vec4<f32>, // x, y how much the bent normal (in the aux texture) turns the diffuse light and dims reflections, zw -
|
||||
};
|
||||
|
||||
@group(0) @binding(0) var<uniform> g: Globals;
|
||||
@@ -446,6 +454,10 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
return unlit(data_out((col + tint) * diff));
|
||||
}
|
||||
|
||||
if (g.bake_neutral.w > 0.5) {
|
||||
return Shaded(neutral_color(n, n_geo, v, i.wpos, orm.r, aux.rgb), vec3<f32>(0.0));
|
||||
}
|
||||
|
||||
// Opacity: dithered alpha test (a new pattern per accumulated frame, so it averages out).
|
||||
if (base_s.a < hash12(i.clip.xy + g.material.z * vec2<f32>(17.0, 59.0))) {
|
||||
discard;
|
||||
|
||||
+148
-24
@@ -3,7 +3,7 @@ use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{OrbitCamera, primitives};
|
||||
use texturecraft_render::headless::Headless;
|
||||
use texturecraft_render::renderer::TAA_SAMPLES;
|
||||
use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind};
|
||||
use texturecraft_render::{BakeOverlay, BakeVisualization, CageGeometry, Frame, NeutralMaterial, Shade, ViewKind};
|
||||
|
||||
/// The UI's key light (`viewport::shade`).
|
||||
const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5];
|
||||
@@ -226,6 +226,91 @@ fn wireframe_3d_overlays_the_mesh() {
|
||||
assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean");
|
||||
}
|
||||
|
||||
/// `overlay` shown
|
||||
fn shown(overlay: BakeOverlay) -> BakeOverlay {
|
||||
BakeOverlay { shown: true, ..overlay }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_neutral_material_shades_the_low_poly_in_its_settings() {
|
||||
const COLOR_LEAD: i32 = 30;
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
|
||||
let neutral = NeutralMaterial { roughness: 0.5, metallic: 0.0, ao_intensity: 1.0, samples_per_pixel: 16, ..NeutralMaterial::default() };
|
||||
let low_poly = BakeOverlay { color: [0.0, 0.0, 0.8], ..shown(BakeVisualization::default().low_poly) };
|
||||
let painted_parts = BakeVisualization { low_poly, ..BakeVisualization::default() };
|
||||
let neutral_parts = BakeVisualization { neutral: Some(neutral), ..painted_parts };
|
||||
let painted = render(&mut h, &shaded(&frame, |s| s.bake = Some(painted_parts)), "bake_neutral_off");
|
||||
let blue = render(&mut h, &shaded(&frame, |s| s.bake = Some(neutral_parts)), "bake_neutral_blue");
|
||||
let center = (frame.size[0] / 2, frame.size[1] / 2);
|
||||
let [red, green, blue_channel] = blue.at(center.0, center.1).map(i32::from);
|
||||
assert!(
|
||||
blue_channel > red + COLOR_LEAD && blue_channel > green + COLOR_LEAD,
|
||||
"the neutral material takes the project mesh's color: {:?}",
|
||||
[red, green, blue_channel]
|
||||
);
|
||||
assert_ne!(blue.px, painted.px, "the painted material is replaced");
|
||||
|
||||
let metal = BakeVisualization { neutral: Some(NeutralMaterial { metallic: 1.0, roughness: 0.1, ..neutral }), ..neutral_parts };
|
||||
assert_ne!(render(&mut h, &shaded(&frame, |s| s.bake = Some(metal)), "bake_neutral_metal").px, blue.px, "roughness and metallic reach the shader");
|
||||
|
||||
let hidden_low_poly = BakeVisualization { low_poly: BakeOverlay { shown: false, ..low_poly }, ..neutral_parts };
|
||||
let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_neutral_background");
|
||||
assert_same(
|
||||
&render(&mut h, &shaded(&frame, |s| s.bake = Some(hidden_low_poly)), "bake_neutral_hidden"),
|
||||
&background,
|
||||
"a hidden project mesh draws nothing",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_neutral_material_looks_the_same_moving_as_still() {
|
||||
// A moving view only ever shows its first frame; with the whole quality in it, it stays close to the settled image (one sample a frame was 6.6 levels off)
|
||||
const MAX_MEAN_LEVELS: f32 = 4.0;
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
|
||||
let neutral = NeutralMaterial { roughness: 0.5, metallic: 1.0, ..NeutralMaterial::default() };
|
||||
let parts = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), neutral: Some(neutral), ..BakeVisualization::default() };
|
||||
let still = shaded(&frame, |s| {
|
||||
s.taa = true;
|
||||
s.bake = Some(parts);
|
||||
});
|
||||
let first = render(&mut h, &still, "bake_neutral_first_frame");
|
||||
for _ in 1..TAA_SAMPLES {
|
||||
render(&mut h, &still, "bake_neutral_settling");
|
||||
}
|
||||
let settled = render(&mut h, &still, "bake_neutral_settled");
|
||||
// Compared on the ball in the middle of the view, where the reflections are
|
||||
let (width, height) = (frame.size[0], frame.size[1]);
|
||||
let ball = (width * 3 / 8..width * 5 / 8).flat_map(|x| (height / 4..height / 2).map(move |y| (x, y)));
|
||||
let differences: Vec<f32> = ball.map(|(x, y)| (first.luma(x, y) - settled.luma(x, y)).abs()).collect();
|
||||
let mean_difference = differences.iter().sum::<f32>() / differences.len() as f32;
|
||||
assert!(mean_difference < MAX_MEAN_LEVELS, "the first frame is {mean_difference} levels off the settled one on average");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_neutral_material_stays_lit_at_any_roughness_once_settled() {
|
||||
// Near roughness 0 a bad sample gave NaN, and the settled average of all frames went black
|
||||
const MIN_BALL_LUMA: f32 = 20.0;
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
|
||||
for roughness in [0.0, 0.05, 0.1] {
|
||||
let neutral = NeutralMaterial { roughness, ..NeutralMaterial::default() };
|
||||
let parts = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), neutral: Some(neutral), ..BakeVisualization::default() };
|
||||
let still = shaded(&frame, |s| {
|
||||
s.taa = true;
|
||||
s.bake = Some(parts);
|
||||
});
|
||||
for _ in 0..TAA_SAMPLES {
|
||||
render(&mut h, &still, "bake_neutral_mirror_settling");
|
||||
}
|
||||
let settled = render(&mut h, &still, "bake_neutral_mirror_settled");
|
||||
let (width, height) = (frame.size[0], frame.size[1]);
|
||||
let ball = settled.mean(width * 3 / 8, height / 4, width * 5 / 8, height / 2);
|
||||
assert!(ball > MIN_BALL_LUMA, "roughness {roughness}: the settled ball is black ({ball})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_visualization_draws_the_high_poly_and_the_cage() {
|
||||
// A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color
|
||||
@@ -246,15 +331,17 @@ fn bake_visualization_draws_the_high_poly_and_the_cage() {
|
||||
}
|
||||
h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID).unwrap();
|
||||
let corners: Vec<Vec3> = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect();
|
||||
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY);
|
||||
let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None };
|
||||
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some(CageGeometry { corners: &corners, edges: &CAGE_EDGES, missing_seams: &CAGE_EDGES }), CAGE_TOPOLOGY);
|
||||
let bake = BakeVisualization { low_poly: shown(BakeVisualization::default().low_poly), ..BakeVisualization::default() };
|
||||
let center = (frame.size[0] / 2, frame.size[1] / 2);
|
||||
|
||||
let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name);
|
||||
let low_only = only(&mut h, bake, "bake_low_only");
|
||||
let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden");
|
||||
let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly");
|
||||
let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage");
|
||||
let high_only = BakeVisualization { high_poly: shown(bake.high_poly), matching_error: shown(bake.matching_error), ..BakeVisualization::default() };
|
||||
let caged_parts = BakeVisualization { cage_surface: shown(bake.cage_surface), cage_wire: shown(bake.cage_wire), ..bake };
|
||||
let hidden = only(&mut h, BakeVisualization::default(), "bake_low_hidden");
|
||||
let high_poly = only(&mut h, high_only, "bake_high_poly");
|
||||
let caged = only(&mut h, caged_parts, "bake_cage");
|
||||
assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly");
|
||||
let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background");
|
||||
assert_same(&hidden, &background, "without the low poly only the background is left");
|
||||
@@ -270,26 +357,63 @@ fn bake_visualization_draws_the_high_poly_and_the_cage() {
|
||||
|
||||
// Vertices the bake's rays miss turn red
|
||||
h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]);
|
||||
let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed");
|
||||
let missed = only(&mut h, high_only, "bake_high_missed");
|
||||
let [red, green, blue] = missed.at(center.0, center.1).map(i32::from);
|
||||
assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]);
|
||||
let no_error = only(&mut h, BakeVisualization { matching_error: bake.matching_error, ..high_only }, "bake_high_missed_hidden");
|
||||
assert_same(&no_error, &high_poly, "with the matching error hidden the missed vertices keep the high poly's color");
|
||||
let green_error = BakeOverlay { color: [0.0, 1.0, 0.0], ..high_only.matching_error };
|
||||
let [red, green, blue] =
|
||||
only(&mut h, BakeVisualization { matching_error: green_error, ..high_only }, "bake_high_missed_green").at(center.0, center.1).map(i32::from);
|
||||
assert!(green > red + COLOR_LEAD && green > blue + COLOR_LEAD, "the matching error's color reaches the shader: {:?}", [red, green, blue]);
|
||||
|
||||
// Show for selected texture set only: the other set's low poly and the cage of set 0 drop out
|
||||
let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set");
|
||||
let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set");
|
||||
assert_ne!(first_set.px, caged.px, "the second set's low poly is left out");
|
||||
assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out");
|
||||
assert_ne!(first_set.px, second_set.px);
|
||||
// Show for selected texture set only filters the cage (only set 0 has one here), never the low poly
|
||||
let first_set = only(&mut h, BakeVisualization { only_set: Some(0), ..caged_parts }, "bake_only_first_set");
|
||||
let second_set = only(&mut h, BakeVisualization { only_set: Some(1), ..caged_parts }, "bake_only_second_set");
|
||||
assert_same(&first_set, &caged, "set 0's cage stays and both sets' low poly draws");
|
||||
assert_same(&second_set, &low_only, "set 0's cage drops out, the low poly stays");
|
||||
|
||||
// UV seams draw over the low poly
|
||||
h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges());
|
||||
let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams");
|
||||
// The cage's surface and wireframe show apart, in their own color and opacity
|
||||
let surface_only = only(&mut h, BakeVisualization { cage_surface: shown(bake.cage_surface), ..bake }, "bake_cage_surface");
|
||||
let wire_only = only(&mut h, BakeVisualization { cage_wire: shown(bake.cage_wire), ..bake }, "bake_cage_wire");
|
||||
assert!(surface_only.px != low_only.px && wire_only.px != low_only.px && surface_only.px != wire_only.px, "each part of the cage draws on its own");
|
||||
let opaque_blue = BakeOverlay { color: [0.0, 0.0, 1.0], opacity: 1.0, ..caged_parts.cage_surface };
|
||||
let [red, green, blue] =
|
||||
only(&mut h, BakeVisualization { cage_surface: opaque_blue, ..bake }, "bake_cage_surface_blue").at(center.0, center.1).map(i32::from);
|
||||
assert!(blue > red + COLOR_LEAD && blue > green + COLOR_LEAD, "an opaque blue cage hides the ball: {:?}", [red, green, blue]);
|
||||
let clear = only(&mut h, BakeVisualization { cage_surface: BakeOverlay { opacity: 0.0, ..opaque_blue }, ..bake }, "bake_cage_surface_clear");
|
||||
assert_same(&clear, &low_only, "a fully transparent cage leaves the ball as it is");
|
||||
|
||||
// High-poly vertices another set owns are left out
|
||||
h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![-1.0; high.positions.len()]);
|
||||
let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_high_hidden_background");
|
||||
assert_same(&only(&mut h, high_only, "bake_high_other_set"), &background, "a high poly owned by other sets draws nothing");
|
||||
h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![0.0; high.positions.len()]);
|
||||
|
||||
// The missing seams draw over the low poly in their color
|
||||
h.renderer.set_missing_seams(&h.device, &h.queue, MESH_ID, &ball.wire_edges());
|
||||
let seams = only(&mut h, BakeVisualization { missing_seams: shown(bake.missing_seams), ..bake }, "bake_missing_seams");
|
||||
assert_ne!(seams.px, low_only.px, "the seams show");
|
||||
let green_seams = BakeOverlay { color: [0.0, 1.0, 0.0], ..shown(bake.missing_seams) };
|
||||
assert_ne!(
|
||||
only(&mut h, BakeVisualization { missing_seams: green_seams, ..bake }, "bake_missing_seams_green").px,
|
||||
seams.px,
|
||||
"the seams' color reaches the shader"
|
||||
);
|
||||
let uv = Frame { view_id: 2, kind: ViewKind::Uv { ts: 0, zoom: 1.0, pan: [0.0, 0.0] }, ..frame.clone() };
|
||||
let uv_plain = render(&mut h, &shaded(&uv, |s| s.bake = Some(bake)), "bake_missing_seams_uv_off");
|
||||
let uv_seams = render(&mut h, &shaded(&uv, |s| s.bake = Some(BakeVisualization { missing_seams: green_seams, ..bake })), "bake_missing_seams_uv");
|
||||
assert_ne!(uv_seams.px, uv_plain.px, "the seams show in the 2D view too");
|
||||
let caged_seams = only(&mut h, BakeVisualization { missing_seams: green_seams, ..caged_parts }, "bake_missing_seams_cage");
|
||||
let uncaged_seams = only(&mut h, BakeVisualization { missing_seams: green_seams, ..bake }, "bake_missing_seams_no_cage");
|
||||
let caged_plain = only(&mut h, caged_parts, "bake_cage_no_seams");
|
||||
assert_ne!(caged_seams.px, caged_plain.px, "the seams show with the cage");
|
||||
assert_ne!(caged_seams.px, uncaged_seams.px);
|
||||
|
||||
// A new distance with the same topology only moves the corners
|
||||
let grown: Vec<Vec3> = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect();
|
||||
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY);
|
||||
let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown");
|
||||
h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some(CageGeometry { corners: &grown, edges: &CAGE_EDGES, missing_seams: &CAGE_EDGES }), CAGE_TOPOLOGY);
|
||||
let bigger = only(&mut h, caged_parts, "bake_cage_grown");
|
||||
assert_ne!(caged.px, bigger.px, "the cage grew");
|
||||
}
|
||||
|
||||
@@ -307,7 +431,7 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() {
|
||||
assert!(error.contains("GPU buffer limit"), "{error}");
|
||||
|
||||
headless.renderer.set_bake_high_missed(&headless.queue, 2, &[]);
|
||||
let bake = BakeVisualization { high_poly: true, cage: false, uv_seams: false, low_poly: false, only_set: None };
|
||||
let bake = BakeVisualization { high_poly: shown(BakeVisualization::default().high_poly), ..BakeVisualization::default() };
|
||||
let cleared = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_cleared");
|
||||
let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_oversized_background");
|
||||
assert_same(&cleared, &background, "an oversized replacement must not leave the previous high poly visible");
|
||||
@@ -317,10 +441,10 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_low_poly_visibility_also_filters_its_wireframe() {
|
||||
fn bake_low_poly_visibility_also_filters_its_wireframe_but_not_by_selected_set() {
|
||||
let Some((mut headless, frame)) = setup() else { return };
|
||||
|
||||
let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: false, only_set: None };
|
||||
let bake = BakeVisualization::default();
|
||||
let hidden = shaded(&frame, |shade| {
|
||||
shade.bake = Some(bake);
|
||||
shade.wireframe_3d = true;
|
||||
@@ -332,13 +456,13 @@ fn bake_low_poly_visibility_also_filters_its_wireframe() {
|
||||
|
||||
for texture_set in [0, 1] {
|
||||
let selected = shaded(&hidden, |shade| {
|
||||
shade.bake = Some(BakeVisualization { low_poly: true, only_set: Some(texture_set), ..bake });
|
||||
shade.bake = Some(BakeVisualization { low_poly: shown(bake.low_poly), only_set: Some(texture_set), ..bake });
|
||||
shade.highlight = Some(texturecraft_render::SetHighlight { set: 1 - texture_set, color: [1.0, 0.5, 0.0] });
|
||||
});
|
||||
let expected = Frame { visible: vec![texture_set == 0, texture_set == 1], ..selected.clone() };
|
||||
let expected = shaded(&selected, |shade| shade.bake = Some(BakeVisualization { only_set: None, ..shade.bake.unwrap_or(bake) }));
|
||||
let actual = render(&mut headless, &selected, &format!("bake_wire_selected_{texture_set}"));
|
||||
let expected = render(&mut headless, &expected, &format!("bake_wire_expected_{texture_set}"));
|
||||
assert_same(&actual, &expected, "the wireframe and highlight respect the selected texture set");
|
||||
assert_same(&actual, &expected, "the selected-set filter leaves the low poly, its wireframe and highlight alone");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,58 +1,189 @@
|
||||
use egui::collapsing_header::CollapsingState;
|
||||
use egui::{Rect, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
use texturecraft_render::BakeOverlay;
|
||||
|
||||
use super::BakeVisualizationToggles;
|
||||
use super::section_opening::SectionOpening;
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::i18n::{n_, tr, trf};
|
||||
use crate::screen_color_pick::eyedropper;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::{icon_button_without_tooltip, section_chevron};
|
||||
use crate::widgets::{color_swatch, combo, icon_button, section_chevron, slider};
|
||||
|
||||
/// The panel's width and its gap from the 3D view's top-left corner
|
||||
const PANEL_WIDTH: f32 = 280.0;
|
||||
const PANEL_MARGIN: f32 = 12.0;
|
||||
|
||||
/// Size of the panel's eye buttons
|
||||
/// Opacity of the panel's backing
|
||||
const PANEL_OPACITY: f32 = 0.92;
|
||||
|
||||
/// Size of the panel's eye button, and of the smaller buttons on its rows
|
||||
const EYE_BUTTON_SIZE: f32 = 22.0;
|
||||
const ROW_BUTTON_SIZE: f32 = 18.0;
|
||||
|
||||
/// Width of an overlay's color swatch
|
||||
const SWATCH_WIDTH: f32 = 44.0;
|
||||
|
||||
/// The neutral material's quality steps: samples per pixel and their names
|
||||
const QUALITIES: [(u32, &str); 6] = [
|
||||
(4, n_("Very Low (4 spp)")),
|
||||
(16, n_("Low (16 spp)")),
|
||||
(32, n_("Medium (32 spp)")),
|
||||
(64, n_("High (64 spp)")),
|
||||
(128, n_("Very High (128 spp)")),
|
||||
(256, n_("Ultra (256 spp)")),
|
||||
];
|
||||
|
||||
/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view`
|
||||
pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) {
|
||||
let toggles = &mut app.ui.bake_visualization;
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show(
|
||||
ui.ctx(),
|
||||
|ui| {
|
||||
ui.set_width(PANEL_WIDTH);
|
||||
let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true);
|
||||
let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open()));
|
||||
if header.clicked() {
|
||||
collapsing_state.toggle(ui);
|
||||
}
|
||||
// Its own backing, so the panel reads in every theme over whatever the 3D view shows
|
||||
egui::Frame::popup(ui.style()).fill(tokens.panel.gamma_multiply(PANEL_OPACITY)).show(ui, |ui| {
|
||||
ui.set_width(PANEL_WIDTH);
|
||||
// Ids renamed with the reference defaults, so open/closed states saved by earlier builds don't carry over
|
||||
let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("baking_visualization_open"), true);
|
||||
if header(ui, toggles, collapsing_state.is_open()).clicked() {
|
||||
collapsing_state.toggle(ui);
|
||||
}
|
||||
|
||||
collapsing_state.show_body_unindented(ui, |ui| {
|
||||
ui.add_enabled_ui(toggles.on, |ui| {
|
||||
ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only"));
|
||||
eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None);
|
||||
eye_row(ui, &mut toggles.cage, tr("Cage"), None);
|
||||
eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None);
|
||||
eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None);
|
||||
});
|
||||
collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles));
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response
|
||||
fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option<bool>) -> egui::Response {
|
||||
/// The panel's sections below its header
|
||||
fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(egui::RichText::new(icon::INFO).color(Tokens::get(ui.ctx()).text_dim))
|
||||
.on_hover_text(tr("Only the cage and the high poly meshes of the selected texture set show."));
|
||||
});
|
||||
});
|
||||
|
||||
// The eye greys what it hides, and holds the project mesh shown
|
||||
let meshes_editable = !toggles.hide_baking_meshes;
|
||||
if collapsible(ui, "high_poly", tr("High Definition Mesh (HP)"), SectionOpening::Open, true, meshes_editable, |ui| {
|
||||
overlay_row(ui, "bake_high_poly_color", tr("Mesh"), &mut toggles.high_poly_mesh);
|
||||
overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error);
|
||||
}) {
|
||||
toggles.reset_high_poly();
|
||||
}
|
||||
|
||||
if collapsible(ui, "cage", tr("Cage"), SectionOpening::Open, true, meshes_editable, |ui| {
|
||||
overlay_row(ui, "bake_cage_surface_color", tr("Cage Surface"), &mut toggles.cage_surface);
|
||||
ui.add_enabled_ui(toggles.cage_surface.shown, |ui| slider(ui, tr("Cage Surface Opacity"), &mut toggles.cage_surface.opacity, 0.0..=1.0, 2));
|
||||
overlay_row(ui, "bake_cage_wire_color", tr("Cage Wireframe"), &mut toggles.cage_wire);
|
||||
ui.add_enabled_ui(toggles.cage_wire.shown, |ui| slider(ui, tr("Cage Wireframe Opacity"), &mut toggles.cage_wire.opacity, 0.0..=1.0, 2));
|
||||
}) {
|
||||
toggles.reset_cage();
|
||||
}
|
||||
|
||||
if collapsible(ui, "seams", tr("UV Seams"), SectionOpening::Closed, true, true, |ui| {
|
||||
overlay_row(ui, "bake_missing_seam_color", tr("Missing Seams on Hard Edges"), &mut toggles.missing_seams);
|
||||
}) {
|
||||
toggles.reset_seams();
|
||||
}
|
||||
|
||||
if collapsible(ui, "project_mesh", tr("Project Mesh (LP)"), SectionOpening::Closed, true, true, |ui| {
|
||||
ui.add_enabled_ui(meshes_editable, |ui| overlay_row(ui, "bake_project_mesh_color", tr("Project Mesh"), &mut toggles.project_mesh));
|
||||
ui.add_enabled_ui(toggles.project_mesh.shown, |ui| {
|
||||
collapsible(ui, "neutral_material", tr("Neutral Material"), SectionOpening::Open, false, true, |ui| neutral_material(ui, toggles))
|
||||
});
|
||||
}) {
|
||||
toggles.reset_project_mesh();
|
||||
}
|
||||
}
|
||||
|
||||
/// The project mesh's neutral material (picked in the 3D view's view menu): its quality, roughness, metallic, occlusion strength and bent normal
|
||||
fn neutral_material(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) {
|
||||
ui.add_enabled_ui(toggles.neutral_shown, |ui| {
|
||||
let neutral = &mut toggles.neutral;
|
||||
let selected = QUALITIES.iter().find(|(samples, _)| *samples == neutral.samples_per_pixel).map_or("", |(_, name)| tr(name));
|
||||
combo(ui, tr("Quality"), selected, |ui| {
|
||||
for (samples, name) in QUALITIES {
|
||||
ui.selectable_value(&mut neutral.samples_per_pixel, samples, tr(name));
|
||||
}
|
||||
});
|
||||
slider(ui, tr("Roughness"), &mut neutral.roughness, 0.0..=1.0, 2);
|
||||
slider(ui, tr("Metallic"), &mut neutral.metallic, 0.0..=1.0, 2);
|
||||
slider(ui, tr("AO intensity"), &mut neutral.ao_intensity, 0.0..=1.0, 2);
|
||||
ui.checkbox(&mut neutral.bent_normal, tr("Bent Normal"));
|
||||
ui.add_enabled_ui(neutral.bent_normal, |ui| {
|
||||
slider(ui, tr("Bent Normal Diffuse Amount"), &mut neutral.bent_normal_diffuse, 0.0..=1.0, 2);
|
||||
slider(ui, tr("Bent Normal Specular Amount"), &mut neutral.bent_normal_specular, 0.0..=1.0, 2);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// A section `title`, open or closed at first as `opening` says, with a reset button on its header when `resettable` and its contents greyed unless `editable`; returns whether the reset was clicked
|
||||
fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, resettable: bool, editable: bool, body: impl FnOnce(&mut Ui)) -> bool {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let mut collapsing_state =
|
||||
CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id(("baking_visualization_section", id)), opening == SectionOpening::Open);
|
||||
let (header, reset) = ui
|
||||
.horizontal(|ui| {
|
||||
ui.set_min_height(EYE_BUTTON_SIZE);
|
||||
let text = egui::RichText::new(format!("{} {title}", section_chevron(ui, collapsing_state.is_open()).text())).strong().color(tokens.text_strong);
|
||||
let header = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click()));
|
||||
// Dimmed while the section is closed, as the reference draws it
|
||||
let reset = resettable.then(|| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.add_enabled_ui(collapsing_state.is_open() && editable, |ui| {
|
||||
icon_button(ui, icon::CLOCK_COUNTER_CLOCKWISE, &trf("Reset {section}", &[("section", &title)]), false, ROW_BUTTON_SIZE)
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner
|
||||
});
|
||||
(header, reset)
|
||||
})
|
||||
.inner;
|
||||
if header.clicked() {
|
||||
collapsing_state.toggle(ui);
|
||||
}
|
||||
|
||||
collapsing_state.show_body_indented(&header, ui, |ui| {
|
||||
ui.add_enabled_ui(editable, body);
|
||||
});
|
||||
reset.is_some_and(|reset| reset.clicked())
|
||||
}
|
||||
|
||||
/// A checkbox for whether `overlay` shows, with its color swatch and an eyedropper for it on the right
|
||||
fn overlay_row(ui: &mut Ui, id: &str, label: &str, overlay: &mut BakeOverlay) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.checkbox(&mut overlay.shown, label);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.add_enabled_ui(overlay.shown, |ui| {
|
||||
eyedropper(
|
||||
ui,
|
||||
ui.make_persistent_id(id),
|
||||
&mut overlay.color,
|
||||
&trf("Pick the {overlay} Color from the Screen", &[("overlay", &label)]),
|
||||
ROW_BUTTON_SIZE,
|
||||
);
|
||||
color_swatch(ui, id, &mut overlay.color, SWATCH_WIDTH);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The panel's title with a chevron showing whether the panel is `open`, and the eye that hides the baking meshes; returns the title's response
|
||||
fn header(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, open: bool) -> egui::Response {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
ui.set_min_height(EYE_BUTTON_SIZE);
|
||||
let text = match open {
|
||||
Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())),
|
||||
None => egui::RichText::new(label),
|
||||
};
|
||||
let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click()));
|
||||
let text = egui::RichText::new(format!("{} {}", section_chevron(ui, open).text(), tr("Baking Visualization"))).color(tokens.text_strong);
|
||||
let response = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click()));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() {
|
||||
*shown = !*shown;
|
||||
if icon_button(ui, icon::EYE_SLASH, tr("Hide Baking Meshes"), toggles.hide_baking_meshes, EYE_BUTTON_SIZE).clicked() {
|
||||
toggles.toggle_hiding();
|
||||
}
|
||||
});
|
||||
response
|
||||
|
||||
@@ -1,34 +1,140 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use texturecraft_render::BakeVisualization;
|
||||
use texturecraft_render::{BakeOverlay, BakeVisualization, NeutralMaterial};
|
||||
|
||||
/// The Baking Visualization panel's switches in bake mode's 3D view
|
||||
/// Opacity of the cage's surface and wireframe until changed
|
||||
const CAGE_OPACITY: f32 = 0.4;
|
||||
|
||||
/// The Baking Visualization panel's settings for bake mode's 3D view (view state, not saved in the project)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct BakeVisualizationToggles {
|
||||
/// The panel's eye: the whole visualization on or off
|
||||
pub on: bool,
|
||||
/// The panel's eye: hides the high poly and the cage, whatever their own switches say
|
||||
pub hide_baking_meshes: bool,
|
||||
pub selected_set_only: bool,
|
||||
pub high_poly: bool,
|
||||
pub cage: bool,
|
||||
pub uv_seams: bool,
|
||||
pub low_poly: bool,
|
||||
pub high_poly_mesh: BakeOverlay,
|
||||
pub matching_error: BakeOverlay,
|
||||
pub cage_surface: BakeOverlay,
|
||||
pub cage_wire: BakeOverlay,
|
||||
pub missing_seams: BakeOverlay,
|
||||
pub project_mesh: BakeOverlay,
|
||||
/// Show the project mesh with [`Self::neutral`] instead of its painted material
|
||||
pub neutral_shown: bool,
|
||||
pub neutral: NeutralMaterial,
|
||||
}
|
||||
|
||||
impl Default for BakeVisualizationToggles {
|
||||
fn default() -> Self {
|
||||
Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true }
|
||||
let parts = BakeVisualization::default();
|
||||
let shown = |overlay: BakeOverlay| BakeOverlay { shown: true, ..overlay };
|
||||
Self {
|
||||
hide_baking_meshes: false,
|
||||
selected_set_only: false,
|
||||
high_poly_mesh: shown(parts.high_poly),
|
||||
matching_error: shown(parts.matching_error),
|
||||
cage_surface: BakeOverlay { opacity: CAGE_OPACITY, ..shown(parts.cage_surface) },
|
||||
cage_wire: BakeOverlay { opacity: CAGE_OPACITY, ..shown(parts.cage_wire) },
|
||||
missing_seams: shown(parts.missing_seams),
|
||||
project_mesh: shown(parts.low_poly),
|
||||
neutral_shown: true,
|
||||
neutral: NeutralMaterial::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BakeVisualizationToggles {
|
||||
/// What the renderer draws with these switches while texture set `selected_set` is selected
|
||||
pub fn visualization(&self, selected_set: usize) -> Option<BakeVisualization> {
|
||||
self.on.then_some(BakeVisualization {
|
||||
high_poly: self.high_poly,
|
||||
cage: self.cage,
|
||||
uv_seams: self.uv_seams,
|
||||
low_poly: self.low_poly,
|
||||
/// What the renderer draws with these settings while texture set `selected_set` is selected
|
||||
pub fn visualization(&self, selected_set: usize) -> BakeVisualization {
|
||||
let unless_hidden = |overlay: BakeOverlay| BakeOverlay { shown: overlay.shown && !self.hide_baking_meshes, ..overlay };
|
||||
BakeVisualization {
|
||||
high_poly: unless_hidden(self.high_poly_mesh),
|
||||
matching_error: self.matching_error,
|
||||
cage_surface: unless_hidden(self.cage_surface),
|
||||
cage_wire: unless_hidden(self.cage_wire),
|
||||
missing_seams: self.missing_seams,
|
||||
low_poly: self.project_mesh,
|
||||
neutral: self.neutral_shown.then_some(self.neutral),
|
||||
only_set: self.selected_set_only.then_some(selected_set),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the project mesh shows the neutral material lit along the bent normal, which the 3D view then reads in place of a mesh map
|
||||
pub fn bent_normal_shown(&self) -> bool {
|
||||
self.project_mesh.shown && self.neutral_shown && self.neutral.bent_normal
|
||||
}
|
||||
|
||||
/// Switch the panel's eye; hiding the baking meshes shows the project mesh, so the view never goes empty
|
||||
pub fn toggle_hiding(&mut self) {
|
||||
self.hide_baking_meshes = !self.hide_baking_meshes;
|
||||
self.project_mesh.shown |= self.hide_baking_meshes;
|
||||
}
|
||||
|
||||
/// Put the High Definition Mesh section back to its defaults
|
||||
pub fn reset_high_poly(&mut self) {
|
||||
let defaults = Self::default();
|
||||
(self.high_poly_mesh, self.matching_error) = (defaults.high_poly_mesh, defaults.matching_error);
|
||||
}
|
||||
|
||||
/// Put the Cage section back to its defaults
|
||||
pub fn reset_cage(&mut self) {
|
||||
let defaults = Self::default();
|
||||
(self.cage_surface, self.cage_wire) = (defaults.cage_surface, defaults.cage_wire);
|
||||
}
|
||||
|
||||
/// Put the UV Seams section back to its defaults
|
||||
pub fn reset_seams(&mut self) {
|
||||
self.missing_seams = Self::default().missing_seams;
|
||||
}
|
||||
|
||||
/// Put the Project Mesh section back to its defaults
|
||||
pub fn reset_project_mesh(&mut self) {
|
||||
let defaults = Self::default();
|
||||
(self.project_mesh, self.neutral_shown, self.neutral) = (defaults.project_mesh, defaults.neutral_shown, defaults.neutral);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn panel_settings_saved_by_earlier_builds_start_over_from_the_defaults() {
|
||||
let mut saved = serde_json::to_value(crate::state::UiState::default()).unwrap();
|
||||
let fields = saved.as_object_mut().unwrap();
|
||||
fields.remove("baking_visualization");
|
||||
fields.insert(
|
||||
"bake_visualization".into(),
|
||||
serde_json::json!({"hide_baking_meshes": false, "missing_seams": {"shown": false, "color": [1, 0, 0], "opacity": 1}}),
|
||||
);
|
||||
let state: crate::state::UiState = serde_json::from_value(saved).unwrap();
|
||||
assert_eq!(state.bake_visualization, BakeVisualizationToggles::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_settings_reach_the_renderer() {
|
||||
let mut toggles = BakeVisualizationToggles::default();
|
||||
toggles.cage_wire.color = [0.1, 0.2, 0.3];
|
||||
toggles.neutral_shown = false;
|
||||
let visualization = toggles.visualization(2);
|
||||
assert_eq!(visualization.cage_wire, toggles.cage_wire);
|
||||
assert_eq!(visualization.neutral, None);
|
||||
assert_eq!(visualization.only_set, None);
|
||||
toggles.selected_set_only = true;
|
||||
assert_eq!(toggles.visualization(2).only_set, Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_eye_hides_the_baking_meshes_and_keeps_the_project_mesh() {
|
||||
let mut toggles = BakeVisualizationToggles::default();
|
||||
let shown = toggles.visualization(0);
|
||||
assert!(shown.high_poly.shown && shown.cage_surface.shown && shown.cage_wire.shown, "the eye starts off, as in the reference");
|
||||
|
||||
toggles.project_mesh.shown = false;
|
||||
toggles.toggle_hiding();
|
||||
let hidden = toggles.visualization(0);
|
||||
assert!(!hidden.high_poly.shown && !hidden.cage_surface.shown && !hidden.cage_wire.shown);
|
||||
assert!(hidden.low_poly.shown, "hiding the baking meshes brings the project mesh back");
|
||||
|
||||
toggles.toggle_hiding();
|
||||
assert!(toggles.visualization(0).high_poly.shown, "the eye switches back");
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ mod bake_visualization_panel;
|
||||
mod bake_visualization_toggles;
|
||||
mod breadcrumb;
|
||||
mod common_settings;
|
||||
mod section_opening;
|
||||
pub use bake_paint_brush::BakePaintBrush;
|
||||
pub(crate) use bake_visualization_panel::bake_visualization_panel;
|
||||
pub use bake_visualization_toggles::BakeVisualizationToggles;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
/// Whether a Baking Visualization section starts open, as the reference shows the panel at first launch (HP and Cage open, UV seams and Project mesh closed)
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum SectionOpening {
|
||||
Open,
|
||||
Closed,
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use super::reach_link::ReachLink;
|
||||
use super::shared_handle::SharedHandle;
|
||||
use crate::gpu::SceneSync;
|
||||
|
||||
/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams
|
||||
/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the missing seams
|
||||
#[derive(Default)]
|
||||
pub struct BakeSceneLink {
|
||||
/// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one)
|
||||
@@ -51,7 +51,7 @@ impl BakeSceneLink {
|
||||
|
||||
let Some(visualization) = visualization else { return };
|
||||
|
||||
if visualization.high_poly {
|
||||
if visualization.high_poly.shown {
|
||||
let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone());
|
||||
let handle = SharedHandle::of(high.as_ref());
|
||||
if handle != self.high {
|
||||
@@ -64,14 +64,19 @@ impl BakeSceneLink {
|
||||
self.high_sent = true;
|
||||
}
|
||||
self.reach.sync(session, self.high_id, visualization.only_set, out);
|
||||
} else if self.high_sent {
|
||||
// A hidden high poly leaves the GPU; showing it again sends it and its colours under the same id, so its reach is not worked out again
|
||||
out.bake_high = Some((None, self.high_id));
|
||||
self.high_sent = false;
|
||||
self.reach.resend();
|
||||
}
|
||||
|
||||
if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) {
|
||||
if visualization.missing_seams.shown && self.seams_mesh_id != Some(session.mesh_id) {
|
||||
self.seams_mesh_id = Some(session.mesh_id);
|
||||
out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges()));
|
||||
out.missing_seams = Some((session.mesh_id, session.mesh.missing_seam_edges()));
|
||||
}
|
||||
|
||||
if visualization.cage {
|
||||
if visualization.cage_shown() {
|
||||
self.sync_cages(session, out);
|
||||
}
|
||||
}
|
||||
@@ -117,7 +122,20 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None };
|
||||
/// Every part of the visualization shown
|
||||
fn everything() -> BakeVisualization {
|
||||
let parts = BakeVisualization::default();
|
||||
let shown = |overlay: texturecraft_render::BakeOverlay| texturecraft_render::BakeOverlay { shown: true, ..overlay };
|
||||
BakeVisualization {
|
||||
high_poly: shown(parts.high_poly),
|
||||
matching_error: shown(parts.matching_error),
|
||||
cage_surface: shown(parts.cage_surface),
|
||||
cage_wire: shown(parts.cage_wire),
|
||||
missing_seams: shown(parts.missing_seams),
|
||||
low_poly: shown(parts.low_poly),
|
||||
..parts
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a test waits for the reach worker: frames, and the pause between them
|
||||
const WAIT_FRAMES: usize = 2000;
|
||||
@@ -165,41 +183,61 @@ mod tests {
|
||||
#[test]
|
||||
fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() {
|
||||
let (mut session, mut link) = (session(), BakeSceneLink::default());
|
||||
let first = sync(&mut link, &session, EVERYTHING);
|
||||
assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len()));
|
||||
let first = sync(&mut link, &session, everything());
|
||||
assert!(first.bake_high.is_some() && first.missing_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len()));
|
||||
let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") };
|
||||
|
||||
let unchanged = sync(&mut link, &session, EVERYTHING);
|
||||
assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent");
|
||||
let unchanged = sync(&mut link, &session, everything());
|
||||
assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.missing_seams.is_none(), "nothing changed, nothing is sent");
|
||||
|
||||
set_distances(&mut session, 0.03);
|
||||
let moved = sync(&mut link, &session, EVERYTHING);
|
||||
let moved = sync(&mut link, &session, everything());
|
||||
let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") };
|
||||
assert_eq!(moved_topology, topology, "a distance only moves the corners");
|
||||
assert_ne!(moved_cage.corners, cage.corners);
|
||||
|
||||
texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap();
|
||||
let rebuilt = sync(&mut link, &session, EVERYTHING);
|
||||
let rebuilt = sync(&mut link, &session, everything());
|
||||
assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage");
|
||||
// The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts
|
||||
red_share(&mut link, &session, EVERYTHING);
|
||||
red_share(&mut link, &session, everything());
|
||||
|
||||
link.resend();
|
||||
let resent = sync(&mut link, &session, EVERYTHING);
|
||||
assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again");
|
||||
let resent = sync(&mut link, &session, everything());
|
||||
assert!(resent.bake_high.is_some() && resent.missing_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again");
|
||||
assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len());
|
||||
assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame");
|
||||
assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id");
|
||||
assert!(!link.busy(), "a lost frame doesn't work out the reach again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_high_poly_leaves_the_gpu_and_comes_back_without_a_new_reach() {
|
||||
let (session, mut link) = (session(), BakeSceneLink::default());
|
||||
let sent = |out: SceneSync| out.bake_high.map(|(high, id)| (high.is_some(), id));
|
||||
let hidden = BakeVisualization { high_poly: BakeVisualization::default().high_poly, ..everything() };
|
||||
let first = sent(sync(&mut link, &session, everything()));
|
||||
red_share(&mut link, &session, everything());
|
||||
let dropped = sent(sync(&mut link, &session, hidden));
|
||||
assert!(sync(&mut link, &session, hidden).bake_high.is_none(), "dropped once");
|
||||
let back = sync(&mut link, &session, everything());
|
||||
assert!(!link.busy(), "showing it again starts no new reach");
|
||||
assert!(back.bake_high_missed.is_some(), "its colours are sent again with it");
|
||||
|
||||
let (Some((true, first_id)), Some((false, dropped_id)), Some((true, back_id))) = (first, dropped, sent(back)) else {
|
||||
panic!("the high poly is sent, dropped, then sent again")
|
||||
};
|
||||
|
||||
assert_eq!((dropped_id, back_id), (first_id, first_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reach_finishes_while_nothing_is_drawn() {
|
||||
let session = session();
|
||||
let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING };
|
||||
let no_high_poly = BakeVisualization { high_poly: BakeVisualization::default().high_poly, ..everything() };
|
||||
for hidden in [None, Some(no_high_poly)] {
|
||||
let mut link = BakeSceneLink::default();
|
||||
sync(&mut link, &session, EVERYTHING);
|
||||
sync(&mut link, &session, everything());
|
||||
assert!(link.busy(), "the first frame starts working out the reach");
|
||||
|
||||
let finished = (0..WAIT_FRAMES).any(|_| {
|
||||
@@ -215,11 +253,11 @@ mod tests {
|
||||
fn the_red_follows_the_distances_and_the_selected_set() {
|
||||
let (mut session, mut link) = (session(), BakeSceneLink::default());
|
||||
set_distances(&mut session, 0.0);
|
||||
let at_zero = red_share(&mut link, &session, EVERYTHING);
|
||||
let at_zero = red_share(&mut link, &session, everything());
|
||||
assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}");
|
||||
|
||||
set_distances(&mut session, 0.05);
|
||||
let covered = red_share(&mut link, &session, EVERYTHING);
|
||||
let covered = red_share(&mut link, &session, everything());
|
||||
assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}");
|
||||
|
||||
set_distances(&mut session, 0.0);
|
||||
@@ -230,10 +268,11 @@ mod tests {
|
||||
}
|
||||
};
|
||||
by_name(&mut session, "_no_such_suffix");
|
||||
let by_name_red = red_share(&mut link, &session, EVERYTHING);
|
||||
let by_name_red = red_share(&mut link, &session, everything());
|
||||
assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}");
|
||||
|
||||
let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING };
|
||||
assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing");
|
||||
let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..everything() };
|
||||
let hidden = texturecraft_engine::bake::HIDDEN_HIGH_POLY_VERTEX;
|
||||
assert_eq!(red_share(&mut link, &session, no_set), hidden, "a filter that keeps no set hides the whole high poly");
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use texturecraft_engine::Session;
|
||||
use texturecraft_engine::compose::{DisplayKind, ImageRes, tile_bytes};
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
use texturecraft_engine::geom::Mesh;
|
||||
use texturecraft_render::{BakeVisualization, Frame, Renderer, wgpu};
|
||||
use texturecraft_render::{BakeVisualization, CageGeometry, Frame, Renderer, wgpu};
|
||||
|
||||
use crate::bake_scene::{BakeSceneLink, CageUpload};
|
||||
|
||||
@@ -27,8 +27,8 @@ pub enum AuxView {
|
||||
/// A texture set's texels across and down, and its mesh material.
|
||||
pub type SetLayout = ((u32, u32), usize);
|
||||
|
||||
/// The low poly's UV seam edges (vertex pairs) per material
|
||||
pub type UvSeamEdges = Vec<Vec<(u32, u32)>>;
|
||||
/// The low poly's hard edges without a UV seam (vertex pairs) per material
|
||||
pub type MissingSeamEdges = Vec<Vec<(u32, u32)>>;
|
||||
|
||||
/// What the renderer must catch up with before drawing.
|
||||
#[derive(Default)]
|
||||
@@ -49,8 +49,8 @@ pub struct SceneSync {
|
||||
pub bake_cages: Vec<(usize, Option<CageUpload>, u64)>,
|
||||
/// Texture sets left after some were removed: their cages go too
|
||||
pub bake_cage_count: Option<usize>,
|
||||
/// The low poly's UV seams per material, for mesh id
|
||||
pub uv_seams: Option<(u64, UvSeamEdges)>,
|
||||
/// The low poly's hard edges without a UV seam per material, for mesh id
|
||||
pub missing_seams: Option<(u64, MissingSeamEdges)>,
|
||||
}
|
||||
|
||||
/// Lives in egui's callback resources.
|
||||
@@ -366,11 +366,15 @@ impl CallbackTrait for ViewCallback {
|
||||
gpu.renderer.truncate_bake_cages(count);
|
||||
}
|
||||
for (texture_set, cage, topology) in &sync.bake_cages {
|
||||
let cage = cage.as_ref().map(|upload| (upload.corners.as_slice(), upload.shell.edges.as_slice()));
|
||||
let cage = cage.as_ref().map(|upload| CageGeometry {
|
||||
corners: &upload.corners,
|
||||
edges: &upload.shell.edges,
|
||||
missing_seams: &upload.shell.missing_seams,
|
||||
});
|
||||
gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology);
|
||||
}
|
||||
if let Some((mesh_id, seams)) = &sync.uv_seams {
|
||||
gpu.renderer.set_uv_seams(device, queue, *mesh_id, seams);
|
||||
if let Some((mesh_id, seams)) = &sync.missing_seams {
|
||||
gpu.renderer.set_missing_seams(device, queue, *mesh_id, seams);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ pub mod render_mode;
|
||||
mod resource_picker;
|
||||
mod resource_picker_item;
|
||||
mod running_bake;
|
||||
mod screen_color_pick;
|
||||
pub mod shelf;
|
||||
pub mod shelf_preview;
|
||||
mod soft_box;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! An eyedropper button: after it is pressed, the next click anywhere in the window picks the color shown there
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use egui::{Id, Pos2, Ui};
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
use crate::widgets::icon_button;
|
||||
|
||||
/// Where the pick in progress is kept between frames
|
||||
const PICK_ID: &str = "screen_color_pick";
|
||||
|
||||
/// Where a screenshot callback leaves the sampled sRGB color for the button that asked for it
|
||||
type SampledSlot = Arc<Mutex<Option<(Id, [u8; 3])>>>;
|
||||
|
||||
/// The pick in progress: which button started it, and the color its screenshot sampled once that arrives
|
||||
#[derive(Clone, Default)]
|
||||
struct ScreenColorPick {
|
||||
target: Option<Id>,
|
||||
/// Filled by the screenshot callback with the target and the sRGB color under the click
|
||||
sampled: SampledSlot,
|
||||
}
|
||||
|
||||
/// An eyedropper button for the linear RGB color `linear`, `size` points square; a picked color lands in `linear` a frame or two after the click
|
||||
pub fn eyedropper(ui: &mut Ui, id: Id, linear: &mut [f32; 3], tooltip: &str, size: f32) {
|
||||
let key = Id::unique(PICK_ID);
|
||||
let mut pick: ScreenColorPick = ui.data(|data| data.get_temp(key)).unwrap_or_default();
|
||||
let picking = pick.target == Some(id);
|
||||
|
||||
let button = icon_button(ui, icon::EYEDROPPER, tooltip, picking, size);
|
||||
if button.clicked() {
|
||||
pick.target = if picking { None } else { Some(id) };
|
||||
} else if picking {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
|
||||
let (clicked, escaped, pointer) =
|
||||
ui.input(|input| (input.pointer.primary_clicked(), input.key_pressed(egui::Key::Escape), input.pointer.interact_pos()));
|
||||
if escaped {
|
||||
pick.target = None;
|
||||
} else if clicked && let Some(point) = pointer {
|
||||
request_sample(ui.ctx(), id, point, pick.sampled.clone());
|
||||
pick.target = None;
|
||||
}
|
||||
}
|
||||
|
||||
let landed = pick.sampled.lock().ok().and_then(|mut sampled| sampled.take_if(|(target, _)| *target == id));
|
||||
if let Some((_, srgb)) = landed {
|
||||
*linear = srgb.map(|channel| texturecraft_engine::texel::srgb_to_linear(f32::from(channel) / 255.0));
|
||||
}
|
||||
|
||||
ui.data_mut(|data| data.insert_temp(key, pick));
|
||||
}
|
||||
|
||||
/// Screenshot the next frame and put the color at `point` (in points) into `sampled` for `target`
|
||||
fn request_sample(ctx: &egui::Context, target: Id, point: Pos2, sampled: SampledSlot) {
|
||||
let pixels_per_point = ctx.pixels_per_point();
|
||||
let repaint = ctx.clone();
|
||||
let callback = egui::ScreenshotCallback::new(move |image| {
|
||||
if let (Some(color), Ok(mut slot)) = (pixel_at(&image, point, pixels_per_point), sampled.lock()) {
|
||||
*slot = Some((target, color));
|
||||
}
|
||||
repaint.request_repaint();
|
||||
});
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
/// The sRGB color of `image` under `point` (in points at `pixels_per_point`); `None` outside it
|
||||
fn pixel_at(image: &egui::ColorImage, point: Pos2, pixels_per_point: f32) -> Option<[u8; 3]> {
|
||||
let (x, y) = ((point.x * pixels_per_point).floor(), (point.y * pixels_per_point).floor());
|
||||
let [width, height] = image.size;
|
||||
if !(x >= 0.0 && y >= 0.0 && (x as usize) < width && (y as usize) < height) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let color = image.pixels.get(y as usize * width + x as usize)?;
|
||||
Some([color.r(), color.g(), color.b()])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_pixel_under_the_point_is_sampled_at_the_display_scale() {
|
||||
let mut image = egui::ColorImage::filled([4, 2], egui::Color32::BLACK);
|
||||
image.pixels[4 + 3] = egui::Color32::from_rgb(10, 20, 30);
|
||||
|
||||
assert_eq!(pixel_at(&image, egui::pos2(1.6, 0.6), 2.0), Some([10, 20, 30]));
|
||||
assert_eq!(pixel_at(&image, egui::pos2(0.2, 0.2), 2.0), Some([0, 0, 0]));
|
||||
for outside in [egui::pos2(-0.1, 0.0), egui::pos2(2.0, 0.0), egui::pos2(0.0, 1.0), egui::pos2(f32::NAN, 0.0)] {
|
||||
assert_eq!(pixel_at(&image, outside, 2.0), None, "{outside:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -329,8 +329,8 @@ pub struct UiState {
|
||||
/// How the 3D view shows symmetry
|
||||
#[serde(default)]
|
||||
pub symmetry: crate::symmetry::SymmetryDisplay,
|
||||
/// What bake mode's 3D view draws besides the low poly (the Baking Visualization panel)
|
||||
#[serde(default)]
|
||||
/// The Baking Visualization panel's settings, under a key of their own since the reference defaults: older saved ones start over
|
||||
#[serde(default, rename = "baking_visualization")]
|
||||
pub bake_visualization: crate::bake_mode::BakeVisualizationToggles,
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
_ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => Some(crate::gpu::AuxView::QuickMask),
|
||||
ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)),
|
||||
ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)),
|
||||
_ if mode == crate::state::Mode::Baking && app.ui.bake_visualization.bent_normal_shown() => Some(crate::gpu::AuxView::MeshMap(BakedMap::BentNormal)),
|
||||
_ => None,
|
||||
};
|
||||
let mut sync = PendingSync(Some(aux_view));
|
||||
@@ -316,7 +317,7 @@ fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] {
|
||||
fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame, sync: &mut PendingSync) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let bake = bake_visualization(app);
|
||||
frame.shade.bake = bake.filter(|_| frame.kind == ViewKind::Scene);
|
||||
frame.shade.bake = bake;
|
||||
let scene = match (sync.0.take(), app.gpu.as_mut()) {
|
||||
(Some(aux), Some(gpu_link)) => {
|
||||
let sync_start_ms = crate::now_ms();
|
||||
@@ -392,28 +393,38 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) {
|
||||
}
|
||||
});
|
||||
|
||||
// Bake mode lights the project mesh with the neutral material unless the painted one is asked for
|
||||
let baking = app.ui.mode == crate::state::Mode::Baking;
|
||||
let neutral = baking && app.session.view == ViewMode::Material && app.ui.bake_visualization.neutral_shown;
|
||||
let label = match app.session.view {
|
||||
_ if neutral => "Neutral Material".to_owned(),
|
||||
ViewMode::MeshMap(map) => crate::i18n::baked_map_label(map).to_owned(),
|
||||
_ => app.session.view.label(),
|
||||
};
|
||||
let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default();
|
||||
egui::ComboBox::from_id_salt(format!("{id}_mode")).width(VIEW_PICKER_WIDTH).selected_text(tr(&label)).show_ui(&mut child, |ui| {
|
||||
if ui.selectable_label(app.session.view == ViewMode::Material, tr("Material")).clicked() {
|
||||
if baking && ui.selectable_label(neutral, tr("Neutral Material")).clicked() {
|
||||
app.ui.bake_visualization.neutral_shown = true;
|
||||
app.run("viewport.view", json!({"mode": "material"}));
|
||||
}
|
||||
if ui.selectable_label(app.session.view == ViewMode::Material && !neutral, tr("Material")).clicked() {
|
||||
// Only bake mode's pick turns the neutral material off; painting mode's Material leaves bake mode's choice alone
|
||||
app.ui.bake_visualization.neutral_shown &= !baking;
|
||||
app.run("viewport.view", json!({"mode": "material"}));
|
||||
}
|
||||
ui.separator();
|
||||
if baking {
|
||||
mesh_map_entries(app, ui);
|
||||
return;
|
||||
}
|
||||
|
||||
for channel in channels {
|
||||
if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel.label())).clicked() {
|
||||
app.run("viewport.view", json!({"mode": channel.id()}));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
for map in BakedMap::ALL {
|
||||
let map_label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]);
|
||||
if ui.selectable_label(app.session.view == ViewMode::MeshMap(map), map_label).clicked() {
|
||||
app.run("viewport.view", json!({"mode": format!("map:{}", map.id())}));
|
||||
}
|
||||
}
|
||||
mesh_map_entries(app, ui);
|
||||
ui.separator();
|
||||
if ui.selectable_label(app.session.view == ViewMode::UvChecker, tr("UV checker")).clicked() {
|
||||
app.run("viewport.view", json!({"mode": "uvChecker"}));
|
||||
@@ -421,6 +432,16 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The view picker's entries that show one baked mesh map
|
||||
fn mesh_map_entries(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
for map in BakedMap::ALL {
|
||||
let map_label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]);
|
||||
if ui.selectable_label(app.session.view == ViewMode::MeshMap(map), map_label).clicked() {
|
||||
app.run("viewport.view", json!({"mode": format!("map:{}", map.id())}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn axis_gizmo(ui: &Ui, rect: Rect, app: &TextureCraftApp, uv: bool) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let o = pos2(rect.left() + 28.0, rect.bottom() - 28.0);
|
||||
@@ -781,7 +802,7 @@ fn bake_visualization(app: &TextureCraftApp) -> Option<texturecraft_render::Bake
|
||||
return None;
|
||||
}
|
||||
|
||||
app.ui.bake_visualization.visualization(app.session.ts())
|
||||
Some(app.ui.bake_visualization.visualization(app.session.ts()))
|
||||
}
|
||||
|
||||
/// What a drag on the selected decal's frame does.
|
||||
@@ -2094,7 +2115,7 @@ mod tests {
|
||||
let app = harness.state_mut();
|
||||
app.ui.mode = crate::state::Mode::Baking;
|
||||
let before = bake_visualization(app).unwrap();
|
||||
assert!(before.high_poly && before.cage);
|
||||
assert!(before.high_poly.shown && before.cage_shown());
|
||||
|
||||
app.start_bake(vec![0]);
|
||||
|
||||
|
||||
@@ -506,3 +506,63 @@ fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_view_menu_picks_the_neutral_or_the_painted_material_in_bake_mode() {
|
||||
let mut harness = harness(None);
|
||||
assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode starts on the neutral material");
|
||||
harness.get_by_value("Neutral Material").click();
|
||||
harness.run_steps(3);
|
||||
assert!(harness.query_by_label("UV checker").is_none(), "bake mode lists lighting and mesh maps only");
|
||||
harness.get_by_label("Material").click();
|
||||
harness.run_steps(3);
|
||||
assert!(!harness.state().ui.bake_visualization.neutral_shown);
|
||||
harness.get_by_value("Material");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_baking_visualization_panel_opens_like_the_reference_at_first_launch() {
|
||||
let harness = harness(None);
|
||||
for shown in ["Show for Selected Texture Set Only", "Mesh", "Matching Error", "Cage Surface", "Cage Wireframe Opacity"] {
|
||||
harness.get_by_label(shown);
|
||||
}
|
||||
for closed in ["Missing Seams on Hard Edges", "Project Mesh", "Roughness"] {
|
||||
assert!(harness.query_by_label(closed).is_none(), "{closed} sits in a section that starts closed");
|
||||
}
|
||||
assert!(harness.state().ui.bake_visualization.missing_seams.shown, "missing seams are ticked in every reference capture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_eye_greys_the_baking_meshes_and_holds_the_project_mesh() {
|
||||
let mut harness = harness(None);
|
||||
assert!(!harness.get_by_label("Mesh").accesskit_node().is_disabled(), "the eye starts off");
|
||||
harness.get_by_label("Hide Baking Meshes").click();
|
||||
harness.run_steps(3);
|
||||
|
||||
for greyed in ["Mesh", "Matching Error", "Cage Surface", "Cage Wireframe Opacity"] {
|
||||
assert!(harness.get_by_label(greyed).accesskit_node().is_disabled(), "{greyed} is greyed");
|
||||
}
|
||||
assert!(harness.state().ui.bake_visualization.project_mesh.shown);
|
||||
// The header, not its "Reset Project Mesh (LP)" button further right
|
||||
let header = harness.get_all_by_label_contains("Project Mesh (LP)").min_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap();
|
||||
header.click();
|
||||
harness.run_steps(3);
|
||||
assert!(harness.get_by_label("Project Mesh").accesskit_node().is_disabled(), "the project mesh stays on");
|
||||
assert!(!harness.get_by_label("Roughness").accesskit_node().is_disabled(), "the neutral material stays editable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_material_while_painting_keeps_bake_modes_neutral_material() {
|
||||
let mut harness = harness(None);
|
||||
harness.state_mut().ui.mode = Mode::Painting;
|
||||
harness.run_steps(3);
|
||||
// Painting mode shows the 3D and 2D views, each with a view menu; the 3D view's comes first
|
||||
harness.get_all_by_value("Material").next().unwrap().click();
|
||||
harness.run_steps(3);
|
||||
// The menu entry, not the dropdown that shows the same word
|
||||
let entry = harness.get_all_by_label("Material").find(|node| node.accesskit_node().role() != Role::ComboBox).unwrap();
|
||||
entry.click();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material");
|
||||
}
|
||||
Reference in new issue
Block a user