svn merge -r 21301:21372 https://svn.blender.org/svnroot/bf-blender/branches/blender2...
[blender-staging.git] / source / blender / editors / armature / meshlaplacian.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.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * meshlaplacian.c: Algorithms using the mesh laplacian.
29  */
30
31 #include <math.h>
32 #include <string.h>
33 #include <assert.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_listBase.h"
38 #include "DNA_object_types.h"
39 #include "DNA_mesh_types.h"
40 #include "DNA_meshdata_types.h"
41 #include "DNA_modifier_types.h"
42 #include "DNA_scene_types.h"
43
44 #include "BLI_arithb.h"
45 #include "BLI_edgehash.h"
46 #include "BLI_memarena.h"
47
48 #include "BKE_DerivedMesh.h"
49 #include "BKE_utildefines.h"
50
51 #ifdef RIGID_DEFORM
52 #include "BLI_editVert.h"
53 #include "BLI_polardecomp.h"
54 #endif
55
56 #include "RE_raytrace.h"
57
58 #include "ONL_opennl.h"
59
60 #include "BLO_sys_types.h" // for intptr_t support
61
62 #include "ED_armature.h"
63 #include "ED_mesh.h"
64
65 #include "meshlaplacian.h"
66
67
68 /* ************* XXX *************** */
69 static void waitcursor() {}
70 static void progress_bar() {}
71 static void start_progress_bar() {}
72 static void end_progress_bar() {}
73 static void error() {}
74 /* ************* XXX *************** */
75
76
77 /************************** Laplacian System *****************************/
78
79 struct LaplacianSystem {
80         NLContext context;      /* opennl context */
81
82         int totvert, totface;
83
84         float **verts;                  /* vertex coordinates */
85         float *varea;                   /* vertex weights for laplacian computation */
86         char *vpinned;                  /* vertex pinning */
87         int (*faces)[3];                /* face vertex indices */
88         float (*fweights)[3];   /* cotangent weights per face */
89
90         int areaweights;                /* use area in cotangent weights? */
91         int storeweights;               /* store cotangent weights in fweights */
92         int nlbegun;                    /* nlBegin(NL_SYSTEM/NL_MATRIX) done */
93
94         EdgeHash *edgehash;             /* edge hash for construction */
95
96         struct HeatWeighting {
97                 Mesh *mesh;
98                 float (*verts)[3];      /* vertex coordinates */
99                 float (*vnors)[3];      /* vertex normals */
100
101                 float (*root)[3];       /* bone root */
102                 float (*tip)[3];        /* bone tip */
103                 int numbones;
104
105                 float *H;                       /* diagonal H matrix */
106                 float *p;                       /* values from all p vectors */
107                 float *mindist;         /* minimum distance to a bone for all vertices */
108                 
109                 RayObject *raytree;     /* ray tracing acceleration structure */
110                 MFace **vface;          /* a face that the vertex belongs to */
111         } heat;
112
113 #ifdef RIGID_DEFORM
114         struct RigidDeformation {
115                 EditMesh *mesh;
116
117                 float (*R)[3][3];
118                 float (*rhs)[3];
119                 float (*origco)[3];
120                 int thrownerror;
121         } rigid;
122 #endif
123 };
124
125 /* Laplacian matrix construction */
126
127 /* Computation of these weights for the laplacian is based on:
128    "Discrete Differential-Geometry Operators for Triangulated 2-Manifolds",
129    Meyer et al, 2002. Section 3.5, formula (8).
130    
131    We do it a bit different by going over faces instead of going over each
132    vertex and adjacent faces, since we don't store this adjacency. Also, the
133    formulas are tweaked a bit to work for non-manifold meshes. */
134
135 static void laplacian_increase_edge_count(EdgeHash *edgehash, int v1, int v2)
136 {
137         void **p = BLI_edgehash_lookup_p(edgehash, v1, v2);
138
139         if(p)
140                 *p = (void*)((intptr_t)*p + (intptr_t)1);
141         else
142                 BLI_edgehash_insert(edgehash, v1, v2, (void*)(intptr_t)1);
143 }
144
145 static int laplacian_edge_count(EdgeHash *edgehash, int v1, int v2)
146 {
147         return (int)(intptr_t)BLI_edgehash_lookup(edgehash, v1, v2);
148 }
149
150 static float cotan_weight(float *v1, float *v2, float *v3)
151 {
152         float a[3], b[3], c[3], clen;
153
154         VecSubf(a, v2, v1);
155         VecSubf(b, v3, v1);
156         Crossf(c, a, b);
157
158         clen = VecLength(c);
159
160         if (clen == 0.0f)
161                 return 0.0f;
162         
163         return Inpf(a, b)/clen;
164 }
165
166 static void laplacian_triangle_area(LaplacianSystem *sys, int i1, int i2, int i3)
167 {
168         float t1, t2, t3, len1, len2, len3, area;
169         float *varea= sys->varea, *v1, *v2, *v3;
170         int obtuse = 0;
171
172         v1= sys->verts[i1];
173         v2= sys->verts[i2];
174         v3= sys->verts[i3];
175
176         t1= cotan_weight(v1, v2, v3);
177         t2= cotan_weight(v2, v3, v1);
178         t3= cotan_weight(v3, v1, v2);
179
180         if(VecAngle3(v2, v1, v3) > 90) obtuse= 1;
181         else if(VecAngle3(v1, v2, v3) > 90) obtuse= 2;
182         else if(VecAngle3(v1, v3, v2) > 90) obtuse= 3;
183
184         if (obtuse > 0) {
185                 area= AreaT3Dfl(v1, v2, v3);
186
187                 varea[i1] += (obtuse == 1)? area: area*0.5;
188                 varea[i2] += (obtuse == 2)? area: area*0.5;
189                 varea[i3] += (obtuse == 3)? area: area*0.5;
190         }
191         else {
192                 len1= VecLenf(v2, v3);
193                 len2= VecLenf(v1, v3);
194                 len3= VecLenf(v1, v2);
195
196                 t1 *= len1*len1;
197                 t2 *= len2*len2;
198                 t3 *= len3*len3;
199
200                 varea[i1] += (t2 + t3)*0.25f;
201                 varea[i2] += (t1 + t3)*0.25f;
202                 varea[i3] += (t1 + t2)*0.25f;
203         }
204 }
205
206 static void laplacian_triangle_weights(LaplacianSystem *sys, int f, int i1, int i2, int i3)
207 {
208         float t1, t2, t3;
209         float *varea= sys->varea, *v1, *v2, *v3;
210
211         v1= sys->verts[i1];
212         v2= sys->verts[i2];
213         v3= sys->verts[i3];
214
215         /* instead of *0.5 we divided by the number of faces of the edge, it still
216            needs to be verified that this is indeed the correct thing to do! */
217         t1= cotan_weight(v1, v2, v3)/laplacian_edge_count(sys->edgehash, i2, i3);
218         t2= cotan_weight(v2, v3, v1)/laplacian_edge_count(sys->edgehash, i3, i1);
219         t3= cotan_weight(v3, v1, v2)/laplacian_edge_count(sys->edgehash, i1, i2);
220
221         nlMatrixAdd(i1, i1, (t2+t3)*varea[i1]);
222         nlMatrixAdd(i2, i2, (t1+t3)*varea[i2]);
223         nlMatrixAdd(i3, i3, (t1+t2)*varea[i3]);
224
225         nlMatrixAdd(i1, i2, -t3*varea[i1]);
226         nlMatrixAdd(i2, i1, -t3*varea[i2]);
227
228         nlMatrixAdd(i2, i3, -t1*varea[i2]);
229         nlMatrixAdd(i3, i2, -t1*varea[i3]);
230
231         nlMatrixAdd(i3, i1, -t2*varea[i3]);
232         nlMatrixAdd(i1, i3, -t2*varea[i1]);
233
234         if(sys->storeweights) {
235                 sys->fweights[f][0]= t1*varea[i1];
236                 sys->fweights[f][1]= t2*varea[i2];
237                 sys->fweights[f][2]= t3*varea[i3];
238         }
239 }
240
241 LaplacianSystem *laplacian_system_construct_begin(int totvert, int totface, int lsq)
242 {
243         LaplacianSystem *sys;
244
245         sys= MEM_callocN(sizeof(LaplacianSystem), "LaplacianSystem");
246
247         sys->verts= MEM_callocN(sizeof(float*)*totvert, "LaplacianSystemVerts");
248         sys->vpinned= MEM_callocN(sizeof(char)*totvert, "LaplacianSystemVpinned");
249         sys->faces= MEM_callocN(sizeof(int)*3*totface, "LaplacianSystemFaces");
250
251         sys->totvert= 0;
252         sys->totface= 0;
253
254         sys->areaweights= 1;
255         sys->storeweights= 0;
256
257         /* create opennl context */
258         nlNewContext();
259         nlSolverParameteri(NL_NB_VARIABLES, totvert);
260         if(lsq)
261                 nlSolverParameteri(NL_LEAST_SQUARES, NL_TRUE);
262
263         sys->context= nlGetCurrent();
264
265         return sys;
266 }
267
268 void laplacian_add_vertex(LaplacianSystem *sys, float *co, int pinned)
269 {
270         sys->verts[sys->totvert]= co;
271         sys->vpinned[sys->totvert]= pinned;
272         sys->totvert++;
273 }
274
275 void laplacian_add_triangle(LaplacianSystem *sys, int v1, int v2, int v3)
276 {
277         sys->faces[sys->totface][0]= v1;
278         sys->faces[sys->totface][1]= v2;
279         sys->faces[sys->totface][2]= v3;
280         sys->totface++;
281 }
282
283 void laplacian_system_construct_end(LaplacianSystem *sys)
284 {
285         int (*face)[3];
286         int a, totvert=sys->totvert, totface=sys->totface;
287
288         laplacian_begin_solve(sys, 0);
289
290         sys->varea= MEM_callocN(sizeof(float)*totvert, "LaplacianSystemVarea");
291
292         sys->edgehash= BLI_edgehash_new();
293         for(a=0, face=sys->faces; a<sys->totface; a++, face++) {
294                 laplacian_increase_edge_count(sys->edgehash, (*face)[0], (*face)[1]);
295                 laplacian_increase_edge_count(sys->edgehash, (*face)[1], (*face)[2]);
296                 laplacian_increase_edge_count(sys->edgehash, (*face)[2], (*face)[0]);
297         }
298
299         if(sys->areaweights)
300                 for(a=0, face=sys->faces; a<sys->totface; a++, face++)
301                         laplacian_triangle_area(sys, (*face)[0], (*face)[1], (*face)[2]);
302         
303         for(a=0; a<totvert; a++) {
304                 if(sys->areaweights) {
305                         if(sys->varea[a] != 0.0f)
306                                 sys->varea[a]= 0.5f/sys->varea[a];
307                 }
308                 else
309                         sys->varea[a]= 1.0f;
310
311                 /* for heat weighting */
312                 if(sys->heat.H)
313                         nlMatrixAdd(a, a, sys->heat.H[a]);
314         }
315
316         if(sys->storeweights)
317                 sys->fweights= MEM_callocN(sizeof(float)*3*totface, "LaplacianFWeight");
318         
319         for(a=0, face=sys->faces; a<totface; a++, face++)
320                 laplacian_triangle_weights(sys, a, (*face)[0], (*face)[1], (*face)[2]);
321
322         MEM_freeN(sys->faces);
323         sys->faces= NULL;
324
325         if(sys->varea) {
326                 MEM_freeN(sys->varea);
327                 sys->varea= NULL;
328         }
329
330         BLI_edgehash_free(sys->edgehash, NULL);
331         sys->edgehash= NULL;
332 }
333
334 void laplacian_system_delete(LaplacianSystem *sys)
335 {
336         if(sys->verts) MEM_freeN(sys->verts);
337         if(sys->varea) MEM_freeN(sys->varea);
338         if(sys->vpinned) MEM_freeN(sys->vpinned);
339         if(sys->faces) MEM_freeN(sys->faces);
340         if(sys->fweights) MEM_freeN(sys->fweights);
341
342         nlDeleteContext(sys->context);
343         MEM_freeN(sys);
344 }
345
346 void laplacian_begin_solve(LaplacianSystem *sys, int index)
347 {
348         int a;
349
350         if (!sys->nlbegun) {
351                 nlBegin(NL_SYSTEM);
352
353                 if(index >= 0) {
354                         for(a=0; a<sys->totvert; a++) {
355                                 if(sys->vpinned[a]) {
356                                         nlSetVariable(0, a, sys->verts[a][index]);
357                                         nlLockVariable(a);
358                                 }
359                         }
360                 }
361
362                 nlBegin(NL_MATRIX);
363                 sys->nlbegun = 1;
364         }
365 }
366
367 void laplacian_add_right_hand_side(LaplacianSystem *sys, int v, float value)
368 {
369         nlRightHandSideAdd(0, v, value);
370 }
371
372 int laplacian_system_solve(LaplacianSystem *sys)
373 {
374         nlEnd(NL_MATRIX);
375         nlEnd(NL_SYSTEM);
376         sys->nlbegun = 0;
377
378         //nlPrintMatrix();
379
380         return nlSolveAdvanced(NULL, NL_TRUE);
381 }
382
383 float laplacian_system_get_solution(int v)
384 {
385         return nlGetVariable(0, v);
386 }
387
388 /************************* Heat Bone Weighting ******************************/
389 /* From "Automatic Rigging and Animation of 3D Characters"
390          Ilya Baran and Jovan Popovic, SIGGRAPH 2007 */
391
392 #define C_WEIGHT                        1.0f
393 #define WEIGHT_LIMIT_START      0.05f
394 #define WEIGHT_LIMIT_END        0.025f
395 #define DISTANCE_EPSILON        1e-4f
396
397 /* Raytracing for vertex to bone visibility */
398 static void heat_ray_tree_create(LaplacianSystem *sys)
399 {
400         Mesh *me = sys->heat.mesh;
401         MFace *mface;
402         int a;
403
404         sys->heat.raytree = RE_rayobject_mesh_create(me, me);
405
406         sys->heat.vface = MEM_callocN(sizeof(MFace*)*me->totvert, "HeatVFaces");
407         for(a=0, mface=me->mface; a<me->totface; a++, mface++) {
408                 sys->heat.vface[mface->v1]= mface;
409                 sys->heat.vface[mface->v2]= mface;
410                 sys->heat.vface[mface->v3]= mface;
411                 if(mface->v4) sys->heat.vface[mface->v4]= mface;
412         }
413 }
414
415 static int heat_ray_bone_visible(LaplacianSystem *sys, int vertex, int bone)
416 {
417         Isect isec;
418         MFace *mface;
419         float end[3];
420         int visible;
421
422         assert( 0 );
423         mface= sys->heat.vface[vertex];
424         if(!mface)
425                 return 1;
426
427         /* setup isec */
428         memset(&isec, 0, sizeof(isec));
429         isec.mode= RE_RAY_SHADOW;
430         isec.lay= -1;
431         isec.orig.face = mface;
432         isec.skip = RE_SKIP_CULLFACE;
433
434         VECCOPY(isec.start, sys->heat.verts[vertex]);
435         PclosestVL3Dfl(end, isec.start, sys->heat.root[bone], sys->heat.tip[bone]);
436
437         VECSUB(isec.vec, end, isec.start);
438         isec.labda = 1.0f;
439
440 #if 0
441         TODO
442         /* add an extra offset to the start position to avoid self intersection */
443         VECCOPY(dir, isec.vec);
444         Normalize(dir);
445         VecMulf(dir, 1e-5);
446         VecAddf(isec.start, isec.start, dir);
447 #endif  
448         visible= !RE_rayobject_raycast(sys->heat.raytree, &isec);
449
450         return visible;
451 }
452
453 static float heat_bone_distance(LaplacianSystem *sys, int vertex, int bone)
454 {
455         float closest[3], d[3], dist, cosine;
456         
457         /* compute euclidian distance */
458         PclosestVL3Dfl(closest, sys->heat.verts[vertex],
459                 sys->heat.root[bone], sys->heat.tip[bone]);
460
461         VecSubf(d, sys->heat.verts[vertex], closest);
462         dist= Normalize(d);
463
464         /* if the vertex normal does not point along the bone, increase distance */
465         cosine= INPR(d, sys->heat.vnors[vertex]);
466
467         return dist/(0.5f*(cosine + 1.001f));
468 }
469
470 static int heat_bone_closest(LaplacianSystem *sys, int vertex, int bone)
471 {
472         float dist;
473         
474         dist= heat_bone_distance(sys, vertex, bone);
475
476         if(dist <= sys->heat.mindist[vertex]*(1.0f + DISTANCE_EPSILON))
477                 if(heat_ray_bone_visible(sys, vertex, bone))
478                         return 1;
479         
480         return 0;
481 }
482
483 static void heat_set_H(LaplacianSystem *sys, int vertex)
484 {
485         float dist, mindist, h;
486         int j, numclosest = 0;
487
488         mindist= 1e10;
489
490         /* compute minimum distance */
491         for(j=0; j<sys->heat.numbones; j++) {
492                 dist= heat_bone_distance(sys, vertex, j);
493
494                 if(dist < mindist)
495                         mindist= dist;
496         }
497
498         sys->heat.mindist[vertex]= mindist;
499
500         /* count number of bones with approximately this minimum distance */
501         for(j=0; j<sys->heat.numbones; j++)
502                 if(heat_bone_closest(sys, vertex, j))
503                         numclosest++;
504
505         sys->heat.p[vertex]= (numclosest > 0)? 1.0f/numclosest: 0.0f;
506
507         /* compute H entry */
508         if(numclosest > 0) {
509                 if(mindist > 1e-5)
510                         h= numclosest*C_WEIGHT/(mindist*mindist);
511                 else
512                         h= 1e10f;
513         }
514         else
515                 h= 0.0f;
516         
517         sys->heat.H[vertex]= h;
518 }
519
520 void heat_calc_vnormals(LaplacianSystem *sys)
521 {
522         float fnor[3];
523         int a, v1, v2, v3, (*face)[3];
524
525         sys->heat.vnors= MEM_callocN(sizeof(float)*3*sys->totvert, "HeatVNors");
526
527         for(a=0, face=sys->faces; a<sys->totface; a++, face++) {
528                 v1= (*face)[0];
529                 v2= (*face)[1];
530                 v3= (*face)[2];
531
532                 CalcNormFloat(sys->verts[v1], sys->verts[v2], sys->verts[v3], fnor);
533                 
534                 VecAddf(sys->heat.vnors[v1], sys->heat.vnors[v1], fnor);
535                 VecAddf(sys->heat.vnors[v2], sys->heat.vnors[v2], fnor);
536                 VecAddf(sys->heat.vnors[v3], sys->heat.vnors[v3], fnor);
537         }
538
539         for(a=0; a<sys->totvert; a++)
540                 Normalize(sys->heat.vnors[a]);
541 }
542
543 static void heat_laplacian_create(LaplacianSystem *sys)
544 {
545         Mesh *me = sys->heat.mesh;
546         MFace *mface;
547         int a;
548
549         /* heat specific definitions */
550         sys->heat.mindist= MEM_callocN(sizeof(float)*me->totvert, "HeatMinDist");
551         sys->heat.H= MEM_callocN(sizeof(float)*me->totvert, "HeatH");
552         sys->heat.p= MEM_callocN(sizeof(float)*me->totvert, "HeatP");
553
554         /* add verts and faces to laplacian */
555         for(a=0; a<me->totvert; a++)
556                 laplacian_add_vertex(sys, sys->heat.verts[a], 0);
557
558         for(a=0, mface=me->mface; a<me->totface; a++, mface++) {
559                 laplacian_add_triangle(sys, mface->v1, mface->v2, mface->v3);
560                 if(mface->v4)
561                         laplacian_add_triangle(sys, mface->v1, mface->v3, mface->v4);
562         }
563
564         /* for distance computation in set_H */
565         heat_calc_vnormals(sys);
566
567         for(a=0; a<me->totvert; a++)
568                 heat_set_H(sys, a);
569 }
570
571 static float heat_limit_weight(float weight)
572 {
573         float t;
574
575         if(weight < WEIGHT_LIMIT_END) {
576                 return 0.0f;
577         }
578         else if(weight < WEIGHT_LIMIT_START) {
579                 t= (weight - WEIGHT_LIMIT_END)/(WEIGHT_LIMIT_START - WEIGHT_LIMIT_END);
580                 return t*WEIGHT_LIMIT_START;
581         }
582         else
583                 return weight;
584 }
585
586 void heat_bone_weighting(Object *ob, Mesh *me, float (*verts)[3], int numbones, bDeformGroup **dgrouplist, bDeformGroup **dgroupflip, float (*root)[3], float (*tip)[3], int *selected)
587 {
588         LaplacianSystem *sys;
589         MFace *mface;
590         float solution, weight;
591         int *vertsflipped = NULL;
592         int a, totface, j, bbone, firstsegment, lastsegment, thrownerror = 0;
593
594         /* count triangles */
595         for(totface=0, a=0, mface=me->mface; a<me->totface; a++, mface++) {
596                 totface++;
597                 if(mface->v4) totface++;
598         }
599
600         /* create laplacian */
601         sys = laplacian_system_construct_begin(me->totvert, totface, 1);
602
603         sys->heat.mesh= me;
604         sys->heat.verts= verts;
605         sys->heat.root= root;
606         sys->heat.tip= tip;
607         sys->heat.numbones= numbones;
608
609         heat_ray_tree_create(sys);
610         heat_laplacian_create(sys);
611
612         laplacian_system_construct_end(sys);
613
614         if(dgroupflip) {
615                 vertsflipped = MEM_callocN(sizeof(int)*me->totvert, "vertsflipped");
616                 for(a=0; a<me->totvert; a++)
617                         vertsflipped[a] = mesh_get_x_mirror_vert(ob, a);
618         }
619
620         /* compute weights per bone */
621         for(j=0; j<numbones; j++) {
622                 if(!selected[j])
623                         continue;
624
625                 firstsegment= (j == 0 || dgrouplist[j-1] != dgrouplist[j]);
626                 lastsegment= (j == numbones-1 || dgrouplist[j] != dgrouplist[j+1]);
627                 bbone= !(firstsegment && lastsegment);
628
629                 /* clear weights */
630                 if(bbone && firstsegment) {
631                         for(a=0; a<me->totvert; a++) {
632                                 remove_vert_defgroup(ob, dgrouplist[j], a);
633                                 if(vertsflipped && dgroupflip[j] && vertsflipped[a] >= 0)
634                                         remove_vert_defgroup(ob, dgroupflip[j], vertsflipped[a]);
635                         }
636                 }
637
638                 /* fill right hand side */
639                 laplacian_begin_solve(sys, -1);
640
641                 for(a=0; a<me->totvert; a++)
642                         if(heat_bone_closest(sys, a, j))
643                                 laplacian_add_right_hand_side(sys, a,
644                                         sys->heat.H[a]*sys->heat.p[a]);
645
646                 /* solve */
647                 if(laplacian_system_solve(sys)) {
648                         /* load solution into vertex groups */
649                         for(a=0; a<me->totvert; a++) {
650                                 solution= laplacian_system_get_solution(a);
651                                 
652                                 if(bbone) {
653                                         if(solution > 0.0f)
654                                                 add_vert_to_defgroup(ob, dgrouplist[j], a, solution,
655                                                         WEIGHT_ADD);
656                                 }
657                                 else {
658                                         weight= heat_limit_weight(solution);
659                                         if(weight > 0.0f)
660                                                 add_vert_to_defgroup(ob, dgrouplist[j], a, weight,
661                                                         WEIGHT_REPLACE);
662                                         else
663                                                 remove_vert_defgroup(ob, dgrouplist[j], a);
664                                 }
665
666                                 /* do same for mirror */
667                                 if(vertsflipped && dgroupflip[j] && vertsflipped[a] >= 0) {
668                                         if(bbone) {
669                                                 if(solution > 0.0f)
670                                                         add_vert_to_defgroup(ob, dgroupflip[j], vertsflipped[a],
671                                                                 solution, WEIGHT_ADD);
672                                         }
673                                         else {
674                                                 weight= heat_limit_weight(solution);
675                                                 if(weight > 0.0f)
676                                                         add_vert_to_defgroup(ob, dgroupflip[j], vertsflipped[a],
677                                                                 weight, WEIGHT_REPLACE);
678                                                 else
679                                                         remove_vert_defgroup(ob, dgroupflip[j], vertsflipped[a]);
680                                         }
681                                 }
682                         }
683                 }
684                 else if(!thrownerror) {
685                         error("Bone Heat Weighting:"
686                                 " failed to find solution for one or more bones");
687                         thrownerror= 1;
688                         break;
689                 }
690
691                 /* remove too small vertex weights */
692                 if(bbone && lastsegment) {
693                         for(a=0; a<me->totvert; a++) {
694                                 weight= get_vert_defgroup(ob, dgrouplist[j], a);
695                                 weight= heat_limit_weight(weight);
696                                 if(weight <= 0.0f)
697                                         remove_vert_defgroup(ob, dgrouplist[j], a);
698
699                                 if(vertsflipped && dgroupflip[j] && vertsflipped[a] >= 0) {
700                                         weight= get_vert_defgroup(ob, dgroupflip[j], vertsflipped[a]);
701                                         weight= heat_limit_weight(weight);
702                                         if(weight <= 0.0f)
703                                                 remove_vert_defgroup(ob, dgroupflip[j], vertsflipped[a]);
704                                 }
705                         }
706                 }
707         }
708
709         /* free */
710         if(vertsflipped) MEM_freeN(vertsflipped);
711
712         RE_rayobject_free(sys->heat.raytree);
713         MEM_freeN(sys->heat.vface);
714
715         MEM_freeN(sys->heat.mindist);
716         MEM_freeN(sys->heat.H);
717         MEM_freeN(sys->heat.p);
718         MEM_freeN(sys->heat.vnors);
719
720         laplacian_system_delete(sys);
721 }
722
723 #ifdef RIGID_DEFORM
724 /********************** As-Rigid-As-Possible Deformation ******************/
725 /* From "As-Rigid-As-Possible Surface Modeling",
726         Olga Sorkine and Marc Alexa, ESGP 2007. */
727
728 /* investigate:
729    - transpose R in orthogonal
730    - flipped normals and per face adding
731    - move cancelling to transform, make origco pointer
732 */
733
734 static LaplacianSystem *RigidDeformSystem = NULL;
735
736 static void rigid_add_half_edge_to_R(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
737 {
738         float e[3], e_[3];
739         int i;
740
741         VecSubf(e, sys->rigid.origco[v1->tmp.l], sys->rigid.origco[v2->tmp.l]);
742         VecSubf(e_, v1->co, v2->co);
743
744         /* formula (5) */
745         for (i=0; i<3; i++) {
746                 sys->rigid.R[v1->tmp.l][i][0] += w*e[0]*e_[i];
747                 sys->rigid.R[v1->tmp.l][i][1] += w*e[1]*e_[i];
748                 sys->rigid.R[v1->tmp.l][i][2] += w*e[2]*e_[i];
749         }
750 }
751
752 static void rigid_add_edge_to_R(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
753 {
754         rigid_add_half_edge_to_R(sys, v1, v2, w);
755         rigid_add_half_edge_to_R(sys, v2, v1, w);
756 }
757
758 static void rigid_orthogonalize_R(float R[][3])
759 {
760         HMatrix M, Q, S;
761
762         Mat4CpyMat3(M, R);
763         polar_decomp(M, Q, S);
764         Mat3CpyMat4(R, Q);
765 }
766
767 static void rigid_add_half_edge_to_rhs(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
768 {
769         /* formula (8) */
770         float Rsum[3][3], rhs[3];
771
772         if (sys->vpinned[v1->tmp.l])
773                 return;
774
775         Mat3AddMat3(Rsum, sys->rigid.R[v1->tmp.l], sys->rigid.R[v2->tmp.l]);
776         Mat3Transp(Rsum);
777
778         VecSubf(rhs, sys->rigid.origco[v1->tmp.l], sys->rigid.origco[v2->tmp.l]);
779         Mat3MulVecfl(Rsum, rhs);
780         VecMulf(rhs, 0.5f);
781         VecMulf(rhs, w);
782
783         VecAddf(sys->rigid.rhs[v1->tmp.l], sys->rigid.rhs[v1->tmp.l], rhs);
784 }
785
786 static void rigid_add_edge_to_rhs(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
787 {
788         rigid_add_half_edge_to_rhs(sys, v1, v2, w);
789         rigid_add_half_edge_to_rhs(sys, v2, v1, w);
790 }
791
792 void rigid_deform_iteration()
793 {
794         LaplacianSystem *sys= RigidDeformSystem;
795         EditMesh *em;
796         EditVert *eve;
797         EditFace *efa;
798         int a, i;
799
800         if(!sys)
801                 return;
802         
803         nlMakeCurrent(sys->context);
804         em= sys->rigid.mesh;
805
806         /* compute R */
807         memset(sys->rigid.R, 0, sizeof(float)*3*3*sys->totvert);
808         memset(sys->rigid.rhs, 0, sizeof(float)*3*sys->totvert);
809
810         for(a=0, efa=em->faces.first; efa; efa=efa->next, a++) {
811                 rigid_add_edge_to_R(sys, efa->v1, efa->v2, sys->fweights[a][2]);
812                 rigid_add_edge_to_R(sys, efa->v2, efa->v3, sys->fweights[a][0]);
813                 rigid_add_edge_to_R(sys, efa->v3, efa->v1, sys->fweights[a][1]);
814
815                 if(efa->v4) {
816                         a++;
817                         rigid_add_edge_to_R(sys, efa->v1, efa->v3, sys->fweights[a][2]);
818                         rigid_add_edge_to_R(sys, efa->v3, efa->v4, sys->fweights[a][0]);
819                         rigid_add_edge_to_R(sys, efa->v4, efa->v1, sys->fweights[a][1]);
820                 }
821         }
822
823         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++) {
824                 rigid_orthogonalize_R(sys->rigid.R[a]);
825                 eve->tmp.l= a;
826         }
827         
828         /* compute right hand sides for solving */
829         for(a=0, efa=em->faces.first; efa; efa=efa->next, a++) {
830                 rigid_add_edge_to_rhs(sys, efa->v1, efa->v2, sys->fweights[a][2]);
831                 rigid_add_edge_to_rhs(sys, efa->v2, efa->v3, sys->fweights[a][0]);
832                 rigid_add_edge_to_rhs(sys, efa->v3, efa->v1, sys->fweights[a][1]);
833
834                 if(efa->v4) {
835                         a++;
836                         rigid_add_edge_to_rhs(sys, efa->v1, efa->v3, sys->fweights[a][2]);
837                         rigid_add_edge_to_rhs(sys, efa->v3, efa->v4, sys->fweights[a][0]);
838                         rigid_add_edge_to_rhs(sys, efa->v4, efa->v1, sys->fweights[a][1]);
839                 }
840         }
841
842         /* solve for positions, for X,Y and Z separately */
843         for(i=0; i<3; i++) {
844                 laplacian_begin_solve(sys, i);
845
846                 for(a=0; a<sys->totvert; a++)
847                         if(!sys->vpinned[a])
848                                 laplacian_add_right_hand_side(sys, a, sys->rigid.rhs[a][i]);
849
850                 if(laplacian_system_solve(sys)) {
851                         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++)
852                                 eve->co[i]= laplacian_system_get_solution(a);
853                 }
854                 else {
855                         if(!sys->rigid.thrownerror) {
856                                 error("RigidDeform: failed to find solution.");
857                                 sys->rigid.thrownerror= 1;
858                         }
859                         break;
860                 }
861         }
862 }
863
864 static void rigid_laplacian_create(LaplacianSystem *sys)
865 {
866         EditMesh *em = sys->rigid.mesh;
867         EditVert *eve;
868         EditFace *efa;
869         int a;
870
871         /* add verts and faces to laplacian */
872         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++) {
873                 laplacian_add_vertex(sys, eve->co, eve->pinned);
874                 eve->tmp.l= a;
875         }
876
877         for(efa=em->faces.first; efa; efa=efa->next) {
878                 laplacian_add_triangle(sys,
879                         efa->v1->tmp.l, efa->v2->tmp.l, efa->v3->tmp.l);
880                 if(efa->v4)
881                         laplacian_add_triangle(sys,
882                                 efa->v1->tmp.l, efa->v3->tmp.l, efa->v4->tmp.l);
883         }
884 }
885
886 void rigid_deform_begin(EditMesh *em)
887 {
888         LaplacianSystem *sys;
889         EditVert *eve;
890         EditFace *efa;
891         int a, totvert, totface;
892
893         /* count vertices, triangles */
894         for(totvert=0, eve=em->verts.first; eve; eve=eve->next)
895                 totvert++;
896
897         for(totface=0, efa=em->faces.first; efa; efa=efa->next) {
898                 totface++;
899                 if(efa->v4) totface++;
900         }
901
902         /* create laplacian */
903         sys = laplacian_system_construct_begin(totvert, totface, 0);
904
905         sys->rigid.mesh= em;
906         sys->rigid.R = MEM_callocN(sizeof(float)*3*3*totvert, "RigidDeformR");
907         sys->rigid.rhs = MEM_callocN(sizeof(float)*3*totvert, "RigidDeformRHS");
908         sys->rigid.origco = MEM_callocN(sizeof(float)*3*totvert, "RigidDeformCo");
909
910         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++)
911                 VecCopyf(sys->rigid.origco[a], eve->co);
912
913         sys->areaweights= 0;
914         sys->storeweights= 1;
915
916         rigid_laplacian_create(sys);
917
918         laplacian_system_construct_end(sys);
919
920         RigidDeformSystem = sys;
921 }
922
923 void rigid_deform_end(int cancel)
924 {
925         LaplacianSystem *sys = RigidDeformSystem;
926
927         if(sys) {
928                 EditMesh *em = sys->rigid.mesh;
929                 EditVert *eve;
930                 int a;
931
932                 if(cancel)
933                         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++)
934                                 if(!eve->pinned)
935                                         VecCopyf(eve->co, sys->rigid.origco[a]);
936
937                 if(sys->rigid.R) MEM_freeN(sys->rigid.R);
938                 if(sys->rigid.rhs) MEM_freeN(sys->rigid.rhs);
939                 if(sys->rigid.origco) MEM_freeN(sys->rigid.origco);
940
941                 /* free */
942                 laplacian_system_delete(sys);
943         }
944
945         RigidDeformSystem = NULL;
946 }
947 #endif
948
949 /************************** Harmonic Coordinates ****************************/
950 /* From "Harmonic Coordinates for Character Articulation",
951         Pushkar Joshi, Mark Meyer, Tony DeRose, Brian Green and Tom Sanocki,
952         SIGGRAPH 2007. */
953
954 #define EPSILON 0.0001f
955
956 #define MESHDEFORM_TAG_UNTYPED  0
957 #define MESHDEFORM_TAG_BOUNDARY 1
958 #define MESHDEFORM_TAG_INTERIOR 2
959 #define MESHDEFORM_TAG_EXTERIOR 3
960
961 #define MESHDEFORM_LEN_THRESHOLD 1e-6
962
963 #define MESHDEFORM_MIN_INFLUENCE 0.0005
964
965 static int MESHDEFORM_OFFSET[7][3] =
966                 {{0,0,0}, {1,0,0}, {-1,0,0}, {0,1,0}, {0,-1,0}, {0,0,1}, {0,0,-1}};
967
968 typedef struct MDefBoundIsect {
969         float co[3], uvw[4];
970         int nvert, v[4], facing;
971         float len;
972 } MDefBoundIsect;
973
974 typedef struct MDefBindInfluence {
975         struct MDefBindInfluence *next;
976         float weight;
977         int vertex;
978 } MDefBindInfluence;
979
980 typedef struct MeshDeformBind {
981         /* grid dimensions */
982         float min[3], max[3];
983         float width[3], halfwidth[3];
984         int size, size3;
985
986         /* meshes */
987         DerivedMesh *cagedm;
988         float (*cagecos)[3];
989         float (*vertexcos)[3];
990         int totvert, totcagevert;
991
992         /* grids */
993         MemArena *memarena;
994         MDefBoundIsect *(*boundisect)[6];
995         int *semibound;
996         int *tag;
997         float *phi, *totalphi;
998
999         /* mesh stuff */
1000         int *inside;
1001         float *weights;
1002         MDefBindInfluence **dyngrid;
1003         float cagemat[4][4];
1004
1005         /* direct solver */
1006         int *varidx;
1007
1008         /* raytrace */
1009         RayObject *raytree;
1010 } MeshDeformBind;
1011
1012 /* ray intersection */
1013
1014 /* our own triangle intersection, so we can fully control the epsilons and
1015  * prevent corner case from going wrong*/
1016 static int meshdeform_tri_intersect(float orig[3], float end[3], float vert0[3],
1017     float vert1[3], float vert2[3], float *isectco, float *uvw)
1018 {
1019         float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
1020         float det,inv_det, u, v, dir[3], isectdir[3];
1021
1022         VECSUB(dir, end, orig);
1023
1024         /* find vectors for two edges sharing vert0 */
1025         VECSUB(edge1, vert1, vert0);
1026         VECSUB(edge2, vert2, vert0);
1027
1028         /* begin calculating determinant - also used to calculate U parameter */
1029         Crossf(pvec, dir, edge2);
1030
1031         /* if determinant is near zero, ray lies in plane of triangle */
1032         det = INPR(edge1, pvec);
1033
1034         if (det == 0.0f)
1035           return 0;
1036         inv_det = 1.0f / det;
1037
1038         /* calculate distance from vert0 to ray origin */
1039         VECSUB(tvec, orig, vert0);
1040
1041         /* calculate U parameter and test bounds */
1042         u = INPR(tvec, pvec) * inv_det;
1043         if (u < -EPSILON || u > 1.0f+EPSILON)
1044           return 0;
1045
1046         /* prepare to test V parameter */
1047         Crossf(qvec, tvec, edge1);
1048
1049         /* calculate V parameter and test bounds */
1050         v = INPR(dir, qvec) * inv_det;
1051         if (v < -EPSILON || u + v > 1.0f+EPSILON)
1052           return 0;
1053
1054         isectco[0]= (1.0f - u - v)*vert0[0] + u*vert1[0] + v*vert2[0];
1055         isectco[1]= (1.0f - u - v)*vert0[1] + u*vert1[1] + v*vert2[1];
1056         isectco[2]= (1.0f - u - v)*vert0[2] + u*vert1[2] + v*vert2[2];
1057
1058         uvw[0]= 1.0 - u - v;
1059         uvw[1]= u;
1060         uvw[2]= v;
1061
1062         /* check if it is within the length of the line segment */
1063         VECSUB(isectdir, isectco, orig);
1064
1065         if(INPR(dir, isectdir) < -EPSILON)
1066                 return 0;
1067         
1068         if(INPR(dir, dir) + EPSILON < INPR(isectdir, isectdir))
1069                 return 0;
1070
1071         return 1;
1072 }
1073
1074 /* blender's raytracer is not use now, even though it is much faster. it can
1075  * give problems with rays falling through, so we use our own intersection 
1076  * function above with tweaked epsilons */
1077
1078 #if 0
1079 static MeshDeformBind *MESHDEFORM_BIND = NULL;
1080
1081 static void meshdeform_ray_coords_func(RayFace *face, float **v1, float **v2, float **v3, float **v4)
1082 {
1083         MFace *mface= (MFace*)face;
1084         float (*cagecos)[3]= MESHDEFORM_BIND->cagecos;
1085
1086         *v1= cagecos[mface->v1];
1087         *v2= cagecos[mface->v2];
1088         *v3= cagecos[mface->v3];
1089         *v4= (mface->v4)? cagecos[mface->v4]: NULL;
1090 }
1091
1092 static int meshdeform_ray_check_func(Isect *is, RayFace *face)
1093 {
1094         return 1;
1095 }
1096
1097 static void meshdeform_ray_tree_create(MeshDeformBind *mdb)
1098 {
1099         MFace *mface;
1100         float min[3], max[3];
1101         int a, totface;
1102
1103         /* create a raytrace tree from the mesh */
1104         INIT_MINMAX(min, max);
1105
1106         for(a=0; a<mdb->totcagevert; a++)
1107                 DO_MINMAX(mdb->cagecos[a], min, max)
1108
1109         MESHDEFORM_BIND= mdb;
1110
1111         mface= mdb->cagedm->getFaceArray(mdb->cagedm);
1112         totface= mdb->cagedm->getNumFaces(mdb->cagedm);
1113
1114         mdb->raytree= RE_ray_tree_create(64, totface, min, max,
1115                 meshdeform_ray_coords_func, meshdeform_ray_check_func);
1116
1117         for(a=0; a<totface; a++, mface++)
1118                 RE_ray_tree_add_face(mdb->raytree, mface);
1119
1120         RE_ray_tree_done(mdb->raytree);
1121 }
1122
1123 static void meshdeform_ray_tree_free(MeshDeformBind *mdb)
1124 {
1125         MESHDEFORM_BIND= NULL;
1126         RE_ray_tree_free(mdb->raytree);
1127 }
1128 #endif
1129
1130 static int meshdeform_intersect(MeshDeformBind *mdb, Isect *isec)
1131 {
1132         MFace *mface;
1133         float face[4][3], co[3], uvw[3], len, nor[3], end[3];
1134         int f, hit, is= 0, totface;
1135
1136         isec->labda= 1e10;
1137
1138         mface= mdb->cagedm->getFaceArray(mdb->cagedm);
1139         totface= mdb->cagedm->getNumFaces(mdb->cagedm);
1140
1141         VECADDFAC( end, isec->start, isec->vec, isec->labda );
1142
1143         for(f=0; f<totface; f++, mface++) {
1144                 VECCOPY(face[0], mdb->cagecos[mface->v1]);
1145                 VECCOPY(face[1], mdb->cagecos[mface->v2]);
1146                 VECCOPY(face[2], mdb->cagecos[mface->v3]);
1147
1148                 if(mface->v4) {
1149                         VECCOPY(face[3], mdb->cagecos[mface->v4]);
1150                         hit = meshdeform_tri_intersect(isec->start, end, face[0], face[1], face[2], co, uvw);
1151
1152                         if(hit) {
1153                                 CalcNormFloat(face[0], face[1], face[2], nor);
1154                         }
1155                         else {
1156                                 hit= meshdeform_tri_intersect(isec->start, end, face[0], face[2], face[3], co, uvw);
1157                                 CalcNormFloat(face[0], face[2], face[3], nor);
1158                         }
1159                 }
1160                 else {
1161                         hit= meshdeform_tri_intersect(isec->start, end, face[0], face[1], face[2], co, uvw);
1162                         CalcNormFloat(face[0], face[1], face[2], nor);
1163                 }
1164
1165                 if(hit) {
1166                         len= VecLenf(isec->start, co)/VecLenf(isec->start, end);
1167                         if(len < isec->labda) {
1168                                 isec->labda= len;
1169                                 isec->hit.face = mface;
1170                                 isec->isect= (INPR(isec->vec, nor) <= 0.0f);
1171                                 is= 1;
1172                         }
1173                 }
1174         }
1175
1176         return is;
1177 }
1178
1179 static MDefBoundIsect *meshdeform_ray_tree_intersect(MeshDeformBind *mdb, float *co1, float *co2)
1180 {
1181         MDefBoundIsect *isect;
1182         Isect isec;
1183         float (*cagecos)[3];
1184         MFace *mface;
1185         float vert[4][3], len, end[3];
1186         static float epsilon[3]= {0, 0, 0}; //1e-4, 1e-4, 1e-4};
1187
1188         /* setup isec */
1189         memset(&isec, 0, sizeof(isec));
1190         isec.mode= RE_RAY_MIRROR; /* we want the closest intersection */
1191         isec.lay= -1;
1192         isec.labda= 1e10f;
1193
1194         VECADD(isec.start, co1, epsilon);
1195         VECADD(end, co2, epsilon);
1196         VECSUB(isec.vec, end, isec.start);
1197
1198 #if 0
1199         /*if(RE_ray_tree_intersect(mdb->raytree, &isec)) {*/
1200 #endif
1201
1202         if(meshdeform_intersect(mdb, &isec)) {
1203                 len= isec.labda;
1204                 mface=(MFace*)isec.hit.face;
1205
1206                 /* create MDefBoundIsect */
1207                 isect= BLI_memarena_alloc(mdb->memarena, sizeof(*isect));
1208
1209                 /* compute intersection coordinate */
1210                 isect->co[0]= co1[0] + isec.vec[0]*len;
1211                 isect->co[1]= co1[1] + isec.vec[1]*len;
1212                 isect->co[2]= co1[2] + isec.vec[2]*len;
1213
1214                 isect->len= VecLenf(co1, isect->co);
1215                 if(isect->len < MESHDEFORM_LEN_THRESHOLD)
1216                         isect->len= MESHDEFORM_LEN_THRESHOLD;
1217
1218                 isect->v[0]= mface->v1;
1219                 isect->v[1]= mface->v2;
1220                 isect->v[2]= mface->v3;
1221                 isect->v[3]= mface->v4;
1222                 isect->nvert= (mface->v4)? 4: 3;
1223
1224                 isect->facing= isec.isect;
1225
1226                 /* compute mean value coordinates for interpolation */
1227                 cagecos= mdb->cagecos;
1228                 VECCOPY(vert[0], cagecos[mface->v1]);
1229                 VECCOPY(vert[1], cagecos[mface->v2]);
1230                 VECCOPY(vert[2], cagecos[mface->v3]);
1231                 if(mface->v4) VECCOPY(vert[3], cagecos[mface->v4]);
1232                 MeanValueWeights(vert, isect->nvert, isect->co, isect->uvw);
1233
1234                 return isect;
1235         }
1236
1237         return NULL;
1238 }
1239
1240 static int meshdeform_inside_cage(MeshDeformBind *mdb, float *co)
1241 {
1242         MDefBoundIsect *isect;
1243         float outside[3], start[3], dir[3];
1244         int i, counter;
1245
1246         for(i=1; i<=6; i++) {
1247                 counter = 0;
1248
1249                 outside[0] = co[0] + (mdb->max[0] - mdb->min[0] + 1.0f)*MESHDEFORM_OFFSET[i][0];
1250                 outside[1] = co[1] + (mdb->max[1] - mdb->min[1] + 1.0f)*MESHDEFORM_OFFSET[i][1];
1251                 outside[2] = co[2] + (mdb->max[2] - mdb->min[2] + 1.0f)*MESHDEFORM_OFFSET[i][2];
1252
1253                 VECCOPY(start, co);
1254                 VECSUB(dir, outside, start);
1255                 Normalize(dir);
1256                 
1257                 isect = meshdeform_ray_tree_intersect(mdb, start, outside);
1258                 if(isect && !isect->facing)
1259                         return 1;
1260         }
1261
1262         return 0;
1263 }
1264
1265 /* solving */
1266
1267 static int meshdeform_index(MeshDeformBind *mdb, int x, int y, int z, int n)
1268 {
1269         int size= mdb->size;
1270         
1271         x += MESHDEFORM_OFFSET[n][0];
1272         y += MESHDEFORM_OFFSET[n][1];
1273         z += MESHDEFORM_OFFSET[n][2];
1274
1275         if(x < 0 || x >= mdb->size)
1276                 return -1;
1277         if(y < 0 || y >= mdb->size)
1278                 return -1;
1279         if(z < 0 || z >= mdb->size)
1280                 return -1;
1281
1282         return x + y*size + z*size*size;
1283 }
1284
1285 static void meshdeform_cell_center(MeshDeformBind *mdb, int x, int y, int z, int n, float *center)
1286 {
1287         x += MESHDEFORM_OFFSET[n][0];
1288         y += MESHDEFORM_OFFSET[n][1];
1289         z += MESHDEFORM_OFFSET[n][2];
1290
1291         center[0]= mdb->min[0] + x*mdb->width[0] + mdb->halfwidth[0];
1292         center[1]= mdb->min[1] + y*mdb->width[1] + mdb->halfwidth[1];
1293         center[2]= mdb->min[2] + z*mdb->width[2] + mdb->halfwidth[2];
1294 }
1295
1296 static void meshdeform_add_intersections(MeshDeformBind *mdb, int x, int y, int z)
1297 {
1298         MDefBoundIsect *isect;
1299         float center[3], ncenter[3];
1300         int i, a;
1301
1302         a= meshdeform_index(mdb, x, y, z, 0);
1303         meshdeform_cell_center(mdb, x, y, z, 0, center);
1304
1305         /* check each outgoing edge for intersection */
1306         for(i=1; i<=6; i++) {
1307                 if(meshdeform_index(mdb, x, y, z, i) == -1)
1308                         continue;
1309
1310                 meshdeform_cell_center(mdb, x, y, z, i, ncenter);
1311
1312                 isect= meshdeform_ray_tree_intersect(mdb, center, ncenter);
1313                 if(isect) {
1314                         mdb->boundisect[a][i-1]= isect;
1315                         mdb->tag[a]= MESHDEFORM_TAG_BOUNDARY;
1316                 }
1317         }
1318 }
1319
1320 static void meshdeform_bind_floodfill(MeshDeformBind *mdb)
1321 {
1322         int *stack, *tag= mdb->tag;
1323         int a, b, i, xyz[3], stacksize, size= mdb->size;
1324
1325         stack= MEM_callocN(sizeof(int)*mdb->size3, "MeshDeformBindStack");
1326
1327         /* we know lower left corner is EXTERIOR because of padding */
1328         tag[0]= MESHDEFORM_TAG_EXTERIOR;
1329         stack[0]= 0;
1330         stacksize= 1;
1331
1332         /* floodfill exterior tag */
1333         while(stacksize > 0) {
1334                 a= stack[--stacksize];
1335
1336                 xyz[2]= a/(size*size);
1337                 xyz[1]= (a - xyz[2]*size*size)/size;
1338                 xyz[0]= a - xyz[1]*size - xyz[2]*size*size;
1339
1340                 for(i=1; i<=6; i++) {
1341                         b= meshdeform_index(mdb, xyz[0], xyz[1], xyz[2], i);
1342
1343                         if(b != -1) {
1344                                 if(tag[b] == MESHDEFORM_TAG_UNTYPED ||
1345                                    (tag[b] == MESHDEFORM_TAG_BOUNDARY && !mdb->boundisect[a][i-1])) {
1346                                         tag[b]= MESHDEFORM_TAG_EXTERIOR;
1347                                         stack[stacksize++]= b;
1348                                 }
1349                         }
1350                 }
1351         }
1352
1353         /* other cells are interior */
1354         for(a=0; a<size*size*size; a++)
1355                 if(tag[a]==MESHDEFORM_TAG_UNTYPED)
1356                         tag[a]= MESHDEFORM_TAG_INTERIOR;
1357
1358 #if 0
1359         {
1360                 int tb, ti, te, ts;
1361                 tb= ti= te= ts= 0;
1362                 for(a=0; a<size*size*size; a++)
1363                         if(tag[a]==MESHDEFORM_TAG_BOUNDARY)
1364                                 tb++;
1365                         else if(tag[a]==MESHDEFORM_TAG_INTERIOR)
1366                                 ti++;
1367                         else if(tag[a]==MESHDEFORM_TAG_EXTERIOR) {
1368                                 te++;
1369
1370                                 if(mdb->semibound[a])
1371                                         ts++;
1372                         }
1373                 
1374                 printf("interior %d exterior %d boundary %d semi-boundary %d\n", ti, te, tb, ts);
1375         }
1376 #endif
1377
1378         MEM_freeN(stack);
1379 }
1380
1381 static float meshdeform_boundary_phi(MeshDeformBind *mdb, MDefBoundIsect *isect, int cagevert)
1382 {
1383         int a;
1384
1385         for(a=0; a<isect->nvert; a++)
1386                 if(isect->v[a] == cagevert)
1387                         return isect->uvw[a];
1388         
1389         return 0.0f;
1390 }
1391
1392 static float meshdeform_interp_w(MeshDeformBind *mdb, float *gridvec, float *vec, int cagevert)
1393 {
1394         float dvec[3], ivec[3], wx, wy, wz, result=0.0f;
1395         float weight, totweight= 0.0f;
1396         int i, a, x, y, z;
1397
1398         for(i=0; i<3; i++) {
1399                 ivec[i]= (int)gridvec[i];
1400                 dvec[i]= gridvec[i] - ivec[i];
1401         }
1402
1403         for(i=0; i<8; i++) {
1404                 if(i & 1) { x= ivec[0]+1; wx= dvec[0]; }
1405                 else { x= ivec[0]; wx= 1.0f-dvec[0]; } 
1406
1407                 if(i & 2) { y= ivec[1]+1; wy= dvec[1]; }
1408                 else { y= ivec[1]; wy= 1.0f-dvec[1]; } 
1409
1410                 if(i & 4) { z= ivec[2]+1; wz= dvec[2]; }
1411                 else { z= ivec[2]; wz= 1.0f-dvec[2]; } 
1412
1413                 CLAMP(x, 0, mdb->size-1);
1414                 CLAMP(y, 0, mdb->size-1);
1415                 CLAMP(z, 0, mdb->size-1);
1416
1417                 a= meshdeform_index(mdb, x, y, z, 0);
1418                 weight= wx*wy*wz;
1419                 result += weight*mdb->phi[a];
1420                 totweight += weight;
1421         }
1422
1423         if(totweight > 0.0f)
1424                 result /= totweight;
1425
1426         return result;
1427 }
1428
1429 static void meshdeform_check_semibound(MeshDeformBind *mdb, int x, int y, int z)
1430 {
1431         int i, a;
1432
1433         a= meshdeform_index(mdb, x, y, z, 0);
1434         if(mdb->tag[a] != MESHDEFORM_TAG_EXTERIOR)
1435                 return;
1436
1437         for(i=1; i<=6; i++)
1438                 if(mdb->boundisect[a][i-1]) 
1439                         mdb->semibound[a]= 1;
1440 }
1441
1442 static float meshdeform_boundary_total_weight(MeshDeformBind *mdb, int x, int y, int z)
1443 {
1444         float weight, totweight= 0.0f;
1445         int i, a;
1446
1447         a= meshdeform_index(mdb, x, y, z, 0);
1448
1449         /* count weight for neighbour cells */
1450         for(i=1; i<=6; i++) {
1451                 if(meshdeform_index(mdb, x, y, z, i) == -1)
1452                         continue;
1453
1454                 if(mdb->boundisect[a][i-1])
1455                         weight= 1.0f/mdb->boundisect[a][i-1]->len;
1456                 else if(!mdb->semibound[a])
1457                         weight= 1.0f/mdb->width[0];
1458                 else
1459                         weight= 0.0f;
1460
1461                 totweight += weight;
1462         }
1463
1464         return totweight;
1465 }
1466
1467 static void meshdeform_matrix_add_cell(MeshDeformBind *mdb, int x, int y, int z)
1468 {
1469         MDefBoundIsect *isect;
1470         float weight, totweight;
1471         int i, a, acenter;
1472
1473         acenter= meshdeform_index(mdb, x, y, z, 0);
1474         if(mdb->tag[acenter] == MESHDEFORM_TAG_EXTERIOR)
1475                 return;
1476
1477         nlMatrixAdd(mdb->varidx[acenter], mdb->varidx[acenter], 1.0f);
1478         
1479         totweight= meshdeform_boundary_total_weight(mdb, x, y, z);
1480         for(i=1; i<=6; i++) {
1481                 a= meshdeform_index(mdb, x, y, z, i);
1482                 if(a == -1 || mdb->tag[a] == MESHDEFORM_TAG_EXTERIOR)
1483                         continue;
1484
1485                 isect= mdb->boundisect[acenter][i-1];
1486                 if (!isect) {
1487                         weight= (1.0f/mdb->width[0])/totweight;
1488                         nlMatrixAdd(mdb->varidx[acenter], mdb->varidx[a], -weight);
1489                 }
1490         }
1491 }
1492
1493 static void meshdeform_matrix_add_rhs(MeshDeformBind *mdb, int x, int y, int z, int cagevert)
1494 {
1495         MDefBoundIsect *isect;
1496         float rhs, weight, totweight;
1497         int i, a, acenter;
1498
1499         acenter= meshdeform_index(mdb, x, y, z, 0);
1500         if(mdb->tag[acenter] == MESHDEFORM_TAG_EXTERIOR)
1501                 return;
1502
1503         totweight= meshdeform_boundary_total_weight(mdb, x, y, z);
1504         for(i=1; i<=6; i++) {
1505                 a= meshdeform_index(mdb, x, y, z, i);
1506                 if(a == -1)
1507                         continue;
1508
1509                 isect= mdb->boundisect[acenter][i-1];
1510
1511                 if (isect) {
1512                         weight= (1.0f/isect->len)/totweight;
1513                         rhs= weight*meshdeform_boundary_phi(mdb, isect, cagevert);
1514                         nlRightHandSideAdd(0, mdb->varidx[acenter], rhs);
1515                 }
1516         }
1517 }
1518
1519 static void meshdeform_matrix_add_semibound_phi(MeshDeformBind *mdb, int x, int y, int z, int cagevert)
1520 {
1521         MDefBoundIsect *isect;
1522         float rhs, weight, totweight;
1523         int i, a;
1524
1525         a= meshdeform_index(mdb, x, y, z, 0);
1526         if(!mdb->semibound[a])
1527                 return;
1528         
1529         mdb->phi[a]= 0.0f;
1530
1531         totweight= meshdeform_boundary_total_weight(mdb, x, y, z);
1532         for(i=1; i<=6; i++) {
1533                 isect= mdb->boundisect[a][i-1];
1534
1535                 if (isect) {
1536                         weight= (1.0f/isect->len)/totweight;
1537                         rhs= weight*meshdeform_boundary_phi(mdb, isect, cagevert);
1538                         mdb->phi[a] += rhs;
1539                 }
1540         }
1541 }
1542
1543 static void meshdeform_matrix_add_exterior_phi(MeshDeformBind *mdb, int x, int y, int z, int cagevert)
1544 {
1545         float phi, totweight;
1546         int i, a, acenter;
1547
1548         acenter= meshdeform_index(mdb, x, y, z, 0);
1549         if(mdb->tag[acenter] != MESHDEFORM_TAG_EXTERIOR || mdb->semibound[acenter])
1550                 return;
1551
1552         phi= 0.0f;
1553         totweight= 0.0f;
1554         for(i=1; i<=6; i++) {
1555                 a= meshdeform_index(mdb, x, y, z, i);
1556
1557                 if(a != -1 && mdb->semibound[a]) {
1558                         phi += mdb->phi[a];
1559                         totweight += 1.0f;
1560                 }
1561         }
1562
1563         if(totweight != 0.0f)
1564                 mdb->phi[acenter]= phi/totweight;
1565 }
1566
1567 static void meshdeform_matrix_solve(MeshDeformBind *mdb)
1568 {
1569         NLContext *context;
1570         float vec[3], gridvec[3];
1571         int a, b, x, y, z, totvar;
1572         char message[1024];
1573
1574         /* setup variable indices */
1575         mdb->varidx= MEM_callocN(sizeof(int)*mdb->size3, "MeshDeformDSvaridx");
1576         for(a=0, totvar=0; a<mdb->size3; a++)
1577                 mdb->varidx[a]= (mdb->tag[a] == MESHDEFORM_TAG_EXTERIOR)? -1: totvar++;
1578
1579         if(totvar == 0) {
1580                 MEM_freeN(mdb->varidx);
1581                 return;
1582         }
1583
1584         progress_bar(0, "Starting mesh deform solve");
1585
1586         /* setup opennl solver */
1587         nlNewContext();
1588         context= nlGetCurrent();
1589
1590         nlSolverParameteri(NL_NB_VARIABLES, totvar);
1591         nlSolverParameteri(NL_NB_ROWS, totvar);
1592         nlSolverParameteri(NL_NB_RIGHT_HAND_SIDES, 1);
1593
1594         nlBegin(NL_SYSTEM);
1595         nlBegin(NL_MATRIX);
1596
1597         /* build matrix */
1598         for(z=0; z<mdb->size; z++)
1599                 for(y=0; y<mdb->size; y++)
1600                         for(x=0; x<mdb->size; x++)
1601                                 meshdeform_matrix_add_cell(mdb, x, y, z);
1602
1603         /* solve for each cage vert */
1604         for(a=0; a<mdb->totcagevert; a++) {
1605                 if(a != 0) {
1606                         nlBegin(NL_SYSTEM);
1607                         nlBegin(NL_MATRIX);
1608                 }
1609
1610                 /* fill in right hand side and solve */
1611                 for(z=0; z<mdb->size; z++)
1612                         for(y=0; y<mdb->size; y++)
1613                                 for(x=0; x<mdb->size; x++)
1614                                         meshdeform_matrix_add_rhs(mdb, x, y, z, a);
1615
1616                 nlEnd(NL_MATRIX);
1617                 nlEnd(NL_SYSTEM);
1618
1619 #if 0
1620                 nlPrintMatrix();
1621 #endif
1622
1623                 if(nlSolveAdvanced(NULL, NL_TRUE)) {
1624                         for(z=0; z<mdb->size; z++)
1625                                 for(y=0; y<mdb->size; y++)
1626                                         for(x=0; x<mdb->size; x++)
1627                                                 meshdeform_matrix_add_semibound_phi(mdb, x, y, z, a);
1628
1629                         for(z=0; z<mdb->size; z++)
1630                                 for(y=0; y<mdb->size; y++)
1631                                         for(x=0; x<mdb->size; x++)
1632                                                 meshdeform_matrix_add_exterior_phi(mdb, x, y, z, a);
1633
1634                         for(b=0; b<mdb->size3; b++) {
1635                                 if(mdb->tag[b] != MESHDEFORM_TAG_EXTERIOR)
1636                                         mdb->phi[b]= nlGetVariable(0, mdb->varidx[b]);
1637                                 mdb->totalphi[b] += mdb->phi[b];
1638                         }
1639
1640                         if(mdb->weights) {
1641                                 /* static bind : compute weights for each vertex */
1642                                 for(b=0; b<mdb->totvert; b++) {
1643                                         if(mdb->inside[b]) {
1644                                                 VECCOPY(vec, mdb->vertexcos[b]);
1645                                                 Mat4MulVecfl(mdb->cagemat, vec);
1646                                                 gridvec[0]= (vec[0] - mdb->min[0] - mdb->halfwidth[0])/mdb->width[0];
1647                                                 gridvec[1]= (vec[1] - mdb->min[1] - mdb->halfwidth[1])/mdb->width[1];
1648                                                 gridvec[2]= (vec[2] - mdb->min[2] - mdb->halfwidth[2])/mdb->width[2];
1649
1650                                                 mdb->weights[b*mdb->totcagevert + a]= meshdeform_interp_w(mdb, gridvec, vec, a);
1651                                         }
1652                                 }
1653                         }
1654                         else {
1655                                 MDefBindInfluence *inf;
1656
1657                                 /* dynamic bind */
1658                                 for(b=0; b<mdb->size3; b++) {
1659                                         if(mdb->phi[b] >= MESHDEFORM_MIN_INFLUENCE) {
1660                                                 inf= BLI_memarena_alloc(mdb->memarena, sizeof(*inf));
1661                                                 inf->vertex= a;
1662                                                 inf->weight= mdb->phi[b];
1663                                                 inf->next= mdb->dyngrid[b];
1664                                                 mdb->dyngrid[b]= inf;
1665                                         }
1666                                 }
1667                         }
1668                 }
1669                 else {
1670                         error("Mesh Deform: failed to find solution.");
1671                         break;
1672                 }
1673
1674                 sprintf(message, "Mesh deform solve %d / %d       |||", a+1, mdb->totcagevert);
1675                 progress_bar((float)(a+1)/(float)(mdb->totcagevert), message);
1676         }
1677
1678 #if 0
1679         /* sanity check */
1680         for(b=0; b<mdb->size3; b++)
1681                 if(mdb->tag[b] != MESHDEFORM_TAG_EXTERIOR)
1682                         if(fabs(mdb->totalphi[b] - 1.0f) > 1e-4)
1683                                 printf("totalphi deficiency [%s|%d] %d: %.10f\n",
1684                                         (mdb->tag[b] == MESHDEFORM_TAG_INTERIOR)? "interior": "boundary", mdb->semibound[b], mdb->varidx[b], mdb->totalphi[b]);
1685 #endif
1686         
1687         /* free */
1688         MEM_freeN(mdb->varidx);
1689
1690         nlDeleteContext(context);
1691 }
1692
1693 void harmonic_coordinates_bind(Scene *scene, MeshDeformModifierData *mmd, float (*vertexcos)[3], int totvert, float cagemat[][4])
1694 {
1695         MeshDeformBind mdb;
1696         MDefBindInfluence *inf;
1697         MDefInfluence *mdinf;
1698         MDefCell *cell;
1699         MVert *mvert;
1700         float center[3], vec[3], maxwidth, totweight;
1701         int a, b, x, y, z, totinside, offset;
1702
1703         waitcursor(1);
1704         start_progress_bar();
1705
1706         memset(&mdb, 0, sizeof(MeshDeformBind));
1707
1708         /* get mesh and cage mesh */
1709         mdb.vertexcos= vertexcos;
1710         mdb.totvert= totvert;
1711         
1712         mdb.cagedm= mesh_create_derived_no_deform(scene, mmd->object, NULL, CD_MASK_BAREMESH);
1713         mdb.totcagevert= mdb.cagedm->getNumVerts(mdb.cagedm);
1714         mdb.cagecos= MEM_callocN(sizeof(*mdb.cagecos)*mdb.totcagevert, "MeshDeformBindCos");
1715         Mat4CpyMat4(mdb.cagemat, cagemat);
1716
1717         mvert= mdb.cagedm->getVertArray(mdb.cagedm);
1718         for(a=0; a<mdb.totcagevert; a++)
1719                 VECCOPY(mdb.cagecos[a], mvert[a].co)
1720
1721         /* compute bounding box of the cage mesh */
1722         INIT_MINMAX(mdb.min, mdb.max);
1723
1724         for(a=0; a<mdb.totcagevert; a++)
1725                 DO_MINMAX(mdb.cagecos[a], mdb.min, mdb.max);
1726
1727         /* allocate memory */
1728         mdb.size= (2<<(mmd->gridsize-1)) + 2;
1729         mdb.size3= mdb.size*mdb.size*mdb.size;
1730         mdb.tag= MEM_callocN(sizeof(int)*mdb.size3, "MeshDeformBindTag");
1731         mdb.phi= MEM_callocN(sizeof(float)*mdb.size3, "MeshDeformBindPhi");
1732         mdb.totalphi= MEM_callocN(sizeof(float)*mdb.size3, "MeshDeformBindTotalPhi");
1733         mdb.boundisect= MEM_callocN(sizeof(*mdb.boundisect)*mdb.size3, "MDefBoundIsect");
1734         mdb.semibound= MEM_callocN(sizeof(int)*mdb.size3, "MDefSemiBound");
1735
1736         mdb.inside= MEM_callocN(sizeof(int)*mdb.totvert, "MDefInside");
1737
1738         if(mmd->flag & MOD_MDEF_DYNAMIC_BIND)
1739                 mdb.dyngrid= MEM_callocN(sizeof(MDefBindInfluence*)*mdb.size3, "MDefDynGrid");
1740         else
1741                 mdb.weights= MEM_callocN(sizeof(float)*mdb.totvert*mdb.totcagevert, "MDefWeights");
1742
1743         mdb.memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
1744         BLI_memarena_use_calloc(mdb.memarena);
1745
1746         /* make bounding box equal size in all directions, add padding, and compute
1747          * width of the cells */
1748         maxwidth = -1.0f;
1749         for(a=0; a<3; a++)
1750                 if(mdb.max[a]-mdb.min[a] > maxwidth)
1751                         maxwidth= mdb.max[a]-mdb.min[a];
1752
1753         for(a=0; a<3; a++) {
1754                 center[a]= (mdb.min[a]+mdb.max[a])*0.5f;
1755                 mdb.min[a]= center[a] - maxwidth*0.5f;
1756                 mdb.max[a]= center[a] + maxwidth*0.5f;
1757
1758                 mdb.width[a]= (mdb.max[a]-mdb.min[a])/(mdb.size-4);
1759                 mdb.min[a] -= 2.1f*mdb.width[a];
1760                 mdb.max[a] += 2.1f*mdb.width[a];
1761
1762                 mdb.width[a]= (mdb.max[a]-mdb.min[a])/mdb.size;
1763                 mdb.halfwidth[a]= mdb.width[a]*0.5f;
1764         }
1765
1766         progress_bar(0, "Setting up mesh deform system");
1767
1768 #if 0
1769         /* create ray tree */
1770         meshdeform_ray_tree_create(&mdb);
1771 #endif
1772
1773         totinside= 0;
1774         for(a=0; a<mdb.totvert; a++) {
1775                 VECCOPY(vec, mdb.vertexcos[a]);
1776                 Mat4MulVecfl(mdb.cagemat, vec);
1777                 mdb.inside[a]= meshdeform_inside_cage(&mdb, vec);
1778                 if(mdb.inside[a])
1779                         totinside++;
1780         }
1781
1782         /* free temporary MDefBoundIsects */
1783         BLI_memarena_free(mdb.memarena);
1784         mdb.memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
1785
1786         /* start with all cells untyped */
1787         for(a=0; a<mdb.size3; a++)
1788                 mdb.tag[a]= MESHDEFORM_TAG_UNTYPED;
1789         
1790         /* detect intersections and tag boundary cells */
1791         for(z=0; z<mdb.size; z++)
1792                 for(y=0; y<mdb.size; y++)
1793                         for(x=0; x<mdb.size; x++)
1794                                 meshdeform_add_intersections(&mdb, x, y, z);
1795
1796 #if 0
1797         /* free ray tree */
1798         meshdeform_ray_tree_free(&mdb);
1799 #endif
1800
1801         /* compute exterior and interior tags */
1802         meshdeform_bind_floodfill(&mdb);
1803
1804         for(z=0; z<mdb.size; z++)
1805                 for(y=0; y<mdb.size; y++)
1806                         for(x=0; x<mdb.size; x++)
1807                                 meshdeform_check_semibound(&mdb, x, y, z);
1808
1809         /* solve */
1810         meshdeform_matrix_solve(&mdb);
1811
1812         /* assign results */
1813         mmd->bindcos= (float*)mdb.cagecos;
1814         mmd->totvert= mdb.totvert;
1815         mmd->totcagevert= mdb.totcagevert;
1816         Mat4CpyMat4(mmd->bindmat, mmd->object->obmat);
1817
1818         if(mmd->flag & MOD_MDEF_DYNAMIC_BIND) {
1819                 mmd->totinfluence= 0;
1820                 for(a=0; a<mdb.size3; a++)
1821                         for(inf=mdb.dyngrid[a]; inf; inf=inf->next)
1822                                 mmd->totinfluence++;
1823
1824                 /* convert MDefBindInfluences to smaller MDefInfluences */
1825                 mmd->dyngrid= MEM_callocN(sizeof(MDefCell)*mdb.size3, "MDefDynGrid");
1826                 mmd->dyninfluences= MEM_callocN(sizeof(MDefInfluence)*mmd->totinfluence, "MDefInfluence");
1827                 offset= 0;
1828                 for(a=0; a<mdb.size3; a++) {
1829                         cell= &mmd->dyngrid[a];
1830                         cell->offset= offset;
1831
1832                         totweight= 0.0f;
1833                         mdinf= mmd->dyninfluences + cell->offset;
1834                         for(inf=mdb.dyngrid[a]; inf; inf=inf->next, mdinf++) {
1835                                 mdinf->weight= inf->weight;
1836                                 mdinf->vertex= inf->vertex;
1837                                 totweight += mdinf->weight;
1838                                 cell->totinfluence++;
1839                         }
1840
1841                         if(totweight > 0.0f) {
1842                                 mdinf= mmd->dyninfluences + cell->offset;
1843                                 for(b=0; b<cell->totinfluence; b++, mdinf++)
1844                                         mdinf->weight /= totweight;
1845                         }
1846
1847                         offset += cell->totinfluence;
1848                 }
1849
1850                 mmd->dynverts= mdb.inside;
1851                 mmd->dyngridsize= mdb.size;
1852                 VECCOPY(mmd->dyncellmin, mdb.min);
1853                 mmd->dyncellwidth= mdb.width[0];
1854                 MEM_freeN(mdb.dyngrid);
1855         }
1856         else {
1857                 mmd->bindweights= mdb.weights;
1858                 MEM_freeN(mdb.inside);
1859         }
1860
1861         /* transform bindcos to world space */
1862         for(a=0; a<mdb.totcagevert; a++)
1863                 Mat4MulVecfl(mmd->object->obmat, mmd->bindcos+a*3);
1864
1865         /* free */
1866         mdb.cagedm->release(mdb.cagedm);
1867         MEM_freeN(mdb.tag);
1868         MEM_freeN(mdb.phi);
1869         MEM_freeN(mdb.totalphi);
1870         MEM_freeN(mdb.boundisect);
1871         MEM_freeN(mdb.semibound);
1872         BLI_memarena_free(mdb.memarena);
1873
1874         end_progress_bar();
1875         waitcursor(0);
1876 }
1877