updated files from meshfrac_alt
[meshfrac] / src / cmesh.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <limits.h>
5 #include <float.h>
6 #include <assert.h>
7 #include "opengl.h"
8 #include "cmesh.h"
9
10
11 struct cmesh_vattrib {
12         int nelem;      /* num elements per attribute [1, 4] */
13         float *data;
14         unsigned int count;     /* number of floats in data */
15         unsigned int vbo;
16         int vbo_valid, data_valid;
17 };
18
19 /* istart,icount are valid only when the mesh is indexed, otherwise icount is 0.
20  * vstart,vcount are define the submesh for non-indexed meshes.
21  * For indexed meshes, vstart,vcount denote the range of vertices used by each
22  * submesh.
23  */
24 struct submesh {
25         char *name;
26         int nfaces;     /* derived from either icount or vcount */
27         int istart, icount;
28         int vstart, vcount;
29         struct submesh *next;
30 };
31
32 struct cmesh {
33         char *name;
34         unsigned int nverts, nfaces;
35
36         struct submesh *sublist, *subtail;
37         int subcount;
38
39         /* current value for each attribute for the immediate mode interface */
40         cgm_vec4 cur_val[CMESH_NUM_ATTR];
41
42         unsigned int buffer_objects[CMESH_NUM_ATTR + 1];
43         struct cmesh_vattrib vattr[CMESH_NUM_ATTR];
44
45         unsigned int *idata;
46         unsigned int icount;
47         unsigned int ibo;
48         int ibo_valid, idata_valid;
49
50         /* index buffer for wireframe rendering (constructed on demand) */
51         unsigned int wire_ibo;
52         int wire_ibo_valid;
53
54         /* axis-aligned bounding box */
55         cgm_vec3 aabb_min, aabb_max;
56         int aabb_valid;
57         /* bounding sphere */
58         cgm_vec3 bsph_center;
59         float bsph_radius;
60         int bsph_valid;
61 };
62
63
64 static int clone(struct cmesh *cmdest, const struct cmesh *cmsrc, struct submesh *sub);
65 static int pre_draw(const struct cmesh *cm);
66 static void post_draw(const struct cmesh *cm, int cur_sdr);
67 static void update_buffers(struct cmesh *cm);
68 static void update_wire_ibo(struct cmesh *cm);
69 static void calc_aabb(struct cmesh *cm);
70 static void calc_bsph(struct cmesh *cm);
71
72 static int def_nelem[CMESH_NUM_ATTR] = {3, 3, 3, 2, 4, 4, 4, 2};
73
74 static int sdr_loc[CMESH_NUM_ATTR] = {0, 1, 2, 3, 4, 5, 6, 7};
75 static int use_custom_sdr_attr;
76
77
78 /* global state */
79 void cmesh_set_attrib_sdrloc(int attr, int loc)
80 {
81         sdr_loc[attr] = loc;
82 }
83
84 int cmesh_get_attrib_sdrloc(int attr)
85 {
86         return sdr_loc[attr];
87 }
88
89 void cmesh_clear_attrib_sdrloc(void)
90 {
91         int i;
92         for(i=0; i<CMESH_NUM_ATTR; i++) {
93                 sdr_loc[i] = -1;
94         }
95 }
96
97 /* mesh functions */
98 struct cmesh *cmesh_alloc(void)
99 {
100         struct cmesh *cm;
101
102         if(!(cm = malloc(sizeof *cm))) {
103                 return 0;
104         }
105         if(cmesh_init(cm) == -1) {
106                 free(cm);
107                 return 0;
108         }
109         return cm;
110 }
111
112 void cmesh_free(struct cmesh *cm)
113 {
114         cmesh_destroy(cm);
115         free(cm);
116 }
117
118 int cmesh_init(struct cmesh *cm)
119 {
120         int i;
121
122         memset(cm, 0, sizeof *cm);
123         cgm_wcons(cm->cur_val + CMESH_ATTR_COLOR, 1, 1, 1, 1);
124
125         glGenBuffers(CMESH_NUM_ATTR + 1, cm->buffer_objects);
126
127         for(i=0; i<CMESH_NUM_ATTR; i++) {
128                 cm->vattr[i].vbo = cm->buffer_objects[i];
129         }
130
131         cm->ibo = cm->buffer_objects[CMESH_NUM_ATTR];
132         return 0;
133 }
134
135 void cmesh_destroy(struct cmesh *cm)
136 {
137         int i;
138
139         free(cm->name);
140
141         for(i=0; i<CMESH_NUM_ATTR; i++) {
142                 free(cm->vattr[i].data);
143         }
144         free(cm->idata);
145
146         cmesh_clear_submeshes(cm);
147
148         glDeleteBuffers(CMESH_NUM_ATTR + 1, cm->buffer_objects);
149         if(cm->wire_ibo) {
150                 glDeleteBuffers(1, &cm->wire_ibo);
151         }
152 }
153
154 void cmesh_clear(struct cmesh *cm)
155 {
156         int i;
157
158         for(i=0; i<CMESH_NUM_ATTR; i++) {
159                 cm->vattr[i].nelem = 0;
160                 cm->vattr[i].vbo_valid = 0;
161                 cm->vattr[i].data_valid = 0;
162                 free(cm->vattr[i].data);
163                 cm->vattr[i].data = 0;
164                 cm->vattr[i].count = 0;
165         }
166         cm->ibo_valid = cm->idata_valid = 0;
167         free(cm->idata);
168         cm->idata = 0;
169         cm->icount = 0;
170
171         cm->wire_ibo_valid = 0;
172         cm->nverts = cm->nfaces = 0;
173
174         cm->bsph_valid = cm->aabb_valid = 0;
175
176         cmesh_clear_submeshes(cm);
177 }
178
179 int cmesh_clone(struct cmesh *cmdest, const struct cmesh *cmsrc)
180 {
181         return clone(cmdest, cmsrc, 0);
182 }
183
184 static int clone(struct cmesh *cmdest, const struct cmesh *cmsrc, struct submesh *sub)
185 {
186         int i, nelem, vstart, vcount, istart, icount;
187         char *srcname, *name = 0;
188         float *varr[CMESH_NUM_ATTR] = {0};
189         float *vptr;
190         unsigned int *iptr, *iarr = 0;
191
192         /* try do anything that can fail first, before making any changes to cmdest
193          * so we have the option of recovering gracefuly
194          */
195
196         srcname = sub ? sub->name : cmsrc->name;
197         if(srcname) {
198                 if(!(name = malloc(strlen(srcname) + 1))) {
199                         return -1;
200                 }
201                 strcpy(name, srcname);
202         }
203
204         if(sub) {
205                 vstart = sub->vstart;
206                 vcount = sub->vcount;
207                 istart = sub->istart;
208                 icount = sub->icount;
209         } else {
210                 vstart = istart = 0;
211                 vcount = cmsrc->nverts;
212                 icount = cmsrc->icount;
213         }
214
215         if(cmesh_indexed(cmsrc)) {
216                 if(!(iarr = malloc(icount * sizeof *iarr))) {
217                         free(name);
218                         return -1;
219                 }
220         }
221
222         for(i=0; i<CMESH_NUM_ATTR; i++) {
223                 if(cmesh_has_attrib(cmsrc, i)) {
224                         nelem = cmsrc->vattr[i].nelem;
225                         if(!(varr[i] = malloc(vcount * nelem * sizeof(float)))) {
226                                 while(--i >= 0) {
227                                         free(varr[i]);
228                                 }
229                                 free(iarr);
230                                 free(name);
231                                 return -1;
232                         }
233                 }
234         }
235
236         /* from this point forward nothing can fail */
237         cmesh_clear(cmdest);
238
239         for(i=0; i<CMESH_NUM_ATTR; i++) {
240                 free(cmdest->vattr[i].data);
241
242                 if(cmesh_has_attrib(cmsrc, i)) {
243                         /* force validation of the actual data on the source mesh */
244                         cmesh_attrib((struct cmesh*)cmsrc, i);
245
246                         nelem = cmsrc->vattr[i].nelem;
247                         cmdest->vattr[i].nelem = nelem;
248                         cmdest->vattr[i].data = varr[i];
249                         cmdest->vattr[i].count = vcount * nelem;
250                         vptr = cmsrc->vattr[i].data + vstart * nelem;
251                         memcpy(cmdest->vattr[i].data, vptr, vcount * nelem * sizeof(float));
252                         cmdest->vattr[i].data_valid = 1;
253                         cmdest->vattr[i].vbo_valid = 0;
254                 } else {
255                         memset(cmdest->vattr + i, 0, sizeof cmdest->vattr[i]);
256                 }
257         }
258
259         if(cmesh_indexed(cmsrc)) {
260                 /* force validation .... */
261                 cmesh_index((struct cmesh*)cmsrc);
262
263                 cmdest->idata = iarr;
264                 cmdest->icount = icount;
265                 if(sub) {
266                         /* need to offset all vertex indices by -vstart */
267                         iptr = cmsrc->idata + istart;
268                         for(i=0; i<icount; i++) {
269                                 cmdest->idata[i] = *iptr++ - vstart;
270                         }
271                 } else {
272                         memcpy(cmdest->idata, cmsrc->idata + istart, icount * sizeof *cmdest->idata);
273                 }
274                 cmdest->idata_valid = 1;
275         } else {
276                 cmdest->idata = 0;
277                 cmdest->idata_valid = cmdest->ibo_valid = 0;
278         }
279
280         free(cmdest->name);
281         cmdest->name = name;
282
283         cmdest->nverts = cmsrc->nverts;
284         cmdest->nfaces = sub ? sub->nfaces : cmsrc->nfaces;
285
286         memcpy(cmdest->cur_val, cmsrc->cur_val, sizeof cmdest->cur_val);
287
288         cmdest->aabb_min = cmsrc->aabb_min;
289         cmdest->aabb_max = cmsrc->aabb_max;
290         cmdest->aabb_valid = cmsrc->aabb_valid;
291         cmdest->bsph_center = cmsrc->bsph_center;
292         cmdest->bsph_radius = cmsrc->bsph_radius;
293         cmdest->bsph_valid = cmsrc->bsph_valid;
294
295         /* copy sublist only if we're not cloning a submesh */
296         if(!sub) {
297                 struct submesh *sm, *n, *head = 0, *tail = 0;
298
299                 sm = cmsrc->sublist;
300                 while(sm) {
301                         if(!(n = malloc(sizeof *n)) || !(name = malloc(strlen(sm->name) + 1))) {
302                                 free(n);
303                                 sm = sm->next;
304                                 continue;
305                         }
306                         strcpy(name, sm->name);
307                         *n = *sm;
308                         n->name = name;
309                         n->next = 0;
310
311                         if(head) {
312                                 tail->next = n;
313                                 tail = n;
314                         } else {
315                                 head = tail = n;
316                         }
317
318                         sm = sm->next;
319                 }
320
321                 cmdest->sublist = head;
322                 cmdest->subtail = tail;
323                 cmdest->subcount = cmsrc->subcount;
324         }
325
326         return 0;
327 }
328
329 int cmesh_set_name(struct cmesh *cm, const char *name)
330 {
331         int len = strlen(name);
332         char *tmp = malloc(len + 1);
333         if(!tmp) return -1;
334         free(cm->name);
335         cm->name = tmp;
336         memcpy(cm->name, name, len + 1);
337         return 0;
338 }
339
340 const char *cmesh_name(const struct cmesh *cm)
341 {
342         return cm->name;
343 }
344
345 int cmesh_has_attrib(const struct cmesh *cm, int attr)
346 {
347         if(attr < 0 || attr >= CMESH_NUM_ATTR) {
348                 return 0;
349         }
350         return cm->vattr[attr].vbo_valid | cm->vattr[attr].data_valid;
351 }
352
353 int cmesh_indexed(const struct cmesh *cm)
354 {
355         return cm->ibo_valid | cm->idata_valid;
356 }
357
358 /* vdata can be 0, in which case only memory is allocated
359  * returns pointer to the attribute array
360  */
361 float *cmesh_set_attrib(struct cmesh *cm, int attr, int nelem, unsigned int num,
362                 const float *vdata)
363 {
364         float *newarr;
365
366         if(attr < 0 || attr >= CMESH_NUM_ATTR) {
367                 return 0;
368         }
369         if(cm->nverts && num != cm->nverts) {
370                 return 0;
371         }
372
373         if(!(newarr = malloc(num * nelem * sizeof *newarr))) {
374                 return 0;
375         }
376         if(vdata) {
377                 memcpy(newarr, vdata, num * nelem * sizeof *newarr);
378         }
379
380         cm->nverts = num;
381
382         free(cm->vattr[attr].data);
383         cm->vattr[attr].data = newarr;
384         cm->vattr[attr].count = num * nelem;
385         cm->vattr[attr].nelem = nelem;
386         cm->vattr[attr].data_valid = 1;
387         cm->vattr[attr].vbo_valid = 0;
388         return newarr;
389 }
390
391 float *cmesh_attrib(struct cmesh *cm, int attr)
392 {
393         if(attr < 0 || attr >= CMESH_NUM_ATTR) {
394                 return 0;
395         }
396         cm->vattr[attr].vbo_valid = 0;
397         return (float*)cmesh_attrib_ro(cm, attr);
398 }
399
400 const float *cmesh_attrib_ro(const struct cmesh *cm, int attr)
401 {
402         void *tmp;
403         int nelem;
404
405         if(attr < 0 || attr >= CMESH_NUM_ATTR) {
406                 return 0;
407         }
408
409         if(!cm->vattr[attr].data_valid) {
410 #if GL_ES_VERSION_2_0
411                 return 0;
412 #else
413                 struct cmesh *m = (struct cmesh*)cm;
414
415                 if(!m->vattr[attr].vbo_valid) {
416                         return 0;
417                 }
418
419                 /* local data copy unavailable, grab the data from the vbo */
420                 nelem = m->vattr[attr].nelem;
421                 if(!(m->vattr[attr].data = malloc(m->nverts * nelem * sizeof(float)))) {
422                         return 0;
423                 }
424                 m->vattr[attr].count = m->nverts * nelem;
425
426                 glBindBuffer(GL_ARRAY_BUFFER, m->vattr[attr].vbo);
427                 tmp = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);
428                 memcpy(m->vattr[attr].data, tmp, m->nverts * nelem * sizeof(float));
429                 glUnmapBuffer(GL_ARRAY_BUFFER);
430
431                 m->vattr[attr].data_valid = 1;
432 #endif
433         }
434         return cm->vattr[attr].data;
435 }
436
437 float *cmesh_attrib_at(struct cmesh *cm, int attr, int idx)
438 {
439         float *vptr = cmesh_attrib(cm, attr);
440         return vptr ? vptr + idx * cm->vattr[attr].nelem : 0;
441 }
442
443 const float *cmesh_attrib_at_ro(const struct cmesh *cm, int attr, int idx)
444 {
445         const float *vptr = cmesh_attrib_ro(cm, attr);
446         return vptr ? vptr + idx * cm->vattr[attr].nelem : 0;
447 }
448
449 int cmesh_attrib_count(const struct cmesh *cm, int attr)
450 {
451         return cmesh_has_attrib(cm, attr) ? cm->nverts : 0;
452 }
453
454 int cmesh_attrib_nelem(const struct cmesh *cm, int attr)
455 {
456         return cmesh_has_attrib(cm, attr) ? cm->vattr[attr].nelem : 0;
457 }
458
459 int cmesh_push_attrib(struct cmesh *cm, int attr, float *v)
460 {
461         float *vptr;
462         int i, cursz, newsz;
463
464         if(!cm->vattr[attr].nelem) {
465                 cm->vattr[attr].nelem = def_nelem[attr];
466         }
467
468         cursz = cm->vattr[attr].count;
469         newsz = cursz + cm->vattr[attr].nelem;
470         if(!(vptr = realloc(cm->vattr[attr].data, newsz * sizeof(float)))) {
471                 return -1;
472         }
473         cm->vattr[attr].data = vptr;
474         cm->vattr[attr].count = newsz;
475         vptr += cursz;
476
477         for(i=0; i<cm->vattr[attr].nelem; i++) {
478                 *vptr++ = *v++;
479         }
480         cm->vattr[attr].data_valid = 1;
481         cm->vattr[attr].vbo_valid = 0;
482
483         if(attr == CMESH_ATTR_VERTEX) {
484                 cm->nverts = newsz / cm->vattr[attr].nelem;
485         }
486         return 0;
487 }
488
489 int cmesh_push_attrib1f(struct cmesh *cm, int attr, float x)
490 {
491         float v[4];
492         v[0] = x;
493         v[1] = v[2] = 0.0f;
494         v[3] = 1.0f;
495         return cmesh_push_attrib(cm, attr, v);
496 }
497
498 int cmesh_push_attrib2f(struct cmesh *cm, int attr, float x, float y)
499 {
500         float v[4];
501         v[0] = x;
502         v[1] = y;
503         v[2] = 0.0f;
504         v[3] = 1.0f;
505         return cmesh_push_attrib(cm, attr, v);
506 }
507
508 int cmesh_push_attrib3f(struct cmesh *cm, int attr, float x, float y, float z)
509 {
510         float v[4];
511         v[0] = x;
512         v[1] = y;
513         v[2] = z;
514         v[3] = 1.0f;
515         return cmesh_push_attrib(cm, attr, v);
516 }
517
518 int cmesh_push_attrib4f(struct cmesh *cm, int attr, float x, float y, float z, float w)
519 {
520         float v[4];
521         v[0] = x;
522         v[1] = y;
523         v[2] = z;
524         v[3] = w;
525         return cmesh_push_attrib(cm, attr, v);
526 }
527
528 /* indices can be 0, in which case only memory is allocated
529  * returns pointer to the index array
530  */
531 unsigned int *cmesh_set_index(struct cmesh *cm, int num, const unsigned int *indices)
532 {
533         unsigned int *tmp;
534         int nidx = cm->nfaces * 3;
535
536         if(nidx && num != nidx) {
537                 return 0;
538         }
539
540         if(!(tmp = malloc(num * sizeof *tmp))) {
541                 return 0;
542         }
543         if(indices) {
544                 memcpy(tmp, indices, num * sizeof *tmp);
545         }
546
547         free(cm->idata);
548         cm->idata = tmp;
549         cm->icount = num;
550         cm->nfaces = num / 3;
551         cm->idata_valid = 1;
552         cm->ibo_valid = 0;
553         return tmp;
554 }
555
556 unsigned int *cmesh_index(struct cmesh *cm)
557 {
558         cm->ibo_valid = 0;
559         return (unsigned int*)cmesh_index_ro(cm);
560 }
561
562 const unsigned int *cmesh_index_ro(const struct cmesh *cm)
563 {
564         int nidx;
565         unsigned int *tmp;
566
567         if(!cm->idata_valid) {
568 #if GL_ES_VERSION_2_0
569                 return 0;
570 #else
571                 struct cmesh *m = (struct cmesh*)cm;
572
573                 if(!m->ibo_valid) {
574                         return 0;
575                 }
576
577                 /* local copy is unavailable, grab the data from the ibo */
578                 nidx = m->nfaces * 3;
579                 if(!(tmp = malloc(nidx * sizeof *m->idata))) {
580                         return 0;
581                 }
582                 free(m->idata);
583                 m->idata = tmp;
584                 m->icount = nidx;
585
586                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ibo);
587                 tmp = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY);
588                 memcpy(m->idata, tmp, nidx * sizeof *m->idata);
589                 glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
590
591                 m->idata_valid = 1;
592 #endif
593         }
594         return cm->idata;
595 }
596
597 int cmesh_index_count(const struct cmesh *cm)
598 {
599         return cm->nfaces * 3;
600 }
601
602 int cmesh_push_index(struct cmesh *cm, unsigned int idx)
603 {
604         unsigned int *iptr;
605         unsigned int cur_sz = cm->icount;
606         if(!(iptr = realloc(cm->idata, (cur_sz + 1) * sizeof *iptr))) {
607                 return -1;
608         }
609         iptr[cur_sz] = idx;
610         cm->idata = iptr;
611         cm->icount = cur_sz + 1;
612         cm->idata_valid = 1;
613         cm->ibo_valid = 0;
614
615         cm->nfaces = cm->icount / 3;
616         return 0;
617 }
618
619 int cmesh_poly_count(const struct cmesh *cm)
620 {
621         if(cm->nfaces) {
622                 return cm->nfaces;
623         }
624         if(cm->nverts) {
625                 return cm->nverts / 3;
626         }
627         return 0;
628 }
629
630 /* attr can be -1 to invalidate all attributes */
631 void cmesh_invalidate_vbo(struct cmesh *cm, int attr)
632 {
633         int i;
634
635         if(attr >= CMESH_NUM_ATTR) {
636                 return;
637         }
638
639         if(attr < 0) {
640                 for(i=0; i<CMESH_NUM_ATTR; i++) {
641                         cm->vattr[i].vbo_valid = 0;
642                 }
643         } else {
644                 cm->vattr[attr].vbo_valid = 0;
645         }
646 }
647
648 void cmesh_invalidate_index(struct cmesh *cm)
649 {
650         cm->ibo_valid = 0;
651 }
652
653 int cmesh_append(struct cmesh *cmdest, const struct cmesh *cmsrc)
654 {
655         int i, nelem, newsz, origsz, srcsz;
656         float *vptr;
657         unsigned int *iptr;
658         unsigned int idxoffs;
659
660         if(!cmdest->nverts) {
661                 return cmesh_clone(cmdest, cmsrc);
662         }
663
664         for(i=0; i<CMESH_NUM_ATTR; i++) {
665                 if(cmesh_has_attrib(cmdest, i) && cmesh_has_attrib(cmsrc, i)) {
666                         /* force validation of the data arrays */
667                         cmesh_attrib(cmdest, i);
668                         cmesh_attrib_ro(cmsrc, i);
669
670                         assert(cmdest->vattr[i].nelem == cmsrc->vattr[i].nelem);
671                         nelem = cmdest->vattr[i].nelem;
672                         origsz = cmdest->nverts * nelem;
673                         newsz = (cmdest->nverts + cmsrc->nverts) * nelem;
674
675                         if(!(vptr = realloc(cmdest->vattr[i].data, newsz * sizeof *vptr))) {
676                                 return -1;
677                         }
678                         memcpy(vptr + origsz, cmsrc->vattr[i].data, cmsrc->nverts * nelem * sizeof(float));
679                         cmdest->vattr[i].data = vptr;
680                         cmdest->vattr[i].count = newsz;
681                 }
682         }
683
684         if(cmesh_indexed(cmdest)) {
685                 assert(cmesh_indexed(cmsrc));
686                 /* force validation ... */
687                 cmesh_index(cmdest);
688                 cmesh_index_ro(cmsrc);
689
690                 idxoffs = cmdest->nverts;
691                 origsz = cmdest->icount;
692                 srcsz = cmsrc->icount;
693                 newsz = origsz + srcsz;
694
695                 if(!(iptr = realloc(cmdest->idata, newsz * sizeof *iptr))) {
696                         return -1;
697                 }
698                 cmdest->idata = iptr;
699                 cmdest->icount = newsz;
700
701                 /* copy and fixup all the new indices */
702                 iptr += origsz;
703                 for(i=0; i<srcsz; i++) {
704                         *iptr++ = cmsrc->idata[i] + idxoffs;
705                 }
706         }
707
708         cmdest->nverts += cmsrc->nverts;
709         cmdest->nfaces += cmsrc->nfaces;
710
711         cmdest->wire_ibo_valid = 0;
712         cmdest->aabb_valid = 0;
713         cmdest->bsph_valid = 0;
714         return 0;
715 }
716
717 void cmesh_clear_submeshes(struct cmesh *cm)
718 {
719         struct submesh *sm;
720
721         while(cm->sublist) {
722                 sm = cm->sublist;
723                 cm->sublist = cm->sublist->next;
724                 free(sm->name);
725                 free(sm);
726         }
727         cm->subcount = 0;
728         cm->subtail = 0;
729 }
730
731 int cmesh_submesh(struct cmesh *cm, const char *name, int fstart, int fcount)
732 {
733         int i;
734         unsigned int minv = UINT_MAX, maxv = 0;
735         unsigned int *iptr;
736         struct submesh *sm;
737
738         if(fstart < 0 || fcount < 1 || fstart + fcount > cm->nfaces) {
739                 return -1;
740         }
741
742         if(!(sm = malloc(sizeof *sm)) || !(sm->name = malloc(strlen(name) + 1))) {
743                 free(sm);
744                 return -1;
745         }
746         strcpy(sm->name, name);
747         sm->nfaces = fcount;
748
749         if(cmesh_indexed(cm)) {
750                 sm->istart = fstart * 3;
751                 sm->icount = fcount * 3;
752
753                 /* find out which vertices are used by this submesh */
754                 iptr = cm->idata + sm->istart;
755                 for(i=0; i<sm->icount; i++) {
756                         unsigned int vidx = *iptr++;
757                         if(vidx < minv) minv = vidx;
758                         if(vidx > maxv) maxv = vidx;
759                 }
760                 sm->vstart = minv;
761                 sm->vcount = maxv - minv + 1;
762         } else {
763                 sm->istart = sm->icount = 0;
764                 sm->vstart = fstart * 3;
765                 sm->vcount = fcount * 3;
766         }
767
768         sm->next = 0;
769         if(cm->sublist) {
770                 cm->subtail->next = sm;
771                 cm->subtail = sm;
772         } else {
773                 cm->sublist = cm->subtail = sm;
774         }
775         cm->subcount++;
776         return 0;
777 }
778
779 int cmesh_remove_submesh(struct cmesh *cm, int idx)
780 {
781         struct submesh dummy;
782         struct submesh *prev, *sm;
783
784         if(idx >= cm->subcount) {
785                 return -1;
786         }
787
788         dummy.next = cm->sublist;
789         prev = &dummy;
790
791         while(prev->next && idx-- > 0) {
792                 prev = prev->next;
793         }
794
795         if(!(sm = prev->next)) return -1;
796
797         prev->next = sm->next;
798         free(sm->name);
799         free(sm);
800
801         if(cm->subtail == sm) {
802                 cm->subtail = prev;
803         }
804
805         cm->subcount--;
806         assert(cm->subcount >= 0);
807
808         if(!dummy.next) {
809                 cm->sublist = cm->subtail = 0;
810         } else {
811                 cm->sublist = dummy.next;
812         }
813         return 0;
814 }
815
816 int cmesh_find_submesh(const struct cmesh *cm, const char *name)
817 {
818         int idx = 0;
819         struct submesh *sm = cm->sublist;
820         while(sm) {
821                 if(strcmp(sm->name, name) == 0) {
822                         assert(idx <= cm->subcount);
823                         return idx;
824                 }
825                 idx++;
826                 sm = sm->next;
827         }
828         return -1;
829 }
830
831 int cmesh_submesh_count(const struct cmesh *cm)
832 {
833         return cm->subcount;
834 }
835
836 static struct submesh *get_submesh(const struct cmesh *m, int idx)
837 {
838         struct submesh *sm = m->sublist;
839         while(sm && --idx >= 0) {
840                 sm = sm->next;
841         }
842         return sm;
843 }
844
845 int cmesh_clone_submesh(struct cmesh *cmdest, const struct cmesh *cm, int subidx)
846 {
847         struct submesh *sub;
848
849         if(!(sub = get_submesh(cm, subidx))) {
850                 return -1;
851         }
852         return clone(cmdest, cm, sub);
853 }
854
855
856 /* assemble a complete vertex by adding all the useful attributes */
857 int cmesh_vertex(struct cmesh *cm, float x, float y, float z)
858 {
859         int i;
860
861         cgm_wcons(cm->cur_val + CMESH_ATTR_VERTEX, x, y, z, 1.0f);
862         cm->vattr[CMESH_ATTR_VERTEX].data_valid = 1;
863         cm->vattr[CMESH_ATTR_VERTEX].nelem = 3;
864
865         for(i=0; i<CMESH_NUM_ATTR; i++) {
866                 if(cm->vattr[i].nelem > 0) {
867                         cmesh_push_attrib(cm, i, &cm->cur_val[i].x);
868                 }
869         }
870
871         if(cm->idata_valid) {
872                 free(cm->idata);
873                 cm->idata = 0;
874                 cm->icount = 0;
875         }
876         cm->ibo_valid = cm->idata_valid = 0;
877         return 0;
878 }
879
880 void cmesh_normal(struct cmesh *cm, float nx, float ny, float nz)
881 {
882         cgm_wcons(cm->cur_val + CMESH_ATTR_NORMAL, nx, ny, nz, 1.0f);
883         cm->vattr[CMESH_ATTR_NORMAL].nelem = 3;
884 }
885
886 void cmesh_tangent(struct cmesh *cm, float tx, float ty, float tz)
887 {
888         cgm_wcons(cm->cur_val + CMESH_ATTR_TANGENT, tx, ty, tz, 1.0f);
889         cm->vattr[CMESH_ATTR_TANGENT].nelem = 3;
890 }
891
892 void cmesh_texcoord(struct cmesh *cm, float u, float v, float w)
893 {
894         cgm_wcons(cm->cur_val + CMESH_ATTR_TEXCOORD, u, v, w, 1.0f);
895         cm->vattr[CMESH_ATTR_TEXCOORD].nelem = 3;
896 }
897
898 void cmesh_boneweights(struct cmesh *cm, float w1, float w2, float w3, float w4)
899 {
900         cgm_wcons(cm->cur_val + CMESH_ATTR_BONEWEIGHTS, w1, w2, w3, w4);
901         cm->vattr[CMESH_ATTR_BONEWEIGHTS].nelem = 4;
902 }
903
904 void cmesh_boneidx(struct cmesh *cm, int idx1, int idx2, int idx3, int idx4)
905 {
906         cgm_wcons(cm->cur_val + CMESH_ATTR_BONEIDX, idx1, idx2, idx3, idx4);
907         cm->vattr[CMESH_ATTR_BONEIDX].nelem = 4;
908 }
909
910 static float *get_vec4(struct cmesh *cm, int attr, int idx, cgm_vec4 *res)
911 {
912         int i;
913         float *sptr, *dptr;
914         cgm_wcons(res, 0, 0, 0, 1);
915         if(!(sptr = cmesh_attrib_at(cm, attr, idx))) {
916                 return 0;
917         }
918         dptr = &res->x;
919
920         for(i=0; i<cm->vattr[attr].nelem; i++) {
921                 *dptr++ = sptr[i];
922         }
923         return sptr;
924 }
925
926 static float *get_vec3(struct cmesh *cm, int attr, int idx, cgm_vec3 *res)
927 {
928         int i;
929         float *sptr, *dptr;
930         cgm_vcons(res, 0, 0, 0);
931         if(!(sptr = cmesh_attrib_at(cm, attr, idx))) {
932                 return 0;
933         }
934         dptr = &res->x;
935
936         for(i=0; i<cm->vattr[attr].nelem; i++) {
937                 *dptr++ = sptr[i];
938         }
939         return sptr;
940 }
941
942 /* dir_xform can be null, in which case it's calculated from xform */
943 void cmesh_apply_xform(struct cmesh *cm, float *xform, float *dir_xform)
944 {
945         unsigned int i;
946         int j;
947         cgm_vec4 v;
948         cgm_vec3 n, t;
949         float *vptr;
950
951         if(!dir_xform) {
952                 dir_xform = xform;
953         }
954
955         for(i=0; i<cm->nverts; i++) {
956                 if(!(vptr = get_vec4(cm, CMESH_ATTR_VERTEX, i, &v))) {
957                         return;
958                 }
959                 cgm_wmul_m4v4(&v, xform);
960                 for(j=0; j<cm->vattr[CMESH_ATTR_VERTEX].nelem; j++) {
961                         *vptr++ = (&v.x)[j];
962                 }
963
964                 if(cmesh_has_attrib(cm, CMESH_ATTR_NORMAL)) {
965                         if((vptr = get_vec3(cm, CMESH_ATTR_NORMAL, i, &n))) {
966                                 cgm_vmul_m3v3(&n, dir_xform);
967                                 for(j=0; j<cm->vattr[CMESH_ATTR_NORMAL].nelem; j++) {
968                                         *vptr++ = (&n.x)[j];
969                                 }
970                         }
971                 }
972                 if(cmesh_has_attrib(cm, CMESH_ATTR_TANGENT)) {
973                         if((vptr = get_vec3(cm, CMESH_ATTR_TANGENT, i, &t))) {
974                                 cgm_vmul_m3v3(&t, dir_xform);
975                                 for(j=0; j<cm->vattr[CMESH_ATTR_TANGENT].nelem; j++) {
976                                         *vptr++ = (&t.x)[j];
977                                 }
978                         }
979                 }
980         }
981 }
982
983 void cmesh_flip(struct cmesh *cm)
984 {
985         cmesh_flip_faces(cm);
986         cmesh_flip_normals(cm);
987 }
988
989 void cmesh_flip_faces(struct cmesh *cm)
990 {
991         int i, j, idxnum, vnum, nelem;
992         unsigned int *indices;
993         float *verts, *vptr;
994
995         if(cmesh_indexed(cm)) {
996                 if(!(indices = cmesh_index(cm))) {
997                         return;
998                 }
999                 idxnum = cmesh_index_count(cm);
1000                 for(i=0; i<idxnum; i+=3) {
1001                         unsigned int tmp = indices[i + 2];
1002                         indices[i + 2] = indices[i + 1];
1003                         indices[i + 1] = tmp;
1004                 }
1005         } else {
1006                 if(!(verts = cmesh_attrib(cm, CMESH_ATTR_VERTEX))) {
1007                         return;
1008                 }
1009                 vnum = cmesh_attrib_count(cm, CMESH_ATTR_VERTEX);
1010                 nelem = cm->vattr[CMESH_ATTR_VERTEX].nelem;
1011                 for(i=0; i<vnum; i+=3) {
1012                         for(j=0; j<nelem; j++) {
1013                                 vptr = verts + (i + 1) * nelem + j;
1014                                 float tmp = vptr[nelem];
1015                                 vptr[nelem] = vptr[0];
1016                                 vptr[0] = tmp;
1017                         }
1018                 }
1019         }
1020 }
1021 void cmesh_flip_normals(struct cmesh *cm)
1022 {
1023         int i, num;
1024         float *nptr = cmesh_attrib(cm, CMESH_ATTR_NORMAL);
1025         if(!nptr) return;
1026
1027         num = cm->nverts * cm->vattr[CMESH_ATTR_NORMAL].nelem;
1028         for(i=0; i<num; i++) {
1029                 *nptr = -*nptr;
1030                 nptr++;
1031         }
1032 }
1033
1034 int cmesh_explode(struct cmesh *cm)
1035 {
1036         int i, j, k, idxnum, nnverts;
1037         unsigned int *indices;
1038
1039         if(!cmesh_indexed(cm)) return 0;
1040
1041         indices = cmesh_index(cm);
1042         assert(indices);
1043
1044         idxnum = cmesh_index_count(cm);
1045         nnverts = idxnum;
1046
1047         for(i=0; i<CMESH_NUM_ATTR; i++) {
1048                 const float *srcbuf;
1049                 float *tmpbuf, *dstptr;
1050
1051                 if(!cmesh_has_attrib(cm, i)) continue;
1052
1053                 srcbuf = cmesh_attrib(cm, i);
1054                 if(!(tmpbuf = malloc(nnverts * cm->vattr[i].nelem * sizeof(float)))) {
1055                         return -1;
1056                 }
1057                 dstptr = tmpbuf;
1058
1059                 for(j=0; j<idxnum; j++) {
1060                         unsigned int idx = indices[j];
1061                         const float *srcptr = srcbuf + idx * cm->vattr[i].nelem;
1062
1063                         for(k=0; k<cm->vattr[i].nelem; k++) {
1064                                 *dstptr++ = *srcptr++;
1065                         }
1066                 }
1067
1068                 free(cm->vattr[i].data);
1069                 cm->vattr[i].data = tmpbuf;
1070                 cm->vattr[i].count = nnverts * cm->vattr[i].nelem;
1071                 cm->vattr[i].data_valid = 1;
1072         }
1073
1074         cm->ibo_valid = 0;
1075         cm->idata_valid = 0;
1076         free(cm->idata);
1077         cm->idata = 0;
1078         cm->icount = 0;
1079
1080         cm->nverts = nnverts;
1081         cm->nfaces = idxnum / 3;
1082         return 0;
1083 }
1084
1085 void cmesh_calc_face_normals(struct cmesh *cm)
1086 {
1087         /* TODO */
1088 }
1089
1090 static int pre_draw(const struct cmesh *cm)
1091 {
1092         int i, loc, cur_sdr;
1093
1094         glGetIntegerv(GL_CURRENT_PROGRAM, &cur_sdr);
1095
1096         update_buffers((struct cmesh*)cm);
1097
1098         if(!cm->vattr[CMESH_ATTR_VERTEX].vbo_valid) {
1099                 return -1;
1100         }
1101
1102         if(cur_sdr && use_custom_sdr_attr) {
1103                 if(sdr_loc[CMESH_ATTR_VERTEX] == -1) {
1104                         return -1;
1105                 }
1106
1107                 for(i=0; i<CMESH_NUM_ATTR; i++) {
1108                         loc = sdr_loc[i];
1109                         if(loc >= 0 && cm->vattr[i].vbo_valid) {
1110                                 glBindBuffer(GL_ARRAY_BUFFER, cm->vattr[i].vbo);
1111                                 glVertexAttribPointer(loc, cm->vattr[i].nelem, GL_FLOAT, GL_FALSE, 0, 0);
1112                                 glEnableVertexAttribArray(loc);
1113                         }
1114                 }
1115         } else {
1116 #ifndef GL_ES_VERSION_2_0
1117                 glBindBuffer(GL_ARRAY_BUFFER, cm->vattr[CMESH_ATTR_VERTEX].vbo);
1118                 glVertexPointer(cm->vattr[CMESH_ATTR_VERTEX].nelem, GL_FLOAT, 0, 0);
1119                 glEnableClientState(GL_VERTEX_ARRAY);
1120
1121                 if(cm->vattr[CMESH_ATTR_NORMAL].vbo_valid) {
1122                         glBindBuffer(GL_ARRAY_BUFFER, cm->vattr[CMESH_ATTR_NORMAL].vbo);
1123                         glNormalPointer(GL_FLOAT, 0, 0);
1124                         glEnableClientState(GL_NORMAL_ARRAY);
1125                 }
1126                 if(cm->vattr[CMESH_ATTR_TEXCOORD].vbo_valid) {
1127                         glBindBuffer(GL_ARRAY_BUFFER, cm->vattr[CMESH_ATTR_TEXCOORD].vbo);
1128                         glTexCoordPointer(cm->vattr[CMESH_ATTR_TEXCOORD].nelem, GL_FLOAT, 0, 0);
1129                         glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1130                 }
1131                 if(cm->vattr[CMESH_ATTR_COLOR].vbo_valid) {
1132                         glBindBuffer(GL_ARRAY_BUFFER, cm->vattr[CMESH_ATTR_COLOR].vbo);
1133                         glColorPointer(cm->vattr[CMESH_ATTR_COLOR].nelem, GL_FLOAT, 0, 0);
1134                         glEnableClientState(GL_COLOR_ARRAY);
1135                 }
1136                 if(cm->vattr[CMESH_ATTR_TEXCOORD2].vbo_valid) {
1137                         glClientActiveTexture(GL_TEXTURE1);
1138                         glBindBuffer(GL_ARRAY_BUFFER, cm->vattr[CMESH_ATTR_TEXCOORD2].vbo);
1139                         glTexCoordPointer(cm->vattr[CMESH_ATTR_TEXCOORD2].nelem, GL_FLOAT, 0, 0);
1140                         glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1141                         glClientActiveTexture(GL_TEXTURE0);
1142                 }
1143 #endif  /* GL_ES_VERSION_2_0 */
1144         }
1145         glBindBuffer(GL_ARRAY_BUFFER, 0);
1146         return cur_sdr;
1147 }
1148
1149 void cmesh_draw(const struct cmesh *cm)
1150 {
1151         int cur_sdr;
1152
1153         if((cur_sdr = pre_draw(cm)) == -1) {
1154                 return;
1155         }
1156
1157         if(cm->ibo_valid) {
1158                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->ibo);
1159                 glDrawElements(GL_TRIANGLES, cm->nfaces * 3, GL_UNSIGNED_INT, 0);
1160                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1161         } else {
1162                 glDrawArrays(GL_TRIANGLES, 0, cm->nverts);
1163         }
1164
1165         post_draw(cm, cur_sdr);
1166 }
1167
1168 void cmesh_draw_range(const struct cmesh *cm, int start, int count)
1169 {
1170         int cur_sdr;
1171
1172         if((cur_sdr = pre_draw(cm)) == -1) {
1173                 return;
1174         }
1175
1176         if(cm->ibo_valid) {
1177                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->ibo);
1178                 glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, (void*)(intptr_t)(start * 4));
1179                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1180         } else {
1181                 glDrawArrays(GL_TRIANGLES, start, count);
1182         }
1183
1184         post_draw(cm, cur_sdr);
1185 }
1186
1187 void cmesh_draw_submesh(const struct cmesh *cm, int subidx)
1188 {
1189         struct submesh *sm = cm->sublist;
1190
1191         while(sm && subidx-- > 0) {
1192                 sm = sm->next;
1193         }
1194         if(!sm) return;
1195
1196         if(sm->icount) {
1197                 cmesh_draw_range(cm, sm->istart, sm->icount);
1198         } else {
1199                 cmesh_draw_range(cm, sm->vstart, sm->vcount);
1200         }
1201 }
1202
1203 static void post_draw(const struct cmesh *cm, int cur_sdr)
1204 {
1205         int i;
1206
1207         if(cur_sdr && use_custom_sdr_attr) {
1208                 for(i=0; i<CMESH_NUM_ATTR; i++) {
1209                         int loc = sdr_loc[i];
1210                         if(loc >= 0 && cm->vattr[i].vbo_valid) {
1211                                 glDisableVertexAttribArray(loc);
1212                         }
1213                 }
1214         } else {
1215 #ifndef GL_ES_VERSION_2_0
1216                 glDisableClientState(GL_VERTEX_ARRAY);
1217                 if(cm->vattr[CMESH_ATTR_NORMAL].vbo_valid) {
1218                         glDisableClientState(GL_NORMAL_ARRAY);
1219                 }
1220                 if(cm->vattr[CMESH_ATTR_TEXCOORD].vbo_valid) {
1221                         glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1222                 }
1223                 if(cm->vattr[CMESH_ATTR_COLOR].vbo_valid) {
1224                         glDisableClientState(GL_COLOR_ARRAY);
1225                 }
1226                 if(cm->vattr[CMESH_ATTR_TEXCOORD2].vbo_valid) {
1227                         glClientActiveTexture(GL_TEXTURE1);
1228                         glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1229                         glClientActiveTexture(GL_TEXTURE0);
1230                 }
1231 #endif  /* GL_ES_VERSION_2_0 */
1232         }
1233 }
1234
1235 void cmesh_draw_wire(const struct cmesh *cm, float linesz)
1236 {
1237         int cur_sdr, nfaces;
1238
1239         if((cur_sdr = pre_draw(cm)) == -1) {
1240                 return;
1241         }
1242         update_wire_ibo((struct cmesh*)cm);
1243
1244         nfaces = cmesh_poly_count(cm);
1245         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->wire_ibo);
1246         glDrawElements(GL_LINES, nfaces * 6, GL_UNSIGNED_INT, 0);
1247         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1248
1249         post_draw(cm, cur_sdr);
1250 }
1251
1252 void cmesh_draw_vertices(const struct cmesh *cm, float ptsz)
1253 {
1254         int cur_sdr;
1255         if((cur_sdr = pre_draw(cm)) == -1) {
1256                 return;
1257         }
1258
1259         glPushAttrib(GL_POINT_BIT);
1260         glPointSize(ptsz);
1261         glDrawArrays(GL_POINTS, 0, cm->nverts);
1262         glPopAttrib();
1263
1264         post_draw(cm, cur_sdr);
1265 }
1266
1267 void cmesh_draw_normals(const struct cmesh *cm, float len)
1268 {
1269 #ifndef GL_ES_VERSION_2_0
1270         int i, cur_sdr, vert_nelem, norm_nelem;
1271         int loc = -1;
1272         const float *varr, *norm;
1273
1274         varr = cmesh_attrib_ro(cm, CMESH_ATTR_VERTEX);
1275         norm = cmesh_attrib_ro(cm, CMESH_ATTR_NORMAL);
1276         if(!varr || !norm) return;
1277
1278         vert_nelem = cm->vattr[CMESH_ATTR_VERTEX].nelem;
1279         norm_nelem = cm->vattr[CMESH_ATTR_NORMAL].nelem;
1280
1281         glGetIntegerv(GL_CURRENT_PROGRAM, &cur_sdr);
1282         if(cur_sdr && use_custom_sdr_attr) {
1283                 if((loc = sdr_loc[CMESH_ATTR_VERTEX]) < 0) {
1284                         return;
1285                 }
1286         }
1287
1288         glBegin(GL_LINES);
1289         for(i=0; i<cm->nverts; i++) {
1290                 float x, y, z, endx, endy, endz;
1291
1292                 x = varr[i * vert_nelem];
1293                 y = varr[i * vert_nelem + 1];
1294                 z = varr[i * vert_nelem + 2];
1295                 endx = x + norm[i * norm_nelem] * len;
1296                 endy = y + norm[i * norm_nelem + 1] * len;
1297                 endz = z + norm[i * norm_nelem + 2] * len;
1298
1299                 if(loc == -1) {
1300                         glVertex3f(x, y, z);
1301                         glVertex3f(endx, endy, endz);
1302                 } else {
1303                         glVertexAttrib3f(loc, x, y, z);
1304                         glVertexAttrib3f(loc, endx, endy, endz);
1305                 }
1306         }
1307         glEnd();
1308 #endif  /* GL_ES_VERSION_2_0 */
1309 }
1310
1311 void cmesh_draw_tangents(const struct cmesh *cm, float len)
1312 {
1313 #ifndef GL_ES_VERSION_2_0
1314         int i, cur_sdr, vert_nelem, tang_nelem;
1315         int loc = -1;
1316         const float *varr, *tang;
1317
1318         varr = cmesh_attrib_ro(cm, CMESH_ATTR_VERTEX);
1319         tang = cmesh_attrib_ro(cm, CMESH_ATTR_TANGENT);
1320         if(!varr || !tang) return;
1321
1322         vert_nelem = cm->vattr[CMESH_ATTR_VERTEX].nelem;
1323         tang_nelem = cm->vattr[CMESH_ATTR_TANGENT].nelem;
1324
1325         glGetIntegerv(GL_CURRENT_PROGRAM, &cur_sdr);
1326         if(cur_sdr && use_custom_sdr_attr) {
1327                 if((loc = sdr_loc[CMESH_ATTR_VERTEX]) < 0) {
1328                         return;
1329                 }
1330         }
1331
1332         glBegin(GL_LINES);
1333         for(i=0; i<cm->nverts; i++) {
1334                 float x, y, z, endx, endy, endz;
1335
1336                 x = varr[i * vert_nelem];
1337                 y = varr[i * vert_nelem + 1];
1338                 z = varr[i * vert_nelem + 2];
1339                 endx = x + tang[i * tang_nelem] * len;
1340                 endy = y + tang[i * tang_nelem + 1] * len;
1341                 endz = z + tang[i * tang_nelem + 2] * len;
1342
1343                 if(loc == -1) {
1344                         glVertex3f(x, y, z);
1345                         glVertex3f(endx, endy, endz);
1346                 } else {
1347                         glVertexAttrib3f(loc, x, y, z);
1348                         glVertexAttrib3f(loc, endx, endy, endz);
1349                 }
1350         }
1351         glEnd();
1352 #endif  /* GL_ES_VERSION_2_0 */
1353 }
1354
1355 static void update_buffers(struct cmesh *cm)
1356 {
1357         int i;
1358
1359         for(i=0; i<CMESH_NUM_ATTR; i++) {
1360                 if(cmesh_has_attrib(cm, i) && !cm->vattr[i].vbo_valid) {
1361                         glBindBuffer(GL_ARRAY_BUFFER, cm->vattr[i].vbo);
1362                         glBufferData(GL_ARRAY_BUFFER, cm->nverts * cm->vattr[i].nelem * sizeof(float),
1363                                         cm->vattr[i].data, GL_STATIC_DRAW);
1364                         cm->vattr[i].vbo_valid = 1;
1365                 }
1366         }
1367         glBindBuffer(GL_ARRAY_BUFFER, 0);
1368
1369         if(cm->idata_valid && !cm->ibo_valid) {
1370                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->ibo);
1371                 glBufferData(GL_ELEMENT_ARRAY_BUFFER, cm->nfaces * 3 * sizeof(unsigned int),
1372                                 cm->idata, GL_STATIC_DRAW);
1373                 cm->ibo_valid = 1;
1374                 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1375         }
1376 }
1377
1378 static void update_wire_ibo(struct cmesh *cm)
1379 {
1380         int i, num_faces;
1381         unsigned int *wire_idxarr, *dest;
1382
1383         update_buffers(cm);
1384
1385         if(cm->wire_ibo_valid) return;
1386
1387         if(!cm->wire_ibo) {
1388                 glGenBuffers(1, &cm->wire_ibo);
1389         }
1390         num_faces = cmesh_poly_count(cm);
1391
1392         if(!(wire_idxarr = malloc(num_faces * 6 * sizeof *wire_idxarr))) {
1393                 return;
1394         }
1395         dest = wire_idxarr;
1396
1397         if(cm->ibo_valid) {
1398                 /* we're dealing with an indexed mesh */
1399                 const unsigned int *idxarr = cmesh_index_ro(cm);
1400
1401                 for(i=0; i<num_faces; i++) {
1402                         *dest++ = idxarr[0];
1403                         *dest++ = idxarr[1];
1404                         *dest++ = idxarr[1];
1405                         *dest++ = idxarr[2];
1406                         *dest++ = idxarr[2];
1407                         *dest++ = idxarr[0];
1408                         idxarr += 3;
1409                 }
1410         } else {
1411                 /* not an indexed mesh */
1412                 for(i=0; i<num_faces; i++) {
1413                         int vidx = i * 3;
1414                         *dest++ = vidx;
1415                         *dest++ = vidx + 1;
1416                         *dest++ = vidx + 1;
1417                         *dest++ = vidx + 2;
1418                         *dest++ = vidx + 2;
1419                         *dest++ = vidx;
1420                 }
1421         }
1422
1423         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cm->wire_ibo);
1424         glBufferData(GL_ELEMENT_ARRAY_BUFFER, num_faces * 6 * sizeof(unsigned int),
1425                         wire_idxarr, GL_STATIC_DRAW);
1426         free(wire_idxarr);
1427         cm->wire_ibo_valid = 1;
1428         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1429 }
1430
1431 static void calc_aabb(struct cmesh *cm)
1432 {
1433         int i, j;
1434
1435         if(!cmesh_attrib_ro(cm, CMESH_ATTR_VERTEX)) {
1436                 return;
1437         }
1438
1439         cgm_vcons(&cm->aabb_min, FLT_MAX, FLT_MAX, FLT_MAX);
1440         cgm_vcons(&cm->aabb_max, -FLT_MAX, -FLT_MAX, -FLT_MAX);
1441
1442         for(i=0; i<cm->nverts; i++) {
1443                 const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_VERTEX, i);
1444                 for(j=0; j<3; j++) {
1445                         if(v[j] < (&cm->aabb_min.x)[j]) {
1446                                 (&cm->aabb_min.x)[j] = v[j];
1447                         }
1448                         if(v[j] > (&cm->aabb_max.x)[j]) {
1449                                 (&cm->aabb_max.x)[j] = v[j];
1450                         }
1451                 }
1452         }
1453         cm->aabb_valid = 1;
1454 }
1455
1456 void cmesh_aabbox(const struct cmesh *cm, cgm_vec3 *vmin, cgm_vec3 *vmax)
1457 {
1458         if(!cm->aabb_valid) {
1459                 calc_aabb((struct cmesh*)cm);
1460         }
1461         *vmin = cm->aabb_min;
1462         *vmax = cm->aabb_max;
1463 }
1464
1465 static void calc_bsph(struct cmesh *cm)
1466 {
1467         int i;
1468         float s, dist_sq;
1469
1470         if(!cmesh_attrib_ro(cm, CMESH_ATTR_VERTEX)) {
1471                 return;
1472         }
1473
1474         cgm_vcons(&cm->bsph_center, 0, 0, 0);
1475
1476         /* first find the center */
1477         for(i=0; i<cm->nverts; i++) {
1478                 const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_VERTEX, i);
1479                 cm->bsph_center.x += v[0];
1480                 cm->bsph_center.y += v[1];
1481                 cm->bsph_center.z += v[2];
1482         }
1483         s = 1.0f / (float)cm->nverts;
1484         cm->bsph_center.x *= s;
1485         cm->bsph_center.y *= s;
1486         cm->bsph_center.z *= s;
1487
1488         cm->bsph_radius = 0.0f;
1489         for(i=0; i<cm->nverts; i++) {
1490                 const cgm_vec3 *v = (const cgm_vec3*)cmesh_attrib_at_ro(cm, CMESH_ATTR_VERTEX, i);
1491                 if((dist_sq = cgm_vdist_sq(v, &cm->bsph_center)) > cm->bsph_radius) {
1492                         cm->bsph_radius = dist_sq;
1493                 }
1494         }
1495         cm->bsph_radius = sqrt(cm->bsph_radius);
1496         cm->bsph_valid = 1;
1497 }
1498
1499 float cmesh_bsphere(const struct cmesh *cm, cgm_vec3 *center, float *rad)
1500 {
1501         if(!cm->bsph_valid) {
1502                 calc_bsph((struct cmesh*)cm);
1503         }
1504         if(center) *center = cm->bsph_center;
1505         if(rad) *rad = cm->bsph_radius;
1506         return cm->bsph_radius;
1507 }
1508
1509 /* TODO */
1510 void cmesh_texcoord_apply_xform(struct cmesh *cm, float *xform);
1511 void cmesh_texcoord_gen_plane(struct cmesh *cm, cgm_vec3 *norm, cgm_vec3 *tang);
1512 void cmesh_texcoord_gen_box(struct cmesh *cm);
1513 void cmesh_texcoord_gen_cylinder(struct cmesh *cm);
1514
1515 int cmesh_dump(const struct cmesh *cm, const char *fname)
1516 {
1517         FILE *fp = fopen(fname, "wb");
1518         if(fp) {
1519                 int res = cmesh_dump_file(cm, fp);
1520                 fclose(fp);
1521                 return res;
1522         }
1523         return -1;
1524 }
1525
1526 int cmesh_dump_file(const struct cmesh *cm, FILE *fp)
1527 {
1528         static const char *label[] = { "pos", "nor", "tan", "tex", "col", "bw", "bid", "tex2" };
1529         static const char *elemfmt[] = { 0, " %s(%g)", " %s(%g, %g)", " %s(%g, %g, %g)", " %s(%g, %g, %g, %g)", 0 };
1530         int i, j;
1531
1532         if(!cmesh_has_attrib(cm, CMESH_ATTR_VERTEX)) {
1533                 return -1;
1534         }
1535
1536         fprintf(fp, "VERTEX ATTRIBUTES\n");
1537
1538         for(i=0; i<cm->nverts; i++) {
1539                 fprintf(fp, "%5u:", i);
1540                 for(j=0; j<CMESH_NUM_ATTR; j++) {
1541                         if(cmesh_has_attrib(cm, j)) {
1542                                 const float *v = cmesh_attrib_at_ro(cm, j, i);
1543                                 int nelem = cm->vattr[j].nelem;
1544                                 fprintf(fp, elemfmt[nelem], label[j], v[0], nelem > 1 ? v[1] : 0.0f,
1545                                                 nelem > 2 ? v[2] : 0.0f, nelem > 3 ? v[3] : 0.0f);
1546                         }
1547                 }
1548                 fputc('\n', fp);
1549         }
1550
1551         if(cmesh_indexed(cm)) {
1552                 const unsigned int *idx = cmesh_index_ro(cm);
1553                 int numidx = cmesh_index_count(cm);
1554                 int numtri = numidx / 3;
1555                 assert(numidx % 3 == 0);
1556
1557                 fprintf(fp, "FACES\n");
1558
1559                 for(i=0; i<numtri; i++) {
1560                         fprintf(fp, "%5d: %d %d %d\n", i, idx[0], idx[1], idx[2]);
1561                         idx += 3;
1562                 }
1563         }
1564         return 0;
1565 }
1566
1567 int cmesh_dump_obj(const struct cmesh *cm, const char *fname)
1568 {
1569         FILE *fp = fopen(fname, "wb");
1570         if(fp) {
1571                 int res = cmesh_dump_obj_file(cm, fp, 0);
1572                 fclose(fp);
1573                 return res;
1574         }
1575         return -1;
1576 }
1577
1578 #define HAS_VN  1
1579 #define HAS_VT  2
1580
1581 int cmesh_dump_obj_file(const struct cmesh *cm, FILE *fp, int voffs)
1582 {
1583         static const char *fmtstr[] = {" %u", " %u//%u", " %u/%u", " %u/%u/%u"};
1584         int i, j, num, nelem;
1585         unsigned int aflags = 0;
1586         const struct submesh *sub = cm->sublist;
1587
1588         if(!cmesh_has_attrib(cm, CMESH_ATTR_VERTEX)) {
1589                 return -1;
1590         }
1591
1592
1593         nelem = cm->vattr[CMESH_ATTR_VERTEX].nelem;
1594         if((num = cm->vattr[CMESH_ATTR_VERTEX].count) != cm->nverts * nelem) {
1595                 fprintf(stderr, "vertex array size (%d) != nverts (%d)\n", num, cm->nverts);
1596         }
1597         for(i=0; i<cm->nverts; i++) {
1598                 const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_VERTEX, i);
1599                 fprintf(fp, "v %f %f %f\n", v[0], nelem > 1 ? v[1] : 0.0f, nelem > 2 ? v[2] : 0.0f);
1600         }
1601
1602         if(cmesh_has_attrib(cm, CMESH_ATTR_NORMAL)) {
1603                 aflags |= HAS_VN;
1604                 nelem = cm->vattr[CMESH_ATTR_NORMAL].nelem;
1605                 if((num = cm->vattr[CMESH_ATTR_NORMAL].count) != cm->nverts * nelem) {
1606                         fprintf(stderr, "normal array size (%d) != nverts (%d)\n", num, cm->nverts);
1607                 }
1608                 for(i=0; i<cm->nverts; i++) {
1609                         const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_NORMAL, i);
1610                         fprintf(fp, "vn %f %f %f\n", v[0], nelem > 1 ? v[1] : 0.0f, nelem > 2 ? v[2] : 0.0f);
1611                 }
1612         }
1613
1614         if(cmesh_has_attrib(cm, CMESH_ATTR_TEXCOORD)) {
1615                 aflags |= HAS_VT;
1616                 nelem = cm->vattr[CMESH_ATTR_TEXCOORD].nelem;
1617                 if((num = cm->vattr[CMESH_ATTR_TEXCOORD].count) != cm->nverts * nelem) {
1618                         fprintf(stderr, "texcoord array size (%d) != nverts (%d)\n", num, cm->nverts);
1619                 }
1620                 for(i=0; i<cm->nverts; i++) {
1621                         const float *v = cmesh_attrib_at_ro(cm, CMESH_ATTR_TEXCOORD, i);
1622                         fprintf(fp, "vt %f %f\n", v[0], nelem > 1 ? v[1] : 0.0f);
1623                 }
1624         }
1625
1626         if(cmesh_indexed(cm)) {
1627                 const unsigned int *idxptr = cmesh_index_ro(cm);
1628                 int numidx = cmesh_index_count(cm);
1629                 int numtri = numidx / 3;
1630                 assert(numidx % 3 == 0);
1631
1632                 for(i=0; i<numtri; i++) {
1633                         if(sub && sub->istart <= *idxptr) {
1634                                 fprintf(fp, "o %s\n", sub->name);
1635                                 sub = sub->next;
1636                         }
1637
1638                         fputc('f', fp);
1639                         for(j=0; j<3; j++) {
1640                                 unsigned int idx = *idxptr++ + 1 + voffs;
1641                                 fprintf(fp, fmtstr[aflags], idx, idx, idx);
1642                         }
1643                         fputc('\n', fp);
1644                 }
1645         } else {
1646                 int numtri = cm->nverts / 3;
1647                 unsigned int idx = 1 + voffs;
1648                 for(i=0; i<numtri; i++) {
1649                         if(sub && sub->vstart == idx - 1) {
1650                                 fprintf(fp, "o %s\n", sub->name);
1651                                 sub = sub->next;
1652                         }
1653
1654                         fputc('f', fp);
1655                         for(j=0; j<3; j++) {
1656                                 fprintf(fp, fmtstr[aflags], idx, idx, idx);
1657                                 ++idx;
1658                         }
1659                         fputc('\n', fp);
1660                 }
1661         }
1662         return 0;
1663 }