Merge pull request #748 from vangel76/feat/uv-unwrap-on-import

Allow rebuilding mesh UVs in New Project
This commit is contained in:
Chris Hassebrook authored and GitHub committed 2026-11-25 20:43:13 -05:00
commit 1abfa79a89
19 files changed
+723 -120

No files matched your search

+16 -3
View File
@@ -9,12 +9,15 @@ use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, Conte
pub use crate::env_alignment::EnvAlignment;
pub use crate::shadow_mode::ShadowMode;
/// Project file format. 3: bent normal maps are in tangent space (older files hold world-space ones).
pub const FORMAT_VERSION: u32 = 3;
/// Latest project file format that TextureCraft can read.
pub const FORMAT_VERSION: u32 = REBUILT_MESH_UVS_VERSION;
/// First format whose baked bent normal maps are in tangent space
pub const TANGENT_BENT_NORMAL_VERSION: u32 = 3;
/// First format that can reopen a project using rebuilt mesh UVs.
pub const REBUILT_MESH_UVS_VERSION: u32 = 4;
/// Most colour swatches a project keeps
pub const MAX_SWATCHES: usize = 64;
@@ -429,6 +432,10 @@ pub struct Project {
/// it, so parts the file leaves unnamed get the same name (from it) as on import.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub mesh_file: String,
/// The mesh UVs were rebuilt on import. The project file keeps the generated layout for
/// reopening; reimporting the mesh from a file rebuilds them again.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub mesh_rebuild_uvs: bool,
/// Where the mesh file was imported from (the project's "3D mesh path"). Reimport mesh reads
/// it again from there, so edits made to the file since are picked up. Empty when unknown
/// (built-in meshes, web imports, projects saved before it was kept).
@@ -450,10 +457,11 @@ pub struct Project {
impl Project {
pub fn new(name: impl Into<String>, mesh: impl Into<String>) -> Project {
Project {
format_version: FORMAT_VERSION,
format_version: TANGENT_BENT_NORMAL_VERSION,
name: name.into(),
mesh: mesh.into(),
mesh_file: String::new(),
mesh_rebuild_uvs: false,
mesh_path: String::new(),
normal_format: NormalFormat::OpenGl,
texture_sets: Vec::new(),
@@ -465,6 +473,11 @@ impl Project {
}
}
/// The on-disk version that preserves the project's UV layout when read back.
pub fn save_format_version(&self) -> u32 {
if self.mesh_rebuild_uvs { self.format_version.max(REBUILT_MESH_UVS_VERSION) } else { self.format_version }
}
pub fn alloc_id(&mut self) -> LayerId {
let id = LayerId(self.next_id);
self.next_id = self.next_id.saturating_add(1);
+85 -35
View File
@@ -12,7 +12,9 @@ use serde_json::{Value, json};
use texturecraft_core::{NormalFormat, PROJECT_EXT};
use texturecraft_core::{Project, TextureSet};
use texturecraft_formats::PlannedFile;
use texturecraft_formats::mesh_import::{MeshUvSource, import_mesh_geometry};
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Mesh, primitives};
use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p};
@@ -26,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New project from a mesh file",
[],
None,
"{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}",
"{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), rebuildUvs?: bool (default false: auto-unwrap where needed), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}",
always,
new_from_mesh
),
@@ -101,10 +103,13 @@ fn leaf_of(name: &str) -> String {
}
/// Read the project's stored mesh `bytes` (extension `ext`) under the name it was imported
/// with, so its unnamed parts keep their names (and the geometry masks that use them).
fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8]) -> Result<texturecraft_formats::ImportedMesh> {
let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("mesh");
texturecraft_formats::import_mesh_bytes(&format!("{stem}.{ext}"), bytes).map_err(fe)
/// with, so its unnamed parts keep their names (and the geometry masks that use them). A saved
/// UV layout replaces the file's UVs and the automatic unwrap.
fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Option<&[Vec2]>) -> Result<Mesh> {
let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|stem| stem.to_str()).filter(|stem| !stem.is_empty()).unwrap_or("mesh");
let file_name = format!("{stem}.{ext}");
import_mesh_geometry(&file_name, bytes, saved_layout.map_or(MeshUvSource::FromFile, MeshUvSource::Saved)).map_err(fe)
}
impl Session {
@@ -163,11 +168,16 @@ impl Session {
/// [`Session::from_mesh_bytes`] with a UV tile mode (see [`Session::new_project_tiled`]).
pub fn from_mesh_bytes_tiled(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option<bool>) -> Result<Session> {
Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles)
Self::from_mesh_bytes_with_uvs(file_name, bytes, resolution, name, uv_tiles, false)
}
fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option<bool>) -> Result<Session> {
let imported = texturecraft_formats::import_mesh_bytes(file_name, &bytes).map_err(fe)?;
/// Create a project with an explicit choice to rebuild the imported mesh's UVs.
pub fn from_mesh_bytes_with_uvs(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option<bool>, rebuild_uvs: bool) -> Result<Session> {
Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles, rebuild_uvs)
}
fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option<bool>, rebuild_uvs: bool) -> Result<Session> {
let imported = texturecraft_formats::mesh_import::import_mesh_bytes_with_uvs(file_name, &bytes, rebuild_uvs).map_err(fe)?;
let extension = ext_of(file_name);
let mut session = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{extension}"), None, resolution, uv_tiles)?;
@@ -176,6 +186,7 @@ impl Session {
source.shrink_to_fit();
session.mesh_source = Some((extension, source));
session.doc.project.mesh_file = leaf_of(file_name);
session.doc.project.mesh_rebuild_uvs = rebuild_uvs;
session.doc.project.cameras = imported.cameras;
session.log.warnings("Importer", imported.report.warnings);
@@ -199,29 +210,39 @@ impl Session {
Session::from_project_file(pf)
}
pub fn from_project_file(pf: ProjectFile) -> Result<Session> {
let mesh = match (&pf.mesh, pf.project.mesh.strip_prefix("builtin:")) {
pub fn from_project_file(project_file: ProjectFile) -> Result<Session> {
project_file.validate_mesh_uvs().map_err(fe)?;
let mesh = match (&project_file.mesh, project_file.project.mesh.strip_prefix("builtin:")) {
(_, Some(id)) => primitives::builtin(id).ok_or_else(|| EngineError::Other(format!("unknown built-in mesh `{id}`")))?,
(Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh,
(Some((ext, bytes)), None) => read_stored_mesh(&project_file.project, ext, bytes, project_file.mesh_uvs.as_deref())?,
(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();
// Mesh construction consumed the layout data, so release it before building session caches
drop(project_file.mesh_uvs);
check_materials(&project_file.project, &mesh)?;
let resources = project_file.resources.into_iter().map(|(name, bytes)| (name, Arc::new(bytes))).collect();
let mut s = Session::new(
Document { bake_meshes: Default::default(), bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources },
let mut session = Session::new(
Document {
bake_meshes: Default::default(),
bake_paint: Default::default(),
project: project_file.project,
pixels: project_file.pixels,
baked: project_file.baked,
resources,
},
mesh,
source,
project_file.mesh,
)?;
s.sync_images();
s.load_bake_meshes(pf.high_poly, pf.cage);
s.load_bake_paint(pf.bake_paint);
s.log.warnings("Project", pf.warnings);
session.sync_images();
session.load_bake_meshes(project_file.high_poly, project_file.cage);
session.load_bake_paint(project_file.bake_paint);
session.log.warnings("Project", project_file.warnings);
Ok(s)
Ok(session)
}
/// The project with independently owned resource bytes.
@@ -235,6 +256,11 @@ impl Session {
self.project_with_resources(self.doc.resources.clone())
}
/// The layout a project with rebuilt mesh UVs saves, so reopening it never runs the unwrapper.
fn saved_uv_layout(&self) -> Option<Vec<Vec2>> {
(self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then(|| texturecraft_formats::mesh_import::corner_uvs(&self.source))
}
fn project_with_resources<Resource>(&self, resources: BTreeMap<String, Resource>) -> ProjectFile<Resource> {
let mut pixels = self.doc.pixels.clone();
@@ -253,11 +279,15 @@ impl Session {
pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
let (high_poly, cage) = self.saved_bake_meshes();
let mut project = self.doc.project.clone();
project.format_version = project.save_format_version();
ProjectFile {
project: self.doc.project.clone(),
project,
pixels,
baked: self.doc.baked.clone(),
mesh: self.mesh_source.clone(),
mesh_uvs: self.saved_uv_layout(),
high_poly,
cage,
bake_paint: self.saved_bake_paint(),
@@ -523,7 +553,7 @@ mod native {
#[cfg(not(target_arch = "wasm32"))]
pub use native::{absolute, open_path, read_mesh};
/// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the
/// `file.new {mesh, name?, resolution?, uvTiles?, rebuildUvs?, template?, importCameras?}`: a new project from the
/// mesh file `mesh`, remembering its path for Reimport mesh.
#[cfg(not(target_arch = "wasm32"))]
fn new_from_mesh(session: &mut Session, params: &Value) -> Result<Value> {
@@ -534,9 +564,11 @@ fn new_from_mesh(session: &mut Session, params: &Value) -> Result<Value> {
let resolution = u64p(params, "resolution").or(template.as_ref().map(|template| u64::from(template.resolution))).unwrap_or(DEFAULT_RESOLUTION_PX);
let name = strp(params, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
let uv_tiles = crate::commands::boolp(params, "uvTiles");
let rebuild_uvs = crate::commands::boolp(params, "rebuildUvs").unwrap_or(false);
let mesh_file = native::read_mesh("file.new", path)?;
let mut next = Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles)?;
let mut next =
Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles, rebuild_uvs)?;
next.doc.project.mesh_path = native::absolute(path);
next.log.warnings("Importer", mesh_file.warnings);
if crate::commands::boolp(params, "importCameras") == Some(false) {
@@ -599,9 +631,11 @@ fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
fn change_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "path", "file.changeMesh")?;
let file = native::read_mesh("file.changeMesh", path)?;
let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?;
// Only after the swap succeeded: Reimport mesh and Save keep following the new file.
let reply = s.replace_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true), false)?;
// Keep following the original path if the swap fails
s.doc.project.mesh_path = native::absolute(path);
Ok(reply)
}
@@ -612,16 +646,24 @@ impl Session {
Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file())
}
/// Replace the mesh with `file` (or re-read the project's own copy), keeping the project when the new mesh fits it; `preserve_strokes` moves painted pixels with the surface; replies `{preserved?}`
/// Replace the mesh with `file` or re-read the project's own copy.
/// With `preserve_strokes`, painted pixels follow the surface. The reply includes
/// `preserved` when preservation was requested.
pub fn reimport_mesh(&mut self, file: Option<texturecraft_formats::MeshFile>, preserve_strokes: bool) -> Result<Value> {
let (mesh, source, warnings, mesh_file) = match file {
Some(f) => {
let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh;
(m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name))
self.replace_mesh(file, preserve_strokes, self.doc.project.mesh_rebuild_uvs)
}
fn replace_mesh(&mut self, file: Option<texturecraft_formats::MeshFile>, preserve_strokes: bool, rebuild_uvs: bool) -> Result<Value> {
let (mesh, replacement_source, warnings, mesh_file) = match file {
Some(file) => {
let mesh = import_mesh_geometry(&file.name, &file.bytes, MeshUvSource::from_rebuild_setting(rebuild_uvs)).map_err(fe)?;
(mesh, Some((ext_of(&file.name), file.bytes)), file.warnings, leaf_of(&file.name))
}
None => match &self.mesh_source {
Some((ext, bytes)) => {
(read_stored_mesh(&self.doc.project, ext, bytes)?.mesh, self.mesh_source.clone(), Vec::new(), self.doc.project.mesh_file.clone())
let layout = self.saved_uv_layout();
let mesh = read_stored_mesh(&self.doc.project, ext, bytes, layout.as_deref())?;
(mesh, None, Vec::new(), self.doc.project.mesh_file.clone())
}
None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")),
},
@@ -629,12 +671,13 @@ impl Session {
check_materials(&self.doc.project, &mesh)?;
let mut doc = self.doc.clone();
if let Some((ext, _)) = &source {
if let Some((ext, _)) = replacement_source.as_ref().or(self.mesh_source.as_ref()) {
doc.project.mesh = format!("mesh.{ext}");
doc.project.mesh_file = mesh_file;
doc.project.mesh_rebuild_uvs = rebuild_uvs;
}
let mut next = Session::new(doc, mesh, source)?;
let mut next = Session::new(doc, mesh, replacement_source)?;
next.log.warnings("Importer", warnings);
next.path = self.path.clone();
next.sync_images();
@@ -645,6 +688,7 @@ impl Session {
next.doc.bake_meshes.cage = None;
next.log.warn("Project", "the cage mesh was dropped: the low-poly mesh changed");
}
if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs {
next.log.warn("Project", "the skew map is laid over the old UV layout; check it in Bake mode");
}
@@ -652,6 +696,12 @@ impl Session {
next.modified = true;
next.project_id = self.project_id;
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
// Keep the stored source in the current session until reimport succeeds
if next.mesh_source.is_none() {
next.mesh_source = self.mesh_source.take();
}
self.switch_to(next);
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
}
+1
View File
@@ -104,6 +104,7 @@ impl Session {
pixels: mini.pixels,
baked: BTreeMap::new(),
mesh: None,
mesh_uvs: None,
high_poly: Vec::new(),
cage: None,
bake_paint: BTreeMap::new(),
+1
View File
@@ -62,6 +62,7 @@ mod pbr_import;
mod perf;
mod polygon_fill;
mod project_recovery;
mod rebuilt_uv_layout;
mod resources_used;
mod sample;
mod solo;
@@ -0,0 +1,68 @@
use std::io::{Cursor, Write};
use serde_json::json;
use texturecraft_engine::Session;
use texturecraft_engine::formats::mesh_import::{corner_uvs, import_mesh_bytes_with_uvs};
use texturecraft_engine::geom::glam::Vec2;
use zip::{ZipWriter, write::SimpleFileOptions};
const QUAD_OBJ: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\n";
/// A layout no unwrapper of this build makes: the quad turned a quarter and inset, per corner
const LOCKED_LAYOUT: [[f32; 2]; 6] = [[0.9, 0.1], [0.9, 0.9], [0.1, 0.9], [0.9, 0.1], [0.1, 0.9], [0.1, 0.1]];
/// `uv_layout.bin` written by hand: magic, version 1, corner count, then u and v per corner
fn layout_entry(layout: &[[f32; 2]]) -> Vec<u8> {
let mut bytes = b"TCUV".to_vec();
bytes.extend(1u32.to_le_bytes());
bytes.extend(u32::try_from(layout.len()).unwrap().to_le_bytes());
for [u, v] in layout {
bytes.extend(u.to_le_bytes());
bytes.extend(v.to_le_bytes());
}
bytes
}
/// A format 4 archive of the quad with rebuilt UVs and the locked layout
fn locked_archive() -> Vec<u8> {
let session = Session::from_mesh_bytes_with_uvs("quad.obj", QUAD_OBJ.as_bytes(), 128, "quad", None, true).unwrap();
let mut project = serde_json::to_value(&session.doc.project).unwrap();
project["format_version"] = json!(4);
let mut archive = ZipWriter::new(Cursor::new(Vec::new()));
for (name, bytes) in
[("project.json", serde_json::to_vec(&project).unwrap()), ("mesh.obj", QUAD_OBJ.as_bytes().to_vec()), ("uv_layout.bin", layout_entry(&LOCKED_LAYOUT))]
{
archive.start_file(name, SimpleFileOptions::default()).unwrap();
archive.write_all(&bytes).unwrap();
}
archive.finish().unwrap().into_inner()
}
#[test]
fn a_rebuilt_project_reopens_with_its_saved_uv_layout_not_a_new_unwrap() {
let locked: Vec<Vec2> = LOCKED_LAYOUT.iter().map(|uv| Vec2::from_array(*uv)).collect();
let unwrapped = import_mesh_bytes_with_uvs("quad.obj", QUAD_OBJ.as_bytes(), true).unwrap().mesh;
let mut reopened = Session::from_project_bytes(&locked_archive()).unwrap();
let opened_layout = corner_uvs(&reopened.source_mesh());
reopened.reimport_mesh(None, false).unwrap();
let reimported_layout = corner_uvs(&reopened.source_mesh());
let resaved = Session::from_project_bytes(&reopened.to_project_bytes().unwrap()).unwrap();
assert_ne!(corner_uvs(&unwrapped), locked, "the locked layout differs from what the unwrapper makes now");
assert_eq!(opened_layout, locked);
assert_eq!(reimported_layout, locked, "reimporting the project's own mesh keeps the saved layout");
assert_eq!(corner_uvs(&resaved.source_mesh()), locked, "saving again keeps the layout");
}
#[test]
fn opening_a_builtin_project_refuses_rebuilt_mesh_uvs() {
let mut file = texturecraft_engine::formats::load_project_bytes(&locked_archive()).unwrap();
file.project.mesh = "builtin:plane".into();
file.mesh = None;
let error = Session::from_project_file(file).map(|_| ()).expect_err("a built-in mesh cannot use the stored layout");
assert!(error.to_string().contains("uv_layout.bin"), "{error}");
}
+9 -2
View File
@@ -145,7 +145,8 @@ Built-in presets (each one lists the public specification its packing follows in
```rust
pub struct ProjectFile {
pub project: Project, pub pixels: PixelStore, pub baked: BTreeMap<usize, BakedMaps>,
pub mesh: Option<(String /* ext */, Vec<u8>)>, pub thumbnail: Option<Vec<u8>>,
pub mesh: Option<(String /* ext */, Vec<u8>)>, pub mesh_uvs: Option<Vec<Vec2>>,
pub thumbnail: Option<Vec<u8>>,
pub warnings: Vec<String>, // Import warnings, never saved
}
pub fn save_project_bytes(pf: &ProjectFile) -> Result<Vec<u8>>;
@@ -162,12 +163,14 @@ pub fn project_open_limit_gib() -> u32;
|---|---|
| `project.json` | serde JSON of `Project` |
| `mesh.<ext>` | the original mesh file bytes (absent for `builtin:<id>` meshes) |
| `uv_layout.bin` | generated UVs for an explicitly rebuilt mesh (format 4) |
| `pixels/layer_<id>_<channelId>.bin` | painted layer (or content paint effect) channel |
| `pixels/mask_<id>.bin` | painted mask effect |
| `baked/<ts>_<mapId>.bin` | baked mesh map of texture set `<ts>` |
| `thumbnail.png` | optional, stored |
`.bin`: header `TCTX`, version, width, height, components, tile count (u32 LE each), then per
Paint and bake `.bin` entries use a `TCTX` header with version, width, height, components and tile
count (u32 LE each), then per
allocated 64×64 tile `tx`, `ty` (u32 LE) and the raw `u16` LE components (sparse, lossless).
Baked maps: the same header with 0 tiles, then `width × height × components` f32 LE.
@@ -180,6 +183,10 @@ Project format version 3 stores baked bent normal maps in tangent space (OpenGL
normal map). Version 2 and older files held them in world space: loading drops those maps, keeps
the bake settings and warns that the Bent Normals map needs a re-bake.
Project format version 4 saves rebuilt mesh UVs so reopening can use the same layout. The
`uv_layout.bin` entry starts with `TCUV`, followed by the layout version and corner count (u32 LE).
Each triangle corner has one little-endian f32 pair in imported index order.
Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError::NewerVersion`),
checks every tile against its texture set's resolution and component count, rejects repeated or
out-of-range tiles and trailing data, and drops pixels of layers that are in no stack. Total
+26 -17
View File
@@ -198,29 +198,36 @@ fn sample_file(with_tri: bool) -> Vec<u8> {
#[test]
fn imports_polymesh_through_xforms_with_face_sets_uvs_and_normals() {
let raw = read(&sample_file(true)).unwrap();
let mut names: Vec<(&str, &str)> = raw.groups.iter().map(|(m, p, _)| (m.as_str(), p.as_str())).collect();
let mut names: Vec<(&str, &str)> = raw.groups.iter().map(|(material, part, _)| (material.as_str(), part.as_str())).collect();
names.sort();
assert_eq!(names, vec![("Default", "tri"), ("left", "strip"), ("right", "strip")], "meshes take their transform's name");
assert_eq!(raw.triangle_count(), 5);
// UVs exist only on the strip, so the whole mesh is unwrapped (with a warning).
// UVs exist only on the strip, so the whole mesh is unwrapped with a warning
assert!(raw.uvs.is_none() && !raw.warnings.is_empty());
// World positions: scaled by 2, then translated.
// World positions are scaled first and then translated
let (lo, hi) = raw.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
assert_eq!((lo, hi), (Vec3::new(0.0, 0.0, 3.0), Vec3::new(5.0, 4.0, 5.0)));
// Clockwise Alembic faces become counter-clockwise: the strip faces +Z.
for (m, _, tris) in &raw.groups {
if m == "Default" {
// Clockwise Alembic faces are reversed so the strip faces +Z
for (material, _, triangles) in &raw.groups {
if material == "Default" {
continue;
}
for t in tris.chunks(3) {
for t in triangles.chunks(3) {
let p = |i: u32| raw.positions[i as usize];
assert!((p(t[1]) - p(t[0])).cross(p(t[2]) - p(t[0])).z > 0.0);
}
}
let mesh = finish(raw).unwrap().mesh;
let mesh = finish(raw, false).unwrap().mesh;
assert_eq!(mesh.materials.len(), 3);
// The strip alone keeps its indexed face-varying UVs: u = x / 2 in the file's own space.
let strip = finish(read(&sample_file(false)).unwrap()).unwrap();
// The strip alone keeps its indexed face-varying UVs with u = x / 2 in local space
let strip = finish(read(&sample_file(false)).unwrap(), false).unwrap();
assert!(!strip.report.uvs_generated);
for (p, uv) in strip.mesh.positions.iter().zip(&strip.mesh.uvs) {
let local = (*p - Vec3::new(1.0, 2.0, 3.0)) / 2.0;
@@ -318,21 +325,23 @@ fn hdf5_and_garbage_are_clear_errors() {
#[test]
fn truncated_and_corrupted_files_never_panic() {
let bytes = sample_file(true);
for n in (0..bytes.len()).step_by(3) {
let _ = read(&bytes[..n]);
for end in (0..bytes.len()).step_by(3) {
let _ = read(&bytes[..end]);
}
let mut rng = 0x9e37_79b9_7f4a_7c15u64;
for _ in 0..4000 {
let mut b = bytes.clone();
let mut corrupted = bytes.clone();
for _ in 0..4 {
rng ^= rng << 13;
rng ^= rng >> 7;
rng ^= rng << 17;
let i = (rng % b.len() as u64) as usize;
b[i] = (rng >> 32) as u8;
let i = (rng % corrupted.len() as u64) as usize;
corrupted[i] = (rng >> 32) as u8;
}
if let Ok(raw) = read(&b) {
let _ = finish(raw);
if let Ok(raw) = read(&corrupted) {
let _ = finish(raw, false);
}
}
}
@@ -0,0 +1,17 @@
use texturecraft_geom::glam::Vec2;
/// How to obtain triangle UVs when reading mesh geometry.
pub enum MeshUvSource<'a> {
/// Keep complete authored UVs, or unwrap a mesh that needs them.
FromFile,
/// Generate a fresh layout even when the file contains UVs.
Rebuild,
/// Apply the project's saved UVs in triangle corner order.
Saved(&'a [Vec2]),
}
impl MeshUvSource<'_> {
pub fn from_rebuild_setting(rebuild_uvs: bool) -> Self {
if rebuild_uvs { Self::Rebuild } else { Self::FromFile }
}
}
+104 -10
View File
@@ -11,6 +11,7 @@ mod dae;
mod external;
mod fbx;
mod gltf;
mod mesh_uv_source;
mod obj;
mod ply;
#[cfg(test)]
@@ -32,6 +33,7 @@ use crate::{FormatError, Result};
#[cfg(not(target_arch = "wasm32"))]
pub use external::read_mesh_file;
pub use external::{MeshFile, self_contained_mesh};
pub use mesh_uv_source::MeshUvSource;
/// Mesh files larger than this are refused before reading.
pub const MAX_MESH_FILE_BYTES: u64 = 2 << 30;
@@ -108,7 +110,7 @@ pub struct MeshReport {
pub triangles: usize,
pub vertices: usize,
pub materials: usize,
/// The file had no UVs; they were generated by the automatic unwrap.
/// The UVs were generated by the automatic unwrap.
pub uvs_generated: bool,
/// Triangles with a UV outside 0..1.
pub uv_out_of_range: usize,
@@ -295,7 +297,32 @@ fn extension(file_name: &str) -> String {
/// self-contained (see [`self_contained_mesh`]); OBJ material libraries are not read (usemtl
/// names are).
pub fn import_mesh_bytes(file_name: &str, bytes: &[u8]) -> Result<ImportedMesh> {
finish(read(file_name, bytes)?)
import_mesh_bytes_with_uvs(file_name, bytes, false)
}
/// Import mesh bytes, optionally rebuilding the UV layout even when the mesh already has UVs.
pub fn import_mesh_bytes_with_uvs(file_name: &str, bytes: &[u8], rebuild_uvs: bool) -> Result<ImportedMesh> {
finish(read(file_name, bytes)?, rebuild_uvs)
}
/// Import mesh bytes with a saved UV layout ([`corner_uvs`] of the mesh as first imported)
/// instead of the file's UVs or the automatic unwrap, so the layout does not depend on the
/// unwrapper of the running version.
pub fn import_mesh_bytes_with_layout(file_name: &str, bytes: &[u8], corner_uvs: &[Vec2]) -> Result<ImportedMesh> {
finish_with_layout(read(file_name, bytes)?, MeshUvSource::Saved(corner_uvs))
}
/// Read validated geometry for project open and mesh replacement, which keep the project's cameras
/// and do not need the import dialog's UV coverage report.
pub fn import_mesh_geometry(file_name: &str, bytes: &[u8], uv_source: MeshUvSource<'_>) -> Result<Mesh> {
let (mesh, _, _) = complete_mesh(read(file_name, bytes)?, uv_source)?;
Ok(mesh)
}
/// The UV of every triangle corner, in index order: a layout that [`import_mesh_bytes_with_layout`]
/// applies to the same mesh file again.
pub fn corner_uvs(mesh: &Mesh) -> Vec<Vec2> {
mesh.indices.iter().map(|index| mesh.uvs.get(*index as usize).copied().unwrap_or_default()).collect()
}
/// Import a mesh file with the files it references next to it ([`read_mesh_file`]).
@@ -491,29 +518,96 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec<String>, Option<Vec<Vec2>>)> {
}
/// Complete a raw mesh: submeshes, normals, UVs, tangents, validation and the report.
pub(crate) fn finish(mut raw: RawMesh) -> Result<ImportedMesh> {
pub(crate) fn finish(raw: RawMesh, rebuild_uvs: bool) -> Result<ImportedMesh> {
finish_with_layout(raw, MeshUvSource::from_rebuild_setting(rebuild_uvs))
}
fn finish_with_layout(mut raw: RawMesh, uv_source: MeshUvSource<'_>) -> Result<ImportedMesh> {
let mut raw_cameras = std::mem::take(&mut raw.cameras);
raw_cameras.truncate(MAX_CAMERAS);
let (mesh, warnings, uvs_generated) = complete_mesh(raw, uv_source)?;
let report = report(&mesh, uvs_generated, warnings);
let cameras = orbit_cameras(&raw_cameras, &mesh);
Ok(ImportedMesh { mesh, report, cameras })
}
fn complete_mesh(raw: RawMesh, uv_source: MeshUvSource<'_>) -> Result<(Mesh, Vec<String>, bool)> {
let (mut mesh, mut warnings, uvs) = geometry(raw)?;
let uvs_generated = match uvs {
Some(uv) if uv.len() == mesh.positions.len() => {
let uvs_generated = match (uv_source, uvs) {
(MeshUvSource::Saved(layout), authored_uvs) => {
drop(authored_uvs);
apply_corner_uvs(&mut mesh, layout)?;
true
}
(MeshUvSource::FromFile, Some(uv)) if uv.len() == mesh.positions.len() => {
if uv.iter().any(|v| !v.is_finite()) {
warnings.push("non-finite UVs were replaced with 0".into());
}
mesh.uvs = uv.into_iter().map(|v| if v.is_finite() { v } else { Vec2::ZERO }).collect();
mesh.compute_tangents();
false
}
_ => {
(source, authored_uvs) => {
drop(authored_uvs);
let charts = auto_unwrap(&mut mesh, UNWRAP_PADDING, UNWRAP_RESOLUTION)?;
warnings.push(format!("the mesh has no UVs; generated an automatic unwrap with {charts} charts"));
let reason = if matches!(source, MeshUvSource::Rebuild) { "rebuild UVs was selected" } else { "the mesh has no UVs" };
warnings.push(format!("{reason}; generated an automatic unwrap with {charts} charts"));
true
}
};
mesh.validate()?;
let report = report(&mesh, uvs_generated, warnings);
let cameras = orbit_cameras(&raw_cameras, &mesh);
Ok(ImportedMesh { mesh, report, cameras })
Ok((mesh, warnings, uvs_generated))
}
/// Give every triangle corner its UV from `layout`, keeping independently packed materials split.
fn apply_corner_uvs(mesh: &mut Mesh, layout: &[Vec2]) -> Result<()> {
if layout.len() != mesh.indices.len() {
return Err(FormatError::Invalid(format!("the saved UV layout has {} corners but the mesh has {}", layout.len(), mesh.indices.len())));
}
if layout.iter().any(|uv| !uv.is_finite()) {
return Err(FormatError::Invalid("the saved UV layout has non-finite UVs".into()));
}
let mut remapped_vertices = HashMap::with_capacity((mesh.positions.len() * 2).min(layout.len()));
let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
let mut indices = Vec::with_capacity(mesh.indices.len());
// Geometry supplies contiguous submesh ranges and validates their vertex indices
for submesh in &mesh.submeshes {
let start = submesh.start as usize;
let end = start + submesh.count as usize;
let material = submesh.material as u32;
for (&vertex, &uv) in mesh.indices[start..end].iter().zip(&layout[start..end]) {
let index = *remapped_vertices.entry((vertex, material, uv.to_array().map(f32::to_bits))).or_insert_with(|| {
let source = vertex as usize;
positions.push(mesh.positions[source]);
normals.push(mesh.normals[source]);
if let Some(color) = mesh.colors.get(source) {
colors.push(*color);
}
uvs.push(uv);
(positions.len() - 1) as u32
});
indices.push(index);
}
}
drop(remapped_vertices);
mesh.positions = positions;
mesh.normals = normals;
mesh.uvs = uvs;
mesh.colors = colors;
mesh.indices = indices;
mesh.compute_tangents();
Ok(())
}
/// File cameras as orbit cameras: the target is where the view axis passes the mesh center
+42
View File
@@ -757,3 +757,45 @@ fn duplicate_gltf_material_names_keep_first_wins_and_order() {
}
assert_eq!(color_by_material.get("Dup").unwrap().factor, Vec4::new(1.0, 0.0, 0.0, 1.0));
}
#[test]
fn a_saved_layout_reproduces_the_rebuilt_mesh_without_unwrapping() {
let rebuilt = import_mesh_bytes_with_uvs("a.obj", OBJ.as_bytes(), true).unwrap().mesh;
let layout = corner_uvs(&rebuilt);
let reopened = import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &layout).unwrap();
let short = import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &layout[1..]);
let mut non_finite = layout.clone();
non_finite[0].x = f32::NAN;
assert!(!reopened.report.warnings.iter().any(|warning| warning.contains("unwrap")), "{:?}", reopened.report.warnings);
assert_eq!((&reopened.mesh.positions, &reopened.mesh.indices, &reopened.mesh.uvs), (&rebuilt.positions, &rebuilt.indices, &rebuilt.uvs));
assert_eq!(reopened.mesh.normals, rebuilt.normals);
assert!(short.is_err(), "a layout for another mesh is refused");
assert!(import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &non_finite).is_err());
}
#[test]
fn a_saved_layout_keeps_coincident_vertices_in_different_materials_split() {
// Synthetic mesh with coincident triangles in independently packed materials
let source = br#"#usda 1.0
def Mesh "Overlaid" {
int[] faceVertexCounts = [3, 3]
int[] faceVertexIndices = [0, 1, 2, 0, 1, 2]
point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
rel material:binding = </First>
def GeomSubset "second" {
uniform token familyName = "materialBind"
int[] indices = [1]
rel material:binding = </Second>
}
}
"#;
let rebuilt = import_mesh_bytes_with_uvs("overlaid.usda", source, true).unwrap().mesh;
let layout = corner_uvs(&rebuilt);
let reopened = import_mesh_bytes_with_layout("overlaid.usda", source, &layout).unwrap().mesh;
assert_eq!(&layout[..3], &layout[3..], "the independently packed triangles have equal UVs");
assert_eq!(reopened, rebuilt);
}
+106 -39
View File
@@ -4,6 +4,7 @@
//! |---|---|
//! | `project.json` | serde JSON of [`Project`] |
//! | `mesh.<ext>` | the original imported mesh file (absent for built-in meshes, `Project.mesh = "builtin:<id>"`) |
//! | `uv_layout.bin` | the UV of every triangle corner of a mesh whose UVs were rebuilt (format 4+, see `uv_layout`) |
//! | `highpoly/<name>` | a high-definition mesh file for baking, in list order |
//! | `cage/<name>` | the baking cage mesh file |
//! | `bake_paint/<ts>_<target>.bin` | cage or skew paint, stored as a one-component baked map |
@@ -18,19 +19,22 @@
//! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture
//! set cover its whole atlas (`resolution` per tile, see `TileGrid`).
use std::borrow::Borrow;
use std::borrow::{Borrow, Cow};
use std::collections::{BTreeMap, HashSet};
use std::io::{Cursor, Read, Seek, Write};
use std::sync::Arc;
use texturecraft_compose::{BakedMaps, PixelStore};
use texturecraft_core::project::REBUILT_MESH_UVS_VERSION;
use texturecraft_core::{BakePaintTarget, BakedMap, Channel, FORMAT_VERSION, LayerId, Project, TANGENT_BENT_NORMAL_VERSION};
use texturecraft_geom::glam::Vec2;
use texturecraft_texel::{TILE_AREA, TileImage};
use zip::write::SimpleFileOptions;
use zip::{CompressionMethod, ZipArchive, ZipWriter};
use self::entries::Entry;
use self::load_budget::LoadBudget;
use self::uv_layout::{MAX_UV_LAYOUT_BYTES, UV_LAYOUT_ENTRY, read_uv_layout, uv_layout_bytes, write_uv_layout};
use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed};
mod entries;
@@ -38,6 +42,7 @@ mod load_budget;
mod project_open_limit;
mod ram_operation;
mod ram_reservation;
mod uv_layout;
#[cfg(not(target_arch = "wasm32"))]
pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, configured_ram_budget, save_ram_budget, set_save_resources};
pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib};
@@ -72,6 +77,9 @@ pub struct ProjectFile<Resource = Vec<u8>> {
pub baked: BTreeMap<usize, BakedMaps>,
/// Original mesh file: (extension, bytes).
pub mesh: Option<(String, Vec<u8>)>,
/// Saved UV layout of `mesh` when its UVs were rebuilt: the UV of every triangle corner, in
/// index order, as the mesh was first imported.
pub mesh_uvs: Option<Vec<Vec2>>,
/// High-definition mesh files for baking: (file name, bytes). Names are
/// [`sanitize_resource_name`]d on save.
pub high_poly: Vec<(String, Vec<u8>)>,
@@ -85,6 +93,21 @@ pub struct ProjectFile<Resource = Vec<u8>> {
pub warnings: Vec<String>,
}
impl<Resource> ProjectFile<Resource> {
/// Check that the mesh source and the rebuild setting agree with the saved layout.
pub fn validate_mesh_uvs(&self) -> Result<()> {
if self.project.mesh_rebuild_uvs != self.mesh_uvs.is_some() {
return Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY} is required exactly when mesh UVs were rebuilt")));
}
if self.mesh_uvs.is_some() && (self.mesh.is_none() || self.project.mesh.starts_with("builtin:")) {
return Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY} requires a stored mesh")));
}
Ok(())
}
}
/// Maximum length of a resource name after sanitization.
pub const MAX_RESOURCE_NAME_LEN: usize = 120;
@@ -187,12 +210,23 @@ fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32])
}
/// The zip entries of a project file, in file order. Bodies run later, possibly on other threads.
fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
fn entries(project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
project_file.validate_mesh_uvs()?;
let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true);
let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?;
let mut project = Cow::Borrowed(&project_file.project);
// Callers can supply a document directly instead of a versioned save snapshot
let version = project.save_format_version();
if project.format_version != version {
project.to_mut().format_version = version;
}
let json = serde_json::to_vec_pretty(project.as_ref()).map_err(|e| FormatError::Invalid(e.to_string()))?;
let mut out = vec![Entry { name: "project.json".into(), options: deflate, weight: json.len() as u64, body: Box::new(move |w| w.write_all(&json)) }];
if let Some((ext, bytes)) = &pf.mesh {
if let Some((ext, bytes)) = &project_file.mesh {
out.push(Entry {
name: format!("mesh.{}", sanitize_ext(ext)),
options: deflate,
@@ -200,8 +234,18 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
body: Box::new(move |w| w.write_all(bytes)),
});
}
if let Some(layout) = &project_file.mesh_uvs {
out.push(Entry {
name: UV_LAYOUT_ENTRY.into(),
options: deflate,
weight: uv_layout_bytes(layout.len()),
body: Box::new(move |w| write_uv_layout(w, layout)),
});
}
let mut used = HashSet::new();
for (dir, (name, bytes)) in pf.high_poly.iter().map(|m| ("highpoly", m)).chain(pf.cage.iter().map(|m| ("cage", m))) {
for (dir, (name, bytes)) in project_file.high_poly.iter().map(|m| ("highpoly", m)).chain(project_file.cage.iter().map(|m| ("cage", m))) {
out.push(Entry {
name: unique_entry_name(dir, name, &mut used),
options: deflate,
@@ -209,7 +253,8 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
body: Box::new(move |w| w.write_all(bytes)),
});
}
for ((texture_set, target), map) in &pf.bake_paint {
for ((texture_set, target), map) in &project_file.bake_paint {
if map.width == 0 || map.height == 0 || map.values.len() as u64 != u64::from(map.width) * u64::from(map.height) {
return Err(FormatError::Invalid("bake paint map dimensions do not match its values".into()));
}
@@ -218,6 +263,7 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
BakePaintTarget::Cage => "cage",
BakePaintTarget::Skew => "skew",
};
out.push(Entry {
name: format!("bake_paint/{texture_set}_{target_name}.bin"),
options: deflate,
@@ -225,7 +271,8 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
body: Box::new(move |w| write_baked(w, map.width, map.height, 1, &map.values)),
});
}
let mut layers: Vec<_> = pf.pixels.layers.iter().collect();
let mut layers: Vec<_> = project_file.pixels.layers.iter().collect();
layers.sort_by_key(|(k, _)| **k);
for ((id, c), img) in layers {
let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64;
@@ -236,13 +283,14 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
body: Box::new(move |mut w| write_tiles(&mut w, img)),
});
}
let mut masks: Vec<_> = pf.pixels.masks.iter().collect();
let mut masks: Vec<_> = project_file.pixels.masks.iter().collect();
masks.sort_by_key(|(k, _)| **k);
for (id, img) in masks {
let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64;
out.push(Entry { name: format!("pixels/mask_{}.bin", id.0), options: deflate, weight, body: Box::new(move |mut w| write_tiles(&mut w, img)) });
}
for (ts, maps) in &pf.baked {
for (ts, maps) in &project_file.baked {
let r = maps.resolution;
for (m, data) in &maps.maps {
// Skip inconsistent maps so the saved project can reopen and bake them again
@@ -260,11 +308,13 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
});
}
}
if let Some(png) = &pf.thumbnail {
if let Some(png) = &project_file.thumbnail {
out.push(Entry { name: "thumbnail.png".into(), options: stored, weight: png.len() as u64, body: Box::new(move |w| w.write_all(png)) });
}
used.clear();
for (name, resource) in &pf.resources {
for (name, resource) in &project_file.resources {
let bytes = resource.borrow();
out.push(Entry {
name: unique_entry_name("resources", name, &mut used),
@@ -273,6 +323,7 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
body: Box::new(move |w| w.write_all(bytes)),
});
}
Ok(out)
}
@@ -406,10 +457,11 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
return Err(malformed(KIND, format!("texture set \"{}\" has resolution {} over {} UV tiles", ts.name, ts.resolution, ts.uv_tiles.len().max(1))));
}
let mut pf = ProjectFile {
let mut project_file = ProjectFile {
pixels: PixelStore::default(),
baked: BTreeMap::new(),
mesh: None,
mesh_uvs: None,
high_poly: Vec::new(),
cage: None,
bake_paint: BTreeMap::new(),
@@ -419,36 +471,36 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
project,
};
for i in 0..zip.len() {
let mut f = zip.by_index(i).map_err(zip_err)?;
let declared_bytes = f.size();
let name = f.name().map_err(zip_err)?.into_owned();
let size_of = |id: LayerId| texture_set_of(&pf.project, id).and_then(|ts| pf.project.texture_sets.get(ts)).map(|t| t.size());
for index in 0..zip.len() {
let mut entry = zip.by_index(index).map_err(zip_err)?;
let declared_bytes = entry.size();
let name = entry.name().map_err(zip_err)?.into_owned();
let size_of = |id: LayerId| texture_set_of(&project_file.project, id).and_then(|ts| project_file.project.texture_sets.get(ts)).map(|t| t.size());
// Unrecognized entries from newer minor revisions may be skipped
if name == "thumbnail.png" {
pf.thumbnail = Some(read_all(&mut f, MAX_THUMBNAIL, &mut budget, &name)?);
project_file.thumbnail = Some(read_all(&mut entry, MAX_THUMBNAIL, &mut budget, &name)?);
} else if let Some(res_name) = name.strip_prefix("resources/") {
if res_name.is_empty() || sanitize_resource_name(res_name) != res_name {
return Err(malformed(KIND, format!("bad resource name {name}")));
}
let bytes = read_all(&mut f, MAX_RESOURCE, &mut budget, &name)?;
pf.resources.insert(res_name.to_string(), bytes);
let bytes = read_all(&mut entry, MAX_RESOURCE, &mut budget, &name)?;
project_file.resources.insert(res_name.to_string(), bytes);
} else if let Some((dir, file)) = name.split_once('/').filter(|(d, _)| *d == "highpoly" || *d == "cage") {
if file.is_empty() || sanitize_resource_name(file) != file {
return Err(malformed(KIND, format!("bad mesh name {name}")));
}
let entry = (file.to_string(), read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?);
let entry = (file.to_string(), read_all(&mut entry, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?);
match dir {
"cage" => pf.cage = Some(entry),
_ => pf.high_poly.push(entry),
"cage" => project_file.cage = Some(entry),
_ => project_file.high_poly.push(entry),
}
} else if let Some(rest) = name.strip_prefix("bake_paint/").and_then(|name| name.strip_suffix(".bin")) {
let (texture_set, target) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry {name}")))?;
let texture_set: usize = texture_set.parse().map_err(|_| malformed(KIND, format!("bad entry {name}")))?;
if texture_set >= pf.project.texture_sets.len() {
if texture_set >= project_file.project.texture_sets.len() {
return Err(malformed(KIND, format!("unknown texture set in {name}")));
}
@@ -457,11 +509,22 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
"skew" => BakePaintTarget::Skew,
_ => return Err(malformed(KIND, format!("unknown bake paint target in {name}"))),
};
let (width, height, values) = read_baked(&mut f, declared_bytes, 1, &mut budget, &name)?;
pf.bake_paint.insert((texture_set, target), BakePaintData { width, height, values });
let (width, height, values) = read_baked(&mut entry, declared_bytes, 1, &mut budget, &name)?;
project_file.bake_paint.insert((texture_set, target), BakePaintData { width, height, values });
} else if let Some(ext) = name.strip_prefix("mesh.").filter(|e| !e.contains('/')) {
let bytes = read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?;
pf.mesh = Some((ext.to_string(), bytes));
let bytes = read_all(&mut entry, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?;
project_file.mesh = Some((ext.to_string(), bytes));
} else if name == UV_LAYOUT_ENTRY {
if version < REBUILT_MESH_UVS_VERSION || !project_file.project.mesh_rebuild_uvs {
return Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY} requires format {REBUILT_MESH_UVS_VERSION} or later and rebuilt mesh UVs")));
}
if declared_bytes > MAX_UV_LAYOUT_BYTES {
return Err(FormatError::TooLarge(format!("{UV_LAYOUT_ENTRY} is larger than {MAX_UV_LAYOUT_BYTES} bytes")));
}
budget.take(declared_bytes).map_err(FormatError::TooLarge)?;
project_file.mesh_uvs = Some(read_uv_layout(&mut entry, declared_bytes)?);
} else if let Some(rest) = name.strip_prefix("pixels/layer_").and_then(|r| r.strip_suffix(".bin")) {
let (id, chan) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?;
let id = LayerId(id.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?);
@@ -470,14 +533,14 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
// Drop pixels of layers that are no longer in any stack
let Some(size) = size_of(id) else { continue };
let img = read_tiles(&mut f, size, c.components() + 1, &mut budget, &name)?;
pf.pixels.layers.insert((id, c), img);
let img = read_tiles(&mut entry, size, c.components() + 1, &mut budget, &name)?;
project_file.pixels.layers.insert((id, c), img);
} else if let Some(rest) = name.strip_prefix("pixels/mask_").and_then(|r| r.strip_suffix(".bin")) {
let id = LayerId(rest.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?);
let Some(size) = size_of(id) else { continue };
let img = read_tiles(&mut f, size, 2, &mut budget, &name)?;
pf.pixels.masks.insert(id, img);
let img = read_tiles(&mut entry, size, 2, &mut budget, &name)?;
project_file.pixels.masks.insert(id, img);
} else if let Some(rest) = name.strip_prefix("baked/").and_then(|r| r.strip_suffix(".bin")) {
let (ts, map) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?;
let ts: usize = ts.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?;
@@ -486,12 +549,12 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
continue;
};
if ts >= pf.project.texture_sets.len() {
if ts >= project_file.project.texture_sets.len() {
continue;
}
let (res, height, data) = read_baked(&mut f, declared_bytes, m.components(), &mut budget, &name)?;
let maps = pf.baked.entry(ts).or_default();
let (res, height, data) = read_baked(&mut entry, declared_bytes, m.components(), &mut budget, &name)?;
let maps = project_file.baked.entry(ts).or_default();
if maps.maps.is_empty() {
maps.resolution = res;
} else if maps.resolution != res || maps.maps.keys().next().is_some_and(|k| maps.height(*k) != height) {
@@ -502,18 +565,22 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
}
}
// Rerunning the unwrapper could lay the saved paint over a different layout
project_file.validate_mesh_uvs()?;
if version < TANGENT_BENT_NORMAL_VERSION {
drop_world_space_bent_normals(&mut pf);
drop_world_space_bent_normals(&mut project_file);
}
pf.project.format_version = FORMAT_VERSION;
project_file.project.format_version = version.max(TANGENT_BENT_NORMAL_VERSION);
if recovered {
pf.warnings.push(
project_file.warnings.push(
"Warning: Some project settings or mesh maps could not be imported. TextureCraft recovered what it could, using defaults where needed.".into(),
);
}
Ok(pf)
Ok(project_file)
}
/// Older files hold bent normal maps in world space, which every reader now takes as tangent
+85 -1
View File
@@ -32,6 +32,7 @@ fn sample() -> Sample {
pixels,
baked: [(0, baked)].into(),
mesh: Some(("glb".into(), vec![1, 2, 3, 4, 5])),
mesh_uvs: None,
high_poly: vec![("b_high.obj".into(), vec![7; 9]), ("a_high.ply".into(), vec![6])],
cage: Some(("cage.obj".into(), vec![5, 5])),
bake_paint: [((0, texturecraft_core::BakePaintTarget::Skew), BakePaintData { width: 3, height: 2, values: vec![0.0, 0.25, 0.5, 0.75, 1.0, 0.125] })]
@@ -55,6 +56,7 @@ fn assert_same(a: &ProjectFile, b: &ProjectFile) {
}
assert_eq!(a.baked, b.baked);
assert_eq!(a.mesh, b.mesh);
assert_eq!(a.mesh_uvs, b.mesh_uvs);
assert_eq!((&a.high_poly, &a.cage), (&b.high_poly, &b.cage), "bake meshes keep their order");
assert_eq!(a.bake_paint, b.bake_paint);
assert_eq!(a.thumbnail, b.thumbnail);
@@ -104,7 +106,7 @@ fn legacy_bakes_load_as_is_without_layout_conversion() {
sample.pf.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() });
let loaded = load_project_bytes(&save_project_bytes(&sample.pf).unwrap()).unwrap();
assert_eq!(loaded.project.format_version, FORMAT_VERSION);
assert_eq!(loaded.project.format_version, TANGENT_BENT_NORMAL_VERSION);
assert_eq!(loaded.baked, sample.pf.baked, "old bake pixels are accepted without preserving their former layout");
assert_eq!(loaded.bake_paint, sample.pf.bake_paint, "correction paint remains in the working layout");
let reopened = load_project_bytes(&save_project_bytes(&loaded).unwrap()).unwrap();
@@ -920,3 +922,85 @@ fn zip64_entry_counts_remain_supported_and_bounded() {
}
}
}
fn rebuilt_uvs_sample() -> ProjectFile {
let mut project_file = sample().pf;
project_file.project.mesh_rebuild_uvs = true;
project_file.mesh_uvs = Some(vec![Vec2::new(0.25, 0.75), Vec2::new(1.0, 0.0), Vec2::new(0.5, 0.125)]);
project_file
}
#[test]
fn a_saved_uv_layout_round_trips_in_format_4() {
const ADDITIONAL_CORNERS: usize = 3000;
let mut project_file = rebuilt_uvs_sample();
let layout = project_file.mesh_uvs.as_mut().unwrap();
// Exercise full batches and a partial final batch with distinct UVs
layout.extend((0..ADDITIONAL_CORNERS).map(|corner| Vec2::new(corner as f32 / ADDITIONAL_CORNERS as f32, 0.5)));
let loaded = load_project_bytes(&save_project_bytes(&project_file).unwrap()).unwrap();
assert_eq!(loaded.mesh_uvs, project_file.mesh_uvs);
assert_eq!(loaded.project.format_version, REBUILT_MESH_UVS_VERSION);
}
#[test]
fn a_saved_uv_layout_requires_format_4_and_the_rebuild_setting() {
let project_file = rebuilt_uvs_sample();
let older_version = edit_project_json(&project_file, |json| json["format_version"] = TANGENT_BENT_NORMAL_VERSION.into());
let disabled_rebuild = edit_project_json(&project_file, |json| json["mesh_rebuild_uvs"] = false.into());
for archive in [older_version, disabled_rebuild] {
let error = load_project_bytes(&archive).map(|_| ()).expect_err("the archive has inconsistent UV layout metadata");
assert!(error.to_string().contains(UV_LAYOUT_ENTRY), "{error}");
}
}
#[test]
fn a_rebuilt_project_cannot_be_saved_without_its_layout() {
let mut project_file = rebuilt_uvs_sample();
project_file.mesh_uvs = None;
let error = save_project_bytes(&project_file).map(|_| ()).expect_err("the snapshot is missing the rebuilt UV layout");
assert!(error.to_string().contains(UV_LAYOUT_ENTRY), "{error}");
}
#[test]
fn rebuilt_uvs_without_a_valid_saved_layout_are_refused() {
let project_file = rebuilt_uvs_sample();
let without_layout = edit_archive(&project_file, |name, _| {
if name == UV_LAYOUT_ENTRY {
*name = "ignored.bin".into();
}
});
let edited_layout = |edit: fn(&mut Vec<u8>)| {
edit_archive(&project_file, |name, data| {
if name == UV_LAYOUT_ENTRY {
edit(data);
}
})
};
let truncated = edited_layout(|data| data.truncate(data.len() - 1));
let trailing_bytes = edited_layout(|data| data.push(0));
let short_header = edited_layout(|data| data.truncate(8));
let wrong_count = edited_layout(|data| data[8] = 9);
let non_finite = edited_layout(|data| data[12..16].copy_from_slice(&f32::NAN.to_le_bytes()));
let bad_magic = edited_layout(|data| data[0] = b'X');
for (case, bytes) in [
("missing", without_layout),
("truncated", truncated),
("trailing bytes", trailing_bytes),
("short header", short_header),
("wrong count", wrong_count),
("non-finite", non_finite),
("bad magic", bad_magic),
] {
let error = load_project_bytes(&bytes).unwrap_err();
assert!(!is_guard_error(&error), "{case}: {error}");
}
}
@@ -0,0 +1,99 @@
//! `uv_layout.bin` stores the generated UVs independently of the running unwrapper.
//! After the magic `TCUV`, the header stores a version and a corner count as little-endian u32s.
//! The body stores a little-endian f32 pair for each triangle corner in index order.
use std::io::{Read, Write};
use texturecraft_geom::MAX_TRIANGLES;
use texturecraft_geom::glam::Vec2;
use super::KIND;
use crate::{Result, malformed};
/// Zip entry name of the saved layout.
pub const UV_LAYOUT_ENTRY: &str = "uv_layout.bin";
const UV_LAYOUT_MAGIC: &[u8; 4] = b"TCUV";
const UV_LAYOUT_VERSION: u32 = 1;
const HEADER_BYTES: usize = 12;
const COORDINATE_BYTES: usize = 4;
const CORNER_BYTES: usize = 2 * COORDINATE_BYTES;
const BATCH_CORNERS: usize = 1024;
const MAX_LAYOUT_CORNERS: usize = MAX_TRIANGLES * 3;
/// Largest entry a valid mesh can need: every corner of the most triangles accepted.
pub const MAX_UV_LAYOUT_BYTES: u64 = uv_layout_bytes(MAX_LAYOUT_CORNERS);
/// Encoded size of a layout of `corners` UVs.
pub const fn uv_layout_bytes(corners: usize) -> u64 {
HEADER_BYTES as u64 + corners as u64 * CORNER_BYTES as u64
}
pub fn write_uv_layout(writer: &mut dyn Write, layout: &[Vec2]) -> std::io::Result<()> {
if layout.len() > MAX_LAYOUT_CORNERS {
return Err(std::io::Error::other("the UV layout has too many corners"));
}
writer.write_all(UV_LAYOUT_MAGIC)?;
writer.write_all(&UV_LAYOUT_VERSION.to_le_bytes())?;
writer.write_all(&(layout.len() as u32).to_le_bytes())?;
let mut buffer = [[0; CORNER_BYTES]; BATCH_CORNERS];
for batch in layout.chunks(BATCH_CORNERS) {
let encoded = &mut buffer[..batch.len()];
for (corner, uv) in encoded.iter_mut().zip(batch) {
if !uv.is_finite() {
return Err(std::io::Error::other("the UV layout has non-finite UVs"));
}
corner.copy_from_slice([uv.x.to_le_bytes(), uv.y.to_le_bytes()].as_flattened());
}
writer.write_all(encoded.as_flattened())?;
}
Ok(())
}
/// Decode one entry while holding only the decoded layout and a fixed-size buffer.
pub fn read_uv_layout(reader: &mut impl Read, entry_bytes: u64) -> Result<Vec<Vec2>> {
let bad = |why: &str| malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {why}"));
let mut header = [[0; COORDINATE_BYTES]; 3];
reader.read_exact(header.as_flattened_mut()).map_err(|error| malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {error}")))?;
let [magic, version, corners] = header;
if magic != *UV_LAYOUT_MAGIC {
return Err(bad("bad magic"));
}
if u32::from_le_bytes(version) != UV_LAYOUT_VERSION {
return Err(bad("unsupported version"));
}
let corners = u32::from_le_bytes(corners) as usize;
if corners > MAX_LAYOUT_CORNERS || uv_layout_bytes(corners) != entry_bytes {
return Err(bad("the corner count does not match the entry size"));
}
let mut layout = Vec::with_capacity(corners);
let mut buffer = [[[0; COORDINATE_BYTES]; 2]; BATCH_CORNERS];
while layout.len() < corners {
let count = (corners - layout.len()).min(BATCH_CORNERS);
let encoded = &mut buffer[..count];
reader.read_exact(encoded.as_flattened_mut().as_flattened_mut()).map_err(|error| malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {error}")))?;
for &[u, v] in encoded.iter() {
let uv = Vec2::new(f32::from_le_bytes(u), f32::from_le_bytes(v));
if !uv.is_finite() {
return Err(bad("non-finite UVs"));
}
layout.push(uv);
}
}
// Read through the end of the ZIP entry so its checksum is checked
match reader.read_exact(&mut [0]) {
Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => Ok(layout),
Err(error) => Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {error}"))),
Ok(()) => Err(bad("the corner count does not match the entry size")),
}
}
+18 -4
View File
@@ -13,8 +13,8 @@ use texturecraft_engine::template_cmds::template_label;
use crate::TextureCraftApp;
use crate::i18n::{tr, trf};
use crate::project_form::{
FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, auto_unwrap_row, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row,
unavailable, uv_tile_radios,
FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable,
uv_tile_radios,
};
use crate::state::{Mode, NewProject};
use crate::theme::{Tokens, caption};
@@ -151,6 +151,7 @@ pub fn create_command(new_project: &NewProject) -> Option<Value> {
"uvTiles": new_project.uv_tiles == Some(true),
"template": new_project.template,
"importCameras": new_project.import_cameras,
"rebuildUvs": new_project.rebuild_uvs,
}))
}
@@ -169,7 +170,14 @@ fn create_project(app: &mut TextureCraftApp) -> bool {
let stem = std::path::Path::new(name).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Untitled").to_string();
let template = app.session.template(&new_project.template);
match texturecraft_engine::Session::from_mesh_bytes_tiled(name, bytes, new_project.resolution, &stem, Some(new_project.uv_tiles == Some(true))) {
match texturecraft_engine::Session::from_mesh_bytes_with_uvs(
name,
bytes,
new_project.resolution,
&stem,
Some(new_project.uv_tiles == Some(true)),
new_project.rebuild_uvs,
) {
Ok(mut next) => {
if !new_project.import_cameras {
next.doc.project.cameras.clear();
@@ -259,12 +267,18 @@ fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) {
if check_row(ui, None, |ui| ui.checkbox(&mut uv_tiles, tr("Use UV Tile workflow")), |_| {}).changed() {
new_project.uv_tiles = Some(uv_tiles);
}
uv_tile_radios(ui, uv_tiles, tr("Tick Use UV Tile workflow first"));
ui.add_space(4.0);
sub_title(ui, tr("Import settings"), None);
check_row(ui, Some(tr("Keep the cameras stored in the mesh file")), |ui| ui.checkbox(&mut new_project.import_cameras, tr("Import cameras")), |_| {});
auto_unwrap_row(ui);
check_row(
ui,
Some(tr("Generate a fresh UV layout even when the mesh already has UVs. Meshes without UVs are always unwrapped.")),
|ui| ui.checkbox(&mut new_project.rebuild_uvs, tr("Rebuild mesh UVs")),
|_| {},
);
ui.add_space(4.0);
collapsible(ui, "np_import_baked_maps", tr("Import baked maps"), true, None, |ui| {
+1
View File
@@ -158,6 +158,7 @@ pub(crate) fn uv_tile_radios(ui: &mut Ui, enabled: bool, disabled_hint: &str) {
/// Import settings ▸ Auto-unwrap and its options. Meshes without UVs are always unwrapped, so the
/// box is ticked; turning it off and the options are not available yet.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn auto_unwrap_row(ui: &mut Ui) {
check_row(
ui,
+4
View File
@@ -295,6 +295,9 @@ pub struct NewProject {
/// Import settings > Import cameras: keep the cameras stored in the mesh file
#[serde(default = "import_cameras_default")]
pub import_cameras: bool,
/// Import settings > Rebuild mesh UVs.
#[serde(default)]
pub rebuild_uvs: bool,
/// Color management as chosen in the window (the project is always created as Legacy)
#[serde(skip)]
pub color_management: crate::project_form::ColorManagement,
@@ -332,6 +335,7 @@ impl Default for NewProject {
template: default_template(),
normal_format: None,
import_cameras: true,
rebuild_uvs: false,
color_management: crate::project_form::ColorManagement::Legacy,
baked_maps: Vec::new(),
}
+32 -5
View File
@@ -97,6 +97,24 @@ fn the_uv_layout_control_is_disabled_when_uv_tiles_are_off() {
assert!(disabled(&h, Role::RadioButton, "Keep UV tiles together per material"));
}
#[test]
fn rebuild_mesh_uvs_is_off_by_default_and_toggles_with_space() {
let mut h = harness();
let rebuild = h.get_by_role_and_label(Role::CheckBox, "Rebuild mesh UVs");
assert!(!rebuild.accesskit_node().is_disabled());
assert_eq!(rebuild.accesskit_node().toggled(), Some(egui::accesskit::Toggled::False));
rebuild.focus();
h.run_steps(2);
h.key_press(egui::Key::Space);
h.run_steps(2);
let rebuild = h.get_by_role_and_label(Role::CheckBox, "Rebuild mesh UVs");
assert_eq!(rebuild.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True));
assert!(h.state().ui.new_project.rebuild_uvs);
}
#[test]
fn create_waits_for_a_mesh_file() {
let mut h = harness();
@@ -117,8 +135,6 @@ fn settings_not_available_yet_are_disabled_with_a_hint() {
let unavailable = [
(Role::CheckBox, "Compute tangent space per fragment"),
(Role::RadioButton, "Use a separate texture set for each tile"),
(Role::CheckBox, "Auto-unwrap"),
(Role::Button, "Auto-unwrap options"),
(Role::RadioButton, "Custom unit scale"),
(Role::CheckBox, "Scale material fills in real-world units"),
];
@@ -257,17 +273,22 @@ fn the_supported_settings_reach_the_create_command() {
#[test]
fn ticking_uv_tiles_creates_a_uv_tile_project() {
for (tick, expected) in [(false, Vec::<u32>::new()), (true, vec![1002])] {
for (enable_uv_tiles, rebuild_uvs, expected_tiles) in [(false, false, vec![]), (true, false, vec![1002]), (true, true, vec![1001])] {
let mut h = harness();
let dir = TempDir::new("new-project-udim");
h.state_mut().ui.new_project.file = Some(mesh_file(&dir, TILE_1002_QUAD));
h.state_mut().ui.new_project.resolution = 128;
h.run_steps(2);
if tick {
if enable_uv_tiles {
h.get_by_role_and_label(Role::CheckBox, "Use UV Tile workflow").click();
h.run_steps(3);
assert!(!disabled(&h, Role::RadioButton, "Keep UV tiles together per material"));
}
if rebuild_uvs {
h.get_by_role_and_label(Role::CheckBox, "Rebuild mesh UVs").click();
h.run_steps(3);
}
h.get_by_role_and_label(Role::CheckBox, "Import cameras").click();
h.run_steps(2);
h.get_by_role_and_label(Role::Button, "Create").click();
@@ -276,8 +297,14 @@ fn ticking_uv_tiles_creates_a_uv_tile_project() {
let app = h.state();
assert!(!app.ui.windows.new_project, "the window closes");
assert_eq!(app.session.doc.project.name, "tiles");
assert_eq!(app.session.doc.project.texture_sets[0].uv_tiles, expected, "UV tiles ticked: {tick}");
assert_eq!(app.session.doc.project.texture_sets[0].uv_tiles, expected_tiles, "UV tiles enabled: {enable_uv_tiles}, rebuild UVs: {rebuild_uvs}");
assert_eq!(app.session.doc.project.texture_sets[0].resolution, 128);
if rebuild_uvs {
let bytes = texturecraft_engine::formats::save_project_bytes(&app.session.project_file()).unwrap();
let reopened = texturecraft_engine::Session::from_project_bytes(&bytes).unwrap();
assert_eq!(reopened.source_mesh().uvs, app.session.source_mesh().uvs);
assert_eq!(reopened.doc.project.format_version, texturecraft_engine::core::project::REBUILT_MESH_UVS_VERSION);
}
}
}
+5
View File
@@ -366,6 +366,11 @@ takes a font family, not a path: it reads only the system's font folders.
`file.close` leaves no project open: `session.inspect` then reports `projectOpen: false`, `command.list` marks every command but the project-independent ones as not enabled: the ones that open or create a project (`file.open`, `file.new`, `project.new`, `project.sample`), `project.inspect`, `viewport.frame`, `project.templates`, the `export.preset*` commands (`export.presets`, `export.preset.get`, `export.preset.save`, `export.preset.remove`) and the library and preset listings (`brush.preset.list`, `alpha.list`, `filter.list`, `material.list`, `mask.smart.list`, `text.fonts`), each still subject to its own enabled check. The rest are refused with "no project is open" until a project is opened or created. A `texturecraft --control` run starts with the sample project (an empty material ball with `--empty`); the app without `--control` starts with no project.
The desktop control channel accepts `rebuildUvs: true` on `file.new` to generate a new UV layout.
The default keeps a complete authored layout and unwraps meshes that need UVs, including on reopen.
With `rebuildUvs: true`, the project file saves the generated layout. Reopening or calling
`file.reimportMesh` without a path reuses it. Reimporting from a mesh file on disk rebuilds its UVs.
| Tool | Params | Notes |
|---|---|---|
| `session_inspect` | | The whole session as JSON |
+4 -4
View File
@@ -129,10 +129,10 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
the picker uses local files.
- **File › New project...** opens a setup form with BASIC SETTINGS (*Select...* a mesh file,
the project template, the document resolution; Create waits for a mesh) and ADVANCED SETTINGS (normal
map format, *Use UV Tile workflow*, *Import cameras*, *Import baked maps*, physical size, color
map format, *Use UV Tile workflow*, *Import cameras*, *Rebuild mesh UVs*, *Import baked maps*, physical size, color
management). The project is named after the mesh file. Settings TextureCraft does not have yet
(tangent space per fragment, UV tiles as separate texture sets, turning auto-unwrap off and its
options, a custom unit scale, OpenColorIO) are shown disabled with a hint; projects use Legacy color
(tangent space per fragment, UV tiles as separate texture sets, a custom unit scale, OpenColorIO)
are shown disabled with a hint; projects use Legacy color
management. In the browser, *Select...* opens the browser's file picker.
- **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs,
other filters and height-to-normal slopes keep their size in UV space at any tile resolution)
@@ -141,7 +141,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
channel types to add or remove. Show, hide or invert them all at once, or **focus** on the
active one. The project's **normal map format** (OpenGL or DirectX, in Texture Set Settings)
says how a normal map image set as a mesh map is read, and is the default for export.
- **Projects** are a single `.tcraft` file: the mesh, every layer (sparse and lossless), baked maps
- **Projects** are a single `.tcraft` file: the mesh (with its generated UV layout when *Rebuild mesh UVs* was chosen), every layer (sparse and lossless), baked maps
and imported images. **Project templates** start new work from a saved setup. *File › More save options › Save as template...* saves the open project's setup (dialog "Save template", in the user templates folder, no confirmation); New project lists "Default (OpenPBR)", the other built-ins with " (starter_assets)", yours with " (your_assets)", and opens on the template of the last project. *More save options* also has *Save as copy...* and *Save and reduce file size* (greyed, "Not available yet"). Closing the app,
or opening, starting or closing another project, with unsaved changes asks whether to save them
first (in the browser too, where Save downloads the project and closing or reloading the tab