Apply a small patch from mikktspace author Morten Mikkelsen (cosmetic changes).
[blender.git] / intern / mikktspace / mikktspace.c
1 /** \file mikktspace/mikktspace.c
2  *  \ingroup mikktspace
3  */
4 /**
5  *  Copyright (C) 2011 by Morten S. Mikkelsen
6  *
7  *  This software is provided 'as-is', without any express or implied
8  *  warranty.  In no event will the authors be held liable for any damages
9  *  arising from the use of this software.
10  *
11  *  Permission is granted to anyone to use this software for any purpose,
12  *  including commercial applications, and to alter it and redistribute it
13  *  freely, subject to the following restrictions:
14  *
15  *  1. The origin of this software must not be misrepresented; you must not
16  *     claim that you wrote the original software. If you use this software
17  *     in a product, an acknowledgment in the product documentation would be
18  *     appreciated but is not required.
19  *  2. Altered source versions must be plainly marked as such, and must not be
20  *     misrepresented as being the original software.
21  *  3. This notice may not be removed or altered from any source distribution.
22  */
23
24 #include <assert.h>
25 #include <stdio.h>
26 #include <math.h>
27 #include <string.h>
28 #include <float.h>
29 #include <stdlib.h>
30
31 #include "mikktspace.h"
32
33 #define TFALSE          0
34 #define TTRUE           1
35
36 #ifndef M_PI
37 #define M_PI    3.1415926535897932384626433832795
38 #endif
39
40 #define INTERNAL_RND_SORT_SEED          39871946
41
42 // internal structure
43 typedef struct
44 {
45         float x, y, z;
46 } SVec3;
47
48 static tbool                    veq( const SVec3 v1, const SVec3 v2 )
49 {
50         return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z);
51 }
52
53 static SVec3            vadd( const SVec3 v1, const SVec3 v2 )
54 {
55         SVec3 vRes;
56
57         vRes.x = v1.x + v2.x;
58         vRes.y = v1.y + v2.y;
59         vRes.z = v1.z + v2.z;
60
61         return vRes;
62 }
63
64
65 static SVec3            vsub( const SVec3 v1, const SVec3 v2 )
66 {
67         SVec3 vRes;
68
69         vRes.x = v1.x - v2.x;
70         vRes.y = v1.y - v2.y;
71         vRes.z = v1.z - v2.z;
72
73         return vRes;
74 }
75
76 static SVec3            vscale(const float fS, const SVec3 v)
77 {
78         SVec3 vRes;
79
80         vRes.x = fS * v.x;
81         vRes.y = fS * v.y;
82         vRes.z = fS * v.z;
83
84         return vRes;
85 }
86
87 static float                    LengthSquared( const SVec3 v )
88 {
89         return v.x*v.x + v.y*v.y + v.z*v.z;
90 }
91
92 static float                    Length( const SVec3 v )
93 {
94         return sqrtf(LengthSquared(v));
95 }
96
97 static SVec3            Normalize( const SVec3 v )
98 {
99         return vscale(1 / Length(v), v);
100 }
101
102 static float            vdot( const SVec3 v1, const SVec3 v2)
103 {
104         return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
105 }
106
107
108 static tbool NotZero(const float fX)
109 {
110         // could possibly use FLT_EPSILON instead
111         return fabsf(fX) > FLT_MIN;
112 }
113
114 static tbool VNotZero(const SVec3 v)
115 {
116         // might change this to an epsilon based test
117         return NotZero(v.x) || NotZero(v.y) || NotZero(v.z);
118 }
119
120
121
122 typedef struct
123 {
124         int iNrFaces;
125         int * pTriMembers;
126 } SSubGroup;
127
128 typedef struct
129 {
130         int iNrFaces;
131         int * pFaceIndices;
132         int iVertexRepresentitive;
133         tbool bOrientPreservering;
134 } SGroup;
135
136 // 
137 #define MARK_DEGENERATE                         1
138 #define QUAD_ONE_DEGEN_TRI                      2
139 #define GROUP_WITH_ANY                          4
140 #define ORIENT_PRESERVING                       8
141
142
143
144 typedef struct
145 {
146         int FaceNeighbors[3];
147         SGroup * AssignedGroup[3];
148         
149         // normalized first order face derivatives
150         SVec3 vOs, vOt;
151         float fMagS, fMagT;     // original magnitudes
152
153         // determines if the current and the next triangle are a quad.
154         int iOrgFaceNumber;
155         int iFlag, iTSpacesOffs;
156         unsigned char vert_num[4];
157 } STriInfo;
158
159 typedef struct
160 {
161         SVec3 vOs;
162         float fMagS;
163         SVec3 vOt;
164         float fMagT;
165         int iCounter;   // this is to average back into quads.
166         tbool bOrient;
167 } STSpace;
168
169 int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
170 void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
171 void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
172 int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn);
173 tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[],
174                                          const int iNrActiveGroups, const int piTriListIn[], const float fThresCos,
175                                          const SMikkTSpaceContext * pContext);
176
177 static int MakeIndex(const int iFace, const int iVert)
178 {
179         assert(iVert>=0 && iVert<4 && iFace>=0);
180         return (iFace<<2) | (iVert&0x3);
181 }
182
183 static void IndexToData(int * piFace, int * piVert, const int iIndexIn)
184 {
185         piVert[0] = iIndexIn&0x3;
186         piFace[0] = iIndexIn>>2;
187 }
188
189 static STSpace AvgTSpace(const STSpace * pTS0, const STSpace * pTS1)
190 {
191         STSpace ts_res;
192
193         // this if is important. Due to floating point precision
194         // averaging when ts0==ts1 will cause a slight difference
195         // which results in tangent space splits later on
196         if(pTS0->fMagS==pTS1->fMagS && pTS0->fMagT==pTS1->fMagT &&
197            veq(pTS0->vOs,pTS1->vOs)     && veq(pTS0->vOt, pTS1->vOt))
198         {
199                 ts_res.fMagS = pTS0->fMagS;
200                 ts_res.fMagT = pTS0->fMagT;
201                 ts_res.vOs = pTS0->vOs;
202                 ts_res.vOt = pTS0->vOt;
203         }
204         else
205         {
206                 ts_res.fMagS = 0.5f*(pTS0->fMagS+pTS1->fMagS);
207                 ts_res.fMagT = 0.5f*(pTS0->fMagT+pTS1->fMagT);
208                 ts_res.vOs = vadd(pTS0->vOs,pTS1->vOs);
209                 ts_res.vOt = vadd(pTS0->vOt,pTS1->vOt);
210                 if( VNotZero(ts_res.vOs) ) ts_res.vOs = Normalize(ts_res.vOs);
211                 if( VNotZero(ts_res.vOt) ) ts_res.vOt = Normalize(ts_res.vOt);
212         }
213
214         return ts_res;
215 }
216
217
218
219 SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index);
220 SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index);
221 SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index);
222
223
224 // degen triangles
225 void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris);
226 void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris);
227
228
229 tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext)
230 {
231         return genTangSpace(pContext, 180.0f);
232 }
233
234 tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold)
235 {
236         // count nr_triangles
237         int * piTriListIn = NULL, * piGroupTrianglesBuffer = NULL;
238         STriInfo * pTriInfos = NULL;
239         SGroup * pGroups = NULL;
240         STSpace * psTspace = NULL;
241         int iNrTrianglesIn = 0, f=0, t=0, i=0;
242         int iNrTSPaces = 0, iTotTris = 0, iDegenTriangles = 0, iNrMaxGroups = 0;
243         int iNrActiveGroups = 0, index = 0;
244         const int iNrFaces = pContext->m_pInterface->m_getNumFaces(pContext);
245         tbool bRes = TFALSE;
246         const float fThresCos = (const float) cos((fAngularThreshold*M_PI)/180);
247
248         // verify all call-backs have been set
249         if( pContext->m_pInterface->m_getNumFaces==NULL ||
250                 pContext->m_pInterface->m_getNumVerticesOfFace==NULL ||
251                 pContext->m_pInterface->m_getPosition==NULL ||
252                 pContext->m_pInterface->m_getNormal==NULL ||
253                 pContext->m_pInterface->m_getTexCoord==NULL )
254                 return TFALSE;
255
256         // count triangles on supported faces
257         for(f=0; f<iNrFaces; f++)
258         {
259                 const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);
260                 if(verts==3) ++iNrTrianglesIn;
261                 else if(verts==4) iNrTrianglesIn += 2;
262         }
263         if(iNrTrianglesIn<=0) return TFALSE;
264
265         // allocate memory for an index list
266         piTriListIn = (int *) malloc(sizeof(int)*3*iNrTrianglesIn);
267         pTriInfos = (STriInfo *) malloc(sizeof(STriInfo)*iNrTrianglesIn);
268         if(piTriListIn==NULL || pTriInfos==NULL)
269         {
270                 if(piTriListIn!=NULL) free(piTriListIn);
271                 if(pTriInfos!=NULL) free(pTriInfos);
272                 return TFALSE;
273         }
274
275         // make an initial triangle --> face index list
276         iNrTSPaces = GenerateInitialVerticesIndexList(pTriInfos, piTriListIn, pContext, iNrTrianglesIn);
277
278         // make a welded index list of identical positions and attributes (pos, norm, texc)
279         //printf("gen welded index list begin\n");
280         GenerateSharedVerticesIndexList(piTriListIn, pContext, iNrTrianglesIn);
281         //printf("gen welded index list end\n");
282
283         // Mark all degenerate triangles
284         iTotTris = iNrTrianglesIn;
285         iNrTrianglesIn = 0;
286         iDegenTriangles = 0;
287         for(t=0; t<iTotTris; t++)
288         {
289                 const int i0 = piTriListIn[t*3+0];
290                 const int i1 = piTriListIn[t*3+1];
291                 const int i2 = piTriListIn[t*3+2];
292                 const SVec3 p0 = GetPosition(pContext, i0);
293                 const SVec3 p1 = GetPosition(pContext, i1);
294                 const SVec3 p2 = GetPosition(pContext, i2);
295                 if(veq(p0,p1) || veq(p0,p2) || veq(p1,p2))      // degenerate
296                 {
297                         pTriInfos[t].iFlag |= MARK_DEGENERATE;
298                         ++iDegenTriangles;
299                 }
300         }
301         iNrTrianglesIn = iTotTris - iDegenTriangles;
302
303         // mark all triangle pairs that belong to a quad with only one
304         // good triangle. These need special treatment in DegenEpilogue().
305         // Additionally, move all good triangles to the start of
306         // pTriInfos[] and piTriListIn[] without changing order and
307         // put the degenerate triangles last.
308         DegenPrologue(pTriInfos, piTriListIn, iNrTrianglesIn, iTotTris);
309
310         
311         // evaluate triangle level attributes and neighbor list
312         //printf("gen neighbors list begin\n");
313         InitTriInfo(pTriInfos, piTriListIn, pContext, iNrTrianglesIn);
314         //printf("gen neighbors list end\n");
315
316         
317         // based on the 4 rules, identify groups based on connectivity
318         iNrMaxGroups = iNrTrianglesIn*3;
319         pGroups = (SGroup *) malloc(sizeof(SGroup)*iNrMaxGroups);
320         piGroupTrianglesBuffer = (int *) malloc(sizeof(int)*iNrTrianglesIn*3);
321         if(pGroups==NULL || piGroupTrianglesBuffer==NULL)
322         {
323                 if(pGroups!=NULL) free(pGroups);
324                 if(piGroupTrianglesBuffer!=NULL) free(piGroupTrianglesBuffer);
325                 free(piTriListIn);
326                 free(pTriInfos);
327                 return TFALSE;
328         }
329         //printf("gen 4rule groups begin\n");
330         iNrActiveGroups =
331                 Build4RuleGroups(pTriInfos, pGroups, piGroupTrianglesBuffer, piTriListIn, iNrTrianglesIn);
332         //printf("gen 4rule groups end\n");
333
334         //
335
336         psTspace = (STSpace *) malloc(sizeof(STSpace)*iNrTSPaces);
337         if(psTspace==NULL)
338         {
339                 free(piTriListIn);
340                 free(pTriInfos);
341                 free(pGroups);
342                 free(piGroupTrianglesBuffer);
343                 return TFALSE;
344         }
345         memset(psTspace, 0, sizeof(STSpace)*iNrTSPaces);
346         for(t=0; t<iNrTSPaces; t++)
347         {
348                 psTspace[t].vOs.x=1.0f; psTspace[t].vOs.y=0.0f; psTspace[t].vOs.z=0.0f; psTspace[t].fMagS = 1.0f;
349                 psTspace[t].vOt.x=0.0f; psTspace[t].vOt.y=1.0f; psTspace[t].vOt.z=0.0f; psTspace[t].fMagT = 1.0f;
350         }
351
352         // make tspaces, each group is split up into subgroups if necessary
353         // based on fAngularThreshold. Finally a tangent space is made for
354         // every resulting subgroup
355         //printf("gen tspaces begin\n");
356         bRes = GenerateTSpaces(psTspace, pTriInfos, pGroups, iNrActiveGroups, piTriListIn, fThresCos, pContext);
357         //printf("gen tspaces end\n");
358         
359         // clean up
360         free(pGroups);
361         free(piGroupTrianglesBuffer);
362
363         if(!bRes)       // if an allocation in GenerateTSpaces() failed
364         {
365                 // clean up and return false
366                 free(pTriInfos); free(piTriListIn); free(psTspace);
367                 return TFALSE;
368         }
369
370
371         // degenerate quads with one good triangle will be fixed by copying a space from
372         // the good triangle to the coinciding vertex.
373         // all other degenerate triangles will just copy a space from any good triangle
374         // with the same welded index in piTriListIn[].
375         DegenEpilogue(psTspace, pTriInfos, piTriListIn, pContext, iNrTrianglesIn, iTotTris);
376
377         free(pTriInfos); free(piTriListIn);
378
379         index = 0;
380         for(f=0; f<iNrFaces; f++)
381         {
382                 const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);
383                 if(verts!=3 && verts!=4) continue;
384                 
385
386                 // I've decided to let degenerate triangles and group-with-anythings
387                 // vary between left/right hand coordinate systems at the vertices.
388                 // All healthy triangles on the other hand are built to always be either or.
389
390                 /*// force the coordinate system orientation to be uniform for every face.
391                 // (this is already the case for good triangles but not for
392                 // degenerate ones and those with bGroupWithAnything==true)
393                 bool bOrient = psTspace[index].bOrient;
394                 if(psTspace[index].iCounter == 0)       // tspace was not derived from a group
395                 {
396                         // look for a space created in GenerateTSpaces() by iCounter>0
397                         bool bNotFound = true;
398                         int i=1;
399                         while(i<verts && bNotFound)
400                         {
401                                 if(psTspace[index+i].iCounter > 0) bNotFound=false;
402                                 else ++i;
403                         }
404                         if(!bNotFound) bOrient = psTspace[index+i].bOrient;
405                 }*/
406
407                 // set data
408                 for(i=0; i<verts; i++)
409                 {
410                         const STSpace * pTSpace = &psTspace[index];
411                         float tang[] = {pTSpace->vOs.x, pTSpace->vOs.y, pTSpace->vOs.z};
412                         float bitang[] = {pTSpace->vOt.x, pTSpace->vOt.y, pTSpace->vOt.z};
413                         if(pContext->m_pInterface->m_setTSpace!=NULL)
414                                 pContext->m_pInterface->m_setTSpace(pContext, tang, bitang, pTSpace->fMagS, pTSpace->fMagT, pTSpace->bOrient, f, i);
415                         if(pContext->m_pInterface->m_setTSpaceBasic!=NULL)
416                                 pContext->m_pInterface->m_setTSpaceBasic(pContext, tang, pTSpace->bOrient==TTRUE ? 1.0f : (-1.0f), f, i);
417
418                         ++index;
419                 }
420         }
421
422         free(psTspace);
423
424         
425         return TTRUE;
426 }
427
428 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
429
430 typedef struct
431 {
432         float vert[3];
433         int index;
434 } STmpVert;
435
436 const int g_iCells = 2048;
437
438 #ifdef _MSC_VER
439         #define NOINLINE __declspec(noinline)
440 #else
441         #define NOINLINE __attribute__ ((noinline))
442 #endif
443
444 // it is IMPORTANT that this function is called to evaluate the hash since
445 // inlining could potentially reorder instructions and generate different
446 // results for the same effective input value fVal.
447 NOINLINE int FindGridCell(const float fMin, const float fMax, const float fVal)
448 {
449         const float fIndex = g_iCells * ((fVal-fMin)/(fMax-fMin));
450         const int iIndex = fIndex<0?0:((int)fIndex);
451         return iIndex<g_iCells?iIndex:(g_iCells-1);
452 }
453
454 void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in);
455 void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries);
456 void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
457
458 void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
459 {
460
461         // Generate bounding box
462         int * piHashTable=NULL, * piHashCount=NULL, * piHashOffsets=NULL, * piHashCount2=NULL;
463         STmpVert * pTmpVert = NULL;
464         int i=0, iChannel=0, k=0, e=0;
465         int iMaxCount=0;
466         SVec3 vMin = GetPosition(pContext, 0), vMax = vMin, vDim;
467         float fMin, fMax;
468         for(i=1; i<(iNrTrianglesIn*3); i++)
469         {
470                 const int index = piTriList_in_and_out[i];
471
472                 const SVec3 vP = GetPosition(pContext, index);
473                 if(vMin.x > vP.x) vMin.x = vP.x;
474                 else if(vMax.x < vP.x) vMax.x = vP.x;
475                 if(vMin.y > vP.y) vMin.y = vP.y;
476                 else if(vMax.y < vP.y) vMax.y = vP.y;
477                 if(vMin.z > vP.z) vMin.z = vP.z;
478                 else if(vMax.z < vP.z) vMax.z = vP.z;
479         }
480
481         vDim = vsub(vMax,vMin);
482         iChannel = 0;
483         fMin = vMin.x; fMax=vMax.x;
484         if(vDim.y>vDim.x && vDim.y>vDim.z)
485         {
486                 iChannel=1;
487                 fMin = vMin.y, fMax=vMax.y;
488         }
489         else if(vDim.z>vDim.x)
490         {
491                 iChannel=2;
492                 fMin = vMin.z, fMax=vMax.z;
493         }
494
495         // make allocations
496         piHashTable = (int *) malloc(sizeof(int)*iNrTrianglesIn*3);
497         piHashCount = (int *) malloc(sizeof(int)*g_iCells);
498         piHashOffsets = (int *) malloc(sizeof(int)*g_iCells);
499         piHashCount2 = (int *) malloc(sizeof(int)*g_iCells);
500
501         if(piHashTable==NULL || piHashCount==NULL || piHashOffsets==NULL || piHashCount2==NULL)
502         {
503                 if(piHashTable!=NULL) free(piHashTable);
504                 if(piHashCount!=NULL) free(piHashCount);
505                 if(piHashOffsets!=NULL) free(piHashOffsets);
506                 if(piHashCount2!=NULL) free(piHashCount2);
507                 GenerateSharedVerticesIndexListSlow(piTriList_in_and_out, pContext, iNrTrianglesIn);
508                 return;
509         }
510         memset(piHashCount, 0, sizeof(int)*g_iCells);
511         memset(piHashCount2, 0, sizeof(int)*g_iCells);
512
513         // count amount of elements in each cell unit
514         for(i=0; i<(iNrTrianglesIn*3); i++)
515         {
516                 const int index = piTriList_in_and_out[i];
517                 const SVec3 vP = GetPosition(pContext, index);
518                 const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z);
519                 const int iCell = FindGridCell(fMin, fMax, fVal);
520                 ++piHashCount[iCell];
521         }
522
523         // evaluate start index of each cell.
524         piHashOffsets[0]=0;
525         for(k=1; k<g_iCells; k++)
526                 piHashOffsets[k]=piHashOffsets[k-1]+piHashCount[k-1];
527
528         // insert vertices
529         for(i=0; i<(iNrTrianglesIn*3); i++)
530         {
531                 const int index = piTriList_in_and_out[i];
532                 const SVec3 vP = GetPosition(pContext, index);
533                 const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z);
534                 const int iCell = FindGridCell(fMin, fMax, fVal);
535                 int * pTable = NULL;
536
537                 assert(piHashCount2[iCell]<piHashCount[iCell]);
538                 pTable = &piHashTable[piHashOffsets[iCell]];
539                 pTable[piHashCount2[iCell]] = i;        // vertex i has been inserted.
540                 ++piHashCount2[iCell];
541         }
542         for(k=0; k<g_iCells; k++)
543                 assert(piHashCount2[k] == piHashCount[k]);      // verify the count
544         free(piHashCount2);
545
546         // find maximum amount of entries in any hash entry
547         iMaxCount = piHashCount[0];
548         for(k=1; k<g_iCells; k++)
549                 if(iMaxCount<piHashCount[k])
550                         iMaxCount=piHashCount[k];
551         pTmpVert = (STmpVert *) malloc(sizeof(STmpVert)*iMaxCount);
552         
553
554         // complete the merge
555         for(k=0; k<g_iCells; k++)
556         {
557                 // extract table of cell k and amount of entries in it
558                 int * pTable = &piHashTable[piHashOffsets[k]];
559                 const int iEntries = piHashCount[k];
560                 if(iEntries < 2) continue;
561
562                 if(pTmpVert!=NULL)
563                 {
564                         for(e=0; e<iEntries; e++)
565                         {
566                                 int i = pTable[e];
567                                 const SVec3 vP = GetPosition(pContext, piTriList_in_and_out[i]);
568                                 pTmpVert[e].vert[0] = vP.x; pTmpVert[e].vert[1] = vP.y;
569                                 pTmpVert[e].vert[2] = vP.z; pTmpVert[e].index = i;
570                         }
571                         MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, 0, iEntries-1);
572                 }
573                 else
574                         MergeVertsSlow(piTriList_in_and_out, pContext, pTable, iEntries);
575         }
576
577         if(pTmpVert!=NULL) { free(pTmpVert); }
578         free(piHashTable);
579         free(piHashCount);
580         free(piHashOffsets);
581 }
582
583 void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in)
584 {
585         // make bbox
586         int c=0, l=0, channel=0;
587         float fvMin[3], fvMax[3];
588         float dx=0, dy=0, dz=0, fSep=0;
589         for(c=0; c<3; c++)
590         {       fvMin[c]=pTmpVert[iL_in].vert[c]; fvMax[c]=fvMin[c];    }
591         for(l=(iL_in+1); l<=iR_in; l++)
592                 for(c=0; c<3; c++)
593                         if(fvMin[c]>pTmpVert[l].vert[c]) fvMin[c]=pTmpVert[l].vert[c];
594                         else if(fvMax[c]<pTmpVert[l].vert[c]) fvMax[c]=pTmpVert[l].vert[c];
595
596         dx = fvMax[0]-fvMin[0];
597         dy = fvMax[1]-fvMin[1];
598         dz = fvMax[2]-fvMin[2];
599
600         channel = 0;
601         if(dy>dx && dy>dz) channel=1;
602         else if(dz>dx) channel=2;
603
604         fSep = 0.5f*(fvMax[channel]+fvMin[channel]);
605
606         // terminate recursion when the separation/average value
607         // is no longer strictly between fMin and fMax values.
608         if(fSep>=fvMax[channel] || fSep<=fvMin[channel])
609         {
610                 // complete the weld
611                 for(l=iL_in; l<=iR_in; l++)
612                 {
613                         int i = pTmpVert[l].index;
614                         const int index = piTriList_in_and_out[i];
615                         const SVec3 vP = GetPosition(pContext, index);
616                         const SVec3 vN = GetNormal(pContext, index);
617                         const SVec3 vT = GetTexCoord(pContext, index);
618
619                         tbool bNotFound = TTRUE;
620                         int l2=iL_in, i2rec=-1;
621                         while(l2<l && bNotFound)
622                         {
623                                 const int i2 = pTmpVert[l2].index;
624                                 const int index2 = piTriList_in_and_out[i2];
625                                 const SVec3 vP2 = GetPosition(pContext, index2);
626                                 const SVec3 vN2 = GetNormal(pContext, index2);
627                                 const SVec3 vT2 = GetTexCoord(pContext, index2);
628                                 i2rec=i2;
629
630                                 //if(vP==vP2 && vN==vN2 && vT==vT2)
631                                 if(vP.x==vP2.x && vP.y==vP2.y && vP.z==vP2.z &&
632                                         vN.x==vN2.x && vN.y==vN2.y && vN.z==vN2.z &&
633                                         vT.x==vT2.x && vT.y==vT2.y && vT.z==vT2.z)
634                                         bNotFound = TFALSE;
635                                 else
636                                         ++l2;
637                         }
638                         
639                         // merge if previously found
640                         if(!bNotFound)
641                                 piTriList_in_and_out[i] = piTriList_in_and_out[i2rec];
642                 }
643         }
644         else
645         {
646                 int iL=iL_in, iR=iR_in;
647                 assert((iR_in-iL_in)>0);        // at least 2 entries
648
649                 // seperate (by fSep) all points between iL_in and iR_in in pTmpVert[]
650                 while(iL < iR)
651                 {
652                         tbool bReadyLeftSwap = TFALSE, bReadyRightSwap = TFALSE;
653                         while((!bReadyLeftSwap) && iL<iR)
654                         {
655                                 assert(iL>=iL_in && iL<=iR_in);
656                                 bReadyLeftSwap = !(pTmpVert[iL].vert[channel]<fSep);
657                                 if(!bReadyLeftSwap) ++iL;
658                         }
659                         while((!bReadyRightSwap) && iL<iR)
660                         {
661                                 assert(iR>=iL_in && iR<=iR_in);
662                                 bReadyRightSwap = pTmpVert[iR].vert[channel]<fSep;
663                                 if(!bReadyRightSwap) --iR;
664                         }
665                         assert( (iL<iR) || !(bReadyLeftSwap && bReadyRightSwap) );
666
667                         if(bReadyLeftSwap && bReadyRightSwap)
668                         {
669                                 const STmpVert sTmp = pTmpVert[iL];
670                                 assert(iL<iR);
671                                 pTmpVert[iL] = pTmpVert[iR];
672                                 pTmpVert[iR] = sTmp;
673                                 ++iL; --iR;
674                         }
675                 }
676
677                 assert(iL==(iR+1) || (iL==iR));
678                 if(iL==iR)
679                 {
680                         const tbool bReadyRightSwap = pTmpVert[iR].vert[channel]<fSep;
681                         if(bReadyRightSwap) ++iL;
682                         else --iR;
683                 }
684
685                 // only need to weld when there is more than 1 instance of the (x,y,z)
686                 if(iL_in < iR)
687                         MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, iL_in, iR);    // weld all left of fSep
688                 if(iL < iR_in)
689                         MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, iL, iR_in);    // weld all right of (or equal to) fSep
690         }
691 }
692
693 void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries)
694 {
695         // this can be optimized further using a tree structure or more hashing.
696         int e=0;
697         for(e=0; e<iEntries; e++)
698         {
699                 int i = pTable[e];
700                 const int index = piTriList_in_and_out[i];
701                 const SVec3 vP = GetPosition(pContext, index);
702                 const SVec3 vN = GetNormal(pContext, index);
703                 const SVec3 vT = GetTexCoord(pContext, index);
704
705                 tbool bNotFound = TTRUE;
706                 int e2=0, i2rec=-1;
707                 while(e2<e && bNotFound)
708                 {
709                         const int i2 = pTable[e2];
710                         const int index2 = piTriList_in_and_out[i2];
711                         const SVec3 vP2 = GetPosition(pContext, index2);
712                         const SVec3 vN2 = GetNormal(pContext, index2);
713                         const SVec3 vT2 = GetTexCoord(pContext, index2);
714                         i2rec = i2;
715
716                         if(veq(vP,vP2) && veq(vN,vN2) && veq(vT,vT2))
717                                 bNotFound = TFALSE;
718                         else
719                                 ++e2;
720                 }
721                 
722                 // merge if previously found
723                 if(!bNotFound)
724                         piTriList_in_and_out[i] = piTriList_in_and_out[i2rec];
725         }
726 }
727
728 void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
729 {
730         int iNumUniqueVerts = 0, t=0, i=0;
731         for(t=0; t<iNrTrianglesIn; t++)
732         {
733                 for(i=0; i<3; i++)
734                 {
735                         const int offs = t*3 + i;
736                         const int index = piTriList_in_and_out[offs];
737
738                         const SVec3 vP = GetPosition(pContext, index);
739                         const SVec3 vN = GetNormal(pContext, index);
740                         const SVec3 vT = GetTexCoord(pContext, index);
741
742                         tbool bFound = TFALSE;
743                         int t2=0, index2rec=-1;
744                         while(!bFound && t2<=t)
745                         {
746                                 int j=0;
747                                 while(!bFound && j<3)
748                                 {
749                                         const int index2 = piTriList_in_and_out[t2*3 + j];
750                                         const SVec3 vP2 = GetPosition(pContext, index2);
751                                         const SVec3 vN2 = GetNormal(pContext, index2);
752                                         const SVec3 vT2 = GetTexCoord(pContext, index2);
753                                         
754                                         if(veq(vP,vP2) && veq(vN,vN2) && veq(vT,vT2))
755                                                 bFound = TTRUE;
756                                         else
757                                                 ++j;
758                                 }
759                                 if(!bFound) ++t2;
760                         }
761
762                         assert(bFound);
763                         // if we found our own
764                         if(index2rec == index) { ++iNumUniqueVerts; }
765
766                         piTriList_in_and_out[offs] = index2rec;
767                 }
768         }
769 }
770
771 int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
772 {
773         int iTSpacesOffs = 0, f=0, t=0;
774         int iDstTriIndex = 0;
775         for(f=0; f<pContext->m_pInterface->m_getNumFaces(pContext); f++)
776         {
777                 const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);
778                 if(verts!=3 && verts!=4) continue;
779
780                 pTriInfos[iDstTriIndex].iOrgFaceNumber = f;
781                 pTriInfos[iDstTriIndex].iTSpacesOffs = iTSpacesOffs;
782
783                 if(verts==3)
784                 {
785                         unsigned char * pVerts = pTriInfos[iDstTriIndex].vert_num;
786                         pVerts[0]=0; pVerts[1]=1; pVerts[2]=2;
787                         piTriList_out[iDstTriIndex*3+0] = MakeIndex(f, 0);
788                         piTriList_out[iDstTriIndex*3+1] = MakeIndex(f, 1);
789                         piTriList_out[iDstTriIndex*3+2] = MakeIndex(f, 2);
790                         ++iDstTriIndex; // next
791                 }
792                 else
793                 {
794                         {
795                                 pTriInfos[iDstTriIndex+1].iOrgFaceNumber = f;
796                                 pTriInfos[iDstTriIndex+1].iTSpacesOffs = iTSpacesOffs;
797                         }
798
799                         {
800                                 // need an order independent way to evaluate
801                                 // tspace on quads. This is done by splitting
802                                 // along the shortest diagonal.
803                                 const int i0 = MakeIndex(f, 0);
804                                 const int i1 = MakeIndex(f, 1);
805                                 const int i2 = MakeIndex(f, 2);
806                                 const int i3 = MakeIndex(f, 3);
807                                 const SVec3 T0 = GetTexCoord(pContext, i0);
808                                 const SVec3 T1 = GetTexCoord(pContext, i1);
809                                 const SVec3 T2 = GetTexCoord(pContext, i2);
810                                 const SVec3 T3 = GetTexCoord(pContext, i3);
811                                 const float distSQ_02 = LengthSquared(vsub(T2,T0));
812                                 const float distSQ_13 = LengthSquared(vsub(T3,T1));
813                                 tbool bQuadDiagIs_02;
814                                 if(distSQ_02<distSQ_13)
815                                         bQuadDiagIs_02 = TTRUE;
816                                 else if(distSQ_13<distSQ_02)
817                                         bQuadDiagIs_02 = TFALSE;
818                                 else
819                                 {
820                                         const SVec3 P0 = GetPosition(pContext, i0);
821                                         const SVec3 P1 = GetPosition(pContext, i1);
822                                         const SVec3 P2 = GetPosition(pContext, i2);
823                                         const SVec3 P3 = GetPosition(pContext, i3);
824                                         const float distSQ_02 = LengthSquared(vsub(P2,P0));
825                                         const float distSQ_13 = LengthSquared(vsub(P3,P1));
826
827                                         bQuadDiagIs_02 = distSQ_13<distSQ_02 ? TFALSE : TTRUE;
828                                 }
829
830                                 if(bQuadDiagIs_02)
831                                 {
832                                         {
833                                                 unsigned char * pVerts_A = pTriInfos[iDstTriIndex].vert_num;
834                                                 pVerts_A[0]=0; pVerts_A[1]=1; pVerts_A[2]=2;
835                                         }
836                                         piTriList_out[iDstTriIndex*3+0] = i0;
837                                         piTriList_out[iDstTriIndex*3+1] = i1;
838                                         piTriList_out[iDstTriIndex*3+2] = i2;
839                                         ++iDstTriIndex; // next
840                                         {
841                                                 unsigned char * pVerts_B = pTriInfos[iDstTriIndex].vert_num;
842                                                 pVerts_B[0]=0; pVerts_B[1]=2; pVerts_B[2]=3;
843                                         }
844                                         piTriList_out[iDstTriIndex*3+0] = i0;
845                                         piTriList_out[iDstTriIndex*3+1] = i2;
846                                         piTriList_out[iDstTriIndex*3+2] = i3;
847                                         ++iDstTriIndex; // next
848                                 }
849                                 else
850                                 {
851                                         {
852                                                 unsigned char * pVerts_A = pTriInfos[iDstTriIndex].vert_num;
853                                                 pVerts_A[0]=0; pVerts_A[1]=1; pVerts_A[2]=3;
854                                         }
855                                         piTriList_out[iDstTriIndex*3+0] = i0;
856                                         piTriList_out[iDstTriIndex*3+1] = i1;
857                                         piTriList_out[iDstTriIndex*3+2] = i3;
858                                         ++iDstTriIndex; // next
859                                         {
860                                                 unsigned char * pVerts_B = pTriInfos[iDstTriIndex].vert_num;
861                                                 pVerts_B[0]=1; pVerts_B[1]=2; pVerts_B[2]=3;
862                                         }
863                                         piTriList_out[iDstTriIndex*3+0] = i1;
864                                         piTriList_out[iDstTriIndex*3+1] = i2;
865                                         piTriList_out[iDstTriIndex*3+2] = i3;
866                                         ++iDstTriIndex; // next
867                                 }
868                         }
869                 }
870
871                 iTSpacesOffs += verts;
872                 assert(iDstTriIndex<=iNrTrianglesIn);
873         }
874
875         for(t=0; t<iNrTrianglesIn; t++)
876                 pTriInfos[t].iFlag = 0;
877
878         // return total amount of tspaces
879         return iTSpacesOffs;
880 }
881
882 SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index)
883 {
884         int iF, iI;
885         SVec3 res; float pos[3];
886         IndexToData(&iF, &iI, index);
887         pContext->m_pInterface->m_getPosition(pContext, pos, iF, iI);
888         res.x=pos[0]; res.y=pos[1]; res.z=pos[2];
889         return res;
890 }
891
892 SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index)
893 {
894         int iF, iI;
895         SVec3 res; float norm[3];
896         IndexToData(&iF, &iI, index);
897         pContext->m_pInterface->m_getNormal(pContext, norm, iF, iI);
898         res.x=norm[0]; res.y=norm[1]; res.z=norm[2];
899         return res;
900 }
901
902 SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index)
903 {
904         int iF, iI;
905         SVec3 res; float texc[2];
906         IndexToData(&iF, &iI, index);
907         pContext->m_pInterface->m_getTexCoord(pContext, texc, iF, iI);
908         res.x=texc[0]; res.y=texc[1]; res.z=1.0f;
909         return res;
910 }
911
912 /////////////////////////////////////////////////////////////////////////////////////////////////////
913 /////////////////////////////////////////////////////////////////////////////////////////////////////
914
915 typedef union
916 {
917         struct
918         {
919                 int i0, i1, f;
920         };
921         int array[3];
922 } SEdge;
923
924 void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn);
925 void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn);
926
927 // returns the texture area times 2
928 static float CalcTexArea(const SMikkTSpaceContext * pContext, const int indices[])
929 {
930         const SVec3 t1 = GetTexCoord(pContext, indices[0]);
931         const SVec3 t2 = GetTexCoord(pContext, indices[1]);
932         const SVec3 t3 = GetTexCoord(pContext, indices[2]);
933
934         const float t21x = t2.x-t1.x;
935         const float t21y = t2.y-t1.y;
936         const float t31x = t3.x-t1.x;
937         const float t31y = t3.y-t1.y;
938
939         const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x;
940
941         return fSignedAreaSTx2<0 ? (-fSignedAreaSTx2) : fSignedAreaSTx2;
942 }
943
944 void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
945 {
946         int f=0, i=0, t=0;
947         // pTriInfos[f].iFlag is cleared in GenerateInitialVerticesIndexList() which is called before this function.
948
949         // generate neighbor info list
950         for(f=0; f<iNrTrianglesIn; f++)
951                 for(i=0; i<3; i++)
952                 {
953                         pTriInfos[f].FaceNeighbors[i] = -1;
954                         pTriInfos[f].AssignedGroup[i] = NULL;
955
956                         pTriInfos[f].vOs.x=0.0f; pTriInfos[f].vOs.y=0.0f; pTriInfos[f].vOs.z=0.0f;
957                         pTriInfos[f].vOt.x=0.0f; pTriInfos[f].vOt.y=0.0f; pTriInfos[f].vOt.z=0.0f;
958                         pTriInfos[f].fMagS = 0;
959                         pTriInfos[f].fMagT = 0;
960
961                         // assumed bad
962                         pTriInfos[f].iFlag |= GROUP_WITH_ANY;
963                 }
964
965         // evaluate first order derivatives
966         for(f=0; f<iNrTrianglesIn; f++)
967         {
968                 // initial values
969                 const SVec3 v1 = GetPosition(pContext, piTriListIn[f*3+0]);
970                 const SVec3 v2 = GetPosition(pContext, piTriListIn[f*3+1]);
971                 const SVec3 v3 = GetPosition(pContext, piTriListIn[f*3+2]);
972                 const SVec3 t1 = GetTexCoord(pContext, piTriListIn[f*3+0]);
973                 const SVec3 t2 = GetTexCoord(pContext, piTriListIn[f*3+1]);
974                 const SVec3 t3 = GetTexCoord(pContext, piTriListIn[f*3+2]);
975
976                 const float t21x = t2.x-t1.x;
977                 const float t21y = t2.y-t1.y;
978                 const float t31x = t3.x-t1.x;
979                 const float t31y = t3.y-t1.y;
980                 const SVec3 d1 = vsub(v2,v1);
981                 const SVec3 d2 = vsub(v3,v1);
982
983                 const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x;
984                 //assert(fSignedAreaSTx2!=0);
985                 SVec3 vOs = vsub(vscale(t31y,d1), vscale(t21y,d2));     // eq 18
986                 SVec3 vOt = vadd(vscale(-t31x,d1), vscale(t21x,d2)); // eq 19
987
988                 pTriInfos[f].iFlag |= (fSignedAreaSTx2>0 ? ORIENT_PRESERVING : 0);
989
990                 if( NotZero(fSignedAreaSTx2) )
991                 {
992                         const float fAbsArea = fabsf(fSignedAreaSTx2);
993                         const float fLenOs = Length(vOs);
994                         const float fLenOt = Length(vOt);
995                         const float fS = (pTriInfos[f].iFlag&ORIENT_PRESERVING)==0 ? (-1.0f) : 1.0f;
996                         if( NotZero(fLenOs) ) pTriInfos[f].vOs = vscale(fS/fLenOs, vOs);
997                         if( NotZero(fLenOt) ) pTriInfos[f].vOt = vscale(fS/fLenOt, vOt);
998
999                         // evaluate magnitudes prior to normalization of vOs and vOt
1000                         pTriInfos[f].fMagS = fLenOs / fAbsArea;
1001                         pTriInfos[f].fMagT = fLenOt / fAbsArea;
1002
1003                         // if this is a good triangle
1004                         if( NotZero(pTriInfos[f].fMagS) && NotZero(pTriInfos[f].fMagT))
1005                                 pTriInfos[f].iFlag &= (~GROUP_WITH_ANY);
1006                 }
1007         }
1008
1009         // force otherwise healthy quads to a fixed orientation
1010         while(t<(iNrTrianglesIn-1))
1011         {
1012                 const int iFO_a = pTriInfos[t].iOrgFaceNumber;
1013                 const int iFO_b = pTriInfos[t+1].iOrgFaceNumber;
1014                 if(iFO_a==iFO_b)        // this is a quad
1015                 {
1016                         const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;
1017                         const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;
1018                         
1019                         // bad triangles should already have been removed by
1020                         // DegenPrologue(), but just in case check bIsDeg_a and bIsDeg_a are false
1021                         if((bIsDeg_a||bIsDeg_b)==TFALSE)
1022                         {
1023                                 const tbool bOrientA = (pTriInfos[t].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1024                                 const tbool bOrientB = (pTriInfos[t+1].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1025                                 // if this happens the quad has extremely bad mapping!!
1026                                 if(bOrientA!=bOrientB)
1027                                 {
1028                                         //printf("found quad with bad mapping\n");
1029                                         tbool bChooseOrientFirstTri = TFALSE;
1030                                         if((pTriInfos[t+1].iFlag&GROUP_WITH_ANY)!=0) bChooseOrientFirstTri = TTRUE;
1031                                         else if( CalcTexArea(pContext, &piTriListIn[t*3+0]) >= CalcTexArea(pContext, &piTriListIn[(t+1)*3+0]) )
1032                                                 bChooseOrientFirstTri = TTRUE;
1033
1034                                         // force match
1035                                         {
1036                                                 const int t0 = bChooseOrientFirstTri ? t : (t+1);
1037                                                 const int t1 = bChooseOrientFirstTri ? (t+1) : t;
1038                                                 pTriInfos[t1].iFlag &= (~ORIENT_PRESERVING);    // clear first
1039                                                 pTriInfos[t1].iFlag |= (pTriInfos[t0].iFlag&ORIENT_PRESERVING); // copy bit
1040                                         }
1041                                 }
1042                         }
1043                         t += 2;
1044                 }
1045                 else
1046                         ++t;
1047         }
1048         
1049         // match up edge pairs
1050         {
1051                 SEdge * pEdges = (SEdge *) malloc(sizeof(SEdge)*iNrTrianglesIn*3);
1052                 if(pEdges==NULL)
1053                         BuildNeighborsSlow(pTriInfos, piTriListIn, iNrTrianglesIn);
1054                 else
1055                 {
1056                         BuildNeighborsFast(pTriInfos, pEdges, piTriListIn, iNrTrianglesIn);
1057         
1058                         free(pEdges);
1059                 }
1060         }
1061 }
1062
1063 /////////////////////////////////////////////////////////////////////////////////////////////////////
1064 /////////////////////////////////////////////////////////////////////////////////////////////////////
1065
1066 tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], const int iMyTriIndex, SGroup * pGroup);
1067 void AddTriToGroup(SGroup * pGroup, const int iTriIndex);
1068
1069 int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn)
1070 {
1071         const int iNrMaxGroups = iNrTrianglesIn*3;
1072         int iNrActiveGroups = 0;
1073         int iOffset = 0, f=0, i=0;
1074         for(f=0; f<iNrTrianglesIn; f++)
1075         {
1076                 for(i=0; i<3; i++)
1077                 {
1078                         // if not assigned to a group
1079                         if((pTriInfos[f].iFlag&GROUP_WITH_ANY)==0 && pTriInfos[f].AssignedGroup[i]==NULL)
1080                         {
1081                                 tbool bOrPre;
1082                                 int neigh_indexL, neigh_indexR;
1083                                 const int vert_index = piTriListIn[f*3+i];
1084                                 assert(iNrActiveGroups<iNrMaxGroups);
1085                                 pTriInfos[f].AssignedGroup[i] = &pGroups[iNrActiveGroups];
1086                                 pTriInfos[f].AssignedGroup[i]->iVertexRepresentitive = vert_index;
1087                                 pTriInfos[f].AssignedGroup[i]->bOrientPreservering = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0;
1088                                 pTriInfos[f].AssignedGroup[i]->iNrFaces = 0;
1089                                 pTriInfos[f].AssignedGroup[i]->pFaceIndices = &piGroupTrianglesBuffer[iOffset];
1090                                 ++iNrActiveGroups;
1091
1092                                 AddTriToGroup(pTriInfos[f].AssignedGroup[i], f);
1093                                 bOrPre = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1094                                 neigh_indexL = pTriInfos[f].FaceNeighbors[i];
1095                                 neigh_indexR = pTriInfos[f].FaceNeighbors[i>0?(i-1):2];
1096                                 if(neigh_indexL>=0) // neighbor
1097                                 {
1098                                         const tbool bAnswer =
1099                                                 AssignRecur(piTriListIn, pTriInfos, neigh_indexL,
1100                                                                         pTriInfos[f].AssignedGroup[i] );
1101                                         
1102                                         const tbool bOrPre2 = (pTriInfos[neigh_indexL].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1103                                         const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE;
1104                                         assert(bAnswer || bDiff);
1105                                 }
1106                                 if(neigh_indexR>=0) // neighbor
1107                                 {
1108                                         const tbool bAnswer =
1109                                                 AssignRecur(piTriListIn, pTriInfos, neigh_indexR,
1110                                                                         pTriInfos[f].AssignedGroup[i] );
1111
1112                                         const tbool bOrPre2 = (pTriInfos[neigh_indexR].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1113                                         const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE;
1114                                         assert(bAnswer || bDiff);
1115                                 }
1116
1117                                 // update offset
1118                                 iOffset += pTriInfos[f].AssignedGroup[i]->iNrFaces;
1119                                 // since the groups are disjoint a triangle can never
1120                                 // belong to more than 3 groups. Subsequently something
1121                                 // is completely screwed if this assertion ever hits.
1122                                 assert(iOffset <= iNrMaxGroups);
1123                         }
1124                 }
1125         }
1126
1127         return iNrActiveGroups;
1128 }
1129
1130 void AddTriToGroup(SGroup * pGroup, const int iTriIndex)
1131 {
1132         pGroup->pFaceIndices[pGroup->iNrFaces] = iTriIndex;
1133         ++pGroup->iNrFaces;
1134 }
1135
1136 tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[],
1137                                  const int iMyTriIndex, SGroup * pGroup)
1138 {
1139         STriInfo * pMyTriInfo = &psTriInfos[iMyTriIndex];
1140
1141         // track down vertex
1142         const int iVertRep = pGroup->iVertexRepresentitive;
1143         const int * pVerts = &piTriListIn[3*iMyTriIndex+0];
1144         int i=-1;
1145         if(pVerts[0]==iVertRep) i=0;
1146         else if(pVerts[1]==iVertRep) i=1;
1147         else if(pVerts[2]==iVertRep) i=2;
1148         assert(i>=0 && i<3);
1149
1150         // early out
1151         if(pMyTriInfo->AssignedGroup[i] == pGroup) return TTRUE;
1152         else if(pMyTriInfo->AssignedGroup[i]!=NULL) return TFALSE;
1153         if((pMyTriInfo->iFlag&GROUP_WITH_ANY)!=0)
1154         {
1155                 // first to group with a group-with-anything triangle
1156                 // determines it's orientation.
1157                 // This is the only existing order dependency in the code!!
1158                 if( pMyTriInfo->AssignedGroup[0] == NULL &&
1159                         pMyTriInfo->AssignedGroup[1] == NULL &&
1160                         pMyTriInfo->AssignedGroup[2] == NULL )
1161                 {
1162                         pMyTriInfo->iFlag &= (~ORIENT_PRESERVING);
1163                         pMyTriInfo->iFlag |= (pGroup->bOrientPreservering ? ORIENT_PRESERVING : 0);
1164                 }
1165         }
1166         {
1167                 const tbool bOrient = (pMyTriInfo->iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1168                 if(bOrient != pGroup->bOrientPreservering) return TFALSE;
1169         }
1170
1171         AddTriToGroup(pGroup, iMyTriIndex);
1172         pMyTriInfo->AssignedGroup[i] = pGroup;
1173
1174         {
1175                 const int neigh_indexL = pMyTriInfo->FaceNeighbors[i];
1176                 const int neigh_indexR = pMyTriInfo->FaceNeighbors[i>0?(i-1):2];
1177                 if(neigh_indexL>=0)
1178                         AssignRecur(piTriListIn, psTriInfos, neigh_indexL, pGroup);
1179                 if(neigh_indexR>=0)
1180                         AssignRecur(piTriListIn, psTriInfos, neigh_indexR, pGroup);
1181         }
1182
1183
1184
1185         return TTRUE;
1186 }
1187
1188 /////////////////////////////////////////////////////////////////////////////////////////////////////
1189 /////////////////////////////////////////////////////////////////////////////////////////////////////
1190
1191 tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2);
1192 void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed);
1193 STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[], const STriInfo pTriInfos[], const SMikkTSpaceContext * pContext, const int iVertexRepresentitive);
1194
1195 tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[],
1196                                          const int iNrActiveGroups, const int piTriListIn[], const float fThresCos,
1197                                          const SMikkTSpaceContext * pContext)
1198 {
1199         STSpace * pSubGroupTspace = NULL;
1200         SSubGroup * pUniSubGroups = NULL;
1201         int * pTmpMembers = NULL;
1202         int iMaxNrFaces=0, iUniqueTspaces=0, g=0, i=0;
1203         for(g=0; g<iNrActiveGroups; g++)
1204                 if(iMaxNrFaces < pGroups[g].iNrFaces)
1205                         iMaxNrFaces = pGroups[g].iNrFaces;
1206
1207         if(iMaxNrFaces == 0) return TTRUE;
1208
1209         // make initial allocations
1210         pSubGroupTspace = (STSpace *) malloc(sizeof(STSpace)*iMaxNrFaces);
1211         pUniSubGroups = (SSubGroup *) malloc(sizeof(SSubGroup)*iMaxNrFaces);
1212         pTmpMembers = (int *) malloc(sizeof(int)*iMaxNrFaces);
1213         if(pSubGroupTspace==NULL || pUniSubGroups==NULL || pTmpMembers==NULL)
1214         {
1215                 if(pSubGroupTspace!=NULL) free(pSubGroupTspace);        
1216                 if(pUniSubGroups!=NULL) free(pUniSubGroups);    
1217                 if(pTmpMembers!=NULL) free(pTmpMembers);        
1218                 return TFALSE;
1219         }
1220
1221
1222         iUniqueTspaces = 0;
1223         for(g=0; g<iNrActiveGroups; g++)
1224         {
1225                 const SGroup * pGroup = &pGroups[g];
1226                 int iUniqueSubGroups = 0, s=0;
1227
1228                 for(i=0; i<pGroup->iNrFaces; i++)       // triangles
1229                 {
1230                         const int f = pGroup->pFaceIndices[i];  // triangle number
1231                         int index=-1, iVertIndex=-1, iOF_1=-1, iMembers=0, j=0, l=0;
1232                         SSubGroup tmp_group;
1233                         tbool bFound;
1234                         SVec3 n, vOs, vOt;
1235                         if(pTriInfos[f].AssignedGroup[0]==pGroup) index=0;
1236                         else if(pTriInfos[f].AssignedGroup[1]==pGroup) index=1;
1237                         else if(pTriInfos[f].AssignedGroup[2]==pGroup) index=2;
1238                         assert(index>=0 && index<3);
1239
1240                         iVertIndex = piTriListIn[f*3+index];
1241                         assert(iVertIndex==pGroup->iVertexRepresentitive);
1242
1243                         // is normalized already
1244                         n = GetNormal(pContext, iVertIndex);
1245                         
1246                         // project
1247                         vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n));
1248                         vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n));
1249                         if( VNotZero(vOs) ) vOs = Normalize(vOs);
1250                         if( VNotZero(vOt) ) vOt = Normalize(vOt);
1251
1252                         // original face number
1253                         iOF_1 = pTriInfos[f].iOrgFaceNumber;
1254                         
1255                         iMembers = 0;
1256                         for(j=0; j<pGroup->iNrFaces; j++)
1257                         {
1258                                 const int t = pGroup->pFaceIndices[j];  // triangle number
1259                                 const int iOF_2 = pTriInfos[t].iOrgFaceNumber;
1260
1261                                 // project
1262                                 SVec3 vOs2 = vsub(pTriInfos[t].vOs, vscale(vdot(n,pTriInfos[t].vOs), n));
1263                                 SVec3 vOt2 = vsub(pTriInfos[t].vOt, vscale(vdot(n,pTriInfos[t].vOt), n));
1264                                 if( VNotZero(vOs2) ) vOs2 = Normalize(vOs2);
1265                                 if( VNotZero(vOt2) ) vOt2 = Normalize(vOt2);
1266
1267                                 {
1268                                         const tbool bAny = ( (pTriInfos[f].iFlag | pTriInfos[t].iFlag) & GROUP_WITH_ANY )!=0 ? TTRUE : TFALSE;
1269                                         // make sure triangles which belong to the same quad are joined.
1270                                         const tbool bSameOrgFace = iOF_1==iOF_2 ? TTRUE : TFALSE;
1271
1272                                         const float fCosS = vdot(vOs,vOs2);
1273                                         const float fCosT = vdot(vOt,vOt2);
1274
1275                                         assert(f!=t || bSameOrgFace);   // sanity check
1276                                         if(bAny || bSameOrgFace || (fCosS>fThresCos && fCosT>fThresCos))
1277                                                 pTmpMembers[iMembers++] = t;
1278                                 }
1279                         }
1280
1281                         // sort pTmpMembers
1282                         tmp_group.iNrFaces = iMembers;
1283                         tmp_group.pTriMembers = pTmpMembers;
1284                         if(iMembers>1)
1285                         {
1286                                 unsigned int uSeed = INTERNAL_RND_SORT_SEED;    // could replace with a random seed?
1287                                 QuickSort(pTmpMembers, 0, iMembers-1, uSeed);
1288                         }
1289
1290                         // look for an existing match
1291                         bFound = TFALSE;
1292                         l=0;
1293                         while(l<iUniqueSubGroups && !bFound)
1294                         {
1295                                 bFound = CompareSubGroups(&tmp_group, &pUniSubGroups[l]);
1296                                 if(!bFound) ++l;
1297                         }
1298                         
1299                         // assign tangent space index
1300                         assert(bFound || l==iUniqueSubGroups);
1301                         //piTempTangIndices[f*3+index] = iUniqueTspaces+l;
1302
1303                         // if no match was found we allocate a new subgroup
1304                         if(!bFound)
1305                         {
1306                                 // insert new subgroup
1307                                 int * pIndices = (int *) malloc(sizeof(int)*iMembers);
1308                                 if(pIndices==NULL)
1309                                 {
1310                                         // clean up and return false
1311                                         int s=0;
1312                                         for(s=0; s<iUniqueSubGroups; s++)
1313                                                 free(pUniSubGroups[s].pTriMembers);
1314                                         free(pUniSubGroups);
1315                                         free(pTmpMembers);
1316                                         free(pSubGroupTspace);
1317                                         return TFALSE;
1318                                 }
1319                                 pUniSubGroups[iUniqueSubGroups].iNrFaces = iMembers;
1320                                 pUniSubGroups[iUniqueSubGroups].pTriMembers = pIndices;
1321                                 memcpy(pIndices, tmp_group.pTriMembers, iMembers*sizeof(int));
1322                                 pSubGroupTspace[iUniqueSubGroups] =
1323                                         EvalTspace(tmp_group.pTriMembers, iMembers, piTriListIn, pTriInfos, pContext, pGroup->iVertexRepresentitive);
1324                                 ++iUniqueSubGroups;
1325                         }
1326
1327                         // output tspace
1328                         {
1329                                 const int iOffs = pTriInfos[f].iTSpacesOffs;
1330                                 const int iVert = pTriInfos[f].vert_num[index];
1331                                 STSpace * pTS_out = &psTspace[iOffs+iVert];
1332                                 assert(pTS_out->iCounter<2);
1333                                 assert(((pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0) == pGroup->bOrientPreservering);
1334                                 if(pTS_out->iCounter==1)
1335                                 {
1336                                         *pTS_out = AvgTSpace(pTS_out, &pSubGroupTspace[l]);
1337                                         pTS_out->iCounter = 2;  // update counter
1338                                         pTS_out->bOrient = pGroup->bOrientPreservering;
1339                                 }
1340                                 else
1341                                 {
1342                                         assert(pTS_out->iCounter==0);
1343                                         *pTS_out = pSubGroupTspace[l];
1344                                         pTS_out->iCounter = 1;  // update counter
1345                                         pTS_out->bOrient = pGroup->bOrientPreservering;
1346                                 }
1347                         }
1348                 }
1349
1350                 // clean up and offset iUniqueTspaces
1351                 for(s=0; s<iUniqueSubGroups; s++)
1352                         free(pUniSubGroups[s].pTriMembers);
1353                 iUniqueTspaces += iUniqueSubGroups;
1354                 iUniqueSubGroups = 0;
1355         }
1356
1357         // clean up
1358         free(pUniSubGroups);
1359         free(pTmpMembers);
1360         free(pSubGroupTspace);
1361
1362         return TTRUE;
1363 }
1364
1365 STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[], const STriInfo pTriInfos[],
1366                                    const SMikkTSpaceContext * pContext, const int iVertexRepresentitive)
1367 {
1368         STSpace res;
1369         float fAngleSum = 0;
1370         int face=0;
1371         res.vOs.x=0.0f; res.vOs.y=0.0f; res.vOs.z=0.0f;
1372         res.vOt.x=0.0f; res.vOt.y=0.0f; res.vOt.z=0.0f;
1373         res.fMagS = 0; res.fMagT = 0;
1374
1375         for(face=0; face<iFaces; face++)
1376         {
1377                 const int f = face_indices[face];
1378
1379                 // only valid triangles get to add their contribution
1380                 if( (pTriInfos[f].iFlag&GROUP_WITH_ANY)==0 )
1381                 {
1382                         SVec3 n, vOs, vOt, p0, p1, p2, v1, v2;
1383                         float fCos, fAngle, fMagS, fMagT;
1384                         int i=-1, index=-1, i0=-1, i1=-1, i2=-1;
1385                         if(piTriListIn[3*f+0]==iVertexRepresentitive) i=0;
1386                         else if(piTriListIn[3*f+1]==iVertexRepresentitive) i=1;
1387                         else if(piTriListIn[3*f+2]==iVertexRepresentitive) i=2;
1388                         assert(i>=0 && i<3);
1389
1390                         // project
1391                         index = piTriListIn[3*f+i];
1392                         n = GetNormal(pContext, index);
1393                         vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n));
1394                         vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n));
1395                         if( VNotZero(vOs) ) vOs = Normalize(vOs);
1396                         if( VNotZero(vOt) ) vOt = Normalize(vOt);
1397
1398                         i2 = piTriListIn[3*f + (i<2?(i+1):0)];
1399                         i1 = piTriListIn[3*f + i];
1400                         i0 = piTriListIn[3*f + (i>0?(i-1):2)];
1401
1402                         p0 = GetPosition(pContext, i0);
1403                         p1 = GetPosition(pContext, i1);
1404                         p2 = GetPosition(pContext, i2);
1405                         v1 = vsub(p0,p1);
1406                         v2 = vsub(p2,p1);
1407
1408                         // project
1409                         v1 = vsub(v1, vscale(vdot(n,v1),n)); if( VNotZero(v1) ) v1 = Normalize(v1);
1410                         v2 = vsub(v2, vscale(vdot(n,v2),n)); if( VNotZero(v2) ) v2 = Normalize(v2);
1411
1412                         // weight contribution by the angle
1413                         // between the two edge vectors
1414                         fCos = vdot(v1,v2); fCos=fCos>1?1:(fCos<(-1) ? (-1) : fCos);
1415                         fAngle = (const float) acos(fCos);
1416                         fMagS = pTriInfos[f].fMagS;
1417                         fMagT = pTriInfos[f].fMagT;
1418
1419                         res.vOs=vadd(res.vOs, vscale(fAngle,vOs));
1420                         res.vOt=vadd(res.vOt,vscale(fAngle,vOt));
1421                         res.fMagS+=(fAngle*fMagS);
1422                         res.fMagT+=(fAngle*fMagT);
1423                         fAngleSum += fAngle;
1424                 }
1425         }
1426
1427         // normalize
1428         if( VNotZero(res.vOs) ) res.vOs = Normalize(res.vOs);
1429         if( VNotZero(res.vOt) ) res.vOt = Normalize(res.vOt);
1430         if(fAngleSum>0)
1431         {
1432                 res.fMagS /= fAngleSum;
1433                 res.fMagT /= fAngleSum;
1434         }
1435
1436         return res;
1437 }
1438
1439 tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2)
1440 {
1441         tbool bStillSame=TTRUE;
1442         int i=0;
1443         if(pg1->iNrFaces!=pg2->iNrFaces) return TFALSE;
1444         while(i<pg1->iNrFaces && bStillSame)
1445         {
1446                 bStillSame = pg1->pTriMembers[i]==pg2->pTriMembers[i] ? TTRUE : TFALSE;
1447                 if(bStillSame) ++i;
1448         }
1449         return bStillSame;
1450 }
1451
1452 void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed)
1453 {
1454         int iL, iR, n, index, iMid, iTmp;
1455
1456         // Random
1457         unsigned int t=uSeed&31;
1458         t=(uSeed<<t)|(uSeed>>(32-t));
1459         uSeed=uSeed+t+3;
1460         // Random end
1461
1462         iL=iLeft; iR=iRight;
1463         n = (iR-iL)+1;
1464         assert(n>=0);
1465         index = (int) (uSeed%n);
1466
1467         iMid=pSortBuffer[index + iL];
1468
1469
1470         do
1471         {
1472                 while(pSortBuffer[iL] < iMid)
1473                         ++iL;
1474                 while(pSortBuffer[iR] > iMid)
1475                         --iR;
1476
1477                 if(iL <= iR)
1478                 {
1479                         iTmp = pSortBuffer[iL];
1480                         pSortBuffer[iL] = pSortBuffer[iR];
1481                         pSortBuffer[iR] = iTmp;
1482                         ++iL; --iR;
1483                 }
1484         }
1485         while(iL <= iR);
1486
1487         if(iLeft < iR)
1488                 QuickSort(pSortBuffer, iLeft, iR, uSeed);
1489         if(iL < iRight)
1490                 QuickSort(pSortBuffer, iL, iRight, uSeed);
1491 }
1492
1493 /////////////////////////////////////////////////////////////////////////////////////////////
1494 /////////////////////////////////////////////////////////////////////////////////////////////
1495
1496 void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed);
1497 void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in);
1498
1499 void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn)
1500 {
1501         // build array of edges
1502         unsigned int uSeed = INTERNAL_RND_SORT_SEED;                            // could replace with a random seed?
1503         int iEntries=0, iCurStartIndex=-1, f=0, i=0;
1504         for(f=0; f<iNrTrianglesIn; f++)
1505                 for(i=0; i<3; i++)
1506                 {
1507                         const int i0 = piTriListIn[f*3+i];
1508                         const int i1 = piTriListIn[f*3+(i<2?(i+1):0)];
1509                         pEdges[f*3+i].i0 = i0 < i1 ? i0 : i1;                   // put minimum index in i0
1510                         pEdges[f*3+i].i1 = !(i0 < i1) ? i0 : i1;                // put maximum index in i1
1511                         pEdges[f*3+i].f = f;                                                    // record face number
1512                 }
1513
1514         // sort over all edges by i0, this is the pricy one.
1515         QuickSortEdges(pEdges, 0, iNrTrianglesIn*3-1, 0, uSeed);        // sort channel 0 which is i0
1516
1517         // sub sort over i1, should be fast.
1518         // could replace this with a 64 bit int sort over (i0,i1)
1519         // with i0 as msb in the quicksort call above.
1520         iEntries = iNrTrianglesIn*3;
1521         iCurStartIndex = 0;
1522         for(i=1; i<iEntries; i++)
1523         {
1524                 if(pEdges[iCurStartIndex].i0 != pEdges[i].i0)
1525                 {
1526                         const int iL = iCurStartIndex;
1527                         const int iR = i-1;
1528                         //const int iElems = i-iL;
1529                         iCurStartIndex = i;
1530                         QuickSortEdges(pEdges, iL, iR, 1, uSeed);       // sort channel 1 which is i1
1531                 }
1532         }
1533
1534         // sub sort over f, which should be fast.
1535         // this step is to remain compliant with BuildNeighborsSlow() when
1536         // more than 2 triangles use the same edge (such as a butterfly topology).
1537         iCurStartIndex = 0;
1538         for(i=1; i<iEntries; i++)
1539         {
1540                 if(pEdges[iCurStartIndex].i0 != pEdges[i].i0 || pEdges[iCurStartIndex].i1 != pEdges[i].i1)
1541                 {
1542                         const int iL = iCurStartIndex;
1543                         const int iR = i-1;
1544                         //const int iElems = i-iL;
1545                         iCurStartIndex = i;
1546                         QuickSortEdges(pEdges, iL, iR, 2, uSeed);       // sort channel 2 which is f
1547                 }
1548         }
1549
1550         // pair up, adjacent triangles
1551         for(i=0; i<iEntries; i++)
1552         {
1553                 const int i0=pEdges[i].i0;
1554                 const int i1=pEdges[i].i1;
1555                 const int f = pEdges[i].f;
1556                 tbool bUnassigned_A;
1557
1558                 int i0_A, i1_A;
1559                 int edgenum_A, edgenum_B=0;     // 0,1 or 2
1560                 GetEdge(&i0_A, &i1_A, &edgenum_A, &piTriListIn[f*3], i0, i1);   // resolve index ordering and edge_num
1561                 bUnassigned_A = pTriInfos[f].FaceNeighbors[edgenum_A] == -1 ? TTRUE : TFALSE;
1562
1563                 if(bUnassigned_A)
1564                 {
1565                         // get true index ordering
1566                         int j=i+1, t;
1567                         tbool bNotFound = TTRUE;
1568                         while(j<iEntries && i0==pEdges[j].i0 && i1==pEdges[j].i1 && bNotFound)
1569                         {
1570                                 tbool bUnassigned_B;
1571                                 int i0_B, i1_B;
1572                                 t = pEdges[j].f;
1573                                 // flip i0_B and i1_B
1574                                 GetEdge(&i1_B, &i0_B, &edgenum_B, &piTriListIn[t*3], pEdges[j].i0, pEdges[j].i1);       // resolve index ordering and edge_num
1575                                 //assert(!(i0_A==i1_B && i1_A==i0_B));
1576                                 bUnassigned_B =  pTriInfos[t].FaceNeighbors[edgenum_B]==-1 ? TTRUE : TFALSE;
1577                                 if(i0_A==i0_B && i1_A==i1_B && bUnassigned_B)
1578                                         bNotFound = TFALSE;
1579                                 else
1580                                         ++j;
1581                         }
1582
1583                         if(!bNotFound)
1584                         {
1585                                 int t = pEdges[j].f;
1586                                 pTriInfos[f].FaceNeighbors[edgenum_A] = t;
1587                                 //assert(pTriInfos[t].FaceNeighbors[edgenum_B]==-1);
1588                                 pTriInfos[t].FaceNeighbors[edgenum_B] = f;
1589                         }
1590                 }
1591         }
1592 }
1593
1594 void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn)
1595 {
1596         int f=0, i=0;
1597         for(f=0; f<iNrTrianglesIn; f++)
1598         {
1599                 for(i=0; i<3; i++)
1600                 {
1601                         // if unassigned
1602                         if(pTriInfos[f].FaceNeighbors[i] == -1)
1603                         {
1604                                 const int i0_A = piTriListIn[f*3+i];
1605                                 const int i1_A = piTriListIn[f*3+(i<2?(i+1):0)];
1606
1607                                 // search for a neighbor
1608                                 tbool bFound = TFALSE;
1609                                 int t=0, j=0;
1610                                 while(!bFound && t<iNrTrianglesIn)
1611                                 {
1612                                         if(t!=f)
1613                                         {
1614                                                 j=0;
1615                                                 while(!bFound && j<3)
1616                                                 {
1617                                                         // in rev order
1618                                                         const int i1_B = piTriListIn[t*3+j];
1619                                                         const int i0_B = piTriListIn[t*3+(j<2?(j+1):0)];
1620                                                         //assert(!(i0_A==i1_B && i1_A==i0_B));
1621                                                         if(i0_A==i0_B && i1_A==i1_B)
1622                                                                 bFound = TTRUE;
1623                                                         else
1624                                                                 ++j;
1625                                                 }
1626                                         }
1627                                         
1628                                         if(!bFound) ++t;
1629                                 }
1630
1631                                 // assign neighbors
1632                                 if(bFound)
1633                                 {
1634                                         pTriInfos[f].FaceNeighbors[i] = t;
1635                                         //assert(pTriInfos[t].FaceNeighbors[j]==-1);
1636                                         pTriInfos[t].FaceNeighbors[j] = f;
1637                                 }
1638                         }
1639                 }
1640         }
1641 }
1642
1643 void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed)
1644 {
1645         unsigned int t;
1646         int iL, iR, n, index, iMid;
1647
1648         // early out
1649         SEdge sTmp;
1650         const int iElems = iRight-iLeft+1;
1651         if(iElems<2) return;
1652         else if(iElems==2)
1653         {
1654                 if(pSortBuffer[iLeft].array[channel] > pSortBuffer[iRight].array[channel])
1655                 {
1656                         sTmp = pSortBuffer[iLeft];
1657                         pSortBuffer[iLeft] = pSortBuffer[iRight];
1658                         pSortBuffer[iRight] = sTmp;
1659                 }
1660                 return;
1661         }
1662
1663         // Random
1664         t=uSeed&31;
1665         t=(uSeed<<t)|(uSeed>>(32-t));
1666         uSeed=uSeed+t+3;
1667         // Random end
1668
1669         iL=iLeft, iR=iRight;
1670         n = (iR-iL)+1;
1671         assert(n>=0);
1672         index = (int) (uSeed%n);
1673
1674         iMid=pSortBuffer[index + iL].array[channel];
1675
1676         do
1677         {
1678                 while(pSortBuffer[iL].array[channel] < iMid)
1679                         ++iL;
1680                 while(pSortBuffer[iR].array[channel] > iMid)
1681                         --iR;
1682
1683                 if(iL <= iR)
1684                 {
1685                         sTmp = pSortBuffer[iL];
1686                         pSortBuffer[iL] = pSortBuffer[iR];
1687                         pSortBuffer[iR] = sTmp;
1688                         ++iL; --iR;
1689                 }
1690         }
1691         while(iL <= iR);
1692
1693         if(iLeft < iR)
1694                 QuickSortEdges(pSortBuffer, iLeft, iR, channel, uSeed);
1695         if(iL < iRight)
1696                 QuickSortEdges(pSortBuffer, iL, iRight, channel, uSeed);
1697 }
1698
1699 // resolve ordering and edge number
1700 void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in)
1701 {
1702         *edgenum_out = -1;
1703         
1704         // test if first index is on the edge
1705         if(indices[0]==i0_in || indices[0]==i1_in)
1706         {
1707                 // test if second index is on the edge
1708                 if(indices[1]==i0_in || indices[1]==i1_in)
1709                 {
1710                         edgenum_out[0]=0;       // first edge
1711                         i0_out[0]=indices[0];
1712                         i1_out[0]=indices[1];
1713                 }
1714                 else
1715                 {
1716                         edgenum_out[0]=2;       // third edge
1717                         i0_out[0]=indices[2];
1718                         i1_out[0]=indices[0];
1719                 }
1720         }
1721         else
1722         {
1723                 // only second and third index is on the edge
1724                 edgenum_out[0]=1;       // second edge
1725                 i0_out[0]=indices[1];
1726                 i1_out[0]=indices[2];
1727         }
1728 }
1729
1730
1731 /////////////////////////////////////////////////////////////////////////////////////////////
1732 /////////////////////////////////// Degenerate triangles ////////////////////////////////////
1733
1734 void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris)
1735 {
1736         int iNextGoodTriangleSearchIndex=-1;
1737         tbool bStillFindingGoodOnes;
1738
1739         // locate quads with only one good triangle
1740         int t=0;
1741         while(t<(iTotTris-1))
1742         {
1743                 const int iFO_a = pTriInfos[t].iOrgFaceNumber;
1744                 const int iFO_b = pTriInfos[t+1].iOrgFaceNumber;
1745                 if(iFO_a==iFO_b)        // this is a quad
1746                 {
1747                         const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;
1748                         const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;
1749                         if((bIsDeg_a^bIsDeg_b)!=0)
1750                         {
1751                                 pTriInfos[t].iFlag |= QUAD_ONE_DEGEN_TRI;
1752                                 pTriInfos[t+1].iFlag |= QUAD_ONE_DEGEN_TRI;
1753                         }
1754                         t += 2;
1755                 }
1756                 else
1757                         ++t;
1758         }
1759
1760         // reorder list so all degen triangles are moved to the back
1761         // without reordering the good triangles
1762         iNextGoodTriangleSearchIndex = 1;
1763         t=0;
1764         bStillFindingGoodOnes = TTRUE;
1765         while(t<iNrTrianglesIn && bStillFindingGoodOnes)
1766         {
1767                 const tbool bIsGood = (pTriInfos[t].iFlag&MARK_DEGENERATE)==0 ? TTRUE : TFALSE;
1768                 if(bIsGood)
1769                 {
1770                         if(iNextGoodTriangleSearchIndex < (t+2))
1771                                 iNextGoodTriangleSearchIndex = t+2;
1772                 }
1773                 else
1774                 {
1775                         int t0, t1;
1776                         // search for the first good triangle.
1777                         tbool bJustADegenerate = TTRUE;
1778                         while(bJustADegenerate && iNextGoodTriangleSearchIndex<iTotTris)
1779                         {
1780                                 const tbool bIsGood = (pTriInfos[iNextGoodTriangleSearchIndex].iFlag&MARK_DEGENERATE)==0 ? TTRUE : TFALSE;
1781                                 if(bIsGood) bJustADegenerate=TFALSE;
1782                                 else ++iNextGoodTriangleSearchIndex;
1783                         }
1784
1785                         t0 = t;
1786                         t1 = iNextGoodTriangleSearchIndex;
1787                         ++iNextGoodTriangleSearchIndex;
1788                         assert(iNextGoodTriangleSearchIndex > (t+1));
1789
1790                         // swap triangle t0 and t1
1791                         if(!bJustADegenerate)
1792                         {
1793                                 int i=0;
1794                                 for(i=0; i<3; i++)
1795                                 {
1796                                         const int index = piTriList_out[t0*3+i];
1797                                         piTriList_out[t0*3+i] = piTriList_out[t1*3+i];
1798                                         piTriList_out[t1*3+i] = index;
1799                                 }
1800                                 {
1801                                         const STriInfo tri_info = pTriInfos[t0];
1802                                         pTriInfos[t0] = pTriInfos[t1];
1803                                         pTriInfos[t1] = tri_info;
1804                                 }
1805                         }
1806                         else
1807                                 bStillFindingGoodOnes = TFALSE; // this is not supposed to happen
1808                 }
1809
1810                 if(bStillFindingGoodOnes) ++t;
1811         }
1812
1813         assert(bStillFindingGoodOnes);  // code will still work.
1814         assert(iNrTrianglesIn == t);
1815 }
1816
1817 void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris)
1818 {
1819         int t=0, i=0;
1820         // deal with degenerate triangles
1821         // punishment for degenerate triangles is O(N^2)
1822         for(t=iNrTrianglesIn; t<iTotTris; t++)
1823         {
1824                 // degenerate triangles on a quad with one good triangle are skipped
1825                 // here but processed in the next loop
1826                 const tbool bSkip = (pTriInfos[t].iFlag&QUAD_ONE_DEGEN_TRI)!=0 ? TTRUE : TFALSE;
1827
1828                 if(!bSkip)
1829                 {
1830                         for(i=0; i<3; i++)
1831                         {
1832                                 const int index1 = piTriListIn[t*3+i];
1833                                 // search through the good triangles
1834                                 tbool bNotFound = TTRUE;
1835                                 int j=0;
1836                                 while(bNotFound && j<(3*iNrTrianglesIn))
1837                                 {
1838                                         const int index2 = piTriListIn[j];
1839                                         if(index1==index2) bNotFound=TFALSE;
1840                                         else ++j;
1841                                 }
1842
1843                                 if(!bNotFound)
1844                                 {
1845                                         const int iTri = j/3;
1846                                         const int iVert = j%3;
1847                                         const int iSrcVert=pTriInfos[iTri].vert_num[iVert];
1848                                         const int iSrcOffs=pTriInfos[iTri].iTSpacesOffs;
1849                                         const int iDstVert=pTriInfos[t].vert_num[i];
1850                                         const int iDstOffs=pTriInfos[t].iTSpacesOffs;
1851                                         
1852                                         // copy tspace
1853                                         psTspace[iDstOffs+iDstVert] = psTspace[iSrcOffs+iSrcVert];
1854                                 }
1855                         }
1856                 }
1857         }
1858
1859         // deal with degenerate quads with one good triangle
1860         for(t=0; t<iNrTrianglesIn; t++)
1861         {
1862                 // this triangle belongs to a quad where the
1863                 // other triangle is degenerate
1864                 if( (pTriInfos[t].iFlag&QUAD_ONE_DEGEN_TRI)!=0 )
1865                 {
1866                         SVec3 vDstP;
1867                         int iOrgF=-1, i=0;
1868                         tbool bNotFound;
1869                         unsigned char * pV = pTriInfos[t].vert_num;
1870                         int iFlag = (1<<pV[0]) | (1<<pV[1]) | (1<<pV[2]);
1871                         int iMissingIndex = 0;
1872                         if((iFlag&2)==0) iMissingIndex=1;
1873                         else if((iFlag&4)==0) iMissingIndex=2;
1874                         else if((iFlag&8)==0) iMissingIndex=3;
1875
1876                         iOrgF = pTriInfos[t].iOrgFaceNumber;
1877                         vDstP = GetPosition(pContext, MakeIndex(iOrgF, iMissingIndex));
1878                         bNotFound = TTRUE;
1879                         i=0;
1880                         while(bNotFound && i<3)
1881                         {
1882                                 const int iVert = pV[i];
1883                                 const SVec3 vSrcP = GetPosition(pContext, MakeIndex(iOrgF, iVert));
1884                                 if(veq(vSrcP, vDstP)==TTRUE)
1885                                 {
1886                                         const int iOffs = pTriInfos[t].iTSpacesOffs;
1887                                         psTspace[iOffs+iMissingIndex] = psTspace[iOffs+iVert];
1888                                         bNotFound=TFALSE;
1889                                 }
1890                                 else
1891                                         ++i;
1892                         }
1893                         assert(!bNotFound);
1894                 }
1895         }
1896 }