def load_model(self, path, postprocess=aiProcessPreset_TargetRealtime_MaxQuality): logger.info("Loading model:" + path + "...") if postprocess: self.scene = pyassimp.load(path, processing=postprocess) else: self.scene = pyassimp.load(path) logger.info("Done.") scene = self.scene # log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) self.bb_min, self.bb_max = get_bounding_box(self.scene) logger.info(" bounding box:" + str(self.bb_min) + " - " + str(self.bb_max)) self.scene_center = [(a + b) / 2. for a, b in zip(self.bb_min, self.bb_max)] for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) self.glize(scene, scene.rootnode) # Finally release the model pyassimp.release(scene) logger.info("Ready for 3D rendering!")
def loadModel(self): # Separates model data from loaded file and processed into a usable format if self.model: logger.info(self.fileMain + " is already loaded.") return logger.info("Loading model:" + self.fileMain + "...") model = None if self.postprocess: model = pyassimp.load(self.fileMain, self.postprocess) else: model = pyassimp.load(self.fileMain) if self.fileReplace: aux = pyassimp.load(self.fileReplace) for i in range(len(model.meshes)): replaced = model.meshes[i].bones model.meshes[i].bones = aux.meshes[i].bones.copy( ) # replaces the bones with those from the secondary file del replaced pyassimp.release(aux) logger.info("Done.") scene = model for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) # Finally release the model pyassimp.release(scene) self.model = model
def load_model(self, path, postprocess = aiProcessPreset_TargetRealtime_MaxQuality): logger.info("Loading model:" + path + "...") if postprocess: self.scene = pyassimp.load(path, postprocess) else: self.scene = pyassimp.load(path) logger.info("Done.") scene = self.scene #log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) self.bb_min, self.bb_max = get_bounding_box(self.scene) logger.info(" bounding box:" + str(self.bb_min) + " - " + str(self.bb_max)) self.scene_center = [(a + b) / 2. for a, b in zip(self.bb_min, self.bb_max)] for index, mesh in enumerate(scene.meshes): """convert the vertice and face in the original mesh, and also give a color in there""" self.c = mestTest.Convert(mesh, path) self.c.convert() modifyVertices, modifyTri, color, triangleSelected = self.c.surfaceDisplay(5,True) mesh.vertices = numpy.array(modifyVertices) mesh.color = numpy.array(color) mesh.faces = numpy.array(modifyTri, dtype = 'int32') self.prepare_gl_buffers(mesh) # Finally release the model pyassimp.release(scene) logger.info("Ready for 3D rendering!")
def load_model(self, path, postprocess=None): logger.info("Loading model:" + path + "...") if postprocess: self.scene = pyassimp.load(path, postprocess) else: self.scene = pyassimp.load(path) logger.info("Done.") scene = self.scene #log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) self.bb_min, self.bb_max = get_bounding_box(self.scene) logger.info(" bounding box:" + str(self.bb_min) + " - " + str(self.bb_max)) self.scene_center = [(a + b) / 2. for a, b in zip(self.bb_min, self.bb_max)] for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) # Finally release the model pyassimp.release(scene)
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 loadModelAll(fname): scene = pyassimp.load(fname, pyassimp.postprocess.aiProcess_Triangulate) # Center and normalise the mesh. normaliseModel(scene) # Load all the materials. material_list = loadMaterials(scene, fname) # Associate mesh indexes with material indexes. vert, UV, RGB, width, height = loadObjects(scene, material_list) # Sanity check: the number of vertices must match the number of UV pairs. assert (len(UV) == len(vert)) for ii in range(len(UV)): assert (len(UV[ii]) // 2 == len(vert[ii]) // 3) # Clear the UV data if there is no texture. for ii in range(len(UV)): if width[ii] == height[ii] == 0: UV[ii] = np.array([], np.float64) # Return the data as a dictionary. data = {'vertices': vert, 'UV': UV, 'RGB': RGB, 'width': width, 'height': height} return data
def _updateShapeData(self, firstTime): if firstTime: uri = self.meshShape.getMeshUri2() retriever = self.meshShape.getResourceRetriever() meshPath = retriever.getFilePath(uri) try: scene = assimp.load(meshPath) except: # TODO(JS): Better error handling warnings.warn("Failed to load a mesh '{}'.".format(uri)) return # Materials # for material in scene.materials: # self.materials += [Material(material)] # # # Texture images # for texture in scene.textures: # self.textures += [Texture(texture)] self.rootAssimpNodeNode = AssimpNodeNode(scene.rootnode, assimpScene=scene, parent=self) else: self.rootAssimpNodeNode.refresh()
def model_geom(file_root, w, nextId, opt): ## Read TINs from the DAE global bid dir_parts = file_root.split("/") if ( len(dir_parts) > 0 ): bid = dir_parts[len(dir_parts)-1] else: bid = "unknown" myProcessing = pas.postprocess.aiProcess_Triangulate | pas.postprocess.aiProcess_PreTransformVertices scene = pas.load(file_root + '.dae', processing=myProcessing) assert len(scene.meshes), "file has no meshes... aborting" if os.path.isfile(file_root + '.czml') and opt.relModelPos: json_data=open(file_root + '.czml', "rb") data = json.load(json_data) json_data.close() else: data = json.loads('[{"skip": "me"},{"position": {"cartographicDegrees": [0,0,0]}}]') [mx,my,mz] = data[1]["position"]["cartographicDegrees"] mx = float(mx) my = float(my) mz = float(mz) g1 = "POINT (%f %f %f)" % (mx,my,mz) if (opt.s_srs != opt.t_srs): g2 = project_point(g1, opt.s_srs, opt.t_srs) else: g2 = ogr.CreateGeometryFromWkt(g1) return convert_meshes(scene, g2, opt, w)
def loadModelAll(fname): scene = pyassimp.load(fname, pyassimp.postprocess.aiProcess_Triangulate) # Center and normalise the mesh. normaliseModel(scene) # Load all the materials. material_list = loadMaterials(scene, fname) # Associate mesh indexes with material indexes. vert, UV, RGB, width, height = loadObjects(scene, material_list) # Sanity check: the number of vertices must match the number of UV pairs. assert (len(UV) == len(vert)) for ii in range(len(UV)): assert (len(UV[ii]) // 2 == len(vert[ii]) // 3) # Clear the UV data if there is no texture. for ii in range(len(UV)): if width[ii] == height[ii] == 0: UV[ii] = np.array([], np.float64) # Return the data as a dictionary. data = { 'vertices': vert, 'UV': UV, 'RGB': RGB, 'width': width, 'height': height } return data
def __init__(self, obj_file, material_file=None, load_materials=True, name_prefix='', name_suffix='', materials_scale=1.0): if material_file is not None: logging.error( 'Ignoring material file input, reading them off obj file.') load_flags = self.get_pyassimp_load_options() scene = assimp.load(obj_file, processing=load_flags) filter_ind = self._filter_triangles(scene.meshes) self.meshes = [scene.meshes[i] for i in filter_ind] for i, m in enumerate(self.meshes): m.name = name_prefix + m.name + '_{:05d}'.format(i) + name_suffix logging.error('#Meshes: %d', len(self.meshes)) dir_name = os.path.dirname(obj_file) # Load materials materials = None if load_materials: materials = [] for m in self.meshes: file_name = os.path.join(dir_name, m.material.properties[('file', 1)]) assert(os.path.exists(file_name)), \ 'Texture file {:s} foes not exist.'.format(file_name) materials.append( self._load_materials_from_file(file_name, materials_scale)) self.scene = scene self.materials = materials
def load_meshes(obj_files, vertex_tmp_store_folder, recalculate_normals=False): from utils.sundermeyer.gl_utils import inout hashed_file_name = hashlib.md5( (''.join(obj_files) + 'load_meshes' + str(recalculate_normals)).encode('utf-8')).hexdigest() + '.npy' out_file = os.path.join(vertex_tmp_store_folder, hashed_file_name) if os.path.exists(out_file): print("loading file...") return np.load(out_file) else: bar = progressbar.ProgressBar() attributes = [] for model_path in bar(obj_files): scene = pyassimp.load(model_path, pyassimp.postprocess.aiProcess_Triangulate) mesh = scene.meshes[0] vertices = mesh.vertices normals = calc_normals( vertices) if recalculate_normals else mesh.normals attributes.append((vertices, normals)) pyassimp.release(scene) #np.save(out_file, attributes) return attributes
def __init__(self,x=0,y=0,z=0,w=1,h=1,d=1): super().__init__() self.x = x self.y = y self.z = z self.w = w self.h = h self.d = d self.set_shaders('res/glsl/suzanne.vs','res/glsl/suzanne.fs') scene = load('res/model/suzanne.obj') self._vertex = scene.meshes[0].vertices self._normal = scene.meshes[0].normals self._index = scene.meshes[0].faces self._vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self._vertex_buffer) glBufferData(GL_ARRAY_BUFFER, self._vertex.nbytes, self._vertex, GL_STATIC_DRAW) self._normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self._normal_buffer) glBufferData(GL_ARRAY_BUFFER, self._normal.nbytes, self._normal, GL_STATIC_DRAW) self._element_buffer = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._element_buffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, self._index.nbytes, self._index, GL_STATIC_DRAW)
def load_model(self, filename=None): flatten = itertools.chain.from_iterable try: with pyassimp.load("./res/models/" + filename) as model_details: count = 0 total_verts = [] for detail in model_details.meshes: tempChild = MeshChild( self.get_name() + str(count), list(flatten(detail.vertices)), list(flatten(detail.normals)), list(flatten(list(flatten(detail.texturecoords)))), list(flatten(detail.faces)), detail.material) tempChild.shader.load_vert_source(self._shader_name + ".vert.glsl") tempChild.shader.load_frag_source(self._shader_name + ".frag.glsl") tempChild.shader.init() tempChild.model = self.model self._children.append(tempChild) total_verts += list(flatten(detail.vertices)) count += 1 centroid = self.calculate_centroid(total_verts) self.centroid = centroid self.calc_model_matrix() # TODO add model matrix to parent so we can use centroid for calcs later on for child in self._children: child.set_centroid(centroid) child.setup() except Exception as e: print("ERROR: ", e)
def load_object(self, path): logger.info('Loading object: ' + path) self.obj = pyassimp.load(path) obj = self.obj logger.info(" meshes: %d" % len(obj.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in obj.meshes])) logger.info(" materials: %d" % len(obj.materials))
def load_meshes(obj_files, vertex_tmp_store_folder, recalculate_normals=False): md5_string = str(''.join(obj_files) + 'load_meshes' + str(recalculate_normals)) md5_string = md5_string.encode('utf-8') # ('utf-8') hashed_file_name = hashlib.md5(md5_string).hexdigest() + '.pickle' out_file = os.path.join(vertex_tmp_store_folder, hashed_file_name) print(md5_string) print(hashed_file_name) if os.path.exists(out_file): loaded_obj = ae_utils.load_pickled_data(out_file) return loaded_obj else: bar = progressbar.ProgressBar() attributes = [] for model_path in bar(obj_files): scene = pyassimp.load(model_path, pyassimp.postprocess.aiProcess_Triangulate) mesh = scene.meshes[0] vertices = mesh.vertices normals = calc_normals( vertices) if recalculate_normals else mesh.normals attributes.append((vertices, normals)) pyassimp.release(scene) ae_utils.save_pickled_data(attributes, out_file) return attributes
def __init__(self, filename): self.filename = filename self.done = False self.triangles = [] scene = pyassimp.load(self.filename, pyassimp.postprocess.aiProcess_Triangulate) if scene: for index, mesh in enumerate(scene.meshes): for num in range(len(mesh.faces)): face = mesh.faces[num] if face.size == 3: vertex = [glm.vec3(), glm.vec3(), glm.vec3()] vertex[0].x = mesh.vertices[face[0], 0] vertex[0].y = mesh.vertices[face[0], 1] vertex[0].z = mesh.vertices[face[0], 2] vertex[1].x = mesh.vertices[face[1], 0] vertex[1].y = mesh.vertices[face[1], 1] vertex[1].z = mesh.vertices[face[1], 2] vertex[2].x = mesh.vertices[face[2], 0] vertex[2].y = mesh.vertices[face[2], 1] vertex[2].z = mesh.vertices[face[2], 2] self.triangles.append(triangle.Triangle(glm.vec3(vertex[0].x, vertex[0].y, vertex[0].z), glm.vec3(vertex[1].x, vertex[1].y, vertex[1].z), glm.vec3(vertex[2].x, vertex[2].y, vertex[2].z), material.Material())) self.done = True
def __init__(self, mesh, width=800, height=600, znear=0.1, zfar=10000.0): self.window_width = width self.window_height = height # Load mesh if mesh == 'cube': self.vertices, self.indices = cube() self.colors = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1], [0, 0, 0]] else: mesh = pyassimp.load(mesh) self.vertices = mesh.meshes[0].vertices self.normals = mesh.meshes[0].normals self.uvs = mesh.meshes[0].texturecoords[0, :, 1::-1] self.indices = mesh.meshes[0].faces self.colors = np.random.rand(*self.vertices.shape) # move scene back a little mean = np.mean(self.vertices, axis=0) stddev = np.std(self.vertices, axis=0) self.view = translation(-mean + [0, 0, stddev[2] * 8]) self.proj = perspective(np.radians(90.0), width / height, znear, zfar) self.start_time = 0.0 self.last_time = 0.0
def __init__(self): #Drawing rectangle self.drawing_area = np.array([-1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0], dtype='float32') self.shaderProg = GLuint self.vbo = GLuint self.ebo = GLuint self.uniforms = dict() self.BSPloaded = 1 self.m_button = [False, False, False, False] self.m_oldpos = [0,0] self.m_pan = [0,0] self.shiftval = 0.0 self.aspect = 1 self.adder = 0.01 self.OBJmodel = assimp.load("tris.obj") self.triangle = np.array([0.0, 0.5, 0.0, 0.5, -0.5,0.0, -0.5, -0.5, 0.0], dtype='float32') # row-major self.matrix = np.array([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0], dtype='float32') #self.OBJmodel.meshes[0].vertices #np.array([0.0,0.5,0.5,-0.5,-0.5,-0.5], dtype='float32') # self.triangle = np.reshape(self.triangle, (len(self.triangle)*3)) print (self.triangle) self.initialize()
def make_mesh(name, pose, filename, scale=(1, 1, 1)): ''' returns a CollisionObject with the mesh defined in the path. mostly copied from https://github.com/ros-planning/moveit_commander/blob/kinetic-devel/src/moveit_commander/planning_scene_interface.py ''' print("Creating mesh with file from", filename) co = CollisionObject() scene = pyassimp.load(filename) if not scene.meshes: raise MoveItCommanderException("There are no meshes in the file") co.operation = CollisionObject.ADD co.id = name co.header = pose.header mesh = Mesh() for face in scene.meshes[0].faces: triangle = MeshTriangle() if len(face) == 3: triangle.vertex_indices = [face[0], face[1], face[2]] mesh.triangles.append(triangle) for vertex in scene.meshes[0].vertices: point = Point() point.x = vertex[0] * scale[0] point.y = vertex[1] * scale[1] point.z = vertex[2] * scale[2] mesh.vertices.append(point) co.meshes = [mesh] co.mesh_poses = [pose.pose] pyassimp.release(scene) return co
def stl_to_mesh(filename, scale=(1, 1, 1)): mesh = Mesh() scene = pyassimp.load(filename) first_face = scene.meshes[0].faces[0] if hasattr(first_face, '__len__'): for face in scene.meshes[0].faces: if len(face) == 3: triangle = MeshTriangle() triangle.vertex_indices = [face[0], face[1], face[2]] mesh.triangles.append(triangle) elif hasattr(first_face, 'indices'): for face in scene.meshes[0].faces: if len(face.indices) == 3: triangle = MeshTriangle() triangle.vertex_indices = [ face.indices[0], face.indices[1], face.indices[2] ] mesh.triangles.append(triangle) else: raise MoveItCommanderException( "Unable to build triangles from mesh due to mesh object structure") for vertex in scene.meshes[0].vertices: point = Point() point.x = vertex[0] * scale[0] point.y = vertex[1] * scale[1] point.z = vertex[2] * scale[2] mesh.vertices.append(point) pyassimp.release(scene) return mesh
def make_mesh(self, co, pose, filename, scale=(1.0, 1.0, 1.0)): try: scene = pyassimp.load(filename) except AssimpError as e: rospy.logerr("Assimp error: %s", e) return False if not scene.meshes: raise MoveItCommanderException("There are no meshes in the file") mesh = Mesh() for face in scene.meshes[0].faces: triangle = MeshTriangle() if len(face.indices) == 3: triangle.vertex_indices = [ face.indices[0], face.indices[1], face.indices[2] ] mesh.triangles.append(triangle) for vertex in scene.meshes[0].vertices: point = Point() point.x = vertex[0] * scale[0] point.y = vertex[1] * scale[1] point.z = vertex[2] * scale[2] mesh.vertices.append(point) if not isinstance(co.meshes, list): co.meshes = [] co.meshes += [mesh] if not isinstance(co.mesh_poses, list): co.mesh_poses = [] co.mesh_poses += [pose.pose] pyassimp.release(scene) return co
def main(): if len(sys.argv) != 2: print(f'{sys.argv[0]} <file type>', file=sys.stderr) return 1 tex_pairs = os.getenv('SOBJ_TEX_MAP', '').split(',') tex_map = {} for pair in tex_pairs: split_pair = pair.split('=') if len(split_pair) != 2: continue tex_map[split_pair[0]] = split_pair[1] with pyassimp.load(sys.stdin.buffer, file_type=sys.argv[1], processing= aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_GenSmoothNormals | aiProcess_SortByPType | aiProcess_FlipUVs | aiProcess_CalcTangentSpace ) as scene: converter = Converter(scene, tex_map=tex_map, skip_textures=bool(os.getenv('SOBJ_SKIP_TEXTURES'))) obj = converter.convert() if os.getenv('SOBJ_TEXT'): text_format.PrintMessage(obj, sys.stdout) else: sys.stdout.buffer.write(obj.SerializeToString()) return 0
def load_meshes(obj_files, vertex_tmp_store_folder, recalculate_normals=False): hashed_file_name = hashlib.md5( (''.join(obj_files) + 'load_meshes' + str(recalculate_normals)).encode('utf-8')).hexdigest() + '.npy' out_file = os.path.join(vertex_tmp_store_folder, hashed_file_name) if os.path.exists(out_file): return np.load(out_file, allow_pickle=True) else: bar = progressbar.ProgressBar() attributes = [] for model_path in bar(obj_files): scene = pyassimp.load(model_path, pyassimp.postprocess.aiProcess_Triangulate) mesh = scene.meshes[0] vertices = [] for face in mesh.faces: vertices.extend([ mesh.vertices[face[0]], mesh.vertices[face[1]], mesh.vertices[face[2]] ]) vertices = np.array(vertices) # vertices = mesh.vertices normals = calc_normals( vertices) if recalculate_normals else mesh.normals attributes.append((vertices, normals)) pyassimp.release(scene) if not os.path.exists(vertex_tmp_store_folder): os.makedirs(vertex_tmp_store_folder) np.save(out_file, attributes) return attributes
def __init__(self): super().__init__() self._tex = texture.load('res/texture/eye.bmp') scene = load('res/model/sphere.obj') mesh = scene.meshes[0] self._vertex = mesh.vertices self._uv = mesh.texturecoords self._normal = mesh.normals self._index = mesh.faces self._vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self._vertex_buffer) glBufferData(GL_ARRAY_BUFFER, self._vertex.nbytes, self._vertex, GL_STATIC_DRAW) self._uv_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self._uv_buffer) glBufferData(GL_ARRAY_BUFFER, self._uv.nbytes, self._uv, GL_STATIC_DRAW) self._normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self._normal_buffer) glBufferData(GL_ARRAY_BUFFER, self._normal.nbytes, self._normal, GL_STATIC_DRAW) self._element_buffer = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._element_buffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, self._index.nbytes, self._index, GL_STATIC_DRAW)
def load(self, filePath): self.geo = Mesh() scene = pyassimp.load(filePath, processing=import_flags) norms = None uvs = None for mesh in scene.meshes: offset = self.geo.getNumVertexes() self.geo.addVertices(mesh.vertices) for vts in mesh.faces: self.geo.mesh.add_face([self.geo.mesh.vertex_handle(i + offset) for i in vts if i >= 0]) normals = mesh.normals if normals.shape[0] > 0: if norms is None: norms = [normals] else: norms.append(normals) elif norms is not None: norms.append(np.zeros((len(mesh.vertices), 3))) texcoords = mesh.texturecoords if texcoords.shape[0] > 0: if uvs is None: uvs = [texcoords[0]] else: uvs.append(texcoords[0]) elif uvs is not None: uvs.append(np.zeros((len(mesh.vertices), 3))) if norms is not None: self.geo.setVertexAttribData('normal', np.vstack(norms), attribType='vector3', defaultValue=[0, 0, 0]) if uvs is not None: self.geo.setVertexAttribData('uv', np.vstack(uvs), attribType='vector3', defaultValue=[0, 0, 0]) pyassimp.release(scene)
def load(file): """ load resources from file using pyassimp, return list of ColorMesh """ try: option = pyassimp.postprocess.aiProcessPreset_TargetRealtime_MaxQuality scene = pyassimp.load(file, option) except pyassimp.errors.AssimpError: print('ERROR: pyassimp unable to load', file) return [] # error reading => return empty list # reorganize and keep only first material properties of each for mat in scene.materials: mat.tokens = dict(reversed(list(mat.properties.items()))) # prepare mesh nodes meshes = [] for mesh in scene.meshes: mat = scene.materials[mesh.materialindex].tokens node = Node(Kd=mat.get('diffuse', (1, 1, 1)), Ka=mat.get('ambient', (0, 0, 0)), Ks=mat.get('specular', (1, 1, 1)), s=mat.get('shininess', 16.)) node.add(PhongMesh([mesh.vertices, mesh.normals], mesh.faces)) meshes.append(node) size = sum((mesh.faces.shape[0] for mesh in scene.meshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(scene.meshes), size)) pyassimp.release(scene) return meshes
def convert_gltf2xxx(start_response, model_name, filename, format): ''' Call the conversion code to convert GLTF string to a certain format :param start_response: function call required to create a response :param model_name: name of model :param filename: filename of GLTF file to be converted :param format: string indicating what format to convert to, e.g. 'DXF' :returns: a response that can be returned from the 'application()' function ''' # Use model name and file name to get full GLTF file path gltf_path = find_gltf(model_name, filename) if not gltf_path: LOGGER.error("Cannot find %s", gltf_path) return make_str_response(start_response, ' ') # Load GLTF file try: assimp_obj = pyassimp.load(gltf_path, 'gltf2') except AssimpError as ae: LOGGER.error("Cannot load %s:%s", gltf_path, str(ae)) return make_str_response(start_response, ' ') # Export as whatever format desired try: blob_obj = pyassimp.export_blob(assimp_obj, format, processing=None) except AssimpError as ae: LOGGER.error("Cannot export %s:%s", gltf_path, str(ae)) return make_str_response(start_response, ' ') return send_blob(start_response, model_name, 'export_{0}_{1}'.format(model_name, filename), blob_obj, 60.0)
def __init__(self, obj_file, material_file=None, load_materials=True, name_prefix='', name_suffix='', materials_scale=1.0): if material_file is not None: logging.error( 'Ignoring material file input, reading them off obj file.') load_flags = self.get_pyassimp_load_options() scene = assimp.load(obj_file, processing=load_flags) filter_ind = self._filter_triangles(scene.meshes) self.meshes = [scene.meshes[i] for i in filter_ind] for i, m in enumerate(self.meshes): m.name = name_prefix + m.name + '_{:05d}'.format(i) + name_suffix logging.info('#Meshes: %d', len(self.meshes)) dir_name = os.path.dirname(obj_file) # Load materials materials = [None for _ in self.meshes] if load_materials: materials = self.load_materials(self.meshes, dir_name, materials_scale) self.scene = scene self.materials = materials
def main(filename=None): filename = filename or DEFAULT_MODEL scene = pyassimp.load(filename) #the model we load print "MODEL:", filename print #write some statistics print "SCENE:" print " meshes:", len(scene.meshes) print " materials:", len(scene.materials) print " textures:", len(scene.textures) print print "NODES:" recur_node(scene.rootnode) print print "MESHES:" for index, mesh in enumerate(scene.meshes): print " MESH", index+1 print " material id:", mesh.materialindex+1 print " vertices:", len(mesh.vertices) print " first 3 verts:", mesh.vertices[:3] if mesh.normals: print " first 3 normals:", mesh.normals[:3] else: print " no normals" print " colors:", len(mesh.colors) tc = mesh.texturecoords if tc: print " texture-coords 1:", len(tc[0]), "first3:", tc[0][:3] print " texture-coords 2:", len(tc[1]), "first3:", tc[1][:3] print " texture-coords 3:", len(tc[2]), "first3:", tc[2][:3] print " texture-coords 4:", len(tc[3]), "first3:", tc[3][:3] else: print " no texture coordinates" print " uv-component-count:", len(mesh.numuvcomponents) print " faces:", len(mesh.faces), "first:", [f.indices for f in mesh.faces[:3]] print " bones:", len(mesh.bones), "first:", [str(b) for b in mesh.bones[:3]] print print "MATERIALS:" for index, material in enumerate(scene.materials): print(" MATERIAL (id:" + str(index+1) + ")") for key, value in material.properties.items(): print " %s: %s" % (key, value) print print "TEXTURES:" for index, texture in enumerate(scene.textures): print " TEXTURE", index+1 print " width:", texture.width print " height:", texture.height print " hint:", texture.achformathint print " data (size):", len(texture.data) # Finally release the model pyassimp.release(scene)
def main(filename=None): scene = pyassimp.load(filename, pyassimp.postprocess.aiProcess_Triangulate) #the model we load print("MODEL:" + filename) print #write some statistics print("SCENE:") print(" meshes:" + str(len(scene.meshes))) print(" materials:" + str(len(scene.materials))) print(" textures:" + str(len(scene.textures))) print print("NODES:") recur_node(scene.rootnode) print print("MESHES:") for index, mesh in enumerate(scene.meshes): print(" MESH" + str(index+1)) print(" material id:" + str(mesh.materialindex+1)) print(" vertices:" + str(len(mesh.vertices))) print(" first 3 verts:\n" + str(mesh.vertices[:3])) if mesh.normals.any(): print(" first 3 normals:\n" + str(mesh.normals[:3])) else: print(" no normals") print(" colors:" + str(len(mesh.colors))) tcs = mesh.texturecoords if tcs.any(): for index, tc in enumerate(tcs): print(" texture-coords "+ str(index) + ":" + str(len(tcs[index])) + "first3:" + str(tcs[index][:3])) else: print(" no texture coordinates") print(" uv-component-count:" + str(len(mesh.numuvcomponents))) print(" faces:" + str(len(mesh.faces)) + " -> first:\n" + str(mesh.faces[:3])) print(" bones:" + str(len(mesh.bones)) + " -> first:" + str([str(b) for b in mesh.bones[:3]])) print print("MATERIALS:") for index, material in enumerate(scene.materials): print(" MATERIAL (id:" + str(index+1) + ")") for key, value in material.properties.items(): print(" %s: %s" % (key, value)) print print("TEXTURES:") for index, texture in enumerate(scene.textures): print(" TEXTURE" + str(index+1)) print(" width:" + str(texture.width)) print(" height:" + str(texture.height)) print(" hint:" + str(texture.achformathint)) print(" data (size):" + str(len(texture.data))) # Finally release the model pyassimp.release(scene)
def main(filename=None): scene = pyassimp.load(filename, processing=pyassimp.postprocess.aiProcess_Triangulate) #the model we load print("MODEL:" + filename) print #write some statistics print("SCENE:") print(" meshes:" + str(len(scene.meshes))) print(" materials:" + str(len(scene.materials))) print(" textures:" + str(len(scene.textures))) print print("NODES:") recur_node(scene.rootnode) print print("MESHES:") for index, mesh in enumerate(scene.meshes): print(" MESH" + str(index+1)) print(" material id:" + str(mesh.materialindex+1)) print(" vertices:" + str(len(mesh.vertices))) print(" first 3 verts:\n" + str(mesh.vertices[:3])) if mesh.normals.any(): print(" first 3 normals:\n" + str(mesh.normals[:3])) else: print(" no normals") print(" colors:" + str(len(mesh.colors))) tcs = mesh.texturecoords if tcs.any(): for tc_index, tc in enumerate(tcs): print(" texture-coords "+ str(tc_index) + ":" + str(len(tcs[tc_index])) + "first3:" + str(tcs[tc_index][:3])) else: print(" no texture coordinates") print(" uv-component-count:" + str(len(mesh.numuvcomponents))) print(" faces:" + str(len(mesh.faces)) + " -> first:\n" + str(mesh.faces[:3])) print(" bones:" + str(len(mesh.bones)) + " -> first:" + str([str(b) for b in mesh.bones[:3]])) print print("MATERIALS:") for index, material in enumerate(scene.materials): print(" MATERIAL (id:" + str(index+1) + ")") for key, value in material.properties.items(): print(" %s: %s" % (key, value)) print print("TEXTURES:") for index, texture in enumerate(scene.textures): print(" TEXTURE" + str(index+1)) print(" width:" + str(texture.width)) print(" height:" + str(texture.height)) print(" hint:" + str(texture.achformathint)) print(" data (size):" + str(len(texture.data))) # Finally release the model pyassimp.release(scene)
def fromFile(cls, fname): aiModel = imp.load(fname) model = cls(aiModel) # model.generateBuffers() assert (len(model.meshBuffers) == 0) for mesh in model.aiModel.meshes: model.meshBuffers.append(MeshBuffer.fromMesh(mesh)) return model
def __init__(self): asset = pyassimp.load("assets/obj/spider.obj", processing=pyassimp_processing_flags) super(Spider, self).__init__(asset) self.rotate((0., pi / 2, 0.)) self.translate((-0.05, 0., 0.)) self.scale((.01, .01, .01))
def fromFile(cls, fname): aiModel = imp.load(fname) model = cls(aiModel) # model.generateBuffers() assert len(model.meshBuffers) == 0 for mesh in model.aiModel.meshes: model.meshBuffers.append(MeshBuffer.fromMesh(mesh)) return model
def add_model(self, name, path, texture_path=None, offset=None, color=None, parent=None, postprocess = aiProcessPreset_TargetRealtime_MaxQuality): logger.info("Loading model " + name + ":" + path + "...") if postprocess: scene = pyassimp.load(path, postprocess) else: scene = pyassimp.load(path) logger.info("Done.") #log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) bb_min, bb_max = get_bounding_box(scene) for i in range(3): self.bb_min[i] = min(self.bb_min[i], bb_min[i]) self.bb_max[i] = max(self.bb_max[i], bb_max[i]) logger.info(" bounding box:" + str(self.bb_min) + " - " + str(self.bb_max)) logger.info(" textures: %d" % len(scene.textures)) scene_center = [(a + b) / 2. for a, b in zip(self.bb_min, self.bb_max)] for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) logger.info(" mesh %d: tex coords %d, uv components %d" % (index, len(mesh.texturecoords), len(mesh.numuvcomponents))) # Finally release the model pyassimp.release(scene) # and load texture if texture_path: print "TEXTURE LOADED" texture = self.TexFromPNG(texture_path) else: texture = None logger.info("Done loading model " + name + "!") if offset is None: offset = [0,0,0,0,0,0] if color is None: color = [1.0,1.0,1.0,1.0] self.models[name] = [scene, texture, offset, parent, color, color] #second color is defualt oclor
def load_textured(file): """ load resources using pyassimp, return list of TexturedMeshes """ try: option = pyassimp.postprocess.aiProcessPreset_TargetRealtime_MaxQuality scene = pyassimp.load(file, option) except pyassimp.errors.AssimpError: print('ERROR: pyassimp unable to load', file) return [] # error reading => return empty list # Note: embedded textures not supported at the moment path = os.path.dirname(file) path = os.path.join('.', '') if path == '' else path for mat in scene.materials: mat.tokens = dict(reversed(list(mat.properties.items()))) if 'file' in mat.tokens: # texture file token tname = mat.tokens['file'].split('/')[-1].split('\\')[-1] # search texture in file's whole subdir since path often screwed up tname = [ os.path.join(d[0], f) for d in os.walk(path) for f in d[2] if tname.startswith(f) or f.startswith(tname) ] if tname: mat.texture = tname[0] else: print('Failed to find texture:', tname) # prepare textured mesh meshes = [] for mesh in scene.meshes: try: texture = scene.materials[mesh.materialindex].texture # tex coords in raster order: compute 1 - y to follow OpenGL convention tex_uv = ((0, 1) + mesh.texturecoords[0][:, :2] * (1, -1) if mesh.texturecoords.size else None) # create the textured mesh object from texture, attributes, and indices meshes.append( TexturedMesh(texture, [mesh.vertices, tex_uv], mesh.faces)) except: print("Error, no texture found") mat = scene.materials[mesh.materialindex].tokens node = Node(K_d=mat.get('diffuse', (1, 1, 1)), K_a=mat.get('ambient', (0, 0, 0)), K_s=mat.get('specular', (1, 1, 1)), s=mat.get('shininess', 16.)) node.add(PhongMesh([mesh.vertices, mesh.normals], mesh.faces)) meshes.append(node) size = sum((mesh.faces.shape[0] for mesh in scene.meshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(scene.meshes), size)) pyassimp.release(scene) return meshes
def __init__(self, obj_file, material_file=None, load_materials=True, name_prefix='', name_suffix='', materials_scale=1.0): if material_file is not None: logging.error( 'Ignoring material file input, reading them off obj file.') load_flags = self.get_pyassimp_load_options() scene = assimp.load(obj_file, processing=load_flags) filter_ind = self._filter_triangles(scene.meshes) self.meshes = [scene.meshes[i] for i in filter_ind] for i, m in enumerate(self.meshes): m.name = name_prefix + m.name + '_{:05d}'.format(i) + name_suffix # logging.error('#Meshes: %d', len(self.meshes)) print('\033[35m', "Number of Meshes:", len(self.meshes), '\033[0m') dir_name = os.path.dirname(obj_file) # Load materials materials = None if load_materials: materials = [] for m in self.meshes: #file_name = os.path.join(dir_name, m.material.properties[('file', 1)]) file_name = os.path.join( dir_name, sorted(glob.glob1(dir_name, '*.jpg'))[i]) # assert(os.path.exists(file_name)), 'Texture file {:s} foes not exist.'.format(file_name) if (not (os.path.exists(file_name))): print('\033[31m', "Texture file", file_name, "does not exist.", '\033[0m') sys.exit(1) img_rgb = cv2.imread(file_name)[::-1, :, ::-1] if img_rgb.shape[0] != img_rgb.shape[1]: logging.warn('Texture image not square.') sz = np.maximum(img_rgb.shape[0], img_rgb.shape[1]) sz = int(np.power(2., np.ceil(np.log2(sz)))) sz = int(sz * materials_scale) img_rgb = cv2.resize(img_rgb, (sz, sz), interpolation=cv2.INTER_LINEAR) else: sz = img_rgb.shape[0] sz_ = int(np.power(2., np.ceil(np.log2(sz)))) if sz != sz_ or materials_scale != 1.: logging.warn( 'Texture image not square of power of 2 size or ' + 'materials_scale is not 1.0. Changing size from %d to %d.', sz, int(sz_ * materials_scale)) sz = int(sz_ * materials_scale) img_rgb = cv2.resize(img_rgb, (sz, sz), interpolation=cv2.INTER_LINEAR) materials.append((file_name, img_rgb)) self.scene = scene print('\033[32m', "All meshes successfully loaded", '\033[0m') self.materials = materials
def read(self, filename): log.debug("Importing %s with assimp...", filename) scene = pyassimp.load(filename) log.debug("Meshes: %d", len(scene.meshes)) log.debug("Mateirals: %d", len(scene.materials)) log.debug("Textures: %d", len(scene.textures)) log.critical("ASSIMP NOT FINISHED!!") return None
def load_model(self, path, postprocess=aiProcessPreset_TargetRealtime_MaxQuality): logger.info("Loading model:" + path + "...") if postprocess: self.scene = pyassimp.load(path, postprocess) else: self.scene = pyassimp.load(path) logger.info("Done.") scene = self.scene # log some statistics logger.info(" meshes: %d" % len(scene.meshes)) logger.info(" total faces: %d" % sum([len(mesh.faces) for mesh in scene.meshes])) logger.info(" materials: %d" % len(scene.materials)) for index, mesh in enumerate(scene.meshes): self.prepare_gl_buffers(mesh) self.putTextures(scene.meshes, scene.materials) pyassimp.release(scene) logger.info("Ready for 3D rendering!")
def load_model(self,path): """Load model from the specified path @param path : Location of the model in the directory """ self.__scene = pyassimp.load(path) scene = self.__scene for index, mesh in enumerate(scene.meshes): self.__prepare_gl_buffers(mesh) pyassimp.release(scene) pass
def __init__(self, source): # super(AssimpObjLoader, **kwargs) # source = kwargs.get('source', '') if not source: print "no source given!" return self.scene = scene = load( source, 0 | postprocess.aiProcess_Triangulate | postprocess.aiProcess_SplitLargeMeshes | postprocess.aiProcess_GenNormals ) self.objects = {} for i, mesh in enumerate(scene.meshes): self.objects[i] = AssimpMesh(scene, mesh)
def __enter__(self): scene = pyassimp.load(self._path) mesh = scene.meshes[0] self._vao = glGenVertexArrays(1) self._vbo = glGenBuffers(1) self._ebo = glGenBuffers(1) glBindVertexArray(self._vao) vertices = array( 'f', [component for vertex in mesh.vertices for component in vertex], ) glBindBuffer(GL_ARRAY_BUFFER, self._vbo) glBufferData( GL_ARRAY_BUFFER, vertices.tostring(), GL_STATIC_DRAW, ) indices = array( 'L', [component for face in mesh.faces for component in face], ) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._ebo) glBufferData( GL_ELEMENT_ARRAY_BUFFER, indices.tostring(), GL_STATIC_DRAW, ) self._length = len(indices) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) # free resources pyassimp.release(scene) return self._draw
def loadModel(self, path): scene = assimp.load(path, processing=(assimp.postprocess.aiProcess_Triangulate | assimp.postprocess.aiProcess_FlipUVs | assimp.postprocess.aiProcess_CalcTangentSpace)) if not scene: raise Exception("ASSIMP can't load model") self.directory = os.path.dirname(path) for mesh in scene.meshes: self.meshes.append(Mesh(mesh, self.directory)) assimp.release(scene) # self.__processNode(scene) # # def __processNode(self, scene): # for mesh in scene.meshes: # self.meshes.append(Mesh(mesh)) # # assimp.release(scene)
def __init__(self, obj_file, material_file=None, load_materials=True, name_prefix='', name_suffix=''): if material_file is not None: logging.error('Ignoring material file input, reading them off obj file.') load_flags = self.get_pyassimp_load_options() scene = assimp.load(obj_file, processing=load_flags) filter_ind = self._filter_triangles(scene.meshes) self.meshes = [scene.meshes[i] for i in filter_ind] for m in self.meshes: m.name = name_prefix + m.name + name_suffix dir_name = os.path.dirname(obj_file) # Load materials materials = None if load_materials: materials = [] for m in self.meshes: file_name = os.path.join(dir_name, m.material.properties[('file', 1)]) assert(os.path.exists(file_name)), \ 'Texture file {:s} foes not exist.'.format(file_name) img_rgb = cv2.imread(file_name)[::-1,:,::-1] if img_rgb.shape[0] != img_rgb.shape[1]: logging.warn('Texture image not square.') sz = np.maximum(img_rgb.shape[0], img_rgb.shape[1]) sz = int(np.power(2., np.ceil(np.log2(sz)))) img_rgb = cv2.resize(img_rgb, (sz,sz), interpolation=cv2.INTER_LINEAR) else: sz = img_rgb.shape[0] sz_ = int(np.power(2., np.ceil(np.log2(sz)))) if sz != sz_: logging.warn('Texture image not square of power of 2 size. ' + 'Changing size from %d to %d.', sz, sz_) sz = sz_ img_rgb = cv2.resize(img_rgb, (sz,sz), interpolation=cv2.INTER_LINEAR) materials.append(img_rgb) self.scene = scene self.materials = materials
def loadColladaModel(filename): """ Load the Collada modle created in Blender. This function makes the following hard coded assumptions about that file: * It contains a node called 'Parent' * That parent contains a mesh called 'MainBody'. """ # Load the scene. scene = pyassimp.load(filename) # Find the node called 'Parent' (hard coded assumption that must be matched # by Blender model). p = None print('\nModel file contains the following meshes:') for child in scene.rootnode.children: print(' *', child.name) if child.name == 'Parent': p = child # The Parent node must exist, and it must contain one mesh called # 'MainBody'. assert p is not None objs = {_.name: _ for _ in p.children} assert 'MainBody' in objs # For later: compute the inverse transform of MainBody. scale, i_transform = inverseTransform(objs['MainBody'].transformation) frags, cshapes = {}, {} for name in objs: # 4x4 transformation matrix for current mesh (this is always in global # coordinates, not relative to anything). t = np.array(objs[name].transformation) # Vertices of current mesh (Nx3). vert = objs[name].meshes[0].vertices # Transpose vertex matrix to obtain the 3xN matrix. Then add a row of # 1s to obtain a 4xN matrix. vert = vert.T vert = np.vstack((vert, np.ones(vert.shape[1]))) # Scale/rotatate/translate the vertices relative to the position of the # MainBody. Then drop the (auxiliary) last row again to get back to a # Nx3 matrix of vertices. vert = i_transform.dot(t.dot(vert)) vert = vert[:-1, :].T # Flatten the vertex matrix into a simple list and compile it into a # fragment. vert = vert.flatten() frags[name] = demolib.getFragMetaRaw(vert, uv=[], rgb=[], scale=1) # All bodies whose name starts with 'cs' get a spherical collision # shape. if name.lower().startswith('cs'): # Compute the combined transformation matrix that represents the # difference between the MainBody's position and this one. To find # this, simpy apply the invers transform of the MainBody to the # transform of the locat body. The latter would move the current # object to its correct position in world coordinates, and the # former will undo offset and rotation of the MainBody. t = i_transform.dot(t) # Determine the position. # Fixme: also determine the quaternion and scale from the total # transformation matrix. _pos = tuple(t[:3, 3].tolist()) _rot = (0, 0, 0, 1) # Create a spherical collision shape and place it relative to the # MainBody. sphere = aztypes.CollShapeSphere(1) cshapes[name] = aztypes.CollShapeMeta('sphere', _pos, _rot, sphere) return frags, cshapes
def load_from_file(path): path_cache = path + '.geomcache' try: fcache = open(path_cache, 'rb') attribs_bytes, indices_bytes, aabb_min, aabb_max, numverts, numtris = cPickle.load(fcache) attribs = (DefaultAttribStruct * numverts).from_buffer(attribs_bytes) indices = (GLuint * numtris).from_buffer(indices_bytes) aabb_min = Vector(*aabb_min) aabb_max = Vector(*aabb_max) return Geometry(attribs, indices, AABB(aabb_min, aabb_max)) except : logging.warn('Failed to load geometry ' + path + ' from cache') scene = pyassimp.load(path, pyassimp.postprocess.aiProcessPreset_TargetRealtime_Quality) mesh = scene.meshes[0] if len(mesh.vertices) == 0: return None attribs = (DefaultAttribStruct * len(mesh.vertices))() indices = (GLuint * (len(mesh.faces) * 3))() # UV layers uv0 = (0.0, 0.0) uvlayers = 0 if mesh.numuvcomponents[0] >= 2: uvlayers += 1 v0 = mesh.vertices[0] aabb_min = Vector(v0[0], v0[1], v0[2]) aabb_max = Vector(v0[0], v0[1], v0[2]) # Fill attributes for idx in range(len(mesh.vertices)): vertex = mesh.vertices[idx] normal = mesh.normals[idx] tangent = mesh.tangents[idx] bitangent = mesh.bitangents[idx] if uvlayers != 0: uv0 = mesh.texturecoords[0][idx] # Build the AABB if vertex[0] < aabb_min.x: aabb_min.x = vertex[0] if vertex[1] < aabb_min.y: aabb_min.y = vertex[1] if vertex[2] < aabb_min.z: aabb_min.z = vertex[2] if vertex[0] > aabb_max.x: aabb_max.x = vertex[0] if vertex[1] > aabb_max.y: aabb_max.y = vertex[1] if vertex[2] > aabb_max.z: aabb_max.z = vertex[2] attribs[idx].position.x = vertex[0] attribs[idx].position.y = vertex[1] attribs[idx].position.z = vertex[2] attribs[idx].normal.x = normal[0] attribs[idx].normal.y = normal[1] attribs[idx].normal.z = normal[2] attribs[idx].tangent.x = tangent[0] attribs[idx].tangent.y = tangent[1] attribs[idx].tangent.z = tangent[2] attribs[idx].bitangent.x = bitangent[0] attribs[idx].bitangent.y = bitangent[1] attribs[idx].bitangent.z = bitangent[2] attribs[idx].uv0.x = uv0[0] attribs[idx].uv0.y = uv0[1] # Create indices array for idx, f in enumerate(mesh.faces): assert len(f) == 3 indices[idx * 3 + 0] = f[0] indices[idx * 3 + 1] = f[1] indices[idx * 3 + 2] = f[2] with open(path_cache, 'wb') as fcache: geom_cache = (bytearray(attribs), bytearray(indices), aabb_min.vals, aabb_max.vals, len(mesh.vertices), len(mesh.faces)*3, ) cPickle.dump(geom_cache, fcache, -1) return Geometry(attribs, indices, AABB(aabb_min, aabb_max))
def loadAssimpSceneFromFile(inFile): baseDir = os.path.dirname(inFile) scene = pyassimp.load(inFile, pyassimp.postprocess.aiProcess_Triangulate) return AssimpScene(scene, baseDir)
def doImportPy(): global path, scene scene = load(pt.join(home, path), processing=flags2)
def convert(self, obj, options): processing = (aiProcess_Triangulate|aiProcessPreset_TargetRealtime_MaxQuality|aiProcess_FlipUVs) if obj.GetStaticBatch(): processing = (aiProcess_Triangulate|aiProcessPreset_TargetRealtime_MaxQuality|aiProcess_FlipUVs|aiProcess_PreTransformVertices) scene = pyassimp.load(obj.GetPath( True ), processing = processing) #the model we load print print("MODEL:" + str(obj)) print #write some statistics print("SCENE:") print(" meshes:" + str(len(scene.meshes))) print(" materials:" + str(len(scene.materials))) print(" textures:" + str(len(scene.textures))) print materials = [] print("MATERIALS:") for index, material in enumerate(scene.materials): print(" MATERIAL (id:" + str(index+1) + ")") path = "" matName = "" for key, value in material.properties.items(): print(" %s: %s" % (key, value)) if key == "file": path = value elif key == "name": matName = value mat = { "id" : index+1, "file" : os.path.basename(path), "path" : path, "name" : matName, } materials.append(mat) print signals.emitNow( 'mesh.assimp_materials', materials ) print("TEXTURES:") for index, texture in enumerate(scene.textures): print(" TEXTURE" + str(index+1)) print(" width:" + str(texture.width)) print(" height:" + str(texture.height)) print(" hint:" + str(texture.achformathint)) print(" data (size):" + str(len(texture.data))) print("MESHES:") meshCount = len(scene.meshes) for index, mesh in enumerate(scene.meshes): if meshCount == 1: mesh.name = obj.GetExportName() else: mesh.name = "{}{}".format(obj.GetExportName(),index+1) print(" MESH id: " + str(index+1) + " (" + str(mesh.name) + ")") print(" material id: " + str(mesh.materialindex+1)) print(" vertices: " + str(len(mesh.vertices))) print(" normals: " + str(len(mesh.normals))) print(" colors: " + str(len(mesh.colors))) print(" uv channels: " + str(len(mesh.texturecoords))) print(" uv-component-count:" + str(len(mesh.numuvcomponents))) print(" faces:" + str(len(mesh.faces))) print(" bones:" + str(len(mesh.bones))) print bonesNames = [] for bone in mesh.bones: bonesNames.append(bone.name) meshDict = { 'name' : mesh.name or index, 'materialID' : mesh.materialindex+1, 'vertices' : mesh.vertices, 'verticesCount' : len(mesh.vertices), 'texturecoords' : mesh.texturecoords, 'uvcounts' : len(mesh.texturecoords), 'faces' : mesh.faces, 'facesCount' : len(mesh.faces), 'bones' : mesh.bones, 'bonesNames' : bonesNames, 'normals' : mesh.normals } signals.emitNow( 'mesh.assimp_mesh', meshDict, obj, options ) print print("NODES:") transforms = [] self.searchNode(scene.rootnode, transforms) size = obj.GetPerPixel() for tr in transforms: pos = tr['pos'] for i, v in enumerate(pos): pos[i] = v * size signals.emitNow( 'mesh.assimp_transforms', obj, transforms ) # Finally release the model pyassimp.release(scene)
def loadBlender(fname_blender: str): """ Compile and return the fragments and collision shapes from ``fname``. The ``fname`` file must specify a Blender file. :param str fname: Blender file name :return: (frags dict, cshapes dict) """ # Use Blender itself to load the Blender file. This will trigger a script # inside Blender that creates a JSON file with custom scene data. The name # of that file is returned in 'fname_az'. fname_az = processBlenderFile(fname_blender) # Load the collision shape data and geometry. pp = pyassimp.postprocess azFile = json.loads(open(fname_az, 'rb').read().decode('utf8')) scene = pyassimp.load(fname_blender, pp.aiProcess_Triangulate) del fname_az, pp # Sanity check: both must contain information about the exact same objects. assert set(azFile.keys()) == {_.name for _ in scene.meshes} # Load all the materials. materials = loadMaterials(scene, fname_blender) # Compile fragments and collision shapes for Azrael. frags, cshapes = {}, {} for mesh in scene.meshes: # Get the material for this mesh. material = materials[mesh.materialindex] # Iterate over the faces and rebuild the vertices. azData = azFile[mesh.name] vert = np.zeros(len(mesh.faces) * 9) for idx, face in enumerate(mesh.faces): tmp = [mesh.vertices[_] for _ in face] start, stop = idx * 9, (idx + 1) * 9 vert[start:stop] = np.hstack(tmp) del start, stop, tmp, idx, face # Copy the UV coordinates, if there are any. if len(mesh.texturecoords) > 0: uv = np.zeros(len(mesh.faces) * 6) for idx, face in enumerate(mesh.faces): tmp = [mesh.texturecoords[0][_, :2] for _ in face] start, stop = 6 * idx, 6 * (idx + 1) uv[start:stop] = np.hstack(tmp) del start, stop, tmp, idx, face # Sanity check. assert (len(uv) // 2 == len(vert) // 3) else: uv = 0.5 * np.ones(2 * (len(vert) // 3)) uv = [] # Azrael does not allow 'dots', yet Bullet uses it prominently to name # objects. As a quick fix, simply replace the dots with something else. # fixme: should be redundant once #149 (https://trello.com/c/wcHX3qGd) # is implemented. azname = mesh.name.replace('.', 'x') # Unpack the position and orientation of the mesh in world coordinates. pos, rot, dim = azData['pos'], azData['rot'], np.array(azData['dimensions']) # Unpack the interior points and put them into any kind of byte string. # This will be attached as yet another file to the fragment data. interior_points = json.dumps(azData['interior_points']).encode('utf8') # Create a RAW fragment. scale = 1 rgb, width, height = material['RGB'], material['width'], material['height'] frag = demolib.getFragMetaRaw(vert, uv, rgb, scale, pos, rot) frag.files['interior_points'] = interior_points frags[azname] = frag # Construct the BOX collision shape based on the Blender dimensions. hlen_x, hlen_y, hlen_z = (dim / 2).tolist() box = aztypes.CollShapeBox(hlen_x, hlen_y, hlen_z) # Construct the CollshapeMeta data. cshapes[azname] = aztypes.CollShapeMeta('box', pos, rot, box) del azData, vert, dim, scale, rgb, width, height, hlen_x, hlen_y, hlen_z return frags, cshapes