Coverage for trimesh/exchange/dae.py: 89%

219 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-12 17:18 +0000

1import copy 

2import io 

3import uuid 

4 

5import numpy as np 

6 

7from .. import util, visual 

8from ..constants import log 

9from ..util import unique_name 

10 

11_EYE = np.eye(4) 

12_EYE.flags.writeable = False 

13 

14 

15def load_collada(file_obj, resolver=None, ignore_broken=True, **kwargs): 

16 """ 

17 Load a COLLADA (.dae) file into a list of trimesh kwargs. 

18 

19 Parameters 

20 ---------- 

21 file_obj : file object 

22 Containing a COLLADA file 

23 resolver : trimesh.visual.Resolver or None 

24 For loading referenced files, like texture images 

25 ignore_broken: bool 

26 Ignores broken references during loading: 

27 [collada.common.DaeUnsupportedError, 

28 collada.common.DaeBrokenRefError] 

29 kwargs : ** 

30 Passed to trimesh.Trimesh.__init__ 

31 

32 Returns 

33 ------- 

34 loaded : list of dict 

35 kwargs for Trimesh constructor 

36 """ 

37 import collada 

38 

39 if ignore_broken: 

40 ignores = [ 

41 collada.common.DaeError, 

42 collada.common.DaeIncompleteError, 

43 collada.common.DaeMalformedError, 

44 collada.common.DaeBrokenRefError, 

45 collada.common.DaeUnsupportedError, 

46 collada.common.DaeIncompleteError, 

47 ] 

48 else: 

49 ignores = None 

50 

51 # load scene using pycollada 

52 c = collada.Collada(file_obj, ignore=ignores) 

53 

54 # Create material map from Material ID to trimesh material 

55 material_map = {} 

56 for m in c.materials: 

57 effect = m.effect 

58 material_map[m.id] = _parse_material(effect, resolver) 

59 

60 unit = c.assetInfo.unitmeter 

61 if unit is None or np.isclose(unit, 1.0): 

62 metadata = {"units": "meters"} 

63 else: 

64 metadata = {"units": f"{unit} * meters"} 

65 

66 # name : kwargs 

67 meshes = {} 

68 # increments to enable `unique_name` to avoid n^2 behavior 

69 meshes_count = {} 

70 # list of dict 

71 graph = [] 

72 

73 for node in c.scene.nodes: 

74 _parse_node( 

75 node=node, 

76 parent_matrix=_EYE, 

77 material_map=material_map, 

78 meshes=meshes, 

79 meshes_count=meshes_count, 

80 graph=graph, 

81 resolver=resolver, 

82 metadata=metadata, 

83 ) 

84 

85 return {"class": "Scene", "graph": graph, "geometry": meshes} 

86 

87 

88def export_collada(mesh, **kwargs): 

89 """ 

90 Export a mesh or a list of meshes as a COLLADA .dae file. 

91 

92 Parameters 

93 ----------- 

94 mesh: Trimesh object or list of Trimesh objects 

95 The mesh(es) to export. 

96 

97 Returns 

98 ----------- 

99 export: str, string of COLLADA format output 

100 """ 

101 import collada 

102 

103 meshes = mesh 

104 if not isinstance(mesh, (list, tuple, set, np.ndarray)): 

105 meshes = [mesh] 

106 

107 c = collada.Collada() 

108 nodes = [] 

109 for i, m in enumerate(meshes): 

110 # Load uv, colors, materials 

111 uv = None 

112 colors = None 

113 mat = _unparse_material(None) 

114 if m.visual.defined: 

115 if m.visual.kind == "texture": 

116 mat = _unparse_material(m.visual.material) 

117 uv = m.visual.uv 

118 elif m.visual.kind == "vertex": 

119 colors = (m.visual.vertex_colors / 255.0)[:, :3] 

120 mat.effect.diffuse = np.array(m.visual.main_color) / 255.0 

121 elif m.visual.kind == "face": 

122 mat.effect.diffuse = np.array(m.visual.main_color) / 255.0 

123 c.effects.append(mat.effect) 

124 c.materials.append(mat) 

125 

126 # Create geometry object 

127 geom_id = f"geometry{i}" 

128 vertices = collada.source.FloatSource( 

129 f"{geom_id}-verts-array", m.vertices.flatten(), ("X", "Y", "Z") 

130 ) 

131 normals = collada.source.FloatSource( 

132 f"{geom_id}-normals-array", m.vertex_normals.flatten(), ("X", "Y", "Z") 

133 ) 

134 input_list = collada.source.InputList() 

135 input_list.addInput(0, "VERTEX", f"#{geom_id}-verts-array") 

136 input_list.addInput(1, "NORMAL", f"#{geom_id}-normals-array") 

137 arrays = [vertices, normals] 

138 if (uv is not None) and (len(uv) > 0): 

139 texcoords = collada.source.FloatSource( 

140 f"{geom_id}-texcoords-array", uv.flatten(), ("U", "V") 

141 ) 

142 input_list.addInput(2, "TEXCOORD", f"#{geom_id}-texcoords-array") 

143 arrays.append(texcoords) 

144 if colors is not None: 

145 idx = 2 

146 if uv: 

147 idx = 3 

148 colors = collada.source.FloatSource( 

149 f"{geom_id}-colors-array", colors.flatten(), ("R", "G", "B") 

150 ) 

151 input_list.addInput(idx, "COLOR", f"#{geom_id}-colors-array") 

152 arrays.append(colors) 

153 geom = collada.geometry.Geometry(c, geom_id, uuid.uuid4().hex, arrays) 

154 indices = np.repeat(m.faces.flatten(), len(arrays)) 

155 

156 matref = f"material{i}" 

157 triset = geom.createTriangleSet(indices, input_list, matref) 

158 geom.primitives.append(triset) 

159 c.geometries.append(geom) 

160 

161 matnode = collada.scene.MaterialNode(matref, mat, inputs=[]) 

162 geomnode = collada.scene.GeometryNode(geom, [matnode]) 

163 node = collada.scene.Node(f"node{i}", children=[geomnode]) 

164 nodes.append(node) 

165 scene = collada.scene.Scene("scene", nodes) 

166 c.scenes.append(scene) 

167 c.scene = scene 

168 

169 b = io.BytesIO() 

170 c.write(b) 

171 b.seek(0) 

172 return b.read() 

173 

174 

175def _parse_node( 

176 node, parent_matrix, material_map, meshes, meshes_count, graph, resolver, metadata 

177): 

178 """ 

179 Recursively parse COLLADA scene nodes. 

180 """ 

181 import collada 

182 

183 # Parse mesh node 

184 if isinstance(node, collada.scene.GeometryNode): 

185 geometry = node.geometry 

186 

187 # Create local material map from material symbol to actual material 

188 local_material_map = {} 

189 for mn in node.materials: 

190 symbol = mn.symbol 

191 m = mn.target 

192 if m.id in material_map: 

193 local_material_map[symbol] = material_map[m.id] 

194 else: 

195 local_material_map[symbol] = _parse_material(m, resolver) 

196 

197 # Iterate over primitives of geometry 

198 for primitive in geometry.primitives: 

199 if isinstance(primitive, collada.polylist.Polylist): 

200 primitive = primitive.triangleset() 

201 if isinstance(primitive, collada.triangleset.TriangleSet): 

202 vertex = primitive.vertex 

203 if vertex is None: 

204 continue 

205 vertex_index = primitive.vertex_index 

206 vertices = vertex[vertex_index].reshape(len(vertex_index) * 3, 3) 

207 

208 # Get normals if present 

209 normals = None 

210 if primitive.normal is not None: 

211 normal = primitive.normal 

212 normal_index = primitive.normal_index 

213 normals = normal[normal_index].reshape(len(normal_index) * 3, 3) 

214 

215 # Get colors if present 

216 colors = None 

217 s = primitive.sources 

218 if "COLOR" in s and len(s["COLOR"]) > 0 and len(primitive.index) > 0: 

219 color = s["COLOR"][0][4].data 

220 color_index = primitive.index[:, :, s["COLOR"][0][0]] 

221 colors = color[color_index].reshape(len(color_index) * 3, -1) 

222 

223 faces = np.arange(vertices.shape[0]).reshape(vertices.shape[0] // 3, 3) 

224 

225 # Get UV coordinates if possible 

226 vis = None 

227 if primitive.material in local_material_map: 

228 material = copy.copy(local_material_map[primitive.material]) 

229 uv = None 

230 if len(primitive.texcoordset) > 0: 

231 texcoord = primitive.texcoordset[0] 

232 texcoord_index = primitive.texcoord_indexset[0] 

233 uv = texcoord[texcoord_index].reshape( 

234 (len(texcoord_index) * 3, 2) 

235 ) 

236 vis = visual.texture.TextureVisuals(uv=uv, material=material) 

237 

238 geom_name = unique_name(geometry.id, contains=meshes, counts=meshes_count) 

239 meshes[geom_name] = { 

240 "vertices": vertices, 

241 "faces": faces, 

242 "vertex_normals": normals, 

243 "vertex_colors": colors, 

244 "visual": vis, 

245 "metadata": metadata, 

246 } 

247 

248 graph.append( 

249 { 

250 "frame_to": geom_name, 

251 "matrix": parent_matrix, 

252 "geometry": geom_name, 

253 } 

254 ) 

255 

256 # recurse down tree for nodes with children 

257 elif isinstance(node, collada.scene.Node): 

258 if node.children is not None: 

259 for child in node.children: 

260 # create the new matrix 

261 matrix = np.dot(parent_matrix, node.matrix) 

262 # parse the child node 

263 _parse_node( 

264 node=child, 

265 parent_matrix=matrix, 

266 material_map=material_map, 

267 meshes=meshes, 

268 meshes_count=meshes_count, 

269 graph=graph, 

270 resolver=resolver, 

271 metadata=metadata, 

272 ) 

273 

274 elif isinstance(node, collada.scene.CameraNode): 

275 # TODO: convert collada cameras to trimesh cameras 

276 pass 

277 elif isinstance(node, collada.scene.LightNode): 

278 # TODO: convert collada lights to trimesh lights 

279 pass 

280 

281 

282def _load_texture(file_name, resolver): 

283 """ 

284 Load a texture from a file into a PIL image. 

285 """ 

286 from PIL import Image 

287 

288 file_data = resolver.get(file_name) 

289 image = Image.open(util.wrap_as_stream(file_data)) 

290 return image 

291 

292 

293def _parse_material(effect, resolver): 

294 """ 

295 Turn a COLLADA effect into a trimesh material. 

296 """ 

297 import collada 

298 

299 # Compute base color 

300 baseColorFactor = np.ones(4) 

301 baseColorTexture = None 

302 if isinstance(effect.diffuse, collada.material.Map): 

303 try: 

304 baseColorTexture = _load_texture( 

305 effect.diffuse.sampler.surface.image.path, resolver 

306 ) 

307 except BaseException: 

308 log.debug("unable to load base texture", exc_info=True) 

309 elif effect.diffuse is not None: 

310 baseColorFactor = effect.diffuse 

311 

312 # Compute emission color 

313 emissiveFactor = np.zeros(3) 

314 emissiveTexture = None 

315 if isinstance(effect.emission, collada.material.Map): 

316 try: 

317 emissiveTexture = _load_texture( 

318 effect.diffuse.sampler.surface.image.path, resolver 

319 ) 

320 except BaseException: 

321 log.warning("unable to load emissive texture", exc_info=True) 

322 elif effect.emission is not None: 

323 emissiveFactor = effect.emission[:3] 

324 

325 # Compute roughness 

326 roughnessFactor = 1.0 

327 if ( 

328 not isinstance(effect.shininess, collada.material.Map) 

329 and effect.shininess is not None 

330 ): 

331 try: 

332 shininess_value = float(effect.shininess) 

333 roughnessFactor = np.sqrt(2.0 / (2.0 + shininess_value)) 

334 except (TypeError, ValueError): 

335 log.warning( 

336 f"Invalid shininess value: {effect.shininess}, using default roughness" 

337 ) 

338 

339 # Compute metallic factor 

340 metallicFactor = 0.0 

341 

342 # Compute normal texture 

343 normalTexture = None 

344 if effect.bumpmap is not None: 

345 try: 

346 normalTexture = _load_texture( 

347 effect.bumpmap.sampler.surface.image.path, resolver 

348 ) 

349 except BaseException: 

350 log.warning("unable to load bumpmap", exc_info=True) 

351 

352 # Compute opacity 

353 if effect.transparent is not None and not isinstance( 

354 effect.transparent, collada.material.Map 

355 ): 

356 baseColorFactor = tuple( 

357 np.append(baseColorFactor[:3], float(effect.transparent[3])) 

358 ) 

359 

360 return visual.material.PBRMaterial( 

361 emissiveFactor=emissiveFactor, 

362 emissiveTexture=emissiveTexture, 

363 normalTexture=normalTexture, 

364 baseColorTexture=baseColorTexture, 

365 baseColorFactor=baseColorFactor, 

366 metallicFactor=metallicFactor, 

367 roughnessFactor=roughnessFactor, 

368 ) 

369 

370 

371def _unparse_material(material): 

372 """ 

373 Turn a trimesh material into a COLLADA material. 

374 """ 

375 import collada 

376 

377 # TODO EXPORT TEXTURES 

378 if isinstance(material, visual.material.PBRMaterial): 

379 diffuse = material.baseColorFactor 

380 if diffuse is None: 

381 diffuse = np.array([255.0, 255.0, 255.0, 255.0]) 

382 diffuse = diffuse / 255.0 

383 if diffuse is not None: 

384 diffuse = list(diffuse) 

385 

386 emission = material.emissiveFactor 

387 if emission is not None: 

388 emission = [float(emission[0]), float(emission[1]), float(emission[2]), 1.0] 

389 

390 shininess = material.roughnessFactor 

391 if shininess is None: 

392 shininess = 1.0 

393 if shininess is not None: 

394 shininess = 2.0 / shininess**2 - 2.0 

395 

396 effect = collada.material.Effect( 

397 uuid.uuid4().hex, 

398 params=[], 

399 shadingtype="phong", 

400 diffuse=diffuse, 

401 emission=emission, 

402 specular=[1.0, 1.0, 1.0, 1.0], 

403 shininess=float(shininess), 

404 ) 

405 material = collada.material.Material(uuid.uuid4().hex, "pbrmaterial", effect) 

406 else: 

407 effect = collada.material.Effect(uuid.uuid4().hex, params=[], shadingtype="phong") 

408 material = collada.material.Material(uuid.uuid4().hex, "defaultmaterial", effect) 

409 return material 

410 

411 

412def load_zae(file_obj, resolver=None, **kwargs): 

413 """ 

414 Load a ZAE file, which is just a zipped DAE file. 

415 

416 Parameters 

417 ------------- 

418 file_obj : file object 

419 Contains ZAE data 

420 resolver : trimesh.visual.Resolver 

421 Resolver to load additional assets 

422 kwargs : dict 

423 Passed to load_collada 

424 

425 Returns 

426 ------------ 

427 loaded : dict 

428 Results of loading 

429 """ 

430 

431 # a dict, {file name : file object} 

432 archive = util.decompress(file_obj, file_type="zip") 

433 

434 # load the first file with a .dae extension 

435 file_name = next(i for i in archive.keys() if i.lower().endswith(".dae")) 

436 

437 # a resolver so the loader can load textures / etc 

438 resolver = visual.resolvers.ZipResolver(archive) 

439 

440 # run the regular collada loader 

441 loaded = load_collada(archive[file_name], resolver=resolver, **kwargs) 

442 return loaded 

443 

444 

445# only provide loaders if `pycollada` is installed 

446_collada_loaders = {} 

447_collada_exporters = {} 

448if util.has_module("collada"): 

449 _collada_loaders["dae"] = load_collada 

450 _collada_loaders["zae"] = load_zae 

451 _collada_exporters["dae"] = export_collada 

452else: 

453 # store an exception to raise later 

454 from ..exceptions import ExceptionWrapper 

455 

456 _exc = ExceptionWrapper(ImportError("missing `pip install pycollada`")) 

457 _collada_loaders.update({"dae": _exc, "zae": _exc}) 

458 _collada_exporters["dae"] = _exc