Skip to content

Instantly share code, notes, and snippets.

@tilkinsc
Created September 8, 2017 08:52
Show Gist options
  • Save tilkinsc/661d9da4a4121101a182b8880857f6fb to your computer and use it in GitHub Desktop.
Save tilkinsc/661d9da4a4121101a182b8880857f6fb to your computer and use it in GitHub Desktop.
Pure C Assimp model file loading example
VAO* load_model(const char* path) {
// import model
const struct aiScene* scene = aiImportFile(path, aiProcess_Triangulate); // http://assimp.sourceforge.net/lib_html/structai_scene.html
if(scene->mNumMeshes <= 0) {
aiReleaseImport(scene);
return 0;
}
struct aiMesh* mesh = *scene->mMeshes; // http://assimp.sourceforge.net/lib_html/structai_mesh.html
// allocate memory
float* farr = malloc(2 * mesh[0].mNumVertices * sizeof(float));
if(farr == 0) {
// TODO: Handle OOM
aiReleaseImport(scene);
return 0;
}
unsigned int* iarr = malloc(3 * mesh[0].mNumFaces * sizeof(unsigned int));
if(iarr == 0) {
// TODO: Handle OOM
free(farr);
aiReleaseImport(scene);
return 0;
}
// copy tex coords from stupid 3d texcoord array
unsigned int farr_count = 0;
for(int i=0; i<mesh[0].mNumVertices; i++) {
farr[farr_count++] = mesh[0].mTextureCoords[0][i].x;
farr[farr_count++] = mesh[0].mTextureCoords[0][i].y;
}
// copy indices from stupid array format
unsigned int iarr_count = 0;
for(int i=0; i<mesh[0].mNumFaces; i++) {
iarr[iarr_count++] = mesh[0].mFaces[i].mIndices[0];
iarr[iarr_count++] = mesh[0].mFaces[i].mIndices[1];
iarr[iarr_count++] = mesh[0].mFaces[i].mIndices[2];
}
// upload data to a vao, this is my code, but you should already know this part
globj_newModel(3);
globj_pushVbo(3 * mesh[0].mNumVertices * sizeof(float), 3, (float*) mesh[0].mVertices);
globj_pushVbo(2 * mesh[0].mNumVertices * sizeof(float), 2, farr);
globj_pushVbo(3 * mesh[0].mNumVertices * sizeof(float), 3, (float*) mesh[0].mNormals);
globj_pushIbo(iarr_count * sizeof(unsigned int), iarr);
// free arrays
free(iarr);
free(farr);
// free scene
aiReleaseImport(scene);
// finalizes model
return globj_finalize(mesh[0].mNumVertices);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment