def convert_file_to_obj(mesh_file, suffix, scale=1): assert mesh_file.endswith(suffix), mesh_file obj_file = mesh_file[:-len(suffix)] + ".obj" print(f"Convert Mesh: {mesh_file} -> {obj_file}") if isfile(obj_file): return scene = load_mesh(mesh_file) # Workaround for issue https://github.com/assimp/assimp/issues/849. if suffix == ".dae": ROT_X_90 = np.matrix([[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) rotate_root_node(scene, ROT_X_90) pyassimp.export(scene, obj_file, file_type="obj") # TODO(marcoag) skip sanity check for now # find a way to do one extent = get_mesh_extent(scene, mesh_file, suffix) scene_obj = load_mesh(obj_file) extent_obj = get_mesh_extent(scene_obj, mesh_file) np.testing.assert_allclose( extent, extent_obj, rtol=1e-05, atol=1e-07, err_msg=repr((mesh_file, obj_file)), )
def convert_mesh(from_filename, to_filename, library='pyassimp', binary=False): """ Convert the given file containing the original mesh to the other specified format using the `pyassimp` library. Args: from_filename (str): filename of the mesh to convert. to_filename (str): filename of the converted mesh. library (str): library to use to convert the meshes. Select between 'pyassimp' and 'trimesh'. binary (bool): if True, it will be in a binary format. This is only valid for some formats such as STL where you have the ASCII version 'stl' and the binary version 'stlb'. """ if library == 'pyassimp': scene = pyassimp.load(from_filename) extension = to_filename.split('.')[-1].lower() if binary: # for binary add 'b' as a suffix. Ex: '<file>.stlb' pyassimp.export(scene, to_filename, file_type=extension + 'b') else: pyassimp.export(scene, to_filename, file_type=extension) pyassimp.release(scene) elif library == 'trimesh': export_mesh(trimesh.load(from_filename), to_filename) else: raise NotImplementedError( "The given library '{}' is currently not supported, select between 'pyassimp' and " "'trimesh'".format(library))
def convert_mesh(old_mesh_file, new_mesh_file, file_type): print(f"Original: {old_mesh_file}") scene_old = load_mesh(old_mesh_file) v_old = get_mesh_vertices(scene_old) pyassimp.export(scene_old, new_mesh_file, file_type=file_type) print(f"Converted: {new_mesh_file}") scene_new = load_mesh(new_mesh_file) v_new = get_mesh_vertices(scene_new) # Sanity check. np.testing.assert_allclose(v_old, v_new, atol=1e-8, rtol=0)
def correct_model(sourcePath, destPath): if not os.path.exists(destPath): os.makedirs(destPath) assetPath = os.path.join(destPath, 'images') if not os.path.exists(assetPath): os.mkdir(assetPath) modelPath = get_model_path(sourcePath) model = pyassimp.load(modelPath) for index, material in enumerate(model.materials): print model.materials[index].properties for key, value in material.properties.iteritems(): if key[0] == "diffuse": # fName = os.path.split(value)[1] # id = fName.rfind('\\') # originalFileName = fName[id+1:] # destFileName = originalFileName.replace(' ','_') # destFileName = destFileName.lower() # shutil.copyfile(os.path.join(sourcePath,originalFileName),os.path.join(assetPath,destFileName)) # print originalFileName # newPath = u'./images/%s' % (destFileName) model.materials[index].properties[key] = [0.6, 0.6, 0.6] # for t in material.properties.keys(): # print t print # print model.materials[index].properties # for key in model.materials[index].properties: # print key # print tst # model.materials[index].properties["file"] = value for index, material in enumerate(model.materials): for key, value in material.properties.iteritems(): print '%s: %s' % (key, value) pyassimp.export(model, os.path.join(destPath, 'model'), 'obj') os.rename(os.path.join(destPath, 'model'), os.path.join(destPath, 'model.obj'))
def convert_file_to_obj(mesh_file, suffix): assert mesh_file.endswith(suffix), mesh_file obj_file = mesh_file[:-len(suffix)] + ".obj" print(f"Convert Mesh: {mesh_file} -> {obj_file}") if isfile(obj_file): return scene = load_mesh(mesh_file) extent = get_mesh_extent(scene, mesh_file) pyassimp.export(scene, obj_file, file_type="obj") # Sanity check. scene_obj = load_mesh(obj_file) extent_obj = get_mesh_extent(scene, mesh_file) np.testing.assert_equal( extent, extent_obj, err_msg=repr((mesh_file, obj_file)), )
def transform(scene, x_rot, y_rot, z_rot, savepath): m = rotzyx(x_rot, y_rot, z_rot, degrees=True) scene.mRootNode.contents.mTransformation.a1 = m[0, 0] scene.mRootNode.contents.mTransformation.a2 = m[0, 1] scene.mRootNode.contents.mTransformation.a3 = m[0, 2] scene.mRootNode.contents.mTransformation.b1 = m[1, 0] scene.mRootNode.contents.mTransformation.b2 = m[1, 1] scene.mRootNode.contents.mTransformation.b3 = m[1, 2] scene.mRootNode.contents.mTransformation.c1 = m[2, 0] scene.mRootNode.contents.mTransformation.c2 = m[2, 1] scene.mRootNode.contents.mTransformation.c3 = m[2, 2] scene.mRootNode.contents.mTransformation.a4 = 0 scene.mRootNode.contents.mTransformation.b4 = 0 scene.mRootNode.contents.mTransformation.c4 = 0 fn = "model_augmented_{:03d}_{:03d}_{:03d}.obj".format(x_rot, y_rot, z_rot) savename = os.path.join(savepath, fn) pyassimp.export(scene, savename, 'obj')
def transform(scene, y_rot, x_trans, y_trans, z_trans, savepath): m = roty(y_rot * 3.1415/180) scene.mRootNode.contents.mTransformation.a1 = m[0,0] scene.mRootNode.contents.mTransformation.a2 = m[0,1] scene.mRootNode.contents.mTransformation.a3 = m[0,2] scene.mRootNode.contents.mTransformation.b1 = m[1,0] scene.mRootNode.contents.mTransformation.b2 = m[1,1] scene.mRootNode.contents.mTransformation.b3 = m[1,2] scene.mRootNode.contents.mTransformation.c1 = m[2,0] scene.mRootNode.contents.mTransformation.c2 = m[2,1] scene.mRootNode.contents.mTransformation.c3 = m[2,2] scene.mRootNode.contents.mTransformation.a4 = x_trans scene.mRootNode.contents.mTransformation.b4 = y_trans scene.mRootNode.contents.mTransformation.c4 = z_trans fn = "model_augmented_{:1.1f}_{:1.1f}_{:1.1f}_{:03d}.obj".format(x_trans, y_trans, z_trans, y_rot) savename = os.path.join(savepath, fn) pyassimp.export(scene, savename, 'obj')
def save(self, basepath): """ Save the outline to a obj file :param str basepath: the base path of output :return: """ path = os.path.join(basepath, 'meshes') if not os.path.exists(path): os.makedirs(path) _obj_filename = os.path.join(path, '_outline_.obj') self._save_to_obj(_obj_filename, BOARD_HEIGHT) # standardize the obj file by pyassimp scene = pyassimp.load(_obj_filename) pyassimp.export(scene, os.path.join(path, 'outline.obj'), file_type='obj') pyassimp.release(scene) # compatible with Assimp 3 and 4 if os.path.isfile(os.path.join(path, 'outline.mtl')): shutil.copyfile(os.path.join(path, 'outline.mtl'), os.path.join(path, 'outline.obj.mtl'))
def end_scene(self, out_filename): ''' Called after geometries have all been added to scene and a file or blob should be created :param out_filename: filename and path of output file, without file extension if an empty string, then a blob is returned and a file is not created :returns: True if file was written out, else returns the GLTF as an assimp blob object ''' #pa.print_scene(self.scn) #sys.stdout.flush() # Create a file if out_filename != '': self.logger.info("Writing GLTF: %s", out_filename + self.FILE_EXT) export(self.scn, out_filename + self.FILE_EXT, self.EXPORT_TYPE) self.logger.info(" DONE.") sys.stdout.flush() return True # Return a blob exp_blob = export_blob(self.scn, self.EXPORT_TYPE, processing=None) #pa.print_blob(exp_blob) return exp_blob
def stl2ply(filename, fileIODir): stlName = os.path.abspath(os.path.join(fileIODir, filename)) scene = pyassimp.load(stlName, file_type='stl', processing=pyassimp.postprocess.aiProcess_Triangulate) plyName = stlName.split('.')[0] + '.ply' pyassimp.export(scene, plyName, file_type='ply')
def importAsset(self, node, reload=False): if not MESH_ENABLED: return False if not node.assetType in ['folder', 'mesh']: return True node.assetType = 'mesh' node.setBundle() node.groupType = 'package' filePath = node.getFilePath() nodePath = node.getNodePath() modelExt = [ '.3ds', '.fbx', '.x', '.lwo', '.obj', '.md5mesh', '.dxf', '.ply', '.stl', '.dae', '.md5anim', '.lws', '.irrmesh', '.nff', '.off', '.blend' ] texExt = ['.bmp', '.jpg', '.tif', '.png', '.jpeg'] rootPath = node.getCacheFile('meshCache1', is_dir=True, clear=True) node.setObjectFile('mesh', rootPath) # print("mesh importing") print(("root path: " + rootPath)) for fileName in os.listdir(node.getAbsFilePath()): fullPath = filePath + '/' + fileName name, ext = os.path.splitext(fileName) if ext in modelExt: saveFilePath = rootPath + '/mesh' print(("mesh path: " + saveFilePath)) # meshPath = node.getCacheFile( 'mesh' ) # node.setObjectFile( 'mesh', ) # print( "fileName: " + fileName ) # print( "fullPath: " + fullPath) # print( "meshPath: " + meshPath ) # print( "nodePath: " + nodePath ) scene = pyassimp.load(fullPath) pyassimp.export( scene, saveFilePath, "assxml", pyassimp.postprocess. aiProcessPreset_TargetRealtime_MaxQuality) # pyassimp.export( scene, "export.xml", "assxml", pyassimp.postprocess.aiProcess_Triangulate ) # print(mesh.vertices[0]) pyassimp.release(scene) print("mesh imported") # elif ext == '.material': # print( "material" ) # materialPath = node.getCacheFile( 'material' ) # node.setObjectFile( 'material', materialPath ) # print( "materialPath: " + materialPath ) # print( "nodePath: " + nodePath ) # internalAtlas = _MOCK.convertSpineAtlasToPrebuiltAtlas( fullPath ) # for page in internalAtlas.pages.values(): # page.source = filePath + '/' + page.texture # atlasNode = node.affirmChildNode( node.getBaseName()+'_spine_atlas', 'prebuilt_atlas', manager = 'asset_manager.prebuilt_atlas' ) # atlasSourceCachePath = atlasNode.getCacheFile( 'atlas_source' ) # internalAtlas.save( internalAtlas, atlasSourceCachePath ) # app.getModule( 'texture_library' ).scheduleImport( atlasNode ) elif ext in texExt: saveFilePath = rootPath + '/' + name + '.png' print(("texture path: " + saveFilePath)) # texturePath = node.getCacheFile( 'texture' ) # node.setObjectFile( 'texture', texturePath ) # print( "texturePath: " + texturePath ) # print( "nodePath: " + nodePath ) img = Image.open(fullPath) img = img.convert("RGBA") img.save(saveFilePath, 'PNG') return True
import sys sys.path.append("/home/trojande/work/freecad-code/lib") import FreeCAD import Part import importDAE import pyassimp file = u"/home/trojande/work/github.com/maul-a/stp-to-gltf/part.stp" FreeCAD.newDocument() FreeCAD.setActiveDocument("Unnamed") doc = FreeCAD.getDocument("Unnamed") Part.insert(file, "Unnamed") importDAE.export(doc.Objects, u"/home/trojande/work/github.com/maul-a/stp-to-gltf/part.dae") assimp_scene = pyassimp.load('part.dae') pyassimp.export(assimp_scene, 'part.gltf', 'gltf2')