Python library for importing Wavefront .obj files and generating interleaved vertex data ready for rendering.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Core functionality for loading Wavefront .obj files with comprehensive parsing options, encoding support, error handling, and optional binary caching for improved performance.
The primary interface for loading .obj files, with extensive configuration options for parsing behavior, encoding, and performance optimization.
class Wavefront:
def __init__(
self,
file_name: str,
strict: bool = False,
encoding: str = "utf-8",
create_materials: bool = False,
collect_faces: bool = False,
parse: bool = True,
cache: bool = False
):
"""
Load and parse a Wavefront .obj file.
Parameters:
- file_name: Path to the .obj file to load
- strict: Enable strict parsing mode (raises exceptions for unsupported features)
- encoding: Text encoding for reading files (default: utf-8)
- create_materials: Create default materials when missing or undefined
- collect_faces: Collect triangle face data for topology analysis
- parse: Parse immediately (True) or defer parsing until manual call (False)
- cache: Write parsed data to binary cache files for faster subsequent loads
Attributes after loading:
- materials: Dict[str, Material] - Materials indexed by name
- meshes: Dict[str, Mesh] - Named meshes indexed by name
- mesh_list: List[Mesh] - All meshes including anonymous ones
- vertices: List[float] - All vertex position data
- mtllibs: List[str] - Material library filenames referenced
"""
def parse(self) -> None:
"""
Manually parse the file when parse=False was used in constructor.
Must be called to populate materials, meshes, and vertex data.
"""
def add_mesh(self, mesh: Mesh) -> None:
"""
Add a mesh to the wavefront object.
Parameters:
- mesh: Mesh object to add
"""The ObjParser class provides low-level parsing control and can be extended for custom parsing behavior.
class ObjParser:
def __init__(
self,
wavefront: Wavefront,
file_name: str,
strict: bool = False,
encoding: str = "utf-8",
create_materials: bool = False,
collect_faces: bool = False,
parse: bool = True,
cache: bool = False
):
"""
Create a new .obj file parser.
Parameters:
- wavefront: Wavefront object to populate with parsed data
- file_name: Path to .obj file
- strict: Enable strict parsing mode
- encoding: File encoding for text reading
- create_materials: Create materials when missing
- collect_faces: Collect face topology data
- parse: Parse immediately or defer
- cache: Enable binary caching system
"""
def parse(self) -> None:
"""
Parse the .obj file and populate the wavefront object.
Handles cache loading and writing automatically.
"""
def load_cache(self) -> None:
"""Load the file using cached data if available."""PyWavefront supports standard Wavefront .obj features and file formats:
Supported File Types:
.obj - Standard Wavefront object files.obj.gz - Gzip-compressed object files.mtl - Material library filesSupported .obj Elements:
v - Vertex positions (3D coordinates, optional vertex colors)vt - Texture coordinates (2D UV mapping)vn - Vertex normals (3D normal vectors)f - Face definitions (triangulated automatically for n-gons)o - Object/mesh namesmtllib - Material library referencesusemtl - Material assignment to facesMaterial Properties (.mtl files):
Automatic binary caching system for significant performance improvements on repeated file loads.
When cache=True, PyWavefront generates two files:
filename.obj.bin - Compressed binary vertex datafilename.obj.json - Cache metadata and structure# Enable caching for faster subsequent loads
scene = pywavefront.Wavefront('large_model.obj', cache=True)
# First load: parses .obj file and writes cache
# Subsequent loads: reads binary cache (10-100x faster)Cache files are automatically invalidated when the source .obj file changes.
class PywavefrontException(Exception):
"""
Custom exception for PyWavefront-specific errors.
Raised for parsing errors, missing files, format issues, etc.
"""Common error scenarios:
# Basic file loading
scene = pywavefront.Wavefront('model.obj')
# Strict parsing with error checking
try:
scene = pywavefront.Wavefront('model.obj', strict=True)
except pywavefront.PywavefrontException as e:
print(f"Parsing error: {e}")
# Deferred parsing for large files
scene = pywavefront.Wavefront('huge_model.obj', parse=False, cache=True)
# ... do other setup work ...
scene.parse() # Parse when ready
# Handle missing materials gracefully
scene = pywavefront.Wavefront(
'model_with_missing_mtl.obj',
create_materials=True # Creates default materials for missing references
)
# Collect face data for topology analysis
scene = pywavefront.Wavefront('model.obj', collect_faces=True)
for mesh in scene.mesh_list:
print(f"Mesh {mesh.name} has {len(mesh.faces)} triangular faces")Install with Tessl CLI
npx tessl i tessl/pypi-pywavefront