formats: stop copying whole OBJ and glTF inputs before parsing (#503)

* formats: stop copying whole OBJ and glTF inputs before parsing

* formats: format the mesh-import copy changes
This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-15 04:18:22 -05:00
1 parent ad3aa8c9b8
commit 75502053db
2 files changed
+12 -7

No files matched your search

+4 -4
View File
@@ -28,9 +28,9 @@ fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option<Vec<u8>>)> {
let (json, blob) = if bytes.starts_with(b"glTF") {
let mut glb = gltf::Glb::from_slice(bytes).map_err(|e| malformed(KIND, e))?;
let blob = glb.bin.take().map(std::borrow::Cow::into_owned);
(glb.json.into_owned(), blob)
(glb.json, blob)
} else {
(bytes.to_vec(), None)
(std::borrow::Cow::Borrowed(bytes), None)
};
let mut value: serde_json::Value = serde_json::from_slice(&json).map_err(|e| malformed(KIND, e))?;
if let Some(scenes) = value.get_mut("scenes").and_then(serde_json::Value::as_array_mut) {
@@ -40,8 +40,8 @@ fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option<Vec<u8>>)> {
}
}
}
let json = serde_json::to_vec(&value).map_err(|e| malformed(KIND, e))?;
let root = gltf::json::Root::from_slice(&json).map_err(|e| malformed(KIND, e))?;
// Consume the DOM directly rather than serialising it back to a second full-size buffer.
let root: gltf::json::Root = serde_json::from_value(value).map_err(|e| malformed(KIND, e))?;
let document = gltf::Document::from_json(root).map_err(|e| malformed(KIND, e))?;
Ok((document, blob))
}
+8 -3
View File
@@ -1,5 +1,7 @@
//! Wavefront OBJ (via `tobj`): polygons fan-triangulated, one vertex per unique v/vt/vn.
use std::io::{BufReader, Read};
use texturecraft_geom::glam::{Vec2, Vec3, Vec4};
use super::{RawMesh, check_triangles, check_vertices};
@@ -27,12 +29,15 @@ fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
}
let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect();
let source = format!("mtllib texturecraft-usemtl.mtl\n{text}");
let prefix = "mtllib texturecraft-usemtl.mtl\n";
// Feed the prefix and the borrowed (or lossily converted) body as one reader: neither a
// whole-file copy nor an extra string is needed before tobj parses it.
let mut source = BufReader::new(prefix.as_bytes().chain(text.as_bytes()));
// Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates
let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true };
let (models, materials) =
tobj::load_obj_buf(&mut source.as_bytes(), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?;
let (models, materials) = tobj::load_obj_buf(&mut source, &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?;
let materials = materials.unwrap_or_default();
let mut raw = RawMesh::default();