0
# File Loading and Parsing
1
2
Core functionality for loading Wavefront .obj files with comprehensive parsing options, encoding support, error handling, and optional binary caching for improved performance.
3
4
## Capabilities
5
6
### Wavefront File Loading
7
8
The primary interface for loading .obj files, with extensive configuration options for parsing behavior, encoding, and performance optimization.
9
10
```python { .api }
11
class Wavefront:
12
def __init__(
13
self,
14
file_name: str,
15
strict: bool = False,
16
encoding: str = "utf-8",
17
create_materials: bool = False,
18
collect_faces: bool = False,
19
parse: bool = True,
20
cache: bool = False
21
):
22
"""
23
Load and parse a Wavefront .obj file.
24
25
Parameters:
26
- file_name: Path to the .obj file to load
27
- strict: Enable strict parsing mode (raises exceptions for unsupported features)
28
- encoding: Text encoding for reading files (default: utf-8)
29
- create_materials: Create default materials when missing or undefined
30
- collect_faces: Collect triangle face data for topology analysis
31
- parse: Parse immediately (True) or defer parsing until manual call (False)
32
- cache: Write parsed data to binary cache files for faster subsequent loads
33
34
Attributes after loading:
35
- materials: Dict[str, Material] - Materials indexed by name
36
- meshes: Dict[str, Mesh] - Named meshes indexed by name
37
- mesh_list: List[Mesh] - All meshes including anonymous ones
38
- vertices: List[float] - All vertex position data
39
- mtllibs: List[str] - Material library filenames referenced
40
"""
41
42
def parse(self) -> None:
43
"""
44
Manually parse the file when parse=False was used in constructor.
45
Must be called to populate materials, meshes, and vertex data.
46
"""
47
48
def add_mesh(self, mesh: Mesh) -> None:
49
"""
50
Add a mesh to the wavefront object.
51
52
Parameters:
53
- mesh: Mesh object to add
54
"""
55
```
56
57
### Advanced Parser Configuration
58
59
The ObjParser class provides low-level parsing control and can be extended for custom parsing behavior.
60
61
```python { .api }
62
class ObjParser:
63
def __init__(
64
self,
65
wavefront: Wavefront,
66
file_name: str,
67
strict: bool = False,
68
encoding: str = "utf-8",
69
create_materials: bool = False,
70
collect_faces: bool = False,
71
parse: bool = True,
72
cache: bool = False
73
):
74
"""
75
Create a new .obj file parser.
76
77
Parameters:
78
- wavefront: Wavefront object to populate with parsed data
79
- file_name: Path to .obj file
80
- strict: Enable strict parsing mode
81
- encoding: File encoding for text reading
82
- create_materials: Create materials when missing
83
- collect_faces: Collect face topology data
84
- parse: Parse immediately or defer
85
- cache: Enable binary caching system
86
"""
87
88
def parse(self) -> None:
89
"""
90
Parse the .obj file and populate the wavefront object.
91
Handles cache loading and writing automatically.
92
"""
93
94
def load_cache(self) -> None:
95
"""Load the file using cached data if available."""
96
```
97
98
### File Format Support
99
100
PyWavefront supports standard Wavefront .obj features and file formats:
101
102
**Supported File Types:**
103
- `.obj` - Standard Wavefront object files
104
- `.obj.gz` - Gzip-compressed object files
105
- `.mtl` - Material library files
106
107
**Supported .obj Elements:**
108
- `v` - Vertex positions (3D coordinates, optional vertex colors)
109
- `vt` - Texture coordinates (2D UV mapping)
110
- `vn` - Vertex normals (3D normal vectors)
111
- `f` - Face definitions (triangulated automatically for n-gons)
112
- `o` - Object/mesh names
113
- `mtllib` - Material library references
114
- `usemtl` - Material assignment to faces
115
116
**Material Properties (.mtl files):**
117
- Diffuse, ambient, specular, and emissive colors
118
- Transparency and optical density
119
- Shininess and illumination models (0-10)
120
- Texture maps (diffuse, ambient, specular, alpha, bump)
121
122
### Binary Caching System
123
124
Automatic binary caching system for significant performance improvements on repeated file loads.
125
126
When `cache=True`, PyWavefront generates two files:
127
- `filename.obj.bin` - Compressed binary vertex data
128
- `filename.obj.json` - Cache metadata and structure
129
130
```python
131
# Enable caching for faster subsequent loads
132
scene = pywavefront.Wavefront('large_model.obj', cache=True)
133
134
# First load: parses .obj file and writes cache
135
# Subsequent loads: reads binary cache (10-100x faster)
136
```
137
138
Cache files are automatically invalidated when the source .obj file changes.
139
140
### Error Handling
141
142
```python { .api }
143
class PywavefrontException(Exception):
144
"""
145
Custom exception for PyWavefront-specific errors.
146
Raised for parsing errors, missing files, format issues, etc.
147
"""
148
```
149
150
Common error scenarios:
151
- File not found or permission errors
152
- Unsupported .obj features in strict mode
153
- Missing material references (when create_materials=False)
154
- Malformed vertex or face data
155
- Encoding issues with international characters
156
157
### Usage Examples
158
159
```python
160
# Basic file loading
161
scene = pywavefront.Wavefront('model.obj')
162
163
# Strict parsing with error checking
164
try:
165
scene = pywavefront.Wavefront('model.obj', strict=True)
166
except pywavefront.PywavefrontException as e:
167
print(f"Parsing error: {e}")
168
169
# Deferred parsing for large files
170
scene = pywavefront.Wavefront('huge_model.obj', parse=False, cache=True)
171
# ... do other setup work ...
172
scene.parse() # Parse when ready
173
174
# Handle missing materials gracefully
175
scene = pywavefront.Wavefront(
176
'model_with_missing_mtl.obj',
177
create_materials=True # Creates default materials for missing references
178
)
179
180
# Collect face data for topology analysis
181
scene = pywavefront.Wavefront('model.obj', collect_faces=True)
182
for mesh in scene.mesh_list:
183
print(f"Mesh {mesh.name} has {len(mesh.faces)} triangular faces")
184
```