tinyobjloader 2.0.0__cp311-abi3-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tinyobjloader/_api.py ADDED
@@ -0,0 +1,937 @@
1
+ """Typed, numpy-optional wrapper around the C11 loader core.
2
+
3
+ The extension returns plain dicts whose array values are read-only
4
+ ``memoryview`` objects (zero copy, buffer protocol). This module turns them
5
+ into small classes, and into ``numpy.ndarray`` views when numpy is installed.
6
+ Nothing here imports numpy unconditionally.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os as _os
12
+ import threading as _threading
13
+ import warnings as _warnings
14
+ from collections.abc import Iterator, Sequence
15
+ from dataclasses import dataclass, fields
16
+ from typing import Any, BinaryIO, Self
17
+
18
+ from . import _core
19
+
20
+ try: # numpy is optional
21
+ import numpy as _np
22
+ except Exception: # noqa: BLE001 - any import failure means "no numpy"
23
+ _np = None
24
+
25
+ __all__ = [
26
+ "Array",
27
+ "Attrib",
28
+ "FreeformInfo",
29
+ "Limits",
30
+ "Lines",
31
+ "Material",
32
+ "MergedMesh",
33
+ "Mesh",
34
+ "ObjChunk",
35
+ "ObjScene",
36
+ "Points",
37
+ "Shape",
38
+ "SkinWeights",
39
+ "Tag",
40
+ "TextureOption",
41
+ "iter_load",
42
+ "load",
43
+ "load_obj",
44
+ "load_obj_from_memory",
45
+ "loads",
46
+ "parse_mtl",
47
+ "write_obj",
48
+ ]
49
+
50
+ Array = Any
51
+
52
+ _NUMPY = _np is not None
53
+ # Buffer format characters used by the extension: "f"/"d" for the two real
54
+ # families, "i"/"I" for the 32-bit index and count arrays, "Q" for 64-bit
55
+ # offsets.
56
+ _DTYPES = {
57
+ "f": _np.float32 if _NUMPY else None,
58
+ "d": _np.float64 if _NUMPY else None,
59
+ "i": _np.int32 if _NUMPY else None,
60
+ "I": _np.uint32 if _NUMPY else None,
61
+ "Q": _np.uint64 if _NUMPY else None,
62
+ }
63
+
64
+
65
+ def _precision_tag(precision: int | str) -> int:
66
+ """Normalize a precision request to 32 or 64."""
67
+ if precision in (32, "f4", "f32", "float32", "single"):
68
+ return 32
69
+ if precision in (64, "f8", "f64", "float64", "double"):
70
+ return 64
71
+ raise ValueError(
72
+ f"precision must be 32 or 64 (got {precision!r})"
73
+ )
74
+
75
+
76
+ def _real_format(bits: int) -> str:
77
+ return "d" if bits == 64 else "f"
78
+
79
+
80
+ def _array(view, fmt: str, columns: int | None = None) -> Array:
81
+ """Build a numpy array (numpy present) or a reshaped memoryview.
82
+
83
+ ``fmt`` is the extension's buffer format character. An empty result is
84
+ one-dimensional when numpy is absent (zero-length multi-dimensional
85
+ memoryview casts are not supported by CPython).
86
+ """
87
+ if view is None:
88
+ if _NUMPY:
89
+ return _np.empty((0, columns) if columns else (0,), dtype=_DTYPES[fmt])
90
+ return memoryview(b"").cast("B").cast(fmt)
91
+ if _NUMPY:
92
+ arr = _np.frombuffer(view, dtype=_DTYPES[fmt])
93
+ return arr.reshape(-1, columns) if columns else arr
94
+ if columns:
95
+ count = len(view) // columns
96
+ try:
97
+ # CPython refuses to cast between two non-byte formats, so go
98
+ # through "B" first: the result is still a zero-copy view.
99
+ return view.cast("B").cast(fmt, (count, columns))
100
+ except (TypeError, ValueError):
101
+ return view
102
+ return view
103
+
104
+
105
+ def _column(array: Array, index: int) -> Array:
106
+ if _NUMPY:
107
+ return array[:, index]
108
+ return [array[i, index] for i in range(len(array))]
109
+
110
+
111
+ def _pair(values) -> tuple:
112
+ return tuple(values)
113
+
114
+
115
+ def _mtl_bytes(value):
116
+ return value.encode() if isinstance(value, str) else value
117
+
118
+
119
+ def _normalize_mtl(mtl):
120
+ """Accept inline text for `.mtl` sources as well as bytes."""
121
+ if mtl is None:
122
+ return None
123
+ if isinstance(mtl, str):
124
+ return mtl.encode()
125
+ if isinstance(mtl, dict):
126
+ return {name: _mtl_bytes(value) for name, value in mtl.items()}
127
+ if isinstance(mtl, (list, tuple)):
128
+ return [(name, _mtl_bytes(value)) for name, value in mtl]
129
+ return mtl
130
+
131
+
132
+ @dataclass(slots=True)
133
+ class TextureOption:
134
+ type: str
135
+ sharpness: float
136
+ brightness: float
137
+ contrast: float
138
+ origin_offset: tuple
139
+ scale: tuple
140
+ turbulence: tuple
141
+ texture_resolution: int
142
+ clamp: bool
143
+ blendu: bool
144
+ blendv: bool
145
+ imfchan: str
146
+ bump_multiplier: float
147
+ colorspace: str
148
+
149
+
150
+ @dataclass(slots=True)
151
+ class Material:
152
+ name: str
153
+ ambient: tuple
154
+ diffuse: tuple
155
+ specular: tuple
156
+ transmittance: tuple
157
+ emission: tuple
158
+ shininess: float
159
+ ior: float
160
+ dissolve: float
161
+ illum: int
162
+ roughness: float
163
+ metallic: float
164
+ sheen: float
165
+ clearcoat_thickness: float
166
+ clearcoat_roughness: float
167
+ anisotropy: float
168
+ anisotropy_rotation: float
169
+ ambient_texname: str
170
+ diffuse_texname: str
171
+ specular_texname: str
172
+ specular_highlight_texname: str
173
+ bump_texname: str
174
+ displacement_texname: str
175
+ alpha_texname: str
176
+ reflection_texname: str
177
+ roughness_texname: str
178
+ metallic_texname: str
179
+ sheen_texname: str
180
+ emissive_texname: str
181
+ normal_texname: str
182
+ texopt: dict[str, TextureOption]
183
+ unknown_params: dict[str, str]
184
+ mtlx_lines: list[str]
185
+
186
+ def __repr__(self) -> str:
187
+ maps = sum(1 for name in _MATERIAL_TEXNAMES if getattr(self, name))
188
+ return f"Material(name={self.name!r}, diffuse={self.diffuse!r}, maps={maps})"
189
+
190
+
191
+ @dataclass(slots=True)
192
+ class Tag:
193
+ name: str
194
+ int_values: Array
195
+ float_values: Array
196
+ string_values: list[str]
197
+
198
+ def __repr__(self) -> str:
199
+ return (
200
+ f"Tag(name={self.name!r}, ints={len(self.int_values)}, "
201
+ f"floats={len(self.float_values)}, strings={len(self.string_values)})"
202
+ )
203
+
204
+
205
+ @dataclass(slots=True)
206
+ class SkinWeights:
207
+ """Flattened `vw` data: per-vertex slice of the joint/weight arrays."""
208
+
209
+ vertex_ids: Array
210
+ offsets: Array
211
+ joint_ids: Array
212
+ weights: Array
213
+ max_joint_id: int
214
+
215
+ def __len__(self) -> int:
216
+ return len(self.vertex_ids)
217
+
218
+ def __getitem__(self, index: int) -> tuple[int, dict[int, float]]:
219
+ start = int(self.offsets[index])
220
+ end = int(self.offsets[index + 1])
221
+ weights = {
222
+ int(self.joint_ids[j]): float(self.weights[j])
223
+ for j in range(start, end)
224
+ }
225
+ return int(self.vertex_ids[index]), weights
226
+
227
+ def __repr__(self) -> str:
228
+ return (
229
+ f"SkinWeights(vertices={len(self.vertex_ids)}, "
230
+ f"max_joint_id={self.max_joint_id})"
231
+ )
232
+
233
+
234
+ @dataclass(slots=True)
235
+ class Attrib:
236
+ vertices: Array
237
+ vertex_weights: Array
238
+ normals: Array
239
+ texcoords: Array
240
+ texcoord_ws: Array
241
+ colors: Array
242
+ skin_weights: SkinWeights | None
243
+ skel_lines: list[str]
244
+
245
+ def __repr__(self) -> str:
246
+ return (
247
+ f"Attrib(vertices={len(self.vertices)}, normals={len(self.normals)}, "
248
+ f"texcoords={len(self.texcoords)}, colors={len(self.colors)}, "
249
+ f"skin_weights={self.skin_weights!r})"
250
+ )
251
+
252
+
253
+ @dataclass(slots=True)
254
+ class Mesh:
255
+ indices: Array
256
+ num_face_vertices: Array
257
+ material_ids: Array
258
+ smoothing_group_ids: Array
259
+ tags: list[Tag]
260
+ tag_lines: list[str]
261
+ num_indices: int
262
+ num_faces: int
263
+
264
+ @property
265
+ def vertex_indices(self) -> Array:
266
+ """Vertex index of every corner (the first int of each triple)."""
267
+ return _column(self.indices, 0)
268
+
269
+ @property
270
+ def normal_indices(self) -> Array:
271
+ return _column(self.indices, 1)
272
+
273
+ @property
274
+ def texcoord_indices(self) -> Array:
275
+ return _column(self.indices, 2)
276
+
277
+ def triangles(self) -> Array:
278
+ """Vertex indices as an ``(F, 3)`` array; every face must be a triangle."""
279
+ if self.num_faces and any_non_triangle(self.num_face_vertices):
280
+ raise ValueError("mesh has non-triangle faces; load with triangulate=True")
281
+ if _NUMPY:
282
+ return self.indices[:, 0].reshape(-1, 3)
283
+ flat = self.vertex_indices
284
+ return [tuple(flat[i : i + 3]) for i in range(0, len(flat), 3)]
285
+
286
+ def split_by_material(self) -> dict[int, Array]:
287
+ """Triangle vertex indices grouped by material id (requires numpy)."""
288
+ if not _NUMPY:
289
+ raise RuntimeError("split_by_material requires numpy")
290
+ tris = self.triangles()
291
+ ids = _np.asarray(self.material_ids)
292
+ return {int(m): tris[ids == m] for m in _np.unique(ids)}
293
+
294
+ def __repr__(self) -> str:
295
+ return (
296
+ f"Mesh(faces={len(self.num_face_vertices)}, corners={self.num_indices}, "
297
+ f"tags={len(self.tags)})"
298
+ )
299
+
300
+
301
+ @dataclass(slots=True, repr=False)
302
+ class MergedMesh(Mesh):
303
+ """Every shape's faces in one set of arrays (see :meth:`ObjScene.merged`).
304
+
305
+ Faces of shape ``i`` are ``shape_face_offsets[i]:shape_face_offsets[i + 1]``.
306
+ """
307
+
308
+ shape_face_offsets: Array = None
309
+
310
+ def __repr__(self) -> str:
311
+ return (
312
+ f"MergedMesh(faces={self.num_faces}, corners={self.num_indices}, "
313
+ f"shapes={max(len(self.shape_face_offsets) - 1, 0)})"
314
+ )
315
+
316
+
317
+ def any_non_triangle(arity) -> bool:
318
+ if _NUMPY:
319
+ return bool((_np.asarray(arity) != 3).any())
320
+ return any(n != 3 for n in arity)
321
+
322
+
323
+ @dataclass(slots=True)
324
+ class Lines:
325
+ indices: Array
326
+ num_line_vertices: Array
327
+ num_lines: int
328
+
329
+ def __repr__(self) -> str:
330
+ return f"Lines(polylines={self.num_lines}, corners={len(self.indices)})"
331
+
332
+
333
+ @dataclass(slots=True)
334
+ class Points:
335
+ indices: Array
336
+
337
+ def __repr__(self) -> str:
338
+ return f"Points(count={len(self.indices)})"
339
+
340
+
341
+ @dataclass(slots=True)
342
+ class FreeformInfo:
343
+ """Summary of retained free-form records (``parse_freeform=True``)."""
344
+
345
+ param_vert_components: int
346
+ num_param_verts: int
347
+ num_curves: int
348
+ num_curves2: int
349
+ num_surfaces: int
350
+
351
+
352
+ @dataclass(slots=True)
353
+ class Shape:
354
+ name: str
355
+ mesh: Mesh
356
+ lines: Lines
357
+ points: Points
358
+ freeform: FreeformInfo | None
359
+
360
+ def __repr__(self) -> str:
361
+ return (
362
+ f"Shape(name={self.name!r}, faces={len(self.mesh.num_face_vertices)}, "
363
+ f"lines={self.lines.num_lines}, points={len(self.points.indices)}, "
364
+ f"freeform={self.freeform!r})"
365
+ )
366
+
367
+
368
+ class _LazyList(Sequence):
369
+ """Read-only sequence that builds items on first access and caches them."""
370
+
371
+ __slots__ = ("_build", "_items", "_lock")
372
+
373
+ def __init__(self, count: int, build) -> None:
374
+ self._build = build
375
+ self._items: list = [None] * count
376
+ self._lock = _threading.Lock()
377
+
378
+ def __len__(self) -> int:
379
+ return len(self._items)
380
+
381
+ def __getitem__(self, index):
382
+ if isinstance(index, slice):
383
+ return [self[i] for i in range(*index.indices(len(self)))]
384
+ item = self._items[index]
385
+ if item is None:
386
+ if index < 0:
387
+ index += len(self._items)
388
+ with self._lock:
389
+ item = self._items[index]
390
+ if item is None:
391
+ item = self._items[index] = self._build(index)
392
+ return item
393
+
394
+ def __repr__(self) -> str:
395
+ return f"<{len(self)} items>"
396
+
397
+
398
+ class ObjScene:
399
+ """A loaded `.obj` scene.
400
+
401
+ ``shapes`` and ``materials`` are built lazily, so scenes with very many
402
+ groups stay cheap until they are visited. Arrays are zero-copy views of
403
+ the loader's memory and keep it alive on their own.
404
+ """
405
+
406
+ __slots__ = ("attrib", "shapes", "materials", "shape_names", "warnings",
407
+ "errors", "precision", "_capsule")
408
+
409
+ def __init__(self, raw: dict, precision: int) -> None:
410
+ capsule = raw["capsule"]
411
+ core = _core_for(precision)
412
+ self._capsule = capsule
413
+ self.precision = precision
414
+ self.attrib = _attrib(raw["attrib"], precision)
415
+ self.shape_names: list[str] = list(raw["shape_names"])
416
+ self.warnings: list[str] = list(raw["warnings"])
417
+ self.errors: list[str] = list(raw["errors"])
418
+ self.shapes: Sequence[Shape] = _LazyList(
419
+ len(self.shape_names),
420
+ lambda i: _shape(core.shape(capsule, i), precision),
421
+ )
422
+ self.materials: Sequence[Material] = _LazyList(
423
+ raw["num_materials"], lambda i: _material(core.material(capsule, i))
424
+ )
425
+
426
+ def merged(self) -> MergedMesh:
427
+ """Concatenate the faces of every shape (one copy, done in C)."""
428
+ raw = _core_for(self.precision).merged(self._require())
429
+ num_faces = 0 if raw["num_face_vertices"] is None else len(raw["num_face_vertices"])
430
+ num_indices = 0 if raw["indices"] is None else len(raw["indices"]) // 3
431
+ return MergedMesh(
432
+ indices=_array(raw["indices"], "i", 3),
433
+ num_face_vertices=_array(raw["num_face_vertices"], "I"),
434
+ material_ids=_array(raw["material_ids"], "i"),
435
+ smoothing_group_ids=_array(raw["smoothing_group_ids"], "I"),
436
+ tags=[],
437
+ tag_lines=[],
438
+ num_indices=num_indices,
439
+ num_faces=num_faces,
440
+ shape_face_offsets=_array(raw["shape_face_offsets"], "Q"),
441
+ )
442
+
443
+ def _require(self):
444
+ if self._capsule is None:
445
+ raise ValueError("the scene has been closed")
446
+ return self._capsule
447
+
448
+ def close(self) -> None:
449
+ """Drop this object's reference to the loaded scene.
450
+
451
+ Arrays and shapes handed out keep the scene alive (they own a
452
+ reference to it), so this never invalidates memory in use.
453
+ """
454
+ self._capsule = None
455
+
456
+ def __enter__(self) -> Self:
457
+ return self
458
+
459
+ def __exit__(self, *exc_info) -> None:
460
+ self.close()
461
+
462
+ @property
463
+ def materials_by_name(self) -> dict[str, Material]:
464
+ """Materials keyed by their ``newmtl`` name (the last one wins)."""
465
+ return {material.name: material for material in self.materials}
466
+
467
+ def __repr__(self) -> str:
468
+ return (
469
+ f"ObjScene(shapes={len(self.shapes)}, materials={len(self.materials)}, "
470
+ f"vertices={len(self.attrib.vertices)}, precision={self.precision}, "
471
+ f"warnings={len(self.warnings)}, errors={len(self.errors)})"
472
+ )
473
+
474
+
475
+ @dataclass(frozen=True, slots=True)
476
+ class Limits:
477
+ """Hard caps for untrusted input; ``0`` keeps the loader's default."""
478
+
479
+ max_vertices: int = 0
480
+ max_indices: int = 0
481
+ max_faces: int = 0
482
+ max_face_arity: int = 0
483
+ max_materials: int = 0
484
+ max_shapes: int = 0
485
+ max_line_bytes: int = 0
486
+ max_input_bytes: int = 0
487
+
488
+ def as_kwargs(self) -> dict[str, int]:
489
+ return {f.name: getattr(self, f.name) for f in fields(self)}
490
+
491
+
492
+ @dataclass(slots=True)
493
+ class ObjChunk:
494
+ """One window of a streamed file (see :func:`iter_load`).
495
+
496
+ Attribute arrays hold only the elements defined in this window; global
497
+ element ``i`` of the file is ``vertex_offset + i`` of the window that
498
+ defined it. Face indices are global (absolute, 0-based), so they may
499
+ refer to vertices from earlier windows. ``material_ids`` and
500
+ ``group_ids`` index :attr:`material_names` / :attr:`group_names`
501
+ (``-1`` = none): the names seen up to and including this window. ``colors`` is
502
+ parallel to ``vertices`` when any vertex of this window has a color and
503
+ empty otherwise (every vertex of the window is then white).
504
+ """
505
+
506
+ vertices: Array
507
+ colors: Array
508
+ normals: Array
509
+ texcoords: Array
510
+ indices: Array
511
+ num_face_vertices: Array
512
+ material_ids: Array
513
+ group_ids: Array
514
+ vertex_offset: int
515
+ normal_offset: int
516
+ texcoord_offset: int
517
+ byte_offset: int
518
+ byte_length: int
519
+ material_names: tuple[str, ...]
520
+ group_names: tuple[str, ...]
521
+
522
+ @property
523
+ def num_faces(self) -> int:
524
+ return len(self.num_face_vertices)
525
+
526
+ def triangles(self) -> Array:
527
+ """Vertex indices as ``(F, 3)``; requires ``triangulate=True``."""
528
+ if self.num_faces and any_non_triangle(self.num_face_vertices):
529
+ raise ValueError("chunk has non-triangle faces; use triangulate=True")
530
+ if _NUMPY:
531
+ return self.indices[:, 0].reshape(-1, 3)
532
+ flat = _column(self.indices, 0)
533
+ return [tuple(flat[i : i + 3]) for i in range(0, len(flat), 3)]
534
+
535
+ def __repr__(self) -> str:
536
+ return (
537
+ f"ObjChunk(bytes={self.byte_offset}+{self.byte_length}, "
538
+ f"vertices={len(self.vertices)}, faces={self.num_faces})"
539
+ )
540
+
541
+
542
+ # ---------------------------------------------------------------------------
543
+ # Raw dict -> objects
544
+ # ---------------------------------------------------------------------------
545
+
546
+
547
+ def _texture_option(raw: dict) -> TextureOption:
548
+ return TextureOption(
549
+ type=raw["type"],
550
+ sharpness=raw["sharpness"],
551
+ brightness=raw["brightness"],
552
+ contrast=raw["contrast"],
553
+ origin_offset=_pair(raw["origin_offset"]),
554
+ scale=_pair(raw["scale"]),
555
+ turbulence=_pair(raw["turbulence"]),
556
+ texture_resolution=raw["texture_resolution"],
557
+ clamp=raw["clamp"],
558
+ blendu=raw["blendu"],
559
+ blendv=raw["blendv"],
560
+ imfchan=raw["imfchan"],
561
+ bump_multiplier=raw["bump_multiplier"],
562
+ colorspace=raw["colorspace"],
563
+ )
564
+
565
+
566
+ _MATERIAL_SCALARS = (
567
+ "shininess",
568
+ "ior",
569
+ "dissolve",
570
+ "illum",
571
+ "roughness",
572
+ "metallic",
573
+ "sheen",
574
+ "clearcoat_thickness",
575
+ "clearcoat_roughness",
576
+ "anisotropy",
577
+ "anisotropy_rotation",
578
+ )
579
+ _MATERIAL_VECTORS = (
580
+ "ambient",
581
+ "diffuse",
582
+ "specular",
583
+ "transmittance",
584
+ "emission",
585
+ )
586
+ _MATERIAL_TEXNAMES = (
587
+ "ambient_texname",
588
+ "diffuse_texname",
589
+ "specular_texname",
590
+ "specular_highlight_texname",
591
+ "bump_texname",
592
+ "displacement_texname",
593
+ "alpha_texname",
594
+ "reflection_texname",
595
+ "roughness_texname",
596
+ "metallic_texname",
597
+ "sheen_texname",
598
+ "emissive_texname",
599
+ "normal_texname",
600
+ )
601
+
602
+
603
+ def _material(raw: dict) -> Material:
604
+ values = {"name": raw["name"]}
605
+ for key in _MATERIAL_VECTORS:
606
+ values[key] = _pair(raw[key])
607
+ for key in _MATERIAL_SCALARS:
608
+ values[key] = raw[key]
609
+ for key in _MATERIAL_TEXNAMES:
610
+ values[key] = raw[key]
611
+ values["texopt"] = {
612
+ key: _texture_option(value) for key, value in raw["texopt"].items()
613
+ }
614
+ values["unknown_params"] = dict(raw["unknown_params"])
615
+ values["mtlx_lines"] = list(raw["mtlx_lines"])
616
+ return Material(**values)
617
+
618
+
619
+ def _tag(raw: dict, precision: int) -> Tag:
620
+ return Tag(
621
+ name=raw["name"],
622
+ int_values=_array(raw["int_values"], "i"),
623
+ float_values=_array(raw["float_values"], _real_format(precision)),
624
+ string_values=list(raw["string_values"]),
625
+ )
626
+
627
+
628
+ def _mesh(raw: dict, precision: int) -> Mesh:
629
+ return Mesh(
630
+ indices=_array(raw["indices"], "i", 3),
631
+ num_face_vertices=_array(raw["num_face_vertices"], "I"),
632
+ material_ids=_array(raw["material_ids"], "i"),
633
+ smoothing_group_ids=_array(raw["smoothing_group_ids"], "I"),
634
+ tags=[_tag(tag, precision) for tag in raw["tags"]],
635
+ tag_lines=list(raw["tag_lines"]),
636
+ num_indices=raw["num_indices"],
637
+ num_faces=raw["num_faces"],
638
+ )
639
+
640
+
641
+ def _shape(raw: dict, precision: int) -> Shape:
642
+ freeform = raw.get("freeform")
643
+ if freeform is not None:
644
+ components = max(int(freeform["param_vert_components"]), 1)
645
+ freeform = FreeformInfo(
646
+ param_vert_components=components,
647
+ num_param_verts=freeform["num_param_verts"] // components,
648
+ num_curves=freeform["num_curves"],
649
+ num_curves2=freeform["num_curves2"],
650
+ num_surfaces=freeform["num_surfaces"],
651
+ )
652
+ return Shape(
653
+ name=raw["name"],
654
+ mesh=_mesh(raw["mesh"], precision),
655
+ lines=Lines(
656
+ indices=_array(raw["lines"]["indices"], "i", 3),
657
+ num_line_vertices=_array(raw["lines"]["num_line_vertices"], "i"),
658
+ num_lines=raw["lines"]["num_lines"],
659
+ ),
660
+ points=Points(indices=_array(raw["points"]["indices"], "i", 3)),
661
+ freeform=freeform,
662
+ )
663
+
664
+
665
+ def _attrib(raw: dict, precision: int) -> Attrib:
666
+ skin = raw["skin_weights"]
667
+ if skin is not None:
668
+ skin = SkinWeights(
669
+ vertex_ids=_array(skin["vertex_ids"], "I"),
670
+ offsets=_array(skin["offsets"], "Q"),
671
+ joint_ids=_array(skin["joint_ids"], "i"),
672
+ weights=_array(skin["weights"], _real_format(precision)),
673
+ max_joint_id=skin["max_joint_id"],
674
+ )
675
+ return Attrib(
676
+ vertices=_array(raw["vertices"], _real_format(precision), 3),
677
+ vertex_weights=_array(raw["vertex_weights"], _real_format(precision)),
678
+ normals=_array(raw["normals"], _real_format(precision), 3),
679
+ texcoords=_array(raw["texcoords"], _real_format(precision), 2),
680
+ texcoord_ws=_array(raw["texcoord_ws"], _real_format(precision)),
681
+ colors=_array(raw["colors"], _real_format(precision), 3),
682
+ skin_weights=skin,
683
+ skel_lines=list(raw["skel_lines"]),
684
+ )
685
+
686
+
687
+ class _CoreFamily:
688
+ __slots__ = ("load_from_file", "load_from_memory", "parse_mtl", "write_obj",
689
+ "shape", "material", "merged", "stream_new", "stream_feed")
690
+
691
+ def __init__(self, suffix: str) -> None:
692
+ for name in self.__slots__:
693
+ setattr(self, name, getattr(_core, f"{name}_{suffix}"))
694
+
695
+
696
+ _CORE = {32: _CoreFamily("f"), 64: _CoreFamily("d")}
697
+
698
+
699
+ def _core_for(bits: int) -> _CoreFamily:
700
+ return _CORE[bits]
701
+
702
+
703
+ # ---------------------------------------------------------------------------
704
+ # Public entry points
705
+ # ---------------------------------------------------------------------------
706
+
707
+
708
+ def _options(triangulate, vertex_colors, vertex_color_fallback, freeform,
709
+ num_threads, limits) -> dict:
710
+ opts = {
711
+ "triangulate": bool(triangulate),
712
+ "vertex_color": bool(vertex_colors),
713
+ "vertex_color_fallback": bool(vertex_color_fallback),
714
+ "parse_freeform": bool(freeform),
715
+ "num_threads": int(num_threads),
716
+ }
717
+ if limits is not None:
718
+ if not isinstance(limits, Limits):
719
+ raise TypeError("limits must be a tinyobjloader.Limits")
720
+ opts.update(limits.as_kwargs())
721
+ return opts
722
+
723
+
724
+ # The single-threaded verified core is the default: the threaded legacy
725
+ # dispatcher is ~2.6x faster and needs ~40% of the memory on large files, but
726
+ # it drops `vw` skin weights and accepts some input the core rejects.
727
+ DEFAULT_NUM_THREADS = 0
728
+
729
+
730
+ def load(
731
+ path,
732
+ *,
733
+ precision: int | str = 32,
734
+ triangulate: bool = True,
735
+ vertex_colors: bool = True,
736
+ vertex_color_fallback: bool = True,
737
+ freeform: bool = False,
738
+ num_threads: int | None = None,
739
+ limits: Limits | None = None,
740
+ ) -> ObjScene:
741
+ """Load an `.obj` file (and the `.mtl` libraries it names) from disk.
742
+
743
+ ``num_threads``: ``None``/``0`` runs the single-threaded, formally
744
+ verified core (peak memory ~10x the file size). ``-1`` (all cores) or
745
+ ``N`` uses the threaded dispatcher: ~2.6x faster at ~4x the file size,
746
+ but it ignores ``vw`` skin weights and is less strict about malformed
747
+ input. For files that do not fit in memory use :func:`iter_load`.
748
+ """
749
+ bits = _precision_tag(precision)
750
+ if num_threads is None:
751
+ num_threads = DEFAULT_NUM_THREADS
752
+ opts = _options(triangulate, vertex_colors, vertex_color_fallback, freeform,
753
+ num_threads, limits)
754
+ raw = _core_for(bits).load_from_file(_os.fspath(path), **opts)
755
+ return ObjScene(raw, bits)
756
+
757
+
758
+ def loads(
759
+ data,
760
+ *,
761
+ mtl=None,
762
+ precision: int | str = 32,
763
+ triangulate: bool = True,
764
+ vertex_colors: bool = True,
765
+ vertex_color_fallback: bool = True,
766
+ freeform: bool = False,
767
+ num_threads: int | None = None,
768
+ limits: Limits | None = None,
769
+ ) -> ObjScene:
770
+ """Load `.obj` contents from text or any bytes-like buffer (no copy).
771
+
772
+ ``mtl`` may be a single `.mtl` blob (bytes or text) or a mapping/sequence
773
+ of ``name -> contents``; names are matched against the ``mtllib`` line.
774
+ """
775
+ bits = _precision_tag(precision)
776
+ if isinstance(data, str):
777
+ data = data.encode()
778
+ if num_threads is None:
779
+ num_threads = DEFAULT_NUM_THREADS
780
+ opts = _options(triangulate, vertex_colors, vertex_color_fallback, freeform,
781
+ num_threads, limits)
782
+ raw = _core_for(bits).load_from_memory(data, mtl=_normalize_mtl(mtl), **opts)
783
+ return ObjScene(raw, bits)
784
+
785
+
786
+ def _open_binary(source) -> tuple[BinaryIO, bool]:
787
+ if hasattr(source, "read"):
788
+ return source, False
789
+ return open(source, "rb", buffering=0), True
790
+
791
+
792
+ def _last_eol(buf: bytearray, start: int, end: int) -> int:
793
+ return max(buf.rfind(b"\n", start, end), buf.rfind(b"\r", start, end))
794
+
795
+
796
+ def iter_load(
797
+ source,
798
+ *,
799
+ chunk_bytes: int = 64 << 20,
800
+ precision: int | str = 32,
801
+ triangulate: bool = True,
802
+ vertex_colors: bool = True,
803
+ ) -> Iterator[ObjChunk]:
804
+ """Stream an `.obj` file window by window with bounded memory.
805
+
806
+ ``source`` is a path or a binary file object (e.g. ``gzip.open(...)``).
807
+ Each :class:`ObjChunk` covers about ``chunk_bytes`` of input. Handles
808
+ ``v``/``vn``/``vt``/``f``/``g``/``o``/``usemtl``; other records are
809
+ skipped. Polygons are fan-triangulated when ``triangulate`` is set.
810
+ """
811
+ if chunk_bytes < 1:
812
+ raise ValueError("chunk_bytes must be positive")
813
+ bits = _precision_tag(precision)
814
+ core = _core_for(bits)
815
+ real = _real_format(bits)
816
+ state = core.stream_new(triangulate=bool(triangulate), vertex_color=bool(vertex_colors))
817
+ material_names: list[str] = []
818
+ group_names: list[str] = []
819
+ handle, owned = _open_binary(source)
820
+
821
+ def emit(window, offset: int) -> ObjChunk:
822
+ raw = core.stream_feed(state, window)
823
+ material_names.extend(raw["new_material_names"])
824
+ group_names.extend(raw["new_group_names"])
825
+ return ObjChunk(
826
+ vertices=_array(raw["vertices"], real, 3),
827
+ colors=_array(raw["colors"], real, 3),
828
+ normals=_array(raw["normals"], real, 3),
829
+ texcoords=_array(raw["texcoords"], real, 2),
830
+ indices=_array(raw["indices"], "i", 3),
831
+ num_face_vertices=_array(raw["num_face_vertices"], "I"),
832
+ material_ids=_array(raw["material_ids"], "i"),
833
+ group_ids=_array(raw["group_ids"], "i"),
834
+ vertex_offset=raw["vertex_offset"],
835
+ normal_offset=raw["normal_offset"],
836
+ texcoord_offset=raw["texcoord_offset"],
837
+ byte_offset=offset,
838
+ byte_length=len(window),
839
+ material_names=tuple(material_names),
840
+ group_names=tuple(group_names),
841
+ )
842
+
843
+ try:
844
+ pending = bytearray()
845
+ offset = 0
846
+ while True:
847
+ block = handle.read(chunk_bytes)
848
+ if not isinstance(block, (bytes, bytearray, memoryview)):
849
+ raise TypeError(
850
+ "iter_load needs a binary file object (open the file with 'rb')"
851
+ )
852
+ if not block:
853
+ if pending:
854
+ yield emit(bytes(pending), offset)
855
+ return
856
+ # Cut after the last line terminator. Only the new block (plus a
857
+ # held-back CR) can hold one, so long lines are not quadratic.
858
+ start = max(len(pending) - 1, 0)
859
+ pending += block
860
+ cut = _last_eol(pending, start, len(pending))
861
+ # A trailing CR may be the first half of a CRLF split across reads:
862
+ # keep it for the next window and cut at the terminator before it.
863
+ if cut == len(pending) - 1 and pending[cut] == 0x0D:
864
+ cut = _last_eol(pending, 0, cut)
865
+ if cut < 0:
866
+ continue
867
+ window = bytes(pending[: cut + 1])
868
+ del pending[: cut + 1]
869
+ yield emit(window, offset)
870
+ offset += len(window)
871
+ finally:
872
+ if owned:
873
+ handle.close()
874
+
875
+
876
+ def parse_mtl(data, *, precision: int | str = 32) -> list[Material]:
877
+ """Parse `.mtl` contents (or a file path) into materials.
878
+
879
+ ``data`` may be text, a bytes-like buffer, or a path-like object.
880
+ """
881
+ bits = _precision_tag(precision)
882
+ if isinstance(data, str):
883
+ data = data.encode()
884
+ elif isinstance(data, _os.PathLike):
885
+ with open(data, "rb") as handle:
886
+ data = handle.read()
887
+ return [_material(raw) for raw in _core_for(bits).parse_mtl(data)]
888
+
889
+
890
+ def write_obj(scene: ObjScene, path=None) -> bytes | None:
891
+ """Write a loaded scene as canonical Wavefront `.obj` text.
892
+
893
+ Returns the bytes, or writes them to ``path`` and returns ``None``.
894
+ """
895
+ text = _core_for(scene.precision).write_obj(scene._require())
896
+ if path is None:
897
+ return text
898
+ with open(path, "wb") as handle:
899
+ handle.write(text)
900
+ return None
901
+
902
+
903
+ def _deprecated(old: str, new: str) -> None:
904
+ _warnings.warn(
905
+ f"tinyobjloader.{old} is deprecated; use tinyobjloader.{new}",
906
+ DeprecationWarning,
907
+ stacklevel=3,
908
+ )
909
+
910
+
911
+ def load_obj(path, **kwargs) -> ObjScene:
912
+ """Deprecated alias of :func:`load`."""
913
+ _deprecated("load_obj", "load")
914
+ return load(path, **_legacy_kwargs(kwargs))
915
+
916
+
917
+ def load_obj_from_memory(data, **kwargs) -> ObjScene:
918
+ """Deprecated alias of :func:`loads`."""
919
+ _deprecated("load_obj_from_memory", "loads")
920
+ return loads(data, **_legacy_kwargs(kwargs))
921
+
922
+
923
+ _LEGACY_NAMES = {"vertex_color": "vertex_colors", "parse_freeform": "freeform"}
924
+
925
+
926
+ def _legacy_kwargs(kwargs: dict) -> dict:
927
+ out = {}
928
+ caps = {}
929
+ limit_names = {f.name for f in fields(Limits)}
930
+ for key, value in kwargs.items():
931
+ if key in limit_names:
932
+ caps[key] = value
933
+ else:
934
+ out[_LEGACY_NAMES.get(key, key)] = value
935
+ if caps:
936
+ out["limits"] = Limits(**caps)
937
+ return out