scenefile

view src/mesh.c @ 0:8c6d64af9505

scenefile
author John Tsiombikas <nuclear@mutantstargoat.com>
date Fri, 13 Jan 2012 09:34:16 +0200
parents
children 38489ad82bf4
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <errno.h>
5 #include "mesh.h"
7 int mattr_init(struct mesh_attrib *ma)
8 {
9 memset(ma, 0, sizeof *ma);
10 return 0;
11 }
13 void mattr_destroy(struct mesh_attrib *ma)
14 {
15 if(ma) {
16 free(ma->name);
17 free(ma->data);
18 }
19 }
21 int mattr_set_name(struct mesh_attrib *ma, const char *name)
22 {
23 char *tmp;
25 if(!(tmp = malloc(strlen(name) + 1))) {
26 return -1;
27 }
28 strcpy(tmp, name);
30 free(ma->name);
31 ma->name = tmp;
32 return 0;
33 }
35 #define INITSZ (16 * ma->elem_size)
36 int mattr_add_elem(struct mesh_attrib *ma, void *data)
37 {
38 int nsz = (ma->count + 1) * ma->elem_size;
40 if(nsz > ma->datasz) {
41 void *tmp;
43 nsz = ma->datasz ? ma->datasz * 2 : INITSZ;
45 if(!(tmp = realloc(ma->data, nsz))) {
46 return -1;
47 }
48 ma->data = tmp;
49 ma->datasz = nsz;
50 }
52 memcpy((char*)ma->data + ma->elem_size * ma->count++, data, ma->elem_size);
53 return 0;
54 }
56 /* -------- mesh -------- */
58 int mesh_init(struct mesh *m)
59 {
60 memset(m, 0, sizeof *m);
61 return 0;
62 }
64 void mesh_destroy(struct mesh *m)
65 {
66 int i;
68 free(m->name);
70 for(i=0; i<m->num_attr; i++) {
71 mattr_destroy(&m->attr[i]);
72 }
73 free(m->attr);
75 for(i=0; i<m->num_attr; i++) {
76 free(m->polyidx[i]);
77 }
78 free(m->polyidx);
79 }
81 int mesh_set_name(struct mesh *m, const char *name)
82 {
83 char *tmp;
85 if(!(tmp = malloc(strlen(name) + 1))) {
86 return -1;
87 }
88 strcpy(tmp, name);
90 free(m->name);
91 m->name = tmp;
92 return 0;
93 }
95 int mesh_add_attrib(struct mesh *m, struct mesh_attrib *attr)
96 {
97 void *tmp;
98 int idx = m->num_attr++;
100 if(!(tmp = realloc(m->attr, m->num_attr * sizeof *attr))) {
101 return -1;
102 }
103 m->attr = tmp;
104 m->attr[idx] = *attr;
106 if(!(tmp = realloc(m->polyidx, m->num_attr * sizeof *m->polyidx))) {
107 m->num_attr--;
108 return -1;
109 }
110 m->polyidx[idx] = 0;
112 return 0;
113 }
115 int mesh_find_attrib(struct mesh *m, const char *name)
116 {
117 int i;
119 for(i=0; i<m->num_attr; i++) {
120 if(strcmp(m->attr[i].name, name) == 0) {
121 return i;
122 }
123 }
124 return -1;
125 }