-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathobj.c
74 lines (62 loc) · 1.35 KB
/
obj.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "mathx.h"
#include "mesh.h"
static const char *skip_space(const char *str)
{
while (isspace(*str))
str++;
return str;
}
static const char *skip_non_space(const char *str)
{
while (*str && !isspace(*str))
str++;
return str;
}
struct mesh *obj_read(const char *file)
{
FILE *f;
char line[512];
const char *str;
struct mesh *mesh;
int has_normals = 0;
if (!(f = fopen(file, "r")))
return NULL;
mesh = mesh_create();
while (!feof(f)) {
if (!fgets(line, sizeof(line), f))
break;
str = line;
if (strncmp(str, "v ", 2) == 0) {
/* Vertex command */
vector v;
sscanf(str, "v %f %f %f", v, v + 1, v + 2);
mesh_add_vertex(mesh, v);
} else if (strncmp(str, "vn ", 3) == 0) {
/* Normal command */
vector n;
sscanf(str, "vn %f %f %f", n, n + 1, n + 2);
mesh_add_normal(mesh, n);
} else if (strncmp(str, "f ", 2) == 0) {
/* Face command */
int vi, ti, ni;
mesh_begin_face(mesh);
str = skip_space(++str); /* Skip 'f ' */
while (*str) {
vi = ti = ni = 0;
if (sscanf(str, "%d/%d/%d", &vi, &ti, &ni) == 3)
has_normals = 1;
mesh_add_index(mesh, vi - 1, ni - 1);
str = skip_non_space(str);
str = skip_space(str);
}
mesh_end_face(mesh);
}
}
fclose(f);
if (!has_normals)
mesh_compute_normals(mesh);
return mesh;
}