bool sa::MeshHandler::importModelsFromScene(const std::string& fileName) { Assimp::Importer importer; std::ifstream fin(fileName.c_str()); if (!fin.fail()) { fin.close(); } else { LOG("Couldn't open file: %s", fileName.c_str()); LOG("%s", importer.GetErrorString()); return false; } const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality); // If the import failed, report it if (!scene) { ASSERT(false, "%s", importer.GetErrorString()); return false; } // Everything will be cleaned up by the importer destructor loadMeshesFromScene(scene); LOG("Import of scene %s succeeded.", fileName.c_str()); return true; }
void loadAssets() { // Read in an asset file, and do some post-processing. There is much // more you can do with this asset loader, including load textures. // More info is here: // http://assimp.sourceforge.net/lib_html/usage.html cathedralScene = cathedralImporter.ReadFile(CATHEDRAL_MODEL_PATH, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcessPreset_TargetRealtime_Quality); if (!cathedralScene || cathedralScene->mNumMeshes <= 0) { std::cerr << cathedralImporter.GetErrorString() << std::endl; exit(-1); } armadilloScene = armadilloImporter.ReadFile(ARMADILLO_MODEL_PATH, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcessPreset_TargetRealtime_Quality); if (!armadilloScene || armadilloScene->mNumMeshes <= 0) { std::cerr << armadilloImporter.GetErrorString() << std::endl; exit(-1); } ////////////////////////////////////////////////////////////////////////// // TODO: LOAD YOUR SHADERS/TEXTURES ////////////////////////////////////////////////////////////////////////// // Load the vertex shader phongShader = new Shader("Shaders/phong"); if (!phongShader->loaded()) { std::cerr << "Shader failed to load" << std::endl; std::cerr << phongShader->errors() << std::endl; exit(-1); } simpleShader = new Shader("Shaders/simple"); if (!simpleShader->loaded()) { std::cerr << "Shader failed to load" << std::endl; std::cerr << simpleShader->errors() << std::endl; exit(-1); } envMapShader = new Shader("Shaders/envmap"); if (!envMapShader->loaded()) { std::cerr << "Shader failed to load" << std::endl; std::cerr << envMapShader->errors() << std::endl; exit(-1); } loadTexturesAndMeshIndices(cathedralScene); loadTexturesAndMeshIndices(armadilloScene); whiteImage = sf::Image(1, 1, sf::Color::White); generateCubeMap(); }
bool Import3DFromFile( const std::string& pFile) { //check if file exists std::ifstream fin(pFile.c_str()); if(!fin.fail()) { fin.close(); } else { MessageBox(NULL, ("Couldn't open file: " + pFile).c_str() , "ERROR", MB_OK | MB_ICONEXCLAMATION); logInfo( importer.GetErrorString()); return false; } scene = importer.ReadFile( pFile, aiProcessPreset_TargetRealtime_Quality); // If the import failed, report it if( !scene) { logInfo( importer.GetErrorString()); return false; } // Now we can access the file's contents. logInfo("Import of scene " + pFile + " succeeded."); // We're done. Everything will be cleaned up by the importer destructor return true; }
void loadAssets() { // Read in an asset file, and do some post-processing. There is much // more you can do with this asset loader, including load textures. // More info is here: // http://assimp.sourceforge.net/lib_html/usage.html scene1 = importer1.ReadFile(CATHEDRAL_PATH, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcessPreset_TargetRealtime_Quality); if (!scene1 || scene1->mNumMeshes <= 0) { std::cerr << importer1.GetErrorString() << std::endl; exit(-1); } scene2 = importer2.ReadFile(STATUE_PATH, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcessPreset_TargetRealtime_Quality); if (!scene2 || scene2->mNumMeshes <= 0) { std::cerr << importer2.GetErrorString() << std::endl; exit(-1); } currentMesh_vec = &meshes_1; // if the display list has not been made yet, create a new one and // fill it with scene contents if(scene_list1 == 0) { scene_list1 = glGenLists(1); glNewList(scene_list1, GL_COMPILE); recursive_load_meshes(scene1, scene1->mRootNode); glEndList(); } glCallList(scene_list1); currentMesh_vec = &meshes_2; // if the display list has not been made yet, create a new one and // fill it with scene contents if(scene_list2 == 0) { scene_list2 = glGenLists(1); glNewList(scene_list2, GL_COMPILE); recursive_load_meshes(scene2, scene2->mRootNode); glEndList(); } glCallList(scene_list2); Shader * shader1 = new Shader("shaders/phongNorm"); shaders.push_back(shader1); Shader * shader2 = new Shader("shaders/phongEnvMap"); shaders.push_back(shader2); }
SharedPointer< Group > SceneImporter::import( std::string filename ) { // check if file exists std::ifstream fin( filename ); bool exists = !fin.fail(); fin.close(); if ( !exists ) { // Is it ok to throw exceptions? throw FileNotFoundException( filename ); } Assimp::Importer importer; importer.SetPropertyInteger( AI_CONFIG_PP_SLM_VERTEX_LIMIT, 15000 ); const aiScene* importedScene = importer.ReadFile( filename, aiProcessPreset_TargetRealtime_MaxQuality ); if ( importedScene == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Error importing file ", filename, "\n", importer.GetErrorString() ); return nullptr; } auto skinnedMesh = crimild::alloc< SkinnedMesh >(); loadAnimations( importedScene, skinnedMesh ); auto root = crimild::alloc< Group >( filename ); auto basePath = FileSystem::getInstance().extractDirectory( filename ) + "/"; recursiveSceneBuilder( root, importedScene, importedScene->mRootNode, basePath, skinnedMesh ); if ( _skeleton != nullptr ) { Transformation globalInverseTransform; computeTransform( importedScene->mRootNode->mTransformation.Inverse(), globalInverseTransform ); _skeleton->setGlobalInverseTransform( globalInverseTransform ); root->attachComponent( _skeleton ); } return root; }
//Init bool cScene::Init(const std::string &lacNameId, const std::string &lacFile) { macFile = lacFile; mbLoaded = false; //Create an instance of the importer class Assimp::Importer lImporter; //Load the scene const aiScene* lpScene = lImporter.ReadFile( macFile.c_str(), aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); // If the import failed, report it if (!lpScene) { printf( lImporter.GetErrorString() ); return false; } ProcessScene(lpScene); lImporter.FreeScene(); mbLoaded = true; return true; }
std::vector<PQP_Model *> Convexer::loadScenario(const std::string& file, bool make_convex) { const aiScene* scene = NULL; std::vector<PQP_Model *> ret_val; // Create an instance of the Importer class Assimp::Importer importer; // And have it read the given file with some example postprocessing // Usually - if speed is not the most important aspect for you - you'll // propably to request more postprocessing than we do in this example. scene = importer.ReadFile( file, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); // If the import failed, report it if( !scene) { std::cerr << "Convexer::loadScenario --> " << importer.GetErrorString() << std::endl; } else { std::cout << "Convexer::loadScenario --> Scene loaded successfully. Num meshes: "; std::cout << scene->mNumMeshes << std::endl; if (make_convex) { cout << "\nConvexer::loadScenario --> Making convex the mesh.\n"; ret_val = makeConvex(scene); } else { ret_val = fromaiScene(scene); } } cout << "Convexer::loadScenario --> Scene loaded contains " << ret_val.size() << " different obstacles.\n"; // We're done. Everything will be cleaned up by the importer destructor return ret_val; }
bool loadDragonFile( const string& fileName ) { // Create an instance of the Importer class Assimp::Importer importer; // And have it read the given file with some example postprocessing // Usually - if speed is not the most important aspect for you - you'll // propably to request more postprocessing than we do in this example. const aiScene* scene = importer.ReadFile( fileName, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); // If the import failed, report it if( !scene) { cout << endl << endl << importer.GetErrorString() << endl << endl; return false; } // Now we can access the file's contents. processDragon( scene ); // We're done. Everything will be cleaned up by the importer destructor return true; }
bool ModelImporter::importModel(std::string file) { std::cout << " Loading model: " << file << std::endl; Assimp::Importer importer; model = importer.ReadFile(file, aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_FlipWindingOrder ); if(!model) { std::cout << "Error importing '" << file << "': " << importer.GetErrorString() << std::endl; return false; } this->printModelInfo(); /* Create the VAOs for the model */ this->extractTriangles(); return true; }
bool Mesh::LoadMesh ( const std::string& filename ) { // Удаляем данные предыдущей модели (если она была загружена) Clear ( ); Assimp::Importer importer; const aiScene* pScene = importer.ReadFile ( filename.c_str ( ), aiPostProcessSteps::aiProcess_Triangulate | aiPostProcessSteps::aiProcess_GenSmoothNormals | aiPostProcessSteps::aiProcess_FlipUVs | aiPostProcessSteps::aiProcess_CalcTangentSpace ); bool returnResult = false; if ( pScene ) { returnResult = InitFromScene ( pScene, filename ); } else { printf ( "Error parsing '%s': '%s'\n", filename.c_str ( ), importer.GetErrorString ( ) ); } return returnResult; }
// load model if not yet cached void Model::load(const std::string& path) { m_pMeshes = std::make_shared<std::vector<Mesh>>(); m_ShaderID = ShaderLoader::Instance().getProgram("Default"); m_MVPMatrixLocation = glGetUniformLocation(m_ShaderID, "mvpMatrix"); m_TextureFrontSamplerLocation = glGetUniformLocation(m_ShaderID, "textureFrontSampler"); m_TextureSideSamplerLocation = glGetUniformLocation(m_ShaderID, "textureSideSampler"); m_ChinVerticalPosLocation = glGetUniformLocation(m_ShaderID, "chinVerticalPos"); m_EyeVerticalPosLocation = glGetUniformLocation(m_ShaderID, "eyeVerticalPos"); m_LEyeTexVerticalPosLocation = glGetUniformLocation(m_ShaderID, "LEyeVerticalTexPos"); m_REyeTexVerticalPosLocation = glGetUniformLocation(m_ShaderID, "REyeVerticalTexPos"); m_ChinTexVerticalPosLocation = glGetUniformLocation(m_ShaderID, "ChinTexVerticalPos"); // Create an instance of the importer class Assimp::Importer importer; // Read in the given file into a scene and set some (example) postprocessing const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_GenNormals);// | aiProcess_FlipUVs); if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { std::string error = importer.GetErrorString(); throw std::exception("Failed to load model. ASSIMP-ERROR"); } // Start processing nodes processNode(scene->mRootNode, scene); }
AnimatedMesh tiny::mesh::io::readAnimatedMesh(const std::string &fileName, const std::string &meshName) { //Use AssImp to read all data from the file. Assimp::Importer importer; const aiScene *scene = importer.ReadFile(fileName.c_str(), aiProcessPreset_TargetRealtime_Quality); if (!scene) { std::cerr << "Unable to read '" << fileName << "' from disk:" << importer.GetErrorString() << "!" << std::endl; throw std::exception(); } const aiMesh *sourceMesh = detail::getAiMesh(scene, meshName); AnimatedMesh mesh; assert(sourceMesh); detail::copyAiMeshVertices<AnimatedMesh, AnimatedMeshVertex>(sourceMesh, mesh, aiMatrix4x4()); detail::copyAiMeshIndices(sourceMesh, mesh); detail::copyAiMeshBones(sourceMesh, mesh); //Copy animations if available. if (scene->HasAnimations()) { detail::copyAiAnimations(scene, sourceMesh, mesh.skeleton); } std::cerr << "Read mesh '" << meshName << "' with " << mesh.vertices.size() << " vertices, " << mesh.indices.size()/3 << " triangles, " << mesh.skeleton.bones.size() << " bones, and " << mesh.skeleton.animations.size() << " animations from '" << fileName << "'." << std::endl; //importer will go out of scope, which will free all read data automatically. return mesh; }
int LoadScene(tchar const *filename, aiScene const **scene) { if(scene == null || filename == null) { return E_POINTER; } Assimp::Importer *importer = new Assimp::Importer(); importer->SetIOHandler(new MyIOSystem()); importer->SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); #if defined(_DEBUG) DefaultLogger::create("", Logger::VERBOSE, aiDefaultLogStream_DEBUGGER); #endif importer->ReadFile(filename, aiProcess_Triangulate | aiProcess_SortByPType); #if defined(_DEBUG) DefaultLogger::kill(); #endif if(importer->GetScene() == null) { TRACE("Error loading %s: %s\n", filename, importer->GetErrorString()); return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); } *scene = importer->GetScene(); return S_OK; }
void Mesh::loadMeshdata(const std::string& a_Filepath) { Assimp::Importer importer; const auto scene = importer.ReadFile(a_Filepath, aiPostProcessSteps::aiProcess_CalcTangentSpace | aiPostProcessSteps::aiProcess_Triangulate | aiPostProcessSteps::aiProcess_JoinIdenticalVertices | aiPostProcessSteps::aiProcess_SortByPType); auto error = importer.GetErrorString(); auto mesh = scene->mMeshes[0]; m_Vertices.reserve(mesh->mNumVertices); for (auto i = 0u; i < mesh->mNumVertices; i++) { m_Vertices.emplace_back(toXMFloat3(mesh->mVertices[i]), mesh->HasVertexColors(i) ? toXMFloat4(mesh->mColors[0][i]) : XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), mesh->HasTextureCoords(i) ? toXMFloat2(mesh->mTextureCoords[0][i]) : XMFLOAT2(0.0f, 0.0f)); } m_Indices.reserve(mesh->mNumFaces * 3); for (auto i = 0u; i < mesh->mNumFaces; ++i) { aiFace currentFace = mesh->mFaces[i]; for (auto j = 0u; j < currentFace.mNumIndices; ++j) { m_Indices.push_back(currentFace.mIndices[j]); } } }
Scene::Scene(int argc, char ** argv) { dist = -6.0f; Assimp::Importer importer; (importer.ReadFile( "C:\\Users\\abrajoe\\Documents\\Visual Studio 2010\\Projects\\Piano-Scene\\Debug\\lung.blend", aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType)); scene = importer.GetOrphanedScene(); // If the import failed, report it if( !scene) { printf( importer.GetErrorString()); return; } glutInit(&argc, argv); dir = argv[0]; glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(0, 0); window = glutCreateWindow("foo"); glutDisplayFunc(&display); glutReshapeFunc(&resize); glutKeyboardFunc(&keyPressed); }
ModelScene* ModelImporter_Impl::Load(const char* path) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); if (!scene) { std::string error = importer.GetErrorString(); return NULL; } std::string strPath = std::string(path); std::stringstream fileName; char ch; for (uint32_t i = 0; i < strPath.length(); ++i) { ch = strPath.at(i); if (ch == '/' || ch == '\\') fileName.str(""); else if (ch == '.') break; else fileName << ch; } ModelScene* myScene = _LoadScene(fileName.str().c_str(), scene); _CalculateModelCenter(myScene); return myScene; }
bool Mesh::loadMesh(const std::string& fileName) { // Release the previously loaded mesh (if it exists) this->textures.clear(); this->entries.clear(); bool res = false; Assimp::Importer importer; const aiScene* pScene = importer.ReadFile(fileName.c_str(), aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs); if (pScene) { res = this->initFromScene(pScene, fileName); } else { printf("Error parsing '%s': '%s'\n", fileName.c_str(), importer.GetErrorString()); } // print debug info printf("Loaded %i verticies\n", this->numVerticies); printf("Loaded %i faces\n", this->numFaces); return res; }
void Model::loadModel(std::string path) { // initialize importer, transform model primitives to triangles and flip texCoords y axis Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { Utils::exitMessage("Assimp Error", importer.GetErrorString()); } directory = path.substr(0, path.find_last_of('/')); processNode(scene->mRootNode, scene); //std::vector<Vertex> concVertices = meshes[5].vertices; //std::vector<GLuint> concIndices = meshes[5].indices; //std::vector<Texture> concTextures = meshes[5].textures; //concVertices.insert(concVertices.end(), meshes[6].vertices.begin(), meshes[6].vertices.end()); //concIndices.insert(concIndices.end(), meshes[6].indices.begin(), meshes[6].indices.end()); //concTextures.insert(concTextures.end(), meshes[6].textures.begin(), meshes[6].textures.end()); //int offset = meshes[5].indices.size(); //for (int i = offset; i < concIndices.size(); i++) //{ // concIndices[i] = concIndices[i] + offset; //} //Mesh(concVertices, concIndices, concTextures); ////meshes[5] = meshes[6]; //meshes.pop_back(); //meshes.pop_back(); //meshes.push_back(Mesh(concVertices, concIndices, concTextures)); }
bool SceneLoader::LoadScene(const std::string& file_name, Scene& scene, std::string& status) { Assimp::Importer importer; importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE); const aiScene* assimp_scene = importer.ReadFile(file_name, aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_FixInfacingNormals | aiProcess_FindDegenerates | aiProcess_ValidateDataStructure); // | aiProcess_ImproveCacheLocality // | aiProcess_RemoveRedundantMaterials // | aiProcess_FixInfacingNormals | aiProcess_FindDegenerates // | aiProcess_OptimizeGraph | aiProcess_OptimizeMeshes); status = std::string(importer.GetErrorString()); if (!status.empty() || NULL == assimp_scene) { return false; } status = "OK"; for (uint32_t i = 0; i < assimp_scene->mNumCameras; ++i) { ImportCamera(scene, assimp_scene->mCameras[i]); } for (uint32_t i = 0; i < assimp_scene->mNumLights; ++i) { ImportLight(scene, assimp_scene->mLights[i]); } std::cout << "mNumMaterials = " << assimp_scene->mNumMaterials << std::endl; for (uint32_t i = 0; i < assimp_scene->mNumMaterials; ++i) { ImportMaterial(scene, assimp_scene->mMaterials[i]); } std::cout << "mNumMeshes = " << assimp_scene->mNumMeshes << std::endl; for (uint32_t i = 0; i < assimp_scene->mNumMeshes; ++i) { ImportMesh(scene, assimp_scene->mMeshes[i]); } return true; }
bool AssimpModel::loadModel(const std::string filename) { std::cout << "loadModel[" << filename << "]" << std::endl; bool returnValue = false; // Create Vertex Array Object glGenVertexArrays(1, &vertexArrayId); glBindVertexArray(vertexArrayId); std::cout << "assimp vao: " << vertexArrayId << std::endl; // Release the previously loaded mesh (if it exists) clear(); Assimp::Importer importer; const aiScene* scene = importer.ReadFile(filename, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); if (scene) { std::cout << " Anzahl der Meshes in dieser Datei: " << scene->mNumMeshes << std::endl; returnValue = this->initAllMeshes(scene, filename); } else { printf("Fehler beim parsen der Datei '%s': '%s'\n", filename.c_str(), importer.GetErrorString()); } // Make sure the VAO is not changed from outside code glBindVertexArray(0); return returnValue; }
// Loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector. void Model::loadModel(string path) { // Read file via ASSIMP Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); // Check for errors if(!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero { cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl; return; } // Retrieve the directory path of the filepath this->directory = path.substr(0, path.find_last_of('/')); aiMatrix4x4 modelMatrix; this->processMaterial(scene); this->processLight(scene); // Process ASSIMP's root node recursively this->processNode(scene->mRootNode, scene, modelMatrix); processMatrices(); m_lightShaderStorageBuffer.bind(); m_matricesSSBO.bind(); }
// Loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector. void loadModel(string path) { // Read file via ASSIMP cout << "reading model from file ..." << endl; Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); // Check for errors if(!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { // if is Not Zero cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl; return; } cout << "model read successfully" << endl; cout << "------------------------------------------------" << endl; cout << "animations " << scene->mNumAnimations << endl; cout << "cameras " << scene->mNumCameras << endl; cout << "lights " << scene->mNumLights << endl; cout << "materials " << scene->mNumMaterials << endl; cout << "meshes " << scene->mNumMeshes << endl; cout << "textures " << scene->mNumTextures << endl; cout << "------------------------------------------------" << endl; // Retrieve the directory path of the filepath directory = path.substr(0, path.find_last_of('/')); // Process ASSIMP's root node recursively processNode(scene->mRootNode, scene); }
bool Mesh::LoadMesh(const string& Filename) { // Release the previously loaded mesh (if it exists) Clear(); // Create the VAO glGenVertexArrays(1, &m_VAO); glBindVertexArray(m_VAO); // Create the buffers for the vertices attributes glGenBuffers(ARRAY_SIZE_IN_ELEMENTS(m_Buffers), m_Buffers); bool Ret = false; Assimp::Importer Importer; const aiScene* pScene = Importer.ReadFile(Filename.c_str(), aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs); if (pScene) { Ret = InitFromScene(pScene, Filename); if (!Ret) { OGLDEV_ERROR("Error initializing model"); } } else { printf("Error parsing '%s': '%s'\n", Filename.c_str(), Importer.GetErrorString()); } // Make sure the VAO is not changed from the outside glBindVertexArray(0); return Ret; }
bool mesh::import_from_file(const std::string& filepath) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile(filepath, aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_GenNormals | aiProcess_PreTransformVertices | // TODO: figure out the node graph aiProcess_FixInfacingNormals | aiProcess_FindDegenerates ); if(!scene) { std::cerr << importer.GetErrorString() << std::endl; return false; } this->scene = importer.GetOrphanedScene(); if (scene->mNumMeshes != 1){ std::cerr << "Scene contains does not contain exactly one mesh(" << scene->mNumMeshes << ")." << std::endl; return false; } return true; }
GLboolean Mesh::loadMesh(const std::string & filename) { clear(); GLboolean res = GL_FALSE; Assimp::Importer import; const aiScene* scene = import.ReadFile(filename.c_str(), aiProcess_FlipUVs | aiProcess_GenSmoothNormals | aiProcess_Triangulate); if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { std::string err = "[ASSIMP]. Could not load file: " + filename + "\n" + import.GetErrorString(); XTEN_ERROR(err); return res; } else { res = initFromScene(scene, filename); } return res; }
std::vector<Ygg::ConverterData>* Ygg::Loader::LoadScene(const std::string filename, std::vector<Entity> *entity_list) { Assimp::Importer importer; importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, 65536); importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE); const aiScene* ascene = importer.ReadFile(filename, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_FindDegenerates | aiProcess_SplitLargeMeshes | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); if (!ascene) { std::fprintf(stderr, "%s\n", importer.GetErrorString()); return &this->results; } // Get path for relative textures int split = (int)filename.rfind("/"); std::string path = filename.substr(0, split + 1); // Now we can access the file's contents. this->ParseScene(ascene, entity_list); return &this->results; }
mesh import_mesh(char const * file_name) { Assimp::Importer importer; aiScene const * ai_scene = importer.ReadFile( file_name, aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_GenNormals | aiProcess_SortByPType ); if (!ai_scene) throw std::runtime_error(std::string("Unable to import mesh: ") + importer.GetErrorString()); aiMesh const & am = *ai_scene->mMeshes[0]; // TODO: What about multiple meshes? vertices vertices; { buffer<hvector4<float>> positions(am.mNumVertices); buffer<vector3<float>> normals(am.mNumVertices); for(unsigned int i = 0; i < am.mNumVertices; ++i) { positions[i] = { am.mVertices[i][0], am.mVertices[i][1], am.mVertices[i][2] }; normals [i] = { am. mNormals[i][0], am. mNormals[i][1], am. mNormals[i][2] }; } vertices.attribute("position", std::move(positions)); vertices.attribute("normal" , std::move(normals )); } for (size_t n = 0; n < am.GetNumColorChannels(); ++n) { buffer<hvector4<float>> colors(am.mNumVertices); for(unsigned int i = 0; i < am.mNumVertices; ++i) { auto const & c = am.mColors[n][i]; colors[i] = {c.r, c.g, c.b, c.a}; } std::ostringstream name("color", std::ios_base::ate); if (n) name << (n + 1); vertices.attribute(name.str(), std::move(colors)); } for (size_t n = 0; n < am.GetNumUVChannels(); ++n) { buffer<vector3<float>> uvs(am.mNumVertices); for(unsigned int i = 0; i < am.mNumVertices; ++i) { uvs[i] = { am.mTextureCoords[n][i][0], am.mTextureCoords[n][i][1], am.mTextureCoords[n][i][1] }; } std::ostringstream name("texture_coordinate", std::ios_base::ate); if (n) name << (n + 1); vertices.attribute(name.str(), std::move(uvs)); } buffer<GLushort> indices(am.mNumFaces * 3); for (size_t i = 0; i < am.mNumFaces; ++i) { indices[i*3 ] = am.mFaces[i].mIndices[0]; indices[i*3+1] = am.mFaces[i].mIndices[1]; indices[i*3+2] = am.mFaces[i].mIndices[2]; } return mesh(std::move(vertices), std::move(indices)); }
/** * Load a scene from a supported 3D file format * * @param filename Name of the file (or asset) to load * @param flags (Optional) Set of ASSIMP processing flags * * @return Returns true if the scene has been loaded */ bool LoadMesh(const std::string& filename, int flags = defaultFlags) { #if defined(__ANDROID__) // Meshes are stored inside the apk on Android (compressed) // So they need to be loaded via the asset manager AAsset* asset = AAssetManager_open(assetManager, filename.c_str(), AASSET_MODE_STREAMING); assert(asset); size_t size = AAsset_getLength(asset); assert(size > 0); void *meshData = malloc(size); AAsset_read(asset, meshData, size); AAsset_close(asset); pScene = Importer.ReadFileFromMemory(meshData, size, flags); free(meshData); #else pScene = Importer.ReadFile(filename.c_str(), flags); #endif if (pScene) { m_Entries.clear(); m_Entries.resize(pScene->mNumMeshes); // Read in all meshes in the scene for (auto i = 0; i < m_Entries.size(); i++) { m_Entries[i].vertexBase = numVertices; numVertices += pScene->mMeshes[i]->mNumVertices; const aiMesh* paiMesh = pScene->mMeshes[i]; InitMesh(&m_Entries[i], paiMesh, pScene); } return true; } else { printf("Error parsing '%s': '%s'\n", filename.c_str(), Importer.GetErrorString()); #if defined(__ANDROID__) LOGE("Error parsing '%s': '%s'", filename.c_str(), Importer.GetErrorString()); #endif return false; } }
GLboolean convert_model_file(const std::string& source_path, const std::string& target_path){ Assimp::Importer importer; std::unordered_map<std::string, GLuint> bone_id_map; const aiScene* scene = importer.ReadFile(source_path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs); if(!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { std::cout << __FILE__ << ":" << __LINE__ << ": " << "ERROR: Assimp failed to load model: " << importer.GetErrorString() << std::endl; errorlogger("ERROR: Assimp failed to load model: ", importer.GetErrorString()); return false; } std::vector<std::string> mesh_names; std::string filename = split(target_path, '/').back(); std::string modelname = split(filename, '.')[0]; process_node(scene->mRootNode, scene, mesh_names, bone_id_map, modelname); if (file_exists(target_path)) { std::cout << __FILE__ << ":" << __LINE__ << ": " << "ERROR: Failed to store binary model, target file exists: " << target_path << std::endl; errorlogger("ERROR: Failed to store binary model, target file exists: ", target_path.c_str()); return false; } std::ofstream contentf (target_path.c_str(), std::ios::binary); if (!contentf.is_open()){ std::cout << __FILE__ << ":" << __LINE__ << ": " << "ERROR: Failed to open content file for storing model data: " << target_path << std::endl; errorlogger("ERROR: Failed to open content file for storing model data: ", target_path.c_str()); return false; } GLuint mesh_count = mesh_names.size(); contentf.write(reinterpret_cast<const char *>(&mesh_count), sizeof(GLuint)); for (const auto &mesh_name : mesh_names) { if (!write_string_to_binary_file(contentf, mesh_name)) { std::cout << __FILE__ << ":" << __LINE__ << ": " << "ERROR: Cannot add empty mesh name as model mesh key for: " << target_path << std::endl; errorlogger("ERROR: Cannot add empty mesh name as model mesh key for: ", target_path.c_str()); return false; } } if (scene->HasAnimations()) { contentf.write(reinterpret_cast<const char *>(&Utility_consts::TRUE_BOOL), sizeof(GLuint)); if (!store_binary_animation_set(scene, modelname, bone_id_map)){ std::cout << __FILE__ << ":" << __LINE__ << ": " << "ERROR: Failed to store animation set for model: " << target_path << std::endl; errorlogger("ERROR: Failed to store animation set for model: ", target_path.c_str()); contentf.close(); return false; } } else{ contentf.write(reinterpret_cast<const char *>(&Utility_consts::FALSE_BOOL), sizeof(GLuint)); } contentf.close(); return true; }
bool Mesh::loadFromFile(const std::string& path) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace); if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl; return false; } const aiMesh* mesh = scene->mMeshes[0]; for (GLuint i = 0; i < mesh->mNumVertices; ++i) { Vertex vertex; vertex.position.x = mesh->mVertices[i].x; vertex.position.y = mesh->mVertices[i].y; vertex.position.z = mesh->mVertices[i].z; vertex.normal.x = mesh->mNormals[i].x; vertex.normal.y = mesh->mNormals[i].y; vertex.normal.z = mesh->mNormals[i].z; if (mesh->mTextureCoords[0]) { vertex.texCoord.x = mesh->mTextureCoords[0][i].x; vertex.texCoord.y = mesh->mTextureCoords[0][i].y; } //else // vertex.texCoord = glm::vec2(0.0f, 0.0f); vertex.tangent.x = mesh->mTangents[i].x; vertex.tangent.y = mesh->mTangents[i].y; vertex.tangent.z = mesh->mTangents[i].z; vertex.biTangent.x = mesh->mBitangents[i].x; vertex.biTangent.y = mesh->mBitangents[i].y; vertex.biTangent.z = mesh->mBitangents[i].z; append(vertex); } for (GLuint i = 0; i < mesh->mNumFaces; ++i) { aiFace face = mesh->mFaces[i]; for (GLuint j = 0; j < face.mNumIndices; ++j) append(face.mIndices[j]); } setupMesh(); return true; }