joeylib3d/main.c

136 lines
2.7 KiB
C

#include <stdio.h>
#include <math.h>
#include "utarray.h"
#define JOEY_MAIN
#include "joey.h"
#ifdef JOEY_IIGS
segment "j3d";
#endif
#pragma GCC diagnostic push
//#pragma GCC diagnostic ignored "-Wcast-align"
typedef struct {
float x;
float y;
float z;
} j3VertexT;
typedef struct {
j3VertexT local[3];
j3VertexT world[3];
j3VertexT camera[3];
} j3TriangleT;
typedef struct {
UT_array *verticies;
UT_array *triangles;
} j3ObjectT;
typedef struct {
UT_array *objects;
} j3WorldT;
static UT_icd j3VertexT_icd = { sizeof(j3VertexT), NULL, NULL, NULL };
static UT_icd j3TriangleT_icd = { sizeof(j3TriangleT), NULL, NULL, NULL };
static UT_icd j3WorldT_icd = { sizeof(j3WorldT), NULL, NULL, NULL };
bool j3WorldLoad(char *file, j3WorldT *world);
bool j3WorldLoad(char *file, j3WorldT *world) {
int r;
int x;
char token[1024];
char *c;
FILE *in;
j3VertexT *vp;
j3VertexT v;
j3ObjectT o;
j3TriangleT t;
in = fopen(jlUtilMakePathname(file, "obj"), "rt");
// Did we find the file?
if (in == NULL) {
// Nope.
return false;
}
// Initialize object array inside world object
utarray_new(world->objects, &j3WorldT_icd);
// Create an initial object to read data into (***TODO*** support multiple objects)
utarray_new(o.verticies, &j3VertexT_icd);
utarray_new(o.triangles, &j3TriangleT_icd);
while (true) {
// Read next token
r = fscanf(in, "%s", token);
//printf("fscanf s = %d [%s]\n", r, token);
// End of file?
if (r == EOF) {
break;
}
// Vertex?
if (strcmp(token, "v" ) == 0) {
r = fscanf(in, "%f %f %f\n", &v.x, &v.y, &v.z);
//printf("fscanf f f f = %d [%s]\n", r, token);
//printf("Vertex: %f %f %f\n", v.x, v.y, v.z);
utarray_push_back(o.verticies, &v);
}
// Face?
if (strcmp(token, "f" ) == 0) {
//printf("Triangle:\n");
for (x=0; x<3; x++) {
// Fetch 'x'th vertex index
r = fscanf(in, "%s", token);
//printf("fscanf s = %d [%s]\n", r, token);
c = strstr(token, "/");
if (c) c[0] = 0;
r = atoi(token);
//printf("atoi = %d\n", r);
vp = (j3VertexT *)utarray_eltptr(o.verticies, (unsigned int)r - 1);
t.local[x] = *vp;
//printf(" Face Index: %s Vertex: %f %f %f\n", token, vp->x, vp->y, vp->z);
}
fscanf(in, "\n");
utarray_push_back(o.triangles, &t);
}
}
// Finished! Clean up.
fclose(in);
return true;
}
int main(void) {
j3WorldT world;
j3ObjectT *object;
jlUtilStartup("JoeyLib 3D");
j3WorldLoad("cube", &world);
printf("Made it here\n");
object = (j3ObjectT *)utarray_front(world.objects);
printf("Verticies: %d\n", utarray_len(object->verticies));
printf("Triangles: %d\n", utarray_len(object->triangles));
jlKeyWaitForAny();
jlUtilShutdown();
}
#pragma GCC diagnostic pop