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