Merge upstream/main into fix/save-over-load-limit

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76andClaude Sonnet 5.5 committed 2026-11-05 02:52:41 +01:00
commit dcb048b5b4
158 files changed
+7913 -4437

No files matched your search

+1
View File
@@ -43,3 +43,4 @@ jobs:
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
+19
View File
@@ -0,0 +1,19 @@
name: SonarCloud
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
sonarcloud:
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
secrets: inherit
+8 -1
View File
@@ -58,6 +58,13 @@ replace it without touching the engine.
## 3. Golden rules
### Never name the reference product (absolutely essential)
- The repository never names the commercial product TextureCraft is modeled on, nor its vendor,
in code, comments, docs, commit messages, test names, file names or UI text. Say "the reference
app", "the professional model-painter workflow" or describe the feature itself.
- Notes that name it may live only in the gitignored `plan/` folder or in this `AGENTS.md` file
### Assets, icons and images (absolutely essential)
- **Never use any icon, image, logo, texture, material, brush, environment, font or other asset
@@ -126,7 +133,7 @@ panic. The shared standard is `../craftrules/standards/never-crash.md`.
Benchmark heavy paths (bake, composite, export) in release and record numbers in the dev log.
8. **Cross-app formats are shared conventions.** MaterialCraft's `.mcmat` portable materials are
read here with our own code (`formats::mcmat`): keep the manifest fields, usage ids and
mesh-map identifiers (`BakedMap::interop_id`) in step with MaterialCraft's
mesh-map identifiers (`BakedMap::id`) in step with MaterialCraft's
`docs/control-protocol.md`, and never depend on MaterialCraft's crates; talk to it through
`materialcraft-cli`.
9. **Verify UI changes visually.** Launch with `--control <port>` and call `ui.screenshot` (whole
Generated
+16 -15
View File
@@ -3812,7 +3812,7 @@ dependencies = [
[[package]]
name = "texturecraft"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"eframe",
"egui",
@@ -3831,7 +3831,7 @@ dependencies = [
[[package]]
name = "texturecraft-automation"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"base64 0.22.1",
"cap-std",
@@ -3852,8 +3852,9 @@ dependencies = [
[[package]]
name = "texturecraft-bake"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"bytemuck",
"rayon",
"texturecraft-core",
"texturecraft-geom",
@@ -3863,7 +3864,7 @@ dependencies = [
[[package]]
name = "texturecraft-cli"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"image",
"serde_json",
@@ -3875,7 +3876,7 @@ dependencies = [
[[package]]
name = "texturecraft-compose"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"half",
"rayon",
@@ -3886,7 +3887,7 @@ dependencies = [
[[package]]
name = "texturecraft-core"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"serde",
"serde_json",
@@ -3895,7 +3896,7 @@ dependencies = [
[[package]]
name = "texturecraft-engine"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"epaint_default_fonts",
"image",
@@ -3915,7 +3916,7 @@ dependencies = [
[[package]]
name = "texturecraft-formats"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"base64 0.22.1",
"exr",
@@ -3939,7 +3940,7 @@ dependencies = [
[[package]]
name = "texturecraft-geom"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"glam 0.30.10",
"mikktspace",
@@ -3950,7 +3951,7 @@ dependencies = [
[[package]]
name = "texturecraft-paint"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"epaint_default_fonts",
"harfrust",
@@ -3965,7 +3966,7 @@ dependencies = [
[[package]]
name = "texturecraft-render"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"bytemuck",
"half",
@@ -3984,11 +3985,11 @@ dependencies = [
[[package]]
name = "texturecraft-texel"
version = "0.3.0"
version = "0.3.1"
[[package]]
name = "texturecraft-ui-egui"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"base64 0.22.1",
"craft-ui",
@@ -4017,7 +4018,7 @@ dependencies = [
[[package]]
name = "texturecraft-web"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"eframe",
"js-sys",
@@ -5281,7 +5282,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"serde_json",
]
+1 -1
View File
@@ -5,7 +5,7 @@ exclude = ["vendor"]
default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "xtask"]
[workspace.package]
version = "0.3.0"
version = "0.3.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
+8 -5
View File
@@ -4,7 +4,7 @@ TextureCraft aims for 1:1 parity with Adobe Substance 3D Painter's texturing wor
performance, a smaller footprint, every feature drivable by agents (MCP, CLI, control channel), and
builds for Windows, macOS, Linux, FreeBSD and the web.
## Honest parity estimate (2026-11-02)
## Honest parity estimate (2026-11-04)
Weighted by how much of a professional's daily work each area carries. "Done" counts what works
end to end today (engine + UI + automation + tests), not what is planned.
@@ -16,13 +16,16 @@ end to end today (engine + UI + automation + tests), not what is planned.
| Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog |
| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) |
| Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's |
| Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **skew correction** (`bake.skew.set`, painted in the 2D view with `bake.skew.paint` and saved in the project: a greyscale map over the atlas that turns the transfer rays onto the base normal, with hard-edge protection), **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; **Auto-rebake** (`bake.autoRebake`: one map bakes itself again in the background when its bake settings, the low poly, the high polys or the skew map change); **mesh maps from images** (baked elsewhere or edited) dropped on a slot; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — |
| Baking | 10 | 90% | All ten mesh-map bakers; low-poly and high-to-low baking with CPU/GPU tracing; mesh-name matching, backface filtering, custom and distance-based cages, frontal/rear distances and average normals; undoable 2D cage/skew painting saved per texture set; rectangular output, antialiasing, dilation/diffusion, ID sources, ray filters, AO attenuation/ground plane, curvature controls and map normalization; per-texture-set selection, progress/cancel and mesh-map import | Residual Painter map differences; reference validation for Height, Bent Normal and Opacity and across additional assets; 3D cage-editing overlay |
| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing |
| Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — |
| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted; the chosen space is recorded in the file as an ICC profile in PNG, JPEG, TIFF and WebP and as chromaticities in EXR), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `<UDIM>` aware), OBJ with MTL and maps, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) |
| UI and UX | 8 | 97% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **History** panel that jumps to any step (back or forward), a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations |
| Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish |
| **Total** | **100** | **≈ 94%** | | |
| **Total** | **100** | **≈ 94%** | Weighted workflow-completion estimate | |
Baking’s 90% estimates workflow completion: all ten map types and exposed settings have implementation
paths, with the remaining work listed above. Pixel-level equivalence with Painter remains unverified.
Beyond the reference app: every command is available to agents through MCP, the CLI and the app's
control channel (MCP workspace tools cover every file action: projects, meshes, high polys and
@@ -38,13 +41,13 @@ parallel on separate crates:
| M1 Layer stack depth | Done | 0 h |
| M2 Tools | Pen tilt, and pen pressure on Linux, macOS and desktop browsers, once the windowing layer reports them | 0.5 h |
| M3 Assets | Done | 0 h |
| M4 Baking | Done | 0 h |
| M4 Baking | Validate outputs across reference assets, refine remaining map differences and add 3D cage editing | TBD |
| M5 Viewport | Hardware ray tracing: wgpu's ray queries are experimental and need an `unsafe` opt-in, which the workspace forbids (owner decision) | 1.5 h |
| M6 Shader | Done | 0 h |
| M7 Formats | Done | 0 h |
| M8 UX | Native review of translations | 1 h |
| M9 Release | The twelve signing secrets and the Default runner group (org admin); first signed release run on every platform (v0.1.0); web deployment; Flathub submission | 3 h |
| **Total** | | **≈ 6 h** |
| **Total** | | **≈ 6 h + baking TBD** |
## Current focus
+1
View File
@@ -12,5 +12,6 @@ workspace = true
texturecraft-core = { workspace = true }
texturecraft-geom = { workspace = true }
texturecraft-texel = { workspace = true }
bytemuck = { workspace = true, features = ["extern_crate_alloc"] }
rayon = { workspace = true }
thiserror = { workspace = true }
+34 -19
View File
@@ -1,26 +1,41 @@
# texturecraft-bake
Mesh-map baker: `bake(&BakeRequest, &Progress) -> BakeOutput` turns one texture set's UV layout into float maps (0..1, rows top → bottom), supersampled, padded and deterministic. The supersamples are processed in batches: their high-poly transfer rays, then the secondary rays of ambient occlusion, bent normals and thickness go to a `rays::Tracer`, then all requested maps are evaluated per sample (rayon over rows).
Clean-room mesh-map baking from low-poly UVs and optional high-poly meshes. Persisted settings live in `texturecraft-core`; localized controls live in `texturecraft-ui-egui`. Types have individual files, with singular module folders.
The rays run on the CPU (`rays::CpuTracer`, the oracle) or, through `bake_on(&BakeRequest, &Progress, &dyn Tracer)`, on a GPU tracer (the render crate's `gpu_bake::GpuBaker`, wgpu compute shaders on the path tracer's BVH traversal). The GPU receives the same rays and per-sample rotations and casts the same secondary-ray directions, so both agree up to float rounding; when the tracer fails (no adapter, a mesh too large for it, a lost device) `bake_on` bakes again on the CPU. `BakeOutput::tracer` says where the rays ran.
`bake(&BakeRequest, &Progress)` runs the CPU oracle. `bake_on` accepts a `tracing::Tracer` such as the render crate's GPU baker, and retries on the CPU if that tracer fails. Both receive identical transfer rays and secondary-ray samples. Output is deterministic, floating point, and stored in rows from top to bottom. Cancellation is checked between bounded batches and before returning the result.
With a high poly (`BakeRequest::high`, every high-definition mesh appended into one), each low-poly sample casts one ray from the cage (`BakeRequest::cage`, same triangles as the low poly) or from `max_frontal` in front of the surface back through it to `max_rear` behind (both relative to the bounding-box diagonal), along normals averaged over hard edges when `average_normals` is on. With `BakeMatch::ByMeshName`, a low-poly part only sees high-poly parts of the same name once `low_suffix` / `high_suffix` are removed (`wheel_low` ↔ `wheel_high`, case-insensitive). Every map but position and world-space direction then reads the high-poly surface that ray found (AO, thickness and bent normals cast against the high poly).
## Projection and common settings
Ambient occlusion, thickness and bent normals each have their own `RaySettings`: ray count, max distance (relative to the bounding-box diagonal), spread angle (the full cone around the normal; 180° = the hemisphere) and distribution (cosine-weighted or uniform over the cone). Ambient occlusion can ignore back faces and limit occluders to parts of the same mesh name (`SelfOcclusion::SameMeshName`); bent normals follow those occluder rules and share the AO rays when their settings match.
- Independent output width and height, antialiasing, per-UV-tile dilation, and optional background diffusion
- High-to-low matching: Always by default, or By Mesh Name using the configured low/high suffixes
- Transfer-ray backface filtering, distance-based or custom-file cages, frontal/rear distances, and averaged normals
- Relative distances use the longest bounding-box extent; absolute distances use imported mesh units
- Painted cage values multiply the frontal distance; painted skew values blend toward mesh or face normals, with optional hard-edge protection
| Map | Meaning | Range |
| --- | --- | --- |
| Ambient occlusion | How open the surface is (rays over the cone, distance falloff) | 0 occluded … 1 open |
| Bent normals | Mean unoccluded direction of the bent-normal rays, world space | packed ·0.5+0.5 |
| Thickness | Mean distance through the mesh along inward rays, relative to the max distance | 0 thin … 1 thick |
| Curvature | Mean curvature of the position-welded mesh, or (`curvature_from_normal`) the divergence of the baked normal map over `curvature_radius` texels (0: by resolution) | 0 concave … 0.5 flat … 1 convex |
| Normal | Tangent-space normal from the high poly (OpenGL, +Y up); flat without one | packed ·0.5+0.5 |
| Height | High-poly offset along the ray, scaled by frontal + rear distance | 0 rear … 0.5 surface … 1 front |
| World normal | Shading normal in world space | packed ·0.5+0.5 |
| Position | Position in the low poly's bounding box (per axis) or bounding sphere (`position_mode`) | 0 … 1 |
| ID | A distinct hue per mesh part (submesh) | RGB 0 … 1 |
| Opacity | 1 where the high poly was found (times its vertex and base color alpha), 0 where the ray missed | 0 … 1 |
| Color map | The high poly's vertex colors times its materials' base color (`HighPoly::base_color`: factor × texture at the hit UV, bilinear in linear light), sRGB-encoded like a base color texture | RGB 0 … 1 |
| World space direction | Facing ratio towards `direction`: signed (0.5 perpendicular) or positive (`direction_mode`) | 0 away … 1 facing |
`BakePaintMap` contains pixel data only. Cage and skew settings remain in their respective model containers. The engine stores paint maps per texture set in document snapshots and project files. The shared 2D brush supports undo, redo, reset, and UV-layout changes.
Uncovered texels beyond the padding get `BakedMap::neutral` values. Benchmarks (2K, the 7 default maps at 64 rays): `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench` (CPU, per-map breakdown) and `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture gpu_bake_speed` (CPU vs GPU).
## Map settings
| Map | Implemented behavior |
| --- | --- |
| Normal | Tangent-space high-poly normal, internally OpenGL; flat without a high-poly transfer |
| World Normal | World-space shading normal |
| ID | Vertex Color, Material Color, Mesh ID, Submesh ID, or File ID; Hue Shift, Random, and Grayscale generation |
| Ambient Occlusion | Independent ray count, distance interval, units, cone and distribution; backface and self-occlusion modes; None, Linear or Smooth attenuation; optional ground plane |
| Bent Normal | Independent occlusion settings and mean visible direction, encoded in world space |
| Thickness | Inward ray distances with self-occlusion filtering; raw, ray-distance or per-UV-tile min/max normalization |
| Curvature | Mesh-ray curvature with radius, ray count, self-intersection and automatic/manual tonemapping; normal-map curvature with detail strength and corresponding UV-edge seam blending |
| Position | All axes or a selected axis; scene or material bounds; box, uniform sphere-style or raw coordinates |
| Height | Signed high-poly displacement with low-mesh, min/max, ray-distance or manual normalization |
| Opacity | High-poly hit coverage multiplied by source vertex/material/texture alpha |
ID Material Color reads the material factor independently of textures and vertex colors. A source without material colors uses neutral gray (0.6). Generated IDs are deterministic. Normal maps are stored in OpenGL convention; display/export apply the project's normal format.
All dropdowns use enums. `BakedMap::id()` and `BakedMap::parse()` provide the shared MaterialCraft mesh-map identifiers. `bake.settings` accepts the complete nested model. No legacy Color or World Orientation map migration is provided.
## Validation and limits
Regression tests cover projection, matching, ray filters, normalization, rectangular maps, painting, persistence, and CPU/GPU agreement. The supplied 2048² high-to-low reference is evaluated separately, outside the repository, on UV-covered pixels. Numerical differences remain, especially in curvature and occlusion; exact Painter parity is not claimed. Painted cage control currently uses the 2D UV brush; it does not provide a 3D cage-editing overlay.
CPU benchmark: `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench`.
GPU comparison: `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture gpu_bake_speed`.
+9
View File
@@ -0,0 +1,9 @@
#[derive(Debug, thiserror::Error)]
pub enum BakeError {
#[error("bake cancelled")]
Cancelled,
#[error("invalid bake request: {0}")]
Invalid(String),
#[error("ray tracer: {0}")]
Tracer(String),
}
+11
View File
@@ -0,0 +1,11 @@
use std::collections::BTreeMap;
use texturecraft_core::BakedMap;
#[derive(Clone, Debug, PartialEq)]
/// Row-major maps, with BakedMap::components() floats per texel
pub struct BakeOutput {
pub resolution: u32,
pub height: u32,
pub maps: BTreeMap<BakedMap, Vec<f32>>,
pub tracer: String,
}
+130
View File
@@ -0,0 +1,130 @@
use crate::{BakeError, MAX_TEXELS};
use texturecraft_geom::glam::Vec2;
pub const MAX_DABS: usize = 200_000;
// Bound total work across all dabs before changing any pixels
pub const MAX_PAINT_TEXELS: u64 = 1 << 26;
#[derive(Clone, Debug, PartialEq)]
pub struct BakePaintMap {
pub width: u32,
pub height: u32,
/// Values in 0..=1 over the texture set UV atlas
pub values: Vec<f32>,
}
impl BakePaintMap {
pub fn constant(value: f32) -> BakePaintMap {
BakePaintMap { width: 1, height: 1, values: vec![value] }
}
pub fn validate(&self) -> Result<(), BakeError> {
let invalid = |m: &str| Err(BakeError::Invalid(m.into()));
let texels = u64::from(self.width) * u64::from(self.height);
if self.width == 0 || self.height == 0 || texels > MAX_TEXELS || self.values.len() as u64 != texels {
return invalid("the bake paint map's size doesn't match its values");
}
if self.values.iter().any(|v| !v.is_finite()) {
return invalid("the bake paint map has a value that is not a finite number");
}
Ok(())
}
pub fn resized(&self, width: u32, height: u32) -> Result<BakePaintMap, BakeError> {
let texels = u64::from(width) * u64::from(height);
if width == 0 || height == 0 || texels > MAX_TEXELS {
return Err(BakeError::Invalid(format!("a {width} × {height} bake paint map is outside the supported size")));
}
let mut values = Vec::with_capacity(texels as usize);
for y in 0..height {
let v = (y as f32 + 0.5) / height as f32;
for x in 0..width {
values.push(self.sample(Vec2::new((x as f32 + 0.5) / width as f32, v)));
}
}
Ok(BakePaintMap { width, height, values })
}
pub fn paint(&mut self, points: &[Vec2], radius: f32, value: f32, hardness: f32, strength: f32) -> Result<(), BakeError> {
let ok = radius.is_finite() && radius > 0.0 && value.is_finite() && hardness.is_finite() && strength.is_finite();
if !ok || points.iter().any(|p| !p.is_finite()) {
return Err(BakeError::Invalid("the bake brush needs finite numbers and a radius above 0".into()));
}
self.validate()?;
let (value, hardness, strength) = (value.clamp(0.0, 1.0), hardness.clamp(0.0, 0.999), strength.clamp(0.0, 1.0));
let step = (radius * 0.25).max(1e-5);
let mut dabs = Vec::new();
for (i, p) in points.iter().enumerate() {
match i.checked_sub(1).and_then(|j| points.get(j)) {
Some(prev) => {
let n = ((*p - *prev).length() / step).ceil().clamp(1.0, MAX_DABS as f32) as usize;
dabs.extend((1..=n).map(|k| *prev + (*p - *prev) * (k as f32 / n as f32)));
}
None => dabs.push(*p),
}
if dabs.len() > MAX_DABS {
return Err(BakeError::Invalid(format!("a bake stroke is limited to {MAX_DABS} dabs; use a larger radius or fewer points")));
}
}
let (w, h) = (self.width as usize, self.height as usize);
let span = |c: Vec2| {
let x0 = (((c.x - radius) * w as f32).floor().max(0.0)) as usize;
let x1 = (((c.x + radius) * w as f32).ceil().min(w as f32)).max(0.0) as usize;
let y0 = (((c.y - radius) * h as f32).floor().max(0.0)) as usize;
let y1 = (((c.y + radius) * h as f32).ceil().min(h as f32)).max(0.0) as usize;
(x0, x1, y0, y1)
};
let work: u64 = dabs
.iter()
.map(|c| {
let (x0, x1, y0, y1) = span(*c);
x1.saturating_sub(x0) as u64 * y1.saturating_sub(y0) as u64
})
.fold(0, u64::saturating_add);
if work > MAX_PAINT_TEXELS {
return Err(BakeError::Invalid(format!(
"this stroke would visit {work} texels (limit {MAX_PAINT_TEXELS}); use a smaller radius, a smaller map or a shorter stroke"
)));
}
for c in dabs {
let (x0, x1, y0, y1) = span(c);
for y in y0..y1 {
let dv = (y as f32 + 0.5) / h as f32 - c.y;
for x in x0..x1 {
let du = (x as f32 + 0.5) / w as f32 - c.x;
let t = (du * du + dv * dv).sqrt() / radius;
if t >= 1.0 {
continue;
}
let fall = if t <= hardness {
1.0
} else {
let k = (1.0 - t) / (1.0 - hardness);
k * k * (3.0 - 2.0 * k)
};
if let Some(v) = self.values.get_mut(y * w + x) {
*v += (value - *v) * fall * strength;
}
}
}
}
Ok(())
}
pub fn sample(&self, uv: Vec2) -> f32 {
let (w, h) = (self.width.max(1) as usize, self.height.max(1) as usize);
if !uv.is_finite() {
return 0.0;
}
let x = (uv.x.clamp(0.0, 1.0) * w as f32 - 0.5).clamp(0.0, w as f32 - 1.0);
let y = (uv.y.clamp(0.0, 1.0) * h as f32 - 0.5).clamp(0.0, h as f32 - 1.0);
let (x0, y0) = (x.floor() as usize, y.floor() as usize);
let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
let (fx, fy) = (x - x0 as f32, y - y0 as f32);
let v = |xx: usize, yy: usize| self.values.get(yy * w + xx).copied().unwrap_or(0.0);
let top = v(x0, y0) * (1.0 - fx) + v(x1, y0) * fx;
let bottom = v(x0, y1) * (1.0 - fx) + v(x1, y1) * fx;
(top * (1.0 - fy) + bottom * fy).clamp(0.0, 1.0)
}
}
+19
View File
@@ -0,0 +1,19 @@
use crate::{BakePaintMap, HighPoly};
use std::sync::Arc;
use texturecraft_core::BakeSettings;
use texturecraft_geom::{BaseColor, Bvh, Mesh};
#[derive(Clone, Copy, Debug)]
pub struct BakeRequest<'a> {
pub mesh: &'a Mesh,
pub bvh: &'a Bvh,
pub material: usize,
pub low_base_color: &'a [Option<Arc<BaseColor>>],
pub settings: &'a BakeSettings,
pub high: Option<HighPoly<'a>>,
pub cage: Option<&'a Mesh>,
pub skew: Option<&'a BakePaintMap>,
pub cage_paint: Option<&'a BakePaintMap>,
/// UV atlas grid; each tile uses the configured output resolution
pub tiles: (u32, u32),
}
+10
View File
@@ -0,0 +1,10 @@
use std::sync::Arc;
use texturecraft_geom::{BaseColor, Bvh, Mesh};
#[derive(Clone, Copy, Debug)]
pub struct HighPoly<'a> {
pub file_ids: &'a [u32],
pub mesh: &'a Mesh,
pub bvh: &'a Bvh,
pub base_color: &'a [Option<Arc<BaseColor>>],
}
+283 -263
View File
@@ -1,374 +1,394 @@
//! # texturecraft-bake
//!
//! Mesh-map baking. [`bake`] rasterizes one texture set's UV layout with a supersampled
//! [`UvGBuffer`] and works through it in batches of samples: the high-poly transfer rays, then
//! the secondary rays of ambient occlusion, bent normals and thickness (each with its own
//! [`texturecraft_core::RaySettings`]) go to a [`rays::Tracer`], then every requested
//! [`BakedMap`] is evaluated per sample (rayon over rows), box-downsampled, and the UV islands
//! are padded with [`DilationMap`]. The rays run on the CPU ([`rays::CpuTracer`], the oracle) or
//! on a GPU tracer passed to [`bake_on`]. With a high poly, every map but position and
//! world-space direction reads the high-poly surface found along the cage / frontal-rear ray;
//! the color map multiplies its vertex colors by its materials' [`BaseColor`]s. Sampling is
//! deterministic, so the same request always gives the same pixels.
//! Deterministic mesh-map baking with bounded batches and CPU fallback
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod maps;
pub mod rays;
mod bake_error;
mod bake_output;
mod bake_request;
mod high_poly;
mod progress;
pub use bake_error::BakeError;
pub use bake_output::BakeOutput;
pub use bake_request::BakeRequest;
pub use high_poly::HighPoly;
pub use progress::Progress;
mod map;
mod skew;
#[cfg(test)]
mod tests;
pub mod tracing;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed};
use std::sync::atomic::Ordering::Relaxed;
use rayon::prelude::*;
use texturecraft_core::{BakeSettings, BakedMap};
use texturecraft_core::{BakedMap, CurvatureMethod};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{BaseColor, Bvh, Mesh, NO_TRI, UvGBuffer};
use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer};
use texturecraft_texel::DilationMap;
use crate::rays::{CpuTracer, RayScene, Tracer};
pub use crate::skew::SkewMap;
mod bake_paint_map;
use crate::tracing::{CpuTracer, RayScene, Tracer};
pub use bake_paint_map::BakePaintMap;
/// Largest accepted output resolution (per axis).
pub const MAX_RESOLUTION: u32 = 8192;
/// Largest accepted ray count per texel (AO, thickness).
pub const MAX_RAYS: u32 = 4096;
/// Largest accepted output (texels over every UV tile).
pub const MAX_TEXELS: u64 = 1 << 27;
/// Supersampled texels rasterized at once: bounds the G-buffer at ~200 MB for any resolution × AA.
// Bound each supersampled G-buffer to roughly 200 MB
const STRIP_TEXELS: usize = 1 << 24;
/// Supersamples ray-cast per batch: bounds the per-sample buffers (~40 MB) and a GPU submission.
const BATCH: usize = 1 << 18;
// Curvature batches stay small so progress and cancellation remain responsive
const CURVATURE_BATCH: usize = 1 << 15;
/// Shared progress / cancellation flag of a running bake.
#[derive(Debug, Default)]
pub struct Progress {
/// Basis points, 0..=10_000 (all requested maps done).
pub done: AtomicU32,
pub cancel: AtomicBool,
}
fn validate(request: &BakeRequest) -> Result<(), BakeError> {
let settings = request.settings;
let invalid = |message: String| Err(BakeError::Invalid(message));
let (resolution, resolution_height) = settings.common.output_size();
impl Progress {
pub fn new() -> Self {
Self::default()
let (columns, rows) = request.tiles;
let width = u64::from(resolution) * u64::from(columns);
let height = u64::from(resolution_height) * u64::from(rows);
if columns == 0 || rows == 0 || width.saturating_mul(height) > MAX_TEXELS {
return invalid(format!("{columns} × {rows} UV tiles at {} exceed {MAX_TEXELS} texels", resolution));
}
/// Completed fraction, 0..=1.
pub fn fraction(&self) -> f32 {
self.done.load(Relaxed).min(10_000) as f32 / 10_000.0
}
/// Ask the bake to stop; it returns [`BakeError::Cancelled`] at the next row.
pub fn cancel(&self) {
self.cancel.store(true, Relaxed);
}
}
/// A high-poly source mesh (all high-definition meshes appended into one).
#[derive(Clone, Copy, Debug)]
pub struct HighPoly<'a> {
pub mesh: &'a Mesh,
pub bvh: &'a Bvh,
/// Base color per material of `mesh` (missing or None: white).
pub base_color: &'a [Option<Arc<BaseColor>>],
}
/// One texture set to bake.
#[derive(Clone, Copy, Debug)]
pub struct BakeRequest<'a> {
pub mesh: &'a Mesh,
/// BVH of the whole low-poly mesh: every material occludes.
pub bvh: &'a Bvh,
pub material: usize,
pub settings: &'a BakeSettings,
pub high: Option<HighPoly<'a>>,
/// Cage: the low poly inflated (same triangles); transfer rays start on it.
pub cage: Option<&'a Mesh>,
/// Skew correction of the high-poly transfer rays (see [`SkewMap`]); ignored with a cage mesh.
pub skew: Option<&'a SkewMap>,
/// UV tile grid (columns, rows) of the texture set: the maps are `settings.resolution` per
/// tile, (1, 1) for a classic set. The mesh's UVs are in atlas space (0..1 over the grid).
pub tiles: (u32, u32),
}
/// Baked maps: row-major `resolution × height`, `BakedMap::components()` floats per texel,
/// rows top → bottom (y = v·H, as [`UvGBuffer`]).
#[derive(Clone, Debug, PartialEq)]
pub struct BakeOutput {
/// Width in texels.
pub resolution: u32,
pub height: u32,
pub maps: BTreeMap<BakedMap, Vec<f32>>,
/// Where the rays ran ([`Tracer::name`]).
pub tracer: String,
}
#[derive(Debug, thiserror::Error)]
pub enum BakeError {
#[error("bake cancelled")]
Cancelled,
#[error("invalid bake request: {0}")]
Invalid(String),
/// The ray tracer failed ([`bake_on`] then bakes on the CPU).
#[error("ray tracer: {0}")]
Tracer(String),
}
fn validate(req: &BakeRequest) -> Result<(), BakeError> {
let s = req.settings;
let invalid = |m: String| Err(BakeError::Invalid(m));
if s.resolution == 0 || s.resolution > MAX_RESOLUTION {
return invalid(format!("resolution {} is not in 1..={MAX_RESOLUTION}", s.resolution));
}
let (cols, rows) = req.tiles;
if cols == 0 || rows == 0 || (s.resolution as u64 * cols as u64) * (s.resolution as u64 * rows as u64) > MAX_TEXELS {
return invalid(format!("{cols} × {rows} UV tiles at {} exceed {MAX_TEXELS} texels", s.resolution));
}
if ![1, 2, 4, 8].contains(&s.antialiasing) {
return invalid(format!("antialiasing {} is not 1, 2, 4 or 8", s.antialiasing));
}
for (map, r) in [(BakedMap::AmbientOcclusion, &s.ao), (BakedMap::Thickness, &s.thickness), (BakedMap::BentNormal, &s.bent_normal)] {
if !s.maps.contains(&map) {
for (map, ray_settings) in [
(BakedMap::AmbientOcclusion, &settings.maps.ao.parameters.rays),
(BakedMap::Thickness, &settings.maps.thickness.parameters.rays),
(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays),
] {
if !settings.maps.is_enabled(map) {
continue;
}
if r.rays == 0 || r.rays > MAX_RAYS {
return invalid(format!("{} ray count {} is not in 1..={MAX_RAYS}", map.label(), r.rays));
if ray_settings.rays == 0 || ray_settings.rays > MAX_RAYS {
return invalid(format!("{} ray count {} is not in 1..={MAX_RAYS}", map.id(), ray_settings.rays));
}
if !(r.max_distance.is_finite() && r.max_distance > 0.0) {
return invalid(format!("{} max distance {} must be positive", map.label(), r.max_distance));
if !(ray_settings.max_distance.is_finite() && ray_settings.max_distance > 0.0) {
return invalid(format!("{} max distance {} must be positive", map.id(), ray_settings.max_distance));
}
if !r.spread.is_finite() {
return invalid(format!("{} spread angle is not finite", map.label()));
if !(ray_settings.min_distance.is_finite() && ray_settings.min_distance >= 0.0 && ray_settings.min_distance <= ray_settings.max_distance) {
return invalid(format!("{} minimum distance must be finite and between zero and its maximum distance", map.id()));
}
if !ray_settings.spread.is_finite() || !(0.0..=180.0).contains(&ray_settings.spread) {
return invalid(format!("{} spread angle is not finite", map.id()));
}
}
if !s.curvature_strength.is_finite() {
return invalid("curvature strength is not finite".into());
if !(settings.cage.max_frontal.is_finite() && settings.cage.max_frontal >= 0.0 && settings.cage.max_rear.is_finite() && settings.cage.max_rear >= 0.0) {
return invalid(format!("frontal/rear distances {}/{} must be finite and ≥ 0", settings.cage.max_frontal, settings.cage.max_rear));
}
if !(s.direction.iter().all(|c| c.is_finite()) && s.direction.iter().any(|c| *c != 0.0)) {
return invalid(format!("direction {:?} must be finite and non-zero", s.direction));
}
if !(s.max_frontal.is_finite() && s.max_frontal >= 0.0 && s.max_rear.is_finite() && s.max_rear >= 0.0) {
return invalid(format!("frontal/rear distances {}/{} must be finite and ≥ 0", s.max_frontal, s.max_rear));
}
req.mesh.validate().map_err(|e| BakeError::Invalid(e.to_string()))?;
if req.material >= req.mesh.materials.len().max(1) {
return invalid(format!("material {} out of range ({} materials)", req.material, req.mesh.materials.len()));
}
if let Some(h) = &req.high {
h.mesh.validate().map_err(|e| BakeError::Invalid(format!("high poly: {e}")))?;
}
if let Some(c) = req.cage {
c.validate().map_err(|e| BakeError::Invalid(format!("cage: {e}")))?;
if c.indices.len() != req.mesh.indices.len() {
return invalid(format!("the cage has {} triangles, the low poly {}", c.triangle_count(), req.mesh.triangle_count()));
let curvature = settings.maps.curvature.parameters;
if settings.maps.curvature.is_enabled {
if curvature.mesh.rays == 0 || curvature.mesh.rays > MAX_RAYS || !curvature.mesh.sampling_radius.is_finite() || curvature.mesh.sampling_radius <= 0.0 {
return invalid("curvature requires a positive finite radius and a supported ray count".into());
}
if !curvature.mesh.value_min.is_finite()
|| !curvature.mesh.value_max.is_finite()
|| (!curvature.mesh.auto_tonemapping && curvature.mesh.value_min >= curvature.mesh.value_max)
{
return invalid("curvature bounds must be finite, with minimum below maximum".into());
}
}
for (name, value) in [
("edge distance", settings.skew.edge_distance),
("edge contrast", settings.skew.edge_contrast),
("curvature details", curvature.normal_map.details),
("seam intensity", curvature.normal_map.seams_intensity),
] {
if !value.is_finite() || !(0.0..=1.0).contains(&value) {
return invalid(format!("{name} must be finite and in 0..=1"));
}
}
if settings.maps.height.is_enabled
&& (!settings.maps.height.parameters.scaling_divisor.is_finite() || settings.maps.height.parameters.scaling_divisor <= 0.0)
{
return invalid("height scaling divisor must be finite and positive".into());
}
if !settings.maps.ao.parameters.ground_plane.offset.is_finite() || settings.maps.ao.parameters.ground_plane.offset < 0.0 {
return invalid("ground plane offset must be finite and nonnegative".into());
}
request.mesh.validate().map_err(|e| BakeError::Invalid(e.to_string()))?;
if request.material >= request.mesh.materials.len().max(1) {
return invalid(format!("material {} out of range ({} materials)", request.material, request.mesh.materials.len()));
}
if let Some(high) = &request.high {
high.mesh.validate().map_err(|e| BakeError::Invalid(format!("high poly: {e}")))?;
}
if let Some(map) = request.cage_paint {
map.validate()?;
}
if let Some(cage) = request.cage {
cage.validate().map_err(|e| BakeError::Invalid(format!("cage: {e}")))?;
if cage.indices.len() != request.mesh.indices.len() {
return invalid(format!("the cage has {} triangles, the low poly {}", cage.triangle_count(), request.mesh.triangle_count()));
}
}
Ok(())
}
/// `vec![value; n]` that reports allocation failure instead of aborting.
fn alloc<T: Clone>(n: usize, value: T) -> Result<Vec<T>, BakeError> {
let mut v = Vec::new();
v.try_reserve_exact(n).map_err(|_| BakeError::Invalid(format!("out of memory allocating {n} texels")))?;
v.resize(n, value);
Ok(v)
fn alloc<T: Clone>(count: usize, value: T) -> Result<Vec<T>, BakeError> {
let mut values = Vec::new();
values.try_reserve_exact(count).map_err(|_| BakeError::Invalid(format!("out of memory allocating {count} texels")))?;
values.resize(count, value);
Ok(values)
}
/// Bake the maps in `req.settings.maps` for one material of the low-poly mesh, on the CPU.
pub fn bake(req: &BakeRequest, progress: &Progress) -> Result<BakeOutput, BakeError> {
bake_in_strips(req, progress, STRIP_TEXELS, &CpuTracer)
pub fn bake(request: &BakeRequest, progress: &Progress) -> Result<BakeOutput, BakeError> {
bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer)
}
/// [`bake`] with the rays cast by `tracer` (a GPU); when the tracer fails (no adapter, a mesh
/// too large for it, a lost device) the bake runs again on the CPU.
pub fn bake_on(req: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result<BakeOutput, BakeError> {
match bake_in_strips(req, progress, STRIP_TEXELS, tracer) {
Err(BakeError::Tracer(e)) => {
let mut out = bake(req, progress)?;
out.tracer = format!("CPU ({} unavailable: {e})", tracer.name());
Ok(out)
/// Retry on the CPU if the supplied tracer fails
pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result<BakeOutput, BakeError> {
match bake_in_strips(request, progress, STRIP_TEXELS, tracer) {
Err(BakeError::Tracer(error)) => {
let mut output = bake(request, progress)?;
output.tracer = format!("CPU ({} unavailable: {error})", tracer.name());
Ok(output)
}
r => r,
result => result,
}
}
/// One output row of a strip: its slice of every map.
type OutRow<'a> = Vec<&'a mut [f32]>;
fn bake_in_strips(req: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result<BakeOutput, BakeError> {
validate(req)?;
let s = req.settings;
let (tile_res, aa) = (s.resolution as usize, s.antialiasing as usize);
let (w, h) = (tile_res * req.tiles.0 as usize, tile_res * req.tiles.1 as usize);
let ctx = maps::Ctx::new(req)?;
let tracer = if ctx.casts_rays() { tracer } else { &CpuTracer };
let meshes = ctx.trace_meshes();
fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result<BakeOutput, BakeError> {
validate(request)?;
let settings = request.settings;
let (tile_width, tile_height) = settings.common.output_size();
let tile_size = (tile_width as usize, tile_height as usize);
let samples_per_axis = settings.common.antialiasing.samples_per_axis() as usize;
let (width, height) = (tile_size.0 * request.tiles.0 as usize, tile_size.1 * request.tiles.1 as usize);
let context = map::BakeContext::new(request)?;
let tracer = if context.casts_rays() { tracer } else { &CpuTracer };
let meshes = context.trace_meshes();
let mut scene = tracer.scene(&meshes)?;
progress.done.store(0, Relaxed);
// Curvature from the normal map needs the normal map: baked alongside when not requested.
let from_normal = s.curvature_from_normal && s.maps.contains(&BakedMap::Curvature);
let mut maps: Vec<BakedMap> = s.maps.iter().copied().collect();
// Normal-map curvature needs a normal bake even when normal output is disabled
let from_normal = settings.maps.curvature.parameters.method == CurvatureMethod::NormalMap && settings.maps.is_enabled(BakedMap::Curvature);
let mut maps: Vec<BakedMap> = settings.maps.enabled().collect();
if from_normal && !maps.contains(&BakedMap::Normal) {
maps.push(BakedMap::Normal);
}
let mut bufs = maps.iter().map(|m| alloc(w * h * m.components(), 0.0f32)).collect::<Result<Vec<_>, _>>()?;
let mut covered = alloc(w * h, false)?;
let mut pad = None;
let total = h.max(1) as u64;
let mut buffers = maps.iter().map(|map| alloc(width * height * map.components(), 0.0f32)).collect::<Result<Vec<_>, _>>()?;
let mut covered = alloc(width * height, false)?;
let mut padding_map = None;
let total_rows = height.max(1) as u64;
let mut rows_done = 0u64;
let strip_err = || BakeError::Invalid("strip out of range".into());
let strip_error = || BakeError::Invalid("strip output of range".into());
// Rasterize in horizontal strips of the supersampled image: a strip's G-buffer is built from
// UVs shifted so that y = v*H - strip_top, which keeps memory bounded at 8K x 8 AA.
let (sw, full_h) = (w * aa, h * aa);
let strip_rows = (strip_texels / (sw * aa)).max(1).min(h);
let batch_rows = (BATCH / (sw * aa)).max(1);
let mut strip_mesh = Mesh { indices: req.mesh.indices.clone(), submeshes: req.mesh.submeshes.clone(), ..Mesh::default() };
for y0 in (0..h).step_by(strip_rows) {
let rows = strip_rows.min(h - y0);
let (sy0, sh) = (y0 * aa, rows * aa);
strip_mesh.uvs = req.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * full_h as f32 - sy0 as f32) / sh as f32)).collect();
let g = UvGBuffer::new(&strip_mesh, req.material, sw as u32, sh as u32);
// A texel is covered when any of its supersamples is.
let cov = covered.get_mut(y0 * w..(y0 + rows) * w).ok_or_else(strip_err)?;
cov.par_chunks_mut(w).enumerate().for_each(|(r, row)| {
for (x, c) in row.iter_mut().enumerate() {
*c = (0..aa * aa).any(|k| g.tri.get((r * aa + k / aa) * sw + x * aa + k % aa).is_some_and(|t| *t != NO_TRI));
let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis);
let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height);
let batch = if context.traces_curvature() { CURVATURE_BATCH } else { BATCH };
let rows_per_batch = (batch / (sample_width * samples_per_axis)).max(1);
let mut strip_mesh = Mesh { indices: request.mesh.indices.clone(), submeshes: request.mesh.submeshes.clone(), ..Mesh::default() };
for strip_start in (0..height).step_by(rows_per_strip) {
let rows = rows_per_strip.min(height - strip_start);
let (sample_start_y, strip_sample_height) = (strip_start * samples_per_axis, rows * samples_per_axis);
strip_mesh.uvs =
request.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * sample_height as f32 - sample_start_y as f32) / strip_sample_height as f32)).collect();
let gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32);
let coverage_rows = covered.get_mut(strip_start * width..(strip_start + rows) * width).ok_or_else(strip_error)?;
coverage_rows.par_chunks_mut(width).enumerate().for_each(|(row_index, row)| {
for (x, covered_pixel) in row.iter_mut().enumerate() {
*covered_pixel = (0..samples_per_axis * samples_per_axis).any(|sample_index| {
gbuffer
.tri
.get(
(row_index * samples_per_axis + sample_index / samples_per_axis) * sample_width
+ x * samples_per_axis
+ sample_index % samples_per_axis,
)
.is_some_and(|triangle_index| *triangle_index != NO_TRI)
});
}
});
let mut out_rows: Vec<OutRow> = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect();
for (m, data) in maps.iter().zip(bufs.iter_mut()) {
let comps = m.components();
let strip = data.get_mut(y0 * w * comps..(y0 + rows) * w * comps).ok_or_else(strip_err)?;
for (row, chunk) in out_rows.iter_mut().zip(strip.chunks_mut(w * comps)) {
let mut output_rows: Vec<OutRow> = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect();
for (map, data) in maps.iter().zip(buffers.iter_mut()) {
let component_count = map.components();
let strip = data.get_mut(strip_start * width * component_count..(strip_start + rows) * width * component_count).ok_or_else(strip_error)?;
for (row, chunk) in output_rows.iter_mut().zip(strip.chunks_mut(width * component_count)) {
row.push(chunk);
}
}
let mut bake_strip = || {
for (b, batch) in out_rows.chunks_mut(batch_rows).enumerate() {
for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() {
if progress.cancel.load(Relaxed) {
return Err(BakeError::Cancelled);
}
// Seed by the global supersample index so strips and batches don't change the noise.
bake_rows(&ctx, &maps, req.mesh, &g, scene.as_mut(), batch, b * batch_rows, (w, aa, sy0 * sw))?;
// Global sample indices keep noise unchanged across strip and batch sizes
bake_rows(
&context,
&maps,
request.mesh,
&gbuffer,
scene.as_mut(),
batch,
batch_index * rows_per_batch,
(width, samples_per_axis, sample_start_y * sample_width),
)?;
rows_done += batch.len() as u64;
progress.done.store((rows_done.saturating_mul(10_000) / total).min(10_000) as u32, Relaxed);
progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed);
}
Ok(())
};
if y0 + rows < h || s.dilation == 0 {
if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) {
bake_strip()?;
} else {
// The coverage is complete: find the padding (UV tile by UV tile) while the last strip bakes.
let padding = || DilationMap::in_blocks(&covered, w as u32, h as u32, Some(s.dilation), s.resolution);
let (p, baked) = rayon::join(padding, bake_strip);
let padding =
|| DilationMap::in_rectangular_blocks(&covered, width as u32, height as u32, Some(settings.common.dilation), (tile_width, tile_height));
let (padding, baked) = rayon::join(padding, bake_strip);
baked?;
pad = Some(p);
padding_map = Some(padding);
}
}
let mut out: BTreeMap<BakedMap, Vec<f32>> = maps.into_iter().zip(bufs).collect();
let mut output: BTreeMap<BakedMap, Vec<f32>> = maps.into_iter().zip(buffers).collect();
if from_normal {
let normal = if s.maps.contains(&BakedMap::Normal) { out.get(&BakedMap::Normal).cloned() } else { out.remove(&BakedMap::Normal) };
if let (Some(normal), Some(curv)) = (normal, out.get_mut(&BakedMap::Curvature)) {
maps::curvature_from_normal(&normal, &covered, w, tile_res, s.curvature_radius, s.curvature_strength, curv);
let normal = if settings.maps.is_enabled(BakedMap::Normal) { output.get(&BakedMap::Normal).cloned() } else { output.remove(&BakedMap::Normal) };
if let (Some(normal), Some(curvature_pixels)) = (normal, output.get_mut(&BakedMap::Curvature)) {
let parameters = settings.maps.curvature.parameters.normal_map;
map::curvature_from_normal(&normal, &covered, width, tile_size, parameters, curvature_pixels);
if parameters.enable_seams {
map::fix_seams(request.mesh, request.material, &covered, (width, height), parameters.seams_intensity, curvature_pixels);
}
}
}
if let Some(pad) = pad {
for (m, data) in out.iter_mut() {
pad.apply(data, m.components());
let (bounds_min, bounds_max) = request.mesh.bounds();
map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6));
if let Some(padding_map) = padding_map {
for (map, data) in output.iter_mut() {
padding_map.apply(data, map.components());
if settings.common.apply_diffusion {
map::diffuse(data, map.components(), &padding_map, tile_size);
}
}
}
if progress.cancel.load(Relaxed) {
return Err(BakeError::Cancelled);
}
progress.done.store(10_000, Relaxed);
Ok(BakeOutput { resolution: w as u32, height: h as u32, maps: out, tracer: tracer.name() })
Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() })
}
/// Bake output rows `r0..` of a strip's G-buffer `g` into `rows`: gather the covered
/// supersamples, cast their transfer and secondary rays in batches on `scene`, then evaluate
/// and average every map per texel. `seed0` is the strip's first supersample index.
#[allow(clippy::too_many_arguments)]
fn bake_rows(
ctx: &maps::Ctx,
context: &map::BakeContext,
maps: &[BakedMap],
mesh: &Mesh,
g: &UvGBuffer,
gbuffer: &UvGBuffer,
scene: &mut dyn RayScene,
rows: &mut [OutRow],
r0: usize,
(w, aa, seed0): (usize, usize, usize),
first_row: usize,
(width, samples_per_axis, first_sample_seed): (usize, usize, usize),
) -> Result<(), BakeError> {
let sw = w * aa;
let per_row: Vec<Vec<maps::Sample>> = (r0..r0 + rows.len())
let sample_width = width * samples_per_axis;
let samples_by_row: Vec<Vec<map::Sample>> = (first_row..first_row + rows.len())
.into_par_iter()
.map(|r| {
let subsamples = (0..w).flat_map(|x| (0..aa * aa).map(move |k| (x, (r * aa + k / aa) * sw + x * aa + k % aa)));
subsamples.filter_map(|(x, i)| Some(maps::Sample { x, surf: g.surface(mesh, i)?, bary: *g.bary.get(i)?, seed: (seed0 + i) as u64 })).collect()
.map(|row| {
let subsamples = (0..width).flat_map(|x| {
(0..samples_per_axis * samples_per_axis).map(move |sample_index| {
(x, (row * samples_per_axis + sample_index / samples_per_axis) * sample_width + x * samples_per_axis + sample_index % samples_per_axis)
})
});
subsamples
.filter_map(|(x, sample_index)| {
Some(map::Sample {
x,
surface: gbuffer.surface(mesh, sample_index)?,
bary: *gbuffer.bary.get(sample_index)?,
seed: (first_sample_seed + sample_index) as u64,
})
})
.collect()
})
.collect();
// Index of each row's first sample in the batch arrays.
let starts: Vec<usize> = per_row
let row_offsets: Vec<usize> = samples_by_row
.iter()
.scan(0, |n, r| {
*n += r.len();
Some(*n - r.len())
.scan(0, |sample_count, row| {
*sample_count += row.len();
Some(*sample_count - row.len())
})
.collect();
let samples = || per_row.par_iter().flat_map_iter(|r| r.iter());
let samples = || samples_by_row.par_iter().flat_map_iter(|row| row.iter());
let transfers = match ctx.has_high() {
let transfers = match context.has_high() {
true => {
let (rays, fronts): (Vec<rays::Ray>, Vec<f32>) = samples().map(|p| ctx.transfer_ray(&p.surf, p.bary)).unzip();
let hits = scene.closest(1, &rays)?;
hits.into_par_iter().zip(fronts).map(|(hit, front)| ctx.transfer(hit, front)).collect()
let (rays, frontal_distances): (Vec<tracing::Ray>, Vec<f32>) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip();
let hits = scene.closest(1, &rays, context.ignore_transfer_backface())?;
hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect()
}
false => Vec::new(),
};
let transfer = |k: usize| transfers.get(k).and_then(Option::as_ref);
let queries: Vec<rays::Query> = match ctx.ao.is_some() || ctx.bent.is_some() || ctx.thickness.is_some() {
let transfer = |sample_index: usize| transfers.get(sample_index).and_then(Option::as_ref);
let curvature = match context.traces_curvature() {
true => {
per_row.par_iter().zip(&starts).flat_map_iter(|(r, &first)| r.iter().zip(first..)).map(|(p, k)| ctx.query(transfer(k), &p.surf, p.seed)).collect()
let items: Vec<(&Surface, Option<&map::Transfer>)> = samples_by_row
.iter()
.zip(&row_offsets)
.flat_map(|(row, &first)| row.iter().zip(first..))
.map(|(sample, sample_index)| (&sample.surface, transfer(sample_index)))
.collect();
context.trace_curvature(scene, &items)?
}
false => Vec::new(),
};
// Bent normals come with the occlusion rays when they share the settings.
let own_bent = ctx.bent.filter(|_| ctx.bent != ctx.ao);
let passes: Vec<rays::Hemisphere> = [ctx.ao, own_bent, ctx.thickness].into_iter().flatten().collect();
let queries: Vec<tracing::Query> = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() {
true => samples_by_row
.par_iter()
.zip(&row_offsets)
.flat_map_iter(|(row, &first)| row.iter().zip(first..))
.map(|(sample, sample_index)| context.query(transfer(sample_index), &sample.surface, sample.seed))
.collect(),
false => Vec::new(),
};
// Share occlusion results when the bent-normal ray settings match
let separate_bent_pass = context.bent.filter(|_| context.bent != context.ao);
let passes: Vec<tracing::Hemisphere> = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect();
let mut results = scene.hemispheres(&passes, &queries)?.into_iter();
let mut next = |on: bool| if on { results.next().unwrap_or_default() } else { Vec::new() };
let (ao, bent_own, thickness) = (next(ctx.ao.is_some()), next(own_bent.is_some()), next(ctx.thickness.is_some()));
let bent = if own_bent.is_some() { &bent_own } else { &ao };
let mut next = |enabled: bool| if enabled { results.next().unwrap_or_default() } else { Vec::new() };
let (occlusion_results, separate_bent_results, thickness) =
(next(context.ao.is_some()), next(separate_bent_pass.is_some()), next(context.thickness.is_some()));
let bent_results = if separate_bent_pass.is_some() { &separate_bent_results } else { &occlusion_results };
rows.par_iter_mut().zip(&per_row).zip(&starts).for_each(|((row, samples), &first)| {
let mut sample = [[0.0f32; 3]; BakedMap::ALL.len()];
let mut j = 0;
for x in 0..w {
let mut acc = [[0.0f32; 3]; BakedMap::ALL.len()];
let mut n = 0u32;
while let Some(p) = samples.get(j).filter(|p| p.x == x) {
let k = first + j;
let traced = maps::Traced {
ao: ao.get(k).map_or(1.0, |v| v[0]),
bent: bent.get(k).map(|v| Vec3::new(v[1], v[2], v[3])),
thickness: thickness.get(k).map_or(1.0, |v| v[0]),
rows.par_iter_mut().zip(&samples_by_row).zip(&row_offsets).for_each(|((row, samples), &first)| {
let mut sample_values = [[0.0f32; 3]; BakedMap::ALL.len()];
let mut row_sample_index = 0;
for x in 0..width {
let mut accumulated = [[0.0f32; 3]; BakedMap::ALL.len()];
let mut sample_count = 0u32;
while let Some(sample) = samples.get(row_sample_index).filter(|sample| sample.x == x) {
let sample_index = first + row_sample_index;
let traced = map::Traced {
ao: occlusion_results.get(sample_index).map_or(1.0, |value| value[0]),
bent: bent_results.get(sample_index).map(|value| Vec3::new(value[1], value[2], value[3])),
thickness: thickness.get(sample_index).map_or(1.0, |value| value[0]),
curvature: curvature.get(sample_index).copied().unwrap_or(0.5),
};
ctx.evaluate(maps, &p.surf, p.bary, transfer(k), &traced, &mut sample);
for (a, v) in acc.iter_mut().zip(&sample) {
a.iter_mut().zip(v).for_each(|(a, v)| *a += v);
context.evaluate(maps, &sample.surface, sample.bary, transfer(sample_index), &traced, &mut sample_values);
for (sum, value) in accumulated.iter_mut().zip(&sample_values) {
sum.iter_mut().zip(value).for_each(|(sum, value)| *sum += value);
}
n += 1;
j += 1;
sample_count += 1;
row_sample_index += 1;
}
for ((m, dst), a) in maps.iter().zip(row.iter_mut()).zip(&acc) {
let comps = m.components();
let mean = a.map(|a| a / n.max(1) as f32);
let v = if n == 0 || mean.iter().any(|v| !v.is_finite()) { m.neutral() } else { mean };
if let Some(d) = dst.get_mut(x * comps..(x + 1) * comps) {
d.iter_mut().zip(v).for_each(|(d, v)| *d = v);
for ((map, destination), sum) in maps.iter().zip(row.iter_mut()).zip(&accumulated) {
let component_count = map.components();
let mean = sum.map(|sum| sum / sample_count.max(1) as f32);
let value = if sample_count == 0 || mean.iter().any(|value| !value.is_finite()) { map.neutral() } else { mean };
if let Some(pixel) = destination.get_mut(x * component_count..(x + 1) * component_count) {
pixel.iter_mut().zip(value).for_each(|(component, value)| *component = value);
}
}
}
+22
View File
@@ -0,0 +1,22 @@
mod bake_context;
mod curvature;
mod curvature_tuning;
mod diffusion;
mod normal_curvature;
mod normalization;
pub(crate) use diffusion::diffuse;
pub(crate) use normalization::normalize;
mod sample;
mod seam;
pub(crate) use seam::fix_seams;
mod position_projection;
mod sampling;
mod source;
mod traced;
mod transfer;
pub(crate) use bake_context::BakeContext;
pub(crate) use normal_curvature::curvature_from_normal;
pub(crate) use sample::Sample;
pub(crate) use traced::Traced;
pub(crate) use transfer::Transfer;
+299
View File
@@ -0,0 +1,299 @@
use super::curvature::Curvature;
use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded};
use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer};
use crate::skew::PreparedSkew;
use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh};
use crate::{BakeError, BakeRequest};
use rayon::prelude::*;
use std::collections::HashMap;
use texturecraft_core::{
AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion,
};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Hit, Mesh, Surface, surface_at};
const CURVATURE_CHUNK: usize = 1 << 15;
pub(crate) struct BakeContext<'a> {
low: Source<'a>,
high: Option<Source<'a>>,
cage: Option<&'a Mesh>,
skew: Option<PreparedSkew<'a>>,
cage_paint: Option<&'a crate::BakePaintMap>,
ray_normals: Vec<Vec3>,
settings: &'a BakeSettings,
eps: f32,
frontal: f32,
rear: f32,
position: PositionProjection,
curvature_method: CurvatureMethod,
curvature: Curvature,
pub ao: Option<Hemisphere>,
pub bent: Option<Hemisphere>,
pub thickness: Option<Hemisphere>,
}
impl<'a> BakeContext<'a> {
pub(crate) fn new(request: &BakeRequest<'a>) -> Result<BakeContext<'a>, BakeError> {
let settings = request.settings;
let (bounds_min, bounds_max) = request.mesh.bounds();
let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6);
if !mesh_diagonal.is_finite() {
return Err(BakeError::Invalid("mesh bounds are too large".into()));
}
let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6);
let mut name_keys = HashMap::new();
let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys);
let high = request.high.map(|high_mesh| {
Source::new(
high_mesh.mesh,
high_mesh.bvh,
high_mesh.base_color,
high_mesh.file_ids,
&settings.high_poly.high_suffix,
&settings.high_poly,
&mut name_keys,
)
});
let ray_normals = match settings.cage.average_normals && high.is_some() {
true => {
let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal);
welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect()
}
false => Vec::new(),
};
let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?;
let ray_epsilon = 1e-6 * mesh_diagonal;
let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| {
let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians();
let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 };
settings.maps.is_enabled(map).then_some(Hemisphere {
kind,
rays: ray_settings.rays,
dmax: ray_settings.max_distance * units,
min_distance: ray_settings.min_distance * units,
attenuation: AmbientOcclusionAttenuation::None,
ground_height: None,
eps: ray_epsilon,
cos_max: half_angle_radians.cos(),
sin_max: half_angle_radians.sin(),
uniform: ray_settings.distribution == RayDistribution::Uniform,
ignore_backface: BackfaceMode::Never,
same_key: false,
})
};
let mut ao = pass(BakedMap::AmbientOcclusion, &settings.maps.ao.parameters.rays, RayKind::Occlusion);
if let Some(pass) = &mut ao {
let parameters = settings.maps.ao.parameters;
pass.ignore_backface = parameters.ignore_backface;
pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName;
pass.attenuation = parameters.attenuation;
pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset);
}
let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion);
if let Some(pass) = &mut bent {
pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface;
pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName;
}
let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness);
if let Some(pass) = &mut thickness {
pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName;
}
let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 };
Ok(BakeContext {
low,
high,
cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None },
skew,
cage_paint: request.cage_paint,
ray_normals,
settings,
eps: ray_epsilon,
frontal: settings.cage.max_frontal * cage_units,
rear: settings.cage.max_rear * cage_units,
position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters),
curvature_method: settings.maps.curvature.parameters.method,
curvature: Curvature::new(settings, request.mesh, mesh_scale, request.tiles),
ao,
bent,
thickness,
})
}
pub(crate) fn ignore_transfer_backface(&self) -> bool {
self.settings.high_poly.ignore_backface
}
pub(crate) fn has_high(&self) -> bool {
self.high.is_some()
}
pub(crate) fn casts_rays(&self) -> bool {
self.has_high() || self.curvature.is_enabled || self.ao.is_some() || self.bent.is_some() || self.thickness.is_some()
}
pub(crate) fn trace_meshes(&self) -> Vec<TraceMesh<'_>> {
std::iter::once(&self.low).chain(&self.high).map(Source::trace).collect()
}
pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) {
let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
let cage = self
.cage
.and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric))
.map(|cage_position| surface.pos - cage_position)
.filter(|offset| offset.length() > self.eps);
let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv));
let (origin, direction, front) = match cage {
Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()),
None => {
let up = match &self.skew {
Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal),
None => averaged_normal,
};
(surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale)
}
};
let key = match self.settings.high_poly.match_mode {
MeshMatchMode::Always => ANY,
MeshMatchMode::ByMeshName => self.low.key.get(surface.tri as usize).copied().unwrap_or(ANY),
};
(Ray { origin, direction, max_distance: front + self.rear, key }, front)
}
pub(crate) fn transfer(&self, hit: Option<Hit>, front: f32) -> Option<Transfer> {
let (high, hit) = (self.high.as_ref()?, hit?);
let surface = surface_at(high.mesh, hit.tri, hit.u, hit.v)?;
Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front })
}
pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query {
let (source, surface, mesh) = match (&self.high, transfer) {
(Some(high), Some(transfer_hit)) => (high, &transfer_hit.surface, 1),
_ => (&self.low, low_surface, 0),
};
let seed_hash = splitmix64(seed);
let rot = [(seed_hash >> 40) as f32 / (1u64 << 24) as f32, ((seed_hash >> 16) & 0xff_ffff) as f32 / (1u64 << 24) as f32];
let geo = if surface.geo_nrm.dot(surface.nrm) < 0.0 { -surface.geo_nrm } else { surface.geo_nrm };
Query { pos: surface.pos, nrm: surface.nrm, geo, rot, key: source.key.get(surface.tri as usize).copied().unwrap_or(ANY), mesh }
}
pub(crate) fn traces_curvature(&self) -> bool {
self.curvature.is_enabled
}
pub(crate) fn trace_curvature(&self, scene: &mut dyn RayScene, samples: &[(&Surface, Option<&Transfer>)]) -> Result<Vec<f32>, BakeError> {
let mut output = vec![0.5; samples.len()];
let curvature = &self.curvature;
for mesh in [0usize, 1] {
let Some(source) = (if mesh == 0 { Some(&self.low) } else { self.high.as_ref() }) else { continue };
let tuning = if mesh == 0 { &curvature.low } else { &curvature.high };
let chosen: Vec<(usize, &Surface, f32)> = samples
.par_iter()
.enumerate()
.filter_map(|(sample_index, (low_surface, transfer_hit))| {
let surface = match (mesh, transfer_hit) {
(1, Some(hit)) => &hit.surface,
(0, None) => *low_surface,
_ => return None,
};
Some((sample_index, surface, curvature.texel(low_surface.tri)))
})
.collect();
let rays_per_sample = curvature.rays_per_sample.max(1);
let key_for = |surface: &Surface| {
if self.settings.maps.curvature.parameters.mesh.self_intersection == SelfOcclusion::SameMeshName {
source.key.get(surface.tri as usize).copied().unwrap_or(ANY)
} else {
ANY
}
};
let chunk_size = CURVATURE_CHUNK.min((1_048_576 / rays_per_sample).max(1));
for chunk in chosen.chunks(chunk_size) {
let mut rays: Vec<Ray> = bytemuck::zeroed_vec(chunk.len() * rays_per_sample);
rays.par_chunks_mut(rays_per_sample)
.zip(chunk)
.for_each(|(output, (_, surface, texel))| curvature.rays(tuning, surface, *texel, key_for(surface), output));
let hits = scene.closest(mesh, &rays, false)?;
let walls =
|chunk_index: usize| hits.get(chunk_index * rays_per_sample..chunk_index * rays_per_sample + curvature.wall_count).unwrap_or_default();
let grounds: Vec<Ray> = chunk
.par_iter()
.enumerate()
.flat_map_iter(|(chunk_index, (_, surface, texel))| {
let mut value = Vec::new();
curvature.ground_rays(surface, *texel, key_for(surface), walls(chunk_index), &mut value);
value
})
.collect();
let ground_hits = scene.closest(mesh, &grounds, false)?;
let ground_offsets: Vec<usize> = (0..chunk.len())
.scan(0, |first, chunk_index| {
let offset = *first;
*first += walls(chunk_index).iter().flatten().count();
Some(offset)
})
.collect();
let values: Vec<(usize, f32)> = chunk
.par_iter()
.zip(&ground_offsets)
.enumerate()
.map(|(chunk_index, ((sample_index, surface, texel), first))| {
let ground_count = walls(chunk_index).iter().flatten().count();
let sample_ground_hits = ground_hits.get(*first..*first + ground_count).unwrap_or_default();
let sample_hits = hits.get(chunk_index * rays_per_sample..(chunk_index + 1) * rays_per_sample).unwrap_or_default();
(*sample_index, curvature.value(tuning, source, surface, *texel, sample_hits, sample_ground_hits))
})
.collect();
for (sample_index, value) in values {
if let Some(destination) = output.get_mut(sample_index) {
*destination = value;
}
}
}
}
Ok(output)
}
pub(crate) fn evaluate(
&self,
maps: &[BakedMap],
low_surface: &Surface,
barycentric: [f32; 2],
transfer: Option<&Transfer>,
traced: &Traced,
outputs: &mut [[f32; 3]],
) {
let (source, surface, source_barycentric) = match (&self.high, transfer) {
(Some(high), Some(hit)) => (high, &hit.surface, hit.bary),
_ => (&self.low, low_surface, barycentric),
};
let missed = self.high.is_some() && transfer.is_none();
for (&map, output) in maps.iter().zip(outputs.iter_mut()) {
*output = match map {
BakedMap::AmbientOcclusion => [traced.ao; 3],
BakedMap::BentNormal => pack(traced.bent.unwrap_or(surface.nrm)),
BakedMap::Thickness => [traced.thickness; 3],
BakedMap::Curvature if self.curvature_method == CurvatureMethod::NormalMap => [0.5; 3],
BakedMap::Curvature => [traced.curvature; 3],
BakedMap::WorldNormal => pack(surface.nrm),
BakedMap::Position => self.position.evaluate(surface.pos),
BakedMap::Id => source.id_color(surface, source_barycentric, self.settings.maps.id.parameters),
BakedMap::Normal => transfer.map_or(map.neutral(), |hit| tangent_normal(low_surface, hit.surface.nrm)),
BakedMap::Height => {
let relative_to_rays = self.settings.maps.height.parameters.normalization == texturecraft_core::HeightNormalization::RelativeToRayDistances;
[transfer.map_or(if relative_to_rays { 0.5 } else { 0.0 }, |hit| {
let height = hit.front - hit.t;
if relative_to_rays { (0.5 + height / (hit.front + self.rear).max(1e-20)).clamp(0.0, 1.0) } else { height }
}); 3]
}
BakedMap::Opacity if missed => [0.0; 3],
BakedMap::Opacity => [source.color(surface, source_barycentric).w; 3],
};
}
}
}
+217
View File
@@ -0,0 +1,217 @@
use super::{curvature_tuning::CurvatureTuning, sampling::interpolate, source::Source};
use crate::tracing::Ray;
use rayon::prelude::*;
use texturecraft_core::{BakeSettings, BakedMap, CurvatureMethod};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Hit, Mesh, Surface};
const RING_COUNT: usize = 4;
const WALL_RADIUS_TEXELS: f32 = 1.5;
const CONCAVE_WEIGHT: f32 = 1.5;
const LOW_POLY_CONVEX_WEIGHT: f32 = 1.5;
const HIGH_POLY_CONVEX_WEIGHT: f32 = 0.5;
const LOW_POLY_CURVATURE_RADIUS_RATIO: f32 = 0.003;
const LOW_POLY_CURVATURE_WEIGHT: f32 = 1.3;
const HIGH_POLY_CURVATURE_RADIUS_RATIO: f32 = 0.0007;
const HIGH_POLY_CURVATURE_WEIGHT: f32 = 1.6;
const HARD_EDGE_NORMAL_CHANGE_THRESHOLD: f32 = 0.05;
const GENTLE_CURVATURE_THRESHOLD: f32 = 0.1;
pub(super) struct Curvature {
pub(super) is_enabled: bool,
walls: f32,
spread: f32,
fallback: f32,
texels: Vec<f32>,
ring: [Vec<(f32, f32)>; RING_COUNT],
pub(super) rays_per_sample: usize,
pub(super) wall_count: usize,
pub(super) low: CurvatureTuning,
pub(super) high: CurvatureTuning,
}
impl Curvature {
pub(super) fn new(settings: &BakeSettings, low: &Mesh, mesh_scale: f32, tiles: (u32, u32)) -> Curvature {
let is_enabled = settings.maps.is_enabled(BakedMap::Curvature) && settings.maps.curvature.parameters.method == CurvatureMethod::Mesh;
let (width, height) = settings.common.output_size();
let resolution = (width as f32 * height as f32 * tiles.0.max(1) as f32 * tiles.1.max(1) as f32).sqrt();
let texel = |triangle: usize| {
let [a, b, c] = low.tri(triangle)?;
let (position_a, position_b, position_c) = (*low.positions.get(a)?, *low.positions.get(b)?, *low.positions.get(c)?);
let (uv_a, uv_b, uv_c) = (*low.uvs.get(a)?, *low.uvs.get(b)?, *low.uvs.get(c)?);
let world_area = (position_b - position_a).cross(position_c - position_a).length();
let uv_area = (uv_b - uv_a).perp_dot(uv_c - uv_a).abs();
(uv_area > 1e-12 && world_area > 0.0).then(|| (world_area / uv_area).sqrt() / resolution)
};
let fallback = mesh_scale * 1e-3;
let triangle_count = if is_enabled { low.triangle_count() } else { 0 };
let parameters = settings.maps.curvature.parameters.mesh;
let radius = parameters.sampling_radius * if parameters.relative_to_bounding_box { mesh_scale } else { 1.0 };
let radius_scale = radius / (mesh_scale * 0.001);
let walls = WALL_RADIUS_TEXELS * radius_scale;
let rays_per_sample = parameters.rays as usize;
let ring: [Vec<(f32, f32)>; RING_COUNT] = std::array::from_fn(|ring_index| {
let count = rays_per_sample / RING_COUNT + usize::from(ring_index < rays_per_sample % RING_COUNT);
(0..count)
.map(|index| {
let angle = std::f32::consts::TAU * index as f32 / count.max(1) as f32;
(angle.cos(), angle.sin())
})
.collect()
});
Curvature {
is_enabled,
rays_per_sample,
wall_count: ring.first().map_or(0, Vec::len),
walls,
spread: walls * 4.0 / 3.0,
fallback,
texels: (0..triangle_count).into_par_iter().map(|t| texel(t).filter(|v| v.is_finite()).unwrap_or(fallback)).collect(),
low: CurvatureTuning {
convex: LOW_POLY_CONVEX_WEIGHT,
true_radius: mesh_scale * LOW_POLY_CURVATURE_RADIUS_RATIO * radius_scale,
true_strength: LOW_POLY_CURVATURE_WEIGHT,
},
high: CurvatureTuning {
convex: HIGH_POLY_CONVEX_WEIGHT,
true_radius: mesh_scale * HIGH_POLY_CURVATURE_RADIUS_RATIO * radius_scale,
true_strength: HIGH_POLY_CURVATURE_WEIGHT,
},
ring,
}
}
pub(super) fn texel(&self, tri: u32) -> f32 {
self.texels.get(tri as usize).copied().unwrap_or(self.fallback)
}
fn radii(&self, tuning: &CurvatureTuning, texel: f32) -> [f32; RING_COUNT] {
let r = self.walls * texel;
[r, r, self.spread * texel, tuning.true_radius]
}
fn directions(&self, ring: usize, tangent: Vec3, bitangent: Vec3) -> impl Iterator<Item = Vec3> + '_ {
self.ring.get(ring).into_iter().flatten().map(move |(cosine, sine)| tangent * *cosine + bitangent * *sine)
}
pub(super) fn rays(&self, tuning: &CurvatureTuning, surface: &Surface, texel_size: f32, key: u32, output: &mut [Ray]) {
let (geometric_normal, tangent, bitangent) = surface_frame(surface);
let mut output = output.iter_mut();
for (ring, radius) in self.radii(tuning, texel_size).into_iter().enumerate() {
for direction in self.directions(ring, tangent, bitangent) {
let Some(ray) = output.next() else {
return;
};
*ray = match ring {
0 => Ray { origin: surface.pos + geometric_normal * (0.15 * radius), direction, max_distance: radius, key },
1 => Ray { origin: surface.pos - geometric_normal * (0.15 * radius), direction, max_distance: radius, key },
_ => Ray {
origin: surface.pos + direction * radius + geometric_normal * (0.25 * radius),
direction: -geometric_normal,
max_distance: 2.25 * radius,
key,
},
};
}
}
}
pub(super) fn ground_rays(&self, surface: &Surface, texel_size: f32, key: u32, walls: &[Option<Hit>], output: &mut Vec<Ray>) {
let (geometric_normal, tangent, bitangent) = surface_frame(surface);
let radius = self.walls * texel_size;
for (w, direction) in walls.iter().zip(self.directions(0, tangent, bitangent)) {
if let Some(hit) = w {
output.push(Ray {
origin: surface.pos + geometric_normal * (0.15 * radius) + direction * (hit.t * 0.85),
direction: -geometric_normal,
max_distance: 0.5 * radius,
key,
});
}
}
}
fn wall(&self, source: &Source, surface: &Surface, geometric_normal: Vec3, radius: f32, hits: &[Option<Hit>], keep: &mut dyn FnMut() -> bool) -> f32 {
let mut sum = 0.0;
for hit in hits.iter().flatten() {
if !keep() {
continue;
}
let upright = triangle_normal(source.mesh, hit.tri).map_or(1.0, |normal| (1.0 - normal.dot(geometric_normal).powi(2)).max(0.0).sqrt());
let shaded = interpolate(source.mesh, &source.mesh.normals, hit.tri, [hit.u, hit.v]).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
let hard = ((1.0 - shaded.dot(surface.nrm)) / HARD_EDGE_NORMAL_CHANGE_THRESHOLD).clamp(0.0, 1.0);
sum += (1.0 - hit.t / radius) * upright * hard;
}
sum / hits.len().max(1) as f32
}
fn spread(
&self,
source: &Source,
surface: &Surface,
geometric_normal: Vec3,
directions: impl Iterator<Item = Vec3>,
hits: &[Option<Hit>],
turn: f32,
) -> (f32, f32) {
let (mut shading, mut faces) = (0.0, 0.0);
for (hit, direction) in hits.iter().zip(directions) {
let Some(hit) = hit else { continue };
let normal = interpolate(source.mesh, &source.mesh.normals, hit.tri, [hit.u, hit.v]).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
if 1.0 - normal.dot(surface.nrm) <= turn {
shading += (normal - surface.nrm).dot(direction);
if let Some(f) = triangle_normal(source.mesh, hit.tri) {
let f = if f.dot(geometric_normal) < 0.0 { -f } else { f };
faces += (f - geometric_normal).dot(direction);
}
}
}
(shading / hits.len().max(1) as f32, faces / hits.len().max(1) as f32)
}
pub(super) fn value(
&self,
tuning: &CurvatureTuning,
source: &Source,
surface: &Surface,
texel_size: f32,
hits: &[Option<Hit>],
ground_hits: &[Option<Hit>],
) -> f32 {
let (geometric_normal, tangent, bitangent) = surface_frame(surface);
let ring = |ring_index: usize| {
let start: usize = self.ring.iter().take(ring_index).map(Vec::len).sum();
let count = self.ring.get(ring_index).map_or(0, Vec::len);
hits.get(start..start + count).unwrap_or_default()
};
let radius = self.walls * texel_size;
let mut next = ground_hits.iter();
let above = self.wall(source, surface, geometric_normal, radius, ring(0), &mut || next.next().copied().flatten().is_some_and(|g| g.t < 0.3 * radius));
let below = self.wall(source, surface, geometric_normal, radius, ring(1), &mut || true);
let (shading, _) = self.spread(source, surface, geometric_normal, self.directions(2, tangent, bitangent), ring(2), 2.0);
let (true_shading, true_faces) = self.spread(source, surface, geometric_normal, self.directions(3, tangent, bitangent), ring(3), 2.0);
let value =
-above * CONCAVE_WEIGHT + (below - above).max(0.0) * tuning.convex + shading * 0.5 + tight(agreed(true_shading, true_faces) * tuning.true_strength);
(value * 2.0).clamp(-1.0, 1.0)
}
}
fn triangle_normal(mesh: &Mesh, tri: u32) -> Option<Vec3> {
let [a, b, c] = mesh.tri(tri as usize)?;
let p = |i: usize| mesh.positions.get(i).copied();
(p(b)? - p(a)?).cross(p(c)? - p(a)?).try_normalize()
}
fn surface_frame(surface: &Surface) -> (Vec3, Vec3, Vec3) {
let geometric_normal = if surface.geo_nrm.dot(surface.nrm) < 0.0 { -surface.geo_nrm } else { surface.geo_nrm };
let (tangent, bitangent) = geometric_normal.any_orthonormal_pair();
(geometric_normal, tangent, bitangent)
}
fn tight(v: f32) -> f32 {
v.signum() * (v.abs() - GENTLE_CURVATURE_THRESHOLD).max(0.0)
}
fn agreed(shading: f32, faces: f32) -> f32 {
if shading * faces <= 0.0 { 0.0 } else { shading.abs().min(faces.abs()).copysign(shading) }
}
+5
View File
@@ -0,0 +1,5 @@
pub(super) struct CurvatureTuning {
pub(super) convex: f32,
pub(super) true_radius: f32,
pub(super) true_strength: f32,
}
+89
View File
@@ -0,0 +1,89 @@
use texturecraft_texel::DilationMap;
pub(crate) fn diffuse(pixels: &mut [f32], components: usize, padding: &DilationMap, tile_size: (usize, usize)) {
let width = padding.width as usize;
let height = padding.height as usize;
for start_y in (0..height).step_by(tile_size.1) {
for start_x in (0..width).step_by(tile_size.0) {
let tile_width = tile_size.0.min(width - start_x);
let tile_height = tile_size.1.min(height - start_y);
let mut values = vec![0.0; tile_width * tile_height * components];
let mut valid = vec![false; tile_width * tile_height];
for (index, covered) in valid.iter_mut().enumerate() {
let source = (start_y + index / tile_width) * width + start_x + index % tile_width;
*covered = padding.src.get(source).is_some_and(|source| *source != u32::MAX);
if let (Some(destination), Some(pixel)) =
(values.get_mut(index * components..(index + 1) * components), pixels.get(source * components..(source + 1) * components))
{
destination.copy_from_slice(pixel);
}
}
if !valid.iter().any(|covered| *covered) {
continue;
}
fill(&mut values, &valid, tile_width, tile_height, components);
for (index, covered) in valid.iter().enumerate() {
if *covered {
continue;
}
let destination = (start_y + index / tile_width) * width + start_x + index % tile_width;
if let (Some(pixel), Some(value)) =
(pixels.get_mut(destination * components..(destination + 1) * components), values.get(index * components..(index + 1) * components))
{
pixel.copy_from_slice(value);
}
}
}
}
}
fn fill(values: &mut [f32], valid: &[bool], width: usize, height: usize, components: usize) {
if width == 1 && height == 1 {
return;
}
let (small_width, small_height) = (width.div_ceil(2), height.div_ceil(2));
let mut small = vec![0.0; small_width * small_height * components];
let mut small_valid = vec![false; small_width * small_height];
for (index, covered) in small_valid.iter_mut().enumerate() {
let (x, y) = (index % small_width * 2, index / small_width * 2);
let mut count = 0;
for child_y in y..(y + 2).min(height) {
for child_x in x..(x + 2).min(width) {
let child = child_y * width + child_x;
if valid.get(child) != Some(&true) {
continue;
}
count += 1;
for component in 0..components {
if let Some(value) = small.get_mut(index * components + component) {
*value += values.get(child * components + component).copied().unwrap_or(0.0);
}
}
}
}
*covered = count > 0;
if let Some(pixel) = small.get_mut(index * components..(index + 1) * components) {
pixel.iter_mut().for_each(|value| *value /= count.max(1) as f32);
}
}
fill(&mut small, &small_valid, small_width, small_height, components);
for (index, covered) in valid.iter().enumerate() {
if *covered {
continue;
}
let (x, y) = ((index % width) as f32 * 0.5 - 0.25, (index / width) as f32 * 0.5 - 0.25);
let (fraction_x, fraction_y) = (x - x.floor(), y - y.floor());
let sample = |offset_x: i32, offset_y: i32, component: usize| {
let sample_x = (x.floor() as i32 + offset_x).clamp(0, small_width as i32 - 1) as usize;
let sample_y = (y.floor() as i32 + offset_y).clamp(0, small_height as i32 - 1) as usize;
small.get((sample_y * small_width + sample_x) * components + component).copied().unwrap_or(0.0)
};
for component in 0..components {
let top = sample(0, 0, component) * (1.0 - fraction_x) + sample(1, 0, component) * fraction_x;
let bottom = sample(0, 1, component) * (1.0 - fraction_x) + sample(1, 1, component) * fraction_x;
if let Some(value) = values.get_mut(index * components + component) {
*value = top * (1.0 - fraction_y) + bottom * fraction_y;
}
}
}
}
+42
View File
@@ -0,0 +1,42 @@
/// Divergence of the tangent-space normal map; positive curvature is convex
pub(crate) fn curvature_from_normal(
normal: &[f32],
covered: &[bool],
width: usize,
tile_size: (usize, usize),
settings: texturecraft_core::NormalMapCurvatureSettings,
output: &mut [f32],
) {
use rayon::prelude::*;
let radius_texels = (tile_size.0.min(tile_size.1) / 512).max(1);
let strength = 2.0f32.powf((settings.details - 0.5) * 4.0);
let normal_component = |x: usize, y: usize, component: usize, fallback: f32| match covered.get(y * width + x) {
Some(true) => normal.get((y * width + x) * 3 + component).copied().unwrap_or(fallback),
_ => fallback,
};
output.par_chunks_mut(width).enumerate().for_each(|(y, row)| {
for (x, value) in row.iter_mut().enumerate() {
if covered.get(y * width + x) != Some(&true) {
continue;
}
let (center_x, center_y) = (normal_component(x, y, 0, 0.5), normal_component(x, y, 1, 0.5));
let (left, right) = (
if x % tile_size.0 >= radius_texels { normal_component(x - radius_texels, y, 0, center_x) } else { center_x },
if x % tile_size.0 + radius_texels < tile_size.0 && x + radius_texels < width {
normal_component(x + radius_texels, y, 0, center_x)
} else {
center_x
},
);
let (up, down) = (
if y % tile_size.1 >= radius_texels { normal_component(x, y - radius_texels, 1, center_y) } else { center_y },
if y % tile_size.1 + radius_texels < tile_size.1 && y + radius_texels < covered.len() / width.max(1) {
normal_component(x, y + radius_texels, 1, center_y)
} else {
center_y
},
);
*value = (0.5 + ((right - left) + (up - down)) * strength).clamp(0.0, 1.0);
}
});
}
+91
View File
@@ -0,0 +1,91 @@
use rayon::prelude::*;
use std::collections::BTreeMap;
use texturecraft_core::{BakeSettings, BakedMap, CurvatureMethod, HeightNormalization, ThicknessNormalization};
pub(crate) fn normalize(
maps: &mut BTreeMap<BakedMap, Vec<f32>>,
covered: &[bool],
width: usize,
tile_size: (usize, usize),
settings: &BakeSettings,
mesh_scale: f32,
) {
for (map, pixels) in maps {
if !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) {
continue;
}
if *map == BakedMap::Height && settings.maps.height.parameters.normalization == HeightNormalization::RelativeToRayDistances {
continue;
}
if *map == BakedMap::Curvature && settings.maps.curvature.parameters.method != CurvatureMethod::Mesh {
continue;
}
pixels.par_chunks_mut(width * tile_size.1).enumerate().for_each(|(tile_row, rows)| {
let coverage = covered.get(tile_row * width * tile_size.1..).unwrap_or_default();
for start_x in (0..width).step_by(tile_size.0) {
let end_x = (start_x + tile_size.0).min(width);
let mut minimum = f32::INFINITY;
let mut maximum = f32::NEG_INFINITY;
for (row_index, row) in rows.chunks(width).enumerate() {
for (x, value) in row.iter().enumerate().take(end_x).skip(start_x) {
if coverage.get(row_index * width + x) == Some(&true) && value.is_finite() {
minimum = minimum.min(*value);
maximum = maximum.max(*value);
}
}
}
if !minimum.is_finite() {
continue;
}
let (lower, upper, flat, raw) = match map {
BakedMap::Thickness => {
let parameters = settings.maps.thickness.parameters;
match parameters.normalization {
ThicknessNormalization::RelativeToMinMax => (minimum, maximum, 1.0, false),
ThicknessNormalization::RelativeToRayDistances => {
let units = if parameters.rays.relative_to_bounding_box { mesh_scale } else { 1.0 };
(parameters.rays.min_distance * units, parameters.rays.max_distance * units, 1.0, false)
}
ThicknessNormalization::None => (0.0, 1.0, 1.0, true),
}
}
BakedMap::Height => match settings.maps.height.parameters.normalization {
HeightNormalization::RelativeToRayDistances => {
let units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 };
(-settings.cage.max_rear * units, settings.cage.max_frontal * units, 0.5, false)
}
HeightNormalization::RelativeToMinMax => (minimum, maximum, 0.5, false),
HeightNormalization::RelativeToLowMesh => {
let magnitude = minimum.abs().max(maximum.abs());
(-magnitude, magnitude, 0.5, false)
}
HeightNormalization::Manual => {
let half_range = settings.maps.height.parameters.scaling_divisor * 0.5;
(-half_range, half_range, 0.5, false)
}
},
_ => {
let parameters = settings.maps.curvature.parameters.mesh;
if parameters.auto_tonemapping {
let magnitude = minimum.abs().max(maximum.abs());
(-magnitude, magnitude, 0.5, false)
} else {
(parameters.value_min, parameters.value_max, 0.5, false)
}
}
};
if raw {
continue;
}
let range = upper - lower;
for (row_index, row) in rows.chunks_mut(width).enumerate() {
for (x, value) in row.iter_mut().enumerate().take(end_x).skip(start_x) {
if coverage.get(row_index * width + x) == Some(&true) {
*value = if range > f32::EPSILON { ((*value - lower) / range).clamp(0.0, 1.0) } else { flat };
}
}
}
}
});
}
}
@@ -0,0 +1,45 @@
use texturecraft_core::{PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings};
use texturecraft_geom::{Mesh, glam::Vec3};
pub(super) struct PositionProjection {
settings: PositionSettings,
minimum: Vec3,
extent: Vec3,
center: Vec3,
diameter: f32,
}
impl PositionProjection {
pub(super) fn new(mesh: &Mesh, material: usize, settings: PositionSettings) -> Self {
let initial = (Vec3::splat(f32::INFINITY), Vec3::splat(f32::NEG_INFINITY));
let expand = |(minimum, maximum): (Vec3, Vec3), position: &Vec3| (minimum.min(*position), maximum.max(*position));
let (minimum, maximum) = match settings.scale {
PositionNormalizationScale::FullScene => mesh.positions.iter().fold(initial, expand),
PositionNormalizationScale::PerMaterial => mesh
.triangles_of(material)
.filter_map(|triangle| mesh.tri(triangle))
.flatten()
.filter_map(|index| mesh.positions.get(index))
.fold(initial, expand),
};
let minimum = if minimum.is_finite() { minimum } else { Vec3::ZERO };
let maximum = if maximum.is_finite() { maximum } else { Vec3::ZERO };
let center = (minimum + maximum) * 0.5;
let extent = maximum - minimum;
Self { settings, minimum, extent, center, diameter: extent.max_element().max(1e-20) }
}
pub(super) fn evaluate(&self, position: Vec3) -> [f32; 3] {
let value = match self.settings.normalization {
PositionMode::BoundingBox => ((position - self.minimum) / self.extent.max(Vec3::splat(1e-20))).clamp(Vec3::ZERO, Vec3::ONE),
PositionMode::BoundingSphere => ((position - self.center) / self.diameter + 0.5).clamp(Vec3::ZERO, Vec3::ONE),
PositionMode::None => position,
};
match self.settings.axis {
PositionAxis::All => value.to_array(),
PositionAxis::X => [value.x; 3],
PositionAxis::Y => [value.y; 3],
PositionAxis::Z => [value.z; 3],
}
}
}
+8
View File
@@ -0,0 +1,8 @@
use texturecraft_geom::Surface;
pub(crate) struct Sample {
pub x: usize,
pub surface: Surface,
pub bary: [f32; 2],
pub seed: u64,
}
+67
View File
@@ -0,0 +1,67 @@
use std::collections::HashMap;
use std::ops::{Add, Mul};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Mesh, Surface};
pub(super) fn interpolate<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option<T> {
let [a, b, c] = mesh.tri(tri as usize)?;
Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2)
}
pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec<u32>, Vec<Vec3>, Vec<Vec3>) {
let q = diag * 1e-5;
let mut ids: HashMap<[i64; 3], u32> = HashMap::new();
let (mut pos, mut nrm) = (Vec::new(), Vec::<Vec3>::new());
let weld: Vec<u32> = mesh
.positions
.iter()
.zip(&mesh.normals)
.map(|(p, n)| {
let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64);
let id = *ids.entry(key).or_insert_with(|| {
pos.push(*p);
nrm.push(Vec3::ZERO);
(pos.len() - 1) as u32
});
if let Some(acc) = nrm.get_mut(id as usize) {
*acc += *n;
}
id
})
.collect();
let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect();
(weld, pos, nrm)
}
pub(super) fn splitmix64(x: u64) -> u64 {
let mut z = x.wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
pub(super) fn pack(v: Vec3) -> [f32; 3] {
(v * 0.5 + 0.5).clamp(Vec3::ZERO, Vec3::ONE).to_array()
}
pub(super) fn generated_hue(part: usize) -> [f32; 3] {
let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32;
let (s, v) = (0.7f32, 0.95f32);
let f = h.fract();
let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f)));
match h as u32 {
0 => [v, t, p],
1 => [q, v, p],
2 => [p, v, t],
3 => [p, q, v],
4 => [t, p, v],
_ => [v, p, q],
}
}
pub(super) fn tangent_normal(s: &Surface, n: Vec3) -> [f32; 3] {
let z = s.nrm;
let t = (s.tangent.truncate() - z * z.dot(s.tangent.truncate())).try_normalize().unwrap_or_else(|| z.any_orthonormal_vector());
let b = z.cross(t) * s.tangent.w;
pack(Vec3::new(t.dot(n), b.dot(n), z.dot(n)))
}
+64
View File
@@ -0,0 +1,64 @@
use std::collections::HashMap;
use texturecraft_geom::{Mesh, glam::Vec2};
pub(crate) fn fix_seams(mesh: &Mesh, material: usize, covered: &[bool], size: (usize, usize), intensity: f32, pixels: &mut [f32]) {
if intensity <= 0.0 {
return;
}
let (minimum, maximum) = mesh.bounds();
let tolerance = (maximum - minimum).length().max(1e-6) * 1e-6;
let position_key = |index: usize| mesh.positions.get(index).map(|position| position.to_array().map(|value| (value / tolerance).round() as i64));
let mut edges = HashMap::new();
let source = pixels.to_vec();
let texel_scale = Vec2::new(size.0 as f32, size.1 as f32);
let texel = |point: Vec2| {
if point.x < 0.0 || point.y < 0.0 || point.x >= size.0 as f32 || point.y >= size.1 as f32 {
return None;
}
let index = point.y.floor() as usize * size.0 + point.x.floor() as usize;
(covered.get(index) == Some(&true)).then_some(index)
};
for triangle in mesh.triangles_of(material) {
let Some(corners) = mesh.tri(triangle) else {
continue;
};
for edge in 0..3 {
let (Some(&first), Some(&second), Some(&third)) = (corners.get(edge), corners.get((edge + 1) % 3), corners.get((edge + 2) % 3)) else {
continue;
};
let (Some(first_key), Some(second_key)) = (position_key(first), position_key(second)) else {
continue;
};
let (first, second, key) =
if first_key <= second_key { (first, second, (first_key, second_key)) } else { (second, first, (second_key, first_key)) };
let (Some(start), Some(end), Some(interior)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else {
continue;
};
let (start, end, interior) = (*start * texel_scale, *end * texel_scale, *interior * texel_scale);
let inward = (interior - (start + end) * 0.5).try_normalize().unwrap_or(Vec2::ZERO) * 0.75;
let Some((other_start, other_end, other_inward)) = edges.insert(key, (start, end, inward)) else {
continue;
};
if start.distance_squared(other_start) + end.distance_squared(other_end) < 0.25 {
continue;
}
let steps = start.distance(end).max(other_start.distance(other_end)).ceil().clamp(1.0, size.0.max(size.1) as f32 * 2.0) as usize;
for step in 0..=steps {
let fraction = step as f32 / steps as f32;
let (Some(first), Some(second)) = (texel(start.lerp(end, fraction) + inward), texel(other_start.lerp(other_end, fraction) + other_inward))
else {
continue;
};
let (Some(&first_value), Some(&second_value)) = (source.get(first), source.get(second)) else {
continue;
};
let average = (first_value + second_value) * 0.5;
for (index, value) in [(first, first_value), (second, second_value)] {
if let Some(destination) = pixels.get_mut(index) {
*destination = value + (average - value) * intensity;
}
}
}
}
}
}
+135
View File
@@ -0,0 +1,135 @@
use super::sampling::{generated_hue, interpolate, splitmix64};
use crate::tracing::{ANY, TraceMesh};
use std::collections::HashMap;
use std::sync::Arc;
use texturecraft_core::{HighPolySettings, IdColorGenerator, IdColorSource, IdSettings};
use texturecraft_geom::glam::{Vec2, Vec4};
use texturecraft_geom::{BaseColor, Bvh, Mesh, Surface};
use texturecraft_texel::{linear_to_srgb, srgb_to_linear};
pub(super) struct Source<'a> {
pub(super) mesh: &'a Mesh,
bvh: &'a Bvh,
pub(super) part: Vec<u32>,
pub(super) key: Vec<u32>,
backface_culling: Vec<bool>,
file_ids: &'a [u32],
mesh_ids: Vec<u32>,
file_count: u32,
mesh_count: u32,
base_color: &'a [Option<Arc<BaseColor>>],
}
impl<'a> Source<'a> {
pub(super) fn new(
mesh: &'a Mesh,
bvh: &'a Bvh,
base_color: &'a [Option<Arc<BaseColor>>],
file_ids: &'a [u32],
suffix: &str,
settings: &HighPolySettings,
keys: &mut HashMap<String, u32>,
) -> Source<'a> {
let triangle_count = mesh.triangle_count();
let mut part = vec![ANY; triangle_count];
let mut backface_culling = vec![false; triangle_count];
let mut mesh_keys = HashMap::new();
let mut mesh_ids = Vec::with_capacity(mesh.submeshes.len());
let mut part_keys = Vec::with_capacity(mesh.submeshes.len());
let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase();
for (part_index, submesh) in mesh.submeshes.iter().enumerate() {
let first_triangle = (submesh.start / 3) as usize;
let last_triangle = (submesh.start.saturating_add(submesh.count) / 3) as usize;
let range = first_triangle.min(last_triangle)..last_triangle.min(triangle_count);
part.get_mut(range.clone()).unwrap_or_default().fill(part_index as u32);
let name = submesh.name.trim().to_lowercase();
let ignore_backface = !backface_suffix.is_empty() && name.ends_with(&backface_suffix);
backface_culling.get_mut(range).unwrap_or_default().fill(ignore_backface);
let name = if ignore_backface { name.strip_suffix(&backface_suffix).unwrap_or(&name) } else { &name };
part_keys.push(match_key(name, suffix, keys));
let next = mesh_keys.len() as u32;
let file_id = file_ids.get(part_index).copied().unwrap_or(0);
mesh_ids.push(*mesh_keys.entry((file_id, name.to_owned())).or_insert(next));
}
let key = part.iter().map(|part_index| part_keys.get(*part_index as usize).copied().unwrap_or(ANY)).collect();
Source {
mesh,
bvh,
part,
key,
backface_culling,
file_ids,
file_count: file_ids.iter().copied().max().unwrap_or(0).saturating_add(1),
mesh_count: mesh_keys.len() as u32,
mesh_ids,
base_color,
}
}
pub(super) fn trace(&self) -> TraceMesh<'_> {
TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key, backface_culling: &self.backface_culling }
}
pub(super) fn id_color(&self, surface: &Surface, barycentric: [f32; 2], settings: IdSettings) -> [f32; 3] {
let part_index = self.part.get(surface.tri as usize).copied().unwrap_or(0) as usize;
match settings.source {
IdColorSource::VertexColor => interpolate(self.mesh, &self.mesh.colors, surface.tri, barycentric).unwrap_or(Vec4::ONE).truncate().to_array(),
IdColorSource::MaterialColor => {
let material = self.mesh.submeshes.get(part_index).map(|part| part.material);
material.and_then(|index| self.base_color.get(index)?.as_ref()).map_or([0.6; 3], |color| color.factor.truncate().to_array())
}
source => {
let (identity, count) = match source {
IdColorSource::FileId => (self.file_ids.get(part_index).copied().unwrap_or(0), self.file_count),
IdColorSource::MeshId => (self.mesh_ids.get(part_index).copied().unwrap_or(0), self.mesh_count),
_ => (part_index as u32, self.mesh.submeshes.len() as u32),
};
match settings.generator {
IdColorGenerator::HueShift => generated_hue(identity as usize),
IdColorGenerator::Grayscale => [(identity + 1) as f32 / count.max(1) as f32; 3],
IdColorGenerator::Random => {
let seed = splitmix64(u64::from(identity));
[0, 16, 32].map(|shift| ((seed >> shift) & 0xffff) as f32 / 65535.0)
}
}
}
}
}
pub(super) fn color(&self, surface: &Surface, barycentric: [f32; 2]) -> Vec4 {
let vertex = interpolate(self.mesh, &self.mesh.colors, surface.tri, barycentric).unwrap_or(Vec4::ONE);
let material = self.part.get(surface.tri as usize).and_then(|part_index| self.mesh.submeshes.get(*part_index as usize)).map(|submesh| submesh.material);
match material.and_then(|material_index| self.base_color.get(material_index)?.as_deref()) {
Some(material_color) => vertex * base_color(material_color, surface.uv),
None => vertex,
}
}
}
fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 {
let sampled_color = if material.texels.is_empty() || !uv.is_finite() {
Vec4::ONE
} else {
let (width, height) = (i64::from(material.width.max(1)), i64::from(material.height.max(1)));
let texel = |x: i64, y: i64| {
let rgba = material.texels.get((y.rem_euclid(height) * width + x.rem_euclid(width)) as usize).copied().unwrap_or([255; 4]);
let color = |component: usize| f32::from(rgba[component]) / 255.0;
Vec4::new(srgb_to_linear(color(0)), srgb_to_linear(color(1)), srgb_to_linear(color(2)), color(3))
};
let (fx, fy) = (uv.x * width as f32 - 0.5, uv.y * height as f32 - 0.5);
let (x0, y0) = (fx.floor(), fy.floor());
let (tx, ty) = (fx - x0, fy - y0);
let (x, y) = (x0 as i64, y0 as i64);
texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty)
};
let color = sampled_color * material.factor;
Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w)
}
fn match_key(name: &str, suffix: &str, keys: &mut HashMap<String, u32>) -> u32 {
let name = name.trim().to_lowercase();
let suffix = suffix.trim().to_lowercase();
let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string();
let next = keys.len() as u32;
*keys.entry(base).or_insert(next)
}
+8
View File
@@ -0,0 +1,8 @@
use texturecraft_geom::glam::Vec3;
pub(crate) struct Traced {
pub ao: f32,
pub bent: Option<Vec3>,
pub thickness: f32,
pub curvature: f32,
}
+8
View File
@@ -0,0 +1,8 @@
use texturecraft_geom::Surface;
pub(crate) struct Transfer {
pub(super) surface: Surface,
pub(super) bary: [f32; 2],
pub(super) t: f32,
pub(super) front: f32,
}
-440
View File
@@ -1,440 +0,0 @@
//! Per-sample evaluation of every baked map.
use std::collections::HashMap;
use std::ops::{Add, Mul};
use std::sync::Arc;
use texturecraft_core::{BakeMatch, BakeSettings, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion};
use texturecraft_geom::glam::{Vec2, Vec3, Vec4};
use texturecraft_geom::{BaseColor, Bvh, Hit, Mesh, Surface, surface_at};
use texturecraft_texel::{linear_to_srgb, srgb_to_linear};
use crate::rays::{ANY, Hemisphere, Query, Ray, RayKind, TraceMesh};
use crate::skew::Prepared;
use crate::{BakeError, BakeRequest};
/// A mesh the bakers sample: the low poly, or the high poly detail is transferred from.
struct Source<'a> {
mesh: &'a Mesh,
bvh: &'a Bvh,
/// Per-vertex curvature offset from 0.5 (empty unless mesh curvature is baked).
curvature: Vec<f32>,
/// Submesh (part) index of each triangle ([`ANY`] outside every part).
part: Vec<u32>,
/// Match key of each triangle: its part name without the low / high suffix.
key: Vec<u32>,
/// Base color per material (empty: vertex colors only).
base_color: &'a [Option<Arc<BaseColor>>],
}
impl<'a> Source<'a> {
fn new(
mesh: &'a Mesh,
bvh: &'a Bvh,
base_color: &'a [Option<Arc<BaseColor>>],
s: &BakeSettings,
diag: f32,
suffix: &str,
keys: &mut HashMap<String, u32>,
) -> Source<'a> {
let mesh_curvature = s.maps.contains(&BakedMap::Curvature) && !s.curvature_from_normal;
let tris = mesh.triangle_count();
let mut part = vec![ANY; tris];
for (i, sm) in mesh.submeshes.iter().enumerate() {
let (a, b) = ((sm.start / 3) as usize, (sm.start.saturating_add(sm.count) / 3) as usize);
part.get_mut(a.min(b)..b.min(tris)).unwrap_or_default().fill(i as u32);
}
let ids: Vec<u32> = mesh.submeshes.iter().map(|sm| match_key(&sm.name, suffix, keys)).collect();
let key = part.iter().map(|p| ids.get(*p as usize).copied().unwrap_or(ANY)).collect();
let curvature = if mesh_curvature { vertex_curvature(mesh, diag, s.curvature_strength) } else { Vec::new() };
Source { mesh, bvh, curvature, part, key, base_color }
}
fn trace(&self) -> TraceMesh<'_> {
TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key }
}
fn curvature(&self, s: &Surface, bary: [f32; 2]) -> f32 {
(0.5 + interpolate(self.mesh, &self.curvature, s.tri, bary).unwrap_or(0.0)).clamp(0.0, 1.0)
}
/// Vertex color times the material's base color (color sRGB-encoded like a base color
/// texture, alpha linear).
fn color(&self, s: &Surface, bary: [f32; 2]) -> Vec4 {
let vertex = interpolate(self.mesh, &self.mesh.colors, s.tri, bary).unwrap_or(Vec4::ONE);
let material = self.part.get(s.tri as usize).and_then(|p| self.mesh.submeshes.get(*p as usize)).map(|sm| sm.material);
match material.and_then(|m| self.base_color.get(m)?.as_deref()) {
Some(b) => vertex * base_color(b, s.uv),
None => vertex,
}
}
}
/// `b` at `uv` (bilinear in linear light, wrapped) times its factor: color sRGB-encoded,
/// alpha linear.
fn base_color(b: &BaseColor, uv: Vec2) -> Vec4 {
let tex = if b.texels.is_empty() || !uv.is_finite() {
Vec4::ONE
} else {
let (w, h) = (i64::from(b.width.max(1)), i64::from(b.height.max(1)));
let texel = |x: i64, y: i64| {
let t = b.texels.get((y.rem_euclid(h) * w + x.rem_euclid(w)) as usize).copied().unwrap_or([255; 4]);
let c = |k: usize| f32::from(t[k]) / 255.0;
Vec4::new(srgb_to_linear(c(0)), srgb_to_linear(c(1)), srgb_to_linear(c(2)), c(3))
};
let (fx, fy) = (uv.x * w as f32 - 0.5, uv.y * h as f32 - 0.5);
let (x0, y0) = (fx.floor(), fy.floor());
let (tx, ty) = (fx - x0, fy - y0);
let (x, y) = (x0 as i64, y0 as i64);
texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty)
};
let c = tex * b.factor;
Vec4::new(linear_to_srgb(c.x), linear_to_srgb(c.y), linear_to_srgb(c.z), c.w)
}
/// The part name without its low / high suffix (case-insensitive), as a shared id.
fn match_key(name: &str, suffix: &str, keys: &mut HashMap<String, u32>) -> u32 {
let name = name.trim().to_lowercase();
let suffix = suffix.trim().to_lowercase();
let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string();
let next = keys.len() as u32;
*keys.entry(base).or_insert(next)
}
/// Barycentric interpolation of a per-vertex attribute over triangle `tri`.
fn interpolate<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option<T> {
let [a, b, c] = mesh.tri(tri as usize)?;
Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2)
}
/// A covered low-poly supersample of a batch.
pub(crate) struct Sample {
/// Output column.
pub x: usize,
pub surf: Surface,
pub bary: [f32; 2],
pub seed: u64,
}
/// The high-poly surface found for a low-poly sample, and where along the ray.
pub(crate) struct Transfer {
surf: Surface,
bary: [f32; 2],
/// Hit distance from the ray origin, and the origin's distance in front of the low poly.
t: f32,
front: f32,
}
/// A sample's secondary-ray results.
pub(crate) struct Traced {
pub ao: f32,
/// None when bent normals are not baked.
pub bent: Option<Vec3>,
pub thickness: f32,
}
/// Everything a sample needs, computed once per bake.
pub(crate) struct Ctx<'a> {
low: Source<'a>,
high: Option<Source<'a>>,
cage: Option<&'a Mesh>,
skew: Option<Prepared<'a>>,
/// Normals averaged over coincident vertices (rays don't split at hard edges); empty when off.
ray_normals: Vec<Vec3>,
lo: Vec3,
extent: Vec3,
/// Ray offset off the surface.
eps: f32,
frontal: f32,
rear: f32,
by_name: bool,
direction: Vec3,
direction_mode: DirectionMode,
position_mode: PositionMode,
curvature_from_normal: bool,
/// Secondary-ray passes of the requested maps.
pub ao: Option<Hemisphere>,
pub bent: Option<Hemisphere>,
pub thickness: Option<Hemisphere>,
}
impl<'a> Ctx<'a> {
pub(crate) fn new(req: &BakeRequest<'a>) -> Result<Ctx<'a>, BakeError> {
let s = req.settings;
let (lo, hi) = req.mesh.bounds();
let diag = (hi - lo).length().max(1e-6);
if !diag.is_finite() {
return Err(BakeError::Invalid("mesh bounds are too large".into()));
}
let mut keys = HashMap::new();
let low = Source::new(req.mesh, req.bvh, &[], s, diag, &s.low_suffix, &mut keys);
let high = req.high.map(|h| Source::new(h.mesh, h.bvh, h.base_color, s, diag, &s.high_suffix, &mut keys));
let ray_normals = match s.average_normals && high.is_some() {
true => {
let (weld, _, nrm) = welded(req.mesh, diag);
weld.iter().map(|w| nrm.get(*w as usize).copied().unwrap_or(Vec3::Y)).collect()
}
false => Vec::new(),
};
let skew = req.skew.map(|m| Prepared::new(m, req.mesh, diag)).transpose()?;
let eps = 1e-4 * diag;
let pass = |map: BakedMap, r: &RaySettings, kind: RayKind| {
let half = (r.spread.clamp(0.0, 180.0) * 0.5).to_radians();
let occlusion = kind == RayKind::Occlusion;
s.maps.contains(&map).then_some(Hemisphere {
kind,
rays: r.rays,
dmax: r.max_distance * diag,
eps,
cos_max: half.cos(),
sin_max: half.sin(),
uniform: r.distribution == RayDistribution::Uniform,
ignore_backface: occlusion && s.ao_ignore_backface,
same_key: occlusion && s.ao_self_occlusion == SelfOcclusion::SameMeshName,
})
};
Ok(Ctx {
low,
high,
cage: req.cage,
skew,
ray_normals,
lo,
extent: hi - lo,
eps,
frontal: s.max_frontal * diag,
rear: s.max_rear * diag,
by_name: s.matching == BakeMatch::ByMeshName,
direction: Vec3::from(s.direction).try_normalize().unwrap_or(Vec3::Y),
direction_mode: s.direction_mode,
position_mode: s.position_mode,
curvature_from_normal: s.curvature_from_normal,
ao: pass(BakedMap::AmbientOcclusion, &s.ao, RayKind::Occlusion),
bent: pass(BakedMap::BentNormal, &s.bent_normal, RayKind::Occlusion),
thickness: pass(BakedMap::Thickness, &s.thickness, RayKind::Thickness),
})
}
pub(crate) fn has_high(&self) -> bool {
self.high.is_some()
}
/// Whether the bake casts any ray.
pub(crate) fn casts_rays(&self) -> bool {
self.has_high() || self.ao.is_some() || self.bent.is_some() || self.thickness.is_some()
}
/// The meshes rays are cast against: the low poly, then the high poly.
pub(crate) fn trace_meshes(&self) -> Vec<TraceMesh<'_>> {
std::iter::once(&self.low).chain(&self.high).map(Source::trace).collect()
}
/// The transfer ray of a low-poly sample: from the cage (or `frontal` in front of the low
/// poly) back through it to `rear` behind, onto the matching high-poly part; and the
/// origin's distance in front of the low poly. Parts without a key cast nothing when
/// matched by name.
pub(crate) fn transfer_ray(&self, s: &Surface, bary: [f32; 2]) -> (Ray, f32) {
let n = interpolate(self.low.mesh, &self.ray_normals, s.tri, bary).and_then(Vec3::try_normalize).unwrap_or(s.nrm);
let cage = self.cage.and_then(|c| interpolate(c, &c.positions, s.tri, bary)).map(|c| s.pos - c).filter(|v| v.length() > self.eps);
let (origin, dir, front) = match cage {
Some(v) => (s.pos - v, v.normalize(), v.length()),
None => {
// Skew correction turns the averaged direction towards the base normal.
let up = match &self.skew {
Some(k) => k.correct(self.low.mesh, s, n),
None => n,
};
(s.pos + up * self.frontal, -up, self.frontal)
}
};
let key = if self.by_name { self.low.key.get(s.tri as usize).copied().unwrap_or(ANY) } else { ANY };
let tmax = if self.by_name && key == ANY { 0.0 } else { front + self.rear };
(Ray { origin, dir, tmax, key }, front)
}
/// The high-poly surface a transfer ray hit.
pub(crate) fn transfer(&self, hit: Option<Hit>, front: f32) -> Option<Transfer> {
let (high, hit) = (self.high.as_ref()?, hit?);
let surf = surface_at(high.mesh, hit.tri, hit.u, hit.v)?;
Some(Transfer { surf, bary: [hit.u, hit.v], t: hit.t, front })
}
/// The secondary-ray query of a sample: on the high poly where the transfer found it.
pub(crate) fn query(&self, transfer: Option<&Transfer>, s: &Surface, seed: u64) -> Query {
let (src, surf, mesh) = match (&self.high, transfer) {
(Some(h), Some(tr)) => (h, &tr.surf, 1),
_ => (&self.low, s, 0),
};
let h = splitmix64(seed);
let rot = [(h >> 40) as f32 / (1u64 << 24) as f32, ((h >> 16) & 0xff_ffff) as f32 / (1u64 << 24) as f32];
// The geometric normal on the side of the shading normal.
let geo = if surf.geo_nrm.dot(surf.nrm) < 0.0 { -surf.geo_nrm } else { surf.geo_nrm };
Query { pos: surf.pos, nrm: surf.nrm, geo, rot, key: src.key.get(surf.tri as usize).copied().unwrap_or(ANY), mesh }
}
/// Every map of `maps` at one low-poly sample, into `out` (scalars fill all three).
pub(crate) fn evaluate(&self, maps: &[BakedMap], s: &Surface, bary: [f32; 2], transfer: Option<&Transfer>, traced: &Traced, out: &mut [[f32; 3]]) {
// The surface the bakers read: the high poly where a ray found it, else the low poly.
let (src, surf, sb) = match (&self.high, transfer) {
(Some(h), Some(tr)) => (h, &tr.surf, tr.bary),
_ => (&self.low, s, bary),
};
let missed = self.high.is_some() && transfer.is_none();
for (&map, o) in maps.iter().zip(out.iter_mut()) {
*o = match map {
BakedMap::AmbientOcclusion => [traced.ao; 3],
BakedMap::BentNormal => pack(traced.bent.unwrap_or(surf.nrm)),
BakedMap::Thickness => [traced.thickness; 3],
BakedMap::Curvature if self.curvature_from_normal => [0.5; 3],
BakedMap::Curvature => [src.curvature(surf, sb); 3],
BakedMap::WorldNormal => pack(surf.nrm),
BakedMap::Position => self.position(surf.pos),
BakedMap::Id => material_color(src.part.get(surf.tri as usize).copied().unwrap_or(0) as usize),
BakedMap::Normal => transfer.map_or(map.neutral(), |tr| tangent_normal(s, tr.surf.nrm)),
BakedMap::Height => [transfer.map_or(0.5, |tr| (0.5 + (tr.front - tr.t) / (tr.front + self.rear)).clamp(0.0, 1.0)); 3],
BakedMap::Opacity if missed => [0.0; 3],
BakedMap::Opacity => [src.color(surf, sb).w; 3],
BakedMap::ColorMap if missed => map.neutral(),
BakedMap::ColorMap => src.color(surf, sb).truncate().to_array(),
BakedMap::WorldDirection => {
let f = surf.nrm.dot(self.direction);
[match self.direction_mode {
DirectionMode::Signed => f * 0.5 + 0.5,
DirectionMode::Positive => f.clamp(0.0, 1.0),
}; 3]
}
};
}
}
/// `p` normalized to 0..1 over the low poly's bounding box or bounding sphere.
fn position(&self, p: Vec3) -> [f32; 3] {
let v = match self.position_mode {
PositionMode::BoundingBox => (p - self.lo) / self.extent.max(Vec3::splat(1e-20)),
PositionMode::BoundingSphere => (p - (self.lo + self.extent * 0.5)) / self.extent.length().max(1e-20) + 0.5,
};
v.clamp(Vec3::ZERO, Vec3::ONE).to_array()
}
}
/// A unit vector packed to 0..1.
fn pack(v: Vec3) -> [f32; 3] {
(v * 0.5 + 0.5).clamp(Vec3::ZERO, Vec3::ONE).to_array()
}
/// `n` in the tangent space of low-poly sample `s` (OpenGL: +Y up the image), packed to 0..1.
fn tangent_normal(s: &Surface, n: Vec3) -> [f32; 3] {
let z = s.nrm;
let t = (s.tangent.truncate() - z * z.dot(s.tangent.truncate())).try_normalize().unwrap_or_else(|| z.any_orthonormal_vector());
let b = z.cross(t) * s.tangent.w;
pack(Vec3::new(t.dot(n), b.dot(n), z.dot(n)))
}
/// Curvature from a baked tangent-space normal map: the divergence of its XY over `radius`
/// texels (convex = above 0.5; 0: one texel per 512 of a UV tile's resolution). Writes covered
/// texels of `out` (one float per texel). `res` is the image width.
pub(crate) fn curvature_from_normal(normal: &[f32], covered: &[bool], res: usize, tile_res: usize, radius: u32, strength: f32, out: &mut [f32]) {
use rayon::prelude::*;
let r = if radius > 0 { radius as usize } else { (tile_res / 512).max(1) };
let n = |x: usize, y: usize, c: usize, fallback: f32| match covered.get(y * res + x) {
Some(true) => normal.get((y * res + x) * 3 + c).copied().unwrap_or(fallback),
_ => fallback,
};
out.par_chunks_mut(res).enumerate().for_each(|(y, row)| {
for (x, v) in row.iter_mut().enumerate() {
if covered.get(y * res + x) != Some(&true) {
continue;
}
let (cx, cy) = (n(x, y, 0, 0.5), n(x, y, 1, 0.5));
let (l, r_) = (n(x.saturating_sub(r), y, 0, cx), if x + r < res { n(x + r, y, 0, cx) } else { cx });
let (u, d) = (n(x, y.saturating_sub(r), 1, cy), if y + r < res { n(x, y + r, 1, cy) } else { cy });
// Image rows run down while +Y (OpenGL) points up: convex bumps tilt +Y above.
*v = (0.5 + strength * ((r_ - l) + (u - d))).clamp(0.0, 1.0);
}
});
}
/// Position-welded copy of `mesh` (UV seams and hard edges share neighbours): the weld id of
/// every vertex, welded positions and their averaged normals.
fn welded(mesh: &Mesh, diag: f32) -> (Vec<u32>, Vec<Vec3>, Vec<Vec3>) {
let q = diag * 1e-5;
let mut ids: HashMap<[i64; 3], u32> = HashMap::new();
let (mut pos, mut nrm) = (Vec::new(), Vec::<Vec3>::new());
let weld: Vec<u32> = mesh
.positions
.iter()
.zip(&mesh.normals)
.map(|(p, n)| {
let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64);
let id = *ids.entry(key).or_insert_with(|| {
pos.push(*p);
nrm.push(Vec3::ZERO);
(pos.len() - 1) as u32
});
if let Some(acc) = nrm.get_mut(id as usize) {
*acc += *n;
}
id
})
.collect();
let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect();
(weld, pos, nrm)
}
/// Per-vertex curvature offset `−k · avg_edge · strength`, where `k` is the mean of
/// `n·(p_j − p_i)/|p_j − p_i|²` over the 1-ring of the welded mesh. Convex edges give a
/// positive offset.
fn vertex_curvature(mesh: &Mesh, diag: f32, strength: f32) -> Vec<f32> {
let q = diag * 1e-5;
let (weld, pos, nrm) = welded(mesh, diag);
let (mut ksum, mut kcnt) = (vec![0.0f32; pos.len()], vec![0u32; pos.len()]);
let (mut edge_sum, mut edge_cnt) = (0.0f64, 0u64);
for t in mesh.indices.chunks_exact(3) {
for (a, b) in [(0, 1), (1, 2), (2, 0), (1, 0), (2, 1), (0, 2)] {
let (Some(&wa), Some(&wb)) = (t.get(a).and_then(|v| weld.get(*v as usize)), t.get(b).and_then(|v| weld.get(*v as usize))) else { continue };
let (Some(pa), Some(pb), Some(na)) = (pos.get(wa as usize), pos.get(wb as usize), nrm.get(wa as usize)) else { continue };
let d = *pb - *pa;
let l2 = d.length_squared();
if wa == wb || l2 <= q * q {
continue;
}
if let (Some(k), Some(c)) = (ksum.get_mut(wa as usize), kcnt.get_mut(wa as usize)) {
*k += na.dot(d) / l2;
*c += 1;
}
edge_sum += f64::from(l2.sqrt());
edge_cnt += 1;
}
}
let scale = (edge_sum / edge_cnt.max(1) as f64) as f32 * strength;
weld.iter()
.map(|w| {
let i = *w as usize;
let k = ksum.get(i).copied().unwrap_or(0.0) / kcnt.get(i).copied().unwrap_or(0).max(1) as f32;
if k.is_finite() { -k * scale } else { 0.0 }
})
.collect()
}
/// A well-separated hue per part (golden-ratio steps around the HSV wheel).
fn material_color(part: usize) -> [f32; 3] {
let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32;
let (s, v) = (0.7f32, 0.95f32);
let f = h.fract();
let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f)));
match h as u32 {
0 => [v, t, p],
1 => [q, v, p],
2 => [p, v, t],
3 => [p, q, v],
4 => [t, p, v],
_ => [v, p, q],
}
}
fn splitmix64(x: u64) -> u64 {
let mut z = x.wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
+22
View File
@@ -0,0 +1,22 @@
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed};
#[derive(Debug, Default)]
pub struct Progress {
/// Completed basis points, from 0 to 10,000
pub done: AtomicU32,
pub cancel: AtomicBool,
}
impl Progress {
pub fn new() -> Self {
Self::default()
}
pub fn fraction(&self) -> f32 {
self.done.load(Relaxed).min(10_000) as f32 / 10_000.0
}
pub fn cancel(&self) {
self.cancel.store(true, Relaxed);
}
}
-206
View File
@@ -1,206 +0,0 @@
//! The ray casts of a bake, in batches. [`CpuTracer`] is the oracle; a GPU [`Tracer`] (the
//! render crate's compute baker) must give the same results: it receives the same rays and
//! queries, and generates the same secondary-ray directions from each query's rotation.
use std::f32::consts::TAU;
use rayon::prelude::*;
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Bvh, Hit, Mesh};
use crate::BakeError;
/// A ray or query key that matches every triangle (no part filter).
pub const ANY: u32 = u32::MAX;
/// A mesh rays are cast against: [`RayScene`] mesh 0 is the low poly, mesh 1 the high poly.
#[derive(Clone, Copy, Debug)]
pub struct TraceMesh<'a> {
pub mesh: &'a Mesh,
pub bvh: &'a Bvh,
/// Part key of every triangle (original order); triangles of no part hold [`ANY`].
pub keys: &'a [u32],
}
impl TraceMesh<'_> {
fn key_matches(&self, tri: u32, key: u32) -> bool {
key == ANY || self.keys.get(tri as usize) == Some(&key)
}
/// Whether `d` meets triangle `tri` from behind (against its winding's normal).
fn back_facing(&self, tri: u32, d: Vec3) -> bool {
let p = |i: usize| self.mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO);
self.mesh.tri(tri as usize).is_some_and(|[a, b, c]| (p(b) - p(a)).cross(p(c) - p(a)).dot(d) > 0.0)
}
}
/// A closest-hit ray (the high-poly transfer).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Ray {
pub origin: Vec3,
pub dir: Vec3,
pub tmax: f32,
/// Only triangles with this part key are hit ([`ANY`]: all).
pub key: u32,
}
/// One sample's secondary rays (ambient occlusion, bent normal or thickness).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Query {
pub pos: Vec3,
/// Shading normal: the axis of the ray cone.
pub nrm: Vec3,
/// Geometric normal on the shading normal's side: rays below its plane are skipped.
pub geo: Vec3,
/// Cranley–Patterson rotation of the sample's ray set.
pub rot: [f32; 2],
/// Part key of the sample's triangle (for [`Hemisphere::same_key`]).
pub key: u32,
/// Scene mesh the rays are cast against.
pub mesh: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RayKind {
/// Out of the surface: ambient occlusion and the bent normal.
Occlusion,
/// Into the surface: the distance through the mesh.
Thickness,
}
/// Parameters of one pass of secondary rays (distances absolute).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Hemisphere {
pub kind: RayKind,
pub rays: u32,
pub dmax: f32,
/// Ray start offset along the geometric normal.
pub eps: f32,
/// Cosine and sine of the cone's half angle.
pub cos_max: f32,
pub sin_max: f32,
/// Uniform over the cone's solid angle (else cosine-weighted).
pub uniform: bool,
pub ignore_backface: bool,
/// Only triangles with the query's part key occlude.
pub same_key: bool,
}
impl Hemisphere {
/// Direction `i` of a query's ray set around `axis` (basis `t`, `b`): Hammersley points
/// rotated by `rot`, mapped onto the cone.
pub fn direction(&self, (t, b, axis): (Vec3, Vec3, Vec3), i: u32, rot: [f32; 2]) -> Vec3 {
let u1 = (i as f32 / self.rays as f32 + rot[0]).fract();
let u2 = (i.reverse_bits() as f32 / 4_294_967_296.0 + rot[1]).fract();
let (r, z) = if self.uniform {
let z = 1.0 - u2 * (1.0 - self.cos_max);
((1.0 - z * z).max(0.0).sqrt(), z)
} else {
let r = self.sin_max * u2.sqrt();
(r, (1.0 - r * r).max(0.0).sqrt())
};
let phi = TAU * u1;
t * (r * phi.cos()) + b * (r * phi.sin()) + axis * z
}
/// The axis, geometric normal and ray origin of `q` for this kind of rays.
fn frame(&self, q: &Query) -> (Vec3, Vec3, Vec3) {
let (axis, geo) = match self.kind {
RayKind::Occlusion => (q.nrm, q.geo),
RayKind::Thickness => (-q.nrm, -q.geo),
};
(axis, geo, q.pos + geo * self.eps)
}
/// `q`'s result on `m`: occlusion gives (ambient occlusion, bent normal), thickness gives
/// (thickness, 0, 0, 0); both relative and in 0..1 (1 = open / thick).
pub fn evaluate(&self, m: &TraceMesh, q: &Query) -> [f32; 4] {
let (axis, geo, o) = self.frame(q);
let (t, b) = axis.any_orthonormal_pair();
let key = if self.same_key && self.kind == RayKind::Occlusion { q.key } else { ANY };
let filtered = key != ANY || (self.ignore_backface && self.kind == RayKind::Occlusion);
let (mut sum, mut bent, mut n) = (0.0f32, Vec3::ZERO, 0u32);
for i in 0..self.rays {
let d = self.direction((t, b, axis), i, q.rot);
if d.dot(geo) <= 0.0 {
continue;
}
let hit = match filtered {
true => m.bvh.closest_filtered(o, d, self.dmax, &|tri| m.key_matches(tri, key) && !(self.ignore_backface && m.back_facing(tri, d))),
false => m.bvh.closest(o, d, self.dmax),
};
match self.kind {
RayKind::Occlusion => {
let v = hit.map_or(0.0, |h| 1.0 - (h.t / self.dmax).powi(2));
sum += v;
bent += d * (1.0 - v);
}
RayKind::Thickness => sum += hit.map_or(self.dmax, |h| h.t),
}
n += 1;
}
match self.kind {
RayKind::Occlusion => {
let ao = if n == 0 { 1.0 } else { (1.0 - sum / n as f32).clamp(0.0, 1.0) };
let bent = bent.try_normalize().unwrap_or(q.nrm);
[ao, bent.x, bent.y, bent.z]
}
RayKind::Thickness => [if n == 0 { 1.0 } else { (sum / n as f32 / self.dmax).clamp(0.0, 1.0) }, 0.0, 0.0, 0.0],
}
}
}
/// Ray casts on the meshes of one bake.
pub trait RayScene: Send {
/// The closest hit of every ray on scene mesh `mesh` (triangles of the ray's key).
fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result<Vec<Option<Hit>>, BakeError>;
/// [`Hemisphere::evaluate`] of every query, for each pass.
fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result<Vec<Vec<[f32; 4]>>, BakeError>;
}
/// Where ray casts run.
pub trait Tracer: Send + Sync {
/// Shown in logs and command results ("CPU", the GPU's name).
fn name(&self) -> String;
/// Prepare `meshes` (low poly, then the high poly if any) for ray casts.
fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result<Box<dyn RayScene + 'a>, BakeError>;
}
/// Ray casts on the CPU (rayon over the batch).
#[derive(Clone, Copy, Debug, Default)]
pub struct CpuTracer;
struct CpuScene<'a>(Vec<TraceMesh<'a>>);
impl CpuScene<'_> {
fn mesh(&self, i: usize) -> Result<&TraceMesh<'_>, BakeError> {
self.0.get(i).ok_or_else(|| BakeError::Invalid(format!("no scene mesh {i}")))
}
}
impl RayScene for CpuScene<'_> {
fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result<Vec<Option<Hit>>, BakeError> {
let m = self.mesh(mesh)?;
Ok(rays
.par_iter()
.map(|r| match r.key {
ANY => m.bvh.closest(r.origin, r.dir, r.tmax),
key => m.bvh.closest_filtered(r.origin, r.dir, r.tmax, &|t| m.key_matches(t, key)),
})
.collect())
}
fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result<Vec<Vec<[f32; 4]>>, BakeError> {
passes.iter().map(|h| queries.par_iter().map(|q| Ok(h.evaluate(self.mesh(q.mesh as usize)?, q))).collect()).collect()
}
}
impl Tracer for CpuTracer {
fn name(&self) -> String {
"CPU".into()
}
fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result<Box<dyn RayScene + 'a>, BakeError> {
Ok(Box::new(CpuScene(meshes.to_vec())))
}
}
+40 -283
View File
@@ -1,261 +1,19 @@
//! Skew correction: a greyscale map over the UV atlas that turns the transfer rays of a
//! high-poly bake from the averaged cage direction towards the low poly's own normal. Where the
//! averaged direction leans away from a surface (the classic "skewed" details on a bevelled
//! edge or a cylinder's cap), painting the map white there sends the rays straight along the
//! surface normal instead, and grey values blend the two.
//!
//! Ported from SurfaceCraft's baker (`crates/bake`, MIT OR Apache-2.0), adapted to this crate's
//! [`crate::maps::Ctx`] rays. Like the averaged cage it only changes rays that start from the
//! built-in distance cage: a custom cage mesh sets its own directions and ignores the map.
//! Skew correction adapted from SurfaceCraft's baker (MIT OR Apache-2.0)
use std::collections::HashMap;
mod prepared_skew;
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{Mesh, Surface};
use crate::{BakeError, MAX_TEXELS};
/// Most dabs one [`SkewMap::paint`] call places.
pub const MAX_DABS: usize = 200_000;
/// Most texels one [`SkewMap::paint`] call may visit, summed over its dabs (about 70 ms of work):
/// a big brush on a big map costs per dab what a whole-map pass costs, so dabs alone don't bound it.
pub const MAX_PAINT_TEXELS: u64 = 1 << 26;
/// Edges steeper than this cosine between two faces count as hard (about 30 degrees).
const HARD_EDGE_COS: f32 = 0.866;
/// A skew map over the whole UV atlas.
#[derive(Clone, Debug, PartialEq)]
pub struct SkewMap {
pub width: u32,
pub height: u32,
/// `width * height` values in 0..=1, row 0 at the top (v = 1): 0 keeps a ray on the cage's
/// averaged direction, 1 turns it fully onto the base normal.
pub values: Vec<f32>,
/// Edge protection: the correction fades out within this fraction of the mesh diagonal of a
/// hard edge (0: off).
pub edge_distance: f32,
/// Edge protection's falloff exponent: 1 is linear, more holds the correction back longer.
pub edge_contrast: f32,
/// Correct towards each triangle's flat normal instead of the interpolated vertex normal.
pub per_triangle: bool,
}
impl SkewMap {
/// A map of one value everywhere.
pub fn constant(value: f32) -> SkewMap {
SkewMap { width: 1, height: 1, values: vec![value], edge_distance: 0.0, edge_contrast: 1.0, per_triangle: false }
}
/// Refuses maps whose size doesn't match their values, non-finite numbers and absurd sizes.
pub fn validate(&self) -> Result<(), BakeError> {
let invalid = |m: &str| Err(BakeError::Invalid(m.into()));
let texels = u64::from(self.width) * u64::from(self.height);
if self.width == 0 || self.height == 0 || texels > MAX_TEXELS || self.values.len() as u64 != texels {
return invalid("the skew map's size doesn't match its values");
}
if !(self.edge_distance.is_finite() && self.edge_distance >= 0.0 && self.edge_contrast.is_finite() && self.edge_contrast > 0.0) {
return invalid("the skew edge distance must be 0 or more and the contrast above 0");
}
if self.values.iter().any(|v| !v.is_finite()) {
return invalid("the skew map has a value that is not a finite number");
}
Ok(())
}
/// The map resampled (bilinear) to `width` × `height`; the other settings carry over.
pub fn resized(&self, width: u32, height: u32) -> Result<SkewMap, BakeError> {
let texels = u64::from(width) * u64::from(height);
if width == 0 || height == 0 || texels > MAX_TEXELS {
return Err(BakeError::Invalid(format!("a {width} × {height} skew map is outside the supported size")));
}
let mut values = Vec::with_capacity(texels as usize);
for y in 0..height {
let v = 1.0 - (y as f32 + 0.5) / height as f32;
for x in 0..width {
values.push(self.at(Vec2::new((x as f32 + 0.5) / width as f32, v)));
}
}
Ok(SkewMap { width, height, values, ..self.clone() })
}
/// Paint round dabs along `points` (atlas uv): `value` is blended in with `strength` (0..=1),
/// fully inside `hardness` (0..=1) of `radius` (in uv units) and fading to nothing at the rim.
/// Dabs are placed a quarter radius apart along each segment; `MAX_DABS` bounds one call.
pub fn paint(&mut self, points: &[Vec2], radius: f32, value: f32, hardness: f32, strength: f32) -> Result<(), BakeError> {
let ok = radius.is_finite() && radius > 0.0 && value.is_finite() && hardness.is_finite() && strength.is_finite();
if !ok || points.iter().any(|p| !p.is_finite()) {
return Err(BakeError::Invalid("the skew brush needs finite numbers and a radius above 0".into()));
}
self.validate()?;
let (value, hardness, strength) = (value.clamp(0.0, 1.0), hardness.clamp(0.0, 0.999), strength.clamp(0.0, 1.0));
let step = (radius * 0.25).max(1e-5);
let mut dabs = Vec::new();
for (i, p) in points.iter().enumerate() {
match i.checked_sub(1).and_then(|j| points.get(j)) {
Some(prev) => {
let n = ((*p - *prev).length() / step).ceil().clamp(1.0, MAX_DABS as f32) as usize;
dabs.extend((1..=n).map(|k| *prev + (*p - *prev) * (k as f32 / n as f32)));
}
None => dabs.push(*p),
}
if dabs.len() > MAX_DABS {
return Err(BakeError::Invalid(format!("a skew stroke is limited to {MAX_DABS} dabs; use a larger radius or fewer points")));
}
}
let (w, h) = (self.width as usize, self.height as usize);
// The texel box of a dab, row 0 at the top (v = 1).
let span = |c: Vec2| {
let x0 = (((c.x - radius) * w as f32).floor().max(0.0)) as usize;
let x1 = (((c.x + radius) * w as f32).ceil().min(w as f32)).max(0.0) as usize;
let y0 = ((((1.0 - c.y) - radius) * h as f32).floor().max(0.0)) as usize;
let y1 = ((((1.0 - c.y) + radius) * h as f32).ceil().min(h as f32)).max(0.0) as usize;
(x0, x1, y0, y1)
};
// Refuse a stroke that would take too long before the first texel changes.
let work: u64 = dabs
.iter()
.map(|c| {
let (x0, x1, y0, y1) = span(*c);
x1.saturating_sub(x0) as u64 * y1.saturating_sub(y0) as u64
})
.fold(0, u64::saturating_add);
if work > MAX_PAINT_TEXELS {
return Err(BakeError::Invalid(format!(
"this stroke would visit {work} texels (limit {MAX_PAINT_TEXELS}); use a smaller radius, a smaller map or a shorter stroke"
)));
}
for c in dabs {
let (x0, x1, y0, y1) = span(c);
for y in y0..y1 {
let dv = (1.0 - (y as f32 + 0.5) / h as f32) - c.y;
for x in x0..x1 {
let du = (x as f32 + 0.5) / w as f32 - c.x;
let t = (du * du + dv * dv).sqrt() / radius;
if t >= 1.0 {
continue;
}
let fall = if t <= hardness {
1.0
} else {
let k = (1.0 - t) / (1.0 - hardness);
k * k * (3.0 - 2.0 * k)
};
if let Some(v) = self.values.get_mut(y * w + x) {
*v += (value - *v) * fall * strength;
}
}
}
}
Ok(())
}
/// The map at atlas `uv`: bilinear, edges clamped.
pub(crate) fn at(&self, uv: Vec2) -> f32 {
let (w, h) = (self.width.max(1) as usize, self.height.max(1) as usize);
if !uv.is_finite() {
return 0.0;
}
let x = (uv.x.clamp(0.0, 1.0) * w as f32 - 0.5).clamp(0.0, w as f32 - 1.0);
let y = ((1.0 - uv.y).clamp(0.0, 1.0) * h as f32 - 0.5).clamp(0.0, h as f32 - 1.0);
let (x0, y0) = (x.floor() as usize, y.floor() as usize);
let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
let (fx, fy) = (x - x0 as f32, y - y0 as f32);
let v = |xx: usize, yy: usize| self.values.get(yy * w + xx).copied().unwrap_or(0.0);
let top = v(x0, y0) * (1.0 - fx) + v(x1, y0) * fx;
let bottom = v(x0, y1) * (1.0 - fx) + v(x1, y1) * fx;
(top * (1.0 - fy) + bottom * fy).clamp(0.0, 1.0)
}
}
/// A skew map ready for a bake: the map plus what edge protection needs.
pub(crate) struct Prepared<'a> {
map: &'a SkewMap,
/// Per triangle, which of its edges (v0-v1, v1-v2, v2-v0) are hard; only with edge protection.
hard: Vec<[bool; 3]>,
diag: f32,
}
impl<'a> Prepared<'a> {
pub(crate) fn new(map: &'a SkewMap, mesh: &Mesh, diag: f32) -> Result<Prepared<'a>, BakeError> {
map.validate()?;
let hard = if map.edge_distance > 0.0 { hard_edges(mesh) } else { Vec::new() };
Ok(Prepared { map, hard, diag })
}
/// The ray direction `up` (unit, away from the surface) at the low-poly sample `s` turned
/// towards its base normal: the interpolated vertex normal, or the flat one per triangle.
pub(crate) fn correct(&self, mesh: &Mesh, s: &Surface, up: Vec3) -> Vec3 {
let amount = self.map.at(s.uv);
if amount <= 0.0 {
return up;
}
let protect = match (self.hard.get(s.tri as usize), mesh.tri(s.tri as usize)) {
(Some(edges), Some(c)) => {
let near = (0..3)
.filter(|&k| edges[k])
.filter_map(|k| {
let a = mesh.positions.get(*c.get(k)?)?;
let b = mesh.positions.get(*c.get((k + 1) % 3)?)?;
Some(segment_distance(s.pos, *a, *b))
})
.fold(f32::INFINITY, f32::min);
(near / (self.map.edge_distance * self.diag).max(1e-9)).clamp(0.0, 1.0).powf(self.map.edge_contrast)
}
_ => 1.0,
};
let base = if self.map.per_triangle { s.geo_nrm } else { s.nrm };
let t = amount * protect;
(up * (1.0 - t) + base * t).try_normalize().unwrap_or(up)
}
}
/// Per triangle, which edges are hard: shared with a triangle whose face normal is more than
/// about 30 degrees away. Edges are matched by position, so split vertices still pair up.
fn hard_edges(mesh: &Mesh) -> Vec<[bool; 3]> {
let pt = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO);
let key = |i: usize| mesh.positions.get(i).map_or([0; 3], |p| p.to_array().map(|c| (c + 0.0).to_bits()));
let ordered = |a: [u32; 3], b: [u32; 3]| if a <= b { (a, b) } else { (b, a) };
let count = mesh.triangle_count();
let mut face = vec![Vec3::ZERO; count];
let mut edges: HashMap<([u32; 3], [u32; 3]), Vec<usize>> = HashMap::new();
for (t, f) in face.iter_mut().enumerate() {
let Some(c) = mesh.tri(t) else { continue };
*f = (pt(c[1]) - pt(c[0])).cross(pt(c[2]) - pt(c[0])).try_normalize().unwrap_or(Vec3::ZERO);
for k in 0..3 {
edges.entry(ordered(key(c[k]), key(c[(k + 1) % 3]))).or_default().push(t);
}
}
(0..count)
.map(|t| {
let mut out = [false; 3];
if let Some(c) = mesh.tri(t) {
let own = face.get(t).copied().unwrap_or(Vec3::ZERO);
for (k, hard) in out.iter_mut().enumerate() {
let others = edges.get(&ordered(key(c[k]), key(c[(k + 1) % 3])));
*hard = others.is_some_and(|ts| ts.iter().any(|&o| o != t && face.get(o).is_some_and(|f| f.dot(own) < HARD_EDGE_COS)));
}
}
out
})
.collect()
}
/// Distance from `p` to the segment `a`-`b`.
fn segment_distance(p: Vec3, a: Vec3, b: Vec3) -> f32 {
let ab = b - a;
let len2 = ab.length_squared();
let t = if len2 > 1e-20 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
(p - (a + ab * t)).length()
}
#[cfg(test)]
use crate::BakePaintMap;
pub(crate) use prepared_skew::PreparedSkew;
#[cfg(test)]
mod tests {
use super::prepared_skew::{hard_edges, segment_distance};
use super::*;
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{Mesh, Surface};
fn fold() -> Mesh {
// Two triangles folded 90 degrees along (0,0,0)-(1,0,0), and a third continuing flat.
Mesh { positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z, Vec3::new(1.0, 1.0, 0.0)], indices: vec![0, 1, 2, 0, 3, 1, 1, 4, 2], ..Mesh::default() }
}
@@ -270,19 +28,19 @@ mod tests {
#[test]
fn maps_sample_bilinearly_and_bad_ones_are_refused() {
let map = SkewMap { width: 2, height: 1, values: vec![0.0, 1.0], ..SkewMap::constant(0.0) };
let map = BakePaintMap { width: 2, height: 1, values: vec![0.0, 1.0] };
assert!(map.validate().is_ok());
assert!(
map.at(Vec2::new(0.0, 0.5)).abs() < 1e-6 && (map.at(Vec2::new(1.0, 0.5)) - 1.0).abs() < 1e-6 && (map.at(Vec2::new(0.5, 0.5)) - 0.5).abs() < 1e-6
map.sample(Vec2::new(0.0, 0.5)).abs() < 1e-6
&& (map.sample(Vec2::new(1.0, 0.5)) - 1.0).abs() < 1e-6
&& (map.sample(Vec2::new(0.5, 0.5)) - 0.5).abs() < 1e-6
);
assert!(map.at(Vec2::new(-3.0, 9.0)).is_finite() && map.at(Vec2::new(f32::NAN, 0.0)) == 0.0);
assert!(map.sample(Vec2::new(-3.0, 9.0)).is_finite() && map.sample(Vec2::new(f32::NAN, 0.0)) == 0.0);
for bad in [
SkewMap { values: vec![0.0], ..map.clone() },
SkewMap { width: 0, values: vec![], ..map.clone() },
SkewMap { values: vec![0.0, f32::NAN], ..map.clone() },
SkewMap { edge_distance: -1.0, ..map.clone() },
SkewMap { edge_contrast: 0.0, ..map.clone() },
SkewMap { width: u32::MAX, height: u32::MAX, ..map.clone() },
BakePaintMap { values: vec![0.0], ..map.clone() },
BakePaintMap { width: 0, values: vec![], ..map.clone() },
BakePaintMap { values: vec![0.0, f32::NAN], ..map.clone() },
BakePaintMap { width: u32::MAX, height: u32::MAX, ..map.clone() },
] {
assert!(bad.validate().is_err());
}
@@ -293,50 +51,51 @@ mod tests {
let mesh = fold();
let up = Vec3::new(0.6, 0.8, 0.0);
let base = Vec3::Y;
let go = |map: &SkewMap, pos: Vec3| {
let go = |map: &BakePaintMap, pos: Vec3, edge_distance: f32| {
let s = Surface { pos, nrm: base, geo_nrm: base, tangent: Default::default(), uv: Vec2::splat(0.5), tri: 0 };
Prepared::new(map, &mesh, 1.0).unwrap().correct(&mesh, &s, up)
PreparedSkew::new(
map,
&mesh,
1.0,
texturecraft_core::SkewSettings { edge_protection: edge_distance > 0.0, edge_distance, edge_contrast: 1.0, ..Default::default() },
)
.unwrap()
.correct(&mesh, &s, up)
};
assert!((go(&SkewMap::constant(0.0), Vec3::ZERO) - up).length() < 1e-6, "black leaves the ray alone");
assert!((go(&SkewMap::constant(1.0), Vec3::ZERO) - base).length() < 1e-6, "white turns it onto the base normal");
let half = go(&SkewMap::constant(0.5), Vec3::ZERO);
assert!((go(&BakePaintMap::constant(0.0), Vec3::ZERO, 0.0) - up).length() < 1e-6, "black leaves the ray alone");
assert!((go(&BakePaintMap::constant(1.0), Vec3::ZERO, 0.0) - base).length() < 1e-6, "white turns it onto the base normal");
let half = go(&BakePaintMap::constant(0.5), Vec3::ZERO, 0.0);
assert!(half.x > 0.0 && half.x < up.x && (half.length() - 1.0).abs() < 1e-5, "grey is in between and still unit: {half}");
// Triangle 0's edge (0,0,0)-(1,0,0) is hard: on it the correction is held back, far from it it is not.
let guarded = SkewMap { edge_distance: 0.5, ..SkewMap::constant(1.0) };
assert!((go(&guarded, Vec3::new(0.5, 0.0, 0.0)) - up).length() < 1e-6, "on the hard edge the ray stays on the cage direction");
assert!((go(&guarded, Vec3::new(0.3, 0.9, 0.0)) - base).length() < 1e-6, "away from every hard edge the correction is full");
let guarded = BakePaintMap::constant(1.0);
assert!((go(&guarded, Vec3::new(0.5, 0.0, 0.0), 0.5) - up).length() < 1e-6, "on the hard edge the ray stays on the cage direction");
assert!((go(&guarded, Vec3::new(0.3, 0.9, 0.0), 0.5) - base).length() < 1e-6, "away from every hard edge the correction is full");
}
#[test]
fn painting_blends_dabs_in_and_resizing_keeps_the_picture() {
let mut map = SkewMap::constant(0.0).resized(64, 64).unwrap();
let mut map = BakePaintMap::constant(0.0).resized(64, 64).unwrap();
assert!(map.values.iter().all(|v| *v == 0.0));
// One hard dab at the centre: white inside, untouched outside, in between at the rim.
map.paint(&[Vec2::new(0.5, 0.5)], 0.2, 1.0, 1.0, 1.0).unwrap();
let at = |m: &SkewMap, u: f32, v: f32| m.at(Vec2::new(u, v));
let at = |m: &BakePaintMap, u: f32, v: f32| m.sample(Vec2::new(u, v));
assert!(at(&map, 0.5, 0.5) > 0.99 && at(&map, 0.95, 0.95) == 0.0, "{} {}", at(&map, 0.5, 0.5), at(&map, 0.95, 0.95));
// Strength blends one dab in part of the way; a stroke's overlapping dabs build up towards the value; v is up.
let mut dab = SkewMap::constant(0.0).resized(64, 64).unwrap();
let mut dab = BakePaintMap::constant(0.0).resized(64, 64).unwrap();
dab.paint(&[Vec2::new(0.5, 0.5)], 0.1, 0.8, 1.0, 0.5).unwrap();
assert!((at(&dab, 0.5, 0.5) - 0.4).abs() < 0.02, "{}", at(&dab, 0.5, 0.5));
let mut line = SkewMap::constant(0.0).resized(64, 64).unwrap();
let mut line = BakePaintMap::constant(0.0).resized(64, 64).unwrap();
line.paint(&[Vec2::new(0.1, 0.9), Vec2::new(0.9, 0.9)], 0.05, 0.5, 1.0, 0.5).unwrap();
assert!(at(&line, 0.5, 0.9) > 0.45 && at(&line, 0.5, 0.9) <= 0.5 + 1e-4, "{}", at(&line, 0.5, 0.9));
assert!(at(&line, 0.5, 0.1) == 0.0, "the other end of v is untouched");
// Erasing (value 0) brings a painted area back down.
map.paint(&[Vec2::new(0.5, 0.5)], 0.2, 0.0, 1.0, 1.0).unwrap();
assert!(at(&map, 0.5, 0.5) < 0.01);
// Resampling keeps the picture and the edge settings.
let mut small = SkewMap { edge_distance: 0.1, ..SkewMap::constant(0.0).resized(8, 8).unwrap() };
let mut small = BakePaintMap::constant(0.0).resized(8, 8).unwrap();
small.paint(&[Vec2::new(0.25, 0.75)], 0.2, 1.0, 1.0, 1.0).unwrap();
let big = small.resized(32, 32).unwrap();
assert_eq!(big.edge_distance, 0.1);
assert!((at(&big, 0.25, 0.75) - at(&small, 0.25, 0.75)).abs() < 0.1 && at(&big, 0.9, 0.1) == 0.0);
}
#[test]
fn hostile_brushes_are_refused_and_change_nothing() {
let mut map = SkewMap::constant(0.3).resized(16, 16).unwrap();
let mut map = BakePaintMap::constant(0.3).resized(16, 16).unwrap();
let before = map.clone();
let c = [Vec2::new(0.5, 0.5)];
for (pts, r, v) in
@@ -344,17 +103,15 @@ mod tests {
{
assert!(map.paint(pts, r, v, 0.5, 1.0).is_err(), "{pts:?} {r} {v}");
}
// Points far outside the atlas are harmless; a huge stroke is refused before any dab lands.
map.paint(&[Vec2::new(1e6, -1e6)], 0.1, 1.0, 0.5, 1.0).unwrap();
assert_eq!(map, before);
assert!(map.paint(&[Vec2::ZERO, Vec2::new(1e6, 1e6)], 1e-4, 1.0, 0.5, 1.0).is_err());
assert_eq!(map, before);
// A big brush over a big map is refused up front, whatever the dab count: one dab here covers 16.7 M texels.
let mut big = SkewMap::constant(0.0).resized(4096, 4096).unwrap();
let mut big = BakePaintMap::constant(0.0).resized(4096, 4096).unwrap();
let untouched = big.clone();
assert!(big.paint(&[Vec2::splat(0.5); 8], 1.0, 1.0, 0.5, 1.0).is_err());
assert_eq!(big, untouched, "nothing was painted before the refusal");
assert!(big.paint(&[Vec2::splat(0.5)], 1.0, 1.0, 0.5, 1.0).is_ok(), "one such dab is within the budget");
assert!(SkewMap::constant(0.0).resized(0, 4).is_err() && SkewMap::constant(0.0).resized(100_000, 100_000).is_err());
assert!(BakePaintMap::constant(0.0).resized(0, 4).is_err() && BakePaintMap::constant(0.0).resized(100_000, 100_000).is_err());
}
}
+92
View File
@@ -0,0 +1,92 @@
use crate::BakeError;
use crate::BakePaintMap;
use std::collections::HashMap;
use texturecraft_core::{SkewCorrectionMethod, SkewSettings};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Mesh, Surface};
const HARD_EDGE_COS: f32 = 0.866;
pub(crate) struct PreparedSkew<'a> {
map: &'a BakePaintMap,
settings: SkewSettings,
hard: Vec<[bool; 3]>,
mesh_scale: f32,
}
impl<'a> PreparedSkew<'a> {
pub(crate) fn new(map: &'a BakePaintMap, mesh: &Mesh, mesh_scale: f32, settings: SkewSettings) -> Result<PreparedSkew<'a>, BakeError> {
map.validate()?;
let hard = if settings.edge_protection && settings.edge_distance > 0.0 { hard_edges(mesh) } else { Vec::new() };
Ok(PreparedSkew { map, settings, hard, mesh_scale })
}
pub(crate) fn correct(&self, mesh: &Mesh, surface: &Surface, up: Vec3) -> Vec3 {
let amount = self.map.sample(surface.uv);
if amount <= 0.0 {
return up;
}
let protection = match (self.hard.get(surface.tri as usize), mesh.tri(surface.tri as usize)) {
(Some(edges), Some(corners)) => {
let nearest_edge_distance = (0..3)
.filter(|&edge_index| edges[edge_index])
.filter_map(|edge_index| {
let edge_start = mesh.positions.get(*corners.get(edge_index)?)?;
let edge_end = mesh.positions.get(*corners.get((edge_index + 1) % 3)?)?;
Some(segment_distance(surface.pos, *edge_start, *edge_end))
})
.fold(f32::INFINITY, f32::min);
(nearest_edge_distance / (self.settings.edge_distance * self.mesh_scale).max(1e-9)).clamp(0.0, 1.0).powf(self.settings.edge_contrast.max(1e-6))
}
_ => 1.0,
};
let base = match self.settings.method {
SkewCorrectionMethod::MeshNormalsBased => surface.nrm,
SkewCorrectionMethod::FaceNormalsBased => {
if surface.geo_nrm.dot(surface.nrm) < 0.0 {
-surface.geo_nrm
} else {
surface.geo_nrm
}
}
};
let blend = amount * protection;
(up * (1.0 - blend) + base * blend).try_normalize().unwrap_or(up)
}
}
pub(super) fn hard_edges(mesh: &Mesh) -> Vec<[bool; 3]> {
let pt = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO);
let key = |i: usize| mesh.positions.get(i).map_or([0; 3], |p| p.to_array().map(|c| (c + 0.0).to_bits()));
let ordered = |a: [u32; 3], b: [u32; 3]| if a <= b { (a, b) } else { (b, a) };
let count = mesh.triangle_count();
let mut face = vec![Vec3::ZERO; count];
let mut edges: HashMap<([u32; 3], [u32; 3]), Vec<usize>> = HashMap::new();
for (t, f) in face.iter_mut().enumerate() {
let Some(c) = mesh.tri(t) else { continue };
*f = (pt(c[1]) - pt(c[0])).cross(pt(c[2]) - pt(c[0])).try_normalize().unwrap_or(Vec3::ZERO);
for k in 0..3 {
edges.entry(ordered(key(c[k]), key(c[(k + 1) % 3]))).or_default().push(t);
}
}
(0..count)
.map(|t| {
let mut out = [false; 3];
if let Some(c) = mesh.tri(t) {
let own = face.get(t).copied().unwrap_or(Vec3::ZERO);
for (k, hard) in out.iter_mut().enumerate() {
let others = edges.get(&ordered(key(c[k]), key(c[(k + 1) % 3])));
*hard = others.is_some_and(|ts| ts.iter().any(|&o| o != t && face.get(o).is_some_and(|f| f.dot(own) < HARD_EDGE_COS)));
}
}
out
})
.collect()
}
pub(super) fn segment_distance(p: Vec3, a: Vec3, b: Vec3) -> f32 {
let ab = b - a;
let len2 = ab.length_squared();
let t = if len2 > 1e-20 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
(p - (a + ab * t)).length()
}
+199
View File
@@ -0,0 +1,199 @@
use super::*;
use texturecraft_core::{
AmbientOcclusionAttenuation, HeightNormalization, IdColorSource, MeshMatchMode, PositionAxis, PositionNormalizationScale, ThicknessNormalization,
};
#[test]
fn rectangular_bakes_and_diffusion_preserve_surface_pixels() {
let mut mesh = quad();
for uv in &mut mesh.uvs {
uv.x *= 0.5;
}
let mut parameters = settings(64, &[BakedMap::Position]);
parameters.common.resolution_height = Some(BakeResolution::R32);
let plain = run(&mesh, &parameters).unwrap();
assert_eq!((plain.resolution, plain.height), (64, 32));
assert_eq!(plain.maps[&BakedMap::Position].len(), 64 * 32 * 3);
parameters.common.apply_diffusion = true;
let diffused = run(&mesh, &parameters).unwrap();
for row in 0..32 {
let covered = row * 64 * 3..(row * 64 + 32) * 3;
assert_eq!(plain.maps[&BakedMap::Position][covered.clone()], diffused.maps[&BakedMap::Position][covered]);
}
let background = (20 * 64 + 50) * 3;
assert_eq!(plain.maps[&BakedMap::Position][background], 0.0);
assert!(diffused.maps[&BakedMap::Position][background] > 0.0);
}
#[test]
fn matching_skips_a_closer_unrelated_high_mesh_and_backfaces() {
let mut low = quad();
low.submeshes[0].name = "Panel_low".into();
let mut high = quad();
high.submeshes[0].name = "Panel_high".into();
high.positions.iter_mut().for_each(|position| position.y = 0.02);
let mut unrelated = quad();
unrelated.submeshes[0].name = "Other_high".into();
unrelated.positions.iter_mut().for_each(|position| position.y = 0.04);
high.append(&unrelated);
let mut parameters = settings(16, &[BakedMap::Height]);
parameters.cage.max_frontal = 0.1;
parameters.cage.relative_to_bounding_box = false;
parameters.maps.height.parameters.normalization = HeightNormalization::Manual;
let height = |parameters: &BakeSettings, high: &Mesh| transfer(&low, high, None, parameters).unwrap().maps[&BakedMap::Height][128];
assert!((height(&parameters, &high) - 0.54).abs() < 1e-5);
parameters.high_poly.match_mode = MeshMatchMode::ByMeshName;
assert!((height(&parameters, &high) - 0.52).abs() < 1e-5);
for triangle in high.indices.chunks_exact_mut(3) {
triangle.swap(1, 2);
}
assert_eq!(height(&parameters, &high), 0.5);
parameters.high_poly.ignore_backface = false;
assert!((height(&parameters, &high) - 0.52).abs() < 1e-5);
}
#[test]
fn occlusion_honors_minimum_distance_units_attenuation_and_named_backfaces() {
let mut mesh = quad();
let mut ceiling = quad();
ceiling.positions.iter_mut().for_each(|position| position.y = 0.1);
ceiling.submeshes[0].name = "Roof_ignorebf".into();
mesh.append(&ceiling);
let mut parameters = settings(16, &[BakedMap::AmbientOcclusion]);
parameters.maps.ao.parameters.rays =
RaySettings { rays: 1, spread: 0.0, min_distance: 0.0, max_distance: 1.0, relative_to_bounding_box: false, ..Default::default() };
let value = |parameters: &BakeSettings| run(&mesh, parameters).unwrap().maps[&BakedMap::AmbientOcclusion][128];
parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::None;
assert_eq!(value(&parameters), 0.0);
parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::Linear;
assert!((value(&parameters) - 0.1).abs() < 1e-4);
parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::Smooth;
assert!((value(&parameters) - 0.028).abs() < 1e-4);
parameters.maps.ao.parameters.rays.min_distance = 0.15;
assert_eq!(value(&parameters), 1.0);
parameters.maps.ao.parameters.rays.min_distance = 0.0;
parameters.maps.ao.parameters.rays.max_distance = 0.075;
assert_eq!(value(&parameters), 1.0);
parameters.maps.ao.parameters.rays.relative_to_bounding_box = true;
assert!(value(&parameters) < 0.8);
parameters.maps.ao.parameters.ignore_backface = BackfaceMode::ByMeshName;
assert_eq!(value(&parameters), 1.0);
parameters.maps.ao.parameters.ignore_backface = BackfaceMode::Never;
parameters.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName;
assert_eq!(value(&parameters), 1.0);
}
#[test]
fn bent_normal_settings_are_independent_of_ambient_occlusion() {
let mesh = primitives::material_ball();
let mut parameters = settings(32, &[BakedMap::BentNormal, BakedMap::AmbientOcclusion]);
let original = run(&mesh, &parameters).unwrap();
parameters.maps.ao.parameters.ignore_backface = BackfaceMode::Always;
parameters.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName;
parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::None;
let changed = run(&mesh, &parameters).unwrap();
assert_eq!(original.maps[&BakedMap::BentNormal], changed.maps[&BakedMap::BentNormal]);
}
#[test]
fn id_sources_keep_material_color_separate_from_vertex_color_and_textures() {
let low = quad();
let mut high = quad();
high.colors = vec![Vec4::new(0.8, 0.1, 0.3, 1.0); high.vertex_count()];
let colors = vec![Some(Arc::new(BaseColor { factor: Vec4::new(0.2, 0.4, 0.7, 1.0), width: 1, height: 1, texels: vec![[255, 0, 0, 255]] }))];
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high));
let mut parameters = settings(16, &[BakedMap::Id]);
for (source, expected) in [(IdColorSource::MaterialColor, [0.2, 0.4, 0.7]), (IdColorSource::VertexColor, [0.8, 0.1, 0.3])] {
parameters.maps.id.parameters.source = source;
let request = BakeRequest {
low_base_color: &[],
mesh: &low,
bvh: &low_bvh,
material: 0,
settings: &parameters,
high: Some(HighPoly { mesh: &high, bvh: &high_bvh, base_color: &colors, file_ids: &[0] }),
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
let output = bake(&request, &Progress::new()).unwrap();
for (value, expected) in output.maps[&BakedMap::Id][128 * 3..129 * 3].iter().zip(expected) {
assert!((value - expected).abs() < 1e-6);
}
}
}
#[test]
fn painted_cage_limits_frontal_projection() {
let low = quad();
let mut high = quad();
high.positions.iter_mut().for_each(|position| position.y = 0.08);
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high));
let mut parameters = settings(16, &[BakedMap::Opacity]);
parameters.cage.max_frontal = 0.1;
parameters.cage.relative_to_bounding_box = false;
let reduced = BakePaintMap::constant(0.5);
let mut request = BakeRequest {
low_base_color: &[],
mesh: &low,
bvh: &low_bvh,
material: 0,
settings: &parameters,
high: Some(HighPoly { mesh: &high, bvh: &high_bvh, base_color: &[], file_ids: &[] }),
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
assert_eq!(bake(&request, &Progress::new()).unwrap().maps[&BakedMap::Opacity][128], 1.0);
request.cage_paint = Some(&reduced);
assert_eq!(bake(&request, &Progress::new()).unwrap().maps[&BakedMap::Opacity][128], 0.0);
}
#[test]
fn position_axis_and_material_bounds_change_only_the_requested_space() {
let mut mesh = quad();
let mut distant = quad();
distant.positions.iter_mut().for_each(|position| position.x += 10.0);
mesh.append(&distant);
let mut parameters = settings(16, &[BakedMap::Position]);
parameters.maps.position.parameters.axis = PositionAxis::X;
let global = run(&mesh, &parameters).unwrap();
parameters.maps.position.parameters.scale = PositionNormalizationScale::PerMaterial;
let local = run(&mesh, &parameters).unwrap();
assert!(global.maps[&BakedMap::Position].iter().all(|value| *value < 0.2));
assert!(local.maps[&BakedMap::Position].iter().any(|value| *value > 0.9));
assert!(local.maps[&BakedMap::Position].chunks_exact(3).all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
}
#[test]
fn curvature_radius_and_manual_bounds_control_edge_response() {
let mesh = primitives::cube(2.0);
let mut parameters = settings(64, &[BakedMap::Curvature]);
let narrow = run(&mesh, &parameters).unwrap();
parameters.maps.curvature.parameters.mesh.sampling_radius *= 4.0;
let wide = run(&mesh, &parameters).unwrap();
let edge_count = |output: &BakeOutput| covered_values(&mesh, output, BakedMap::Curvature).iter().filter(|(_, value)| *value > 0.6).count();
assert!(edge_count(&wide) > edge_count(&narrow));
parameters.maps.curvature.parameters.mesh.value_min = -2.0;
parameters.maps.curvature.parameters.mesh.value_max = 2.0;
let reduced = run(&mesh, &parameters).unwrap();
assert!(reduced.maps[&BakedMap::Curvature].iter().all(|value| (0.25..=0.75).contains(value)));
}
#[test]
fn thickness_can_preserve_distance_or_normalize_each_tile() {
let mesh = primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0);
let mut parameters = settings(32, &[BakedMap::Thickness]);
parameters.maps.thickness.parameters.normalization = ThicknessNormalization::None;
parameters.maps.thickness.parameters.rays.relative_to_bounding_box = false;
parameters.maps.thickness.parameters.rays.max_distance = 0.3;
let distance = run(&mesh, &parameters).unwrap();
assert!(covered_values(&mesh, &distance, BakedMap::Thickness).iter().all(|(_, value)| *value <= 0.30001));
parameters.maps.thickness.parameters.normalization = ThicknessNormalization::RelativeToMinMax;
let normalized = run(&mesh, &parameters).unwrap();
let values = covered_values(&mesh, &normalized, BakedMap::Thickness);
assert!(values.iter().any(|(_, value)| *value == 0.0));
assert!(values.iter().any(|(_, value)| *value == 1.0));
}
+695 -240
View File
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
mod cpu_scene;
mod cpu_tracer;
mod hemisphere;
mod query;
mod ray;
mod ray_kind;
mod ray_scene;
mod trace_mesh;
mod tracer;
pub use cpu_tracer::CpuTracer;
pub use hemisphere::Hemisphere;
pub use query::Query;
pub use ray::Ray;
pub use ray_kind::RayKind;
pub use ray_scene::RayScene;
pub use trace_mesh::TraceMesh;
pub use tracer::Tracer;
/// Part key that disables triangle filtering
pub const ANY: u32 = u32::MAX;
+34
View File
@@ -0,0 +1,34 @@
use super::{ANY, Hemisphere, Query, Ray, RayScene, TraceMesh};
use crate::BakeError;
use rayon::prelude::*;
use texturecraft_geom::Hit;
pub(super) struct CpuScene<'a>(pub(super) Vec<TraceMesh<'a>>);
impl CpuScene<'_> {
fn mesh(&self, index: usize) -> Result<&TraceMesh<'_>, BakeError> {
self.0.get(index).ok_or_else(|| BakeError::Invalid(format!("no scene mesh {index}")))
}
}
impl RayScene for CpuScene<'_> {
fn closest(&mut self, mesh: usize, rays: &[Ray], ignore_backface: bool) -> Result<Vec<Option<Hit>>, BakeError> {
let trace_mesh = self.mesh(mesh)?;
Ok(rays
.par_iter()
.map(|ray| {
if ray.key == ANY && !ignore_backface {
trace_mesh.bvh.closest(ray.origin, ray.direction, ray.max_distance)
} else {
trace_mesh.bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| {
trace_mesh.key_matches(triangle, ray.key) && !(ignore_backface && trace_mesh.back_facing(triangle, ray.direction))
})
}
})
.collect())
}
fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result<Vec<Vec<[f32; 4]>>, BakeError> {
passes.iter().map(|hemisphere| queries.par_iter().map(|query| Ok(hemisphere.evaluate(self.mesh(query.mesh as usize)?, query))).collect()).collect()
}
}
+16
View File
@@ -0,0 +1,16 @@
use super::cpu_scene::CpuScene;
use super::{RayScene, TraceMesh, Tracer};
use crate::BakeError;
#[derive(Clone, Copy, Debug, Default)]
pub struct CpuTracer;
impl Tracer for CpuTracer {
fn name(&self) -> String {
"CPU".into()
}
fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result<Box<dyn RayScene + 'a>, BakeError> {
Ok(Box::new(CpuScene(meshes.to_vec())))
}
}
+107
View File
@@ -0,0 +1,107 @@
use super::{ANY, Query, RayKind, TraceMesh};
use std::f32::consts::TAU;
use texturecraft_core::{AmbientOcclusionAttenuation, BackfaceMode};
use texturecraft_geom::glam::Vec3;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Hemisphere {
pub kind: RayKind,
pub rays: u32,
/// Maximum ray distance in mesh units
pub dmax: f32,
pub min_distance: f32,
pub attenuation: AmbientOcclusionAttenuation,
pub ground_height: Option<f32>,
/// Ray origin offset along the geometric normal
pub eps: f32,
pub cos_max: f32,
pub sin_max: f32,
pub uniform: bool,
pub ignore_backface: BackfaceMode,
pub same_key: bool,
}
impl Hemisphere {
pub fn direction(&self, (tangent, bitangent, axis): (Vec3, Vec3, Vec3), ray_index: u32, rotation: [f32; 2]) -> Vec3 {
let azimuth_sample = (ray_index as f32 / self.rays as f32 + rotation[0]).fract();
let elevation_sample = (ray_index.reverse_bits() as f32 / 4_294_967_296.0 + rotation[1]).fract();
let (radius, height) = if self.uniform {
let height = 1.0 - elevation_sample * (1.0 - self.cos_max);
((1.0 - height * height).max(0.0).sqrt(), height)
} else {
let radius = self.sin_max * elevation_sample.sqrt();
(radius, (1.0 - radius * radius).max(0.0).sqrt())
};
let azimuth = TAU * azimuth_sample;
tangent * (radius * azimuth.cos()) + bitangent * (radius * azimuth.sin()) + axis * height
}
fn frame(&self, query: &Query) -> (Vec3, Vec3, Vec3) {
let (axis, geometric_normal) = match self.kind {
RayKind::Occlusion => (query.nrm, query.geo),
RayKind::Thickness => (-query.nrm, -query.geo),
};
(axis, geometric_normal, query.pos + geometric_normal * self.eps)
}
pub fn evaluate(&self, mesh: &TraceMesh, query: &Query) -> [f32; 4] {
let (axis, geometric_normal, origin) = self.frame(query);
let (tangent, bitangent) = axis.any_orthonormal_pair();
let key = if self.same_key { query.key } else { ANY };
let filtered = key != ANY || self.ignore_backface != BackfaceMode::Never;
let (mut accumulated, mut bent_normal, mut accepted_ray_count) = (0.0f32, Vec3::ZERO, 0u32);
for ray_index in 0..self.rays {
let direction = self.direction((tangent, bitangent, axis), ray_index, query.rot);
if direction.dot(geometric_normal) <= 0.0 {
continue;
}
let ray_origin = origin + direction * self.min_distance;
let ray_length = (self.dmax - self.min_distance).max(0.0);
let hit = if filtered {
mesh.bvh.closest_filtered(ray_origin, direction, ray_length, &|triangle| {
let ignore_backface = match self.ignore_backface {
BackfaceMode::Never => false,
BackfaceMode::Always => true,
BackfaceMode::ByMeshName => mesh.backface_culling.get(triangle as usize).copied().unwrap_or(false),
};
mesh.key_matches(triangle, key) && !(ignore_backface && mesh.back_facing(triangle, direction))
})
} else {
mesh.bvh.closest(ray_origin, direction, ray_length)
};
let mut distance = hit.map(|hit| hit.t + self.min_distance);
if let Some(height) = self.ground_height.filter(|_| direction.y < -1e-8) {
let ground_distance = (height - origin.y) / direction.y;
if (self.min_distance..=self.dmax).contains(&ground_distance) {
distance = Some(distance.map_or(ground_distance, |distance| distance.min(ground_distance)));
}
}
match self.kind {
RayKind::Occlusion => {
let occlusion = distance.map_or(0.0, |distance| self.occlusion(distance));
accumulated += occlusion;
bent_normal += direction * (1.0 - occlusion);
}
RayKind::Thickness => accumulated += distance.unwrap_or(self.dmax),
}
accepted_ray_count += 1;
}
match self.kind {
RayKind::Occlusion => {
let ambient_occlusion = if accepted_ray_count == 0 { 1.0 } else { (1.0 - accumulated / accepted_ray_count as f32).clamp(0.0, 1.0) };
let bent_normal = bent_normal.try_normalize().unwrap_or(query.nrm);
[ambient_occlusion, bent_normal.x, bent_normal.y, bent_normal.z]
}
RayKind::Thickness => [if accepted_ray_count == 0 { self.dmax } else { accumulated / accepted_ray_count as f32 }, 0.0, 0.0, 0.0],
}
}
fn occlusion(&self, distance: f32) -> f32 {
let fraction = ((distance - self.min_distance) / (self.dmax - self.min_distance).max(f32::EPSILON)).clamp(0.0, 1.0);
match self.attenuation {
AmbientOcclusionAttenuation::None => 1.0,
AmbientOcclusionAttenuation::Linear => 1.0 - fraction,
AmbientOcclusionAttenuation::Smooth => 1.0 - fraction * fraction * (3.0 - 2.0 * fraction),
}
}
}
+11
View File
@@ -0,0 +1,11 @@
use texturecraft_geom::glam::Vec3;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Query {
pub pos: Vec3,
pub nrm: Vec3,
pub geo: Vec3,
pub rot: [f32; 2],
pub key: u32,
pub mesh: u32,
}
+11
View File
@@ -0,0 +1,11 @@
use texturecraft_geom::glam::Vec3;
/// GPU buffer layout; batches upload without repacking
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Ray {
pub origin: Vec3,
pub max_distance: f32,
pub direction: Vec3,
pub key: u32,
}
+5
View File
@@ -0,0 +1,5 @@
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RayKind {
Occlusion,
Thickness,
}
+8
View File
@@ -0,0 +1,8 @@
use super::{Hemisphere, Query, Ray};
use crate::BakeError;
use texturecraft_geom::Hit;
pub trait RayScene: Send {
fn closest(&mut self, mesh: usize, rays: &[Ray], ignore_backface: bool) -> Result<Vec<Option<Hit>>, BakeError>;
fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result<Vec<Vec<[f32; 4]>>, BakeError>;
}
+23
View File
@@ -0,0 +1,23 @@
use super::ANY;
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Bvh, Mesh};
#[derive(Clone, Copy, Debug)]
pub struct TraceMesh<'a> {
pub mesh: &'a Mesh,
pub bvh: &'a Bvh,
/// Part key per triangle in original mesh order
pub keys: &'a [u32],
pub backface_culling: &'a [bool],
}
impl TraceMesh<'_> {
pub(super) fn key_matches(&self, triangle: u32, key: u32) -> bool {
key == ANY || self.keys.get(triangle as usize) == Some(&key)
}
pub(super) fn back_facing(&self, triangle: u32, direction: Vec3) -> bool {
let position = |vertex_index: usize| self.mesh.positions.get(vertex_index).copied().unwrap_or(Vec3::ZERO);
self.mesh.tri(triangle as usize).is_some_and(|[a, b, c]| (position(b) - position(a)).cross(position(c) - position(a)).dot(direction) > 0.0)
}
}
+7
View File
@@ -0,0 +1,7 @@
use super::{RayScene, TraceMesh};
use crate::BakeError;
pub trait Tracer: Send + Sync {
fn name(&self) -> String;
fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result<Box<dyn RayScene + 'a>, BakeError>;
}
+2 -2
View File
@@ -159,7 +159,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) };
for i in 0..TILE_AREA {
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, res).unwrap_or(1.0);
let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, (res, comp.height)).unwrap_or(1.0);
let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0);
let px = &mut out[i * 4..i * 4 + 4];
px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
@@ -175,7 +175,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
let px = &mut out[i * 4..i * 4 + 4];
// The baked normal is the base the painted normal details sit on (as in export).
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
let base = baked.sample(BakedMap::Normal, x, y, res);
let base = baked.sample(BakedMap::Normal, x, y, (res, comp.height));
match (n, base) {
(Some(t), None) => {
for (k, d) in px.iter_mut().take(3).enumerate() {
+2 -2
View File
@@ -1043,7 +1043,7 @@ impl<'a, 'b> Texel<'a, 'b> {
}
fn baked(&self, m: BakedMap) -> Option<f32> {
self.inp.baked.scalar(m, self.x, self.y, self.res)
self.inp.baked.scalar(m, self.x, self.y, (self.res, self.inp.gbuf.height))
}
/// Where projection `proj` samples this texel: the texel's coordinates, or for a decal its
@@ -1179,7 +1179,7 @@ impl<'a, 'b> Texel<'a, 'b> {
v += (val - v) * o;
}
EffectKind::ColorSelection { colors, tolerance } => {
let id = self.inp.baked.sample(BakedMap::Id, self.x, self.y, self.res);
let id = self.inp.baked.sample(BakedMap::Id, self.x, self.y, (self.res, self.inp.gbuf.height));
let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance));
let val = if hit { 1.0 } else { 0.0 };
v += (blend1(e.blend, v, val) - v) * o;
+14 -14
View File
@@ -57,8 +57,7 @@ pub fn decode(kind: ChannelKind, v: u16) -> f32 {
}
/// Baked mesh maps of one texture set (dense, row-major, `components()` floats per texel). The
/// maps cover the texture set's texels at another density: `resolution` wide, and as tall as
/// the set's aspect makes them (square for classic sets, the UV tile grid's aspect otherwise).
/// width is `resolution`; height follows the output size and UV tile grid
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BakedMaps {
/// Width in texels.
@@ -72,20 +71,21 @@ impl BakedMaps {
self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32)
}
/// Sample map `m` at texel (x, y) of an image `res` wide with the same aspect (nearest texel
/// of the bake).
pub fn sample(&self, m: BakedMap, x: u32, y: u32, res: u32) -> Option<[f32; 3]> {
let data = self.maps.get(&m)?;
let r = self.resolution.max(1) as u64;
let (bx, by) = ((x as u64 * r / res.max(1) as u64).min(r - 1), (y as u64 * r / res.max(1) as u64).min(self.height(m).max(1) as u64 - 1));
let comps = m.components();
let i = ((by * r + bx) as usize) * comps;
let s = data.get(i..i + comps)?;
Some(if comps == 3 { [s[0], s[1], s[2]] } else { [s[0]; 3] })
/// Sample the corresponding texel of an image with the supplied output size
pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> {
let data = self.maps.get(&map)?;
let width = u64::from(self.resolution.max(1));
let height = u64::from(self.height(map).max(1));
let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1);
let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1);
let component_count = map.components();
let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?;
let texel = data.get(offset..offset.checked_add(component_count)?)?;
Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] })
}
pub fn scalar(&self, m: BakedMap, x: u32, y: u32, res: u32) -> Option<f32> {
self.sample(m, x, y, res).map(|v| v[0])
pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option<f32> {
self.sample(m, x, y, size).map(|v| v[0])
}
}
+77
View File
@@ -0,0 +1,77 @@
//! Bake model types and component defaults
mod ambient_occlusion_attenuation;
mod ambient_occlusion_settings;
mod backface_mode;
mod bake_antialiasing;
mod bake_paint_target;
mod bake_resolution;
mod bake_settings;
mod mesh_match_mode;
mod skew_correction_method;
pub use bake_paint_target::BakePaintTarget;
mod baked_map;
mod bent_normal_settings;
mod cage_settings;
mod cage_type;
mod common_bake_settings;
mod curvature_method;
mod curvature_settings;
mod ground_plane_settings;
mod height_normalization;
mod height_settings;
mod high_poly_settings;
mod id_color_generator;
mod id_color_source;
mod id_settings;
mod map_settings;
mod mesh_curvature_settings;
mod mesh_map_settings;
mod normal_map_curvature_settings;
mod position_axis;
mod position_mode;
mod position_normalization_scale;
mod position_settings;
mod ray_distribution;
mod ray_settings;
mod self_occlusion;
mod skew_settings;
mod thickness_normalization;
mod thickness_settings;
pub use ambient_occlusion_attenuation::AmbientOcclusionAttenuation;
pub use ambient_occlusion_settings::AmbientOcclusionSettings;
pub use backface_mode::BackfaceMode;
pub use bake_antialiasing::BakeAntialiasing;
pub use bake_resolution::BakeResolution;
pub use bake_settings::BakeSettings;
pub use baked_map::BakedMap;
pub use bent_normal_settings::BentNormalSettings;
pub use cage_settings::CageSettings;
pub use cage_type::CageType;
pub use common_bake_settings::CommonBakeSettings;
pub use curvature_method::CurvatureMethod;
pub use curvature_settings::CurvatureSettings;
pub use ground_plane_settings::GroundPlaneSettings;
pub use height_normalization::HeightNormalization;
pub use height_settings::HeightSettings;
pub use high_poly_settings::HighPolySettings;
pub use id_color_generator::IdColorGenerator;
pub use id_color_source::IdColorSource;
pub use id_settings::IdSettings;
pub use map_settings::MapSettings;
pub use mesh_curvature_settings::MeshCurvatureSettings;
pub use mesh_map_settings::MeshMapSettings;
pub use mesh_match_mode::MeshMatchMode;
pub use normal_map_curvature_settings::NormalMapCurvatureSettings;
pub use position_axis::PositionAxis;
pub use position_mode::PositionMode;
pub use position_normalization_scale::PositionNormalizationScale;
pub use position_settings::PositionSettings;
pub use ray_distribution::RayDistribution;
pub use ray_settings::RaySettings;
pub use self_occlusion::SelfOcclusion;
pub use skew_correction_method::SkewCorrectionMethod;
pub use skew_settings::SkewSettings;
pub use thickness_normalization::ThicknessNormalization;
pub use thickness_settings::ThicknessSettings;
@@ -0,0 +1,9 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum AmbientOcclusionAttenuation {
None,
Smooth,
#[default]
Linear,
}
@@ -0,0 +1,12 @@
use super::{AmbientOcclusionAttenuation, BackfaceMode, GroundPlaneSettings, RaySettings, SelfOcclusion};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct AmbientOcclusionSettings {
pub rays: RaySettings,
pub ignore_backface: BackfaceMode,
pub self_occlusion: SelfOcclusion,
pub attenuation: AmbientOcclusionAttenuation,
pub ground_plane: GroundPlaneSettings,
}
+9
View File
@@ -0,0 +1,9 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum BackfaceMode {
#[default]
Never,
Always,
ByMeshName,
}
+27
View File
@@ -0,0 +1,27 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum BakeAntialiasing {
#[default]
None,
Subsampling2x2,
Subsampling4x4,
Subsampling8x8,
}
impl BakeAntialiasing {
pub const ALL: [Self; 4] = [Self::None, Self::Subsampling2x2, Self::Subsampling4x4, Self::Subsampling8x8];
pub fn samples_per_axis(self) -> u32 {
match self {
Self::None => 1,
Self::Subsampling2x2 => 2,
Self::Subsampling4x4 => 4,
Self::Subsampling8x8 => 8,
}
}
pub fn from_samples_per_axis(samples: u32) -> Option<Self> {
Self::ALL.into_iter().find(|antialiasing| antialiasing.samples_per_axis() == samples)
}
}
@@ -0,0 +1,8 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum BakePaintTarget {
Cage,
#[default]
Skew,
}
+39
View File
@@ -0,0 +1,39 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum BakeResolution {
R16,
R32,
R64,
R128,
R256,
R512,
R1024,
#[default]
R2048,
R4096,
R8192,
}
impl BakeResolution {
pub const ALL: [Self; 10] = [Self::R16, Self::R32, Self::R64, Self::R128, Self::R256, Self::R512, Self::R1024, Self::R2048, Self::R4096, Self::R8192];
pub fn pixels(self) -> u32 {
match self {
Self::R16 => 16,
Self::R32 => 32,
Self::R64 => 64,
Self::R128 => 128,
Self::R256 => 256,
Self::R512 => 512,
Self::R1024 => 1024,
Self::R2048 => 2048,
Self::R4096 => 4096,
Self::R8192 => 8192,
}
}
pub fn from_pixels(pixels: u32) -> Option<Self> {
Self::ALL.into_iter().find(|resolution| resolution.pixels() == pixels)
}
}
+13
View File
@@ -0,0 +1,13 @@
use super::{CageSettings, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings};
use serde::{Deserialize, Serialize};
/// Persisted clean-room bake settings, grouped by the controls they belong to
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct BakeSettings {
pub common: CommonBakeSettings,
pub high_poly: HighPolySettings,
pub cage: CageSettings,
pub skew: SkewSettings,
pub maps: MeshMapSettings,
}
+82
View File
@@ -0,0 +1,82 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum BakedMap {
Normal,
WorldNormal,
Id,
AmbientOcclusion,
Curvature,
Position,
Thickness,
Height,
/// World-space direction of least occlusion (packed like the world-space normal)
BentNormal,
/// High-poly coverage times vertex and material alpha
Opacity,
}
impl BakedMap {
pub const ALL: [BakedMap; 10] = [
BakedMap::Normal,
BakedMap::WorldNormal,
BakedMap::Id,
BakedMap::AmbientOcclusion,
BakedMap::Curvature,
BakedMap::Position,
BakedMap::Thickness,
BakedMap::Height,
BakedMap::BentNormal,
BakedMap::Opacity,
];
/// Mesh-map identifier shared with MaterialCraft
pub fn id(self) -> &'static str {
match self {
BakedMap::Normal => "normal",
BakedMap::WorldNormal => "worldNormal",
BakedMap::Id => "id",
BakedMap::AmbientOcclusion => "ambientOcclusion",
BakedMap::Curvature => "curvature",
BakedMap::Position => "position",
BakedMap::Thickness => "thickness",
BakedMap::Height => "height",
BakedMap::BentNormal => "bentNormal",
BakedMap::Opacity => "opacity",
}
}
/// Components stored (3 for vector maps, 1 for scalar maps)
pub fn components(self) -> usize {
match self {
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Id | BakedMap::Position | BakedMap::BentNormal => 3,
_ => 1,
}
}
/// Value where nothing was baked (uncovered texels, missing maps)
pub fn neutral(self) -> [f32; 3] {
match self {
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::BentNormal => [0.5, 0.5, 1.0],
BakedMap::AmbientOcclusion | BakedMap::Thickness => [1.0; 3],
BakedMap::Curvature | BakedMap::Height => [0.5; 3],
BakedMap::Id | BakedMap::Position | BakedMap::Opacity => [0.0; 3],
}
}
pub fn parse(identifier: &str) -> Option<BakedMap> {
match identifier {
"normal" => Some(BakedMap::Normal),
"worldNormal" => Some(BakedMap::WorldNormal),
"id" => Some(BakedMap::Id),
"ambientOcclusion" => Some(BakedMap::AmbientOcclusion),
"curvature" => Some(BakedMap::Curvature),
"position" => Some(BakedMap::Position),
"thickness" => Some(BakedMap::Thickness),
"height" => Some(BakedMap::Height),
"bentNormal" => Some(BakedMap::BentNormal),
"opacity" => Some(BakedMap::Opacity),
_ => None,
}
}
}
@@ -0,0 +1,10 @@
use super::{BackfaceMode, RaySettings, SelfOcclusion};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct BentNormalSettings {
pub rays: RaySettings,
pub ignore_backface: BackfaceMode,
pub self_occlusion: SelfOcclusion,
}
+19
View File
@@ -0,0 +1,19 @@
use super::CageType;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct CageSettings {
pub kind: CageType,
/// Distance-based cage offsets (slider range 0..=0.05)
pub max_frontal: f32,
pub max_rear: f32,
pub relative_to_bounding_box: bool,
pub average_normals: bool,
}
impl Default for CageSettings {
fn default() -> Self {
Self { kind: CageType::DistanceBased, max_frontal: 0.01, max_rear: 0.01, relative_to_bounding_box: true, average_normals: true }
}
}
+8
View File
@@ -0,0 +1,8 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum CageType {
#[default]
DistanceBased,
CustomFile,
}
@@ -0,0 +1,34 @@
use super::{BakeAntialiasing, BakeResolution};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct CommonBakeSettings {
pub is_enabled: bool,
pub resolution: BakeResolution,
/// None locks both axes to the same resolution
pub resolution_height: Option<BakeResolution>,
pub antialiasing: BakeAntialiasing,
/// Padding width in pixels (0..=128)
pub dilation: u32,
pub apply_diffusion: bool,
}
impl Default for CommonBakeSettings {
fn default() -> Self {
Self {
is_enabled: true,
resolution: BakeResolution::R2048,
resolution_height: None,
antialiasing: BakeAntialiasing::None,
dilation: 1,
apply_diffusion: true,
}
}
}
impl CommonBakeSettings {
pub fn output_size(&self) -> (u32, u32) {
(self.resolution.pixels(), self.resolution_height.unwrap_or(self.resolution).pixels())
}
}
+8
View File
@@ -0,0 +1,8 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum CurvatureMethod {
#[default]
NormalMap,
Mesh,
}
@@ -0,0 +1,16 @@
use super::{CurvatureMethod, MeshCurvatureSettings, NormalMapCurvatureSettings};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct CurvatureSettings {
pub method: CurvatureMethod,
pub normal_map: NormalMapCurvatureSettings,
pub mesh: MeshCurvatureSettings,
}
impl Default for CurvatureSettings {
fn default() -> Self {
Self { method: CurvatureMethod::NormalMap, normal_map: NormalMapCurvatureSettings::default(), mesh: MeshCurvatureSettings::default() }
}
}
@@ -0,0 +1,9 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct GroundPlaneSettings {
pub enabled: bool,
/// Offset in mesh units (0..=100)
pub offset: f32,
}
@@ -0,0 +1,10 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum HeightNormalization {
RelativeToRayDistances,
#[default]
RelativeToLowMesh,
RelativeToMinMax,
Manual,
}
+15
View File
@@ -0,0 +1,15 @@
use super::HeightNormalization;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct HeightSettings {
pub normalization: HeightNormalization,
pub scaling_divisor: f32,
}
impl Default for HeightSettings {
fn default() -> Self {
Self { normalization: HeightNormalization::RelativeToLowMesh, scaling_divisor: 1.0 }
}
}
@@ -0,0 +1,26 @@
use super::MeshMatchMode;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct HighPolySettings {
pub use_low_as_high: bool,
pub ignore_backface: bool,
pub match_mode: MeshMatchMode,
pub low_suffix: String,
pub high_suffix: String,
pub ignore_backface_suffix: String,
}
impl Default for HighPolySettings {
fn default() -> Self {
Self {
use_low_as_high: false,
ignore_backface: true,
match_mode: MeshMatchMode::Always,
low_suffix: "_low".into(),
high_suffix: "_high".into(),
ignore_backface_suffix: "_ignorebf".into(),
}
}
}
@@ -0,0 +1,9 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum IdColorGenerator {
Random,
#[default]
HueShift,
Grayscale,
}
+11
View File
@@ -0,0 +1,11 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum IdColorSource {
VertexColor,
#[default]
MaterialColor,
FileId,
MeshId,
Submesh,
}
+9
View File
@@ -0,0 +1,9 @@
use super::{IdColorGenerator, IdColorSource};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct IdSettings {
pub source: IdColorSource,
pub generator: IdColorGenerator,
}
+20
View File
@@ -0,0 +1,20 @@
use serde::{Deserialize, Serialize};
/// One map's enablement and typed parameters
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapSettings<T: Default = ()> {
pub is_enabled: bool,
pub parameters: T,
}
impl<T: Default> Default for MapSettings<T> {
fn default() -> Self {
Self { is_enabled: true, parameters: T::default() }
}
}
impl<T: Default> MapSettings<T> {
pub fn disabled() -> Self {
Self { is_enabled: false, ..Self::default() }
}
}
@@ -0,0 +1,30 @@
use super::SelfOcclusion;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct MeshCurvatureSettings {
pub rays: u32,
/// Radius (0.00001..=10 relative to bounds, 0.00001..=1 in mesh units)
pub sampling_radius: f32,
pub relative_to_bounding_box: bool,
pub self_intersection: SelfOcclusion,
pub auto_tonemapping: bool,
/// Value bounds (-10..=10)
pub value_min: f32,
pub value_max: f32,
}
impl Default for MeshCurvatureSettings {
fn default() -> Self {
Self {
rays: 32,
sampling_radius: 0.001,
relative_to_bounding_box: true,
self_intersection: SelfOcclusion::Always,
auto_tonemapping: true,
value_min: -1.0,
value_max: 1.0,
}
}
}
+83
View File
@@ -0,0 +1,83 @@
use super::{
AmbientOcclusionSettings, BakedMap, BentNormalSettings, CurvatureSettings, HeightSettings, IdSettings, MapSettings, PositionSettings, ThicknessSettings,
};
use serde::{Deserialize, Serialize};
/// Per-map configuration; enabled outputs are derived from these flags
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct MeshMapSettings {
pub normal: MapSettings,
pub world_normal: MapSettings,
pub id: MapSettings<IdSettings>,
pub ao: MapSettings<AmbientOcclusionSettings>,
pub curvature: MapSettings<CurvatureSettings>,
pub position: MapSettings<PositionSettings>,
pub thickness: MapSettings<ThicknessSettings>,
pub height: MapSettings<HeightSettings>,
pub bent_normal: MapSettings<BentNormalSettings>,
pub opacity: MapSettings,
}
impl Default for MeshMapSettings {
fn default() -> Self {
Self {
normal: MapSettings::default(),
world_normal: MapSettings::default(),
id: MapSettings::default(),
ao: MapSettings::default(),
curvature: MapSettings::default(),
position: MapSettings::default(),
thickness: MapSettings::default(),
height: MapSettings::disabled(),
bent_normal: MapSettings::disabled(),
opacity: MapSettings::disabled(),
}
}
}
impl MeshMapSettings {
pub fn is_enabled(&self, map: BakedMap) -> bool {
match map {
BakedMap::Normal => self.normal.is_enabled,
BakedMap::WorldNormal => self.world_normal.is_enabled,
BakedMap::Id => self.id.is_enabled,
BakedMap::AmbientOcclusion => self.ao.is_enabled,
BakedMap::Curvature => self.curvature.is_enabled,
BakedMap::Position => self.position.is_enabled,
BakedMap::Thickness => self.thickness.is_enabled,
BakedMap::Height => self.height.is_enabled,
BakedMap::BentNormal => self.bent_normal.is_enabled,
BakedMap::Opacity => self.opacity.is_enabled,
}
}
pub fn set_enabled(&mut self, map: BakedMap, is_enabled: bool) {
let enabled = match map {
BakedMap::Normal => &mut self.normal.is_enabled,
BakedMap::WorldNormal => &mut self.world_normal.is_enabled,
BakedMap::Id => &mut self.id.is_enabled,
BakedMap::AmbientOcclusion => &mut self.ao.is_enabled,
BakedMap::Curvature => &mut self.curvature.is_enabled,
BakedMap::Position => &mut self.position.is_enabled,
BakedMap::Thickness => &mut self.thickness.is_enabled,
BakedMap::Height => &mut self.height.is_enabled,
BakedMap::BentNormal => &mut self.bent_normal.is_enabled,
BakedMap::Opacity => &mut self.opacity.is_enabled,
};
*enabled = is_enabled;
}
pub fn enabled(&self) -> impl Iterator<Item = BakedMap> {
BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map))
}
pub fn select(&mut self, maps: impl IntoIterator<Item = BakedMap>) {
for map in BakedMap::ALL {
self.set_enabled(map, false);
}
for map in maps {
self.set_enabled(map, true);
}
}
}
+8
View File
@@ -0,0 +1,8 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum MeshMatchMode {
#[default]
Always,
ByMeshName,
}
@@ -0,0 +1,15 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct NormalMapCurvatureSettings {
pub details: f32,
pub enable_seams: bool,
pub seams_intensity: f32,
}
impl Default for NormalMapCurvatureSettings {
fn default() -> Self {
Self { details: 0.5, enable_seams: true, seams_intensity: 1.0 }
}
}
+10
View File
@@ -0,0 +1,10 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum PositionAxis {
#[default]
All,
X,
Y,
Z,
}
+13
View File
@@ -0,0 +1,13 @@
use serde::{Deserialize, Serialize};
/// Position map normalization
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum PositionMode {
/// Each axis spans the bounding box (0..1 per axis)
BoundingBox,
/// One scale for every axis: the largest extent around the box centre (keeps proportions)
#[default]
BoundingSphere,
/// Keep mesh coordinates without normalization
None,
}
@@ -0,0 +1,8 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum PositionNormalizationScale {
PerMaterial,
#[default]
FullScene,
}
+10
View File
@@ -0,0 +1,10 @@
use super::{PositionAxis, PositionMode, PositionNormalizationScale};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PositionSettings {
pub axis: PositionAxis,
pub normalization: PositionMode,
pub scale: PositionNormalizationScale,
}
+11
View File
@@ -0,0 +1,11 @@
use serde::{Deserialize, Serialize};
/// How secondary rays spread over their cone
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum RayDistribution {
/// Cosine-weighted: more rays near the normal
#[default]
Cosine,
/// Uniform over the cone's solid angle
Uniform,
}
+24
View File
@@ -0,0 +1,24 @@
use super::RayDistribution;
use serde::{Deserialize, Serialize};
/// Secondary-ray parameters of one map (ambient occlusion, thickness, bent normals)
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct RaySettings {
/// Rays per sample (settings range 1..=256)
pub rays: u32,
/// Minimum distance in the same units as max_distance (0.00001..=1)
pub min_distance: f32,
/// Maximum distance: 0.00001..=1 relative to the bounding box, or 0.00001..=10 in mesh units
pub max_distance: f32,
pub relative_to_bounding_box: bool,
/// Full cone angle around the normal in degrees (180 = the whole hemisphere)
pub spread: f32,
pub distribution: RayDistribution,
}
impl Default for RaySettings {
fn default() -> Self {
RaySettings { rays: 64, min_distance: 0.00001, max_distance: 1.0, relative_to_bounding_box: true, spread: 180.0, distribution: RayDistribution::Cosine }
}
}
+11
View File
@@ -0,0 +1,11 @@
use serde::{Deserialize, Serialize};
/// Mesh filtering for occlusion, thickness and curvature rays
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum SelfOcclusion {
/// Every part occludes every other
#[default]
Always,
/// Only parts with the same mesh name (suffixes removed) occlude each other
SameMeshName,
}
@@ -0,0 +1,8 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SkewCorrectionMethod {
#[default]
MeshNormalsBased,
FaceNormalsBased,
}
+20
View File
@@ -0,0 +1,20 @@
use super::SkewCorrectionMethod;
use serde::{Deserialize, Serialize};
/// Skew controls independent of the painted pixel asset
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct SkewSettings {
pub method: SkewCorrectionMethod,
pub edge_protection: bool,
/// Edge protection distance (0..=1), retained while protection is disabled
pub edge_distance: f32,
/// Edge protection contrast (0..=1)
pub edge_contrast: f32,
}
impl Default for SkewSettings {
fn default() -> Self {
Self { method: SkewCorrectionMethod::MeshNormalsBased, edge_protection: false, edge_distance: 0.15, edge_contrast: 0.5 }
}
}
@@ -0,0 +1,9 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum ThicknessNormalization {
RelativeToRayDistances,
#[default]
RelativeToMinMax,
None,
}
@@ -0,0 +1,20 @@
use super::{RaySettings, SelfOcclusion, ThicknessNormalization};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ThicknessSettings {
pub rays: RaySettings,
pub self_occlusion: SelfOcclusion,
pub normalization: ThicknessNormalization,
}
impl Default for ThicknessSettings {
fn default() -> Self {
Self {
rays: RaySettings { max_distance: 0.1, ..RaySettings::default() },
self_occlusion: SelfOcclusion::Always,
normalization: ThicknessNormalization::RelativeToMinMax,
}
}
}
+10 -3
View File
@@ -7,11 +7,19 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod bake;
pub mod blend;
pub mod channel;
pub mod layer;
pub mod project;
pub use bake::{
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap,
BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization,
HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, MeshMatchMode,
NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion,
SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings,
};
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use layer::{
@@ -19,9 +27,8 @@ pub use layer::{
LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit,
};
pub use project::{
AoMixing, BakeMatch, BakeSettings, BakedMap, BlockScales, Camera, DepthOfField, DirectionMode, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION,
MIN_RESOLUTION, NormalFormat, NormalMixing, PositionMode, Project, RayDistribution, RaySettings, SelfOcclusion, TextureSet, TileGrid, ToneMapping,
UDIM_RANGE, udim_at,
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project,
TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at,
};
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
+18 -298
View File
@@ -1,14 +1,14 @@
//! The project: texture sets, their layer stacks, and project-wide settings.
//! The project: texture sets, their layer stacks, and project-wide settings
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::{Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result};
use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result};
pub const FORMAT_VERSION: u32 = 1;
/// Maximum group nesting (also bounds recursion over hostile project files).
/// Maximum group nesting (also bounds recursion over hostile project files)
pub const MAX_DEPTH: usize = 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
@@ -18,273 +18,6 @@ pub enum NormalFormat {
DirectX,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum BakedMap {
Normal,
WorldNormal,
Id,
AmbientOcclusion,
Curvature,
Position,
Thickness,
Height,
/// World-space direction of least occlusion (packed like the world-space normal).
BentNormal,
/// 1 where the high poly covers the low poly (times the high poly's vertex alpha).
Opacity,
/// The high poly's vertex colors.
ColorMap,
/// Facing ratio towards [`BakeSettings::direction`] (0.5 = perpendicular).
WorldDirection,
}
impl BakedMap {
pub const ALL: [BakedMap; 12] = [
BakedMap::Normal,
BakedMap::WorldNormal,
BakedMap::Id,
BakedMap::AmbientOcclusion,
BakedMap::Curvature,
BakedMap::Position,
BakedMap::Thickness,
BakedMap::Height,
BakedMap::BentNormal,
BakedMap::Opacity,
BakedMap::ColorMap,
BakedMap::WorldDirection,
];
pub fn label(self) -> &'static str {
match self {
BakedMap::Normal => "Normal",
BakedMap::WorldNormal => "World space normal",
BakedMap::Id => "ID",
BakedMap::AmbientOcclusion => "Ambient occlusion",
BakedMap::Curvature => "Curvature",
BakedMap::Position => "Position",
BakedMap::Thickness => "Thickness",
BakedMap::Height => "Height",
BakedMap::BentNormal => "Bent normals",
BakedMap::Opacity => "Opacity",
BakedMap::ColorMap => "Color map",
BakedMap::WorldDirection => "World space direction",
}
}
pub fn id(self) -> &'static str {
match self {
BakedMap::Normal => "normal_base",
BakedMap::WorldNormal => "world_space_normals",
BakedMap::Id => "id",
BakedMap::AmbientOcclusion => "ambient_occlusion",
BakedMap::Curvature => "curvature",
BakedMap::Position => "position",
BakedMap::Thickness => "thickness",
BakedMap::Height => "height",
BakedMap::BentNormal => "bent_normals",
BakedMap::Opacity => "opacity",
BakedMap::ColorMap => "color_map",
BakedMap::WorldDirection => "world_space_direction",
}
}
/// The identifier shared with MaterialCraft (graph inputs fed from this map).
pub fn interop_id(self) -> &'static str {
match self {
BakedMap::Normal => "normal",
BakedMap::WorldNormal => "worldNormal",
BakedMap::Id => "id",
BakedMap::AmbientOcclusion => "ambientOcclusion",
BakedMap::Curvature => "curvature",
BakedMap::Position => "position",
BakedMap::Thickness => "thickness",
BakedMap::Height => "height",
BakedMap::BentNormal => "bentNormal",
BakedMap::Opacity => "opacity",
BakedMap::ColorMap => "colorMap",
BakedMap::WorldDirection => "worldDirection",
}
}
/// The map a MaterialCraft graph input `identifier` reads: its shared or own id, ignoring
/// case and underscores (`ambient_occlusion` = `ambientOcclusion`).
pub fn for_input(identifier: &str) -> Option<BakedMap> {
let norm = |x: &str| x.to_ascii_lowercase().replace(['_', '-', ' '], "");
let want = norm(identifier);
BakedMap::ALL.into_iter().find(|m| norm(m.interop_id()) == want || norm(m.id()) == want)
}
/// Components stored (3 for vector maps, 1 for scalar maps).
pub fn components(self) -> usize {
match self {
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Id | BakedMap::Position | BakedMap::BentNormal | BakedMap::ColorMap => 3,
_ => 1,
}
}
/// Value where nothing was baked (uncovered texels, missing maps).
pub fn neutral(self) -> [f32; 3] {
match self {
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::BentNormal => [0.5, 0.5, 1.0],
BakedMap::AmbientOcclusion | BakedMap::Thickness => [1.0; 3],
BakedMap::Curvature | BakedMap::Height | BakedMap::WorldDirection => [0.5; 3],
BakedMap::Id | BakedMap::Position | BakedMap::Opacity | BakedMap::ColorMap => [0.0; 3],
}
}
pub fn parse(s: &str) -> Option<BakedMap> {
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], "");
BakedMap::ALL.into_iter().find(|m| norm(m.label()) == norm(s) || norm(m.id()) == norm(s) || norm(&format!("{m:?}")) == norm(s))
}
}
/// How low-poly parts find their high-poly counterparts (the bake "Match" option).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum BakeMatch {
/// Every low-poly part sees every high-poly part.
#[default]
Always,
/// A low-poly part sees only high-poly parts of the same name once the suffixes are removed
/// (`wheel_low` ↔ `wheel_high`).
ByMeshName,
}
/// How secondary rays spread over their cone.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum RayDistribution {
/// Cosine-weighted: more rays near the normal.
#[default]
Cosine,
/// Uniform over the cone's solid angle.
Uniform,
}
/// Which geometry occludes ambient occlusion and bent-normal rays.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum SelfOcclusion {
/// Every part occludes every other.
#[default]
Always,
/// Only parts with the same mesh name (suffixes removed) occlude each other.
SameMeshName,
}
/// Position map normalization.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum PositionMode {
/// Each axis spans the bounding box (0..1 per axis).
#[default]
BoundingBox,
/// One scale for every axis: the bounding sphere around the box centre (keeps proportions).
BoundingSphere,
}
/// World space direction map encoding.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum DirectionMode {
/// −1..1 to 0..1: mid grey where the surface is perpendicular to the direction.
#[default]
Signed,
/// 0..1: black where the surface is perpendicular or faces away.
Positive,
}
/// Secondary-ray parameters of one map (ambient occlusion, thickness, bent normals).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct RaySettings {
/// Rays per sample.
pub rays: u32,
/// Max ray length relative to the bounding-box diagonal.
pub max_distance: f32,
/// Full cone angle around the normal in degrees (180 = the whole hemisphere).
pub spread: f32,
pub distribution: RayDistribution,
}
impl Default for RaySettings {
fn default() -> Self {
RaySettings { rays: 32, max_distance: 0.25, spread: 180.0, distribution: RayDistribution::Cosine }
}
}
/// Bake parameters (the common parameters plus the per-map parameters). Fields missing
/// from older projects take their defaults.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct BakeSettings {
/// Included by "Bake selected textures".
pub enabled: bool,
pub resolution: u32,
/// Supersampling per axis: 1 (none), 2, 4 or 8.
pub antialiasing: u32,
pub dilation: u32,
/// Ambient occlusion rays.
pub ao: RaySettings,
/// Ambient occlusion and bent-normal rays ignore surfaces they hit from behind.
pub ao_ignore_backface: bool,
pub ao_self_occlusion: SelfOcclusion,
/// Thickness rays (into the surface).
pub thickness: RaySettings,
/// Bent-normal rays (they follow the ambient occlusion's occluder rules).
pub bent_normal: RaySettings,
/// Curvature strength.
pub curvature_strength: f32,
/// Curvature from the baked normal map instead of the mesh.
pub curvature_from_normal: bool,
/// Sampling radius of curvature from the normal map, in texels (0: by resolution).
pub curvature_radius: u32,
pub position_mode: PositionMode,
/// World-space direction of the "World space direction" map.
pub direction: [f32; 3],
pub direction_mode: DirectionMode,
pub maps: BTreeSet<BakedMap>,
/// Bake from the low poly itself ("Use low poly mesh as high poly").
pub use_low_as_high: bool,
/// Ray start distance in front of the low poly, relative to the bbox diagonal.
pub max_frontal: f32,
pub max_rear: f32,
/// Cast rays along normals averaged over hard edges (no gaps at split normals).
pub average_normals: bool,
pub matching: BakeMatch,
pub low_suffix: String,
pub high_suffix: String,
}
impl Default for BakeSettings {
fn default() -> Self {
BakeSettings {
enabled: true,
resolution: 1024,
antialiasing: 1,
dilation: 16,
ao: RaySettings::default(),
ao_ignore_backface: false,
ao_self_occlusion: SelfOcclusion::Always,
// Thickness is hit distance / max distance: long rays turn thin parts almost black.
thickness: RaySettings { max_distance: 0.1, ..RaySettings::default() },
bent_normal: RaySettings::default(),
curvature_strength: 1.0,
curvature_from_normal: false,
curvature_radius: 0,
position_mode: PositionMode::BoundingBox,
direction: [0.0, 1.0, 0.0],
direction_mode: DirectionMode::Signed,
maps: [
BakedMap::Normal,
BakedMap::WorldNormal,
BakedMap::Id,
BakedMap::AmbientOcclusion,
BakedMap::Curvature,
BakedMap::Position,
BakedMap::Thickness,
]
.into_iter()
.collect(),
use_low_as_high: true,
max_frontal: 0.01,
max_rear: 0.01,
average_normals: true,
matching: BakeMatch::Always,
low_suffix: "_low".into(),
high_suffix: "_high".into(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum NormalMixing {
#[default]
@@ -1027,34 +760,21 @@ mod tests {
}
#[test]
fn per_map_bake_settings_round_trip_and_old_projects_load() {
let mut p = project();
let b = &mut p.texture_sets[0].bake;
b.ao = RaySettings { rays: 96, max_distance: 0.4, spread: 120.0, distribution: RayDistribution::Uniform };
b.ao_ignore_backface = true;
b.ao_self_occlusion = SelfOcclusion::SameMeshName;
b.thickness.spread = 60.0;
b.bent_normal.rays = 8;
b.curvature_radius = 3;
b.position_mode = PositionMode::BoundingSphere;
b.direction_mode = DirectionMode::Positive;
let json = serde_json::to_string(&p).unwrap();
assert_eq!(serde_json::from_str::<Project>(&json).unwrap(), p);
// Settings saved before per-map rays (one shared ray count) load with the defaults.
let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
let old = v["texture_sets"][0]["bake"].as_object_mut().unwrap();
for k in ["ao", "ao_ignore_backface", "ao_self_occlusion", "thickness", "bent_normal", "curvature_radius", "position_mode", "direction_mode"] {
old.remove(k);
}
old.insert("rays".into(), 64.into());
old.insert("max_distance".into(), 0.3.into());
let back: Project = serde_json::from_value(v).unwrap();
let d = BakeSettings::default();
let b = &back.texture_sets[0].bake;
assert_eq!(
(b.ao, b.thickness, b.bent_normal, b.ao_self_occlusion, b.position_mode),
(d.ao, d.thickness, d.bent_normal, d.ao_self_occlusion, d.position_mode)
);
fn per_map_bake_settings_round_trip() {
use crate::{BackfaceMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion};
let mut project = project();
let settings = &mut project.texture_sets[0].bake;
settings.maps.ao.parameters.rays =
RaySettings { rays: 96, max_distance: 0.4, spread: 120.0, distribution: RayDistribution::Uniform, ..RaySettings::default() };
settings.maps.ao.parameters.ignore_backface = BackfaceMode::Always;
settings.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName;
settings.maps.thickness.parameters.rays.spread = 60.0;
settings.maps.bent_normal.parameters.rays.rays = 8;
settings.maps.position.parameters.normalization = PositionMode::BoundingSphere;
let json = serde_json::to_string(&project).unwrap();
assert_eq!(serde_json::from_str::<Project>(&json).unwrap(), project);
}
#[test]
+190
View File
@@ -0,0 +1,190 @@
#![recursion_limit = "256"]
use serde::{Serialize, de::DeserializeOwned};
use serde_json::{Value, json};
use texturecraft_core::{self as bake, BakedMap, Project, TextureSet};
#[test]
fn reference_defaults_cover_common_and_per_map_settings() {
let rays = json!({
"rays": 64, "min_distance": 0.00001, "max_distance": 1.0,
"relative_to_bounding_box": true, "spread": 180.0, "distribution": "Cosine"
});
let mut thickness_rays = rays.clone();
thickness_rays["max_distance"] = json!(0.1);
let mut expected = json!({
"common": {"is_enabled": true, "resolution": "R2048", "resolution_height": null, "antialiasing": "None", "dilation": 1, "apply_diffusion": true},
"high_poly": {"match_mode": "Always", "use_low_as_high": false, "ignore_backface": true, "low_suffix": "_low", "high_suffix": "_high", "ignore_backface_suffix": "_ignorebf"},
"cage": {"kind": "DistanceBased", "max_frontal": 0.01, "max_rear": 0.01, "relative_to_bounding_box": true, "average_normals": true},
"skew": {"method": "MeshNormalsBased", "edge_protection": false, "edge_distance": 0.15, "edge_contrast": 0.5},
"id": {"source": "MaterialColor", "generator": "HueShift"},
"ao": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always", "attenuation": "Linear", "ground_plane": {"enabled": false, "offset": 0.0}},
"curvature": {
"method": "NormalMap",
"normal_map": {"details": 0.5, "enable_seams": true, "seams_intensity": 1.0},
"mesh": {"rays": 32, "sampling_radius": 0.001, "relative_to_bounding_box": true, "self_intersection": "Always", "auto_tonemapping": true, "value_min": -1.0, "value_max": 1.0}
},
"position": {"axis": "All", "normalization": "BoundingSphere", "scale": "FullScene"},
"thickness": {"rays": thickness_rays, "self_occlusion": "Always", "normalization": "RelativeToMinMax"},
"height": {"normalization": "RelativeToLowMesh", "scaling_divisor": 1.0},
"bent_normal": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always"}
});
let mut maps = serde_json::Map::new();
for key in ["id", "ao", "curvature", "position", "thickness", "height", "bent_normal"] {
let parameters = expected.as_object_mut().unwrap().remove(key).unwrap();
maps.insert(key.into(), json!({"is_enabled": !["height", "bent_normal"].contains(&key), "parameters": parameters}));
}
for key in ["normal", "world_normal", "opacity"] {
maps.insert(key.into(), json!({"is_enabled": key != "opacity", "parameters": null}));
}
expected["maps"] = Value::Object(maps);
// Normalize the expected JSON floats to f32 before comparing every value
let decoded: bake::BakeSettings = serde_json::from_value(expected.clone()).unwrap();
assert_eq!(bake::BakeSettings::default(), decoded);
assert_eq!(serde_json::from_str::<bake::BakeSettings>("{}").unwrap(), decoded);
assert_eq!(decoded.common.output_size(), (2048, 2048));
fn assert_shape(actual: &Value, expected: &Value) {
if let (Some(actual), Some(expected)) = (actual.as_object(), expected.as_object()) {
assert_eq!(actual.keys().collect::<Vec<_>>(), expected.keys().collect::<Vec<_>>());
for (key, expected) in expected {
assert_shape(&actual[key], expected);
}
}
}
assert_shape(&serde_json::to_value(decoded).unwrap(), &expected);
assert_eq!(BakedMap::ALL.len(), 10);
for name in ["color_map", "Color map", "WorldDirection", "world_space_direction"] {
assert_eq!(BakedMap::parse(name), None);
}
}
fn assert_choices<T: Copy + std::fmt::Debug + PartialEq + Serialize + DeserializeOwned>(choices: &[T]) {
for choice in choices {
let encoded = serde_json::to_value(choice).unwrap();
assert!(encoded.is_string());
assert_eq!(serde_json::from_value::<T>(encoded).unwrap(), *choice);
}
for invalid in [json!(true), json!(false), json!(1), json!(3), json!("invalid")] {
assert!(serde_json::from_value::<T>(invalid).is_err());
}
}
#[test]
fn all_dropdowns_store_enum_choices() {
assert_choices(&[bake::MeshMatchMode::Always, bake::MeshMatchMode::ByMeshName]);
assert_choices(&[bake::SkewCorrectionMethod::MeshNormalsBased, bake::SkewCorrectionMethod::FaceNormalsBased]);
assert_choices(&bake::BakeResolution::ALL);
assert_choices(&bake::BakeAntialiasing::ALL);
assert_choices(&[bake::CageType::DistanceBased, bake::CageType::CustomFile]);
assert_choices(&[bake::CurvatureMethod::NormalMap, bake::CurvatureMethod::Mesh]);
assert_choices(&[
bake::IdColorSource::VertexColor,
bake::IdColorSource::MaterialColor,
bake::IdColorSource::FileId,
bake::IdColorSource::MeshId,
bake::IdColorSource::Submesh,
]);
assert_choices(&[bake::IdColorGenerator::Random, bake::IdColorGenerator::HueShift, bake::IdColorGenerator::Grayscale]);
assert_choices(&[bake::RayDistribution::Uniform, bake::RayDistribution::Cosine]);
assert_choices(&[bake::BackfaceMode::Never, bake::BackfaceMode::Always, bake::BackfaceMode::ByMeshName]);
assert_choices(&[bake::SelfOcclusion::Always, bake::SelfOcclusion::SameMeshName]);
assert_choices(&[bake::AmbientOcclusionAttenuation::None, bake::AmbientOcclusionAttenuation::Smooth, bake::AmbientOcclusionAttenuation::Linear]);
assert_choices(&[bake::PositionAxis::All, bake::PositionAxis::X, bake::PositionAxis::Y, bake::PositionAxis::Z]);
assert_choices(&[bake::PositionMode::BoundingBox, bake::PositionMode::BoundingSphere, bake::PositionMode::None]);
assert_choices(&[bake::PositionNormalizationScale::PerMaterial, bake::PositionNormalizationScale::FullScene]);
assert_choices(&[bake::ThicknessNormalization::RelativeToRayDistances, bake::ThicknessNormalization::RelativeToMinMax, bake::ThicknessNormalization::None]);
assert_choices(&[
bake::HeightNormalization::RelativeToRayDistances,
bake::HeightNormalization::RelativeToLowMesh,
bake::HeightNormalization::RelativeToMinMax,
bake::HeightNormalization::Manual,
]);
}
#[test]
fn components_keep_their_own_defaults() {
let settings: bake::BakeSettings = serde_json::from_value(json!({
"common": {}, "cage": {}, "high_poly": {}, "skew": {},
"maps": {
"ao": {"is_enabled": true, "parameters": {"ground_plane": {}}},
"curvature": {"is_enabled": true, "parameters": {"normal_map": {}, "mesh": {}}}
}
}))
.unwrap();
assert_eq!(settings, bake::BakeSettings::default());
assert_eq!(settings.maps.thickness.parameters.rays.max_distance, 0.1);
}
#[test]
fn nested_settings_round_trip_per_texture_set() {
let mut settings = bake::BakeSettings::default();
settings.common.resolution = bake::BakeResolution::R16;
settings.common.resolution_height = Some(bake::BakeResolution::R8192);
settings.common.antialiasing = bake::BakeAntialiasing::Subsampling8x8;
settings.common.apply_diffusion = false;
settings.high_poly.ignore_backface_suffix = "_two_sided".into();
settings.cage.kind = bake::CageType::CustomFile;
settings.skew.edge_protection = true;
settings.maps.id.parameters.source = bake::IdColorSource::Submesh;
settings.maps.id.parameters.generator = bake::IdColorGenerator::Grayscale;
settings.maps.ao.parameters.ignore_backface = bake::BackfaceMode::ByMeshName;
settings.maps.ao.parameters.ground_plane = bake::GroundPlaneSettings { enabled: true, offset: 5.0 };
settings.maps.curvature.parameters.method = bake::CurvatureMethod::Mesh;
settings.maps.curvature.parameters.normal_map.details = 0.25;
settings.maps.curvature.parameters.mesh.sampling_radius = 0.25;
settings.maps.curvature.parameters.mesh.auto_tonemapping = false;
settings.maps.position.parameters.axis = bake::PositionAxis::Z;
settings.maps.position.parameters.normalization = bake::PositionMode::None;
settings.maps.thickness.parameters.normalization = bake::ThicknessNormalization::None;
settings.maps.height.parameters.normalization = bake::HeightNormalization::Manual;
settings.maps.height.parameters.scaling_divisor = 2.0;
settings.maps.bent_normal.parameters.ignore_backface = bake::BackfaceMode::ByMeshName;
let mut project = Project::new("Bake options", "builtin:plane");
project.texture_sets.push(TextureSet::new("A", 0, 128));
project.texture_sets.push(TextureSet::new("B", 1, 128));
project.texture_sets[0].bake = settings;
let reloaded: Project = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap();
assert_eq!(project, reloaded);
assert_eq!(reloaded.texture_sets[0].bake.common.output_size(), (16, 8192));
assert_eq!(reloaded.texture_sets[1].bake, bake::BakeSettings::default());
}
#[test]
fn malformed_settings_are_rejected() {
for invalid in [
json!({"maps": {"ao": {"is_enabled": "yes", "parameters": {}}}}),
json!({"maps": {"ao": {"is_enabled": true, "parameters": {"rays": {"min_distance": "bad"}}}}}),
json!({"common": {"resolution_height": -1}}),
json!({"maps": {"curvature": {"is_enabled": true, "parameters": {"method": true}}}}),
Value::Null,
] {
assert!(serde_json::from_value::<bake::BakeSettings>(invalid).is_err());
}
}
#[test]
fn map_enablement_is_owned_by_each_map() {
let mut settings = bake::BakeSettings::default();
settings.maps.ao.parameters.rays.rays = 23;
settings.maps.ao.is_enabled = false;
settings.maps.height.is_enabled = true;
assert!(!settings.maps.enabled().any(|map| map == BakedMap::AmbientOcclusion));
assert!(settings.maps.enabled().any(|map| map == BakedMap::Height));
let encoded = serde_json::to_value(&settings).unwrap();
assert_eq!(encoded["maps"]["ao"]["is_enabled"], false);
assert!(encoded.get("selection").is_none());
let mut reloaded: bake::BakeSettings = serde_json::from_value(encoded).unwrap();
assert_eq!(reloaded, settings);
reloaded.maps.select([BakedMap::AmbientOcclusion]);
assert_eq!(reloaded.maps.enabled().collect::<Vec<_>>(), [BakedMap::AmbientOcclusion]);
assert!(reloaded.maps.ao.is_enabled);
assert_eq!(reloaded.maps.ao.parameters.rays.rays, 23);
}
-209
View File
@@ -1,209 +0,0 @@
//! Auto-rebake: one mesh map that bakes itself again when what it was baked from changes.
//!
//! The map is chosen with `bake.autoRebake`. From then on, [`Session::auto_rebake_due`] names the
//! texture sets whose bake inputs (the set's bake settings except the list of maps, the low poly,
//! the high polys, the cage and the skew map) differ from those of their last bake of that map.
//! The apps poll it each frame and bake the due sets in the background; `bake.autoRebake.run`
//! does the same thing once, blocking, for agents and scripts.
//!
//! A set only takes part once it has the map baked at its current output size: Auto-rebake
//! keeps a bake up to date, it doesn't start one, and it never leaves a set's maps at two sizes.
//! The choice isn't part of the project.
use std::collections::BTreeMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Weak};
use serde_json::{Value, json};
use texturecraft_bake::Progress;
use texturecraft_core::BakedMap;
use crate::bake_cmds::BakeTask;
use crate::commands::{CommandSpec, always, bad, boolp};
use crate::{Result, Session, cmd};
/// Which map rebakes itself, and what each texture set was last baked from.
#[derive(Clone, Debug, Default)]
pub struct AutoRebake {
pub map: Option<BakedMap>,
/// Fingerprint of each set's bake inputs when it last baked [`AutoRebake::map`].
seen: BTreeMap<usize, u64>,
/// Fingerprint taken when a set's bake started, kept when that bake finishes.
pending: BTreeMap<usize, u64>,
/// What each map image in use was baked from. Undo and redo bring back an older image; its own
/// entry says its inputs no longer match. Weak, so a freed image doesn't linger and its
/// address can't be taken by a new one.
origin: Vec<(Weak<Vec<f32>>, u64)>,
}
impl AutoRebake {
fn remember(&mut self, image: &Arc<Vec<f32>>, key: u64) {
self.origin.retain(|(w, _)| w.strong_count() > 0);
self.origin.retain(|(w, _)| !std::ptr::eq(w.as_ptr(), Arc::as_ptr(image)));
self.origin.push((Arc::downgrade(image), key));
}
fn origin_of(&self, image: &Arc<Vec<f32>>) -> Option<u64> {
self.origin.iter().find(|(w, _)| std::ptr::eq(w.as_ptr(), Arc::as_ptr(image))).map(|(_, k)| *k)
}
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"bake.autoRebake",
"Auto-rebake",
[],
None,
"{map?: map id (e.g. \"normal_base\", \"height\") to keep up to date, or null / off: true to turn it off; no params: just report} → {map, due: [texture sets that need a rebake]}",
always,
auto_rebake
),
cmd!(
"bake.autoRebake.run",
"Run Auto-rebake",
[],
None,
"{cpu?: true (skip the GPU)} → {rebaked: [texture sets]}: bakes the Auto-rebake map of every set whose bake inputs changed since it was last baked, now",
always,
auto_rebake_run
),
]
}
impl Session {
/// A fingerprint of everything a bake of texture set `ts` is made from, except which maps it
/// makes.
pub fn bake_inputs_key(&self, ts: usize) -> Option<u64> {
let set = self.doc.project.texture_sets.get(ts)?;
let mut settings = set.bake.clone();
settings.maps.clear();
settings.enabled = true;
let mut h = DefaultHasher::new();
serde_json::to_string(&settings).ok()?.hash(&mut h);
(Arc::as_ptr(&self.mesh) as usize).hash(&mut h);
for m in &self.bake_meshes.high {
(Arc::as_ptr(&m.mesh) as usize).hash(&mut h);
}
self.bake_meshes.cage.as_ref().map(|c| Arc::as_ptr(&c.mesh) as usize).hash(&mut h);
(self.bake_meshes.skew.is_some(), self.bake_meshes.skew_rev).hash(&mut h);
Some(h.finish())
}
/// Texture sets whose Auto-rebake map is out of date. A set seen for the first time (a project
/// just opened, a bake from before Auto-rebake was on) is taken as up to date.
pub fn auto_rebake_due(&mut self) -> Vec<usize> {
let Some(map) = self.auto_rebake.map else { return Vec::new() };
let mut due = Vec::new();
for ts in 0..self.doc.project.texture_sets.len() {
let Some(set) = self.doc.project.texture_sets.get(ts).filter(|t| t.bake.enabled) else { continue };
let columns = set.tile_grid().map_or(1, |g| g.cols);
let baked = self.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map) && b.resolution == set.bake.resolution.saturating_mul(columns));
let Some(key) = self.bake_inputs_key(ts).filter(|_| baked) else { continue };
let image = self.doc.baked.get(&ts).and_then(|b| b.maps.get(&map)).cloned();
// An image whose inputs are known is judged by them (this is what undo is caught by);
// one not seen before is taken as up to date, like a project just opened.
match (image.as_ref().and_then(|i| self.auto_rebake.origin_of(i)), self.auto_rebake.seen.get(&ts)) {
(Some(made_from), _) if made_from != key => due.push(ts),
(Some(_), _) => {}
(None, Some(seen)) if *seen != key => due.push(ts),
(None, Some(_)) => {}
(None, None) => {
self.auto_rebake.seen.insert(ts, key);
if let Some(image) = &image {
self.auto_rebake.remember(image, key);
}
}
}
}
due
}
/// Call right before building the bake task of `ts`: remembers what it is baked from, so a
/// finished bake of the Auto-rebake map marks the set up to date (and a change made while it
/// ran still triggers another).
pub fn begin_bake(&mut self, ts: usize) {
if let Some(key) = self.bake_inputs_key(ts) {
self.auto_rebake.pending.insert(ts, key);
}
}
/// The bake task of `ts` restricted to one map (Auto-rebake's: the other maps stay as they are).
pub fn bake_task_for(&self, ts: usize, only: Option<BakedMap>) -> Result<BakeTask> {
let mut task = self.bake_task(ts)?;
if let Some(m) = only {
task.settings.maps = std::iter::once(m).collect();
}
Ok(task)
}
/// Records a finished bake: when it made the Auto-rebake map, the set is up to date.
pub(crate) fn note_baked(&mut self, ts: usize, mut made: impl Iterator<Item = BakedMap>) {
let key = self.auto_rebake.pending.remove(&ts);
if let (Some(key), Some(map)) = (key, self.auto_rebake.map)
&& made.any(|m| m == map)
{
self.auto_rebake.seen.insert(ts, key);
if let Some(image) = self.doc.baked.get(&ts).and_then(|b| b.maps.get(&map)).cloned() {
self.auto_rebake.remember(&image, key);
}
}
}
/// Records bakes of `sets` that were cancelled, failed or never started: Auto-rebake leaves
/// those sets alone until their bake inputs change again, instead of retrying every frame.
pub fn bake_abandoned(&mut self, sets: impl IntoIterator<Item = usize>) {
for ts in sets {
if let Some(key) = self.auto_rebake.pending.remove(&ts).or_else(|| self.bake_inputs_key(ts)) {
self.auto_rebake.seen.insert(ts, key);
// The map as it stands is left alone for these inputs.
let image = self.auto_rebake.map.and_then(|m| self.doc.baked.get(&ts)?.maps.get(&m).cloned());
if let Some(image) = image {
self.auto_rebake.remember(&image, key);
}
}
}
}
/// Bakes every due set's Auto-rebake map now (blocking); returns the sets.
pub fn auto_rebake_now(&mut self, cpu: bool) -> Result<Vec<usize>> {
let due = self.auto_rebake_due();
let map = self.auto_rebake.map;
for &ts in &due {
self.begin_bake(ts);
let mut task = self.bake_task_for(ts, map)?;
if cpu {
task.tracer = None;
}
let out = task.run(&Progress::new())?;
self.apply_bake(ts, out)?;
}
Ok(due)
}
}
fn state(s: &mut Session) -> Value {
json!({ "map": s.auto_rebake.map.map(BakedMap::id), "due": s.auto_rebake_due() })
}
fn auto_rebake(s: &mut Session, p: &Value) -> Result<Value> {
if boolp(p, "off") == Some(true) || p.get("map").is_some_and(Value::is_null) {
s.auto_rebake = AutoRebake::default();
} else if let Some(id) = p.get("map") {
let map = id.as_str().and_then(BakedMap::parse).ok_or_else(|| bad("bake.autoRebake", format!("unknown mesh map {id}")))?;
if s.auto_rebake.map != Some(map) {
s.auto_rebake = AutoRebake { map: Some(map), ..AutoRebake::default() };
}
}
Ok(state(s))
}
fn auto_rebake_run(s: &mut Session, p: &Value) -> Result<Value> {
if s.auto_rebake.map.is_none() {
return Err(bad("bake.autoRebake.run", "no Auto-rebake map is set; run bake.autoRebake {map} first"));
}
let rebaked = s.auto_rebake_now(boolp(p, "cpu") == Some(true))?;
s.update();
Ok(json!({ "rebaked": rebaked }))
}
+12
View File
@@ -0,0 +1,12 @@
use std::sync::Arc;
use texturecraft_geom::{BaseColor, Mesh};
/// A mesh file the baker reads (high poly or cage): its name, original bytes (saved in the
/// project), parsed mesh and its materials' base colors (high polys).
#[derive(Clone, Debug)]
pub struct BakeMesh {
pub name: String,
pub bytes: Arc<Vec<u8>>,
pub mesh: Arc<Mesh>,
pub base_color: Vec<Option<Arc<BaseColor>>>,
}
+29
View File
@@ -0,0 +1,29 @@
use super::{BakeMesh, MergedHigh};
use std::sync::{Arc, OnceLock};
use texturecraft_geom::{Bvh, Mesh};
/// The high-definition meshes and the cage. Like the low-poly mesh they are not part of the
/// undo history.
#[derive(Clone, Debug, Default)]
pub struct BakeMeshes {
pub(crate) low_base_color: OnceLock<std::result::Result<super::MaterialColors, String>>,
pub high: Vec<BakeMesh>,
pub cage: Option<BakeMesh>,
/// Every high poly appended into one mesh (rebuilt when the list changes).
pub(crate) merged: Option<MergedHigh>,
}
impl BakeMeshes {
pub(crate) fn rebuild(&mut self) {
self.merged = (!self.high.is_empty()).then(|| {
let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new());
for (file_index, source) in self.high.iter().enumerate() {
file_ids.extend(std::iter::repeat_n(file_index as u32, source.mesh.submeshes.len()));
mesh.append(&source.mesh);
base_color.extend(source.base_color.iter().cloned().chain(std::iter::repeat(None)).take(source.mesh.materials.len()));
}
let bvh = Bvh::new(&mesh);
MergedHigh { file_ids: Arc::new(file_ids), mesh: Arc::new(mesh), bvh: Arc::new(bvh), base_color: Arc::new(base_color) }
});
}
}
+49
View File
@@ -0,0 +1,49 @@
use super::MergedHigh;
use crate::{EngineError, Result};
use std::sync::Arc;
use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake, bake_on, tracing::Tracer};
use texturecraft_core::BakeSettings;
use texturecraft_geom::{Bvh, Mesh};
/// A self-contained bake task that can run on another thread.
pub struct BakeTask {
pub low_base_color: super::MaterialColors,
pub ts: usize,
pub mesh: Arc<Mesh>,
pub bvh: Arc<Bvh>,
pub material: usize,
pub settings: BakeSettings,
/// The merged high polys, unless the set bakes from the low poly.
pub high: Option<MergedHigh>,
pub cage: Option<Arc<Mesh>>,
pub skew: Option<Arc<BakePaintMap>>,
pub cage_paint: Option<Arc<BakePaintMap>>,
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles.
pub tiles: (u32, u32),
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`).
pub tracer: Option<Arc<dyn Tracer>>,
}
impl BakeTask {
pub fn run(&self, progress: &Progress) -> Result<BakeOutput> {
let high =
self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color });
let request = BakeRequest {
low_base_color: &self.low_base_color,
mesh: &self.mesh,
bvh: &self.bvh,
material: self.material,
settings: &self.settings,
high,
cage: self.cage.as_deref(),
skew: self.skew.as_deref(),
cage_paint: self.cage_paint.as_deref(),
tiles: self.tiles,
};
match &self.tracer {
Some(tracer) => bake_on(&request, progress, tracer.as_ref()),
None => bake(&request, progress),
}
.map_err(|e| EngineError::Other(format!("bake failed: {e}")))
}
}
+11
View File
@@ -0,0 +1,11 @@
use std::sync::Arc;
use texturecraft_geom::{Bvh, Mesh};
/// Every high poly appended into one mesh, its BVH and per-material base colors.
#[derive(Clone, Debug)]
pub struct MergedHigh {
pub file_ids: Arc<Vec<u32>>,
pub mesh: Arc<Mesh>,
pub bvh: Arc<Bvh>,
pub base_color: super::MaterialColors,
}
+11
View File
@@ -0,0 +1,11 @@
mod bake_mesh;
mod bake_meshes;
mod bake_task;
mod merged_high;
pub use bake_mesh::BakeMesh;
pub use bake_meshes::BakeMeshes;
pub use bake_task::BakeTask;
pub use merged_high::MergedHigh;
type MaterialColors = std::sync::Arc<Vec<Option<std::sync::Arc<texturecraft_geom::BaseColor>>>>;
+351 -403
View File
@@ -2,14 +2,17 @@
//! high-definition mesh list, the cage, and running a bake. Bakes cast their rays on the GPU
//! tracer the app installs ([`install_gpu_tracer`]) and on the CPU otherwise.
use std::collections::BTreeSet;
use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};
use texturecraft_core::BakePaintTarget;
use crate::{BakeMesh, BakeTask};
use serde_json::{Value, json};
use texturecraft_bake::rays::Tracer;
use texturecraft_bake::{BakeOutput, BakeRequest, HighPoly, MAX_RAYS, Progress, SkewMap, bake, bake_on};
use texturecraft_core::{BakeMatch, BakeSettings, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion};
use texturecraft_geom::{BaseColor, Bvh, Mesh};
use texturecraft_bake::tracing::Tracer;
use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress};
use texturecraft_core::{
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion,
};
use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p};
use crate::{EngineError, Result, Session, cmd};
@@ -30,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Bake settings",
[],
None,
"{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureStrength?, curvatureFromNormal?, curvatureRadius?: texels (0 = auto), positionMode?: boundingBox|boundingSphere, direction?: [x,y,z], directionMode?: signed|positive, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, matching?: always|byMeshName, lowSuffix?, highSuffix?}",
"{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}",
always,
settings
),
@@ -39,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add high definition mesh",
[],
None,
"{path} — a mesh file (glb, gltf, fbx, dae, usd, usda, usdc, usdz, abc, obj, ply, stl; base color textures from glTF, embedded FBX media, usdz packages and image files next to a .gltf or USD layer feed the color map)",
"{path} — a mesh file (glb, gltf, fbx, dae, usd, usda, usdc, usdz, abc, obj, ply, stl; base color textures from glTF, embedded FBX media, usdz packages and image files next to a .gltf or USD layer supply opacity)",
always,
high_add
),
@@ -51,54 +54,12 @@ pub fn specs() -> Vec<CommandSpec> {
s.modified = true;
Ok(meshes_json(s))
}),
cmd!(
"bake.skew.set",
"Set skew correction",
[],
None,
"{value?: 0..1 (a constant map, default 1) | path: a greyscale image over the UV atlas (white turns the rays onto the base normal, black keeps the cage's averaged direction), edgeDistance?: fraction of the mesh diagonal over which hard edges hold the correction back (default 0), edgeContrast?: falloff exponent (default 1), base?: mesh|triangle (default mesh)} → {skew}. Applies to the transfer rays of a bake from the built-in distance cage; a cage mesh ignores it",
always,
skew_set
),
cmd!(
"bake.skew.paint",
"Paint skew correction",
[],
None,
"{points: [[u, v], ...] (atlas uv, a stroke), radius?: uv units (default 0.03), value?: 0..1 (1 turns rays onto the base normal, 0 erases; default 1), hardness?: 0..1 (default 0.5), strength?: 0..1 per dab (default 1), size?: px of a new or constant map (default 1024, 16..4096)} → {skew}. Paints into the skew map; a missing or constant map is first widened to `size`",
always,
skew_paint
),
cmd!("bake.skew.clear", "Remove skew correction", [], None, "{}", always, |s, _| {
s.bake_meshes.skew = None;
s.bake_meshes.skew_rev += 1;
s.modified = true;
Ok(meshes_json(s))
}),
]
}
/// A mesh file as saved in a project: (file name, bytes).
type MeshFile = (String, Vec<u8>);
/// A mesh file the baker reads (high poly or cage): its name, original bytes (saved in the
/// project), parsed mesh and its materials' base colors (high polys).
#[derive(Clone, Debug)]
pub struct BakeMesh {
pub name: String,
pub bytes: Arc<Vec<u8>>,
pub mesh: Arc<Mesh>,
pub base_color: Vec<Option<Arc<BaseColor>>>,
}
/// Every high poly appended into one mesh, its BVH and per-material base colors.
#[derive(Clone, Debug)]
pub struct MergedHigh {
pub mesh: Arc<Mesh>,
pub bvh: Arc<Bvh>,
pub base_color: Arc<Vec<Option<Arc<BaseColor>>>>,
}
static GPU_TRACER: OnceLock<Arc<dyn Tracer>> = OnceLock::new();
/// Cast bake rays with `tracer` (the apps install the render crate's GPU baker at start-up);
@@ -107,74 +68,6 @@ pub fn install_gpu_tracer(tracer: Arc<dyn Tracer>) {
let _ = GPU_TRACER.set(tracer);
}
/// The high-definition meshes and the cage. Like the low-poly mesh they are not part of the
/// undo history.
#[derive(Clone, Debug, Default)]
pub struct BakeMeshes {
pub high: Vec<BakeMesh>,
pub cage: Option<BakeMesh>,
/// Skew correction of the transfer rays (saved in the project as `skew.bin`).
pub skew: Option<Arc<SkewMap>>,
/// Counts changes to `skew`, so a view knows when to redraw it.
pub skew_rev: u64,
/// Every high poly appended into one mesh (rebuilt when the list changes).
merged: Option<MergedHigh>,
}
impl BakeMeshes {
// shortcut: the merged copy doubles high-poly memory; build the BVH over the parts in place if
// multi-million-triangle sets run out of memory.
fn rebuild(&mut self) {
self.merged = (!self.high.is_empty()).then(|| {
let (mut all, mut base_color) = (Mesh::default(), Vec::new());
for h in &self.high {
all.append(&h.mesh);
base_color.extend(h.base_color.iter().cloned().chain(std::iter::repeat(None)).take(h.mesh.materials.len()));
}
let bvh = Bvh::new(&all);
MergedHigh { mesh: Arc::new(all), bvh: Arc::new(bvh), base_color: Arc::new(base_color) }
});
}
}
/// A self-contained bake task that can run on another thread.
pub struct BakeTask {
pub ts: usize,
pub mesh: Arc<Mesh>,
pub bvh: Arc<Bvh>,
pub material: usize,
pub settings: BakeSettings,
/// The merged high polys, unless the set bakes from the low poly.
pub high: Option<MergedHigh>,
pub cage: Option<Arc<Mesh>>,
pub skew: Option<Arc<SkewMap>>,
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles.
pub tiles: (u32, u32),
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`).
pub tracer: Option<Arc<dyn Tracer>>,
}
impl BakeTask {
pub fn run(&self, progress: &Progress) -> Result<BakeOutput> {
let high = self.high.as_ref().map(|h| HighPoly { mesh: &h.mesh, bvh: &h.bvh, base_color: &h.base_color });
let req = BakeRequest {
mesh: &self.mesh,
bvh: &self.bvh,
material: self.material,
settings: &self.settings,
high,
cage: self.cage.as_deref(),
skew: self.skew.as_deref(),
tiles: self.tiles,
};
match &self.tracer {
Some(t) => bake_on(&req, progress, t.as_ref()),
None => bake(&req, progress),
}
.map_err(|e| EngineError::Other(format!("bake failed: {e}")))
}
}
/// A mesh file name made unique among `taken` (and safe as a project file entry).
fn unique_name(file_name: &str, taken: &[&str]) -> String {
let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh");
@@ -197,35 +90,71 @@ fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
impl Session {
pub fn bake_task(&self, ts: usize) -> Result<BakeTask> {
let set = self.doc.project.texture_set(ts)?;
let high = if set.bake.use_low_as_high { None } else { self.bake_meshes.merged.clone() };
let cage = high.as_ref().and(self.bake_meshes.cage.as_ref()).map(|c| c.mesh.clone());
let skew = high.as_ref().and(self.bake_meshes.skew.clone());
let needs_low_color = set.bake.maps.opacity.is_enabled
|| (set.bake.maps.id.is_enabled && set.bake.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor);
let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.bake_meshes.high.is_empty()) {
self.bake_meshes
.low_base_color
.get_or_init(|| match &self.mesh_source {
Some((extension, bytes)) => texturecraft_formats::import_high_poly_bytes(&format!("mesh.{extension}"), bytes)
.map(|imported| Arc::new(imported.base_color.into_iter().map(|color| color.map(Arc::new)).collect()))
.map_err(|error| error.to_string()),
None => Ok(Arc::new(Vec::new())),
})
.clone()
.map_err(EngineError::Other)?
} else {
Arc::new(Vec::new())
};
let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() };
let cage = if high.is_some() && set.bake.cage.kind == texturecraft_core::CageType::CustomFile {
Some(self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?.mesh.clone())
} else {
None
};
let skew = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Skew)).cloned());
let cage_paint = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Cage)).cloned());
let tiles = set.tile_grid().map_or((1, 1), |g| (g.cols, g.rows));
let tracer = GPU_TRACER.get().cloned();
Ok(BakeTask { ts, mesh: self.mesh.clone(), bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), high, cage, skew, tiles, tracer })
Ok(BakeTask {
low_base_color,
ts,
mesh: self.mesh.clone(),
bvh: self.bvh.clone(),
material: set.material,
settings: set.bake.clone(),
high,
cage,
skew,
cage_paint,
tiles,
tracer,
})
}
/// Store a finished bake (one undo step).
pub fn apply_bake(&mut self, ts: usize, out: BakeOutput) -> Result<()> {
self.log.push(format!("Baked texture set {ts} ({})", out.tracer));
let made: Vec<BakedMap> = out.maps.keys().copied().collect();
self.edit("Bake mesh maps", |s| {
let maps: BTreeSet<BakedMap> = out.maps.keys().copied().collect();
let entry = s.doc.baked.entry(ts).or_default();
entry.resolution = out.resolution;
for (m, data) in out.maps {
entry.maps.insert(m, Arc::new(data));
}
s.doc.project.texture_set_mut(ts)?.baked.extend(maps);
Ok(())
})?;
self.note_baked(ts, made.into_iter());
/// Store a finished bake as one undo step
pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
let tracer = output.tracer.clone();
self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output))?;
self.log.push(format!("Baked texture set {texture_set} ({tracer})"));
Ok(())
}
fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
let entry = self.doc.baked.entry(texture_set).or_default();
if entry.resolution != output.resolution || entry.maps.keys().any(|map| entry.height(*map) != output.height) {
entry.maps.clear();
}
entry.resolution = output.resolution;
for (map, pixels) in output.maps {
entry.maps.insert(map, Arc::new(pixels));
}
self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect();
Ok(())
}
/// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran.
pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result<String> {
self.begin_bake(ts);
let mut task = self.bake_task(ts)?;
if cpu {
task.tracer = None;
@@ -248,7 +177,7 @@ impl Session {
self.bake_meshes.high.push(m);
self.bake_meshes.rebuild();
for set in &mut self.doc.project.texture_sets {
set.bake.use_low_as_high = false;
set.bake.high_poly.use_low_as_high = false;
}
self.modified = true;
Ok(name)
@@ -307,37 +236,28 @@ impl Session {
}
}
/// The skew map of a project file, if it passes the baker's checks.
pub(crate) fn load_skew(&mut self, skew: Option<texturecraft_formats::SkewData>) {
let Some(k) = skew else { return };
let map = SkewMap {
width: k.width,
height: k.height,
values: k.values,
edge_distance: k.edge_distance,
edge_contrast: k.edge_contrast,
per_triangle: k.per_triangle,
};
match map.validate() {
Ok(()) => {
self.bake_meshes.skew = Some(Arc::new(map));
self.bake_meshes.skew_rev += 1;
pub(crate) fn load_bake_paint(&mut self, maps: BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData>) {
for (key, data) in maps {
if key.0 >= self.doc.project.texture_sets.len() {
self.log.push(format!("skipped bake paint map for missing texture set {}", key.0));
continue;
}
let map = BakePaintMap { width: data.width, height: data.height, values: data.values };
match map.validate() {
Ok(()) => {
self.doc.bake_paint.insert(key, Arc::new(map));
}
Err(error) => self.log.push(format!("skipped bake paint map: {error}")),
}
Err(e) => self.log.push(format!("skipped skew map: {e}")),
}
}
/// The skew map for a project file.
pub(crate) fn saved_skew(&self) -> Option<texturecraft_formats::SkewData> {
let k = self.bake_meshes.skew.as_ref()?;
Some(texturecraft_formats::SkewData {
width: k.width,
height: k.height,
values: k.values.clone(),
edge_distance: k.edge_distance,
edge_contrast: k.edge_contrast,
per_triangle: k.per_triangle,
})
pub(crate) fn saved_bake_paint(&self) -> BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData> {
self.doc
.bake_paint
.iter()
.map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() }))
.collect()
}
/// The bake meshes for a project file: (high polys, cage).
@@ -350,10 +270,11 @@ impl Session {
/// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`).
pub fn meshes_json(s: &Session) -> Value {
let one = |m: &BakeMesh| json!({ "name": m.name, "triangles": m.mesh.triangle_count(), "parts": m.mesh.submeshes.iter().map(|p| p.name.as_str()).collect::<Vec<_>>() });
let skew = s.bake_meshes.skew.as_ref().map(|k| {
json!({ "width": k.width, "height": k.height, "edgeDistance": k.edge_distance, "edgeContrast": k.edge_contrast, "base": if k.per_triangle { "triangle" } else { "mesh" } })
});
json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::<Vec<_>>(), "cage": s.bake_meshes.cage.as_ref().map(one), "skew": skew })
let painted = |target| s.doc.bake_paint.get(&(s.ts(), target)).map(|map| json!({ "width": map.width, "height": map.height }));
json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::<Vec<_>>(), "cage": s.bake_meshes.cage.as_ref().map(one), "skew": painted(BakePaintTarget::Skew), "paintedCage": painted(BakePaintTarget::Cage), "paintMaps": s.doc.bake_paint.iter().map(|((texture_set, target), map)| {
let default = match target { BakePaintTarget::Cage => 1.0, BakePaintTarget::Skew => 0.0 };
json!({"textureSet": texture_set, "target": target, "width": map.width, "height": map.height, "paintedTexels": map.values.iter().filter(|value| **value != default).count()})
}).collect::<Vec<_>>() })
}
#[cfg(not(target_arch = "wasm32"))]
@@ -387,49 +308,6 @@ fn high_remove(s: &mut Session, p: &Value) -> Result<Value> {
Ok(meshes_json(s))
}
/// The greyscale skew map of an image file (the mean of its colour channels, as stored).
#[cfg(not(target_arch = "wasm32"))]
fn skew_image(path: &str) -> Result<(u32, u32, Vec<f32>)> {
const MAX_BYTES: u64 = 256 << 20;
let cmd = "bake.skew.set";
let len = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?.len();
if len > MAX_BYTES {
return Err(bad(cmd, format!("{path} is over 256 MiB")));
}
let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?;
// The size is checked from the header, before the pixels are decoded.
let img = texturecraft_formats::decode_image_within(&bytes, texturecraft_bake::MAX_TEXELS).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
Ok((img.width, img.height, img.rgba.iter().map(|p| (p[0] + p[1] + p[2]) / 3.0).collect()))
}
#[cfg(target_arch = "wasm32")]
fn skew_image(_: &str) -> Result<(u32, u32, Vec<f32>)> {
Err(EngineError::Other("file paths are not available in the browser".into()))
}
fn skew_set(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "bake.skew.set";
let mut map = match strp(p, "path") {
Some(path) => {
let (width, height, values) = skew_image(path)?;
SkewMap { width, height, values: values.into_iter().map(|v| v.clamp(0.0, 1.0)).collect(), ..SkewMap::constant(0.0) }
}
None => SkewMap::constant(f32p(p, "value").unwrap_or(1.0).clamp(0.0, 1.0)),
};
map.edge_distance = f32p(p, "edgeDistance").unwrap_or(0.0);
map.edge_contrast = f32p(p, "edgeContrast").unwrap_or(1.0);
map.per_triangle = match strp(p, "base") {
None | Some("mesh") => false,
Some("triangle") => true,
Some(other) => return Err(bad(cmd, format!("unknown base `{other}`"))),
};
map.validate().map_err(|e| bad(cmd, e.to_string()))?;
s.bake_meshes.skew = Some(Arc::new(map));
s.bake_meshes.skew_rev += 1;
s.modified = true;
Ok(meshes_json(s))
}
fn cage_set(s: &mut Session, p: &Value) -> Result<Value> {
s.add_bake_mesh(read_mesh_file("bake.cage.set", p)?, true)
}
@@ -440,242 +318,312 @@ fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result<Vec<usize>> {
let one = |v: &Value| v.as_u64().map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(cmd, format!("invalid texture set {v}")));
match p.get("ts") {
Some(Value::String(a)) if a == "all" => Ok((0..n).collect()),
Some(Value::String(a)) if a == "selected" => Ok((0..n).filter(|t| s.doc.project.texture_sets.get(*t).is_some_and(|set| set.bake.enabled)).collect()),
Some(Value::String(a)) if a == "selected" => {
Ok((0..n).filter(|t| s.doc.project.texture_sets.get(*t).is_some_and(|set| set.bake.common.is_enabled)).collect())
}
Some(Value::Array(a)) => a.iter().map(one).collect(),
Some(v) => Ok(vec![one(v)?]),
None => Ok(vec![s.ts()]),
}
}
/// `b` as `bake.settings` parameters (what the command returns and the UI sends back).
pub fn settings_params(b: &BakeSettings) -> Value {
let mut ao = rays_params(&b.ao);
ao["ignoreBackface"] = b.ao_ignore_backface.into();
ao["selfOcclusion"] = SELF_OCCLUSION.name(b.ao_self_occlusion).into();
/// Parameters shared by the current bake command and UI
pub fn settings_params(settings: &BakeSettings) -> Value {
let mut ao = rays_params(&settings.maps.ao.parameters.rays);
ao["ignoreBackface"] = match settings.maps.ao.parameters.ignore_backface {
BackfaceMode::Never => "never",
BackfaceMode::Always => "always",
BackfaceMode::ByMeshName => "byMeshName",
}
.into();
ao["selfOcclusion"] = match settings.maps.ao.parameters.self_occlusion {
SelfOcclusion::Always => "always",
SelfOcclusion::SameMeshName => "sameMeshName",
}
.into();
json!({
"resolution": b.resolution,
"antialiasing": b.antialiasing,
"dilation": b.dilation,
"resolution": settings.common.resolution.pixels(),
"antialiasing": settings.common.antialiasing.samples_per_axis(),
"dilation": settings.common.dilation,
"ao": ao,
"thickness": rays_params(&b.thickness),
"bentNormal": rays_params(&b.bent_normal),
"curvatureStrength": b.curvature_strength,
"curvatureFromNormal": b.curvature_from_normal,
"curvatureRadius": b.curvature_radius,
"positionMode": POSITION_MODE.name(b.position_mode),
"direction": b.direction,
"directionMode": DIRECTION_MODE.name(b.direction_mode),
"maps": b.maps.iter().map(|m| m.id()).collect::<Vec<_>>(),
"enabled": b.enabled,
"useLowAsHigh": b.use_low_as_high,
"maxFrontal": b.max_frontal,
"maxRear": b.max_rear,
"averageNormals": b.average_normals,
"matching": match b.matching { BakeMatch::Always => "always", BakeMatch::ByMeshName => "byMeshName" },
"lowSuffix": b.low_suffix,
"highSuffix": b.high_suffix,
"thickness": rays_params(&settings.maps.thickness.parameters.rays),
"bentNormal": rays_params(&settings.maps.bent_normal.parameters.rays),
"curvatureMethod": match settings.maps.curvature.parameters.method { CurvatureMethod::NormalMap => "normalMap", CurvatureMethod::Mesh => "mesh" },
"positionMode": match settings.maps.position.parameters.normalization { PositionMode::BoundingBox => "boundingBox", PositionMode::BoundingSphere => "boundingSphere", PositionMode::None => "none" },
"maps": settings.maps.enabled().map(|m| m.id()).collect::<Vec<_>>(),
"enabled": settings.common.is_enabled,
"useLowAsHigh": settings.high_poly.use_low_as_high,
"maxFrontal": settings.cage.max_frontal,
"maxRear": settings.cage.max_rear,
"averageNormals": settings.cage.average_normals,
"lowSuffix": settings.high_poly.low_suffix,
"highSuffix": settings.high_poly.high_suffix,
})
}
/// Apply the `bake.settings` parameters present in `p` to `b`.
fn apply_settings(b: &mut BakeSettings, p: &Value, cmd: &str) -> Result<()> {
if let Some(r) = u64p(p, "resolution") {
b.resolution = crate::session::check_resolution(u32::try_from(r).unwrap_or(0))?;
}
if let Some(a) = u64p(p, "antialiasing") {
if ![1, 2, 4, 8].contains(&a) {
return Err(bad(cmd, "antialiasing must be 1, 2, 4 or 8"));
}
b.antialiasing = a as u32;
}
if let Some(d) = u64p(p, "dilation") {
b.dilation = d.min(256) as u32;
}
// `rays` / `maxDistance` set every ray map; the per-map objects override.
for r in [&mut b.ao, &mut b.thickness, &mut b.bent_normal] {
apply_rays(r, p, cmd)?;
}
for (k, r) in [("ao", &mut b.ao), ("thickness", &mut b.thickness), ("bentNormal", &mut b.bent_normal)] {
if let Some(o) = p.get(k) {
apply_rays(r, o, cmd)?;
/// Apply only the bake parameters supplied by the caller
fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> Result<()> {
// Keep the current command limits until the reference controls are integrated
const MAX_DILATION_PIXELS: u32 = 256;
const MAX_SUFFIX_CHARS: usize = 64;
if let Some(model) = params.get("model") {
let replacement: BakeSettings = serde_json::from_value(model.clone()).map_err(|error| bad(command, error.to_string()))?;
validate_model_settings(&replacement, command)?;
let is_enabled = settings.common.is_enabled;
*settings = replacement;
if boolp(params, "preserveEnabled") == Some(true) {
settings.common.is_enabled = is_enabled;
}
}
if let Some(ao) = p.get("ao") {
if let Some(v) = boolp(ao, "ignoreBackface") {
b.ao_ignore_backface = v;
}
if let Some(v) = strp(ao, "selfOcclusion") {
b.ao_self_occlusion = SELF_OCCLUSION.parse(cmd, "selfOcclusion", v)?;
}
if let Some(resolution) = u64p(params, "resolution") {
settings.common.resolution = u32::try_from(resolution)
.ok()
.and_then(BakeResolution::from_pixels)
.ok_or_else(|| bad(command, "resolution must be a power of two from 16 to 8192"))?;
}
if let Some(v) = strp(p, "positionMode") {
b.position_mode = POSITION_MODE.parse(cmd, "positionMode", v)?;
if let Some(antialiasing) = u64p(params, "antialiasing") {
settings.common.antialiasing = u32::try_from(antialiasing)
.ok()
.and_then(BakeAntialiasing::from_samples_per_axis)
.ok_or_else(|| bad(command, "antialiasing must be 1, 2, 4 or 8"))?;
}
if let Some(v) = strp(p, "directionMode") {
b.direction_mode = DIRECTION_MODE.parse(cmd, "directionMode", v)?;
if let Some(dilation) = u64p(params, "dilation") {
settings.common.dilation = dilation.min(u64::from(MAX_DILATION_PIXELS)) as u32;
}
if let Some(r) = u64p(p, "curvatureRadius") {
b.curvature_radius = r.min(64) as u32;
// Per-map values override the shared ray settings
for ray_settings in [&mut settings.maps.ao.parameters.rays, &mut settings.maps.thickness.parameters.rays, &mut settings.maps.bent_normal.parameters.rays] {
apply_rays(ray_settings, params, command)?;
}
for (k, slot, lo, hi) in
[("curvatureStrength", &mut b.curvature_strength, 0.0, 16.0), ("maxFrontal", &mut b.max_frontal, 0.0, 1.0), ("maxRear", &mut b.max_rear, 0.0, 1.0)]
{
if let Some(v) = f32p(p, k).filter(|v| v.is_finite()) {
*slot = v.clamp(lo, hi);
}
}
for (k, slot) in [
("curvatureFromNormal", &mut b.curvature_from_normal),
("enabled", &mut b.enabled),
("useLowAsHigh", &mut b.use_low_as_high),
("averageNormals", &mut b.average_normals),
for (key, ray_settings) in [
("ao", &mut settings.maps.ao.parameters.rays),
("thickness", &mut settings.maps.thickness.parameters.rays),
("bentNormal", &mut settings.maps.bent_normal.parameters.rays),
] {
if let Some(v) = boolp(p, k) {
*slot = v;
if let Some(map_params) = params.get(key) {
apply_rays(ray_settings, map_params, command)?;
}
}
if let Some(d) = p.get("direction") {
let v: Vec<f32> = d.as_array().into_iter().flatten().filter_map(Value::as_f64).map(|x| x as f32).collect();
match v[..] {
[x, y, z] if [x, y, z].iter().all(|c| c.is_finite()) && [x, y, z] != [0.0; 3] => b.direction = [x, y, z],
_ => return Err(bad(cmd, "`direction` must be three finite numbers, not all zero")),
if let Some(ao) = params.get("ao") {
if let Some(value) = ao.get("ignoreBackface") {
let mode = value.as_str().ok_or_else(|| bad(command, "ignoreBackface must be never, always or byMeshName"))?;
settings.maps.ao.parameters.ignore_backface = match mode {
"never" => BackfaceMode::Never,
"always" => BackfaceMode::Always,
"byMeshName" => BackfaceMode::ByMeshName,
_ => return Err(bad(command, "ignoreBackface must be never, always or byMeshName")),
};
}
if let Some(self_occlusion) = strp(ao, "selfOcclusion") {
settings.maps.ao.parameters.self_occlusion = match self_occlusion {
"always" => SelfOcclusion::Always,
"sameMeshName" => SelfOcclusion::SameMeshName,
_ => return Err(bad(command, "selfOcclusion must be always or sameMeshName")),
};
}
}
if let Some(a) = p.get("maps").and_then(Value::as_array) {
b.maps = a.iter().map(|v| v.as_str().and_then(BakedMap::parse).ok_or_else(|| bad(cmd, format!("unknown mesh map {v}")))).collect::<Result<_>>()?;
if let Some(position_mode) = strp(params, "positionMode") {
settings.maps.position.parameters.normalization = match position_mode {
"boundingBox" => PositionMode::BoundingBox,
"boundingSphere" => PositionMode::BoundingSphere,
"none" => PositionMode::None,
_ => return Err(bad(command, "positionMode must be boundingBox, boundingSphere or none")),
};
}
match strp(p, "matching") {
Some("always") => b.matching = BakeMatch::Always,
Some("byMeshName") | Some("byName") => b.matching = BakeMatch::ByMeshName,
Some(o) => return Err(bad(cmd, format!("unknown matching `{o}` (always|byMeshName)"))),
None => {}
if let Some(value) = params.get("curvatureMethod") {
let method = value.as_str().ok_or_else(|| bad(command, "curvatureMethod must be normalMap or mesh"))?;
settings.maps.curvature.parameters.method = match method {
"normalMap" => CurvatureMethod::NormalMap,
"mesh" => CurvatureMethod::Mesh,
_ => return Err(bad(command, "curvatureMethod must be normalMap or mesh")),
};
}
for (k, slot) in [("lowSuffix", &mut b.low_suffix), ("highSuffix", &mut b.high_suffix)] {
if let Some(v) = strp(p, k) {
*slot = v.chars().take(64).collect();
for (key, setting, minimum, maximum) in [("maxFrontal", &mut settings.cage.max_frontal, 0.0, 1.0), ("maxRear", &mut settings.cage.max_rear, 0.0, 1.0)] {
if let Some(value) = f32p(params, key).filter(|value| value.is_finite()) {
*setting = value.clamp(minimum, maximum);
}
}
for (key, setting) in [
("enabled", &mut settings.common.is_enabled),
("useLowAsHigh", &mut settings.high_poly.use_low_as_high),
("averageNormals", &mut settings.cage.average_normals),
] {
if let Some(value) = boolp(params, key) {
*setting = value;
}
}
if let Some(maps) = params.get("maps").and_then(Value::as_array) {
let selected = maps
.iter()
.map(|map| map.as_str().and_then(BakedMap::parse).ok_or_else(|| bad(command, format!("unknown mesh map {map}"))))
.collect::<Result<Vec<_>>>()?;
settings.maps.select(selected);
}
for (key, setting) in [("lowSuffix", &mut settings.high_poly.low_suffix), ("highSuffix", &mut settings.high_poly.high_suffix)] {
if let Some(suffix) = strp(params, key) {
*setting = suffix.chars().take(MAX_SUFFIX_CHARS).collect();
}
}
Ok(())
}
fn validate_model_settings(settings: &BakeSettings, command: &str) -> Result<()> {
let range = |name: &str, value: f32, minimum: f32, maximum: f32| {
if value.is_finite() && (minimum..=maximum).contains(&value) { Ok(()) } else { Err(bad(command, format!("{name} must be in {minimum}..={maximum}"))) }
};
if settings.common.dilation > 128 {
return Err(bad(command, "dilation must be at most 128"));
}
for rays in [&settings.maps.ao.parameters.rays, &settings.maps.thickness.parameters.rays, &settings.maps.bent_normal.parameters.rays] {
if !(1..=256).contains(&rays.rays) {
return Err(bad(command, "secondary rays must be in 1..=256"));
}
range("minimum occluder distance", rays.min_distance, 0.00001, 1.0)?;
range("maximum occluder distance", rays.max_distance, 0.00001, if rays.relative_to_bounding_box { 1.0 } else { 10.0 })?;
range("spread angle", rays.spread, 0.0, 180.0)?;
if rays.min_distance > rays.max_distance {
return Err(bad(command, "minimum occluder distance must not exceed maximum distance"));
}
}
let curvature = &settings.maps.curvature.parameters;
if !(1..=256).contains(&curvature.mesh.rays) {
return Err(bad(command, "curvature rays must be in 1..=256"));
}
if !curvature.mesh.auto_tonemapping && curvature.mesh.value_min >= curvature.mesh.value_max {
return Err(bad(command, "curvature minimum must be below maximum"));
}
range("sampling radius", curvature.mesh.sampling_radius, 0.00001, if curvature.mesh.relative_to_bounding_box { 10.0 } else { 1.0 })?;
for (name, value, minimum, maximum) in [
("frontal distance", settings.cage.max_frontal, 0.0, 0.05),
("rear distance", settings.cage.max_rear, 0.0, 0.05),
("edge distance", settings.skew.edge_distance, 0.0, 1.0),
("edge contrast", settings.skew.edge_contrast, 0.0, 1.0),
("ground plane offset", settings.maps.ao.parameters.ground_plane.offset, 0.0, 100.0),
("curvature details", curvature.normal_map.details, 0.0, 1.0),
("seams intensity", curvature.normal_map.seams_intensity, 0.0, 1.0),
("value bounds minimum", curvature.mesh.value_min, -10.0, 10.0),
("value bounds maximum", curvature.mesh.value_max, -10.0, 10.0),
("height scaling divisor", settings.maps.height.parameters.scaling_divisor, 0.00001, 100.0),
] {
range(name, value, minimum, maximum)?;
}
Ok(())
}
/// Parameter names of a settings enum.
struct Names<T: 'static>(&'static [(&'static str, T)]);
impl<T: Copy + PartialEq> Names<T> {
fn name(&self, v: T) -> &'static str {
self.0.iter().find(|(_, x)| *x == v).map_or("", |(n, _)| n)
}
fn parse(&self, cmd: &str, key: &str, s: &str) -> Result<T> {
let all = || self.0.iter().map(|(n, _)| *n).collect::<Vec<_>>().join("|");
self.0.iter().find(|(n, _)| *n == s).map(|(_, v)| *v).ok_or_else(|| bad(cmd, format!("unknown {key} `{s}` ({})", all())))
}
/// Ray settings supported by the current bake command
fn rays_params(settings: &RaySettings) -> Value {
json!({
"rays": settings.rays,
"maxDistance": settings.max_distance,
"spread": settings.spread,
"distribution": match settings.distribution {
RayDistribution::Cosine => "cosine",
RayDistribution::Uniform => "uniform",
},
})
}
const SELF_OCCLUSION: Names<SelfOcclusion> = Names(&[("always", SelfOcclusion::Always), ("sameMeshName", SelfOcclusion::SameMeshName)]);
const DISTRIBUTION: Names<RayDistribution> = Names(&[("cosine", RayDistribution::Cosine), ("uniform", RayDistribution::Uniform)]);
const POSITION_MODE: Names<PositionMode> = Names(&[("boundingBox", PositionMode::BoundingBox), ("boundingSphere", PositionMode::BoundingSphere)]);
const DIRECTION_MODE: Names<DirectionMode> = Names(&[("signed", DirectionMode::Signed), ("positive", DirectionMode::Positive)]);
/// `r` as `bake.settings` parameters.
fn rays_params(r: &RaySettings) -> Value {
json!({ "rays": r.rays, "maxDistance": r.max_distance, "spread": r.spread, "distribution": DISTRIBUTION.name(r.distribution) })
}
/// Apply the ray parameters present in `p` (`rays`, `maxDistance`, `spread`, `distribution`).
fn apply_rays(r: &mut RaySettings, p: &Value, cmd: &str) -> Result<()> {
if let Some(n) = u64p(p, "rays") {
r.rays = n.clamp(1, u64::from(MAX_RAYS)) as u32;
/// Apply only the ray parameters supplied by the caller
fn apply_rays(settings: &mut RaySettings, params: &Value, command: &str) -> Result<()> {
if let Some(count) = u64p(params, "rays") {
settings.rays = count.clamp(1, u64::from(MAX_RAYS)) as u32;
}
for (k, slot, lo, hi) in [("maxDistance", &mut r.max_distance, 0.001, 10.0), ("spread", &mut r.spread, 0.0, 180.0)] {
if let Some(v) = f32p(p, k).filter(|v| v.is_finite()) {
*slot = v.clamp(lo, hi);
for (key, setting, minimum, maximum) in [("maxDistance", &mut settings.max_distance, 0.001, 10.0), ("spread", &mut settings.spread, 0.0, 180.0)] {
if let Some(value) = f32p(params, key).filter(|value| value.is_finite()) {
*setting = value.clamp(minimum, maximum);
}
}
if let Some(v) = strp(p, "distribution") {
r.distribution = DISTRIBUTION.parse(cmd, "distribution", v)?;
if let Some(distribution) = strp(params, "distribution") {
settings.distribution = match distribution {
"cosine" => RayDistribution::Cosine,
"uniform" => RayDistribution::Uniform,
_ => return Err(bad(command, "distribution must be cosine or uniform")),
};
}
Ok(())
}
/// Validate and apply the settings parameters to every set first, so a bad parameter changes
/// nothing.
fn set_settings(s: &mut Session, p: &Value, cmd: &str) -> Result<Vec<usize>> {
let sets = sets_param(s, cmd, p)?;
let mut next = Vec::with_capacity(sets.len());
for &ts in &sets {
let mut b = s.doc.project.texture_set(ts)?.bake.clone();
apply_settings(&mut b, p, cmd)?;
next.push((ts, b));
}
for (ts, b) in next {
let set = s.doc.project.texture_set_mut(ts)?;
if set.bake != b {
set.bake = b;
s.modified = true;
}
fn updated_settings(session: &Session, params: &Value, command: &str) -> Result<Vec<(usize, BakeSettings)>> {
sets_param(session, command, params)?
.into_iter()
.map(|index| {
let mut settings = session.doc.project.texture_set(index)?.bake.clone();
apply_settings(&mut settings, params, command)?;
Ok((index, settings))
})
.collect()
}
fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result<Vec<usize>> {
let next = updated_settings(session, params, command)?;
let sets = next.iter().map(|(index, _)| *index).collect();
if next.iter().any(|(index, settings)| session.doc.project.texture_sets.get(*index).is_some_and(|set| set.bake != *settings)) {
session.edit("Bake Settings", |session| {
for (index, settings) in next {
session.doc.project.texture_set_mut(index)?.bake = settings;
}
Ok(())
})?;
}
Ok(sets)
}
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
let sets = set_settings(s, p, "bake.settings")?;
let out: Vec<Value> =
sets.iter().filter_map(|t| s.doc.project.texture_sets.get(*t).map(|set| json!({ "ts": t, "settings": settings_params(&set.bake) }))).collect();
Ok(json!(out))
}
fn bake_run(s: &mut Session, p: &Value) -> Result<Value> {
let sets = set_settings(s, p, "bake.run")?;
let cpu = boolp(p, "cpu") == Some(true);
let tracer = sets.iter().map(|&ts| s.bake_now(ts, cpu)).collect::<Result<Vec<_>>>()?;
s.update();
Ok(json!({ "baked": sets, "tracer": tracer }))
}
fn skew_paint(s: &mut Session, p: &Value) -> Result<Value> {
use texturecraft_geom::glam::Vec2;
let cmd = "bake.skew.paint";
const MAX_POINTS: usize = 100_000;
let points: Vec<Vec2> = p
.get("points")
.and_then(Value::as_array)
.ok_or_else(|| bad(cmd, "`points` is required: [[u, v], ...]"))?
fn settings(session: &mut Session, params: &Value) -> Result<Value> {
let sets = set_settings(session, params, "bake.settings")?;
let result: Vec<Value> = sets
.iter()
.map(|q| match (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) {
(Some(u), Some(v)) => Ok(Vec2::new(u as f32, v as f32)),
_ => Err(bad(cmd, "each point is [u, v]")),
.filter_map(|set_index| {
session
.doc
.project
.texture_sets
.get(*set_index)
.map(|texture_set| json!({ "ts": set_index, "settings": settings_params(&texture_set.bake), "model": &texture_set.bake }))
})
.collect::<Result<_>>()?;
if points.is_empty() || points.len() > MAX_POINTS {
return Err(bad(cmd, format!("give 1 to {MAX_POINTS} points")));
}
let size = p.get("size").and_then(Value::as_u64).unwrap_or(1024);
if !(16..=4096).contains(&size) {
return Err(bad(cmd, "`size` is 16 to 4096"));
}
let (value, radius) = (f32p(p, "value").unwrap_or(1.0), f32p(p, "radius").unwrap_or(0.03));
if !(radius.is_finite() && radius > 0.0 && radius <= 1.0) {
return Err(bad(cmd, "`radius` is above 0 and at most 1 (uv units)"));
}
let (hardness, strength) = (f32p(p, "hardness").unwrap_or(0.5), f32p(p, "strength").unwrap_or(1.0));
let stroke = |m: &mut SkewMap| m.paint(&points, radius, value, hardness, strength).map_err(|e| bad(cmd, e.to_string()));
match s.bake_meshes.skew.as_mut() {
// In place: the map is copied only while a running bake still holds it, and `paint`
// refuses a stroke before it changes a texel.
Some(k) if k.values.len() > 1 => stroke(Arc::make_mut(k))?,
// A constant map has no resolution to paint at: widen it, keeping its value everywhere.
k => {
let mut map = match k {
Some(k) => k.resized(size as u32, size as u32),
None => SkewMap::constant(0.0).resized(size as u32, size as u32),
.collect();
Ok(json!(result))
}
fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
let next = updated_settings(session, params, "bake.run")?;
let sets: Vec<usize> = next.iter().map(|(index, _)| *index).collect();
let cpu = boolp(params, "cpu") == Some(true);
let tracers = session.edit("Bake mesh maps", |session| {
let mut tracers = Vec::with_capacity(next.len());
for (index, settings) in next {
session.doc.project.texture_set_mut(index)?.bake = settings;
let mut task = session.bake_task(index)?;
if cpu {
task.tracer = None;
}
.map_err(|e| bad(cmd, e.to_string()))?;
stroke(&mut map)?;
s.bake_meshes.skew = Some(Arc::new(map));
let output = task.run(&Progress::new())?;
tracers.push(output.tracer.clone());
session.store_bake(index, output)?;
}
Ok(tracers)
})?;
for (index, tracer) in sets.iter().zip(&tracers) {
session.log.push(format!("Baked texture set {index} ({tracer})"));
}
s.bake_meshes.skew_rev += 1;
s.modified = true;
Ok(meshes_json(s))
session.update();
Ok(json!({ "baked": sets, "tracer": tracers }))
}
+147
View File
@@ -0,0 +1,147 @@
use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p};
use crate::{Result, Session, cmd};
use serde_json::Value;
use std::sync::Arc;
use texturecraft_bake::BakePaintMap;
use texturecraft_core::BakePaintTarget;
use texturecraft_geom::glam::Vec2;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("bake.skew.set", "Set Skew Correction", [], None, "{ts?, value?: 0..1 | path: grayscale image}", always, |session, parameters| set(
session,
parameters,
BakePaintTarget::Skew
)),
cmd!(
"bake.skew.paint",
"Paint Skew Correction",
[],
None,
"{ts?, points: [[u,v],...], radius?: 0.03, value?: 1, hardness?: 0.5, strength?: 1, size?: 1024, continue?: false}",
always,
|session, parameters| paint(session, parameters, BakePaintTarget::Skew)
),
cmd!("bake.skew.clear", "Remove Skew Correction", [], None, "{ts?}", always, |session, parameters| clear(session, parameters, BakePaintTarget::Skew)),
cmd!(
"bake.cage.paint",
"Paint Cage",
[],
None,
"{ts?, points: [[u,v],...], radius?: 0.03, value?: 1 (frontal distance multiplier, 0..1), hardness?: 0.5, strength?: 1, size?: 1024, continue?: false}",
always,
|session, parameters| paint(session, parameters, BakePaintTarget::Cage)
),
cmd!("bake.cage.reset", "Reset Painted Cage", [], None, "{ts?}", always, |session, parameters| clear(session, parameters, BakePaintTarget::Cage)),
]
}
fn texture_set(session: &Session, parameters: &Value) -> Result<usize> {
let index = match parameters.get("ts") {
None => session.ts(),
Some(value) => value.as_u64().and_then(|value| usize::try_from(value).ok()).ok_or_else(|| bad("bake.paint", "ts must be a texture set index"))?,
};
session.doc.project.texture_set(index)?;
Ok(index)
}
fn number(parameters: &Value, name: &str, default: f32, minimum: f32, maximum: f32) -> Result<f32> {
if parameters.get(name).is_none() {
return Ok(default);
}
f32p(parameters, name)
.filter(|value| (minimum..=maximum).contains(value))
.ok_or_else(|| bad("bake.paint", format!("{name} must be in {minimum}..={maximum}")))
}
fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result<Value> {
let texture_set = texture_set(session, parameters)?;
let map = match strp(parameters, "path") {
Some(path) => load_image(path)?,
None => BakePaintMap::constant(number(parameters, "value", 1.0, 0.0, 1.0)?),
};
map.validate().map_err(|error| bad("bake.paint", error.to_string()))?;
session.edit("Set Bake Paint Map", |session| {
session.doc.bake_paint.insert((texture_set, target), Arc::new(map));
Ok(())
})?;
Ok(crate::bake_cmds::meshes_json(session))
}
fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result<Value> {
let texture_set = texture_set(session, parameters)?;
if session.doc.bake_paint.contains_key(&(texture_set, target)) {
session.edit("Clear Bake Paint Map", |session| {
session.doc.bake_paint.remove(&(texture_set, target));
Ok(())
})?;
}
Ok(crate::bake_cmds::meshes_json(session))
}
fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result<Value> {
const MAX_POINTS: usize = 100_000;
let texture_set = texture_set(session, parameters)?;
let points = parameters
.get("points")
.and_then(Value::as_array)
.filter(|points| !points.is_empty() && points.len() <= MAX_POINTS)
.ok_or_else(|| bad("bake.paint", "points must contain 1 to 100000 UV coordinates"))?;
let points = points
.iter()
.map(|point| {
let coordinate = |index| point.get(index).and_then(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite());
match (coordinate(0), coordinate(1)) {
(Some(u), Some(v)) => Ok(Vec2::new(u, v)),
_ => Err(bad("bake.paint", "each point must contain two finite UV coordinates")),
}
})
.collect::<Result<Vec<_>>>()?;
let value = number(parameters, "value", 1.0, 0.0, 1.0)?;
let radius = number(parameters, "radius", 0.03, 0.00001, 1.0)?;
let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?;
let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?;
let size = match parameters.get("size") {
None => 1024,
Some(_) => u64p(parameters, "size").ok_or_else(|| bad("bake.paint", "size must be an integer"))?,
};
if !(16..=4096).contains(&size) {
return Err(bad("bake.paint", "size must be between 16 and 4096"));
}
let default = match target {
BakePaintTarget::Cage => 1.0,
BakePaintTarget::Skew => 0.0,
};
let label = match target {
BakePaintTarget::Cage => "Paint Cage",
BakePaintTarget::Skew => "Paint Skew Correction",
};
session.edit_merging(label, boolp(parameters, "continue") == Some(true), |session| {
let map = session.doc.bake_paint.entry((texture_set, target)).or_insert_with(|| Arc::new(BakePaintMap::constant(default)));
if map.values.len() == 1 {
*map = Arc::new(map.resized(size as u32, size as u32).map_err(|error| bad("bake.paint", error.to_string()))?);
}
Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string()))
})?;
Ok(crate::bake_cmds::meshes_json(session))
}
#[cfg(not(target_arch = "wasm32"))]
fn load_image(path: &str) -> Result<BakePaintMap> {
let length = std::fs::metadata(path).map_err(|error| bad("bake.paint", error.to_string()))?.len();
if length > 256 << 20 {
return Err(bad("bake.paint", "image exceeds 256 MiB"));
}
let bytes = std::fs::read(path).map_err(|error| bad("bake.paint", error.to_string()))?;
let image = texturecraft_formats::decode_image_within(&bytes, texturecraft_bake::MAX_TEXELS).map_err(|error| bad("bake.paint", error.to_string()))?;
Ok(BakePaintMap {
width: image.width,
height: image.height,
values: image.rgba.iter().map(|pixel| ((pixel[0] + pixel[1] + pixel[2]) / 3.0).clamp(0.0, 1.0)).collect(),
})
}
#[cfg(target_arch = "wasm32")]
fn load_image(_: &str) -> Result<BakePaintMap> {
Err(bad("bake.paint", "file paths are unavailable in the browser"))
}
+1 -1
View File
@@ -68,8 +68,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::uv_tile_cmds::specs());
v.extend(crate::template_cmds::specs());
v.extend(crate::project_cmds::specs());
v.extend(crate::auto_rebake::specs());
v.extend(crate::bake_cmds::specs());
v.extend(crate::bake_paint_cmds::specs());
v.extend(crate::materialx_cmds::specs());
v.extend(crate::file_cmds::specs());
v.extend(crate::preset_cmds::specs());
+11 -4
View File
@@ -174,20 +174,25 @@ impl Session {
(Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh,
(None, None) => return Err(EngineError::Other("the project has no mesh".into())),
};
check_materials(&pf.project, &mesh)?;
let source = pf.mesh.clone();
let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect();
let mut s = Session::new(Document { project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?;
let mut s =
Session::new(Document { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?;
s.sync_images();
s.load_bake_meshes(pf.high_poly, pf.cage);
s.load_skew(pf.skew);
s.load_bake_paint(pf.bake_paint);
s.log.extend(pf.warnings);
Ok(s)
}
/// The project as a `ProjectFile` (for saving).
pub fn project_file(&self) -> ProjectFile {
let mut pixels = self.doc.pixels.clone();
// Drop pixel images whose size no longer matches their texture set (never unloadable).
// Drop pixel images whose size no longer matches their texture set
let size_of = |id: texturecraft_core::LayerId| {
self.doc.project.locate(id).and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| {
self.doc
@@ -200,6 +205,7 @@ impl Session {
};
pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height())));
pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
let (high_poly, cage) = self.saved_bake_meshes();
ProjectFile {
project: self.doc.project.clone(),
@@ -208,9 +214,10 @@ impl Session {
mesh: self.mesh_source.clone(),
high_poly,
cage,
skew: self.saved_skew(),
bake_paint: self.saved_bake_paint(),
thumbnail: None,
resources: self.doc.resources.iter().map(|(k, v)| (k.clone(), v.as_ref().clone())).collect(),
warnings: Vec::new(),
}
}
+4 -2
View File
@@ -8,8 +8,10 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod auto_rebake;
pub mod bake_cmds;
#[path = "bake/mod.rs"]
mod bake_data;
mod bake_paint_cmds;
pub mod brush_preset_cmds;
pub mod camera_cmds;
pub mod commands;
@@ -46,7 +48,7 @@ pub mod tool_cmds;
pub mod uv_tile_cmds;
pub mod view_cmds;
pub use bake_cmds::{BakeMesh, BakeMeshes, BakeTask};
pub use bake_data::{BakeMesh, BakeMeshes, BakeTask};
pub use commands::{CommandSpec, command_specs, execute, find};
pub use path_tool::PathState;
pub use project_cmds::sample_session;
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more