pygltflib is a Python library for reading, writing, and managing 3D objects in the Khronos Group glTF (GL Transmission Format) and glTF2 formats. It supports the entire GLTF v2 specification, including materials, animations, and extensions, with all attributes being type-hinted. The library is actively maintained, with frequent updates addressing features and bug fixes.
pip install pygltflibVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to create a basic, empty glTF 2.0 file with a scene and a node, and then save it to disk. Real-world applications would involve populating the glTF object with meshes, materials, accessors, and buffer data. Ensure you have write permissions in the execution directory for the `gltf.save()` operation.
Replace `AlphaMode` with constants like `pygltflib.BLEND`, `MASK`, or `OPAQUE`. Use `AccessorSparseIndices` and `AccessorSparseValues` instead of `SparseAccessor`. Replace `MaterialTexture` with `TextureInfo`.
Implement explicit file existence checks or wrap `GLTF2.load()` calls in `try-except FileNotFoundError` blocks to handle missing files gracefully.
Explicitly set `material.alphaCutoff = 0.5` (or desired value) if your materials require it, especially for `alphaMode = 'MASK'` materials.
Utilize `pygltflib.convert_buffers()` and `pygltflib.convert_images()` for explicit buffer and image data conversion (e.g., to/from external files, data URIs, or GLB binary blobs). For file-based conversions, consider `pygltflib.utils.glb2gltf` and `pygltflib.utils.gltf2glb`. Custom paths for image conversion can be specified using `GLTF.convert_images` with a `path` argument (from v1.13.10).
Install the library using pip: `pip install pygltflib`
Ensure the file path is correct and the file exists. You can add an explicit file existence check:
```python
import os
from pygltflib import GLTF2
filename = 'your_model.gltf'
if os.path.exists(filename):
gltf = GLTF2().load(filename)
else:
print(f"Error: File not found at {filename}")
```Validate the glTF file using a glTF validator (e.g., Khronos glTF Validator online) or a JSON linter to identify and correct syntax errors. Ensure proper quoting (double quotes for keys and string values) and correct structure.
Before accessing optional attributes, check if the object or attribute itself is not `None`. For example, if accessing `baseColorTexture` on `pbrMetallicRoughness`:
```python
from pygltflib import GLTF2
gltf = GLTF2().load('your_model.gltf')
material = gltf.materials # Assuming a material exists
if material.pbrMetallicRoughness and material.pbrMetallicRoughness.baseColorTexture:
# Access baseColorTexture safely
texture_info = material.pbrMetallicRoughness.baseColorTexture
# ... further processing
else:
print("Material does not have a baseColorTexture.")
```