Coverage for trimesh/exchange/gltf/__init__.py: 92%

805 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-22 02:08 +0000

1""" 

2gltf/__init__.py 

3------------ 

4 

5Provides GLTF 2.0 exports of trimesh.Trimesh objects 

6as GL_TRIANGLES, and trimesh.Path2D/Path3D as GL_LINES 

7""" 

8 

9import base64 

10import json 

11from collections import OrderedDict, defaultdict, deque 

12from copy import deepcopy 

13 

14import numpy as np 

15 

16from ... import rendering, resources, transformations, util, visual 

17from ...caching import hash_fast 

18from ...constants import log, tol 

19from ...iteration import IndexedDict 

20from ...resolvers import ResolverLike, ZipResolver 

21from ...scene.cameras import Camera 

22from ...scene.transforms import DEFAULT_BASE_FRAME 

23from ...typed import NDArray, Stream 

24from ...util import triangle_strips_to_faces, unique_name 

25from .extensions import handle_extensions, unregistered 

26 

27# magic numbers which have meaning in GLTF 

28# most are uint32's of UTF-8 text 

29_magic = {"gltf": 1179937895, "json": 1313821514, "bin": 5130562} 

30 

31# GLTF data type codes: little endian numpy dtypes 

32_dtypes = {5120: "<i1", 5121: "<u1", 5122: "<i2", 5123: "<u2", 5125: "<u4", 5126: "<f4"} 

33# a string we can use to look up numpy dtype : GLTF dtype 

34_dtypes_lookup = {v[1:]: k for k, v in _dtypes.items()} 

35 

36 

37# GLTF data formats: numpy shapes 

38_shapes = { 

39 "SCALAR": 1, 

40 "VEC2": (2), 

41 "VEC3": (3), 

42 "VEC4": (4), 

43 "MAT2": (2, 2), 

44 "MAT3": (3, 3), 

45 "MAT4": (4, 4), 

46} 

47 

48# a default PBR metallic material 

49_default_material = { 

50 "pbrMetallicRoughness": { 

51 "baseColorFactor": [1, 1, 1, 1], 

52 "metallicFactor": 0, 

53 "roughnessFactor": 0, 

54 } 

55} 

56 

57# GL geometry modes 

58_GL_LINES = 1 

59_GL_POINTS = 0 

60_GL_TRIANGLES = 4 

61_GL_STRIP = 5 

62 

63_EYE = np.eye(4) 

64_EYE.flags.writeable = False 

65 

66# schema validators are slow to build so cache them once built 

67_GLTF_VALIDATOR = {} 

68 

69# specify dtypes with forced little endian 

70float32 = np.dtype("<f4") 

71uint32 = np.dtype("<u4") 

72uint8 = np.dtype("<u1") 

73 

74 

75def export_gltf( 

76 scene, 

77 include_normals=None, 

78 merge_buffers=False, 

79 unitize_normals=True, 

80 tree_postprocessor=None, 

81 embed_buffers=False, 

82 extension_webp=False, 

83 extension_draco=False, 

84): 

85 """ 

86 Export a scene object as a GLTF directory. 

87 

88 This puts each mesh into a separate file (i.e. a `buffer`) 

89 as opposed to one larger file. 

90 

91 Parameters 

92 ----------- 

93 scene : trimesh.Scene 

94 Scene to be exported 

95 include_normals : None or bool 

96 Include vertex normals 

97 merge_buffers : bool 

98 Merge buffers into one blob. 

99 unitize_normals 

100 GLTF requires unit normals, however sometimes people 

101 want to include non-unit normals for shading reasons. 

102 resolver : trimesh.resolvers.Resolver 

103 If passed will use to write each file. 

104 tree_postprocessor : None or callable 

105 Run this on the header tree before exiting. 

106 embed_buffers : bool 

107 Embed the buffer into JSON file as a base64 string in the URI 

108 extension_webp : bool 

109 Export textures as webP (using glTF's EXT_texture_webp extension). 

110 extension_draco : bool 

111 Compress mesh data using Draco (KHR_draco_mesh_compression). 

112 Requires the `DracoPy` package to be installed. 

113 

114 Returns 

115 ---------- 

116 export : dict 

117 Format: {file name : file data} 

118 """ 

119 # if we were passed a bare Trimesh or Path3D object 

120 if not util.is_instance_named(scene, "Scene") and hasattr(scene, "scene"): 

121 scene = scene.scene() 

122 

123 # create the header and buffer data 

124 tree, buffer_items = _create_gltf_structure( 

125 scene=scene, 

126 unitize_normals=unitize_normals, 

127 include_normals=include_normals, 

128 extension_webp=extension_webp, 

129 extension_draco=extension_draco, 

130 ) 

131 

132 # allow custom postprocessing 

133 if tree_postprocessor is not None: 

134 tree_postprocessor(tree) 

135 

136 # store files as {name : data} 

137 files = {} 

138 

139 base64_buffer_format = "data:application/octet-stream;base64,{}" 

140 if merge_buffers: 

141 views = _build_views(buffer_items) 

142 buffer_data = b"".join(buffer_items.values()) 

143 if embed_buffers: 

144 buffer_name = base64_buffer_format.format( 

145 base64.b64encode(buffer_data).decode() 

146 ) 

147 else: 

148 buffer_name = "gltf_buffer.bin" 

149 files[buffer_name] = buffer_data 

150 buffers = [{"uri": buffer_name, "byteLength": len(buffer_data)}] 

151 else: 

152 # make one buffer per buffer_items 

153 buffers = [None] * len(buffer_items) 

154 # A bufferView is a slice of a file 

155 views = [None] * len(buffer_items) 

156 # create the buffer views 

157 for i, item in enumerate(buffer_items.values()): 

158 views[i] = {"buffer": i, "byteOffset": 0, "byteLength": len(item)} 

159 if embed_buffers: 

160 buffer_name = base64_buffer_format.format(base64.b64encode(item).decode()) 

161 else: 

162 buffer_name = f"gltf_buffer_{i}.bin" 

163 files[buffer_name] = item 

164 buffers[i] = {"uri": buffer_name, "byteLength": len(item)} 

165 

166 if len(buffers) > 0: 

167 tree["buffers"] = buffers 

168 tree["bufferViews"] = views 

169 # dump tree with compact separators 

170 files["model.gltf"] = util.jsonify(tree, separators=(",", ":")).encode("utf-8") 

171 

172 if tol.strict: 

173 validate(tree) 

174 

175 return files 

176 

177 

178def export_glb( 

179 scene, 

180 include_normals=None, 

181 unitize_normals=True, 

182 tree_postprocessor=None, 

183 buffer_postprocessor=None, 

184 extension_webp=False, 

185 extension_draco=False, 

186): 

187 """ 

188 Export a scene as a binary GLTF (GLB) file. 

189 

190 Parameters 

191 ------------ 

192 scene: trimesh.Scene 

193 Input geometry 

194 extras : JSON serializable 

195 Will be stored in the extras field. 

196 include_normals : bool 

197 Include vertex normals in output file? 

198 tree_postprocessor : func 

199 Custom function to (in-place) post-process the tree 

200 before exporting. 

201 extension_webp : bool 

202 Export textures as webP using EXT_texture_webp extension. 

203 extension_draco : bool 

204 Compress mesh data using Draco (KHR_draco_mesh_compression). 

205 Requires the `DracoPy` package to be installed. 

206 

207 Returns 

208 ---------- 

209 exported : bytes 

210 Exported result in GLB 2.0 

211 """ 

212 # if we were passed a bare Trimesh or Path3D object 

213 if not util.is_instance_named(scene, "Scene") and hasattr(scene, "scene"): 

214 # generate a scene with just that mesh in it 

215 scene = scene.scene() 

216 

217 tree, buffer_items = _create_gltf_structure( 

218 scene=scene, 

219 unitize_normals=unitize_normals, 

220 include_normals=include_normals, 

221 buffer_postprocessor=buffer_postprocessor, 

222 extension_webp=extension_webp, 

223 extension_draco=extension_draco, 

224 ) 

225 

226 # A bufferView is a slice of a file 

227 views = _build_views(buffer_items) 

228 

229 # combine bytes into a single blob 

230 buffer_data = b"".join(buffer_items.values()) 

231 

232 # add the information about the buffer data 

233 if len(buffer_data) > 0: 

234 tree["buffers"] = [{"byteLength": len(buffer_data)}] 

235 tree["bufferViews"] = views 

236 

237 # allow custom postprocessing 

238 if tree_postprocessor is not None: 

239 tree_postprocessor(tree) 

240 

241 # export the tree to JSON for the header 

242 content = util.jsonify(tree, separators=(",", ":")) 

243 # add spaces to content, so the start of the data 

244 # is 4 byte aligned as per spec 

245 content += (4 - ((len(content) + 20) % 4)) * " " 

246 content = content.encode("utf-8") 

247 # make sure we didn't screw it up 

248 assert (len(content) % 4) == 0 

249 

250 # the initial header of the file 

251 header = _byte_pad( 

252 np.array( 

253 [ 

254 _magic["gltf"], # magic, turns into glTF 

255 2, # GLTF version 

256 # length is the total length of the Binary glTF 

257 # including Header and all Chunks, in bytes. 

258 len(content) + len(buffer_data) + 28, 

259 # contentLength is the length, in bytes, 

260 # of the glTF content (JSON) 

261 len(content), 

262 # magic number which is 'JSON' 

263 _magic["json"], 

264 ], 

265 dtype="<u4", 

266 ).tobytes() 

267 ) 

268 

269 # the header of the binary data section 

270 bin_header = _byte_pad( 

271 np.array([len(buffer_data), 0x004E4942], dtype="<u4").tobytes() 

272 ) 

273 

274 exported = b"".join([header, content, bin_header, buffer_data]) 

275 

276 if tol.strict: 

277 validate(tree) 

278 

279 return exported 

280 

281 

282def load_gltf( 

283 file_obj: Stream | None = None, 

284 resolver: ResolverLike | None = None, 

285 ignore_broken: bool = False, 

286 merge_primitives: bool = False, 

287 skip_materials: bool = False, 

288 **mesh_kwargs, 

289): 

290 """ 

291 Load a GLTF file, which consists of a directory structure 

292 with multiple files. 

293 

294 Parameters 

295 ------------- 

296 file_obj : None or file-like 

297 Object containing header JSON, or None 

298 resolver : trimesh.visual.Resolver 

299 Object which can be used to load other files by name 

300 ignore_broken : bool 

301 If there is a mesh we can't load and this 

302 is True don't raise an exception but return 

303 a partial result 

304 merge_primitives : bool 

305 If True, each GLTF 'mesh' will correspond 

306 to a single Trimesh object 

307 skip_materials : bool 

308 If true, will not load materials (if present). 

309 **mesh_kwargs : dict 

310 Passed to mesh constructor 

311 

312 Returns 

313 -------------- 

314 kwargs : dict 

315 Arguments to create scene 

316 """ 

317 try: 

318 # see if we've been passed the GLTF header file 

319 tree = json.loads(util.decode_text(file_obj.read())) 

320 except BaseException: 

321 # otherwise header should be in 'model.gltf' 

322 data = resolver["model.gltf"] 

323 # old versions of python/json need strings 

324 tree = json.loads(util.decode_text(data)) 

325 

326 # gltf 1.0 is a totally different format 

327 # that wasn't widely deployed before they fixed it 

328 version = tree.get("asset", {}).get("version", "2.0") 

329 if isinstance(version, str): 

330 # parse semver like '1.0.1' into just a major integer 

331 major = int(version.split(".", 1)[0]) 

332 else: 

333 major = int(float(version)) 

334 

335 if major < 2: 

336 raise NotImplementedError(f"only GLTF 2 is supported not `{version}`") 

337 

338 # use the URI and resolver to get data from file names 

339 buffers = [ 

340 _uri_to_bytes(uri=b["uri"], resolver=resolver) for b in tree.get("buffers", []) 

341 ] 

342 

343 # turn the layout header and data into kwargs 

344 # that can be used to instantiate a trimesh.Scene object 

345 kwargs = _read_buffers( 

346 header=tree, 

347 buffers=buffers, 

348 ignore_broken=ignore_broken, 

349 merge_primitives=merge_primitives, 

350 mesh_kwargs=mesh_kwargs, 

351 skip_materials=skip_materials, 

352 resolver=resolver, 

353 ) 

354 return kwargs 

355 

356 

357def load_glb( 

358 file_obj: Stream, 

359 resolver: ResolverLike | None = None, 

360 ignore_broken: bool = False, 

361 merge_primitives: bool = False, 

362 skip_materials: bool = False, 

363 **mesh_kwargs, 

364): 

365 """ 

366 Load a GLTF file in the binary GLB format into a trimesh.Scene. 

367 

368 Implemented from specification: 

369 https://github.com/KhronosGroup/glTF/tree/master/specification/2.0 

370 

371 Parameters 

372 ------------ 

373 file_obj : file- like object 

374 Containing GLB data 

375 resolver : trimesh.visual.Resolver 

376 Object which can be used to load other files by name 

377 ignore_broken : bool 

378 If there is a mesh we can't load and this 

379 is True don't raise an exception but return 

380 a partial result 

381 merge_primitives : bool 

382 If True, each GLTF 'mesh' will correspond to a 

383 single Trimesh object. 

384 skip_materials : bool 

385 If true, will not load materials (if present). 

386 

387 Returns 

388 ------------ 

389 kwargs : dict 

390 Kwargs to instantiate a trimesh.Scene 

391 """ 

392 # read the first 20 bytes which contain section lengths 

393 head_data = file_obj.read(20) 

394 head = np.frombuffer(head_data, dtype="<u4") 

395 

396 # check to make sure first index is gltf magic header 

397 if head[0] != _magic["gltf"]: 

398 raise ValueError("incorrect header on GLB file") 

399 

400 # and second value is version: should be 2 for GLTF 2.0 

401 if head[1] != 2: 

402 raise NotImplementedError(f"only GLTF 2 is supported not `{head[1]}`") 

403 

404 # overall file length 

405 # first chunk length 

406 # first chunk type 

407 length, chunk_length, chunk_type = head[2:] 

408 

409 # first chunk should be JSON header 

410 if chunk_type != _magic["json"]: 

411 raise ValueError("no initial JSON header!") 

412 

413 # uint32 causes an error in read, so we convert to native int 

414 # for the length passed to read, for the JSON header 

415 json_data = file_obj.read(int(chunk_length)) 

416 # convert to text 

417 if hasattr(json_data, "decode"): 

418 json_data = util.decode_text(json_data) 

419 # load the json header to native dict 

420 header = json.loads(json_data) 

421 

422 # read the binary data referred to by GLTF as 'buffers' 

423 buffers = [] 

424 start = file_obj.tell() 

425 

426 # header can contain base64 encoded data in the URI field 

427 info = header.get("buffers", []).copy() 

428 

429 while (file_obj.tell() - start) < length: 

430 # if we have buffer infos with URI check it here 

431 try: 

432 # if they have interleaved URI data with GLB data handle it here 

433 uri = info.pop(0)["uri"] 

434 buffers.append(_uri_to_bytes(uri=uri, resolver=resolver)) 

435 continue 

436 except (IndexError, KeyError): 

437 # if there was no buffer info or URI we still need to read 

438 pass 

439 

440 # the last read put us past the JSON chunk 

441 # we now read the chunk header, which is 8 bytes 

442 chunk_head = file_obj.read(8) 

443 if len(chunk_head) != 8: 

444 # double check to make sure we didn't 

445 # read the whole file 

446 break 

447 chunk_length, chunk_type = np.frombuffer(chunk_head, dtype="<u4") 

448 # read the chunk 

449 chunk_data = file_obj.read(int(chunk_length)) 

450 if len(chunk_data) != chunk_length: 

451 raise ValueError("chunk was not expected length!") 

452 # the GLTF spec requires ignoring chunks with unknown types 

453 if chunk_type == _magic["bin"]: 

454 buffers.append(chunk_data) 

455 

456 # turn the layout header and data into kwargs 

457 # that can be used to instantiate a trimesh.Scene object 

458 kwargs = _read_buffers( 

459 header=header, 

460 buffers=buffers, 

461 ignore_broken=ignore_broken, 

462 merge_primitives=merge_primitives, 

463 skip_materials=skip_materials, 

464 mesh_kwargs=mesh_kwargs, 

465 resolver=resolver, 

466 ) 

467 

468 return kwargs 

469 

470 

471def _uri_to_bytes(uri: str, resolver: ResolverLike | None) -> bytes: 

472 """ 

473 Take a URI string and load it as a 

474 a filename or as base64. 

475 

476 Parameters 

477 -------------- 

478 uri 

479 Usually a filename or something like: 

480 "data:object/stuff,base64,AABA112A..." 

481 resolver 

482 A resolver to load referenced assets 

483 

484 Returns 

485 --------------- 

486 data 

487 Loaded data from URI 

488 """ 

489 # see if the URI has base64 data 

490 index = uri.find("base64,") 

491 if index < 0: 

492 # string didn't contain the base64 header 

493 # so return the result from the resolver 

494 return resolver[uri] 

495 # strip the base64 header and decode: note that the decoded result is 

496 # 3/4 the length of the payload which is already in-memory 

497 return base64.b64decode(uri[index + 7 :]) 

498 

499 

500def _buffer_append(ordered: IndexedDict, data: bytes) -> int: 

501 """ 

502 Append data to an existing IndexedDict and 

503 pad it to a 4-byte boundary. 

504 

505 Parameters 

506 ---------- 

507 ordered : IndexedDict 

508 Keyed like { hash : data } 

509 data : bytes 

510 To be stored 

511 

512 Returns 

513 ---------- 

514 index : int 

515 Index of buffer_items stored in 

516 """ 

517 # hash the data to see if we have it already 

518 hashed = hash_fast(data) 

519 if hashed in ordered: 

520 return ordered.index(hashed) 

521 # not in buffer items so append and then return index 

522 ordered[hashed] = _byte_pad(data) 

523 

524 return len(ordered) - 1 

525 

526 

527def _data_append( 

528 acc: IndexedDict, 

529 buff: IndexedDict, 

530 blob: dict, 

531 data: NDArray, 

532 claimed: dict[int, NDArray] | None = None, 

533): 

534 """ 

535 Append a new accessor to an IndexedDict. 

536 

537 Parameters 

538 ------------ 

539 acc 

540 Collection of accessors, will be mutated in-place 

541 buff 

542 Collection of buffer bytes, will be mutated in-place 

543 blob 

544 Candidate accessor 

545 data 

546 Data to fill in details to blob 

547 claimed 

548 If passed store `data` here keyed by the returned accessor index and 

549 don't write it into `buff`, for an extension which stores it itself. 

550 

551 Returns 

552 ---------- 

553 index : int 

554 Index of accessor that was added or reused. 

555 """ 

556 # if we have data include that in the key 

557 as_bytes = data.tobytes() 

558 if hasattr(data, "hash_fast"): 

559 # passed a TrackedArray object 

560 hashed = data.hash_fast() 

561 else: 

562 # someone passed a vanilla numpy array 

563 hashed = hash_fast(as_bytes) 

564 

565 if claimed is not None: 

566 # an extension stores this itself: `byteOffset` is only valid alongside a 

567 # `bufferView` and an accessor with neither can't collide with a stored copy 

568 blob.pop("byteOffset", None) 

569 elif hashed in buff: 

570 blob["bufferView"] = buff.index(hashed) 

571 else: 

572 # not in buffer items so append and then return index 

573 buff[hashed] = _byte_pad(as_bytes) 

574 blob["bufferView"] = len(buff) - 1 

575 

576 # start by hashing the dict blob 

577 # note that this will not work if a value is a list 

578 try: 

579 # simple keys can be hashed as tuples without JSON 

580 key = hash(tuple(blob.items())) 

581 except BaseException: 

582 # if there are list keys that break the simple hash 

583 key = hash(json.dumps(blob, sort_keys=True)) 

584 

585 # xor the hash for the blob to the key 

586 key ^= hashed 

587 

588 # a claim records here too as this is another primitive's accessor 

589 if key in acc: 

590 index = acc.index(key) 

591 if claimed is not None: 

592 claimed[index] = data 

593 return index 

594 

595 # get a numpy dtype for our components 

596 dtype = np.dtype(_dtypes[blob["componentType"]]) 

597 # see if we're an array, matrix, etc 

598 kind = blob["type"] 

599 

600 if tol.strict: 

601 # in unit tests make sure everything we're trying to export 

602 # is finite, which also checks for accidental NaN values 

603 assert np.isfinite(data).all() 

604 

605 if kind == "SCALAR": 

606 # is probably (n, 1) 

607 blob["count"] = int(np.prod(data.shape)) 

608 blob["max"] = np.array([data.max()], dtype=dtype).tolist() 

609 blob["min"] = np.array([data.min()], dtype=dtype).tolist() 

610 elif kind.startswith("MAT"): 

611 # i.e. (n, 4, 4) matrices 

612 blob["count"] = len(data) 

613 else: 

614 # reshape the data into what we're actually exporting 

615 resh = data.reshape((-1, _shapes[kind])) 

616 blob["count"] = len(resh) 

617 blob["max"] = resh.max(axis=0).astype(dtype).tolist() 

618 blob["min"] = resh.min(axis=0).astype(dtype).tolist() 

619 

620 # store the accessor and return the index 

621 acc[key] = blob 

622 index = len(acc) - 1 

623 if claimed is not None: 

624 claimed[index] = data 

625 return index 

626 

627 

628def _jsonify(blob): 

629 """ 

630 Roundtrip a blob through json export-import cycle 

631 skipping any internal keys. 

632 """ 

633 return json.loads( 

634 util.jsonify({k: v for k, v in blob.items() if not k.startswith("_")}) 

635 ) 

636 

637 

638def _create_gltf_structure( 

639 scene, 

640 include_normals=None, 

641 include_metadata=True, 

642 unitize_normals=None, 

643 buffer_postprocessor=None, 

644 extension_webp=False, 

645 extension_draco=False, 

646): 

647 """ 

648 Generate a GLTF header. 

649 

650 Parameters 

651 ------------- 

652 scene : trimesh.Scene 

653 Input scene data 

654 include_metadata : bool 

655 Include `scene.metadata` as `scenes/{idx}/extras/metadata` 

656 include_normals : bool 

657 Include vertex normals in output file? 

658 unitize_normals : bool 

659 Unitize all exported normals so as to pass GLTF validation 

660 extension_webp : bool 

661 Export textures as webP using EXT_texture_webp extension. 

662 extension_draco : bool 

663 Compress mesh data using Draco (KHR_draco_mesh_compression). 

664 

665 Returns 

666 --------------- 

667 tree : dict 

668 Contains required keys for a GLTF scene 

669 buffer_items : list 

670 Contains bytes of data 

671 """ 

672 if extension_draco: 

673 # fail once here rather than warning per mesh and writing an uncompressed file 

674 import DracoPy # noqa: F401 

675 

676 # we are defining a single scene, and will be setting the 

677 # world node to the 0-index 

678 tree = { 

679 "scene": 0, 

680 # the root node indices are filled in from the scene graph 

681 "scenes": [{}], 

682 "asset": {"version": "2.0", "generator": "https://github.com/mikedh/trimesh"}, 

683 "accessors": IndexedDict(), 

684 "meshes": [], 

685 "images": [], 

686 "textures": [], 

687 "materials": [], 

688 } 

689 

690 if scene.has_camera: 

691 tree["cameras"] = [_convert_camera(scene.camera)] 

692 

693 if include_metadata and len(scene.metadata) > 0: 

694 try: 

695 # fail here if data isn't json compatible 

696 # only export the extras if there is something there 

697 tree["scenes"][0]["extras"] = _jsonify(scene.metadata) 

698 extensions = tree["scenes"][0]["extras"].pop("gltf_extensions", None) 

699 if isinstance(extensions, dict): 

700 tree["extensions"] = extensions 

701 except BaseException: 

702 log.debug("failed to export scene metadata!", exc_info=True) 

703 

704 # store materials as {hash : index} to avoid duplicates 

705 mat_hashes = {} 

706 # store data from geometries 

707 buffer_items = IndexedDict() 

708 

709 # map the name of each mesh to the index in tree['meshes'] 

710 mesh_index = {} 

711 previous = len(tree["meshes"]) 

712 

713 # loop through every geometry 

714 for name, geometry in scene.geometry.items(): 

715 if util.is_instance_named(geometry, "Trimesh"): 

716 # add the mesh 

717 _append_mesh( 

718 mesh=geometry, 

719 name=name, 

720 tree=tree, 

721 buffer_items=buffer_items, 

722 include_normals=include_normals, 

723 unitize_normals=unitize_normals, 

724 mat_hashes=mat_hashes, 

725 extension_webp=extension_webp, 

726 extension_draco=extension_draco, 

727 ) 

728 elif util.is_instance_named(geometry, "Path"): 

729 # add Path2D and Path3D objects 

730 _append_path(path=geometry, name=name, tree=tree, buffer_items=buffer_items) 

731 elif util.is_instance_named(geometry, "PointCloud"): 

732 # add PointCloud objects 

733 _append_point( 

734 points=geometry, name=name, tree=tree, buffer_items=buffer_items 

735 ) 

736 

737 # only store the index if the append did anything 

738 if len(tree["meshes"]) != previous: 

739 previous = len(tree["meshes"]) 

740 mesh_index[name] = previous - 1 

741 

742 # grab the flattened scene graph in GLTF's format 

743 nodes = scene.graph.to_gltf(scene=scene, mesh_index=mesh_index) 

744 # set the roots on the existing scene dict — it may already 

745 # hold `extras` with the scene metadata 

746 tree["scenes"][0]["nodes"] = nodes.pop("scene_roots") 

747 tree.update(nodes) 

748 

749 extensions_used = set() 

750 extensions_required = set() 

751 # Add any scene extensions used 

752 if "extensions" in tree: 

753 extensions_used = extensions_used.union(set(tree["extensions"].keys())) 

754 # Add any mesh extensions used 

755 for mesh in tree["meshes"]: 

756 if "extensions" in mesh: 

757 extensions_used = extensions_used.union(set(mesh["extensions"].keys())) 

758 # Check primitives for extensions too 

759 for prim in mesh.get("primitives", []): 

760 if "extensions" in prim: 

761 extensions_used = extensions_used.union(set(prim["extensions"].keys())) 

762 # Add any extensions already in the tree (e.g. node extensions) 

763 if "extensionsUsed" in tree: 

764 extensions_used = extensions_used.union(set(tree["extensionsUsed"])) 

765 # Add WebP if used 

766 if extension_webp: 

767 extensions_used.add("EXT_texture_webp") 

768 extensions_required.add("EXT_texture_webp") 

769 # draco has no fallback so it is required, but only if a primitive really got 

770 # compressed: a file requiring an extension nothing uses is refused by loaders 

771 if "KHR_draco_mesh_compression" in extensions_used: 

772 extensions_required.add("KHR_draco_mesh_compression") 

773 if len(extensions_used) > 0: 

774 tree["extensionsUsed"] = list(extensions_used) 

775 if len(extensions_required) > 0: 

776 tree["extensionsRequired"] = list(extensions_required) 

777 

778 if buffer_postprocessor is not None: 

779 buffer_postprocessor(buffer_items, tree) 

780 

781 # convert accessors back to a flat list 

782 tree["accessors"] = list(tree["accessors"].values()) 

783 

784 # cull empty or unpopulated fields 

785 # check keys that might be empty so we can remove them 

786 check = ["textures", "materials", "images", "accessors", "meshes"] 

787 # remove the keys with nothing stored in them 

788 [tree.pop(key) for key in check if len(tree[key]) == 0] 

789 

790 return tree, buffer_items 

791 

792 

793def _append_mesh( 

794 mesh, 

795 name, 

796 tree, 

797 buffer_items, 

798 include_normals: bool | None, 

799 unitize_normals: bool, 

800 mat_hashes: dict, 

801 extension_webp: bool, 

802 extension_draco: bool = False, 

803): 

804 """ 

805 Append a mesh to the scene structure and put the 

806 data into buffer_items. 

807 

808 Parameters 

809 ------------- 

810 mesh : trimesh.Trimesh 

811 Source geometry 

812 name : str 

813 Name of geometry 

814 tree : dict 

815 Will be updated with data from mesh 

816 buffer_items 

817 Will have buffer appended with mesh data 

818 include_normals : bool 

819 Include vertex normals in export or not 

820 unitize_normals : bool 

821 Transform normals into unit vectors. 

822 May be undesirable but will fail validators without this. 

823 

824 mat_hashes : dict 

825 Which materials have already been added 

826 extension_webp : bool 

827 Export textures as webP (using glTF's EXT_texture_webp extension). 

828 extension_draco : bool 

829 Compress mesh data using Draco (KHR_draco_mesh_compression). 

830 """ 

831 # return early from empty meshes to avoid crashing later 

832 if len(mesh.faces) == 0 or len(mesh.vertices) == 0: 

833 log.debug("skipping empty mesh!") 

834 return 

835 

836 # draco absorbs geometry into a buffer of its own, so collect the arrays as 

837 # they are appended for the handler below rather than storing each one twice 

838 claimed = {} if extension_draco else None 

839 

840 # convert mesh data to the correct dtypes 

841 # faces: 5125 is an unsigned 32 bit integer 

842 # accessors refer to data locations 

843 # mesh faces are stored as flat list of integers 

844 acc_face = _data_append( 

845 acc=tree["accessors"], 

846 buff=buffer_items, 

847 blob={"componentType": 5125, "type": "SCALAR"}, 

848 data=mesh.faces.astype(uint32), 

849 claimed=claimed, 

850 ) 

851 

852 # vertices: 5126 is a float32 

853 # create or reuse an accessor for these vertices 

854 acc_vertex = _data_append( 

855 acc=tree["accessors"], 

856 buff=buffer_items, 

857 blob={"componentType": 5126, "type": "VEC3", "byteOffset": 0}, 

858 data=mesh.vertices.astype(float32), 

859 claimed=claimed, 

860 ) 

861 

862 # meshes reference accessor indexes 

863 current = { 

864 "name": name, 

865 "extras": {}, 

866 "primitives": [ 

867 { 

868 "attributes": {"POSITION": acc_vertex}, 

869 "indices": acc_face, 

870 "mode": _GL_TRIANGLES, 

871 } 

872 ], 

873 } 

874 # if units are defined, store them as an extra 

875 # the GLTF spec says everything is implicit meters 

876 # we're not doing that as our unit conversions are expensive 

877 # although that might be better, implicit works for 3DXML 

878 # https://github.com/KhronosGroup/glTF/tree/master/extensions 

879 try: 

880 # skip jsonify any metadata, skipping internal keys 

881 current["extras"] = _jsonify(mesh.metadata) 

882 

883 # extract extensions if any 

884 extensions = current["extras"].pop("gltf_extensions", None) 

885 if isinstance(extensions, dict): 

886 current["extensions"] = extensions 

887 

888 if mesh.units not in [None, "m", "meters", "meter"]: 

889 current["extras"]["units"] = str(mesh.units) 

890 except BaseException: 

891 log.debug("metadata not serializable, dropping!", exc_info=True) 

892 

893 # check to see if we have vertex or face colors 

894 # or if a TextureVisual has colors included as an attribute 

895 if mesh.visual.kind in ["vertex", "face"]: 

896 vertex_colors = mesh.visual.vertex_colors 

897 elif ( 

898 hasattr(mesh.visual, "vertex_attributes") 

899 and "color" in mesh.visual.vertex_attributes 

900 ): 

901 vertex_colors = mesh.visual.vertex_attributes["color"] 

902 else: 

903 vertex_colors = None 

904 

905 if vertex_colors is not None: 

906 if len(vertex_colors) == len(mesh.vertices): 

907 # convert color data to bytes and append 

908 acc_color = _data_append( 

909 acc=tree["accessors"], 

910 buff=buffer_items, 

911 blob={ 

912 "componentType": 5121, 

913 "normalized": True, 

914 "type": "VEC4", 

915 "byteOffset": 0, 

916 }, 

917 data=vertex_colors.astype(uint8), 

918 claimed=claimed, 

919 ) 

920 

921 # add the reference for vertex color 

922 current["primitives"][0]["attributes"]["COLOR_0"] = acc_color 

923 else: 

924 log.warning( 

925 "Vertex colors have different length than mesh vertices, dropping!" 

926 ) 

927 

928 if hasattr(mesh.visual, "material"): 

929 # append the material and then set from returned index 

930 current_material = _append_material( 

931 mat=mesh.visual.material, 

932 tree=tree, 

933 buffer_items=buffer_items, 

934 mat_hashes=mat_hashes, 

935 extension_webp=extension_webp, 

936 ) 

937 

938 # if mesh has UV coordinates defined export them 

939 has_uv = ( 

940 hasattr(mesh.visual, "uv") 

941 and mesh.visual.uv is not None 

942 and len(mesh.visual.uv) == len(mesh.vertices) 

943 ) 

944 if has_uv: 

945 # slice off W if passed 

946 uv = mesh.visual.uv.copy()[:, :2] 

947 # reverse the Y for GLTF 

948 uv[:, 1] = 1.0 - uv[:, 1] 

949 # add an accessor describing the blob of UV's 

950 acc_uv = _data_append( 

951 acc=tree["accessors"], 

952 buff=buffer_items, 

953 blob={"componentType": 5126, "type": "VEC2", "byteOffset": 0}, 

954 data=uv.astype(float32), 

955 claimed=claimed, 

956 ) 

957 # add the reference for UV coordinates 

958 current["primitives"][0]["attributes"]["TEXCOORD_0"] = acc_uv 

959 

960 # reference the material 

961 current["primitives"][0]["material"] = current_material 

962 

963 if include_normals or ( 

964 include_normals is None and "vertex_normals" in mesh._cache.cache 

965 ): 

966 # store vertex normals if requested 

967 if unitize_normals: 

968 normals = util.unitize(mesh.vertex_normals) 

969 else: 

970 # we don't have to copy them since 

971 # they aren't being altered 

972 normals = mesh.vertex_normals 

973 

974 acc_norm = _data_append( 

975 acc=tree["accessors"], 

976 buff=buffer_items, 

977 blob={ 

978 "componentType": 5126, 

979 "count": len(mesh.vertices), 

980 "type": "VEC3", 

981 "byteOffset": 0, 

982 }, 

983 data=normals.astype(float32), 

984 claimed=claimed, 

985 ) 

986 # add the reference for vertex color 

987 current["primitives"][0]["attributes"]["NORMAL"] = acc_norm 

988 

989 # for each attribute with a leading underscore, assign them to trimesh 

990 # vertex_attributes 

991 for key, attrib in mesh.vertex_attributes.items(): 

992 # make sure vertex attribute length matches vertices 

993 if len(attrib) != len(mesh.vertices): 

994 log.warning( 

995 f"Vertex attribute `{key}` has different length than mesh vertices skipping!" 

996 ) 

997 continue 

998 

999 # application specific attributes must be prefixed with an underscore 

1000 if not key.startswith("_"): 

1001 key = "_" + key 

1002 

1003 # cast anything GLTF has no component type for to float32 

1004 if attrib.dtype.str[1:] not in _dtypes_lookup: 

1005 data = attrib.astype(float32) 

1006 else: 

1007 # force little-endian to match GLTF binary format 

1008 data = attrib.astype(attrib.dtype.newbyteorder("<"), copy=False) 

1009 

1010 if len(data.shape) == 1: 

1011 data = data[:, np.newaxis] 

1012 

1013 # every accessor VALUE must be 4-byte aligned 

1014 row_mod = (data.shape[1] * data.dtype.itemsize) % 4 

1015 # if the row size is not a multiple of 4, pad it 

1016 if row_mod != 0: 

1017 # how many columns of padding for this value 

1018 pad_columns = (4 - row_mod) // data.dtype.itemsize 

1019 # pad this custom attribute with zeros -_- 

1020 data = np.pad(data, ((0, 0), (0, pad_columns)), mode="constant") 

1021 

1022 # store custom vertex attributes 

1023 current["primitives"][0]["attributes"][key] = _data_append( 

1024 acc=tree["accessors"], 

1025 buff=buffer_items, 

1026 blob=_build_accessor(data), 

1027 data=data, 

1028 ) 

1029 

1030 # Handle Draco compression via extension handler 

1031 if extension_draco: 

1032 # Call primitive_export handlers 

1033 compressed = handle_extensions( 

1034 extensions={"KHR_draco_mesh_compression": {}}, 

1035 scope="primitive_export", 

1036 mesh=mesh, 

1037 name=name, 

1038 tree=tree, 

1039 buffer_items=buffer_items, 

1040 primitive=current["primitives"][0], 

1041 arrays=claimed, 

1042 ) 

1043 if not compressed: 

1044 # nothing claimed the arrays so store them after all, keyed by accessor 

1045 # not content: two of these landing on one view would need a `byteStride` 

1046 blobs = list(tree["accessors"].values()) 

1047 for index, data in claimed.items(): 

1048 key = ("accessor", index) 

1049 buffer_items[key] = _byte_pad(data.tobytes()) 

1050 blobs[index]["bufferView"] = buffer_items.index(key) 

1051 blobs[index]["byteOffset"] = 0 

1052 

1053 tree["meshes"].append(current) 

1054 

1055 

1056def _build_views(buffer_items): 

1057 """ 

1058 Create views for buffers that are simply 

1059 based on how many bytes they are long. 

1060 

1061 Parameters 

1062 -------------- 

1063 buffer_items : IndexedDict 

1064 Buffers to build views for 

1065 

1066 Returns 

1067 ---------- 

1068 views : (n,) list of dict 

1069 GLTF views 

1070 """ 

1071 views = [] 

1072 # create the buffer views 

1073 current_pos = 0 

1074 for current_item in buffer_items.values(): 

1075 views.append( 

1076 {"buffer": 0, "byteOffset": current_pos, "byteLength": len(current_item)} 

1077 ) 

1078 assert (current_pos % 4) == 0 

1079 assert (len(current_item) % 4) == 0 

1080 current_pos += len(current_item) 

1081 return views 

1082 

1083 

1084def _build_accessor(array): 

1085 """ 

1086 Build an accessor for an arbitrary array. 

1087 

1088 Parameters 

1089 ----------- 

1090 array : numpy array 

1091 The array to build an accessor for 

1092 

1093 Returns 

1094 ---------- 

1095 accessor : dict 

1096 The accessor for array. 

1097 """ 

1098 shape = array.shape 

1099 data_type = "SCALAR" 

1100 if len(shape) == 2: 

1101 vec_length = shape[1] 

1102 if vec_length > 4: 

1103 raise ValueError("The GLTF spec does not support vectors larger than 4") 

1104 if vec_length > 1: 

1105 data_type = f"VEC{int(vec_length)}" 

1106 else: 

1107 data_type = "SCALAR" 

1108 

1109 if len(shape) == 3: 

1110 if shape[2] not in [2, 3, 4]: 

1111 raise ValueError("Matrix types must have 4, 9 or 16 components") 

1112 data_type = f"MAT{int(shape[2])}" 

1113 

1114 # get the array data type as a str stripping off endian 

1115 lookup = array.dtype.str.lstrip("<>|") 

1116 

1117 if lookup == "u4": 

1118 # spec: UNSIGNED_INT is only allowed when the accessor 

1119 # contains indices i.e. the accessor is only referenced 

1120 # by `primitive.indices` 

1121 log.debug("custom uint32 may cause validation failures") 

1122 

1123 # map the numpy dtype to a GLTF code (i.e. 5121) 

1124 componentType = _dtypes_lookup[lookup] 

1125 accessor = {"componentType": componentType, "type": data_type, "byteOffset": 0} 

1126 

1127 if len(shape) < 3: 

1128 accessor["max"] = array.max(axis=0).tolist() 

1129 accessor["min"] = array.min(axis=0).tolist() 

1130 

1131 return accessor 

1132 

1133 

1134def _byte_pad(data, bound=4): 

1135 """ 

1136 GLTF wants chunks aligned with 4 byte boundaries. 

1137 This function will add padding to the end of a 

1138 chunk of bytes so that it aligns with the passed 

1139 boundary size. 

1140 

1141 Parameters 

1142 -------------- 

1143 data : bytes 

1144 Data to be padded 

1145 bound : int 

1146 Length of desired boundary 

1147 

1148 Returns 

1149 -------------- 

1150 padded : bytes 

1151 Result where: (len(padded) % bound) == 0 

1152 """ 

1153 assert isinstance(data, bytes) 

1154 if len(data) % bound != 0: 

1155 # extra bytes to pad with 

1156 count = bound - (len(data) % bound) 

1157 pad = bytes(count) 

1158 # combine the padding and data 

1159 result = b"".join([data, pad]) 

1160 # we should always divide evenly 

1161 if tol.strict and (len(result) % bound) != 0: 

1162 raise ValueError("byte_pad failed!") 

1163 return result 

1164 return data 

1165 

1166 

1167def _append_path(path, name, tree, buffer_items): 

1168 """ 

1169 Append a 2D or 3D path to the scene structure and put the 

1170 data into buffer_items. 

1171 

1172 Parameters 

1173 ------------- 

1174 path : trimesh.Path2D or trimesh.Path3D 

1175 Source geometry 

1176 name : str 

1177 Name of geometry 

1178 tree : dict 

1179 Will be updated with data from path 

1180 buffer_items 

1181 Will have buffer appended with path data 

1182 """ 

1183 

1184 # convert the path to the unnamed args for 

1185 # a pyglet vertex list 

1186 vxlist = rendering.path_to_vertexlist(path) 

1187 

1188 # of the count of things to export is zero exit early 

1189 if vxlist[0] == 0: 

1190 return 

1191 

1192 # TODO add color support to Path object 

1193 # this is just exporting everying as black 

1194 try: 

1195 material_idx = tree["materials"].index(_default_material) 

1196 except ValueError: 

1197 material_idx = len(tree["materials"]) 

1198 tree["materials"].append(_default_material) 

1199 

1200 # data is the second value of the fifth field 

1201 # which is a (data type, data) tuple 

1202 acc_vertex = _data_append( 

1203 acc=tree["accessors"], 

1204 buff=buffer_items, 

1205 blob={"componentType": 5126, "type": "VEC3", "byteOffset": 0}, 

1206 data=vxlist[4][1].astype(float32), 

1207 ) 

1208 

1209 current = { 

1210 "name": name, 

1211 "primitives": [ 

1212 { 

1213 "attributes": {"POSITION": acc_vertex}, 

1214 "mode": _GL_LINES, # i.e. 1 

1215 "material": material_idx, 

1216 } 

1217 ], 

1218 } 

1219 

1220 # if units are defined, store them as an extra: 

1221 # https://github.com/KhronosGroup/glTF/tree/master/extensions 

1222 try: 

1223 current["extras"] = _jsonify(path.metadata) 

1224 except BaseException: 

1225 log.debug("failed to serialize metadata, dropping!", exc_info=True) 

1226 

1227 if path.colors is not None: 

1228 acc_color = _data_append( 

1229 acc=tree["accessors"], 

1230 buff=buffer_items, 

1231 blob={ 

1232 "componentType": 5121, 

1233 "normalized": True, 

1234 "type": "VEC4", 

1235 "byteOffset": 0, 

1236 }, 

1237 data=np.array(vxlist[5][1]).astype(uint8), 

1238 ) 

1239 # add color to attributes 

1240 current["primitives"][0]["attributes"]["COLOR_0"] = acc_color 

1241 

1242 # for each attribute with a leading underscore, assign them to path 

1243 # vertex_attributes 

1244 for key, attrib in path.vertex_attributes.items(): 

1245 # Application specific attributes must be 

1246 # prefixed with an underscore 

1247 if not key.startswith("_"): 

1248 key = "_" + key 

1249 

1250 # cast anything GLTF has no component type for to float32 

1251 if attrib.dtype.str[1:] not in _dtypes_lookup: 

1252 data = attrib.astype(float32) 

1253 else: 

1254 # force little-endian to match GLTF binary format 

1255 data = attrib.astype(attrib.dtype.newbyteorder("<"), copy=False) 

1256 

1257 if not all(util.is_instance_named(e, "Line") for e in path.entities): 

1258 log.warning( 

1259 f"Vertex attributes are only supported for Line entities, skipping `{key}`" 

1260 ) 

1261 continue 

1262 

1263 data_discretized = np.array( 

1264 [util.stack_lines(e.discrete(data)) for e in path.entities] 

1265 ) 

1266 stacked_data = data_discretized.reshape((-1,)) 

1267 

1268 # store custom vertex attributes 

1269 current["primitives"][0]["attributes"][key] = _data_append( 

1270 acc=tree["accessors"], 

1271 buff=buffer_items, 

1272 blob=_build_accessor(stacked_data), 

1273 data=stacked_data, 

1274 ) 

1275 

1276 tree["meshes"].append(current) 

1277 

1278 

1279def _append_point(points, name, tree, buffer_items): 

1280 """ 

1281 Append a 2D or 3D pointCloud to the scene structure and 

1282 put the data into buffer_items. 

1283 

1284 Parameters 

1285 ------------- 

1286 points : trimesh.PointCloud 

1287 Source geometry 

1288 name : str 

1289 Name of geometry 

1290 tree : dict 

1291 Will be updated with data from points 

1292 buffer_items 

1293 Will have buffer appended with points data 

1294 """ 

1295 

1296 # convert the points to the unnamed args for 

1297 # a pyglet vertex list 

1298 vxlist = rendering.points_to_vertexlist(points=points.vertices, colors=points.colors) 

1299 

1300 # data is the second value of the fifth field 

1301 # which is a (data type, data) tuple 

1302 acc_vertex = _data_append( 

1303 acc=tree["accessors"], 

1304 buff=buffer_items, 

1305 blob={"componentType": 5126, "type": "VEC3", "byteOffset": 0}, 

1306 data=vxlist[4][1].astype(float32), 

1307 ) 

1308 current = { 

1309 "name": name, 

1310 "primitives": [ 

1311 { 

1312 "attributes": {"POSITION": acc_vertex}, 

1313 "mode": _GL_POINTS, 

1314 "material": len(tree["materials"]), 

1315 } 

1316 ], 

1317 } 

1318 

1319 # TODO add color support to Points object 

1320 # this is just exporting everying as black 

1321 tree["materials"].append(_default_material) 

1322 

1323 if len(np.shape(points.colors)) == 2: 

1324 # colors may be returned as "c3f" or other RGBA 

1325 color_type, color_data = vxlist[5] 

1326 if "3" in color_type: 

1327 kind = "VEC3" 

1328 elif "4" in color_type: 

1329 kind = "VEC4" 

1330 else: 

1331 raise ValueError("unknown color: %s", color_type) 

1332 acc_color = _data_append( 

1333 acc=tree["accessors"], 

1334 buff=buffer_items, 

1335 blob={ 

1336 "componentType": 5121, 

1337 "count": vxlist[0], 

1338 "normalized": True, 

1339 "type": kind, 

1340 "byteOffset": 0, 

1341 }, 

1342 data=np.array(color_data).astype(uint8), 

1343 ) 

1344 # add color to attributes 

1345 current["primitives"][0]["attributes"]["COLOR_0"] = acc_color 

1346 tree["meshes"].append(current) 

1347 

1348 

1349def _parse_textures(header, views, resolver=None): 

1350 try: 

1351 import PIL.Image 

1352 except ImportError: 

1353 log.debug("unable to load textures without pillow!") 

1354 return None 

1355 

1356 # load any images 

1357 images = None 

1358 if "images" in header: 

1359 # images are referenced by index 

1360 images = [None] * len(header["images"]) 

1361 # loop through images 

1362 for i, img in enumerate(header["images"]): 

1363 if img.get("mimeType", "") == "image/ktx2": 

1364 log.debug("`image/ktx2` textures are unsupported, skipping!") 

1365 continue 

1366 # get the bytes representing an image 

1367 if "bufferView" in img: 

1368 blob = views[img["bufferView"]] 

1369 elif "uri" in img: 

1370 try: 

1371 # will get bytes from filesystem or base64 URI 

1372 blob = _uri_to_bytes(uri=img["uri"], resolver=resolver) 

1373 except BaseException: 

1374 log.debug(f"unable to load image from: {img.keys()}", exc_info=True) 

1375 continue 

1376 else: 

1377 log.debug(f"unable to load image from: {img.keys()}") 

1378 continue 

1379 # i.e. 'image/jpeg' 

1380 # mime = img['mimeType'] 

1381 try: 

1382 # load the buffer into a PIL image 

1383 images[i] = PIL.Image.open(util.wrap_as_stream(blob)) 

1384 except BaseException: 

1385 log.debug("failed to load image!", exc_info=True) 

1386 return images 

1387 

1388 

1389def _parse_materials(header, views, resolver=None): 

1390 """ 

1391 Convert materials and images stored in a GLTF header 

1392 and buffer views to PBRMaterial objects. 

1393 

1394 Parameters 

1395 ------------ 

1396 header : dict 

1397 Contains layout of file 

1398 views : (n,) bytes 

1399 Raw data 

1400 

1401 Returns 

1402 ------------ 

1403 materials : list 

1404 List of trimesh.visual.texture.Material objects 

1405 """ 

1406 

1407 def parse_textures(*, data): 

1408 result = {} 

1409 for k, v in data.items(): 

1410 if isinstance(v, (list, tuple)): 

1411 # colors are always float 0.0 - 1.0 in GLTF 

1412 result[k] = np.array(v, dtype=np.float64) 

1413 elif not isinstance(v, dict): 

1414 result[k] = v 

1415 elif images is not None and "index" in v: 

1416 try: 

1417 index = None 

1418 texture = header["textures"][v["index"]] 

1419 # Handle texture extensions through registry 

1420 if tex_ext := texture.get("extensions"): 

1421 index = handle_extensions( 

1422 extensions=tex_ext, scope="texture_source" 

1423 ) 

1424 

1425 if index is None: 

1426 # fall back to standard source key 

1427 index = texture.get("source") 

1428 if index is not None: 

1429 result[k] = images[index] 

1430 except BaseException: 

1431 log.debug("unable to store texture", exc_info=True) 

1432 return result 

1433 

1434 images = _parse_textures(header, views, resolver) 

1435 

1436 # store materials which reference images 

1437 materials = [] 

1438 if "materials" in header: 

1439 for mat in header["materials"]: 

1440 # flatten key structure so we can loop it 

1441 loopable = mat.copy() 

1442 # this key stores another dict of crap 

1443 if "pbrMetallicRoughness" in loopable: 

1444 # add keys of keys to top level dict 

1445 loopable.update(loopable.pop("pbrMetallicRoughness")) 

1446 

1447 # Handle material extensions through registry 

1448 if mat_extensions := mat.get("extensions"): 

1449 ext_results = handle_extensions( 

1450 extensions=mat_extensions, 

1451 scope="material", 

1452 parse_textures=parse_textures, 

1453 images=images, 

1454 ) 

1455 # Flatten extension results into the material parameters 

1456 for ext_result in ext_results.values(): 

1457 if isinstance(ext_result, dict): 

1458 loopable.update(ext_result) 

1459 

1460 # save flattened keys we can use for kwargs 

1461 pbr = parse_textures(data=loopable) 

1462 # create a PBR material object for the GLTF material 

1463 materials.append(visual.material.PBRMaterial(**pbr)) 

1464 

1465 return materials 

1466 

1467 

1468def _read_buffers( 

1469 header: dict, 

1470 buffers: list[bytes], 

1471 mesh_kwargs: dict, 

1472 resolver: ResolverLike | None, 

1473 ignore_broken: bool = False, 

1474 merge_primitives: bool = False, 

1475 skip_materials: bool = False, 

1476): 

1477 """ 

1478 Given binary data and a layout return the 

1479 kwargs to create a scene object. 

1480 

1481 Parameters 

1482 ----------- 

1483 header : dict 

1484 With GLTF keys 

1485 buffers : list of bytes 

1486 Stored data 

1487 mesh_kwargs : dict 

1488 To be passed to the mesh constructor. 

1489 ignore_broken : bool 

1490 If there is a mesh we can't load and this 

1491 is True don't raise an exception but return 

1492 a partial result 

1493 merge_primitives : bool 

1494 If true, combine primitives into a single mesh. 

1495 skip_materials : bool 

1496 If true, will not load materials (if present). 

1497 resolver : trimesh.resolvers.Resolver 

1498 Resolver to load referenced assets 

1499 

1500 Returns 

1501 ----------- 

1502 kwargs : dict 

1503 Can be passed to load_kwargs for a trimesh.Scene 

1504 """ 

1505 

1506 if "bufferViews" in header: 

1507 # split buffer data into buffer views 

1508 views = [None] * len(header["bufferViews"]) 

1509 for i, view in enumerate(header["bufferViews"]): 

1510 if "byteOffset" in view: 

1511 start = view["byteOffset"] 

1512 else: 

1513 start = 0 

1514 end = start + view["byteLength"] 

1515 views[i] = buffers[view["buffer"]][start:end] 

1516 assert len(views[i]) == view["byteLength"] 

1517 # load data from buffers into numpy arrays 

1518 # using the layout described by accessors 

1519 access = [None] * len(header["accessors"]) 

1520 # bufferless, non-sparse accessors must be filled by an extension or stay zero 

1521 placeholders = set() 

1522 for index, a in enumerate(header["accessors"]): 

1523 # number of items 

1524 count = a["count"] 

1525 # what is the datatype 

1526 dtype = np.dtype(_dtypes[a["componentType"]]) 

1527 # basically how many columns 

1528 # for types like (4, 4) 

1529 per_item = _shapes[a["type"]] 

1530 # use reported count to generate shape 

1531 shape = np.append(count, per_item) 

1532 # number of items when flattened 

1533 # i.e. a (4, 4) MAT4 has 16 

1534 per_count = np.abs(np.prod(per_item)) 

1535 if "bufferView" in a: 

1536 # data was stored in a buffer view so get raw bytes 

1537 

1538 # load the bytes data into correct dtype and shape 

1539 buffer_view = header["bufferViews"][a["bufferView"]] 

1540 

1541 # is the accessor offset in a buffer 

1542 # will include the start, length, and offset 

1543 # but not the bytestride as that is easier to do 

1544 # in numpy rather than in python looping 

1545 data = views[a["bufferView"]] 

1546 

1547 # both bufferView *and* accessors are allowed 

1548 # to have a byteOffset 

1549 start = a.get("byteOffset", 0) 

1550 

1551 if "byteStride" in buffer_view: 

1552 # how many bytes for each chunk 

1553 stride = buffer_view["byteStride"] 

1554 # we want to get the bytes for every row 

1555 per_row = per_count * dtype.itemsize 

1556 # the total block we're looking at 

1557 length = (count - 1) * stride + per_row 

1558 # apply as_strided for fast construction of strided array 

1559 # and copy to ensure contiguous layout 

1560 assert stride > 0, "byteStride should be positive" 

1561 assert 0 <= start <= start + length <= len(data) 

1562 access[index] = np.array( 

1563 np.lib.stride_tricks.as_strided( 

1564 np.frombuffer( 

1565 data, dtype=np.uint8, offset=start, count=length 

1566 ), 

1567 [count, per_row], 

1568 [stride, 1], 

1569 ) 

1570 .view(dtype) 

1571 .reshape(shape) 

1572 ) 

1573 else: 

1574 # length is the number of bytes per item times total 

1575 length = dtype.itemsize * count * per_count 

1576 access[index] = np.frombuffer( 

1577 data[start : start + length], dtype=dtype 

1578 ).reshape(shape) 

1579 else: 

1580 # zero placeholder a decoder may replace 

1581 if "sparse" not in a: 

1582 placeholders.add(index) 

1583 access[index] = np.zeros(count * per_count, dtype=dtype).reshape(shape) 

1584 

1585 # possibly load images and textures into material objects 

1586 if skip_materials: 

1587 materials = [] 

1588 else: 

1589 materials = _parse_materials(header, views=views, resolver=resolver) 

1590 

1591 mesh_prim = defaultdict(list) 

1592 # load data from accessors into Trimesh objects 

1593 meshes = OrderedDict() 

1594 

1595 # keep track of how many times each name has been attempted to 

1596 # be inserted to avoid a potentially slow search through our 

1597 # dict of names 

1598 name_counts = {} 

1599 # extensions whose geometry we couldn't decode for lack of a handler 

1600 undecoded = set() 

1601 for index, m in enumerate(header.get("meshes", [])): 

1602 try: 

1603 # GLTF spec indicates implicit units are meters 

1604 metadata = { 

1605 "units": "meters", 

1606 "from_gltf_primitive": len(m["primitives"]) > 1, 

1607 } 

1608 

1609 # try to load all mesh metadata 

1610 if isinstance(m.get("extras"), dict): 

1611 metadata.update(m["extras"]) 

1612 

1613 # put any mesh extensions in a field of the metadata 

1614 if "extensions" in m: 

1615 metadata["gltf_extensions"] = m["extensions"] 

1616 

1617 for p in m["primitives"]: 

1618 # preprocessing extensions like draco decompression run 

1619 # before reading accessors as they may modify them 

1620 if prim_extensions := p.get("extensions"): 

1621 # a handler which raised can't have decoded anything 

1622 failed = set() 

1623 handle_extensions( 

1624 extensions=prim_extensions, 

1625 scope="primitive_preprocess", 

1626 failed=failed, 

1627 primitive=p, 

1628 accessors=access, 

1629 views=views, 

1630 ) 

1631 # warn later if an extension left placeholder zeros, whether 

1632 # it had no handler or its handler failed 

1633 if not placeholders.isdisjoint(p.get("attributes", {}).values()): 

1634 undecoded.update(failed) 

1635 undecoded.update( 

1636 unregistered(prim_extensions, "primitive_preprocess") 

1637 ) 

1638 

1639 # if we don't have a triangular mesh continue 

1640 # if not specified assume it is a mesh 

1641 kwargs = deepcopy(mesh_kwargs) 

1642 if kwargs.get("metadata", None) is None: 

1643 kwargs["metadata"] = {} 

1644 if "process" not in kwargs: 

1645 kwargs["process"] = False 

1646 kwargs["metadata"].update(metadata) 

1647 # i.e. GL_LINES, GL_TRIANGLES, etc 

1648 # specification says the default mode is GL_TRIANGLES 

1649 mode = p.get("mode", _GL_TRIANGLES) 

1650 # colors, normals, etc 

1651 attr = p["attributes"] 

1652 # create a unique mesh name per- primitive 

1653 name = m.get("name", "GLTF") 

1654 # make name unique across multiple meshes 

1655 name = unique_name(name, meshes, counts=name_counts) 

1656 

1657 if mode == _GL_LINES: 

1658 # load GL_LINES into a Path object 

1659 from ...path.entities import Line 

1660 

1661 kwargs["vertices"] = access[attr["POSITION"]] 

1662 kwargs["entities"] = [Line(points=np.arange(len(kwargs["vertices"])))] 

1663 

1664 # custom attributes starting with a `_` 

1665 custom = { 

1666 a: access[attr[a]] for a in attr.keys() if a.startswith("_") 

1667 } 

1668 if len(custom) > 0: 

1669 kwargs["vertex_attributes"] = custom 

1670 elif mode == _GL_POINTS: 

1671 kwargs["vertices"] = access[attr["POSITION"]] 

1672 visuals = None 

1673 if "COLOR_0" in attr: 

1674 try: 

1675 # try to load vertex colors from the accessors 

1676 colors = access[attr["COLOR_0"]] 

1677 if len(colors) == len(kwargs["vertices"]): 

1678 if visuals is None: 

1679 # just pass to mesh as vertex color 

1680 kwargs["vertex_colors"] = colors.copy() 

1681 else: 

1682 # we ALSO have texture so save as vertex 

1683 # attribute 

1684 visuals.vertex_attributes["color"] = colors.copy() 

1685 except BaseException: 

1686 # survive failed colors 

1687 log.debug("failed to load colors", exc_info=True) 

1688 if visuals is not None: 

1689 kwargs["visual"] = visuals 

1690 elif mode in (_GL_TRIANGLES, _GL_STRIP): 

1691 # get vertices from accessors 

1692 kwargs["vertices"] = access[attr["POSITION"]] 

1693 # get faces from accessors 

1694 if "indices" in p: 

1695 if mode == _GL_STRIP: 

1696 # this is triangle strips 

1697 flat = access[p["indices"]].reshape(-1) 

1698 kwargs["faces"] = triangle_strips_to_faces([flat]) 

1699 else: 

1700 kwargs["faces"] = access[p["indices"]].reshape((-1, 3)) 

1701 else: 

1702 # indices are apparently optional and we are supposed to 

1703 # do the same thing as webGL drawArrays? 

1704 if mode == _GL_STRIP: 

1705 kwargs["faces"] = triangle_strips_to_faces( 

1706 np.array([np.arange(len(kwargs["vertices"]))]) 

1707 ) 

1708 else: 

1709 # GL_TRIANGLES 

1710 kwargs["faces"] = np.arange( 

1711 len(kwargs["vertices"]), dtype=np.int64 

1712 ).reshape((-1, 3)) 

1713 

1714 if "NORMAL" in attr: 

1715 # vertex normals are specified 

1716 kwargs["vertex_normals"] = access[attr["NORMAL"]] 

1717 # do we have UV coordinates 

1718 visuals = None 

1719 if "material" in p and not skip_materials: 

1720 if materials is None: 

1721 log.debug("no materials! `pip install pillow`") 

1722 else: 

1723 uv = None 

1724 if "TEXCOORD_0" in attr: 

1725 # flip UV's top- bottom to move origin to lower-left: 

1726 # https://github.com/KhronosGroup/glTF/issues/1021 

1727 uv = access[attr["TEXCOORD_0"]].copy() 

1728 uv[:, 1] = 1.0 - uv[:, 1] 

1729 # create a texture visual 

1730 visuals = visual.texture.TextureVisuals( 

1731 uv=uv, material=materials[p["material"]] 

1732 ) 

1733 

1734 if "COLOR_0" in attr: 

1735 try: 

1736 # try to load vertex colors from the accessors 

1737 colors = access[attr["COLOR_0"]] 

1738 if len(colors) == len(kwargs["vertices"]): 

1739 if visuals is None: 

1740 # just pass to mesh as vertex color 

1741 kwargs["vertex_colors"] = colors.copy() 

1742 else: 

1743 # we ALSO have texture so save as vertex 

1744 # attribute 

1745 visuals.vertex_attributes["color"] = colors.copy() 

1746 except BaseException: 

1747 # survive failed colors 

1748 log.debug("failed to load colors", exc_info=True) 

1749 if visuals is not None: 

1750 kwargs["visual"] = visuals 

1751 

1752 # custom attributes starting with a `_` 

1753 custom = { 

1754 a: access[attr[a]] for a in attr.keys() if a.startswith("_") 

1755 } 

1756 if len(custom) > 0: 

1757 kwargs["vertex_attributes"] = custom 

1758 

1759 # Process primitive-level extensions through registry 

1760 if prim_extensions := p.get("extensions"): 

1761 handle_extensions( 

1762 extensions=prim_extensions, 

1763 scope="primitive", 

1764 primitive=p, 

1765 mesh_kwargs=kwargs, 

1766 accessors=access, 

1767 ) 

1768 else: 

1769 log.debug("skipping primitive with mode %s!", mode) 

1770 continue 

1771 # this should absolutely not be stomping on itself 

1772 assert name not in meshes 

1773 meshes[name] = kwargs 

1774 mesh_prim[index].append(name) 

1775 except BaseException as E: 

1776 if ignore_broken: 

1777 log.debug("failed to load mesh", exc_info=True) 

1778 else: 

1779 raise E 

1780 

1781 if undecoded: 

1782 log.warning( 

1783 "`%s` GLTF extension didn't decode, values are placeholder zeros", 

1784 ", ".join(sorted(undecoded)), 

1785 ) 

1786 

1787 # sometimes GLTF "meshes" come with multiple "primitives" 

1788 # by default we return one Trimesh object per "primitive" 

1789 # but if merge_primitives is True we combine the primitives 

1790 # for the "mesh" into a single Trimesh object 

1791 if merge_primitives: 

1792 # if we are only returning one Trimesh object 

1793 # replace `mesh_prim` with updated values 

1794 mesh_prim_replace = {} 

1795 # these are the names of meshes we need to remove 

1796 mesh_pop = set() 

1797 for mesh_index, names in mesh_prim.items(): 

1798 if len(names) <= 1: 

1799 mesh_prim_replace[mesh_index] = names 

1800 continue 

1801 

1802 # only triangle primitives can be merged, any lines 

1803 # or points primitives are kept as separate geometry 

1804 tris = [n for n in names if "faces" in meshes[n]] 

1805 if len(tris) <= 1: 

1806 mesh_prim_replace[mesh_index] = names 

1807 continue 

1808 

1809 # just take the shortest name option available 

1810 name = min(tris) 

1811 # remove the other meshes after we're done looping 

1812 # since we're reusing the shortest one don't pop 

1813 # that as we'll be overwriting it with the combined 

1814 mesh_pop.update(set(tris).difference([name])) 

1815 

1816 # get all meshes for this group 

1817 current = [meshes[n] for n in tris] 

1818 v_seq = [p["vertices"] for p in current] 

1819 f_seq = [p["faces"] for p in current] 

1820 v, f = util.append_faces(v_seq, f_seq) 

1821 if "metadata" in meshes[tris[0]]: 

1822 metadata = meshes[tris[0]]["metadata"] 

1823 else: 

1824 metadata = {} 

1825 merged = { 

1826 "vertices": v, 

1827 "faces": f, 

1828 "metadata": metadata, 

1829 "process": False, 

1830 } 

1831 # primitives have no visual with `skip_materials` 

1832 if all("visual" in p for p in current): 

1833 materials = [p["visual"].material for p in current] 

1834 face_materials = [] 

1835 for i, p in enumerate(current): 

1836 face_materials += [i] * len(p["faces"]) 

1837 merged["visual"] = visual.texture.TextureVisuals( 

1838 material=visual.material.MultiMaterial(materials=materials), 

1839 face_materials=face_materials, 

1840 ) 

1841 meshes[name] = merged 

1842 mesh_prim_replace[mesh_index] = [name] + [n for n in names if n not in tris] 

1843 # avoid altering inside loop 

1844 mesh_prim = mesh_prim_replace 

1845 # remove outdated meshes 

1846 [meshes.pop(p, None) for p in mesh_pop] 

1847 

1848 # make it easier to reference nodes 

1849 nodes = header.get("nodes", []) 

1850 # nodes are referenced by index 

1851 # save their string names if they have one 

1852 # we have to accumulate in a for loop opposed 

1853 # to a dict comprehension as it will be checking 

1854 # the mutated dict in every loop 

1855 name_index = {} 

1856 name_counts = {} 

1857 

1858 # store the mapping of node name to index and the inverse 

1859 # name_index: {name: index} 

1860 for i, n in enumerate(nodes): 

1861 name_index[unique_name(n.get("name", str(i)), name_index, counts=name_counts)] = i 

1862 # names: {index: name} 

1863 names = {v: k for k, v in name_index.items()} 

1864 

1865 # rename any file node that collides with the synthetic base frame 

1866 # so its transform and children survive under their own frame — 

1867 # trimesh's own exports never contain one, #2421 

1868 world = name_index.get(DEFAULT_BASE_FRAME) 

1869 if world is not None: 

1870 names[world] = unique_name(DEFAULT_BASE_FRAME, set(names.values())) 

1871 

1872 # traversal edges are seeded as (DEFAULT_BASE_FRAME, index) so the 

1873 # index-keyed dict intentionally holds one string key for the base 

1874 names[DEFAULT_BASE_FRAME] = DEFAULT_BASE_FRAME 

1875 

1876 # visited, kwargs for scene.graph.update 

1877 graph = deque() 

1878 # unvisited, pairs of node indexes 

1879 queue = deque() 

1880 

1881 # camera(s), if they exist 

1882 camera = None 

1883 camera_transform = None 

1884 

1885 if "scene" in header: 

1886 # specify the index of scenes if specified 

1887 scene_index = header["scene"] 

1888 else: 

1889 # otherwise just use the first index 

1890 scene_index = 0 

1891 

1892 if "scenes" in header: 

1893 # start the traversal from the base frame to the roots 

1894 for root in header["scenes"][scene_index].get("nodes", []): 

1895 # add transform from base frame to these root nodes 

1896 queue.append((DEFAULT_BASE_FRAME, root)) 

1897 

1898 # make sure we don't process an edge multiple times 

1899 consumed = set() 

1900 

1901 # go through the nodes tree to populate 

1902 # kwargs for scene graph loader 

1903 while len(queue) > 0: 

1904 # (int, int) pair of node indexes 

1905 edge = queue.pop() 

1906 

1907 # avoid looping forever if someone specified 

1908 # recursive nodes 

1909 if edge in consumed: 

1910 continue 

1911 

1912 consumed.add(edge) 

1913 a, b = edge 

1914 

1915 # dict of child node 

1916 # parent = nodes[a] 

1917 child = nodes[b] 

1918 # add edges of children to be processed 

1919 if "children" in child: 

1920 queue.extend([(b, i) for i in child["children"]]) 

1921 

1922 # kwargs to be passed to scene.graph.update 

1923 kwargs = {"frame_from": names[a], "frame_to": names[b]} 

1924 

1925 # grab matrix from child 

1926 # parent -> child relationships have matrix stored in child 

1927 # for the transform from parent to child 

1928 if "matrix" in child: 

1929 kwargs["matrix"] = ( 

1930 np.array(child["matrix"], dtype=np.float64).reshape((4, 4)).T 

1931 ) 

1932 else: 

1933 # if no matrix set identity 

1934 kwargs["matrix"] = _EYE 

1935 

1936 # Now apply keyword translations 

1937 # GLTF applies these in order: T * R * S 

1938 if "translation" in child: 

1939 kwargs["matrix"] = np.dot( 

1940 kwargs["matrix"], transformations.translation_matrix(child["translation"]) 

1941 ) 

1942 if "rotation" in child: 

1943 # GLTF rotations are stored as (4,) XYZW unit quaternions 

1944 # we need to re- order to our quaternion style, WXYZ 

1945 quat = np.reshape(child["rotation"], 4)[[3, 0, 1, 2]] 

1946 # add the rotation to the matrix 

1947 kwargs["matrix"] = np.dot( 

1948 kwargs["matrix"], transformations.quaternion_matrix(quat) 

1949 ) 

1950 if "scale" in child: 

1951 # add scale to the matrix 

1952 kwargs["matrix"] = np.dot( 

1953 kwargs["matrix"], np.diag(np.concatenate((child["scale"], [1.0]))) 

1954 ) 

1955 

1956 # If a camera exists, create the camera and dont add the node to the graph 

1957 # TODO only process the first camera, ignore the rest 

1958 # TODO assumes the camera node is child of the world frame 

1959 # TODO will only read perspective camera 

1960 if "camera" in child and camera is None: 

1961 cam_idx = child["camera"] 

1962 try: 

1963 camera = _cam_from_gltf(header["cameras"][cam_idx]) 

1964 except KeyError: 

1965 log.debug("GLTF camera is not fully-defined") 

1966 if camera: 

1967 camera_transform = kwargs["matrix"] 

1968 continue 

1969 

1970 # treat node metadata similarly to mesh metadata 

1971 if isinstance(child.get("extras"), dict): 

1972 kwargs["metadata"] = child["extras"] 

1973 

1974 # put any node extensions in a field of the metadata 

1975 if "extensions" in child: 

1976 if "metadata" not in kwargs: 

1977 kwargs["metadata"] = {} 

1978 kwargs["metadata"]["gltf_extensions"] = child["extensions"] 

1979 

1980 if "mesh" in child: 

1981 geometries = mesh_prim[child["mesh"]] 

1982 

1983 # if the node has a mesh associated with it 

1984 if len(geometries) > 1: 

1985 # append root node 

1986 graph.append(kwargs.copy()) 

1987 # put primitives as children 

1988 for geom_name in geometries: 

1989 # save the name of the geometry 

1990 kwargs["geometry"] = geom_name 

1991 # no transformations 

1992 kwargs["matrix"] = _EYE 

1993 kwargs["frame_from"] = names[b] 

1994 # if we have more than one primitive assign a new UUID 

1995 # frame name for the primitives after the first one 

1996 frame_to = f"{names[b]}_{util.unique_id(length=6)}" 

1997 kwargs["frame_to"] = frame_to 

1998 # append the edge with the mesh frame 

1999 graph.append(kwargs.copy()) 

2000 elif len(geometries) == 1: 

2001 kwargs["geometry"] = geometries[0] 

2002 if "name" in child: 

2003 kwargs["frame_to"] = names[b] 

2004 graph.append(kwargs.copy()) 

2005 else: 

2006 # if the node doesn't have any geometry just add 

2007 graph.append(kwargs) 

2008 

2009 # kwargs for load_kwargs 

2010 result = { 

2011 "class": "Scene", 

2012 "geometry": meshes, 

2013 "graph": graph, 

2014 "base_frame": DEFAULT_BASE_FRAME, 

2015 "camera": camera, 

2016 "camera_transform": camera_transform, 

2017 "metadata": {}, 

2018 } 

2019 

2020 try: 

2021 # load any scene extras into scene.metadata 

2022 # use a try except to avoid nested key checks 

2023 result["metadata"].update(header["scenes"][header["scene"]]["extras"]) 

2024 except BaseException: 

2025 pass 

2026 try: 

2027 # load any scene extensions into a field of scene.metadata 

2028 # use a try except to avoid nested key checks 

2029 result["metadata"]["gltf_extensions"] = header["extensions"] 

2030 except BaseException: 

2031 pass 

2032 

2033 return result 

2034 

2035 

2036def _cam_from_gltf(cam): 

2037 """ 

2038 Convert a gltf perspective camera to trimesh. 

2039 

2040 The retrieved camera will have default resolution, since the gltf specification 

2041 does not contain it. 

2042 

2043 If the camera is not perspective will return None. 

2044 If the camera is perspective but is missing fields, will raise `KeyError` 

2045 

2046 Parameters 

2047 ------------ 

2048 cam : dict 

2049 Camera represented as a dictionary according to glTF 

2050 

2051 Returns 

2052 ------------- 

2053 camera : trimesh.scene.cameras.Camera 

2054 Trimesh camera object 

2055 """ 

2056 if "perspective" not in cam: 

2057 return 

2058 name = cam.get("name") 

2059 znear = cam["perspective"]["znear"] 

2060 aspect_ratio = cam["perspective"]["aspectRatio"] 

2061 yfov = np.degrees(cam["perspective"]["yfov"]) 

2062 

2063 fov = (aspect_ratio * yfov, yfov) 

2064 

2065 return Camera(name=name, fov=fov, z_near=znear) 

2066 

2067 

2068def _convert_camera(camera): 

2069 """ 

2070 Convert a trimesh camera to a GLTF camera. 

2071 

2072 Parameters 

2073 ------------ 

2074 camera : trimesh.scene.cameras.Camera 

2075 Trimesh camera object 

2076 

2077 Returns 

2078 ------------- 

2079 gltf_camera : dict 

2080 Camera represented as a GLTF dict 

2081 """ 

2082 result = { 

2083 "name": camera.name, 

2084 "type": "perspective", 

2085 "perspective": { 

2086 "aspectRatio": camera.fov[0] / camera.fov[1], 

2087 "yfov": np.radians(camera.fov[1]), 

2088 "znear": float(camera.z_near), 

2089 }, 

2090 } 

2091 return result 

2092 

2093 

2094def _append_image(img, tree, buffer_items, extension_webp): 

2095 """ 

2096 Append a PIL image to a GLTF2.0 tree. 

2097 

2098 Parameters 

2099 ------------ 

2100 img : PIL.Image 

2101 Image object 

2102 tree : dict 

2103 GLTF 2.0 format tree 

2104 buffer_items : (n,) bytes 

2105 Binary blobs containing data 

2106 extension_webp : bool 

2107 Export textures as webP (using glTF's EXT_texture_webp extension). 

2108 

2109 Returns 

2110 ----------- 

2111 index : int or None 

2112 The index of the image in the tree 

2113 None if image append failed for any reason 

2114 """ 

2115 # probably not a PIL image so exit 

2116 if not hasattr(img, "format"): 

2117 return None 

2118 

2119 if extension_webp: 

2120 # support WebP if extension is specified 

2121 save_as = "WEBP" 

2122 elif img.format == "JPEG": 

2123 # don't re-encode JPEGs 

2124 save_as = "JPEG" 

2125 else: 

2126 # for everything else just use PNG 

2127 save_as = "png" 

2128 

2129 # get the image data into a bytes object 

2130 with util.BytesIO() as f: 

2131 img.save(f, format=save_as) 

2132 f.seek(0) 

2133 data = f.read() 

2134 

2135 index = _buffer_append(buffer_items, data) 

2136 # append buffer index and the GLTF-acceptable mimetype 

2137 tree["images"].append({"bufferView": index, "mimeType": f"image/{save_as.lower()}"}) 

2138 

2139 # index is length minus one 

2140 return len(tree["images"]) - 1 

2141 

2142 

2143def _append_material(mat, tree, buffer_items, mat_hashes, extension_webp): 

2144 """ 

2145 Add passed PBRMaterial as GLTF 2.0 specification JSON 

2146 serializable data: 

2147 - images are added to `tree['images']` 

2148 - texture is added to `tree['texture']` 

2149 - material is added to `tree['materials']` 

2150 

2151 Parameters 

2152 ------------ 

2153 mat : trimesh.visual.materials.PBRMaterials 

2154 Source material to convert 

2155 tree : dict 

2156 GLTF header blob 

2157 buffer_items : (n,) bytes 

2158 Binary blobs with various data 

2159 mat_hashes : dict 

2160 Which materials have already been added 

2161 Stored as { hashed : material index } 

2162 extension_webp : bool 

2163 Export textures as webP using EXT_texture_webp extension. 

2164 

2165 Returns 

2166 ------------- 

2167 index : int 

2168 Index at which material was added 

2169 """ 

2170 # materials are hashable 

2171 hashed = hash(mat) 

2172 # check stored material indexes to see if material 

2173 # has already been added 

2174 if mat_hashes is not None and hashed in mat_hashes: 

2175 return mat_hashes[hashed] 

2176 

2177 # convert passed input to PBR if necessary 

2178 if hasattr(mat, "to_pbr"): 

2179 as_pbr = mat.to_pbr() 

2180 else: 

2181 as_pbr = mat 

2182 

2183 # a default PBR metallic material 

2184 result = {"pbrMetallicRoughness": {}} 

2185 try: 

2186 # try to convert base color to (4,) float color 

2187 result["baseColorFactor"] = ( 

2188 visual.color.to_float(as_pbr.baseColorFactor).reshape(4).tolist() 

2189 ) 

2190 except BaseException: 

2191 pass 

2192 

2193 try: 

2194 result["emissiveFactor"] = as_pbr.emissiveFactor.reshape(3).tolist() 

2195 except BaseException: 

2196 pass 

2197 

2198 # if name is defined, export 

2199 if isinstance(as_pbr.name, str): 

2200 result["name"] = as_pbr.name 

2201 

2202 # if alphaMode is defined, export 

2203 if isinstance(as_pbr.alphaMode, str): 

2204 result["alphaMode"] = as_pbr.alphaMode 

2205 

2206 # if alphaCutoff is defined, export 

2207 if isinstance(as_pbr.alphaCutoff, float): 

2208 result["alphaCutoff"] = as_pbr.alphaCutoff 

2209 

2210 # if doubleSided is defined, export 

2211 if isinstance(as_pbr.doubleSided, bool): 

2212 result["doubleSided"] = as_pbr.doubleSided 

2213 

2214 # if scalars are defined correctly export 

2215 if isinstance(as_pbr.metallicFactor, float): 

2216 result["metallicFactor"] = as_pbr.metallicFactor 

2217 if isinstance(as_pbr.roughnessFactor, float): 

2218 result["roughnessFactor"] = as_pbr.roughnessFactor 

2219 

2220 # which keys of the PBRMaterial are images 

2221 image_mapping = { 

2222 "baseColorTexture": as_pbr.baseColorTexture, 

2223 "emissiveTexture": as_pbr.emissiveTexture, 

2224 "normalTexture": as_pbr.normalTexture, 

2225 "occlusionTexture": as_pbr.occlusionTexture, 

2226 "metallicRoughnessTexture": as_pbr.metallicRoughnessTexture, 

2227 } 

2228 

2229 for key, img in image_mapping.items(): 

2230 if img is None: 

2231 continue 

2232 # try adding the base image to the export object 

2233 index = _append_image( 

2234 img=img, tree=tree, buffer_items=buffer_items, extension_webp=extension_webp 

2235 ) 

2236 # if the image was added successfully it will return index 

2237 # if it failed for any reason, it will return None 

2238 if index is not None: 

2239 # add a reference to the base color texture 

2240 result[key] = {"index": len(tree["textures"])} 

2241 

2242 # add texture object, optionally using EXT_texture_webp 

2243 if extension_webp: 

2244 tree["textures"].append( 

2245 {"extensions": {"EXT_texture_webp": {"source": index}}} 

2246 ) 

2247 else: 

2248 tree["textures"].append({"source": index}) 

2249 

2250 # for our PBRMaterial object we flatten all keys 

2251 # however GLTF would like some of them under the 

2252 # "pbrMetallicRoughness" key 

2253 pbr_subset = [ 

2254 "baseColorTexture", 

2255 "baseColorFactor", 

2256 "roughnessFactor", 

2257 "metallicFactor", 

2258 "metallicRoughnessTexture", 

2259 ] 

2260 # move keys down a level 

2261 for key in pbr_subset: 

2262 if key in result: 

2263 result["pbrMetallicRoughness"][key] = result.pop(key) 

2264 

2265 # if we didn't have any PBR keys remove the empty key 

2266 if len(result["pbrMetallicRoughness"]) == 0: 

2267 result.pop("pbrMetallicRoughness") 

2268 

2269 # which index are we inserting material at 

2270 index = len(tree["materials"]) 

2271 # add the material to the data structure 

2272 tree["materials"].append(result) 

2273 # add the material index in-place 

2274 mat_hashes[hashed] = index 

2275 

2276 return index 

2277 

2278 

2279def validate(header): 

2280 """ 

2281 Validate a GLTF 2.0 header against the schema. 

2282 

2283 Returns result from validating against `get_schema()`. 

2284 

2285 Parameters 

2286 ------------- 

2287 header : dict 

2288 Populated GLTF 2.0 header 

2289 

2290 Raises 

2291 -------------- 

2292 err : jsonschema.exceptions.ValidationError 

2293 If the tree is an invalid GLTF2.0 header 

2294 """ 

2295 try: 

2296 validator = _GLTF_VALIDATOR["glTF.schema.json"] 

2297 except KeyError: 

2298 # a soft dependency 

2299 import jsonschema 

2300 

2301 # will do the reference replacement 

2302 schema = get_schema() 

2303 # `jsonschema.validate` re-checks the schema against its meta-schema 

2304 # on every call which is most of the cost so `test_schema` does that once 

2305 validator = jsonschema.validators.validator_for(schema)(schema) 

2306 _GLTF_VALIDATOR["glTF.schema.json"] = validator 

2307 

2308 return validator.validate(header) 

2309 

2310 

2311def get_schema(): 

2312 """ 

2313 Get a copy of the GLTF 2.0 schema with references resolved. 

2314 

2315 Returns 

2316 ------------ 

2317 schema : dict 

2318 A copy of the GLTF 2.0 schema without external references. 

2319 """ 

2320 # replace references 

2321 # get zip resolver to access referenced assets 

2322 from ...schemas import resolve 

2323 

2324 # get a blob of a zip file including the GLTF 2.0 schema 

2325 stream = resources.get_stream("schema/gltf2.schema.zip") 

2326 # get the zip file as a dict keyed by file name 

2327 archive = util.decompress(stream, "zip") 

2328 # get a resolver object for accessing the schema 

2329 resolver = ZipResolver(archive) 

2330 # get a loaded dict from the base file 

2331 unresolved = json.loads(util.decode_text(resolver.get("glTF.schema.json"))) 

2332 # resolve `$ref` references to other files in the schema 

2333 schema = resolve(unresolved, resolver=resolver) 

2334 

2335 return schema 

2336 

2337 

2338# exporters 

2339_gltf_loaders = {"glb": load_glb, "gltf": load_gltf}