本文整理汇总了C++中assimp::Importer::ReadFile方法的典型用法代码示例。如果您正苦于以下问题:C++ Importer::ReadFile方法的具体用法?C++ Importer::ReadFile怎么用?C++ Importer::ReadFile使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类assimp::Importer
的用法示例。
在下文中一共展示了Importer::ReadFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: importerTest
virtual bool importerTest() {
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile( ASSIMP_TEST_MODELS_DIR "/OBJ/spider.obj", 0 );
return nullptr != scene;
}
示例2: IndexedMesh
IndexedMesh * MeshLoader::LoadMesh(const std::string &path)
{
// Load the file
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(
path,
aiProcess_Triangulate
| aiProcess_JoinIdenticalVertices
| aiProcess_OptimizeGraph
| aiProcess_OptimizeMeshes
| aiProcess_RemoveRedundantMaterials
| aiProcess_GenSmoothNormals
);
if (scene->HasMeshes())
{
// Get the model mesh
aiMesh &mesh = *scene->mMeshes[0];
if (!mesh.HasPositions() || !mesh.HasFaces())
return NULL;
// Initialize the model
vector<glm::vec3> vertices;
vector<GLuint> indices;
vector<glm::vec4> colors;
vector<glm::vec3> normals;
// Get mesh properties
for (unsigned int i=0; i<mesh.mNumVertices; ++i)
{
// Get vertices
vertices.push_back(glm::vec3(mesh.mVertices[i].x, mesh.mVertices[i].y, mesh.mVertices[i].z));
// Get colors
if(mesh.HasVertexColors(0))
{
colors.push_back(glm::vec4(mesh.mColors[0][i].r, mesh.mColors[0][i].g, mesh.mColors[0][i].b, mesh.mColors[0][i].a));
}
else
{
colors.push_back(glm::vec4(1,1,1,1));
}
// Get normals
normals.push_back(glm::vec3(mesh.mNormals[i].x, mesh.mNormals[i].y, mesh.mNormals[i].z));
}
// Normalize vertices
normalizeVertices(vertices);
// Get indices
for (unsigned int i=0; i<mesh.mNumFaces; ++i)
{
aiFace face = mesh.mFaces[i];
indices.push_back(face.mIndices[0]);
indices.push_back(face.mIndices[1]);
indices.push_back(face.mIndices[2]);
}
return new IndexedMesh(vertices, indices, colors, normals);
}
return NULL;
}
示例3: importerTest
virtual bool importerTest() {
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile( ASSIMP_TEST_MODELS_DIR "/glTF2/BoxTextured-glTF/BoxTextured.gltf", aiProcess_ValidateDataStructure);
return nullptr != scene;
}
示例4: aiZeroVector
Mesh::Mesh(const std::string& fileName) :
m_fileName(fileName),
m_meshData(0)
{
std::map<std::string, MeshData*>::const_iterator it = s_resourceMap.find(fileName);
if(it != s_resourceMap.end())
{
m_meshData = it->second;
m_meshData->AddReference();
}
else
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(("./res/models/" + fileName).c_str(),
aiProcess_Triangulate |
aiProcess_GenSmoothNormals |
aiProcess_FlipUVs |
aiProcess_CalcTangentSpace);
if(!scene)
{
std::cout << "Mesh load failed!: " << fileName << std::endl;
assert(0 == 0);
}
const aiMesh* model = scene->mMeshes[0];
std::vector<Vector3f> positions;
std::vector<Vector2f> texCoords;
std::vector<Vector3f> normals;
std::vector<Vector3f> tangents;
std::vector<unsigned int> indices;
const aiVector3D aiZeroVector(0.0f, 0.0f, 0.0f);
for(unsigned int i = 0; i < model->mNumVertices; i++)
{
const aiVector3D pos = model->mVertices[i];
const aiVector3D normal = model->mNormals[i];
const aiVector3D texCoord = model->HasTextureCoords(0) ? model->mTextureCoords[0][i] : aiZeroVector;
const aiVector3D tangent = model->mTangents[i];
positions.push_back(Vector3f(pos.x, pos.y, pos.z));
texCoords.push_back(Vector2f(texCoord.x, texCoord.y));
normals.push_back(Vector3f(normal.x, normal.y, normal.z));
tangents.push_back(Vector3f(tangent.x, tangent.y, tangent.z));
}
for(unsigned int i = 0; i < model->mNumFaces; i++)
{
const aiFace& face = model->mFaces[i];
assert(face.mNumIndices == 3);
indices.push_back(face.mIndices[0]);
indices.push_back(face.mIndices[1]);
indices.push_back(face.mIndices[2]);
}
m_meshData = new MeshData(IndexedModel(indices, positions, texCoords, normals, tangents));
s_resourceMap.insert(std::pair<std::string, MeshData*>(fileName, m_meshData));
}
}
示例5: Load
S3DModel* CAssParser::Load(const std::string& modelFilePath)
{
LOG_SL(LOG_SECTION_MODEL, L_INFO, "Loading model: %s", modelFilePath.c_str());
const std::string& modelPath = FileSystem::GetDirectory(modelFilePath);
const std::string& modelName = FileSystem::GetBasename(modelFilePath);
// Load the lua metafile. This contains properties unique to Spring models and must return a table
std::string metaFileName = modelFilePath + ".lua";
if (!CFileHandler::FileExists(metaFileName, SPRING_VFS_ZIP)) {
// Try again without the model file extension
metaFileName = modelPath + '/' + modelName + ".lua";
}
if (!CFileHandler::FileExists(metaFileName, SPRING_VFS_ZIP)) {
LOG_SL(LOG_SECTION_MODEL, L_INFO, "No meta-file '%s'. Using defaults.", metaFileName.c_str());
}
LuaParser metaFileParser(metaFileName, SPRING_VFS_MOD_BASE, SPRING_VFS_ZIP);
if (!metaFileParser.Execute()) {
LOG_SL(LOG_SECTION_MODEL, L_INFO, "'%s': %s. Using defaults.", metaFileName.c_str(), metaFileParser.GetErrorLog().c_str());
}
// Get the (root-level) model table
const LuaTable& modelTable = metaFileParser.GetRoot();
if (!modelTable.IsValid()) {
LOG_SL(LOG_SECTION_MODEL, L_INFO, "No valid model metadata in '%s' or no meta-file", metaFileName.c_str());
}
// Create a model importer instance
Assimp::Importer importer;
// Give the importer an IO class that handles Spring's VFS
importer.SetIOHandler(new AssVFSSystem());
// Speed-up processing by skipping things we don't need
importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, ASS_IMPORTER_OPTIONS);
#ifndef BITMAP_NO_OPENGL
{
importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, maxVertices);
importer.SetPropertyInteger(AI_CONFIG_PP_SLM_TRIANGLE_LIMIT, maxIndices / 3);
}
#endif
// Read the model file to build a scene object
LOG_SL(LOG_SECTION_MODEL, L_INFO, "Importing model file: %s", modelFilePath.c_str());
const aiScene* scene = nullptr;
{
// ASSIMP spams many SIGFPEs atm in normal & tangent generation
ScopedDisableFpuExceptions fe;
scene = importer.ReadFile(modelFilePath, ASS_POSTPROCESS_OPTIONS);
}
if (scene != nullptr) {
LOG_SL(LOG_SECTION_MODEL, L_INFO,
"Processing scene for model: %s (%d meshes / %d materials / %d textures)",
modelFilePath.c_str(), scene->mNumMeshes, scene->mNumMaterials,
scene->mNumTextures);
} else {
throw content_error("[AssimpParser] Model Import: " + std::string(importer.GetErrorString()));
}
ModelPieceMap pieceMap;
ParentNameMap parentMap;
S3DModel* model = new S3DModel();
model->name = modelFilePath;
model->type = MODELTYPE_ASS;
// Load textures
FindTextures(model, scene, modelTable, modelPath, modelName);
LOG_SL(LOG_SECTION_MODEL, L_INFO, "Loading textures. Tex1: '%s' Tex2: '%s'", model->texs[0].c_str(), model->texs[1].c_str());
texturehandlerS3O->PreloadTexture(model, modelTable.GetBool("fliptextures", true), modelTable.GetBool("invertteamcolor", true));
// Load all pieces in the model
LOG_SL(LOG_SECTION_MODEL, L_INFO, "Loading pieces from root node '%s'", scene->mRootNode->mName.data);
LoadPiece(model, scene->mRootNode, scene, modelTable, pieceMap, parentMap);
// Update piece hierarchy based on metadata
BuildPieceHierarchy(model, pieceMap, parentMap);
CalculateModelProperties(model, modelTable);
// Verbose logging of model properties
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->name: %s", model->name.c_str());
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->numobjects: %d", model->numPieces);
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->radius: %f", model->radius);
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->height: %f", model->height);
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->mins: (%f,%f,%f)", model->mins[0], model->mins[1], model->mins[2]);
LOG_SL(LOG_SECTION_MODEL, L_DEBUG, "model->maxs: (%f,%f,%f)", model->maxs[0], model->maxs[1], model->maxs[2]);
LOG_SL(LOG_SECTION_MODEL, L_INFO, "Model %s Imported.", model->name.c_str());
return model;
}
示例6: importerTest
virtual bool importerTest() {
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile( ASSIMP_TEST_MODELS_DIR "/X3D/ComputerKeyboard.x3d", aiProcess_ValidateDataStructure );
return nullptr != scene;
}
示例7:
TEST_F( utSTLImporterExporter, test_with_two_solids ) {
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile( ASSIMP_TEST_MODELS_DIR "/STL/triangle_with_two_solids.stl", aiProcess_ValidateDataStructure );
EXPECT_NE( nullptr, scene );
}
示例8: main
//.........这里部分代码省略.........
{
// VERTEXTYPE_MINIMAL
aiComponent_COLORS
| aiComponent_TEXCOORDS
| aiComponent_NORMALS
| aiComponent_TANGENTS_AND_BITANGENTS
| aiComponent_BONEWEIGHTS
| aiComponent_ANIMATIONS
| aiComponent_TEXTURES
| aiComponent_LIGHTS
| aiComponent_CAMERAS
| aiComponent_MATERIALS,
// VERTEXTYPE_SIMPLE
aiComponent_COLORS
| aiComponent_TEXCOORDSn(1)
| aiComponent_TEXCOORDSn(2)
| aiComponent_TEXCOORDSn(3)
| aiComponent_BONEWEIGHTS
| aiComponent_ANIMATIONS
| aiComponent_TEXTURES
| aiComponent_LIGHTS
| aiComponent_CAMERAS
| aiComponent_MATERIALS,
};
importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, removeComponents[format]);
static u32 preProcess[VERTEXTYPE_COUNT] =
{
// VERTEXTYPE_MINIMAL
aiProcess_Triangulate
| aiProcess_RemoveComponent
| aiProcess_JoinIdenticalVertices
| aiProcess_ImproveCacheLocality
| aiProcess_OptimizeMeshes
| aiProcess_FindInstances
| aiProcess_FindInvalidData
| aiProcess_RemoveRedundantMaterials
| aiProcess_FindDegenerates
| aiProcess_ValidateDataStructure,
// VERTEXTYPE_SIMPLE
aiProcess_CalcTangentSpace
| aiProcess_GenNormals
| aiProcess_Triangulate
| aiProcess_RemoveComponent
| aiProcess_JoinIdenticalVertices
| aiProcess_ImproveCacheLocality
| aiProcess_OptimizeMeshes
| aiProcess_FindInstances
| aiProcess_FindInvalidData
| aiProcess_RemoveRedundantMaterials
| aiProcess_FindDegenerates
| aiProcess_ValidateDataStructure,
// VERTEXTYPE_SPRITE
aiProcess_Triangulate
| aiProcess_RemoveComponent
| aiProcess_JoinIdenticalVertices
| aiProcess_ImproveCacheLocality
| aiProcess_OptimizeMeshes
| aiProcess_FindInstances
| aiProcess_FindInvalidData
| aiProcess_RemoveRedundantMaterials
| aiProcess_FindDegenerates
| aiProcess_ValidateDataStructure,
};
const aiScene* scene = importer.ReadFile(argv[1], preProcess[format]);
if ( scene == 0 )
{
fprintf(stderr, "Couldn't load %s.\n", argv[1]);
fprintf(stderr, importer.GetErrorString());
return 42;
}
RemoveExtension(argv[1]);
for ( u32 i = 0 ; i < scene->mNumMeshes ; i++ )
{
aiMesh* mesh = scene->mMeshes[i];
static char filename[4096];
if ( mesh->mName.length != 0 )
{
sprintf(filename, "%s-%s.mesh", argv[1], mesh->mName.data);
}
else
{
sprintf(filename, "%s-%d.mesh", argv[1], i + 1);
}
printf("Exporting %d:\"%s\" to %s...\n", i + 1, mesh->mName.data, filename);
ExportMesh(mesh, filename, format);
}
return 0;
}
示例9: Initialize
void MultiLightDemo::Initialize()
{
glEnable(GL_DEPTH_TEST);
glClearColor(0.3f, 0.2f, 0.7f, 1.0f);
program.AddShaderFile(ShaderType::Vertex, "Assets/Shaders/Vertex/multiLight.vert");
program.AddShaderFile(ShaderType::Fragment, "Assets/Shaders/Fragment/multiLight.frag");
program.Build();
program.AddUniformBlock({ "TransformBlock",{
{ "TransformBlock.view",&camera->GetView()[0][0], sizeof(camera->GetView()) },
{ "TransformBlock.projection",&camera->GetProjection()[0][0], sizeof(camera->GetProjection()) },
{ "TransformBlock.eyePosition",&camera->GetPosition()[0], sizeof(camera->GetPosition()) },
} });
lights[0].position = glm::vec3(0.0f, 0.0f, -2.0f);
lights[1].position = glm::vec3(-2.0f, -3.0f, -2.0f);
lights[2].position = glm::vec3(4.0f, 7.0f, -2.0f);
lights[0].color = glm::vec3(0.9f,0.5f,0.3f);
lights[1].color = glm::vec3(0.2f,0.9f,0.2f);
lights[2].color = glm::vec3(0.2f,0.4f,0.9f);
program.AddUniform("lights[0].position", &lights[0].position[0], UniformType::VEC3);
program.AddUniform("lights[0].color", &lights[0].color[0], UniformType::VEC3);
program.AddUniform("lights[1].position", &lights[1].position[0], UniformType::VEC3);
program.AddUniform("lights[1].color", &lights[1].color[0], UniformType::VEC3);
program.AddUniform("lights[2].position", &lights[2].position[0], UniformType::VEC3);
program.AddUniform("lights[2].color", &lights[2].color[0], UniformType::VEC3);
input->addBinding(GLFW_KEY_LEFT, [this](InputInfo info) {
camera->MoveLeft();
program.UpdateUniformBlock("TransformBlock");
});
input->addBinding(GLFW_KEY_RIGHT, [this](InputInfo info) {
camera->MoveRight();
program.UpdateUniformBlock("TransformBlock");
});
input->addBinding(GLFW_KEY_UP, [this](InputInfo info) {
camera->MoveForward();
program.UpdateUniformBlock("TransformBlock");
});
input->addBinding(GLFW_KEY_DOWN, [this](InputInfo info) {
camera->MoveBack();
program.UpdateUniformBlock("TransformBlock");
});
//program.AddUniform("light[0].position", &lights[0].position[0], UniformType::VEC3);
//program.AddUniform("light[0].color", &lights[0].color[0], UniformType::VEC3);
//program.AddUniform("light[1].position", &lights[1].position[0], UniformType::VEC3);
//program.AddUniform("light[1].color", &lights[1].color[0], UniformType::VEC3);
//program.AddUniform("light[2].position", &lights[2].position[0], UniformType::VEC3);
//program.AddUniform("light[2].color", &lights[2].color[0], UniformType::VEC3);
using std::unique_ptr;
monkey = unique_ptr<GameObject>(new GameObject());
monkey->GetTransform()->SetPosition({ 0.0f,0.0f,-5.0f });
monkey->Update();
Assimp::Importer importer;
auto scene = importer.ReadFile("Assets/Models/Obj/monkey.obj", aiProcess_Triangulate);
if (scene && scene->HasMeshes())
{
mesh = unique_ptr<MeshComponent>(new MeshComponent(monkey.get()));
mesh->Initialize(scene->mMeshes[0], program, {
{ "world", UniformType::MAT4, &monkey->GetWorld()[0][0] },
{ "material.ambient", UniformType::VEC3, &mesh->GetMaterial().ambient[0] },
{ "material.diffuse", UniformType::VEC3, &mesh->GetMaterial().diffuse[0] },
{ "material.specular", UniformType::VEC4, &mesh->GetMaterial().specular[0] },
});
monkey->AddComponent(mesh.get());
}
mesh->GetMaterial().ambient = glm::vec3(0.6f, 0.7f, 0.1f);
mesh->GetMaterial().diffuse = glm::vec3(0.5f, 0.2f, 0.8f);
mesh->GetMaterial().specular = glm::vec4(0.3f, 0.2f, 0.2f, 10.0f);
importer.FreeScene();
}
示例10: vbuf
std::shared_ptr<gameplay::Model> OBJWriter::readModel(const boost::filesystem::path& path, const std::shared_ptr<gameplay::ShaderProgram>& shaderProgram, const glm::vec3& ambientColor) const
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile((m_basePath / path).string(), aiProcess_JoinIdenticalVertices | aiProcess_Triangulate | aiProcess_ValidateDataStructure | aiProcess_FlipUVs);
BOOST_ASSERT(scene != nullptr);
auto renderModel = std::make_shared<gameplay::Model>();
for( unsigned int mi = 0; mi < scene->mNumMeshes; ++mi )
{
BOOST_LOG_TRIVIAL(info) << "Converting mesh " << mi + 1 << " of " << scene->mNumMeshes << " from " << m_basePath / path;
const aiMesh* mesh = scene->mMeshes[mi];
if( mesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE )
BOOST_THROW_EXCEPTION(std::runtime_error("Mesh does not consist of triangles only"));
if( !mesh->HasTextureCoords(0) )
BOOST_THROW_EXCEPTION(std::runtime_error("Mesh does not have UV coordinates"));
if( mesh->mNumUVComponents[0] != 2 )
BOOST_THROW_EXCEPTION(std::runtime_error("Mesh does not have a 2D UV channel"));
if( !mesh->HasFaces() )
BOOST_THROW_EXCEPTION(std::runtime_error("Mesh does not have faces"));
if( !mesh->HasPositions() )
BOOST_THROW_EXCEPTION(std::runtime_error("Mesh does not have positions"));
std::shared_ptr<gameplay::Mesh> renderMesh;
if( mesh->HasNormals() )
{
std::vector<VDataNormal> vbuf(mesh->mNumVertices);
for( unsigned int i = 0; i < mesh->mNumVertices; ++i )
{
vbuf[i].position = glm::vec3{mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z} * static_cast<float>(SectorSize);
vbuf[i].normal = glm::vec3{mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z};
vbuf[i].uv = glm::vec2{mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y};
if( mesh->HasVertexColors(0) )
vbuf[i].color = glm::vec4(mesh->mColors[0][i].r, mesh->mColors[0][i].g, mesh->mColors[0][i].b, mesh->mColors[0][i].a);
else
vbuf[i].color = glm::vec4(ambientColor, 1);
}
renderMesh = std::make_shared<gameplay::Mesh>(VDataNormal::getFormat(), mesh->mNumVertices, false);
renderMesh->rebuild(reinterpret_cast<const float*>(vbuf.data()), mesh->mNumVertices);
}
else
{
std::vector<VData> vbuf(mesh->mNumVertices);
for( unsigned int i = 0; i < mesh->mNumVertices; ++i )
{
vbuf[i].position = glm::vec3{mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z} * static_cast<float>(SectorSize);
vbuf[i].uv = glm::vec2{mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y};
if( mesh->HasVertexColors(0) )
vbuf[i].color = glm::vec4(mesh->mColors[0][i].r, mesh->mColors[0][i].g, mesh->mColors[0][i].b, mesh->mColors[0][i].a);
else
vbuf[i].color = glm::vec4(ambientColor, 1);
}
renderMesh = std::make_shared<gameplay::Mesh>(VData::getFormat(), mesh->mNumVertices, false);
renderMesh->rebuild(reinterpret_cast<const float*>(vbuf.data()), mesh->mNumVertices);
}
std::vector<uint32_t> faces;
for( const aiFace& face : gsl::span<aiFace>(mesh->mFaces, mesh->mNumFaces) )
{
BOOST_ASSERT(face.mNumIndices == 3);
faces.push_back(face.mIndices[0]);
faces.push_back(face.mIndices[1]);
faces.push_back(face.mIndices[2]);
}
auto part = renderMesh->addPart(gameplay::Mesh::TRIANGLES, gameplay::Mesh::INDEX32, mesh->mNumFaces * 3, false);
part->setIndexData(faces.data(), 0, faces.size());
const aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
aiString textureName;
if( material->GetTexture(aiTextureType_DIFFUSE, 0, &textureName) != aiReturn_SUCCESS )
BOOST_THROW_EXCEPTION(std::runtime_error("Failed to get diffuse texture path from mesh"));
part->setMaterial(readMaterial(textureName.C_Str(), shaderProgram));
renderModel->addMesh(renderMesh);
}
return renderModel;
}
示例11: LoadAssimp
void ObjLoader::LoadAssimp( const std::string &FileName )
{
auto t0 = std::chrono::high_resolution_clock::now();
Assimp::Importer Importer;
const aiScene *scene = Importer.ReadFile( FileName,
aiProcessPreset_TargetRealtime_Quality );
if( !scene )
{
std::cout << "ASSIMP cos poszlo nie tak\n";
std::cout << "ASSIMP ERROR: " << Importer.GetErrorString() << std::endl;
}
//w petli przez wszystkie meshe
const aiMesh * mesh = scene->mMeshes[0];
for( uint t = 0; t < mesh->mNumFaces ; t++ )
{
const aiFace *face = &mesh->mFaces[ t ] ;
mGpuIndices.push_back( face->mIndices[ 0 ] );
mGpuIndices.push_back( face->mIndices[ 1 ] );
mGpuIndices.push_back( face->mIndices[ 2 ] );
}
// verteksy
if( mesh->HasPositions() )
{
mVertex.resize( mesh->mNumVertices );
memcpy( &mVertex[0], mesh->mVertices, 3*4* mesh->mNumVertices );
}
if( mesh->HasNormals() )
{
mNormals.resize( mesh->mNumVertices );
memcpy( &mNormals[0], mesh->mNormals, 3*4* mesh->mNumVertices );
}
if( mesh->HasTextureCoords(0) )
{
for( uint k = 0; k < mesh->mNumVertices; ++k )
{
glm::vec2 tmp;
tmp.x = mesh->mTextureCoords[0][k].x;
tmp.y = mesh->mTextureCoords[0][k].y;
mTexcoords.push_back( tmp );
}
}
mGpuBuffer.resize( mesh->mNumVertices*8);
for( uint i = 0; i < mesh->mNumVertices; ++i )
{
mGpuBuffer[ i*8 ] = mVertex[ i ].x;
mGpuBuffer[ i*8 +1 ] = mVertex[ i ].y;
mGpuBuffer[ i*8 +2] = mVertex[ i ].z;
mGpuBuffer[ i*8 +3] = mNormals[ i ].x;
mGpuBuffer[ i*8 +4] = mNormals[ i ].y;
mGpuBuffer[ i*8 +5] = mNormals[ i ].z;
if( mesh->HasTextureCoords(0) ) {
mGpuBuffer[i * 8 + 6] = mTexcoords[i].s;
mGpuBuffer[i * 8 + 7] = mTexcoords[i].t;
}
}
auto t1 = std::chrono::high_resolution_clock::now();
std::chrono::milliseconds total_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);
std::cout << "Time: " << total_ms.count() << " ms " << std::endl;
Surface *pSurface = new Surface();
VertexBufferManager &VBOMan = VertexBufferManager::GetSingleton();
IndexBuffer *pIndex = VBOMan.CreateIndexBuffer();
pIndex->SetIndexData( mGpuIndices );
pIndex->Prepare();
VertexDeclaration *pDecl = VBOMan.GetVertexDeclaration( "Default" );
VertexSettings( PT_TRIANGLE, UT_STATIC_DRAW, pIndex, pDecl );
VertexBuffer *pVertex = VBOMan.CreateVertexBuffer(
VertexSettings( PT_TRIANGLE, UT_STATIC_DRAW, pIndex, pDecl ) );
pVertex->SetVertexData( mGpuBuffer );
pVertex->Prepare();
pSurface->SetVertexBuffer( pVertex );
mSurfaces.push_back( pSurface );
}
示例12: loadModel
// Load a model from file using the ASSIMP model loader and generate all resources required to render the model
void loadModel(std::string filename)
{
// Load the model from file using ASSIMP
const aiScene* scene;
Assimp::Importer Importer;
// Flags for loading the mesh
static const int assimpFlags = aiProcess_FlipWindingOrder | aiProcess_Triangulate | aiProcess_PreTransformVertices;
#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(androidApp->activity->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);
scene = Importer.ReadFileFromMemory(meshData, size, assimpFlags);
free(meshData);
#else
scene = Importer.ReadFile(filename.c_str(), assimpFlags);
#endif
// Generate vertex buffer from ASSIMP scene data
float scale = 1.0f;
std::vector<Vertex> vertexBuffer;
// Iterate through all meshes in the file and extract the vertex components
for (uint32_t m = 0; m < scene->mNumMeshes; m++)
{
for (uint32_t v = 0; v < scene->mMeshes[m]->mNumVertices; v++)
{
Vertex vertex;
// Use glm make_* functions to convert ASSIMP vectors to glm vectors
vertex.pos = glm::make_vec3(&scene->mMeshes[m]->mVertices[v].x) * scale;
vertex.normal = glm::make_vec3(&scene->mMeshes[m]->mNormals[v].x);
// Texture coordinates and colors may have multiple channels, we only use the first [0] one
vertex.uv = glm::make_vec2(&scene->mMeshes[m]->mTextureCoords[0][v].x);
// Mesh may not have vertex colors
vertex.color = (scene->mMeshes[m]->HasVertexColors(0)) ? glm::make_vec3(&scene->mMeshes[m]->mColors[0][v].r) : glm::vec3(1.0f);
// Vulkan uses a right-handed NDC (contrary to OpenGL), so simply flip Y-Axis
vertex.pos.y *= -1.0f;
vertexBuffer.push_back(vertex);
}
}
size_t vertexBufferSize = vertexBuffer.size() * sizeof(Vertex);
// Generate index buffer from ASSIMP scene data
std::vector<uint32_t> indexBuffer;
for (uint32_t m = 0; m < scene->mNumMeshes; m++)
{
uint32_t indexBase = static_cast<uint32_t>(indexBuffer.size());
for (uint32_t f = 0; f < scene->mMeshes[m]->mNumFaces; f++)
{
// We assume that all faces are triangulated
for (uint32_t i = 0; i < 3; i++)
{
indexBuffer.push_back(scene->mMeshes[m]->mFaces[f].mIndices[i] + indexBase);
}
}
}
size_t indexBufferSize = indexBuffer.size() * sizeof(uint32_t);
model.indices.count = static_cast<uint32_t>(indexBuffer.size());
// Static mesh should always be device local
bool useStaging = true;
if (useStaging)
{
struct {
VkBuffer buffer;
VkDeviceMemory memory;
} vertexStaging, indexStaging;
// Create staging buffers
// Vertex data
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
vertexBufferSize,
&vertexStaging.buffer,
&vertexStaging.memory,
vertexBuffer.data()));
// Index data
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
//.........这里部分代码省略.........
示例13: t
BumpedTexturedMesh * MeshLoader::LoadBumpedMesh(const std::string &path, const string &texturePath, const string &normalPath)
{
// Load the file
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(
path,
aiProcess_Triangulate
| aiProcess_JoinIdenticalVertices
| aiProcess_OptimizeGraph
| aiProcess_OptimizeMeshes
| aiProcess_RemoveRedundantMaterials
| aiProcess_GenSmoothNormals
| aiProcess_CalcTangentSpace
);
if (scene->HasMeshes())
{
// Get the model mesh
aiMesh &mesh = *scene->mMeshes[0];
if (!mesh.HasPositions() || !mesh.HasFaces())
return NULL;
// Initialize the model
vector<glm::vec3> vertices;
vector<GLuint> indices;
vector<glm::vec3> normals;
vector<glm::vec2> uvs;
vector<glm::vec4> tangents;
// Get mesh properties
for (unsigned int i=0; i<mesh.mNumVertices; ++i)
{
// Get vertices
vertices.push_back(glm::vec3(mesh.mVertices[i].x, mesh.mVertices[i].y, mesh.mVertices[i].z));
//vertices[vertices.size()-1] /= 38;
// Get normals
normals.push_back(glm::vec3(mesh.mNormals[i].x, mesh.mNormals[i].y, mesh.mNormals[i].z));
// Get UVs
uvs.push_back(glm::vec2(mesh.mTextureCoords[0][i].x, mesh.mTextureCoords[0][i].y));
if (mesh.HasTangentsAndBitangents())
{
const aiVector3D tangent = mesh.mTangents[i];
const aiVector3D bitangent = mesh.mBitangents[i];
// put the three vectors into my vec3 struct format for doing maths
vec3 t (tangent.x, tangent.y, tangent.z);
vec3 b (bitangent.x, bitangent.y, bitangent.z);
// orthogonalise and normalise the tangent so we can use it in something
// approximating a T,N,B inverse matrix
vec3 t_i = t - normals[i] * dot (normals[i], t);
//5std::cout << i << ": " << t_i.x << " " << t_i.y << " " << t_i.z << std::endl;
if(!isnan(t_i.x)) t_i = normalize(t_i);
// get determinant of T,B,N 3x3 matrix by dot*cross method
float det = (dot (cross (normals[i], t), b));
if (det < 0.0f) {
det = -1.0f;
} else {
det = 1.0f;
}
tangents.push_back(vec4(t_i, det));
}
}
// Normalize vertices
normalizeVertices(vertices);
// Get indices
for (unsigned int i=0; i<mesh.mNumFaces; ++i)
{
aiFace face = mesh.mFaces[i];
indices.push_back(face.mIndices[0]);
indices.push_back(face.mIndices[1]);
indices.push_back(face.mIndices[2]);
}
BumpedTexturedMesh * modelMesh = new BumpedTexturedMesh(vertices, indices, normals, uvs, tangents);
modelMesh->SetTexture(loadTexture(texturePath));
modelMesh->SetNormalTexture(loadTexture(normalPath));
return modelMesh;
}
return NULL;
}
示例14: Load
bool Mesh::Load ( const char* filePath )
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile ( filePath,
aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices |
aiProcess_FlipWindingOrder |
aiProcess_CalcTangentSpace );
if ( !scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode )
{
return false;
}
for ( unsigned int i = 0; i < scene->mNumMeshes; ++i )
{
SubMesh* submesh = new SubMesh;
const aiMesh* aimesh = scene->mMeshes[i];
///// VERTEX BUFFER /////
submesh->m_vertexCount = aimesh->mNumVertices;
submesh->m_verts = malloc( sizeof( Vertex ) * submesh->m_vertexCount );
Vertex* vertBuffer = ( Vertex* )submesh->m_verts;
for ( unsigned int j = 0; j < aimesh->mNumVertices; ++j )
{
Vertex v;
v.pos[0] = aimesh->mVertices[j].x;
v.pos[1] = aimesh->mVertices[j].y;
v.pos[2] = aimesh->mVertices[j].z;
if ( aimesh->mNormals )
{
v.norm[0] = aimesh->mNormals[j].x;
v.norm[1] = aimesh->mNormals[j].y;
v.norm[2] = aimesh->mNormals[j].z;
}
else
{
v.norm[0] = 0;
v.norm[1] = 0;
v.norm[2] = 0;
}
if ( aimesh->mTextureCoords[0] )
{
v.uv[0] = aimesh->mTextureCoords[0][j].x;
v.uv[1] = aimesh->mTextureCoords[0][j].y;
}
else
{
v.uv[0] = 0;
v.uv[1] = 0;
}
if ( aimesh->mTangents )
{
v.tanget[0] = aimesh->mTangents[j].x;
v.tanget[1] = aimesh->mTangents[j].y;
v.tanget[2] = aimesh->mTangents[j].z;
}
else
{
v.tanget[0] = 0;
v.tanget[1] = 0;
v.tanget[2] = 0;
}
if ( aimesh->mBitangents )
{
v.bitangent[0] = aimesh->mBitangents[j].x;
v.bitangent[1] = aimesh->mBitangents[j].y;
v.bitangent[2] = aimesh->mBitangents[j].z;
}
else
{
v.bitangent[0] = 0;
v.bitangent[1] = 0;
v.bitangent[2] = 0;
}
vertBuffer[j] = v;
}
submesh->m_vertexHandle = GraphicsManager::Instance().CreateVertexBuffer( submesh->m_verts, sizeof( Vertex ) * submesh->m_vertexCount );
///// INDEX BUFFER /////
submesh->m_indexCount = aimesh->mNumFaces * 3; // 3 verts per face
submesh->m_indices = ( uint16_t* )malloc( submesh->m_indexCount * sizeof( uint16_t ) );
uint16_t idx = 0;
for ( unsigned int j = 0; j < aimesh->mNumFaces; ++j )
{
const aiFace& face = aimesh->mFaces[j];
if ( face.mNumIndices != 3 )
return false;
for ( uint8_t k = 0; k < 3; ++k )
{
dDAssert( idx < aimesh->mNumFaces * 3 );
submesh->m_indices[idx++] = face.mIndices[k];
}
}
//.........这里部分代码省略.........
示例15: TexturedIndexedMesh
TexturedIndexedMesh * MeshLoader::LoadMesh(const std::string &path, const string &texturePath)
{
// Load the file
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(
path,
aiProcess_Triangulate
| aiProcess_JoinIdenticalVertices
| aiProcess_OptimizeGraph
| aiProcess_OptimizeMeshes
| aiProcess_RemoveRedundantMaterials
| aiProcess_GenSmoothNormals
);
if (scene->HasMeshes())
{
// Get the model mesh
aiMesh &mesh = *scene->mMeshes[0];
if (!mesh.HasPositions() || !mesh.HasFaces())
return NULL;
// Initialize the model
vector<glm::vec3> vertices;
vector<GLuint> indices;
vector<glm::vec3> normals;
vector<glm::vec2> uvs;
// Get mesh properties
for (unsigned int i=0; i<mesh.mNumVertices; ++i)
{
// Get vertices
vertices.push_back(glm::vec3(mesh.mVertices[i].x, mesh.mVertices[i].y, mesh.mVertices[i].z));
//vertices[vertices.size()-1] /= 38;
// Get normals
normals.push_back(glm::vec3(mesh.mNormals[i].x, mesh.mNormals[i].y, mesh.mNormals[i].z));
// Get UVs
uvs.push_back(glm::vec2(mesh.mTextureCoords[0][i].x, mesh.mTextureCoords[0][i].y));
}
// Normalize vertices
normalizeVertices(vertices);
// Get indices
for (unsigned int i=0; i<mesh.mNumFaces; ++i)
{
aiFace face = mesh.mFaces[i];
indices.push_back(face.mIndices[0]);
indices.push_back(face.mIndices[1]);
indices.push_back(face.mIndices[2]);
}
TexturedIndexedMesh * modelMesh = new TexturedIndexedMesh(vertices, indices, normals, uvs);
modelMesh->SetTexture(loadTexture(texturePath));
return modelMesh;
}
return NULL;
}