Merge pull request #1731 from storytold/codex/obj-compat-options

Expose compatible OBJ read options
This commit is contained in:
FredApps
2026-11-15 23:55:19 +01:00
committed by GitHub
2 changed files with 53 additions and 3 deletions
+32 -3
View File
@@ -167,8 +167,22 @@ struct Object {
slots: HashMap<(String, Option<usize>, u32), usize>,
}
/// Options for callers that need strict parsing or original face-run order.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ReadOptions {
/// Return an error when a vertex or face line cannot be read.
pub strict: bool,
/// Keep separate runs when groups, materials or smoothing change.
pub preserve_runs: bool,
/// Do not resolve or report material libraries; `usemtl` names remain available.
pub ignore_material_libraries: bool,
/// Treat each group declaration as an object boundary, retaining repeated names.
pub groups_as_objects: bool,
}
struct Reader<'a> {
limits: &'a Limits,
options: ReadOptions,
v: Vec<[f64; 3]>,
colors: Vec<[f32; 4]>,
vt: Vec<[f32; 2]>,
@@ -314,7 +328,7 @@ impl Reader<'_> {
let Some(object) = self.objects.last_mut() else { return Ok(None) };
let slot = match self.slot {
Some(s) => s,
None => match object.slots.get(&(self.group.clone(), self.material, self.smoothing)) {
None => match (!self.options.preserve_runs).then(|| object.slots.get(&(self.group.clone(), self.material, self.smoothing))).flatten() {
Some(s) => *s,
None => {
if self.parts >= self.limits.max_parts {
@@ -386,6 +400,7 @@ impl Reader<'_> {
self.vn.push(n.unwrap_or(NAN3));
self.bad_lines += usize::from(n.is_none());
}
"s" if self.options.groups_as_objects => {}
"s" => {
self.slot = None;
self.smoothing = match it.next() {
@@ -395,12 +410,16 @@ impl Reader<'_> {
};
}
"o" => self.start_object(after.to_string())?,
"g" if self.options.groups_as_objects => {
self.group.clear();
self.start_object(after.to_string())?;
}
"g" => {
self.slot = None;
self.group = after.to_string();
}
"usemtl" => self.use_material(after)?,
"mtllib" => self.library(after, resolve)?,
"mtllib" if !self.options.ignore_material_libraries => self.library(after, resolve)?,
"f" => self.face(it)?,
_ => {}
}
@@ -456,6 +475,11 @@ impl Reader<'_> {
/// writes; every name asked, and every image a library names, is listed in
/// [`Scene::external`].
pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result<Scene> {
read_with_options(bytes, limits, resolve, &ReadOptions::default())
}
/// Read an OBJ using the selected compatibility behavior.
pub fn read_with_options(bytes: &[u8], limits: &Limits, resolve: Resolver, options: &ReadOptions) -> Result<Scene> {
// Lossy UTF-8 conversion can allocate, so bound it before copying invalid input.
if std::str::from_utf8(bytes).is_err() && bytes.len() > limits.max_data_bytes {
return Err(too_large(KIND, "invalid UTF-8 text exceeds the memory limit"));
@@ -463,6 +487,7 @@ pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result<Scene> {
let text = String::from_utf8_lossy(bytes);
let mut r = Reader {
limits,
options: *options,
v: vec![],
colors: vec![],
vt: vec![],
@@ -482,7 +507,8 @@ pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result<Scene> {
};
// A line ending in `\` continues on the next.
let mut joined = String::new();
for raw in text.lines() {
for (i, raw) in text.lines().enumerate() {
let raw = if i == 0 { raw.trim_start_matches('\u{feff}') } else { raw };
let line = raw.split('#').next().unwrap_or("");
if line.len() > limits.max_data_bytes || joined.len().checked_add(line.len()).is_none_or(|n| n > limits.max_data_bytes) {
return Err(too_large(KIND, "a continued line exceeds the memory limit"));
@@ -501,6 +527,9 @@ pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result<Scene> {
}
}
r.line(joined.trim(), resolve)?;
if options.strict && r.bad_lines > 0 {
return Err(malformed(KIND, "invalid vertex or face line"));
}
r.finish()
}
+21
View File
@@ -352,3 +352,24 @@ fn face_tokens_and_continued_lines_are_bounded_before_collection() {
let invalid = b"v 0 0 0\nf 1 1 1\n\xff";
assert!(matches!(read(invalid, &Limits { max_data_bytes: 4, ..Limits::default() }, &mut no_external), Err(Error::TooLarge(_))));
}
#[test]
fn compatibility_options_keep_runs_and_skip_material_libraries() {
let input = b"\xef\xbb\xbf v 0 0 0\nv 1 0 0\nv 0 1 0\nmtllib missing.mtl\nusemtl Red\nf 1 2 3\nusemtl Blue\nf 1 2 3\nusemtl Red\nf 1 2 3\n";
let options = crate::obj::ReadOptions { strict: true, preserve_runs: true, ignore_material_libraries: true, ..Default::default() };
let scene = crate::obj::read_with_options(input, &Limits::default(), &mut no_external, &options).unwrap();
let parts = &scene.meshes[0].parts;
assert_eq!(parts.len(), 3);
assert_eq!(parts[0].material, parts[2].material);
assert!(scene.warnings.is_empty());
assert!(crate::obj::read_with_options(b"v NaN 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n", &Limits::default(), &mut no_external, &options).is_err());
}
#[test]
fn group_boundaries_keep_repeated_names_separate() {
let input = b"v 0 0 0\nv 1 0 0\nv 0 1 0\ng Same\nusemtl M\nf 1 2 3\ng Same\nf 1 3 2\n";
let options = crate::obj::ReadOptions { groups_as_objects: true, ..Default::default() };
let scene = crate::obj::read_with_options(input, &Limits::default(), &mut no_external, &options).unwrap();
assert_eq!(scene.meshes.len(), 2);
assert!(scene.meshes.iter().all(|m| m.name == "Same"));
}