scene.c (2669B)
1 #include "../inc/scene.h" /* for Scene, Mesh, Material */ 2 #include "../inc/materials.h" /* for g_hrt_materials */ 3 #include "../inc/common.h" /* for PERROT_CLEANUP_EXIT */ 4 5 #include <stdio.h> /* for fopen, FILE, fclose */ 6 7 void scene_save( 8 IN Scene* scene, 9 IN const char* filepath 10 ) 11 { 12 FILE *fp = fopen(filepath, "wb"); 13 if (fp == NULL) 14 PERROR_CLEANUP_EXIT("Error: cannot open file", 8); 15 16 /* MAGIC */ 17 fwrite("HRT", 1, 3, fp); 18 /* SCENE */ 19 /* num_meshes */ 20 fwrite(&scene->num_meshes, sizeof(uint32_t), 1, fp); 21 /* meshes */ 22 for (uint32_t i = 0; i != scene->num_meshes; ++i) { 23 /* MESH */ 24 Mesh *mesh = &scene->meshes[i]; 25 fwrite(&mesh->num_vertices, sizeof(uint32_t), 1, fp); 26 fwrite(mesh->vs, sizeof(Vec3), mesh->num_vertices, fp); 27 fwrite(&mesh->num_triangles, sizeof(uint32_t), 1, fp); 28 fwrite(mesh->is, sizeof(uint32_t), 3 * mesh->num_triangles, fp); 29 fwrite(&mesh->material_index, sizeof(uint32_t), 1, fp); 30 fwrite(&mesh->velocity, sizeof(Vec3), 1, fp); 31 } 32 33 fclose(fp); 34 } 35 36 Scene scene_load(IN const char *filepath) 37 { 38 /* Open the HRT file */ 39 FILE *f = fopen(filepath, "rb"); 40 if (f == NULL) 41 PERROR_CLEANUP_EXIT("Could not open scene file", 8); 42 43 /* Parse the file */ 44 /* MAGIC */ 45 char magic[3]; 46 if (fread(magic, 1, 3, f) != 3) exit(8); 47 if (strncmp(magic, "HRT", 3)) exit(8); 48 /* SCENE */ 49 Scene scene; 50 /* num_meshes */ 51 if (fread(&scene.num_meshes, sizeof(uint32_t), 1, f) != 1) exit(8); 52 if (scene.num_meshes == 0) 53 PERROR_CLEANUP_EXIT("Scene has no meshes", 8); 54 if (scene.num_meshes > 1000) 55 PERROR_CLEANUP_EXIT("Scene has too many meshes", 8); 56 /* meshes */ 57 scene.meshes = (Mesh*)malloc(scene.num_meshes * sizeof(Mesh)); 58 for (uint32_t i = 0; i != scene.num_meshes; ++i) { 59 /* MESH */ 60 Mesh *mesh = &scene.meshes[i]; 61 /* num_vertices */ 62 if(fread(&mesh->num_vertices, sizeof(uint32_t), 1, f) != 1) exit(8); 63 /* vertices */ 64 mesh->vs = (Vec3*)malloc(mesh->num_vertices * sizeof(Vec3)); 65 if (fread(mesh->vs, sizeof(float) * 3, mesh->num_vertices, f) != mesh->num_vertices) 66 exit(8); 67 /* num_triangles */ 68 if (fread(&mesh->num_triangles, sizeof(uint32_t), 1, f) != 1) exit(8); 69 /* triangles */ 70 mesh->is = (uint32_t*)malloc(mesh->num_triangles * 3 * sizeof(uint32_t)); 71 if (fread(mesh->is, sizeof(uint32_t), mesh->num_triangles * 3, f) != mesh->num_triangles * 3) 72 exit(8); 73 /* material_index */ 74 if (fread(&mesh->material_index, sizeof(uint32_t), 1, f) != 1) exit(8); 75 /* velocity */ 76 if (fread(&mesh->velocity, sizeof(Vec3), 1, f) != 1) exit(8); 77 /* normals */ 78 mesh->ns = NULL; 79 } 80 81 fclose(f); 82 return scene; 83 } 84