mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-20 22:40:44 +01:00
MCP tools for mesh files: bake_mesh_add, mesh_export, mesh_reimport
Agents in a workspace can now do everything the file menu and bake panel do with mesh files:
add high polys and the bake cage, export the mesh with its textures, and reimport the
project's mesh. Paths stay below the read and write roots, as for the other workspace tools.
- MCP tools bake_mesh_add {path, cage?}, mesh_export {path, format?} and
mesh_reimport {path?, preserveStrokes?}; control-channel methods bake.mesh.add, mesh.export
and mesh.reimport (headless); bridge mode reimports the app's own copy
- engine: Session::add_bake_mesh, Session::mesh_export and Session::reimport_mesh, shared by
bake.highPoly.add, bake.cage.set, file.exportMesh and file.reimportMesh (the cage now logs
textures it could not read, like high polys)
- docs/control-protocol.md lists the new tools and methods
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9eb200863b
commit
1187d0a4c1
7 files changed
+241
-66
No files matched your search
@@ -188,6 +188,34 @@ impl Headless {
|
||||
texturecraft_formats::self_contained_mesh(path, bytes, &mut |rel| self.read(&join(dir, rel)).ok()).map_err(|e| bad(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// Add a high-definition mesh for baking from `path` (or, with `cage`, set the bake cage).
|
||||
pub fn add_bake_mesh(&mut self, path: &str, cage: bool) -> Result<Value, AutomationError> {
|
||||
let f = self.read_mesh(path)?;
|
||||
Ok(self.session.add_bake_mesh(f, cage)?)
|
||||
}
|
||||
|
||||
/// Reimport the mesh from `path`, or from the project's own copy, keeping the project.
|
||||
pub fn reimport_mesh(&mut self, path: Option<&str>, preserve_strokes: bool) -> Result<Value, AutomationError> {
|
||||
let file = path.map(|p| self.read_mesh(p)).transpose()?;
|
||||
Ok(self.session.reimport_mesh(file, preserve_strokes)?)
|
||||
}
|
||||
|
||||
/// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the
|
||||
/// extension); usda and usdc write their textures next to it.
|
||||
pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result<Value, AutomationError> {
|
||||
let out = self.session.mesh_export(path, format)?;
|
||||
let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or(".");
|
||||
self.create_dir_all(dir)?;
|
||||
let mut textures = Vec::new();
|
||||
for (name, bytes) in &out.textures {
|
||||
let file = join(dir, name);
|
||||
self.write(&file, bytes)?;
|
||||
textures.push(file);
|
||||
}
|
||||
self.write(&out.path, &out.bytes)?;
|
||||
Ok(out.reply(textures))
|
||||
}
|
||||
|
||||
/// Import an image file as a project resource (for `layer.add.image`, `tool.stencil`).
|
||||
pub fn import_resource(&mut self, path: &str) -> Result<Value, AutomationError> {
|
||||
let bytes = self.read(path)?;
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
//!
|
||||
//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
|
||||
//! `session.inspect`, plus `command.batch {steps}`, `project.open {path}`,
|
||||
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `resource.import {path}`,
|
||||
//! `material.save {path, layer?, name?}`, `material.load {path}` (workspace-scoped versions of
|
||||
//! the engine commands),
|
||||
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `mesh.reimport {path?,
|
||||
//! preserveStrokes?}`, `mesh.export {path, format?}`, `bake.mesh.add {path, cage?}`,
|
||||
//! `resource.import {path}`, `material.save {path, layer?, name?}`, `material.load {path}`
|
||||
//! (workspace-scoped versions of the engine commands),
|
||||
//! `textures.export {dir, …}`, `render {view?, width?, height?, yaw?, pitch?}` (PNG base64, the
|
||||
//! shape of the app's `viewport.screenshot`) and `methods`.
|
||||
|
||||
@@ -32,6 +33,9 @@ pub const METHODS: &[&str] = &[
|
||||
"project.open",
|
||||
"project.save",
|
||||
"mesh.import",
|
||||
"mesh.reimport",
|
||||
"mesh.export",
|
||||
"bake.mesh.add",
|
||||
"resource.import",
|
||||
"material.save",
|
||||
"material.load",
|
||||
@@ -57,6 +61,13 @@ fn f32_of(p: &Value, k: &str) -> Result<Option<f32>, AutomationError> {
|
||||
}
|
||||
}
|
||||
|
||||
fn bool_of(p: &Value, k: &str) -> Result<bool, AutomationError> {
|
||||
match p.get(k) {
|
||||
None | Some(Value::Null) => Ok(false),
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(format!("`{k}` must be true or false"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn required<'a>(p: &'a Value, k: &str) -> Result<&'a str, AutomationError> {
|
||||
str_of(p, k).ok_or_else(|| bad(format!("`{k}` is required")))
|
||||
}
|
||||
@@ -80,6 +91,9 @@ impl Headless {
|
||||
"project.open" => self.open(required(p, "path")?),
|
||||
"project.save" => self.save(str_of(p, "path")),
|
||||
"mesh.import" => self.import_mesh(required(p, "path")?, u32_of(p, "resolution")?, str_of(p, "name")),
|
||||
"mesh.reimport" => self.reimport_mesh(str_of(p, "path"), bool_of(p, "preserveStrokes")?),
|
||||
"mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format")),
|
||||
"bake.mesh.add" => self.add_bake_mesh(required(p, "path")?, bool_of(p, "cage")?),
|
||||
"resource.import" => self.import_resource(required(p, "path")?),
|
||||
"material.save" => self.material_save(p),
|
||||
"material.load" => self.material_load(required(p, "path")?),
|
||||
@@ -93,10 +107,7 @@ impl Headless {
|
||||
pitch: f32_of(p, "pitch")?,
|
||||
samples: u32_of(p, "samples")?,
|
||||
bounces: u32_of(p, "bounces")?,
|
||||
cpu: match p.get("cpu") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad("`cpu` must be true or false"))?,
|
||||
},
|
||||
cpu: bool_of(p, "cpu")?,
|
||||
};
|
||||
let r = self.render_png(&o)?;
|
||||
Ok(json!({ "width": r.width, "height": r.height, "by": r.by, "png": base64::engine::general_purpose::STANDARD.encode(r.png) }))
|
||||
|
||||
@@ -109,6 +109,36 @@ pub struct ImportParams {
|
||||
pub resolution: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct BakeMeshParams {
|
||||
/// High-definition mesh file relative to the read root (any format `mesh_import` reads; base
|
||||
/// color textures feed the color map).
|
||||
pub path: String,
|
||||
/// Set the bake cage (a mesh with the low poly's triangles) instead of adding a high poly.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cage: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct ReimportParams {
|
||||
/// Mesh file relative to the read root; omit to re-read the project's own copy.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<String>,
|
||||
/// Painted pixels follow the surface where the new mesh's UVs changed.
|
||||
#[serde(default, rename = "preserveStrokes", skip_serializing_if = "Option::is_none")]
|
||||
pub preserve_strokes: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct MeshExportParams {
|
||||
/// Output file relative to the write root; the format's extension is appended if missing.
|
||||
pub path: String,
|
||||
/// obj, glb (textures embedded), usda, usdc (textures written next to it) or usdz (textures
|
||||
/// packaged); default: from the extension, else obj.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct ExportParams {
|
||||
/// Output folder relative to the write root (created if missing; `.` = the root).
|
||||
@@ -299,8 +329,11 @@ impl TexturecraftMcp {
|
||||
b.call(method, p).await
|
||||
}
|
||||
"project.save" if p.get("path").is_none() => b.call("ui.menu.invoke", json!({"id": "file.save"})).await,
|
||||
"project.save" | "project.open" | "mesh.import" | "resource.import" | "material.save" | "material.load" | "textures.export"
|
||||
| "command.batch" | "render" => {
|
||||
"mesh.reimport" if p.get("path").is_none() => {
|
||||
b.call("command.run", json!({"id": "file.reimportMesh", "params": {"preserveStrokes": p.get("preserveStrokes")}})).await
|
||||
}
|
||||
"project.save" | "project.open" | "mesh.import" | "mesh.reimport" | "mesh.export" | "bake.mesh.add" | "resource.import" | "material.save"
|
||||
| "material.load" | "textures.export" | "command.batch" | "render" => {
|
||||
Err(bad(format!("`{method}` with paths works in headless mode only: the running app reads and writes its own files (use ui_menu_invoke)")))
|
||||
}
|
||||
_ => b.call(method, p).await,
|
||||
@@ -357,7 +390,8 @@ impl TexturecraftMcp {
|
||||
|
||||
#[tool(description = "Run an engine command by id with JSON params (see command_list). Runs with defaults, never opens a \
|
||||
dialog. Commands given host paths (file.open, file.save, resource.import, material.save, …) are disabled: use the \
|
||||
workspace tools (project_open, project_save, mesh_import, resource_import, material_save, material_load, textures_export).")]
|
||||
workspace tools (project_open, project_save, mesh_import, mesh_reimport, mesh_export, bake_mesh_add, resource_import, \
|
||||
material_save, material_load, textures_export).")]
|
||||
async fn command_run(&self, Parameters(p): Parameters<RunParams>) -> Result<CallToolResult, McpError> {
|
||||
to_result(self.call("command.run", params(&p)).await)
|
||||
}
|
||||
@@ -412,6 +446,26 @@ impl TexturecraftMcp {
|
||||
to_result(self.call("mesh.import", params(&p)).await)
|
||||
}
|
||||
|
||||
#[tool(description = "Reimport the project's mesh from a file (path relative to the read root) or, without a path, from \
|
||||
the project's own copy. Texture sets map by material index; `preserveStrokes` re-projects painted pixels where the UVs \
|
||||
changed. Returns {preserved?}.")]
|
||||
async fn mesh_reimport(&self, Parameters(p): Parameters<ReimportParams>) -> Result<CallToolResult, McpError> {
|
||||
to_result(self.call("mesh.reimport", params(&p)).await)
|
||||
}
|
||||
|
||||
#[tool(description = "Export the mesh with its textures (obj, glb, usda, usdc or usdz; path relative to the write root). \
|
||||
Returns {path, textures?}.")]
|
||||
async fn mesh_export(&self, Parameters(p): Parameters<MeshExportParams>) -> Result<CallToolResult, McpError> {
|
||||
to_result(self.call("mesh.export", params(&p)).await)
|
||||
}
|
||||
|
||||
#[tool(description = "Add a high-definition mesh for baking (path relative to the read root), or with `cage: true` set the \
|
||||
bake cage. Files next to a .gltf or USD layer (buffers, base color textures) come along. Returns {name, meshes}; bake \
|
||||
with `bake`.")]
|
||||
async fn bake_mesh_add(&self, Parameters(p): Parameters<BakeMeshParams>) -> Result<CallToolResult, McpError> {
|
||||
to_result(self.call("bake.mesh.add", params(&p)).await)
|
||||
}
|
||||
|
||||
#[tool(description = "Import an image (png, jpg, tga, tif, bmp, webp, exr, hdr; path relative to the read root) as a project \
|
||||
resource. Returns its name, for command_run layer.add.image {name} or tool.stencil {image}.")]
|
||||
async fn resource_import(&self, Parameters(p): Parameters<OpenParams>) -> Result<CallToolResult, McpError> {
|
||||
@@ -481,7 +535,8 @@ impl TexturecraftMcp {
|
||||
instructions = "TextureCraft 3D texture painter. Every edit is an engine command: `command_list` shows ids and params, \
|
||||
`command_run`/`command_batch` run them. Start with `project_new` (built-in mesh) or `project_open`/`mesh_import` (files \
|
||||
relative to the workspace root), check your work with `session_inspect` and `viewport_render`, paint with `paint_stroke`, \
|
||||
bake with `bake`, then `project_save` (.tcraft) and `textures_export`. Undo: command_run edit.undo."
|
||||
bake with `bake` (high polys and the cage: `bake_mesh_add`), then `project_save` (.tcraft), `textures_export` and \
|
||||
`mesh_export`. Undo: command_run edit.undo."
|
||||
)]
|
||||
impl ServerHandler for TexturecraftMcp {}
|
||||
|
||||
|
||||
@@ -235,7 +235,10 @@ async fn agent_completes_texturing_tasks() {
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
const TOOLS: [&str; 19] = [
|
||||
const TOOLS: [&str; 22] = [
|
||||
"mesh_reimport",
|
||||
"mesh_export",
|
||||
"bake_mesh_add",
|
||||
"resource_import",
|
||||
"material_save",
|
||||
"material_load",
|
||||
@@ -274,6 +277,9 @@ async fn paths_outside_the_workspace_are_rejected() {
|
||||
tool_err(&c, "material_load", json!({"path": path})).await;
|
||||
tool_err(&c, "material_save", json!({"path": path})).await;
|
||||
tool_err(&c, "project_save", json!({"path": path})).await;
|
||||
tool_err(&c, "mesh_export", json!({"path": path})).await;
|
||||
tool_err(&c, "mesh_reimport", json!({"path": path})).await;
|
||||
tool_err(&c, "bake_mesh_add", json!({"path": path})).await;
|
||||
}
|
||||
let e = tool_err(&c, "textures_export", json!({"dir": "../outside/tex"})).await;
|
||||
assert!(e.contains("rejected"), "{e}");
|
||||
@@ -410,3 +416,31 @@ async fn mesh_import_reads_files_next_to_the_mesh() {
|
||||
shutdown(c, server).await;
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
/// The mesh round trip an agent does over MCP: export the mesh (with its textures) into the
|
||||
/// workspace, bake from it as a high poly and a cage, and reimport the project from it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn mesh_files_export_bake_and_reimport_in_the_workspace() {
|
||||
let base = tmp("mesh-files");
|
||||
let (c, server) = connect(workspace(&base)).await;
|
||||
run(&c, "layer.add.fill", json!({"color": [0.8, 0.2, 0.1], "roughness": 0.4})).await;
|
||||
let usda = tool(&c, "mesh_export", json!({"path": "out/cube", "format": "usda"})).await;
|
||||
assert_eq!(usda["path"], "out/cube.usda", "{usda}");
|
||||
let textures = usda["textures"].as_array().unwrap();
|
||||
assert!(!textures.is_empty() && textures.iter().all(|t| base.join(t.as_str().unwrap()).is_file()), "{usda}");
|
||||
assert_eq!(tool(&c, "mesh_export", json!({"path": "out/cube.glb"})).await["path"], "out/cube.glb");
|
||||
assert!(base.join("out/cube.usda").is_file() && base.join("out/cube.glb").is_file());
|
||||
// The loose usda arrives packaged with its textures.
|
||||
let high = tool(&c, "bake_mesh_add", json!({"path": "out/cube.usda"})).await;
|
||||
assert_eq!(high["name"], "cube.usdz", "{high}");
|
||||
let cage = tool(&c, "bake_mesh_add", json!({"path": "out/cube.glb", "cage": true})).await;
|
||||
assert_eq!(cage["meshes"]["cage"]["name"], "cube.glb", "{cage}");
|
||||
assert_eq!(inspect(&c).await["bakeMeshes"]["highPoly"][0]["name"], "cube.usdz");
|
||||
// A built-in mesh has no file to re-read; a file does.
|
||||
assert!(tool_err(&c, "mesh_reimport", json!({})).await.contains("built-in"));
|
||||
tool(&c, "mesh_reimport", json!({"path": "out/cube.glb", "preserveStrokes": true})).await;
|
||||
assert_eq!(inspect(&c).await["mesh"]["source"], "mesh.glb");
|
||||
tool(&c, "mesh_reimport", json!({})).await;
|
||||
shutdown(c, server).await;
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
@@ -248,6 +248,14 @@ impl Session {
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Add mesh file `f` as a high-definition mesh, or set it as the cage, logging what it could
|
||||
/// not fold in. Replies like `bake.highPoly.add` / `bake.cage.set`: `{name, meshes}`.
|
||||
pub fn add_bake_mesh(&mut self, f: texturecraft_formats::MeshFile, cage: bool) -> Result<Value> {
|
||||
let name = if cage { self.set_cage_bytes(&f.name, f.bytes)? } else { self.add_high_poly_bytes(&f.name, f.bytes)? };
|
||||
self.log.extend(f.warnings);
|
||||
Ok(json!({ "name": name, "meshes": meshes_json(self) }))
|
||||
}
|
||||
|
||||
/// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped.
|
||||
pub(crate) fn load_bake_meshes(&mut self, high: Vec<MeshFile>, cage: Option<MeshFile>) {
|
||||
for (name, bytes) in high {
|
||||
@@ -289,10 +297,7 @@ fn read_mesh_file(_: &str, _: &Value) -> Result<texturecraft_formats::MeshFile>
|
||||
}
|
||||
|
||||
fn high_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = read_mesh_file("bake.highPoly.add", p)?;
|
||||
let name = s.add_high_poly_bytes(&f.name, f.bytes)?;
|
||||
s.log.extend(f.warnings);
|
||||
Ok(json!({ "name": name, "meshes": meshes_json(s) }))
|
||||
s.add_bake_mesh(read_mesh_file("bake.highPoly.add", p)?, false)
|
||||
}
|
||||
|
||||
fn high_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -312,9 +317,7 @@ fn high_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn cage_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = read_mesh_file("bake.cage.set", p)?;
|
||||
let name = s.set_cage_bytes(&f.name, f.bytes)?;
|
||||
Ok(json!({ "name": name, "meshes": meshes_json(s) }))
|
||||
s.add_bake_mesh(read_mesh_file("bake.cage.set", p)?, true)
|
||||
}
|
||||
|
||||
/// Texture sets named by `ts` (default: the active one).
|
||||
|
||||
@@ -373,30 +373,41 @@ fn save_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Re-read the mesh and keep the project (texture sets map by material index). Nothing in `s`
|
||||
// changes unless the new mesh fits the project.
|
||||
let (mesh, source, warnings) = match strp(p, "path") {
|
||||
Some(path) => {
|
||||
let f = native::read_mesh("file.reimportMesh", path)?;
|
||||
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)
|
||||
let file = strp(p, "path").map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?;
|
||||
s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Session {
|
||||
/// Replace the mesh with `file` (or re-read the project's own copy) and keep the project:
|
||||
/// texture sets map by material index. Nothing changes unless the new mesh fits the project.
|
||||
/// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies
|
||||
/// like `file.reimportMesh`: `{preserved?}`.
|
||||
pub fn reimport_mesh(&mut self, file: Option<texturecraft_formats::MeshFile>, preserve_strokes: bool) -> Result<Value> {
|
||||
let (mesh, source, warnings) = 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)
|
||||
}
|
||||
None => match &self.mesh_source {
|
||||
Some((ext, bytes)) => {
|
||||
(texturecraft_formats::import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(fe)?.mesh, self.mesh_source.clone(), Vec::new())
|
||||
}
|
||||
None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")),
|
||||
},
|
||||
};
|
||||
check_materials(&self.doc.project, &mesh)?;
|
||||
let mut doc = self.doc.clone();
|
||||
if let Some((ext, _)) = &source {
|
||||
doc.project.mesh = format!("mesh.{ext}");
|
||||
}
|
||||
None => match &s.mesh_source {
|
||||
Some((ext, bytes)) => (texturecraft_formats::import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(fe)?.mesh, s.mesh_source.clone(), Vec::new()),
|
||||
None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")),
|
||||
},
|
||||
};
|
||||
check_materials(&s.doc.project, &mesh)?;
|
||||
let mut doc = s.doc.clone();
|
||||
if let Some((ext, _)) = &source {
|
||||
doc.project.mesh = format!("mesh.{ext}");
|
||||
let mut next = Session::new(doc, mesh, source)?;
|
||||
next.log.extend(warnings);
|
||||
next.path = self.path.clone();
|
||||
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
|
||||
self.switch_to(next);
|
||||
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
|
||||
}
|
||||
let mut next = Session::new(doc, mesh, source)?;
|
||||
next.log.extend(warnings);
|
||||
next.path = s.path.clone();
|
||||
let preserved = crate::commands::boolp(p, "preserveStrokes").unwrap_or(false).then(|| crate::preserve::preserve_strokes(s, &mut next));
|
||||
s.switch_to(next);
|
||||
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -414,33 +425,60 @@ fn export_textures(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn export_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const FORMATS: [&str; 5] = ["obj", "glb", "usda", "usdc", "usdz"];
|
||||
let path = native::path_param(p, "path", "file.exportMesh")?;
|
||||
let ext = match strp(p, "format") {
|
||||
Some(f) if FORMATS.contains(&f) => f.to_string(),
|
||||
Some(other) => return Err(bad("file.exportMesh", format!("unknown mesh format `{other}` ({})", FORMATS.join(", ")))),
|
||||
None if FORMATS.contains(&ext_of(path).as_str()) => ext_of(path),
|
||||
None => "obj".into(),
|
||||
};
|
||||
let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") };
|
||||
let out = s.mesh_export(path, strp(p, "format"))?;
|
||||
let write = |path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| bad("file.exportMesh", format!("cannot write {path}: {e}")));
|
||||
let dir = std::path::Path::new(&out.path).parent().unwrap_or(std::path::Path::new(""));
|
||||
let mut textures = Vec::new();
|
||||
match (ext.as_str(), texturecraft_formats::UsdFormat::from_ext(&ext)) {
|
||||
("glb", _) => write(&path, &s.mesh_glb_bytes()?)?,
|
||||
(_, Some(format)) => {
|
||||
let usd = s.mesh_usd(format)?;
|
||||
let dir = std::path::Path::new(&path).parent().unwrap_or(std::path::Path::new(""));
|
||||
for (name, bytes) in &usd.textures {
|
||||
let file = dir.join(name).display().to_string();
|
||||
write(&file, bytes)?;
|
||||
textures.push(file);
|
||||
for (name, bytes) in &out.textures {
|
||||
let file = dir.join(name).display().to_string();
|
||||
write(&file, bytes)?;
|
||||
textures.push(file);
|
||||
}
|
||||
write(&out.path, &out.bytes)?;
|
||||
s.log.push(format!("Exported mesh to {}", out.path));
|
||||
Ok(out.reply(textures))
|
||||
}
|
||||
|
||||
/// The mesh formats `file.exportMesh` writes.
|
||||
pub const MESH_EXPORT_FORMATS: [&str; 5] = ["obj", "glb", "usda", "usdc", "usdz"];
|
||||
|
||||
/// A mesh export: the mesh file's path (with its extension) and bytes, and (usda, usdc) the
|
||||
/// textures it references, by file name, to write next to it.
|
||||
pub struct MeshExport {
|
||||
pub path: String,
|
||||
pub bytes: Vec<u8>,
|
||||
pub textures: Vec<(String, Vec<u8>)>,
|
||||
}
|
||||
|
||||
impl MeshExport {
|
||||
/// The `file.exportMesh` reply, given where the textures were written.
|
||||
pub fn reply(&self, textures: Vec<String>) -> Value {
|
||||
if textures.is_empty() { json!({ "path": self.path }) } else { json!({ "path": self.path, "textures": textures }) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The working mesh as a file for `path`, in `format` (obj, glb, usda, usdc, usdz; default:
|
||||
/// from the extension, else OBJ). The extension is appended when it doesn't match.
|
||||
pub fn mesh_export(&mut self, path: &str, format: Option<&str>) -> Result<MeshExport> {
|
||||
let ext = match format {
|
||||
Some(f) if MESH_EXPORT_FORMATS.contains(&f) => f.to_string(),
|
||||
Some(other) => return Err(bad("file.exportMesh", format!("unknown mesh format `{other}` ({})", MESH_EXPORT_FORMATS.join(", ")))),
|
||||
None if MESH_EXPORT_FORMATS.contains(&ext_of(path).as_str()) => ext_of(path),
|
||||
None => "obj".into(),
|
||||
};
|
||||
let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") };
|
||||
let (bytes, textures) = match (ext.as_str(), texturecraft_formats::UsdFormat::from_ext(&ext)) {
|
||||
("glb", _) => (self.mesh_glb_bytes()?, Vec::new()),
|
||||
(_, Some(format)) => {
|
||||
let usd = self.mesh_usd(format)?;
|
||||
(usd.bytes, usd.textures)
|
||||
}
|
||||
write(&path, &usd.bytes)?;
|
||||
}
|
||||
_ => write(&path, &s.mesh_obj_bytes())?,
|
||||
_ => (self.mesh_obj_bytes(), Vec::new()),
|
||||
};
|
||||
Ok(MeshExport { path, bytes, textures })
|
||||
}
|
||||
s.log.push(format!("Exported mesh to {path}"));
|
||||
Ok(if textures.is_empty() { json!({ "path": path }) } else { json!({ "path": path, "textures": textures }) })
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -92,8 +92,8 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1
|
||||
|
||||
- **Headless** (default): an in-process session that starts on the material ball (1024).
|
||||
Files are reachable only below the roots given at launch, as forward-slash paths relative to
|
||||
them: `--read-root <dir>` for `project_open` / `mesh_import`, `--write-root <dir>` for
|
||||
`project_save` / `material_save` / `textures_export`. Without roots there is no file access. `..`, absolute
|
||||
them: `--read-root <dir>` for `project_open` / `mesh_import` / `mesh_reimport` / `bake_mesh_add`,
|
||||
`--write-root <dir>` for `project_save` / `material_save` / `textures_export` / `mesh_export`. Without roots there is no file access. `..`, absolute
|
||||
paths, drive letters, device names and symlink or junction escapes are refused.
|
||||
- **Bridge**: `--bridge <port>` forwards to a running `texturecraft --control <port>` (token from
|
||||
`--token`, `TEXTURECRAFT_CONTROL_TOKEN` or the app's token file). The app reads and writes its
|
||||
@@ -113,7 +113,10 @@ a `path`) is refused, and so is any command given a `path` or `dir` (`resource.i
|
||||
| `project_new` | `{mesh?, resolution?, name?, template?}` | Built-in mesh: material_ball, sphere, cube, rounded_cube, cylinder, torus, plane, crate; `template` names a project template (`project.templates`) |
|
||||
| `project_open` | `{path}` | `.tcraft` or a mesh file, relative to the read root |
|
||||
| `project_save` | `{path?}` | `.tcraft` (appended if missing), relative to the write root |
|
||||
| `mesh_import` | `{path, resolution?}` | New project from .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.obj/.ply/.stl |
|
||||
| `mesh_import` | `{path, resolution?}` | New project from .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl; a .gltf's buffers and images and a loose USD layer's textures are read from its folder |
|
||||
| `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter |
|
||||
| `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (usda / usdc textures next to it) → `{path, textures?}` |
|
||||
| `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` |
|
||||
| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil` |
|
||||
| `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root |
|
||||
| `material_load` | `{path}` | Add a `.tcmat` smart material above the selection |
|
||||
@@ -186,6 +189,9 @@ File access follows `--read-root` / `--write-root` as for MCP.
|
||||
| `project.open` | `{path}` |
|
||||
| `project.save` | `{path?}` |
|
||||
| `mesh.import` | `{path, resolution?, name?}` |
|
||||
| `mesh.reimport` | `{path?, preserveStrokes?}` |
|
||||
| `mesh.export` | `{path, format?}` |
|
||||
| `bake.mesh.add` | `{path, cage?}` |
|
||||
| `resource.import` | `{path}` |
|
||||
| `material.save` | `{path, layer?, name?}` |
|
||||
| `material.load` | `{path}` |
|
||||
|
||||
Reference in new issue
Block a user