Coverage for trimesh/exchange/misc.py: 77%

70 statements  

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

1import json 

2import os 

3from tempfile import NamedTemporaryFile 

4 

5from .. import util 

6from ..exceptions import ExceptionWrapper 

7 

8 

9def load_dict(file_obj, **kwargs): 

10 """ 

11 Load multiple input types into kwargs for a Trimesh constructor. 

12 Tries to extract keys: 

13 'faces' 

14 'vertices' 

15 'face_normals' 

16 'vertex_normals' 

17 

18 Parameters 

19 ---------- 

20 file_obj : dict 

21 accepts multiple forms 

22 -dict: has keys for vertices and faces as (n,3) numpy arrays 

23 -dict: has keys for vertices/faces (n,3) arrays encoded as dicts/base64 

24 with trimesh.util.array_to_encoded/trimesh.util.encoded_to_array 

25 -str: json blob as dict with either straight array or base64 values 

26 -file object: json blob of dict 

27 file_type: not used 

28 

29 Returns 

30 ----------- 

31 loaded: dict with keys 

32 -vertices: (n,3) float 

33 -faces: (n,3) int 

34 -face_normals: (n,3) float (optional) 

35 """ 

36 if file_obj is None: 

37 raise ValueError("file_obj passed to load_dict was None!") 

38 if util.is_instance_named(file_obj, "Trimesh"): 

39 return file_obj 

40 if isinstance(file_obj, str): 

41 if "{" not in file_obj: 

42 raise ValueError("Object is not a JSON encoded dictionary!") 

43 file_obj = json.loads(file_obj.decode("utf-8")) 

44 elif util.is_file(file_obj): 

45 file_obj = json.load(file_obj) 

46 

47 # what shape should the file_obj be to be usable 

48 mesh_file_obj = { 

49 "vertices": (-1, 3), 

50 "faces": (-1, (3, 4)), 

51 "face_normals": (-1, 3), 

52 "face_colors": (-1, (3, 4)), 

53 "vertex_normals": (-1, 3), 

54 "vertex_colors": (-1, (3, 4)), 

55 } 

56 

57 # now go through file_obj structure and if anything is encoded as base64 

58 # pull it back into numpy arrays 

59 if not isinstance(file_obj, dict): 

60 raise ValueError(f"`{type(file_obj)}` object passed to dict loader!") 

61 

62 loaded = {} 

63 file_obj = util.decode_keys(file_obj, "utf-8") 

64 for key, shape in mesh_file_obj.items(): 

65 if key in file_obj: 

66 loaded[key] = util.encoded_to_array(file_obj[key]) 

67 if not util.is_shape(loaded[key], shape): 

68 raise ValueError( 

69 "Shape of %s is %s, not %s!", 

70 key, 

71 str(loaded[key].shape), 

72 str(shape), 

73 ) 

74 if len(loaded) == 0: 

75 raise ValueError("Unable to extract a mesh from the dict!") 

76 

77 return loaded 

78 

79 

80def load_meshio(file_obj, file_type: str, **kwargs): 

81 """ 

82 Load a meshio-supported file into the kwargs for a Trimesh 

83 constructor. 

84 

85 

86 Parameters 

87 ---------- 

88 file_obj : file object 

89 Contains a meshio file 

90 file_type : str 

91 File extension, aka 'vtk' 

92 

93 Returns 

94 ---------- 

95 loaded : dict 

96 kwargs for Trimesh constructor 

97 """ 

98 import warnings 

99 

100 warnings.warn( 

101 "`meshio` loading is deprecated and will be removed after June 2027; " 

102 + "use `meshio` directly if you need these formats.", 

103 category=DeprecationWarning, 

104 stacklevel=2, 

105 ) 

106 

107 # trimesh "file types" are really filename extensions 

108 # meshio may return multiple answers for each file extension 

109 file_formats = meshio.extension_to_filetypes["." + file_type] 

110 

111 mesh = None 

112 exceptions = [] 

113 

114 # meshio appears to only support loading by file name so use a tempfile 

115 # and close it before reading as Windows can't reopen an open tempfile 

116 temp = NamedTemporaryFile(suffix=f".{file_type}", delete=False) 

117 try: 

118 with temp: 

119 temp.write(file_obj.read()) 

120 # try the loaders in order 

121 for file_format in file_formats: 

122 try: 

123 mesh = meshio.read(temp.name, file_format=file_format) 

124 break 

125 except BaseException as E: 

126 exceptions.append(str(E)) 

127 finally: 

128 os.remove(temp.name) 

129 

130 if mesh is None: 

131 raise ValueError("Failed to load file:" + "\n".join(exceptions)) 

132 

133 # save file_obj as kwargs for a trimesh.Trimesh 

134 result = {} 

135 # pass kwargs to mesh constructor 

136 result.update(kwargs) 

137 # add vertices 

138 result["vertices"] = mesh.points 

139 try: 

140 # add faces 

141 result["faces"] = mesh.get_cells_type("triangle") 

142 except BaseException: 

143 util.log.warning("unable to get faces", exc_info=True) 

144 result["faces"] = [] 

145 

146 return result 

147 

148 

149_misc_loaders = {"dict": load_dict, "dict64": load_dict} 

150_misc_loaders = {} 

151 

152 

153try: 

154 import meshio 

155 

156 # add meshio loaders here 

157 _meshio_loaders = {k[1:]: load_meshio for k in meshio.extension_to_filetypes.keys()} 

158 _misc_loaders.update(_meshio_loaders) 

159except BaseException: 

160 _meshio_loaders = {} 

161 

162try: 

163 import openctm 

164 

165 _misc_loaders["ctm"] = openctm.load_ctm 

166except BaseException as E: 

167 _misc_loaders["ctm"] = ExceptionWrapper(E)