merge with trunk at r27259 and commit of a patch by anthony jones to fix msvc (though...
[blender-staging.git] / source / blender / editors / armature / reeb.c
1 /**
2  * $Id: 
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22  *
23  * Contributor(s): Martin Poirier
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27  
28 #include <math.h>
29 #include <string.h> // for memcpy
30 #include <stdio.h>
31 #include <stdlib.h> // for qsort
32 #include <float.h>
33
34 #include "PIL_time.h"
35
36 #include "DNA_listBase.h"
37 #include "DNA_scene_types.h"
38 #include "DNA_space_types.h"
39 #include "DNA_object_types.h"
40 #include "DNA_meshdata_types.h"
41 #include "DNA_armature_types.h"
42
43 #include "BKE_context.h"
44
45 #include "MEM_guardedalloc.h"
46
47 #include "BLI_blenlib.h"
48 #include "BLI_math.h"
49 #include "BLI_editVert.h"
50 #include "BLI_edgehash.h"
51 #include "BLI_ghash.h"
52 #include "BLI_heap.h"
53
54 //#include "BDR_editobject.h"
55
56 #include "ED_mesh.h"
57 #include "ED_armature.h"
58 //#include "BIF_interface.h"
59 //#include "BIF_toolbox.h"
60 //#include "BIF_graphics.h"
61 #include "BIF_gl.h"
62 #include "UI_resources.h"
63
64 #include "BKE_global.h"
65 #include "BKE_utildefines.h"
66 #include "BKE_customdata.h"
67 #include "BKE_mesh.h"
68
69 //#include "blendef.h"
70
71 #include "ONL_opennl.h"
72
73 #include "reeb.h"
74
75
76 ReebGraph *GLOBAL_RG = NULL;
77 ReebGraph *FILTERED_RG = NULL;
78
79 /*
80  * Skeleton generation algorithm based on: 
81  * "Harmonic Skeleton for Realistic Character Animation"
82  * Gregoire Aujay, Franck Hetroy, Francis Lazarus and Christine Depraz
83  * SIGGRAPH 2007
84  * 
85  * Reeb graph generation algorithm based on: 
86  * "Robust On-line Computation of Reeb Graphs: Simplicity and Speed"
87  * Valerio Pascucci, Giorgio Scorzelli, Peer-Timo Bremer and Ajith Mascarenhas
88  * SIGGRAPH 2007
89  * 
90  * */
91  
92 #define DEBUG_REEB
93 #define DEBUG_REEB_NODE
94
95 typedef struct VertexData
96 {
97         float w; /* weight */
98         int i; /* index */
99         ReebNode *n;
100 } VertexData;
101
102 typedef struct EdgeIndex
103 {
104         EditEdge **edges;
105         int              *offset;
106 } EdgeIndex;
107
108 typedef enum {
109         MERGE_LOWER,
110         MERGE_HIGHER,
111         MERGE_APPEND
112 } MergeDirection;
113
114 int mergeArcs(ReebGraph *rg, ReebArc *a0, ReebArc *a1);
115 void mergeArcEdges(ReebGraph *rg, ReebArc *aDst, ReebArc *aSrc, MergeDirection direction);
116 int mergeConnectedArcs(ReebGraph *rg, ReebArc *a0, ReebArc *a1);
117 EditEdge * NextEdgeForVert(EdgeIndex *indexed_edges, int index);
118 void mergeArcFaces(ReebGraph *rg, ReebArc *aDst, ReebArc *aSrc);
119 void addFacetoArc(ReebArc *arc, EditFace *efa);
120
121 void REEB_RadialSymmetry(BNode* root_node, RadialArc* ring, int count);
122 void REEB_AxialSymmetry(BNode* root_node, BNode* node1, BNode* node2, struct BArc* barc1, BArc* barc2);
123
124 void flipArcBuckets(ReebArc *arc);
125
126
127 /***************************************** UTILS **********************************************/
128
129 VertexData *allocVertexData(EditMesh *em)
130 {
131         VertexData *data;
132         EditVert *eve;
133         int totvert, index;
134         
135         totvert = BLI_countlist(&em->verts);
136         
137         data = MEM_callocN(sizeof(VertexData) * totvert, "VertexData");
138
139         for(index = 0, eve = em->verts.first; eve; index++, eve = eve->next)
140         {
141                 data[index].i = index;
142                 data[index].w = 0;
143                 eve->tmp.p = data + index;
144         }
145                 
146         return data;
147 }
148
149 int indexData(EditVert *eve)
150 {
151         return ((VertexData*)eve->tmp.p)->i;
152 }
153
154 float weightData(EditVert *eve)
155 {
156         return ((VertexData*)eve->tmp.p)->w;
157 }
158
159 void weightSetData(EditVert *eve, float w)
160 {
161         ((VertexData*)eve->tmp.p)->w = w;
162 }
163
164 ReebNode* nodeData(EditVert *eve)
165 {
166         return ((VertexData*)eve->tmp.p)->n;
167 }
168
169 void nodeSetData(EditVert *eve, ReebNode *n)
170 {
171         ((VertexData*)eve->tmp.p)->n = n;
172 }
173
174 void REEB_freeArc(BArc *barc)
175 {
176         ReebArc *arc = (ReebArc*)barc;
177         BLI_freelistN(&arc->edges);
178         
179         if (arc->buckets)
180                 MEM_freeN(arc->buckets);
181                 
182         if (arc->faces)
183                 BLI_ghash_free(arc->faces, NULL, NULL);
184         
185         MEM_freeN(arc);
186 }
187
188 void REEB_freeGraph(ReebGraph *rg)
189 {
190         ReebArc *arc;
191         ReebNode *node;
192         
193         // free nodes
194         for( node = rg->nodes.first; node; node = node->next )
195         {
196                 BLI_freeNode((BGraph*)rg, (BNode*)node);
197         }
198         BLI_freelistN(&rg->nodes);
199         
200         // free arcs
201         arc = rg->arcs.first;
202         while( arc )
203         {
204                 ReebArc *next = arc->next;
205                 REEB_freeArc((BArc*)arc);
206                 arc = next;
207         }
208         
209         // free edge map
210         BLI_edgehash_free(rg->emap, NULL);
211         
212         /* free linked graph */
213         if (rg->link_up)
214         {
215                 REEB_freeGraph(rg->link_up);
216         }
217         
218         MEM_freeN(rg);
219 }
220
221 ReebGraph * newReebGraph()
222 {
223         ReebGraph *rg;
224         rg = MEM_callocN(sizeof(ReebGraph), "reeb graph");
225         
226         rg->totnodes = 0;
227         rg->emap = BLI_edgehash_new();
228         
229         
230         rg->free_arc = REEB_freeArc;
231         rg->free_node = NULL;
232         rg->radial_symmetry = REEB_RadialSymmetry;
233         rg->axial_symmetry = REEB_AxialSymmetry;
234         
235         return rg;
236 }
237
238 void BIF_flagMultiArcs(ReebGraph *rg, int flag)
239 {
240         for ( ; rg; rg = rg->link_up)
241         {
242                 BLI_flagArcs((BGraph*)rg, flag);
243         }
244 }
245
246 ReebNode * addNode(ReebGraph *rg, EditVert *eve)
247 {
248         float weight;
249         ReebNode *node = NULL;
250         
251         weight = weightData(eve);
252         
253         node = MEM_callocN(sizeof(ReebNode), "reeb node");
254         
255         node->flag = 0; // clear flag on init
256         node->symmetry_level = 0;
257         node->arcs = NULL;
258         node->degree = 0;
259         node->weight = weight;
260         node->index = rg->totnodes;
261         VECCOPY(node->p, eve->co);      
262         
263         BLI_addtail(&rg->nodes, node);
264         rg->totnodes++;
265         
266         nodeSetData(eve, node);
267         
268         return node;
269 }
270
271 ReebNode * copyNode(ReebGraph *rg, ReebNode *node)
272 {
273         ReebNode *cp_node = NULL;
274         
275         cp_node = MEM_callocN(sizeof(ReebNode), "reeb node copy");
276         
277         memcpy(cp_node, node, sizeof(ReebNode));
278         
279         cp_node->prev = NULL;
280         cp_node->next = NULL;
281         cp_node->arcs = NULL;
282         
283         cp_node->link_up = NULL;
284         cp_node->link_down = NULL;
285         
286         BLI_addtail(&rg->nodes, cp_node);
287         rg->totnodes++;
288         
289         return cp_node; 
290 }
291
292 void relinkNodes(ReebGraph *low_rg, ReebGraph *high_rg)
293 {
294         ReebNode *low_node, *high_node;
295         
296         if (low_rg == NULL || high_rg == NULL)
297         {
298                 return;
299         }
300         
301         for (low_node = low_rg->nodes.first; low_node; low_node = low_node->next)
302         {
303                 for (high_node = high_rg->nodes.first; high_node; high_node = high_node->next)
304                 {
305                         if (low_node->index == high_node->index)
306                         {
307                                 high_node->link_down = low_node;
308                                 low_node->link_up = high_node;
309                                 break;
310                         }
311                 }
312         }
313 }
314
315 ReebNode *BIF_otherNodeFromIndex(ReebArc *arc, ReebNode *node)
316 {
317         return (arc->head->index == node->index) ? arc->tail : arc->head;
318 }
319
320 ReebNode *BIF_NodeFromIndex(ReebArc *arc, ReebNode *node)
321 {
322         return (arc->head->index == node->index) ? arc->head : arc->tail;
323 }
324
325 ReebNode *BIF_lowestLevelNode(ReebNode *node)
326 {
327         while (node->link_down)
328         {
329                 node = node->link_down;
330         }
331         
332         return node;
333 }
334
335 ReebArc * copyArc(ReebGraph *rg, ReebArc *arc)
336 {
337         ReebArc *cp_arc;
338         ReebNode *node;
339         
340         cp_arc = MEM_callocN(sizeof(ReebArc), "reeb arc copy");
341
342         memcpy(cp_arc, arc, sizeof(ReebArc));
343         
344         cp_arc->link_up = arc;
345         
346         cp_arc->head = NULL;
347         cp_arc->tail = NULL;
348
349         cp_arc->prev = NULL;
350         cp_arc->next = NULL;
351
352         cp_arc->edges.first = NULL;
353         cp_arc->edges.last = NULL;
354
355         /* copy buckets */      
356         cp_arc->buckets = MEM_callocN(sizeof(EmbedBucket) * cp_arc->bcount, "embed bucket");
357         memcpy(cp_arc->buckets, arc->buckets, sizeof(EmbedBucket) * cp_arc->bcount);
358         
359         /* copy faces map */
360         cp_arc->faces = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
361         mergeArcFaces(rg, cp_arc, arc);
362         
363         /* find corresponding head and tail */
364         for (node = rg->nodes.first; node && (cp_arc->head == NULL || cp_arc->tail == NULL); node = node->next)
365         {
366                 if (node->index == arc->head->index)
367                 {
368                         cp_arc->head = node;
369                 }
370                 else if (node->index == arc->tail->index)
371                 {
372                         cp_arc->tail = node;
373                 }
374         }
375         
376         BLI_addtail(&rg->arcs, cp_arc);
377         
378         return cp_arc;
379 }
380
381 ReebGraph * copyReebGraph(ReebGraph *rg, int level)
382 {
383         ReebNode *node;
384         ReebArc *arc;
385         ReebGraph *cp_rg = newReebGraph();
386         
387         cp_rg->resolution = rg->resolution;
388         cp_rg->length = rg->length;
389         cp_rg->link_up = rg;
390         cp_rg->multi_level = level;
391
392         /* Copy nodes */        
393         for (node = rg->nodes.first; node; node = node->next)
394         {
395                 ReebNode *cp_node = copyNode(cp_rg, node);
396                 cp_node->multi_level = level;
397         }
398         
399         /* Copy arcs */
400         for (arc = rg->arcs.first; arc; arc = arc->next)
401         {
402                 copyArc(cp_rg, arc);
403         }
404         
405         BLI_buildAdjacencyList((BGraph*)cp_rg);
406         
407         return cp_rg;
408 }
409
410 ReebGraph *BIF_graphForMultiNode(ReebGraph *rg, ReebNode *node)
411 {
412         ReebGraph *multi_rg = rg;
413         
414         while(multi_rg && multi_rg->multi_level != node->multi_level)
415         {
416                 multi_rg = multi_rg->link_up;
417         }
418         
419         return multi_rg;
420 }
421
422 ReebEdge * copyEdge(ReebEdge *edge)
423 {
424         ReebEdge *newEdge = NULL;
425         
426         newEdge = MEM_callocN(sizeof(ReebEdge), "reeb edge");
427         memcpy(newEdge, edge, sizeof(ReebEdge));
428         
429         newEdge->next = NULL;
430         newEdge->prev = NULL;
431         
432         return newEdge;
433 }
434
435 void printArc(ReebArc *arc)
436 {
437         ReebEdge *edge;
438         ReebNode *head = (ReebNode*)arc->head;
439         ReebNode *tail = (ReebNode*)arc->tail;
440         printf("arc: (%i) %f -> (%i) %f\n", head->index, head->weight, tail->index, tail->weight);
441         
442         for(edge = arc->edges.first; edge ; edge = edge->next)
443         {
444                 printf("\tedge (%i, %i)\n", edge->v1->index, edge->v2->index);
445         }
446 }
447
448 void flipArc(ReebArc *arc)
449 {
450         ReebNode *tmp;
451         tmp = arc->head;
452         arc->head = arc->tail;
453         arc->tail = tmp;
454         
455         flipArcBuckets(arc);
456 }
457
458 #ifdef DEBUG_REEB_NODE
459 void NodeDegreeDecrement(ReebGraph *rg, ReebNode *node)
460 {
461         node->degree--;
462
463 //      if (node->degree == 0)
464 //      {
465 //              printf("would remove node %i\n", node->index);
466 //      }
467 }
468
469 void NodeDegreeIncrement(ReebGraph *rg, ReebNode *node)
470 {
471 //      if (node->degree == 0)
472 //      {
473 //              printf("first connect node %i\n", node->index);
474 //      }
475
476         node->degree++;
477 }
478
479 #else
480 #define NodeDegreeDecrement(rg, node) {node->degree--;}
481 #define NodeDegreeIncrement(rg, node) {node->degree++;}
482 #endif
483
484 void repositionNodes(ReebGraph *rg)
485 {
486         BArc *arc = NULL;
487         BNode *node = NULL;
488         
489         // Reset node positions
490         for(node = rg->nodes.first; node; node = node->next)
491         {
492                 node->p[0] = node->p[1] = node->p[2] = 0;
493         }
494         
495         for(arc = rg->arcs.first; arc; arc = arc->next)
496         {
497                 if (((ReebArc*)arc)->bcount > 0)
498                 {
499                         float p[3];
500                         
501                         VECCOPY(p, ((ReebArc*)arc)->buckets[0].p);
502                         mul_v3_fl(p, 1.0f / arc->head->degree);
503                         add_v3_v3v3(arc->head->p, arc->head->p, p);
504                         
505                         VECCOPY(p, ((ReebArc*)arc)->buckets[((ReebArc*)arc)->bcount - 1].p);
506                         mul_v3_fl(p, 1.0f / arc->tail->degree);
507                         add_v3_v3v3(arc->tail->p, arc->tail->p, p);
508                 }
509         }
510 }
511
512 void verifyNodeDegree(ReebGraph *rg)
513 {
514 #ifdef DEBUG_REEB
515         ReebNode *node = NULL;
516         ReebArc *arc = NULL;
517
518         for(node = rg->nodes.first; node; node = node->next)
519         {
520                 int count = 0;
521                 for(arc = rg->arcs.first; arc; arc = arc->next)
522                 {
523                         if (arc->head == node || arc->tail == node)
524                         {
525                                 count++;
526                         }
527                 }
528                 if (count != node->degree)
529                 {
530                         printf("degree error in node %i: expected %i got %i\n", node->index, count, node->degree);
531                 }
532                 if (node->degree == 0)
533                 {
534                         printf("zero degree node %i with weight %f\n", node->index, node->weight);
535                 }
536         }
537 #endif
538 }
539
540 void verifyBucketsArc(ReebGraph *rg, ReebArc *arc)
541 {
542         ReebNode *head = (ReebNode*)arc->head;
543         ReebNode *tail = (ReebNode*)arc->tail;
544
545         if (arc->bcount > 0)
546         {
547                 int i;
548                 for(i = 0; i < arc->bcount; i++)
549                 {
550                         if (arc->buckets[i].nv == 0)
551                         {
552                                 printArc(arc);
553                                 printf("count error in bucket %i/%i\n", i+1, arc->bcount);
554                         }
555                 }
556                 
557                 if (ceil(head->weight) != arc->buckets[0].val)
558                 {
559                         printArc(arc);
560                         printf("alloc error in first bucket: %f should be %f \n", arc->buckets[0].val, ceil(head->weight));
561                 }
562                 if (floor(tail->weight) != arc->buckets[arc->bcount - 1].val)
563                 {
564                         printArc(arc);
565                         printf("alloc error in last bucket: %f should be %f \n", arc->buckets[arc->bcount - 1].val, floor(tail->weight));
566                 }
567         }
568 }
569
570 void verifyBuckets(ReebGraph *rg)
571 {
572 #ifdef DEBUG_REEB
573         ReebArc *arc = NULL;
574         for(arc = rg->arcs.first; arc; arc = arc->next)
575         {
576                 verifyBucketsArc(rg, arc);
577         }
578 #endif
579 }
580
581 void verifyFaces(ReebGraph *rg)
582 {
583 #ifdef DEBUG_REEB
584         int total = 0;
585         ReebArc *arc = NULL;
586         for(arc = rg->arcs.first; arc; arc = arc->next)
587         {
588                 total += BLI_ghash_size(arc->faces);
589         }
590         
591 #endif
592 }
593
594 void verifyArcs(ReebGraph *rg)
595 {
596         ReebArc *arc;
597         
598         for (arc = rg->arcs.first; arc; arc = arc->next)
599         {
600                 if (arc->head->weight > arc->tail->weight)
601                 {
602                         printf("FLIPPED ARC!\n");
603                 }
604         }
605 }
606
607 void verifyMultiResolutionLinks(ReebGraph *rg, int level)
608 {
609 #ifdef DEBUG_REEB
610         ReebGraph *lower_rg = rg->link_up;
611         
612         if (lower_rg)
613         {
614                 ReebArc *arc;
615                 
616                 for (arc = rg->arcs.first; arc; arc = arc->next)
617                 {
618                         if (BLI_findindex(&lower_rg->arcs, arc->link_up) == -1)
619                         {
620                                 printf("missing arc %p for level %i\n", arc->link_up, level);
621                                 printf("Source arc was ---\n");
622                                 printArc(arc);
623
624                                 arc->link_up = NULL;
625                         }
626                 }
627                 
628                 
629                 verifyMultiResolutionLinks(lower_rg, level + 1);
630         }
631 #endif
632 }
633 /***************************************** BUCKET UTILS **********************************************/
634
635 void addVertToBucket(EmbedBucket *b, float co[3])
636 {
637         b->nv++;
638         interp_v3_v3v3(b->p, b->p, co, 1.0f / b->nv);
639 }
640
641 void removeVertFromBucket(EmbedBucket *b, float co[3])
642 {
643         mul_v3_fl(b->p, (float)b->nv);
644         sub_v3_v3v3(b->p, b->p, co);
645         b->nv--;
646         mul_v3_fl(b->p, 1.0f / (float)b->nv);
647 }
648
649 void mergeBuckets(EmbedBucket *bDst, EmbedBucket *bSrc)
650 {
651         if (bDst->nv > 0 && bSrc->nv > 0)
652         {
653                 bDst->nv += bSrc->nv;
654                 interp_v3_v3v3(bDst->p, bDst->p, bSrc->p, (float)bSrc->nv / (float)(bDst->nv));
655         }
656         else if (bSrc->nv > 0)
657         {
658                 bDst->nv = bSrc->nv;
659                 VECCOPY(bDst->p, bSrc->p);
660         }
661 }
662
663 void mergeArcBuckets(ReebArc *aDst, ReebArc *aSrc, float start, float end)
664 {
665         if (aDst->bcount > 0 && aSrc->bcount > 0)
666         {
667                 int indexDst = 0, indexSrc = 0;
668                 
669                 start = MAX3(start, aDst->buckets[0].val, aSrc->buckets[0].val);
670                 
671                 while(indexDst < aDst->bcount && aDst->buckets[indexDst].val < start)
672                 {
673                         indexDst++;
674                 }
675
676                 while(indexSrc < aSrc->bcount && aSrc->buckets[indexSrc].val < start)
677                 {
678                         indexSrc++;
679                 }
680                 
681                 for( ;  indexDst < aDst->bcount &&
682                                 indexSrc < aSrc->bcount &&
683                                 aDst->buckets[indexDst].val <= end &&
684                                 aSrc->buckets[indexSrc].val <= end
685                                 
686                          ;      indexDst++, indexSrc++)
687                 {
688                         mergeBuckets(aDst->buckets + indexDst, aSrc->buckets + indexSrc);
689                 }
690         }
691 }
692
693 void flipArcBuckets(ReebArc *arc)
694 {
695         int i, j;
696         
697         for (i = 0, j = arc->bcount - 1; i < j; i++, j--)
698         {
699                 EmbedBucket tmp;
700                 
701                 tmp = arc->buckets[i];
702                 arc->buckets[i] = arc->buckets[j];
703                 arc->buckets[j] = tmp;
704         }
705 }
706
707 int countArcBuckets(ReebArc *arc)
708 {
709         return (int)(floor(arc->tail->weight) - ceil(arc->head->weight)) + 1;
710 }
711
712 void allocArcBuckets(ReebArc *arc)
713 {
714         int i;
715         float start = ceil(arc->head->weight);
716         arc->bcount = countArcBuckets(arc);
717         
718         if (arc->bcount > 0)
719         {
720                 arc->buckets = MEM_callocN(sizeof(EmbedBucket) * arc->bcount, "embed bucket");
721                 
722                 for(i = 0; i < arc->bcount; i++)
723                 {
724                         arc->buckets[i].val = start + i;
725                 }
726         }
727         else
728         {
729                 arc->buckets = NULL;
730         }
731         
732 }
733
734 void resizeArcBuckets(ReebArc *arc)
735 {
736         EmbedBucket *oldBuckets = arc->buckets;
737         int oldBCount = arc->bcount;
738         
739         if (countArcBuckets(arc) == oldBCount)
740         {
741                 return;
742         }
743         
744         allocArcBuckets(arc);
745         
746         if (oldBCount != 0 && arc->bcount != 0)
747         {
748                 int oldStart = (int)oldBuckets[0].val;
749                 int oldEnd = (int)oldBuckets[oldBCount - 1].val;
750                 int newStart = (int)arc->buckets[0].val;
751                 int newEnd = (int)arc->buckets[arc->bcount - 1].val;
752                 int oldOffset = 0;
753                 int newOffset = 0;
754                 int len;
755                 
756                 if (oldStart < newStart)
757                 {
758                         oldOffset = newStart - oldStart;
759                 }
760                 else
761                 {
762                         newOffset = oldStart - newStart;
763                 }
764                 
765                 len = MIN2(oldEnd - (oldStart + oldOffset) + 1, newEnd - (newStart - newOffset) + 1);
766                 
767                 memcpy(arc->buckets + newOffset, oldBuckets + oldOffset, len * sizeof(EmbedBucket)); 
768         }
769
770         if (oldBuckets != NULL)
771         {
772                 MEM_freeN(oldBuckets);
773         }
774 }
775
776 void reweightBuckets(ReebArc *arc)
777 {
778         int i;
779         float start = ceil((arc->head)->weight);
780         
781         if (arc->bcount > 0)
782         {
783                 for(i = 0; i < arc->bcount; i++)
784                 {
785                         arc->buckets[i].val = start + i;
786                 }
787         }
788 }
789
790 static void interpolateBuckets(ReebArc *arc, float *start_p, float *end_p, int start_index, int end_index)
791 {
792         int total;
793         int j;
794         
795         total = end_index - start_index + 2;
796         
797         for (j = start_index; j <= end_index; j++)
798         {
799                 EmbedBucket *empty = arc->buckets + j;
800                 empty->nv = 1;
801                 interp_v3_v3v3(empty->p, start_p, end_p, (float)(j - start_index + 1) / total);
802         }
803 }
804
805 void fillArcEmptyBuckets(ReebArc *arc)
806 {
807         float *start_p, *end_p;
808         int start_index = 0, end_index = 0;
809         int missing = 0;
810         int i;
811         
812         start_p = arc->head->p;
813         
814         for(i = 0; i < arc->bcount; i++)
815         {
816                 EmbedBucket *bucket = arc->buckets + i;
817                 
818                 if (missing)
819                 {
820                         if (bucket->nv > 0)
821                         {
822                                 missing = 0;
823                                 
824                                 end_p = bucket->p;
825                                 end_index = i - 1;
826                                 
827                                 interpolateBuckets(arc, start_p, end_p, start_index, end_index);
828                         }
829                 }
830                 else
831                 {
832                         if (bucket->nv == 0)
833                         {
834                                 missing = 1;
835                                 
836                                 if (i > 0)
837                                 {
838                                         start_p = arc->buckets[i - 1].p;
839                                 }
840                                 start_index = i;
841                         }
842                 }
843         }
844         
845         if (missing)
846         {
847                 end_p = arc->tail->p;
848                 end_index = arc->bcount - 1;
849                 
850                 interpolateBuckets(arc, start_p, end_p, start_index, end_index);
851         }
852 }
853
854 static void ExtendArcBuckets(ReebArc *arc)
855 {
856         ReebArcIterator arc_iter;
857         BArcIterator *iter = (BArcIterator*)&arc_iter;
858         EmbedBucket *last_bucket, *first_bucket;
859         float *previous = NULL;
860         float average_length = 0, length;
861         int padding_head = 0, padding_tail = 0;
862         
863         if (arc->bcount == 0)
864         {
865                 return; /* failsafe, shouldn't happen */
866         }
867         
868         initArcIterator(iter, arc, arc->head);
869         IT_next(iter);
870         previous = iter->p;
871         
872         for (   IT_next(iter);
873                         IT_stopped(iter) == 0;
874                         previous = iter->p, IT_next(iter)
875                 )
876         {
877                 average_length += len_v3v3(previous, iter->p);
878         }
879         average_length /= (arc->bcount - 1);
880         
881         first_bucket = arc->buckets;
882         last_bucket = arc->buckets + (arc->bcount - 1);
883         
884         length = len_v3v3(first_bucket->p, arc->head->p);
885         if (length > 2 * average_length)
886         {
887                 padding_head = (int)floor(length / average_length);
888         }
889
890         length = len_v3v3(last_bucket->p, arc->tail->p);
891         if (length > 2 * average_length)
892         {
893                 padding_tail = (int)floor(length / average_length);
894         }
895         
896         if (padding_head + padding_tail > 0)
897         {
898                 EmbedBucket *old_buckets = arc->buckets;
899                 
900                 arc->buckets = MEM_callocN(sizeof(EmbedBucket) * (padding_head + arc->bcount + padding_tail), "embed bucket");
901                 memcpy(arc->buckets + padding_head, old_buckets, arc->bcount * sizeof(EmbedBucket));
902                 
903                 arc->bcount = padding_head + arc->bcount + padding_tail;
904                 
905                 MEM_freeN(old_buckets);
906         }
907         
908         if (padding_head > 0)
909         {
910                 interpolateBuckets(arc, arc->head->p, first_bucket->p, 0, padding_head);
911         }
912         
913         if (padding_tail > 0)
914         {
915                 interpolateBuckets(arc, last_bucket->p, arc->tail->p, arc->bcount - padding_tail, arc->bcount - 1);
916         }
917 }
918
919 /* CALL THIS ONLY AFTER FILTERING, SINCE IT MESSES UP WEIGHT DISTRIBUTION */
920 void extendGraphBuckets(ReebGraph *rg)
921 {
922         ReebArc *arc;
923         
924         for (arc = rg->arcs.first; arc; arc = arc->next)
925         {
926                 ExtendArcBuckets(arc);
927         }
928 }
929
930 /**************************************** LENGTH CALCULATIONS ****************************************/
931
932 void calculateArcLength(ReebArc *arc)
933 {
934         ReebArcIterator arc_iter;
935         BArcIterator *iter = (BArcIterator*)&arc_iter;
936         float *vec0, *vec1;
937
938         arc->length = 0;
939         
940         initArcIterator(iter, arc, arc->head);
941
942         vec0 = arc->head->p;
943         vec1 = arc->head->p; /* in case there's no embedding */
944
945         while (IT_next(iter))   
946         {
947                 vec1 = iter->p;
948                 
949                 arc->length += len_v3v3(vec0, vec1);
950                 
951                 vec0 = vec1;
952         }
953         
954         arc->length += len_v3v3(arc->tail->p, vec1);    
955 }
956
957 void calculateGraphLength(ReebGraph *rg)
958 {
959         ReebArc *arc;
960         
961         for (arc = rg->arcs.first; arc; arc = arc->next)
962         {
963                 calculateArcLength(arc);
964         }
965 }
966
967 /**************************************** SYMMETRY HANDLING ******************************************/
968
969 void REEB_RadialSymmetry(BNode* root_node, RadialArc* ring, int count)
970 {
971         ReebNode *node = (ReebNode*)root_node;
972         float axis[3];
973         int i;
974         
975         VECCOPY(axis, root_node->symmetry_axis);
976         
977         /* first pass, merge incrementally */
978         for (i = 0; i < count - 1; i++)
979         {
980                 ReebNode *node1, *node2;
981                 ReebArc *arc1, *arc2;
982                 float tangent[3];
983                 float normal[3];
984                 int j = i + 1;
985
986                 add_v3_v3v3(tangent, ring[i].n, ring[j].n);
987                 cross_v3_v3v3(normal, tangent, axis);
988                 
989                 node1 = (ReebNode*)BLI_otherNode(ring[i].arc, root_node);
990                 node2 = (ReebNode*)BLI_otherNode(ring[j].arc, root_node);
991                 
992                 arc1 = (ReebArc*)ring[i].arc;
993                 arc2 = (ReebArc*)ring[j].arc;
994
995                 /* mirror first node and mix with the second */
996                 BLI_mirrorAlongAxis(node1->p, root_node->p, normal);
997                 interp_v3_v3v3(node2->p, node2->p, node1->p, 1.0f / (j + 1));
998                 
999                 /* Merge buckets
1000                  * there shouldn't be any null arcs here, but just to be safe 
1001                  * */
1002                 if (arc1->bcount > 0 && arc2->bcount > 0)
1003                 {
1004                         ReebArcIterator arc_iter1, arc_iter2;
1005                         BArcIterator *iter1 = (BArcIterator*)&arc_iter1;
1006                         BArcIterator *iter2 = (BArcIterator*)&arc_iter2;
1007                         EmbedBucket *bucket1 = NULL, *bucket2 = NULL;
1008                         
1009                         initArcIterator(iter1, arc1, (ReebNode*)root_node);
1010                         initArcIterator(iter2, arc2, (ReebNode*)root_node);
1011                         
1012                         bucket1 = IT_next(iter1);
1013                         bucket2 = IT_next(iter2);
1014                 
1015                         /* Make sure they both start at the same value */       
1016                         while(bucket1 && bucket2 && bucket1->val < bucket2->val)
1017                         {
1018                                 bucket1 = IT_next(iter1);
1019                         }
1020                         
1021                         while(bucket1 && bucket2 && bucket2->val < bucket1->val)
1022                         {
1023                                 bucket2 = IT_next(iter2);
1024                         }
1025         
1026         
1027                         for ( ;bucket1 && bucket2; bucket1 = IT_next(iter1), bucket2 = IT_next(iter2))
1028                         {
1029                                 bucket2->nv += bucket1->nv; /* add counts */
1030                                 
1031                                 /* mirror on axis */
1032                                 BLI_mirrorAlongAxis(bucket1->p, root_node->p, normal);
1033                                 /* add bucket2 in bucket1 */
1034                                 interp_v3_v3v3(bucket2->p, bucket2->p, bucket1->p, (float)bucket1->nv / (float)(bucket2->nv));
1035                         }
1036                 }
1037         }
1038         
1039         /* second pass, mirror back on previous arcs */
1040         for (i = count - 1; i > 0; i--)
1041         {
1042                 ReebNode *node1, *node2;
1043                 ReebArc *arc1, *arc2;
1044                 float tangent[3];
1045                 float normal[3];
1046                 int j = i - 1;
1047
1048                 add_v3_v3v3(tangent, ring[i].n, ring[j].n);
1049                 cross_v3_v3v3(normal, tangent, axis);
1050                 
1051                 node1 = (ReebNode*)BLI_otherNode(ring[i].arc, root_node);
1052                 node2 = (ReebNode*)BLI_otherNode(ring[j].arc, root_node);
1053                 
1054                 arc1 = (ReebArc*)ring[i].arc;
1055                 arc2 = (ReebArc*)ring[j].arc;
1056
1057                 /* copy first node than mirror */
1058                 VECCOPY(node2->p, node1->p);
1059                 BLI_mirrorAlongAxis(node2->p, root_node->p, normal);
1060                 
1061                 /* Copy buckets
1062                  * there shouldn't be any null arcs here, but just to be safe 
1063                  * */
1064                 if (arc1->bcount > 0 && arc2->bcount > 0)
1065                 {
1066                         ReebArcIterator arc_iter1, arc_iter2;
1067                         BArcIterator *iter1 = (BArcIterator*)&arc_iter1;
1068                         BArcIterator *iter2 = (BArcIterator*)&arc_iter2;
1069                         EmbedBucket *bucket1 = NULL, *bucket2 = NULL;
1070                         
1071                         initArcIterator(iter1, arc1, node);
1072                         initArcIterator(iter2, arc2, node);
1073                         
1074                         bucket1 = IT_next(iter1);
1075                         bucket2 = IT_next(iter2);
1076                 
1077                         /* Make sure they both start at the same value */       
1078                         while(bucket1 && bucket1->val < bucket2->val)
1079                         {
1080                                 bucket1 = IT_next(iter1);
1081                         }
1082                         
1083                         while(bucket2 && bucket2->val < bucket1->val)
1084                         {
1085                                 bucket2 = IT_next(iter2);
1086                         }
1087         
1088         
1089                         for ( ;bucket1 && bucket2; bucket1 = IT_next(iter1), bucket2 = IT_next(iter2))
1090                         {
1091                                 /* copy and mirror back to bucket2 */                   
1092                                 bucket2->nv = bucket1->nv;
1093                                 VECCOPY(bucket2->p, bucket1->p);
1094                                 BLI_mirrorAlongAxis(bucket2->p, node->p, normal);
1095                         }
1096                 }
1097         }
1098 }
1099
1100 void REEB_AxialSymmetry(BNode* root_node, BNode* node1, BNode* node2, struct BArc* barc1, BArc* barc2)
1101 {
1102         ReebArc *arc1, *arc2;
1103         float nor[3], p[3];
1104
1105         arc1 = (ReebArc*)barc1;
1106         arc2 = (ReebArc*)barc2;
1107
1108         VECCOPY(nor, root_node->symmetry_axis);
1109         
1110         /* mirror node2 along axis */
1111         VECCOPY(p, node2->p);
1112         BLI_mirrorAlongAxis(p, root_node->p, nor);
1113
1114         /* average with node1 */
1115         add_v3_v3v3(node1->p, node1->p, p);
1116         mul_v3_fl(node1->p, 0.5f);
1117         
1118         /* mirror back on node2 */
1119         VECCOPY(node2->p, node1->p);
1120         BLI_mirrorAlongAxis(node2->p, root_node->p, nor);
1121         
1122         /* Merge buckets
1123          * there shouldn't be any null arcs here, but just to be safe 
1124          * */
1125         if (arc1->bcount > 0 && arc2->bcount > 0)
1126         {
1127                 ReebArcIterator arc_iter1, arc_iter2;
1128                 BArcIterator *iter1 = (BArcIterator*)&arc_iter1;
1129                 BArcIterator *iter2 = (BArcIterator*)&arc_iter2;
1130                 EmbedBucket *bucket1 = NULL, *bucket2 = NULL;
1131                 
1132                 initArcIterator(iter1, arc1, (ReebNode*)root_node);
1133                 initArcIterator(iter2, arc2, (ReebNode*)root_node);
1134                 
1135                 bucket1 = IT_next(iter1);
1136                 bucket2 = IT_next(iter2);
1137         
1138                 /* Make sure they both start at the same value */       
1139                 while(bucket1 && bucket1->val < bucket2->val)
1140                 {
1141                         bucket1 = IT_next(iter1);
1142                 }
1143                 
1144                 while(bucket2 && bucket2->val < bucket1->val)
1145                 {
1146                         bucket2 = IT_next(iter2);
1147                 }
1148
1149
1150                 for ( ;bucket1 && bucket2; bucket1 = IT_next(iter1), bucket2 = IT_next(iter2))
1151                 {
1152                         bucket1->nv += bucket2->nv; /* add counts */
1153                         
1154                         /* mirror on axis */
1155                         BLI_mirrorAlongAxis(bucket2->p, root_node->p, nor);
1156                         /* add bucket2 in bucket1 */
1157                         interp_v3_v3v3(bucket1->p, bucket1->p, bucket2->p, (float)bucket2->nv / (float)(bucket1->nv));
1158
1159                         /* copy and mirror back to bucket2 */                   
1160                         bucket2->nv = bucket1->nv;
1161                         VECCOPY(bucket2->p, bucket1->p);
1162                         BLI_mirrorAlongAxis(bucket2->p, root_node->p, nor);
1163                 }
1164         }
1165 }
1166
1167 /************************************** ADJACENCY LIST *************************************************/
1168
1169
1170 /****************************************** SMOOTHING **************************************************/
1171
1172 void postprocessGraph(ReebGraph *rg, char mode)
1173 {
1174         ReebArc *arc;
1175         float fac1 = 0, fac2 = 1, fac3 = 0;
1176
1177         switch(mode)
1178         {
1179         case SKGEN_AVERAGE:
1180                 fac1 = fac2 = fac3 = 1.0f / 3.0f;
1181                 break;
1182         case SKGEN_SMOOTH:
1183                 fac1 = fac3 = 0.25f;
1184                 fac2 = 0.5f;
1185                 break;
1186         case SKGEN_SHARPEN:
1187                 fac1 = fac2 = -0.25f;
1188                 fac2 = 1.5f;
1189                 break;
1190         default:
1191 //              XXX
1192 //              error("Unknown post processing mode");
1193                 return;
1194         }
1195         
1196         for(arc = rg->arcs.first; arc; arc = arc->next)
1197         {
1198                 EmbedBucket *buckets = arc->buckets;
1199                 int bcount = arc->bcount;
1200                 int index;
1201
1202                 for(index = 1; index < bcount - 1; index++)
1203                 {
1204                         interp_v3_v3v3(buckets[index].p, buckets[index].p, buckets[index - 1].p, fac1 / (fac1 + fac2));
1205                         interp_v3_v3v3(buckets[index].p, buckets[index].p, buckets[index + 1].p, fac3 / (fac1 + fac2 + fac3));
1206                 }
1207         }
1208 }
1209
1210 /********************************************SORTING****************************************************/
1211
1212 int compareNodesWeight(void *vnode1, void *vnode2)
1213 {
1214         ReebNode *node1 = (ReebNode*)vnode1;
1215         ReebNode *node2 = (ReebNode*)vnode2;
1216         
1217         if (node1->weight < node2->weight)
1218         {
1219                 return -1;
1220         }
1221         if (node1->weight > node2->weight)
1222         {
1223                 return 1;
1224         }
1225         else
1226         {
1227                 return 0;
1228         }
1229 }
1230
1231 void sortNodes(ReebGraph *rg)
1232 {
1233         BLI_sortlist(&rg->nodes, compareNodesWeight);
1234 }
1235
1236 int compareArcsWeight(void *varc1, void *varc2)
1237 {
1238         ReebArc *arc1 = (ReebArc*)varc1;
1239         ReebArc *arc2 = (ReebArc*)varc2;
1240         ReebNode *node1 = (ReebNode*)arc1->head; 
1241         ReebNode *node2 = (ReebNode*)arc2->head; 
1242         
1243         if (node1->weight < node2->weight)
1244         {
1245                 return -1;
1246         }
1247         if (node1->weight > node2->weight)
1248         {
1249                 return 1;
1250         }
1251         else
1252         {
1253                 return 0;
1254         }
1255 }
1256
1257 void sortArcs(ReebGraph *rg)
1258 {
1259         BLI_sortlist(&rg->arcs, compareArcsWeight);
1260 }
1261 /******************************************* JOINING ***************************************************/
1262
1263 void reweightArc(ReebGraph *rg, ReebArc *arc, ReebNode *start_node, float start_weight)
1264 {
1265         ReebNode *node;
1266         float old_weight;
1267         float end_weight = start_weight + ABS(arc->tail->weight - arc->head->weight);
1268         int i;
1269         
1270         node = (ReebNode*)BLI_otherNode((BArc*)arc, (BNode*)start_node);
1271         
1272         /* prevent backtracking */
1273         if (node->flag == 1)
1274         {
1275                 return;
1276         }
1277
1278         if (arc->tail == start_node)
1279         {
1280                 flipArc(arc);
1281         }
1282         
1283         start_node->flag = 1;
1284         
1285         for (i = 0; i < node->degree; i++)
1286         {
1287                 ReebArc *next_arc = node->arcs[i];
1288                 
1289                 reweightArc(rg, next_arc, node, end_weight);
1290         }
1291
1292         /* update only if needed */     
1293         if (arc->head->weight != start_weight || arc->tail->weight != end_weight)
1294         {
1295                 old_weight = arc->head->weight; /* backup head weight, other arcs need it intact, it will be fixed by the source arc */
1296                 
1297                 arc->head->weight = start_weight;
1298                 arc->tail->weight = end_weight;
1299                 
1300                 reweightBuckets(arc);
1301                 resizeArcBuckets(arc);
1302                 fillArcEmptyBuckets(arc);
1303                 
1304                 arc->head->weight = old_weight;
1305         }
1306
1307
1308 void reweightSubgraph(ReebGraph *rg, ReebNode *start_node, float start_weight)
1309 {
1310         int i;
1311                 
1312         BLI_flagNodes((BGraph*)rg, 0);
1313
1314         for (i = 0; i < start_node->degree; i++)
1315         {
1316                 ReebArc *next_arc = start_node->arcs[i];
1317                 
1318                 reweightArc(rg, next_arc, start_node, start_weight);
1319         }
1320         start_node->weight = start_weight;
1321 }
1322
1323 int joinSubgraphsEnds(ReebGraph *rg, float threshold, int nb_subgraphs)
1324 {
1325         int joined = 0;
1326         int subgraph;
1327         
1328         for (subgraph = 1; subgraph <= nb_subgraphs; subgraph++)
1329         {
1330                 ReebNode *start_node, *end_node;
1331                 ReebNode *min_node_start = NULL, *min_node_end = NULL;
1332                 float min_distance = FLT_MAX;
1333                 
1334                 for (start_node = rg->nodes.first; start_node; start_node = start_node->next)
1335                 {
1336                         if (start_node->subgraph_index == subgraph && start_node->degree == 1)
1337                         {
1338                                 
1339                                 for (end_node = rg->nodes.first; end_node; end_node = end_node->next)
1340                                 {
1341                                         if (end_node->subgraph_index != subgraph)
1342                                         {
1343                                                 float distance = len_v3v3(start_node->p, end_node->p);
1344                                                 
1345                                                 if (distance < threshold && distance < min_distance)
1346                                                 {
1347                                                         min_distance = distance;
1348                                                         min_node_end = end_node;
1349                                                         min_node_start = start_node;
1350                                                 }
1351                                         }
1352                                 }
1353                         }
1354                 }
1355                 
1356                 end_node = min_node_end;
1357                 start_node = min_node_start;
1358                 
1359                 if (end_node && start_node)
1360                 {
1361                         ReebArc *start_arc, *end_arc;
1362                         int merging = 0;
1363                         
1364                         start_arc = start_node->arcs[0];
1365                         end_arc = end_node->arcs[0];
1366                         
1367                         if (start_arc->tail == start_node)
1368                         {
1369                                 reweightSubgraph(rg, end_node, start_node->weight);
1370                                 
1371                                 start_arc->tail = end_node;
1372                                 
1373                                 merging = 1;
1374                         }
1375                         else if (start_arc->head == start_node)
1376                         {
1377                                 reweightSubgraph(rg, start_node, end_node->weight);
1378
1379                                 start_arc->head = end_node;
1380
1381                                 merging = 2;
1382                         }
1383                         
1384                         if (merging)
1385                         {
1386                                 BLI_ReflagSubgraph((BGraph*)rg, end_node->flag, subgraph);
1387                                                                         
1388                                 resizeArcBuckets(start_arc);
1389                                 fillArcEmptyBuckets(start_arc);
1390                                 
1391                                 NodeDegreeIncrement(rg, end_node);
1392                                 BLI_rebuildAdjacencyListForNode((BGraph*)rg, (BNode*)end_node);
1393                                 
1394                                 BLI_removeNode((BGraph*)rg, (BNode*)start_node);
1395                         }
1396                         
1397                         joined = 1;
1398                 }               
1399         }
1400         
1401         return joined;
1402 }
1403
1404 /* Reweight graph from smallest node, fix fliped arcs */
1405 void fixSubgraphsOrientation(ReebGraph *rg, int nb_subgraphs)
1406 {
1407         int subgraph;
1408         
1409         for (subgraph = 1; subgraph <= nb_subgraphs; subgraph++)
1410         {
1411                 ReebNode *node;
1412                 ReebNode *start_node = NULL;
1413                 
1414                 for (node = rg->nodes.first; node; node = node->next)
1415                 {
1416                         if (node->subgraph_index == subgraph)
1417                         {
1418                                 if (start_node == NULL || node->weight < start_node->weight)
1419                                 {
1420                                         start_node = node;
1421                                 }
1422                         }
1423                 }
1424                 
1425                 if (start_node)
1426                 {
1427                         reweightSubgraph(rg, start_node, start_node->weight);
1428                 }
1429         }
1430 }
1431
1432 int joinSubgraphs(ReebGraph *rg, float threshold)
1433 {
1434         int nb_subgraphs;
1435         int joined = 0;
1436         
1437         BLI_buildAdjacencyList((BGraph*)rg);
1438         
1439         if (BLI_isGraphCyclic((BGraph*)rg))
1440         {
1441                 /* don't deal with cyclic graphs YET */
1442                 return 0;
1443         }
1444         
1445         /* sort nodes before flagging subgraphs to make sure root node is subgraph 0 */
1446         sortNodes(rg);
1447         
1448         nb_subgraphs = BLI_FlagSubgraphs((BGraph*)rg);
1449         
1450         /* Harmonic function can create flipped arcs, take the occasion to fix them */
1451 //      XXX
1452 //      if (G.scene->toolsettings->skgen_options & SKGEN_HARMONIC)
1453 //      {
1454                 fixSubgraphsOrientation(rg, nb_subgraphs);
1455 //      }
1456
1457         if (nb_subgraphs > 1)
1458         {
1459                 joined |= joinSubgraphsEnds(rg, threshold, nb_subgraphs);
1460                 
1461                 if (joined)
1462                 {
1463                         removeNormalNodes(rg);
1464                         BLI_buildAdjacencyList((BGraph*)rg);
1465                 }
1466         }
1467         
1468         return joined;
1469 }
1470
1471 /****************************************** FILTERING **************************************************/
1472
1473 float lengthArc(ReebArc *arc)
1474 {
1475 #if 0
1476         ReebNode *head = (ReebNode*)arc->head;
1477         ReebNode *tail = (ReebNode*)arc->tail;
1478         
1479         return tail->weight - head->weight;
1480 #else
1481         return arc->length;
1482 #endif
1483 }
1484
1485 int compareArcs(void *varc1, void *varc2)
1486 {
1487         ReebArc *arc1 = (ReebArc*)varc1;
1488         ReebArc *arc2 = (ReebArc*)varc2;
1489         float len1 = lengthArc(arc1);
1490         float len2 = lengthArc(arc2);
1491         
1492         if (len1 < len2)
1493         {
1494                 return -1;
1495         }
1496         if (len1 > len2)
1497         {
1498                 return 1;
1499         }
1500         else
1501         {
1502                 return 0;
1503         }
1504 }
1505
1506 void filterArc(ReebGraph *rg, ReebNode *newNode, ReebNode *removedNode, ReebArc * srcArc, int merging)
1507 {
1508         ReebArc *arc = NULL, *nextArc = NULL;
1509
1510         if (merging)
1511         {
1512                 /* first pass, merge buckets for arcs that spawned the two nodes into the source arc*/
1513                 for(arc = rg->arcs.first; arc; arc = arc->next)
1514                 {
1515                         if (arc->head == srcArc->head && arc->tail == srcArc->tail && arc != srcArc)
1516                         {
1517                                 ReebNode *head = srcArc->head;
1518                                 ReebNode *tail = srcArc->tail;
1519                                 mergeArcBuckets(srcArc, arc, head->weight, tail->weight);
1520                         }
1521                 }
1522         }
1523
1524         /* second pass, replace removedNode by newNode, remove arcs that are collapsed in a loop */
1525         arc = rg->arcs.first;
1526         while(arc)
1527         {
1528                 nextArc = arc->next;
1529                 
1530                 if (arc->head == removedNode || arc->tail == removedNode)
1531                 {
1532                         if (arc->head == removedNode)
1533                         {
1534                                 arc->head = newNode;
1535                         }
1536                         else
1537                         {
1538                                 arc->tail = newNode;
1539                         }
1540
1541                         // Remove looped arcs                   
1542                         if (arc->head == arc->tail)
1543                         {
1544                                 // v1 or v2 was already newNode, since we're removing an arc, decrement degree
1545                                 NodeDegreeDecrement(rg, newNode);
1546                                 
1547                                 // If it's srcArc, it'll be removed later, so keep it for now
1548                                 if (arc != srcArc)
1549                                 {
1550                                         BLI_remlink(&rg->arcs, arc);
1551                                         REEB_freeArc((BArc*)arc);
1552                                 }
1553                         }
1554                         else
1555                         {
1556                                 /* flip arcs that flipped, can happen on diamond shapes, mostly on null arcs */
1557                                 if (arc->head->weight > arc->tail->weight)
1558                                 {
1559                                         flipArc(arc);
1560                                 }
1561                                 //newNode->degree++; // incrementing degree since we're adding an arc
1562                                 NodeDegreeIncrement(rg, newNode);
1563                                 mergeArcFaces(rg, arc, srcArc);
1564
1565                                 if (merging)
1566                                 {
1567                                         ReebNode *head = arc->head;
1568                                         ReebNode *tail = arc->tail;
1569
1570                                         // resize bucket list
1571                                         resizeArcBuckets(arc);
1572                                         mergeArcBuckets(arc, srcArc, head->weight, tail->weight);
1573                                         
1574                                         /* update length */
1575                                         arc->length += srcArc->length;
1576                                 }
1577                         }
1578                 }
1579                 
1580                 arc = nextArc;
1581         }
1582 }
1583
1584 void filterNullReebGraph(ReebGraph *rg)
1585 {
1586         ReebArc *arc = NULL, *nextArc = NULL;
1587         
1588         arc = rg->arcs.first;
1589         while(arc)
1590         {
1591                 nextArc = arc->next;
1592                 // Only collapse arcs too short to have any embed bucket
1593                 if (arc->bcount == 0)
1594                 {
1595                         ReebNode *newNode = (ReebNode*)arc->head;
1596                         ReebNode *removedNode = (ReebNode*)arc->tail;
1597                         float blend;
1598                         
1599                         blend = (float)newNode->degree / (float)(newNode->degree + removedNode->degree); // blending factors
1600                         
1601                         interp_v3_v3v3(newNode->p, removedNode->p, newNode->p, blend);
1602                         
1603                         filterArc(rg, newNode, removedNode, arc, 0);
1604
1605                         // Reset nextArc, it might have changed
1606                         nextArc = arc->next;
1607                         
1608                         BLI_remlink(&rg->arcs, arc);
1609                         REEB_freeArc((BArc*)arc);
1610                         
1611                         BLI_removeNode((BGraph*)rg, (BNode*)removedNode);
1612                 }
1613                 
1614                 arc = nextArc;
1615         }
1616 }
1617
1618 int filterInternalExternalReebGraph(ReebGraph *rg, float threshold_internal, float threshold_external)
1619 {
1620         ReebArc *arc = NULL, *nextArc = NULL;
1621         int value = 0;
1622         
1623         BLI_sortlist(&rg->arcs, compareArcs);
1624         
1625         for (arc = rg->arcs.first; arc; arc = nextArc)
1626         {
1627                 nextArc = arc->next;
1628
1629                 // Only collapse non-terminal arcs that are shorter than threshold
1630                 if (threshold_internal > 0 && arc->head->degree > 1 && arc->tail->degree > 1 && (lengthArc(arc) < threshold_internal))
1631                 {
1632                         ReebNode *newNode = NULL;
1633                         ReebNode *removedNode = NULL;
1634                         
1635                         /* Always remove lower node, so arcs don't flip */
1636                         newNode = arc->head;
1637                         removedNode = arc->tail;
1638
1639                         filterArc(rg, newNode, removedNode, arc, 1);
1640
1641                         // Reset nextArc, it might have changed
1642                         nextArc = arc->next;
1643                         
1644                         BLI_remlink(&rg->arcs, arc);
1645                         REEB_freeArc((BArc*)arc);
1646                         
1647                         BLI_removeNode((BGraph*)rg, (BNode*)removedNode);
1648                         value = 1;
1649                 }
1650                 
1651                 // Only collapse terminal arcs that are shorter than threshold
1652                 else if (threshold_external > 0 && (arc->head->degree == 1 || arc->tail->degree == 1) && (lengthArc(arc) < threshold_external))
1653                 {
1654                         ReebNode *terminalNode = NULL;
1655                         ReebNode *middleNode = NULL;
1656                         ReebNode *removedNode = NULL;
1657                         
1658                         // Assign terminal and middle nodes
1659                         if (arc->head->degree == 1)
1660                         {
1661                                 terminalNode = arc->head;
1662                                 middleNode = arc->tail;
1663                         }
1664                         else
1665                         {
1666                                 terminalNode = arc->tail;
1667                                 middleNode = arc->head;
1668                         }
1669                         
1670                         if (middleNode->degree == 2 && middleNode != rg->nodes.first)
1671                         {
1672 #if 1
1673                                 // If middle node is a normal node, it will be removed later
1674                                 // Only if middle node is not the root node
1675                                 /* USE THIS IF YOU WANT TO PROLONG ARCS TO THEIR TERMINAL NODES
1676                                  * FOR HANDS, THIS IS NOT THE BEST RESULT 
1677                                  * */
1678                                 continue;
1679 #else
1680                                 removedNode = terminalNode;
1681
1682                                 // removing arc, so we need to decrease the degree of the remaining node
1683                                 NodeDegreeDecrement(rg, middleNode);
1684 #endif
1685                         }
1686                         // Otherwise, just plain remove of the arc
1687                         else
1688                         {
1689                                 removedNode = terminalNode;
1690
1691                                 // removing arc, so we need to decrease the degree of the remaining node
1692                                 NodeDegreeDecrement(rg, middleNode);
1693                         }
1694
1695                         // Reset nextArc, it might have changed
1696                         nextArc = arc->next;
1697                         
1698                         BLI_remlink(&rg->arcs, arc);
1699                         REEB_freeArc((BArc*)arc);
1700                         
1701                         BLI_removeNode((BGraph*)rg, (BNode*)removedNode);
1702                         value = 1;
1703                 }
1704         }
1705         
1706         return value;
1707 }
1708
1709 int filterCyclesReebGraph(ReebGraph *rg, float distance_threshold)
1710 {
1711         ReebArc *arc1, *arc2;
1712         ReebArc *next2;
1713         int filtered = 0;
1714         
1715         for (arc1 = rg->arcs.first; arc1; arc1 = arc1->next)
1716         {
1717                 for (arc2 = arc1->next; arc2; arc2 = next2)
1718                 {
1719                         next2 = arc2->next;
1720                         if (arc1 != arc2 && arc1->head == arc2->head && arc1->tail == arc2->tail)
1721                         {
1722                                 mergeArcEdges(rg, arc1, arc2, MERGE_APPEND);
1723                                 mergeArcFaces(rg, arc1, arc2);
1724                                 mergeArcBuckets(arc1, arc2, arc1->head->weight, arc1->tail->weight);
1725
1726                                 NodeDegreeDecrement(rg, arc1->head);
1727                                 NodeDegreeDecrement(rg, arc1->tail);
1728
1729                                 BLI_remlink(&rg->arcs, arc2);
1730                                 REEB_freeArc((BArc*)arc2);
1731                                 
1732                                 filtered = 1;
1733                         }
1734                 }
1735         }
1736         
1737         return filtered;
1738 }
1739
1740 int filterSmartReebGraph(ReebGraph *rg, float threshold)
1741 {
1742         int value = 0;
1743 #if 0 //XXX
1744         ReebArc *arc = NULL, *nextArc = NULL;
1745         
1746         BLI_sortlist(&rg->arcs, compareArcs);
1747
1748 #ifdef DEBUG_REEB
1749         {       
1750                 EditFace *efa;
1751                 for(efa=G.editMesh->faces.first; efa; efa=efa->next) {
1752                         efa->tmp.fp = -1;
1753                 }
1754         }
1755 #endif
1756
1757         arc = rg->arcs.first;
1758         while(arc)
1759         {
1760                 nextArc = arc->next;
1761                 
1762                 /* need correct normals and center */
1763                 recalc_editnormals();
1764
1765                 // Only test terminal arcs
1766                 if (arc->head->degree == 1 || arc->tail->degree == 1)
1767                 {
1768                         GHashIterator ghi;
1769                         int merging = 0;
1770                         int total = BLI_ghash_size(arc->faces);
1771                         float avg_angle = 0;
1772                         float avg_vec[3] = {0,0,0};
1773                         
1774                         for(BLI_ghashIterator_init(&ghi, arc->faces);
1775                                 !BLI_ghashIterator_isDone(&ghi);
1776                                 BLI_ghashIterator_step(&ghi))
1777                         {
1778                                 EditFace *efa = BLI_ghashIterator_getValue(&ghi);
1779
1780 #if 0
1781                                 ReebArcIterator arc_iter;
1782                                 BArcIterator *iter = (BArcIterator*)&arc_iter;
1783                                 EmbedBucket *bucket = NULL;
1784                                 EmbedBucket *previous = NULL;
1785                                 float min_distance = -1;
1786                                 float angle = 0;
1787                 
1788                                 initArcIterator(iter, arc, arc->head);
1789                 
1790                                 bucket = nextBucket(iter);
1791                                 
1792                                 while (bucket != NULL)
1793                                 {
1794                                         float *vec0 = NULL;
1795                                         float *vec1 = bucket->p;
1796                                         float midpoint[3], tangent[3];
1797                                         float distance;
1798                 
1799                                         /* first bucket. Previous is head */
1800                                         if (previous == NULL)
1801                                         {
1802                                                 vec0 = arc->head->p;
1803                                         }
1804                                         /* Previous is a valid bucket */
1805                                         else
1806                                         {
1807                                                 vec0 = previous->p;
1808                                         }
1809                                         
1810                                         VECCOPY(midpoint, vec1);
1811                                         
1812                                         distance = len_v3v3(midpoint, efa->cent);
1813                                         
1814                                         if (min_distance == -1 || distance < min_distance)
1815                                         {
1816                                                 min_distance = distance;
1817                                         
1818                                                 sub_v3_v3v3(tangent, vec1, vec0);
1819                                                 normalize_v3(tangent);
1820                                                 
1821                                                 angle = dot_v3v3(tangent, efa->n);
1822                                         }
1823                                         
1824                                         previous = bucket;
1825                                         bucket = nextBucket(iter);
1826                                 }
1827                                 
1828                                 avg_angle += saacos(fabs(angle));
1829 #ifdef DEBUG_REEB
1830                                 efa->tmp.fp = saacos(fabs(angle));
1831 #endif
1832 #else
1833                                 add_v3_v3v3(avg_vec, avg_vec, efa->n);          
1834 #endif
1835                         }
1836
1837
1838 #if 0                   
1839                         avg_angle /= total;
1840 #else
1841                         mul_v3_fl(avg_vec, 1.0 / total);
1842                         avg_angle = dot_v3v3(avg_vec, avg_vec);
1843 #endif
1844                         
1845                         arc->angle = avg_angle;
1846                         
1847                         if (avg_angle > threshold)
1848                                 merging = 1;
1849                         
1850                         if (merging)
1851                         {
1852                                 ReebNode *terminalNode = NULL;
1853                                 ReebNode *middleNode = NULL;
1854                                 ReebNode *newNode = NULL;
1855                                 ReebNode *removedNode = NULL;
1856                                 int merging = 0;
1857                                 
1858                                 // Assign terminal and middle nodes
1859                                 if (arc->head->degree == 1)
1860                                 {
1861                                         terminalNode = arc->head;
1862                                         middleNode = arc->tail;
1863                                 }
1864                                 else
1865                                 {
1866                                         terminalNode = arc->tail;
1867                                         middleNode = arc->head;
1868                                 }
1869                                 
1870                                 // If middle node is a normal node, merge to terminal node
1871                                 if (middleNode->degree == 2)
1872                                 {
1873                                         merging = 1;
1874                                         newNode = terminalNode;
1875                                         removedNode = middleNode;
1876                                 }
1877                                 // Otherwise, just plain remove of the arc
1878                                 else
1879                                 {
1880                                         merging = 0;
1881                                         newNode = middleNode;
1882                                         removedNode = terminalNode;
1883                                 }
1884                                 
1885                                 // Merging arc
1886                                 if (merging)
1887                                 {
1888                                         filterArc(rg, newNode, removedNode, arc, 1);
1889                                 }
1890                                 else
1891                                 {
1892                                         // removing arc, so we need to decrease the degree of the remaining node
1893                                         //newNode->degree--;
1894                                         NodeDegreeDecrement(rg, newNode);
1895                                 }
1896         
1897                                 // Reset nextArc, it might have changed
1898                                 nextArc = arc->next;
1899                                 
1900                                 BLI_remlink(&rg->arcs, arc);
1901                                 REEB_freeArc((BArc*)arc);
1902                                 
1903                                 BLI_freelinkN(&rg->nodes, removedNode);
1904                                 value = 1;
1905                         }
1906                 }
1907                 
1908                 arc = nextArc;
1909         }
1910         
1911         #endif
1912         
1913         return value;
1914 }
1915
1916 void filterGraph(ReebGraph *rg, short options, float threshold_internal, float threshold_external)
1917 {
1918         int done = 1;
1919         
1920         calculateGraphLength(rg);
1921
1922         if ((options & SKGEN_FILTER_EXTERNAL) == 0)
1923         {
1924                 threshold_external = 0;
1925         }
1926
1927         if ((options & SKGEN_FILTER_INTERNAL) == 0)
1928         {
1929                 threshold_internal = 0;
1930         }
1931
1932         if (threshold_internal > 0 || threshold_external > 0)
1933         { 
1934                 /* filter until there's nothing more to do */
1935                 while (done == 1)
1936                 {
1937                         done = 0; /* no work done yet */
1938                         
1939                         done = filterInternalExternalReebGraph(rg, threshold_internal, threshold_external);
1940                 }
1941         }
1942
1943         if (options & SKGEN_FILTER_SMART)
1944         {
1945                 filterSmartReebGraph(rg, 0.5);
1946                 filterCyclesReebGraph(rg, 0.5);
1947         }
1948
1949         repositionNodes(rg);
1950
1951         /* Filtering might have created degree 2 nodes, so remove them */
1952         removeNormalNodes(rg);
1953 }
1954
1955 void finalizeGraph(ReebGraph *rg, char passes, char method)
1956 {
1957         int i;
1958         
1959         BLI_buildAdjacencyList((BGraph*)rg);
1960
1961         sortNodes(rg);
1962         
1963         sortArcs(rg);
1964         
1965         for(i = 0; i <  passes; i++)
1966         {
1967                 postprocessGraph(rg, method);
1968         }
1969         
1970         extendGraphBuckets(rg);
1971 }
1972
1973 /************************************** WEIGHT SPREADING ***********************************************/
1974
1975 int compareVerts( const void* a, const void* b )
1976 {
1977         EditVert *va = *(EditVert**)a;
1978         EditVert *vb = *(EditVert**)b;
1979         int value = 0;
1980         
1981         if (weightData(va) < weightData(vb))
1982         {
1983                 value = -1;
1984         }
1985         else if (weightData(va) > weightData(vb))
1986         {
1987                 value = 1;
1988         }
1989
1990         return value;           
1991 }
1992
1993 void spreadWeight(EditMesh *em)
1994 {
1995         EditVert **verts, *eve;
1996         float lastWeight = 0.0f;
1997         int totvert = BLI_countlist(&em->verts);
1998         int i;
1999         int work_needed = 1;
2000         
2001         verts = MEM_callocN(sizeof(EditVert*) * totvert, "verts array");
2002         
2003         for(eve = em->verts.first, i = 0; eve; eve = eve->next, i++)
2004         {
2005                 verts[i] = eve;
2006         }
2007         
2008         while(work_needed == 1)
2009         {
2010                 work_needed = 0;
2011                 qsort(verts, totvert, sizeof(EditVert*), compareVerts);
2012                 
2013                 for(i = 0; i < totvert; i++)
2014                 {
2015                         eve = verts[i];
2016                         
2017                         if (i == 0 || (weightData(eve) - lastWeight) > FLT_EPSILON)
2018                         {
2019                                 lastWeight = weightData(eve);
2020                         }
2021                         else
2022                         {
2023                                 work_needed = 1;
2024                                 weightSetData(eve, lastWeight + FLT_EPSILON * 2);
2025                                 lastWeight = weightData(eve);
2026                         }
2027                 }
2028         }
2029         
2030         MEM_freeN(verts);
2031 }
2032
2033 /******************************************** EXPORT ***************************************************/
2034
2035 void exportNode(FILE *f, char *text, ReebNode *node)
2036 {
2037         fprintf(f, "%s i:%i w:%f d:%i %f %f %f\n", text, node->index, node->weight, node->degree, node->p[0], node->p[1], node->p[2]);
2038 }
2039
2040 void REEB_exportGraph(ReebGraph *rg, int count)
2041 {
2042         ReebArc *arc;
2043         char filename[128];
2044         FILE *f;
2045         
2046         if (count == -1)
2047         {
2048                 sprintf(filename, "test.txt");
2049         }
2050         else
2051         {
2052                 sprintf(filename, "test%05i.txt", count);
2053         }
2054         f = fopen(filename, "w");
2055
2056         for(arc = rg->arcs.first; arc; arc = arc->next)
2057         {
2058                 int i;
2059                 float p[3];
2060                 
2061                 exportNode(f, "v1", arc->head);
2062                 
2063                 for(i = 0; i < arc->bcount; i++)
2064                 {
2065                         fprintf(f, "b nv:%i %f %f %f\n", arc->buckets[i].nv, arc->buckets[i].p[0], arc->buckets[i].p[1], arc->buckets[i].p[2]);
2066                 }
2067                 
2068                 add_v3_v3v3(p, arc->tail->p, arc->head->p);
2069                 mul_v3_fl(p, 0.5f);
2070                 
2071                 fprintf(f, "angle %0.3f %0.3f %0.3f %0.3f %i\n", p[0], p[1], p[2], arc->angle, BLI_ghash_size(arc->faces));
2072                 exportNode(f, "v2", arc->tail);
2073         }       
2074         
2075         fclose(f);
2076 }
2077
2078 /***************************************** MAIN ALGORITHM **********************************************/
2079
2080 /* edges alone will create zero degree nodes, use this function to remove them */
2081 void removeZeroNodes(ReebGraph *rg)
2082 {
2083         ReebNode *node, *next_node;
2084         
2085         for (node = rg->nodes.first; node; node = next_node)
2086         {
2087                 next_node = node->next;
2088                 
2089                 if (node->degree == 0)
2090                 {
2091                         BLI_removeNode((BGraph*)rg, (BNode*)node);
2092                 }
2093         }
2094 }
2095
2096 void removeNormalNodes(ReebGraph *rg)
2097 {
2098         ReebArc *arc, *nextArc;
2099         
2100         // Merge degree 2 nodes
2101         for(arc = rg->arcs.first; arc; arc = nextArc)
2102         {
2103                 nextArc = arc->next;
2104                 
2105                 while (arc->head->degree == 2 || arc->tail->degree == 2)
2106                 {
2107                         // merge at v1
2108                         if (arc->head->degree == 2)
2109                         {
2110                                 ReebArc *connectedArc = (ReebArc*)BLI_findConnectedArc((BGraph*)rg, (BArc*)arc, (BNode*)arc->head);
2111
2112                                 /* If arcs are one after the other */
2113                                 if (arc->head == connectedArc->tail)
2114                                 {               
2115                                         /* remove furthest arc */               
2116                                         if (arc->tail->weight < connectedArc->head->weight)
2117                                         {
2118                                                 mergeConnectedArcs(rg, arc, connectedArc);
2119                                                 nextArc = arc->next;
2120                                         }
2121                                         else
2122                                         {
2123                                                 mergeConnectedArcs(rg, connectedArc, arc);
2124                                                 break; /* arc was removed, move to next */
2125                                         }
2126                                 }
2127                                 /* Otherwise, arcs are side by side */
2128                                 else
2129                                 {
2130                                         /* Don't do anything, we need to keep the lowest node, even if degree 2 */
2131                                         break;
2132                                 }
2133                         }
2134                         
2135                         // merge at v2
2136                         if (arc->tail->degree == 2)
2137                         {
2138                                 ReebArc *connectedArc = (ReebArc*)BLI_findConnectedArc((BGraph*)rg, (BArc*)arc, (BNode*)arc->tail);
2139                                 
2140                                 /* If arcs are one after the other */
2141                                 if (arc->tail == connectedArc->head)
2142                                 {                               
2143                                         /* remove furthest arc */               
2144                                         if (arc->head->weight < connectedArc->tail->weight)
2145                                         {
2146                                                 mergeConnectedArcs(rg, arc, connectedArc);
2147                                                 nextArc = arc->next;
2148                                         }
2149                                         else
2150                                         {
2151                                                 mergeConnectedArcs(rg, connectedArc, arc);
2152                                                 break; /* arc was removed, move to next */
2153                                         }
2154                                 }
2155                                 /* Otherwise, arcs are side by side */
2156                                 else
2157                                 {
2158                                         /* Don't do anything, we need to keep the lowest node, even if degree 2 */
2159                                         break;
2160                                 }
2161                         }
2162                 }
2163         }
2164         
2165 }
2166
2167 int edgeEquals(ReebEdge *e1, ReebEdge *e2)
2168 {
2169         return (e1->v1 == e2->v1 && e1->v2 == e2->v2);
2170 }
2171
2172 ReebArc *nextArcMappedToEdge(ReebArc *arc, ReebEdge *e)
2173 {
2174         ReebEdge *nextEdge = NULL;
2175         ReebEdge *edge = NULL;
2176         ReebArc *result = NULL;
2177
2178         /* Find the ReebEdge in the edge list */
2179         for(edge = arc->edges.first; edge && !edgeEquals(edge, e); edge = edge->next)
2180         {       }
2181         
2182         nextEdge = edge->nextEdge;
2183         
2184         if (nextEdge != NULL)
2185         {
2186                 result = nextEdge->arc;
2187         }
2188
2189         return result;
2190 }
2191
2192 void addFacetoArc(ReebArc *arc, EditFace *efa)
2193 {
2194         BLI_ghash_insert(arc->faces, efa, efa);
2195 }
2196
2197 void mergeArcFaces(ReebGraph *rg, ReebArc *aDst, ReebArc *aSrc)
2198 {
2199         GHashIterator ghi;
2200         
2201         for(BLI_ghashIterator_init(&ghi, aSrc->faces);
2202                 !BLI_ghashIterator_isDone(&ghi);
2203                 BLI_ghashIterator_step(&ghi))
2204         {
2205                 EditFace *efa = BLI_ghashIterator_getValue(&ghi);
2206                 BLI_ghash_insert(aDst->faces, efa, efa);
2207         }
2208
2209
2210 void mergeArcEdges(ReebGraph *rg, ReebArc *aDst, ReebArc *aSrc, MergeDirection direction)
2211 {
2212         ReebEdge *e = NULL;
2213         
2214         if (direction == MERGE_APPEND)
2215         {
2216                 for(e = aSrc->edges.first; e; e = e->next)
2217                 {
2218                         e->arc = aDst; // Edge is stolen by new arc
2219                 }
2220                 
2221                 addlisttolist(&aDst->edges , &aSrc->edges);
2222         }
2223         else
2224         {
2225                 for(e = aSrc->edges.first; e; e = e->next)
2226                 {
2227                         ReebEdge *newEdge = copyEdge(e);
2228
2229                         newEdge->arc = aDst;
2230                         
2231                         BLI_addtail(&aDst->edges, newEdge);
2232                         
2233                         if (direction == MERGE_LOWER)
2234                         {
2235                                 void **p = BLI_edgehash_lookup_p(rg->emap, e->v1->index, e->v2->index);
2236                                 
2237                                 newEdge->nextEdge = e;
2238
2239                                 // if edge was the first in the list, point the edit edge to the new reeb edge instead.                                                 
2240                                 if (*p == e)
2241                                 {
2242                                         *p = (void*)newEdge;
2243                                 }
2244                                 // otherwise, advance in the list until the predecessor is found then insert it there
2245                                 else
2246                                 {
2247                                         ReebEdge *previous = (ReebEdge*)*p;
2248                                         
2249                                         while(previous->nextEdge != e)
2250                                         {
2251                                                 previous = previous->nextEdge;
2252                                         }
2253                                         
2254                                         previous->nextEdge = newEdge;
2255                                 }
2256                         }
2257                         else
2258                         {
2259                                 newEdge->nextEdge = e->nextEdge;
2260                                 e->nextEdge = newEdge;
2261                         }
2262                 }
2263         }
2264
2265
2266 // return 1 on full merge
2267 int mergeConnectedArcs(ReebGraph *rg, ReebArc *a0, ReebArc *a1)
2268 {
2269         int result = 0;
2270         ReebNode *removedNode = NULL;
2271         
2272         a0->length += a1->length;
2273         
2274         mergeArcEdges(rg, a0, a1, MERGE_APPEND);
2275         mergeArcFaces(rg, a0, a1);
2276         
2277         // Bring a0 to the combine length of both arcs
2278         if (a0->tail == a1->head)
2279         {
2280                 removedNode = a0->tail;
2281                 a0->tail = a1->tail;
2282         }
2283         else if (a0->head == a1->tail)
2284         {
2285                 removedNode = a0->head;
2286                 a0->head = a1->head;
2287         }
2288         
2289         resizeArcBuckets(a0);
2290         // Merge a1 in a0
2291         mergeArcBuckets(a0, a1, a0->head->weight, a0->tail->weight);
2292         
2293         // remove a1 from graph
2294         BLI_remlink(&rg->arcs, a1);
2295         REEB_freeArc((BArc*)a1);
2296         
2297         BLI_removeNode((BGraph*)rg, (BNode*)removedNode);
2298         result = 1;
2299         
2300         return result;
2301 }
2302 // return 1 on full merge
2303 int mergeArcs(ReebGraph *rg, ReebArc *a0, ReebArc *a1)
2304 {
2305         int result = 0;
2306         // TRIANGLE POINTS DOWN
2307         if (a0->head->weight == a1->head->weight) // heads are the same
2308         {
2309                 if (a0->tail->weight == a1->tail->weight) // tails also the same, arcs can be totally merge together
2310                 {
2311                         mergeArcEdges(rg, a0, a1, MERGE_APPEND);
2312                         mergeArcFaces(rg, a0, a1);
2313                         
2314                         mergeArcBuckets(a0, a1, a0->head->weight, a0->tail->weight);
2315                         
2316                         // Adjust node degree
2317                         //a1->head->degree--;
2318                         NodeDegreeDecrement(rg, a1->head);
2319                         //a1->tail->degree--;
2320                         NodeDegreeDecrement(rg, a1->tail);
2321                         
2322                         // remove a1 from graph
2323                         BLI_remlink(&rg->arcs, a1);
2324                         
2325                         REEB_freeArc((BArc*)a1);
2326                         result = 1;
2327                 }
2328                 else if (a0->tail->weight > a1->tail->weight) // a1->tail->weight is in the middle
2329                 {
2330                         mergeArcEdges(rg, a1, a0, MERGE_LOWER);
2331                         mergeArcFaces(rg, a1, a0);
2332
2333                         // Adjust node degree
2334                         //a0->head->degree--;
2335                         NodeDegreeDecrement(rg, a0->head);
2336                         //a1->tail->degree++;
2337                         NodeDegreeIncrement(rg, a1->tail);
2338                         
2339                         mergeArcBuckets(a1, a0, a1->head->weight, a1->tail->weight);
2340                         a0->head = a1->tail;
2341                         resizeArcBuckets(a0);
2342                 }
2343                 else // a0>n2 is in the middle
2344                 {
2345                         mergeArcEdges(rg, a0, a1, MERGE_LOWER);
2346                         mergeArcFaces(rg, a0, a1);
2347                         
2348                         // Adjust node degree
2349                         //a1->head->degree--;
2350                         NodeDegreeDecrement(rg, a1->head);
2351                         //a0->tail->degree++;
2352                         NodeDegreeIncrement(rg, a0->tail);
2353                         
2354                         mergeArcBuckets(a0, a1, a0->head->weight, a0->tail->weight);
2355                         a1->head = a0->tail;
2356                         resizeArcBuckets(a1);
2357                 }
2358         }
2359         // TRIANGLE POINTS UP
2360         else if (a0->tail->weight == a1->tail->weight) // tails are the same
2361         {
2362                 if (a0->head->weight > a1->head->weight) // a0->head->weight is in the middle
2363                 {
2364                         mergeArcEdges(rg, a0, a1, MERGE_HIGHER);
2365                         mergeArcFaces(rg, a0, a1);
2366                         
2367                         // Adjust node degree
2368                         //a1->tail->degree--;
2369                         NodeDegreeDecrement(rg, a1->tail);
2370                         //a0->head->degree++;
2371                         NodeDegreeIncrement(rg, a0->head);
2372                         
2373                         mergeArcBuckets(a0, a1, a0->head->weight, a0->tail->weight);
2374                         a1->tail = a0->head;
2375                         resizeArcBuckets(a1);
2376                 }
2377                 else // a1->head->weight is in the middle
2378                 {
2379                         mergeArcEdges(rg, a1, a0, MERGE_HIGHER);
2380                         mergeArcFaces(rg, a1, a0);
2381
2382                         // Adjust node degree
2383                         //a0->tail->degree--;
2384                         NodeDegreeDecrement(rg, a0->tail);
2385                         //a1->head->degree++;
2386                         NodeDegreeIncrement(rg, a1->head);
2387
2388                         mergeArcBuckets(a1, a0, a1->head->weight, a1->tail->weight);
2389                         a0->tail = a1->head;
2390                         resizeArcBuckets(a0);
2391                 }
2392         }
2393         else
2394         {
2395                 // Need something here (OR NOT)
2396         }
2397         
2398         return result;
2399 }
2400
2401 void glueByMergeSort(ReebGraph *rg, ReebArc *a0, ReebArc *a1, ReebEdge *e0, ReebEdge *e1)
2402 {
2403         int total = 0;
2404         while (total == 0 && a0 != a1 && a0 != NULL && a1 != NULL)
2405         {
2406                 total = mergeArcs(rg, a0, a1);
2407                 
2408                 if (total == 0) // if it wasn't a total merge, go forward
2409                 {
2410                         if (a0->tail->weight < a1->tail->weight)
2411                         {
2412                                 a0 = nextArcMappedToEdge(a0, e0);
2413                         }
2414                         else
2415                         {
2416                                 a1 = nextArcMappedToEdge(a1, e1);
2417                         }
2418                 }
2419         }
2420 }
2421
2422 void mergePaths(ReebGraph *rg, ReebEdge *e0, ReebEdge *e1, ReebEdge *e2)
2423 {
2424         ReebArc *a0, *a1, *a2;
2425         a0 = e0->arc;
2426         a1 = e1->arc;
2427         a2 = e2->arc;
2428         
2429         glueByMergeSort(rg, a0, a1, e0, e1);
2430         glueByMergeSort(rg, a0, a2, e0, e2);
2431
2432
2433 ReebEdge * createArc(ReebGraph *rg, ReebNode *node1, ReebNode *node2)
2434 {
2435         ReebEdge *edge;
2436         
2437         edge = BLI_edgehash_lookup(rg->emap, node1->index, node2->index);
2438         
2439         // Only add existing edges that haven't been added yet
2440         if (edge == NULL)
2441         {
2442                 ReebArc *arc;
2443                 ReebNode *v1, *v2;
2444                 float len, offset;
2445                 int i;
2446                 
2447                 arc = MEM_callocN(sizeof(ReebArc), "reeb arc");
2448                 edge = MEM_callocN(sizeof(ReebEdge), "reeb edge");
2449                 
2450                 arc->flag = 0; // clear flag on init
2451                 arc->symmetry_level = 0;
2452                 arc->faces = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
2453                 
2454                 if (node1->weight <= node2->weight)
2455                 {
2456                         v1 = node1;     
2457                         v2 = node2;     
2458                 }
2459                 else
2460                 {
2461                         v1 = node2;     
2462                         v2 = node1;     
2463                 }
2464                 
2465                 arc->head = v1;
2466                 arc->tail = v2;
2467                 
2468                 // increase node degree
2469                 //v1->degree++;
2470                 NodeDegreeIncrement(rg, v1);
2471                 //v2->degree++;
2472                 NodeDegreeIncrement(rg, v2);
2473
2474                 BLI_edgehash_insert(rg->emap, node1->index, node2->index, edge);
2475                 
2476                 edge->arc = arc;
2477                 edge->nextEdge = NULL;
2478                 edge->v1 = v1;
2479                 edge->v2 = v2;
2480                 
2481                 BLI_addtail(&rg->arcs, arc);
2482                 BLI_addtail(&arc->edges, edge);
2483                 
2484                 /* adding buckets for embedding */
2485                 allocArcBuckets(arc);
2486                 
2487                 offset = arc->head->weight;
2488                 len = arc->tail->weight - arc->head->weight;
2489
2490 #if 0
2491                 /* This is the actual embedding filling described in the paper
2492                  * the problem is that it only works with really dense meshes
2493                  */
2494                 if (arc->bcount > 0)
2495                 {
2496                         addVertToBucket(&(arc->buckets[0]), arc->head->co);
2497                         addVertToBucket(&(arc->buckets[arc->bcount - 1]), arc->tail->co);
2498                 }
2499 #else
2500                 for(i = 0; i < arc->bcount; i++)
2501                 {
2502                         float co[3];
2503                         float f = (arc->buckets[i].val - offset) / len;
2504                         
2505                         interp_v3_v3v3(co, v1->p, v2->p, f);
2506                         addVertToBucket(&(arc->buckets[i]), co);
2507                 }
2508 #endif
2509
2510         }
2511         
2512         return edge;
2513 }
2514
2515 void addTriangleToGraph(ReebGraph *rg, ReebNode * n1, ReebNode * n2, ReebNode * n3, EditFace *efa)
2516 {
2517         ReebEdge *re1, *re2, *re3;
2518         ReebEdge *e1, *e2, *e3;
2519         float len1, len2, len3;
2520         
2521         re1 = createArc(rg, n1, n2);
2522         re2 = createArc(rg, n2, n3);
2523         re3 = createArc(rg, n3, n1);
2524         
2525         addFacetoArc(re1->arc, efa);
2526         addFacetoArc(re2->arc, efa);
2527         addFacetoArc(re3->arc, efa);
2528         
2529         len1 = (float)fabs(n1->weight - n2->weight);
2530         len2 = (float)fabs(n2->weight - n3->weight);
2531         len3 = (float)fabs(n3->weight - n1->weight);
2532         
2533         /* The rest of the algorithm assumes that e1 is the longest edge */
2534         
2535         if (len1 >= len2 && len1 >= len3)
2536         {
2537                 e1 = re1;
2538                 e2 = re2;
2539                 e3 = re3;
2540         }
2541         else if (len2 >= len1 && len2 >= len3)
2542         {
2543                 e1 = re2;
2544                 e2 = re1;
2545                 e3 = re3;
2546         }
2547         else
2548         {
2549                 e1 = re3;
2550                 e2 = re2;
2551                 e3 = re1;
2552         }
2553         
2554         /* And e2 is the lowest edge
2555          * If e3 is lower than e2, swap them
2556          */
2557         if (e3->v1->weight < e2->v1->weight)
2558         {
2559                 ReebEdge *etmp = e2;
2560                 e2 = e3;
2561                 e3 = etmp;
2562         }
2563         
2564         
2565         mergePaths(rg, e1, e2, e3);
2566 }
2567
2568 ReebGraph * generateReebGraph(EditMesh *em, int subdivisions)
2569 {
2570         ReebGraph *rg;
2571         EditVert *eve;
2572         EditFace *efa;
2573         int index;
2574         int totvert;
2575         int totfaces;
2576         
2577 #ifdef DEBUG_REEB
2578         int countfaces = 0;
2579 #endif
2580         
2581         rg = newReebGraph();
2582         
2583         rg->resolution = subdivisions;
2584         
2585         totvert = BLI_countlist(&em->verts);
2586         totfaces = BLI_countlist(&em->faces);
2587         
2588         renormalizeWeight(em, 1.0f);
2589         
2590         /* Spread weight to minimize errors */
2591         spreadWeight(em);
2592
2593         renormalizeWeight(em, (float)rg->resolution);
2594
2595         /* Adding vertice */
2596         for(index = 0, eve = em->verts.first; eve; eve = eve->next)
2597         {
2598                 if (eve->h == 0)
2599                 {
2600                         addNode(rg, eve);
2601                         eve->f2 = 0;
2602                         index++;
2603                 }
2604         }
2605         
2606         /* Adding face, edge per edge */
2607         for(efa = em->faces.first; efa; efa = efa->next)
2608         {
2609                 if (efa->h == 0)
2610                 {
2611                         ReebNode *n1, *n2, *n3;
2612                         
2613                         n1 = nodeData(efa->v1);
2614                         n2 = nodeData(efa->v2);
2615                         n3 = nodeData(efa->v3);
2616                         
2617                         addTriangleToGraph(rg, n1, n2, n3, efa);
2618                         
2619                         if (efa->v4)
2620                         {
2621                                 ReebNode *n4 = nodeData(efa->v4);
2622                                 addTriangleToGraph(rg, n1, n3, n4, efa);
2623                         }
2624 #ifdef DEBUG_REEB
2625                         countfaces++;
2626                         if (countfaces % 100 == 0)
2627                         {
2628                                 printf("\rface %i of %i", countfaces, totfaces);
2629                         }
2630 #endif
2631                 }
2632         }
2633         
2634         printf("\n");
2635         
2636         removeZeroNodes(rg);
2637         
2638         removeNormalNodes(rg);
2639         
2640         return rg;
2641 }
2642
2643 /***************************************** WEIGHT UTILS **********************************************/
2644
2645 void renormalizeWeight(EditMesh *em, float newmax)
2646 {
2647         EditVert *eve;
2648         float minimum, maximum, range;
2649         
2650         if (em == NULL || BLI_countlist(&em->verts) == 0)
2651                 return;
2652
2653         /* First pass, determine maximum and minimum */
2654         eve = em->verts.first;
2655         minimum = weightData(eve);
2656         maximum = minimum;
2657         for(eve = em->verts.first; eve; eve = eve->next)
2658         {
2659                 maximum = MAX2(maximum, weightData(eve));
2660                 minimum = MIN2(minimum, weightData(eve));
2661         }
2662         
2663         range = maximum - minimum;
2664
2665         /* Normalize weights */
2666         for(eve = em->verts.first; eve; eve = eve->next)
2667         {
2668                 float weight = (weightData(eve) - minimum) / range * newmax;
2669                 weightSetData(eve, weight);
2670         }
2671 }
2672
2673
2674 int weightFromLoc(EditMesh *em, int axis)
2675 {
2676         EditVert *eve;
2677         
2678         if (em == NULL || BLI_countlist(&em->verts) == 0 || axis < 0 || axis > 2)
2679                 return 0;
2680
2681         /* Copy coordinate in weight */
2682         for(eve = em->verts.first; eve; eve = eve->next)
2683         {
2684                 weightSetData(eve, eve->co[axis]);
2685         }
2686
2687         return 1;
2688 }
2689
2690 static float cotan_weight(float *v1, float *v2, float *v3)
2691 {
2692         float a[3], b[3], c[3], clen;
2693
2694         sub_v3_v3v3(a, v2, v1);
2695         sub_v3_v3v3(b, v3, v1);
2696         cross_v3_v3v3(c, a, b);
2697
2698         clen = len_v3(c);
2699
2700         if (clen == 0.0f)
2701                 return 0.0f;
2702         
2703         return dot_v3v3(a, b)/clen;
2704 }
2705
2706 void addTriangle(EditVert *v1, EditVert *v2, EditVert *v3, int e1, int e2, int e3)
2707 {
2708         /* Angle opposite e1 */
2709         float t1= cotan_weight(v1->co, v2->co, v3->co) / e2;
2710         
2711         /* Angle opposite e2 */
2712         float t2 = cotan_weight(v2->co, v3->co, v1->co) / e3;
2713
2714         /* Angle opposite e3 */
2715         float t3 = cotan_weight(v3->co, v1->co, v2->co) / e1;
2716         
2717         int i1 = indexData(v1);
2718         int i2 = indexData(v2);
2719         int i3 = indexData(v3);
2720         
2721         nlMatrixAdd(i1, i1, t2+t3);
2722         nlMatrixAdd(i2, i2, t1+t3);
2723         nlMatrixAdd(i3, i3, t1+t2);
2724
2725         nlMatrixAdd(i1, i2, -t3);
2726         nlMatrixAdd(i2, i1, -t3);
2727
2728         nlMatrixAdd(i2, i3, -t1);
2729         nlMatrixAdd(i3, i2, -t1);
2730
2731         nlMatrixAdd(i3, i1, -t2);
2732         nlMatrixAdd(i1, i3, -t2);
2733 }
2734
2735 int weightToHarmonic(EditMesh *em, EdgeIndex *indexed_edges)
2736 {
2737         NLboolean success;
2738         EditVert *eve;
2739         EditEdge *eed;
2740         EditFace *efa;
2741         int totvert = 0;
2742         int index;
2743         int rval;
2744         
2745         /* Find local extrema */
2746         for(eve = em->verts.first; eve; eve = eve->next)
2747         {
2748                 totvert++;
2749         }
2750
2751         /* Solve with openNL */
2752         
2753         nlNewContext();
2754
2755         nlSolverParameteri(NL_NB_VARIABLES, totvert);
2756
2757         nlBegin(NL_SYSTEM);
2758         
2759         /* Find local extrema */
2760         for(index = 0, eve = em->verts.first; eve; index++, eve = eve->next)
2761         {
2762                 if (eve->h == 0)
2763                 {
2764                         EditEdge *eed;
2765                         int maximum = 1;
2766                         int minimum = 1;
2767                         
2768                         NextEdgeForVert(indexed_edges, -1); /* Reset next edge */
2769                         for(eed = NextEdgeForVert(indexed_edges, index); eed && (maximum || minimum); eed = NextEdgeForVert(indexed_edges, index))
2770                         {
2771                                 EditVert *eve2;
2772                                 
2773                                 if (eed->v1 == eve)
2774                                 {
2775                                         eve2 = eed->v2;
2776                                 }
2777                                 else
2778                                 {
2779                                         eve2 = eed->v1;
2780                                 }
2781                                 
2782                                 if (eve2->h == 0)
2783                                 {
2784                                         /* Adjacent vertex is bigger, not a local maximum */
2785                                         if (weightData(eve2) > weightData(eve))
2786                                         {
2787                                                 maximum = 0;
2788                                         }
2789                                         /* Adjacent vertex is smaller, not a local minimum */
2790                                         else if (weightData(eve2) < weightData(eve))
2791                                         {
2792                                                 minimum = 0;
2793                                         }
2794                                 }
2795                         }
2796                         
2797                         if (maximum || minimum)
2798                         {
2799                                 float w = weightData(eve);
2800                                 eve->f1 = 0;
2801                                 nlSetVariable(0, index, w);
2802                                 nlLockVariable(index);
2803                         }
2804                         else
2805                         {
2806                                 eve->f1 = 1;
2807                         }
2808                 }
2809         }
2810         
2811         nlBegin(NL_MATRIX);
2812
2813         /* Zero edge weight */
2814         for(eed = em->edges.first; eed; eed = eed->next)
2815         {
2816                 eed->tmp.l = 0;
2817         }
2818         
2819         /* Add faces count to the edge weight */
2820         for(efa = em->faces.first; efa; efa = efa->next)
2821         {
2822                 if (efa->h == 0)
2823                 {
2824                         efa->e1->tmp.l++;
2825                         efa->e2->tmp.l++;
2826                         efa->e3->tmp.l++;
2827                         
2828                         if (efa->e4)
2829                         {
2830                                 efa->e4->tmp.l++;
2831                         }
2832                 }
2833         }
2834
2835         /* Add faces angle to the edge weight */
2836         for(efa = em->faces.first; efa; efa = efa->next)
2837         {
2838                 if (efa->h == 0)
2839                 {
2840                         if (efa->v4 == NULL)
2841                         {
2842                                 addTriangle(efa->v1, efa->v2, efa->v3, efa->e1->tmp.l, efa->e2->tmp.l, efa->e3->tmp.l);
2843                         }
2844                         else
2845                         {
2846                                 addTriangle(efa->v1, efa->v2, efa->v3, efa->e1->tmp.l, efa->e2->tmp.l, 2);
2847                                 addTriangle(efa->v3, efa->v4, efa->v1, efa->e3->tmp.l, efa->e4->tmp.l, 2);
2848                         }
2849                 }
2850         }
2851         
2852         nlEnd(NL_MATRIX);
2853
2854         nlEnd(NL_SYSTEM);
2855
2856         success = nlSolveAdvanced(NULL, NL_TRUE);
2857
2858         if (success)
2859         {
2860                 rval = 1;
2861                 for(index = 0, eve = em->verts.first; eve; index++, eve = eve->next)
2862                 {
2863                         weightSetData(eve, nlGetVariable(0, index));
2864                 }
2865         }
2866         else
2867         {
2868                 rval = 0;
2869         }
2870
2871         nlDeleteContext(nlGetCurrent());
2872
2873         return rval;
2874 }
2875
2876
2877 EditEdge * NextEdgeForVert(EdgeIndex *indexed_edges, int index)
2878 {
2879         static int offset = -1;
2880         
2881         /* Reset method, call with NULL mesh pointer */
2882         if (index == -1)
2883         {
2884                 offset = -1;
2885                 return NULL;
2886         }
2887         
2888         /* first pass, start at the head of the list */
2889         if (offset == -1)
2890         {
2891                 offset = indexed_edges->offset[index];
2892         }
2893         /* subsequent passes, start on the next edge */
2894         else
2895         {
2896                 offset++;
2897         }
2898         
2899         return indexed_edges->edges[offset];
2900 }
2901
2902 void shortestPathsFromVert(EditMesh *em, EditVert *starting_vert, EdgeIndex *indexed_edges)
2903 {
2904         Heap     *edge_heap;
2905         EditVert *current_eve = NULL;
2906         EditEdge *eed = NULL;
2907         EditEdge *select_eed = NULL;
2908         
2909         edge_heap = BLI_heap_new();
2910         
2911         current_eve = starting_vert;
2912         
2913         /* insert guard in heap, when that is returned, no more edges */
2914         BLI_heap_insert(edge_heap, FLT_MAX, NULL);
2915
2916         /* Initialize edge flag */
2917         for(eed= em->edges.first; eed; eed= eed->next)
2918         {
2919                 eed->f1 = 0;
2920         }
2921         
2922         while (BLI_heap_size(edge_heap) > 0)
2923         {
2924                 float current_weight;
2925                 
2926                 current_eve->f1 = 1; /* mark vertex as selected */
2927                 
2928                 /* Add all new edges connected to current_eve to the list */
2929                 NextEdgeForVert(indexed_edges, -1); // Reset next edge
2930                 for(eed = NextEdgeForVert(indexed_edges, indexData(current_eve)); eed; eed = NextEdgeForVert(indexed_edges, indexData(current_eve)))
2931                 { 
2932                         if (eed->f1 == 0)
2933                         {
2934                                 BLI_heap_insert(edge_heap, weightData(current_eve) + eed->tmp.fp, eed);
2935                                 eed->f1 = 1;
2936                         }
2937                 }
2938                 
2939                 /* Find next shortest edge with unselected verts */
2940                 do
2941                 {
2942                         current_weight = BLI_heap_node_value(BLI_heap_top(edge_heap));
2943                         select_eed = BLI_heap_popmin(edge_heap);
2944                 } while (select_eed != NULL && select_eed->v1->f1 != 0 && select_eed->v2->f1);
2945                 
2946                 if (select_eed != NULL)
2947                 {
2948                         select_eed->f1 = 2;
2949                         
2950                         if (select_eed->v1->f1 == 0) /* v1 is the new vertex */
2951                         {
2952                                 current_eve = select_eed->v1;
2953                         }
2954                         else /* otherwise, it's v2 */
2955                         {
2956                                 current_eve = select_eed->v2;
2957                         }
2958                         
2959                         weightSetData(current_eve, current_weight);
2960                 }
2961         }
2962         
2963         BLI_heap_free(edge_heap, NULL);
2964 }
2965
2966 void freeEdgeIndex(EdgeIndex *indexed_edges)
2967 {
2968         MEM_freeN(indexed_edges->offset);
2969         MEM_freeN(indexed_edges->edges);
2970 }
2971
2972 void buildIndexedEdges(EditMesh *em, EdgeIndex *indexed_edges)
2973 {
2974         EditVert *eve;
2975         EditEdge *eed;
2976         int totvert = 0;
2977         int tot_indexed = 0;
2978         int offset = 0;
2979
2980         totvert = BLI_countlist(&em->verts);
2981
2982         indexed_edges->offset = MEM_callocN(totvert * sizeof(int), "EdgeIndex offset");
2983
2984         for(eed = em->edges.first; eed; eed = eed->next)
2985         {
2986                 if (eed->v1->h == 0 && eed->v2->h == 0)
2987                 {
2988                         tot_indexed += 2;
2989                         indexed_edges->offset[indexData(eed->v1)]++;
2990                         indexed_edges->offset[indexData(eed->v2)]++;
2991                 }
2992         }
2993         
2994         tot_indexed += totvert;
2995
2996         indexed_edges->edges = MEM_callocN(tot_indexed * sizeof(EditEdge*), "EdgeIndex edges");
2997
2998         /* setting vert offsets */
2999         for(eve = em->verts.first; eve; eve = eve->next)
3000         {
3001                 if (eve->h == 0)
3002                 {
3003                         int d = indexed_edges->offset[indexData(eve)];
3004                         indexed_edges->offset[indexData(eve)] = offset;
3005                         offset += d + 1;
3006                 }
3007         }
3008
3009         /* adding edges in array */
3010         for(eed = em->edges.first; eed; eed= eed->next)
3011         {
3012                 if (eed->v1->h == 0 && eed->v2->h == 0)
3013                 {
3014                         int i;
3015                         for (i = indexed_edges->offset[indexData(eed->v1)]; i < tot_indexed; i++)
3016                         {
3017                                 if (indexed_edges->edges[i] == NULL)
3018                                 {
3019                                         indexed_edges->edges[i] = eed;
3020                                         break;
3021                                 }
3022                         }
3023                         
3024                         for (i = indexed_edges->offset[indexData(eed->v2)]; i < tot_indexed; i++)
3025                         {
3026                                 if (indexed_edges->edges[i] == NULL)
3027                                 {
3028                                         indexed_edges->edges[i] = eed;
3029                                         break;
3030                                 }
3031                         }
3032                 }
3033         }
3034 }
3035
3036 int weightFromDistance(EditMesh *em, EdgeIndex *indexed_edges)
3037 {
3038         EditVert *eve;
3039         int totedge = 0;
3040         int totvert = 0;
3041         int vCount = 0;
3042         
3043         totvert = BLI_countlist(&em->verts);
3044         
3045         if (em == NULL || totvert == 0)
3046         {
3047                 return 0;
3048         }
3049         
3050         totedge = BLI_countlist(&em->edges);
3051         
3052         if (totedge == 0)
3053         {
3054                 return 0;
3055         }
3056         
3057         /* Initialize vertice flag and find at least one selected vertex */
3058         for(eve = em->verts.first; eve; eve = eve->next)
3059         {
3060                 eve->f1 = 0;
3061                 if (eve->f & SELECT)
3062                 {
3063                         vCount = 1;
3064                 }
3065         }
3066         
3067         if (vCount == 0)
3068         {
3069                 return 0; /* no selected vert, failure */
3070         }
3071         else
3072         {
3073                 EditEdge *eed;
3074                 int allDone = 0;
3075
3076                 /* Calculate edge weight */
3077                 for(eed = em->edges.first; eed; eed= eed->next)
3078                 {
3079                         if (eed->v1->h == 0 && eed->v2->h == 0)
3080                         {
3081                                 eed->tmp.fp = len_v3v3(eed->v1->co, eed->v2->co);
3082                         }
3083                 }
3084
3085                 /* Apply dijkstra spf for each selected vert */
3086                 for(eve = em->verts.first; eve; eve = eve->next)
3087                 {
3088                         if (eve->f & SELECT)
3089                         {
3090                                 shortestPathsFromVert(em, eve, indexed_edges);                          
3091                         }
3092                 }
3093                 
3094                 /* connect unselected islands */
3095                 while (allDone == 0)
3096                 {
3097                         EditVert *selected_eve = NULL;
3098                         float selected_weight = 0;
3099                         float min_distance = FLT_MAX;
3100                         
3101                         allDone = 1;
3102                         
3103                         for (eve = em->verts.first; eve; eve = eve->next)
3104                         {
3105                                 /* for every vertex visible that hasn't been processed yet */
3106                                 if (eve->h == 0 && eve->f1 != 1)
3107                                 {
3108                                         EditVert *closest_eve;
3109                                         
3110                                         /* find the closest processed vertex */
3111                                         for (closest_eve = em->verts.first; closest_eve; closest_eve = closest_eve->next)
3112                                         {
3113                                                 /* vertex is already processed and distance is smaller than current minimum */
3114                                                 if (closest_eve->f1 == 1)
3115                                                 {
3116                                                         float distance = len_v3v3(closest_eve->co, eve->co);
3117                                                         if (distance < min_distance)
3118                                                         {
3119                                                                 min_distance = distance;
3120                                                                 selected_eve = eve;
3121                                                                 selected_weight = weightData(closest_eve);
3122                                                         }
3123                                                 }
3124                                         }
3125                                 }
3126                         }
3127                         
3128                         if (selected_eve)
3129                         {
3130                                 allDone = 0;
3131
3132                                 weightSetData(selected_eve, selected_weight + min_distance);
3133                                 shortestPathsFromVert(em, selected_eve, indexed_edges);
3134                         }
3135                 }
3136         }
3137