def load_phong_mesh(file, shader, light_position): """ load resources from file using assimp, return list of ColorMesh """ try: pp = assimpcy.aiPostProcessSteps flags = pp.aiProcess_Triangulate | pp.aiProcess_GenSmoothNormals scene = assimpcy.aiImportFile(file, flags) except assimpcy.all.AssimpError as exception: print('ERROR loading', file + ': ', exception.args[0].decode()) return [] # prepare mesh nodes meshes = [] for mesh in scene.mMeshes: mat = scene.mMaterials[mesh.mMaterialIndex].properties mesh = PhongMesh(shader, [mesh.mVertices, mesh.mNormals], mesh.mFaces, k_d=mat.get('COLOR_DIFFUSE', (1, 1, 1)), k_s=mat.get('COLOR_SPECULAR', (1, 1, 1)), k_a=mat.get('COLOR_AMBIENT', (0, 0, 0)), s=mat.get('SHININESS', 16.), light_position=light_position) meshes.append(mesh) size = sum((mesh.mNumFaces for mesh in scene.mMeshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(meshes), size)) return meshes
def load_skybox(file, shader, tex_files=None): """ load resources from file using assimp, return list of TexturedMesh """ try: pp = assimpcy.aiPostProcessSteps flags = pp.aiProcess_Triangulate | pp.aiProcess_FlipUVs scene = assimpcy.aiImportFile(file, flags) except assimpcy.all.AssimpError as exception: print('ERROR loading', file + ': ', exception.args[0].decode()) return [] # Note: embedded textures not supported at the moment path = os.path.dirname(file) if os.path.dirname(file) != '' else './' for mat in scene.mMaterials: if not tex_files and 'TEXTURE_BASE' in mat.properties: # texture token name = os.path.basename(mat.properties['TEXTURE_BASE']) if tex_files: mat.properties['diffuse_map'] = SkyboxTexture(tex_files) # prepare textured mesh meshes = [] for mesh in scene.mMeshes: mat = scene.mMaterials[mesh.mMaterialIndex].properties assert mat['diffuse_map'], "Trying to map using a textureless material" attributes = [mesh.mVertices, mesh.mTextureCoords[0]] mesh = TexturedCubeMapMesh(shader, mat['diffuse_map'], attributes, mesh.mFaces) meshes.append(mesh) size = sum((mesh.mNumFaces for mesh in scene.mMeshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(meshes), size)) return meshes
def setUp(self): flags = pp.aiProcess_JoinIdenticalVertices | pp.aiProcess_Triangulate | pp.aiProcess_CalcTangentSpace | \ pp.aiProcess_OptimizeGraph | pp.aiProcess_OptimizeMeshes | pp.aiProcess_FixInfacingNormals | \ pp.aiProcess_GenUVCoords | pp.aiProcess_LimitBoneWeights | pp.aiProcess_SortByPType | \ pp.aiProcess_RemoveRedundantMaterials self.scene = aiImportFile(EXAMPLE_FILE_PATH, flags)
def doImport(): global path, scene flags = pp.aiProcess_JoinIdenticalVertices | pp.aiProcess_Triangulate | pp.aiProcess_CalcTangentSpace | \ pp.aiProcess_OptimizeGraph | pp.aiProcess_OptimizeMeshes | \ pp.aiProcess_FixInfacingNormals | pp.aiProcess_GenUVCoords | \ pp.aiProcess_LimitBoneWeights | pp.aiProcess_SortByPType | pp.aiProcess_RemoveRedundantMaterials scene = aiImportFile(pt.join(home, path), flags)
def setUp(self): flags = pp.aiProcess_JoinIdenticalVertices | pp.aiProcess_Triangulate | pp.aiProcess_CalcTangentSpace | \ pp.aiProcess_OptimizeGraph | pp.aiProcess_OptimizeMeshes | pp.aiProcess_FixInfacingNormals | \ pp.aiProcess_GenUVCoords | pp.aiProcess_LimitBoneWeights | pp.aiProcess_SortByPType | \ pp.aiProcess_RemoveRedundantMaterials self.scene = aiImportFile( path.join(path.dirname(__file__), path.pardir, 'examples', 'models', 'cil', 'cil.x'), flags)
def __init__(self, file, shader): self.file = file self.shader = shader try: pp = assimpcy.aiPostProcessSteps flags = pp.aiProcess_Triangulate | pp.aiProcess_GenSmoothNormals self.scene = assimpcy.aiImportFile(file, flags) except assimpcy.all.AssimpError as exception: print('ERROR loading', file + ': ', exception.args[0].decode()) exit()
def load(file, shader): """ load resources from file using assimp, return list of Mesh """ try: pp = assimpcy.aiPostProcessSteps flags = pp.aiProcess_Triangulate | pp.aiProcess_GenSmoothNormals scene = assimpcy.aiImportFile(file, flags) except assimpcy.all.AssimpError as exception: print('ERROR loading', file + ': ', exception.args[0].decode()) return [] meshes = [Mesh(shader, [m.mVertices, m.mNormals], m.mFaces) for m in scene.mMeshes] size = sum((mesh.mNumFaces for mesh in scene.mMeshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(meshes), size)) return meshes
def LoadMeshes(file): """ load resources from file using assimp, return a mesh list """ try: pp = assimp.aiPostProcessSteps flags = pp.aiProcess_Triangulate scene = assimp.aiImportFile(file, flags) except assimp.all.AssimpError as exception: print('ERROR loading', file + ': ', exception.args[0].decode()) return [] meshes = [ Mesh(vertices=m.mVertices, normals=m.mNormals, perVertexColor=m.mNormals, indexes=m.mFaces) for m in scene.mMeshes ] return meshes
def load_phong_tex_mesh(file, shader, tex_file, light_dir): """ load resources from file using assimp, return list of ColorMesh """ try: pp = assimpcy.aiPostProcessSteps flags = pp.aiProcess_Triangulate | pp.aiProcess_GenSmoothNormals | pp.aiProcess_FlipUVs scene = assimpcy.aiImportFile(file, flags) except assimpcy.all.AssimpError as exception: print('ERROR loading', file + ': ', exception.args[0].decode()) return [] # Note: embedded textures not supported at the moment path = os.path.dirname(file) if os.path.dirname(file) != '' else './' for mat in scene.mMaterials: if not tex_file and 'TEXTURE_BASE' in mat.properties: # texture token name = os.path.basename(mat.properties['TEXTURE_BASE']) # search texture in file's whole subdir since path often screwed up paths = os.walk(path, followlinks=True) found = [ os.path.join(d, f) for d, _, n in paths for f in n if name.startswith(f) or f.startswith(name) ] assert found, 'Cannot find texture %s in %s subtree' % (name, path) tex_file = found[0] if tex_file: mat.properties['diffuse_map'] = Texture(tex_file) # prepare mesh nodes meshes = [] for mesh in scene.mMeshes: mat = scene.mMaterials[mesh.mMaterialIndex].properties assert mat['diffuse_map'], "Trying to map using a textureless material" attributes = [mesh.mVertices, mesh.mNormals, mesh.mTextureCoords[0]] mesh = TexturedPhongMesh(shader, mat['diffuse_map'], attributes, mesh.mFaces, k_d=mat.get('COLOR_DIFFUSE', (1, 1, 1)), k_s=mat.get('COLOR_SPECULAR', (1, 1, 1)), k_a=mat.get('COLOR_AMBIENT', (0, 0, 0)), s=mat.get('SHININESS', 16.), light_dir=light_dir) meshes.append(mesh) size = sum((mesh.mNumFaces for mesh in scene.mMeshes)) print('Loaded %s\t(%d meshes, %d faces)' % (file, len(meshes), size)) return meshes
def load_skinned(file, shader, light_dir, tex_file=None): """load resources from file using assimp, return node hierarchy """ try: pp = assimpcy.aiPostProcessSteps flags = pp.aiProcess_Triangulate | pp.aiProcess_GenSmoothNormals scene = assimpcy.aiImportFile(file, flags) except assimpcy.all.AssimpError as exception: print('ERROR loading', file + ': ', exception.args[0].decode()) return [] # ----- load animations def conv(assimp_keys, ticks_per_second): """ Conversion from assimp key struct to our dict representation """ return {key.mTime / ticks_per_second: key.mValue for key in assimp_keys} # load first animation in scene file (could be a loop over all animations) transform_keyframes = {} if scene.mAnimations: anim = scene.mAnimations[0] for channel in anim.mChannels: # for each animation bone, store TRS dict with {times: transforms} transform_keyframes[channel.mNodeName] = ( conv(channel.mPositionKeys, anim.mTicksPerSecond), conv(channel.mRotationKeys, anim.mTicksPerSecond), conv(channel.mScalingKeys, anim.mTicksPerSecond) ) # ---- prepare scene graph nodes # create SkinningControlNode for each assimp node. # node creation needs to happen first as SkinnedMeshes store an array of # these nodes that represent their bone transforms nodes = {} # nodes name -> node lookup nodes_per_mesh_id = [[] for _ in scene.mMeshes] # nodes holding a mesh_id def make_nodes(assimp_node): """ Recursively builds nodes for our graph, matching assimp nodes """ trs_keyframes = transform_keyframes.get(assimp_node.mName, (None,)) skin_node = SkinningControlNode(*trs_keyframes, transform=assimp_node.mTransformation) nodes[assimp_node.mName] = skin_node for mesh_index in assimp_node.mMeshes: nodes_per_mesh_id[mesh_index].append(skin_node) skin_node.add(*(make_nodes(child) for child in assimp_node.mChildren)) return skin_node path = os.path.dirname(file) if os.path.dirname(file) != '' else './' for mat in scene.mMaterials: if not tex_file and 'TEXTURE_BASE' in mat.properties: # texture token name = os.path.basename(mat.properties['TEXTURE_BASE']) # search texture in file's whole subdir since path often screwed up paths = os.walk(path, followlinks=True) found = [os.path.join(d, f) for d, _, n in paths for f in n if name.startswith(f) or f.startswith(name)] assert found, 'Cannot find texture %s in %s subtree' % (name, path) tex_file = found[0] if tex_file: mat.properties['diffuse_map'] = Texture(tex_file=tex_file) root_node = make_nodes(scene.mRootNode) # ---- create SkinnedMesh objects for mesh_id, mesh in enumerate(scene.mMeshes): # -- skinned mesh: weights given per bone => convert per vertex for GPU # first, populate an array with MAX_BONES entries per vertex v_bone = np.array([[(0, 0)]*MAX_BONES] * mesh.mNumVertices, dtype=[('weight', 'f4'), ('id', 'u4')]) for bone_id, bone in enumerate(mesh.mBones[:MAX_BONES]): for entry in bone.mWeights: # weight,id pairs necessary for sorting v_bone[entry.mVertexId][bone_id] = (entry.mWeight, bone_id) v_bone.sort(order='weight') # sort rows, high weights last v_bone = v_bone[:, -MAX_VERTEX_BONES:] # limit bone size, keep highest # prepare bone lookup array & offset matrix, indexed by bone index (id) bone_nodes = [nodes[bone.mName] for bone in mesh.mBones] bone_offsets = [bone.mOffsetMatrix for bone in mesh.mBones] mat = scene.mMaterials[mesh.mMaterialIndex].properties assert mat['diffuse_map'], "Trying to map using a textureless material" # initialize skinned mesh and store in assimp mesh for node addition attrib = [mesh.mVertices, mesh.mNormals, v_bone['id'], v_bone['weight'], mesh.mTextureCoords[0]] mesh = SkinnedMesh(shader, mat['diffuse_map'], attrib, bone_nodes, bone_offsets, mesh.mFaces, k_d=mat.get('COLOR_DIFFUSE', (1, 1, 1)), k_s=mat.get('COLOR_SPECULAR', (1, 1, 1)), k_a=mat.get('COLOR_AMBIENT', (0, 0, 0)), s=mat.get('SHININESS', 16.), light_dir=light_dir) for node in nodes_per_mesh_id[mesh_id]: node.add(mesh) nb_triangles = sum((mesh.mNumFaces for mesh in scene.mMeshes)) print('Loaded', file, '\t(%d meshes, %d faces, %d nodes, %d animations)' % (scene.mNumMeshes, nb_triangles, len(nodes), scene.mNumAnimations)) return [root_node]
def doImport(): global path, scene scene = aiImportFile(path, flags1)
def main(args): pp = assimpcy.aiPostProcessSteps flags = pp.aiProcess_JoinIdenticalVertices | pp.aiProcess_FlipUVs flags |= pp.aiProcess_Triangulate | pp.aiProcess_GenSmoothNormals for f in args.files: scene = assimpcy.aiImportFile(f, flags) # the model we load print("MODEL:", f) print() # write some statistics print("SCENE:") print(" meshes:", scene.mNumMeshes) print(" materials:", scene.mNumMaterials) print(" textures:", scene.mNumTextures) print(" animations:", scene.mNumAnimations) print(" lights:", scene.mNumLights) print(" cameras:", scene.mNumCameras) print() print("MESHES:") for index, mesh in enumerate(scene.mMeshes): print(" MESH", index + 1) print(" material:", mesh.mMaterialIndex + 1) print(" vertices:", len(mesh.mVertices)) print(" first:", [list(v) for v in mesh.mVertices[:3]], '...') print(" normals:", len(mesh.mNormals)) print(" first:", [list(n) for n in mesh.mNormals[:3]], '...') print(" colors:", len(mesh.mColors)) for i, tex in enumerate(mesh.mTextureCoords): if tex is not None: print(" texture-coords " + str(i) + ", first:", [list(t) for t in tex[:3]], '...') print(" uv-component-count:", mesh.mNumUVComponents) print(" faces:", len(mesh.mFaces), "first:", [list(f) for f in mesh.mFaces[:3]], '...') print(" bones:", len(mesh.mBones), "first:", [b.mName[2:-1] for b in mesh.mBones[:3]]) print() print("MATERIALS:") for index, material in enumerate(scene.mMaterials): print(" MATERIAL " + str(index + 1)) for key, value in material.properties.items(): print(" %s: %s" % (key, value)) print() print("ANIMATIONS:") for index, anim in enumerate(scene.mAnimations): print(" ANIMATION", index + 1, ": ", anim.mName[2:-1]) print(" duration:", anim.mDuration) print(" tickspersecond:", anim.mTicksPerSecond) print(" nummeshchannels:", len(anim.mChannels)) for idx, chan in enumerate(anim.mChannels): print(" CHANNEL", idx, chan.mNodeName[2:-1]) lenpos = len(chan.mPositionKeys) lenrot = len(chan.mRotationKeys) lenscl = len(chan.mScalingKeys) print(" pos keys", lenpos, keys(chan.mPositionKeys), '...') print(" rot keys", lenrot, keys(chan.mRotationKeys), '...') print(" scl keys", lenscl, keys(chan.mScalingKeys), '...') print() if scene.mNumTextures: print("TEXTURES:") for index, texture in enumerate(scene.mTextures): print(" TEXTURE", index + 1) print(" width:", texture.mWidth) print(" height:", texture.mHeight) print(" hint:", texture.AchFormatHint) print(" data (size):", texture.mWidth * texture.mHeight) print() print("NODES:") print_node(scene.mRootNode)