forked from lsalzman/iqm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iqm.cpp
3764 lines (3432 loc) · 119 KB
/
iqm.cpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "util.h"
struct triangle { uint vert[3]; triangle() {} triangle(uint v0, uint v1, uint v2) { vert[0] = v0; vert[1] = v1; vert[2] = v2; } };
vector<triangle> triangles, neighbors;
struct mesh { uint name, material; uint firstvert, numverts; uint firsttri, numtris; mesh() : name(0), material(0), firstvert(0), numverts(0), firsttri(0), numtris(0) {} };
vector<mesh> meshes;
struct anim { uint name; uint firstframe, numframes; float fps; uint flags; anim() : name(0), firstframe(0), numframes(0), fps(0), flags(0) {} };
vector<anim> anims;
struct joint { uint name; int parent; float pos[3], orient[4], scale[3]; joint() : name(0), parent(-1) { memset(pos, 0, sizeof(pos)); memset(orient, 0, sizeof(orient)); memset(scale, 0, sizeof(scale)); } };
vector<joint> joints;
struct pose { int parent; uint flags; float offset[10], scale[10]; pose() : parent(-1), flags(0) { memset(offset, 0, sizeof(offset)); memset(scale, 0, sizeof(scale)); } };
vector<pose> poses;
struct framebounds { Vec3 bbmin, bbmax; double xyradius, radius; framebounds() : bbmin(0, 0, 0), bbmax(0, 0, 0), xyradius(0), radius(0) {} };
vector<framebounds> bounds;
struct transform
{
Vec3 pos;
Quat orient;
Vec3 scale;
transform() {}
transform(const Vec3 &pos, const Quat &orient, const Vec3 &scale = Vec3(1, 1, 1)) : pos(pos), orient(orient), scale(scale) {}
};
vector<transform> frames;
vector<char> stringdata, commentdata;
struct sharedstring
{
uint offset;
sharedstring() {}
sharedstring(const char *s) : offset(stringdata.length()) { stringdata.put(s, strlen(s)+1); }
};
static inline bool htcmp(const char *x, const sharedstring &s)
{
return htcmp(x, &stringdata[s.offset]);
}
static inline uint hthash(const sharedstring &s)
{
return hthash(&stringdata[s.offset]);
}
hashtable<sharedstring, uint> stringoffsets;
uint sharestring(const char *s)
{
if(stringdata.empty()) stringoffsets.access("", 0);
return stringoffsets.access(s ? s : "", stringdata.length());
}
struct blendcombo
{
int sorted;
double weights[4];
uchar bones[4];
blendcombo() : sorted(0) {}
void reset() { sorted = 0; }
void addweight(double weight, int bone)
{
if(weight <= 1e-3) return;
loopk(sorted) if(weight > weights[k])
{
for(int l = min(sorted-1, 2); l >= k; l--)
{
weights[l+1] = weights[l];
bones[l+1] = bones[l];
}
weights[k] = weight;
bones[k] = bone;
if(sorted<4) sorted++;
return;
}
if(sorted>=4) return;
weights[sorted] = weight;
bones[sorted] = bone;
sorted++;
}
void finalize()
{
loopj(4-sorted) { weights[sorted+j] = 0; bones[sorted+j] = 0; }
if(sorted <= 0) return;
double total = 0;
loopj(sorted) total += weights[j];
total = 1.0/total;
loopj(sorted) weights[j] *= total;
}
void serialize(uchar *vweights) const
{
int total = 0;
loopk(4) total += (vweights[k] = uchar(0.5 + weights[k]*255));
if(sorted <= 0) return;
while(total > 255)
{
loopk(4) if(vweights[k] > 0 && total > 255) { vweights[k]--; total--; }
}
while(total < 255)
{
loopk(4) if(vweights[k] < 255 && total < 255) { vweights[k]++; total++; }
}
}
bool operator==(const blendcombo &c) { loopi(4) if(weights[i] != c.weights[i] || bones[i] != c.bones[i]) return false; return true; }
bool operator!=(const blendcombo &c) { loopi(4) if(weights[i] != c.weights[i] || bones[i] != c.bones[i]) return true; return false; }
};
static bool parseindex(char *&c, int &val)
{
while(isspace(*c)) c++;
char *end = NULL;
int rval = strtol(c, &end, 10);
if(c == end) return false;
val = rval;
c = end;
return true;
}
static double parseattrib(char *&c, double ival = 0)
{
while(isspace(*c)) c++;
char *end = NULL;
double val = strtod(c, &end);
if(c == end) val = ival;
else c = end;
return val;
}
static bool maybeparseattrib(char *&c, double &result)
{
while(isspace(*c)) c++;
char *end = NULL;
double val = strtod(c, &end);
if(c == end) return false;
c = end;
result = val;
return true;
}
#if 0
static bool parsename(char *&c, char *buf, int bufsize = sizeof(string))
{
while(isspace(*c)) c++;
char *end;
if(*c == '"')
{
c++;
end = c;
while(*end && *end != '"') end++;
copystring(buf, c, min(int(end-c+1), bufsize));
if(*end == '"') end++;
}
else
{
end = c;
while(*end && !isspace(*end)) end++;
copystring(buf, c, min(int(end-c+1), bufsize));
}
if(c == end) return false;
c = end;
return true;
}
#endif
static char *trimname(char *&c)
{
while(isspace(*c)) c++;
char *start, *end;
if(*c == '"')
{
c++;
start = end = c;
while(*end && *end != '"') end++;
if(*end) { *end = '\0'; end++; }
}
else
{
start = end = c;
while(*end && !isspace(*end)) end++;
if(*end) { *end = '\0'; end++; }
}
c = end;
return start;
}
static Vec4 parseattribs4(char *&c, const Vec4 &ival = Vec4(0, 0, 0, 0))
{
Vec4 val;
loopk(4) val[k] = parseattrib(c, ival[k]);
return val;
}
static Vec3 parseattribs3(char *&c, const Vec3 &ival = Vec3(0, 0, 0))
{
Vec3 val;
loopk(3) val[k] = parseattrib(c, ival[k]);
return val;
}
static blendcombo parseblends(char *&c)
{
blendcombo b;
int index;
while(parseindex(c, index))
{
double weight = parseattrib(c, 0);
b.addweight(weight, index);
}
b.finalize();
return b;
}
struct ejoint
{
const char *name;
int parent;
ejoint() : name(NULL), parent(-1) {}
};
struct eanim
{
const char *name;
int startframe, endframe;
double fps;
uint flags;
eanim() : name(NULL), startframe(0), endframe(INT_MAX), fps(0), flags(0) {}
};
struct emesh
{
const char *name, *material;
int firsttri;
bool used;
emesh() : name(NULL), material(NULL), firsttri(0), used(false) {}
emesh(const char *name, const char *material, int firsttri = 0) : name(name), material(material), firsttri(firsttri), used(false) {}
};
struct evarray
{
string name;
int type, format, size;
evarray() : type(IQM_POSITION), format(IQM_FLOAT), size(3) { name[0] = '\0'; }
evarray(int type, int format, int size, const char *initname = "") : type(type), format(format), size(size) { copystring(name, initname); }
};
struct esmoothgroup
{
enum
{
F_USED = 1<<0,
F_UVSMOOTH = 1<<1
};
int key;
float angle;
int flags;
esmoothgroup() : key(-1), angle(-1), flags(0) {}
};
struct etriangle
{
int smoothgroup;
uint vert[3], weld[3];
etriangle()
: smoothgroup(-1)
{
}
etriangle(int v0, int v1, int v2, int smoothgroup = -1)
: smoothgroup(smoothgroup)
{
vert[0] = v0;
vert[1] = v1;
vert[2] = v2;
}
};
vector<Vec4> mpositions, epositions, etexcoords, etangents, ecolors, ecustom[10];
vector<Vec3> enormals, ebitangents;
vector<blendcombo> mblends, eblends;
vector<etriangle> etriangles;
vector<esmoothgroup> esmoothgroups;
vector<int> esmoothindexes;
vector<uchar> esmoothedges;
vector<ejoint> ejoints;
vector<transform> eposes;
vector<Matrix3x4> mjoints;
vector<int> eframes;
vector<eanim> eanims;
vector<emesh> emeshes;
vector<evarray> evarrays;
hashtable<const char *, char *> enames;
const char *getnamekey(const char *name)
{
char **exists = enames.access(name);
if(exists) return *exists;
char *key = newstring(name);
enames[key] = key;
return key;
}
struct weldinfo
{
int tri, vert;
weldinfo *next;
};
void weldvert(const vector<Vec3> &norms, const Vec4 &pos, weldinfo *welds, int &numwelds, unionfind<int> &welder)
{
welder.clear();
int windex = 0;
for(weldinfo *w = welds; w; w = w->next, windex++)
{
etriangle &wt = etriangles[w->tri];
esmoothgroup &wg = esmoothgroups[wt.smoothgroup];
int vindex = windex + 1;
for(weldinfo *v = w->next; v; v = v->next, vindex++)
{
etriangle &vt = etriangles[v->tri];
esmoothgroup &vg = esmoothgroups[vt.smoothgroup];
if(wg.key != vg.key) continue;
if(norms[w->tri].dot(norms[v->tri]) < max(wg.angle, vg.angle)) continue;
if(((wg.flags | vg.flags) & esmoothgroup::F_UVSMOOTH) &&
etexcoords[wt.vert[w->vert]] != etexcoords[vt.vert[v->vert]])
continue;
if(esmoothindexes.length() > max(w->vert, v->vert) && esmoothindexes[w->vert] != esmoothindexes[v->vert])
continue;
if(esmoothedges.length())
{
int w0 = w->vert, w1 = (w->vert+1)%3, w2 = (w->vert+2)%3;
const Vec4 &wp1 = epositions[wt.vert[w1]],
&wp2 = epositions[wt.vert[w2]];
int v0 = v->vert, v1 = (v->vert+1)%3, v2 = (v->vert+2)%3;
const Vec4 &vp1 = epositions[vt.vert[v1]],
&vp2 = epositions[vt.vert[v2]];
int wf = esmoothedges[w->tri], vf = esmoothedges[v->tri];
if((wp1 != vp1 || !(((wf>>w0)|(vf>>v0))&1)) &&
(wp1 != vp2 || !(((wf>>w0)|(vf>>v2))&1)) &&
(wp2 != vp1 || !(((wf>>w2)|(vf>>v0))&1)) &&
(wp2 != vp2 || !(((wf>>w2)|(vf>>v2))&1)))
continue;
}
welder.unite(windex, vindex, -1);
}
}
windex = 0;
for(weldinfo *w = welds; w; w = w->next, windex++)
{
etriangle &wt = etriangles[w->tri];
wt.weld[w->vert] = welder.find(windex, -1, numwelds);
if(wt.weld[w->vert] == uint(numwelds)) numwelds++;
}
}
void smoothverts(bool areaweight = true)
{
if(etriangles.empty()) return;
if(enormals.length())
{
loopv(etriangles)
{
etriangle &t = etriangles[i];
loopk(3) t.weld[k] = t.vert[k];
}
return;
}
if(etexcoords.empty()) loopv(esmoothgroups) esmoothgroups[i].flags &= ~esmoothgroup::F_UVSMOOTH;
if(esmoothedges.length()) while(esmoothedges.length() < etriangles.length()) esmoothedges.add(7);
vector<Vec3> tarea, tnorms;
loopv(etriangles)
{
etriangle &t = etriangles[i];
Vec3 v0(epositions[t.vert[0]]),
v1(epositions[t.vert[1]]),
v2(epositions[t.vert[2]]);
tnorms.add(tarea.add((v2 - v0).cross(v1 - v0)).normalize());
}
int nextalloc = 0;
vector<weldinfo *> allocs;
hashtable<Vec4, weldinfo *> welds(1<<12);
loopv(etriangles)
{
etriangle &t = etriangles[i];
loopk(3)
{
weldinfo **next = &welds.access(epositions[t.vert[k]], NULL);
if(! (nextalloc % 1024)) allocs.add(new weldinfo[1024]);
weldinfo &w = allocs[nextalloc/1024][nextalloc%1024];
nextalloc++;
w.tri = i;
w.vert = k;
w.next = *next;
*next = &w;
}
}
int numwelds = 0;
unionfind<int> welder;
enumerate(welds, Vec4, vpos, weldinfo *, vwelds, weldvert(tnorms, vpos, vwelds, numwelds, welder));
loopv(allocs) delete[] allocs[i];
loopi(numwelds) enormals.add(Vec3(0, 0, 0));
loopv(etriangles)
{
etriangle &t = etriangles[i];
loopk(3) enormals[t.weld[k]]+= areaweight ? tarea[i] : tnorms[i];
}
loopv(enormals) if(enormals[i] != Vec3(0, 0, 0)) enormals[i] = enormals[i].normalize();
}
struct sharedvert
{
int index, weld;
sharedvert() {}
sharedvert(int index, int weld) : index(index), weld(weld) {}
};
static inline bool htcmp(const sharedvert &v, const sharedvert &s)
{
if(epositions[v.index] != epositions[s.index]) return false;
if(etexcoords.length() && etexcoords[v.index] != etexcoords[s.index]) return false;
if(enormals.length() && enormals[v.weld] != enormals[s.weld]) return false;
if(eblends.length() && eblends[v.index] != eblends[s.index]) return false;
if(ecolors.length() && ecolors[v.index] != ecolors[s.index]) return false;
loopi(10) if(ecustom[i].length() && ecustom[i][v.index] != ecustom[i][s.index]) return false;
return true;
}
static inline uint hthash(const sharedvert &v)
{
return hthash(epositions[v.index]);
}
const struct vertexarraytype
{
const char *name;
int code;
} vatypes[] =
{
{ "position", IQM_POSITION },
{ "texcoord", IQM_TEXCOORD },
{ "normal", IQM_NORMAL },
{ "tangent", IQM_TANGENT },
{ "blendindexes", IQM_BLENDINDEXES },
{ "blendweights", IQM_BLENDWEIGHTS },
{ "color", IQM_COLOR },
{ "custom0", IQM_CUSTOM + 0 },
{ "custom1", IQM_CUSTOM + 1 },
{ "custom2", IQM_CUSTOM + 2 },
{ "custom3", IQM_CUSTOM + 3 },
{ "custom4", IQM_CUSTOM + 4 },
{ "custom5", IQM_CUSTOM + 5 },
{ "custom6", IQM_CUSTOM + 6 },
{ "custom7", IQM_CUSTOM + 7 },
{ "custom8", IQM_CUSTOM + 8 },
{ "custom9", IQM_CUSTOM + 9 }
};
int findvertexarraytype(const char *name)
{
loopi(sizeof(vatypes)/sizeof(vatypes[0]))
{
if(!strcasecmp(vatypes[i].name, name))
return vatypes[i].code;
}
return -1;
}
const struct vertexarrayformat
{
const char *name;
int code;
int size;
} vaformats[] =
{
{ "byte", IQM_BYTE, 1 },
{ "ubyte", IQM_UBYTE, 1 },
{ "short", IQM_SHORT, 2 },
{ "ushort", IQM_USHORT, 2 },
{ "int", IQM_INT, 4 },
{ "uint", IQM_UINT, 4 },
{ "half", IQM_HALF, 2 },
{ "float", IQM_FLOAT, 4 },
{ "double", IQM_DOUBLE, 8 }
};
int findvertexarrayformat(const char *name)
{
loopi(sizeof(vaformats)/sizeof(vaformats[0]))
{
if(!strcasecmp(vaformats[i].name, name))
return vaformats[i].code;
}
return -1;
}
struct vertexarray
{
uint type, flags, format, size, offset;
vertexarray(uint type, uint format, uint size, uint offset) : type(type), flags(0), format(format), size(size), offset(offset) {}
int formatsize() const
{
return vaformats[format].size;
}
int bytesize() const
{
return size * vaformats[format].size;
}
};
vector<sharedvert> vmap;
vector<vertexarray> varrays;
vector<uchar> vdata;
struct halfdata
{
ushort val;
halfdata(double d)
{
union
{
ullong i;
double d;
} conv;
conv.d = d;
ushort signbit = ushort((conv.i>>63)&1);
ushort mantissa = ushort((conv.i>>(52-10))&0x3FF);
int exponent = int((conv.i>>52)&0x7FF) - 1023 + 15;
if(exponent <= 0)
{
mantissa |= 0x400;
mantissa >>= min(1-exponent, 10+1);
exponent = 0;
}
else if(exponent >= 0x1F)
{
mantissa = 0;
exponent = 0x1F;
}
val = (signbit<<15) | (ushort(exponent)<<10) | mantissa;
}
};
template<> inline halfdata endianswap<halfdata>(halfdata n) { n.val = endianswap16(n.val); return n; }
template<int TYPE> static inline int remapindex(int i, const sharedvert &v) { return v.index; }
template<> inline int remapindex<IQM_NORMAL>(int i, const sharedvert &v) { return v.weld; }
template<> inline int remapindex<IQM_TANGENT>(int i, const sharedvert &v) { return i; }
template<class T, class U>
static inline void putattrib(T &out, const U &val) { out = T(val); }
template<class T, class U>
static inline void uroundattrib(T &out, const U &val, double scale) { out = T(clamp(0.5 + val*scale, 0.0, scale)); }
template<class T, class U>
static inline void sroundattrib(T &out, const U &val, double scale, double low, double high) { double n = val*scale*0.5; out = T(clamp(n < 0 ? ceil(n - 1) : floor(n), low, high)); }
template<class T, class U>
static inline void scaleattrib(T &out, const U &val) { putattrib(out, val); }
template<class U>
static inline void scaleattrib(char &out, const U &val) { sroundattrib(out, val, 255.0, -128.0, 127.0); }
template<class U>
static inline void scaleattrib(short &out, const U &val) { sroundattrib(out, val, 65535.0, -32768.0, 32767.0); }
template<class U>
static inline void scaleattrib(int &out, const U &val) { sroundattrib(out, val, 4294967295.0, -2147483648.0, 2147483647.0); }
template<class U>
static inline void scaleattrib(uchar &out, const U &val) { uroundattrib(out, val, 255.0); }
template<class U>
static inline void scaleattrib(ushort &out, const U &val) { uroundattrib(out, val, 65535.0); }
template<class U>
static inline void scaleattrib(uint &out, const U &val) { uroundattrib(out, val, 4294967295.0); }
template<int T>
static inline bool normalizedattrib() { return true; }
template<int TYPE, int FMT, class T, class U>
static inline void serializeattrib(const vertexarray &va, T *data, const U &attrib)
{
if(normalizedattrib<TYPE>()) switch(va.size)
{
case 4: scaleattrib(data[3], attrib.w);
case 3: scaleattrib(data[2], attrib.z);
case 2: scaleattrib(data[1], attrib.y);
case 1: scaleattrib(data[0], attrib.x);
}
else switch(va.size)
{
case 4: putattrib(data[3], attrib.w);
case 3: putattrib(data[2], attrib.z);
case 2: putattrib(data[1], attrib.y);
case 1: putattrib(data[0], attrib.x);
}
lilswap(data, va.size);
}
template<int TYPE, int FMT, class T>
static inline void serializeattrib(const vertexarray &va, T *data, const Vec3 &attrib)
{
if(normalizedattrib<TYPE>()) switch(va.size)
{
case 3: scaleattrib(data[2], attrib.z);
case 2: scaleattrib(data[1], attrib.y);
case 1: scaleattrib(data[0], attrib.x);
}
else switch(va.size)
{
case 3: putattrib(data[2], attrib.z);
case 2: putattrib(data[1], attrib.y);
case 1: putattrib(data[0], attrib.x);
}
lilswap(data, va.size);
}
template<int TYPE, int FMT, class T>
static inline void serializeattrib(const vertexarray &va, T *data, const blendcombo &blend)
{
if(TYPE == IQM_BLENDINDEXES)
{
switch(va.size)
{
case 4: putattrib(data[3], blend.bones[3]);
case 3: putattrib(data[2], blend.bones[2]);
case 2: putattrib(data[1], blend.bones[1]);
case 1: putattrib(data[0], blend.bones[0]);
}
}
else if(FMT == IQM_UBYTE)
{
uchar weights[4];
blend.serialize(weights);
switch(va.size)
{
case 4: putattrib(data[3], weights[3]);
case 3: putattrib(data[2], weights[2]);
case 2: putattrib(data[1], weights[1]);
case 1: putattrib(data[0], weights[0]);
}
}
else
{
switch(va.size)
{
case 4: scaleattrib(data[3], blend.weights[3]);
case 3: scaleattrib(data[2], blend.weights[2]);
case 2: scaleattrib(data[1], blend.weights[1]);
case 1: scaleattrib(data[0], blend.weights[0]);
}
}
lilswap(data, va.size);
}
template<int TYPE, class T>
void setupvertexarray(const vector<T> &attribs, int type, int fmt, int size)
{
vertexarray &va = varrays.add(vertexarray(type, fmt, size, vdata.length()));
const char *name = "";
loopv(evarrays) if(evarrays[i].type == (int)va.type)
{
evarray &info = evarrays[i];
va.format = info.format;
va.size = clamp(info.size, 1, 4);
name = info.name;
break;
}
uint align = max(va.formatsize(), 4);
if(va.offset%align) { uint pad = align - va.offset%align; va.offset += pad; loopi(pad) vdata.add(0); }
if(va.type >= IQM_CUSTOM)
{
if(!name[0])
{
defformatstring(customname, "custom%d", va.type-IQM_CUSTOM);
va.type = IQM_CUSTOM + sharestring(customname);
}
else va.type = IQM_CUSTOM + sharestring(name);
}
int totalsize = va.bytesize() * vmap.length();
uchar *data = vdata.reserve(totalsize);
vdata.advance(totalsize);
loopv(vmap)
{
const T &attrib = attribs[remapindex<TYPE>(i, vmap[i])];
switch(va.format)
{
case IQM_BYTE: serializeattrib<TYPE, IQM_BYTE>(va, (char *)data, attrib); break;
case IQM_UBYTE: serializeattrib<TYPE, IQM_UBYTE>(va, (uchar *)data, attrib); break;
case IQM_SHORT: serializeattrib<TYPE, IQM_SHORT>(va, (short *)data, attrib); break;
case IQM_USHORT: serializeattrib<TYPE, IQM_USHORT>(va, (ushort *)data, attrib); break;
case IQM_INT: serializeattrib<TYPE, IQM_INT>(va, (int *)data, attrib); break;
case IQM_UINT: serializeattrib<TYPE, IQM_UINT>(va, (uint *)data, attrib); break;
case IQM_HALF: serializeattrib<TYPE, IQM_HALF>(va, (halfdata *)data, attrib); break;
case IQM_FLOAT: serializeattrib<TYPE, IQM_FLOAT>(va, (float *)data, attrib); break;
case IQM_DOUBLE: serializeattrib<TYPE, IQM_DOUBLE>(va, (double *)data, attrib); break;
}
data += va.bytesize();
}
}
// linear speed vertex cache optimization from Tom Forsyth
#define MAXVCACHE 32
struct triangleinfo
{
bool used;
float score;
uint vert[3];
triangleinfo() {}
triangleinfo(uint v0, uint v1, uint v2)
{
vert[0] = v0;
vert[1] = v1;
vert[2] = v2;
}
};
struct vertexcache : listnode<vertexcache>
{
int index, rank;
float score;
int numuses;
triangleinfo **uses;
vertexcache() : index(-1), rank(-1), score(-1.0f), numuses(0), uses(NULL) {}
void calcscore()
{
if(numuses > 0)
{
score = 2.0f * powf(numuses, -0.5f);
if(rank >= 3) score += powf(1.0f - (rank - 3)/float(MAXVCACHE - 3), 1.5f);
else if(rank >= 0) score += 0.75f;
}
else score = -1.0f;
}
void removeuse(triangleinfo *t)
{
loopi(numuses) if(uses[i] == t)
{
uses[i] = uses[--numuses];
return;
}
}
};
void maketriangles(vector<triangleinfo> &tris, const vector<sharedvert> &mmap)
{
triangleinfo **uses = new triangleinfo *[3*tris.length()];
vertexcache *verts = new vertexcache[mmap.length()];
list<vertexcache> vcache;
loopv(tris)
{
triangleinfo &t = tris[i];
t.used = t.vert[0] == t.vert[1] || t.vert[1] == t.vert[2] || t.vert[2] == t.vert[0];
if(t.used) continue;
loopk(3) verts[t.vert[k]].numuses++;
}
triangleinfo **curuse = uses;
loopvrev(tris)
{
triangleinfo &t = tris[i];
if(t.used) continue;
loopk(3)
{
vertexcache &v = verts[t.vert[k]];
if(!v.uses) { curuse += v.numuses; v.uses = curuse; }
*--v.uses = &t;
}
}
loopv(mmap) verts[i].calcscore();
triangleinfo *besttri = NULL;
float bestscore = -1e16f;
loopv(tris)
{
triangleinfo &t = tris[i];
if(t.used) continue;
t.score = verts[t.vert[0]].score + verts[t.vert[1]].score + verts[t.vert[2]].score;
if(t.score > bestscore) { besttri = &t; bestscore = t.score; }
}
//int reloads = 0, n = 0;
while(besttri)
{
besttri->used = true;
triangle &t = triangles.add();
loopk(3)
{
vertexcache &v = verts[besttri->vert[k]];
if(v.index < 0) { v.index = vmap.length(); vmap.add(mmap[besttri->vert[k]]); }
t.vert[k] = v.index;
v.removeuse(besttri);
if(v.rank >= 0) vcache.remove(&v)->rank = -1;
//else reloads++;
if(v.numuses <= 0) continue;
vcache.insertfirst(&v);
v.rank = 0;
}
int rank = 0;
for(vertexcache *v = vcache.first(); v != vcache.end(); v = v->next)
{
v->rank = rank++;
v->calcscore();
}
besttri = NULL;
bestscore = -1e16f;
for(vertexcache *v = vcache.first(); v != vcache.end(); v = v->next)
{
loopi(v->numuses)
{
triangleinfo &t = *v->uses[i];
t.score = verts[t.vert[0]].score + verts[t.vert[1]].score + verts[t.vert[2]].score;
if(t.score > bestscore) { besttri = &t; bestscore = t.score; }
}
}
while(vcache.size > MAXVCACHE) vcache.removelast()->rank = -1;
if(!besttri) loopv(tris)
{
triangleinfo &t = tris[i];
if(!t.used && t.score > bestscore) { besttri = &t; bestscore = t.score; }
}
}
//printf("reloads: %d, worst: %d, best: %d\n", reloads, tris.length()*3, mmap.length());
delete[] uses;
delete[] verts;
}
void calctangents(bool areaweight = true)
{
Vec3 *tangent = new Vec3[2*vmap.length()], *bitangent = tangent+vmap.length();
memset(tangent, 0, 2*vmap.length()*sizeof(Vec3));
loopv(triangles)
{
const triangle &t = triangles[i];
sharedvert &i0 = vmap[t.vert[0]],
&i1 = vmap[t.vert[1]],
&i2 = vmap[t.vert[2]];
Vec3 v0(epositions[i0.index]), e1 = Vec3(epositions[i1.index]) - v0, e2 = Vec3(epositions[i2.index]) - v0;
double u1 = etexcoords[i1.index].x - etexcoords[i0.index].x, v1 = etexcoords[i1.index].y - etexcoords[i0.index].y,
u2 = etexcoords[i2.index].x - etexcoords[i0.index].x, v2 = etexcoords[i2.index].y - etexcoords[i0.index].y;
Vec3 u = e2*v1 - e1*v2,
v = e2*u1 - e1*u2;
if(e2.cross(e1).dot(v.cross(u)) < 0)
{
u = -u;
v = -v;
}
if(!areaweight)
{
u = u.normalize();
v = v.normalize();
}
loopj(3)
{
tangent[t.vert[j]] += u;
bitangent[t.vert[j]] += v;
}
}
loopv(vmap)
{
const Vec3 &n = enormals[vmap[i].weld],
&t = tangent[i],
&bt = bitangent[i];
etangents.add(Vec4((t - n*n.dot(t)).normalize(), n.cross(t).dot(bt) < 0 ? -1 : 1));
}
delete[] tangent;
}
struct neighborkey
{
uint e0, e1;
neighborkey() {}
neighborkey(uint i0, uint i1)
{
if(epositions[i0] < epositions[i1]) { e0 = i0; e1 = i1; }
else { e0 = i1; e1 = i0; }
}
uint hash() const { return hthash(epositions[e0]) + hthash(epositions[e1]); }
bool operator==(const neighborkey &n) const
{
return epositions[e0] == epositions[n.e0] && epositions[e1] == epositions[n.e1] &&
(eblends.empty() || (eblends[e0] == eblends[n.e0] && eblends[e1] == eblends[n.e1]));
}
};
static inline uint hthash(const neighborkey &n) { return n.hash(); }
static inline bool htcmp(const neighborkey &x, const neighborkey &y) { return x == y; }
struct neighborval
{
uint tris[2];
neighborval() {}
neighborval(uint i) { tris[0] = i; tris[1] = 0xFFFFFFFFU; }
void add(uint i)
{
if(tris[1] != 0xFFFFFFFFU) tris[0] = tris[1] = 0xFFFFFFFFU;
else if(tris[0] != 0xFFFFFFFFU) tris[1] = i;
}
int opposite(uint i) const
{
return tris[0] == i ? tris[1] : tris[0];
}
};
void makeneighbors()
{
hashtable<neighborkey, neighborval> nhash;
loopv(triangles)
{
triangle &t = triangles[i];
for(int j = 0, p = 2; j < 3; p = j, j++)
{
neighborkey key(t.vert[p], t.vert[j]);
neighborval *val = nhash.access(key);
if(val) val->add(i);
else nhash[key] = neighborval(i);
}
}
loopv(triangles)
{
triangle &t = triangles[i];
triangle &n = neighbors.add();
for(int j = 0, p = 2; j < 3; p = j, j++)
n.vert[p] = nhash[neighborkey(t.vert[p], t.vert[j])].opposite(i);
}
}
Quat erotate(0, 0, 0, 1);
double escale = 1;
Vec3 emeshtrans(0, 0, 0);
void makemeshes()
{
meshes.setsize(0);
triangles.setsize(0);
neighbors.setsize(0);
vmap.setsize(0);
varrays.setsize(0);
vdata.setsize(0);
hashtable<sharedvert, uint> mshare(1<<12);
vector<sharedvert> mmap;
vector<triangleinfo> tinfo;
loopv(emeshes)
{
emesh &em1 = emeshes[i];
if(em1.used) continue;
for(int j = i; j < emeshes.length(); j++)
{
emesh &em = emeshes[j];
if(em.name != em1.name || em.material != em1.material) continue;
int lasttri = emeshes.inrange(i+1) ? emeshes[i+1].firsttri : etriangles.length();
for(int k = em.firsttri; k < lasttri; k++)
{
etriangle &et = etriangles[k];
triangleinfo &t = tinfo.add();
loopl(3)